diff --git "a/final_codegen_1000_entries.json" "b/final_codegen_1000_entries.json" new file mode 100644--- /dev/null +++ "b/final_codegen_1000_entries.json" @@ -0,0 +1,999 @@ +{"Prompt":"Given a list lst and a number N, create a new list that contains each number of the list at most N times without reordering. For example if N 2, and the input is 1,2,3,1,2,1,2,3, you take 1,2,3,1,2, drop the next 1,2 since this would lead to 1 and 2 being in the result 3 times, and then take 3, which leads to 1,2,3,1,2,3 Time complexity On2 Time Complexity On, using hash tables.","Completions":"import collections\n\n\n# Time complexity O(n^2)\ndef delete_nth_naive(array, n):\n ans = []\n for num in array:\n if ans.count(num) < n:\n ans.append(num)\n return ans\n\n\n# Time Complexity O(n), using hash tables.\ndef delete_nth(array, n):\n result = []\n counts = collections.defaultdict(int) # keep track of occurrences\n\n for i in array:\n\n if counts[i] < n:\n result.append(i)\n counts[i] += 1\n\n return result\n"} +{"Prompt":"Implement Flatten Arrays. Given an array that may contain nested arrays, produce a single resultant array. return list returns iterator Takes as input multi dimensional iterable and returns generator which produces one dimensional output.","Completions":"from collections.abc import Iterable\n\n\n# return list\ndef flatten(input_arr, output_arr=None):\n if output_arr is None:\n output_arr = []\n for ele in input_arr:\n if not isinstance(ele, str) and isinstance(ele, Iterable):\n flatten(ele, output_arr) #tail-recursion\n else:\n output_arr.append(ele) #produce the result\n return output_arr\n\n\n# returns iterator\ndef flatten_iter(iterable):\n \"\"\"\n Takes as input multi dimensional iterable and\n returns generator which produces one dimensional output.\n \"\"\"\n for element in iterable:\n if not isinstance(element, str) and isinstance(element, Iterable):\n yield from flatten_iter(element) \n else:\n yield element\n"} +{"Prompt":"There is a parking lot with only one empty spot. Given the initial state of the parking lot and the final state. Each step we are only allowed to move a car out of its place and move it into the empty spot. The goal is to find out the least movement needed to rearrange the parking lot from the initial state to the final state. Say the initial state is an array: 1, 2, 3, 0, 4, where 1, 2, 3, 4 are different cars, and 0 is the empty spot. And the final state is 0, 3, 2, 1, 4. We can swap 1 with 0 in the initial array to get 0, 2, 3, 1, 4 and so on. Each step swap with 0 only. Edit: Now also prints the sequence of changes in states. Output of this example : initial: 1, 2, 3, 0, 4 final: 0, 3, 2, 1, 4 Steps 4 Sequence : 0 2 3 1 4 2 0 3 1 4 2 3 0 1 4 0 3 2 1 4 e.g.: 4, 0, 2, 3, 1, 4, 2, 0, 3, 1, 4, 2, 3, 0, 1, 4, 0, 3, 2, 1, 4 thus: 1 2 3 0 4 zero 3, true, cartomove final3 1, pos initial.index1 0, switched 0, 3 0 2 3 1 4 zero 0, f, initial1 ! final1, switched 0,1 2 0 3 1 4 zero 1, t, cartomove final1 3, pos initial.index3 2, switched 1, 2 2 3 0 1 4 zero 2, t, cartomove final2 2, pos initial.index2 0, switched 0, 2 0 3 2 1 4 initial final","Completions":"def garage(initial, final):\n\n initial = initial[::] # prevent changes in original 'initial'\n seq = [] # list of each step in sequence\n steps = 0\n while initial != final:\n zero = initial.index(0)\n if zero != final.index(0): # if zero isn't where it should be,\n car_to_move = final[zero] # what should be where zero is,\n pos = initial.index(car_to_move) # and where is it?\n initial[zero], initial[pos] = initial[pos], initial[zero]\n else:\n for i in range(len(initial)):\n if initial[i] != final[i]:\n initial[zero], initial[i] = initial[i], initial[zero]\n break\n seq.append(initial[::])\n steps += 1\n\n return steps, seq \n # e.g.: 4, [{0, 2, 3, 1, 4}, {2, 0, 3, 1, 4}, \n # {2, 3, 0, 1, 4}, {0, 3, 2, 1, 4}]\n\n\"\"\"\nthus:\n1 2 3 0 4 -- zero = 3, true, car_to_move = final[3] = 1,\n pos = initial.index(1) = 0, switched [0], [3]\n0 2 3 1 4 -- zero = 0, f, initial[1] != final[1], switched 0,1\n2 0 3 1 4 -- zero = 1, t, car_to_move = final[1] = 3,\n pos = initial.index(3) = 2, switched [1], [2]\n2 3 0 1 4 -- zero = 2, t, car_to_move = final[2] = 2, \n pos = initial.index(2) = 0, switched [0], [2]\n0 3 2 1 4 -- initial == final\n\"\"\""} +{"Prompt":"There are people sitting in a circular fashion, print every third member while removing them, the next counter starts immediately after the member is removed. Print till all the members are exhausted. For example: Input: consider 123456789 members sitting in a circular fashion, Output: 369485271","Completions":"def josephus(int_list, skip):\n skip = skip - 1 # list starts with 0 index\n idx = 0\n len_list = (len(int_list))\n while len_list > 0:\n idx = (skip + idx) % len_list # hash index to every 3rd\n yield int_list.pop(idx)\n len_list -= 1\n"} +{"Prompt":"Sometimes you need to limit array result to use. Such as you only need the value over 10 or, you need value under than 100. By use this algorithms, you can limit your array to specific value If array, Min, Max value was given, it returns array that contains values of given array which was larger than Min, and lower than Max. You need to give 'unlimit' to use only Min or Max. ex limit1,2,3,4,5, None, 3 1,2,3 Complexity On tl:dr array slicing by value","Completions":"# tl:dr -- array slicing by value\ndef limit(arr, min_lim=None, max_lim=None):\n if len(arr) == 0:\n return arr\n\n if min_lim is None:\n min_lim = min(arr)\n if max_lim is None:\n max_lim = max(arr)\n\n return list(filter(lambda x: (min_lim <= x <= max_lim), arr))\n"} +{"Prompt":"Given a string, find the length of the longest substring without repeating characters. Examples: Given abcabcbb, the answer is abc, which the length is 3. Given bbbbb, the answer is b, with the length of 1. Given pwwkew, the answer is wke, with the length of 3. Note that the answer must be a substring, pwke is a subsequence and not a substring. Find the length of the longest substring without repeating characters. Find the length of the longest substring without repeating characters. Uses alternative algorithm. get functions of above, returning the maxlen and substring Find the length of the longest substring without repeating characters. Return maxlen and the substring as a tuple Find the length of the longest substring without repeating characters. Uses alternative algorithm. Return maxlen and the substring as a tuple","Completions":"def longest_non_repeat_v1(string):\n \"\"\"\n Find the length of the longest substring\n without repeating characters.\n \"\"\"\n if string is None:\n return 0\n dict = {}\n max_length = 0\n j = 0\n for i in range(len(string)):\n if string[i] in dict:\n j = max(dict[string[i]], j)\n dict[string[i]] = i + 1\n max_length = max(max_length, i - j + 1)\n return max_length\n\ndef longest_non_repeat_v2(string):\n \"\"\"\n Find the length of the longest substring\n without repeating characters.\n Uses alternative algorithm.\n \"\"\"\n if string is None:\n return 0\n start, max_len = 0, 0\n used_char = {}\n for index, char in enumerate(string):\n if char in used_char and start <= used_char[char]:\n start = used_char[char] + 1\n else:\n max_len = max(max_len, index - start + 1)\n used_char[char] = index\n return max_len\n\n# get functions of above, returning the max_len and substring\ndef get_longest_non_repeat_v1(string):\n \"\"\"\n Find the length of the longest substring\n without repeating characters.\n Return max_len and the substring as a tuple\n \"\"\"\n if string is None:\n return 0, ''\n sub_string = ''\n dict = {}\n max_length = 0\n j = 0\n for i in range(len(string)):\n if string[i] in dict:\n j = max(dict[string[i]], j)\n dict[string[i]] = i + 1\n if i - j + 1 > max_length:\n max_length = i - j + 1\n sub_string = string[j: i + 1]\n return max_length, sub_string\n\ndef get_longest_non_repeat_v2(string):\n \"\"\"\n Find the length of the longest substring\n without repeating characters.\n Uses alternative algorithm.\n Return max_len and the substring as a tuple\n \"\"\"\n if string is None:\n return 0, ''\n sub_string = ''\n start, max_len = 0, 0\n used_char = {}\n for index, char in enumerate(string):\n if char in used_char and start <= used_char[char]:\n start = used_char[char] + 1\n else:\n if index - start + 1 > max_len:\n max_len = index - start + 1\n sub_string = string[start: index + 1]\n used_char[char] = index\n return max_len, sub_string"} +{"Prompt":"Find the index of 0 to be replaced with 1 to get longest continuous sequence of 1s in a binary array. Returns index of 0 to be replaced with 1 to get longest continuous sequence of 1s. If there is no 0 in array, then it returns 1. e.g. let input array 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1 If we replace 0 at index 3 with 1, we get the longest continuous sequence of 1s in the array. So the function return 3 If current element is 0, then calculate the difference between curr and prevprevzero","Completions":"def max_ones_index(arr):\n\n n = len(arr)\n max_count = 0\n max_index = 0\n prev_zero = -1\n prev_prev_zero = -1\n\n for curr in range(n):\n\n # If current element is 0,\n # then calculate the difference\n # between curr and prev_prev_zero\n if arr[curr] == 0:\n if curr - prev_prev_zero > max_count:\n max_count = curr - prev_prev_zero\n max_index = prev_zero\n\n prev_prev_zero = prev_zero\n prev_zero = curr\n\n if n - prev_prev_zero > max_count:\n max_index = prev_zero\n\n return max_index\n"} +{"Prompt":"In mathematics, a real interval is a set of real numbers with the property that any number that lies between two numbers in the set is also included in the set. A set of real numbers with methods to determine if other numbers are included in the set. Includes related methods to merge and print interval sets. Return interval as list. return listself staticmethod def mergeintervals: Print out the intervals. res for i in intervals: res.appendrepri print.joinres def mergeintervalsintervals:","Completions":"class Interval:\n \"\"\"\n A set of real numbers with methods to determine if other\n numbers are included in the set.\n Includes related methods to merge and print interval sets.\n \"\"\"\n def __init__(self, start=0, end=0):\n self.start = start\n self.end = end\n\n def __repr__(self):\n return \"Interval ({}, {})\".format(self.start, self.end)\n\n def __iter__(self):\n return iter(range(self.start, self.end))\n\n def __getitem__(self, index):\n if index < 0:\n return self.end + index\n return self.start + index\n\n def __len__(self):\n return self.end - self.start\n\n def __contains__(self, item):\n if self.start >= item >= self.end:\n return True\n return False\n\n def __eq__(self, other):\n if self.start == other.start and self.end == other.end:\n return True\n return False\n\n def as_list(self):\n \"\"\" Return interval as list. \"\"\"\n return list(self)\n\n @staticmethod\n def merge(intervals):\n \"\"\" Merge two intervals into one. \"\"\"\n out = []\n for i in sorted(intervals, key=lambda i: i.start):\n if out and i.start <= out[-1].end:\n out[-1].end = max(out[-1].end, i.end)\n else:\n out += i,\n return out\n\n @staticmethod\n def print_intervals(intervals):\n \"\"\" Print out the intervals. \"\"\"\n res = []\n for i in intervals:\n res.append(repr(i))\n print(\"\".join(res))\n\n\ndef merge_intervals(intervals):\n \"\"\" Merge intervals in the form of a list. \"\"\"\n if intervals is None:\n return None\n intervals.sort(key=lambda i: i[0])\n out = [intervals.pop(0)]\n for i in intervals:\n if out[-1][-1] >= i[0]:\n out[-1][-1] = max(out[-1][-1], i[-1])\n else:\n out.append(i)\n return out\n"} +{"Prompt":"Find missing ranges between low and high in the given array. Ex 3, 5 lo1 hi10 answer: 1, 2, 4, 4, 6, 10","Completions":"def missing_ranges(arr, lo, hi):\n\n res = []\n start = lo\n\n for n in arr:\n\n if n == start:\n start += 1\n elif n > start:\n res.append((start, n-1))\n start = n + 1\n\n if start <= hi: # after done iterating thru array,\n res.append((start, hi)) # append remainder to list\n\n return res\n"} +{"Prompt":"Write an algorithm that takes an array and moves all of the zeros to the end, preserving the order of the other elements. movezerosfalse, 1, 0, 1, 2, 0, 1, 3, a returns false, 1, 1, 2, 1, 3, a, 0, 0 The time complexity of the below algorithm is On. False 0 is True","Completions":"# False == 0 is True\ndef move_zeros(array):\n result = []\n zeros = 0\n\n for i in array:\n if i == 0 and type(i) != bool: # not using `not i` to avoid `False`, `[]`, etc.\n zeros += 1\n else:\n result.append(i)\n \n result.extend([0] * zeros)\n return result\n\n\nprint(move_zeros([False, 1, 0, 1, 2, 0, 1, 3, \"a\"]))"} +{"Prompt":"Given an array of n integers, are there elements a, b, .. , n in nums such that a b .. n target? Find all unique ntuplets in the array which gives the sum of target. Example: basic: Given: n 4 nums 1, 0, 1, 0, 2, 2 target 0, return 2, 1, 1, 2, 2, 0, 0, 2, 1, 0, 0, 1 advanced: Given: n 2 nums 3, 0, 2, 1, 2, 2, 3, 3, 8, 4, 9, 5 target 5 def suma, b: return a0 b1, a1 b0 def comparenum, target: if num0 target: return 1 elif if num0 target: return 1 else: return 0 return 9, 5, 8, 4 TL:DR because 9 4 5 n: int nums: listobject target: object sumclosure: function, optional Given two elements of nums, return sum of both. compareclosure: function, optional Given one object of nums and target, return 1, 1, or 0. sameclosure: function, optional Given two object of nums, return bool. return: listlistobject Note: 1. type of sumclosure's return should be same as type of compareclosure's first param above, below, or right on? if num target: return 1 elif num target: return 1 else: return 0 def sameclosuredefaulta, b: return a b def nsumn, nums, target: if n 2: want answers with only 2 terms? easy! results twosumnums, target else: results prevnum None for index, num in enumeratenums: if prevnum is not None and sameclosureprevnum, num: continue prevnum num nminus1results nsum recursive call n 1, a numsindex 1:, b target num c x nsum a, b, c nminus1results x nminus1results appendelemtoeachlistnum, nminus1results results nminus1results return unionresults def twosumnums, target: nums.sort lt 0 rt lennums 1 results while lt rt: sum sumclosurenumslt, numsrt flag compareclosuresum, target if flag 1: lt 1 elif flag 1: rt 1 else: results.appendsortednumslt, numsrt lt 1 rt 1 while lt lennums and sameclosurenumslt 1, numslt: lt 1 while 0 rt and sameclosurenumsrt, numsrt 1: rt 1 return results def appendelemtoeachlistelem, container: results for elems in container: elems.appendelem results.appendsortedelems return results def unionduplicateresults: results if lenduplicateresults ! 0: duplicateresults.sort results.appendduplicateresults0 for result in duplicateresults1:: if results1 ! result: results.appendresult return results sumclosure kv.get'sumclosure', sumclosuredefault sameclosure kv.get'sameclosure', sameclosuredefault compareclosure kv.get'compareclosure', compareclosuredefault nums.sort return nsumn, nums, target","Completions":"def n_sum(n, nums, target, **kv):\n \"\"\"\n n: int\n nums: list[object]\n target: object\n sum_closure: function, optional\n Given two elements of nums, return sum of both.\n compare_closure: function, optional\n Given one object of nums and target, return -1, 1, or 0.\n same_closure: function, optional\n Given two object of nums, return bool.\n return: list[list[object]]\n\n Note:\n 1. type of sum_closure's return should be same \n as type of compare_closure's first param\n \"\"\"\n\n def sum_closure_default(a, b):\n return a + b\n\n def compare_closure_default(num, target):\n \"\"\" above, below, or right on? \"\"\"\n if num < target:\n return -1\n elif num > target:\n return 1\n else:\n return 0\n\n def same_closure_default(a, b):\n return a == b\n\n def n_sum(n, nums, target):\n if n == 2: # want answers with only 2 terms? easy!\n results = two_sum(nums, target)\n else:\n results = []\n prev_num = None\n for index, num in enumerate(nums):\n if prev_num is not None and \\\n same_closure(prev_num, num):\n continue\n\n prev_num = num\n n_minus1_results = (\n n_sum( # recursive call\n n - 1, # a\n nums[index + 1:], # b\n target - num # c\n ) # x = n_sum( a, b, c )\n ) # n_minus1_results = x\n\n n_minus1_results = (\n append_elem_to_each_list(num, n_minus1_results)\n )\n results += n_minus1_results\n return union(results)\n\n def two_sum(nums, target):\n nums.sort()\n lt = 0\n rt = len(nums) - 1\n results = []\n while lt < rt:\n sum_ = sum_closure(nums[lt], nums[rt])\n flag = compare_closure(sum_, target)\n if flag == -1:\n lt += 1\n elif flag == 1:\n rt -= 1\n else:\n results.append(sorted([nums[lt], nums[rt]]))\n lt += 1\n rt -= 1\n while (lt < len(nums) and\n same_closure(nums[lt - 1], nums[lt])):\n lt += 1\n while (0 <= rt and\n same_closure(nums[rt], nums[rt + 1])):\n rt -= 1\n return results\n\n def append_elem_to_each_list(elem, container):\n results = []\n for elems in container:\n elems.append(elem)\n results.append(sorted(elems))\n return results\n\n def union(duplicate_results):\n results = []\n\n if len(duplicate_results) != 0:\n duplicate_results.sort()\n results.append(duplicate_results[0])\n for result in duplicate_results[1:]:\n if results[-1] != result:\n results.append(result)\n\n return results\n\n sum_closure = kv.get('sum_closure', sum_closure_default)\n same_closure = kv.get('same_closure', same_closure_default)\n compare_closure = kv.get('compare_closure', compare_closure_default)\n nums.sort()\n return n_sum(n, nums, target)\n"} +{"Prompt":"Given a nonnegative number represented as an array of digits, adding one to each numeral. The digits are stored bigendian, such that the most significant digit is at the head of the list. :type digits: Listint :rtype: Listint","Completions":"def plus_one_v1(digits):\n \"\"\"\n :type digits: List[int]\n :rtype: List[int]\n \"\"\"\n digits[-1] = digits[-1] + 1\n res = []\n ten = 0\n i = len(digits)-1\n while i >= 0 or ten == 1:\n summ = 0\n if i >= 0:\n summ += digits[i]\n if ten:\n summ += 1\n res.append(summ % 10)\n ten = summ \/\/ 10\n i -= 1\n return res[::-1]\n\n\ndef plus_one_v2(digits):\n n = len(digits)\n for i in range(n-1, -1, -1):\n if digits[i] < 9:\n digits[i] += 1\n return digits\n digits[i] = 0\n digits.insert(0, 1)\n return digits\n\n\ndef plus_one_v3(num_arr):\n\n for idx in reversed(list(enumerate(num_arr))):\n num_arr[idx[0]] = (num_arr[idx[0]] + 1) % 10\n if num_arr[idx[0]]:\n return num_arr\n return [1] + num_arr\n"} +{"Prompt":"Rotate an array of n elements to the right by k steps. For example, with n 7 and k 3, the array 1,2,3,4,5,6,7 is rotated to 5,6,7,1,2,3,4. Note: Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem. Rotate the entire array 'k' times Tn Onk :type array: Listint :type k: int :rtype: void Do not return anything, modify array inplace instead. Reverse segments of the array, followed by the entire array Tn On :type array: Listint :type k: int :rtype: void Do not return anything, modify nums inplace instead.","Completions":"def rotate_v1(array, k):\n \"\"\"\n Rotate the entire array 'k' times\n T(n)- O(nk)\n\n :type array: List[int]\n :type k: int\n :rtype: void Do not return anything, modify array in-place instead.\n \"\"\"\n array = array[:]\n n = len(array)\n for i in range(k): # unused variable is not a problem\n temp = array[n - 1]\n for j in range(n-1, 0, -1):\n array[j] = array[j - 1]\n array[0] = temp\n return array\n\n\ndef rotate_v2(array, k):\n \"\"\"\n Reverse segments of the array, followed by the entire array\n T(n)- O(n)\n :type array: List[int]\n :type k: int\n :rtype: void Do not return anything, modify nums in-place instead.\n \"\"\"\n array = array[:]\n\n def reverse(arr, a, b):\n while a < b:\n arr[a], arr[b] = arr[b], arr[a]\n a += 1\n b -= 1\n\n n = len(array)\n k = k % n\n reverse(array, 0, n - k - 1)\n reverse(array, n - k, n - 1)\n reverse(array, 0, n - 1)\n return array\n\n\ndef rotate_v3(array, k):\n if array is None:\n return None\n length = len(array)\n k = k % length\n return array[length - k:] + array[:length - k]\n"} +{"Prompt":"Given a sorted integer array without duplicates, return the summary of its ranges. For example, given 0, 1, 2, 4, 5, 7, return 0, 2, 4, 5, 7, 7. :type array: Listint :rtype: List","Completions":"def summarize_ranges(array):\n \"\"\"\n :type array: List[int]\n :rtype: List[]\n \"\"\"\n res = []\n if len(array) == 1:\n return [str(array[0])]\n i = 0\n while i < len(array):\n num = array[i]\n while i + 1 < len(array) and array[i + 1] - array[i] == 1:\n i += 1\n if array[i] != num:\n res.append((num, array[i]))\n else:\n res.append((num, num))\n i += 1\n return res\n"} +{"Prompt":"Given an array S of n integers, are there three distinct elements a, b, c in S such that a b c 0? Find all unique triplets in the array which gives the sum of zero. Note: The solution set must not contain duplicate triplets. For example, given array S 1, 0, 1, 2, 1, 4, A solution set is: 1, 0, 1, 1, 1, 2 :param array: Listint :return: Set Tupleint, int, int found three sum remove duplicates","Completions":"def three_sum(array):\n \"\"\"\n :param array: List[int]\n :return: Set[ Tuple[int, int, int] ]\n \"\"\"\n res = set()\n array.sort()\n for i in range(len(array) - 2):\n if i > 0 and array[i] == array[i - 1]:\n continue\n l, r = i + 1, len(array) - 1\n while l < r:\n s = array[i] + array[l] + array[r]\n if s > 0:\n r -= 1\n elif s < 0:\n l += 1\n else:\n # found three sum\n res.add((array[i], array[l], array[r]))\n\n # remove duplicates\n while l < r and array[l] == array[l + 1]:\n l += 1\n\n while l < r and array[r] == array[r - 1]:\n r -= 1\n\n l += 1\n r -= 1\n return res\n"} +{"Prompt":"This algorithm receives an array and returns mostfrequentvalue Also, sometimes it is possible to have multiple 'mostfrequentvalue's, so this function returns a list. This result can be used to find a representative value in an array. This algorithm gets an array, makes a dictionary of it, finds the most frequent count, and makes the result list. For example: top11, 1, 2, 2, 3, 4 will return 1, 2 TL:DR Get mathematical Mode Complexity: On reserve each value which first appears on keys reserve how many time each value appears by index number on values","Completions":"def top_1(arr):\n values = {}\n #reserve each value which first appears on keys\n #reserve how many time each value appears by index number on values\n result = []\n f_val = 0\n\n for i in arr:\n if i in values:\n values[i] += 1\n else:\n values[i] = 1\n\n f_val = max(values.values())\n \n for i in values.keys():\n if values[i] == f_val:\n result.append(i)\n else:\n continue\n \n return result\n "} +{"Prompt":"When make reliable means, we need to neglect best and worst values. For example, when making average score on athletes we need this option. So, this algorithm affixes some percentage to neglect when making mean. For example, if you suggest 20, it will neglect the best 10 of values and the worst 10 of values. This algorithm takes an array and percentage to neglect. After sorted, if index of array is larger or smaller than desired ratio, we don't compute it. Compleity: On 100 for easy calculation by , and 2 for easy adaption to best and worst parts. sum value to be calculated to trimmean.","Completions":"def trimmean(arr, per):\n ratio = per\/200\n # \/100 for easy calculation by *, and \/2 for easy adaption to best and worst parts.\n cal_sum = 0\n # sum value to be calculated to trimmean.\n arr.sort()\n neg_val = int(len(arr)*ratio)\n arr = arr[neg_val:len(arr)-neg_val]\n for i in arr:\n cal_sum += i\n return cal_sum\/len(arr)\n"} +{"Prompt":"Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exactly one solution, and you may not use the same element twice. Example: Given nums 2, 7, 11, 15, target 9, Because nums0 nums1 2 7 9, return 0, 1","Completions":"def two_sum(array, target):\n dic = {}\n for i, num in enumerate(array):\n if num in dic:\n return dic[num], i\n else:\n dic[target - num] = i\n return None\n"} +{"Prompt":"Given a string that contains only digits 09 and a target value, return all possibilities to add binary operators not unary , , or between the digits so they prevuate to the target value. Examples: 123, 6 123, 123 232, 8 232, 232 105, 5 105,105 00, 0 00, 00, 00 3456237490, 9191 :type num: str :type target: int :rtype: Liststr","Completions":"def add_operators(num, target):\n \"\"\"\n :type num: str\n :type target: int\n :rtype: List[str]\n \"\"\"\n\n def dfs(res, path, num, target, pos, prev, multed):\n if pos == len(num):\n if target == prev:\n res.append(path)\n return\n for i in range(pos, len(num)):\n if i != pos and num[pos] == '0': # all digits have to be used\n break\n cur = int(num[pos:i+1])\n if pos == 0:\n dfs(res, path + str(cur), num, target, i+1, cur, cur)\n else:\n dfs(res, path + \"+\" + str(cur), num, target,\n i+1, prev + cur, cur)\n dfs(res, path + \"-\" + str(cur), num, target,\n i+1, prev - cur, -cur)\n dfs(res, path + \"*\" + str(cur), num, target,\n i+1, prev - multed + multed * cur, multed * cur)\n\n res = []\n if not num:\n return res\n dfs(res, \"\", num, target, 0, 0, 0)\n return res\n"} +{"Prompt":"Given two strings, determine if they are equal after reordering. Examples: apple, pleap True apple, cherry False","Completions":"def anagram(s1, s2):\n c1 = [0] * 26\n c2 = [0] * 26\n\n for c in s1:\n pos = ord(c)-ord('a')\n c1[pos] = c1[pos] + 1\n\n for c in s2:\n pos = ord(c)-ord('a')\n c2[pos] = c2[pos] + 1\n\n return c1 == c2\n"} +{"Prompt":"WAP to take one element from each of the array add it to the target sum. Print all those threeelement combinations. A 1, 2, 3, 3 B 2, 3, 3, 4 C 2, 3, 3, 4 target 7 Result: 1, 2, 4, 1, 3, 3, 1, 3, 3, 1, 3, 3, 1, 3, 3, 1, 4, 2, 2, 2, 3, 2, 2, 3, 2, 3, 2, 2, 3, 2, 3, 2, 2, 3, 2, 2 1. Sort all the arrays a,b,c. This improves average time complexity. 2. If ci Sum, then look for Sum ci in array a and b. When pair found, insert ci, aj bk into the result list. This can be done in On. 3. Keep on doing the above procedure while going through complete c array. Complexity: Onmp","Completions":"import itertools\nfrom functools import partial\n\n\ndef array_sum_combinations(A, B, C, target):\n\n def over(constructed_sofar):\n sum = 0\n to_stop, reached_target = False, False\n for elem in constructed_sofar:\n sum += elem\n if sum >= target or len(constructed_sofar) >= 3:\n to_stop = True\n if sum == target and 3 == len(constructed_sofar):\n reached_target = True\n return to_stop, reached_target\n\n def construct_candidates(constructed_sofar):\n array = A\n if 1 == len(constructed_sofar):\n array = B\n elif 2 == len(constructed_sofar):\n array = C\n return array\n\n def backtrack(constructed_sofar=[], res=[]):\n to_stop, reached_target = over(constructed_sofar)\n if to_stop:\n if reached_target:\n res.append(constructed_sofar)\n return\n candidates = construct_candidates(constructed_sofar)\n\n for candidate in candidates:\n constructed_sofar.append(candidate)\n backtrack(constructed_sofar[:], res)\n constructed_sofar.pop()\n\n res = []\n backtrack([], res)\n return res\n\n\ndef unique_array_sum_combinations(A, B, C, target):\n \"\"\"\n 1. Sort all the arrays - a,b,c. - This improves average time complexity.\n 2. If c[i] < Sum, then look for Sum - c[i] in array a and b.\n When pair found, insert c[i], a[j] & b[k] into the result list.\n This can be done in O(n).\n 3. Keep on doing the above procedure while going through complete c array.\n\n Complexity: O(n(m+p))\n \"\"\"\n def check_sum(n, *nums):\n if sum(x for x in nums) == n:\n return (True, nums)\n else:\n return (False, nums)\n\n pro = itertools.product(A, B, C)\n func = partial(check_sum, target)\n sums = list(itertools.starmap(func, pro))\n\n res = set()\n for s in sums:\n if s[0] is True and s[1] not in res:\n res.add(s[1])\n\n return list(res)\n"} +{"Prompt":"Given a set of candidate numbers C without duplicates and a target number T, find all unique combinations in C where the candidate numbers sums to T. The same repeated number may be chosen from C unlimited number of times. Note: All numbers including target will be positive integers. The solution set must not contain duplicate combinations. For example, given candidate set 2, 3, 6, 7 and target 7, A solution set is: 7, 2, 2, 3","Completions":"def combination_sum(candidates, target):\n\n def dfs(nums, target, index, path, res):\n if target < 0:\n return # backtracking\n if target == 0:\n res.append(path)\n return\n for i in range(index, len(nums)):\n dfs(nums, target-nums[i], i, path+[nums[i]], res)\n\n res = []\n candidates.sort()\n dfs(candidates, target, 0, [], res)\n return res\n"} +{"Prompt":"Numbers can be regarded as product of its factors. For example, 8 2 x 2 x 2; 2 x 4. Write a function that takes an integer n and return all possible combinations of its factors. Note: You may assume that n is always positive. Factors should be greater than 1 and less than n. Examples: input: 1 output: input: 37 output: input: 12 output: 2, 6, 2, 2, 3, 3, 4 input: 32 output: 2, 16, 2, 2, 8, 2, 2, 2, 4, 2, 2, 2, 2, 2, 2, 4, 4, 4, 8 Iterative: Recursive:","Completions":"# Iterative:\ndef get_factors(n):\n todo, combis = [(n, 2, [])], []\n while todo:\n n, i, combi = todo.pop()\n while i * i <= n:\n if n % i == 0:\n combis.append(combi + [i, n\/\/i])\n todo.append((n\/\/i, i, combi+[i]))\n i += 1\n return combis\n\n\n# Recursive:\ndef recursive_get_factors(n):\n\n def factor(n, i, combi, combis):\n while i * i <= n:\n if n % i == 0:\n combis.append(combi + [i, n\/\/i]),\n factor(n\/\/i, i, combi+[i], combis)\n i += 1\n return combis\n\n return factor(n, 2, [], [])\n"} +{"Prompt":"Given a matrix of words and a list of words to search, return a list of words that exists in the board This is Word Search II on LeetCode board 'o','a','a','n', 'e','t','a','e', 'i','h','k','r', 'i','f','l','v' words oath,pea,eat,rain backtrack tries to build each words from the board and return all words found param: board, the passed in board of characters param: i, the row index param: j, the column index param: trie, a trie of the passed in words param: pre, a buffer of currently build string that differs by recursion stack param: used, a replica of the board except in booleans to state whether a character has been used param: result, the resulting set that contains all words found return: list of words found make a trie structure that is essentially dictionaries of dictionaries that map each character to a potential next character result is a set of found words since we do not want repeats","Completions":"def find_words(board, words):\n\n def backtrack(board, i, j, trie, pre, used, result):\n '''\n backtrack tries to build each words from\n the board and return all words found\n\n @param: board, the passed in board of characters\n @param: i, the row index\n @param: j, the column index\n @param: trie, a trie of the passed in words\n @param: pre, a buffer of currently build string that differs\n by recursion stack\n @param: used, a replica of the board except in booleans\n to state whether a character has been used\n @param: result, the resulting set that contains all words found\n\n @return: list of words found\n '''\n\n if '#' in trie:\n result.add(pre)\n\n if i < 0 or i >= len(board) or j < 0 or j >= len(board[0]):\n return\n\n if not used[i][j] and board[i][j] in trie:\n used[i][j] = True\n backtrack(board, i+1, j, trie[board[i][j]],\n pre+board[i][j], used, result)\n backtrack(board, i, j+1, trie[board[i][j]],\n pre+board[i][j], used, result)\n backtrack(board, i-1, j, trie[board[i][j]],\n pre+board[i][j], used, result)\n backtrack(board, i, j-1, trie[board[i][j]],\n pre+board[i][j], used, result)\n used[i][j] = False\n\n # make a trie structure that is essentially dictionaries of dictionaries\n # that map each character to a potential next character\n trie = {}\n for word in words:\n curr_trie = trie\n for char in word:\n if char not in curr_trie:\n curr_trie[char] = {}\n curr_trie = curr_trie[char]\n curr_trie['#'] = '#'\n\n # result is a set of found words since we do not want repeats\n result = set()\n used = [[False]*len(board[0]) for _ in range(len(board))]\n\n for i in range(len(board)):\n for j in range(len(board[0])):\n backtrack(board, i, j, trie, '', used, result)\n return list(result)\n"} +{"Prompt":"given input word, return the list of abbreviations. ex word 'word', 'wor1', 'wo1d', 'wo2', 'w1rd', 'w1r1', 'w2d', 'w3', '1ord', '1or1', '1o1d', '1o2', '2rd', '2r1', '3d', '4' skip the current word","Completions":"def generate_abbreviations(word):\n\n def backtrack(result, word, pos, count, cur):\n if pos == len(word):\n if count > 0:\n cur += str(count)\n result.append(cur)\n return\n\n if count > 0: # add the current word\n backtrack(result, word, pos+1, 0, cur+str(count)+word[pos])\n else:\n backtrack(result, word, pos+1, 0, cur+word[pos])\n # skip the current word\n backtrack(result, word, pos+1, count+1, cur)\n\n result = []\n backtrack(result, word, 0, 0, \"\")\n return result\n"} +{"Prompt":"Given n pairs of parentheses, write a function to generate all combinations of wellformed parentheses. For example, given n 3, a solution set is: , , , ,","Completions":"def generate_parenthesis_v1(n):\n def add_pair(res, s, left, right):\n if left == 0 and right == 0:\n res.append(s)\n return\n if right > 0:\n add_pair(res, s + \")\", left, right - 1)\n if left > 0:\n add_pair(res, s + \"(\", left - 1, right + 1)\n\n res = []\n add_pair(res, \"\", n, 0)\n return res\n\n\ndef generate_parenthesis_v2(n):\n def add_pair(res, s, left, right):\n if left == 0 and right == 0:\n res.append(s)\n if left > 0:\n add_pair(res, s + \"(\", left - 1, right)\n if right > 0 and left < right:\n add_pair(res, s + \")\", left, right - 1)\n\n res = []\n add_pair(res, \"\", n, n)\n return res\n"} +{"Prompt":"Given a digit string, return all possible letter combinations that the number could represent. A mapping of digit to letters just like on the telephone buttons is given below: 2: abc 3: def 4: ghi 5: jkl 6: mno 7: pqrs 8: tuv 9: wxyz Input:Digit string 23 Output: ad, ae, af, bd, be, bf, cd, ce, cf.","Completions":"def letter_combinations(digits):\n if digits == \"\":\n return []\n kmaps = {\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 ans = [\"\"]\n for num in digits:\n tmp = []\n for an in ans:\n for char in kmaps[num]:\n tmp.append(an + char)\n ans = tmp\n return ans\n"} +{"Prompt":"It looks like you need to be looking not for all palindromic substrings, but rather for all the ways you can divide the input string up into palindromic substrings. There's always at least one way, since onecharacter substrings are always palindromes. ex 'abcbab' 'abcba', 'b', 'a', 'bcb', 'a', 'b', 'a', 'b', 'c', 'bab', 'a', 'b', 'c', 'b', 'a', 'b' There's two loops. The outer loop checks each length of initial substring in descending length order to see if it is a palindrome. If so, it recurses on the rest of the string and loops over the returned values, adding the initial substring to each item before adding it to the results. A slightly more Pythonic approach with a recursive generator","Completions":"def palindromic_substrings(s):\n if not s:\n return [[]]\n results = []\n for i in range(len(s), 0, -1):\n sub = s[:i]\n if sub == sub[::-1]:\n for rest in palindromic_substrings(s[i:]):\n results.append([sub] + rest)\n return results\n\n\n\"\"\"\nThere's two loops.\nThe outer loop checks each length of initial substring\n(in descending length order) to see if it is a palindrome.\nIf so, it recurses on the rest of the string and loops over the returned\nvalues, adding the initial substring to\neach item before adding it to the results.\n\"\"\"\n\n\ndef palindromic_substrings_iter(s):\n \"\"\"\n A slightly more Pythonic approach with a recursive generator\n \"\"\"\n if not s:\n yield []\n return\n for i in range(len(s), 0, -1):\n sub = s[:i]\n if sub == sub[::-1]:\n for rest in palindromic_substrings_iter(s[i:]):\n yield [sub] + rest\n"} +{"Prompt":"Given a pattern and a string str, find if str follows the same pattern. Here follow means a full match, such that there is a bijection between a letter in pattern and a nonempty substring in str. Examples: pattern abab, str redblueredblue should return true. pattern aaaa, str asdasdasdasd should return true. pattern aabb, str xyzabcxzyabc should return false. Notes: You may assume both pattern and str contains only lowercase letters. :type pattern: str :type string: str :rtype: bool","Completions":"def pattern_match(pattern, string):\n \"\"\"\n :type pattern: str\n :type string: str\n :rtype: bool\n \"\"\"\n def backtrack(pattern, string, dic):\n\n if len(pattern) == 0 and len(string) > 0:\n return False\n\n if len(pattern) == len(string) == 0:\n return True\n\n for end in range(1, len(string)-len(pattern)+2):\n if pattern[0] not in dic and string[:end] not in dic.values():\n dic[pattern[0]] = string[:end]\n if backtrack(pattern[1:], string[end:], dic):\n return True\n del dic[pattern[0]]\n elif pattern[0] in dic and dic[pattern[0]] == string[:end]:\n if backtrack(pattern[1:], string[end:], dic):\n return True\n return False\n\n return backtrack(pattern, string, {})\n"} +{"Prompt":"Given a collection of distinct numbers, return all possible permutations. For example, 1,2,3 have the following permutations: 1,2,3, 1,3,2, 2,1,3, 2,3,1, 3,1,2, 3,2,1 returns a list with the permuations. iterator: returns a perumation by each call. DFS Version","Completions":"def permute(elements):\n \"\"\"\n returns a list with the permuations.\n \"\"\"\n if len(elements) <= 1:\n return [elements]\n else:\n tmp = []\n for perm in permute(elements[1:]):\n for i in range(len(elements)):\n tmp.append(perm[:i] + elements[0:1] + perm[i:])\n return tmp\n\n\ndef permute_iter(elements):\n \"\"\"\n iterator: returns a perumation by each call.\n \"\"\"\n if len(elements) <= 1:\n yield elements\n else:\n for perm in permute_iter(elements[1:]):\n for i in range(len(elements)):\n yield perm[:i] + elements[0:1] + perm[i:]\n\n\n# DFS Version\ndef permute_recursive(nums):\n def dfs(res, nums, path):\n if not nums:\n res.append(path)\n for i in range(len(nums)):\n print(nums[:i]+nums[i+1:])\n dfs(res, nums[:i]+nums[i+1:], path+[nums[i]])\n\n res = []\n dfs(res, nums, [])\n return res\n"} +{"Prompt":"Given a collection of numbers that might contain duplicates, return all possible unique permutations. For example, 1,1,2 have the following unique permutations: 1,1,2, 1,2,1, 2,1,1","Completions":"def permute_unique(nums):\n perms = [[]]\n for n in nums:\n new_perms = []\n for l in perms:\n for i in range(len(l)+1):\n new_perms.append(l[:i]+[n]+l[i:])\n if i < len(l) and l[i] == n:\n break # handles duplication\n perms = new_perms\n return perms\n"} +{"Prompt":"Given a set of distinct integers, nums, return all possible subsets. Note: The solution set must not contain duplicate subsets. For example, If nums 1,2,3, a solution is: 3, 1, 2, 1,2,3, 1,3, 2,3, 1,2, O2n take numspos dont take numspos simplified backtrack def backtrackres, nums, cur, pos: if pos lennums: res.appendcur else: backtrackres, nums, curnumspos, pos1 backtrackres, nums, cur, pos1 Iteratively","Completions":"def subsets(nums):\n \"\"\"\n O(2**n)\n \"\"\"\n def backtrack(res, nums, stack, pos):\n if pos == len(nums):\n res.append(list(stack))\n else:\n # take nums[pos]\n stack.append(nums[pos])\n backtrack(res, nums, stack, pos+1)\n stack.pop()\n # dont take nums[pos]\n backtrack(res, nums, stack, pos+1)\n\n res = []\n backtrack(res, nums, [], 0)\n return res\n\n\n\"\"\"\nsimplified backtrack\n\ndef backtrack(res, nums, cur, pos):\n if pos >= len(nums):\n res.append(cur)\n else:\n backtrack(res, nums, cur+[nums[pos]], pos+1)\n backtrack(res, nums, cur, pos+1)\n\"\"\"\n\n\n# Iteratively\ndef subsets_v2(nums):\n res = [[]]\n for num in sorted(nums):\n res += [item+[num] for item in res]\n return res\n"} +{"Prompt":"Given a collection of integers that might contain duplicates, nums, return all possible subsets. Note: The solution set must not contain duplicate subsets. For example, If nums 1,2,2, a solution is: 2, 1, 1,2,2, 2,2, 1,2, take don't take","Completions":"def subsets_unique(nums):\n\n def backtrack(res, nums, stack, pos):\n if pos == len(nums):\n res.add(tuple(stack))\n else:\n # take\n stack.append(nums[pos])\n backtrack(res, nums, stack, pos+1)\n stack.pop()\n\n # don't take\n backtrack(res, nums, stack, pos+1)\n\n res = set()\n backtrack(res, nums, [], 0)\n return list(res)\n"} +{"Prompt":"This is a bfsversion of countingislands problem in dfs section. Given 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. Example 1: 11110 11010 11000 00000 Answer: 1 Example 2: 11000 11000 00100 00011 Answer: 3 Example 3: 111000 110000 100001 001101 001100 Answer: 3 Example 4: 110011 001100 000001 111100 Answer: 5","Completions":"def count_islands(grid):\n row = len(grid)\n col = len(grid[0])\n\n num_islands = 0\n visited = [[0] * col for i in range(row)]\n directions = [[-1, 0], [1, 0], [0, -1], [0, 1]]\n queue = []\n\n for i in range(row):\n for j, num in enumerate(grid[i]):\n if num == 1 and visited[i][j] != 1:\n visited[i][j] = 1\n queue.append((i, j))\n while queue:\n x, y = queue.pop(0)\n for k in range(len(directions)):\n nx_x = x + directions[k][0]\n nx_y = y + directions[k][1]\n if nx_x >= 0 and nx_y >= 0 and nx_x < row and nx_y < col:\n if visited[nx_x][nx_y] != 1 and grid[nx_x][nx_y] == 1:\n queue.append((nx_x, nx_y))\n visited[nx_x][nx_y] = 1\n num_islands += 1\n\n return num_islands\n"} +{"Prompt":"BFS time complexity : OE V BFS space complexity : OE V do BFS from 0,0 of the grid and get the minimum number of steps needed to get to the lower right column only step on the columns whose value is 1 if there is no path, it returns 1 Ex 1 If grid is 1,0,1,1,1,1, 1,0,1,0,1,0, 1,0,1,0,1,1, 1,1,1,0,1,1, the answer is: 14 Ex 2 If grid is 1,0,0, 0,1,1, 0,1,1, the answer is: 1","Completions":"from collections import deque\n\n'''\nBFS time complexity : O(|E| + |V|)\nBFS space complexity : O(|E| + |V|)\n\ndo BFS from (0,0) of the grid and get the minimum number of steps needed to get to the lower right column\n\nonly step on the columns whose value is 1\n\nif there is no path, it returns -1\n\nEx 1)\nIf grid is\n[[1,0,1,1,1,1],\n [1,0,1,0,1,0],\n [1,0,1,0,1,1],\n [1,1,1,0,1,1]], \nthe answer is: 14\n\nEx 2)\nIf grid is\n[[1,0,0],\n [0,1,1],\n [0,1,1]], \nthe answer is: -1\n'''\n\ndef maze_search(maze):\n BLOCKED, ALLOWED = 0, 1\n UNVISITED, VISITED = 0, 1\n\n initial_x, initial_y = 0, 0\n\n if maze[initial_x][initial_y] == BLOCKED:\n return -1\n \n directions = [(0, -1), (0, 1), (-1, 0), (1, 0)]\n\n height, width = len(maze), len(maze[0])\n\n target_x, target_y = height - 1, width - 1\n\n queue = deque([(initial_x, initial_y, 0)])\n\n is_visited = [[UNVISITED for w in range(width)] for h in range(height)]\n is_visited[initial_x][initial_y] = VISITED\n\n while queue:\n x, y, steps = queue.popleft()\n\n if x == target_x and y == target_y:\n return steps\n\n for dx, dy in directions:\n new_x = x + dx\n new_y = y + dy\n\n if not (0 <= new_x < height and 0 <= new_y < width):\n continue\n\n if maze[new_x][new_y] == ALLOWED and is_visited[new_x][new_y] == UNVISITED:\n queue.append((new_x, new_y, steps + 1))\n is_visited[new_x][new_y] = VISITED\n\n return -1 \n\n"} +{"Prompt":"do BFS from each building, and decrement all empty place for every building visit when gridij bnums, it means that gridij are already visited from all bnums and use dist to record distances from bnums only the position be visited by count times will append to queue","Completions":"import collections\n\n\"\"\"\ndo BFS from each building, and decrement all empty place for every building visit\nwhen grid[i][j] == -b_nums, it means that grid[i][j] are already visited from all b_nums\nand use dist to record distances from b_nums\n\"\"\"\n\ndef shortest_distance(grid):\n if not grid or not grid[0]:\n return -1\n\n matrix = [[[0,0] for i in range(len(grid[0]))] for j in range(len(grid))]\n\n count = 0 # count how many building we have visited\n for i in range(len(grid)):\n for j in range(len(grid[0])):\n if grid[i][j] == 1:\n bfs(grid, matrix, i, j, count)\n count += 1\n\n res = float('inf')\n for i in range(len(matrix)):\n for j in range(len(matrix[0])):\n if matrix[i][j][1]==count:\n res = min(res, matrix[i][j][0])\n\n return res if res!=float('inf') else -1\n\ndef bfs(grid, matrix, i, j, count):\n q = [(i, j, 0)]\n while q:\n i, j, step = q.pop(0)\n for k, l in [(i-1,j), (i+1,j), (i,j-1), (i,j+1)]:\n # only the position be visited by count times will append to queue\n if 0<=k len(end_set):\n begin_set, end_set = end_set, begin_set\n\n next_begin_set = set()\n for word in begin_set:\n for ladder_word in word_range(word):\n if ladder_word in end_set:\n return result\n if ladder_word in word_list:\n next_begin_set.add(ladder_word)\n word_list.remove(ladder_word)\n begin_set = next_begin_set\n result += 1\n # print(begin_set)\n # print(result)\n return -1\n\n\ndef word_range(word):\n for ind in range(len(word)):\n temp = word[ind]\n for c in [chr(x) for x in range(ord('a'), ord('z') + 1)]:\n if c != temp:\n yield word[:ind] + c + word[ind + 1:]\n"} +{"Prompt":"The following code adds two positive integers without using the '' operator. The code uses bitwise operations to add two numbers. Input: 2 3 Output: 5","Completions":"def add_bitwise_operator(x, y):\n\n while y:\n carry = x & y\n x = x ^ y\n y = carry << 1\n return x\n"} +{"Prompt":"Given a positive integer N, find and return the longest distance between two consecutive 1' in the binary representation of N. If there are not two consecutive 1's, return 0 For example: Input: 22 Output: 2 Explanation: 22 in binary is 10110 In the binary representation of 22, there are three ones, and two consecutive pairs of 1's. The first consecutive pair of 1's have distance 2. The second consecutive pair of 1's have distance 1. The answer is the largest of these two distances, which is 2 binarygap2 binarygapimproved The original method is binarygap, but the experimental results show that the algorithm seems to be wrong, regardless of the number, the output value is up to 2. The improved method is binarygapimproved.","Completions":"# \u539f\u65b9\u6cd5\u4e3a binary_gap\uff0c\u4f46\u901a\u8fc7\u5b9e\u9a8c\u53d1\u73b0\u7b97\u6cd5\u6709\u8bef\uff0c\u4e0d\u8bba\u662f\u4ec0\u4e48\u6570\uff0c\u8f93\u51fa\u503c\u6700\u591a\u4e3a2\u3002\n# \u6539\u8fdb\u65b9\u6cd5\u4e3abinary_gap_improved\u3002\n# The original method is binary_gap,\n# but the experimental results show that the algorithm seems to be wrong,\n# regardless of the number, the output value is up to 2.\n# The improved method is binary_gap_improved.\ndef binary_gap(N):\n last = None\n ans = 0\n index = 0\n while N != 0:\n if N & 1:\n if last is not None:\n ans = max(ans, index - last)\n last = index\n index = index + 1\n N = N >> 1\n return ans\n\n\ndef binary_gap_improved(N):\n last = None\n ans = 0\n index = 0\n while N != 0:\n tes = N & 1\n if tes:\n if last is not None:\n ans = max(ans, index - last + 1)\n else:\n last = index\n else:\n last = index + 1\n index = index + 1\n N = N >> 1\n return ans\n\n\nprint(binary_gap(111))\nprint(binary_gap_improved(111))"} +{"Prompt":"Fundamental bit operation: getbitnum, i: get an exact bit at specific index setbitnum, i: set a bit at specific index clearbitnum, i: clear a bit at specific index updatebitnum, i, bit: update a bit at specific index This function shifts 1 over by i bits, creating a value being like 0001000. By performing an AND with num, we clear all bits other than the bit at bit i. Finally we compare that to 0 This function shifts 1 over by i bits, creating a value being like 0001000. By performing an OR with num, only value at bit i will change. This method operates in almost the reverse of setbit To set the ith bit to value, we first clear the bit at position i by using a mask. Then, we shift the intended value. Finally we OR these two numbers","Completions":"\"\"\"\nThis function shifts 1 over by i bits, creating a value being like 0001000. By\nperforming an AND with num, we clear all bits other than the bit at bit i.\nFinally we compare that to 0\n\"\"\"\ndef get_bit(num, i):\n return (num & (1 << i)) != 0\n\n\"\"\"\nThis function shifts 1 over by i bits, creating a value being like 0001000. By\nperforming an OR with num, only value at bit i will change.\n\"\"\"\ndef set_bit(num, i):\n return num | (1 << i)\n\n\"\"\"\nThis method operates in almost the reverse of set_bit\n\"\"\"\ndef clear_bit(num, i):\n mask = ~(1 << i)\n return num & mask\n\n\"\"\"\nTo set the ith bit to value, we first clear the bit at position i by using a\nmask. Then, we shift the intended value. Finally we OR these two numbers\n\"\"\"\ndef update_bit(num, i, bit):\n mask = ~(1 << i)\n return (num & mask) | (bit << i)\n"} +{"Prompt":"list.insert0, ... is inefficient","Completions":"from collections import deque\n\n\ndef int_to_bytes_big_endian(num):\n bytestr = deque()\n while num > 0:\n # list.insert(0, ...) is inefficient\n bytestr.appendleft(num & 0xff)\n num >>= 8\n return bytes(bytestr)\n\n\ndef int_to_bytes_little_endian(num):\n bytestr = []\n while num > 0:\n bytestr.append(num & 0xff)\n num >>= 8\n return bytes(bytestr)\n\n\ndef bytes_big_endian_to_int(bytestr):\n num = 0\n for b in bytestr:\n num <<= 8\n num += b\n return num\n\n\ndef bytes_little_endian_to_int(bytestr):\n num = 0\n e = 0\n for b in bytestr:\n num += b << e\n e += 8\n return num\n"} +{"Prompt":"Write a function to determine the minimal number of bits you would need to flip to convert integer A to integer B. For example: Input: 29 or: 11101, 15 or: 01111 Output: 2 count number of ones in diff","Completions":"def count_flips_to_convert(a, b):\n\n diff = a ^ b\n\n # count number of ones in diff\n count = 0\n while diff:\n diff &= (diff - 1)\n count += 1\n return count\n"} +{"Prompt":"Write a function that takes an unsigned integer and returns the number of '1' bits it has also known as the Hamming weight. For example, the 32bit integer '11' has binary representation 00000000000000000000000000001011, so the function should return 3. Tn Ok : k is the number of 1s present in binary representation. NOTE: this complexity is better than Olog n. e.g. for n 00010100000000000000000000000000 only 2 iterations are required. Number of loops is equal to the number of 1s in the binary representation. def countonesrecurn: Using Brian Kernighan's Algorithm. Iterative Approach count 0 while n: n n1 count 1 return count","Completions":"def count_ones_recur(n):\n \"\"\"Using Brian Kernighan's Algorithm. (Recursive Approach)\"\"\"\n\n if not n:\n return 0\n return 1 + count_ones_recur(n & (n-1))\n\n\ndef count_ones_iter(n):\n \"\"\"Using Brian Kernighan's Algorithm. (Iterative Approach)\"\"\"\n\n count = 0\n while n:\n n &= (n-1)\n count += 1\n return count\n"} +{"Prompt":"Given two strings s and t which consist of only lowercase letters. String t is generated by random shuffling string s and then add one more letter at a random position. Find the letter that was added in t. For example: Input: s abcd t abecd Output: 'e' Explanation: 'e' is the letter that was added. We use the characteristic equation of XOR. A xor B xor C A xor C xor B If A C, then A xor C 0 and then, B xor 0 B ordch return an integer representing the Unicode code point of that character chri Return the string representing a character whose Unicode code point is the integer i","Completions":"\"\"\"\nWe use the characteristic equation of XOR.\nA xor B xor C = A xor C xor B\nIf A == C, then A xor C = 0\nand then, B xor 0 = B\n\"\"\"\ndef find_difference(s, t):\n ret = 0\n for ch in s + t:\n # ord(ch) return an integer representing the Unicode code point of that character\n ret = ret ^ ord(ch)\n # chr(i) Return the string representing a character whose Unicode code point is the integer i\n return chr(ret)\n"} +{"Prompt":"Returns the missing number from a sequence of unique integers in range 0..n in On time and space. The difference between consecutive integers cannot be more than 1. If the sequence is already complete, the next integer in the sequence will be returned. For example: Input: nums 4, 1, 3, 0, 6, 5, 2 Output: 7","Completions":"def find_missing_number(nums):\n\n missing = 0\n for i, num in enumerate(nums):\n missing ^= num\n missing ^= i + 1\n\n return missing\n\n\ndef find_missing_number2(nums):\n\n num_sum = sum(nums)\n n = len(nums)\n total_sum = n*(n+1) \/\/ 2\n missing = total_sum - num_sum\n return missing\n"} +{"Prompt":"You have an integer and you can flip exactly one bit from a 0 to 1. Write code to find the length of the longest sequence of 1s you could create. For example: Input: 1775 or: 11011101111 Output: 8","Completions":"def flip_bit_longest_seq(num):\n\n curr_len = 0\n prev_len = 0\n max_len = 0\n\n while num:\n if num & 1 == 1: # last digit is 1\n curr_len += 1\n\n elif num & 1 == 0: # last digit is 0\n if num & 2 == 0: # second last digit is 0\n prev_len = 0\n else:\n prev_len = curr_len\n curr_len = 0\n\n max_len = max(max_len, prev_len + curr_len)\n num = num >> 1 # right shift num\n\n return max_len + 1\n"} +{"Prompt":"Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values. For example: Input: 5 Output: True because the binary representation of 5 is: 101. Input: 7 Output: False because the binary representation of 7 is: 111. Input: 11 Output: False because the binary representation of 11 is: 1011. Input: 10 Output: True because The binary representation of 10 is: 1010. Time Complexity Onumber of bits in n Time Complexity O1","Completions":"# Time Complexity - O(number of bits in n)\ndef has_alternative_bit(n):\n first_bit = 0\n second_bit = 0\n while n:\n first_bit = n & 1\n if n >> 1:\n second_bit = (n >> 1) & 1\n if not first_bit ^ second_bit:\n return False\n else:\n return True\n n = n >> 1\n return True \n\n# Time Complexity - O(1)\ndef has_alternative_bit_fast(n):\n mask1 = int('aaaaaaaa', 16) # for bits ending with zero (...1010)\n mask2 = int('55555555', 16) # for bits ending with one (...0101)\n return mask1 == (n + (n ^ mask1)) or mask2 == (n + (n ^ mask2))\n"} +{"Prompt":"Insertion: insertonebitnum, bit, i: insert exact one bit at specific position For example: Input: num 10101 21 insertonebitnum, 1, 2: 101101 45 insertonebitnum, 0, 2: 101001 41 insertonebitnum, 1, 5: 110101 53 insertonebitnum, 1, 0: 101011 43 insertmultbitsnum, bits, len, i: insert multiple bits with len at specific position For example: Input: num 101 5 insertmultbitsnum, 7, 3, 1: 101111 47 insertmultbitsnum, 7, 3, 0: 101111 47 insertmultbitsnum, 7, 3, 3: 111101 61 Insert exact one bit at specific position Algorithm: 1. Create a mask having bit from i to the most significant bit, and append the new bit at 0 position 2. Keep the bit from 0 position to i position like 000...001111 3. Merge mask and num Create mask Keep the bit from 0 position to i position","Completions":"\"\"\"\nInsert exact one bit at specific position\n\nAlgorithm:\n1. Create a mask having bit from i to the most significant bit, and append the new bit at 0 position\n2. Keep the bit from 0 position to i position ( like 000...001111)\n3. Merge mask and num\n\"\"\"\ndef insert_one_bit(num, bit, i):\n # Create mask\n mask = num >> i\n mask = (mask << 1) | bit\n mask = mask << i\n # Keep the bit from 0 position to i position\n right = ((1 << i) - 1) & num\n return right | mask\n\ndef insert_mult_bits(num, bits, len, i):\n mask = num >> i\n mask = (mask << len) | bits\n mask = mask << i\n right = ((1 << i) - 1) & num\n return right | mask\n"} +{"Prompt":"given an integer, write a function to determine if it is a power of two :type n: int :rtype: bool","Completions":"def is_power_of_two(n):\n \"\"\"\n :type n: int\n :rtype: bool\n \"\"\"\n return n > 0 and not n & (n-1)\n"} +{"Prompt":"Removebitnum, i: remove a bit at specific position. For example: Input: num 10101 21 removebitnum, 2: output 1001 9 removebitnum, 4: output 101 5 removebitnum, 0: output 1010 10","Completions":"def remove_bit(num, i):\n mask = num >> (i + 1)\n mask = mask << i\n right = ((1 << i) - 1) & num\n return mask | right\n"} +{"Prompt":"Reverse bits of a given 32 bits unsigned integer. For example, given input 43261596 represented in binary as 00000010100101000001111010011100, return 964176192 represented in binary as 00111001011110000010100101000000.","Completions":"def reverse_bits(n):\n m = 0\n i = 0\n while i < 32:\n m = (m << 1) + (n & 1)\n n >>= 1\n i += 1\n return m\n"} +{"Prompt":"Given an array of integers, every element appears twice except for one. Find that single one. NOTE: This also works for finding a number occurring odd number of times, where all the other numbers appear even number of times. Note: Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? Returns single number, if found. Else if all numbers appear twice, returns 0. :type nums: Listint :rtype: int","Completions":"def single_number(nums):\n \"\"\"\n Returns single number, if found.\n Else if all numbers appear twice, returns 0.\n :type nums: List[int]\n :rtype: int\n \"\"\"\n i = 0\n for num in nums:\n i ^= num\n return i\n"} +{"Prompt":"Given an array of integers, every element appears three times except for one, which appears exactly once. Find that single one. Note: Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? Solution: 32 bits for each integer. Consider 1 bit in it, the sum of each integer's corresponding bit except for the single number should be 0 if mod by 3. Hence, we sum the bits of all integers and mod by 3, the remaining should be the exact bit of the single number. In this way, you get the 32 bits of the single number. Another awesome answer","Completions":"# Another awesome answer\ndef single_number2(nums):\n ones, twos = 0, 0\n for i in range(len(nums)):\n ones = (ones ^ nums[i]) & ~twos\n twos = (twos ^ nums[i]) & ~ones\n return ones\n"} +{"Prompt":"Given 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. Limitation: Time Complexity: ON and Space Complexity O1 For example: Given nums 1, 2, 1, 3, 2, 5, return 3, 5. Note: The order of the result is not important. So in the above example, 5, 3 is also correct. Solution: 1. Use XOR to cancel out the pairs and isolate AB 2. It is guaranteed that at least 1 bit exists in AB since A and B are different numbers. ex 010 111 101 3. Single out one bit R right most bit in this solution to use it as a pivot 4. Divide all numbers into two groups. One group with a bit in the position R One group without a bit in the position R 5. Use the same strategy we used in step 1 to isolate A and B from each group. :type nums: Listint :rtype: Listint isolate ab from pairs using XOR isolate right most bit from ab isolate a and b from ab","Completions":"def single_number3(nums):\n \"\"\"\n :type nums: List[int]\n :rtype: List[int]\n \"\"\"\n # isolate a^b from pairs using XOR\n ab = 0\n for n in nums:\n ab ^= n\n\n # isolate right most bit from a^b\n right_most = ab & (-ab)\n\n # isolate a and b from a^b\n a, b = 0, 0\n for n in nums:\n if n & right_most:\n a ^= n\n else:\n b ^= n\n return [a, b]\n"} +{"Prompt":"Given a set of distinct integers, nums, return all possible subsets. Note: The solution set must not contain duplicate subsets. For example, If nums 1,2,3, a solution is: 1, 2, 1, 3, 1,, 2,, 3,, 1, 2, 3, , 2, 3 :param nums: Listint :return: Settuple this explanation is from leetnik leetcode This is an amazing solution. Learnt a lot. Number of subsets for 1 , 2 , 3 23 . why ? case possible outcomes for the set of subsets 1 Take or dont take 2 2 Take or dont take 2 3 Take or dont take 2 therefore, total 222 23 , 1, 2, 3, 1,2, 1,3, 2,3, 1,2,3 Lets assign bits to each outcome First bit to 1 , Second bit to 2 and third bit to 3 Take 1 Dont take 0 0 0 0 0 Dont take 3 , Dont take 2 , Dont take 1 1 0 0 1 Dont take 3 , Dont take 2 , take 1 1 2 0 1 0 Dont take 3 , take 2 , Dont take 1 2 3 0 1 1 Dont take 3 , take 2 , take 1 1 , 2 4 1 0 0 take 3 , Dont take 2 , Dont take 1 3 5 1 0 1 take 3 , Dont take 2 , take 1 1 , 3 6 1 1 0 take 3 , take 2 , Dont take 1 2 , 3 7 1 1 1 take 3 , take 2 , take 1 1 , 2 , 3 In the above logic ,Insert Si only if ji1 true j E 0,1,2,3,4,5,6,7 i ith element in the input array element 1 is inserted only into those places where 1st bit of j is 1 if j 0 1 for above above eg. this is true for sl.no. j 1 , 3 , 5 , 7 element 2 is inserted only into those places where 2nd bit of j is 1 if j 1 1 for above above eg. this is true for sl.no. j 2 , 3 , 6 , 7 element 3 is inserted only into those places where 3rd bit of j is 1 if j 2 1 for above above eg. this is true for sl.no. j 4 , 5 , 6 , 7 Time complexity : On2n , for every input element loop traverses the whole solution set length i.e. 2n","Completions":"def subsets(nums):\n \"\"\"\n :param nums: List[int]\n :return: Set[tuple]\n \"\"\"\n n = len(nums)\n total = 1 << n\n res = set()\n\n for i in range(total):\n subset = tuple(num for j, num in enumerate(nums) if i & 1 << j)\n res.add(subset)\n\n return res\n\"\"\"\nthis explanation is from leet_nik @ leetcode\nThis is an amazing solution. Learnt a lot.\n\nNumber of subsets for {1 , 2 , 3 } = 2^3 .\nwhy ?\ncase possible outcomes for the set of subsets\n 1 -> Take or dont take = 2\n 2 -> Take or dont take = 2\n 3 -> Take or dont take = 2\n\ntherefore,\ntotal = 2*2*2 = 2^3 = {{}, {1}, {2}, {3}, {1,2}, {1,3}, {2,3}, {1,2,3}}\n\nLets assign bits to each outcome ->\nFirst bit to 1 , Second bit to 2 and third bit to 3\nTake = 1\nDont take = 0\n\n0) 0 0 0 -> Dont take 3 , Dont take 2 , Dont take 1 = { }\n1) 0 0 1 -> Dont take 3 , Dont take 2 , take 1 = { 1 }\n2) 0 1 0 -> Dont take 3 , take 2 , Dont take 1 = { 2 }\n3) 0 1 1 -> Dont take 3 , take 2 , take 1 = { 1 , 2 }\n4) 1 0 0 -> take 3 , Dont take 2 , Dont take 1 = { 3 }\n5) 1 0 1 -> take 3 , Dont take 2 , take 1 = { 1 , 3 }\n6) 1 1 0 -> take 3 , take 2 , Dont take 1 = { 2 , 3 }\n7) 1 1 1 -> take 3 , take 2 , take 1 = { 1 , 2 , 3 }\n\nIn the above logic ,Insert S[i] only if (j>>i)&1 ==true\n{ j E { 0,1,2,3,4,5,6,7 } i = ith element in the input array }\n\nelement 1 is inserted only into those places where 1st bit of j is 1\nif( j >> 0 &1 ) ==> for above above eg.\nthis is true for sl.no.( j )= 1 , 3 , 5 , 7\n\nelement 2 is inserted only into those places where 2nd bit of j is 1\nif( j >> 1 &1 ) == for above above eg.\nthis is true for sl.no.( j ) = 2 , 3 , 6 , 7\n\nelement 3 is inserted only into those places where 3rd bit of j is 1\nif( j >> 2 & 1 ) == for above above eg.\nthis is true for sl.no.( j ) = 4 , 5 , 6 , 7\n\nTime complexity : O(n*2^n) , for every input element loop traverses\nthe whole solution set length i.e. 2^n\n\"\"\"\n"} +{"Prompt":"Swappair: A function swap odd and even bits in an integer with as few instructions as possible Ex bit and bit 1 are swapped, bit 2 and bit 3 are swapped For example: 22: 010110 41: 101001 10: 1010 5 : 0101 We can approach this as operating on the odds bit first, and then the even bits. We can mask all odd bits with 10101010 in binary 'AA' then shift them right by 1 Similarly, we mask all even bit with 01010101 in binary '55' then shift them left by 1. Finally, we merge these two values by OR operation. odd bit arithmetic right shift 1 bit even bit left shift 1 bit","Completions":"\"\"\"\nWe can approach this as operating on the odds bit first, and then the even bits.\nWe can mask all odd bits with 10101010 in binary ('AA') then shift them right by 1\nSimilarly, we mask all even bit with 01010101 in binary ('55') then shift them left\nby 1. Finally, we merge these two values by OR operation.\n\"\"\"\ndef swap_pair(num):\n # odd bit arithmetic right shift 1 bit\n odd = (num & int('AAAAAAAA', 16)) >> 1\n # even bit left shift 1 bit\n even = (num & int('55555555', 16)) << 1\n return odd | even\n"} +{"Prompt":"Elias code or Elias gamma code is a universal code encoding positive integers. It is used most commonly when coding integers whose upperbound cannot be determined beforehand. Elias code or Elias delta code is a universal code encoding the positive integers, that includes Elias code when calculating. Both were developed by Peter Elias. Calculates the binary number Calculates the unary number The compressed data is calculated in two parts. The first part is the unary number of 1 log2x. The second part is the binary number of x 2log2x. For the final result we add these two parts. For the first part we put the unary number of x. For the first part we put the eliasg of the number.","Completions":"from math import log\n\nlog2 = lambda x: log(x, 2)\n\n# Calculates the binary number\ndef binary(x, l=1):\n\tfmt = '{0:0%db}' % l\n\treturn fmt.format(x)\n\n# Calculates the unary number\ndef unary(x):\n\treturn (x-1)*'1'+'0'\n\ndef elias_generic(lencoding, x):\n\t\"\"\"\n\tThe compressed data is calculated in two parts.\n\tThe first part is the unary number of 1 + \u230alog2(x)\u230b.\n\tThe second part is the binary number of x - 2^(\u230alog2(x)\u230b).\n\tFor the final result we add these two parts.\n\t\"\"\"\n\tif x == 0:\n\t\treturn '0'\n\t\n\tfirst_part = 1 + int(log2(x))\n\t\n\ta = x - 2**(int(log2(x)))\n\t\n\tk = int(log2(x))\n\n\treturn lencoding(first_part) + binary(a, k)\n\ndef elias_gamma(x):\n\t\"\"\"\n\tFor the first part we put the unary number of x.\n\t\"\"\"\n\treturn elias_generic(unary, x)\n\ndef elias_delta(x):\n\t\"\"\"\n\tFor the first part we put the elias_g of the number.\n\t\"\"\"\n\treturn elias_generic(elias_gamma, x)\n"} +{"Prompt":"Huffman coding is an efficient method of compressing data without losing information. This algorithm analyzes the symbols that appear in a message. Symbols that appear more often will be encoded as a shorterbit string while symbols that aren't used as much will be encoded as longer strings. Load tree from file :return: Load values to tree after reading tree :param leavesqueue: :return: Load next byte is buffer is less than bufflimit :param bufflimit: :return: True if there is enough bits in buffer to read Generate and save tree code to file :param tree: :return: Overwrite first three bits in the file :param additionalbits: number of bits that were appended to fill last byte :return: overwrite first three bits Class to help find signs in tree Find sign in tree :param bit: :return: True if sign is found","Completions":"from collections import defaultdict, deque\nimport heapq\n\n\nclass Node:\n def __init__(self, frequency=0, sign=None, left=None, right=None):\n self.frequency = frequency\n self.sign = sign\n self.left = left\n self.right = right\n\n def __lt__(self, other):\n return self.frequency < other.frequency\n\n def __gt__(self, other):\n return self.frequency > other.frequency\n\n def __eq__(self, other):\n return self.frequency == other.frequency\n\n def __str__(self):\n return \"\".format(self.sign, self.frequency)\n\n def __repr__(self):\n return \"\".format(self.sign, self.frequency)\n\n\nclass HuffmanReader:\n def __init__(self, file):\n self.file = file\n self.buffer = []\n self.is_last_byte = False\n\n def get_number_of_additional_bits_in_the_last_byte(self) -> int:\n bin_num = self.get_bit() + self.get_bit() + self.get_bit()\n return int(bin_num, 2)\n\n def load_tree(self) -> Node:\n \"\"\"\n Load tree from file\n\n :return:\n \"\"\"\n node_stack = deque()\n queue_leaves = deque()\n root = Node()\n\n current_node = root\n is_end_of_tree = False\n while not is_end_of_tree:\n current_bit = self.get_bit()\n if current_bit == \"0\":\n current_node.left = Node()\n current_node.right = Node()\n node_stack.append(current_node.right) # going to left node, right push on stack\n current_node = current_node.left\n else:\n queue_leaves.append(current_node)\n if node_stack:\n current_node = node_stack.pop()\n else:\n is_end_of_tree = True\n\n self._fill_tree(queue_leaves)\n\n return root\n\n def _fill_tree(self, leaves_queue):\n \"\"\"\n Load values to tree after reading tree\n :param leaves_queue:\n :return:\n \"\"\"\n leaves_queue.reverse()\n while leaves_queue:\n node = leaves_queue.pop()\n s = int(self.get_byte(), 2)\n node.sign = s\n\n def _load_byte(self, buff_limit=8) -> bool:\n \"\"\"\n Load next byte is buffer is less than buff_limit\n :param buff_limit:\n :return: True if there is enough bits in buffer to read\n \"\"\"\n if len(self.buffer) <= buff_limit:\n byte = self.file.read(1)\n\n if not byte:\n return False\n\n i = int.from_bytes(byte, \"big\")\n self.buffer.extend(list(\"{0:08b}\".format(i)))\n\n return True\n\n def get_bit(self, buff_limit=8):\n if self._load_byte(buff_limit):\n bit = self.buffer.pop(0)\n return bit\n else:\n return -1\n\n def get_byte(self):\n if self._load_byte():\n byte_list = self.buffer[:8]\n self.buffer = self.buffer[8:]\n\n return \"\".join(byte_list)\n else:\n return -1\n\n\nclass HuffmanWriter:\n def __init__(self, file):\n self.file = file\n self.buffer = \"\"\n self.saved_bits = 0\n\n def write_char(self, char):\n self.write_int(ord(char))\n\n def write_int(self, num):\n bin_int = \"{0:08b}\".format(num)\n self.write_bits(bin_int)\n\n def write_bits(self, bits):\n self.saved_bits += len(bits)\n\n self.buffer += bits\n\n while len(self.buffer) >= 8:\n i = int(self.buffer[:8], 2)\n self.file.write(bytes([i]))\n self.buffer = self.buffer[8:]\n\n def save_tree(self, tree):\n \"\"\"\n Generate and save tree code to file\n :param tree:\n :return:\n \"\"\"\n signs = []\n tree_code = \"\"\n\n def get_code_tree(T):\n nonlocal tree_code\n if T.sign is not None:\n signs.append(T.sign)\n if T.left:\n tree_code += \"0\"\n get_code_tree(T.left)\n if T.right:\n tree_code += \"1\"\n get_code_tree(T.right)\n\n get_code_tree(tree)\n self.write_bits(tree_code + \"1\") # \"1\" indicates that tree ended (it will be needed to load the tree)\n for int_sign in signs:\n self.write_int(int_sign)\n\n def _save_information_about_additional_bits(self, additional_bits: int):\n \"\"\"\n Overwrite first three bits in the file\n :param additional_bits: number of bits that were appended to fill last byte\n :return:\n \"\"\"\n self.file.seek(0)\n first_byte_raw = self.file.read(1)\n self.file.seek(0)\n first_byte = \"{0:08b}\".format(int.from_bytes(first_byte_raw, \"big\"))\n # overwrite first three bits\n first_byte = first_byte[3:]\n first_byte = \"{0:03b}\".format(additional_bits) + first_byte\n\n self.write_bits(first_byte)\n\n def close(self):\n additional_bits = 8 - len(self.buffer)\n if additional_bits != 8: # buffer is empty, no need to append extra \"0\"\n self.write_bits(\"0\" * additional_bits)\n self._save_information_about_additional_bits(additional_bits)\n\n\nclass TreeFinder:\n \"\"\"\n Class to help find signs in tree\n \"\"\"\n\n def __init__(self, tree):\n self.root = tree\n self.current_node = tree\n self.found = None\n\n def find(self, bit):\n \"\"\"\n Find sign in tree\n :param bit:\n :return: True if sign is found\n \"\"\"\n if bit == \"0\":\n self.current_node = self.current_node.left\n elif bit == \"1\":\n self.current_node = self.current_node.right\n else:\n self._reset()\n return True\n\n if self.current_node.sign is not None:\n self._reset(self.current_node.sign)\n return True\n else:\n return False\n\n def _reset(self, found=\"\"):\n self.found = found\n self.current_node = self.root\n\n\nclass HuffmanCoding:\n def __init__(self):\n pass\n\n @staticmethod\n def decode_file(file_in_name, file_out_name):\n with open(file_in_name, \"rb\") as file_in, open(file_out_name, \"wb\") as file_out:\n reader = HuffmanReader(file_in)\n additional_bits = reader.get_number_of_additional_bits_in_the_last_byte()\n tree = reader.load_tree()\n\n HuffmanCoding._decode_and_write_signs_to_file(file_out, reader, tree, additional_bits)\n\n print(\"File decoded.\")\n\n @staticmethod\n def _decode_and_write_signs_to_file(file, reader: HuffmanReader, tree: Node, additional_bits: int):\n tree_finder = TreeFinder(tree)\n is_end_of_file = False\n\n while not is_end_of_file:\n bit = reader.get_bit()\n if bit != -1:\n while not tree_finder.find(bit): # read whole code\n bit = reader.get_bit(0)\n file.write(bytes([tree_finder.found]))\n else: # There is last byte in buffer to parse\n is_end_of_file = True\n last_byte = reader.buffer\n last_byte = last_byte[:-additional_bits] # remove additional \"0\" used to fill byte\n for bit in last_byte:\n if tree_finder.find(bit):\n file.write(bytes([tree_finder.found]))\n\n @staticmethod\n def encode_file(file_in_name, file_out_name):\n with open(file_in_name, \"rb\") as file_in, open(file_out_name, mode=\"wb+\") as file_out:\n signs_frequency = HuffmanCoding._get_char_frequency(file_in)\n file_in.seek(0)\n tree = HuffmanCoding._create_tree(signs_frequency)\n codes = HuffmanCoding._generate_codes(tree)\n\n writer = HuffmanWriter(file_out)\n writer.write_bits(\"000\") # leave space to save how many bits will be appended to fill the last byte\n writer.save_tree(tree)\n HuffmanCoding._encode_and_write_signs_to_file(file_in, writer, codes)\n writer.close()\n\n print(\"File encoded.\")\n\n @staticmethod\n def _encode_and_write_signs_to_file(file, writer: HuffmanWriter, codes: dict):\n sign = file.read(1)\n while sign:\n int_char = int.from_bytes(sign, \"big\")\n writer.write_bits(codes[int_char])\n sign = file.read(1)\n\n @staticmethod\n def _get_char_frequency(file) -> dict:\n is_end_of_file = False\n signs_frequency = defaultdict(lambda: 0)\n while not is_end_of_file:\n prev_pos = file.tell()\n sign = file.read(1)\n curr_pos = file.tell()\n if prev_pos == curr_pos:\n is_end_of_file = True\n else:\n signs_frequency[int.from_bytes(sign, \"big\")] += 1\n\n return signs_frequency\n\n @staticmethod\n def _generate_codes(tree: Node) -> dict:\n codes = dict()\n HuffmanCoding._go_through_tree_and_create_codes(tree, \"\", codes)\n return codes\n\n @staticmethod\n def _create_tree(signs_frequency: dict) -> Node:\n nodes = [Node(frequency=frequency, sign=char_int) for char_int, frequency in signs_frequency.items()]\n heapq.heapify(nodes)\n\n while len(nodes) > 1:\n left = heapq.heappop(nodes)\n right = heapq.heappop(nodes)\n new_node = Node(frequency=left.frequency + right.frequency, left=left, right=right)\n heapq.heappush(nodes, new_node)\n\n return nodes[0] # root\n\n @staticmethod\n def _go_through_tree_and_create_codes(tree: Node, code: str, dict_codes: dict):\n if tree.sign is not None:\n dict_codes[tree.sign] = code\n\n if tree.left:\n HuffmanCoding._go_through_tree_and_create_codes(tree.left, code + \"0\", dict_codes)\n\n if tree.right:\n HuffmanCoding._go_through_tree_and_create_codes(tree.right, code + \"1\", dict_codes)\n"} +{"Prompt":"Runlength encoding RLE is a simple compression algorithm that gets a stream of data as the input and returns a sequence of counts of consecutive data values in a row. When decompressed the data will be fully recovered as RLE is a lossless data compression. Gets a stream of data and compresses it under a RunLength Encoding. :param input: The data to be encoded. :return: The encoded string. Check If the subsequent character does not match Add the count and character Reset the count and set the character Otherwise increment the counter Gets a stream of data and decompresses it under a RunLength Decoding. :param input: The data to be decoded. :return: The decoded string. If not numerical Expand it for the decoding Add it in the counter","Completions":"def encode_rle(input):\n \"\"\"\n Gets a stream of data and compresses it\n under a Run-Length Encoding.\n :param input: The data to be encoded.\n :return: The encoded string.\n \"\"\"\n if not input: return ''\n\n encoded_str = ''\n prev_ch = ''\n count = 1\n\n for ch in input:\n\n # Check If the subsequent character does not match\n if ch != prev_ch:\n # Add the count and character\n if prev_ch:\n encoded_str += str(count) + prev_ch\n # Reset the count and set the character\n count = 1\n prev_ch = ch\n else:\n # Otherwise increment the counter\n count += 1\n else:\n return encoded_str + (str(count) + prev_ch)\n\n\ndef decode_rle(input):\n \"\"\"\n Gets a stream of data and decompresses it\n under a Run-Length Decoding.\n :param input: The data to be decoded.\n :return: The decoded string.\n \"\"\"\n decode_str = ''\n count = ''\n\n for ch in input:\n # If not numerical\n if not ch.isdigit():\n # Expand it for the decoding\n decode_str += ch * int(count)\n count = ''\n else:\n # Add it in the counter\n count += ch\n return decode_str\n"} +{"Prompt":"Numbers can be regarded as product of its factors. For example, 8 2 x 2 x 2; 2 x 4. Write a function that takes an integer n and return all possible combinations of its factors.Numbers can be regarded as product of its factors. For example, 8 2 x 2 x 2; 2 x 4. Examples: input: 1 output: input: 37 output: input: 32 output: 2, 16, 2, 2, 8, 2, 2, 2, 4, 2, 2, 2, 2, 2, summary Arguments: n int to analysed number Returns: list of lists all factors of the number n summary helper function Arguments: n int number i int to tested divisor combi list catch divisors res list all factors of the number n Returns: list res summary Computes all factors of n. Translated the function getfactors... in a callstack modell. Arguments: n int to analysed number Returns: list of lists all factors summary analog as above Arguments: n int description Returns: list of lists all factors of n","Completions":"def get_factors(n):\n \"\"\"[summary]\n \n Arguments:\n n {[int]} -- [to analysed number]\n \n Returns:\n [list of lists] -- [all factors of the number n]\n \"\"\"\n\n def factor(n, i, combi, res):\n \"\"\"[summary]\n helper function\n\n Arguments:\n n {[int]} -- [number]\n i {[int]} -- [to tested divisor]\n combi {[list]} -- [catch divisors]\n res {[list]} -- [all factors of the number n]\n \n Returns:\n [list] -- [res]\n \"\"\"\n\n while i * i <= n:\n if n % i == 0:\n res += combi + [i, int(n\/i)],\n factor(n\/i, i, combi+[i], res)\n i += 1\n return res\n return factor(n, 2, [], [])\n\n\ndef get_factors_iterative1(n):\n \"\"\"[summary]\n Computes all factors of n.\n Translated the function get_factors(...) in\n a call-stack modell.\n\n Arguments:\n n {[int]} -- [to analysed number]\n \n Returns:\n [list of lists] -- [all factors]\n \"\"\"\n\n todo, res = [(n, 2, [])], []\n while todo:\n n, i, combi = todo.pop()\n while i * i <= n:\n if n % i == 0:\n res += combi + [i, n\/\/i],\n todo.append((n\/\/i, i, combi+[i])),\n i += 1\n return res\n\n\ndef get_factors_iterative2(n):\n \"\"\"[summary]\n analog as above\n\n Arguments:\n n {[int]} -- [description]\n \n Returns:\n [list of lists] -- [all factors of n]\n \"\"\"\n\n ans, stack, x = [], [], 2\n while True:\n if x > n \/\/ x:\n if not stack:\n return ans\n ans.append(stack + [n])\n x = stack.pop()\n n *= x\n x += 1\n elif n % x == 0:\n stack.append(x)\n n \/\/= x\n else:\n x += 1\n"} +{"Prompt":"Given 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. Example 1: 11110 11010 11000 00000 Answer: 1 Example 2: 11000 11000 00100 00011 Answer: 3","Completions":"def num_islands(grid):\n count = 0\n for i in range(len(grid)):\n for j, col in enumerate(grid[i]):\n if col == 1:\n dfs(grid, i, j)\n count += 1\n return count\n\n\ndef dfs(grid, i, j):\n if (i < 0 or i >= len(grid)) or (j < 0 or j >= len(grid[0])):\n return\n if grid[i][j] != 1:\n return\n grid[i][j] = 0\n dfs(grid, i+1, j)\n dfs(grid, i-1, j)\n dfs(grid, i, j+1)\n dfs(grid, i, j-1)\n"} +{"Prompt":"Find shortest path from top left column to the right lowest column using DFS. only step on the columns whose value is 1 if there is no path, it returns 1 The first columntop left column is not included in the answer. Ex 1 If maze is 1,0,1,1,1,1, 1,0,1,0,1,0, 1,0,1,0,1,1, 1,1,1,0,1,1, the answer is: 14 Ex 2 If maze is 1,0,0, 0,1,1, 0,1,1, the answer is: 1","Completions":"def find_path(maze):\n cnt = dfs(maze, 0, 0, 0, -1)\n return cnt\n\n\ndef dfs(maze, i, j, depth, cnt):\n directions = [(0, -1), (0, 1), (-1, 0), (1, 0)]\n\n row = len(maze)\n col = len(maze[0])\n\n if i == row - 1 and j == col - 1:\n if cnt == -1:\n cnt = depth\n else:\n if cnt > depth:\n cnt = depth\n return cnt\n\n maze[i][j] = 0\n\n for k in range(len(directions)):\n nx_i = i + directions[k][0]\n nx_j = j + directions[k][1]\n\n if nx_i >= 0 and nx_i < row and nx_j >= 0 and nx_j < col:\n if maze[nx_i][nx_j] == 1:\n cnt = dfs(maze, nx_i, nx_j, depth + 1, cnt)\n\n maze[i][j] = 1\n\n return cnt\n"} +{"Prompt":"Given an m x n matrix of nonnegative integers representing the height of each unit cell in a continent, the Pacific ocean touches the left and top edges of the matrix and the Atlantic ocean touches the right and bottom edges. Water can only flow in four directions up, down, left, or right from a cell to another one with height equal or lower. Find the list of grid coordinates where water can flow to both the Pacific and Atlantic ocean. Note: The order of returned grid coordinates does not matter. Both m and n are less than 150. Example: Given the following 5x5 matrix: Pacific 1 2 2 3 5 3 2 3 4 4 2 4 5 3 1 6 7 1 4 5 5 1 1 2 4 Atlantic Return: 0, 4, 1, 3, 1, 4, 2, 2, 3, 0, 3, 1, 4, 0 positions with parentheses in above matrix. :type matrix: ListListint :rtype: ListListint","Completions":"# Given an m x n matrix of non-negative integers representing\n# the height of each unit cell in a continent,\n# the \"Pacific ocean\" touches the left and top edges of the matrix\n# and the \"Atlantic ocean\" touches the right and bottom edges.\n\n# Water can only flow in four directions (up, down, left, or right)\n# from a cell to another one with height equal or lower.\n\n# Find the list of grid coordinates where water can flow to both the\n# Pacific and Atlantic ocean.\n\n# Note:\n# The order of returned grid coordinates does not matter.\n# Both m and n are less than 150.\n# Example:\n\n# Given the following 5x5 matrix:\n\n # Pacific ~ ~ ~ ~ ~\n # ~ 1 2 2 3 (5) *\n # ~ 3 2 3 (4) (4) *\n # ~ 2 4 (5) 3 1 *\n # ~ (6) (7) 1 4 5 *\n # ~ (5) 1 1 2 4 *\n # * * * * * Atlantic\n\n# Return:\n\n# [[0, 4], [1, 3], [1, 4], [2, 2], [3, 0], [3, 1], [4, 0]]\n# (positions with parentheses in above matrix).\n\ndef pacific_atlantic(matrix):\n \"\"\"\n :type matrix: List[List[int]]\n :rtype: List[List[int]]\n \"\"\"\n n = len(matrix)\n if not n: return []\n m = len(matrix[0])\n if not m: return []\n res = []\n atlantic = [[False for _ in range (n)] for _ in range(m)]\n pacific = [[False for _ in range (n)] for _ in range(m)]\n for i in range(n):\n dfs(pacific, matrix, float(\"-inf\"), i, 0)\n dfs(atlantic, matrix, float(\"-inf\"), i, m-1)\n for i in range(m):\n dfs(pacific, matrix, float(\"-inf\"), 0, i)\n dfs(atlantic, matrix, float(\"-inf\"), n-1, i)\n for i in range(n):\n for j in range(m):\n if pacific[i][j] and atlantic[i][j]:\n res.append([i, j])\n return res\n\ndef dfs(grid, matrix, height, i, j):\n if i < 0 or i >= len(matrix) or j < 0 or j >= len(matrix[0]):\n return\n if grid[i][j] or matrix[i][j] < height:\n return\n grid[i][j] = True\n dfs(grid, matrix, matrix[i][j], i-1, j)\n dfs(grid, matrix, matrix[i][j], i+1, j)\n dfs(grid, matrix, matrix[i][j], i, j-1)\n dfs(grid, matrix, matrix[i][j], i, j+1)\n"} +{"Prompt":"It's similar to how human solve Sudoku. create a hash table dictionary val to store possible values in every location. Each time, start from the location with fewest possible values, choose one value from it and then update the board and possible values at other locations. If this update is valid, keep solving DFS. If this update is invalid leaving zero possible values at some locations or this value doesn't lead to the solution, undo the updates and then choose the next value. Since we calculated val at the beginning and start filling the board from the location with fewest possible values, the amount of calculation and thus the runtime can be significantly reduced: The run time is 4868 ms on LeetCode OJ, which seems to be among the fastest python solutions here. The PossibleVals function may be further simplifiedoptimized, but it works just fine for now. it would look less lengthy if we are allowed to use numpy array for the board lol. summary Generates a board representation as string. Returns: str board representation","Completions":"class Sudoku: \n def __init__ (self, board, row, col):\n self.board = board\n self.row = row\n self.col = col\n self.val = self.possible_values()\n\n def possible_values(self):\n a = \"123456789\"\n d, val = {}, {}\n for i in range(self.row):\n for j in range(self.col):\n ele = self.board[i][j]\n if ele != \".\":\n d[(\"r\", i)] = d.get((\"r\", i), []) + [ele]\n d[(\"c\", j)] = d.get((\"c\", j), []) + [ele]\n d[(i\/\/3, j\/\/3)] = d.get((i\/\/3, j\/\/3), []) + [ele]\n else:\n val[(i,j)] = []\n for (i,j) in val.keys():\n inval = d.get((\"r\",i),[])+d.get((\"c\",j),[])+d.get((i\/3,j\/3),[])\n val[(i,j)] = [n for n in a if n not in inval ]\n return val\n\n def solve(self):\n if len(self.val)==0:\n return True\n kee = min(self.val.keys(), key=lambda x: len(self.val[x]))\n nums = self.val[kee]\n for n in nums:\n update = {kee:self.val[kee]}\n if self.valid_one(n, kee, update): # valid choice\n if self.solve(): # keep solving\n return True\n self.undo(kee, update) # invalid choice or didn't solve it => undo\n return False\n\n def valid_one(self, n, kee, update):\n self.board[kee[0]][kee[1]] = n\n del self.val[kee]\n i, j = kee\n for ind in self.val.keys():\n if n in self.val[ind]:\n if ind[0]==i or ind[1]==j or (ind[0]\/3,ind[1]\/3)==(i\/3,j\/3):\n update[ind] = n\n self.val[ind].remove(n)\n if len(self.val[ind])==0:\n return False\n return True\n\n def undo(self, kee, update):\n self.board[kee[0]][kee[1]]=\".\"\n for k in update:\n if k not in self.val:\n self.val[k]= update[k]\n else:\n self.val[k].append(update[k])\n return None\n\n def __str__(self):\n \"\"\"[summary]\n Generates a board representation as string.\n\n Returns:\n [str] -- [board representation]\n \"\"\"\n\n resp = \"\"\n for i in range(self.row):\n for j in range(self.col):\n resp += \" {0} \".format(self.board[i][j])\n resp += \"\\n\"\n return resp\n"} +{"Prompt":"You are given a m x n 2D grid initialized with these three possible values: 1: A wall or an obstacle. 0: A gate. INF: Infinity means an empty room. We use the value 231 1 2147483647 to represent INF as you may assume that the distance to a gate is less than 2147483647. Fill the empty room with distance to its nearest gate. If it is impossible to reach a gate, it should be filled with INF. For example, given the 2D grid: INF 1 0 INF INF INF INF 1 INF 1 INF 1 0 1 INF INF After running your function, the 2D grid should be: 3 1 0 1 2 2 1 1 1 1 2 1 0 1 3 4","Completions":"def walls_and_gates(rooms):\n for i in range(len(rooms)):\n for j in range(len(rooms[0])):\n if rooms[i][j] == 0:\n dfs(rooms, i, j, 0)\n\n\ndef dfs(rooms, i, j, depth):\n if (i < 0 or i >= len(rooms)) or (j < 0 or j >= len(rooms[0])):\n return # out of bounds\n if rooms[i][j] < depth:\n return # crossed\n rooms[i][j] = depth\n dfs(rooms, i+1, j, depth+1)\n dfs(rooms, i-1, j, depth+1)\n dfs(rooms, i, j+1, depth+1)\n dfs(rooms, i, j-1, depth+1)\n"} +{"Prompt":"Histogram function. Histogram is an accurate representation of the distribution of numerical data. It is an estimate of the probability distribution of a continuous variable. https:en.wikipedia.orgwikiHistogram Example: list1 3, 3, 2, 1 :return 1: 1, 2: 1, 3: 2 list2 2, 3, 5, 5, 5, 6, 4, 3, 7 :return 2: 1, 3: 2, 4: 1, 5: 3, 6: 1, 7: 1 Get histogram representation :param inputlist: list with different and unordered values :return histogram: dict with histogram of inputlist Create dict to store histogram For each list value, add one to the respective histogram dict position","Completions":"def get_histogram(input_list: list) -> dict:\n \"\"\"\n Get histogram representation\n :param input_list: list with different and unordered values\n :return histogram: dict with histogram of input_list\n \"\"\"\n # Create dict to store histogram\n histogram = {}\n # For each list value, add one to the respective histogram dict position\n for i in input_list:\n histogram[i] = histogram.get(i, 0) + 1\n return histogram\n"} +{"Prompt":"Say you have an array for which the ith element is the price of a given stock on day i. If you were only permitted to complete at most one transaction ie, buy one and sell one share of the stock, design an algorithm to find the maximum profit. Example 1: Input: 7, 1, 5, 3, 6, 4 Output: 5 max. difference 61 5 not 71 6, as selling price needs to be larger than buying price Example 2: Input: 7, 6, 4, 3, 1 Output: 0 In this case, no transaction is done, i.e. max profit 0. On2 time :type prices: Listint :rtype: int On time input: 7, 1, 5, 3, 6, 4 diff : X, 6, 4, 2, 3, 2 :type prices: Listint :rtype: int","Completions":"# O(n^2) time\ndef max_profit_naive(prices):\n \"\"\"\n :type prices: List[int]\n :rtype: int\n \"\"\"\n max_so_far = 0\n for i in range(0, len(prices) - 1):\n for j in range(i + 1, len(prices)):\n max_so_far = max(max_so_far, prices[j] - prices[i])\n return max_so_far\n\n\n# O(n) time\ndef max_profit_optimized(prices):\n \"\"\"\n input: [7, 1, 5, 3, 6, 4]\n diff : [X, -6, 4, -2, 3, -2]\n :type prices: List[int]\n :rtype: int\n \"\"\"\n cur_max, max_so_far = 0, 0\n for i in range(1, len(prices)):\n cur_max = max(0, cur_max + prices[i] - prices[i-1])\n max_so_far = max(max_so_far, cur_max)\n return max_so_far\n"} +{"Prompt":"You are climbing a stair case. It takes steps number of steps to reach to the top. Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? Note: Given argument steps will be a positive integer. On space :type steps: int :rtype: int the above function can be optimized as: O1 space :type steps: int :rtype: int","Completions":"# O(n) space\n\ndef climb_stairs(steps):\n \"\"\"\n :type steps: int\n :rtype: int\n \"\"\"\n arr = [1, 1]\n for _ in range(1, steps):\n arr.append(arr[-1] + arr[-2])\n return arr[-1]\n\n\n# the above function can be optimized as:\n# O(1) space\n\ndef climb_stairs_optimized(steps):\n \"\"\"\n :type steps: int\n :rtype: int\n \"\"\"\n a_steps = b_steps = 1\n for _ in range(steps):\n a_steps, b_steps = b_steps, a_steps + b_steps\n return a_steps\n"} +{"Prompt":"Problem Given a value value, if we want to make change for value cents, and we have infinite supply of each of coins S1, S2, .. , Sm valued coins, how many ways can we make the change? The order of coins doesn't matter. For example, for value 4 and coins 1, 2, 3, there are four solutions: 1, 1, 1, 1, 1, 1, 2, 2, 2, 1, 3. So output should be 4. For value 10 and coins 2, 5, 3, 6, there are five solutions: 2, 2, 2, 2, 2, 2, 2, 3, 3, 2, 2, 6, 2, 3, 5 and 5, 5. So the output should be 5. Time complexity: On m where n is the value and m is the number of coins Space complexity: On Find number of combination of coins that adds upp to value Keyword arguments: coins int value int initialize dp array and set base case as 1 fill dp in a bottom up manner","Completions":"def count(coins, value):\n \"\"\" Find number of combination of `coins` that adds upp to `value`\n\n Keyword arguments:\n coins -- int[]\n value -- int\n \"\"\"\n # initialize dp array and set base case as 1\n dp_array = [1] + [0] * value\n\n # fill dp in a bottom up manner\n for coin in coins:\n for i in range(coin, value+1):\n dp_array[i] += dp_array[i-coin]\n\n return dp_array[value]\n"} +{"Prompt":"Given an integer array with all positive numbers and no duplicates, find the number of possible combinations that add up to a positive integer target. Example: nums 1, 2, 3 target 4 The possible combination ways are: 1, 1, 1, 1 1, 1, 2 1, 2, 1 1, 3 2, 1, 1 2, 2 3, 1 Note that different sequences are counted as different combinations. Therefore the output is 7. Follow up: What if negative numbers are allowed in the given array? How does it change the problem? What limitation we need to add to the question to allow negative numbers? Generates DP and finds result. Keyword arguments: nums positive integer array without duplicates target integer describing what a valid combination should add to Find number of possible combinations in nums that add up to target, in topdown manner. Keyword arguments: nums positive integer array without duplicates target integer describing what a valid combination should add to Find number of possible combinations in nums that add up to target, in bottomup manner. Keyword arguments: nums positive integer array without duplicates target integer describing what a valid combination should add to","Completions":"DP = None\n\ndef helper_topdown(nums, target):\n \"\"\"Generates DP and finds result.\n\n Keyword arguments:\n nums -- positive integer array without duplicates\n target -- integer describing what a valid combination should add to\n \"\"\"\n if DP[target] != -1:\n return DP[target]\n res = 0\n for num in nums:\n if target >= num:\n res += helper_topdown(nums, target - num)\n DP[target] = res\n return res\n\n\ndef combination_sum_topdown(nums, target):\n \"\"\"Find number of possible combinations in nums that add up to target, in top-down manner.\n\n Keyword arguments:\n nums -- positive integer array without duplicates\n target -- integer describing what a valid combination should add to\n \"\"\"\n global DP\n DP = [-1] * (target + 1)\n DP[0] = 1\n return helper_topdown(nums, target)\n\ndef combination_sum_bottom_up(nums, target):\n \"\"\"Find number of possible combinations in nums that add up to target, in bottom-up manner.\n\n Keyword arguments:\n nums -- positive integer array without duplicates\n target -- integer describing what a valid combination should add to\n \"\"\"\n combs = [0] * (target + 1)\n combs[0] = 1\n for i in range(0, len(combs)):\n for num in nums:\n if i - num >= 0:\n combs[i] += combs[i - num]\n return combs[target]\n"} +{"Prompt":"The edit distance between two words is the minimum number of letter insertions, letter deletions, and letter substitutions required to transform one word into another. For example, the edit distance between FOOD and MONEY is at most four: FOOD MOOD MOND MONED MONEY Given two words A and B, find the minimum number of operations required to transform one string into the other. In other words, find the edit distance between A and B. Thought process: Let editi, j denote the edit distance between the prefixes A1..i and B1..j. Then, the function satifies the following recurrence: editi, j i if j 0 j if i 0 minediti1, j 1, editi, j1, 1, editi1, j1 cost otherwise There are two base cases, both of which occur when one string is empty and the other is not. 1. To convert an empty string A into a string B of length n, perform n insertions. 2. To convert a string A of length m into an empty string B, perform m deletions. Here, the cost is 1 if a substitution is required, or 0 if both chars in words A and B are the same at indexes i and j, respectively. To find the edit distance between two words A and B, we need to find editlengtha, lengthb. Time: Olengthalengthb Space: Olengthalengthb Finds edit distance between worda and wordb Kwyword arguments: worda string wordb string","Completions":"def edit_distance(word_a, word_b):\n \"\"\"Finds edit distance between word_a and word_b\n\n Kwyword arguments:\n word_a -- string\n word_b -- string\n \"\"\"\n\n length_a, length_b = len(word_a) + 1, len(word_b) + 1\n\n edit = [[0 for _ in range(length_b)] for _ in range(length_a)]\n\n for i in range(1, length_a):\n edit[i][0] = i\n\n for j in range(1, length_b):\n edit[0][j] = j\n\n for i in range(1, length_a):\n for j in range(1, length_b):\n cost = 0 if word_a[i - 1] == word_b[j - 1] else 1\n edit[i][j] = min(edit[i - 1][j] + 1, edit[i][j - 1] + 1, edit[i - 1][j - 1] + cost)\n\n return edit[-1][-1] # this is the same as edit[length_a][length_b]\n"} +{"Prompt":"You are given K eggs, and you have access to a building with N floors from 1 to N. Each egg is identical in function, and if an egg breaks, you cannot drop it again. You know that there exists a floor F with 0 F N such that any egg dropped at a floor higher than F will break, and any egg dropped at or below floor F will not break. Each move, you may take an egg if you have an unbroken one and drop it from any floor X with 1 X N. Your goal is to know with certainty what the value of F is. What is the minimum number of moves that you need to know with certainty what F is, regardless of the initial value of F? Example: Input: K 1, N 2 Output: 2 Explanation: Drop the egg from floor 1. If it breaks, we know with certainty that F 0. Otherwise, drop the egg from floor 2. If it breaks, we know with certainty that F 1. If it didn't break, then we know with certainty F 2. Hence, we needed 2 moves in the worst case to know what F is with certainty. A Dynamic Programming based Python Program for the Egg Dropping Puzzle Keyword arguments: n number of floors k number of eggs A 2D table where entery eggFloorij will represent minimum number of trials needed for i eggs and j floors. We need one trial for one floor and 0 trials for 0 floors We always need j trials for one egg and j floors. Fill rest of the entries in table using optimal substructure property eggFloornk holds the result","Completions":"# A Dynamic Programming based Python Program for the Egg Dropping Puzzle\nINT_MAX = 32767\n\n\ndef egg_drop(n, k):\n \"\"\"\n Keyword arguments:\n n -- number of floors\n k -- number of eggs\n \"\"\"\n # A 2D table where entery eggFloor[i][j] will represent minimum\n # number of trials needed for i eggs and j floors.\n egg_floor = [[0 for _ in range(k + 1)] for _ in range(n + 1)]\n\n # We need one trial for one floor and 0 trials for 0 floors\n for i in range(1, n+1):\n egg_floor[i][1] = 1\n egg_floor[i][0] = 0\n\n # We always need j trials for one egg and j floors.\n for j in range(1, k+1):\n egg_floor[1][j] = j\n\n # Fill rest of the entries in table using optimal substructure\n # property\n for i in range(2, n+1):\n for j in range(2, k+1):\n egg_floor[i][j] = INT_MAX\n for x in range(1, j+1):\n res = 1 + max(egg_floor[i-1][x-1], egg_floor[i][j-x])\n if res < egg_floor[i][j]:\n egg_floor[i][j] = res\n\n # eggFloor[n][k] holds the result\n return egg_floor[n][k]\n"} +{"Prompt":"In mathematics, the Fibonacci numbers, commonly denoted Fn, form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1. That is, F00 , F11 and Fn Fn1 Fn2 The Fibonacci numbers are the numbers in the following integer sequence. 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, . In mathematical terms, the sequence Fn of Fibonacci numbers is defined by the recurrence relation Here, given a number n, print nth Fibonacci Number. summary Computes the nth fibonacci number recursive. Problem: This implementation is very slow. approximate O2n Arguments: n int description Returns: int description precondition printfibrecursive35 9227465 slow summary This algorithm computes the nth fibbonacci number very quick. approximate On The algorithm use dynamic programming. Arguments: n int description Returns: int description precondition printfiblist100 354224848179261915075 summary Works iterative approximate On Arguments: n int description Returns: int description precondition printfibiter100 354224848179261915075","Completions":"def fib_recursive(n):\n \"\"\"[summary]\n Computes the n-th fibonacci number recursive.\n Problem: This implementation is very slow.\n approximate O(2^n)\n\n Arguments:\n n {[int]} -- [description]\n\n Returns:\n [int] -- [description]\n \"\"\"\n\n # precondition\n assert n >= 0, 'n must be a positive integer'\n\n if n <= 1:\n return n\n return fib_recursive(n-1) + fib_recursive(n-2)\n\n# print(fib_recursive(35)) # => 9227465 (slow)\n\n\ndef fib_list(n):\n \"\"\"[summary]\n This algorithm computes the n-th fibbonacci number\n very quick. approximate O(n)\n The algorithm use dynamic programming.\n\n Arguments:\n n {[int]} -- [description]\n\n Returns:\n [int] -- [description]\n \"\"\"\n\n # precondition\n assert n >= 0, 'n must be a positive integer'\n\n list_results = [0, 1]\n for i in range(2, n+1):\n list_results.append(list_results[i-1] + list_results[i-2])\n return list_results[n]\n\n# print(fib_list(100)) # => 354224848179261915075\n\n\ndef fib_iter(n):\n \"\"\"[summary]\n Works iterative approximate O(n)\n\n Arguments:\n n {[int]} -- [description]\n\n Returns:\n [int] -- [description]\n \"\"\"\n\n # precondition\n assert n >= 0, 'n must be positive integer'\n\n fib_1 = 0\n fib_2 = 1\n res = 0\n if n <= 1:\n return n\n for _ in range(n-1):\n res = fib_1 + fib_2\n fib_1 = fib_2\n fib_2 = res\n return res\n\n# print(fib_iter(100)) # => 354224848179261915075\n"} +{"Prompt":"Hosoya triangle originally Fibonacci triangle is a triangular arrangement of numbers, where if you take any number it is the sum of 2 numbers above. First line is always 1, and second line is always 1 1. This printHosoya function takes argument n which is the height of the triangle number of lines. For example: printHosoya 6 would return: 1 1 1 2 1 2 3 2 2 3 5 3 4 3 5 8 5 6 6 5 8 The complexity is On3. Calculates the hosoya triangle height height of the triangle Prints the hosoya triangle height height of the triangle Test hosoya function height height of the triangle","Completions":"def hosoya(height, width):\n \"\"\" Calculates the hosoya triangle\n\n height -- height of the triangle\n \"\"\"\n if (width == 0) and (height in (0,1)):\n return 1\n if (width == 1) and (height in (1,2)):\n return 1\n if height > width:\n return hosoya(height - 1, width) + hosoya(height - 2, width)\n if width == height:\n return hosoya(height - 1, width - 1) + hosoya(height - 2, width - 2)\n return 0\n\ndef print_hosoya(height):\n \"\"\"Prints the hosoya triangle\n\n height -- height of the triangle\n \"\"\"\n for i in range(height):\n for j in range(i + 1):\n print(hosoya(i, j) , end = \" \")\n print (\"\\n\", end = \"\")\n\ndef hosoya_testing(height):\n \"\"\"Test hosoya function\n\n height -- height of the triangle\n \"\"\"\n res = []\n for i in range(height):\n for j in range(i + 1):\n res.append(hosoya(i, j))\n return res\n"} +{"Prompt":"You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night. Given a list of nonnegative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police.","Completions":"def house_robber(houses):\n last, now = 0, 0\n for house in houses:\n last, now = now, max(last + house, now)\n return now\n"} +{"Prompt":"Given positive integer decompose, find an algorithm to find the number of nonnegative number division, or decomposition. The complexity is On2. Example 1: Input: 4 Output: 5 Explaination: 44 431 422 4211 41111 Example : Input: 7 Output: 15 Explaination: 77 761 752 7511 743 7421 74111 7331 7322 73211 731111 72221 722111 7211111 71111111 Find number of decompositions from decompose decompose integer","Completions":"def int_divide(decompose):\n \"\"\"Find number of decompositions from `decompose`\n\n decompose -- integer\n \"\"\"\n arr = [[0 for i in range(decompose + 1)] for j in range(decompose + 1)]\n arr[1][1] = 1\n for i in range(1, decompose + 1):\n for j in range(1, decompose + 1):\n if i < j:\n arr[i][j] = arr[i][i]\n elif i == j:\n arr[i][j] = 1 + arr[i][j - 1]\n else:\n arr[i][j] = arr[i][j - 1] + arr[i - j][j]\n return arr[decompose][decompose]\n"} +{"Prompt":"Python program for weighted job scheduling using Dynamic Programming and Binary Search Class to represent a job A Binary Search based function to find the latest job before current job that doesn't conflict with current job. index is index of the current job. This function returns 1 if all jobs before index conflict with it. The array jobs is sorted in increasing order of finish time. Perform binary Search iteratively The main function that returns the maximum possible profit from given array of jobs Sort jobs according to finish time Create an array to store solutions of subproblems. tablei stores the profit for jobs till arri including arri Fill entries in table using recursive property Find profit including the current job Store maximum of including and excluding","Completions":"class Job:\n \"\"\"\n Class to represent a job\n \"\"\"\n def __init__(self, start, finish, profit):\n self.start = start\n self.finish = finish\n self.profit = profit\n\ndef binary_search(job, start_index):\n \"\"\"\n A Binary Search based function to find the latest job\n (before current job) that doesn't conflict with current\n job. \"index\" is index of the current job. This function\n returns -1 if all jobs before index conflict with it.\n The array jobs[] is sorted in increasing order of finish\n time.\n \"\"\"\n\n left = 0\n right = start_index - 1\n\n # Perform binary Search iteratively\n while left <= right:\n mid = (left + right) \/\/ 2\n if job[mid].finish <= job[start_index].start:\n if job[mid + 1].finish <= job[start_index].start:\n left = mid + 1\n else:\n return mid\n else:\n right = mid - 1\n return -1\n\ndef schedule(job):\n \"\"\"\n The main function that returns the maximum possible\n profit from given array of jobs\n \"\"\"\n\n # Sort jobs according to finish time\n job = sorted(job, key = lambda j: j.finish)\n\n # Create an array to store solutions of subproblems. table[i]\n # stores the profit for jobs till arr[i] (including arr[i])\n length = len(job)\n table = [0 for _ in range(length)]\n\n table[0] = job[0].profit\n\n # Fill entries in table[] using recursive property\n for i in range(1, length):\n\n # Find profit including the current job\n incl_prof = job[i].profit\n pos = binary_search(job, i)\n if pos != -1:\n incl_prof += table[pos]\n\n # Store maximum of including and excluding\n table[i] = max(incl_prof, table[i - 1])\n\n return table[length-1]\n"} +{"Prompt":"The K factor of a string is defined as the number of times 'abba' appears as a substring. Given two numbers length and kfactor, find the number of strings of length length with 'K factor' kfactor. The algorithms is as follows: dplengthkfactor will be a 4 element array, wherein each element can be the number of strings of length length and 'K factor' kfactor which belong to the criteria represented by that index: dplengthkfactor0 can be the number of strings of length length and Kfactor kfactor which end with substring 'a' dplengthkfactor1 can be the number of strings of length length and Kfactor kfactor which end with substring 'ab' dplengthkfactor2 can be the number of strings of length length and Kfactor kfactor which end with substring 'abb' dplengthkfactor3 can be the number of strings of length and Kfactor kfactor which end with anything other than the above substrings anything other than 'a' 'ab' 'abb' Example inputs length4 kfactor1 no of strings 1 length7 kfactor1 no of strings 70302 length10 kfactor2 no of strings 74357 Find the number of strings of length length with K factor kfactor. Keyword arguments: length integer kfactor integer base cases adding a at the end adding b at the end adding any other lowercase character adding a at the end adding b at the end adding any other lowercase character","Completions":"def find_k_factor(length, k_factor):\n \"\"\"Find the number of strings of length `length` with K factor = `k_factor`.\n\n Keyword arguments:\n length -- integer\n k_factor -- integer\n \"\"\"\n mat=[[[0 for i in range(4)]for j in range((length-1)\/\/3+2)]for k in range(length+1)]\n if 3*k_factor+1>length:\n return 0\n #base cases\n mat[1][0][0]=1\n mat[1][0][1]=0\n mat[1][0][2]=0\n mat[1][0][3]=25\n\n for i in range(2,length+1):\n for j in range((length-1)\/\/3+2):\n if j==0:\n #adding a at the end\n mat[i][j][0]=mat[i-1][j][0]+mat[i-1][j][1]+mat[i-1][j][3]\n\n #adding b at the end\n mat[i][j][1]=mat[i-1][j][0]\n mat[i][j][2]=mat[i-1][j][1]\n\n #adding any other lowercase character\n mat[i][j][3]=mat[i-1][j][0]*24+mat[i-1][j][1]*24+mat[i-1][j][2]*25+mat[i-1][j][3]*25\n\n elif 3*j+1 sequence[j]:\n counts[i] = max(counts[i], counts[j] + 1)\n print(counts)\n return max(counts)\n\n\ndef longest_increasing_subsequence_optimized(sequence):\n \"\"\"\n Optimized dynamic programming algorithm for\n couting the length of the longest increasing subsequence\n using segment tree data structure to achieve better complexity\n if max element is larger than 10^5 then use\n longest_increasing_subsequence_optimied2() instead\n type sequence: list[int]\n rtype: int\n \"\"\"\n max_seq = max(sequence)\n tree = [0] * (max_seq<<2)\n\n def update(pos, left, right, target, vertex):\n if left == right:\n tree[pos] = vertex\n return\n mid = (left+right)>>1\n if target <= mid:\n update(pos<<1, left, mid, target, vertex)\n else:\n update((pos<<1)|1, mid+1, right, target, vertex)\n tree[pos] = max_seq(tree[pos<<1], tree[(pos<<1)|1])\n\n def get_max(pos, left, right, start, end):\n if left > end or right < start:\n return 0\n if left >= start and right <= end:\n return tree[pos]\n mid = (left+right)>>1\n return max_seq(get_max(pos<<1, left, mid, start, end),\n get_max((pos<<1)|1, mid+1, right, start, end))\n ans = 0\n for element in sequence:\n cur = get_max(1, 0, max_seq, 0, element-1)+1\n ans = max_seq(ans, cur)\n update(1, 0, max_seq, element, cur)\n return ans\n\n\ndef longest_increasing_subsequence_optimized2(sequence):\n \"\"\"\n Optimized dynamic programming algorithm for\n counting the length of the longest increasing subsequence\n using segment tree data structure to achieve better complexity\n type sequence: list[int]\n rtype: int\n \"\"\"\n length = len(sequence)\n tree = [0] * (length<<2)\n sorted_seq = sorted((x, -i) for i, x in enumerate(sequence))\n def update(pos, left, right, target, vertex):\n if left == right:\n tree[pos] = vertex\n return\n mid = (left+right)>>1\n if target <= mid:\n vertex(pos<<1, left, mid, target, vertex)\n else:\n vertex((pos<<1)|1, mid+1, right, target, vertex)\n tree[pos] = max(tree[pos<<1], tree[(pos<<1)|1])\n\n def get_max(pos, left, right, start, end):\n if left > end or right < start:\n return 0\n if left >= start and right <= end:\n return tree[pos]\n mid = (left+right)>>1\n return max(get_max(pos<<1, left, mid, start, end),\n get_max((pos<<1)|1, mid+1, right, start, end))\n ans = 0\n for tup in sorted_seq:\n i = -tup[1]\n cur = get_max(1, 0, length-1, 0, i-1)+1\n ans = max(ans, cur)\n update(1, 0, length-1, i, cur)\n return ans\n"} +{"Prompt":"Dynamic Programming Implementation of matrix Chain Multiplication Time Complexity: On3 Space Complexity: On2 Finds optimal order to multiply matrices array int Print order of matrix with Ai as matrix Print the solution optimalsolution int i int j int Testing for matrixchainordering Size of matrix created from above array will be 3035 3515 155 510 1020 2025","Completions":"INF = float(\"inf\")\n\n\ndef matrix_chain_order(array):\n \"\"\"Finds optimal order to multiply matrices\n\n array -- int[]\n \"\"\"\n n = len(array)\n matrix = [[0 for x in range(n)] for x in range(n)]\n sol = [[0 for x in range(n)] for x in range(n)]\n for chain_length in range(2, n):\n for a in range(1, n-chain_length+1):\n b = a+chain_length-1\n\n matrix[a][b] = INF\n for c in range(a, b):\n cost = matrix[a][c] + matrix[c+1][b] + array[a-1]*array[c]*array[b]\n if cost < matrix[a][b]:\n matrix[a][b] = cost\n sol[a][b] = c\n return matrix, sol\n# Print order of matrix with Ai as matrix\n\ndef print_optimal_solution(optimal_solution,i,j):\n \"\"\"Print the solution\n\n optimal_solution -- int[][]\n i -- int[]\n j -- int[]\n \"\"\"\n if i==j:\n print(\"A\" + str(i),end = \" \")\n else:\n print(\"(\", end=\" \")\n print_optimal_solution(optimal_solution, i, optimal_solution[i][j])\n print_optimal_solution(optimal_solution, optimal_solution[i][j]+1, j)\n print(\")\", end=\" \")\n\n\ndef main():\n \"\"\"\n Testing for matrix_chain_ordering\n \"\"\"\n array=[30,35,15,5,10,20,25]\n length=len(array)\n #Size of matrix created from above array will be\n # 30*35 35*15 15*5 5*10 10*20 20*25\n matrix, optimal_solution = matrix_chain_order(array)\n\n print(\"No. of Operation required: \"+str((matrix[1][length-1])))\n print_optimal_solution(optimal_solution,1,length-1)\n\nif __name__ == '__main__':\n main()\n"} +{"Prompt":"Find the contiguous subarray within an array containing at least one number which has the largest product. For example, given the array 2,3,2,4, the contiguous subarray 2,3 has the largest product 6. :type nums: Listint :rtype: int Another approach that would print max product and the subarray Examples: subarraywithmaxproduct2,3,6,1,1,9,5 maxproductsofar: 45, 1, 1, 9, 5 subarraywithmaxproduct2,3,6,0,7,5 maxproductsofar: 36, 2, 3, 6 subarraywithmaxproduct4,3,2,1 maxproductsofar: 24, 4, 3, 2, 1 subarraywithmaxproduct3,0,1 maxproductsofar: 1, 1 arr is list of positivenegative numbers ''' length lenarr productsofar maxproductend 1 maxstarti 0 sofarstarti sofarendi 0 allnegativeflag True for i in rangelength: maxproductend arri if arri 0: allnegativeflag False if maxproductend 0: maxproductend arri maxstarti i if productsofar maxproductend: productsofar maxproductend sofarendi i sofarstarti maxstarti if allnegativeflag: printfmaxproductsofar: reducelambda x, y: x y, arr, arr else: printfmaxproductsofar: productsofar,arrsofarstarti:sofarendi 1","Completions":"from functools import reduce\n\n\ndef max_product(nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n lmin = lmax = gmax = nums[0]\n for num in nums:\n t_1 = num * lmax\n t_2 = num * lmin\n lmax = max(max(t_1, t_2), num)\n lmin = min(min(t_1, t_2), num)\n gmax = max(gmax, lmax)\n\n\n\"\"\"\nAnother approach that would print max product and the subarray\n\nExamples:\nsubarray_with_max_product([2,3,6,-1,-1,9,5])\n #=> max_product_so_far: 45, [-1, -1, 9, 5]\nsubarray_with_max_product([-2,-3,6,0,-7,-5])\n #=> max_product_so_far: 36, [-2, -3, 6]\nsubarray_with_max_product([-4,-3,-2,-1])\n #=> max_product_so_far: 24, [-4, -3, -2, -1]\nsubarray_with_max_product([-3,0,1])\n #=> max_product_so_far: 1, [1]\n\"\"\"\n\n\ndef subarray_with_max_product(arr):\n ''' arr is list of positive\/negative numbers '''\n length = len(arr)\n product_so_far = max_product_end = 1\n max_start_i = 0\n so_far_start_i = so_far_end_i = 0\n all_negative_flag = True\n\n for i in range(length):\n max_product_end *= arr[i]\n if arr[i] > 0:\n all_negative_flag = False\n\n if max_product_end <= 0:\n max_product_end = arr[i]\n max_start_i = i\n\n if product_so_far <= max_product_end:\n product_so_far = max_product_end\n so_far_end_i = i\n so_far_start_i = max_start_i\n\n if all_negative_flag:\n print(f\"max_product_so_far: {reduce(lambda x, y: x * y, arr)}, {arr}\")\n\n else:\n print(f\"max_product_so_far: {product_so_far},{arr[so_far_start_i:so_far_end_i + 1]}\")\n"} +{"Prompt":"author goswamirahul To find minimum cost path from station 0 to station N1, where cost of moving from ith station to jth station is given as: Matrix of size N x N where Matrixij denotes the cost of moving from station i station j for i j NOTE that values where Matrixij and i j does not mean anything, and hence represented by 1 or INF For the input below cost matrix, Minimum cost is obtained as from 0 1 3 cost01 cost13 65 the Output will be: The Minimum cost to reach station 4 is 65 Time Complexity: On2 Space Complexity: On Find minimum cost. Keyword arguments: cost matrix containing costs disti stores minimum cost from 0 i.","Completions":"INF = float(\"inf\")\n\n\ndef min_cost(cost):\n \"\"\"Find minimum cost.\n\n Keyword arguments:\n cost -- matrix containing costs\n \"\"\"\n length = len(cost)\n # dist[i] stores minimum cost from 0 --> i.\n dist = [INF] * length\n\n dist[0] = 0 # cost from 0 --> 0 is zero.\n\n for i in range(length):\n for j in range(i+1,length):\n dist[j] = min(dist[j], dist[i] + cost[i][j])\n\n return dist[length-1]\n\n\nif __name__ == '__main__':\n costs = [ [ 0, 15, 80, 90], # cost[i][j] is the cost of\n [-1, 0, 40, 50], # going from i --> j\n [-1, -1, 0, 70],\n [-1, -1, -1, 0] ] # cost[i][j] = -1 for i > j\n TOTAL_LEN = len(costs)\n\n mcost = min_cost(costs)\n assert mcost == 65\n\n print(f\"The minimum cost to reach station {TOTAL_LEN} is {mcost}\")\n"} +{"Prompt":"A message containing letters from AZ is being encoded to numbers using the following mapping: 'A' 1 'B' 2 ... 'Z' 26 Given an encoded message containing digits, determine the total number of ways to decode it. For example, Given encoded message 12, it could be decoded as AB 1 2 or L 12. The number of ways decoding 12 is 2. :type s: str :rtype: int :type s: str :rtype: int only '10', '20' is valid '01 09' is not allowed other case '01, 09, 27'","Completions":"def num_decodings(enc_mes):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n if not enc_mes or enc_mes[0] == \"0\":\n return 0\n last_char, last_two_chars = 1, 1\n for i in range(1, len(enc_mes)):\n last = last_char if enc_mes[i] != \"0\" else 0\n last_two = last_two_chars if int(enc_mes[i-1:i+1]) < 27 and enc_mes[i-1] != \"0\" else 0\n last_two_chars = last_char\n last_char = last+last_two\n return last_char\n\n\ndef num_decodings2(enc_mes):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n if not enc_mes or enc_mes.startswith('0'):\n return 0\n stack = [1, 1]\n for i in range(1, len(enc_mes)):\n if enc_mes[i] == '0':\n if enc_mes[i-1] == '0' or enc_mes[i-1] > '2':\n # only '10', '20' is valid\n return 0\n stack.append(stack[-2])\n elif 9 < int(enc_mes[i-1:i+1]) < 27:\n # '01 - 09' is not allowed\n stack.append(stack[-2]+stack[-1])\n else:\n # other case '01, 09, 27'\n stack.append(stack[-1])\n return stack[-1]\n"} +{"Prompt":"An even number of trees are left along one side of a country road. You've been assigned the job to plant these trees at an even interval on both sides of the road. The length and width of the road are variable, and a pair of trees must be planted at the beginning at 0 and at the end at length of the road. Only one tree can be moved at a time. The goal is to calculate the lowest amount of distance that the trees have to be moved before they are all in a valid position. Returns the minimum distance that trees have to be moved before they are all in a valid state. Parameters: tree listint: A sorted list of integers with all trees' position along the road. length int: An integer with the length of the road. width int: An integer with the width of the road. Returns: A float number with the total distance trees have been moved.","Completions":"from math import sqrt\n\ndef planting_trees(trees, length, width):\n \"\"\"\n Returns the minimum distance that trees have to be moved before they\n are all in a valid state.\n\n Parameters:\n tree (list): A sorted list of integers with all trees'\n position along the road.\n length (int): An integer with the length of the road.\n width (int): An integer with the width of the road.\n\n Returns:\n A float number with the total distance trees have been moved.\n \"\"\"\n trees = [0] + trees\n\n n_pairs = int(len(trees)\/2)\n\n space_between_pairs = length\/(n_pairs-1)\n\n target_locations = [location*space_between_pairs for location in range(n_pairs)]\n\n cmatrix = [[0 for _ in range(n_pairs+1)] for _ in range(n_pairs+1)]\n for r_i in range(1, n_pairs+1):\n cmatrix[r_i][0] = cmatrix[r_i-1][0] + sqrt(\n width + abs(trees[r_i]-target_locations[r_i-1])**2)\n for l_i in range(1, n_pairs+1):\n cmatrix[0][l_i] = cmatrix[0][l_i-1] + abs(trees[l_i]-target_locations[l_i-1])\n\n for r_i in range(1, n_pairs+1):\n for l_i in range(1, n_pairs+1):\n cmatrix[r_i][l_i] = min(\n cmatrix[r_i-1][l_i] + sqrt(width + (trees[l_i + r_i]-target_locations[r_i-1])**2),\n cmatrix[r_i][l_i-1] + abs(trees[l_i + r_i]-target_locations[l_i-1])\n )\n\n return cmatrix[n_pairs][n_pairs]\n"} +{"Prompt":"Implement regular expression matching with support for '.' and ''. '.' Matches any single character. '' Matches zero or more of the preceding element. The matching should cover the entire input string not partial. The function prototype should be: bool ismatchconst char s, const char p Some examples: ismatchaa,a false ismatchaa,aa true ismatchaaa,aa false ismatchaa, a true ismatchaa, . true ismatchab, . true ismatchaab, cab true Finds if stra matches strb Keyword arguments: stra string strb string Match empty string with empty pattern Match empty string with . The previous character has matched and the current one has to be matched. Two possible matches: the same or . Horizontal look up j 2. Not use the character before . Vertical look up i 1. Use at least one character before . p a b s 1 0 0 0 a 0 1 0 1 b 0 0 1 1 b 0 0 0 ?","Completions":"def is_match(str_a, str_b):\n \"\"\"Finds if `str_a` matches `str_b`\n\n Keyword arguments:\n str_a -- string\n str_b -- string\n \"\"\"\n len_a, len_b = len(str_a) + 1, len(str_b) + 1\n matches = [[False] * len_b for _ in range(len_a)]\n\n # Match empty string with empty pattern\n matches[0][0] = True\n\n # Match empty string with .*\n for i, element in enumerate(str_b[1:], 2):\n matches[0][i] = matches[0][i - 2] and element == '*'\n\n for i, char_a in enumerate(str_a, 1):\n for j, char_b in enumerate(str_b, 1):\n if char_b != '*':\n # The previous character has matched and the current one\n # has to be matched. Two possible matches: the same or .\n matches[i][j] = matches[i - 1][j - 1] and \\\n char_b in (char_a, '.')\n else:\n # Horizontal look up [j - 2].\n # Not use the character before *.\n matches[i][j] |= matches[i][j - 2]\n\n # Vertical look up [i - 1].\n # Use at least one character before *.\n # p a b *\n # s 1 0 0 0\n # a 0 1 0 1\n # b 0 0 1 1\n # b 0 0 0 ?\n if char_a == str_b[j - 2] or str_b[j - 2] == '.':\n matches[i][j] |= matches[i - 1][j]\n\n return matches[-1][-1]\n"} +{"Prompt":"A Dynamic Programming solution for Rod cutting problem Returns the best obtainable price for a rod of length n and price as prices of different pieces Build the table val in bottom up manner and return the last entry from the table Driver program to test above functions This code is contributed by Bhavya Jain","Completions":"INT_MIN = -32767\n\ndef cut_rod(price):\n \"\"\"\n Returns the best obtainable price for a rod of length n and\n price[] as prices of different pieces\n \"\"\"\n n = len(price)\n val = [0]*(n+1)\n\n # Build the table val[] in bottom up manner and return\n # the last entry from the table\n for i in range(1, n+1):\n max_val = INT_MIN\n for j in range(i):\n max_val = max(max_val, price[j] + val[i-j-1])\n val[i] = max_val\n\n return val[n]\n\n# Driver program to test above functions\narr = [1, 5, 8, 9, 10, 17, 17, 20]\nprint(\"Maximum Obtainable Value is \" + str(cut_rod(arr)))\n\n# This code is contributed by Bhavya Jain\n"} +{"Prompt":"Given a nonempty string s and a dictionary wordDict containing a list of nonempty words, determine if word can be segmented into a spaceseparated sequence of one or more dictionary words. You may assume the dictionary does not contain duplicate words. For example, given word leetcode, dict leet, code. Return true because leetcode can be segmented as leet code. word abc worddict a,bc True False False False TC: ON2 SC: ON :type word: str :type worddict: Setstr :rtype: bool","Completions":"# TC: O(N^2) SC: O(N)\ndef word_break(word, word_dict):\n \"\"\"\n :type word: str\n :type word_dict: Set[str]\n :rtype: bool\n \"\"\"\n dp_array = [False] * (len(word)+1)\n dp_array[0] = True\n for i in range(1, len(word)+1):\n for j in range(0, i):\n if dp_array[j] and word[j:i] in word_dict:\n dp_array[i] = True\n break\n return dp_array[-1]\n\n\nif __name__ == \"__main__\":\n STR = \"keonkim\"\n dic = [\"keon\", \"kim\"]\n\n print(word_break(str, dic))\n"} +{"Prompt":"Collection of algorithms on graphs.","Completions":"from .tarjan import *\nfrom .check_bipartite import *\nfrom .maximum_flow import *\nfrom .maximum_flow_bfs import *\nfrom .maximum_flow_dfs import *\nfrom .all_pairs_shortest_path import *\nfrom .bellman_ford import *\nfrom .prims_minimum_spanning import *\n"} +{"Prompt":"Given a nn adjacency array. it will give you all pairs shortest path length. use deepcopy to preserve the original information. Time complexity : OE3 example a 0 , 0.1 , 0.101, 0.142, 0.277, 0.465, 0 , 0.191, 0.192, 0.587, 0.245, 0.554, 0 , 0.333, 0.931, 1.032, 0.668, 0.656, 0 , 0.151, 0.867, 0.119, 0.352, 0.398, 0 result 0 , 0.1 , 0.101, 0.142, 0.277, 0.436, 0 , 0.191, 0.192, 0.343, 0.245, 0.345, 0 , 0.333, 0.484, 0.706, 0.27 , 0.461, 0 , 0.151, 0.555, 0.119, 0.31 , 0.311, 0 Given a matrix of the edge weights between respective nodes, returns a matrix containing the shortest distance distance between the two nodes.","Completions":"import copy\n\ndef all_pairs_shortest_path(adjacency_matrix):\n \"\"\"\n Given a matrix of the edge weights between respective nodes, returns a\n matrix containing the shortest distance distance between the two nodes.\n \"\"\"\n\n new_array = copy.deepcopy(adjacency_matrix)\n\n size = len(new_array)\n for k in range(size):\n for i in range(size):\n for j in range(size):\n if new_array[i][j] > new_array[i][k] + new_array[k][j]:\n new_array[i][j] = new_array[i][k] + new_array[k][j]\n\n return new_array\n"} +{"Prompt":"Determination of singlesource shortestpath. This BellmanFord Code is for determination whether we can get shortest path from given graph or not for singlesource shortestpaths problem. In other words, if given graph has any negativeweight cycle that is reachable from the source, then it will give answer False for no solution exits. For argument graph, it should be a dictionary type such as graph 'a': 'b': 6, 'e': 7, 'b': 'c': 5, 'd': 4, 'e': 8, 'c': 'b': 2, 'd': 'a': 2, 'c': 7, 'e': 'b': 3 Initialize data structures for BellmanFord algorithm.","Completions":"def bellman_ford(graph, source):\n \"\"\"\n This Bellman-Ford Code is for determination whether we can get\n shortest path from given graph or not for single-source shortest-paths problem.\n In other words, if given graph has any negative-weight cycle that is reachable\n from the source, then it will give answer False for \"no solution exits\".\n For argument graph, it should be a dictionary type\n such as\n graph = {\n 'a': {'b': 6, 'e': 7},\n 'b': {'c': 5, 'd': -4, 'e': 8},\n 'c': {'b': -2},\n 'd': {'a': 2, 'c': 7},\n 'e': {'b': -3}\n }\n \"\"\"\n weight = {}\n pre_node = {}\n\n initialize_single_source(graph, source, weight, pre_node)\n\n for _ in range(1, len(graph)):\n for node in graph:\n for adjacent in graph[node]:\n if weight[adjacent] > weight[node] + graph[node][adjacent]:\n weight[adjacent] = weight[node] + graph[node][adjacent]\n pre_node[adjacent] = node\n\n for node in graph:\n for adjacent in graph[node]:\n if weight[adjacent] > weight[node] + graph[node][adjacent]:\n return False\n\n return True\n\ndef initialize_single_source(graph, source, weight, pre_node):\n \"\"\"\n Initialize data structures for Bellman-Ford algorithm.\n \"\"\"\n for node in graph:\n weight[node] = float('inf')\n pre_node[node] = None\n\n weight[source] = 0\n"} +{"Prompt":"Bipartite graph is a graph whose vertices can be divided into two disjoint and independent sets. https:en.wikipedia.orgwikiBipartitegraph Determine if the given graph is bipartite. Time complexity is OE Space complexity is OV Divide vertexes in the graph into settype 0 and 1 Initialize all settypes as 1 If there is a selfloop, it cannot be bipartite set type of u opposite of v","Completions":"def check_bipartite(adj_list):\n \"\"\"\n Determine if the given graph is bipartite.\n\n Time complexity is O(|E|)\n Space complexity is O(|V|)\n \"\"\"\n\n vertices = len(adj_list)\n\n # Divide vertexes in the graph into set_type 0 and 1\n # Initialize all set_types as -1\n set_type = [-1 for v in range(vertices)]\n set_type[0] = 0\n\n queue = [0]\n\n while queue:\n current = queue.pop(0)\n\n # If there is a self-loop, it cannot be bipartite\n if adj_list[current][current]:\n return False\n\n for adjacent in range(vertices):\n if adj_list[current][adjacent]:\n if set_type[adjacent] == set_type[current]:\n return False\n\n if set_type[adjacent] == -1:\n # set type of u opposite of v\n set_type[adjacent] = 1 - set_type[current]\n queue.append(adjacent)\n\n return True\n"} +{"Prompt":"In a directed graph, a strongly connected component is a set of vertices such that for any pairs of vertices u and v there exists a path u...v that connects them. A graph is strongly connected if it is a single strongly connected component. A directed graph where edges are oneway a twoway edge can be represented by using two edges. Create a new graph with vertexcount vertices. Add an edge going from source to target Determine if all nodes are reachable from node 0 Determine if all nodes are reachable from the given node Create a new graph where every edge ab is replaced with an edge ba Note: we reverse the order of arguments pylint: disableargumentsoutoforder Determine if the graph is strongly connected.","Completions":"from collections import defaultdict\n\nclass Graph:\n \"\"\"\n A directed graph where edges are one-way (a two-way edge can be represented by using two edges).\n \"\"\"\n\n def __init__(self,vertex_count):\n \"\"\"\n Create a new graph with vertex_count vertices.\n \"\"\"\n\n self.vertex_count = vertex_count\n self.graph = defaultdict(list)\n\n def add_edge(self,source,target):\n \"\"\"\n Add an edge going from source to target\n \"\"\"\n self.graph[source].append(target)\n\n def dfs(self):\n \"\"\"\n Determine if all nodes are reachable from node 0\n \"\"\"\n visited = [False] * self.vertex_count\n self.dfs_util(0,visited)\n if visited == [True]*self.vertex_count:\n return True\n return False\n\n def dfs_util(self,source,visited):\n \"\"\"\n Determine if all nodes are reachable from the given node\n \"\"\"\n visited[source] = True\n for adjacent in self.graph[source]:\n if not visited[adjacent]:\n self.dfs_util(adjacent,visited)\n\n def reverse_graph(self):\n \"\"\"\n Create a new graph where every edge a->b is replaced with an edge b->a\n \"\"\"\n reverse_graph = Graph(self.vertex_count)\n for source, adjacent in self.graph.items():\n for target in adjacent:\n # Note: we reverse the order of arguments\n # pylint: disable=arguments-out-of-order\n reverse_graph.add_edge(target,source)\n return reverse_graph\n\n\n def is_strongly_connected(self):\n \"\"\"\n Determine if the graph is strongly connected.\n \"\"\"\n if self.dfs():\n reversed_graph = self.reverse_graph()\n if reversed_graph.dfs():\n return True\n return False\n"} +{"Prompt":"import collections class UndirectedGraphNode: def initself, label: self.label label self.neighbors def shallowcopyself: return UndirectedGraphNodeself.label def addneighborself, node: self.neighbors.appendnode def clonegraph1node: if not node: return None nodecopy node.shallowcopy dic node: nodecopy queue collections.dequenode while queue: node queue.popleft for neighbor in node.neighbors: if neighbor not in dic: neighbor is not visited neighborcopy neighbor.shallowcopy dicneighbor neighborcopy dicnode.addneighborneighborcopy queue.appendneighbor else: dicnode.addneighbordicneighbor return nodecopy def clonegraph2node: if not node: return None nodecopy node.shallowcopy dic node: nodecopy stack node while stack: node stack.pop for neighbor in node.neighbors: if neighbor not in dic: neighborcopy neighbor.shallowcopy dicneighbor neighborcopy dicnode.addneighborneighborcopy stack.appendneighbor else: dicnode.addneighbordicneighbor return nodecopy def clonegraphnode: if not node: return None nodecopy node.shallowcopy dic node: nodecopy dfsnode, dic return nodecopy def dfsnode, dic: for neighbor in node.neighbors: if neighbor not in dic: neighborcopy neighbor.shallowcopy dicneighbor neighborcopy dicnode.addneighborneighborcopy dfsneighbor, dic else: dicnode.addneighbordicneighbor","Completions":"r\"\"\"\nClone an undirected graph. Each node in the graph contains a label and a list\nof its neighbors.\n\n\nOJ's undirected graph serialization:\nNodes are labeled uniquely.\n\nWe use # as a separator for each node, and , as a separator for node label and\neach neighbor of the node.\nAs an example, consider the serialized graph {0,1,2#1,2#2,2}.\n\nThe graph has a total of three nodes, and therefore contains three parts as\nseparated by #.\n\nFirst node is labeled as 0. Connect node 0 to both nodes 1 and 2.\nSecond node is labeled as 1. Connect node 1 to node 2.\nThird node is labeled as 2. Connect node 2 to node 2 (itself), thus forming a\nself-cycle.\nVisually, the graph looks like the following:\n\n 1\n \/ \\\n \/ \\\n 0 --- 2\n \/ \\\n \\_\/\n\"\"\"\nimport collections\n\n\nclass UndirectedGraphNode:\n \"\"\"\n A node in an undirected graph. Contains a label and a list of neighbouring\n nodes (initially empty).\n \"\"\"\n\n def __init__(self, label):\n self.label = label\n self.neighbors = []\n\n def shallow_copy(self):\n \"\"\"\n Return a shallow copy of this node (ignoring any neighbors)\n \"\"\"\n return UndirectedGraphNode(self.label)\n\n def add_neighbor(self, node):\n \"\"\"\n Adds a new neighbor\n \"\"\"\n self.neighbors.append(node)\n\n\ndef clone_graph1(node):\n \"\"\"\n Returns a new graph as seen from the given node using a breadth first search (BFS).\n \"\"\"\n if not node:\n return None\n node_copy = node.shallow_copy()\n dic = {node: node_copy}\n queue = collections.deque([node])\n while queue:\n node = queue.popleft()\n for neighbor in node.neighbors:\n if neighbor not in dic: # neighbor is not visited\n neighbor_copy = neighbor.shallow_copy()\n dic[neighbor] = neighbor_copy\n dic[node].add_neighbor(neighbor_copy)\n queue.append(neighbor)\n else:\n dic[node].add_neighbor(dic[neighbor])\n return node_copy\n\n\ndef clone_graph2(node):\n \"\"\"\n Returns a new graph as seen from the given node using an iterative depth first search (DFS).\n \"\"\"\n if not node:\n return None\n node_copy = node.shallow_copy()\n dic = {node: node_copy}\n stack = [node]\n while stack:\n node = stack.pop()\n for neighbor in node.neighbors:\n if neighbor not in dic:\n neighbor_copy = neighbor.shallow_copy()\n dic[neighbor] = neighbor_copy\n dic[node].add_neighbor(neighbor_copy)\n stack.append(neighbor)\n else:\n dic[node].add_neighbor(dic[neighbor])\n return node_copy\n\n\ndef clone_graph(node):\n \"\"\"\n Returns a new graph as seen from the given node using a recursive depth first search (DFS).\n \"\"\"\n if not node:\n return None\n node_copy = node.shallow_copy()\n dic = {node: node_copy}\n dfs(node, dic)\n return node_copy\n\n\ndef dfs(node, dic):\n \"\"\"\n Clones a graph using a recursive depth first search. Stores the clones in\n the dictionary, keyed by the original nodes.\n \"\"\"\n for neighbor in node.neighbors:\n if neighbor not in dic:\n neighbor_copy = neighbor.shallow_copy()\n dic[neighbor] = neighbor_copy\n dic[node].add_neighbor(neighbor_copy)\n dfs(neighbor, dic)\n else:\n dic[node].add_neighbor(dic[neighbor])\n"} +{"Prompt":"count connected no of component using DFS In graph theory, a component, sometimes called a connected component, of an undirected graph is a subgraph in which any two vertices are connected to each other by paths. Example: 1 37 24 output 2 65 Code is Here Function that performs DFS ''' visitedsource True for child in adjacencylistsource: if not visitedchild: dfschild,visited,adjacencylist def countcomponentsadjacencylist,size: count 0 visited Falsesize1 for i in range1,size1: if not visitedi: dfsi,visited,adjacencylist count1 return count def main: nodecount,edgecount mapint, inputEnter the Number of Nodes and Edges n.split' ' adjacency for in rangenodecount1 for in rangeedgecount: printEnter the edge's Nodes in form of source targetn source,target mapint,input.split' ' adjacencysource.appendtarget adjacencytarget.appendsource printTotal number of Connected Components are : , countcomponentsadjacency,nodecount Driver code if name 'main': main","Completions":"#count connected no of component using DFS\n'''\nIn graph theory, a component, sometimes called a connected component,\nof an undirected graph is a subgraph in which any\ntwo vertices are connected to each other by paths.\n\nExample:\n\n\n 1 3------------7\n |\n |\n 2--------4\n | |\n | | output = 2\n 6--------5\n\n'''\n\n# Code is Here\n\ndef dfs(source,visited,adjacency_list):\n ''' Function that performs DFS '''\n\n visited[source] = True\n for child in adjacency_list[source]:\n if not visited[child]:\n dfs(child,visited,adjacency_list)\n\ndef count_components(adjacency_list,size):\n '''\n Function that counts the Connected components on bases of DFS.\n return type : int\n '''\n\n count = 0\n visited = [False]*(size+1)\n for i in range(1,size+1):\n if not visited[i]:\n dfs(i,visited,adjacency_list)\n count+=1\n return count\n\ndef main():\n \"\"\"\n Example application\n \"\"\"\n node_count,edge_count = map(int, input(\"Enter the Number of Nodes and Edges \\n\").split(' '))\n adjacency = [[] for _ in range(node_count+1)]\n for _ in range(edge_count):\n print(\"Enter the edge's Nodes in form of `source target`\\n\")\n source,target = map(int,input().split(' '))\n adjacency[source].append(target)\n adjacency[target].append(source)\n print(\"Total number of Connected Components are : \", count_components(adjacency,node_count))\n\n# Driver code\nif __name__ == '__main__':\n main()\n"} +{"Prompt":"Given a directed graph, check whether it contains a cycle. Reallife scenario: deadlock detection in a system. Processes may be represented by vertices, then and an edge A B could mean that process A is waiting for B to release its lock on a resource. For a given node: WHITE: has not been visited yet GRAY: is currently being investigated for a cycle BLACK: is not part of a cycle Determines if the given vertex is in a cycle. :param: traversalstates: for each vertex, the state it is in Determines if there is a cycle in the given graph. The graph should be given as a dictionary: graph 'A': 'B', 'C', 'B': 'D', 'C': 'F', 'D': 'E', 'F', 'E': 'B', 'F':","Completions":"from enum import Enum\n\n\nclass TraversalState(Enum):\n \"\"\"\n For a given node:\n - WHITE: has not been visited yet\n - GRAY: is currently being investigated for a cycle\n - BLACK: is not part of a cycle\n \"\"\"\n WHITE = 0\n GRAY = 1\n BLACK = 2\n\ndef is_in_cycle(graph, traversal_states, vertex):\n \"\"\"\n Determines if the given vertex is in a cycle.\n\n :param: traversal_states: for each vertex, the state it is in\n \"\"\"\n if traversal_states[vertex] == TraversalState.GRAY:\n return True\n traversal_states[vertex] = TraversalState.GRAY\n for neighbor in graph[vertex]:\n if is_in_cycle(graph, traversal_states, neighbor):\n return True\n traversal_states[vertex] = TraversalState.BLACK\n return False\n\n\ndef contains_cycle(graph):\n \"\"\"\n Determines if there is a cycle in the given graph.\n The graph should be given as a dictionary:\n\n graph = {'A': ['B', 'C'],\n 'B': ['D'],\n 'C': ['F'],\n 'D': ['E', 'F'],\n 'E': ['B'],\n 'F': []}\n \"\"\"\n traversal_states = {vertex: TraversalState.WHITE for vertex in graph}\n for vertex, state in traversal_states.items():\n if (state == TraversalState.WHITE and\n is_in_cycle(graph, traversal_states, vertex)):\n return True\n return False\n"} +{"Prompt":"Dijkstra's singlesource shortestpath algorithm A fully connected directed graph with edge weights Find the vertex that is closest to the visited set Given a node, returns the shortest distance to every other node minimum distance vertex that is not processed put minimum distance vertex in shortest tree Update dist value of the adjacent vertices","Completions":"class Dijkstra():\n \"\"\"\n A fully connected directed graph with edge weights\n \"\"\"\n\n def __init__(self, vertex_count):\n self.vertex_count = vertex_count\n self.graph = [[0 for _ in range(vertex_count)] for _ in range(vertex_count)]\n\n def min_distance(self, dist, min_dist_set):\n \"\"\"\n Find the vertex that is closest to the visited set\n \"\"\"\n min_dist = float(\"inf\")\n for target in range(self.vertex_count):\n if min_dist_set[target]:\n continue\n if dist[target] < min_dist:\n min_dist = dist[target]\n min_index = target\n return min_index\n\n def dijkstra(self, src):\n \"\"\"\n Given a node, returns the shortest distance to every other node\n \"\"\"\n dist = [float(\"inf\")] * self.vertex_count\n dist[src] = 0\n min_dist_set = [False] * self.vertex_count\n\n for _ in range(self.vertex_count):\n #minimum distance vertex that is not processed\n source = self.min_distance(dist, min_dist_set)\n\n #put minimum distance vertex in shortest tree\n min_dist_set[source] = True\n\n #Update dist value of the adjacent vertices\n for target in range(self.vertex_count):\n if self.graph[source][target] <= 0 or min_dist_set[target]:\n continue\n if dist[target] > dist[source] + self.graph[source][target]:\n dist[target] = dist[source] + self.graph[source][target]\n\n return dist\n"} +{"Prompt":"Finds all cliques in an undirected graph. A clique is a set of vertices in the graph such that the subgraph is fully connected ie. for any pair of nodes in the subgraph there is an edge between them. takes dict of sets each key is a vertex value is set of all edges connected to vertex returns list of lists each sub list is a maximal clique implementation of the basic algorithm described in: Bron, Coen; Kerbosch, Joep 1973, Algorithm 457: finding all cliques of an undirected graph,","Completions":"def find_all_cliques(edges):\n \"\"\"\n takes dict of sets\n each key is a vertex\n value is set of all edges connected to vertex\n returns list of lists (each sub list is a maximal clique)\n implementation of the basic algorithm described in:\n Bron, Coen; Kerbosch, Joep (1973), \"Algorithm 457: finding all cliques of an undirected graph\",\n \"\"\"\n\n def expand_clique(candidates, nays):\n nonlocal compsub\n if not candidates and not nays:\n nonlocal solutions\n solutions.append(compsub.copy())\n else:\n for selected in candidates.copy():\n candidates.remove(selected)\n candidates_temp = get_connected(selected, candidates)\n nays_temp = get_connected(selected, nays)\n compsub.append(selected)\n expand_clique(candidates_temp, nays_temp)\n nays.add(compsub.pop())\n\n def get_connected(vertex, old_set):\n new_set = set()\n for neighbor in edges[str(vertex)]:\n if neighbor in old_set:\n new_set.add(neighbor)\n return new_set\n\n compsub = []\n solutions = []\n possibles = set(edges.keys())\n expand_clique(possibles, set())\n return solutions\n"} +{"Prompt":"Functions for finding paths in graphs. pylint: disabledangerousdefaultvalue Find a path between two nodes using recursion and backtracking. pylint: disabledangerousdefaultvalue Find all paths between two nodes using recursion and backtracking find the shortest path between two nodes","Completions":"# pylint: disable=dangerous-default-value\ndef find_path(graph, start, end, path=[]):\n \"\"\"\n Find a path between two nodes using recursion and backtracking.\n \"\"\"\n path = path + [start]\n if start == end:\n return path\n if not start in graph:\n return None\n for node in graph[start]:\n if node not in path:\n newpath = find_path(graph, node, end, path)\n return newpath\n return None\n\n# pylint: disable=dangerous-default-value\ndef find_all_path(graph, start, end, path=[]):\n \"\"\"\n Find all paths between two nodes using recursion and backtracking\n \"\"\"\n path = path + [start]\n if start == end:\n return [path]\n if not start in graph:\n return []\n paths = []\n for node in graph[start]:\n if node not in path:\n newpaths = find_all_path(graph, node, end, path)\n for newpath in newpaths:\n paths.append(newpath)\n return paths\n\ndef find_shortest_path(graph, start, end, path=[]):\n \"\"\"\n find the shortest path between two nodes\n \"\"\"\n path = path + [start]\n if start == end:\n return path\n if start not in graph:\n return None\n shortest = None\n for node in graph[start]:\n if node not in path:\n newpath = find_shortest_path(graph, node, end, path)\n if newpath:\n if not shortest or len(newpath) < len(shortest):\n shortest = newpath\n return shortest\n"} +{"Prompt":"These are classes to represent a Graph and its elements. It can be shared across graph algorithms. A nodevertex in a graph. Return the name of the node A directed edge in a directed graph. Stores the source and target node of the edge. A directed graph. Stores a set of nodes, edges and adjacency matrix. pylint: disabledangerousdefaultvalue Add a new named node to the graph. Add a new edge to the graph between two nodes.","Completions":"class Node:\n \"\"\"\n A node\/vertex in a graph.\n \"\"\"\n\n def __init__(self, name):\n self.name = name\n\n @staticmethod\n def get_name(obj):\n \"\"\"\n Return the name of the node\n \"\"\"\n if isinstance(obj, Node):\n return obj.name\n if isinstance(obj, str):\n return obj\n return''\n\n def __eq__(self, obj):\n return self.name == self.get_name(obj)\n\n def __repr__(self):\n return self.name\n\n def __hash__(self):\n return hash(self.name)\n\n def __ne__(self, obj):\n return self.name != self.get_name(obj)\n\n def __lt__(self, obj):\n return self.name < self.get_name(obj)\n\n def __le__(self, obj):\n return self.name <= self.get_name(obj)\n\n def __gt__(self, obj):\n return self.name > self.get_name(obj)\n\n def __ge__(self, obj):\n return self.name >= self.get_name(obj)\n\n def __bool__(self):\n return self.name\n\nclass DirectedEdge:\n \"\"\"\n A directed edge in a directed graph.\n Stores the source and target node of the edge.\n \"\"\"\n\n def __init__(self, node_from, node_to):\n self.source = node_from\n self.target = node_to\n\n def __eq__(self, obj):\n if isinstance(obj, DirectedEdge):\n return obj.source == self.source and obj.target == self.target\n return False\n\n def __repr__(self):\n return f\"({self.source} -> {self.target})\"\n\nclass DirectedGraph:\n \"\"\"\n A directed graph.\n Stores a set of nodes, edges and adjacency matrix.\n \"\"\"\n\n # pylint: disable=dangerous-default-value\n def __init__(self, load_dict={}):\n self.nodes = []\n self.edges = []\n self.adjacency_list = {}\n\n if load_dict and isinstance(load_dict, dict):\n for vertex in load_dict:\n node_from = self.add_node(vertex)\n self.adjacency_list[node_from] = []\n for neighbor in load_dict[vertex]:\n node_to = self.add_node(neighbor)\n self.adjacency_list[node_from].append(node_to)\n self.add_edge(vertex, neighbor)\n\n def add_node(self, node_name):\n \"\"\"\n Add a new named node to the graph.\n \"\"\"\n try:\n return self.nodes[self.nodes.index(node_name)]\n except ValueError:\n node = Node(node_name)\n self.nodes.append(node)\n return node\n\n def add_edge(self, node_name_from, node_name_to):\n \"\"\"\n Add a new edge to the graph between two nodes.\n \"\"\"\n try:\n node_from = self.nodes[self.nodes.index(node_name_from)]\n node_to = self.nodes[self.nodes.index(node_name_to)]\n self.edges.append(DirectedEdge(node_from, node_to))\n except ValueError:\n pass\n"} +{"Prompt":"Implements a markov chain. Chains are described using a dictionary: mychain 'A': 'A': 0.6, 'E': 0.4, 'E': 'A': 0.7, 'E': 0.3 Choose the next state randomly Given a markovchain, randomly chooses the next state given the current state. Yield a sequence of states given a markov chain and the initial state","Completions":"import random\n\ndef __choose_state(state_map):\n \"\"\"\n Choose the next state randomly\n \"\"\"\n choice = random.random()\n probability_reached = 0\n for state, probability in state_map.items():\n probability_reached += probability\n if probability_reached > choice:\n return state\n return None\n\ndef next_state(chain, current_state):\n \"\"\"\n Given a markov-chain, randomly chooses the next state given the current state.\n \"\"\"\n next_state_map = chain.get(current_state)\n return __choose_state(next_state_map)\n\ndef iterating_markov_chain(chain, state):\n \"\"\"\n Yield a sequence of states given a markov chain and the initial state\n \"\"\"\n while True:\n state = next_state(chain, state)\n yield state\n"} +{"Prompt":"Given the capacity, source and sink of a graph, computes the maximum flow from source to sink. Input : capacity, source, sink Output : maximum flow from source to sink Capacity is a twodimensional array that is vv. capacityij implies the capacity of the edge from i to j. If there is no edge from i to j, capacityij should be zero. pylint: disabletoomanyarguments Depth First Search implementation for FordFulkerson algorithm. DFS function for fordfulkerson algorithm. Computes maximum flow from source to sink using DFS. Time Complexity : OEf E is the number of edges and f is the maximum flow in the graph. Computes maximum flow from source to sink using BFS. Time complexity : OVE2 V is the number of vertices and E is the number of edges. Finds new flow using BFS. Update flow array following parent starting from sink. BFS function for Dinic algorithm. Check whether sink is reachable only using edges that is not full. DFS function for Dinic algorithm. Finds new flow using edges that is not full. Computes maximum flow from source to sink using Dinic algorithm. Time complexity : OV2E V is the number of vertices and E is the number of edges.","Completions":"from queue import Queue\n\n# pylint: disable=too-many-arguments\ndef dfs(capacity, flow, visit, vertices, idx, sink, current_flow = 1 << 63):\n \"\"\"\n Depth First Search implementation for Ford-Fulkerson algorithm.\n \"\"\"\n\n # DFS function for ford_fulkerson algorithm.\n if idx == sink:\n return current_flow\n visit[idx] = True\n for nxt in range(vertices):\n if not visit[nxt] and flow[idx][nxt] < capacity[idx][nxt]:\n available_flow = min(current_flow, capacity[idx][nxt]-flow[idx][nxt])\n tmp = dfs(capacity, flow, visit, vertices, nxt, sink, available_flow)\n if tmp:\n flow[idx][nxt] += tmp\n flow[nxt][idx] -= tmp\n return tmp\n return 0\n\ndef ford_fulkerson(capacity, source, sink):\n \"\"\"\n Computes maximum flow from source to sink using DFS.\n Time Complexity : O(Ef)\n E is the number of edges and f is the maximum flow in the graph.\n \"\"\"\n vertices = len(capacity)\n ret = 0\n flow = [[0]*vertices for _ in range(vertices)]\n while True:\n visit = [False for _ in range(vertices)]\n tmp = dfs(capacity, flow, visit, vertices, source, sink)\n if tmp:\n ret += tmp\n else:\n break\n return ret\n\ndef edmonds_karp(capacity, source, sink):\n \"\"\"\n Computes maximum flow from source to sink using BFS.\n Time complexity : O(V*E^2)\n V is the number of vertices and E is the number of edges.\n \"\"\"\n vertices = len(capacity)\n ret = 0\n flow = [[0]*vertices for _ in range(vertices)]\n while True:\n tmp = 0\n queue = Queue()\n visit = [False for _ in range(vertices)]\n par = [-1 for _ in range(vertices)]\n visit[source] = True\n queue.put((source, 1 << 63))\n # Finds new flow using BFS.\n while queue.qsize():\n front = queue.get()\n idx, current_flow = front\n if idx == sink:\n tmp = current_flow\n break\n for nxt in range(vertices):\n if not visit[nxt] and flow[idx][nxt] < capacity[idx][nxt]:\n visit[nxt] = True\n par[nxt] = idx\n queue.put((nxt, min(current_flow, capacity[idx][nxt]-flow[idx][nxt])))\n if par[sink] == -1:\n break\n ret += tmp\n parent = par[sink]\n idx = sink\n # Update flow array following parent starting from sink.\n while parent != -1:\n flow[parent][idx] += tmp\n flow[idx][parent] -= tmp\n idx = parent\n parent = par[parent]\n return ret\n\ndef dinic_bfs(capacity, flow, level, source, sink):\n \"\"\"\n BFS function for Dinic algorithm.\n Check whether sink is reachable only using edges that is not full.\n \"\"\"\n vertices = len(capacity)\n queue = Queue()\n queue.put(source)\n level[source] = 0\n while queue.qsize():\n front = queue.get()\n for nxt in range(vertices):\n if level[nxt] == -1 and flow[front][nxt] < capacity[front][nxt]:\n level[nxt] = level[front] + 1\n queue.put(nxt)\n return level[sink] != -1\n\ndef dinic_dfs(capacity, flow, level, idx, sink, work, current_flow = 1 << 63):\n \"\"\"\n DFS function for Dinic algorithm.\n Finds new flow using edges that is not full.\n \"\"\"\n if idx == sink:\n return current_flow\n vertices = len(capacity)\n while work[idx] < vertices:\n nxt = work[idx]\n if level[nxt] == level[idx] + 1 and flow[idx][nxt] < capacity[idx][nxt]:\n available_flow = min(current_flow, capacity[idx][nxt] - flow[idx][nxt])\n tmp = dinic_dfs(capacity, flow, level, nxt, sink, work, available_flow)\n if tmp > 0:\n flow[idx][nxt] += tmp\n flow[nxt][idx] -= tmp\n return tmp\n work[idx] += 1\n return 0\n\ndef dinic(capacity, source, sink):\n \"\"\"\n Computes maximum flow from source to sink using Dinic algorithm.\n Time complexity : O(V^2*E)\n V is the number of vertices and E is the number of edges.\n \"\"\"\n vertices = len(capacity)\n flow = [[0]*vertices for i in range(vertices)]\n ret = 0\n while True:\n level = [-1 for i in range(vertices)]\n work = [0 for i in range(vertices)]\n if not dinic_bfs(capacity, flow, level, source, sink):\n break\n while True:\n tmp = dinic_dfs(capacity, flow, level, source, sink, work)\n if tmp > 0:\n ret += tmp\n else:\n break\n return ret\n"} +{"Prompt":"Given a nn adjacency array. it will give you a maximum flow. This version use BFS to search path. Assume the first is the source and the last is the sink. Time complexity OEf example graph 0, 16, 13, 0, 0, 0, 0, 0, 10, 12, 0, 0, 0, 4, 0, 0, 14, 0, 0, 0, 9, 0, 0, 20, 0, 0, 0, 7, 0, 4, 0, 0, 0, 0, 0, 0 answer should be 23 Get the maximum flow through a graph using a breadth first search initial setting setting min to maxvalue save visited nodes save parent nodes initialize queue for BFS initial setting BFS to find path pop from queue checking capacity and visit if not, put into queue and chage to visit and save path if there is no path from src to sink initial setting Get minimum flow find minimum flow initial setting reduce capacity","Completions":"import copy\nimport queue\nimport math\n\ndef maximum_flow_bfs(adjacency_matrix):\n \"\"\"\n Get the maximum flow through a graph using a breadth first search\n \"\"\"\n #initial setting\n new_array = copy.deepcopy(adjacency_matrix)\n total = 0\n\n while True:\n #setting min to max_value\n min_flow = math.inf\n #save visited nodes\n visited = [0]*len(new_array)\n #save parent nodes\n path = [0]*len(new_array)\n\n #initialize queue for BFS\n bfs = queue.Queue()\n\n #initial setting\n visited[0] = 1\n bfs.put(0)\n\n #BFS to find path\n while bfs.qsize() > 0:\n #pop from queue\n src = bfs.get()\n for k in range(len(new_array)):\n #checking capacity and visit\n if(new_array[src][k] > 0 and visited[k] == 0 ):\n #if not, put into queue and chage to visit and save path\n visited[k] = 1\n bfs.put(k)\n path[k] = src\n\n #if there is no path from src to sink\n if visited[len(new_array) - 1] == 0:\n break\n\n #initial setting\n tmp = len(new_array) - 1\n\n #Get minimum flow\n while tmp != 0:\n #find minimum flow\n if min_flow > new_array[path[tmp]][tmp]:\n min_flow = new_array[path[tmp]][tmp]\n tmp = path[tmp]\n\n #initial setting\n tmp = len(new_array) - 1\n\n #reduce capacity\n while tmp != 0:\n new_array[path[tmp]][tmp] = new_array[path[tmp]][tmp] - min_flow\n tmp = path[tmp]\n\n total = total + min_flow\n\n return total\n"} +{"Prompt":"Given a nn adjacency array. it will give you a maximum flow. This version use DFS to search path. Assume the first is the source and the last is the sink. Time complexity OEf example graph 0, 16, 13, 0, 0, 0, 0, 0, 10, 12, 0, 0, 0, 4, 0, 0, 14, 0, 0, 0, 9, 0, 0, 20, 0, 0, 0, 7, 0, 4, 0, 0, 0, 0, 0, 0 answer should be 23 Get the maximum flow through a graph using a depth first search initial setting setting min to maxvalue save visited nodes save parent nodes initialize stack for DFS initial setting DFS to find path pop from queue checking capacity and visit if not, put into queue and chage to visit and save path if there is no path from src to sink initial setting Get minimum flow find minimum flow initial setting reduce capacity","Completions":"import copy\nimport math\n\ndef maximum_flow_dfs(adjacency_matrix):\n \"\"\"\n Get the maximum flow through a graph using a depth first search\n \"\"\"\n\n #initial setting\n new_array = copy.deepcopy(adjacency_matrix)\n total = 0\n\n while True:\n #setting min to max_value\n min = math.inf\n #save visited nodes\n visited = [0]*len(new_array)\n #save parent nodes\n path = [0]*len(new_array)\n\n #initialize stack for DFS\n stack = []\n\n #initial setting\n visited[0] = 1\n stack.append(0)\n\n #DFS to find path\n while len(stack) > 0:\n #pop from queue\n src = stack.pop()\n for k in range(len(new_array)):\n #checking capacity and visit\n if new_array[src][k] > 0 and visited[k] == 0:\n #if not, put into queue and chage to visit and save path\n visited[k] = 1\n stack.append(k)\n path[k] = src\n\n #if there is no path from src to sink\n if visited[len(new_array) - 1] == 0:\n break\n\n #initial setting\n tmp = len(new_array) - 1\n\n #Get minimum flow\n while tmp != 0:\n #find minimum flow\n if min > new_array[path[tmp]][tmp]:\n min = new_array[path[tmp]][tmp]\n tmp = path[tmp]\n\n #initial setting\n tmp = len(new_array) - 1\n\n #reduce capacity\n while tmp != 0:\n new_array[path[tmp]][tmp] = new_array[path[tmp]][tmp] - min\n tmp = path[tmp]\n\n total = total + min\n\n return total\n\n"} +{"Prompt":"Minimum spanning tree MST is going to use an undirected graph pylint: disabletoofewpublicmethods An edge of an undirected graph The disjoint set is represented with an list n of integers where ni is the parent of the node at position i. If ni i, i it's a root, or a head, of a set Args: n int: Number of vertices in the graph Args: node1, node2 int: Indexes of nodes whose sets will be merged. Get the set of nodes at position a and b If a and b are the roots, this will be constant O1 Join the shortest node to the longest, minimizing tree size faster find Get the root element of the set containing a Very important, memoize result of the recursion in the list to optimize next calls and make this operation practically constant, O1 node a it's the set root, so we can return that index Args: vertexcount int: Number of vertices in the graph edges list of Edge: Edges of the graph forest DisjointSet: DisjointSet of the vertices Returns: int: sum of weights of the minnimum spanning tree Kruskal algorithm: This algorithm will find the optimal graph with less edges and less total weight to connect all vertices MST, the MST will always contain n1 edges because it's the minimum required to connect n vertices. Procedure: Sort the edges criteria: less weight. Only take edges of nodes in different sets. If we take a edge, we need to merge the sets to discard these. After repeat this until select n1 edges, we will have the complete MST. If we have selected n1 edges, all the other edges will be discarted, so, we can stop here Test. How input works: Input consists of different weighted, connected, undirected graphs. line 1: integers n, m lines 2..m2: edge with the format node index u, node index v, integer weight Samples of input: 5 6 1 2 3 1 3 8 2 4 5 3 4 2 3 5 4 4 5 6 3 3 2 1 20 3 1 20 2 3 100 Sum of weights of the optimal paths: 14, 40 Read m edges from input After finish input and graph creation, use Kruskal algorithm for MST:","Completions":"import sys\n\n# pylint: disable=too-few-public-methods\nclass Edge:\n \"\"\"\n An edge of an undirected graph\n \"\"\"\n\n def __init__(self, source, target, weight):\n self.source = source\n self.target = target\n self.weight = weight\n\n\nclass DisjointSet:\n \"\"\"\n The disjoint set is represented with an list of integers where\n is the parent of the node at position .\n If = , it's a root, or a head, of a set\n \"\"\"\n\n def __init__(self, size):\n \"\"\"\n Args:\n n (int): Number of vertices in the graph\n \"\"\"\n\n self.parent = [None] * size # Contains wich node is the parent of the node at poisition \n self.size = [1] * size # Contains size of node at index , used to optimize merge\n for i in range(size):\n self.parent[i] = i # Make all nodes his own parent, creating n sets.\n\n def merge_set(self, node1, node2):\n \"\"\"\n Args:\n node1, node2 (int): Indexes of nodes whose sets will be merged.\n \"\"\"\n\n # Get the set of nodes at position and \n # If and are the roots, this will be constant O(1)\n node1 = self.find_set(node1)\n node2 = self.find_set(node2)\n\n # Join the shortest node to the longest, minimizing tree size (faster find)\n if self.size[node1] < self.size[node2]:\n self.parent[node1] = node2 # Merge set(a) and set(b)\n self.size[node2] += self.size[node1] # Add size of old set(a) to set(b)\n else:\n self.parent[node2] = node1 # Merge set(b) and set(a)\n self.size[node1] += self.size[node2] # Add size of old set(b) to set(a)\n\n def find_set(self, node):\n \"\"\"\n Get the root element of the set containing \n \"\"\"\n if self.parent[node] != node:\n # Very important, memoize result of the\n # recursion in the list to optimize next\n # calls and make this operation practically constant, O(1)\n self.parent[node] = self.find_set(self.parent[node])\n\n # node it's the set root, so we can return that index\n return self.parent[node]\n\n\ndef kruskal(vertex_count, edges, forest):\n \"\"\"\n Args:\n vertex_count (int): Number of vertices in the graph\n edges (list of Edge): Edges of the graph\n forest (DisjointSet): DisjointSet of the vertices\n Returns:\n int: sum of weights of the minnimum spanning tree\n\n Kruskal algorithm:\n This algorithm will find the optimal graph with less edges and less\n total weight to connect all vertices (MST), the MST will always contain\n n-1 edges because it's the minimum required to connect n vertices.\n\n Procedure:\n Sort the edges (criteria: less weight).\n Only take edges of nodes in different sets.\n If we take a edge, we need to merge the sets to discard these.\n After repeat this until select n-1 edges, we will have the complete MST.\n \"\"\"\n edges.sort(key=lambda edge: edge.weight)\n\n mst = [] # List of edges taken, minimum spanning tree\n\n for edge in edges:\n set_u = forest.find_set(edge.u) # Set of the node \n set_v = forest.find_set(edge.v) # Set of the node \n if set_u != set_v:\n forest.merge_set(set_u, set_v)\n mst.append(edge)\n if len(mst) == vertex_count-1:\n # If we have selected n-1 edges, all the other\n # edges will be discarted, so, we can stop here\n break\n\n return sum([edge.weight for edge in mst])\n\n\ndef main():\n \"\"\"\n Test. How input works:\n Input consists of different weighted, connected, undirected graphs.\n line 1:\n integers n, m\n lines 2..m+2:\n edge with the format -> node index u, node index v, integer weight\n\n Samples of input:\n\n 5 6\n 1 2 3\n 1 3 8\n 2 4 5\n 3 4 2\n 3 5 4\n 4 5 6\n\n 3 3\n 2 1 20\n 3 1 20\n 2 3 100\n\n Sum of weights of the optimal paths:\n 14, 40\n \"\"\"\n for size in sys.stdin:\n vertex_count, edge_count = map(int, size.split())\n forest = DisjointSet(edge_count)\n edges = [None] * edge_count # Create list of size \n\n # Read edges from input\n for i in range(edge_count):\n source, target, weight = map(int, input().split())\n source -= 1 # Convert from 1-indexed to 0-indexed\n target -= 1 # Convert from 1-indexed to 0-indexed\n edges[i] = Edge(source, target, weight)\n\n # After finish input and graph creation, use Kruskal algorithm for MST:\n print(\"MST weights sum:\", kruskal(vertex_count, edges, forest))\n\nif __name__ == \"__main__\":\n main()\n"} +{"Prompt":"Determine if there is a path between nodes in a graph A directed graph Add a new directed edge to the graph Determine if there is a path from source to target using a depth first search Determine if there is a path from source to target using a depth first search. :param: visited should be an array of booleans determining if the corresponding vertex has been visited already Determine if there is a path from source to target","Completions":"from collections import defaultdict\n\n\nclass Graph:\n \"\"\"\n A directed graph\n \"\"\"\n\n def __init__(self,vertex_count):\n self.vertex_count = vertex_count\n self.graph = defaultdict(list)\n self.has_path = False\n\n def add_edge(self,source,target):\n \"\"\"\n Add a new directed edge to the graph\n \"\"\"\n self.graph[source].append(target)\n\n def dfs(self,source,target):\n \"\"\"\n Determine if there is a path from source to target using a depth first search\n \"\"\"\n visited = [False] * self.vertex_count\n self.dfsutil(visited,source,target,)\n\n def dfsutil(self,visited,source,target):\n \"\"\"\n Determine if there is a path from source to target using a depth first search.\n :param: visited should be an array of booleans determining if the\n corresponding vertex has been visited already\n \"\"\"\n visited[source] = True\n for i in self.graph[source]:\n if target in self.graph[source]:\n self.has_path = True\n return\n if not visited[i]:\n self.dfsutil(visited,source,i)\n\n def is_reachable(self,source,target):\n \"\"\"\n Determine if there is a path from source to target\n \"\"\"\n self.has_path = False\n self.dfs(source,target)\n return self.has_path\n"} +{"Prompt":"This Prim's Algorithm Code is for finding weight of minimum spanning tree of a connected graph. For argument graph, it should be a dictionary type such as: graph 'a': 3, 'b', 8,'c' , 'b': 3, 'a', 5, 'd' , 'c': 8, 'a', 2, 'd', 4, 'e' , 'd': 5, 'b', 2, 'c', 6, 'e' , 'e': 4, 'c', 6, 'd' where 'a','b','c','d','e' are nodes these can be 1,2,3,4,5 as well Prim's algorithm to find weight of minimum spanning tree","Completions":"import heapq # for priority queue\n\ndef prims_minimum_spanning(graph_used):\n \"\"\"\n Prim's algorithm to find weight of minimum spanning tree\n \"\"\"\n vis=[]\n heap=[[0,1]]\n prim = set()\n mincost=0\n\n while len(heap) > 0:\n cost, node = heapq.heappop(heap)\n if node in vis:\n continue\n\n mincost += cost\n prim.add(node)\n vis.append(node)\n\n for distance, adjacent in graph_used[node]:\n if adjacent not in vis:\n heapq.heappush(heap, [distance, adjacent])\n\n return mincost\n"} +{"Prompt":"Given a formula in conjunctive normal form 2CNF, finds a way to assign TrueFalse values to all variables to satisfy all clauses, or reports there is no solution. https:en.wikipedia.orgwiki2satisfiability Format: each clause is a pair of literals each literal in the form name, isneg where name is an arbitrary identifier, and isneg is true if the literal is negated Perform a depth first search traversal of the graph starting at the given vertex. Stores the order in which nodes were visited to the list, in transposed order. Perform a depth first search traversal of the graph starting at the given vertex. Records all visited nodes as being of a certain strongly connected component. Add a directed edge to the graph. Computes the strongly connected components of a graph ''' order visited vertex: False for vertex in graph graphtransposed vertex: for vertex in graph for source, neighbours in graph.iteritems: for target in neighbours: addedgegraphtransposed, target, source for vertex in graph: if not visitedvertex: dfstransposedvertex, graphtransposed, order, visited visited vertex: False for vertex in graph vertexscc currentcomp 0 for vertex in reversedorder: if not visitedvertex: Each dfs will visit exactly one component dfsvertex, currentcomp, vertexscc, graph, visited currentcomp 1 return vertexscc def buildgraphformula: Solves the 2SAT problem Entry point for testing","Completions":"def dfs_transposed(vertex, graph, order, visited):\n \"\"\"\n Perform a depth first search traversal of the graph starting at the given vertex.\n Stores the order in which nodes were visited to the list, in transposed order.\n \"\"\"\n visited[vertex] = True\n\n for adjacent in graph[vertex]:\n if not visited[adjacent]:\n dfs_transposed(adjacent, graph, order, visited)\n\n order.append(vertex)\n\n\ndef dfs(vertex, current_comp, vertex_scc, graph, visited):\n \"\"\"\n Perform a depth first search traversal of the graph starting at the given vertex.\n Records all visited nodes as being of a certain strongly connected component.\n \"\"\"\n visited[vertex] = True\n vertex_scc[vertex] = current_comp\n\n for adjacent in graph[vertex]:\n if not visited[adjacent]:\n dfs(adjacent, current_comp, vertex_scc, graph, visited)\n\n\ndef add_edge(graph, vertex_from, vertex_to):\n \"\"\"\n Add a directed edge to the graph.\n \"\"\"\n if vertex_from not in graph:\n graph[vertex_from] = []\n\n graph[vertex_from].append(vertex_to)\n\n\ndef scc(graph):\n ''' Computes the strongly connected components of a graph '''\n order = []\n visited = {vertex: False for vertex in graph}\n\n graph_transposed = {vertex: [] for vertex in graph}\n\n for (source, neighbours) in graph.iteritems():\n for target in neighbours:\n add_edge(graph_transposed, target, source)\n\n for vertex in graph:\n if not visited[vertex]:\n dfs_transposed(vertex, graph_transposed, order, visited)\n\n visited = {vertex: False for vertex in graph}\n vertex_scc = {}\n\n current_comp = 0\n for vertex in reversed(order):\n if not visited[vertex]:\n # Each dfs will visit exactly one component\n dfs(vertex, current_comp, vertex_scc, graph, visited)\n current_comp += 1\n\n return vertex_scc\n\n\ndef build_graph(formula):\n ''' Builds the implication graph from the formula '''\n graph = {}\n\n for clause in formula:\n for (lit, _) in clause:\n for neg in [False, True]:\n graph[(lit, neg)] = []\n\n for ((a_lit, a_neg), (b_lit, b_neg)) in formula:\n add_edge(graph, (a_lit, a_neg), (b_lit, not b_neg))\n add_edge(graph, (b_lit, b_neg), (a_lit, not a_neg))\n\n return graph\n\n\ndef solve_sat(formula):\n \"\"\"\n Solves the 2-SAT problem\n \"\"\"\n graph = build_graph(formula)\n vertex_scc = scc(graph)\n\n for (var, _) in graph:\n if vertex_scc[(var, False)] == vertex_scc[(var, True)]:\n return None # The formula is contradictory\n\n comp_repr = {} # An arbitrary representant from each component\n\n for vertex in graph:\n if not vertex_scc[vertex] in comp_repr:\n comp_repr[vertex_scc[vertex]] = vertex\n\n comp_value = {} # True\/False value for each strongly connected component\n components = sorted(vertex_scc.values())\n\n for comp in components:\n if comp not in comp_value:\n comp_value[comp] = False\n\n (lit, neg) = comp_repr[comp]\n comp_value[vertex_scc[(lit, not neg)]] = True\n\n value = {var: comp_value[vertex_scc[(var, False)]] for (var, _) in graph}\n\n return value\n\n\ndef main():\n \"\"\"\n Entry point for testing\n \"\"\"\n formula = [(('x', False), ('y', False)),\n (('y', True), ('y', True)),\n (('a', False), ('b', False)),\n (('a', True), ('c', True)),\n (('c', False), ('b', True))]\n\n result = solve_sat(formula)\n\n for (variable, assign) in result.items():\n print(f\"{variable}:{assign}\")\n\nif __name__ == '__main__':\n main()\n"} +{"Prompt":"Implements Tarjan's algorithm for finding strongly connected components in a graph. https:en.wikipedia.orgwikiTarjan27sstronglyconnectedcomponentsalgorithm pylint: disabletoofewpublicmethods A directed graph used for finding strongly connected components Runs Tarjan Set all node index to None Given a vertex, adds all successors of the given vertex to the same connected component Set the depth index for v to the smallest unused index Consider successors of v Successor w has not yet been visited; recurse on it Successor w is in stack S and hence in the current SCC If w is not on stack, then v, w is a crossedge in the DFS tree and must be ignored Note: The next line may look odd but is correct. It says w.index not w.lowlink; that is deliberate and from the original paper If v is a root node, pop the stack and generate an SCC start a new strongly connected component","Completions":"from algorithms.graph.graph import DirectedGraph\n\n\n# pylint: disable=too-few-public-methods\nclass Tarjan:\n \"\"\"\n A directed graph used for finding strongly connected components\n \"\"\"\n def __init__(self, dict_graph):\n self.graph = DirectedGraph(dict_graph)\n self.index = 0\n self.stack = []\n\n # Runs Tarjan\n # Set all node index to None\n for vertex in self.graph.nodes:\n vertex.index = None\n\n self.sccs = []\n for vertex in self.graph.nodes:\n if vertex.index is None:\n self.strongconnect(vertex, self.sccs)\n\n def strongconnect(self, vertex, sccs):\n \"\"\"\n Given a vertex, adds all successors of the given vertex to the same connected component\n \"\"\"\n # Set the depth index for v to the smallest unused index\n vertex.index = self.index\n vertex.lowlink = self.index\n self.index += 1\n self.stack.append(vertex)\n vertex.on_stack = True\n\n # Consider successors of v\n for adjacent in self.graph.adjacency_list[vertex]:\n if adjacent.index is None:\n # Successor w has not yet been visited; recurse on it\n self.strongconnect(adjacent, sccs)\n vertex.lowlink = min(vertex.lowlink, adjacent.lowlink)\n elif adjacent.on_stack:\n # Successor w is in stack S and hence in the current SCC\n # If w is not on stack, then (v, w) is a cross-edge in the DFS\n # tree and must be ignored\n # Note: The next line may look odd - but is correct.\n # It says w.index not w.lowlink; that is deliberate and from the original paper\n vertex.lowlink = min(vertex.lowlink, adjacent.index)\n\n # If v is a root node, pop the stack and generate an SCC\n if vertex.lowlink == vertex.index:\n # start a new strongly connected component\n scc = []\n while True:\n adjacent = self.stack.pop()\n adjacent.on_stack = False\n scc.append(adjacent)\n if adjacent == vertex:\n break\n scc.sort()\n sccs.append(scc)\n"} +{"Prompt":"Finds the transitive closure of a graph. reference: https:en.wikipedia.orgwikiTransitiveclosureIngraphtheory This class represents a directed graph using adjacency lists No. of vertices default dictionary to store graph To store transitive closure Adds a directed edge to the graph A recursive DFS traversal function that finds all reachable vertices for source Mark reachability from source to target as true. Find all the vertices reachable through target The function to find transitive closure. It uses recursive dfsutil Call the recursive helper function to print DFS traversal starting from all vertices one by one","Completions":"class Graph:\n \"\"\"\n This class represents a directed graph using adjacency lists\n \"\"\"\n def __init__(self, vertices):\n # No. of vertices\n self.vertex_count = vertices\n\n # default dictionary to store graph\n self.graph = {}\n\n # To store transitive closure\n self.closure = [[0 for j in range(vertices)] for i in range(vertices)]\n\n def add_edge(self, source, target):\n \"\"\"\n Adds a directed edge to the graph\n \"\"\"\n if source in self.graph:\n self.graph[source].append(target)\n else:\n self.graph[source] = [target]\n\n def dfs_util(self, source, target):\n \"\"\"\n A recursive DFS traversal function that finds\n all reachable vertices for source\n \"\"\"\n\n # Mark reachability from source to target as true.\n self.closure[source][target] = 1\n\n # Find all the vertices reachable through target\n for adjacent in self.graph[target]:\n if self.closure[source][adjacent] == 0:\n self.dfs_util(source, adjacent)\n\n def transitive_closure(self):\n \"\"\"\n The function to find transitive closure. It uses\n recursive dfs_util()\n \"\"\"\n\n # Call the recursive helper function to print DFS\n # traversal starting from all vertices one by one\n for i in range(self.vertex_count):\n self.dfs_util(i, i)\n\n return self.closure\n"} +{"Prompt":"Different ways to traverse a graph dfs and bfs are the ultimately same except that they are visiting nodes in different order. To simulate this ordering we would use stack for dfs and queue for bfs. Traversal by depth first search. Traversal by breadth first search. Traversal by recursive depth first search.","Completions":"# dfs and bfs are the ultimately same except that they are visiting nodes in\n# different order. To simulate this ordering we would use stack for dfs and\n# queue for bfs.\n#\n\ndef dfs_traverse(graph, start):\n \"\"\"\n Traversal by depth first search.\n \"\"\"\n visited, stack = set(), [start]\n while stack:\n node = stack.pop()\n if node not in visited:\n visited.add(node)\n for next_node in graph[node]:\n if next_node not in visited:\n stack.append(next_node)\n return visited\n\ndef bfs_traverse(graph, start):\n \"\"\"\n Traversal by breadth first search.\n \"\"\"\n visited, queue = set(), [start]\n while queue:\n node = queue.pop(0)\n if node not in visited:\n visited.add(node)\n for next_node in graph[node]:\n if next_node not in visited:\n queue.append(next_node)\n return visited\n\ndef dfs_traverse_recursive(graph, start, visited=None):\n \"\"\"\n Traversal by recursive depth first search.\n \"\"\"\n if visited is None:\n visited = set()\n visited.add(start)\n for next_node in graph[start]:\n if next_node not in visited:\n dfs_traverse_recursive(graph, next_node, visited)\n return visited\n"} +{"Prompt":"Algorithm used Kadane's Algorithm kadane's algorithm is used for finding the maximum sum of contiguous subsequence in a sequence. It is considered a greedydp algorithm but I think they more greedy than dp here are some of the examples to understand the use case more clearly Example1 2, 3, 8, 1, 4 result 3, 8, 1, 4 14 Example2 1, 1, 0 result 1 1 Example3 1, 3, 4 result 1 Example1 2, 3, 8, 12, 8, 4 result 8, 4 12 Basic Algorithm Idea If the sum of the current contiguous subsequence after adding the value at the current position is less than the value at the current position then we know that it will be better if we start the current contiguous subsequence from this position. Else we add the value at the current position to the current contiguous subsequence. Note In the implementation, the contiguous subsequence has at least one element. If it can have 0 elements then the result will be maxmaxtillnow, 0","Completions":"def max_contiguous_subsequence_sum(arr) -> int:\n arr_size = len(arr)\n\n if arr_size == 0:\n return 0\n\n max_till_now = arr[0]\n curr_sub_sum = 0\n\n for i in range(0, arr_size):\n if curr_sub_sum + arr[i] < arr[i]:\n curr_sub_sum = arr[i]\n else:\n curr_sub_sum += arr[i]\n\n max_till_now = max(max_till_now, curr_sub_sum)\n\n return max_till_now\n"} +{"Prompt":"from abc import ABCMeta, abstractmethod class AbstractHeapmetaclassABCMeta: Pass. abstractmethod def percupself, i: Pass. abstractmethod def percdownself, i: Pass. abstractmethod def removeminself: Binary Heap Class def initself: self.currentsize 0 self.heap 0 def percupself, i: while i 2 0: if self.heapi self.heapi 2: Swap value of child with value of its parent self.heapi, self.heapi2 self.heapi2, self.heapi i i 2 def insertself, val: self.heap.appendval self.currentsize self.currentsize 1 self.percupself.currentsize def minchildself, i: if 2 i 1 self.currentsize: No right child return 2 i if self.heap2 i self.heap2 i 1: return 2 i 1 return 2 i def percdownself, i: while 2 i self.currentsize: minchild self.minchildi if self.heapminchild self.heapi: Swap min child with parent self.heapminchild, self.heapi self.heapi, self.heapminchild i minchild def removeminself: ret self.heap1 the smallest value at beginning Replace it by the last value self.heap1 self.heapself.currentsize self.currentsize self.currentsize 1 self.heap.pop self.percdown1 return ret","Completions":"r\"\"\"\nBinary Heap. A min heap is a complete binary tree where each node is smaller than\nits children. The root, therefore, is the minimum element in the tree. The min\nheap uses an array to represent the data and operation. For example a min heap:\n\n 4\n \/ \\\n 50 7\n \/ \\ \/\n55 90 87\n\nHeap [0, 4, 50, 7, 55, 90, 87]\n\nMethod in class: insert, remove_min\nFor example insert(2) in a min heap:\n\n 4 4 2\n \/ \\ \/ \\ \/ \\\n 50 7 --> 50 2 --> 50 4\n \/ \\ \/ \\ \/ \\ \/ \\ \/ \\ \/ \\\n55 90 87 2 55 90 87 7 55 90 87 7\n\nFor example remove_min() in a min heap:\n\n 4 87 7\n \/ \\ \/ \\ \/ \\\n 50 7 --> 50 7 --> 50 87\n \/ \\ \/ \/ \\ \/ \\\n55 90 87 55 90 55 90\n\n\"\"\"\nfrom abc import ABCMeta, abstractmethod\n\n\nclass AbstractHeap(metaclass=ABCMeta):\n \"\"\"Abstract Class for Binary Heap.\"\"\"\n\n def __init__(self):\n \"\"\"Pass.\"\"\"\n\n @abstractmethod\n def perc_up(self, i):\n \"\"\"Pass.\"\"\"\n\n @abstractmethod\n def insert(self, val):\n \"\"\"Pass.\"\"\"\n\n @abstractmethod\n def perc_down(self, i):\n \"\"\"Pass.\"\"\"\n\n @abstractmethod\n def min_child(self, i):\n \"\"\"Pass.\"\"\"\n\n @abstractmethod\n def remove_min(self):\n \"\"\"Pass.\"\"\"\n\n\nclass BinaryHeap(AbstractHeap):\n \"\"\"Binary Heap Class\"\"\"\n\n def __init__(self):\n self.current_size = 0\n self.heap = [(0)]\n\n def perc_up(self, i):\n while i \/\/ 2 > 0:\n if self.heap[i] < self.heap[i \/\/ 2]:\n # Swap value of child with value of its parent\n self.heap[i], self.heap[i\/\/2] = self.heap[i\/\/2], self.heap[i]\n i = i \/\/ 2\n\n def insert(self, val):\n \"\"\"\n Method insert always start by inserting the element at the bottom.\n It inserts rightmost spot so as to maintain the complete tree property.\n Then, it fixes the tree by swapping the new element with its parent,\n until it finds an appropriate spot for the element. It essentially\n perc_up the minimum element\n Complexity: O(logN)\n \"\"\"\n self.heap.append(val)\n self.current_size = self.current_size + 1\n self.perc_up(self.current_size)\n\n \"\"\"\n Method min_child returns the index of smaller of 2 children of parent at index i\n \"\"\"\n\n def min_child(self, i):\n if 2 * i + 1 > self.current_size: # No right child\n return 2 * i\n if self.heap[2 * i] > self.heap[2 * i + 1]:\n return 2 * i + 1\n return 2 * i\n\n def perc_down(self, i):\n while 2 * i < self.current_size:\n min_child = self.min_child(i)\n if self.heap[min_child] < self.heap[i]:\n # Swap min child with parent\n self.heap[min_child], self.heap[i] = self.heap[i], self.heap[min_child]\n i = min_child\n \"\"\"\n Remove Min method removes the minimum element and swap it with the last\n element in the heap( the bottommost, rightmost element). Then, it\n perc_down this element, swapping it with one of its children until the\n min heap property is restored\n Complexity: O(logN)\n \"\"\"\n\n def remove_min(self):\n ret = self.heap[1] # the smallest value at beginning\n # Replace it by the last value\n self.heap[1] = self.heap[self.current_size]\n self.current_size = self.current_size - 1\n self.heap.pop()\n self.perc_down(1)\n return ret\n"} +{"Prompt":"Given a list of points, find the k closest to the origin. Idea: Maintain a max heap of k elements. We can iterate through all points. If a point p has a smaller distance to the origin than the top element of a heap, we add point p to the heap and remove the top element. After iterating through all points, our heap contains the k closest points to the origin. Time: Oknklogk Space: Ok Initialize max heap with first k points. Python does not support a max heap; thus we can use the default min heap where the keys distance are negated. For every point p in pointsk:, check if p is smaller than the root of the max heap; if it is, add p to heap and remove root. Reheapify. Same as: if d heap00: heappushheap, d,p heappopheap Note: heappushpop is more efficient than separate push and pop calls. Each heappushpop call takes Ologk time. Calculates the distance for a point from origo return point0 origin02 point1 origin12","Completions":"from heapq import heapify, heappushpop\n\n\ndef k_closest(points, k, origin=(0, 0)):\n # Time: O(k+(n-k)logk)\n # Space: O(k)\n \"\"\"Initialize max heap with first k points.\n Python does not support a max heap; thus we can use the default min heap\n where the keys (distance) are negated.\n \"\"\"\n heap = [(-distance(p, origin), p) for p in points[:k]]\n heapify(heap)\n\n \"\"\"\n For every point p in points[k:],\n check if p is smaller than the root of the max heap;\n if it is, add p to heap and remove root. Reheapify.\n \"\"\"\n for point in points[k:]:\n dist = distance(point, origin)\n\n heappushpop(heap, (-dist, point)) # heappushpop does conditional check\n \"\"\"Same as:\n if d < -heap[0][0]:\n heappush(heap, (-d,p))\n heappop(heap)\n\n Note: heappushpop is more efficient than separate push and pop calls.\n Each heappushpop call takes O(logk) time.\n \"\"\"\n\n return [point for nd, point in heap] # return points in heap\n\n\ndef distance(point, origin=(0, 0)):\n \"\"\" Calculates the distance for a point from origo\"\"\"\n return (point[0] - origin[0])**2 + (point[1] - origin[1])**2\n"} +{"Prompt":"Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity. Definition for singlylinked list. ListNode Class def initself, val: self.val val self.next None def mergeklistslists: Merge List dummy ListNodeNone curr dummy q PriorityQueue for node in lists: if node: q.putnode.val, node while not q.empty: curr.next q.get1 These two lines seem to curr curr.next be equivalent to : curr q.get1 if curr.next: q.putcurr.next.val, curr.next return dummy.next","Completions":"from heapq import heappop, heapreplace, heapify\nfrom queue import PriorityQueue\n\n\n# Definition for singly-linked list.\nclass ListNode(object):\n \"\"\" ListNode Class\"\"\"\n\n def __init__(self, val):\n self.val = val\n self.next = None\n\n\ndef merge_k_lists(lists):\n \"\"\" Merge Lists \"\"\"\n dummy = node = ListNode(0)\n list_h = [(n.val, n) for n in lists if n]\n heapify(list_h)\n while list_h:\n _, n_val = list_h[0]\n if n_val.next is None:\n heappop(list_h) # only change heap size when necessary\n else:\n heapreplace(list_h, (n_val.next.val, n_val.next))\n node.next = n_val\n node = node.next\n\n return dummy.next\n\n\ndef merge_k_lists(lists):\n \"\"\" Merge List \"\"\"\n dummy = ListNode(None)\n curr = dummy\n q = PriorityQueue()\n for node in lists:\n if node:\n q.put((node.val, node))\n while not q.empty():\n curr.next = q.get()[1] # These two lines seem to\n curr = curr.next # be equivalent to :- curr = q.get()[1]\n if curr.next:\n q.put((curr.next.val, curr.next))\n return dummy.next\n\n\n\"\"\"\nI think my code's complexity is also O(nlogk) and not using heap or priority queue,\nn means the total elements and k means the size of list.\n\nThe mergeTwoLists function in my code comes from the problem Merge Two Sorted Lists\nwhose complexity obviously is O(n), n is the sum of length of l1 and l2.\n\nTo put it simpler, assume the k is 2^x, So the progress of combination is like a full binary tree,\nfrom bottom to top. So on every level of tree, the combination complexity is n,\nbecause every level have all n numbers without repetition.\nThe level of tree is x, ie log k. So the complexity is O(n log k).\n\nfor example, 8 ListNode, and the length of every ListNode is x1, x2,\nx3, x4, x5, x6, x7, x8, total is n.\n\non level 3: x1+x2, x3+x4, x5+x6, x7+x8 sum: n\n\non level 2: x1+x2+x3+x4, x5+x6+x7+x8 sum: n\n\non level 1: x1+x2+x3+x4+x5+x6+x7+x8 sum: n\n\"\"\"\n"} +{"Prompt":"coding: utf8 A city's skyline is the outer contour of the silhouette formed by all the buildings in that city when viewed from a distance. Now suppose you are given the locations and height of all the buildings as shown on a cityscape photo Figure A, write a program to output the skyline formed by these buildings collectively Figure B. The geometric information of each building is represented by a triplet of integers Li, Ri, Hi, where Li and Ri are the x coordinates of the left and right edge of the ith building, respectively, and Hi is its height. It is guaranteed that 0 Li, Ri INTMAX, 0 Hi INTMAX, and Ri Li 0. You may assume all buildings are perfect rectangles grounded on an absolutely flat surface at height 0. For instance, the dimensions of all buildings in Figure A are recorded as: 2 9 10, 3 7 15, 5 12 12, 15 20 10, 19 24 8 . The output is a list of key points red dots in Figure B in the format of x1,y1, x2, y2, x3, y3, ... that uniquely defines a skyline. A key point is the left endpoint of a horizontal line segment. Note that the last key point, where the rightmost building ends, is merely used to mark the termination of the skyline, and always has zero height. Also, the ground in between any two adjacent buildings should be considered part of the skyline contour. For instance, the skyline in Figure B should be represented as: 2 10, 3 15, 7 12, 12 0, 15 10, 20 8, 24, 0 . Notes: The number of buildings in any input list is guaranteed to be in the range 0, 10000. The input list is already sorted in ascending order by the left x position Li. The output list must be sorted by the x position. There must be no consecutive horizontal lines of equal height in the output skyline. For instance, ...2 3, 4 5, 7 5, 11 5, 12 7... is not acceptable; the three lines of height 5 should be merged into one in the final output as such: ...2 3, 4 5, 12 7, ... Wortst Time Complexity: ONlogN :type buildings: ListListint :rtype: ListListint","Completions":"# -*- coding: utf-8 -*-\n\"\"\"\nA city's skyline is the outer contour of the silhouette formed by all the buildings\nin that city when viewed from a distance.\nNow suppose you are given the locations and height of all the buildings\nas shown on a cityscape photo (Figure A),\nwrite a program to output the skyline formed by these buildings collectively (Figure B).\n\nThe geometric information of each building is represented by a triplet of integers [Li, Ri, Hi],\nwhere Li and Ri are the x coordinates of the left and right edge of the ith building, respectively,\nand Hi is its height. It is guaranteed that 0 \u2264 Li, Ri \u2264 INT_MAX, 0 < Hi \u2264 INT_MAX, and Ri - Li > 0.\nYou may assume all buildings are perfect rectangles grounded on an absolutely flat surface at height 0.\n\nFor instance, the dimensions of all buildings in Figure A are recorded as:\n[ [2 9 10], [3 7 15], [5 12 12], [15 20 10], [19 24 8] ] .\n\nThe output is a list of \"key points\" (red dots in Figure B) in the format of\n[ [x1,y1], [x2, y2], [x3, y3], ... ]\nthat uniquely defines a skyline.\nA key point is the left endpoint of a horizontal line segment. Note that the last key point,\nwhere the rightmost building ends,\nis merely used to mark the termination of the skyline, and always has zero height.\nAlso, the ground in between any two adjacent buildings should be considered part of the skyline contour.\n\nFor instance, the skyline in Figure B should be represented as:[ [2 10], [3 15], [7 12], [12 0], [15 10], [20 8], [24, 0] ].\n\nNotes:\n\nThe number of buildings in any input list is guaranteed to be in the range [0, 10000].\nThe input list is already sorted in ascending order by the left x position Li.\nThe output list must be sorted by the x position.\nThere must be no consecutive horizontal lines of equal height in the output skyline. For instance,\n[...[2 3], [4 5], [7 5], [11 5], [12 7]...] is not acceptable; the three lines of height 5 should be merged\ninto one in the final output as such: [...[2 3], [4 5], [12 7], ...]\n\n\"\"\"\nimport heapq\n\ndef get_skyline(lrh):\n \"\"\"\n Wortst Time Complexity: O(NlogN)\n :type buildings: List[List[int]]\n :rtype: List[List[int]]\n \"\"\"\n skyline, live = [], []\n i, n = 0, len(lrh)\n while i < n or live:\n if not live or i < n and lrh[i][0] <= -live[0][1]:\n x = lrh[i][0]\n while i < n and lrh[i][0] == x:\n heapq.heappush(live, (-lrh[i][2], -lrh[i][1]))\n i += 1\n else:\n x = -live[0][1]\n while live and -live[0][1] <= x:\n heapq.heappop(live)\n height = len(live) and -live[0][0]\n if not skyline or height != skyline[-1][1]:\n skyline += [x, height],\n return skyline\n"} +{"Prompt":"Given an array nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position. For example, Given nums 1,3,1,3,5,3,6,7, and k 3. Window position Max 1 3 1 3 5 3 6 7 3 1 3 1 3 5 3 6 7 3 1 3 1 3 5 3 6 7 5 1 3 1 3 5 3 6 7 5 1 3 1 3 5 3 6 7 6 1 3 1 3 5 3 6 7 7 Therefore, return the max sliding window as 3,3,5,5,6,7. :type nums: Listint :type k: int :rtype: Listint","Completions":"import collections\n\n\ndef max_sliding_window(nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: List[int]\n \"\"\"\n if not nums:\n return nums\n queue = collections.deque()\n res = []\n for num in nums:\n if len(queue) < k:\n queue.append(num)\n else:\n res.append(max(queue))\n queue.popleft()\n queue.append(num)\n res.append(max(queue))\n return res\n"} +{"Prompt":"You are given two nonempty linked lists representing two nonnegative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. You may assume the two numbers do not contain any leading zero, except the number 0 itself. Input: 2 4 3 5 6 4 Output: 7 0 8 converts a positive integer into a reversed linked list. for example: give 112 result 2 1 1 converts the nonnegative number list into a string. testsuite for the linked list structure and the adding function, above. 1. test case 2. test case 3. test case 4. test case","Completions":"import unittest\n\n\nclass Node:\n def __init__(self, x):\n self.val = x\n self.next = None\n\n\ndef add_two_numbers(left: Node, right: Node) -> Node:\n head = Node(0)\n current = head\n sum = 0\n while left or right:\n print(\"adding: \", left.val, right.val)\n sum \/\/= 10\n if left:\n sum += left.val\n left = left.next\n if right:\n sum += right.val\n right = right.next\n current.next = Node(sum % 10)\n current = current.next\n if sum \/\/ 10 == 1:\n current.next = Node(1)\n return head.next\n\n\ndef convert_to_list(number: int) -> Node:\n \"\"\"\n converts a positive integer into a (reversed) linked list.\n for example: give 112\n result 2 -> 1 -> 1\n \"\"\"\n if number >= 0:\n head = Node(0)\n current = head\n remainder = number % 10\n quotient = number \/\/ 10\n\n while quotient != 0:\n current.next = Node(remainder)\n current = current.next\n remainder = quotient % 10\n quotient \/\/= 10\n current.next = Node(remainder)\n return head.next\n else:\n print(\"number must be positive!\")\n\n\ndef convert_to_str(l: Node) -> str:\n \"\"\"\n converts the non-negative number list into a string.\n \"\"\"\n result = \"\"\n while l:\n result += str(l.val)\n l = l.next\n return result\n\n\nclass TestSuite(unittest.TestCase):\n \"\"\"\n testsuite for the linked list structure and\n the adding function, above.\n \"\"\"\n\n def test_convert_to_str(self):\n number1 = Node(2)\n number1.next = Node(4)\n number1.next.next = Node(3)\n self.assertEqual(\"243\", convert_to_str(number1))\n\n def test_add_two_numbers(self):\n # 1. test case\n number1 = Node(2)\n number1.next = Node(4)\n number1.next.next = Node(3)\n number2 = Node(5)\n number2.next = Node(6)\n number2.next.next = Node(4)\n result = convert_to_str(add_two_numbers(number1, number2))\n self.assertEqual(\"708\", result)\n\n # 2. test case\n number3 = Node(1)\n number3.next = Node(1)\n number3.next.next = Node(9)\n number4 = Node(1)\n number4.next = Node(0)\n number4.next.next = Node(1)\n result = convert_to_str(add_two_numbers(number3, number4))\n self.assertEqual(\"2101\", result)\n\n # 3. test case\n number5 = Node(1)\n number6 = Node(0)\n result = convert_to_str(add_two_numbers(number5, number6))\n self.assertEqual(\"1\", result)\n\n # 4. test case\n number7 = Node(9)\n number7.next = Node(1)\n number7.next.next = Node(1)\n number8 = Node(1)\n number8.next = Node(0)\n number8.next.next = Node(1)\n result = convert_to_str(add_two_numbers(number7, number8))\n self.assertEqual(\"022\", result)\n\n def test_convert_to_list(self):\n result = convert_to_str(convert_to_list(112))\n self.assertEqual(\"211\", result)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n"} +{"Prompt":"A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null. Return a deep copy of the list. :type head: RandomListNode :rtype: RandomListNode On :type head: RandomListNode :rtype: RandomListNode","Completions":"from collections import defaultdict\n\n\nclass RandomListNode(object):\n def __init__(self, label):\n self.label = label\n self.next = None\n self.random = None\n\n\ndef copy_random_pointer_v1(head):\n \"\"\"\n :type head: RandomListNode\n :rtype: RandomListNode\n \"\"\"\n dic = dict()\n m = n = head\n while m:\n dic[m] = RandomListNode(m.label)\n m = m.next\n while n:\n dic[n].next = dic.get(n.next)\n dic[n].random = dic.get(n.random)\n n = n.next\n return dic.get(head)\n\n\n# O(n)\ndef copy_random_pointer_v2(head):\n \"\"\"\n :type head: RandomListNode\n :rtype: RandomListNode\n \"\"\"\n copy = defaultdict(lambda: RandomListNode(0))\n copy[None] = None\n node = head\n while node:\n copy[node].label = node.label\n copy[node].next = copy[node.next]\n copy[node].random = copy[node.random]\n node = node.next\n return copy[head]\n"} +{"Prompt":"Write a function to delete a node except the tail in a singly linked list, given only access to that node. Supposed the linked list is 1 2 3 4 and you are given the third node with value 3, the linked list should become 1 2 4 after calling your function. make linkedlist 1 2 3 4 node3 3 after deletenode 1 2 4","Completions":"import unittest\n\n\nclass Node:\n def __init__(self, x):\n self.val = x\n self.next = None\n\n\ndef delete_node(node):\n if node is None or node.next is None:\n raise ValueError\n node.val = node.next.val\n node.next = node.next.next\n\n\nclass TestSuite(unittest.TestCase):\n\n def test_delete_node(self):\n\n # make linkedlist 1 -> 2 -> 3 -> 4\n head = Node(1)\n curr = head\n for i in range(2, 6):\n curr.next = Node(i)\n curr = curr.next\n\n # node3 = 3\n node3 = head.next.next\n\n # after delete_node => 1 -> 2 -> 4\n delete_node(node3)\n\n curr = head\n self.assertEqual(1, curr.val)\n\n curr = curr.next\n self.assertEqual(2, curr.val)\n\n curr = curr.next\n self.assertEqual(4, curr.val)\n\n curr = curr.next\n self.assertEqual(5, curr.val)\n\n tail = curr\n self.assertIsNone(tail.next)\n\n self.assertRaises(ValueError, delete_node, tail)\n self.assertRaises(ValueError, delete_node, tail.next)\n\n\nif __name__ == '__main__':\n\n unittest.main()\n"} +{"Prompt":"Given a linked list, find the first node of a cycle in it. 1 2 3 4 5 1 1 A B C D E C C Note: The solution is a direct implementation Floyd's cyclefinding algorithm Floyd's Tortoise and Hare. :type head: Node :rtype: Node create linked list A B C D E C","Completions":"import unittest\n\n\nclass Node:\n\n def __init__(self, x):\n self.val = x\n self.next = None\n\n\ndef first_cyclic_node(head):\n \"\"\"\n :type head: Node\n :rtype: Node\n \"\"\"\n runner = walker = head\n while runner and runner.next:\n runner = runner.next.next\n walker = walker.next\n if runner is walker:\n break\n\n if runner is None or runner.next is None:\n return None\n\n walker = head\n while runner is not walker:\n runner, walker = runner.next, walker.next\n return runner\n\n\nclass TestSuite(unittest.TestCase):\n\n def test_first_cyclic_node(self):\n\n # create linked list => A -> B -> C -> D -> E -> C\n head = Node('A')\n head.next = Node('B')\n curr = head.next\n\n cyclic_node = Node('C')\n curr.next = cyclic_node\n\n curr = curr.next\n curr.next = Node('D')\n curr = curr.next\n curr.next = Node('E')\n curr = curr.next\n curr.next = cyclic_node\n\n self.assertEqual('C', first_cyclic_node(head).val)\n\n\nif __name__ == '__main__':\n\n unittest.main()\n"} +{"Prompt":"This function takes two lists and returns the node they have in common, if any. In this example: 1 3 5 7 9 11 2 4 6 ...we would return 7. Note that the node itself is the unique identifier, not the value of the node. We hit the end of one of the lists, set a flag for this force the longer of the two lists to catch up The nodes match, return the node create linked list as: 1 3 5 7 9 11 2 4 6","Completions":"import unittest\n\n\nclass Node(object):\n def __init__(self, val=None):\n self.val = val\n self.next = None\n\n\ndef intersection(h1, h2):\n\n count = 0\n flag = None\n h1_orig = h1\n h2_orig = h2\n\n while h1 or h2:\n count += 1\n\n if not flag and (h1.next is None or h2.next is None):\n # We hit the end of one of the lists, set a flag for this\n flag = (count, h1.next, h2.next)\n\n if h1:\n h1 = h1.next\n if h2:\n h2 = h2.next\n\n long_len = count # Mark the length of the longer of the two lists\n short_len = flag[0]\n\n if flag[1] is None:\n shorter = h1_orig\n longer = h2_orig\n elif flag[2] is None:\n shorter = h2_orig\n longer = h1_orig\n\n while longer and shorter:\n\n while long_len > short_len:\n # force the longer of the two lists to \"catch up\"\n longer = longer.next\n long_len -= 1\n\n if longer == shorter:\n # The nodes match, return the node\n return longer\n else:\n longer = longer.next\n shorter = shorter.next\n\n return None\n\n\nclass TestSuite(unittest.TestCase):\n\n def test_intersection(self):\n\n # create linked list as:\n # 1 -> 3 -> 5\n # \\\n # 7 -> 9 -> 11\n # \/\n # 2 -> 4 -> 6\n a1 = Node(1)\n b1 = Node(3)\n c1 = Node(5)\n d = Node(7)\n a2 = Node(2)\n b2 = Node(4)\n c2 = Node(6)\n e = Node(9)\n f = Node(11)\n\n a1.next = b1\n b1.next = c1\n c1.next = d\n a2.next = b2\n b2.next = c2\n c2.next = d\n d.next = e\n e.next = f\n\n self.assertEqual(7, intersection(a1, a2).val)\n\n\nif __name__ == '__main__':\n\n unittest.main()\n"} +{"Prompt":"Given a linked list, determine if it has a cycle in it. Follow up: Can you solve it without using extra space? :type head: Node :rtype: bool","Completions":"class Node:\n\n def __init__(self, x):\n self.val = x\n self.next = None\n\ndef is_cyclic(head):\n \"\"\"\n :type head: Node\n :rtype: bool\n \"\"\"\n if not head:\n return False\n runner = head\n walker = head\n while runner.next and runner.next.next:\n runner = runner.next.next\n walker = walker.next\n if runner == walker:\n return True\n return False\n"} +{"Prompt":"split the list to two parts reverse the second part compare two parts second part has the same or one less node 1. Get the midpoint slow 2. Push the second half into the stack 3. Comparison This function builds up a dictionary where the keys are the values of the list, and the values are the positions at which these values occur in the list. We then iterate over the dict and if there is more than one key with an odd number of occurrences, bail out and return False. Otherwise, we want to ensure that the positions of occurrence sum to the value of the length of the list 1, working from the outside of the list inward. For example: Input: 1 1 2 3 2 1 1 d 1: 0,1,5,6, 2: 2,4, 3: 3 '3' is the middle outlier, 246, 066 and 516 so we have a palindrome.","Completions":"def is_palindrome(head):\n if not head:\n return True\n # split the list to two parts\n fast, slow = head.next, head\n while fast and fast.next:\n fast = fast.next.next\n slow = slow.next\n second = slow.next\n slow.next = None # Don't forget here! But forget still works!\n # reverse the second part\n node = None\n while second:\n nxt = second.next\n second.next = node\n node = second\n second = nxt\n # compare two parts\n # second part has the same or one less node\n while node:\n if node.val != head.val:\n return False\n node = node.next\n head = head.next\n return True\n\n\ndef is_palindrome_stack(head):\n if not head or not head.next:\n return True\n\n # 1. Get the midpoint (slow)\n slow = fast = cur = head\n while fast and fast.next:\n fast, slow = fast.next.next, slow.next\n\n # 2. Push the second half into the stack\n stack = [slow.val]\n while slow.next:\n slow = slow.next\n stack.append(slow.val)\n\n # 3. Comparison\n while stack:\n if stack.pop() != cur.val:\n return False\n cur = cur.next\n\n return True\n\n\ndef is_palindrome_dict(head):\n \"\"\"\n This function builds up a dictionary where the keys are the values of the list,\n and the values are the positions at which these values occur in the list.\n We then iterate over the dict and if there is more than one key with an odd\n number of occurrences, bail out and return False.\n Otherwise, we want to ensure that the positions of occurrence sum to the\n value of the length of the list - 1, working from the outside of the list inward.\n For example:\n Input: 1 -> 1 -> 2 -> 3 -> 2 -> 1 -> 1\n d = {1: [0,1,5,6], 2: [2,4], 3: [3]}\n '3' is the middle outlier, 2+4=6, 0+6=6 and 5+1=6 so we have a palindrome.\n \"\"\"\n if not head or not head.next:\n return True\n d = {}\n pos = 0\n while head:\n if head.val in d.keys():\n d[head.val].append(pos)\n else:\n d[head.val] = [pos]\n head = head.next\n pos += 1\n checksum = pos - 1\n middle = 0\n for v in d.values():\n if len(v) % 2 != 0:\n middle += 1\n else:\n step = 0\n for i in range(0, len(v)):\n if v[i] + v[len(v) - 1 - step] != checksum:\n return False\n step += 1\n if middle > 1:\n return False\n return True\n"} +{"Prompt":"Given a linked list, issort function returns true if the list is in sorted increasing order and return false otherwise. An empty list is considered to be sorted. For example: Null :List is sorted 1 2 3 4 :List is sorted 1 2 1 3 :List is not sorted","Completions":"def is_sorted(head):\n if not head:\n return True\n current = head\n while current.next:\n if current.val > current.next.val:\n return False\n current = current.next\n return True\n"} +{"Prompt":"This is a suboptimal, hacky method using eval, which is not safe for user input. We guard against danger by ensuring k in an int This is a brute force method where we keep a dict the size of the list Then we check it for the value we need. If the key is not in the dict, our and statement will short circuit and return False This is an optimal method using iteration. We move p1 k steps ahead into the list. Then we move p1 and p2 together until p1 hits the end. Went too far, k is not valid def maketestli A A B C D C F G test kthtolasteval test kthtolastdict test kthtolast","Completions":"class Node():\n def __init__(self, val=None):\n self.val = val\n self.next = None\n\n\ndef kth_to_last_eval(head, k):\n \"\"\"\n This is a suboptimal, hacky method using eval(), which is not\n safe for user input. We guard against danger by ensuring k in an int\n \"\"\"\n if not isinstance(k, int) or not head.val:\n return False\n\n nexts = '.'.join(['next' for n in range(1, k+1)])\n seeker = str('.'.join(['head', nexts]))\n\n while head:\n if eval(seeker) is None:\n return head\n else:\n head = head.next\n\n return False\n\n\ndef kth_to_last_dict(head, k):\n \"\"\"\n This is a brute force method where we keep a dict the size of the list\n Then we check it for the value we need. If the key is not in the dict,\n our and statement will short circuit and return False\n \"\"\"\n if not (head and k > -1):\n return False\n d = dict()\n count = 0\n while head:\n d[count] = head\n head = head.next\n count += 1\n return len(d)-k in d and d[len(d)-k]\n\n\ndef kth_to_last(head, k):\n \"\"\"\n This is an optimal method using iteration.\n We move p1 k steps ahead into the list.\n Then we move p1 and p2 together until p1 hits the end.\n \"\"\"\n if not (head or k > -1):\n return False\n p1 = head\n p2 = head\n for i in range(1, k+1):\n if p1 is None:\n # Went too far, k is not valid\n raise IndexError\n p1 = p1.next\n while p1:\n p1 = p1.next\n p2 = p2.next\n return p2\n\n\ndef print_linked_list(head):\n string = \"\"\n while head.next:\n string += head.val + \" -> \"\n head = head.next\n string += head.val\n print(string)\n\n\ndef test():\n # def make_test_li\n # A A B C D C F G\n a1 = Node(\"A\")\n a2 = Node(\"A\")\n b = Node(\"B\")\n c1 = Node(\"C\")\n d = Node(\"D\")\n c2 = Node(\"C\")\n f = Node(\"F\")\n g = Node(\"G\")\n a1.next = a2\n a2.next = b\n b.next = c1\n c1.next = d\n d.next = c2\n c2.next = f\n f.next = g\n print_linked_list(a1)\n\n # test kth_to_last_eval\n kth = kth_to_last_eval(a1, 4)\n try:\n assert kth.val == \"D\"\n except AssertionError as e:\n e.args += (\"Expecting D, got %s\" % kth.val,)\n raise\n\n # test kth_to_last_dict\n kth = kth_to_last_dict(a1, 4)\n try:\n assert kth.val == \"D\"\n except AssertionError as e:\n e.args += (\"Expecting D, got %s\" % kth.val,)\n raise\n\n # test kth_to_last\n kth = kth_to_last(a1, 4)\n try:\n assert kth.val == \"D\"\n except AssertionError as e:\n e.args += (\"Expecting D, got %s\" % kth.val,)\n raise\n print(\"all passed.\")\n\nif __name__ == '__main__':\n test()\n"} +{"Prompt":"Pros Linked Lists have constanttime insertions and deletions in any position, in comparison, arrays require On time to do the same thing. Linked lists can continue to expand without having to specify their size ahead of time remember our lectures on Array sizing from the Array Sequence section of the course! Cons To access an element in a linked list, you need to take Ok time to go from the head of the list to the kth element. In contrast, arrays have constant time operations to access elements in an array.","Completions":"# Pros\n# Linked Lists have constant-time insertions and deletions in any position,\n# in comparison, arrays require O(n) time to do the same thing.\n# Linked lists can continue to expand without having to specify\n# their size ahead of time (remember our lectures on Array sizing\n# from the Array Sequence section of the course!)\n\n# Cons\n# To access an element in a linked list, you need to take O(k) time\n# to go from the head of the list to the kth element.\n# In contrast, arrays have constant time operations to access\n# elements in an array.\n\nclass DoublyLinkedListNode(object):\n def __init__(self, value):\n self.value = value\n self.next = None\n self.prev = None\n\n\nclass SinglyLinkedListNode(object):\n def __init__(self, value):\n self.value = value\n self.next = None\n"} +{"Prompt":"Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists. For example: Input: 124, 134 Output: 112344 recursively","Completions":"class Node:\n\n def __init__(self, x):\n self.val = x\n self.next = None\n\ndef merge_two_list(l1, l2):\n ret = cur = Node(0)\n while l1 and l2:\n if l1.val < l2.val:\n cur.next = l1\n l1 = l1.next\n else:\n cur.next = l2\n l2 = l2.next\n cur = cur.next\n cur.next = l1 or l2\n return ret.next\n\n# recursively\ndef merge_two_list_recur(l1, l2):\n if not l1 or not l2:\n return l1 or l2\n if l1.val < l2.val:\n l1.next = merge_two_list_recur(l1.next, l2)\n return l1\n else:\n l2.next = merge_two_list_recur(l1, l2.next)\n return l2\n"} +{"Prompt":"Write code to partition a linked list around a value x, such that all nodes less than x come before all nodes greater than or equal to x. If x is contained within the list, the values of x only need to be after the elements less than x. The partition element x can appear anywhere in the right partition; it does not need to appear between the left and right partitions. 3 5 8 5 10 2 1 partition5 3 1 2 10 5 5 8 We assume the values of all linked list nodes are int and that x in an int. cache previous value in case it needs to be pointed elsewhere","Completions":"class Node():\n def __init__(self, val=None):\n self.val = int(val)\n self.next = None\n\n\ndef print_linked_list(head):\n string = \"\"\n while head.next:\n string += str(head.val) + \" -> \"\n head = head.next\n string += str(head.val)\n print(string)\n\n\ndef partition(head, x):\n left = None\n right = None\n prev = None\n current = head\n while current:\n if int(current.val) >= x:\n if not right:\n right = current\n else:\n if not left:\n left = current\n else:\n prev.next = current.next\n left.next = current\n left = current\n left.next = right\n if prev and prev.next is None:\n break\n # cache previous value in case it needs to be pointed elsewhere\n prev = current\n current = current.next\n\n\ndef test():\n a = Node(\"3\")\n b = Node(\"5\")\n c = Node(\"8\")\n d = Node(\"5\")\n e = Node(\"10\")\n f = Node(\"2\")\n g = Node(\"1\")\n\n a.next = b\n b.next = c\n c.next = d\n d.next = e\n e.next = f\n f.next = g\n\n print_linked_list(a)\n partition(a, 5)\n print_linked_list(a)\n\n\nif __name__ == '__main__':\n test()\n"} +{"Prompt":"Time Complexity: ON Space Complexity: ON Time Complexity: ON2 Space Complexity: O1 A A B C D C F G","Completions":"class Node():\n def __init__(self, val = None):\n self.val = val\n self.next = None\n\ndef remove_dups(head):\n \"\"\"\n Time Complexity: O(N)\n Space Complexity: O(N)\n \"\"\"\n hashset = set()\n prev = Node()\n while head:\n if head.val in hashset:\n prev.next = head.next\n else:\n hashset.add(head.val)\n prev = head\n head = head.next\n\ndef remove_dups_wothout_set(head):\n \"\"\"\n Time Complexity: O(N^2)\n Space Complexity: O(1)\n \"\"\"\n current = head\n while current:\n runner = current\n while runner.next:\n if runner.next.val == current.val:\n runner.next = runner.next.next\n else:\n runner = runner.next\n current = current.next\n\ndef print_linked_list(head):\n string = \"\"\n while head.next:\n string += head.val + \" -> \"\n head = head.next\n string += head.val\n print(string)\n\n# A A B C D C F G\n\na1 = Node(\"A\")\na2 = Node(\"A\")\nb = Node(\"B\")\nc1 = Node(\"C\")\nd = Node(\"D\")\nc2 = Node(\"C\")\nf = Node(\"F\")\ng = Node(\"G\")\n\na1.next = a2\na2.next = b\nb.next = c1\nc1.next = d\nd.next = c2\nc2.next = f\nf.next = g\n\nremove_dups(a1)\nprint_linked_list(a1)\nremove_dups_wothout_set(a1)\nprint_linked_list(a1)\n"} +{"Prompt":"Given a linked list, removerange function accepts a starting and ending index as parameters and removes the elements at those indexes inclusive from the list For example: List: 8, 13, 17, 4, 9, 12, 98, 41, 7, 23, 0, 92 removerangelist, 3, 8; List becomes: 8, 13, 17, 23, 0, 92 legal range of the list 0 start index end index size of list. Case: remove node at head Move pointer to start position Remove data until the end","Completions":"def remove_range(head, start, end):\n assert(start <= end)\n # Case: remove node at head\n if start == 0:\n for i in range(0, end+1):\n if head != None:\n head = head.next\n else:\n current = head\n # Move pointer to start position\n for i in range(0,start-1):\n current = current.next\n # Remove data until the end\n for i in range(0, end-start + 1):\n if current != None and current.next != None:\n current.next = current.next.next\n return head\n"} +{"Prompt":"Reverse a singly linked list. For example: 1 2 3 4 After reverse: 4 3 2 1 Iterative solution Tn On :type head: ListNode :rtype: ListNode Recursive solution Tn On :type head: ListNode :rtype: ListNode","Completions":"#\n# Iterative solution\n# T(n)- O(n)\n#\ndef reverse_list(head):\n \"\"\"\n :type head: ListNode\n :rtype: ListNode\n \"\"\"\n if not head or not head.next:\n return head\n prev = None\n while head:\n current = head\n head = head.next\n current.next = prev\n prev = current\n return prev\n\n\n#\n# Recursive solution\n# T(n)- O(n)\n#\ndef reverse_list_recursive(head):\n \"\"\"\n :type head: ListNode\n :rtype: ListNode\n \"\"\"\n if head is None or head.next is None:\n return head\n p = head.next\n head.next = None\n revrest = reverse_list_recursive(p)\n p.next = head\n return revrest\n"} +{"Prompt":"Given a list, rotate the list to the right by k places, where k is nonnegative. For example: Given 12345NULL and k 2, return 45123NULL. Definition for singlylinked list. class ListNodeobject: def initself, x: self.val x self.next None :type head: ListNode :type k: int :rtype: ListNode count length of the list make it circular rotate until lengthk","Completions":"# Definition for singly-linked list.\n# class ListNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\n\ndef rotate_right(head, k):\n \"\"\"\n :type head: ListNode\n :type k: int\n :rtype: ListNode\n \"\"\"\n if not head or not head.next:\n return head\n current = head\n length = 1\n # count length of the list\n while current.next:\n current = current.next\n length += 1\n # make it circular\n current.next = head\n k = k % length\n # rotate until length-k\n for i in range(length-k):\n current = current.next\n head = current.next\n current.next = None\n return head\n"} +{"Prompt":"Given a linked list, swap every two adjacent nodes and return its head. For example, Given 1234, you should return the list as 2143. Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.","Completions":"class Node(object):\n def __init__(self, x):\n self.val = x\n self.next = None\n\ndef swap_pairs(head):\n if not head:\n return head\n start = Node(0)\n start.next = head\n current = start\n while current.next and current.next.next:\n first = current.next\n second = current.next.next\n first.next = second.next\n current.next = second\n current.next.next = first\n current = current.next.next\n return start.next\n"} +{"Prompt":"HashMap Data Type HashMap Create a new, empty map. It returns an empty map collection. putkey, val Add a new keyvalue pair to the map. If the key is already in the map then replace the old value with the new value. getkey Given a key, return the value stored in the map or None otherwise. delkey or del mapkey Delete the keyvalue pair from the map using a statement of the form del mapkey. len Return the number of keyvalue pairs stored in the map. in Return True for a statement of the form key in map, if the given key is in the map, False otherwise. can assign to hash index key already exists here, assign over table is full That key was never assigned key found table is full and wrapped around That key was never assigned key found, assign with deleted sentinel table is full and wrapped around linear probing increase size of dict 2 if filled 23 size like python dict","Completions":"class HashTable(object):\n \"\"\"\n HashMap Data Type\n HashMap() Create a new, empty map. It returns an empty map collection.\n put(key, val) Add a new key-value pair to the map. If the key is already in the map then replace\n the old value with the new value.\n get(key) Given a key, return the value stored in the map or None otherwise.\n del_(key) or del map[key] Delete the key-value pair from the map using a statement of the form del map[key].\n len() Return the number of key-value pairs stored in the map.\n in Return True for a statement of the form key in map, if the given key is in the map, False otherwise.\n \"\"\"\n\n _empty = object()\n _deleted = object()\n\n def __init__(self, size=11):\n self.size = size\n self._len = 0\n self._keys = [self._empty] * size # keys\n self._values = [self._empty] * size # values\n\n def put(self, key, value):\n initial_hash = hash_ = self.hash(key)\n\n while True:\n if self._keys[hash_] is self._empty or self._keys[hash_] is self._deleted:\n # can assign to hash_ index\n self._keys[hash_] = key\n self._values[hash_] = value\n self._len += 1\n return\n elif self._keys[hash_] == key:\n # key already exists here, assign over\n self._keys[hash_] = key\n self._values[hash_] = value\n return\n\n hash_ = self._rehash(hash_)\n\n if initial_hash == hash_:\n # table is full\n raise ValueError(\"Table is full\")\n\n def get(self, key):\n initial_hash = hash_ = self.hash(key)\n while True:\n if self._keys[hash_] is self._empty:\n # That key was never assigned\n return None\n elif self._keys[hash_] == key:\n # key found\n return self._values[hash_]\n\n hash_ = self._rehash(hash_)\n if initial_hash == hash_:\n # table is full and wrapped around\n return None\n\n def del_(self, key):\n initial_hash = hash_ = self.hash(key)\n while True:\n if self._keys[hash_] is self._empty:\n # That key was never assigned\n return None\n elif self._keys[hash_] == key:\n # key found, assign with deleted sentinel\n self._keys[hash_] = self._deleted\n self._values[hash_] = self._deleted\n self._len -= 1\n return\n\n hash_ = self._rehash(hash_)\n if initial_hash == hash_:\n # table is full and wrapped around\n return None\n\n def hash(self, key):\n return key % self.size\n\n def _rehash(self, old_hash):\n \"\"\"\n linear probing\n \"\"\"\n return (old_hash + 1) % self.size\n\n def __getitem__(self, key):\n return self.get(key)\n\n def __delitem__(self, key):\n return self.del_(key)\n\n def __setitem__(self, key, value):\n self.put(key, value)\n\n def __len__(self):\n return self._len\n\n\nclass ResizableHashTable(HashTable):\n MIN_SIZE = 8\n\n def __init__(self):\n super().__init__(self.MIN_SIZE)\n\n def put(self, key, value):\n rv = super().put(key, value)\n # increase size of dict * 2 if filled >= 2\/3 size (like python dict)\n if len(self) >= (self.size * 2) \/ 3:\n self.__resize()\n\n def __resize(self):\n keys, values = self._keys, self._values\n self.size *= 2 # this will be the new size\n self._len = 0\n self._keys = [self._empty] * self.size\n self._values = [self._empty] * self.size\n for key, value in zip(keys, values):\n if key is not self._empty and key is not self._deleted:\n self.put(key, value)\n"} +{"Prompt":"Given two strings s and t , write a function to determine if t is an anagram of s. Example 1: Input: s anagram, t nagaram Output: true Example 2: Input: s rat, t car Output: false Note: You may assume the string contains only lowercase alphabets. Reference: https:leetcode.comproblemsvalidanagramdescription :type s: str :type t: str :rtype: bool","Completions":"def is_anagram(s, t):\n \"\"\"\n :type s: str\n :type t: str\n :rtype: bool\n \"\"\"\n maps = {}\n mapt = {}\n for i in s:\n maps[i] = maps.get(i, 0) + 1\n for i in t:\n mapt[i] = mapt.get(i, 0) + 1\n return maps == mapt\n"} +{"Prompt":"Given two strings s and t, determine if they are isomorphic. Two strings are isomorphic if the characters in s can be replaced to get t. All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character but a character may map to itself. Example 1: Input: s egg, t add Output: true Example 2: Input: s foo, t bar Output: false Example 3: Input: s paper, t title Output: true Reference: https:leetcode.comproblemsisomorphicstringsdescription :type s: str :type t: str :rtype: bool","Completions":"def is_isomorphic(s, t):\n \"\"\"\n :type s: str\n :type t: str\n :rtype: bool\n \"\"\"\n if len(s) != len(t):\n return False\n dict = {}\n set_value = set()\n for i in range(len(s)):\n if s[i] not in dict:\n if t[i] in set_value:\n return False\n dict[s[i]] = t[i]\n set_value.add(t[i])\n else:\n if dict[s[i]] != t[i]:\n return False\n return True\n"} +{"Prompt":"Given string a and b, with b containing all distinct characters, find the longest common sub sequence's length. Expected complexity On logn. Assuming s2 has all unique chars","Completions":"def max_common_sub_string(s1, s2):\n # Assuming s2 has all unique chars\n s2dic = {s2[i]: i for i in range(len(s2))}\n maxr = 0\n subs = ''\n i = 0\n while i < len(s1):\n if s1[i] in s2dic:\n j = s2dic[s1[i]]\n k = i\n while j < len(s2) and k < len(s1) and s1[k] == s2[j]:\n k += 1\n j += 1\n if k - i > maxr:\n maxr = k-i\n subs = s1[i:k]\n i = k\n else:\n i += 1\n return subs\n"} +{"Prompt":"from icecream import ic ics, logestSubStr","Completions":"def longest_palindromic_subsequence(s):\n\n k = len(s)\n olist = [0] * k # \u7533\u8bf7\u957f\u5ea6\u4e3an\u7684\u5217\u8868\uff0c\u5e76\u521d\u59cb\u5316\n nList = [0] * k # \u540c\u4e0a\n logestSubStr = \"\"\n logestLen = 0\n\n for j in range(0, k):\n for i in range(0, j + 1):\n if j - i <= 1:\n if s[i] == s[j]:\n nList[i] = 1 # \u5f53 j \u65f6\uff0c\u7b2c i \u4e2a\u5b50\u4e32\u4e3a\u56de\u6587\u5b50\u4e32\n len_t = j - i + 1\n if logestLen < len_t: # \u5224\u65ad\u957f\u5ea6\n logestSubStr = s[i:j + 1]\n logestLen = len_t\n else:\n if s[i] == s[j] and olist[i+1]: # \u5f53j-i>1\u65f6\uff0c\u5224\u65ads[i]\u662f\u5426\u7b49\u4e8es[j]\uff0c\u5e76\u5224\u65ad\u5f53j-1\u65f6\uff0c\u7b2ci+1\u4e2a\u5b50\u4e32\u662f\u5426\u4e3a\u56de\u6587\u5b50\u4e32\n nList[i] = 1 # \u5f53 j \u65f6\uff0c\u7b2c i \u4e2a\u5b50\u4e32\u4e3a\u56de\u6587\u5b50\u4e32\n len_t = j - i + 1\n if logestLen < len_t:\n logestSubStr = s[i:j + 1]\n logestLen = len_t\n olist = nList # \u8986\u76d6\u65e7\u7684\u5217\u8868\n nList = [0] * k # \u65b0\u7684\u5217\u8868\u6e05\u7a7a\n # ~ from icecream import ic\n # ~ ic(s, logestSubStr)\n return logestLen#, logestSubStr\n"} +{"Prompt":"Design a data structure that supports all following operations in average O1 time. insertval: Inserts an item val to the set if not already present. removeval: Removes an item val from the set if present. getRandom: Returns a random element from current set of elements. Each element must have the same probability of being returned.","Completions":"import random\n\n\nclass RandomizedSet:\n def __init__(self):\n self.nums = []\n self.idxs = {}\n\n def insert(self, val):\n if val not in self.idxs:\n self.nums.append(val)\n self.idxs[val] = len(self.nums)-1\n return True\n return False\n\n def remove(self, val):\n if val in self.idxs:\n idx, last = self.idxs[val], self.nums[-1]\n self.nums[idx], self.idxs[last] = last, idx\n self.nums.pop()\n self.idxs.pop(val, 0)\n return True\n return False\n\n def get_random(self):\n idx = random.randint(0, len(self.nums)-1)\n return self.nums[idx]\n\n\nif __name__ == \"__main__\":\n rs = RandomizedSet()\n print(\"insert 1: \", rs.insert(1))\n print(\"insert 2: \", rs.insert(2))\n print(\"insert 3: \", rs.insert(3))\n print(\"insert 4: \", rs.insert(4))\n print(\"remove 3: \", rs.remove(3))\n print(\"remove 3: \", rs.remove(3))\n print(\"remove 1: \", rs.remove(1))\n print(\"random: \", rs.get_random())\n print(\"random: \", rs.get_random())\n print(\"random: \", rs.get_random())\n print(\"random: \", rs.get_random())\n"} +{"Prompt":"HashTable Data Type: By having each bucket contain a linked list of elements that are hashed to that bucket. Usage: table SeparateChainingHashTable Create a new, empty map. table.put'hello', 'world' Add a new keyvalue pair. lentable Return the number of keyvalue pairs stored in the map. 1 table.get'hello' Get value by key. 'world' del table'hello' Equivalent to table.del'hello', deleting keyvalue pair. table.get'hello' is None Return None if a key doesn't exist. True","Completions":"import unittest\n\n\nclass Node(object):\n def __init__(self, key=None, value=None, next=None):\n self.key = key\n self.value = value\n self.next = next\n\n\nclass SeparateChainingHashTable(object):\n \"\"\"\n HashTable Data Type:\n By having each bucket contain a linked list of elements that are hashed to that bucket.\n\n Usage:\n >>> table = SeparateChainingHashTable() # Create a new, empty map.\n >>> table.put('hello', 'world') # Add a new key-value pair.\n >>> len(table) # Return the number of key-value pairs stored in the map.\n 1\n >>> table.get('hello') # Get value by key.\n 'world'\n >>> del table['hello'] # Equivalent to `table.del_('hello')`, deleting key-value pair.\n >>> table.get('hello') is None # Return `None` if a key doesn't exist.\n True\n \"\"\"\n _empty = None\n\n def __init__(self, size=11):\n self.size = size\n self._len = 0\n self._table = [self._empty] * size\n\n def put(self, key, value):\n hash_ = self.hash(key)\n node_ = self._table[hash_]\n if node_ is self._empty:\n self._table[hash_] = Node(key, value)\n else:\n while node_.next is not None:\n if node_.key == key:\n node_.value = value\n return\n node_ = node_.next\n node_.next = Node(key, value)\n self._len += 1\n\n def get(self, key):\n hash_ = self.hash(key)\n node_ = self._table[hash_]\n while node_ is not self._empty:\n if node_.key == key:\n return node_.value\n node_ = node_.next\n return None\n\n def del_(self, key):\n hash_ = self.hash(key)\n node_ = self._table[hash_]\n pre_node = None\n while node_ is not None:\n if node_.key == key:\n if pre_node is None:\n self._table[hash_] = node_.next\n else:\n pre_node.next = node_.next\n self._len -= 1\n pre_node = node_\n node_ = node_.next\n\n def hash(self, key):\n return hash(key) % self.size\n\n def __len__(self):\n return self._len\n\n def __getitem__(self, key):\n return self.get(key)\n\n def __delitem__(self, key):\n return self.del_(key)\n\n def __setitem__(self, key, value):\n self.put(key, value)\n"} +{"Prompt":"Determine if a Sudoku is valid, according to: Sudoku Puzzles The Rules. The Sudoku board could be partially filled, where empty cells are filled with the character '.'.","Completions":"def is_valid_sudoku(self, board):\n seen = []\n for i, row in enumerate(board):\n for j, c in enumerate(row):\n if c != '.':\n seen += [(c,j),(i,c),(i\/3,j\/3,c)]\n return len(seen) == len(set(seen))\n"} +{"Prompt":"Given a pattern and a string str, find if str follows the same pattern. Here follow means a full match, such that there is a bijection between a letter in pattern and a nonempty word in str. Example 1: Input: pattern abba, str dog cat cat dog Output: true Example 2: Input:pattern abba, str dog cat cat fish Output: false Example 3: Input: pattern aaaa, str dog cat cat dog Output: false Example 4: Input: pattern abba, str dog dog dog dog Output: false Notes: You may assume pattern contains only lowercase letters, and str contains lowercase letters separated by a single space. Reference: https:leetcode.comproblemswordpatterndescription","Completions":"def word_pattern(pattern, str):\n dict = {}\n set_value = set()\n list_str = str.split()\n if len(list_str) != len(pattern):\n return False\n for i in range(len(pattern)):\n if pattern[i] not in dict:\n if list_str[i] in set_value:\n return False\n dict[pattern[i]] = list_str[i]\n set_value.add(list_str[i])\n else:\n if dict[pattern[i]] != list_str[i]:\n return False\n return True\n"} +{"Prompt":"Collection of mathematical algorithms and functions.","Completions":"from .base_conversion import *\nfrom .decimal_to_binary_ip import *\nfrom .euler_totient import *\nfrom .extended_gcd import *\nfrom .factorial import *\nfrom .gcd import *\nfrom .generate_strobogrammtic import *\nfrom .is_strobogrammatic import *\nfrom .modular_exponential import *\nfrom .next_perfect_square import *\nfrom .prime_check import *\nfrom .primes_sieve_of_eratosthenes import *\nfrom .pythagoras import *\nfrom .rabin_miller import *\nfrom .rsa import *\nfrom .combination import *\nfrom .cosine_similarity import *\nfrom .find_order_simple import *\nfrom .find_primitive_root_simple import *\nfrom .diffie_hellman_key_exchange import *\nfrom .num_digits import *\nfrom .power import *\nfrom .magic_number import *\nfrom .krishnamurthy_number import *\nfrom .num_perfect_squares import *\n"} +{"Prompt":"Integer base conversion algorithm inttobase5, 2 return '101'. basetoint'F', 16 return 15. :type num: int :type base: int :rtype: str Note : You can use int builtin function instead of this. :type strtoconvert: str :type base: int :rtype: int","Completions":"import string\n\ndef int_to_base(num, base):\n \"\"\"\n :type num: int\n :type base: int\n :rtype: str\n \"\"\"\n is_negative = False\n if num == 0:\n return '0'\n if num < 0:\n is_negative = True\n num *= -1\n digit = string.digits + string.ascii_uppercase\n res = ''\n while num > 0:\n res += digit[num % base]\n num \/\/= base\n if is_negative:\n return '-' + res[::-1]\n return res[::-1]\n\n\ndef base_to_int(str_to_convert, base):\n \"\"\"\n Note : You can use int() built-in function instead of this.\n :type str_to_convert: str\n :type base: int\n :rtype: int\n \"\"\"\n\n digit = {}\n for ind, char in enumerate(string.digits + string.ascii_uppercase):\n digit[char] = ind\n multiplier = 1\n res = 0\n for char in str_to_convert[::-1]:\n res += digit[char] * multiplier\n multiplier *= base\n return res\n"} +{"Prompt":"Solves system of equations using the chinese remainder theorem if possible. Computes the smallest x that satisfies the chinese remainder theorem for a system of equations. The system of equations has the form: x nums0 rems0 x nums1 rems1 ... x numsk 1 remsk 1 Where k is the number of elements in nums and rems, k 0. All numbers in nums needs to be pariwise coprime otherwise an exception is raised returns x: the smallest value for x that satisfies the system of equations","Completions":"from typing import List\nfrom algorithms.maths.gcd import gcd\n\ndef solve_chinese_remainder(nums : List[int], rems : List[int]):\n \"\"\"\n Computes the smallest x that satisfies the chinese remainder theorem\n for a system of equations.\n The system of equations has the form:\n x % nums[0] = rems[0]\n x % nums[1] = rems[1]\n ...\n x % nums[k - 1] = rems[k - 1]\n Where k is the number of elements in nums and rems, k > 0.\n All numbers in nums needs to be pariwise coprime otherwise an exception is raised\n returns x: the smallest value for x that satisfies the system of equations\n \"\"\"\n if not len(nums) == len(rems):\n raise Exception(\"nums and rems should have equal length\")\n if not len(nums) > 0:\n raise Exception(\"Lists nums and rems need to contain at least one element\")\n for num in nums:\n if not num > 1:\n raise Exception(\"All numbers in nums needs to be > 1\")\n if not _check_coprime(nums):\n raise Exception(\"All pairs of numbers in nums are not coprime\")\n k = len(nums)\n x = 1\n while True:\n i = 0\n while i < k:\n if x % nums[i] != rems[i]:\n break\n i += 1\n if i == k:\n return x\n x += 1\n\ndef _check_coprime(list_to_check : List[int]):\n for ind, num in enumerate(list_to_check):\n for num2 in list_to_check[ind + 1:]:\n if gcd(num, num2) != 1:\n return False\n return True\n"} +{"Prompt":"Functions to calculate nCr ie how many ways to choose r items from n items This function calculates nCr. if n r or r 0: return 1 return combinationn1, r1 combinationn1, r def combinationmemon, r:","Completions":"def combination(n, r):\n \"\"\"This function calculates nCr.\"\"\"\n if n == r or r == 0:\n return 1\n return combination(n-1, r-1) + combination(n-1, r)\n\ndef combination_memo(n, r):\n \"\"\"This function calculates nCr using memoization method.\"\"\"\n memo = {}\n def recur(n, r):\n if n == r or r == 0:\n return 1\n if (n, r) not in memo:\n memo[(n, r)] = recur(n - 1, r - 1) + recur(n - 1, r)\n return memo[(n, r)]\n return recur(n, r)\n"} +{"Prompt":"Calculate cosine similarity between given two 1d list. Two list must have the same length. Example: cosinesimilarity1, 1, 1, 1, 2, 1 output : 0.47140452079103173 Calculate l2 distance from two given vectors. Calculate cosine similarity between given two vectors :type vec1: list :type vec2: list Calculate the dot product of two vectors","Completions":"import math\n\n\ndef _l2_distance(vec):\n \"\"\"\n Calculate l2 distance from two given vectors.\n \"\"\"\n norm = 0.\n for element in vec:\n norm += element * element\n norm = math.sqrt(norm)\n return norm\n\n\ndef cosine_similarity(vec1, vec2):\n \"\"\"\n Calculate cosine similarity between given two vectors\n :type vec1: list\n :type vec2: list\n \"\"\"\n if len(vec1) != len(vec2):\n raise ValueError(\"The two vectors must be the same length. Got shape \" + str(len(vec1))\n + \" and \" + str(len(vec2)))\n\n norm_a = _l2_distance(vec1)\n norm_b = _l2_distance(vec2)\n\n similarity = 0.\n\n # Calculate the dot product of two vectors\n for vec1_element, vec2_element in zip(vec1, vec2):\n similarity += vec1_element * vec2_element\n\n similarity \/= (norm_a * norm_b)\n\n return similarity\n"} +{"Prompt":"Given an ip address in dotteddecimal representation, determine the binary representation. For example, decimaltobinary255.0.0.5 returns 11111111.00000000.00000000.00000101 accepts string returns string Convert 8bit decimal number to binary representation :type val: str :rtype: str Convert dotteddecimal ip address to binary representation with help of decimaltobinaryutil","Completions":"def decimal_to_binary_util(val):\n \"\"\"\n Convert 8-bit decimal number to binary representation\n :type val: str\n :rtype: str\n \"\"\"\n bits = [128, 64, 32, 16, 8, 4, 2, 1]\n val = int(val)\n binary_rep = ''\n for bit in bits:\n if val >= bit:\n binary_rep += str(1)\n val -= bit\n else:\n binary_rep += str(0)\n\n return binary_rep\n\ndef decimal_to_binary_ip(ip):\n \"\"\"\n Convert dotted-decimal ip address to binary representation with help of decimal_to_binary_util\n \"\"\"\n values = ip.split('.')\n binary_list = []\n for val in values:\n binary_list.append(decimal_to_binary_util(val))\n return '.'.join(binary_list)\n"} +{"Prompt":"Algorithms for performing diffiehellman key exchange. Code from algorithmsmathsprimecheck.py, written by 'goswamirahul' and 'Hai Honag Dang' Return True if num is a prime number Else return False. For positive integer n and given integer a that satisfies gcda, n 1, the order of a modulo n is the smallest positive integer k that satisfies pow a, k n 1. In other words, ak 1 mod n. Order of certain number may or may not exist. If not, return 1. Exception Handeling : 1 is the order of of 1 Euler's totient function, also known as phifunction n, counts the number of integers between 1 and n inclusive, which are coprime to n. Two numbers are coprime if their greatest common divisor GCD equals 1. Code from algorithmsmathseulertotient.py, written by 'goswamirahul' Euler's totient function or Phi function. Time Complexity: Osqrtn. result n for i in range2, intn 0.5 1: if n i 0: while n i 0: n i result result i if n 1: result result n return result def findprimitiverootn: Exception Handeling : 0 is the only primitive root of 1 To have order, a and n must be relative prime with each other. DiffieHellman key exchange is the method that enables two entities in here, Alice and Bob, not knowing each other, to share common secret key through notencrypted communication network. This method use the property of oneway function discrete logarithm For example, given a, b and n, it is easy to calculate x that satisfies ab x mod n. However, it is very hard to calculate x that satisfies ax b mod n. For using this method, large prime number p and its primitive root a must be given. Alice determine her private key in the range of 1 p1. This must be kept in secret return randint1, p1 def alicepublickeyaprk, a, p: Bob determine his private key in the range of 1 p1. This must be kept in secret return randint1, p1 def bobpublickeybprk, a, p: Alice calculate secret key shared with Bob, with her private key and Bob's public key. This must be kept in secret return powbpuk, aprk p def bobsharedkeyapuk, bprk, p: Perform diffiehelmman key exchange. if option is not None: Print explanation of process when option parameter is given option 1 if primecheckp is False: printfp is not a prime number p must be large prime number return False try: prootlist findprimitiverootp prootlist.indexa except ValueError: printfa is not a primitive root of p a must be primitive root of p return False aprk aliceprivatekeyp apuk alicepublickeyaprk, a, p bprk bobprivatekeyp bpuk bobpublickeybprk, a, p if option 1: printfAlice's private key: aprk printfAlice's public key: apuk printfBob's private key: bprk printfBob's public key: bpuk In here, Alice send her public key to Bob, and Bob also send his public key to Alice. ashk alicesharedkeybpuk, aprk, p bshk bobsharedkeyapuk, bprk, p print fShared key calculated by Alice ashk print fShared key calculated by Bob bshk return ashk bshk","Completions":"import math\nfrom random import randint\n\n\n\"\"\"\nCode from \/algorithms\/maths\/prime_check.py,\nwritten by 'goswami-rahul' and 'Hai Honag Dang'\n\"\"\"\ndef prime_check(num):\n \"\"\"Return True if num is a prime number\n Else return False.\n \"\"\"\n\n if num <= 1:\n return False\n if num == 2 or num == 3:\n return True\n if num % 2 == 0 or num % 3 == 0:\n return False\n j = 5\n while j * j <= num:\n if num % j == 0 or num % (j + 2) == 0:\n return False\n j += 6\n return True\n\n\n\"\"\"\nFor positive integer n and given integer a that satisfies gcd(a, n) = 1,\nthe order of a modulo n is the smallest positive integer k that satisfies\npow (a, k) % n = 1. In other words, (a^k) \u2261 1 (mod n).\nOrder of certain number may or may not exist. If not, return -1.\n\"\"\"\ndef find_order(a, n):\n if (a == 1) & (n == 1):\n # Exception Handeling : 1 is the order of of 1\n return 1\n if math.gcd(a, n) != 1:\n print (\"a and n should be relative prime!\")\n return -1\n for i in range(1, n):\n if pow(a, i) % n == 1:\n return i\n return -1\n\n\n\"\"\"\nEuler's totient function, also known as phi-function \u03d5(n),\ncounts the number of integers between 1 and n inclusive,\nwhich are coprime to n.\n(Two numbers are coprime if their greatest common divisor (GCD) equals 1).\nCode from \/algorithms\/maths\/euler_totient.py, written by 'goswami-rahul'\n\"\"\"\ndef euler_totient(n):\n \"\"\"Euler's totient function or Phi function.\n Time Complexity: O(sqrt(n)).\"\"\"\n result = n\n for i in range(2, int(n ** 0.5) + 1):\n if n % i == 0:\n while n % i == 0:\n n \/\/= i\n result -= result \/\/ i\n if n > 1:\n result -= result \/\/ n\n return result\n\n\"\"\"\nFor positive integer n and given integer a that satisfies gcd(a, n) = 1,\na is the primitive root of n, if a's order k for n satisfies k = \u03d5(n).\nPrimitive roots of certain number may or may not be exist.\nIf so, return empty list.\n\"\"\"\n\ndef find_primitive_root(n):\n \"\"\" Returns all primitive roots of n. \"\"\"\n if n == 1:\n # Exception Handeling : 0 is the only primitive root of 1\n return [0]\n phi = euler_totient(n)\n p_root_list = []\n for i in range (1, n):\n if math.gcd(i, n) != 1:\n # To have order, a and n must be relative prime with each other.\n continue\n order = find_order(i, n)\n if order == phi:\n p_root_list.append(i)\n return p_root_list\n\n\n\"\"\"\nDiffie-Hellman key exchange is the method that enables\ntwo entities (in here, Alice and Bob), not knowing each other,\nto share common secret key through not-encrypted communication network.\nThis method use the property of one-way function (discrete logarithm)\nFor example, given a, b and n, it is easy to calculate x\nthat satisfies (a^b) \u2261 x (mod n).\nHowever, it is very hard to calculate x that satisfies (a^x) \u2261 b (mod n).\nFor using this method, large prime number p and its primitive root a\nmust be given.\n\"\"\"\n\ndef alice_private_key(p):\n \"\"\"Alice determine her private key\n in the range of 1 ~ p-1.\n This must be kept in secret\"\"\"\n return randint(1, p-1)\n\n\ndef alice_public_key(a_pr_k, a, p):\n \"\"\"Alice calculate her public key\n with her private key.\n This is open to public\"\"\"\n return pow(a, a_pr_k) % p\n\n\ndef bob_private_key(p):\n \"\"\"Bob determine his private key\n in the range of 1 ~ p-1.\n This must be kept in secret\"\"\"\n return randint(1, p-1)\n\n\ndef bob_public_key(b_pr_k, a, p):\n \"\"\"Bob calculate his public key\n with his private key.\n This is open to public\"\"\"\n return pow(a, b_pr_k) % p\n\n\ndef alice_shared_key(b_pu_k, a_pr_k, p):\n \"\"\" Alice calculate secret key shared with Bob,\n with her private key and Bob's public key.\n This must be kept in secret\"\"\"\n return pow(b_pu_k, a_pr_k) % p\n\n\ndef bob_shared_key(a_pu_k, b_pr_k, p):\n \"\"\" Bob calculate secret key shared with Alice,\n with his private key and Alice's public key.\n This must be kept in secret\"\"\"\n return pow(a_pu_k, b_pr_k) % p\n\n\ndef diffie_hellman_key_exchange(a, p, option = None):\n \"\"\" Perform diffie-helmman key exchange. \"\"\"\n if option is not None:\n # Print explanation of process when option parameter is given\n option = 1\n if prime_check(p) is False:\n print(f\"{p} is not a prime number\")\n # p must be large prime number\n return False\n try:\n p_root_list = find_primitive_root(p)\n p_root_list.index(a)\n except ValueError:\n print(f\"{a} is not a primitive root of {p}\")\n # a must be primitive root of p\n return False\n\n a_pr_k = alice_private_key(p)\n a_pu_k = alice_public_key(a_pr_k, a, p)\n\n b_pr_k = bob_private_key(p)\n b_pu_k = bob_public_key(b_pr_k, a, p)\n\n if option == 1:\n print(f\"Alice's private key: {a_pr_k}\")\n print(f\"Alice's public key: {a_pu_k}\")\n print(f\"Bob's private key: {b_pr_k}\")\n print(f\"Bob's public key: {b_pu_k}\")\n\n # In here, Alice send her public key to Bob, and Bob also send his public key to Alice.\n\n a_sh_k = alice_shared_key(b_pu_k, a_pr_k, p)\n b_sh_k = bob_shared_key(a_pu_k, b_pr_k, p)\n print (f\"Shared key calculated by Alice = {a_sh_k}\")\n print (f\"Shared key calculated by Bob = {b_sh_k}\")\n\n return a_sh_k == b_sh_k\n"} +{"Prompt":"Euler's totient function, also known as phifunction n, counts the number of integers between 1 and n inclusive, which are coprime to n. Two numbers are coprime if their greatest common divisor GCD equals 1. Euler's totient function or Phi function. Time Complexity: Osqrtn. result n for i in range2, intn 0.5 1: if n i 0: while n i 0: n i result result i if n 1: result result n return result","Completions":"def euler_totient(n):\n \"\"\"Euler's totient function or Phi function.\n Time Complexity: O(sqrt(n)).\"\"\"\n result = n\n for i in range(2, int(n ** 0.5) + 1):\n if n % i == 0:\n while n % i == 0:\n n \/\/= i\n result -= result \/\/ i\n if n > 1:\n result -= result \/\/ n\n return result\n"} +{"Prompt":"Provides extended GCD functionality for finding coprime numbers s and t such that: num1 s num2 t GCDnum1, num2. Ie the coefficients of Bzout's identity. Extended GCD algorithm. Return s, t, g such that num1 s num2 t GCDnum1, num2 and s and t are coprime.","Completions":"def extended_gcd(num1, num2):\n \"\"\"Extended GCD algorithm.\n Return s, t, g\n such that num1 * s + num2 * t = GCD(num1, num2)\n and s and t are co-prime.\n \"\"\"\n\n old_s, s = 1, 0\n old_t, t = 0, 1\n old_r, r = num1, num2\n\n while r != 0:\n quotient = old_r \/ r\n\n old_r, r = r, old_r - quotient * r\n old_s, s = s, old_s - quotient * s\n old_t, t = t, old_t - quotient * t\n\n return old_s, old_t, old_r\n"} +{"Prompt":"Calculates the factorial with the added functionality of calculating it modulo mod. Calculates factorial iteratively. If mod is not None, then return n! mod Time Complexity On if not isinstancen, int and n 0: raise ValueError'n' must be a nonnegative integer. if mod is not None and not isinstancemod, int and mod 0: raise ValueError'mod' must be a positive integer result 1 if n 0: return 1 for i in range2, n1: result i if mod: result mod return result def factorialrecurn, modNone:","Completions":"def factorial(n, mod=None):\n \"\"\"Calculates factorial iteratively.\n If mod is not None, then return (n! % mod)\n Time Complexity - O(n)\"\"\"\n if not (isinstance(n, int) and n >= 0):\n raise ValueError(\"'n' must be a non-negative integer.\")\n if mod is not None and not (isinstance(mod, int) and mod > 0):\n raise ValueError(\"'mod' must be a positive integer\")\n result = 1\n if n == 0:\n return 1\n for i in range(2, n+1):\n result *= i\n if mod:\n result %= mod\n return result\n\n\ndef factorial_recur(n, mod=None):\n \"\"\"Calculates factorial recursively.\n If mod is not None, then return (n! % mod)\n Time Complexity - O(n)\"\"\"\n if not (isinstance(n, int) and n >= 0):\n raise ValueError(\"'n' must be a non-negative integer.\")\n if mod is not None and not (isinstance(mod, int) and mod > 0):\n raise ValueError(\"'mod' must be a positive integer\")\n if n == 0:\n return 1\n result = n * factorial(n - 1, mod)\n if mod:\n result %= mod\n return result\n"} +{"Prompt":"Implementation of the CooleyTukey, which is the most common FFT algorithm. Input: an array of complex values which has a size of N, where N is an integer power of 2 Output: an array of complex values which is the discrete fourier transform of the input Example 1 Input: 2.02j, 1.03j, 3.01j, 2.02j Output: 88j, 2j, 22j, 20j Pseudocode: https:en.wikipedia.orgwikiCooleyE28093TukeyFFTalgorithm Recursive implementation of the CooleyTukey N lenx if N 1: return x get the elements at evenodd indices even fftx0::2 odd fftx1::2 y 0 for i in rangeN for k in rangeN2: q exp2jpikNoddk yk evenk q yk N2 evenk q return y","Completions":"from cmath import exp, pi\n\ndef fft(x):\n \"\"\" Recursive implementation of the Cooley-Tukey\"\"\"\n N = len(x)\n if N == 1:\n return x\n\n # get the elements at even\/odd indices\n even = fft(x[0::2])\n odd = fft(x[1::2])\n\n y = [0 for i in range(N)]\n for k in range(N\/\/2):\n q = exp(-2j*pi*k\/N)*odd[k]\n y[k] = even[k] + q\n y[k + N\/\/2] = even[k] - q\n\n return y\n"} +{"Prompt":"For positive integer n and given integer a that satisfies gcda, n 1, the order of a modulo n is the smallest positive integer k that satisfies pow a, k n 1. In other words, ak 1 mod n. Order of a certain number may or may not be exist. If not, return 1. Total time complexity Onlogn: On for iteration loop, Ologn for builtin power function Find order for positive integer n and given integer a that satisfies gcda, n 1. Exception Handeling : 1 is the order of of 1","Completions":"import math\n\ndef find_order(a, n):\n \"\"\"\n Find order for positive integer n and given integer a that satisfies gcd(a, n) = 1.\n \"\"\"\n if (a == 1) & (n == 1):\n # Exception Handeling : 1 is the order of of 1\n return 1\n if math.gcd(a, n) != 1:\n print (\"a and n should be relative prime!\")\n return -1\n for i in range(1, n):\n if pow(a, i) % n == 1:\n return i\n return -1\n"} +{"Prompt":"Function to find the primitive root of a number. For positive integer n and given integer a that satisfies gcda, n 1, the order of a modulo n is the smallest positive integer k that satisfies pow a, k n 1. In other words, ak 1 mod n. Order of certain number may or may not be exist. If so, return 1. Find order for positive integer n and given integer a that satisfies gcda, n 1. Time complexity Onlogn Exception Handeling : 1 is the order of of 1 Euler's totient function, also known as phifunction n, counts the number of integers between 1 and n inclusive, which are coprime to n. Two numbers are coprime if their greatest common divisor GCD equals 1. Code from algorithmsmathseulertotient.py, written by 'goswamirahul' Euler's totient function or Phi function. Time Complexity: Osqrtn. result n for i in range2, intn 0.5 1: if n i 0: while n i 0: n i result result i if n 1: result result n return result def findprimitiverootn: if n 1: Exception Handeling : 0 is the only primitive root of 1 return 0 phi eulertotientn prootlist To have order, a and n must be relative prime with each other.","Completions":"import math\n\n\"\"\"\nFor positive integer n and given integer a that satisfies gcd(a, n) = 1,\nthe order of a modulo n is the smallest positive integer k that satisfies\npow (a, k) % n = 1. In other words, (a^k) \u2261 1 (mod n).\nOrder of certain number may or may not be exist. If so, return -1.\n\"\"\"\ndef find_order(a, n):\n \"\"\"\n Find order for positive integer n and given integer a that satisfies gcd(a, n) = 1.\n Time complexity O(nlog(n))\n \"\"\"\n if (a == 1) & (n == 1):\n # Exception Handeling : 1 is the order of of 1\n return 1\n if math.gcd(a, n) != 1:\n print (\"a and n should be relative prime!\")\n return -1\n for i in range(1, n):\n if pow(a, i) % n == 1:\n return i\n return -1\n\n\"\"\"\nEuler's totient function, also known as phi-function \u03d5(n),\ncounts the number of integers between 1 and n inclusive,\nwhich are coprime to n.\n(Two numbers are coprime if their greatest common divisor (GCD) equals 1).\nCode from \/algorithms\/maths\/euler_totient.py, written by 'goswami-rahul'\n\"\"\"\ndef euler_totient(n):\n \"\"\"Euler's totient function or Phi function.\n Time Complexity: O(sqrt(n)).\"\"\"\n result = n\n for i in range(2, int(n ** 0.5) + 1):\n if n % i == 0:\n while n % i == 0:\n n \/\/= i\n result -= result \/\/ i\n if n > 1:\n result -= result \/\/ n\n return result\n\n\"\"\"\nFor positive integer n and given integer a that satisfies gcd(a, n) = 1,\na is the primitive root of n, if a's order k for n satisfies k = \u03d5(n).\nPrimitive roots of certain number may or may not exist.\nIf so, return empty list.\n\"\"\"\ndef find_primitive_root(n):\n if n == 1:\n # Exception Handeling : 0 is the only primitive root of 1\n return [0]\n phi = euler_totient(n)\n p_root_list = []\n \"\"\" It will return every primitive roots of n. \"\"\"\n for i in range (1, n):\n #To have order, a and n must be relative prime with each other.\n if math.gcd(i, n) == 1:\n order = find_order(i, n)\n if order == phi:\n p_root_list.append(i)\n return p_root_list\n"} +{"Prompt":"Functions for calculating the greatest common divisor of two integers or their least common multiple. Computes the greatest common divisor of integers a and b using Euclid's Algorithm. gcd,gcd,gcd,gcd, See proof: https:proofwiki.orgwikiGCDforNegativeIntegers Computes the lowest common multiple of integers a and b. return absa absb gcda, b def trailingzerox: count 0 while x and not x 1: count 1 x 1 return count def gcdbita, b:","Completions":"def gcd(a, b):\n \"\"\"Computes the greatest common divisor of integers a and b using\n Euclid's Algorithm.\n gcd{\ud835\udc4e,\ud835\udc4f}=gcd{\u2212\ud835\udc4e,\ud835\udc4f}=gcd{\ud835\udc4e,\u2212\ud835\udc4f}=gcd{\u2212\ud835\udc4e,\u2212\ud835\udc4f}\n See proof: https:\/\/proofwiki.org\/wiki\/GCD_for_Negative_Integers\n \"\"\"\n a_int = isinstance(a, int)\n b_int = isinstance(b, int)\n a = abs(a)\n b = abs(b)\n if not(a_int or b_int):\n raise ValueError(\"Input arguments are not integers\")\n\n if (a == 0) or (b == 0) :\n raise ValueError(\"One or more input arguments equals zero\")\n\n while b != 0:\n a, b = b, a % b\n return a\n\ndef lcm(a, b):\n \"\"\"Computes the lowest common multiple of integers a and b.\"\"\"\n return abs(a) * abs(b) \/ gcd(a, b)\n\n\"\"\"\nGiven a positive integer x, computes the number of trailing zero of x.\nExample\nInput : 34(100010)\n ~~~~~^\nOutput : 1\n\nInput : 40(101000)\n ~~~^^^\nOutput : 3\n\"\"\"\ndef trailing_zero(x):\n count = 0\n while x and not x & 1:\n count += 1\n x >>= 1\n return count\n\n\"\"\"\nGiven two non-negative integer a and b,\ncomputes the greatest common divisor of a and b using bitwise operator.\n\"\"\"\ndef gcd_bit(a, b):\n \"\"\" Similar to gcd but uses bitwise operators and less error handling.\"\"\"\n tza = trailing_zero(a)\n tzb = trailing_zero(b)\n a >>= tza\n b >>= tzb\n while b:\n if a < b:\n a, b = b, a\n a -= b\n a >>= trailing_zero(a)\n return a << min(tza, tzb)\n"} +{"Prompt":"A strobogrammatic number is a number that looks the same when rotated 180 degrees looked at upside down. Find all strobogrammatic numbers that are of length n. For example, Given n 2, return 11,69,88,96. Given n, generate all strobogrammatic numbers of length n. :type n: int :rtype: Liststr :type low: str :type high: str :rtype: int","Completions":"def gen_strobogrammatic(n):\n \"\"\"\n Given n, generate all strobogrammatic numbers of length n.\n :type n: int\n :rtype: List[str]\n \"\"\"\n return helper(n, n)\n\ndef helper(n, length):\n if n == 0:\n return [\"\"]\n if n == 1:\n return [\"1\", \"0\", \"8\"]\n middles = helper(n-2, length)\n result = []\n for middle in middles:\n if n != length:\n result.append(\"0\" + middle + \"0\")\n result.append(\"8\" + middle + \"8\")\n result.append(\"1\" + middle + \"1\")\n result.append(\"9\" + middle + \"6\")\n result.append(\"6\" + middle + \"9\")\n return result\n\ndef strobogrammatic_in_range(low, high):\n \"\"\"\n :type low: str\n :type high: str\n :rtype: int\n \"\"\"\n res = []\n count = 0\n low_len = len(low)\n high_len = len(high)\n for i in range(low_len, high_len + 1):\n res.extend(helper2(i, i))\n for perm in res:\n if len(perm) == low_len and int(perm) < int(low):\n continue\n if len(perm) == high_len and int(perm) > int(high):\n continue\n count += 1\n return count\n\ndef helper2(n, length):\n if n == 0:\n return [\"\"]\n if n == 1:\n return [\"0\", \"8\", \"1\"]\n mids = helper(n-2, length)\n res = []\n for mid in mids:\n if n != length:\n res.append(\"0\"+mid+\"0\")\n res.append(\"1\"+mid+\"1\")\n res.append(\"6\"+mid+\"9\")\n res.append(\"9\"+mid+\"6\")\n res.append(\"8\"+mid+\"8\")\n return res\n"} +{"Prompt":"Implementation of hailstone function which generates a sequence for some n by following these rules: n 1 : done n is even : the next n n2 n is odd : the next n 3n 1 Return the 'hailstone sequence' from n to 1 n: The starting point of the hailstone sequence","Completions":"def hailstone(n):\n \"\"\"\n Return the 'hailstone sequence' from n to 1\n n: The starting point of the hailstone sequence\n \"\"\"\n\n sequence = [n]\n while n > 1:\n if n%2 != 0:\n n = 3*n + 1\n else:\n n = int(n\/2)\n sequence.append(n)\n return sequence\n"} +{"Prompt":"A strobogrammatic number is a number that looks the same when rotated 180 degrees looked at upside down. Write a function to determine if a number is strobogrammatic. The number is represented as a string. For example, the numbers 69, 88, and 818 are all strobogrammatic. :type num: str :rtype: bool Another implementation. return num num::1.replace'6', ''.replace'9', '6'.replace'', '9'","Completions":"def is_strobogrammatic(num):\n \"\"\"\n :type num: str\n :rtype: bool\n \"\"\"\n comb = \"00 11 88 69 96\"\n i = 0\n j = len(num) - 1\n while i <= j:\n if comb.find(num[i]+num[j]) == -1:\n return False\n i += 1\n j -= 1\n return True\n\n\ndef is_strobogrammatic2(num: str):\n \"\"\"Another implementation.\"\"\"\n return num == num[::-1].replace('6', '#').replace('9', '6').replace('#', '9')\n"} +{"Prompt":"A Krishnamurthy number is a number whose sum total of the factorials of each digit is equal to the number itself. The following are some examples of Krishnamurthy numbers: 145 is a Krishnamurthy Number because, 1! 4! 5! 1 24 120 145 40585 is also a Krishnamurthy Number. 4! 0! 5! 8! 5! 40585 357 or 25965 is NOT a Krishnamurthy Number 3! 5! 7! 6 120 5040 ! 357 The following function will check if a number is a Krishnamurthy Number or not and return a boolean value. Calculates the factorial of a given number n fact 1 while n ! 0: fact n n 1 return fact def krishnamurthynumbern: if n 0: return False sumofdigits 0 will hold sum of FACTORIAL of digits temp n while temp ! 0: get the factorial of of the last digit of n and add it to sumofdigits sumofdigits findfactorialtemp 10 replace value of temp by temp10 i.e. will remove the last digit from temp temp 10 returns True if number is krishnamurthy return sumofdigits n","Completions":"def find_factorial(n):\n \"\"\" Calculates the factorial of a given number n \"\"\"\n fact = 1\n while n != 0:\n fact *= n\n n -= 1\n return fact\n\n\ndef krishnamurthy_number(n):\n if n == 0:\n return False\n sum_of_digits = 0 # will hold sum of FACTORIAL of digits\n temp = n\n\n while temp != 0:\n\n # get the factorial of of the last digit of n and add it to sum_of_digits\n sum_of_digits += find_factorial(temp % 10)\n\n # replace value of temp by temp\/10\n # i.e. will remove the last digit from temp\n temp \/\/= 10\n\n # returns True if number is krishnamurthy\n return sum_of_digits == n\n"} +{"Prompt":"Magic Number A number is said to be a magic number, if summing the digits of the number and then recursively repeating this process for the given sum untill the number becomes a single digit number equal to 1. Example: Number 50113 5011310 101 This is a Magic Number Number 1234 123410 101 This is a Magic Number Number 199 19919 1910 101 This is a Magic Number Number 111 1113 This is NOT a Magic Number The following function checks for Magic numbers and returns a Boolean accordingly. Checks if n is a magic number totalsum 0 will end when n becomes 0 AND sum becomes single digit. while n 0 or totalsum 9: when n becomes 0 but we have a totalsum, we update the value of n with the value of the sum digits if n 0: n totalsum only when sum of digits isn't single digit totalsum 0 totalsum n 10 n 10 Return true if sum becomes 1 return totalsum 1","Completions":"def magic_number(n):\n \"\"\" Checks if n is a magic number \"\"\"\n total_sum = 0\n\n # will end when n becomes 0\n # AND\n # sum becomes single digit.\n while n > 0 or total_sum > 9:\n # when n becomes 0 but we have a total_sum,\n # we update the value of n with the value of the sum digits\n if n == 0:\n n = total_sum # only when sum of digits isn't single digit\n total_sum = 0\n total_sum += n % 10\n n \/\/= 10\n\n # Return true if sum becomes 1\n return total_sum == 1\n"} +{"Prompt":"Computes base exponent mod. Time complexity Olog n Use similar to Python inbuilt function pow. if exponent 0: raise ValueErrorExponent must be positive. base mod result 1 while exponent 0: If the last bit is 1, add 2k. if exponent 1: result result base mod exponent exponent 1 Utilize modular multiplication properties to combine the computed mod C values. base base base mod return result","Completions":"def modular_exponential(base, exponent, mod):\n \"\"\"Computes (base ^ exponent) % mod.\n Time complexity - O(log n)\n Use similar to Python in-built function pow.\"\"\"\n if exponent < 0:\n raise ValueError(\"Exponent must be positive.\")\n base %= mod\n result = 1\n\n while exponent > 0:\n # If the last bit is 1, add 2^k.\n if exponent & 1:\n result = (result * base) % mod\n exponent = exponent >> 1\n # Utilize modular multiplication properties to combine the computed mod C values.\n base = (base * base) % mod\n\n return result\n"} +{"Prompt":"extendedgcda, b modified from https:github.comkeonalgorithmsblobmasteralgorithmsmathsextendedgcd.py Extended GCD algorithm. Return s, t, g such that a s b t GCDa, b and s and t are coprime. Returns x such that a x 1 mod m a and m must be coprime","Completions":"# extended_gcd(a, b) modified from\n# https:\/\/github.com\/keon\/algorithms\/blob\/master\/algorithms\/maths\/extended_gcd.py\n\ndef extended_gcd(a: int, b: int) -> [int, int, int]:\n \"\"\"Extended GCD algorithm.\n Return s, t, g\n such that a * s + b * t = GCD(a, b)\n and s and t are co-prime.\n \"\"\"\n\n old_s, s = 1, 0\n old_t, t = 0, 1\n old_r, r = a, b\n\n while r != 0:\n quotient = old_r \/\/ r\n\n old_r, r = r, old_r - quotient * r\n old_s, s = s, old_s - quotient * s\n old_t, t = t, old_t - quotient * t\n\n return old_s, old_t, old_r\n\n\ndef modular_inverse(a: int, m: int) -> int:\n \"\"\"\n Returns x such that a * x = 1 (mod m)\n a and m must be coprime\n \"\"\"\n\n s, _, g = extended_gcd(a, m)\n if g != 1:\n raise ValueError(\"a and m must be coprime\")\n return s % m\n"} +{"Prompt":"I just bombed an interview and made pretty much zero progress on my interview question. Given a number, find the next higher number which has the exact same set of digits as the original number. For example: given 38276 return 38627. given 99999 return 1. no such number exists Condensed mathematical description: Find largest index i such that arrayi 1 arrayi. If no such i exists, then this is already the last permutation. Find largest index j such that j i and arrayj arrayi 1. Swap arrayj and arrayi 1. Reverse the suffix starting at arrayi.","Completions":"import unittest\n\n\ndef next_bigger(num):\n\n digits = [int(i) for i in str(num)]\n idx = len(digits) - 1\n\n while idx >= 1 and digits[idx-1] >= digits[idx]:\n idx -= 1\n\n if idx == 0:\n return -1 # no such number exists\n\n pivot = digits[idx-1]\n swap_idx = len(digits) - 1\n\n while pivot >= digits[swap_idx]:\n swap_idx -= 1\n\n digits[swap_idx], digits[idx-1] = digits[idx-1], digits[swap_idx]\n digits[idx:] = digits[:idx-1:-1] # prefer slicing instead of reversed(digits[idx:])\n\n return int(''.join(str(x) for x in digits))\n\n\nclass TestSuite(unittest.TestCase):\n\n def test_next_bigger(self):\n\n self.assertEqual(next_bigger(38276), 38627)\n self.assertEqual(next_bigger(12345), 12354)\n self.assertEqual(next_bigger(1528452), 1528524)\n self.assertEqual(next_bigger(138654), 143568)\n\n self.assertEqual(next_bigger(54321), -1)\n self.assertEqual(next_bigger(999), -1)\n self.assertEqual(next_bigger(5), -1)\n\n\nif __name__ == '__main__':\n\n unittest.main()\n"} +{"Prompt":"This program will look for the next perfect square. Check the argument to see if it is a perfect square itself, if it is not then return 1 otherwise look for the next perfect square. for instance if you pass 121 then the script should return the next perfect square which is 144. Alternative method, works by evaluating anything nonzero as True 0.000001 True root sq0.5 return 1 if root 1 else root12","Completions":"def find_next_square(sq):\n root = sq ** 0.5\n if root.is_integer():\n return (root + 1)**2\n return -1\n\ndef find_next_square2(sq):\n \"\"\" Alternative method, works by evaluating anything non-zero as True (0.000001 --> True) \"\"\"\n root = sq**0.5\n return -1 if root % 1 else (root+1)**2\n"} +{"Prompt":"find the nth digit of given number. 1. find the length of the number where the nth digit is from. 2. find the actual number where the nth digit is from 3. find the nth digit and return","Completions":"def find_nth_digit(n):\n \"\"\"find the nth digit of given number.\n 1. find the length of the number where the nth digit is from.\n 2. find the actual number where the nth digit is from\n 3. find the nth digit and return\n \"\"\"\n length = 1\n count = 9\n start = 1\n while n > length * count:\n n -= length * count\n length += 1\n count *= 10\n start *= 10\n start += (n-1) \/ length\n s = str(start)\n return int(s[(n-1) % length])\n"} +{"Prompt":"numdigits method will return the number of digits of a number in O1 time using math.log10 method.","Completions":"import math\n\ndef num_digits(n):\n n=abs(n)\n if n==0:\n return 1\n return int(math.log10(n))+1\n"} +{"Prompt":"Given an integer numperfectsquares will return the minimum amount of perfect squares are required to sum to the specified number. Lagrange's foursquare theorem gives us that the answer will always be between 1 and 4 https:en.wikipedia.orgwikiLagrange27sfoursquaretheorem. Some examples: Number Perfect Squares representation Answer 9 32 1 10 32 12 2 12 22 22 22 3 31 52 22 12 12 4 Returns the smallest number of perfect squares that sum to the specified number. :return: int between 1 4 If the number is a perfect square then we only need 1 number. We check if https:en.wikipedia.orgwikiLegendre27sthreesquaretheorem holds and divide the number accordingly. Ie. if the number can be written as a sum of 3 squares where the 02 is allowed, which is possible for all numbers except those of the form: 4a8b 7. If the number is of the form: 4a8b 7 it can't be expressed as a sum of three or less excluding the 02 perfect squares. If the number was of that form, the previous while loop divided away the 4a, so by now it would be of the form: 8b 7. So check if this is the case and return 4 since it neccessarily must be a sum of 4 perfect squares, in accordance with https:en.wikipedia.orgwikiLagrange27sfoursquaretheorem. By now we know that the number wasn't of the form 4a8b 7 so it can be expressed as a sum of 3 or less perfect squares. Try first to express it as a sum of 2 perfect squares, and if that fails, we know finally that it can be expressed as a sum of 3 perfect squares.","Completions":"import math\n\ndef num_perfect_squares(number):\n \"\"\"\n Returns the smallest number of perfect squares that sum to the specified number.\n :return: int between 1 - 4\n \"\"\"\n # If the number is a perfect square then we only need 1 number.\n if int(math.sqrt(number))**2 == number:\n return 1\n\n # We check if https:\/\/en.wikipedia.org\/wiki\/Legendre%27s_three-square_theorem holds and divide\n # the number accordingly. Ie. if the number can be written as a sum of 3 squares (where the\n # 0^2 is allowed), which is possible for all numbers except those of the form: 4^a(8b + 7).\n while number > 0 and number % 4 == 0:\n number \/= 4\n\n # If the number is of the form: 4^a(8b + 7) it can't be expressed as a sum of three (or less\n # excluding the 0^2) perfect squares. If the number was of that form, the previous while loop\n # divided away the 4^a, so by now it would be of the form: 8b + 7. So check if this is the case\n # and return 4 since it neccessarily must be a sum of 4 perfect squares, in accordance \n # with https:\/\/en.wikipedia.org\/wiki\/Lagrange%27s_four-square_theorem.\n if number % 8 == 7:\n return 4\n\n # By now we know that the number wasn't of the form 4^a(8b + 7) so it can be expressed as a sum\n # of 3 or less perfect squares. Try first to express it as a sum of 2 perfect squares, and if\n # that fails, we know finally that it can be expressed as a sum of 3 perfect squares.\n for i in range(1, int(math.sqrt(number)) + 1):\n if int(math.sqrt(number - i**2))**2 == number - i**2:\n return 2\n\n return 3\n"} +{"Prompt":"from future import annotations A simple Monomial class to record the details of all variables that a typical monomial is composed of. Create a monomial in the given variables: Examples: Monomial1:1 a11 Monomial 1:3, 2:2, 4:1, 5:0 , 12 12a13a22a4 Monomial 0 Monomial2:3, 3:1, 1.5 32a23a31 A helper for converting numbers to Fraction only when possible. def equaluptoscalarself, other: Monomial bool: Return True if other is a monomial and is equivalent to self up to a scalar multiple. def addself, other: Unionint, float, Fraction, Monomial: Define the addition of two monomials or the addition of a monomial with an int, float, or a Fraction. If they don't share same variables then by the definition, if they are added, the result becomes a polynomial and not a monomial. Thus, raise ValueError in that case. def eqself, other: Monomial bool: Return True if two monomials are equal upto a scalar multiple. def mulself, other: Unionint, float, Fraction, Monomial Monomial: Multiply two monomials and merge the variables in both of them. Examples: Monomial1:1 Monomial1: 3, 2: 1 a12a2 Monomial3:2 2.5 52a32 def inverseself Monomial: Compute the inverse of a monomial. Examples: Monomial1:1, 2:1, 3:2, 2.5.inverse Monomial1:1, 2:1, 3:2 ,25 def truedivself, other: Unionint, float, Fraction, Monomial Monomial: Compute the division between two monomials or a monomial and some other datatype like intfloatFraction. def floordivself, other: Unionint, float, Fraction, Monomial Monomial: For monomials, floor div is the same as true div. def cloneself Monomial: Clone the monomial. def cleanself Monomial: Clean the monomial by dropping any variables that have power 0. def subself, other: Unionint, float, Fraction, Monomial Monomial: Compute the subtraction of a monomial and a datatype such as int, float, Fraction, or Monomial. Define the hash of a monomial by the underlying variables. If hashing is implemented in Ovlogv where v represents the number of variables in the monomial, then search queries for the purposes of simplification of a polynomial can be performed in Ovlogv as well; much better than the length of the polynomial. Get the set of all variables present in the monomial. Substitute the variables in the monomial for values defined by the substitutions dictionary. Get a string representation of the monomial. A simple implementation of a polynomial class that records the details about two polynomials that are potentially comprised of multiple variables. Create a polynomial in the given variables: Examples: Polynomial Monomial1:1, 2, Monomial2:3, 1:1, 1, math.pi, Fraction1, 2 a12 1a23a11 2.6415926536 Polynomial 0 A helper for converting numbers to Fraction only when possible. def addself, other: Unionint, float, Fraction, Monomial, Polynomial Polynomial: Add a given poylnomial to a copy of self. def subself, other: Unionint, float, Fraction, Monomial, Polynomial Polynomial: Subtract the given polynomial from a copy of self. def mulself, other: Unionint, float, Fraction, Monomial, Polynomial Polynomial: Multiply a given polynomial to a copy of self. def floordivself, other: Unionint, float, Fraction, Monomial, Polynomial Polynomial: For Polynomials, floordiv is the same as truediv. def truedivself, other: Unionint, float, Fraction, Monomial, Polynomial Polynomial: For Polynomials, only division by a monomial is defined. TODO: Implement polynomial polynomial. def cloneself Polynomial: Clone the polynomial. Get all the variables present in this polynomials. res.sort Get the monomials of this polynomial. Return True if the other polynomial is the same as this. Get the value after substituting certain values for the variables defined in substitutions. Get a string representation of the polynomial.","Completions":"# from __future__ import annotations\n\nfrom fractions import Fraction\nfrom typing import Dict, Union, Set, Iterable\nfrom numbers import Rational\nfrom functools import reduce\n\n\nclass Monomial:\n \"\"\"\n A simple Monomial class to\n record the details of all variables\n that a typical monomial is composed of.\n \"\"\"\n def __init__(self, variables: Dict[int, int], coeff: Union[int, float, Fraction, None]= None) -> None:\n '''\n Create a monomial in the given variables:\n Examples:\n\n Monomial({1:1}) = (a_1)^1\n\n Monomial({\n 1:3,\n 2:2,\n 4:1,\n 5:0\n }, 12) = 12(a_1)^3(a_2)^2(a_4)\n\n Monomial({}) = 0\n\n Monomial({2:3, 3:-1}, 1.5) = (3\/2)(a_2)^3(a_3)^(-1)\n\n '''\n self.variables = dict()\n\n if coeff is None:\n if len(variables) == 0:\n coeff = Fraction(0, 1)\n else:\n coeff = Fraction(1, 1)\n elif coeff == 0:\n self.coeff = Fraction(0, 1)\n return\n\n if len(variables) == 0:\n self.coeff = Monomial._rationalize_if_possible(coeff)\n return\n\n for i in variables:\n if variables[i] != 0:\n self.variables[i] = variables[i]\n self.coeff = Monomial._rationalize_if_possible(coeff)\n\n @staticmethod\n def _rationalize_if_possible(num):\n '''\n A helper for converting numbers\n to Fraction only when possible.\n '''\n if isinstance(num, Rational):\n res = Fraction(num, 1)\n return Fraction(res.numerator, res.denominator)\n else:\n return num\n\n # def equal_upto_scalar(self, other: Monomial) -> bool:\n def equal_upto_scalar(self, other) -> bool:\n \"\"\"\n Return True if other is a monomial\n and is equivalent to self up to a scalar\n multiple.\n \"\"\"\n if not isinstance(other, Monomial):\n raise ValueError('Can only compare monomials.')\n return other.variables == self.variables\n\n # def __add__(self, other: Union[int, float, Fraction, Monomial]):\n def __add__(self, other: Union[int, float, Fraction]):\n \"\"\"\n Define the addition of two\n monomials or the addition of\n a monomial with an int, float, or a Fraction.\n \"\"\"\n if isinstance(other, int) or isinstance(other, float) or isinstance(other, Fraction):\n return self.__add__(Monomial({}, Monomial._rationalize_if_possible(other)))\n\n if not isinstance(other, Monomial):\n raise ValueError('Can only add monomials, ints, floats, or Fractions.')\n\n if self.variables == other.variables:\n mono = {i: self.variables[i] for i in self.variables}\n return Monomial(mono, Monomial._rationalize_if_possible(self.coeff + other.coeff)).clean()\n \n # If they don't share same variables then by the definition,\n # if they are added, the result becomes a polynomial and not a monomial.\n # Thus, raise ValueError in that case.\n\n raise ValueError(f'Cannot add {str(other)} to {self.__str__()} because they don\\'t have same variables.')\n\n # def __eq__(self, other: Monomial) -> bool:\n def __eq__(self, other) -> bool:\n \"\"\"\n Return True if two monomials\n are equal upto a scalar multiple.\n \"\"\"\n return self.equal_upto_scalar(other) and self.coeff == other.coeff\n\n # def __mul__(self, other: Union[int, float, Fraction, Monomial]) -> Monomial:\n def __mul__(self, other: Union[int, float, Fraction]):\n \"\"\"\n Multiply two monomials and merge the variables\n in both of them.\n\n Examples:\n\n Monomial({1:1}) * Monomial({1: -3, 2: 1}) = (a_1)^(-2)(a_2)\n Monomial({3:2}) * 2.5 = (5\/2)(a_3)^2\n\n \"\"\"\n if isinstance(other, float) or isinstance(other, int) or isinstance(other, Fraction):\n mono = {i: self.variables[i] for i in self.variables}\n return Monomial(mono, Monomial._rationalize_if_possible(self.coeff * other)).clean()\n\n if not isinstance(other, Monomial):\n raise ValueError('Can only multiply monomials, ints, floats, or Fractions.')\n else:\n mono = {i: self.variables[i] for i in self.variables}\n for i in other.variables:\n if i in mono:\n mono[i] += other.variables[i]\n else:\n mono[i] = other.variables[i]\n\n temp = dict()\n for k in mono:\n if mono[k] != 0:\n temp[k] = mono[k]\n\n return Monomial(temp, Monomial._rationalize_if_possible(self.coeff * other.coeff)).clean()\n\n # def inverse(self) -> Monomial:\n def inverse(self):\n \"\"\"\n Compute the inverse of a monomial.\n\n Examples:\n\n Monomial({1:1, 2:-1, 3:2}, 2.5).inverse() = Monomial({1:-1, 2:1, 3:-2} ,2\/5)\n\n\n \"\"\"\n mono = {i: self.variables[i] for i in self.variables if self.variables[i] != 0}\n for i in mono:\n mono[i] *= -1\n if self.coeff == 0:\n raise ValueError(\"Coefficient must not be 0.\")\n return Monomial(mono, Monomial._rationalize_if_possible(1\/self.coeff)).clean()\n\n # def __truediv__(self, other: Union[int, float, Fraction, Monomial]) -> Monomial:\n def __truediv__(self, other: Union[int, float, Fraction]):\n \"\"\"\n Compute the division between two monomials\n or a monomial and some other datatype\n like int\/float\/Fraction.\n \"\"\"\n if isinstance(other, int) or isinstance(other, float) or isinstance(other, Fraction):\n mono = {i: self.variables[i] for i in self.variables}\n if other == 0:\n raise ValueError('Cannot divide by 0.')\n return Monomial(mono, Monomial._rationalize_if_possible(self.coeff \/ other)).clean()\n\n o = other.inverse()\n return self.__mul__(o)\n\n # def __floordiv__(self, other: Union[int, float, Fraction, Monomial]) -> Monomial:\n def __floordiv__(self, other: Union[int, float, Fraction]):\n \"\"\"\n For monomials,\n floor div is the same as true div.\n \"\"\"\n return self.__truediv__(other)\n\n # def clone(self) -> Monomial:\n def clone(self):\n \"\"\"\n Clone the monomial.\n \"\"\"\n temp_variables = {i: self.variables[i] for i in self.variables}\n return Monomial(temp_variables, Monomial._rationalize_if_possible(self.coeff)).clean()\n\n # def clean(self) -> Monomial:\n def clean(self):\n \"\"\"\n Clean the monomial by dropping any variables that have power 0.\n \"\"\"\n temp_variables = {i: self.variables[i] for i in self.variables if self.variables[i] != 0}\n return Monomial(temp_variables, Monomial._rationalize_if_possible(self.coeff))\n\n # def __sub__(self, other: Union[int, float, Fraction, Monomial]) -> Monomial:\n def __sub__(self, other: Union[int, float, Fraction]):\n \"\"\"\n Compute the subtraction\n of a monomial and a datatype\n such as int, float, Fraction, or Monomial.\n \"\"\"\n if isinstance(other, int) or isinstance(other, float) or isinstance(other, Fraction):\n mono = {i: self.variables[i] for i in self.variables if self.variables[i] != 0}\n if len(mono) != 0:\n raise ValueError('Can only subtract like monomials.')\n other_term = Monomial(mono, Monomial._rationalize_if_possible(other))\n return self.__sub__(other_term)\n if not isinstance(other, Monomial):\n raise ValueError('Can only subtract monomials')\n return self.__add__(other.__mul__(Fraction(-1, 1)))\n\n def __hash__(self) -> int:\n \"\"\"\n Define the hash of a monomial\n by the underlying variables.\n\n If hashing is implemented in O(v*log(v))\n where v represents the number of\n variables in the monomial,\n then search queries for the\n purposes of simplification of a\n polynomial can be performed in\n O(v*log(v)) as well; much better than\n the length of the polynomial.\n \"\"\"\n arr = []\n for i in sorted(self.variables):\n if self.variables[i] > 0:\n for _ in range(self.variables[i]):\n arr.append(i)\n return hash(tuple(arr))\n\n def all_variables(self) -> Set:\n \"\"\"\n Get the set of all variables\n present in the monomial.\n \"\"\"\n return set(sorted(self.variables.keys()))\n\n def substitute(self, substitutions: Union[int, float, Fraction, Dict[int, Union[int, float, Fraction]]]) -> Fraction:\n \"\"\"\n Substitute the variables in the\n monomial for values defined by\n the substitutions dictionary.\n \"\"\"\n if isinstance(substitutions, int) or isinstance(substitutions, float) or isinstance(substitutions, Fraction):\n substitutions = {v: Monomial._rationalize_if_possible(substitutions) for v in self.all_variables()}\n else:\n if not self.all_variables().issubset(set(substitutions.keys())):\n raise ValueError('Some variables didn\\'t receive their values.')\n if self.coeff == 0:\n return Fraction(0, 1)\n ans = Monomial._rationalize_if_possible(self.coeff)\n for k in self.variables:\n ans *= Monomial._rationalize_if_possible(substitutions[k]**self.variables[k])\n return Monomial._rationalize_if_possible(ans)\n\n def __str__(self) -> str:\n \"\"\"\n Get a string representation of\n the monomial.\n \"\"\"\n if len(self.variables) == 0:\n return str(self.coeff)\n\n result = str(self.coeff)\n result += '('\n for i in self.variables:\n temp = 'a_{}'.format(str(i))\n if self.variables[i] > 1:\n temp = '(' + temp + ')**{}'.format(self.variables[i])\n elif self.variables[i] < 0:\n temp = '(' + temp + ')**(-{})'.format(-self.variables[i])\n elif self.variables[i] == 0:\n continue\n else:\n temp = '(' + temp + ')'\n result += temp\n return result + ')'\n\n\nclass Polynomial:\n \"\"\"\n A simple implementation\n of a polynomial class that\n records the details about two polynomials\n that are potentially comprised of multiple\n variables.\n \"\"\"\n def __init__(self, monomials: Iterable[Union[int, float, Fraction, Monomial]]) -> None:\n '''\n Create a polynomial in the given variables:\n Examples:\n\n Polynomial([\n Monomial({1:1}, 2),\n Monomial({2:3, 1:-1}, -1),\n math.pi,\n Fraction(-1, 2)\n ]) = (a_1)^2 + (-1)(a_2)^3(a_1)^(-1) + 2.6415926536\n\n Polynomial([]) = 0\n\n '''\n self.monomials = set()\n for m in monomials:\n if any(map(lambda x: isinstance(m, x), [int, float, Fraction])):\n self.monomials |= {Monomial({}, m)}\n elif isinstance(m, Monomial):\n self.monomials |= {m}\n else:\n raise ValueError('Iterable should have monomials, int, float, or Fraction.')\n self.monomials -= {Monomial({}, 0)}\n\n @staticmethod\n def _rationalize_if_possible(num):\n '''\n A helper for converting numbers\n to Fraction only when possible.\n '''\n if isinstance(num, Rational):\n res = Fraction(num, 1)\n return Fraction(res.numerator, res.denominator)\n else:\n return num\n\n\n # def __add__(self, other: Union[int, float, Fraction, Monomial, Polynomial]) -> Polynomial:\n def __add__(self, other: Union[int, float, Fraction, Monomial]):\n \"\"\"\n Add a given poylnomial to a copy of self.\n\n \"\"\"\n if isinstance(other, int) or isinstance(other, float) or isinstance(other, Fraction):\n return self.__add__(Monomial({}, Polynomial._rationalize_if_possible(other)))\n elif isinstance(other, Monomial):\n monos = {m.clone() for m in self.monomials}\n\n for _own_monos in monos:\n if _own_monos.equal_upto_scalar(other):\n scalar = _own_monos.coeff\n monos -= {_own_monos}\n temp_variables = {i: other.variables[i] for i in other.variables}\n monos |= {Monomial(temp_variables, Polynomial._rationalize_if_possible(scalar + other.coeff))}\n return Polynomial([z for z in monos])\n\n monos |= {other.clone()}\n return Polynomial([z for z in monos])\n elif isinstance(other, Polynomial):\n temp = list(z for z in {m.clone() for m in self.all_monomials()})\n\n p = Polynomial(temp)\n for o in other.all_monomials():\n p = p.__add__(o.clone())\n return p\n else:\n raise ValueError('Can only add int, float, Fraction, Monomials, or Polynomials to Polynomials.')\n\n # def __sub__(self, other: Union[int, float, Fraction, Monomial, Polynomial]) -> Polynomial:\n def __sub__(self, other: Union[int, float, Fraction, Monomial]):\n \"\"\"\n Subtract the given polynomial\n from a copy of self.\n\n \"\"\"\n if isinstance(other, int) or isinstance(other, float) or isinstance(other, Fraction):\n return self.__sub__(Monomial({}, Polynomial._rationalize_if_possible(other)))\n elif isinstance(other, Monomial):\n monos = {m.clone() for m in self.all_monomials()}\n for _own_monos in monos:\n if _own_monos.equal_upto_scalar(other):\n scalar = _own_monos.coeff\n monos -= {_own_monos}\n temp_variables = {i: other.variables[i] for i in other.variables}\n monos |= {Monomial(temp_variables, Polynomial._rationalize_if_possible(scalar - other.coeff))}\n return Polynomial([z for z in monos])\n\n to_insert = other.clone()\n to_insert.coeff *= -1\n\n monos |= {to_insert}\n return Polynomial([z for z in monos])\n\n elif isinstance(other, Polynomial):\n p = Polynomial(list(z for z in {m.clone() for m in self.all_monomials()}))\n for o in other.all_monomials():\n p = p.__sub__(o.clone())\n return p\n\n else:\n raise ValueError('Can only subtract int, float, Fraction, Monomials, or Polynomials from Polynomials.')\n return\n\n # def __mul__(self, other: Union[int, float, Fraction, Monomial, Polynomial]) -> Polynomial:\n def __mul__(self, other: Union[int, float, Fraction, Monomial]):\n \"\"\"\n Multiply a given polynomial\n to a copy of self.\n \"\"\"\n if isinstance(other, int) or isinstance(other, float) or isinstance(other, Fraction):\n result = Polynomial([])\n monos = {m.clone() for m in self.all_monomials()}\n for m in monos:\n result = result.__add__(m.clone()*other)\n return result\n elif isinstance(other, Monomial):\n result = Polynomial([])\n monos = {m.clone() for m in self.all_monomials()}\n for m in monos:\n result = result.__add__(m.clone() * other)\n return result\n elif isinstance(other, Polynomial):\n temp_self = {m.clone() for m in self.all_monomials()}\n temp_other = {m.clone() for m in other.all_monomials()}\n\n result = Polynomial([])\n\n for i in temp_self:\n for j in temp_other:\n result = result.__add__(i * j)\n\n return result\n else:\n raise ValueError('Can only multiple int, float, Fraction, Monomials, or Polynomials with Polynomials.')\n\n # def __floordiv__(self, other: Union[int, float, Fraction, Monomial, Polynomial]) -> Polynomial:\n def __floordiv__(self, other: Union[int, float, Fraction, Monomial]):\n \"\"\"\n For Polynomials, floordiv is the same\n as truediv.\n \"\"\"\n return self.__truediv__(other)\n\n # def __truediv__(self, other: Union[int, float, Fraction, Monomial, Polynomial]) -> Polynomial:\n def __truediv__(self, other: Union[int, float, Fraction, Monomial]):\n \"\"\"\n For Polynomials, only division by a monomial\n is defined.\n\n TODO: Implement polynomial \/ polynomial.\n \"\"\"\n if isinstance(other, int) or isinstance(other, float) or isinstance(other, Fraction):\n return self.__truediv__( Monomial({}, other) )\n elif isinstance(other, Monomial):\n poly_temp = reduce(lambda acc, val: acc + val, map(lambda x: x \/ other, [z for z in self.all_monomials()]), Polynomial([Monomial({}, 0)]))\n return poly_temp\n elif isinstance(other, Polynomial):\n if Monomial({}, 0) in other.all_monomials():\n if len(other.all_monomials()) == 2:\n temp_set = {x for x in other.all_monomials() if x != Monomial({}, 0)}\n only = temp_set.pop()\n return self.__truediv__(only)\n elif len(other.all_monomials()) == 1:\n temp_set = {x for x in other.all_monomials()}\n only = temp_set.pop()\n return self.__truediv__(only)\n\n raise ValueError('Can only divide a polynomial by an int, float, Fraction, or a Monomial.')\n\n return\n\n # def clone(self) -> Polynomial:\n def clone(self):\n \"\"\"\n Clone the polynomial.\n \"\"\"\n return Polynomial(list({m.clone() for m in self.all_monomials()}))\n\n def variables(self) -> Set:\n \"\"\"\n Get all the variables present\n in this polynomials.\n \"\"\"\n res = set()\n for i in self.all_monomials():\n res |= {j for j in i.variables}\n res = list(res)\n # res.sort()\n return set(res)\n\n def all_monomials(self) -> Iterable[Monomial]:\n \"\"\"\n Get the monomials of this polynomial.\n \"\"\"\n return {m for m in self.monomials if m != Monomial({}, 0)}\n\n\n def __eq__(self, other) -> bool:\n \"\"\"\n Return True if the other polynomial is the same as\n this.\n \"\"\"\n if isinstance(other, int) or isinstance(other, float) or isinstance(other, Fraction):\n other_poly = Polynomial([Monomial({}, other)])\n return self.__eq__(other_poly)\n elif isinstance(other, Monomial):\n return self.__eq__(Polynomial([other]))\n elif isinstance(other, Polynomial):\n return self.all_monomials() == other.all_monomials()\n else:\n raise ValueError('Can only compare a polynomial with an int, float, Fraction, Monomial, or another Polynomial.')\n\n\n def subs(self, substitutions: Union[int, float, Fraction, Dict[int, Union[int, float, Fraction]]]) -> Union[int, float, Fraction]:\n \"\"\"\n Get the value after substituting\n certain values for the variables\n defined in substitutions.\n \"\"\"\n if isinstance(substitutions, int) or isinstance(substitutions, float) or isinstance(substitutions, Fraction):\n substitutions = {i: Polynomial._rationalize_if_possible(substitutions) for i in set(self.variables())}\n return self.subs(substitutions)\n elif not isinstance(substitutions, dict):\n raise ValueError('The substitutions should be a dictionary.')\n if not self.variables().issubset(set(substitutions.keys())):\n raise ValueError('Some variables didn\\'t receive their values.')\n\n ans = 0\n for m in self.all_monomials():\n ans += Polynomial._rationalize_if_possible(m.substitute(substitutions))\n return Polynomial._rationalize_if_possible(ans)\n\n def __str__(self) -> str:\n \"\"\"\n Get a string representation of\n the polynomial.\n \"\"\"\n return ' + '.join(str(m) for m in self.all_monomials() if m.coeff != Fraction(0, 1))\n"} +{"Prompt":"Performs exponentiation, similarly to the builtin pow or functions. Allows also for calculating the exponentiation modulo. Iterative version of binary exponentiation Calculate a n if mod is specified, return the result modulo mod Time Complexity : Ologn Space Complexity : O1 Recursive version of binary exponentiation Calculate a n if mod is specified, return the result modulo mod Time Complexity : Ologn Space Complexity : Ologn","Completions":"def power(a: int, n: int, mod: int = None):\n \"\"\"\n Iterative version of binary exponentiation\n\n Calculate a ^ n\n if mod is specified, return the result modulo mod\n\n Time Complexity : O(log(n))\n Space Complexity : O(1)\n \"\"\"\n ans = 1\n while n:\n if n & 1:\n ans = ans * a\n a = a * a\n if mod:\n ans %= mod\n a %= mod\n n >>= 1\n return ans\n\n\ndef power_recur(a: int, n: int, mod: int = None):\n \"\"\"\n Recursive version of binary exponentiation\n\n Calculate a ^ n\n if mod is specified, return the result modulo mod\n\n Time Complexity : O(log(n))\n Space Complexity : O(log(n))\n \"\"\"\n if n == 0:\n ans = 1\n elif n == 1:\n ans = a\n else:\n ans = power_recur(a, n \/\/ 2, mod)\n ans = ans * ans\n if n % 2:\n ans = ans * a\n if mod:\n ans %= mod\n return ans\n"} +{"Prompt":"Return True if n is a prime number Else return False.","Completions":"def prime_check(n):\n \"\"\"Return True if n is a prime number\n Else return False.\n \"\"\"\n\n if n <= 1:\n return False\n if n == 2 or n == 3:\n return True\n if n % 2 == 0 or n % 3 == 0:\n return False\n j = 5\n while j * j <= n:\n if n % j == 0 or n % (j + 2) == 0:\n return False\n j += 6\n return True\n"} +{"Prompt":"Return list of all primes less than n, Using sieve of Eratosthenes. Modification: We don't need to check all even numbers, we can make the sieve excluding even numbers and adding 2 to the primes list by default. We are going to make an array of: x 2 1 if number is even, else x 2 The 1 with even number it's to exclude the number itself Because we just need numbers from 3..x if x is odd We can get value represented at index i with i2 3 For example, for x 10, we start with an array of x 2 1 4 1, 1, 1, 1 3 5 7 9 For x 11: 1, 1, 1, 1, 1 3 5 7 9 11 11 is odd, it's included in the list With this, we have reduced the array size to a half, and complexity it's also a half now. Return list of all primes less than n, Using sieve of Eratosthenes. If x is even, exclude x from list 1:","Completions":"def get_primes(n):\n \"\"\"Return list of all primes less than n,\n Using sieve of Eratosthenes.\n \"\"\"\n if n <= 0:\n raise ValueError(\"'n' must be a positive integer.\")\n # If x is even, exclude x from list (-1):\n sieve_size = (n \/\/ 2 - 1) if n % 2 == 0 else (n \/\/ 2)\n sieve = [True for _ in range(sieve_size)] # Sieve\n primes = [] # List of Primes\n if n >= 2:\n primes.append(2) # 2 is prime by default\n for i in range(sieve_size):\n if sieve[i]:\n value_at_i = i*2 + 3\n primes.append(value_at_i)\n for j in range(i, sieve_size, value_at_i):\n sieve[j] = False\n return primes\n"} +{"Prompt":"Given the lengths of two of the three sides of a right angled triangle, this function returns the length of the third side. Returns length of a third side of a right angled triangle. Passing ? will indicate the unknown side.","Completions":"def pythagoras(opposite, adjacent, hypotenuse):\n \"\"\"\n Returns length of a third side of a right angled triangle.\n Passing \"?\" will indicate the unknown side.\n \"\"\"\n try:\n if opposite == str(\"?\"):\n return (\"Opposite = \" + str(((hypotenuse**2) - (adjacent**2))**0.5))\n if adjacent == str(\"?\"):\n return (\"Adjacent = \" + str(((hypotenuse**2) - (opposite**2))**0.5))\n if hypotenuse == str(\"?\"):\n return (\"Hypotenuse = \" + str(((opposite**2) + (adjacent**2))**0.5))\n return \"You already know the answer!\"\n except:\n raise ValueError(\"invalid argument(s) were given.\")\n"} +{"Prompt":"RabinMiller primality test returning False implies that n is guaranteed composite returning True means that n is probably prime with a 4 k chance of being wrong factor n into a power of 2 times an odd number power 0 while num 2 0: num 2 power 1 return power, num def validwitnessa: x powinta, intd, intn if x 1 or x n 1: return False for in ranger 1: x powintx, int2, intn if x 1: return True if x n 1: return False return True precondition n 5 if n 5: return n 2 or n 3 True for prime r, d pow2factorn 1 for in rangek: if validwitnessrandom.randrange2, n 2: return False return True","Completions":"import random\n\n\ndef is_prime(n, k):\n\n def pow2_factor(num):\n \"\"\"factor n into a power of 2 times an odd number\"\"\"\n power = 0\n while num % 2 == 0:\n num \/= 2\n power += 1\n return power, num\n\n def valid_witness(a):\n \"\"\"\n returns true if a is a valid 'witness' for n\n a valid witness increases chances of n being prime\n an invalid witness guarantees n is composite\n \"\"\"\n x = pow(int(a), int(d), int(n))\n\n if x == 1 or x == n - 1:\n return False\n\n for _ in range(r - 1):\n x = pow(int(x), int(2), int(n))\n\n if x == 1:\n return True\n if x == n - 1:\n return False\n\n return True\n\n # precondition n >= 5\n if n < 5:\n return n == 2 or n == 3 # True for prime\n\n r, d = pow2_factor(n - 1)\n\n for _ in range(k):\n if valid_witness(random.randrange(2, n - 2)):\n return False\n\n return True\n"} +{"Prompt":"Calculates the binomial coefficient, Cn,k, with nk using recursion Time complexity is Ok, so can calculate fairly quickly for large values of k. recursivebinomialcoefficient5,0 1 recursivebinomialcoefficient8,2 28 recursivebinomialcoefficient500,300 5054949849935535817667719165973249533761635252733275327088189563256013971725761702359997954491403585396607971745777019273390505201262259748208640 function is only defined for nk Cn,0 Cn,n 1, so this is our base case. Cn,k Cn,nk, so if n2 is sufficiently small, we can reduce the problem size. else, we know Cn,k nkCn1,k1, so we can use this to reduce our problem size.","Completions":"def recursive_binomial_coefficient(n,k):\n \"\"\"Calculates the binomial coefficient, C(n,k), with n>=k using recursion\n Time complexity is O(k), so can calculate fairly quickly for large values of k.\n\n >>> recursive_binomial_coefficient(5,0)\n 1\n\n >>> recursive_binomial_coefficient(8,2)\n 28\n\n >>> recursive_binomial_coefficient(500,300)\n 5054949849935535817667719165973249533761635252733275327088189563256013971725761702359997954491403585396607971745777019273390505201262259748208640\n\n \"\"\"\n\n if k>n:\n raise ValueError('Invalid Inputs, ensure that n >= k')\n #function is only defined for n>=k\n if k == 0 or n == k:\n #C(n,0) = C(n,n) = 1, so this is our base case.\n return 1\n if k > n\/2:\n #C(n,k) = C(n,n-k), so if n\/2 is sufficiently small, we can reduce the problem size.\n return recursive_binomial_coefficient(n,n-k)\n #else, we know C(n,k) = (n\/k)C(n-1,k-1), so we can use this to reduce our problem size.\n return int((n\/k)*recursive_binomial_coefficient(n-1,k-1))\n"} +{"Prompt":"RSA encryption algorithm a method for encrypting a number that uses seperate encryption and decryption keys this file only implements the key generation algorithm there are three important numbers in RSA called n, e, and d e is called the encryption exponent d is called the decryption exponent n is called the modulus these three numbers satisfy x e d n x n to use this system for encryption, n and e are made publicly available, and d is kept secret a number x can be encrypted by computing x e n the original number can then be recovered by computing E d n, where E is the encrypted number fortunately, python provides a three argument version of pow that can compute powers modulo a number very quickly: a b c powa,b,c sample usage: n,e,d generatekey16 data 20 encrypted powdata,e,n decrypted powencrypted,d,n assert decrypted data the RSA key generating algorithm k is the number of bits in n calculate the inverse of a mod m that is, find b such that a b m 1 b 1 while not a b m 1: b 1 return b def genprimek, seedNone: size in bits of p and q need to add up to the size of n","Completions":"# sample usage:\n# n,e,d = generate_key(16)\n# data = 20\n# encrypted = pow(data,e,n)\n# decrypted = pow(encrypted,d,n)\n# assert decrypted == data\n\nimport random\n\n\ndef generate_key(k, seed=None):\n \"\"\"\n the RSA key generating algorithm\n k is the number of bits in n\n \"\"\"\n\n def modinv(a, m):\n \"\"\"calculate the inverse of a mod m\n that is, find b such that (a * b) % m == 1\"\"\"\n b = 1\n while not (a * b) % m == 1:\n b += 1\n return b\n\n def gen_prime(k, seed=None):\n \"\"\"generate a prime with k bits\"\"\"\n\n def is_prime(num):\n if num == 2:\n return True\n for i in range(2, int(num ** 0.5) + 1):\n if num % i == 0:\n return False\n return True\n\n random.seed(seed)\n while True:\n key = random.randrange(int(2 ** (k - 1)), int(2 ** k))\n if is_prime(key):\n return key\n\n # size in bits of p and q need to add up to the size of n\n p_size = k \/ 2\n q_size = k - p_size\n\n e = gen_prime(k, seed) # in many cases, e is also chosen to be a small constant\n\n while True:\n p = gen_prime(p_size, seed)\n if p % e != 1:\n break\n\n while True:\n q = gen_prime(q_size, seed)\n if q % e != 1:\n break\n\n n = p * q\n l = (p - 1) * (q - 1) # calculate totient function\n d = modinv(e, l)\n\n return int(n), int(e), int(d)\n\n\ndef encrypt(data, e, n):\n return pow(int(data), int(e), int(n))\n\n\ndef decrypt(data, d, n):\n return pow(int(data), int(d), int(n))\n"} +{"Prompt":"Given a positive integer N and a precision factor P, it produces an output with a maximum error P from the actual square root of N. Example: Given N 5 and P 0.001, can produce output x such that 2.235 x 2.237. Actual square root of 5 being 2.236. Return square root of n, with maximum absolute error epsilon guess n 2 while absguess guess n epsilon: guess guess n guess 2 return guess","Completions":"def square_root(n, epsilon=0.001):\n \"\"\"Return square root of n, with maximum absolute error epsilon\"\"\"\n guess = n \/ 2\n\n while abs(guess * guess - n) > epsilon:\n guess = (guess + (n \/ guess)) \/ 2\n\n return guess\n"} +{"Prompt":"Recently, I encountered an interview question whose description was as below: The number 89 is the first integer with more than one digit whose digits when raised up to consecutive powers give the same number. For example, 89 81 92 gives the number 89. The next number after 89 with this property is 135 11 32 53 135. Write a function that returns a list of numbers with the above property. The function will receive range as parameter. Some test cases:","Completions":"def sum_dig_pow(low, high):\n result = []\n\n for number in range(low, high + 1):\n exponent = 1 # set to 1\n summation = 0 # set to 1\n number_as_string = str(number)\n\n tokens = list(map(int, number_as_string)) # parse the string into individual digits\n\n for k in tokens:\n summation = summation + (k ** exponent)\n exponent += 1\n\n if summation == number:\n result.append(number)\n return result\n\n\n# Some test cases:\nassert sum_dig_pow(1, 10) == [1, 2, 3, 4, 5, 6, 7, 8, 9]\nassert sum_dig_pow(1, 100) == [1, 2, 3, 4, 5, 6, 7, 8, 9, 89]\n"} +{"Prompt":"The significance of the cycle index polynomial of symmetry group is deeply rooted in counting the number of configurations of an object excluding those that are symmetric in terms of permutations. For example, the following problem can be solved as a direct application of the cycle index polynomial of the symmetry group. Note: I came across this problem as a Google's foo.bar challenge at Level 5 and solved it using a purely Group Theoretic approach. : Problem: Given positive integers w, h, and s, compute the number of distinct 2D grids of dimensions w x h that contain entries from 0, 1, ..., s1. Note that two grids are defined to be equivalent if one can be obtained from the other by switching rows and columns some number of times. Approach: Compute the cycle index polynomials of Sw, and Sh, i.e. the Symmetry group on w and h symbols respectively. Compute the product of the two cycle indices while combining two monomials in such a way that for any pair of cycles c1, and c2 in the elements of Sw X Sh, the resultant monomial contains terms of the form: xlcmc1, c2gcdc1, c2 Return the specialization of the product of cycle indices at xi s for all the valid i. Code: def solvew, h, s: s1 getcycleindexsymw s2 getcycleindexsymh result cycleproductfortwopolynomialss1, s2, s return strresult Given two monomials from the cycle index of a symmetry group, compute the resultant monomial in the cartesian product corresponding to their merging. Compute the product of given cycle indices p1, and p2 and evaluate it at q. A helper for the dpstyle evaluation of the cycle index. The recurrence is given in: https:en.wikipedia.orgwikiCycleindexSymmetricgroupSn Compute the cycle index of Sn, i.e. the symmetry group of n symbols.","Completions":"from fractions import Fraction\nfrom typing import Dict, Union\nfrom polynomial import ( Monomial, Polynomial )\nfrom gcd import lcm\n\n\ndef cycle_product(m1: Monomial, m2: Monomial) -> Monomial:\n \"\"\"\n Given two monomials (from the\n cycle index of a symmetry group),\n compute the resultant monomial\n in the cartesian product\n corresponding to their merging.\n \"\"\"\n assert isinstance(m1, Monomial) and isinstance(m2, Monomial)\n A = m1.variables\n B = m2.variables\n result_variables = dict()\n for i in A:\n for j in B:\n k = lcm(i, j)\n g = (i * j) \/\/ k\n if k in result_variables:\n result_variables[k] += A[i] * B[j] * g\n else:\n result_variables[k] = A[i] * B[j] * g\n\n return Monomial(result_variables, Fraction(m1.coeff * m2.coeff, 1))\n\n\ndef cycle_product_for_two_polynomials(p1: Polynomial, p2: Polynomial, q: Union[float, int, Fraction]) -> Union[float, int, Fraction]:\n \"\"\"\n Compute the product of\n given cycle indices p1,\n and p2 and evaluate it at q.\n \"\"\"\n ans = Fraction(0, 1)\n for m1 in p1.monomials:\n for m2 in p2.monomials:\n ans += cycle_product(m1, m2).substitute(q)\n\n return ans\n\n\ndef cycle_index_sym_helper(n: int, memo: Dict[int, Polynomial]) -> Polynomial:\n \"\"\"\n A helper for the dp-style evaluation\n of the cycle index.\n\n The recurrence is given in:\n https:\/\/en.wikipedia.org\/wiki\/Cycle_index#Symmetric_group_Sn\n\n \"\"\"\n if n in memo:\n return memo[n]\n ans = Polynomial([Monomial({}, Fraction(0, 1))])\n for t in range(1, n+1):\n ans = ans.__add__(Polynomial([Monomial({t: 1}, Fraction(1, 1))]) * cycle_index_sym_helper(n-t, memo))\n ans *= Fraction(1, n)\n memo[n] = ans\n return memo[n]\n\n\ndef get_cycle_index_sym(n: int) -> Polynomial:\n \"\"\"\n Compute the cycle index\n of S_n, i.e. the symmetry\n group of n symbols.\n\n \"\"\"\n if n < 0:\n raise ValueError('n should be a non-negative integer.')\n\n memo = {\n 0: Polynomial([\n Monomial({}, Fraction(1, 1))\n ]),\n 1: Polynomial([\n Monomial({1: 1}, Fraction(1, 1))\n ]),\n 2: Polynomial([\n Monomial({1: 2}, Fraction(1, 2)),\n Monomial({2: 1}, Fraction(1, 2))\n ]),\n 3: Polynomial([\n Monomial({1: 3}, Fraction(1, 6)),\n Monomial({1: 1, 2: 1}, Fraction(1, 2)),\n Monomial({3: 1}, Fraction(1, 3))\n ]),\n 4: Polynomial([\n Monomial({1: 4}, Fraction(1, 24)),\n Monomial({2: 1, 1: 2}, Fraction(1, 4)),\n Monomial({3: 1, 1: 1}, Fraction(1, 3)),\n Monomial({2: 2}, Fraction(1, 8)),\n Monomial({4: 1}, Fraction(1, 4)),\n ])\n }\n result = cycle_index_sym_helper(n, memo)\n return result\n"} +{"Prompt":"Given a 2D grid, each cell is either a wall 'W', an enemy 'E' or empty '0' the number zero, return the maximum enemies you can kill using one bomb. The bomb kills all the enemies in the same row and column from the planted point until it hits the wall since the wall is too strong to be destroyed. Note that you can only put the bomb at an empty cell. Example: For the given grid 0 E 0 0 E 0 W E 0 E 0 0 return 3. Placing a bomb at 1,1 kills 3 enemies iterates over all cells in the grid makes sure we are next to a wall. makes sure we are next to a wall. makes sure the cell contains a 0 updates the variable calculate killed enemies for row i from column j calculate killed enemies for column j from row i TESTS Testsuite for the project","Completions":"def max_killed_enemies(grid):\n if not grid:\n return 0\n m, n = len(grid), len(grid[0])\n max_killed = 0\n row_e, col_e = 0, [0] * n\n # iterates over all cells in the grid\n for i in range(m):\n for j in range(n):\n # makes sure we are next to a wall.\n if j == 0 or grid[i][j-1] == 'W':\n row_e = row_kills(grid, i, j)\n # makes sure we are next to a wall.\n if i == 0 or grid[i-1][j] == 'W':\n col_e[j] = col_kills(grid, i, j)\n # makes sure the cell contains a 0\n if grid[i][j] == '0':\n # updates the variable\n max_killed = max(max_killed, row_e + col_e[j])\n\n return max_killed\n\n\n# calculate killed enemies for row i from column j\ndef row_kills(grid, i, j):\n num = 0\n len_row = len(grid[0])\n while j < len_row and grid[i][j] != 'W':\n if grid[i][j] == 'E':\n num += 1\n j += 1\n return num\n\n\n# calculate killed enemies for column j from row i\ndef col_kills(grid, i, j):\n num = 0\n len_col = len(grid)\n while i < len_col and grid[i][j] != 'W':\n if grid[i][j] == 'E':\n num += 1\n i += 1\n return num\n\n\n# ----------------- TESTS -------------------------\n\n\"\"\"\n Testsuite for the project\n\"\"\"\n\nimport unittest\n\n\nclass TestBombEnemy(unittest.TestCase):\n def test_3x4(self):\n grid1 = [[\"0\", \"E\", \"0\", \"0\"],\n [\"E\", \"0\", \"W\", \"E\"],\n [\"0\", \"E\", \"0\", \"0\"]]\n self.assertEqual(3, max_killed_enemies(grid1))\n\n def test_4x4(self):\n grid1 = [\n [\"0\", \"E\", \"0\", \"E\"],\n [\"E\", \"E\", \"E\", \"0\"],\n [\"E\", \"0\", \"W\", \"E\"],\n [\"0\", \"E\", \"0\", \"0\"]]\n grid2 = [\n [\"0\", \"0\", \"0\", \"E\"],\n [\"E\", \"0\", \"0\", \"0\"],\n [\"E\", \"0\", \"W\", \"E\"],\n [\"0\", \"E\", \"0\", \"0\"]]\n self.assertEqual(5, max_killed_enemies(grid1))\n self.assertEqual(3, max_killed_enemies(grid2))\n\n\nif __name__ == \"__main__\":\n unittest.main()\n"} +{"Prompt":"Cholesky matrix decomposition is used to find the decomposition of a Hermitian positivedefinite matrix A into matrix V, so that V V A, where V denotes the conjugate transpose of L. The dimensions of the matrix A must match. This method is mainly used for numeric solution of linear equations Ax b. example: Input matrix A: 4, 12, 16, 12, 37, 43, 16, 43, 98 Result: 2.0, 0.0, 0.0, 6.0, 1.0, 0.0, 8.0, 5.0, 3.0 Time complexity of this algorithm is On3, specifically about n33 :param A: Hermitian positivedefinite matrix of type ListListfloat :return: matrix of type ListListfloat if A can be decomposed, otherwise None","Completions":"import math\n\n\ndef cholesky_decomposition(A):\n \"\"\"\n :param A: Hermitian positive-definite matrix of type List[List[float]]\n :return: matrix of type List[List[float]] if A can be decomposed,\n otherwise None\n \"\"\"\n n = len(A)\n for ai in A:\n if len(ai) != n:\n return None\n V = [[0.0] * n for _ in range(n)]\n for j in range(n):\n sum_diagonal_element = 0\n for k in range(j):\n sum_diagonal_element = sum_diagonal_element + math.pow(V[j][k], 2)\n sum_diagonal_element = A[j][j] - sum_diagonal_element\n if sum_diagonal_element <= 0:\n return None\n V[j][j] = math.pow(sum_diagonal_element, 0.5)\n for i in range(j+1, n):\n sum_other_element = 0\n for k in range(j):\n sum_other_element += V[i][k]*V[j][k]\n V[i][j] = (A[i][j] - sum_other_element)\/V[j][j]\n return V\n"} +{"Prompt":"Count the number of unique paths from a00 to am1n1 We are allowed to move either right or down from a cell in the matrix. Approaches i Recursion Recurse starting from am1n1, upwards and leftwards, add the path count of both recursions and return count. ii Dynamic Programming Start from a00.Store the count in a count matrix. Return countm1n1 Tn Omn, Sn Omn Taking care of the edge cases matrix of size 1xn or mx1 Number of ways to reach aij number of ways to reach ai1j aij1","Completions":"#\n# Count the number of unique paths from a[0][0] to a[m-1][n-1]\n# We are allowed to move either right or down from a cell in the matrix.\n# Approaches-\n# (i) Recursion- Recurse starting from a[m-1][n-1], upwards and leftwards,\n# add the path count of both recursions and return count.\n# (ii) Dynamic Programming- Start from a[0][0].Store the count in a count\n# matrix. Return count[m-1][n-1]\n# T(n)- O(mn), S(n)- O(mn)\n#\n\n\ndef count_paths(m, n):\n if m < 1 or n < 1:\n return -1\n count = [[None for j in range(n)] for i in range(m)]\n\n # Taking care of the edge cases- matrix of size 1xn or mx1\n for i in range(n):\n count[0][i] = 1\n for j in range(m):\n count[j][0] = 1\n\n for i in range(1, m):\n for j in range(1, n):\n # Number of ways to reach a[i][j] = number of ways to reach\n # a[i-1][j] + a[i][j-1]\n count[i][j] = count[i - 1][j] + count[i][j - 1]\n\n print(count[m - 1][n - 1])\n\n\ndef main():\n m, n = map(int, input('Enter two positive integers: ').split())\n count_paths(m, n)\n\n\nif __name__ == '__main__':\n main()\n"} +{"Prompt":"Crout matrix decomposition is used to find two matrices that, when multiplied give our input matrix, so L U A. L stands for lower and L has nonzero elements only on diagonal and below. U stands for upper and U has nonzero elements only on diagonal and above. This can for example be used to solve systems of linear equations. The last if is used if to avoid dividing by zero. Example: We input the A matrix: 1,2,3, 3,4,5, 6,7,8 We get: L 1.0, 0.0, 0.0 3.0, 2.0, 0.0 6.0, 5.0, 0.0 U 1.0, 2.0, 3.0 0.0, 1.0, 2.0 0.0, 0.0, 1.0 We can check that L U A. I think the complexity should be On3.","Completions":"def crout_matrix_decomposition(A):\n n = len(A)\n L = [[0.0] * n for i in range(n)]\n U = [[0.0] * n for i in range(n)]\n for j in range(n):\n U[j][j] = 1.0\n for i in range(j, n):\n alpha = float(A[i][j])\n for k in range(j):\n alpha -= L[i][k]*U[k][j]\n L[i][j] = float(alpha)\n for i in range(j+1, n):\n tempU = float(A[j][i])\n for k in range(j):\n tempU -= float(L[j][k]*U[k][i])\n if int(L[j][j]) == 0:\n L[j][j] = float(0.1**40)\n U[j][i] = float(tempU\/L[j][j])\n return (L, U)\n"} +{"Prompt":"Multiplies two square matrices matA and matB of size n x n Time Complexity: On3 Returns the Identity matrix of size n x n Time Complexity: On2 Calculates matn by repeated squaring Time Complexity: Od3 logn d: dimension of the square matrix mat n: power the matrix is raised to","Completions":"def multiply(matA: list, matB: list) -> list:\n \"\"\"\n Multiplies two square matrices matA and matB of size n x n\n Time Complexity: O(n^3)\n \"\"\"\n n = len(matA)\n matC = [[0 for i in range(n)] for j in range(n)]\n\n for i in range(n):\n for j in range(n):\n for k in range(n):\n matC[i][j] += matA[i][k] * matB[k][j]\n\n return matC\n\n\ndef identity(n: int) -> list:\n \"\"\"\n Returns the Identity matrix of size n x n\n Time Complexity: O(n^2)\n \"\"\"\n I = [[0 for i in range(n)] for j in range(n)]\n\n for i in range(n):\n I[i][i] = 1\n\n return I\n\n\ndef matrix_exponentiation(mat: list, n: int) -> list:\n \"\"\"\n Calculates mat^n by repeated squaring\n Time Complexity: O(d^3 log(n))\n d: dimension of the square matrix mat\n n: power the matrix is raised to\n \"\"\"\n if n == 0:\n return identity(len(mat))\n elif n % 2 == 1:\n return multiply(matrix_exponentiation(mat, n - 1), mat)\n else:\n tmp = matrix_exponentiation(mat, n \/\/ 2)\n return multiply(tmp, tmp)\n"} +{"Prompt":"Inverts an invertible n x n matrix i.e., given an n x n matrix A, returns an n x n matrix B such that AB BA In, the n x n identity matrix. For a 2 x 2 matrix, inversion is simple using the cofactor equation. For larger matrices, this is a four step process: 1. calculate the matrix of minors: create an n x n matrix by considering each position in the original matrix in turn. Exclude the current row and column and calculate the determinant of the remaining matrix, then place that value in the current position's equivalent in the matrix of minors. 2. create the matrix of cofactors: take the matrix of minors and multiply alternate values by 1 in a checkerboard pattern. 3. adjugate: hold the top left to bottom right diagonal constant, but swap all other values over it. 4. multiply the adjugated matrix by 1 the determinant of the original matrix This code combines steps 1 and 2 into one method to reduce traversals of the matrix. Possible edge cases: will not work for 0x0 or 1x1 matrix, though these are trivial to calculate without use of this file. invert an n x n matrix Error conditions if not arrayismatrixm: printInvalid matrix: array is not a matrix return 1 elif lenm ! lenm0: printInvalid matrix: matrix is not square return 2 elif lenm 2: printInvalid matrix: matrix is too small return 3 elif getdeterminantm 0: printInvalid matrix: matrix is square, but singular determinant 0 return 4 Calculation elif lenm 2: simple case multiplier 1 getdeterminantm inverted multiplier lenm for n in rangelenm inverted01 inverted01 1 m01 inverted10 inverted10 1 m10 inverted00 multiplier m11 inverted11 multiplier m00 return inverted else: get matrix of minors w checkerboard signs calculate determinant we need to know 1det adjugate swap on diagonals and multiply by 1det recursively calculate the determinant of an n x n matrix, n 2 if lenm 2: trivial case return m00 m11 m01 m10 else: sign 1 det 0 for i in rangelenm: det sign m0i getdeterminantgetminorm, 0, i sign 1 return det def getmatrixofminorsm: get the minor of the matrix position mrowcol all values mrc where r ! row and c ! col swap values along diagonal, optionally adding multiplier for row in rangelenm: for col in rangerow 1: temp mrowcol multiplier mrowcol mcolrow multiplier mcolrow temp return m def arrayismatrixm: if lenm 0: return False firstcol lenm0 for row in m: if lenrow ! firstcol: return False return True","Completions":"import fractions\n\n\ndef invert_matrix(m):\n \"\"\"invert an n x n matrix\"\"\"\n # Error conditions\n if not array_is_matrix(m):\n print(\"Invalid matrix: array is not a matrix\")\n return [[-1]]\n elif len(m) != len(m[0]):\n print(\"Invalid matrix: matrix is not square\")\n return [[-2]]\n elif len(m) < 2:\n print(\"Invalid matrix: matrix is too small\")\n return [[-3]]\n elif get_determinant(m) == 0:\n print(\"Invalid matrix: matrix is square, but singular (determinant = 0)\")\n return [[-4]]\n\n # Calculation\n elif len(m) == 2:\n # simple case\n multiplier = 1 \/ get_determinant(m)\n inverted = [[multiplier] * len(m) for n in range(len(m))]\n inverted[0][1] = inverted[0][1] * -1 * m[0][1]\n inverted[1][0] = inverted[1][0] * -1 * m[1][0]\n inverted[0][0] = multiplier * m[1][1]\n inverted[1][1] = multiplier * m[0][0]\n return inverted\n else:\n \"\"\"some steps combined in helpers to reduce traversals\"\"\"\n # get matrix of minors w\/ \"checkerboard\" signs\n m_of_minors = get_matrix_of_minors(m)\n\n # calculate determinant (we need to know 1\/det)\n multiplier = fractions.Fraction(1, get_determinant(m))\n\n # adjugate (swap on diagonals) and multiply by 1\/det\n inverted = transpose_and_multiply(m_of_minors, multiplier)\n\n return inverted\n\n\ndef get_determinant(m):\n \"\"\"recursively calculate the determinant of an n x n matrix, n >= 2\"\"\"\n if len(m) == 2:\n # trivial case\n return (m[0][0] * m[1][1]) - (m[0][1] * m[1][0])\n else:\n sign = 1\n det = 0\n for i in range(len(m)):\n det += sign * m[0][i] * get_determinant(get_minor(m, 0, i))\n sign *= -1\n return det\n\n\ndef get_matrix_of_minors(m):\n \"\"\"get the matrix of minors and alternate signs\"\"\"\n matrix_of_minors = [[0 for i in range(len(m))] for j in range(len(m))]\n for row in range(len(m)):\n for col in range(len(m[0])):\n if (row + col) % 2 == 0:\n sign = 1\n else:\n sign = -1\n matrix_of_minors[row][col] = sign * get_determinant(get_minor(m, row, col))\n return matrix_of_minors\n\n\ndef get_minor(m, row, col):\n \"\"\"\n get the minor of the matrix position m[row][col]\n (all values m[r][c] where r != row and c != col)\n \"\"\"\n minors = []\n for i in range(len(m)):\n if i != row:\n new_row = m[i][:col]\n new_row.extend(m[i][col + 1:])\n minors.append(new_row)\n return minors\n\n\ndef transpose_and_multiply(m, multiplier=1):\n \"\"\"swap values along diagonal, optionally adding multiplier\"\"\"\n for row in range(len(m)):\n for col in range(row + 1):\n temp = m[row][col] * multiplier\n m[row][col] = m[col][row] * multiplier\n m[col][row] = temp\n return m\n\n\ndef array_is_matrix(m):\n if len(m) == 0:\n return False\n first_col = len(m[0])\n for row in m:\n if len(row) != first_col:\n return False\n return True\n"} +{"Prompt":"This algorithm takes two compatible two dimensional matrix and return their product Space complexity: On2 Possible edge case: the number of columns of multiplicand not consistent with the number of rows of multiplier, will raise exception :type A: ListListint :type B: ListListint :rtype: ListListint create a result matrix","Completions":"def multiply(multiplicand: list, multiplier: list) -> list:\n \"\"\"\n :type A: List[List[int]]\n :type B: List[List[int]]\n :rtype: List[List[int]]\n \"\"\"\n multiplicand_row, multiplicand_col = len(\n multiplicand), len(multiplicand[0])\n multiplier_row, multiplier_col = len(multiplier), len(multiplier[0])\n if(multiplicand_col != multiplier_row):\n raise Exception(\n \"Multiplicand matrix not compatible with Multiplier matrix.\")\n # create a result matrix\n result = [[0] * multiplier_col for i in range(multiplicand_row)]\n for i in range(multiplicand_row):\n for j in range(multiplier_col):\n for k in range(len(multiplier)):\n result[i][j] += multiplicand[i][k] * multiplier[k][j]\n return result\n"} +{"Prompt":"You are given an n x n 2D mat representing an image. Rotate the image by 90 degrees clockwise. Follow up: Could you do this inplace? clockwise rotate first reverse up to down, then swap the symmetry 1 2 3 7 8 9 7 4 1 4 5 6 4 5 6 8 5 2 7 8 9 1 2 3 9 6 3","Completions":"# clockwise rotate\n# first reverse up to down, then swap the symmetry\n# 1 2 3 7 8 9 7 4 1\n# 4 5 6 => 4 5 6 => 8 5 2\n# 7 8 9 1 2 3 9 6 3\n\ndef rotate(mat):\n if not mat:\n return mat\n mat.reverse()\n for i in range(len(mat)):\n for j in range(i):\n mat[i][j], mat[j][i] = mat[j][i], mat[i][j]\n return mat\n\n\nif __name__ == \"__main__\":\n mat = [[1, 2, 3],\n [4, 5, 6],\n [7, 8, 9]]\n print(mat)\n rotate(mat)\n print(mat)\n"} +{"Prompt":"Search a key in a row wise and column wise sorted nondecreasing matrix. m Number of rows in the matrix n Number of columns in the matrix Tn Omn","Completions":"#\n# Search a key in a row wise and column wise sorted (non-decreasing) matrix.\n# m- Number of rows in the matrix\n# n- Number of columns in the matrix\n# T(n)- O(m+n)\n#\n\n\ndef search_in_a_sorted_matrix(mat, m, n, key):\n i, j = m-1, 0\n while i >= 0 and j < n:\n if key == mat[i][j]:\n print('Key %s found at row- %s column- %s' % (key, i+1, j+1))\n return\n if key < mat[i][j]:\n i -= 1\n else:\n j += 1\n print('Key %s not found' % (key))\n\n\ndef main():\n mat = [\n [2, 5, 7],\n [4, 8, 13],\n [9, 11, 15],\n [12, 17, 20]\n ]\n key = 13\n print(mat)\n search_in_a_sorted_matrix(mat, len(mat), len(mat[0]), key)\n\n\nif __name__ == '__main__':\n main()\n"} +{"Prompt":"Given a m n matrix mat of integers, sort it diagonally in ascending order from the topleft to the bottomright then return the sorted array. mat 3,3,1,1, 2,2,1,2, 1,1,1,2 Should return: 1,1,1,1, 1,2,2,2, 1,2,3,3 If the input is a vector, return the vector Rows columns 1 The 1 helps you to not repeat a column Process the rows Initialize heap, set row and column Traverse diagonally, and add the values to the heap Sort the diagonal Process the columns Initialize heap, row and column Traverse Diagonally Sort the diagonal Return the updated matrix","Completions":"from heapq import heappush, heappop\nfrom typing import List\n\n\ndef sort_diagonally(mat: List[List[int]]) -> List[List[int]]:\n # If the input is a vector, return the vector\n if len(mat) == 1 or len(mat[0]) == 1:\n return mat\n\n # Rows + columns - 1\n # The -1 helps you to not repeat a column\n for i in range(len(mat)+len(mat[0])-1):\n # Process the rows\n if i+1 < len(mat):\n # Initialize heap, set row and column\n h = []\n row = len(mat)-(i+1)\n col = 0\n\n # Traverse diagonally, and add the values to the heap\n while row < len(mat):\n heappush(h, (mat[row][col]))\n row += 1\n col += 1\n\n # Sort the diagonal\n row = len(mat)-(i+1)\n col = 0\n while h:\n ele = heappop(h)\n mat[row][col] = ele\n row += 1\n col += 1\n else:\n # Process the columns\n # Initialize heap, row and column\n h = []\n row = 0\n col = i - (len(mat)-1)\n\n # Traverse Diagonally\n while col < len(mat[0]) and row < len(mat):\n heappush(h, (mat[row][col]))\n row += 1\n col += 1\n\n # Sort the diagonal\n row = 0\n col = i - (len(mat)-1)\n while h:\n ele = heappop(h)\n mat[row][col] = ele\n row += 1\n col += 1\n\n # Return the updated matrix\n return mat\n"} +{"Prompt":"! usrbinenv python3 Suppose we have very large sparse vectors, which contains a lot of zeros and double . find a data structure to store them get the dot product of them 10","Completions":"#! \/usr\/bin\/env python3\n\n\"\"\"\nSuppose we have very large sparse vectors, which contains a lot of\nzeros and double .\n\nfind a data structure to store them\nget the dot product of them\n\"\"\"\n\n\ndef vector_to_index_value_list(vector):\n return [(i, v) for i, v in enumerate(vector) if v != 0.0]\n\n\ndef dot_product(iv_list1, iv_list2):\n\n product = 0\n p1 = len(iv_list1) - 1\n p2 = len(iv_list2) - 1\n\n while p1 >= 0 and p2 >= 0:\n i1, v1 = iv_list1[p1]\n i2, v2 = iv_list2[p2]\n\n if i1 < i2:\n p1 -= 1\n elif i2 < i1:\n p2 -= 1\n else:\n product += v1 * v2\n p1 -= 1\n p2 -= 1\n\n return product\n\n\ndef __test_simple():\n print(dot_product(vector_to_index_value_list([1., 2., 3.]),\n vector_to_index_value_list([0., 2., 2.])))\n # 10\n\n\ndef __test_time():\n vector_length = 1024\n vector_count = 1024\n nozero_counut = 10\n\n def random_vector():\n import random\n vector = [0 for _ in range(vector_length)]\n for i in random.sample(range(vector_length), nozero_counut):\n vector[i] = random.random()\n return vector\n\n vectors = [random_vector() for _ in range(vector_count)]\n iv_lists = [vector_to_index_value_list(vector) for vector in vectors]\n\n import time\n\n time_start = time.time()\n for i in range(vector_count):\n for j in range(i):\n dot_product(iv_lists[i], iv_lists[j])\n time_end = time.time()\n\n print(time_end - time_start, 'seconds')\n\n\nif __name__ == '__main__':\n __test_simple()\n __test_time()\n"} +{"Prompt":"Given two sparse matrices A and B, return the result of AB. You may assume that A's column number is equal to B's row number. Example: A 1, 0, 0, 1, 0, 3 B 7, 0, 0 , 0, 0, 0 , 0, 0, 1 1 0 0 7 0 0 7 0 0 AB 1 0 3 x 0 0 0 7 0 3 0 0 1 Python solution without table 156ms: :type A: ListListint :type B: ListListint :rtype: ListListint Python solution with only one table for B 196ms: :type A: ListListint :type B: ListListint :rtype: ListListint Python solution with two tables 196ms: :type A: ListListint :type B: ListListint :rtype: ListListint","Completions":"# Python solution without table (~156ms):\ndef multiply(self, a, b):\n \"\"\"\n :type A: List[List[int]]\n :type B: List[List[int]]\n :rtype: List[List[int]]\n \"\"\"\n if a is None or b is None:\n return None\n m, n, l = len(a), len(b[0]), len(b[0])\n if len(b) != n:\n raise Exception(\"A's column number must be equal to B's row number.\")\n c = [[0 for _ in range(l)] for _ in range(m)]\n for i, row in enumerate(a):\n for k, eleA in enumerate(row):\n if eleA:\n for j, eleB in enumerate(b[k]):\n if eleB:\n c[i][j] += eleA * eleB\n return c\n\n\n# Python solution with only one table for B (~196ms):\ndef multiply(self, a, b):\n \"\"\"\n :type A: List[List[int]]\n :type B: List[List[int]]\n :rtype: List[List[int]]\n \"\"\"\n if a is None or b is None:\n return None\n m, n, l = len(a), len(a[0]), len(b[0])\n if len(b) != n:\n raise Exception(\"A's column number must be equal to B's row number.\")\n c = [[0 for _ in range(l)] for _ in range(m)]\n table_b = {}\n for k, row in enumerate(b):\n table_b[k] = {}\n for j, eleB in enumerate(row):\n if eleB:\n table_b[k][j] = eleB\n for i, row in enumerate(a):\n for k, eleA in enumerate(row):\n if eleA:\n for j, eleB in table_b[k].iteritems():\n c[i][j] += eleA * eleB\n return c\n\n\n# Python solution with two tables (~196ms):\ndef multiply(self, a, b):\n \"\"\"\n :type A: List[List[int]]\n :type B: List[List[int]]\n :rtype: List[List[int]]\n \"\"\"\n if a is None or b is None:\n return None\n m, n = len(a), len(b[0])\n if len(b) != n:\n raise Exception(\"A's column number must be equal to B's row number.\")\n l = len(b[0])\n table_a, table_b = {}, {}\n for i, row in enumerate(a):\n for j, ele in enumerate(row):\n if ele:\n if i not in table_a:\n table_a[i] = {}\n table_a[i][j] = ele\n for i, row in enumerate(b):\n for j, ele in enumerate(row):\n if ele:\n if i not in table_b:\n table_b[i] = {}\n table_b[i][j] = ele\n c = [[0 for j in range(l)] for i in range(m)]\n for i in table_a:\n for k in table_a[i]:\n if k not in table_b:\n continue\n for j in table_b[k]:\n c[i][j] += table_a[i][k] * table_b[k][j]\n return c\n"} +{"Prompt":"Given a matrix of m x n elements m rows, n columns, return all elements of the matrix in spiral order. For example, Given the following matrix: 1, 2, 3 , 4, 5, 6 , 7, 8, 9 You should return 1,2,3,6,9,8,7,4,5.","Completions":"def spiral_traversal(matrix):\n res = []\n if len(matrix) == 0:\n return res\n row_begin = 0\n row_end = len(matrix) - 1\n col_begin = 0\n col_end = len(matrix[0]) - 1\n\n while row_begin <= row_end and col_begin <= col_end:\n for i in range(col_begin, col_end+1):\n res.append(matrix[row_begin][i])\n row_begin += 1\n\n for i in range(row_begin, row_end+1):\n res.append(matrix[i][col_end])\n col_end -= 1\n\n if row_begin <= row_end:\n for i in range(col_end, col_begin-1, -1):\n res.append(matrix[row_end][i])\n row_end -= 1\n\n if col_begin <= col_end:\n for i in range(row_end, row_begin-1, -1):\n res.append(matrix[i][col_begin])\n col_begin += 1\n\n return res\n\n\nif __name__ == \"__main__\":\n mat = [[1, 2, 3],\n [4, 5, 6],\n [7, 8, 9]]\n print(spiral_traversal(mat))\n"} +{"Prompt":"Write a function validSolutionValidateSolutionvalidsolution that accepts a 2D array representing a Sudoku board, and returns true if it is a valid solution, or false otherwise. The cells of the sudoku board may also contain 0's, which will represent empty cells. Boards containing one or more zeroes are considered to be invalid solutions. The board is always 9 cells by 9 cells, and every cell only contains integers from 0 to 9. More info at: http:en.wikipedia.orgwikiSudoku Using dicthashtable Without hashtabledict check rows check columns check regions if everything correct Using set","Completions":"# Using dict\/hash-table\nfrom collections import defaultdict\n\n\ndef valid_solution_hashtable(board):\n for i in range(len(board)):\n dict_row = defaultdict(int)\n dict_col = defaultdict(int)\n for j in range(len(board[0])):\n value_row = board[i][j]\n value_col = board[j][i]\n if not value_row or value_col == 0:\n return False\n if value_row in dict_row:\n return False\n else:\n dict_row[value_row] += 1\n\n if value_col in dict_col:\n return False\n else:\n dict_col[value_col] += 1\n\n for i in range(3):\n for j in range(3):\n grid_add = 0\n for k in range(3):\n for l in range(3):\n grid_add += board[i * 3 + k][j * 3 + l]\n if grid_add != 45:\n return False\n return True\n\n\n# Without hash-table\/dict\ndef valid_solution(board):\n correct = [1, 2, 3, 4, 5, 6, 7, 8, 9]\n # check rows\n for row in board:\n if sorted(row) != correct:\n return False\n\n # check columns\n for column in zip(*board):\n if sorted(column) != correct:\n return False\n\n # check regions\n for i in range(3):\n for j in range(3):\n region = []\n for line in board[i*3:(i+1)*3]:\n region += line[j*3:(j+1)*3]\n\n if sorted(region) != correct:\n return False\n\n # if everything correct\n return True\n\n\n# Using set\ndef valid_solution_set(board):\n valid = set(range(1, 10))\n\n for row in board:\n if set(row) != valid:\n return False\n\n for col in [[row[i] for row in board] for i in range(9)]:\n if set(col) != valid:\n return False\n\n for x in range(3):\n for y in range(3):\n if set(sum([row[x*3:(x+1)*3] for row in board[y*3:(y+1)*3]], [])) != valid:\n return False\n\n return True\n"} +{"Prompt":"Function to find sum of all subsquares of size k x k in a given square matrix of size n x n Calculate and print sum of current subsquare","Completions":"# Function to find sum of all\n# sub-squares of size k x k in a given\n# square matrix of size n x n\ndef sum_sub_squares(matrix, k):\n n = len(matrix)\n result = [[0 for i in range(k)] for j in range(k)]\n\n if k > n:\n return\n for i in range(n - k + 1):\n l = 0\n for j in range(n - k + 1):\n sum = 0\n\n # Calculate and print sum of current sub-square\n for p in range(i, k + i):\n for q in range(j, k + j):\n sum += matrix[p][q]\n\n result[i][l] = sum\n l += 1\n\n return result\n"} +{"Prompt":"summary HELPERFUNCTION calculates the eulidean distance between vector x and y. Arguments: x tuple vector y tuple vector summary Implements the nearest neighbor algorithm Arguments: x tupel vector tSet dict training set Returns: type result of the ANDfunction","Completions":"import math\n\ndef distance(x,y):\n \"\"\"[summary]\n HELPER-FUNCTION\n calculates the (eulidean) distance between vector x and y.\n\n Arguments:\n x {[tuple]} -- [vector]\n y {[tuple]} -- [vector]\n \"\"\"\n assert len(x) == len(y), \"The vector must have same length\"\n result = ()\n sum = 0\n for i in range(len(x)):\n result += (x[i] -y[i],)\n for component in result:\n sum += component**2\n return math.sqrt(sum)\n\n\ndef nearest_neighbor(x, tSet):\n \"\"\"[summary]\n Implements the nearest neighbor algorithm\n\n Arguments:\n x {[tupel]} -- [vector]\n tSet {[dict]} -- [training set]\n\n Returns:\n [type] -- [result of the AND-function]\n \"\"\"\n assert isinstance(x, tuple) and isinstance(tSet, dict)\n current_key = ()\n min_d = float('inf')\n for key in tSet:\n d = distance(x, key)\n if d < min_d:\n min_d = d\n current_key = key\n return tSet[current_key]\n"} +{"Prompt":"Given an array and a number k Find the max elements of each of its subarrays of length k. Keep indexes of good candidates in deque d. The indexes in d are from the current window, they're increasing, and their corresponding nums are decreasing. Then the first deque element is the index of the largest window value. For each index i: 1. Pop from the end indexes of smaller elements they'll be useless. 2. Append the current index. 3. Pop from the front the index i k, if it's still in the deque it falls out of the window. 4. If our window has reached size k, append the current window maximum to the output.","Completions":"import collections\n\n\ndef max_sliding_window(arr, k):\n qi = collections.deque() # queue storing indexes of elements\n result = []\n for i, n in enumerate(arr):\n while qi and arr[qi[-1]] < n:\n qi.pop()\n qi.append(i)\n if qi[0] == i - k:\n qi.popleft()\n if i >= k - 1:\n result.append(arr[qi[0]])\n return result\n"} +{"Prompt":"Initialize your data structure here. :type size: int :type val: int :rtype: float Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window.","Completions":"from __future__ import division\nfrom collections import deque\n\n\nclass MovingAverage(object):\n def __init__(self, size):\n \"\"\"\n Initialize your data structure here.\n :type size: int\n \"\"\"\n self.queue = deque(maxlen=size)\n\n def next(self, val):\n \"\"\"\n :type val: int\n :rtype: float\n \"\"\"\n self.queue.append(val)\n return sum(self.queue) \/ len(self.queue)\n\n\n# Given a stream of integers and a window size,\n# calculate the moving average of all integers in the sliding window.\nif __name__ == '__main__':\n m = MovingAverage(3)\n assert m.next(1) == 1\n assert m.next(10) == (1 + 10) \/ 2\n assert m.next(3) == (1 + 10 + 3) \/ 3\n assert m.next(5) == (10 + 3 + 5) \/ 3\n"} +{"Prompt":"Implementation of priority queue using linear array. Insertion On Extract minmax Node O1 Create a priority queue with items list or iterable. If items is not passed, create empty priority queue. self.priorityqueuelist if items is None: return if priorities is None: priorities itertools.repeatNone for item, priority in zipitems, priorities: self.pushitem, prioritypriority def reprself: return PriorityQueue!r.formatself.priorityqueuelist def sizeself: return lenself.priorityqueuelist def pushself, item, priorityNone: priority item if priority is None else priority node PriorityQueueNodeitem, priority for index, current in enumerateself.priorityqueuelist: if current.priority node.priority: self.priorityqueuelist.insertindex, node return when traversed complete queue self.priorityqueuelist.appendnode def popself: remove and return the first node from the queue return self.priorityqueuelist.pop.data","Completions":"import itertools\n\n\nclass PriorityQueueNode:\n def __init__(self, data, priority):\n self.data = data\n self.priority = priority\n\n def __repr__(self):\n return \"{}: {}\".format(self.data, self.priority)\n\n\nclass PriorityQueue:\n def __init__(self, items=None, priorities=None):\n \"\"\"Create a priority queue with items (list or iterable).\n If items is not passed, create empty priority queue.\"\"\"\n self.priority_queue_list = []\n if items is None:\n return\n if priorities is None:\n priorities = itertools.repeat(None)\n for item, priority in zip(items, priorities):\n self.push(item, priority=priority)\n\n def __repr__(self):\n return \"PriorityQueue({!r})\".format(self.priority_queue_list)\n\n def size(self):\n \"\"\"Return size of the priority queue.\n \"\"\"\n return len(self.priority_queue_list)\n\n def push(self, item, priority=None):\n \"\"\"Push the item in the priority queue.\n if priority is not given, priority is set to the value of item.\n \"\"\"\n priority = item if priority is None else priority\n node = PriorityQueueNode(item, priority)\n for index, current in enumerate(self.priority_queue_list):\n if current.priority < node.priority:\n self.priority_queue_list.insert(index, node)\n return\n # when traversed complete queue\n self.priority_queue_list.append(node)\n\n def pop(self):\n \"\"\"Remove and return the item with the lowest priority.\n \"\"\"\n # remove and return the first node from the queue\n return self.priority_queue_list.pop().data\n"} +{"Prompt":"Queue Abstract Data Type ADT Queue creates a new queue that is empty. It needs no parameters and returns an empty queue. enqueueitem adds a new item to the rear of the queue. It needs the item and returns nothing. dequeue removes the front item from the queue. It needs no parameters and returns the item. The queue is modified. isEmpty tests to see whether the queue is empty. It needs no parameters and returns a boolean value. size returns the number of items in the queue. It needs no parameters and returns an integer. peek returns the front element of the queue. Initialize python List with capacity of 10 or user given input. Python List type is a dynamic array, so we have to restrict its dynamic nature to make it work like a static array. returns the front element of queue. if self.isempty: raise IndexErrorQueue is empty return self.arrayself.front def expandself: self.array None lenself.array class QueueNode: def initself, value: self.value value self.next None class LinkedListQueueAbstractQueue: def initself: super.init self.front None self.rear None def iterself: probe self.front while True: if probe is None: return yield probe.value probe probe.next def enqueueself, value: node QueueNodevalue if self.front is None: self.front node self.rear node else: self.rear.next node self.rear node self.size 1 def dequeueself: if self.isempty: raise IndexErrorQueue is empty value self.front.value if self.front is self.rear: self.front None self.rear None else: self.front self.front.next self.size 1 return value def peekself:","Completions":"from abc import ABCMeta, abstractmethod\n\n\nclass AbstractQueue(metaclass=ABCMeta):\n\n def __init__(self):\n self._size = 0\n\n def __len__(self):\n return self._size\n\n def is_empty(self):\n return self._size == 0\n\n @abstractmethod\n def enqueue(self, value):\n pass\n\n @abstractmethod\n def dequeue(self):\n pass\n\n @abstractmethod\n def peek(self):\n pass\n\n @abstractmethod\n def __iter__(self):\n pass\n\n\nclass ArrayQueue(AbstractQueue):\n\n def __init__(self, capacity=10):\n \"\"\"\n Initialize python List with capacity of 10 or user given input.\n Python List type is a dynamic array, so we have to restrict its\n dynamic nature to make it work like a static array.\n \"\"\"\n super().__init__()\n self._array = [None] * capacity\n self._front = 0\n self._rear = 0\n\n def __iter__(self):\n probe = self._front\n while True:\n if probe == self._rear:\n return\n yield self._array[probe]\n probe += 1\n\n def enqueue(self, value):\n if self._rear == len(self._array):\n self._expand()\n self._array[self._rear] = value\n self._rear += 1\n self._size += 1\n\n def dequeue(self):\n if self.is_empty():\n raise IndexError(\"Queue is empty\")\n value = self._array[self._front]\n self._array[self._front] = None\n self._front += 1\n self._size -= 1\n return value\n\n def peek(self):\n \"\"\"returns the front element of queue.\"\"\"\n if self.is_empty():\n raise IndexError(\"Queue is empty\")\n return self._array[self._front]\n\n def _expand(self):\n \"\"\"expands size of the array.\n Time Complexity: O(n)\n \"\"\"\n self._array += [None] * len(self._array)\n\n\nclass QueueNode:\n def __init__(self, value):\n self.value = value\n self.next = None\n\n\nclass LinkedListQueue(AbstractQueue):\n\n def __init__(self):\n super().__init__()\n self._front = None\n self._rear = None\n\n def __iter__(self):\n probe = self._front\n while True:\n if probe is None:\n return\n yield probe.value\n probe = probe.next\n\n def enqueue(self, value):\n node = QueueNode(value)\n if self._front is None:\n self._front = node\n self._rear = node\n else:\n self._rear.next = node\n self._rear = node\n self._size += 1\n\n def dequeue(self):\n if self.is_empty():\n raise IndexError(\"Queue is empty\")\n value = self._front.value\n if self._front is self._rear:\n self._front = None\n self._rear = None\n else:\n self._front = self._front.next\n self._size -= 1\n return value\n\n def peek(self):\n \"\"\"returns the front element of queue.\"\"\"\n if self.is_empty():\n raise IndexError(\"Queue is empty\")\n return self._front.value\n"} +{"Prompt":"Suppose 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. Note: The number of people is less than 1,100. Example Input: 7,0, 4,4, 7,1, 5,0, 6,1, 5,2 Output: 5,0, 7,0, 5,2, 6,1, 4,4, 7,1 :type people: ListListint :rtype: ListListint","Completions":"# Suppose you have a random list of people standing in a queue.\n# Each person is described by a pair of integers (h, k),\n# where h is the height of the person and k is the number of people\n# in front of this person who have a height greater than or equal to h.\n# Write an algorithm to reconstruct the queue.\n\n# Note:\n# The number of people is less than 1,100.\n\n# Example\n\n# Input:\n# [[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]]\n\n# Output:\n# [[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]]\n\ndef reconstruct_queue(people):\n \"\"\"\n :type people: List[List[int]]\n :rtype: List[List[int]]\n \"\"\"\n queue = []\n people.sort(key=lambda x: (-x[0], x[1]))\n for h, k in people:\n queue.insert(k, [h, k])\n return queue\n"} +{"Prompt":"Initialize your data structure here. :type v1: Listint :type v2: Listint :rtype: int :rtype: bool","Completions":"class ZigZagIterator:\n def __init__(self, v1, v2):\n \"\"\"\n Initialize your data structure here.\n :type v1: List[int]\n :type v2: List[int]\n \"\"\"\n self.queue = [_ for _ in (v1, v2) if _]\n print(self.queue)\n\n def next(self):\n \"\"\"\n :rtype: int\n \"\"\"\n v = self.queue.pop(0)\n ret = v.pop(0)\n if v:\n self.queue.append(v)\n return ret\n\n def has_next(self):\n \"\"\"\n :rtype: bool\n \"\"\"\n if self.queue:\n return True\n return False\n\n\nl1 = [1, 2]\nl2 = [3, 4, 5, 6]\nit = ZigZagIterator(l1, l2)\nwhile it.has_next():\n print(it.next())\n"} +{"Prompt":"Collection of search algorithms: finding the needle in a haystack.","Completions":"from .binary_search import *\nfrom .ternary_search import *\nfrom .first_occurrence import *\nfrom .last_occurrence import *\nfrom .linear_search import *\nfrom .search_insert import *\nfrom .two_sum import *\nfrom .search_range import *\nfrom .find_min_rotate import *\nfrom .search_rotate import *\nfrom .jump_search import *\nfrom .next_greatest_letter import *\nfrom .interpolation_search import *\n"} +{"Prompt":"Binary Search Find an element in a sorted array in ascending order. For Binary Search, TN TN2 O1 the recurrence relation Apply Masters Theorem for computing Run time complexity of recurrence relations: TN aTNb fN Here, a 1, b 2 log a base b 1 also, here fN nc logkn k 0 c log a base b So, TN ONc logk1N OlogN Worstcase Complexity: Ologn reference: https:en.wikipedia.orgwikiBinarysearchalgorithm In this below function we are passing array, it's first index , last index and value to be searched Worstcase Complexity: Ologn reference: https:en.wikipedia.orgwikiBinarysearchalgorithm Here in Logic section first we are checking if low is greater than high which means its an error condition because low index should not move ahead of high index","Completions":"# For Binary Search, T(N) = T(N\/2) + O(1) \/\/ the recurrence relation\n# Apply Masters Theorem for computing Run time complexity of recurrence relations:\n# T(N) = aT(N\/b) + f(N)\n# Here,\n# a = 1, b = 2 => log (a base b) = 1\n# also, here\n# f(N) = n^c log^k(n) \/\/ k = 0 & c = log (a base b)\n# So,\n# T(N) = O(N^c log^(k+1)N) = O(log(N))\n\ndef binary_search(array, query):\n \"\"\"\n Worst-case Complexity: O(log(n))\n\n reference: https:\/\/en.wikipedia.org\/wiki\/Binary_search_algorithm\n \"\"\"\n\n low, high = 0, len(array) - 1\n while low <= high:\n mid = (high + low) \/\/ 2\n val = array[mid]\n if val == query:\n return mid\n\n if val < query:\n low = mid + 1\n else:\n high = mid - 1\n return None\n\n#In this below function we are passing array, it's first index , last index and value to be searched\ndef binary_search_recur(array, low, high, val):\n \"\"\"\n Worst-case Complexity: O(log(n))\n\n reference: https:\/\/en.wikipedia.org\/wiki\/Binary_search_algorithm\n \"\"\"\n#Here in Logic section first we are checking if low is greater than high which means its an error condition because low index should not move ahead of high index\n if low > high: \n return -1\n mid = low + (high-low)\/\/2 #This mid will not break integer range\n if val < array[mid]: \n return binary_search_recur(array, low, mid - 1, val) #Go search in the left subarray\n if val > array[mid]:\n return binary_search_recur(array, mid + 1, high, val) #Go search in the right subarray\n return mid\n"} +{"Prompt":"Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2. Find the minimum element. The complexity must be OlogN You may assume no duplicate exists in the array. Finds the minimum element in a sorted array that has been rotated. Finds the minimum element in a sorted array that has been rotated.","Completions":"def find_min_rotate(array):\n \"\"\"\n Finds the minimum element in a sorted array that has been rotated.\n \"\"\"\n low = 0\n high = len(array) - 1\n while low < high:\n mid = (low + high) \/\/ 2\n if array[mid] > array[high]:\n low = mid + 1\n else:\n high = mid\n\n return array[low]\n\ndef find_min_rotate_recur(array, low, high):\n \"\"\"\n Finds the minimum element in a sorted array that has been rotated.\n \"\"\"\n mid = (low + high) \/\/ 2\n if mid == low:\n return array[low]\n if array[mid] > array[high]:\n return find_min_rotate_recur(array, mid + 1, high)\n return find_min_rotate_recur(array, low, mid)\n"} +{"Prompt":"Find first occurance of a number in a sorted array increasing order Approach Binary Search Tn Olog n Returns the index of the first occurance of the given element in an array. The array has to be sorted in increasing order. printlo: , lo, hi: , hi, mid: , mid","Completions":"def first_occurrence(array, query):\n \"\"\"\n Returns the index of the first occurance of the given element in an array.\n The array has to be sorted in increasing order.\n \"\"\"\n\n low, high = 0, len(array) - 1\n while low <= high:\n mid = low + (high-low)\/\/2 #Now mid will be ininteger range\n #print(\"lo: \", lo, \" hi: \", hi, \" mid: \", mid)\n if low == high:\n break\n if array[mid] < query:\n low = mid + 1\n else:\n high = mid\n if array[low] == query:\n return low\n"} +{"Prompt":"Python implementation of the Interpolation Search algorithm. Given a sorted array in increasing order, interpolation search calculates the starting point of its search according to the search key. FORMULA: startpos low x arrlowhigh low arrhigh arrlow Doc: https:en.wikipedia.orgwikiInterpolationsearch Time Complexity: Olog2log2 n for average cases, On for the worst case. The algorithm performs best with uniformly distributed arrays. :param array: The array to be searched. :param searchkey: The key to be searched in the array. :returns: Index of searchkey in array if found, else 1. Examples: interpolationsearch25, 12, 1, 10, 12, 15, 20, 41, 55, 1 2 interpolationsearch5, 10, 12, 14, 17, 20, 21, 55 1 interpolationsearch5, 10, 12, 14, 17, 20, 21, 5 1 highest and lowest index in array calculate the search position searchkey is found if searchkey is larger, searchkey is in upper part if searchkey is smaller, searchkey is in lower part","Completions":"from typing import List\n\n\ndef interpolation_search(array: List[int], search_key: int) -> int:\n \"\"\"\n :param array: The array to be searched.\n :param search_key: The key to be searched in the array.\n\n :returns: Index of search_key in array if found, else -1.\n\n Examples:\n\n >>> interpolation_search([-25, -12, -1, 10, 12, 15, 20, 41, 55], -1)\n 2\n >>> interpolation_search([5, 10, 12, 14, 17, 20, 21], 55)\n -1\n >>> interpolation_search([5, 10, 12, 14, 17, 20, 21], -5)\n -1\n\n \"\"\"\n\n # highest and lowest index in array\n high = len(array) - 1\n low = 0\n\n while (low <= high) and (array[low] <= search_key <= array[high]):\n # calculate the search position\n pos = low + int(((search_key - array[low]) *\n (high - low) \/ (array[high] - array[low])))\n\n # search_key is found\n if array[pos] == search_key:\n return pos\n\n # if search_key is larger, search_key is in upper part\n if array[pos] < search_key:\n low = pos + 1\n\n # if search_key is smaller, search_key is in lower part\n else:\n high = pos - 1\n\n return -1\n\n\nif __name__ == \"__main__\":\n import doctest\n doctest.testmod()\n"} +{"Prompt":"Jump Search Find an element in a sorted array. Worstcase Complexity: On rootn All items in list must be sorted like binary search Find block that contains target value and search it linearly in that block It returns a first target value in array reference: https:en.wikipedia.orgwikiJumpsearch return 1 means that array doesn't contain target value find block that contains target value find target value in block if there is target value in array, return it","Completions":"import math\n\ndef jump_search(arr,target):\n \"\"\"\n Worst-case Complexity: O(\u221an) (root(n))\n All items in list must be sorted like binary search\n\n Find block that contains target value and search it linearly in that block\n It returns a first target value in array\n\n reference: https:\/\/en.wikipedia.org\/wiki\/Jump_search\n \"\"\"\n\n length = len(arr)\n block_size = int(math.sqrt(length))\n block_prev = 0\n block= block_size\n\n # return -1 means that array doesn't contain target value\n # find block that contains target value\n\n if arr[length - 1] < target:\n return -1\n while block <= length and arr[block - 1] < target:\n block_prev = block\n block += block_size\n\n # find target value in block\n\n while arr[block_prev] < target :\n block_prev += 1\n if block_prev == min(block, length) :\n return -1\n\n # if there is target value in array, return it\n\n if arr[block_prev] == target :\n return block_prev\n return -1\n"} +{"Prompt":"Find last occurance of a number in a sorted array increasing order Approach Binary Search Tn Olog n Returns the index of the last occurance of the given element in an array. The array has to be sorted in increasing order.","Completions":"def last_occurrence(array, query):\n \"\"\"\n Returns the index of the last occurance of the given element in an array.\n The array has to be sorted in increasing order.\n \"\"\"\n low, high = 0, len(array) - 1\n while low <= high:\n mid = (high + low) \/\/ 2\n if (array[mid] == query and mid == len(array)-1) or \\\n (array[mid] == query and array[mid+1] > query):\n return mid\n if array[mid] <= query:\n low = mid + 1\n else:\n high = mid - 1\n"} +{"Prompt":"Linear search works in any array. Tn: On Find the index of the given element in the array. There are no restrictions on the order of the elements in the array. If the element couldn't be found, returns 1.","Completions":"def linear_search(array, query):\n \"\"\"\n Find the index of the given element in the array.\n There are no restrictions on the order of the elements in the array.\n If the element couldn't be found, returns -1.\n \"\"\"\n for i, value in enumerate(array):\n if value == query:\n return i\n return -1\n"} +{"Prompt":"Given a list of sorted characters letters containing only lowercase letters, and given a target letter target, find the smallest element in the list that is larger than the given target. Letters also wrap around. For example, if the target is target 'z' and letters 'a', 'b', the answer is 'a'. Input: letters c, f, j target a Output: c Input: letters c, f, j target c Output: f Input: letters c, f, j target d Output: f Reference: https:leetcode.comproblemsfindsmallestlettergreaterthantargetdescription Using bisect libarary Using binary search: complexity OlogN Brute force: complexity ON","Completions":"import bisect\n\ndef next_greatest_letter(letters, target):\n \"\"\"\n Using bisect libarary\n \"\"\"\n index = bisect.bisect(letters, target)\n return letters[index % len(letters)]\n\ndef next_greatest_letter_v1(letters, target):\n \"\"\"\n Using binary search: complexity O(logN)\n \"\"\"\n if letters[0] > target:\n return letters[0]\n if letters[len(letters) - 1] <= target:\n return letters[0]\n left, right = 0, len(letters) - 1\n while left <= right:\n mid = left + (right - left) \/\/ 2\n if letters[mid] > target:\n right = mid - 1\n else:\n left = mid + 1\n return letters[left]\n\ndef next_greatest_letter_v2(letters, target):\n \"\"\"\n Brute force: complexity O(N)\n \"\"\"\n for index in letters:\n if index > target:\n return index\n return letters[0]\n"} +{"Prompt":"Helper methods for implementing insertion sort. Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. For example: 1,3,5,6, 5 2 1,3,5,6, 2 1 1,3,5,6, 7 4 1,3,5,6, 0 0","Completions":"def search_insert(array, val):\n \"\"\"\n Given a sorted array and a target value, return the index if the target is\n found. If not, return the index where it would be if it were inserted in order.\n\n For example:\n [1,3,5,6], 5 -> 2\n [1,3,5,6], 2 -> 1\n [1,3,5,6], 7 -> 4\n [1,3,5,6], 0 -> 0\n \"\"\"\n low = 0\n high = len(array) - 1\n while low <= high:\n mid = low + (high - low) \/\/ 2\n if val > array[mid]:\n low = mid + 1\n else:\n high = mid - 1\n return low\n"} +{"Prompt":"Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value. If the target is not found in the array, return 1, 1. For example: Input: nums 5,7,7,8,8,8,10, target 8 Output: 3,5 Input: nums 5,7,7,8,8,8,10, target 11 Output: 1,1 :type nums: Listint :type target: int :rtype: Listint breaks at low high both pointing to first occurence of target","Completions":"def search_range(nums, target):\n \"\"\"\n :type nums: List[int]\n :type target: int\n :rtype: List[int]\n \"\"\"\n low = 0\n high = len(nums) - 1\n # breaks at low == high\n # both pointing to first occurence of target\n while low < high:\n mid = low + (high - low) \/\/ 2\n if target <= nums[mid]:\n high = mid\n else:\n low = mid + 1\n\n for j in range(len(nums) - 1, -1, -1):\n if nums[j] == target:\n return [low, j]\n\n return [-1, -1]\n"} +{"Prompt":"Search in Rotated Sorted Array Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. i.e., 0,1,2,4,5,6,7 might become 4,5,6,7,0,1,2. You are given a target value to search. If found in the array return its index, otherwise return 1. Your algorithm's runtime complexity must be in the order of Olog n. Explanation algorithm: In classic binary search, we compare val with the midpoint to figure out if val belongs on the low or the high side. The complication here is that the array is rotated and may have an inflection point. Consider, for example: Array1: 10, 15, 20, 0, 5 Array2: 50, 5, 20, 30, 40 Note that both arrays have a midpoint of 20, but 5 appears on the left side of one and on the right side of the other. Therefore, comparing val with the midpoint is insufficient. However, if we look a bit deeper, we can see that one half of the array must be ordered normallyincreasing order. We can therefore look at the normally ordered half to determine whether we should search the low or hight side. For example, if we are searching for 5 in Array1, we can look at the left element 10 and middle element 20. Since 10 20, the left half must be ordered normally. And, since 5 is not between those, we know that we must search the right half In array2, we can see that since 50 20, the right half must be ordered normally. We turn to the middle 20, and right 40 element to check if 5 would fall between them. The value 5 would not Therefore, we search the left half. There are 2 possible solution: iterative and recursion. Recursion helps you understand better the above algorithm explanation Finds the index of the given value in an array that has been sorted in ascending order and then rotated at some unknown pivot. Recursion technique Finds the index of the given value in an array that has been sorted in ascending order and then rotated at some unknown pivot.","Completions":"def search_rotate(array, val):\n \"\"\"\n Finds the index of the given value in an array that has been sorted in\n ascending order and then rotated at some unknown pivot.\n \"\"\"\n low, high = 0, len(array) - 1\n while low <= high:\n mid = (low + high) \/\/ 2\n if val == array[mid]:\n return mid\n\n if array[low] <= array[mid]:\n if array[low] <= val <= array[mid]:\n high = mid - 1\n else:\n low = mid + 1\n else:\n if array[mid] <= val <= array[high]:\n low = mid + 1\n else:\n high = mid - 1\n\n return -1\n\n# Recursion technique\ndef search_rotate_recur(array, low, high, val):\n \"\"\"\n Finds the index of the given value in an array that has been sorted in\n ascending order and then rotated at some unknown pivot.\n \"\"\"\n if low >= high:\n return -1\n mid = (low + high) \/\/ 2\n if val == array[mid]: # found element\n return mid\n if array[low] <= array[mid]:\n if array[low] <= val <= array[mid]:\n return search_rotate_recur(array, low, mid - 1, val) # Search left\n return search_rotate_recur(array, mid + 1, high, val) # Search right\n if array[mid] <= val <= array[high]:\n return search_rotate_recur(array, mid + 1, high, val) # Search right\n return search_rotate_recur(array, low, mid - 1, val) # Search left\n"} +{"Prompt":"Ternary search is a divide and conquer algorithm that can be used to find an element in an array. It is similar to binary search where we divide the array into two parts but in this algorithm, we divide the given array into three parts and determine which has the key searched element. We can divide the array into three parts by taking mid1 and mid2. Initially, l and r will be equal to 0 and n1 respectively, where n is the length of the array. mid1 l rl3 mid2 r rl3 Note: Array needs to be sorted to perform ternary search on it. TN Olog3N log3 log base 3 Find the given value key in an array sorted in ascending order. Returns the index of the value if found, and 1 otherwise. If the index is not in the range left..right ie. left index right returns 1. key lies between l and mid1 key lies between mid2 and r key lies between mid1 and mid2 key not found","Completions":"def ternary_search(left, right, key, arr):\n \"\"\"\n Find the given value (key) in an array sorted in ascending order.\n Returns the index of the value if found, and -1 otherwise.\n If the index is not in the range left..right (ie. left <= index < right) returns -1.\n \"\"\"\n\n while right >= left:\n mid1 = left + (right-left) \/\/ 3\n mid2 = right - (right-left) \/\/ 3\n\n if key == arr[mid1]:\n return mid1\n if key == mid2:\n return mid2\n\n if key < arr[mid1]:\n # key lies between l and mid1\n right = mid1 - 1\n elif key > arr[mid2]:\n # key lies between mid2 and r\n left = mid2 + 1\n else:\n # key lies between mid1 and mid2\n left = mid1 + 1\n right = mid2 - 1\n\n # key not found\n return -1\n"} +{"Prompt":"Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number. The function twosum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers both index1 and index2 are not zerobased. You may assume that each input would have exactly one solution and you may not use the same element twice. Input: numbers 2, 7, 11, 15, target9 Output: index1 1, index2 2 Solution: twosum: using binary search twosum1: using dictionary as a hash table twosum2: using two pointers Given a list of numbers sorted in ascending order, find the indices of two numbers such that their sum is the given target. Using binary search. Given a list of numbers, find the indices of two numbers such that their sum is the given target. Using a hash table. Given a list of numbers sorted in ascending order, find the indices of two numbers such that their sum is the given target. Using a bidirectional linear search.","Completions":"def two_sum(numbers, target):\n \"\"\"\n Given a list of numbers sorted in ascending order, find the indices of two\n numbers such that their sum is the given target.\n\n Using binary search.\n \"\"\"\n for i, number in enumerate(numbers):\n second_val = target - number\n low, high = i+1, len(numbers)-1\n while low <= high:\n mid = low + (high - low) \/\/ 2\n if second_val == numbers[mid]:\n return [i + 1, mid + 1]\n\n if second_val > numbers[mid]:\n low = mid + 1\n else:\n high = mid - 1\n return None\n\ndef two_sum1(numbers, target):\n \"\"\"\n Given a list of numbers, find the indices of two numbers such that their\n sum is the given target.\n\n Using a hash table.\n \"\"\"\n dic = {}\n for i, num in enumerate(numbers):\n if target - num in dic:\n return [dic[target - num] + 1, i + 1]\n dic[num] = i\n return None\n\ndef two_sum2(numbers, target):\n \"\"\"\n Given a list of numbers sorted in ascending order, find the indices of two\n numbers such that their sum is the given target.\n\n Using a bidirectional linear search.\n \"\"\"\n left = 0 # pointer 1 holds from left of array numbers\n right = len(numbers) - 1 # pointer 2 holds from right of array numbers\n while left < right:\n current_sum = numbers[left] + numbers[right]\n if current_sum == target:\n return [left + 1, right + 1]\n\n if current_sum > target:\n right = right - 1\n else:\n left = left + 1\n"} +{"Prompt":"Given a List of words, return the words that can be typed using letters of alphabet on only one row's of American keyboard. For example: Input: Hello, Alaska, Dad, Peace Output: Alaska, Dad Reference: https:leetcode.comproblemskeyboardrowdescription :type words: Liststr :rtype: Liststr","Completions":"def find_keyboard_row(words):\n \"\"\"\n :type words: List[str]\n :rtype: List[str]\n \"\"\"\n keyboard = [\n set('qwertyuiop'),\n set('asdfghjkl'),\n set('zxcvbnm'),\n ]\n result = []\n for word in words:\n for key in keyboard:\n if set(word.lower()).issubset(key):\n result.append(word)\n return result\n"} +{"Prompt":"! usrbinenv python3 Design a data structure that supports all following operations in average O1 time. insertval: Inserts an item val to the set if not already present. removeval: Removes an item val from the set if present. randomelement: Returns a random element from current set of elements. Each element must have the same probability of being returned. idea: shoot Remove a half","Completions":"#! \/usr\/bin\/env python3\n\n\"\"\"\nDesign a data structure that supports all following operations\nin average O(1) time.\n\ninsert(val): Inserts an item val to the set if not already present.\nremove(val): Removes an item val from the set if present.\nrandom_element: Returns a random element from current set of elements.\n Each element must have the same probability of being returned.\n\"\"\"\n\nimport random\n\n\nclass RandomizedSet():\n \"\"\"\n idea: shoot\n \"\"\"\n\n def __init__(self):\n self.elements = []\n self.index_map = {} # element -> index\n\n def insert(self, new_one):\n if new_one in self.index_map:\n return\n self.index_map[new_one] = len(self.elements)\n self.elements.append(new_one)\n\n def remove(self, old_one):\n if not old_one in self.index_map:\n return\n index = self.index_map[old_one]\n last = self.elements.pop()\n self.index_map.pop(old_one)\n if index == len(self.elements):\n return\n self.elements[index] = last\n self.index_map[last] = index\n\n def random_element(self):\n return random.choice(self.elements)\n\n\ndef __test():\n rset = RandomizedSet()\n ground_truth = set()\n n = 64\n\n for i in range(n):\n rset.insert(i)\n ground_truth.add(i)\n\n # Remove a half\n for i in random.sample(range(n), n \/\/ 2):\n rset.remove(i)\n ground_truth.remove(i)\n\n print(len(ground_truth), len(rset.elements), len(rset.index_map))\n for i in ground_truth:\n assert(i == rset.elements[rset.index_map[i]])\n\n for i in range(n):\n print(rset.random_element(), end=' ')\n print()\n\n\nif __name__ == \"__main__\":\n __test()\n"} +{"Prompt":"Universe U of n elements Collection of subsets of U: S S1,S2...,Sm Where every substet Si has an associated cost. Find a minimum cost subcollection of S that covers all elements of U Example: U 1,2,3,4,5 S S1,S2,S3 S1 4,1,3, CostS1 5 S2 2,5, CostS2 10 S3 1,4,3,2, CostS3 3 Output: Set cover S2, S3 Min Cost 13 Calculate the powerset of any iterable. For a range of integers up to the length of the given list, make all possible combinations and chain them together as one object. From https:docs.python.org3libraryitertools.htmlitertoolsrecipes Optimal algorithm DONT USE ON BIG INPUTS O2n complexity! Finds the minimum cost subcollection os S that covers all elements of U Args: universe list: Universe of elements subsets dict: Subsets of U S1:elements,S2:elements costs dict: Costs of each subset in S S1:cost, S2:cost... Approximate greedy algorithm for setcovering. Can be used on large inputs though not an optimal solution. Args: universe list: Universe of elements subsets dict: Subsets of U S1:elements,S2:elements costs dict: Costs of each subset in S S1:cost, S2:cost... elements don't cover universe invalid input for set cover track elements of universe covered find set with minimum cost:elementsadded ratio set may have same elements as already covered newelements 0 check to avoid division by 0 error union","Completions":"from itertools import chain, combinations\n\n\"\"\"\nUniverse *U* of n elements\nCollection of subsets of U:\n S = S1,S2...,Sm\n Where every substet Si has an associated cost.\n\nFind a minimum cost subcollection of S that covers all elements of U\n\nExample:\n U = {1,2,3,4,5}\n S = {S1,S2,S3}\n\n S1 = {4,1,3}, Cost(S1) = 5\n S2 = {2,5}, Cost(S2) = 10\n S3 = {1,4,3,2}, Cost(S3) = 3\n\n Output:\n Set cover = {S2, S3}\n Min Cost = 13\n\"\"\"\n\n\ndef powerset(iterable):\n \"\"\"Calculate the powerset of any iterable.\n\n For a range of integers up to the length of the given list,\n make all possible combinations and chain them together as one object.\n From https:\/\/docs.python.org\/3\/library\/itertools.html#itertools-recipes\n \"\"\"\n \"list(powerset([1,2,3])) --> [(), (1,), (2,), (3,), (1,2), (1,3), (2,3), (1,2,3)]\"\n s = list(iterable)\n return chain.from_iterable(combinations(s, r) for r in range(len(s) + 1))\n\n\ndef optimal_set_cover(universe, subsets, costs):\n \"\"\" Optimal algorithm - DONT USE ON BIG INPUTS - O(2^n) complexity!\n Finds the minimum cost subcollection os S that covers all elements of U\n\n Args:\n universe (list): Universe of elements\n subsets (dict): Subsets of U {S1:elements,S2:elements}\n costs (dict): Costs of each subset in S - {S1:cost, S2:cost...}\n \"\"\"\n pset = powerset(subsets.keys())\n best_set = None\n best_cost = float(\"inf\")\n for subset in pset:\n covered = set()\n cost = 0\n for s in subset:\n covered.update(subsets[s])\n cost += costs[s]\n if len(covered) == len(universe) and cost < best_cost:\n best_set = subset\n best_cost = cost\n return best_set\n\n\ndef greedy_set_cover(universe, subsets, costs):\n \"\"\"Approximate greedy algorithm for set-covering. Can be used on large\n inputs - though not an optimal solution.\n\n Args:\n universe (list): Universe of elements\n subsets (dict): Subsets of U {S1:elements,S2:elements}\n costs (dict): Costs of each subset in S - {S1:cost, S2:cost...}\n \"\"\"\n elements = set(e for s in subsets.keys() for e in subsets[s])\n # elements don't cover universe -> invalid input for set cover\n if elements != universe:\n return None\n\n # track elements of universe covered\n covered = set()\n cover_sets = []\n\n while covered != universe:\n min_cost_elem_ratio = float(\"inf\")\n min_set = None\n # find set with minimum cost:elements_added ratio\n for s, elements in subsets.items():\n new_elements = len(elements - covered)\n # set may have same elements as already covered -> new_elements = 0\n # check to avoid division by 0 error\n if new_elements != 0:\n cost_elem_ratio = costs[s] \/ new_elements\n if cost_elem_ratio < min_cost_elem_ratio:\n min_cost_elem_ratio = cost_elem_ratio\n min_set = s\n cover_sets.append(min_set)\n # union\n covered |= subsets[min_set]\n return cover_sets\n\n\nif __name__ == '__main__':\n universe = {1, 2, 3, 4, 5}\n subsets = {'S1': {4, 1, 3}, 'S2': {2, 5}, 'S3': {1, 4, 3, 2}}\n costs = {'S1': 5, 'S2': 10, 'S3': 3}\n\n optimal_cover = optimal_set_cover(universe, subsets, costs)\n optimal_cost = sum(costs[s] for s in optimal_cover)\n\n greedy_cover = greedy_set_cover(universe, subsets, costs)\n greedy_cost = sum(costs[s] for s in greedy_cover)\n\n print('Optimal Set Cover:')\n print(optimal_cover)\n print('Cost = %s' % optimal_cost)\n\n print('Greedy Set Cover:')\n print(greedy_cover)\n print('Cost = %s' % greedy_cost)\n"} +{"Prompt":"bitonic sort is sorting algorithm to use multiple process, but this code not containing parallel process It can sort only array that sizes power of 2 It can sort array in both increasing order and decreasing order by giving argument trueincreasing and falsedecreasing Worstcase in parallel: Ologn2 Worstcase in nonparallel: Onlogn2 reference: https:en.wikipedia.orgwikiBitonicsorter end of functioncompare and bitionicmerge definition checks if n is power of two","Completions":"def bitonic_sort(arr, reverse=False):\n \"\"\"\n bitonic sort is sorting algorithm to use multiple process, but this code not containing parallel process\n It can sort only array that sizes power of 2\n It can sort array in both increasing order and decreasing order by giving argument true(increasing) and false(decreasing)\n \n Worst-case in parallel: O(log(n)^2)\n Worst-case in non-parallel: O(nlog(n)^2)\n \n reference: https:\/\/en.wikipedia.org\/wiki\/Bitonic_sorter\n \"\"\"\n def compare(arr, reverse):\n n = len(arr)\/\/2\n for i in range(n):\n if reverse != (arr[i] > arr[i+n]):\n arr[i], arr[i+n] = arr[i+n], arr[i]\n return arr\n\n def bitonic_merge(arr, reverse):\n n = len(arr)\n \n if n <= 1:\n return arr\n \n arr = compare(arr, reverse)\n left = bitonic_merge(arr[:n \/\/ 2], reverse)\n right = bitonic_merge(arr[n \/\/ 2:], reverse)\n return left + right\n \n #end of function(compare and bitionic_merge) definition\n n = len(arr)\n if n <= 1:\n return arr\n # checks if n is power of two\n if not (n and (not(n & (n - 1))) ):\n raise ValueError(\"the size of input should be power of two\")\n \n left = bitonic_sort(arr[:n \/\/ 2], True)\n right = bitonic_sort(arr[n \/\/ 2:], False)\n\n arr = bitonic_merge(left + right, reverse)\n \n return arr\n"} +{"Prompt":"Bogo Sort Best Case Complexity: On Worst Case Complexity: O Average Case Complexity: Onn1! check the array is inorder","Completions":"import random\n\ndef bogo_sort(arr, simulation=False):\n \"\"\"Bogo Sort\n Best Case Complexity: O(n)\n Worst Case Complexity: O(\u221e)\n Average Case Complexity: O(n(n-1)!)\n \"\"\"\n \n iteration = 0\n if simulation:\n print(\"iteration\",iteration,\":\",*arr)\n \n def is_sorted(arr):\n #check the array is inorder\n i = 0\n arr_len = len(arr)\n while i+1 < arr_len:\n if arr[i] > arr[i+1]:\n return False\n i += 1\n \n\n return True\n while not is_sorted(arr):\n random.shuffle(arr)\n \n if simulation:\n iteration = iteration + 1\n print(\"iteration\",iteration,\":\",*arr)\n \n return arr\n"} +{"Prompt":"https:en.wikipedia.orgwikiBubblesort Worstcase performance: ON2 If you call bubblesortarr,True, you can see the process of the sort Default is simulation False","Completions":"def bubble_sort(arr, simulation=False):\n def swap(i, j):\n arr[i], arr[j] = arr[j], arr[i]\n\n n = len(arr)\n swapped = True\n \n iteration = 0\n if simulation:\n print(\"iteration\",iteration,\":\",*arr)\n x = -1\n while swapped:\n swapped = False\n x = x + 1\n for i in range(1, n-x):\n if arr[i - 1] > arr[i]:\n swap(i - 1, i)\n swapped = True\n if simulation:\n iteration = iteration + 1\n print(\"iteration\",iteration,\":\",*arr)\n \n return arr\n"} +{"Prompt":"Bucket Sort Complexity: On2 The complexity is dominated by nextSort The number of buckets and make buckets Assign values into bucketsort Sort We will use insertion sort here.","Completions":"def bucket_sort(arr):\n ''' Bucket Sort\n Complexity: O(n^2)\n The complexity is dominated by nextSort\n '''\n # The number of buckets and make buckets\n num_buckets = len(arr)\n buckets = [[] for bucket in range(num_buckets)]\n # Assign values into bucket_sort\n for value in arr:\n index = value * num_buckets \/\/ (max(arr) + 1)\n buckets[index].append(value)\n # Sort\n sorted_list = []\n for i in range(num_buckets):\n sorted_list.extend(next_sort(buckets[i]))\n return sorted_list\n\ndef next_sort(arr):\n # We will use insertion sort here.\n for i in range(1, len(arr)):\n j = i - 1\n key = arr[i]\n while arr[j] > key and j >= 0:\n arr[j+1] = arr[j]\n j = j - 1\n arr[j + 1] = key\n return arr\n"} +{"Prompt":"Cocktailshakersort Sorting a given array mutation of bubble sort reference: https:en.wikipedia.orgwikiCocktailshakersort Worstcase performance: ON2","Completions":"def cocktail_shaker_sort(arr):\n \"\"\"\n Cocktail_shaker_sort\n Sorting a given array\n mutation of bubble sort\n\n reference: https:\/\/en.wikipedia.org\/wiki\/Cocktail_shaker_sort\n \n Worst-case performance: O(N^2)\n \"\"\"\n\n def swap(i, j):\n arr[i], arr[j] = arr[j], arr[i]\n\n n = len(arr)\n swapped = True\n while swapped:\n swapped = False\n for i in range(1, n):\n if arr[i - 1] > arr[i]:\n swap(i - 1, i)\n swapped = True\n if swapped == False:\n return arr\n swapped = False\n for i in range(n-1,0,-1):\n if arr[i - 1] > arr[i]:\n swap(i - 1, i)\n swapped = True\n return arr\n"} +{"Prompt":"https:en.wikipedia.orgwikiCombsort Worstcase performance: ON2","Completions":"def comb_sort(arr):\n def swap(i, j):\n arr[i], arr[j] = arr[j], arr[i]\n\n n = len(arr)\n gap = n\n shrink = 1.3\n sorted = False\n while not sorted:\n gap = int(gap \/ shrink)\n if gap > 1:\n sorted = False\n else:\n gap = 1\n sorted = True\n\n i = 0\n while i + gap < n:\n if arr[i] > arr[i + gap]:\n swap(i, i + gap)\n sorted = False\n i = i + 1\n return arr\n"} +{"Prompt":"Countingsort Sorting a array which has no element greater than k Creating a new temparr,where temparri contain the number of element less than or equal to i in the arr Then placing the number i into a correct position in the resultarr return the resultarr Complexity: 0n in case there are negative elements, change the array to all positive element save the change, so that we can convert the array back to all positive number temparrayi contain the times the number i appear in arr temparrayi contain the number of element less than or equal i in arr creating a resultarr an put the element in a correct positon","Completions":"def counting_sort(arr):\n \"\"\"\n Counting_sort\n Sorting a array which has no element greater than k\n Creating a new temp_arr,where temp_arr[i] contain the number of\n element less than or equal to i in the arr\n Then placing the number i into a correct position in the result_arr\n return the result_arr\n Complexity: 0(n)\n \"\"\"\n\n m = min(arr)\n # in case there are negative elements, change the array to all positive element\n different = 0\n if m < 0:\n # save the change, so that we can convert the array back to all positive number\n different = -m\n for i in range(len(arr)):\n arr[i] += -m\n k = max(arr)\n temp_arr = [0] * (k + 1)\n for i in range(0, len(arr)):\n temp_arr[arr[i]] = temp_arr[arr[i]] + 1\n # temp_array[i] contain the times the number i appear in arr\n\n for i in range(1, k + 1):\n temp_arr[i] = temp_arr[i] + temp_arr[i - 1]\n # temp_array[i] contain the number of element less than or equal i in arr\n\n result_arr = arr.copy()\n # creating a result_arr an put the element in a correct positon\n for i in range(len(arr) - 1, -1, -1):\n result_arr[temp_arr[arr[i]] - 1] = arr[i] - different\n temp_arr[arr[i]] = temp_arr[arr[i]] - 1\n\n return result_arr\n"} +{"Prompt":"cyclesort This is based on the idea that the permutations to be sorted can be decomposed into cycles, and the results can be individually sorted by cycling. reference: https:en.wikipedia.orgwikiCyclesort Average time complexity : ON2 Worst case time complexity : ON2 Finding cycle to rotate. Finding an indx to put items in. Case of there is not a cycle Putting the item immediately right after the duplicate item or on the right. Rotating the remaining cycle. Finding where to put the item. After item is duplicated, put it in place or put it there.","Completions":"def cycle_sort(arr):\n \"\"\"\n cycle_sort\n This is based on the idea that the permutations to be sorted\n can be decomposed into cycles,\n and the results can be individually sorted by cycling.\n \n reference: https:\/\/en.wikipedia.org\/wiki\/Cycle_sort\n \n Average time complexity : O(N^2)\n Worst case time complexity : O(N^2)\n \"\"\"\n len_arr = len(arr)\n # Finding cycle to rotate.\n for cur in range(len_arr - 1):\n item = arr[cur]\n\n # Finding an indx to put items in.\n index = cur\n for i in range(cur + 1, len_arr):\n if arr[i] < item:\n index += 1\n\n # Case of there is not a cycle\n if index == cur:\n continue\n\n # Putting the item immediately right after the duplicate item or on the right.\n while item == arr[index]:\n index += 1\n arr[index], item = item, arr[index]\n\n # Rotating the remaining cycle.\n while index != cur:\n\n # Finding where to put the item.\n index = cur\n for i in range(cur + 1, len_arr):\n if arr[i] < item:\n index += 1\n\n # After item is duplicated, put it in place or put it there.\n while item == arr[index]:\n index += 1\n arr[index], item = item, arr[index]\n return arr\n"} +{"Prompt":"Reference : https:en.wikipedia.orgwikiSortingalgorithmExchangesort Complexity : On2","Completions":"def exchange_sort(arr):\n \"\"\"\n Reference : https:\/\/en.wikipedia.org\/wiki\/Sorting_algorithm#Exchange_sort\n Complexity : O(n^2)\n \"\"\"\n arr_len = len(arr)\n for i in range(arr_len-1):\n for j in range(i+1, arr_len):\n if(arr[i] > arr[j]):\n arr[i], arr[j] = arr[j], arr[i]\n return arr\n"} +{"Prompt":"Gnome Sort Best case performance is On Worst case performance is On2","Completions":"def gnome_sort(arr):\n n = len(arr)\n index = 0\n while index < n:\n if index == 0 or arr[index] >= arr[index-1]:\n index = index + 1\n else:\n arr[index], arr[index-1] = arr[index-1], arr[index]\n index = index - 1\n return arr\n"} +{"Prompt":"Heap Sort that uses a max heap to sort an array in ascending order Complexity: On logn Max heapify helper for maxheapsort Iterate from last parent to first Iterate from currentparent to lastparent Find greatest child of currentparent Swap if child is greater than parent If no swap occurred, no need to keep iterating Heap Sort that uses a min heap to sort an array in ascending order Complexity: On logn Min heapify helper for minheapsort Offset lastparent by the start lastparent calculated as if start index was 0 All array accesses need to be offset by start Iterate from last parent to first Iterate from currentparent to lastparent Find lesser child of currentparent Swap if child is less than parent If no swap occurred, no need to keep iterating","Completions":"def max_heap_sort(arr, simulation=False):\n \"\"\" Heap Sort that uses a max heap to sort an array in ascending order\n Complexity: O(n log(n))\n \"\"\"\n iteration = 0\n if simulation:\n print(\"iteration\",iteration,\":\",*arr)\n \n for i in range(len(arr) - 1, 0, -1):\n iteration = max_heapify(arr, i, simulation, iteration)\n\n if simulation:\n iteration = iteration + 1\n print(\"iteration\",iteration,\":\",*arr)\n return arr\n\n\ndef max_heapify(arr, end, simulation, iteration):\n \"\"\" Max heapify helper for max_heap_sort\n \"\"\"\n last_parent = (end - 1) \/\/ 2\n\n # Iterate from last parent to first\n for parent in range(last_parent, -1, -1):\n current_parent = parent\n\n # Iterate from current_parent to last_parent\n while current_parent <= last_parent:\n # Find greatest child of current_parent\n child = 2 * current_parent + 1\n if child + 1 <= end and arr[child] < arr[child + 1]:\n child = child + 1\n\n # Swap if child is greater than parent\n if arr[child] > arr[current_parent]:\n arr[current_parent], arr[child] = arr[child], arr[current_parent]\n current_parent = child\n if simulation:\n iteration = iteration + 1\n print(\"iteration\",iteration,\":\",*arr)\n # If no swap occurred, no need to keep iterating\n else:\n break\n arr[0], arr[end] = arr[end], arr[0]\n return iteration\n\ndef min_heap_sort(arr, simulation=False):\n \"\"\" Heap Sort that uses a min heap to sort an array in ascending order\n Complexity: O(n log(n))\n \"\"\"\n iteration = 0\n if simulation:\n print(\"iteration\",iteration,\":\",*arr)\n \n for i in range(0, len(arr) - 1):\n iteration = min_heapify(arr, i, simulation, iteration)\n\n return arr\n\n\ndef min_heapify(arr, start, simulation, iteration):\n \"\"\" Min heapify helper for min_heap_sort\n \"\"\"\n # Offset last_parent by the start (last_parent calculated as if start index was 0)\n # All array accesses need to be offset by start\n end = len(arr) - 1\n last_parent = (end - start - 1) \/\/ 2\n\n # Iterate from last parent to first\n for parent in range(last_parent, -1, -1):\n current_parent = parent\n\n # Iterate from current_parent to last_parent\n while current_parent <= last_parent:\n # Find lesser child of current_parent\n child = 2 * current_parent + 1\n if child + 1 <= end - start and arr[child + start] > arr[\n child + 1 + start]:\n child = child + 1\n \n # Swap if child is less than parent\n if arr[child + start] < arr[current_parent + start]:\n arr[current_parent + start], arr[child + start] = \\\n arr[child + start], arr[current_parent + start]\n current_parent = child\n if simulation:\n iteration = iteration + 1\n print(\"iteration\",iteration,\":\",*arr)\n # If no swap occurred, no need to keep iterating\n else:\n break\n return iteration\n"} +{"Prompt":"Insertion Sort Complexity: On2 Swap the number down the list Break and do the final swap","Completions":"def insertion_sort(arr, simulation=False):\n \"\"\" Insertion Sort\n Complexity: O(n^2)\n \"\"\"\n \n iteration = 0\n if simulation:\n print(\"iteration\",iteration,\":\",*arr)\n \n for i in range(len(arr)):\n cursor = arr[i]\n pos = i\n \n while pos > 0 and arr[pos - 1] > cursor:\n # Swap the number down the list\n arr[pos] = arr[pos - 1]\n pos = pos - 1\n # Break and do the final swap\n arr[pos] = cursor\n \n if simulation:\n iteration = iteration + 1\n print(\"iteration\",iteration,\":\",*arr)\n\n return arr\n"} +{"Prompt":"Given an array of meeting time intervals consisting of start and end times s1,e1,s2,e2,... si ei, determine if a person could attend all meetings. For example, Given 0, 30,5, 10,15, 20, return false. :type intervals: ListInterval :rtype: bool","Completions":"def can_attend_meetings(intervals):\n \"\"\"\n :type intervals: List[Interval]\n :rtype: bool\n \"\"\"\n intervals = sorted(intervals, key=lambda x: x.start)\n for i in range(1, len(intervals)):\n if intervals[i].start < intervals[i - 1].end:\n return False\n return True\n"} +{"Prompt":"Merge Sort Complexity: On logn Our recursive base case Perform mergesort recursively on both halves Merge each side together return mergeleft, right, arr.copy changed, no need to copy, mutate inplace. Merge helper Complexity: On Sort each one and place into the result Add the left overs if there's any left to the result Add the left overs if there's any left to the result Return result return merged do not return anything, as it is replacing inplace.","Completions":"def merge_sort(arr):\n \"\"\" Merge Sort\n Complexity: O(n log(n))\n \"\"\"\n # Our recursive base case\n if len(arr) <= 1:\n return arr\n mid = len(arr) \/\/ 2\n # Perform merge_sort recursively on both halves\n left, right = merge_sort(arr[:mid]), merge_sort(arr[mid:])\n\n # Merge each side together\n # return merge(left, right, arr.copy()) # changed, no need to copy, mutate inplace.\n merge(left,right,arr)\n return arr\n\n\ndef merge(left, right, merged):\n \"\"\" Merge helper\n Complexity: O(n)\n \"\"\"\n\n left_cursor, right_cursor = 0, 0\n while left_cursor < len(left) and right_cursor < len(right):\n # Sort each one and place into the result\n if left[left_cursor] <= right[right_cursor]:\n merged[left_cursor+right_cursor]=left[left_cursor]\n left_cursor += 1\n else:\n merged[left_cursor + right_cursor] = right[right_cursor]\n right_cursor += 1\n # Add the left overs if there's any left to the result\n for left_cursor in range(left_cursor, len(left)):\n merged[left_cursor + right_cursor] = left[left_cursor]\n # Add the left overs if there's any left to the result\n for right_cursor in range(right_cursor, len(right)):\n merged[left_cursor + right_cursor] = right[right_cursor]\n\n # Return result\n # return merged # do not return anything, as it is replacing inplace.\n"} +{"Prompt":"Pancakesort Sorting a given array mutation of selection sort reference: https:www.geeksforgeeks.orgpancakesorting Overall time complexity : ON2 Finding index of maximum number in arr Needs moving reverse from 0 to indexmax Reverse list","Completions":"def pancake_sort(arr):\n \"\"\"\n Pancake_sort\n Sorting a given array\n mutation of selection sort\n\n reference: https:\/\/www.geeksforgeeks.org\/pancake-sorting\/\n \n Overall time complexity : O(N^2)\n \"\"\"\n\n len_arr = len(arr)\n if len_arr <= 1:\n return arr\n for cur in range(len(arr), 1, -1):\n #Finding index of maximum number in arr\n index_max = arr.index(max(arr[0:cur]))\n if index_max+1 != cur:\n #Needs moving\n if index_max != 0:\n #reverse from 0 to index_max\n arr[:index_max+1] = reversed(arr[:index_max+1])\n # Reverse list\n arr[:cur] = reversed(arr[:cur])\n return arr\n"} +{"Prompt":"https:en.wikipedia.orgwikiPigeonholesort Time complexity: On Range where n number of elements and Range possible values in the array Suitable for lists where the number of elements and key values are mostly the same.","Completions":"def pigeonhole_sort(arr):\n Max = max(arr)\n Min = min(arr)\n size = Max - Min + 1\n\n holes = [0]*size\n\n for i in arr:\n holes[i-Min] += 1\n\n i = 0\n for count in range(size):\n while holes[count] > 0:\n holes[count] -= 1\n arr[i] = count + Min\n i += 1\n return arr\n"} +{"Prompt":"Quick sort Complexity: best On logn avg On logn, worst ON2 Start our two recursive calls","Completions":"def quick_sort(arr, simulation=False):\n \"\"\" Quick sort\n Complexity: best O(n log(n)) avg O(n log(n)), worst O(N^2)\n \"\"\"\n \n iteration = 0\n if simulation:\n print(\"iteration\",iteration,\":\",*arr)\n arr, _ = quick_sort_recur(arr, 0, len(arr) - 1, iteration, simulation)\n return arr\n\ndef quick_sort_recur(arr, first, last, iteration, simulation):\n if first < last:\n pos = partition(arr, first, last)\n # Start our two recursive calls\n if simulation:\n iteration = iteration + 1\n print(\"iteration\",iteration,\":\",*arr)\n \n _, iteration = quick_sort_recur(arr, first, pos - 1, iteration, simulation)\n _, iteration = quick_sort_recur(arr, pos + 1, last, iteration, simulation)\n\n return arr, iteration\n\ndef partition(arr, first, last):\n wall = first\n for pos in range(first, last):\n if arr[pos] < arr[last]: # last is the pivot\n arr[pos], arr[wall] = arr[wall], arr[pos]\n wall += 1\n arr[wall], arr[last] = arr[last], arr[wall]\n return wall\n"} +{"Prompt":"radix sort complexity: Onk n . n is the size of input list and k is the digit length of the number","Completions":"def radix_sort(arr, simulation=False):\n position = 1\n max_number = max(arr)\n\n iteration = 0\n if simulation:\n print(\"iteration\", iteration, \":\", *arr)\n\n while position <= max_number:\n queue_list = [list() for _ in range(10)]\n\n for num in arr:\n digit_number = num \/\/ position % 10\n queue_list[digit_number].append(num)\n\n index = 0\n for numbers in queue_list:\n for num in numbers:\n arr[index] = num\n index += 1\n\n if simulation:\n iteration = iteration + 1\n print(\"iteration\", iteration, \":\", *arr)\n\n position *= 10\n return arr\n "} +{"Prompt":"Selection Sort Complexity: On2 Select the correct value","Completions":"def selection_sort(arr, simulation=False):\n \"\"\" Selection Sort\n Complexity: O(n^2)\n \"\"\"\n iteration = 0\n if simulation:\n print(\"iteration\",iteration,\":\",*arr)\n \n for i in range(len(arr)):\n minimum = i\n \n for j in range(i + 1, len(arr)):\n # \"Select\" the correct value\n if arr[j] < arr[minimum]:\n minimum = j\n\n arr[minimum], arr[i] = arr[i], arr[minimum]\n \n if simulation:\n iteration = iteration + 1\n print(\"iteration\",iteration,\":\",*arr)\n \n return arr\n"} +{"Prompt":"Shell Sort Complexity: On2 Initialize size of the gap","Completions":"def shell_sort(arr):\n ''' Shell Sort\n Complexity: O(n^2)\n '''\n n = len(arr)\n # Initialize size of the gap\n gap = n\/\/2\n \n while gap > 0:\n y_index = gap\n while y_index < len(arr):\n y = arr[y_index]\n x_index = y_index - gap\n while x_index >= 0 and y < arr[x_index]:\n arr[x_index + gap] = arr[x_index]\n x_index = x_index - gap\n arr[x_index + gap] = y\n y_index = y_index + 1\n gap = gap\/\/2\n \n return arr\n"} +{"Prompt":"Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue. Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively. Note: You are not suppose to use the library's sort function for this problem.","Completions":"def sort_colors(nums):\n i = j = 0\n for k in range(len(nums)):\n v = nums[k]\n nums[k] = 2\n if v < 2:\n nums[j] = 1\n j += 1\n if v == 0:\n nums[i] = 0\n i += 1\n\n\nif __name__ == \"__main__\":\n nums = [0, 1, 1, 1, 2, 2, 2, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 2, 2]\n sort_colors(nums)\n print(nums)\n"} +{"Prompt":"Stooge Sort Time Complexity : On2.709 Reference: https:www.geeksforgeeks.orgstoogesort If first element is smaller than last, swap them If there are more than 2 elements in the array Recursively sort first 2 3 elements Recursively sort last 2 3 elements Recursively sort first 2 3 elements again to confirm","Completions":"def stoogesort(arr, l, h): \n if l >= h: \n return\n \n # If first element is smaller \n # than last, swap them \n if arr[l]>arr[h]: \n t = arr[l] \n arr[l] = arr[h] \n arr[h] = t \n \n # If there are more than 2 elements in \n # the array \n if h-l + 1 > 2: \n t = (int)((h-l + 1)\/3) \n \n # Recursively sort first 2 \/ 3 elements \n stoogesort(arr, l, (h-t)) \n \n # Recursively sort last 2 \/ 3 elements \n stoogesort(arr, l + t, (h)) \n \n # Recursively sort first 2 \/ 3 elements \n # again to confirm \n stoogesort(arr, l, (h-t)) \n \n\nif __name__ == \"__main__\":\n array = [1,3,64,5,7,8]\n n = len(array) \n stoogesort(array, 0, n-1) \n for i in range(0, n): \n print(array[i], end = ' ') \n"} +{"Prompt":"Time complexity is the same as DFS, which is OV E Space complexity: OV printnode Time complexity is the same as DFS, which is OV E Space complexity: OV","Completions":"GRAY, BLACK = 0, 1\n\ndef top_sort_recursive(graph):\n \"\"\" Time complexity is the same as DFS, which is O(V + E)\n Space complexity: O(V)\n \"\"\"\n order, enter, state = [], set(graph), {}\n \n def dfs(node):\n state[node] = GRAY\n #print(node)\n for k in graph.get(node, ()):\n sk = state.get(k, None)\n if sk == GRAY:\n raise ValueError(\"cycle\")\n if sk == BLACK:\n continue\n enter.discard(k)\n dfs(k)\n order.append(node)\n state[node] = BLACK\n \n while enter: dfs(enter.pop())\n return order\n\ndef top_sort(graph):\n \"\"\" Time complexity is the same as DFS, which is O(V + E)\n Space complexity: O(V)\n \"\"\"\n order, enter, state = [], set(graph), {}\n \n def is_ready(node):\n lst = graph.get(node, ())\n if len(lst) == 0:\n return True\n for k in lst:\n sk = state.get(k, None)\n if sk == GRAY: \n raise ValueError(\"cycle\")\n if sk != BLACK:\n return False\n return True\n \n while enter:\n node = enter.pop()\n stack = []\n while True:\n state[node] = GRAY\n stack.append(node)\n for k in graph.get(node, ()):\n sk = state.get(k, None)\n if sk == GRAY: \n raise ValueError(\"cycle\")\n if sk == BLACK: \n continue\n enter.discard(k)\n stack.append(k)\n while stack and is_ready(stack[-1]):\n node = stack.pop()\n order.append(node)\n state[node] = BLACK\n if len(stack) == 0:\n break\n node = stack.pop()\n \n return order\n"} +{"Prompt":"Given an unsorted array nums, reorder it such that nums0 nums1 nums2 nums3....","Completions":"def wiggle_sort(nums):\n for i in range(len(nums)):\n if (i % 2 == 1) == (nums[i-1] > nums[i]):\n nums[i-1], nums[i] = nums[i], nums[i-1]\n\nif __name__ == \"__main__\":\n array = [3, 5, 2, 1, 6, 4]\n\n print(array)\n wiggle_sort(array)\n print(array)\n\n\n"} +{"Prompt":"Given a stack, a function isconsecutive takes a stack as a parameter and that returns whether or not the stack contains a sequence of consecutive integers starting from the bottom of the stack returning true if it does, returning false if it does not. For example: bottom 3, 4, 5, 6, 7 top Then the call of isconsecutives should return true. bottom 3, 4, 6, 7 top Then the call of isconsecutives should return false. bottom 3, 2, 1 top The function should return false due to reverse order. Note: There are 2 solutions: firstisconsecutive: it uses a single stack as auxiliary storage secondisconsecutive: it uses a single queue as auxiliary storage Back up stack from storage stack Back up stack from queue","Completions":"import collections\n\n\ndef first_is_consecutive(stack):\n storage_stack = []\n for i in range(len(stack)):\n first_value = stack.pop()\n if len(stack) == 0: # Case odd number of values in stack\n return True\n second_value = stack.pop()\n if first_value - second_value != 1: # Not consecutive\n return False\n stack.append(second_value) # Backup second value\n storage_stack.append(first_value)\n\n # Back up stack from storage stack\n for i in range(len(storage_stack)):\n stack.append(storage_stack.pop())\n return True\n\n\ndef second_is_consecutive(stack):\n q = collections.deque()\n for i in range(len(stack)):\n first_value = stack.pop()\n if len(stack) == 0: # Case odd number of values in stack\n return True\n second_value = stack.pop()\n if first_value - second_value != 1: # Not consecutive\n return False\n stack.append(second_value) # Backup second value\n q.append(first_value)\n\n # Back up stack from queue\n for i in range(len(q)):\n stack.append(q.pop())\n for i in range(len(stack)):\n q.append(stack.pop())\n for i in range(len(q)):\n stack.append(q.pop())\n\n return True\n"} +{"Prompt":"Given a stack, a function issorted accepts a stack as a parameter and returns true if the elements in the stack occur in ascending increasing order from bottom, and false otherwise. That is, the smallest element should be at bottom For example: bottom 6, 3, 5, 1, 2, 4 top The function should return false bottom 1, 2, 3, 4, 5, 6 top The function should return true Backup stack","Completions":"def is_sorted(stack):\n storage_stack = []\n for i in range(len(stack)):\n if len(stack) == 0:\n break\n first_val = stack.pop()\n if len(stack) == 0:\n break\n second_val = stack.pop()\n if first_val < second_val:\n return False\n storage_stack.append(first_val)\n stack.append(second_val)\n\n # Backup stack\n for i in range(len(storage_stack)):\n stack.append(storage_stack.pop())\n\n return True\n"} +{"Prompt":"def lengthLongestPathinput: maxlen 0 pathlen 0: 0 for line in input.splitlines: print printline:, line name line.strip't' printname:, name depth lenline lenname printdepth:, depth if '.' in name: maxlen maxmaxlen, pathlendepth lenname else: pathlendepth 1 pathlendepth lenname 1 printmaxlen:, maxlen return maxlen def lengthLongestPathinput: paths input.splitn level 0 10 maxLength 0 for path in paths: print levelIdx path.rfindt printPath: , path printpath.rfindt, path.rfindt printlevelIdx: , levelIdx printlevel: , level levellevelIdx 1 levellevelIdx lenpath levelIdx 1 printlevel: , level if . in path: maxLength maxmaxLength, levellevelIdx1 1 printmaxlen: , maxLength return maxLength :type input: str :rtype: int","Completions":"# def lengthLongestPath(input):\n# maxlen = 0\n# pathlen = {0: 0}\n# for line in input.splitlines():\n# print(\"---------------\")\n# print(\"line:\", line)\n# name = line.strip('\\t')\n# print(\"name:\", name)\n# depth = len(line) - len(name)\n# print(\"depth:\", depth)\n# if '.' in name:\n# maxlen = max(maxlen, pathlen[depth] + len(name))\n# else:\n# pathlen[depth + 1] = pathlen[depth] + len(name) + 1\n# print(\"maxlen:\", maxlen)\n# return maxlen\n\n# def lengthLongestPath(input):\n# paths = input.split(\"\\n\")\n# level = [0] * 10\n# maxLength = 0\n# for path in paths:\n# print(\"-------------\")\n# levelIdx = path.rfind(\"\\t\")\n# print(\"Path: \", path)\n# print(\"path.rfind(\\\\t)\", path.rfind(\"\\t\"))\n# print(\"levelIdx: \", levelIdx)\n# print(\"level: \", level)\n# level[levelIdx + 1] = level[levelIdx] + len(path) - levelIdx + 1\n# print(\"level: \", level)\n# if \".\" in path:\n# maxLength = max(maxLength, level[levelIdx+1] - 1)\n# print(\"maxlen: \", maxLength)\n# return maxLength\n\ndef length_longest_path(input):\n \"\"\"\n :type input: str\n :rtype: int\n \"\"\"\n curr_len, max_len = 0, 0 # running length and max length\n stack = [] # keep track of the name length\n for s in input.split('\\n'):\n print(\"---------\")\n print(\":\", s)\n depth = s.count('\\t') # the depth of current dir or file\n print(\"depth: \", depth)\n print(\"stack: \", stack)\n print(\"curlen: \", curr_len)\n while len(stack) > depth: # go back to the correct depth\n curr_len -= stack.pop()\n stack.append(len(s.strip('\\t'))+1) # 1 is the length of '\/'\n curr_len += stack[-1] # increase current length\n print(\"stack: \", stack)\n print(\"curlen: \", curr_len)\n if '.' in s: # update maxlen only when it is a file\n max_len = max(max_len, curr_len-1) # -1 is to minus one '\/'\n return max_len\n\n\nst = \"dir\\n\\tsubdir1\\n\\t\\tfile1.ext\\n\\t\\tsubsubdirectory1\\n\\tsubdir2\\n\\t\\tsubsubdir2\\n\\t\\t\\tfile2.ext\"\nst2 = \"a\\n\\tb1\\n\\t\\tf1.txt\\n\\taaaaa\\n\\t\\tf2.txt\"\nprint(\"path:\", st2)\n\nprint(\"answer:\", length_longest_path(st2))\n"} +{"Prompt":"The stack remains always ordered such that the highest value is at the top and the lowest at the bottom push method to maintain order when pushing new elements","Completions":"# The stack remains always ordered such that the highest value\n# is at the top and the lowest at the bottom\n\n\nclass OrderedStack:\n def __init__(self):\n self.items = []\n\n def is_empty(self):\n return self.items == []\n\n def push_t(self, item):\n self.items.append(item)\n\n # push method to maintain order when pushing new elements\n def push(self, item):\n temp_stack = OrderedStack()\n if self.is_empty() or item > self.peek():\n self.push_t(item)\n else:\n while item < self.peek() and not self.is_empty():\n temp_stack.push_t(self.pop())\n self.push_t(item)\n while not temp_stack.is_empty():\n self.push_t(temp_stack.pop())\n\n def pop(self):\n if self.is_empty():\n raise IndexError(\"Stack is empty\")\n return self.items.pop()\n\n def peek(self):\n return self.items[len(self.items) - 1]\n\n def size(self):\n return len(self.items)\n"} +{"Prompt":"Given a stack, a function removemin accepts a stack as a parameter and removes the smallest value from the stack. For example: bottom 2, 8, 3, 6, 7, 3 top After removeminstack: bottom 2, 8, 3, 7, 3 top Find the smallest value Back up stack and remove min value","Completions":"def remove_min(stack):\n storage_stack = []\n if len(stack) == 0: # Stack is empty\n return stack\n # Find the smallest value\n min = stack.pop()\n stack.append(min)\n for i in range(len(stack)):\n val = stack.pop()\n if val <= min:\n min = val\n storage_stack.append(val)\n # Back up stack and remove min value\n for i in range(len(storage_stack)):\n val = storage_stack.pop()\n if val != min:\n stack.append(val)\n return stack\n"} +{"Prompt":"Given an absolute path for a file Unixstyle, simplify it. For example, path home, home path a.b....c, c Did you consider the case where path ..? In this case, you should return . Another corner case is the path might contain multiple slashes '' together, such as homefoo. In this case, you should ignore redundant slashes and return homefoo. :type path: str :rtype: str","Completions":"def simplify_path(path):\n \"\"\"\n :type path: str\n :rtype: str\n \"\"\"\n skip = {'..', '.', ''}\n stack = []\n paths = path.split('\/')\n for tok in paths:\n if tok == '..':\n if stack:\n stack.pop()\n elif tok not in skip:\n stack.append(tok)\n return '\/' + '\/'.join(stack)\n"} +{"Prompt":"Stack Abstract Data Type ADT Stack creates a new stack that is empty. It needs no parameters and returns an empty stack. pushitem adds a new item to the top of the stack. It needs the item and returns nothing. pop removes the top item from the stack. It needs no parameters and returns the item. The stack is modified. peek returns the top item from the stack but does not remove it. It needs no parameters. The stack is not modified. isempty tests to see whether the stack is empty. It needs no parameters and returns a boolean value. Abstract Class for Stacks. def initself: self.top 1 def lenself: return self.top 1 def strself: result .joinmapstr, self return 'Top ' result def isemptyself: return self.top 1 abstractmethod def iterself: pass abstractmethod def pushself, value: pass abstractmethod def popself: pass abstractmethod def peekself: pass class ArrayStackAbstractStack: def initself, size10: super.init self.array None size def iterself: probe self.top while True: if probe 1: return yield self.arrayprobe probe 1 def pushself, value: self.top 1 if self.top lenself.array: self.expand self.arrayself.top value def popself: if self.isempty: raise IndexErrorStack is empty value self.arrayself.top self.top 1 return value def peekself: expands size of the array. Time Complexity: On Represents a single stack node. def initself, value: self.value value self.next None class LinkedListStackAbstractStack: def initself: super.init self.head None def iterself: probe self.head while True: if probe is None: return yield probe.value probe probe.next def pushself, value: node StackNodevalue node.next self.head self.head node self.top 1 def popself: if self.isempty: raise IndexErrorStack is empty value self.head.value self.head self.head.next self.top 1 return value def peekself: if self.isempty: raise IndexErrorStack is empty return self.head.value","Completions":"from abc import ABCMeta, abstractmethod\n\n\nclass AbstractStack(metaclass=ABCMeta):\n \"\"\"Abstract Class for Stacks.\"\"\"\n def __init__(self):\n self._top = -1\n\n def __len__(self):\n return self._top + 1\n\n def __str__(self):\n result = \" \".join(map(str, self))\n return 'Top-> ' + result\n\n def is_empty(self):\n return self._top == -1\n\n @abstractmethod\n def __iter__(self):\n pass\n\n @abstractmethod\n def push(self, value):\n pass\n\n @abstractmethod\n def pop(self):\n pass\n\n @abstractmethod\n def peek(self):\n pass\n\n\nclass ArrayStack(AbstractStack):\n def __init__(self, size=10):\n \"\"\"\n Initialize python List with size of 10 or user given input.\n Python List type is a dynamic array, so we have to restrict its\n dynamic nature to make it work like a static array.\n \"\"\"\n super().__init__()\n self._array = [None] * size\n\n def __iter__(self):\n probe = self._top\n while True:\n if probe == -1:\n return\n yield self._array[probe]\n probe -= 1\n\n def push(self, value):\n self._top += 1\n if self._top == len(self._array):\n self._expand()\n self._array[self._top] = value\n\n def pop(self):\n if self.is_empty():\n raise IndexError(\"Stack is empty\")\n value = self._array[self._top]\n self._top -= 1\n return value\n\n def peek(self):\n \"\"\"returns the current top element of the stack.\"\"\"\n if self.is_empty():\n raise IndexError(\"Stack is empty\")\n return self._array[self._top]\n\n def _expand(self):\n \"\"\"\n expands size of the array.\n Time Complexity: O(n)\n \"\"\"\n self._array += [None] * len(self._array) # double the size of the array\n\n\nclass StackNode:\n \"\"\"Represents a single stack node.\"\"\"\n def __init__(self, value):\n self.value = value\n self.next = None\n\n\nclass LinkedListStack(AbstractStack):\n\n def __init__(self):\n super().__init__()\n self.head = None\n\n def __iter__(self):\n probe = self.head\n while True:\n if probe is None:\n return\n yield probe.value\n probe = probe.next\n\n def push(self, value):\n node = StackNode(value)\n node.next = self.head\n self.head = node\n self._top += 1\n\n def pop(self):\n if self.is_empty():\n raise IndexError(\"Stack is empty\")\n value = self.head.value\n self.head = self.head.next\n self._top -= 1\n return value\n\n def peek(self):\n if self.is_empty():\n raise IndexError(\"Stack is empty\")\n return self.head.value\n"} +{"Prompt":"Given a stack, stutter takes a stack as a parameter and replaces every value in the stack with two occurrences of that value. For example, suppose the stack stores these values: bottom 3, 7, 1, 14, 9 top Then the stack should store these values after the method terminates: bottom 3, 3, 7, 7, 1, 1, 14, 14, 9, 9 top Note: There are 2 solutions: firststutter: it uses a single stack as auxiliary storage secondstutter: it uses a single queue as auxiliary storage Put all values into queue from stack Put values back into stack from queue Now, stack is reverse, put all values into queue from stack Put 2 times value into stack from queue","Completions":"import collections\n\n\ndef first_stutter(stack):\n storage_stack = []\n for i in range(len(stack)):\n storage_stack.append(stack.pop())\n for i in range(len(storage_stack)):\n val = storage_stack.pop()\n stack.append(val)\n stack.append(val)\n\n return stack\n\n\ndef second_stutter(stack):\n q = collections.deque()\n # Put all values into queue from stack\n for i in range(len(stack)):\n q.append(stack.pop())\n # Put values back into stack from queue\n for i in range(len(q)):\n stack.append(q.pop())\n # Now, stack is reverse, put all values into queue from stack\n for i in range(len(stack)):\n q.append(stack.pop())\n # Put 2 times value into stack from queue\n for i in range(len(q)):\n val = q.pop()\n stack.append(val)\n stack.append(val)\n\n return stack\n"} +{"Prompt":"Given a stack, switchpairs function takes a stack as a parameter and that switches successive pairs of numbers starting at the bottom of the stack. For example, if the stack initially stores these values: bottom 3, 8, 17, 9, 1, 10 top Your function should switch the first pair 3, 8, the second pair 17, 9, ...: bottom 8, 3, 9, 17, 10, 1 top if there are an odd number of values in the stack, the value at the top of the stack is not moved: For example: bottom 3, 8, 17, 9, 1 top It would again switch pairs of values, but the value at the top of the stack 1 would not be moved bottom 8, 3, 9, 17, 1 top Note: There are 2 solutions: firstswitchpairs: it uses a single stack as auxiliary storage secondswitchpairs: it uses a single queue as auxiliary storage Put all values into queue from stack Put values back into stack from queue Now, stack is reverse, put all values into queue from stack Swap pairs by appending the 2nd value before appending 1st value","Completions":"import collections\n\n\ndef first_switch_pairs(stack):\n storage_stack = []\n for i in range(len(stack)):\n storage_stack.append(stack.pop())\n for i in range(len(storage_stack)):\n if len(storage_stack) == 0:\n break\n first = storage_stack.pop()\n if len(storage_stack) == 0: # case: odd number of values in stack\n stack.append(first)\n break\n second = storage_stack.pop()\n stack.append(second)\n stack.append(first)\n return stack\n\n\ndef second_switch_pairs(stack):\n q = collections.deque()\n # Put all values into queue from stack\n for i in range(len(stack)):\n q.append(stack.pop())\n # Put values back into stack from queue\n for i in range(len(q)):\n stack.append(q.pop())\n # Now, stack is reverse, put all values into queue from stack\n for i in range(len(stack)):\n q.append(stack.pop())\n # Swap pairs by appending the 2nd value before appending 1st value\n for i in range(len(q)):\n if len(q) == 0:\n break\n first = q.pop()\n if len(q) == 0: # case: odd number of values in stack\n stack.append(first)\n break\n second = q.pop()\n stack.append(second)\n stack.append(first)\n\n return stack\n"} +{"Prompt":"Given a string containing just the characters '', '', '', '', '' and '', determine if the input string is valid. The brackets must close in the correct order, and are all valid but and are not.","Completions":"def is_valid(s: str) -> bool:\n stack = []\n dic = {\")\": \"(\",\n \"}\": \"{\",\n \"]\": \"[\"}\n for char in s:\n if char in dic.values():\n stack.append(char)\n elif char in dic:\n if not stack or dic[char] != stack.pop():\n return False\n return not stack\n"} +{"Prompt":"Implementation of the MisraGries algorithm. Given a list of items and a value k, it returns the every item in the list that appears at least nk times, where n is the length of the array By default, k is set to 2, solving the majority problem. For the majority problem, this algorithm only guarantees that if there is an element that appears more than n2 times, it will be outputed. If there is no such element, any arbitrary element is returned by the algorithm. Therefore, we need to iterate through again at the end. But since we have filtred out the suspects, the memory complexity is significantly lower than it would be to create counter for every element in the list. For example: Input misrasgries1,4,4,4,5,4,4 Output '4':5 Input misrasgries0,0,0,1,1,1,1 Output '1':4 Input misrasgries0,0,0,0,1,1,1,2,2,3 Output '0':4,'1':3 Input misrasgries0,0,0,1,1,1 Output None MisraGries algorithm Keyword arguments: array list of integers k value of k default 2","Completions":"def misras_gries(array,k=2):\n \"\"\"Misra-Gries algorithm\n\n Keyword arguments:\n array -- list of integers\n k -- value of k (default 2)\n \"\"\"\n keys = {}\n for i in array:\n val = str(i)\n if val in keys:\n keys[val] = keys[val] + 1\n\n elif len(keys) < k - 1:\n keys[val] = 1\n\n else:\n for key in list(keys):\n keys[key] = keys[key] - 1\n if keys[key] == 0:\n del keys[key]\n\n suspects = keys.keys()\n frequencies = {}\n for suspect in suspects:\n freq = _count_frequency(array,int(suspect))\n if freq >= len(array) \/ k:\n frequencies[suspect] = freq\n\n return frequencies if len(frequencies) > 0 else None\n\n\ndef _count_frequency(array,element):\n return array.count(element)\n"} +{"Prompt":"Nonnegative 1sparse recovery problem. This algorithm assumes we have a non negative dynamic stream. Given a stream of tuples, where each tuple contains a number and a sign , it check if the stream is 1sparse, meaning if the elements in the stream cancel eacheother out in such a way that ther is only a unique number at the end. Examples: 1 Input: 4,'', 2,'',2,'',4,'',3,'',3,'', Output: 4 Comment: Since 2 and 3 gets removed. 2 Input: 2,'',2,'',2,'',2,'',2,'',2,'',2,'' Output: 2 Comment: No other numbers present 3 Input: 2,'',2,'',2,'',2,'',2,'',2,'',1,'' Output: None Comment: Not 1sparse 1sparse algorithm Keyword arguments: array stream of tuples Helper function to check that every entry in the list is either 0 or the same as the sum of signs Adds bit representation value to bitsum array","Completions":"def one_sparse(array):\n \"\"\"1-sparse algorithm\n\n Keyword arguments:\n array -- stream of tuples\n \"\"\"\n sum_signs = 0\n bitsum = [0]*32\n sum_values = 0\n for val,sign in array:\n if sign == \"+\":\n sum_signs += 1\n sum_values += val\n else:\n sum_signs -= 1\n sum_values -= val\n\n _get_bit_sum(bitsum,val,sign)\n\n if sum_signs > 0 and _check_every_number_in_bitsum(bitsum,sum_signs):\n return int(sum_values\/sum_signs)\n else:\n return None\n\n#Helper function to check that every entry in the list is either 0 or the same as the\n#sum of signs\ndef _check_every_number_in_bitsum(bitsum,sum_signs):\n for val in bitsum:\n if val != 0 and val != sum_signs :\n return False\n return True\n\n# Adds bit representation value to bitsum array\ndef _get_bit_sum(bitsum,val,sign):\n i = 0\n if sign == \"+\":\n while val:\n bitsum[i] += val & 1\n i +=1\n val >>=1\n else :\n while val:\n bitsum[i] -= val & 1\n i +=1\n val >>=1\n"} +{"Prompt":"Given two binary strings, return their sum also a binary string. For example, a 11 b 1 Return 100.","Completions":"def add_binary(a, b):\n s = \"\"\n c, i, j = 0, len(a)-1, len(b)-1\n zero = ord('0')\n while (i >= 0 or j >= 0 or c == 1):\n if (i >= 0):\n c += ord(a[i]) - zero\n i -= 1\n if (j >= 0):\n c += ord(b[j]) - zero\n j -= 1\n s = chr(c % 2 + zero) + s\n c \/\/= 2 \n \n return s\n"} +{"Prompt":"Atbash cipher is mapping the alphabet to it's reverse. So if we take a as it is the first letter, we change it to the last z. Example: Attack at dawn Zggzxp zg wzdm Complexity: On","Completions":"def atbash(s):\n translated = \"\"\n for i in range(len(s)):\n n = ord(s[i])\n \n if s[i].isalpha():\n \n if s[i].isupper():\n x = n - ord('A')\n translated += chr(ord('Z') - x)\n \n if s[i].islower():\n x = n - ord('a')\n translated += chr(ord('z') - x)\n else:\n translated += s[i]\n return translated"} +{"Prompt":"Given an api which returns an array of words and an array of symbols, display the word with their matched symbol surrounded by square brackets. If the word string matches more than one symbol, then choose the one with longest length. ex. 'Microsoft' matches 'i' and 'cro': Example: Words array: 'Amazon', 'Microsoft', 'Google' Symbols: 'i', 'Am', 'cro', 'Na', 'le', 'abc' Output: Amazon, Microsoft, Google My solutionWrong: I sorted the symbols array in descending order of length and ran loop over words array to find a symbol matchusing indexOf in javascript which worked. But I didn't make it through the interview, I am guessing my solution was On2 and they expected an efficient algorithm. output: 'Amazon', 'Microsoft', 'Google', 'Amazon', 'Microsoft', 'Google' reversely sort the symbols according to their lengths. once match, append the wordreplaced to res, process next word if this word matches no symbol, append it. Another approach is to use a Tree for the dictionary the symbols, and then match brute force. The complexity will depend on the dictionary; if all are suffixes of the other, it will be nm where m is the size of the dictionary. For example, in Python:","Completions":"from functools import reduce\n\n\ndef match_symbol(words, symbols):\n import re\n combined = []\n for s in symbols:\n for c in words:\n r = re.search(s, c)\n if r:\n combined.append(re.sub(s, \"[{}]\".format(s), c))\n return combined\n\ndef match_symbol_1(words, symbols):\n res = []\n # reversely sort the symbols according to their lengths.\n symbols = sorted(symbols, key=lambda _: len(_), reverse=True)\n for word in words:\n for symbol in symbols:\n word_replaced = ''\n # once match, append the `word_replaced` to res, process next word\n if word.find(symbol) != -1:\n word_replaced = word.replace(symbol, '[' + symbol + ']')\n res.append(word_replaced)\n break\n # if this word matches no symbol, append it.\n if word_replaced == '':\n res.append(word)\n return res\n\n\"\"\"\nAnother approach is to use a Tree for the dictionary (the symbols), and then\nmatch brute force. The complexity will depend on the dictionary;\nif all are suffixes of the other, it will be n*m\n(where m is the size of the dictionary). For example, in Python:\n\"\"\"\n\n\nclass TreeNode:\n def __init__(self):\n self.c = dict()\n self.sym = None\n\n\ndef bracket(words, symbols):\n root = TreeNode()\n for s in symbols:\n t = root\n for char in s:\n if char not in t.c:\n t.c[char] = TreeNode()\n t = t.c[char]\n t.sym = s\n result = dict()\n for word in words:\n i = 0\n symlist = list()\n while i < len(word):\n j, t = i, root\n while j < len(word) and word[j] in t.c:\n t = t.c[word[j]]\n if t.sym is not None:\n symlist.append((j + 1 - len(t.sym), j + 1, t.sym))\n j += 1\n i += 1\n if len(symlist) > 0:\n sym = reduce(lambda x, y: x if x[1] - x[0] >= y[1] - y[0] else y,\n symlist)\n result[word] = \"{}[{}]{}\".format(word[:sym[0]], sym[2],\n word[sym[1]:])\n return tuple(word if word not in result else result[word] for word in words)\n"} +{"Prompt":"Julius Caesar protected his confidential information by encrypting it using a cipher. Caesar's cipher shifts each letter by a number of letters. If the shift takes you past the end of the alphabet, just rotate back to the front of the alphabet. In the case of a rotation by 3, w, x, y and z would map to z, a, b and c. Original alphabet: abcdefghijklmnopqrstuvwxyz Alphabet rotated 3: defghijklmnopqrstuvwxyzabc","Completions":"def caesar_cipher(s, k):\n result = \"\"\n for char in s:\n n = ord(char)\n if 64 < n < 91:\n n = ((n - 65 + k) % 26) + 65\n if 96 < n < 123:\n n = ((n - 97 + k) % 26) + 97\n result = result + chr(n)\n return result\n"} +{"Prompt":"Algorithm that checks if a given string is a pangram or not","Completions":"def check_pangram(input_string):\n alphabet = \"abcdefghijklmnopqrstuvwxyz\"\n for ch in alphabet:\n if ch not in input_string.lower():\n return False\n return True "} +{"Prompt":"Implement strStr. Return the index of the first occurrence of needle in haystack, or 1 if needle is not part of haystack. Example 1: Input: haystack hello, needle ll Output: 2 Example 2: Input: haystack aaaaa, needle bba Output: 1 Reference: https:leetcode.comproblemsimplementstrstrdescription","Completions":"def contain_string(haystack, needle):\n if len(needle) == 0:\n return 0\n if len(needle) > len(haystack):\n return -1\n for i in range(len(haystack)):\n if len(haystack) - i < len(needle):\n return -1\n if haystack[i:i+len(needle)] == needle:\n return i\n return -1\n"} +{"Prompt":"Give a string s, count the number of nonempty contiguous substrings that have the same number of 0's and 1's, and all the 0's and all the 1's in these substrings are grouped consecutively. Substrings that occur multiple times are counted the number of times they occur. Example 1: Input: 00110011 Output: 6 Explanation: There are 6 substrings that have equal number of consecutive 1's and 0's: 0011, 01, 1100, 10, 0011, and 01. Notice that some of these substrings repeat and are counted the number of times they occur. Also, 00110011 is not a valid substring because all the 0's and 1's are not grouped together. Example 2: Input: 10101 Output: 4 Explanation: There are 4 substrings: 10, 01, 10, 01 that have equal number of consecutive 1's and 0's. Reference: https:leetcode.comproblemscountbinarysubstringsdescription","Completions":"def count_binary_substring(s):\n cur = 1\n pre = 0\n count = 0\n for i in range(1, len(s)):\n if s[i] != s[i - 1]:\n count = count + min(pre, cur)\n pre = cur\n cur = 1\n else:\n cur = cur + 1\n count = count + min(pre, cur)\n return count\n"} +{"Prompt":"Given an encoded string, return it's decoded string. The encoding rule is: kencodedstring, where the encodedstring inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer. You may assume that the input string is always valid; No extra white spaces, square brackets are wellformed, etc. Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, k. For example, there won't be input like 3a or 24. Examples: s 3a2bc, return aaabcbc. s 3a2c, return accaccacc. s 2abc3cdef, return abcabccdcdcdef. :type s: str :rtype: str","Completions":"# Given an encoded string, return it's decoded string.\n\n# The encoding rule is: k[encoded_string], where the encoded_string\n# inside the square brackets is being repeated exactly k times.\n# Note that k is guaranteed to be a positive integer.\n\n# You may assume that the input string is always valid; No extra white spaces,\n# square brackets are well-formed, etc.\n\n# Furthermore, you may assume that the original data does not contain any\n# digits and that digits are only for those repeat numbers, k.\n# For example, there won't be input like 3a or 2[4].\n\n# Examples:\n\n# s = \"3[a]2[bc]\", return \"aaabcbc\".\n# s = \"3[a2[c]]\", return \"accaccacc\".\n# s = \"2[abc]3[cd]ef\", return \"abcabccdcdcdef\".\n\ndef decode_string(s):\n \"\"\"\n :type s: str\n :rtype: str\n \"\"\"\n stack = []; cur_num = 0; cur_string = ''\n for c in s:\n if c == '[':\n stack.append((cur_string, cur_num))\n cur_string = ''\n cur_num = 0\n elif c == ']':\n prev_string, num = stack.pop()\n cur_string = prev_string + num * cur_string\n elif c.isdigit():\n cur_num = cur_num*10 + int(c)\n else:\n cur_string += c\n return cur_string\n"} +{"Prompt":"QUESTION: Given a string as your input, delete any reoccurring character, and return the new string. This is a Google warmup interview question that was asked duirng phone screening at my university. time complexity On","Completions":"# time complexity O(n)\ndef delete_reoccurring_characters(string):\n seen_characters = set()\n output_string = ''\n for char in string:\n if char not in seen_characters:\n seen_characters.add(char)\n output_string += char\n return output_string\n\n "} +{"Prompt":"Write a function that when given a URL as a string, parses out just the domain name and returns it as a string. Examples: domainnamehttp:github.comSaadBenn github domainnamehttp:www.zombiebites.com zombiebites domainnamehttps:www.cnet.com cnet Note: The idea is not to use any builtin libraries such as re regular expression or urlparse except .split builtin function Non pythonic way grab only the non https part grab the actual one depending on the len of the list case when www is in the url case when www is not in the url pythonic one liner","Completions":"# Non pythonic way\ndef domain_name_1(url):\n\t#grab only the non http(s) part\n full_domain_name = url.split('\/\/')[-1] \n #grab the actual one depending on the len of the list \n actual_domain = full_domain_name.split('.') \n \n # case when www is in the url\n if (len(actual_domain) > 2):\n return actual_domain[1] \n # case when www is not in the url\n return actual_domain[0]\n\n\n# pythonic one liner\ndef domain_name_2(url):\n return url.split(\"\/\/\")[-1].split(\"www.\")[-1].split(\".\")[0]\n\n"} +{"Prompt":"Design an algorithm to encode a list of strings to a string. The encoded mystring is then sent over the network and is decoded back to the original list of strings. Implement the encode and decode methods. Encodes a list of strings to a single string. :type strs: Liststr :rtype: str Decodes a single string to a list of strings. :type s: str :rtype: Liststr","Completions":"# Implement the encode and decode methods.\n\ndef encode(strs):\n \"\"\"Encodes a list of strings to a single string.\n :type strs: List[str]\n :rtype: str\n \"\"\"\n res = ''\n for string in strs.split():\n res += str(len(string)) + \":\" + string\n return res\n\ndef decode(s):\n \"\"\"Decodes a single string to a list of strings.\n :type s: str\n :rtype: List[str]\n \"\"\"\n strs = []\n i = 0\n while i < len(s):\n index = s.find(\":\", i)\n size = int(s[i:index])\n strs.append(s[index+1: index+1+size])\n i = index+1+size\n return strs"} +{"Prompt":"Given a string, find the first nonrepeating character in it and return it's index. If it doesn't exist, return 1. For example: s leetcode return 0. s loveleetcode, return 2. Reference: https:leetcode.comproblemsfirstuniquecharacterinastringdescription :type s: str :rtype: int","Completions":"def first_unique_char(s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n if (len(s) == 1):\n return 0\n ban = []\n for i in range(len(s)):\n if all(s[i] != s[k] for k in range(i + 1, len(s))) == True and s[i] not in ban:\n return i\n else:\n ban.append(s[i])\n return -1 \n"} +{"Prompt":"Write a function that returns an array containing the numbers from 1 to N, where N is the parametered value. N will never be less than 1. Replace certain values however if any of the following conditions are met: If the value is a multiple of 3: use the value 'Fizz' instead If the value is a multiple of 5: use the value 'Buzz' instead If the value is a multiple of 3 5: use the value 'FizzBuzz' instead There is no fancy algorithm to solve fizz buzz. Iterate from 1 through n Use the mod operator to determine if the current iteration is divisible by: 3 and 5 'FizzBuzz' 3 'Fizz' 5 'Buzz' else string of current iteration return the results Complexity: Time: On Space: On Validate the input Alternative solution","Completions":"\"\"\"\nThere is no fancy algorithm to solve fizz buzz.\n\nIterate from 1 through n\nUse the mod operator to determine if the current iteration is divisible by:\n3 and 5 -> 'FizzBuzz'\n3 -> 'Fizz'\n5 -> 'Buzz'\nelse -> string of current iteration\nreturn the results\nComplexity:\n\nTime: O(n)\nSpace: O(n)\n\"\"\"\n\ndef fizzbuzz(n):\n \n # Validate the input\n if n < 1:\n raise ValueError('n cannot be less than one')\n if n is None:\n raise TypeError('n cannot be None')\n \n result = []\n \n for i in range(1, n+1):\n if i%3 == 0 and i%5 == 0:\n result.append('FizzBuzz')\n elif i%3 == 0:\n result.append('Fizz')\n elif i%5 == 0:\n result.append('Buzz')\n else:\n result.append(i)\n return result\n\n# Alternative solution\ndef fizzbuzz_with_helper_func(n):\n return [fb(m) for m in range(1,n+1)]\n \ndef fb(m):\n r = (m % 3 == 0) * \"Fizz\" + (m % 5 == 0) * \"Buzz\"\n return r if r != \"\" else m\n"} +{"Prompt":"Given an array of strings, group anagrams together. For example, given: eat, tea, tan, ate, nat, bat, Return: ate, eat,tea, nat,tan, bat","Completions":"def group_anagrams(strs):\n d = {}\n ans = []\n k = 0\n for str in strs:\n sstr = ''.join(sorted(str))\n if sstr not in d:\n d[sstr] = k\n k += 1\n ans.append([])\n ans[-1].append(str)\n else:\n ans[d[sstr]].append(str)\n return ans\n"} +{"Prompt":"Given an integer, convert it to a roman numeral. Input is guaranteed to be within the range from 1 to 3999. :type num: int :rtype: str","Completions":"def int_to_roman(num):\n \"\"\"\n :type num: int\n :rtype: str\n \"\"\"\n m = [\"\", \"M\", \"MM\", \"MMM\"];\n c = [\"\", \"C\", \"CC\", \"CCC\", \"CD\", \"D\", \"DC\", \"DCC\", \"DCCC\", \"CM\"];\n x = [\"\", \"X\", \"XX\", \"XXX\", \"XL\", \"L\", \"LX\", \"LXX\", \"LXXX\", \"XC\"];\n i = [\"\", \"I\", \"II\", \"III\", \"IV\", \"V\", \"VI\", \"VII\", \"VIII\", \"IX\"];\n return m[num\/\/1000] + c[(num%1000)\/\/100] + x[(num%100)\/\/10] + i[num%10];\n"} +{"Prompt":"Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. For example, A man, a plan, a canal: Panama is a palindrome. race a car is not a palindrome. Note: Have you consider that the string might be empty? This is a good question to ask during an interview. For the purpose of this problem, we define empty string as valid palindrome. :type s: str :rtype: bool Here is a bunch of other variations of ispalindrome function. Variation 1: Find the reverse of the string and compare it with the original string Variation 2: Loop from the start to length2 and check the first character and last character and so on... for instance s0 compared with sn1, s1 sn2... Variation 3: Using stack idea. Note: We are assuming that we are just checking a one word string. To check if a complete sentence Remove punctuation, case sensitivity and spaces Variation 1 can also get rid of the stringreverse function and just do this return s s::1 in one line. Variation 2 Variation 3 Variation 4 using deque","Completions":"from string import ascii_letters\nfrom collections import deque\n\n\ndef is_palindrome(s):\n \"\"\"\n :type s: str\n :rtype: bool\n \"\"\"\n i = 0\n j = len(s)-1\n while i < j:\n while not s[i].isalnum():\n i += 1\n while not s[j].isalnum():\n j -= 1\n if s[i].lower() != s[j].lower():\n return False\n i, j = i+1, j-1\n return True\n\n\"\"\"\nHere is a bunch of other variations of is_palindrome function.\n\nVariation 1:\nFind the reverse of the string and compare it with the original string\n\nVariation 2:\nLoop from the start to length\/2 and check the first character and last character\nand so on... for instance s[0] compared with s[n-1], s[1] == s[n-2]...\n\nVariation 3:\nUsing stack idea. \n\nNote: We are assuming that we are just checking a one word string. To check if a complete sentence \n\"\"\" \ndef remove_punctuation(s):\n \"\"\"\n Remove punctuation, case sensitivity and spaces\n \"\"\"\n return \"\".join(i.lower() for i in s if i in ascii_letters)\n\n# Variation 1\ndef string_reverse(s):\n\treturn s[::-1]\n\ndef is_palindrome_reverse(s):\n\ts = remove_punctuation(s)\n\t\n\t# can also get rid of the string_reverse function and just do this return s == s[::-1] in one line.\n\tif (s == string_reverse(s)): \n\t\treturn True\n\treturn False\t\n\n\n# Variation 2\ndef is_palindrome_two_pointer(s):\n s = remove_punctuation(s)\n\t\n for i in range(0, len(s)\/\/2):\n if (s[i] != s[len(s) - i - 1]):\n return False\n return True\n\t\n\n# Variation 3\ndef is_palindrome_stack(s):\n stack = []\n s = remove_punctuation(s)\n\t\n for i in range(len(s)\/\/2, len(s)):\n stack.append(s[i])\n for i in range(0, len(s)\/\/2):\n if s[i] != stack.pop():\n return False\n return True\t\n\n# Variation 4 (using deque)\ndef is_palindrome_deque(s):\n s = remove_punctuation(s)\n deq = deque()\n for char in s:\n deq.appendleft(char)\n\n equal = True\n\n while len(deq) > 1 and equal:\n first = deq.pop()\n last = deq.popleft()\n if first != last :\n equal = False\n\n return equal\n"} +{"Prompt":"Given two strings s1 and s2, determine if s2 is a rotated version of s1. For example, isrotatedhello, llohe returns True isrotatedhello, helol returns False accepts two strings returns bool Reference: https:leetcode.comproblemsrotatestringdescription Another solution: brutal force Complexity: ON2","Completions":"def is_rotated(s1, s2):\n if len(s1) == len(s2):\n return s2 in s1 + s1\n else:\n return False\n\n\"\"\"\nAnother solution: brutal force\nComplexity: O(N^2)\n\"\"\"\ndef is_rotated_v1(s1, s2):\n if len(s1) != len(s2):\n return False\n if len(s1) == 0:\n return True\n\n for c in range(len(s1)):\n if all(s1[(c + i) % len(s1)] == s2[i] for i in range(len(s1))):\n return True\n return False\n"} +{"Prompt":"Initially, there is a Robot at position 0, 0. Given a sequence of its moves, judge if this robot makes a circle, which means it moves back to the original place. The move sequence is represented by a string. And each move is represent by a character. The valid robot moves are R Right, L Left, U Up and D down. The output should be true or false representing whether the robot makes a circle. Example 1: Input: UD Output: true Example 2: Input: LL Output: false","Completions":"def judge_circle(moves):\n dict_moves = {\n 'U' : 0,\n 'D' : 0,\n 'R' : 0,\n 'L' : 0\n }\n for char in moves:\n dict_moves[char] = dict_moves[char] + 1\n return dict_moves['L'] == dict_moves['R'] and dict_moves['U'] == dict_moves['D']\n"} +{"Prompt":"Given two strings text and pattern, return the list of start indexes in text that matches with the pattern using knuthmorrispratt algorithm. Args: text: Text to search pattern: Pattern to search in the text Returns: List of indices of patterns found Example: knuthmorrispratt'hello there hero!', 'he' 0, 7, 12 If idx is in the list, textidx : idx M matches with pattern. Time complexity of the algorithm is ONM, with N and M the length of text and pattern, respectively. making pi table finding pattern","Completions":"from typing import Sequence, List\n\ndef knuth_morris_pratt(text : Sequence, pattern : Sequence) -> List[int]:\n \"\"\"\n Given two strings text and pattern, return the list of start indexes in text that matches with the pattern\n using knuth_morris_pratt algorithm.\n\n Args:\n text: Text to search\n pattern: Pattern to search in the text\n Returns:\n List of indices of patterns found\n\n Example:\n >>> knuth_morris_pratt('hello there hero!', 'he')\n [0, 7, 12]\n\n If idx is in the list, text[idx : idx + M] matches with pattern.\n Time complexity of the algorithm is O(N+M), with N and M the length of text and pattern, respectively.\n \"\"\"\n n = len(text)\n m = len(pattern)\n pi = [0 for i in range(m)]\n i = 0\n j = 0\n # making pi table\n for i in range(1, m):\n while j and pattern[i] != pattern[j]:\n j = pi[j - 1]\n if pattern[i] == pattern[j]:\n j += 1\n pi[i] = j\n # finding pattern\n j = 0\n ret = []\n for i in range(n):\n while j and text[i] != pattern[j]:\n j = pi[j - 1]\n if text[i] == pattern[j]:\n j += 1\n if j == m:\n ret.append(i - m + 1)\n j = pi[j - 1]\n return ret\n"} +{"Prompt":"Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string . Example 1: Input: flower,flow,flight Output: fl Example 2: Input: dog,racecar,car Output: Explanation: There is no common prefix among the input strings. Reference: https:leetcode.comproblemslongestcommonprefixdescription First solution: Horizontal scanning Second solution: Vertical scanning Third solution: Divide and Conquer","Completions":"\"\"\"\nFirst solution: Horizontal scanning\n\"\"\"\ndef common_prefix(s1, s2):\n \"Return prefix common of 2 strings\"\n if not s1 or not s2:\n return \"\"\n k = 0\n while s1[k] == s2[k]:\n k = k + 1\n if k >= len(s1) or k >= len(s2):\n return s1[0:k]\n return s1[0:k]\n\ndef longest_common_prefix_v1(strs):\n if not strs:\n return \"\"\n result = strs[0]\n for i in range(len(strs)):\n result = common_prefix(result, strs[i])\n return result\n\n\"\"\"\nSecond solution: Vertical scanning\n\"\"\"\ndef longest_common_prefix_v2(strs):\n if not strs:\n return \"\"\n for i in range(len(strs[0])):\n for string in strs[1:]:\n if i == len(string) or string[i] != strs[0][i]:\n return strs[0][0:i]\n return strs[0]\n\n\"\"\"\nThird solution: Divide and Conquer\n\"\"\"\ndef longest_common_prefix_v3(strs):\n if not strs:\n return \"\"\n return longest_common(strs, 0, len(strs) -1)\n\ndef longest_common(strs, left, right):\n if left == right:\n return strs[left]\n mid = (left + right) \/\/ 2\n lcp_left = longest_common(strs, left, mid)\n lcp_right = longest_common(strs, mid + 1, right)\n return common_prefix(lcp_left, lcp_right)\n"} +{"Prompt":"Given string s, find the longest palindromic substring. Example1: input: dasdasdasdasdasdadsa output: asdadsa Example2: input: acdbbdaa output: dbbd Manacher's algorithm","Completions":"def longest_palindrome(s):\n if len(s) < 2:\n return s\n\n n_str = '#' + '#'.join(s) + '#'\n p = [0] * len(n_str)\n mx, loc = 0, 0\n index, maxlen = 0, 0\n for i in range(len(n_str)):\n if i < mx and 2 * loc - i < len(n_str):\n p[i] = min(mx - i, p[2 * loc - i])\n else:\n p[i] = 1\n\n while p[i] + i < len(n_str) and i - p[i] >= 0 and n_str[\n i - p[i]] == n_str[i + p[i]]:\n p[i] += 1\n\n if i + p[i] > mx:\n mx = i + p[i]\n loc = i\n\n if p[i] > maxlen:\n index = i\n maxlen = p[i]\n s = n_str[index - p[index] + 1:index + p[index]]\n return s.replace('#', '')\n"} +{"Prompt":"For a given string and dictionary, how many sentences can you make from the string, such that all the words are contained in the dictionary. eg: for given string appletablet apple, tablet applet, able, t apple, table, t app, let, able, t applet, app, let, apple, t, applet 3 thing, thing 1","Completions":"count = 0\n\n\ndef make_sentence(str_piece, dictionaries):\n global count\n if len(str_piece) == 0:\n return True\n for i in range(0, len(str_piece)):\n prefix, suffix = str_piece[0:i], str_piece[i:]\n if prefix in dictionaries:\n if suffix in dictionaries or make_sentence(suffix, dictionaries):\n count += 1\n return True\n"} +{"Prompt":"At a job interview, you are challenged to write an algorithm to check if a given string, s, can be formed from two other strings, part1 and part2. The restriction is that the characters in part1 and part2 are in the same order as in s. The interviewer gives you the following example and tells you to figure out the rest from the given test cases. 'codewars' is a merge from 'cdw' and 'oears': s: c o d e w a r s codewars part1: c d w cdw part2: o e a r s oears Recursive Solution An iterative approach","Completions":"# Recursive Solution\ndef is_merge_recursive(s, part1, part2):\n if not part1:\n return s == part2\n if not part2:\n return s == part1\n if not s:\n return part1 + part2 == ''\n if s[0] == part1[0] and is_merge_recursive(s[1:], part1[1:], part2):\n return True\n if s[0] == part2[0] and is_merge_recursive(s[1:], part1, part2[1:]):\n return True\n return False\n\n\n# An iterative approach\ndef is_merge_iterative(s, part1, part2):\n tuple_list = [(s, part1, part2)]\n while tuple_list:\n string, p1, p2 = tuple_list.pop() \n if string:\n if p1 and string[0] == p1[0]:\n tuple_list.append((string[1:], p1[1:], p2))\n if p2 and string[0] == p2[0]:\n tuple_list.append((string[1:], p1, p2[1:]))\n else:\n if not p1 and not p2:\n return True\n return False\n"} +{"Prompt":"Given two words word1 and word2, find the minimum number of steps required to make word1 and word2 the same, where in each step you can delete one character in either string. For example: Input: sea, eat Output: 2 Explanation: You need one step to make sea to ea and another step to make eat to ea. Reference: https:leetcode.comproblemsdeleteoperationfortwostringsdescription Finds minimum distance by getting longest common subsequence :type word1: str :type word2: str :rtype: int The length of longest common subsequence among the two given strings word1 and word2 Finds minimum distance in a dynamic programming manner TC: Olength1length2, SC: Olength1length2 :type word1: str :type word2: str :rtype: int","Completions":"def min_distance(word1, word2):\n \"\"\"\n Finds minimum distance by getting longest common subsequence\n\n :type word1: str\n :type word2: str\n :rtype: int\n \"\"\"\n return len(word1) + len(word2) - 2 * lcs(word1, word2, len(word1), len(word2))\n\ndef lcs(word1, word2, i, j):\n \"\"\"\n The length of longest common subsequence among the two given strings word1 and word2\n \"\"\"\n if i == 0 or j == 0:\n return 0\n if word1[i - 1] == word2[j - 1]:\n return 1 + lcs(word1, word2, i - 1, j - 1)\n return max(lcs(word1, word2, i - 1, j), lcs(word1, word2, i, j - 1))\n\ndef min_distance_dp(word1, word2):\n \"\"\"\n Finds minimum distance in a dynamic programming manner\n TC: O(length1*length2), SC: O(length1*length2)\n\n :type word1: str\n :type word2: str\n :rtype: int\n \"\"\"\n length1, length2 = len(word1)+1, len(word2)+1\n res = [[0 for _ in range(length2)] for _ in range(length1)]\n\n if length1 == length2:\n for i in range(1, length1):\n res[i][0], res[0][i] = i, i\n else:\n for i in range(length1):\n res[i][0] = i\n for i in range(length2):\n res[0][i] = i\n\n for i in range(1, length1):\n for j in range(1, length2):\n if word1[i-1] == word2[j-1]:\n res[i][j] = res[i-1][j-1]\n else:\n res[i][j] = min(res[i-1][j], res[i][j-1]) + 1\n\n return res[len(word1)][len(word2)]\n"} +{"Prompt":"Given two nonnegative integers num1 and num2 represented as strings, return the product of num1 and num2. Note: The length of both num1 and num2 is 110. Both num1 and num2 contains only digits 09. Both num1 and num2 does not contain any leading zero. You must not use any builtin BigInteger library or convert the inputs to integer directly.","Completions":"def multiply(num1: \"str\", num2: \"str\") -> \"str\":\n interm = []\n zero = ord('0')\n i_pos = 1\n for i in reversed(num1):\n j_pos = 1\n add = 0\n for j in reversed(num2):\n mult = (ord(i)-zero) * (ord(j)-zero) * j_pos * i_pos\n j_pos *= 10\n add += mult\n i_pos *= 10\n interm.append(add)\n return str(sum(interm))\n\n\nif __name__ == \"__main__\":\n print(multiply(\"1\", \"23\"))\n print(multiply(\"23\", \"23\"))\n print(multiply(\"100\", \"23\"))\n print(multiply(\"100\", \"10000\"))\n"} +{"Prompt":"Given two strings S and T, determine if they are both one edit distance apart. :type s: str :type t: str :rtype: bool","Completions":"def is_one_edit(s, t):\n \"\"\"\n :type s: str\n :type t: str\n :rtype: bool\n \"\"\"\n if len(s) > len(t):\n return is_one_edit(t, s)\n if len(t) - len(s) > 1 or t == s:\n return False\n for i in range(len(s)):\n if s[i] != t[i]:\n return s[i+1:] == t[i+1:] or s[i:] == t[i+1:]\n return True\n\n\ndef is_one_edit2(s, t):\n l1, l2 = len(s), len(t)\n if l1 > l2:\n return is_one_edit2(t, s)\n if len(t) - len(s) > 1 or t == s:\n return False\n for i in range(len(s)):\n if s[i] != t[i]:\n if l1 == l2:\n s = s[:i]+t[i]+s[i+1:] # modify\n else:\n s = s[:i]+t[i]+s[i:] # insertion\n break\n return s == t or s == t[:-1]\n"} +{"Prompt":"Given a string, check whether it is a panagram or not. A panagram is a sentence that uses every letter at least once. The most famous example is: he quick brown fox jumps over the lazy dog. Note: A panagram in one language isn't necessarily a panagram in another. This module assumes the english language. Hence, the Finnish panagram 'Trkylempijvongahdus' won't pass for a panagram despite being considered a perfect panagram in its language. However, the Swedish panagram 'Yxmrdaren Julia Blomqvist p fktning i Schweiz' will pass despite including letters not used in the english alphabet. This is because the Swedish alphabet only extends the Latin one. Returns whether the input string is an English panagram or not. Parameters: string str: A sentence in the form of a string. Returns: A boolean with the result.","Completions":"from string import ascii_lowercase\n\ndef panagram(string):\n \"\"\"\n Returns whether the input string is an English panagram or not.\n\n Parameters:\n string (str): A sentence in the form of a string.\n\n Returns:\n A boolean with the result.\n \"\"\"\n letters = set(ascii_lowercase)\n for c in string:\n try:\n letters.remove(c.lower())\n except:\n pass\n return len(letters) == 0"} +{"Prompt":"Following program is the python implementation of Rabin Karp Algorithm ord maps the character to a number subtract out the ASCII value of a to start the indexing at zero start index of current window end of index window remove left letter from hash value wordhash.movewindow","Completions":"# Following program is the python implementation of\n# Rabin Karp Algorithm\n\nclass RollingHash:\n def __init__(self, text, size_word):\n self.text = text\n self.hash = 0\n self.size_word = size_word\n\n for i in range(0, size_word):\n #ord maps the character to a number\n #subtract out the ASCII value of \"a\" to start the indexing at zero\n self.hash += (ord(self.text[i]) - ord(\"a\")+1)*(26**(size_word - i -1))\n\n #start index of current window\n self.window_start = 0\n #end of index window\n self.window_end = size_word\n\n def move_window(self):\n if self.window_end <= len(self.text) - 1:\n #remove left letter from hash value\n self.hash -= (ord(self.text[self.window_start]) - ord(\"a\")+1)*26**(self.size_word-1)\n self.hash *= 26\n self.hash += ord(self.text[self.window_end])- ord(\"a\")+1\n self.window_start += 1\n self.window_end += 1\n\n def window_text(self):\n return self.text[self.window_start:self.window_end]\n\ndef rabin_karp(word, text):\n if word == \"\" or text == \"\":\n return None\n if len(word) > len(text):\n return None\n\n rolling_hash = RollingHash(text, len(word))\n word_hash = RollingHash(word, len(word))\n #word_hash.move_window()\n\n for i in range(len(text) - len(word) + 1):\n if rolling_hash.hash == word_hash.hash:\n if rolling_hash.window_text() == word:\n return i\n rolling_hash.move_window()\n return None\n\n"} +{"Prompt":"Given two strings A and B, find the minimum number of times A has to be repeated such that B is a substring of it. If no such solution, return 1. For example, with A abcd and B cdabcdab. Return 3, because by repeating A three times abcdabcdabcd, B is a substring of it; and B is not a substring of A repeated two times abcdabcd. Note: The length of A and B will be between 1 and 10000. Reference: https:leetcode.comproblemsrepeatedstringmatchdescription","Completions":"def repeat_string(A, B):\n count = 1\n tmp = A\n max_count = (len(B) \/ len(A)) + 1\n while not(B in tmp):\n tmp = tmp + A\n if (count > max_count):\n count = -1\n break\n count = count + 1\n\n return count\n"} +{"Prompt":"Given a nonempty string check if it can be constructed by taking a substring of it and appending multiple copies of the substring together. For example: Input: abab Output: True Explanation: It's the substring ab twice. Input: aba Output: False Input: abcabcabcabc Output: True Explanation: It's the substring abc four times. Reference: https:leetcode.comproblemsrepeatedsubstringpatterndescription :type s: str :rtype: bool","Completions":"def repeat_substring(s):\n \"\"\"\n :type s: str\n :rtype: bool\n \"\"\"\n str = (s + s)[1:-1]\n return s in str\n"} +{"Prompt":"Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999.","Completions":"def roman_to_int(s:\"str\")->\"int\":\n number = 0\n roman = {'M':1000, 'D':500, 'C': 100, 'L':50, 'X':10, 'V':5, 'I':1}\n for i in range(len(s)-1):\n if roman[s[i]] < roman[s[i+1]]:\n number -= roman[s[i]]\n else:\n number += roman[s[i]]\n return number + roman[s[-1]]\n\n\nif __name__ == \"__main__\":\n roman = \"DCXXI\"\n print(roman_to_int(roman))\n"} +{"Prompt":"Given a strings s and int k, return a string that rotates k times k can be any positive integer. For example, rotatehello, 2 return llohe rotatehello, 5 return hello rotatehello, 6 return elloh rotatehello, 7 return llohe rotatehello, 102 return lohel","Completions":"def rotate(s, k):\n long_string = s * (k \/\/ len(s) + 2)\n if k <= len(s):\n return long_string[k:k + len(s)]\n else:\n return long_string[k-len(s):k]\n \ndef rotate_alt(string, k):\n k = k % len(string)\n return string[k:] + string[:k]\n"} +{"Prompt":"Write a function that does the following: Removes any duplicate query string parameters from the url Removes any query string parameters specified within the 2nd argument optional array An example: www.saadbenn.com?a1b2a2' returns 'www.saadbenn.com?a1b2' Here is a very nonpythonic grotesque solution add the '?' to our result if it is in the url logic for removing duplicate query strings build up the list by splitting the querystring using digits logic for checking whether we should add the string to our result A very friendly pythonic solution easy to follow Here is my friend's solution using python's builtin libraries","Completions":"from collections import defaultdict\nimport urllib\nimport urllib.parse\n\n# Here is a very non-pythonic grotesque solution\ndef strip_url_params1(url, params_to_strip=None):\n \n if not params_to_strip:\n params_to_strip = []\n if url:\n result = '' # final result to be returned\n tokens = url.split('?')\n domain = tokens[0]\n query_string = tokens[-1]\n result += domain\n # add the '?' to our result if it is in the url\n if len(tokens) > 1:\n result += '?'\n if not query_string:\n return url\n else:\n # logic for removing duplicate query strings\n # build up the list by splitting the query_string using digits\n key_value_string = []\n string = ''\n for char in query_string:\n if char.isdigit():\n key_value_string.append(string + char)\n string = ''\n else:\n string += char\n dict = defaultdict(int)\n # logic for checking whether we should add the string to our result\n for i in key_value_string:\n _token = i.split('=')\n if _token[0]:\n length = len(_token[0])\n if length == 1:\n if _token and (not(_token[0] in dict)):\n if params_to_strip:\n if _token[0] != params_to_strip[0]:\n dict[_token[0]] = _token[1]\n result = result + _token[0] + '=' + _token[1]\n else:\n if not _token[0] in dict:\n dict[_token[0]] = _token[1]\n result = result + _token[0] + '=' + _token[1]\n else:\n check = _token[0]\n letter = check[1]\n if _token and (not(letter in dict)):\n if params_to_strip:\n if letter != params_to_strip[0]:\n dict[letter] = _token[1]\n result = result + _token[0] + '=' + _token[1]\n else:\n if not letter in dict:\n dict[letter] = _token[1]\n result = result + _token[0] + '=' + _token[1]\n return result\n\n# A very friendly pythonic solution (easy to follow)\ndef strip_url_params2(url, param_to_strip=[]):\n if '?' not in url:\n return url\n\n queries = (url.split('?')[1]).split('&')\n queries_obj = [query[0] for query in queries]\n for i in range(len(queries_obj) - 1, 0, -1):\n if queries_obj[i] in param_to_strip or queries_obj[i] in queries_obj[0:i]:\n queries.pop(i)\n\n return url.split('?')[0] + '?' + '&'.join(queries)\n\n\n# Here is my friend's solution using python's builtin libraries\ndef strip_url_params3(url, strip=None):\n if not strip: strip = []\n \n parse = urllib.parse.urlparse(url)\n query = urllib.parse.parse_qs(parse.query)\n \n query = {k: v[0] for k, v in query.items() if k not in strip}\n query = urllib.parse.urlencode(query)\n new = parse._replace(query=query)\n \n return new.geturl()"} +{"Prompt":"The signup page required her to input a name and a password. However, the password must be strong. The website considers a password to be strong if it satisfies the following criteria: 1 Its length is at least 6. 2 It contains at least one digit. 3 It contains at least one lowercase English character. 4 It contains at least one uppercase English character. 5 It contains at least one special character. The special characters are: ! She typed a random string of length in the password field but wasn't sure if it was strong. Given the string she typed, can you find the minimum number of characters she must add to make her password strong? Note: Here's the set of types of characters in a form you can paste in your solution: numbers 0123456789 lowercase abcdefghijklmnopqrstuvwxyz uppercase ABCDEFGHIJKLMNOPQRSTUVWXYZ specialcharacters ! Input Format The first line contains an integer denoting the length of the string. The second line contains a string consisting of characters, the password typed by Louise. Each character is either a lowercaseuppercase English alphabet, a digit, or a special character. Sample Input 1: strongpassword3,Ab1 Output: 3 Because She can make the password strong by adding characters,for example, hk, turning the password into Ab1hk which is strong. 2 characters aren't enough since the length must be at least 6. Sample Output 2: strongpassword11,Algorithms Output: 1 Because the password isn't strong, but she can make it strong by adding a single digit. Return the minimum number of characters to make the password strong","Completions":"def strong_password(n, password):\n count_error = 0\n # Return the minimum number of characters to make the password strong\n if any(i.isdigit() for i in password) == False:\n count_error = count_error + 1\n if any(i.islower() for i in password) == False:\n count_error = count_error + 1\n if any(i.isupper() for i in password) == False:\n count_error = count_error + 1\n if any(i in '!@#$%^&*()-+' for i in password) == False:\n count_error = count_error + 1\n return max(count_error, 6 - n)\n"} +{"Prompt":"Given an array of words and a width maxWidth, format the text such that each line has exactly maxWidth characters and is fully left and right justified. You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces ' ' when necessary so that each line has exactly maxWidth characters. Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line do not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right. For the last line of text, it should be left justified and no extra space is inserted between words. Note: A word is defined as a character sequence consisting of nonspace characters only. Each word's length is guaranteed to be greater than 0 and not exceed maxWidth. The input array words contains at least one word. Example: Input: words What,must,be,acknowledgment,shall,be maxWidth 16 Output: What must be, acknowledgment , shall be :type words: list :type maxwidth: int :rtype: list here we have already got a row of str , then we should supplement enough ' ' to make sure the length is maxwidth. if the row is the last not the last row and more than one word row with only one word after a row , reset those value","Completions":"def text_justification(words, max_width):\n '''\n :type words: list\n :type max_width: int\n :rtype: list\n '''\n ret = [] # return value\n row_len = 0 # current length of strs in a row\n row_words = [] # current words in a row\n index = 0 # the index of current word in words\n is_first_word = True # is current word the first in a row\n while index < len(words):\n while row_len <= max_width and index < len(words):\n if len(words[index]) > max_width:\n raise ValueError(\"there exists word whose length is larger than max_width\")\n tmp = row_len\n row_words.append(words[index])\n tmp += len(words[index])\n if not is_first_word:\n tmp += 1 # except for the first word, each word should have at least a ' ' before it.\n if tmp > max_width:\n row_words.pop()\n break\n row_len = tmp\n index += 1\n is_first_word = False\n # here we have already got a row of str , then we should supplement enough ' ' to make sure the length is max_width.\n row = \"\"\n # if the row is the last\n if index == len(words):\n for word in row_words:\n row += (word + ' ')\n row = row[:-1]\n row += ' ' * (max_width - len(row))\n # not the last row and more than one word\n elif len(row_words) != 1:\n space_num = max_width - row_len\n space_num_of_each_interval = space_num \/\/ (len(row_words) - 1)\n space_num_rest = space_num - space_num_of_each_interval * (len(row_words) - 1)\n for j in range(len(row_words)):\n row += row_words[j]\n if j != len(row_words) - 1:\n row += ' ' * (1 + space_num_of_each_interval)\n if space_num_rest > 0:\n row += ' '\n space_num_rest -= 1\n # row with only one word\n else:\n row += row_words[0]\n row += ' ' * (max_width - len(row))\n ret.append(row)\n # after a row , reset those value\n row_len = 0\n row_words = []\n is_first_word = True\n return ret\n"} +{"Prompt":"International Morse Code defines a standard encoding where each letter is mapped to a series of dots and dashes, as follows: a maps to ., b maps to ..., c maps to .., and so on. For convenience, the full table for the 26 letters of the English alphabet is given below: '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':.. Now, given a list of words, each word can be written as a concatenation of the Morse code of each letter. For example, cab can be written as ......, which is the concatenation .. ... .. We'll call such a concatenation, the transformation of a word. Return the number of different transformations among all words we have. Example: Input: words gin, zen, gig, msg Output: 2 Explanation: The transformation of each word is: gin .... zen .... gig .... msg .... There are 2 different transformations, .... and .....","Completions":"morse_code = {\n 'a':\".-\",\n 'b':\"-...\",\n 'c':\"-.-.\",\n 'd': \"-..\",\n 'e':\".\",\n 'f':\"..-.\",\n 'g':\"--.\",\n 'h':\"....\",\n 'i':\"..\",\n 'j':\".---\",\n 'k':\"-.-\",\n 'l':\".-..\",\n 'm':\"--\",\n 'n':\"-.\",\n 'o':\"---\",\n 'p':\".--.\",\n 'q':\"--.-\",\n 'r':\".-.\",\n 's':\"...\",\n 't':\"-\",\n 'u':\"..-\",\n 'v':\"...-\",\n 'w':\".--\",\n 'x':\"-..-\",\n 'y':\"-.--\",\n 'z':\"--..\"\n}\ndef convert_morse_word(word):\n morse_word = \"\"\n word = word.lower()\n for char in word:\n morse_word = morse_word + morse_code[char]\n return morse_word\n\ndef unique_morse(words):\n unique_morse_word = []\n for word in words:\n morse_word = convert_morse_word(word)\n if morse_word not in unique_morse_word:\n unique_morse_word.append(morse_word)\n return len(unique_morse_word)\n"} +{"Prompt":"Create a function that will validate if given parameters are valid geographical coordinates. Valid coordinates look like the following: 23.32353342, 32.543534534. The return value should be either true or false. Latitude which is first float can be between 0 and 90, positive or negative. Longitude which is second float can be between 0 and 180, positive or negative. Coordinates can only contain digits, or one of the following symbols including space after comma , . There should be no space between the minus sign and the digit after it. Here are some valid coordinates: 23, 25 43.91343345, 143 4, 3 And some invalid ones: 23.234, 23.4234 N23.43345, E32.6457 6.325624, 43.34345.345 0, 1,2 I'll be adding my attempt as well as my friend's solution took us 1 hour my attempt friends solutions using regular expression","Completions":"# I'll be adding my attempt as well as my friend's solution (took us ~ 1 hour)\n\n# my attempt\nimport re\ndef is_valid_coordinates_0(coordinates):\n for char in coordinates:\n if not (char.isdigit() or char in ['-', '.', ',', ' ']):\n return False\n l = coordinates.split(\", \")\n if len(l) != 2:\n return False\n try:\n latitude = float(l[0])\n longitude = float(l[1])\n except:\n return False\n return -90 <= latitude <= 90 and -180 <= longitude <= 180\n\n# friends solutions\ndef is_valid_coordinates_1(coordinates):\n try:\n lat, lng = [abs(float(c)) for c in coordinates.split(',') if 'e' not in c]\n except ValueError:\n return False\n\n return lat <= 90 and lng <= 180\n\n# using regular expression\ndef is_valid_coordinates_regular_expression(coordinates):\n return bool(re.match(\"-?(\\d|[1-8]\\d|90)\\.?\\d*, -?(\\d|[1-9]\\d|1[0-7]\\d|180)\\.?\\d*$\", coordinates)) \n"} +{"Prompt":"Given a set of words without duplicates, find all word squares you can build from them. A sequence of words forms a valid word square if the kth row and column read the exact same string, where 0 k maxnumRows, numColumns. For example, the word sequence ball,area,lead,lady forms a word square because each word reads the same both horizontally and vertically. b a l l a r e a l e a d l a d y Note: There are at least 1 and at most 1000 words. All words will have the exact same length. Word length is at least 1 and at most 5. Each word contains only lowercase English alphabet az. Example 1: Input: area,lead,wall,lady,ball Output: wall, area, lead, lady , ball, area, lead, lady Explanation: The output consists of two word squares. The order of output does not matter just the order of words in each word square matters.","Completions":"# Given a set of words (without duplicates),\n# find all word squares you can build from them.\n\n# A sequence of words forms a valid word square\n# if the kth row and column read the exact same string,\n# where 0 \u2264 k < max(numRows, numColumns).\n\n# For example, the word sequence [\"ball\",\"area\",\"lead\",\"lady\"] forms\n# a word square because each word reads the same both horizontally\n# and vertically.\n\n# b a l l\n# a r e a\n# l e a d\n# l a d y\n# Note:\n# There are at least 1 and at most 1000 words.\n# All words will have the exact same length.\n# Word length is at least 1 and at most 5.\n# Each word contains only lowercase English alphabet a-z.\n\n# Example 1:\n\n# Input:\n# [\"area\",\"lead\",\"wall\",\"lady\",\"ball\"]\n\n# Output:\n# [\n # [ \"wall\",\n # \"area\",\n # \"lead\",\n # \"lady\"\n # ],\n # [ \"ball\",\n # \"area\",\n # \"lead\",\n # \"lady\"\n # ]\n# ]\n\n# Explanation:\n# The output consists of two word squares. The order of output does not matter\n# (just the order of words in each word square matters).\n\nimport collections\n\ndef word_squares(words):\n n = len(words[0])\n fulls = collections.defaultdict(list)\n for word in words:\n for i in range(n):\n fulls[word[:i]].append(word)\n\n def build(square):\n if len(square) == n:\n squares.append(square)\n return\n prefix = \"\"\n for k in range(len(square)):\n prefix += square[k][len(square)]\n for word in fulls[prefix]:\n build(square + [word])\n squares = []\n for word in words:\n build([word])\n return squares\n\n"} +{"Prompt":"Imports TreeNodes from tree.tree import TreeNode class AvlTreeobject: def initself: Root node of the tree. self.node None self.height 1 self.balance 0 def insertself, key: Create new node node TreeNodekey if not self.node: self.node node self.node.left AvlTree self.node.right AvlTree elif key self.node.val: self.node.left.insertkey elif key self.node.val: self.node.right.insertkey self.rebalance def rebalanceself: self.updateheightsrecursiveFalse self.updatebalancesFalse while self.balance 1 or self.balance 1: if self.balance 1: if self.node.left.balance 0: self.node.left.rotateleft self.updateheights self.updatebalances self.rotateright self.updateheights self.updatebalances if self.balance 1: if self.node.right.balance 0: self.node.right.rotateright self.updateheights self.updatebalances self.rotateleft self.updateheights self.updatebalances def updateheightsself, recursiveTrue: if self.node: if recursive: if self.node.left: self.node.left.updateheights if self.node.right: self.node.right.updateheights self.height 1 maxself.node.left.height, self.node.right.height else: self.height 1 def updatebalancesself, recursiveTrue: if self.node: if recursive: if self.node.left: self.node.left.updatebalances if self.node.right: self.node.right.updatebalances self.balance self.node.left.height self.node.right.height else: self.balance 0 def rotaterightself: newroot self.node.left.node newleftsub newroot.right.node oldroot self.node self.node newroot oldroot.left.node newleftsub newroot.right.node oldroot def rotateleftself: newroot self.node.right.node newleftsub newroot.left.node oldroot self.node self.node newroot oldroot.right.node newleftsub newroot.left.node oldroot def inordertraverseself: result if not self.node: return result result.extendself.node.left.inordertraverse result.appendself.node.key result.extendself.node.right.inordertraverse return result","Completions":"from tree.tree import TreeNode\n\n\nclass AvlTree(object):\n \"\"\"\n An avl tree.\n \"\"\"\n\n def __init__(self):\n # Root node of the tree.\n self.node = None\n self.height = -1\n self.balance = 0\n\n def insert(self, key):\n \"\"\"\n Insert new key into node\n \"\"\"\n # Create new node\n node = TreeNode(key)\n if not self.node:\n self.node = node\n self.node.left = AvlTree()\n self.node.right = AvlTree()\n elif key < self.node.val:\n self.node.left.insert(key)\n elif key > self.node.val:\n self.node.right.insert(key)\n self.re_balance()\n\n def re_balance(self):\n \"\"\"\n Re balance tree. After inserting or deleting a node,\n \"\"\"\n self.update_heights(recursive=False)\n self.update_balances(False)\n\n while self.balance < -1 or self.balance > 1:\n if self.balance > 1:\n if self.node.left.balance < 0:\n self.node.left.rotate_left()\n self.update_heights()\n self.update_balances()\n self.rotate_right()\n self.update_heights()\n self.update_balances()\n\n if self.balance < -1:\n if self.node.right.balance > 0:\n self.node.right.rotate_right()\n self.update_heights()\n self.update_balances()\n self.rotate_left()\n self.update_heights()\n self.update_balances()\n\n def update_heights(self, recursive=True):\n \"\"\"\n Update tree height\n \"\"\"\n if self.node:\n if recursive:\n if self.node.left:\n self.node.left.update_heights()\n if self.node.right:\n self.node.right.update_heights()\n\n self.height = 1 + max(self.node.left.height,\n self.node.right.height)\n else:\n self.height = -1\n\n def update_balances(self, recursive=True):\n \"\"\"\n Calculate tree balance factor\n\n \"\"\"\n if self.node:\n if recursive:\n if self.node.left:\n self.node.left.update_balances()\n if self.node.right:\n self.node.right.update_balances()\n\n self.balance = self.node.left.height - self.node.right.height\n else:\n self.balance = 0\n\n def rotate_right(self):\n \"\"\"\n Right rotation\n \"\"\"\n new_root = self.node.left.node\n new_left_sub = new_root.right.node\n old_root = self.node\n\n self.node = new_root\n old_root.left.node = new_left_sub\n new_root.right.node = old_root\n\n def rotate_left(self):\n \"\"\"\n Left rotation\n \"\"\"\n new_root = self.node.right.node\n new_left_sub = new_root.left.node\n old_root = self.node\n\n self.node = new_root\n old_root.right.node = new_left_sub\n new_root.left.node = old_root\n\n def in_order_traverse(self):\n \"\"\"\n In-order traversal of the tree\n \"\"\"\n result = []\n\n if not self.node:\n return result\n\n result.extend(self.node.left.in_order_traverse())\n result.append(self.node.key)\n result.extend(self.node.right.in_order_traverse())\n return result\n"} +{"Prompt":"Btree is used to disk operations. Each node except root contains at least t1 keys t children and at most 2t 1 keys 2t children where t is the degree of btree. It is not a kind of typical bst tree, because this tree grows up. Btree is balanced which means that the difference between height of left subtree and right subtree is at most 1. Complexity n number of elements t degree of tree Tree always has height at most logt n12 Algorithm Average Worst case Space On On Search Olog n Olog n Insert Olog n Olog n Delete Olog n Olog n Class of Node def initself: self.isleaf isleaf self.keys self.children def reprself: return idnode: 0.formatself.keys property def isleafself: Class of BTree def initself, tval2: self.minnumbersofkeys tval 1 self.maxnumberofkeys 2 tval 1 self.root Node def splitchildself, parent: Node, childindex: int: newrightchild Node halfmax self.maxnumberofkeys 2 child parent.childrenchildindex middlekey child.keyshalfmax newrightchild.keys child.keyshalfmax 1: child.keys child.keys:halfmax child is left child of parent after splitting if not child.isleaf: newrightchild.children child.childrenhalfmax 1: child.children child.children:halfmax 1 parent.keys.insertchildindex, middlekey parent.children.insertchildindex 1, newrightchild def insertkeyself, key: overflow decide which child is going to have a new key Finds key currentnode self.root while True: i lencurrentnode.keys 1 while i 0 and currentnode.keysi key: i 1 if i 0 and currentnode.keysi key: return True if currentnode.isleaf: return False currentnode currentnode.childreni 1 def removekeyself, key: self.removekeyself.root, key def removekeyself, node: Node, key bool: try: keyindex node.keys.indexkey if node.isleaf: node.keys.removekey else: self.removefromnonleafnodenode, keyindex return True except ValueError: key not found in node if node.isleaf: printKey not found. return False key not found else: i 0 numberofkeys lennode.keys decide in which subtree may be key while i numberofkeys and key node.keysi: i 1 actionperformed self.repairtreenode, i if actionperformed: return self.removekeynode, key else: return self.removekeynode.childreni, key def repairtreeself, node: Node, childindex: int bool: child node.childrenchildindex The leafnode is correct if self.minnumbersofkeys lenchild.keys self.maxnumberofkeys: return False if childindex 0 and lennode.childrenchildindex 1.keys self.minnumbersofkeys: self.rotaterightnode, childindex return True if childindex lennode.children 1 and lennode.childrenchildindex 1.keys self.minnumbersofkeys: 0 1 self.rotateleftnode, childindex return True if childindex 0: merge child with brother on the left self.mergenode, childindex 1, childindex else: merge child with brother on the right self.mergenode, childindex, childindex 1 return True def rotateleftself, parentnode: Node, childindex: int: newchildkey parentnode.keyschildindex newparentkey parentnode.childrenchildindex 1.keys.pop0 parentnode.childrenchildindex.keys.appendnewchildkey parentnode.keyschildindex newparentkey if not parentnode.childrenchildindex 1.isleaf: ownerlesschild parentnode.childrenchildindex 1.children.pop0 make ownerlesschild as a new biggest child with highest key transfer from right subtree to left subtree parentnode.childrenchildindex.children.appendownerlesschild def rotaterightself, parentnode: Node, childindex: int: parentkey parentnode.keyschildindex 1 newparentkey parentnode.childrenchildindex 1.keys.pop parentnode.childrenchildindex.keys.insert0, parentkey parentnode.keyschildindex 1 newparentkey if not parentnode.childrenchildindex 1.isleaf: ownerlesschild parentnode.childrenchildindex 1.children.pop make ownerlesschild as a new lowest child with lowest key transfer from left subtree to right subtree parentnode.childrenchildindex.children.insert 0, ownerlesschild def mergeself, parentnode: Node, tomergeindex: int, transferedchildindex: int: frommergenode parentnode.children.poptransferedchildindex parentkeytomerge parentnode.keys.poptomergeindex tomergenode parentnode.childrentomergeindex tomergenode.keys.appendparentkeytomerge tomergenode.keys.extendfrommergenode.keys if not tomergenode.isleaf: tomergenode.children.extendfrommergenode.children if parentnode self.root and not parentnode.keys: self.root tomergenode def removefromnonleafnodeself, node: Node, keyindex: int: key node.keyskeyindex leftsubtree node.childrenkeyindex if lenleftsubtree.keys self.minnumbersofkeys: largestkey self.findlargestanddeleteinleftsubtree leftsubtree elif lennode.childrenkeyindex 1.keys self.minnumbersofkeys: largestkey self.findlargestanddeleteinrightsubtree node.childrenkeyindex 1 else: self.mergenode, keyindex, keyindex 1 return self.removekeynode, key node.keyskeyindex largestkey def findlargestanddeleteinleftsubtreeself, node: Node: if node.isleaf: return node.keys.pop else: chindex lennode.children 1 self.repairtreenode, chindex largestkeyinsubtree self.findlargestanddeleteinleftsubtree node.childrenlennode.children 1 self.repairtreenode, chindex return largestkeyinsubtree def findlargestanddeleteinrightsubtreeself, node: Node: if node.isleaf: return node.keys.pop0 else: chindex 0 self.repairtreenode, chindex largestkeyinsubtree self.findlargestanddeleteinrightsubtree node.children0 self.repairtreenode, chindex return largestkeyinsubtree def traversetreeself: self.traversetreeself.root print def traversetreeself, node: Node: if node.isleaf: printnode.keys, end else: for i, key in enumeratenode.keys: self.traversetreenode.childreni printkey, end self.traversetreenode.children1","Completions":"class Node:\n \"\"\" Class of Node\"\"\"\n\n def __init__(self):\n # self.is_leaf = is_leaf\n self.keys = []\n self.children = []\n\n def __repr__(self):\n return \"\".format(self.keys)\n\n @property\n def is_leaf(self):\n \"\"\" Return if it is a leaf\"\"\"\n return len(self.children) == 0\n\n\nclass BTree:\n \"\"\" Class of BTree \"\"\"\n\n def __init__(self, t_val=2):\n self.min_numbers_of_keys = t_val - 1\n self.max_number_of_keys = 2 * t_val - 1\n\n self.root = Node()\n\n def _split_child(self, parent: Node, child_index: int):\n new_right_child = Node()\n half_max = self.max_number_of_keys \/\/ 2\n child = parent.children[child_index]\n middle_key = child.keys[half_max]\n new_right_child.keys = child.keys[half_max + 1:]\n child.keys = child.keys[:half_max]\n # child is left child of parent after splitting\n\n if not child.is_leaf:\n new_right_child.children = child.children[half_max + 1:]\n child.children = child.children[:half_max + 1]\n\n parent.keys.insert(child_index, middle_key)\n parent.children.insert(child_index + 1, new_right_child)\n\n def insert_key(self, key):\n \"\"\" overflow, tree increases in height \"\"\"\n if len(self.root.keys) >= self.max_number_of_keys:\n new_root = Node()\n new_root.children.append(self.root)\n self.root = new_root\n self._split_child(new_root, 0)\n self._insert_to_nonfull_node(self.root, key)\n else:\n self._insert_to_nonfull_node(self.root, key)\n\n def _insert_to_nonfull_node(self, node: Node, key):\n i = len(node.keys) - 1\n while i >= 0 and node.keys[i] >= key: # find position where insert key\n i -= 1\n\n if node.is_leaf:\n node.keys.insert(i + 1, key)\n else:\n # overflow\n if len(node.children[i + 1].keys) >= self.max_number_of_keys:\n self._split_child(node, i + 1)\n # decide which child is going to have a new key\n if node.keys[i + 1] < key:\n i += 1\n\n self._insert_to_nonfull_node(node.children[i + 1], key)\n\n def find(self, key) -> bool:\n \"\"\" Finds key \"\"\"\n current_node = self.root\n while True:\n i = len(current_node.keys) - 1\n while i >= 0 and current_node.keys[i] > key:\n i -= 1\n if i >= 0 and current_node.keys[i] == key:\n return True\n if current_node.is_leaf:\n return False\n current_node = current_node.children[i + 1]\n\n def remove_key(self, key):\n self._remove_key(self.root, key)\n\n def _remove_key(self, node: Node, key) -> bool:\n try:\n key_index = node.keys.index(key)\n if node.is_leaf:\n node.keys.remove(key)\n else:\n self._remove_from_nonleaf_node(node, key_index)\n return True\n\n except ValueError: # key not found in node\n if node.is_leaf:\n print(\"Key not found.\")\n return False # key not found\n else:\n i = 0\n number_of_keys = len(node.keys)\n # decide in which subtree may be key\n while i < number_of_keys and key > node.keys[i]:\n i += 1\n\n action_performed = self._repair_tree(node, i)\n if action_performed:\n return self._remove_key(node, key)\n else:\n return self._remove_key(node.children[i], key)\n\n def _repair_tree(self, node: Node, child_index: int) -> bool:\n child = node.children[child_index]\n # The leaf\/node is correct\n if self.min_numbers_of_keys < len(child.keys) <= self.max_number_of_keys:\n return False\n\n if child_index > 0 and len(node.children[child_index - 1].keys) > self.min_numbers_of_keys:\n self._rotate_right(node, child_index)\n return True\n\n if (child_index < len(node.children) - 1\n and len(node.children[child_index + 1].keys) > self.min_numbers_of_keys): # 0 <-- 1\n self._rotate_left(node, child_index)\n return True\n\n if child_index > 0:\n # merge child with brother on the left\n self._merge(node, child_index - 1, child_index)\n else:\n # merge child with brother on the right\n self._merge(node, child_index, child_index + 1)\n\n return True\n\n def _rotate_left(self, parent_node: Node, child_index: int):\n \"\"\"\n Take key from right brother of the child and transfer to the child\n \"\"\"\n new_child_key = parent_node.keys[child_index]\n new_parent_key = parent_node.children[child_index + 1].keys.pop(0)\n parent_node.children[child_index].keys.append(new_child_key)\n parent_node.keys[child_index] = new_parent_key\n\n if not parent_node.children[child_index + 1].is_leaf:\n ownerless_child = parent_node.children[child_index\n + 1].children.pop(0)\n # make ownerless_child as a new biggest child (with highest key)\n # -> transfer from right subtree to left subtree\n parent_node.children[child_index].children.append(ownerless_child)\n\n def _rotate_right(self, parent_node: Node, child_index: int):\n \"\"\"\n Take key from left brother of the child and transfer to the child\n \"\"\"\n parent_key = parent_node.keys[child_index - 1]\n new_parent_key = parent_node.children[child_index - 1].keys.pop()\n parent_node.children[child_index].keys.insert(0, parent_key)\n parent_node.keys[child_index - 1] = new_parent_key\n\n if not parent_node.children[child_index - 1].is_leaf:\n ownerless_child = parent_node.children[child_index\n - 1].children.pop()\n # make ownerless_child as a new lowest child (with lowest key)\n # -> transfer from left subtree to right subtree\n parent_node.children[child_index].children.insert(\n 0, ownerless_child)\n\n def _merge(self, parent_node: Node, to_merge_index: int, transfered_child_index: int):\n from_merge_node = parent_node.children.pop(transfered_child_index)\n parent_key_to_merge = parent_node.keys.pop(to_merge_index)\n to_merge_node = parent_node.children[to_merge_index]\n to_merge_node.keys.append(parent_key_to_merge)\n to_merge_node.keys.extend(from_merge_node.keys)\n\n if not to_merge_node.is_leaf:\n to_merge_node.children.extend(from_merge_node.children)\n\n if parent_node == self.root and not parent_node.keys:\n self.root = to_merge_node\n\n def _remove_from_nonleaf_node(self, node: Node, key_index: int):\n key = node.keys[key_index]\n left_subtree = node.children[key_index]\n if len(left_subtree.keys) > self.min_numbers_of_keys:\n largest_key = self._find_largest_and_delete_in_left_subtree(\n left_subtree)\n elif len(node.children[key_index + 1].keys) > self.min_numbers_of_keys:\n largest_key = self._find_largest_and_delete_in_right_subtree(\n node.children[key_index + 1])\n else:\n self._merge(node, key_index, key_index + 1)\n return self._remove_key(node, key)\n\n node.keys[key_index] = largest_key\n\n def _find_largest_and_delete_in_left_subtree(self, node: Node):\n if node.is_leaf:\n return node.keys.pop()\n else:\n ch_index = len(node.children) - 1\n self._repair_tree(node, ch_index)\n largest_key_in_subtree = self._find_largest_and_delete_in_left_subtree(\n node.children[len(node.children) - 1])\n # self._repair_tree(node, ch_index)\n return largest_key_in_subtree\n\n def _find_largest_and_delete_in_right_subtree(self, node: Node):\n if node.is_leaf:\n return node.keys.pop(0)\n else:\n ch_index = 0\n self._repair_tree(node, ch_index)\n largest_key_in_subtree = self._find_largest_and_delete_in_right_subtree(\n node.children[0])\n # self._repair_tree(node, ch_index)\n return largest_key_in_subtree\n\n def traverse_tree(self):\n self._traverse_tree(self.root)\n print()\n\n def _traverse_tree(self, node: Node):\n if node.is_leaf:\n print(node.keys, end=\" \")\n else:\n for i, key in enumerate(node.keys):\n self._traverse_tree(node.children[i])\n print(key, end=\" \")\n self._traverse_tree(node.children[-1])\n"} +{"Prompt":"type root: root class","Completions":"from tree.tree import TreeNode\n\n\ndef bin_tree_to_list(root):\n \"\"\"\n type root: root class\n \"\"\"\n if not root:\n return root\n root = bin_tree_to_list_util(root)\n while root.left:\n root = root.left\n return root\n\n\ndef bin_tree_to_list_util(root):\n if not root:\n return root\n if root.left:\n left = bin_tree_to_list_util(root.left)\n while left.right:\n left = left.right\n left.right = root\n root.left = left\n if root.right:\n right = bin_tree_to_list_util(root.right)\n while right.left:\n right = right.left\n right.left = root\n root.right = right\n return root\n\n\ndef print_tree(root):\n while root:\n print(root.val)\n root = root.right\n"} +{"Prompt":"Given an array where elements are sorted in ascending order, convert it to a height balanced BST.","Completions":"class TreeNode(object):\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\n\ndef array_to_bst(nums):\n if not nums:\n return None\n mid = len(nums)\/\/2\n node = TreeNode(nums[mid])\n node.left = array_to_bst(nums[:mid])\n node.right = array_to_bst(nums[mid+1:])\n return node\n"} +{"Prompt":"Implement Binary Search Tree. It has method: 1. Insert 2. Search 3. Size 4. Traversal Preorder, Inorder, Postorder Get the number of elements Using recursion. Complexity OlogN Search data in bst Using recursion. Complexity OlogN Insert data in bst Using recursion. Complexity OlogN Preorder, Postorder, Inorder traversal bst The tree is created for testing: 10 6 15 4 9 12 24 7 20 30 18","Completions":"import unittest\n\nclass Node(object):\n def __init__(self, data):\n self.data = data\n self.left = None\n self.right = None\n\nclass BST(object):\n def __init__(self):\n self.root = None\n\n def get_root(self):\n return self.root\n\n \"\"\"\n Get the number of elements\n Using recursion. Complexity O(logN)\n \"\"\"\n def size(self):\n return self.recur_size(self.root)\n\n def recur_size(self, root):\n if root is None:\n return 0\n else:\n return 1 + self.recur_size(root.left) + self.recur_size(root.right)\n\n \"\"\"\n Search data in bst\n Using recursion. Complexity O(logN)\n \"\"\"\n def search(self, data):\n return self.recur_search(self.root, data)\n\n def recur_search(self, root, data):\n if root is None:\n return False\n if root.data == data:\n return True\n elif data > root.data: # Go to right root\n return self.recur_search(root.right, data)\n else: # Go to left root\n return self.recur_search(root.left, data)\n\n \"\"\"\n Insert data in bst\n Using recursion. Complexity O(logN)\n \"\"\"\n def insert(self, data):\n if self.root:\n return self.recur_insert(self.root, data)\n else:\n self.root = Node(data)\n return True\n\n def recur_insert(self, root, data):\n if root.data == data: # The data is already there\n return False\n elif data < root.data: # Go to left root\n if root.left: # If left root is a node\n return self.recur_insert(root.left, data)\n else: # left root is a None\n root.left = Node(data)\n return True\n else: # Go to right root\n if root.right: # If right root is a node\n return self.recur_insert(root.right, data)\n else:\n root.right = Node(data)\n return True\n\n \"\"\"\n Preorder, Postorder, Inorder traversal bst\n \"\"\"\n def preorder(self, root):\n if root:\n print(str(root.data), end = ' ')\n self.preorder(root.left)\n self.preorder(root.right)\n\n def inorder(self, root):\n if root:\n self.inorder(root.left)\n print(str(root.data), end = ' ')\n self.inorder(root.right)\n\n def postorder(self, root):\n if root:\n self.postorder(root.left)\n self.postorder(root.right)\n print(str(root.data), end = ' ')\n\n\"\"\"\n The tree is created for testing:\n\n 10\n \/ \\\n 6 15\n \/ \\ \/ \\\n 4 9 12 24\n \/ \/ \\\n 7 20 30\n \/\n 18\n\"\"\"\n\nclass TestSuite(unittest.TestCase):\n def setUp(self):\n self.tree = BST()\n self.tree.insert(10)\n self.tree.insert(15)\n self.tree.insert(6)\n self.tree.insert(4)\n self.tree.insert(9)\n self.tree.insert(12)\n self.tree.insert(24)\n self.tree.insert(7)\n self.tree.insert(20)\n self.tree.insert(30)\n self.tree.insert(18)\n\n def test_search(self):\n self.assertTrue(self.tree.search(24))\n self.assertFalse(self.tree.search(50))\n\n def test_size(self):\n self.assertEqual(11, self.tree.size())\n\nif __name__ == '__main__':\n unittest.main()\n"} +{"Prompt":"Given a nonempty binary search tree and a target value, find the value in the BST that is closest to the target. Note: Given target value is a floating point. You are guaranteed to have only one unique value in the BST that is closest to the target. Definition for a binary tree node. class TreeNodeobject: def initself, x: self.val x self.left None self.right None :type root: TreeNode :type target: float :rtype: int","Completions":"# Given a non-empty binary search tree and a target value,\n# find the value in the BST that is closest to the target.\n\n# Note:\n# Given target value is a floating point.\n# You are guaranteed to have only one unique value in the BST\n# that is closest to the target.\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\ndef closest_value(root, target):\n \"\"\"\n :type root: TreeNode\n :type target: float\n :rtype: int\n \"\"\"\n a = root.val\n kid = root.left if target < a else root.right\n if not kid:\n return a\n b = closest_value(kid, target)\n return min((a,b), key=lambda x: abs(target-x))\n"} +{"Prompt":"Write a function countleftnode returns the number of left children in the tree. For example: the following tree has four left children the nodes storing the values 6, 3, 7, and 10: 9 6 12 3 8 10 15 7 18 countleftnode 4 The tree is created for testing: 9 6 12 3 8 10 15 7 18 countleftnode 4","Completions":"import unittest\nfrom bst import Node\nfrom bst import bst\n\ndef count_left_node(root):\n if root is None:\n return 0\n elif root.left is None:\n return count_left_node(root.right)\n else:\n return 1 + count_left_node(root.left) + count_left_node(root.right)\n\n\"\"\"\n The tree is created for testing:\n\n 9\n \/ \\\n 6 12\n \/ \\ \/ \\\n 3 8 10 15\n \/ \\\n 7 18\n\n count_left_node = 4\n\n\"\"\"\n\nclass TestSuite(unittest.TestCase):\n def setUp(self):\n self.tree = bst()\n self.tree.insert(9)\n self.tree.insert(6)\n self.tree.insert(12)\n self.tree.insert(3)\n self.tree.insert(8)\n self.tree.insert(10)\n self.tree.insert(15)\n self.tree.insert(7)\n self.tree.insert(18)\n\n def test_count_left_node(self):\n self.assertEqual(4, count_left_node(self.tree.root))\n\nif __name__ == '__main__':\n unittest.main()\n"} +{"Prompt":"Given a root node reference of a BST and a key, delete the node with the given key in the BST. Return the root node reference possibly updated of the BST. Basically, the deletion can be divided into two stages: Search for a node to remove. If the node is found, delete the node. Note: Time complexity should be Oheight of tree. Example: root 5,3,6,2,4,null,7 key 3 5 3 6 2 4 7 Given key to delete is 3. So we find the node with value 3 and delete it. One valid answer is 5,4,6,2,null,null,7, shown in the following BST. 5 4 6 2 7 Another valid answer is 5,2,6,null,4,null,7. 5 2 6 4 7 :type root: TreeNode :type key: int :rtype: TreeNode Find the right most leaf of the left subtree Attach right child to the right of that leaf Return left child instead of root, a.k.a delete root If left or right child got deleted, the returned root is the child of the deleted node.","Completions":"class Solution(object):\n def delete_node(self, root, key):\n \"\"\"\n :type root: TreeNode\n :type key: int\n :rtype: TreeNode\n \"\"\"\n if not root: return None\n\n if root.val == key:\n if root.left:\n # Find the right most leaf of the left sub-tree\n left_right_most = root.left\n while left_right_most.right:\n left_right_most = left_right_most.right\n # Attach right child to the right of that leaf\n left_right_most.right = root.right\n # Return left child instead of root, a.k.a delete root\n return root.left\n else:\n return root.right\n # If left or right child got deleted, the returned root is the child of the deleted node.\n elif root.val > key:\n root.left = self.deleteNode(root.left, key)\n else:\n root.right = self.deleteNode(root.right, key)\n return root\n"} +{"Prompt":"Write a function depthSum returns the sum of the values stored in a binary search tree of integers weighted by the depth of each value. For example: 9 6 12 3 8 10 15 7 18 depthsum 19 2612 3381015 4718 The tree is created for testing: 9 6 12 3 8 10 15 7 18 depthsum 19 2612 3381015 4718","Completions":"import unittest\nfrom bst import Node\nfrom bst import bst\n\ndef depth_sum(root, n):\n if root:\n return recur_depth_sum(root, 1)\n\ndef recur_depth_sum(root, n):\n if root is None:\n return 0\n elif root.left is None and root.right is None:\n return root.data * n\n else:\n return n * root.data + recur_depth_sum(root.left, n+1) + recur_depth_sum(root.right, n+1)\n\n\"\"\"\n The tree is created for testing:\n\n 9\n \/ \\\n 6 12\n \/ \\ \/ \\\n 3 8 10 15\n \/ \\\n 7 18\n\n depth_sum = 1*9 + 2*(6+12) + 3*(3+8+10+15) + 4*(7+18)\n\n\"\"\"\n\nclass TestSuite(unittest.TestCase):\n def setUp(self):\n self.tree = bst()\n self.tree.insert(9)\n self.tree.insert(6)\n self.tree.insert(12)\n self.tree.insert(3)\n self.tree.insert(8)\n self.tree.insert(10)\n self.tree.insert(15)\n self.tree.insert(7)\n self.tree.insert(18)\n\n def test_depth_sum(self):\n self.assertEqual(253, depth_sum(self.tree.root, 4))\n\nif __name__ == '__main__':\n unittest.main()\n"} +{"Prompt":"Write a function height returns the height of a tree. The height is defined to be the number of levels. The empty tree has height 0, a tree of one node has height 1, a root node with one or two leaves as children has height 2, and so on For example: height of tree is 4 9 6 12 3 8 10 15 7 18 height 4 The tree is created for testing: 9 6 12 3 8 10 15 7 18 countleftnode 4","Completions":"import unittest\nfrom bst import Node\nfrom bst import bst\n\ndef height(root):\n if root is None:\n return 0\n else:\n return 1 + max(height(root.left), height(root.right))\n\n\"\"\"\n The tree is created for testing:\n\n 9\n \/ \\\n 6 12\n \/ \\ \/ \\\n 3 8 10 15\n \/ \\\n 7 18\n\n count_left_node = 4\n\n\"\"\"\n\nclass TestSuite(unittest.TestCase):\n def setUp(self):\n self.tree = bst()\n self.tree.insert(9)\n self.tree.insert(6)\n self.tree.insert(12)\n self.tree.insert(3)\n self.tree.insert(8)\n self.tree.insert(10)\n self.tree.insert(15)\n self.tree.insert(7)\n self.tree.insert(18)\n\n def test_height(self):\n self.assertEqual(4, height(self.tree.root))\n\nif __name__ == '__main__':\n unittest.main()\n"} +{"Prompt":"Given a binary tree, determine if it is a valid binary search tree BST. Assume a BST is defined as follows: The left subtree of a node contains only nodes with keys less than the node's key. The right subtree of a node contains only nodes with keys greater than the node's key. Both the left and right subtrees must also be binary search trees. Example 1: 2 1 3 Binary tree 2,1,3, return true. Example 2: 1 2 3 Binary tree 1,2,3, return false. :type root: TreeNode :rtype: bool","Completions":"def is_bst(root):\n \"\"\"\n :type root: TreeNode\n :rtype: bool\n \"\"\"\n\n stack = []\n pre = None\n \n while root or stack:\n while root:\n stack.append(root)\n root = root.left\n root = stack.pop()\n if pre and root.val <= pre.val:\n return False\n pre = root\n root = root.right\n\n return True\n"} +{"Prompt":":type root: TreeNode :type k: int :rtype: int","Completions":"class Node:\n\n def __init__(self, val, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\n\ndef kth_smallest(root, k):\n stack = []\n while root or stack:\n while root:\n stack.append(root)\n root = root.left\n root = stack.pop()\n k -= 1\n if k == 0:\n break\n root = root.right\n return root.val\n\n\nclass Solution(object):\n def kth_smallest(self, root, k):\n \"\"\"\n :type root: TreeNode\n :type k: int\n :rtype: int\n \"\"\"\n count = []\n self.helper(root, count)\n return count[k-1]\n\n def helper(self, node, count):\n if not node:\n return\n\n self.helper(node.left, count)\n count.append(node.val)\n self.helper(node.right, count)\n\nif __name__ == '__main__':\n n1 = Node(100)\n n2 = Node(50)\n n3 = Node(150)\n n4 = Node(25)\n n5 = Node(75)\n n6 = Node(125)\n n7 = Node(175)\n n1.left, n1.right = n2, n3\n n2.left, n2.right = n4, n5\n n3.left, n3.right = n6, n7\n print(kth_smallest(n1, 2))\n print(Solution().kth_smallest(n1, 2))\n"} +{"Prompt":"Given a binary search tree BST, find the lowest common ancestor LCA of two given nodes in the BST. According to the definition of LCA on Wikipedia: The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants where we allow a node to be a descendant of itself. 6 2 8 0 4 7 9 3 5 For example, the lowest common ancestor LCA of nodes 2 and 8 is 6. Another example is LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition. :type root: Node :type p: Node :type q: Node :rtype: Node","Completions":"def lowest_common_ancestor(root, p, q):\n \"\"\"\n :type root: Node\n :type p: Node\n :type q: Node\n :rtype: Node\n \"\"\"\n while root:\n if p.val > root.val < q.val:\n root = root.right\n elif p.val < root.val > q.val:\n root = root.left\n else:\n return root\n"} +{"Prompt":"Write a function numempty returns returns the number of empty branches in a tree. Function should count the total number of empty branches among the nodes of the tree. A leaf node has two empty branches. In the case, if root is None, it considered as a 1 empty branch For example: the following tree has 10 empty branch is empty branch 9 6 12 3 8 10 15 7 18 emptybranch 10 The tree is created for testing: 9 6 12 3 8 10 15 7 18 numempty 10","Completions":"import unittest\nfrom bst import Node\nfrom bst import bst\n\ndef num_empty(root):\n if root is None:\n return 1\n elif root.left is None and root.right:\n return 1 + num_empty(root.right)\n elif root.right is None and root.left:\n return 1 + num_empty(root.left)\n else:\n return num_empty(root.left) + num_empty(root.right)\n\n\"\"\"\n The tree is created for testing:\n\n 9\n \/ \\\n 6 12\n \/ \\ \/ \\\n 3 8 10 15\n \/ \\\n 7 18\n\n num_empty = 10\n\n\"\"\"\n\nclass TestSuite(unittest.TestCase):\n def setUp(self):\n self.tree = bst()\n self.tree.insert(9)\n self.tree.insert(6)\n self.tree.insert(12)\n self.tree.insert(3)\n self.tree.insert(8)\n self.tree.insert(10)\n self.tree.insert(15)\n self.tree.insert(7)\n self.tree.insert(18)\n\n def test_num_empty(self):\n self.assertEqual(10, num_empty(self.tree.root))\n\nif __name__ == '__main__':\n unittest.main()\n"} +{"Prompt":"Given n, how many structurally unique BST's binary search trees that store values 1...n? For example, Given n 3, there are a total of 5 unique BST's. 1 3 3 2 1 3 2 1 1 3 2 2 1 2 3 Taking 1n as root respectively: 1 as root: of trees F0 Fn1 F0 1 2 as root: of trees F1 Fn2 3 as root: of trees F2 Fn3 ... n1 as root: of trees Fn2 F1 n as root: of trees Fn1 F0 So, the formulation is: Fn F0 Fn1 F1 Fn2 F2 Fn3 ... Fn2 F1 Fn1 F0 :type n: int :rtype: int","Completions":"\"\"\"\nTaking 1~n as root respectively:\n1 as root: # of trees = F(0) * F(n-1) \/\/ F(0) == 1\n2 as root: # of trees = F(1) * F(n-2)\n3 as root: # of trees = F(2) * F(n-3)\n...\nn-1 as root: # of trees = F(n-2) * F(1)\nn as root: # of trees = F(n-1) * F(0)\n\nSo, the formulation is:\nF(n) = F(0) * F(n-1) + F(1) * F(n-2) + F(2) * F(n-3) + ... + F(n-2) * F(1) + F(n-1) * F(0)\n\"\"\"\n\ndef num_trees(n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n dp = [0] * (n+1)\n dp[0] = 1\n dp[1] = 1\n for i in range(2, n+1):\n for j in range(i+1):\n dp[i] += dp[i-j] * dp[j-1]\n return dp[-1]\n"} +{"Prompt":"Given two arrays representing preorder and postorder traversal of a full binary tree, construct the binary tree and print the inorder traversal of the tree. A full binary tree has either 0 or 2 children. Algorithm: 1. Assign the first element of preorder array as root of the tree. 2. Find the same element in the postorder array and divide the postorder array into left and right subtree. 3. Repeat the above steps for all the elements and construct the tree. Eg: pre 1, 2, 4, 8, 9, 5, 3, 6, 7 post 8, 9, 4, 5, 2, 6, 7, 3, 1 Tree: 1 2 3 4 5 6 7 8 9 Output: 8 4 9 2 5 1 6 3 7 Recursive function that constructs tree from preorder and postorder array. preIndex is a global variable that keeps track of the index in preorder array. preorder and postorder array are represented are pre and post respectively. low and high are the indices for the postorder array. Base case If only one element in the subarray return root Find the next element of pre in post Use index of element present in postorder to divide postorder array to two parts: left subtree and right subtree Main Function that will construct the full binary tree from given preorder and postorder array. Prints the tree constructed in inorder format","Completions":"class TreeNode:\n\n def __init__(self, val, left = None, right = None):\n self.val = val\n self.left = left\n self.right = right\n\npre_index = 0\n \ndef construct_tree_util(pre: list, post: list, low: int, high: int, size: int):\n \"\"\"\n Recursive function that constructs tree from preorder and postorder array.\n \n preIndex is a global variable that keeps track of the index in preorder\n array.\n preorder and postorder array are represented are pre[] and post[] respectively.\n low and high are the indices for the postorder array.\n \"\"\"\n\n global pre_index\n\n if pre_index == -1:\n pre_index = 0\n \n \n #Base case\n if(pre_index >= size or low > high):\n return None\n\n root = TreeNode(pre[pre_index])\n pre_index += 1\n\n #If only one element in the subarray return root\n if(low == high or pre_index >= size):\n return root\n\n #Find the next element of pre[] in post[]\n i = low\n while i <= high:\n if(pre[pre_index] == post[i]):\n break\n\n i += 1\n\n #Use index of element present in postorder to divide postorder array\n #to two parts: left subtree and right subtree\n if(i <= high):\n root.left = construct_tree_util(pre, post, low, i, size)\n root.right = construct_tree_util(pre, post, i+1, high, size)\n\n return root\n\n\ndef construct_tree(pre: list, post: list, size: int):\n \"\"\"\n Main Function that will construct the full binary tree from given preorder\n and postorder array.\n \"\"\"\n\n global pre_index\n root = construct_tree_util(pre, post, 0, size-1, size)\n\n return print_inorder(root)\n\n\n\ndef print_inorder(root: TreeNode, result = None):\n \"\"\"\n Prints the tree constructed in inorder format\n \"\"\"\n if root is None:\n return []\n if result is None: \n result = []\n \n print_inorder(root.left, result)\n result.append(root.val)\n print_inorder(root.right, result)\n return result\n\nif __name__ == '__main__':\n pre = [1, 2, 4, 5, 3, 6, 7]\n post = [4, 5, 2, 6, 7, 3, 1]\n size = len(pre)\n\n result = construct_tree(pre, post, size)\n\n print(result)\n"} +{"Prompt":"Given a binary tree, find the deepest node that is the left child of its parent node. Example: 1 2 3 4 5 6 7 should return 4.","Completions":"# Given a binary tree, find the deepest node\n# that is the left child of its parent node.\n\n# Example:\n\n # 1\n # \/ \\\n # 2 3\n # \/ \\ \\\n# 4 5 6\n # \\\n # 7\n# should return 4.\n\nfrom tree.tree import TreeNode\n\n\nclass DeepestLeft:\n def __init__(self):\n self.depth = 0\n self.Node = None\n\n\ndef find_deepest_left(root, is_left, depth, res):\n if not root:\n return\n if is_left and depth > res.depth:\n res.depth = depth\n res.Node = root\n find_deepest_left(root.left, True, depth + 1, res)\n find_deepest_left(root.right, False, depth + 1, res)\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.right = TreeNode(6)\n root.right.right.right = TreeNode(7)\n\n res = DeepestLeft()\n find_deepest_left(root, True, 1, res)\n if res.Node:\n print(res.Node.val)\n"} +{"Prompt":"Fenwick Tree Binary Indexed Tree Consider we have an array arr0 . . . n1. We would like to 1. Compute the sum of the first i elements. 2. Modify the value of a specified element of the array arri x where 0 i n1. A simple solution is to run a loop from 0 to i1 and calculate the sum of the elements. To update a value, simply do arri x. The first operation takes On time and the second operation takes O1 time. Another simple solution is to create an extra array and store the sum of the first ith elements at the ith index in this new array. The sum of a given range can now be calculated in O1 time, but the update operation takes On time now. This works well if there are a large number of query operations but a very few number of update operations. There are two solutions that can perform both the query and update operations in Ologn time. 1. Fenwick Tree 2. Segment Tree Compared with Segment Tree, Binary Indexed Tree requires less space and is easier to implement. Returns sum of arr0..index. This function assumes that the array is preprocessed and partial sums of array elements are stored in bittree. index in bittree is 1 more than the index in arr Traverse ancestors of bittreeindex Add current element of bittree to sum Move index to parent node in getSum View Updates a node in Binary Index Tree bittree at given index in bittree. The given value 'val' is added to bittreei and all of its ancestors in tree. index in bitree is 1 more than the index in arr Traverse all ancestors and add 'val' Add 'val' to current node of bittree Update index to that of parent in update View Constructs and returns a Binary Indexed Tree for given array of size n. Create and initialize bitree as 0 Store the actual values in bitree using update","Completions":"class Fenwick_Tree(object):\n def __init__(self, freq):\n self.arr = freq\n self.n = len(freq)\n \n def get_sum(self, bit_tree, i):\n \"\"\"\n Returns sum of arr[0..index]. This function assumes that the array is preprocessed and partial sums of array elements are stored in bit_tree[]. \n \"\"\"\n\n s = 0\n \n # index in bit_tree[] is 1 more than the index in arr[] \n i = i+1\n \n # Traverse ancestors of bit_tree[index] \n while i > 0: \n \n # Add current element of bit_tree to sum \n s += bit_tree[i] \n \n # Move index to parent node in getSum View \n i -= i & (-i) \n return s \n \n def update_bit(self, bit_tree, i, v):\n \"\"\"\n Updates a node in Binary Index Tree (bit_tree) at given index in bit_tree. The given value 'val' is added to bit_tree[i] and all of its ancestors in tree. \n \"\"\"\n \n # index in bit_ree[] is 1 more than the index in arr[] \n i += 1\n \n # Traverse all ancestors and add 'val' \n while i <= self.n: \n \n # Add 'val' to current node of bit_tree \n bit_tree[i] += v \n \n # Update index to that of parent in update View \n i += i & (-i) \n \n \n def construct(self):\n \"\"\"\n Constructs and returns a Binary Indexed Tree for given array of size n. \n \"\"\"\n \n # Create and initialize bit_ree[] as 0 \n bit_tree = [0]*(self.n+1) \n \n # Store the actual values in bit_ree[] using update() \n for i in range(self.n): \n self.update_bit(bit_tree, i, self.arr[i]) \n\n return bit_tree \n"} +{"Prompt":"invert a binary tree","Completions":"# invert a binary tree\n\ndef reverse(root):\n if root is None:\n return\n root.left, root.right = root.right, root.left\n if root.left:\n reverse(root.left)\n if root.right:\n reverse(root.right)\n"} +{"Prompt":"ON solution return 0 if unbalanced else depth 1 def isbalancedroot: ON2 solution left maxheightroot.left right maxheightroot.right return absleftright 1 and isbalancedroot.left and isbalancedroot.right def maxheightroot: if root is None: return 0 return maxmaxheightroot.left, maxheightroot.right 1","Completions":"def is_balanced(root):\n return __is_balanced_recursive(root)\n\n\ndef __is_balanced_recursive(root):\n \"\"\"\n O(N) solution\n \"\"\"\n return -1 != __get_depth(root)\n\n\ndef __get_depth(root):\n \"\"\"\n return 0 if unbalanced else depth + 1\n \"\"\"\n if root is None:\n return 0\n left = __get_depth(root.left)\n right = __get_depth(root.right)\n if abs(left-right) > 1 or -1 in [left, right]:\n return -1\n return 1 + max(left, right)\n\n\n# def is_balanced(root):\n# \"\"\"\n# O(N^2) solution\n# \"\"\"\n# left = max_height(root.left)\n# right = max_height(root.right)\n# return abs(left-right) <= 1 and is_balanced(root.left) and\n# is_balanced(root.right)\n\n# def max_height(root):\n# if root is None:\n# return 0\n# return max(max_height(root.left), max_height(root.right)) + 1\n"} +{"Prompt":"Given two binary trees s and t, check if t is a subtree of s. A subtree of a tree t is a tree consisting of a node in t and all of its descendants in t. Example 1: Given s: 3 4 5 1 2 Given t: 4 1 2 Return true, because t is a subtree of s. Example 2: Given s: 3 4 5 1 2 0 Given t: 3 4 1 2 Return false, because even though t is part of s, it does not contain all descendants of t. Follow up: What if one tree is significantly lager than the other?","Completions":"import collections\n\n\ndef is_subtree(big, small):\n flag = False\n queue = collections.deque()\n queue.append(big)\n while queue:\n node = queue.popleft()\n if node.val == small.val:\n flag = comp(node, small)\n break\n else:\n queue.append(node.left)\n queue.append(node.right)\n return flag\n\n\ndef comp(p, q):\n if p is None and q is None:\n return True\n if p is not None and q is not None:\n return p.val == q.val and comp(p.left,q.left) and comp(p.right, q.right)\n return False\n"} +{"Prompt":"Given a binary tree, check whether it is a mirror of itself ie, symmetric around its center. For example, this binary tree 1,2,2,3,4,4,3 is symmetric: 1 2 2 3 4 4 3 But the following 1,2,2,null,3,null,3 is not: 1 2 2 3 3 Note: Bonus points if you could solve it both recursively and iteratively. TC: Ob SC: Olog n","Completions":"# TC: O(b) SC: O(log n)\ndef is_symmetric(root):\n if root is None:\n return True\n return helper(root.left, root.right)\n\n\ndef helper(p, q):\n if p is None and q is None:\n return True\n if p is not None or q is not None or q.val != p.val:\n return False\n return helper(p.left, q.right) and helper(p.right, q.left)\n\n\ndef is_symmetric_iterative(root):\n if root is None:\n return True\n stack = [[root.left, root.right]]\n while stack:\n left, right = stack.pop() # popleft\n if left is None and right is None:\n continue\n if left is None or right is None:\n return False\n if left.val == right.val:\n stack.append([left.left, right.right])\n stack.append([left.right, right.left])\n else:\n return False\n return True\n"} +{"Prompt":"Given a binary tree, find the length of the longest consecutive sequence path. The path refers to any sequence of nodes from some starting node to any node in the tree along the parentchild connections. The longest consecutive path need to be from parent to child cannot be the reverse. For example, 1 3 2 4 5 Longest consecutive sequence path is 345, so return 3. 2 3 2 1 :type root: TreeNode :rtype: int","Completions":"def longest_consecutive(root):\n \"\"\"\n :type root: TreeNode\n :rtype: int\n \"\"\"\n if root is None:\n return 0\n max_len = 0\n dfs(root, 0, root.val, max_len)\n return max_len\n\n\ndef dfs(root, cur, target, max_len):\n if root is None:\n return\n if root.val == target:\n cur += 1\n else:\n cur = 1\n max_len = max(cur, max_len)\n dfs(root.left, cur, root.val+1, max_len)\n dfs(root.right, cur, root.val+1, max_len)\n"} +{"Prompt":"Given a binary tree, find the lowest common ancestor LCA of two given nodes in the tree. According to the definition of LCA on Wikipedia: The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants where we allow a node to be a descendant of itself. 3 5 1 6 2 0 8 7 4 For example, the lowest common ancestor LCA of nodes 5 and 1 is 3. Another example is LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition. :type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode","Completions":"def lca(root, p, q):\n \"\"\"\n :type root: TreeNode\n :type p: TreeNode\n :type q: TreeNode\n :rtype: TreeNode\n \"\"\"\n if root is None or root is p or root is q:\n return root\n left = lca(root.left, p, q)\n right = lca(root.right, p, q)\n if left is not None and right is not None:\n return root\n return left if left else right\n"} +{"Prompt":"Given a binary tree, find its maximum depth. The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. def maxheightroot: if not root: return 0 return maxmaxDepthroot.left, maxDepthroot.right 1 iterative","Completions":"# def max_height(root):\n# if not root:\n# return 0\n# return max(maxDepth(root.left), maxDepth(root.right)) + 1\n\n# iterative\n\nfrom tree import TreeNode\n\n\ndef max_height(root):\n if root is None:\n return 0\n height = 0\n queue = [root]\n while queue:\n height += 1\n level = []\n while queue:\n node = queue.pop(0)\n if node.left is not None:\n level.append(node.left)\n if node.right is not None:\n level.append(node.right)\n queue = level\n return height\n\n\ndef print_tree(root):\n if root is not None:\n print(root.val)\n print_tree(root.left)\n print_tree(root.right)\n\n\nif __name__ == '__main__':\n tree = TreeNode(10)\n tree.left = TreeNode(12)\n tree.right = TreeNode(15)\n tree.left.left = TreeNode(25)\n tree.left.left.right = TreeNode(100)\n tree.left.right = TreeNode(30)\n tree.right.left = TreeNode(36)\n\n height = max_height(tree)\n print_tree(tree)\n print(\"height:\", height)\n"} +{"Prompt":":type root: TreeNode :rtype: int iterative","Completions":"from tree import TreeNode\n\n\ndef min_depth(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: int\n \"\"\"\n if root is None:\n return 0\n if root.left is not None or root.right is not None:\n return max(self.minDepth(root.left), self.minDepth(root.right))+1\n return min(self.minDepth(root.left), self.minDepth(root.right)) + 1\n\n\n# iterative\ndef min_height(root):\n if root is None:\n return 0\n height = 0\n level = [root]\n while level:\n height += 1\n new_level = []\n for node in level:\n if node.left is None and node.right is None:\n return height\n if node.left is not None:\n new_level.append(node.left)\n if node.right is not None:\n new_level.append(node.right)\n level = new_level\n return height\n\n\ndef print_tree(root):\n if root is not None:\n print(root.val)\n print_tree(root.left)\n print_tree(root.right)\n\n\nif __name__ == '__main__':\n tree = TreeNode(10)\n tree.left = TreeNode(12)\n tree.right = TreeNode(15)\n tree.left.left = TreeNode(25)\n tree.left.left.right = TreeNode(100)\n tree.left.right = TreeNode(30)\n tree.right.left = TreeNode(36)\n\n height = min_height(tree)\n print_tree(tree)\n print(\"height:\", height)\n"} +{"Prompt":"Given a binary tree and a sum, determine if the tree has a roottoleaf path such that adding up all the values along the path equals the given sum. For example: Given the below binary tree and sum 22, 5 4 8 11 13 4 7 2 1 return true, as there exist a roottoleaf path 54112 which sum is 22. :type root: TreeNode :type sum: int :rtype: bool DFS with stack BFS with queue","Completions":"def has_path_sum(root, sum):\n \"\"\"\n :type root: TreeNode\n :type sum: int\n :rtype: bool\n \"\"\"\n if root is None:\n return False\n if root.left is None and root.right is None and root.val == sum:\n return True\n sum -= root.val\n return has_path_sum(root.left, sum) or has_path_sum(root.right, sum)\n\n\n# DFS with stack\ndef has_path_sum2(root, sum):\n if root is None:\n return False\n stack = [(root, root.val)]\n while stack:\n node, val = stack.pop()\n if node.left is None and node.right is None:\n if val == sum:\n return True\n if node.left is not None:\n stack.append((node.left, val+node.left.val))\n if node.right is not None:\n stack.append((node.right, val+node.right.val))\n return False\n\n\n# BFS with queue\ndef has_path_sum3(root, sum):\n if root is None:\n return False\n queue = [(root, sum-root.val)]\n while queue:\n node, val = queue.pop(0) # popleft\n if node.left is None and node.right is None:\n if val == 0:\n return True\n if node.left is not None:\n queue.append((node.left, val-node.left.val))\n if node.right is not None:\n queue.append((node.right, val-node.right.val))\n return False\n"} +{"Prompt":"Given a binary tree and a sum, find all roottoleaf paths where each path's sum equals the given sum. For example: Given the below binary tree and sum 22, 5 4 8 11 13 4 7 2 5 1 return 5,4,11,2, 5,8,4,5 DFS with stack BFS with queue","Completions":"def path_sum(root, sum):\n if root is None:\n return []\n res = []\n dfs(root, sum, [], res)\n return res\n\n\ndef dfs(root, sum, ls, res):\n if root.left is None and root.right is None and root.val == sum:\n ls.append(root.val)\n res.append(ls)\n if root.left is not None:\n dfs(root.left, sum-root.val, ls+[root.val], res)\n if root.right is not None:\n dfs(root.right, sum-root.val, ls+[root.val], res)\n\n\n# DFS with stack\ndef path_sum2(root, s):\n if root is None:\n return []\n res = []\n stack = [(root, [root.val])]\n while stack:\n node, ls = stack.pop()\n if node.left is None and node.right is None and sum(ls) == s:\n res.append(ls)\n if node.left is not None:\n stack.append((node.left, ls+[node.left.val]))\n if node.right is not None:\n stack.append((node.right, ls+[node.right.val]))\n return res\n\n\n# BFS with queue\ndef path_sum3(root, sum):\n if root is None:\n return []\n res = []\n queue = [(root, root.val, [root.val])]\n while queue:\n node, val, ls = queue.pop(0) # popleft\n if node.left is None and node.right is None and val == sum:\n res.append(ls)\n if node.left is not None:\n queue.append((node.left, val+node.left.val, ls+[node.left.val]))\n if node.right is not None:\n queue.append((node.right, val+node.right.val, ls+[node.right.val]))\n return res\n"} +{"Prompt":"a Adam Book 4 b Bill Computer 5 TV 6 Jill Sports 1 c Bill Sports 3 d Adam Computer 3 Quin Computer 3 e Quin Book 5 TV 2 f Adam Computer 7","Completions":"# a -> Adam -> Book -> 4\n# b -> Bill -> Computer -> 5\n# -> TV -> 6\n# Jill -> Sports -> 1\n# c -> Bill -> Sports -> 3\n# d -> Adam -> Computer -> 3\n# Quin -> Computer -> 3\n# e -> Quin -> Book -> 5\n# -> TV -> 2\n# f -> Adam -> Computer -> 7\n\nfrom __future__ import print_function\n\n\ndef tree_print(tree):\n for key in tree:\n print(key, end=' ') # end=' ' prevents a newline character\n tree_element = tree[key] # multiple lookups is expensive, even amortized O(1)!\n for subElem in tree_element:\n print(\" -> \", subElem, end=' ')\n if type(subElem) != str: # OP wants indenting after digits\n print(\"\\n \") # newline and a space to match indenting\n print() # forces a newline\n"} +{"Prompt":"Implementation of RedBlack tree. set the node as the left child node of the current node's right node right node's left node become the right node of current node check the parent case set the node as the right child node of the current node's left node left node's right node become the left node of current node check the parent case the inserted node's color is default is red find the position of inserted node set the n ode's parent node case 1 inserted tree is null case 2 not null and find left or right fix the tree to case 1 the parent is null, then set the inserted node as root and color 0 case 2 the parent color is black, do nothing case 3 the parent color is red case 3.1 the uncle node is red then set parent and uncle color is black and grandparent is red then node node.parent case 3.2 the uncle node is black or null, and the node is right of parent then set his parent node is current node left rotate the node and continue the next case 3.3 the uncle node is black and parent node is left then parent node set black and grandparent set red case 3.1 the uncle node is red then set parent and uncle color is black and grandparent is red then node node.parent case 3.2 the uncle node is black or null, and the node is right of parent then set his parent node is current node left rotate the node and continue the next case 3.3 the uncle node is black and parent node is left then parent node set black and grandparent set red replace u with v :param nodeu: replaced node :param nodev: :return: None check is nodev is None find the max node when node regard as a root node :param node: :return: max node find the minimum node when node regard as a root node :param node: :return: minimum node find the node position both child exits ,and find minimum child of right child when node is black, then need to fix it with 4 cases 4 cases node is not root and color is black node is left node case 1: node's red, can not get black node set brother is black and parent is red case 2: brother node is black, and its children node is both black case 3: brother node is black , and its left child node is red and right is black case 4: brother node is black, and right is red, and left is any color","Completions":"class RBNode:\n def __init__(self, val, is_red, parent=None, left=None, right=None):\n self.val = val\n self.parent = parent\n self.left = left\n self.right = right\n self.color = is_red\n\n\nclass RBTree:\n def __init__(self):\n self.root = None\n\n def left_rotate(self, node):\n # set the node as the left child node of the current node's right node\n right_node = node.right\n if right_node is None:\n return\n else:\n # right node's left node become the right node of current node\n node.right = right_node.left\n if right_node.left is not None:\n right_node.left.parent = node\n right_node.parent = node.parent\n # check the parent case\n if node.parent is None:\n self.root = right_node\n elif node is node.parent.left:\n node.parent.left = right_node\n else:\n node.parent.right = right_node\n right_node.left = node\n node.parent = right_node\n\n def right_rotate(self, node):\n # set the node as the right child node of the current node's left node\n left_node = node.left\n if left_node is None:\n return\n else:\n # left node's right node become the left node of current node\n node.left = left_node.right\n if left_node.right is not None:\n left_node.right.parent = node\n left_node.parent = node.parent\n # check the parent case\n if node.parent is None:\n self.root = left_node\n elif node is node.parent.left:\n node.parent.left = left_node\n else:\n node.parent.right = left_node\n left_node.right = node\n node.parent = left_node\n\n def insert(self, node):\n # the inserted node's color is default is red\n root = self.root\n insert_node_parent = None\n # find the position of inserted node\n while root is not None:\n insert_node_parent = root\n if insert_node_parent.val < node.val:\n root = root.right\n else:\n root = root.left\n # set the n ode's parent node\n node.parent = insert_node_parent\n if insert_node_parent is None:\n # case 1 inserted tree is null\n self.root = node\n elif insert_node_parent.val > node.val:\n # case 2 not null and find left or right\n insert_node_parent.left = node\n else:\n insert_node_parent.right = node\n node.left = None\n node.right = None\n node.color = 1\n # fix the tree to \n self.fix_insert(node)\n\n def fix_insert(self, node):\n # case 1 the parent is null, then set the inserted node as root and color = 0\n if node.parent is None:\n node.color = 0\n self.root = node\n return\n # case 2 the parent color is black, do nothing\n # case 3 the parent color is red\n while node.parent and node.parent.color == 1:\n if node.parent is node.parent.parent.left:\n uncle_node = node.parent.parent.right\n if uncle_node and uncle_node.color == 1:\n # case 3.1 the uncle node is red\n # then set parent and uncle color is black and grandparent is red\n # then node => node.parent\n node.parent.color = 0\n node.parent.parent.right.color = 0\n node.parent.parent.color = 1\n node = node.parent.parent\n continue\n elif node is node.parent.right:\n # case 3.2 the uncle node is black or null, and the node is right of parent\n # then set his parent node is current node\n # left rotate the node and continue the next\n node = node.parent\n self.left_rotate(node)\n # case 3.3 the uncle node is black and parent node is left\n # then parent node set black and grandparent set red\n node.parent.color = 0\n node.parent.parent.color = 1\n self.right_rotate(node.parent.parent)\n else:\n uncle_node = node.parent.parent.left\n if uncle_node and uncle_node.color == 1:\n # case 3.1 the uncle node is red\n # then set parent and uncle color is black and grandparent is red\n # then node => node.parent\n node.parent.color = 0\n node.parent.parent.left.color = 0\n node.parent.parent.color = 1\n node = node.parent.parent\n continue\n elif node is node.parent.left:\n # case 3.2 the uncle node is black or null, and the node is right of parent\n # then set his parent node is current node\n # left rotate the node and continue the next\n node = node.parent\n self.right_rotate(node)\n # case 3.3 the uncle node is black and parent node is left\n # then parent node set black and grandparent set red\n node.parent.color = 0\n node.parent.parent.color = 1\n self.left_rotate(node.parent.parent)\n self.root.color = 0\n\n def transplant(self, node_u, node_v):\n \"\"\"\n replace u with v\n :param node_u: replaced node\n :param node_v: \n :return: None\n \"\"\"\n if node_u.parent is None:\n self.root = node_v\n elif node_u is node_u.parent.left:\n node_u.parent.left = node_v\n elif node_u is node_u.parent.right:\n node_u.parent.right = node_v\n # check is node_v is None \n if node_v:\n node_v.parent = node_u.parent\n\n def maximum(self, node):\n \"\"\"\n find the max node when node regard as a root node \n :param node: \n :return: max node \n \"\"\"\n temp_node = node\n while temp_node.right is not None:\n temp_node = temp_node.right\n return temp_node\n\n def minimum(self, node):\n \"\"\"\n find the minimum node when node regard as a root node \n :param node:\n :return: minimum node \n \"\"\"\n temp_node = node\n while temp_node.left:\n temp_node = temp_node.left\n return temp_node\n\n def delete(self, node):\n # find the node position\n node_color = node.color\n if node.left is None:\n temp_node = node.right\n self.transplant(node, node.right)\n elif node.right is None:\n temp_node = node.left\n self.transplant(node, node.left)\n else:\n # both child exits ,and find minimum child of right child\n node_min = self.minimum(node.right)\n node_color = node_min.color\n temp_node = node_min.right\n ## \n if node_min.parent is not node:\n self.transplant(node_min, node_min.right)\n node_min.right = node.right\n node_min.right.parent = node_min\n self.transplant(node, node_min)\n node_min.left = node.left\n node_min.left.parent = node_min\n node_min.color = node.color\n # when node is black, then need to fix it with 4 cases\n if node_color == 0:\n self.delete_fixup(temp_node)\n\n def delete_fixup(self, node):\n # 4 cases\n while node is not self.root and node.color == 0:\n # node is not root and color is black\n if node is node.parent.left:\n # node is left node\n node_brother = node.parent.right\n\n # case 1: node's red, can not get black node\n # set brother is black and parent is red \n if node_brother.color == 1:\n node_brother.color = 0\n node.parent.color = 1\n self.left_rotate(node.parent)\n node_brother = node.parent.right\n\n # case 2: brother node is black, and its children node is both black\n if (node_brother.left is None or node_brother.left.color == 0) and (\n node_brother.right is None or node_brother.right.color == 0):\n node_brother.color = 1\n node = node.parent\n else:\n\n # case 3: brother node is black , and its left child node is red and right is black\n if node_brother.right is None or node_brother.right.color == 0:\n node_brother.color = 1\n node_brother.left.color = 0\n self.right_rotate(node_brother)\n node_brother = node.parent.right\n\n # case 4: brother node is black, and right is red, and left is any color\n node_brother.color = node.parent.color\n node.parent.color = 0\n node_brother.right.color = 0\n self.left_rotate(node.parent)\n node = self.root\n else:\n node_brother = node.parent.left\n if node_brother.color == 1:\n node_brother.color = 0\n node.parent.color = 1\n self.left_rotate(node.parent)\n node_brother = node.parent.right\n if (node_brother.left is None or node_brother.left.color == 0) and (\n node_brother.right is None or node_brother.right.color == 0):\n node_brother.color = 1\n node = node.parent\n else:\n if node_brother.left is None or node_brother.left.color == 0:\n node_brother.color = 1\n node_brother.right.color = 0\n self.left_rotate(node_brother)\n node_brother = node.parent.left\n node_brother.color = node.parent.color\n node.parent.color = 0\n node_brother.left.color = 0\n self.right_rotate(node.parent)\n node = self.root\n node.color = 0\n\n def inorder(self):\n res = []\n if not self.root:\n return res\n stack = []\n root = self.root\n while root or stack:\n while root:\n stack.append(root)\n root = root.left\n root = stack.pop()\n res.append({'val': root.val, 'color': root.color})\n root = root.right\n return res\n\n\nif __name__ == \"__main__\":\n rb = RBTree()\n children = [11, 2, 14, 1, 7, 15, 5, 8, 4]\n for child in children:\n node = RBNode(child, 1)\n print(child)\n rb.insert(node)\n print(rb.inorder())\n"} +{"Prompt":"Given two binary trees, write a function to check if they are equal or not. Two binary trees are considered equal if they are structurally identical and the nodes have the same value. Time Complexity OminN,M where N and M are the number of nodes for the trees. Space Complexity Ominheight1, height2 levels of recursion is the mininum height between the two trees.","Completions":"def is_same_tree(tree_p, tree_q):\n if tree_p is None and tree_q is None:\n return True\n if tree_p is not None and tree_q is not None and tree_p.val == tree_q.val:\n return is_same_tree(tree_p.left, tree_q.left) and is_same_tree(tree_p.right, tree_q.right)\n return False\n\n# Time Complexity O(min(N,M))\n# where N and M are the number of nodes for the trees.\n\n# Space Complexity O(min(height1, height2))\n# levels of recursion is the mininum height between the two trees.\n"} +{"Prompt":"SegmentTree creates a segment tree with a given array and a commutative function, this nonrecursive version uses less memory than the recursive version and include: 1. range queries in logN time 2. update an element in logN time the function should be commutative and takes 2 values and returns the same type value Examples mytree SegmentTree2, 4, 5, 3, 4,max printmytree.query2, 4 mytree.update3, 6 printmytree.query0, 3 ... mytree SegmentTree4, 5, 2, 3, 4, 43, 3, lambda a, b: a b printmytree.query0, 6 mytree.update2, 10 printmytree.query0, 6 ... mytree SegmentTree1, 2, 4, 6, 4, 5, lambda a, b: a0 b0, a1 b1 printmytree.query0, 2 mytree.update2, 1, 2 printmytree.query0, 2 ...","Completions":"class SegmentTree:\n def __init__(self, arr, function):\n self.tree = [None for _ in range(len(arr))] + arr\n self.size = len(arr)\n self.fn = function\n self.build_tree()\n\n def build_tree(self):\n for i in range(self.size - 1, 0, -1):\n self.tree[i] = self.fn(self.tree[i * 2], self.tree[i * 2 + 1])\n\n def update(self, p, v):\n p += self.size\n self.tree[p] = v\n while p > 1:\n p = p \/\/ 2\n self.tree[p] = self.fn(self.tree[p * 2], self.tree[p * 2 + 1])\n\n def query(self, l, r):\n l, r = l + self.size, r + self.size\n res = None\n while l <= r:\n if l % 2 == 1:\n res = self.tree[l] if res is None else self.fn(res, self.tree[l])\n if r % 2 == 0:\n res = self.tree[r] if res is None else self.fn(res, self.tree[r])\n l, r = (l + 1) \/\/ 2, (r - 1) \/\/ 2\n return res\n"} +{"Prompt":"Segmenttree creates a segment tree with a given array and function, allowing queries to be done later in logN time function takes 2 values and returns a same type value Example mytree SegmentTree2,4,5,3,4,max mytree.query2,4 mytree.query0,3 ... mytree SegmentTree4,5,2,3,4,43,3,sum mytree.query1,8 ...","Completions":"class SegmentTree:\n def __init__(self,arr,function):\n self.segment = [0 for x in range(3*len(arr)+3)]\n self.arr = arr\n self.fn = function\n self.make_tree(0,0,len(arr)-1)\n\n def make_tree(self,i,l,r):\n if l==r:\n self.segment[i] = self.arr[l]\n elif lR or rR or l>r:\n return None\n if L>=l and R<=r:\n return self.segment[i]\n val1 = self.__query(2*i+1,L,int((L+R)\/2),l,r)\n val2 = self.__query(2*i+2,int((L+R+2)\/2),R,l,r)\n print(L,R,\" returned \",val1,val2)\n if val1 != None:\n if val2 != None:\n return self.fn(val1,val2)\n return val1\n return val2\n \n\n def query(self,L,R):\n return self.__query(0,0,len(self.arr)-1,L,R)\n\n'''\nExample -\nmytree = SegmentTree([2,4,5,3,4],max)\nmytree.query(2,4)\nmytree.query(0,3) ...\n\nmytree = SegmentTree([4,5,2,3,4,43,3],sum)\nmytree.query(1,8)\n...\n\n'''\n"} +{"Prompt":"Time complexity : On In order function res if not root: return res stack while root or stack: while root: stack.appendroot root root.left root stack.pop res.appendroot.val root root.right return res def inorderrecroot, resNone:","Completions":"class Node:\n\n def __init__(self, val, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\n\ndef inorder(root):\n \"\"\" In order function \"\"\"\n res = []\n if not root:\n return res\n stack = []\n while root or stack:\n while root:\n stack.append(root)\n root = root.left\n root = stack.pop()\n res.append(root.val)\n root = root.right\n return res\n\ndef inorder_rec(root, res=None):\n \"\"\" Recursive Implementation \"\"\"\n if root is None:\n return []\n if res is None:\n res = []\n inorder_rec(root.left, res)\n res.append(root.val)\n inorder_rec(root.right, res)\n return res\n\n\nif __name__ == '__main__':\n n1 = Node(100)\n n2 = Node(50)\n n3 = Node(150)\n n4 = Node(25)\n n5 = Node(75)\n n6 = Node(125)\n n7 = Node(175)\n n1.left, n1.right = n2, n3\n n2.left, n2.right = n4, n5\n n3.left, n3.right = n6, n7\n\n assert inorder(n1) == [25, 50, 75, 100, 125, 150, 175]\n assert inorder_rec(n1) == [25, 50, 75, 100, 125, 150, 175]\n"} +{"Prompt":"Given a binary tree, return the level order traversal of its nodes' values. ie, from left to right, level by level. For example: Given binary tree 3,9,20,null,null,15,7, 3 9 20 15 7 return its level order traversal as: 3, 9,20, 15,7","Completions":"def level_order(root):\n ans = []\n if not root:\n return ans\n level = [root]\n while level:\n current = []\n new_level = []\n for node in level:\n current.append(node.val)\n if node.left:\n new_level.append(node.left)\n if node.right:\n new_level.append(node.right)\n level = new_level\n ans.append(current)\n return ans\n"} +{"Prompt":"Time complexity : On Recursive Implementation","Completions":"class Node:\n\n def __init__(self, val, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\n\ndef postorder(root):\n res_temp = []\n res = []\n if not root:\n return res\n stack = []\n stack.append(root)\n while stack:\n root = stack.pop()\n res_temp.append(root.val)\n if root.left:\n stack.append(root.left)\n if root.right:\n stack.append(root.right)\n while res_temp:\n res.append(res_temp.pop())\n return res\n\n# Recursive Implementation\ndef postorder_rec(root, res=None):\n if root is None:\n return []\n if res is None:\n res = []\n postorder_rec(root.left, res)\n postorder_rec(root.right, res)\n res.append(root.val)\n return res\n\n"} +{"Prompt":"Time complexity : On This is a class of Node def initself, val, leftNone, rightNone: self.val val self.left left self.right right def preorderroot: Recursive Implementation if root is None: return if res is None: res res.appendroot.val preorderrecroot.left, res preorderrecroot.right, res return res","Completions":"class Node:\n \"\"\" This is a class of Node \"\"\"\n\n def __init__(self, val, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\n\ndef preorder(root):\n \"\"\" Function to Preorder \"\"\"\n res = []\n if not root:\n return res\n stack = []\n stack.append(root)\n while stack:\n root = stack.pop()\n res.append(root.val)\n if root.right:\n stack.append(root.right)\n if root.left:\n stack.append(root.left)\n return res\n\ndef preorder_rec(root, res=None):\n \"\"\" Recursive Implementation \"\"\"\n if root is None:\n return []\n if res is None:\n res = []\n res.append(root.val)\n preorder_rec(root.left, res)\n preorder_rec(root.right, res)\n return res\n"} +{"Prompt":"Given a binary tree, return the zigzag level order traversal of its nodes' values. ie, from left to right, then right to left for the next level and alternate between. For example: Given binary tree 3,9,20,null,null,15,7, 3 9 20 15 7 return its zigzag level order traversal as: 3, 20,9, 15,7","Completions":"def zigzag_level(root):\n res = []\n if not root:\n return res\n level = [root]\n flag = 1\n while level:\n current = []\n new_level = []\n for node in level:\n current.append(node.val)\n if node.left:\n new_level.append(node.left)\n if node.right:\n new_level.append(node.right)\n level = new_level\n res.append(current[::flag])\n flag *= -1\n return res\n"} +{"Prompt":"We are asked to design an efficient data structure that allows us to add and search for words. The search can be a literal word or regular expression containing ., where . can be any letter. Example: addWordbad addWorddad addWordmad searchpad false searchbad true search.ad true searchb.. true if dot if letter match xx.xx.x with yyyyyyy","Completions":"import collections\n\nclass TrieNode(object):\n def __init__(self, letter, is_terminal=False):\n self.children = dict()\n self.letter = letter\n self.is_terminal = is_terminal\n\nclass WordDictionary(object):\n def __init__(self):\n self.root = TrieNode(\"\")\n\n def add_word(self, word):\n cur = self.root\n for letter in word:\n if letter not in cur.children:\n cur.children[letter] = TrieNode(letter)\n cur = cur.children[letter]\n cur.is_terminal = True\n\n def search(self, word, node=None):\n cur = node\n if not cur:\n cur = self.root\n for i, letter in enumerate(word):\n # if dot\n if letter == \".\":\n if i == len(word) - 1: # if last character\n for child in cur.children.itervalues():\n if child.is_terminal:\n return True\n return False\n for child in cur.children.itervalues():\n if self.search(word[i+1:], child) == True:\n return True\n return False\n # if letter\n if letter not in cur.children:\n return False\n cur = cur.children[letter]\n return cur.is_terminal\n\nclass WordDictionary2(object):\n def __init__(self):\n self.word_dict = collections.defaultdict(list)\n\n\n def add_word(self, word):\n if word:\n self.word_dict[len(word)].append(word)\n\n def search(self, word):\n if not word:\n return False\n if '.' not in word:\n return word in self.word_dict[len(word)]\n for v in self.word_dict[len(word)]:\n # match xx.xx.x with yyyyyyy\n for i, ch in enumerate(word):\n if ch != v[i] and ch != '.':\n break\n else:\n return True\n return False\n"} +{"Prompt":"Implement a trie with insert, search, and startsWith methods. Note: You may assume that all inputs are consist of lowercase letters az.","Completions":"import collections\n\n\nclass TrieNode:\n def __init__(self):\n self.children = collections.defaultdict(TrieNode)\n self.is_word = 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 letter in word:\n current = current.children[letter]\n current.is_word = True\n\n def search(self, word):\n current = self.root\n for letter in word:\n current = current.children.get(letter)\n if current is None:\n return False\n return current.is_word\n\n def starts_with(self, prefix):\n current = self.root\n for letter in prefix:\n current = current.children.get(letter)\n if current is None:\n return False\n return True\n\n"} +{"Prompt":"Defines the UnionFind or Disjoint Set data structure. A disjoint set is made up of a number of elements contained within another number of sets. Initially, elements are put in their own set, but sets may be merged using the unite operation. We can check if two elements are in the same seet by comparing their roots. If they are identical, the two elements are in the same set. All operations can be completed in Oan where n is the number of elements, and a the inverse ackermann function. an grows so slowly that it might as well be constant for any conceivable n. A UnionFind data structure. Consider the following sequence of events: Starting with the elements 1, 2, 3, and 4: 1 2 3 4 Initally they all live in their own sets, which means that root1 ! root3, however, if we call unite1, 3 we would then have the following: 1,3 2 4 Now we have root1 root3, but it is still the case that root1 ! root2. We may call unite2, 4 and end up with: 1,3 2,4 Again we have root1 ! root2. But after unite3, 4 we end up with: 1,2,3,4 which results in root1 root2. Add a new set containing the single element Find the root element which represents the set of a given element. That is, all elements that are in the same set will return the same root element. Finds the sets which contains the two elements and merges them into a single set. Given a list of positions to operate, count the number of islands after each addLand operation. 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. Given a 3x3 grid, positions 0,0, 0,1, 1,2, 2,1. Initially, the 2d grid grid is filled with water. Assume 0 represents water and 1 represents land. 0 0 0 0 0 0 0 0 0 Operation 1: addLand0, 0 turns the water at grid00 into a land. 1 0 0 0 0 0 Number of islands 1 0 0 0 Operation 2: addLand0, 1 turns the water at grid01 into a land. 1 1 0 0 0 0 Number of islands 1 0 0 0 Operation 3: addLand1, 2 turns the water at grid12 into a land. 1 1 0 0 0 1 Number of islands 2 0 0 0 Operation 4: addLand2, 1 turns the water at grid21 into a land. 1 1 0 0 0 1 Number of islands 3 0 1 0","Completions":"class Union:\n \"\"\"\n A Union-Find data structure.\n\n Consider the following sequence of events:\n Starting with the elements 1, 2, 3, and 4:\n\n {1} {2} {3} {4}\n\n Initally they all live in their own sets, which means that `root(1) !=\n root(3)`, however, if we call `unite(1, 3)` we would then have the following:\n\n {1,3} {2} {4}\n\n Now we have `root(1) == root(3)`, but it is still the case that `root(1) != root(2)`.\n\n We may call `unite(2, 4)` and end up with:\n\n {1,3} {2,4}\n\n Again we have `root(1) != root(2)`. But after `unite(3, 4)` we end up with:\n\n {1,2,3,4}\n\n which results in `root(1) == root(2)`.\n \"\"\"\n\n def __init__(self):\n self.parents = {}\n self.size = {}\n self.count = 0\n\n def add(self, element):\n \"\"\"\n Add a new set containing the single element\n \"\"\"\n\n self.parents[element] = element\n self.size[element] = 1\n self.count += 1\n\n def root(self, element):\n \"\"\"\n Find the root element which represents the set of a given element.\n That is, all elements that are in the same set will return the same\n root element.\n \"\"\"\n\n while element != self.parents[element]:\n self.parents[element] = self.parents[self.parents[element]]\n element = self.parents[element]\n return element\n\n def unite(self, element1, element2):\n \"\"\"\n Finds the sets which contains the two elements and merges them into a\n single set.\n \"\"\"\n\n root1, root2 = self.root(element1), self.root(element2)\n if root1 == root2:\n return\n if self.size[root1] > self.size[root2]:\n root1, root2 = root2, root1\n self.parents[root1] = root2\n self.size[root2] += self.size[root1]\n self.count -= 1\n\ndef num_islands(positions):\n \"\"\"\n Given a list of positions to operate, count the number of islands\n after each addLand operation. An island is surrounded by water and is\n formed by connecting adjacent lands horizontally or vertically. You may\n assume all four edges of the grid are all surrounded by water.\n\n Given a 3x3 grid, positions = [[0,0], [0,1], [1,2], [2,1]].\n Initially, the 2d grid grid is filled with water.\n (Assume 0 represents water and 1 represents land).\n\n 0 0 0\n 0 0 0\n 0 0 0\n Operation #1: addLand(0, 0) turns the water at grid[0][0] into a land.\n\n 1 0 0\n 0 0 0 Number of islands = 1\n 0 0 0\n Operation #2: addLand(0, 1) turns the water at grid[0][1] into a land.\n\n 1 1 0\n 0 0 0 Number of islands = 1\n 0 0 0\n Operation #3: addLand(1, 2) turns the water at grid[1][2] into a land.\n\n 1 1 0\n 0 0 1 Number of islands = 2\n 0 0 0\n Operation #4: addLand(2, 1) turns the water at grid[2][1] into a land.\n\n 1 1 0\n 0 0 1 Number of islands = 3\n 0 1 0\n \"\"\"\n\n ans = []\n islands = Union()\n for position in map(tuple, positions):\n islands.add(position)\n for delta in (0, 1), (0, -1), (1, 0), (-1, 0):\n adjacent = (position[0] + delta[0], position[1] + delta[1])\n if adjacent in islands.parents:\n islands.unite(position, adjacent)\n ans += [islands.count]\n return ans\n"} +{"Prompt":"Get a full absolute path a file","Completions":"import os\ndef full_path(file):\n return os.path.abspath(os.path.expanduser(file))\n"} +{"Prompt":"Both URL and file path joins use slashes as dividers between their parts. For example: pathtodir file pathtodirfile pathtodir file pathtodirfile http:algorithms.com part http:algorithms.compart http:algorithms.com part http:algorithmspart Remove trailing Remove leading","Completions":"import os\n\ndef join_with_slash(base, suffix):\n # Remove \/ trailing\n base = base.rstrip('\/')\n # Remove \/ leading\n suffix = suffix.lstrip('\/').rstrip()\n full_path = \"{}\/{}\".format(base, suffix)\n return full_path\n"} +{"Prompt":"Given an absolute path for a file Unixstyle, simplify it. For example, path home, home path a.b....c, c Corner Cases: Did you consider the case where path ..? In this case, you should return . Another corner case is the path might contain multiple slashes '' together, such as homefoo. In this case, you should ignore redundant slashes and return homefoo. Reference: https:leetcode.comproblemssimplifypathdescription","Completions":"import os\ndef simplify_path_v1(path):\n return os.path.abspath(path)\n\ndef simplify_path_v2(path):\n stack, tokens = [], path.split(\"\/\")\n for token in tokens:\n if token == \"..\" and stack:\n stack.pop()\n elif token != \"..\" and token != \".\" and token:\n stack.append(token)\n return \"\/\" + \"\/\".join(stack)\n"} +{"Prompt":"Splitting a path into 2 parts Example: Input: https:algorithmsunixtest.py for url Output: part0: https:algorithmsunix part1: test.py Input: algorithmsunixtest.py for file path Output: part0: algorithmsunix part1: test.py Takt the origin path without the last part Take the last element of list","Completions":"import os\n\ndef split(path):\n parts = []\n split_part = path.rpartition('\/')\n # Takt the origin path without the last part\n parts.append(split_part[0])\n # Take the last element of list\n parts.append(split_part[2])\n return parts\n"} +{"Prompt":"!usrbinenv python3 coding: utf8 algorithms documentation build configuration file, created by sphinxquickstart on Wed Jun 6 01:17:26 2018. This file is execfiled with the current directory set to its containing dir. Note that not all possible configuration values are present in this autogenerated file. All configuration values have a default; values that are commented out serve to show the default. If extensions or modules to document with autodoc are in another directory, add these directories to sys.path here. If the directory is relative to the documentation root, use os.path.abspath to make it absolute, like shown here. import os import sys sys.path.insert0, os.path.abspath'.' General configuration If your documentation needs a minimal Sphinx version, state it here. needssphinx '1.0' Add any Sphinx extension module names here, as strings. They can be extensions coming with Sphinx named 'sphinx.ext.' or your custom ones. Add any paths that contain templates here, relative to this directory. The suffixes of source filenames. You can specify multiple suffix as a list of string: The master toctree document. General information about the project. The version info for the project you're documenting, acts as replacement for version and release, also used in various other places throughout the built documents. The short X.Y version. The full version, including alphabetarc tags. The language for content autogenerated by Sphinx. Refer to documentation for a list of supported languages. This is also used if you do content translation via gettext catalogs. Usually you set language from the command line for these cases. List of patterns, relative to source directory, that match files and directories to ignore when looking for source files. This patterns also effect to htmlstaticpath and htmlextrapath The name of the Pygments syntax highlighting style to use. If true, todo and todoList produce output, else they produce nothing. Options for HTML output The theme to use for HTML and HTML Help pages. See the documentation for a list of builtin themes. Theme options are themespecific and customize the look and feel of a theme further. For a list of options available for each theme, see the documentation. htmlthemeoptions Add any paths that contain custom static files such as style sheets here, relative to this directory. They are copied after the builtin static files, so a file named default.css will overwrite the builtin default.css. Custom sidebar templates, must be a dictionary that maps document names to template names. This is required for the alabaster theme refs: http:alabaster.readthedocs.ioenlatestinstallation.htmlsidebars Options for HTMLHelp output Output file base name for HTML help builder. Options for LaTeX output The paper size 'letterpaper' or 'a4paper'. 'papersize': 'letterpaper', The font size '10pt', '11pt' or '12pt'. 'pointsize': '10pt', Additional stuff for the LaTeX preamble. 'preamble': '', Latex figure float alignment 'figurealign': 'htbp', Grouping the document tree into LaTeX files. List of tuples source start file, target name, title, author, documentclass howto, manual, or own class. Options for manual page output One entry per manual page. List of tuples source start file, name, description, authors, manual section. Options for Texinfo output Grouping the document tree into Texinfo files. List of tuples source start file, target name, title, author, dir menu entry, description, category","Completions":"#!\/usr\/bin\/env python3\n# -*- coding: utf-8 -*-\n#\n# algorithms documentation build configuration file, created by\n# sphinx-quickstart on Wed Jun 6 01:17:26 2018.\n#\n# This file is execfile()d with the current directory set to its\n# containing dir.\n#\n# Note that not all possible configuration values are present in this\n# autogenerated file.\n#\n# All configuration values have a default; values that are commented out\n# serve to show the default.\n\n# If extensions (or modules to document with autodoc) are in another directory,\n# add these directories to sys.path here. If the directory is relative to the\n# documentation root, use os.path.abspath to make it absolute, like shown here.\n#\n# import os\n# import sys\n# sys.path.insert(0, os.path.abspath('.'))\nfrom recommonmark.parser import CommonMarkParser\n\n# -- General configuration ------------------------------------------------\n\n# If your documentation needs a minimal Sphinx version, state it here.\n#\n# needs_sphinx = '1.0'\n\n# Add any Sphinx extension module names here, as strings. They can be\n# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom\n# ones.\nextensions = ['sphinx.ext.autodoc',\n 'sphinx.ext.doctest',\n 'sphinx.ext.todo',\n 'sphinx.ext.coverage',\n 'sphinx.ext.mathjax',\n 'sphinx.ext.ifconfig',\n 'sphinx.ext.viewcode',\n 'sphinx.ext.githubpages']\n\n# Add any paths that contain templates here, relative to this directory.\ntemplates_path = ['_templates']\n\n# The suffix(es) of source filenames.\n# You can specify multiple suffix as a list of string:\n#\nsource_parsers = {\n '.md': CommonMarkParser\n}\nsource_suffix = ['.rst', '.md']\n\n# The master toctree document.\nmaster_doc = 'index'\n\n# General information about the project.\nproject = 'algorithms'\ncopyright = '2018, Algorithms Team & Contributors'\nauthor = 'Algorithms Team & Contributors'\n\n# The version info for the project you're documenting, acts as replacement for\n# |version| and |release|, also used in various other places throughout the\n# built documents.\n#\n# The short X.Y version.\nversion = '0.1.0'\n# The full version, including alpha\/beta\/rc tags.\nrelease = '0.1.0'\n\n# The language for content autogenerated by Sphinx. Refer to documentation\n# for a list of supported languages.\n#\n# This is also used if you do content translation via gettext catalogs.\n# Usually you set \"language\" from the command line for these cases.\nlanguage = None\n\n# List of patterns, relative to source directory, that match files and\n# directories to ignore when looking for source files.\n# This patterns also effect to html_static_path and html_extra_path\nexclude_patterns = []\n\n# The name of the Pygments (syntax highlighting) style to use.\npygments_style = 'sphinx'\n\n# If true, `todo` and `todoList` produce output, else they produce nothing.\ntodo_include_todos = True\n\n\n# -- Options for HTML output ----------------------------------------------\n\n# The theme to use for HTML and HTML Help pages. See the documentation for\n# a list of builtin themes.\n#\nhtml_theme = 'alabaster'\n\n# Theme options are theme-specific and customize the look and feel of a theme\n# further. For a list of options available for each theme, see the\n# documentation.\n#\n# html_theme_options = {}\n\n# Add any paths that contain custom static files (such as style sheets) here,\n# relative to this directory. They are copied after the builtin static files,\n# so a file named \"default.css\" will overwrite the builtin \"default.css\".\nhtml_static_path = ['_static']\n\n# Custom sidebar templates, must be a dictionary that maps document names\n# to template names.\n#\n# This is required for the alabaster theme\n# refs: http:\/\/alabaster.readthedocs.io\/en\/latest\/installation.html#sidebars\nhtml_sidebars = {\n '**': [\n 'about.html',\n 'searchbox.html',\n 'navigation.html',\n 'relations.html', # needs 'show_related': True theme option to display\n ]\n}\n\n\n# -- Options for HTMLHelp output ------------------------------------------\n\n# Output file base name for HTML help builder.\nhtmlhelp_basename = 'algorithmsdoc'\n\n\n# -- Options for LaTeX output ---------------------------------------------\n\nlatex_elements = {\n # The paper size ('letterpaper' or 'a4paper').\n #\n # 'papersize': 'letterpaper',\n\n # The font size ('10pt', '11pt' or '12pt').\n #\n # 'pointsize': '10pt',\n\n # Additional stuff for the LaTeX preamble.\n #\n # 'preamble': '',\n\n # Latex figure (float) alignment\n #\n # 'figure_align': 'htbp',\n}\n\n# Grouping the document tree into LaTeX files. List of tuples\n# (source start file, target name, title,\n# author, documentclass [howto, manual, or own class]).\nlatex_documents = [\n (master_doc, 'algorithms.tex', 'algorithms Documentation',\n 'Algorithms Team \\\\& Contributors', 'manual'),\n]\n\n\n# -- Options for manual page output ---------------------------------------\n\n# One entry per manual page. List of tuples\n# (source start file, name, description, authors, manual section).\nman_pages = [\n (master_doc, 'algorithms', 'algorithms Documentation',\n [author], 1)\n]\n\n\n# -- Options for Texinfo output -------------------------------------------\n\n# Grouping the document tree into Texinfo files. List of tuples\n# (source start file, target name, title, author,\n# dir menu entry, description, category)\ntexinfo_documents = [\n (master_doc, 'algorithms', 'algorithms Documentation',\n author, 'algorithms', 'One line description of project.',\n 'Miscellaneous'),\n]\n"} +{"Prompt":"123, 6 123, 123 232, 8 232, 232","Completions":"from algorithms.backtrack import (\n add_operators,\n permute_iter,\n anagram,\n array_sum_combinations,\n unique_array_sum_combinations,\n combination_sum,\n get_factors,\n recursive_get_factors,\n find_words,\n generate_abbreviations,\n generate_parenthesis_v1,\n generate_parenthesis_v2,\n letter_combinations,\n palindromic_substrings,\n pattern_match,\n permute_unique,\n permute,\n permute_recursive,\n subsets_unique,\n subsets,\n subsets_v2,\n)\n\nimport unittest\n\n\nclass TestAddOperator(unittest.TestCase):\n def test_add_operators(self):\n # \"123\", 6 -> [\"1+2+3\", \"1*2*3\"]\n s = \"123\"\n target = 6\n self.assertEqual(add_operators(s, target), [\"1+2+3\", \"1*2*3\"])\n # \"232\", 8 -> [\"2*3+2\", \"2+3*2\"]\n s = \"232\"\n target = 8\n self.assertEqual(add_operators(s, target), [\"2+3*2\", \"2*3+2\"])\n\n s = \"123045\"\n target = 3\n answer = ['1+2+3*0*4*5',\n '1+2+3*0*45',\n '1+2-3*0*4*5',\n '1+2-3*0*45',\n '1-2+3+0-4+5',\n '1-2+3-0-4+5',\n '1*2+3*0-4+5',\n '1*2-3*0-4+5',\n '1*23+0-4*5',\n '1*23-0-4*5',\n '12+3*0-4-5',\n '12-3*0-4-5']\n self.assertEqual(add_operators(s, target), answer)\n\n\nclass TestPermuteAndAnagram(unittest.TestCase):\n\n def test_permute(self):\n perms = ['abc', 'bac', 'bca', 'acb', 'cab', 'cba']\n self.assertEqual(perms, permute(\"abc\"))\n\n def test_permute_iter(self):\n it = permute_iter(\"abc\")\n perms = ['abc', 'bac', 'bca', 'acb', 'cab', 'cba']\n for i in range(len(perms)):\n self.assertEqual(perms[i], next(it))\n\n def test_angram(self):\n self.assertTrue(anagram('apple', 'pleap'))\n self.assertFalse(anagram(\"apple\", \"cherry\"))\n\n\nclass TestArrayCombinationSum(unittest.TestCase):\n\n def test_array_sum_combinations(self):\n A = [1, 2, 3, 3]\n B = [2, 3, 3, 4]\n C = [2, 3, 3, 4]\n target = 7\n answer = [[1, 2, 4], [1, 3, 3], [1, 3, 3], [1, 3, 3],\n [1, 3, 3], [1, 4, 2], [2, 2, 3], [2, 2, 3],\n [2, 3, 2], [2, 3, 2], [3, 2, 2], [3, 2, 2]]\n answer.sort()\n self.assertListEqual(sorted(array_sum_combinations(A, B, C, target)),\n answer)\n\n def test_unique_array_sum_combinations(self):\n A = [1, 2, 3, 3]\n B = [2, 3, 3, 4]\n C = [2, 3, 3, 4]\n target = 7\n answer = [(2, 3, 2), (3, 2, 2), (1, 2, 4),\n (1, 4, 2), (2, 2, 3), (1, 3, 3)]\n answer.sort()\n self.assertListEqual(sorted(unique_array_sum_combinations(A, B, C,\n target)),\n answer)\n\n\nclass TestCombinationSum(unittest.TestCase):\n\n def check_sum(self, nums, target):\n if sum(nums) == target:\n return (True, nums)\n else:\n return (False, nums)\n\n def test_combination_sum(self):\n candidates1 = [2, 3, 6, 7]\n target1 = 7\n answer1 = [\n [2, 2, 3],\n [7]\n ]\n self.assertEqual(combination_sum(candidates1, target1), answer1)\n\n candidates2 = [2, 3, 5]\n target2 = 8\n answer2 = [\n [2, 2, 2, 2],\n [2, 3, 3],\n [3, 5]\n ]\n self.assertEqual(combination_sum(candidates2, target2), answer2)\n\n\nclass TestFactorCombinations(unittest.TestCase):\n\n def test_get_factors(self):\n target1 = 32\n answer1 = [\n [2, 16],\n [2, 2, 8],\n [2, 2, 2, 4],\n [2, 2, 2, 2, 2],\n [2, 4, 4],\n [4, 8]\n ]\n self.assertEqual(sorted(get_factors(target1)), sorted(answer1))\n\n target2 = 12\n answer2 = [\n [2, 6],\n [2, 2, 3],\n [3, 4]\n ]\n self.assertEqual(sorted(get_factors(target2)), sorted(answer2))\n self.assertEqual(sorted(get_factors(1)), [])\n self.assertEqual(sorted(get_factors(37)), [])\n\n def test_recursive_get_factors(self):\n target1 = 32\n answer1 = [\n [2, 16],\n [2, 2, 8],\n [2, 2, 2, 4],\n [2, 2, 2, 2, 2],\n [2, 4, 4],\n [4, 8]\n ]\n self.assertEqual(sorted(recursive_get_factors(target1)),\n sorted(answer1))\n\n target2 = 12\n answer2 = [\n [2, 6],\n [2, 2, 3],\n [3, 4]\n ]\n self.assertEqual(sorted(recursive_get_factors(target2)),\n sorted(answer2))\n self.assertEqual(sorted(recursive_get_factors(1)), [])\n self.assertEqual(sorted(recursive_get_factors(37)), [])\n\n\nclass TestFindWords(unittest.TestCase):\n\n def test_normal(self):\n board = [\n ['o', 'a', 'a', 'n'],\n ['e', 't', 'a', 'e'],\n ['i', 'h', 'k', 'r'],\n ['i', 'f', 'l', 'v']\n ]\n\n words = [\"oath\", \"pea\", \"eat\", \"rain\"]\n result = find_words(board, words)\n test_result = ['oath', 'eat']\n self.assertEqual(sorted(result),sorted(test_result))\n\n def test_none(self):\n board = [\n ['o', 'a', 'a', 'n'],\n ['e', 't', 'a', 'e'],\n ['i', 'h', 'k', 'r'],\n ['i', 'f', 'l', 'v']\n ]\n\n words = [\"chicken\", \"nugget\", \"hello\", \"world\"]\n self.assertEqual(find_words(board, words), [])\n\n def test_empty(self):\n board = []\n words = []\n self.assertEqual(find_words(board, words), [])\n\n def test_uneven(self):\n board = [\n ['o', 'a', 'a', 'n'],\n ['e', 't', 'a', 'e']\n ]\n words = [\"oath\", \"pea\", \"eat\", \"rain\"]\n self.assertEqual(find_words(board, words), ['eat'])\n\n def test_repeat(self):\n board = [\n ['a', 'a', 'a'],\n ['a', 'a', 'a'],\n ['a', 'a', 'a']\n ]\n words = [\"a\", \"aa\", \"aaa\", \"aaaa\", \"aaaaa\"]\n self.assertTrue(len(find_words(board, words)) == 5)\n\n\nclass TestGenerateAbbreviations(unittest.TestCase):\n def test_generate_abbreviations(self):\n word1 = \"word\"\n answer1 = ['word', 'wor1', 'wo1d', 'wo2', 'w1rd', 'w1r1', 'w2d', 'w3',\n '1ord', '1or1', '1o1d', '1o2', '2rd', '2r1', '3d', '4']\n self.assertEqual(sorted(generate_abbreviations(word1)),\n sorted(answer1))\n\n word2 = \"hello\"\n answer2 = ['hello', 'hell1', 'hel1o', 'hel2', 'he1lo', 'he1l1', 'he2o',\n 'he3', 'h1llo', 'h1ll1', 'h1l1o', 'h1l2', 'h2lo', 'h2l1',\n 'h3o', 'h4', '1ello', '1ell1', '1el1o', '1el2', '1e1lo',\n '1e1l1', '1e2o', '1e3', '2llo', '2ll1', '2l1o', '2l2',\n '3lo', '3l1', '4o', '5']\n self.assertEqual(sorted(generate_abbreviations(word2)),\n sorted(answer2))\n\n\nclass TestPatternMatch(unittest.TestCase):\n\n def test_pattern_match(self):\n pattern1 = \"abab\"\n string1 = \"redblueredblue\"\n pattern2 = \"aaaa\"\n string2 = \"asdasdasdasd\"\n pattern3 = \"aabb\"\n string3 = \"xyzabcxzyabc\"\n\n self.assertTrue(pattern_match(pattern1, string1))\n self.assertTrue(pattern_match(pattern2, string2))\n self.assertFalse(pattern_match(pattern3, string3))\n\n\nclass TestGenerateParenthesis(unittest.TestCase):\n\n def test_generate_parenthesis(self):\n self.assertEqual(generate_parenthesis_v1(2), ['()()', '(())'])\n self.assertEqual(generate_parenthesis_v1(3), ['()()()', '()(())',\n '(())()', '(()())', '((()))'])\n self.assertEqual(generate_parenthesis_v2(2), ['(())', '()()'])\n self.assertEqual(generate_parenthesis_v2(3), ['((()))', '(()())',\n '(())()', '()(())', '()()()'])\n\n\nclass TestLetterCombinations(unittest.TestCase):\n\n def test_letter_combinations(self):\n digit1 = \"23\"\n answer1 = [\"ad\", \"ae\", \"af\", \"bd\", \"be\", \"bf\", \"cd\", \"ce\", \"cf\"]\n self.assertEqual(sorted(letter_combinations(digit1)), sorted(answer1))\n\n digit2 = \"34\"\n answer2 = ['dg', 'dh', 'di', 'eg', 'eh', 'ei', 'fg', 'fh', 'fi']\n self.assertEqual(sorted(letter_combinations(digit2)), sorted(answer2))\n\n\nclass TestPalindromicSubstrings(unittest.TestCase):\n\n def test_palindromic_substrings(self):\n string1 = \"abc\"\n answer1 = [['a', 'b', 'c']]\n self.assertEqual(palindromic_substrings(string1), sorted(answer1))\n\n string2 = \"abcba\"\n answer2 = [['abcba'], ['a', 'bcb', 'a'], ['a', 'b', 'c', 'b', 'a']]\n self.assertEqual(sorted(palindromic_substrings(string2)),\n sorted(answer2))\n\n string3 = \"abcccba\"\n answer3 = [['abcccba'], ['a', 'bcccb', 'a'],\n ['a', 'b', 'ccc', 'b', 'a'],\n ['a', 'b', 'cc', 'c', 'b', 'a'],\n ['a', 'b', 'c', 'cc', 'b', 'a'],\n ['a', 'b', 'c', 'c', 'c', 'b', 'a']]\n self.assertEqual(sorted(palindromic_substrings(string3)),\n sorted(answer3))\n\n\nclass TestPermuteUnique(unittest.TestCase):\n\n def test_permute_unique(self):\n nums1 = [1, 1, 2]\n answer1 = [[2, 1, 1], [1, 2, 1], [1, 1, 2]]\n self.assertEqual(sorted(permute_unique(nums1)), sorted(answer1))\n\n nums2 = [1, 2, 1, 3]\n answer2 = [[3, 1, 2, 1], [1, 3, 2, 1], [1, 2, 3, 1], [1, 2, 1, 3],\n [3, 2, 1, 1], [2, 3, 1, 1], [2, 1, 3, 1], [2, 1, 1, 3],\n [3, 1, 1, 2], [1, 3, 1, 2], [1, 1, 3, 2], [1, 1, 2, 3]]\n self.assertEqual(sorted(permute_unique(nums2)), sorted(answer2))\n\n nums3 = [1, 2, 3]\n answer3 = [[3, 2, 1], [2, 3, 1], [2, 1, 3], [3, 1, 2],\n [1, 3, 2], [1, 2, 3]]\n self.assertEqual(sorted(permute_unique(nums3)), sorted(answer3))\n\n\nclass TestPermute(unittest.TestCase):\n\n def test_permute(self):\n nums1 = [1, 2, 3, 4]\n answer1 = [[1, 2, 3, 4], [2, 1, 3, 4], [2, 3, 1, 4], [2, 3, 4, 1],\n [1, 3, 2, 4], [3, 1, 2, 4], [3, 2, 1, 4], [3, 2, 4, 1],\n [1, 3, 4, 2], [3, 1, 4, 2], [3, 4, 1, 2], [3, 4, 2, 1],\n [1, 2, 4, 3], [2, 1, 4, 3], [2, 4, 1, 3], [2, 4, 3, 1],\n [1, 4, 2, 3], [4, 1, 2, 3], [4, 2, 1, 3], [4, 2, 3, 1],\n [1, 4, 3, 2], [4, 1, 3, 2], [4, 3, 1, 2], [4, 3, 2, 1]]\n self.assertEqual(sorted(permute(nums1)), sorted(answer1))\n\n nums2 = [1, 2, 3]\n answer2 = [[3, 2, 1], [2, 3, 1], [2, 1, 3], [3, 1, 2],\n [1, 3, 2], [1, 2, 3]]\n self.assertEqual(sorted(permute(nums2)), sorted(answer2))\n\n def test_permute_recursive(self):\n nums1 = [1, 2, 3, 4]\n answer1 = [[1, 2, 3, 4], [2, 1, 3, 4], [2, 3, 1, 4], [2, 3, 4, 1],\n [1, 3, 2, 4], [3, 1, 2, 4], [3, 2, 1, 4], [3, 2, 4, 1],\n [1, 3, 4, 2], [3, 1, 4, 2], [3, 4, 1, 2], [3, 4, 2, 1],\n [1, 2, 4, 3], [2, 1, 4, 3], [2, 4, 1, 3], [2, 4, 3, 1],\n [1, 4, 2, 3], [4, 1, 2, 3], [4, 2, 1, 3], [4, 2, 3, 1],\n [1, 4, 3, 2], [4, 1, 3, 2], [4, 3, 1, 2], [4, 3, 2, 1]]\n self.assertEqual(sorted(permute_recursive(nums1)), sorted(answer1))\n\n nums2 = [1, 2, 3]\n answer2 = [[3, 2, 1], [2, 3, 1], [2, 1, 3], [3, 1, 2],\n [1, 3, 2], [1, 2, 3]]\n self.assertEqual(sorted(permute_recursive(nums2)), sorted(answer2))\n\n\nclass TestSubsetsUnique(unittest.TestCase):\n\n def test_subsets_unique(self):\n nums1 = [1, 2, 2]\n answer1 = [(1, 2), (1,), (1, 2, 2), (2,), (), (2, 2)]\n self.assertEqual(sorted(subsets_unique(nums1)), sorted(answer1))\n\n nums2 = [1, 2, 3, 4]\n answer2 = [(1, 2), (1, 3), (1, 2, 3, 4), (1,), (2,), (3,),\n (1, 4), (1, 2, 3), (4,), (), (2, 3), (1, 2, 4),\n (1, 3, 4), (2, 3, 4), (3, 4), (2, 4)]\n self.assertEqual(sorted(subsets_unique(nums2)), sorted(answer2))\n\n\nclass TestSubsets(unittest.TestCase):\n\n def test_subsets(self):\n nums1 = [1, 2, 3]\n answer1 = [[1, 2, 3], [1, 2], [1, 3], [1], [2, 3], [2], [3], []]\n self.assertEqual(sorted(subsets(nums1)), sorted(answer1))\n\n nums2 = [1, 2, 3, 4]\n answer2 = [[1, 2, 3, 4], [1, 2, 3], [1, 2, 4], [1, 2], [1, 3, 4],\n [1, 3], [1, 4], [1], [2, 3, 4], [2, 3], [2, 4], [2],\n [3, 4], [3], [4], []]\n self.assertEqual(sorted(subsets(nums2)), sorted(answer2))\n\n def test_subsets_v2(self):\n nums1 = [1, 2, 3]\n answer1 = [[1, 2, 3], [1, 2], [1, 3], [1], [2, 3], [2], [3], []]\n self.assertEqual(sorted(subsets_v2(nums1)), sorted(answer1))\n\n nums2 = [1, 2, 3, 4]\n answer2 = [[1, 2, 3, 4], [1, 2, 3], [1, 2, 4], [1, 2], [1, 3, 4],\n [1, 3], [1, 4], [1], [2, 3, 4], [2, 3], [2, 4], [2],\n [3, 4], [3], [4], []]\n self.assertEqual(sorted(subsets_v2(nums2)), sorted(answer2))\n\n\nif __name__ == '__main__':\n\n unittest.main()\n"} +{"Prompt":"hit hot dot dog cog pick sick sink sank tank 5 live life 1, no matter what is the wordlist. 0 length from ate ate not possible to reach !","Completions":"from algorithms.bfs import (\n count_islands,\n maze_search,\n ladder_length\n)\n\nimport unittest\n\n\nclass TestCountIslands(unittest.TestCase):\n\n def test_count_islands(self):\n grid_1 = [[1, 1, 1, 1, 0], [1, 1, 0, 1, 0], [1, 1, 0, 0, 0],\n [0, 0, 0, 0, 0]]\n self.assertEqual(1, count_islands(grid_1))\n grid_2 = [[1, 1, 0, 0, 0], [1, 1, 0, 0, 0], [0, 0, 1, 0, 0],\n [0, 0, 0, 1, 1]]\n self.assertEqual(3, count_islands(grid_2))\n grid_3 = [[1, 1, 1, 0, 0, 0], [1, 1, 0, 0, 0, 0], [1, 0, 0, 0, 0, 1],\n [0, 0, 1, 1, 0, 1], [0, 0, 1, 1, 0, 0]]\n self.assertEqual(3, count_islands(grid_3))\n grid_4 = [[1, 1, 0, 0, 1, 1], [0, 0, 1, 1, 0, 0], [0, 0, 0, 0, 0, 1],\n [1, 1, 1, 1, 0, 0]]\n self.assertEqual(5, count_islands(grid_4))\n\n\nclass TestMazeSearch(unittest.TestCase):\n\n def test_maze_search(self):\n grid_1 = [[1, 0, 1, 1, 1, 1], [1, 0, 1, 0, 1, 0], [1, 0, 1, 0, 1, 1],\n [1, 1, 1, 0, 1, 1]]\n self.assertEqual(14, maze_search(grid_1))\n grid_2 = [[1, 0, 0], [0, 1, 1], [0, 1, 1]]\n self.assertEqual(-1, maze_search(grid_2))\n\n\nclass TestWordLadder(unittest.TestCase):\n\n def test_ladder_length(self):\n\n # hit -> hot -> dot -> dog -> cog\n self.assertEqual(5, ladder_length('hit', 'cog', [\"hot\", \"dot\", \"dog\",\n \"lot\", \"log\"]))\n\n # pick -> sick -> sink -> sank -> tank == 5\n self.assertEqual(5, ladder_length('pick', 'tank',\n ['tock', 'tick', 'sank', 'sink',\n 'sick']))\n\n # live -> life == 1, no matter what is the word_list.\n self.assertEqual(1, ladder_length('live', 'life', ['hoho', 'luck']))\n\n # 0 length from ate -> ate\n self.assertEqual(0, ladder_length('ate', 'ate', []))\n\n # not possible to reach !\n self.assertEqual(-1, ladder_length('rahul', 'coder', ['blahh',\n 'blhah']))\n\n\nif __name__ == \"__main__\":\n unittest.main()\n"} +{"Prompt":"Initialize seed. random.seedtest def testaddbitwiseoperatorself: self.assertEqual5432 97823, addbitwiseoperator5432, 97823 self.assertEqual0, addbitwiseoperator0, 0 self.assertEqual10, addbitwiseoperator10, 0 self.assertEqual10, addbitwiseoperator0, 10 def testcountonesrecurself: 8 1000 self.assertEqual1, countonesrecur8 109 1101101 self.assertEqual5, countonesrecur109 63 111111 self.assertEqual6, countonesrecur63 0 0 self.assertEqual0, countonesrecur0 def testcountonesiterself: 8 1000 self.assertEqual1, countonesiter8 109 1101101 self.assertEqual5, countonesiter109 63 111111 self.assertEqual6, countonesiter63 0 0 self.assertEqual0, countonesiter0 def testcountflipstoconvertself: 29: 11101 and 15: 01111 self.assertEqual2, countflipstoconvert29, 15 45: 0000101101 and 987: 1111011011 self.assertEqual8, countflipstoconvert45, 987 34: 100010 self.assertEqual0, countflipstoconvert34, 34 34: 100010 and 53: 110101 self.assertEqual4, countflipstoconvert34, 53 def testfindmissingnumberself: self.assertEqual7, findmissingnumber4, 1, 3, 0, 6, 5, 2 self.assertEqual0, findmissingnumber1 self.assertEqual1, findmissingnumber0 nums i for i in range100000 if i ! 12345 random.shufflenums self.assertEqual12345, findmissingnumbernums def testfindmissingnumber2self: self.assertEqual7, findmissingnumber24, 1, 3, 0, 6, 5, 2 self.assertEqual0, findmissingnumber21 self.assertEqual1, findmissingnumber20 nums i for i in range100000 if i ! 12345 random.shufflenums self.assertEqual12345, findmissingnumber2nums def testflipbitlongestseqself: 1775: 11011101111 self.assertEqual8, flipbitlongestseq1775 5: 101 self.assertEqual3, flipbitlongestseq5 71: 1000111 self.assertEqual4, flipbitlongestseq71 0: 0 self.assertEqual1, flipbitlongestseq0 def testispoweroftwoself: self.assertTrueispoweroftwo64 self.assertFalseispoweroftwo91 self.assertTrueispoweroftwo21001 self.assertTrueispoweroftwo1 self.assertFalseispoweroftwo0 def testreversebitsself: self.assertEqual43261596, reversebits964176192 self.assertEqual964176192, reversebits43261596 self.assertEqual1, reversebits2147483648 bin0 00000000000000000000000000000000 self.assertEqual0, reversebits0 bin232 1 11111111111111111111111111111111 self.assertEqual232 1, reversebits232 1 def testsinglenumberself: random.seed'test' self.assertEqual0, singlenumber1, 0, 2, 1, 2, 3, 3 self.assertEqual101, singlenumber101 single random.randint1, 100000 nums random.randint1, 100000 for in range1000 nums 2 nums contains pairs of random integers nums.appendsingle random.shufflenums self.assertEqualsingle, singlenumbernums def testsinglenumber2self: self.assertEqual3, singlenumber24, 2, 3, 2, 1, 1, 4, 2, 4, 1 single random.randint1, 100000 nums random.randint1, 100000 for in range1000 nums 3 nums contains triplets of random integers nums.appendsingle random.shufflenums self.assertEqualsingle, singlenumber2nums def testsinglenumber3self: self.assertEqualsorted2, 5, sortedsinglenumber32, 1, 5, 6, 6, 1 self.assertEqualsorted4, 3, sortedsinglenumber39, 9, 4, 3 def testsubsetsself: self.assertSetEqualsubsets1, 2, 3, , 1,, 2,, 3,, 1, 2, 1, 3, 2, 3, 1, 2, 3 self.assertSetEqualsubsets10, 20, 30, 40, 10, 40, 10, 20, 40, 10, 30, 10, 20, 30, 40, 40,, 10, 30, 40, 30,, 20, 30, 30, 40, 10,, , 10, 20, 20, 40, 20, 30, 40, 10, 20, 30, 20, def testgetbitself: 22 10110 self.assertEqual1, getbit22, 2 self.assertEqual0, getbit22, 3 def testsetbitself: 22 10110 after set bit at 3th position: 30 11110 self.assertEqual30, setbit22, 3 def testclearbitself: 22 10110 after clear bit at 2nd position: 20 10010 self.assertEqual18, clearbit22, 2 def testupdatebitself: 22 10110 after update bit at 3th position with value 1: 30 11110 self.assertEqual30, updatebit22, 3, 1 22 10110 after update bit at 2nd position with value 0: 20 10010 self.assertEqual18, updatebit22, 2, 0 def testinttobytesbigendianself: self.assertEqualb'x11', inttobytesbigendian17 def testinttobyteslittleendianself: self.assertEqualb'x11', inttobyteslittleendian17 def testbytesbigendiantointself: self.assertEqual17, bytesbigendiantointb'x11' def testbyteslittleendiantointself: self.assertEqual17, byteslittleendiantointb'x11' def testswappairself: 22: 10110 41: 101001 self.assertEqual41, swappair22 10: 1010 5 : 0101 self.assertEqual5, swappair10 def testfinddifferenceself: self.assertEqual'e', finddifferenceabcd, abecd def testhasalternativebitself: self.assertTruehasalternativebit5 self.assertFalsehasalternativebit7 self.assertFalsehasalternativebit11 self.assertTruehasalternativebit10 def testhasalternativebitfastself: self.assertTruehasalternativebitfast5 self.assertFalsehasalternativebitfast7 self.assertFalsehasalternativebitfast11 self.assertTruehasalternativebitfast10 def testinsertonebitself: self.assertEqual45, insertonebit21, 1, 2 self.assertEqual41, insertonebit21, 0, 2 self.assertEqual53, insertonebit21, 1, 5 self.assertEqual43, insertonebit21, 1, 0 def testinsertmultbitsself: self.assertEqual47, insertmultbits5, 7, 3, 1 self.assertEqual47, insertmultbits5, 7, 3, 0 self.assertEqual61, insertmultbits5, 7, 3, 3 def testremovebitself: self.assertEqual9, removebit21, 2 self.assertEqual5, removebit21, 4 self.assertEqual10, removebit21, 0 def testbinarygapself: 22 10110 self.assertEqual2, binarygap22 6 110 self.assertEqual1, binarygap6 8 1000 self.assertEqual0, binarygap8 145 10010001 self.assertEqual4, binarygap145 if name 'main': unittest.main","Completions":"from algorithms.bit import (\n add_bitwise_operator,\n count_ones_iter, count_ones_recur,\n count_flips_to_convert,\n find_missing_number, find_missing_number2,\n flip_bit_longest_seq,\n is_power_of_two,\n reverse_bits,\n single_number,\n single_number2,\n single_number3,\n subsets,\n get_bit, set_bit, clear_bit, update_bit,\n int_to_bytes_big_endian, int_to_bytes_little_endian,\n bytes_big_endian_to_int, bytes_little_endian_to_int,\n swap_pair,\n find_difference,\n has_alternative_bit, has_alternative_bit_fast,\n insert_one_bit, insert_mult_bits,\n remove_bit,\n binary_gap\n)\n\nimport unittest\nimport random\n\n\nclass TestSuite(unittest.TestCase):\n\n def setUp(self):\n \"\"\"Initialize seed.\"\"\"\n random.seed(\"test\")\n\n def test_add_bitwise_operator(self):\n self.assertEqual(5432 + 97823, add_bitwise_operator(5432, 97823))\n self.assertEqual(0, add_bitwise_operator(0, 0))\n self.assertEqual(10, add_bitwise_operator(10, 0))\n self.assertEqual(10, add_bitwise_operator(0, 10))\n\n def test_count_ones_recur(self):\n\n # 8 -> 1000\n self.assertEqual(1, count_ones_recur(8))\n\n # 109 -> 1101101\n self.assertEqual(5, count_ones_recur(109))\n\n # 63 -> 111111\n self.assertEqual(6, count_ones_recur(63))\n\n # 0 -> 0\n self.assertEqual(0, count_ones_recur(0))\n\n def test_count_ones_iter(self):\n\n # 8 -> 1000\n self.assertEqual(1, count_ones_iter(8))\n\n # 109 -> 1101101\n self.assertEqual(5, count_ones_iter(109))\n\n # 63 -> 111111\n self.assertEqual(6, count_ones_iter(63))\n\n # 0 -> 0\n self.assertEqual(0, count_ones_iter(0))\n\n def test_count_flips_to_convert(self):\n # 29: 11101 and 15: 01111\n self.assertEqual(2, count_flips_to_convert(29, 15))\n # 45: 0000101101 and 987: 1111011011\n self.assertEqual(8, count_flips_to_convert(45, 987))\n # 34: 100010\n self.assertEqual(0, count_flips_to_convert(34, 34))\n # 34: 100010 and 53: 110101\n self.assertEqual(4, count_flips_to_convert(34, 53))\n\n def test_find_missing_number(self):\n\n self.assertEqual(7, find_missing_number([4, 1, 3, 0, 6, 5, 2]))\n self.assertEqual(0, find_missing_number([1]))\n self.assertEqual(1, find_missing_number([0]))\n\n nums = [i for i in range(100000) if i != 12345]\n random.shuffle(nums)\n self.assertEqual(12345, find_missing_number(nums))\n\n def test_find_missing_number2(self):\n\n self.assertEqual(7, find_missing_number2([4, 1, 3, 0, 6, 5, 2]))\n self.assertEqual(0, find_missing_number2([1]))\n self.assertEqual(1, find_missing_number2([0]))\n\n nums = [i for i in range(100000) if i != 12345]\n random.shuffle(nums)\n self.assertEqual(12345, find_missing_number2(nums))\n\n def test_flip_bit_longest_seq(self):\n # 1775: 11011101111\n self.assertEqual(8, flip_bit_longest_seq(1775))\n # 5: 101\n self.assertEqual(3, flip_bit_longest_seq(5))\n # 71: 1000111\n self.assertEqual(4, flip_bit_longest_seq(71))\n # 0: 0\n self.assertEqual(1, flip_bit_longest_seq(0))\n\n def test_is_power_of_two(self):\n\n self.assertTrue(is_power_of_two(64))\n self.assertFalse(is_power_of_two(91))\n self.assertTrue(is_power_of_two(2**1001))\n self.assertTrue(is_power_of_two(1))\n self.assertFalse(is_power_of_two(0))\n\n def test_reverse_bits(self):\n\n self.assertEqual(43261596, reverse_bits(964176192))\n self.assertEqual(964176192, reverse_bits(43261596))\n self.assertEqual(1, reverse_bits(2147483648))\n\n # bin(0) => 00000000000000000000000000000000\n self.assertEqual(0, reverse_bits(0))\n\n # bin(2**32 - 1) => 11111111111111111111111111111111\n self.assertEqual(2**32 - 1, reverse_bits(2**32 - 1))\n\n def test_single_number(self):\n\n random.seed('test')\n\n self.assertEqual(0, single_number([1, 0, 2, 1, 2, 3, 3]))\n self.assertEqual(101, single_number([101]))\n\n single = random.randint(1, 100000)\n nums = [random.randint(1, 100000) for _ in range(1000)]\n nums *= 2 # nums contains pairs of random integers\n nums.append(single)\n random.shuffle(nums)\n\n self.assertEqual(single, single_number(nums))\n\n def test_single_number2(self):\n\n self.assertEqual(3, single_number2([4, 2, 3, 2, 1, 1, 4, 2, 4, 1]))\n single = random.randint(1, 100000)\n nums = [random.randint(1, 100000) for _ in range(1000)]\n nums *= 3 # nums contains triplets of random integers\n nums.append(single)\n random.shuffle(nums)\n self.assertEqual(single, single_number2(nums))\n\n def test_single_number3(self):\n self.assertEqual(sorted([2, 5]),\n sorted(single_number3([2, 1, 5, 6, 6, 1])))\n self.assertEqual(sorted([4, 3]),\n sorted(single_number3([9, 9, 4, 3])))\n\n def test_subsets(self):\n\n self.assertSetEqual(subsets([1, 2, 3]),\n {(), (1,), (2,), (3,), (1, 2), (1, 3), (2, 3),\n (1, 2, 3)})\n\n self.assertSetEqual(subsets([10, 20, 30, 40]),\n {(10, 40), (10, 20, 40), (10, 30),\n (10, 20, 30, 40), (40,),\n (10, 30, 40), (30,), (20, 30), (30, 40), (10,),\n (),\n (10, 20), (20, 40), (20, 30, 40), (10, 20, 30),\n (20,)})\n\n def test_get_bit(self):\n # 22 = 10110\n self.assertEqual(1, get_bit(22, 2))\n self.assertEqual(0, get_bit(22, 3))\n\n def test_set_bit(self):\n # 22 = 10110 --> after set bit at 3th position: 30 = 11110\n self.assertEqual(30, set_bit(22, 3))\n\n def test_clear_bit(self):\n # 22 = 10110 --> after clear bit at 2nd position: 20 = 10010\n self.assertEqual(18, clear_bit(22, 2))\n\n def test_update_bit(self):\n # 22 = 10110 --> after update bit at 3th position with\n # value 1: 30 = 11110\n self.assertEqual(30, update_bit(22, 3, 1))\n # 22 = 10110 --> after update bit at 2nd position with\n # value 0: 20 = 10010\n self.assertEqual(18, update_bit(22, 2, 0))\n\n def test_int_to_bytes_big_endian(self):\n self.assertEqual(b'\\x11', int_to_bytes_big_endian(17))\n\n def test_int_to_bytes_little_endian(self):\n self.assertEqual(b'\\x11', int_to_bytes_little_endian(17))\n\n def test_bytes_big_endian_to_int(self):\n self.assertEqual(17, bytes_big_endian_to_int(b'\\x11'))\n\n def test_bytes_little_endian_to_int(self):\n self.assertEqual(17, bytes_little_endian_to_int(b'\\x11'))\n\n def test_swap_pair(self):\n # 22: 10110 --> 41: 101001\n self.assertEqual(41, swap_pair(22))\n # 10: 1010 --> 5 : 0101\n self.assertEqual(5, swap_pair(10))\n\n def test_find_difference(self):\n self.assertEqual('e', find_difference(\"abcd\", \"abecd\"))\n\n def test_has_alternative_bit(self):\n self.assertTrue(has_alternative_bit(5))\n self.assertFalse(has_alternative_bit(7))\n self.assertFalse(has_alternative_bit(11))\n self.assertTrue(has_alternative_bit(10))\n\n def test_has_alternative_bit_fast(self):\n self.assertTrue(has_alternative_bit_fast(5))\n self.assertFalse(has_alternative_bit_fast(7))\n self.assertFalse(has_alternative_bit_fast(11))\n self.assertTrue(has_alternative_bit_fast(10))\n\n def test_insert_one_bit(self):\n \"\"\"\n Input: num = 10101 (21)\n insert_one_bit(num, 1, 2): 101101 (45)\n insert_one_bit(num, 0 ,2): 101001 (41)\n insert_one_bit(num, 1, 5): 110101 (53)\n insert_one_bit(num, 1, 0): 101010 (42)\n \"\"\"\n self.assertEqual(45, insert_one_bit(21, 1, 2))\n self.assertEqual(41, insert_one_bit(21, 0, 2))\n self.assertEqual(53, insert_one_bit(21, 1, 5))\n self.assertEqual(43, insert_one_bit(21, 1, 0))\n\n def test_insert_mult_bits(self):\n \"\"\"\n Input: num = 101 (5)\n insert_mult_bits(num, 7, 3, 1): 101111 (47)\n insert_mult_bits(num, 7, 3, 0): 101111 (47)\n insert_mult_bits(num, 7, 3, 3): 111101 (61)\n \"\"\"\n self.assertEqual(47, insert_mult_bits(5, 7, 3, 1))\n self.assertEqual(47, insert_mult_bits(5, 7, 3, 0))\n self.assertEqual(61, insert_mult_bits(5, 7, 3, 3))\n\n def test_remove_bit(self):\n \"\"\"\n Input: num = 10101 (21)\n remove_bit(num, 2): output = 1001 (9)\n remove_bit(num, 4): output = 101 (5)\n remove_bit(num, 0): output = 1010 (10)\n \"\"\"\n self.assertEqual(9, remove_bit(21, 2))\n self.assertEqual(5, remove_bit(21, 4))\n self.assertEqual(10, remove_bit(21, 0))\n\n def test_binary_gap(self):\n # 22 = 10110\n self.assertEqual(2, binary_gap(22))\n # 6 = 110\n self.assertEqual(1, binary_gap(6))\n # 8 = 1000\n self.assertEqual(0, binary_gap(8))\n # 145 = 10010001\n self.assertEqual(4, binary_gap(145))\n\n\nif __name__ == '__main__':\n unittest.main()\n"} +{"Prompt":"summary Test for the file hosoyatriangle Arguments: unittest type description Test 1 Test 2 Test 3 Test 4 Test 5 arrange act assert arrange act assert E.g. s a b b p 1 0 0 0 a 0 1 0 0 b 0 0 1 0 0 1 1 1","Completions":"from algorithms.dp import (\n max_profit_naive, max_profit_optimized,\n climb_stairs, climb_stairs_optimized,\n count,\n combination_sum_topdown, combination_sum_bottom_up,\n edit_distance,\n egg_drop,\n fib_recursive, fib_list, fib_iter,\n hosoya_testing,\n house_robber,\n Job, schedule,\n Item, get_maximum_value,\n longest_increasing_subsequence,\n longest_increasing_subsequence_optimized,\n longest_increasing_subsequence_optimized2,\n int_divide,find_k_factor,\n planting_trees, regex_matching\n)\n\n\nimport unittest\n\n\nclass TestBuySellStock(unittest.TestCase):\n def test_max_profit_naive(self):\n self.assertEqual(max_profit_naive([7, 1, 5, 3, 6, 4]), 5)\n self.assertEqual(max_profit_naive([7, 6, 4, 3, 1]), 0)\n\n def test_max_profit_optimized(self):\n self.assertEqual(max_profit_optimized([7, 1, 5, 3, 6, 4]), 5)\n self.assertEqual(max_profit_optimized([7, 6, 4, 3, 1]), 0)\n\n\nclass TestClimbingStairs(unittest.TestCase):\n def test_climb_stairs(self):\n self.assertEqual(climb_stairs(2), 2)\n self.assertEqual(climb_stairs(10), 89)\n\n def test_climb_stairs_optimized(self):\n self.assertEqual(climb_stairs_optimized(2), 2)\n self.assertEqual(climb_stairs_optimized(10), 89)\n\n\nclass TestCoinChange(unittest.TestCase):\n def test_count(self):\n self.assertEqual(count([1, 2, 3], 4), 4)\n self.assertEqual(count([2, 5, 3, 6], 10), 5)\n\n\nclass TestCombinationSum(unittest.TestCase):\n def test_combination_sum_topdown(self):\n self.assertEqual(combination_sum_topdown([1, 2, 3], 4), 7)\n\n def test_combination_sum_bottom_up(self):\n self.assertEqual(combination_sum_bottom_up([1, 2, 3], 4), 7)\n\n\nclass TestEditDistance(unittest.TestCase):\n def test_edit_distance(self):\n self.assertEqual(edit_distance('food', 'money'), 4)\n self.assertEqual(edit_distance('horse', 'ros'), 3)\n\n\nclass TestEggDrop(unittest.TestCase):\n def test_egg_drop(self):\n self.assertEqual(egg_drop(1, 2), 2)\n self.assertEqual(egg_drop(2, 6), 3)\n self.assertEqual(egg_drop(3, 14), 4)\n\n\nclass TestFib(unittest.TestCase):\n def test_fib_recursive(self):\n self.assertEqual(fib_recursive(10), 55)\n self.assertEqual(fib_recursive(30), 832040)\n\n def test_fib_list(self):\n self.assertEqual(fib_list(10), 55)\n self.assertEqual(fib_list(30), 832040)\n\n def test_fib_iter(self):\n self.assertEqual(fib_iter(10), 55)\n self.assertEqual(fib_iter(30), 832040)\n\n\nclass TestHosoyaTriangle(unittest.TestCase):\n \"\"\"[summary]\n Test for the file hosoya_triangle\n\n Arguments:\n unittest {[type]} -- [description]\n \"\"\"\n\n def test_hosoya(self):\n self.assertEqual([1], hosoya_testing(1))\n self.assertEqual([1,\n 1, 1,\n 2, 1, 2,\n 3, 2, 2, 3,\n 5, 3, 4, 3, 5,\n 8, 5, 6, 6, 5, 8],\n hosoya_testing(6))\n self.assertEqual([1,\n 1, 1,\n 2, 1, 2,\n 3, 2, 2, 3,\n 5, 3, 4, 3, 5,\n 8, 5, 6, 6, 5, 8,\n 13, 8, 10, 9, 10, 8, 13,\n 21, 13, 16, 15, 15, 16, 13, 21,\n 34, 21, 26, 24, 25, 24, 26, 21, 34,\n 55, 34, 42, 39, 40, 40, 39, 42, 34, 55],\n hosoya_testing(10))\n\n\nclass TestHouseRobber(unittest.TestCase):\n def test_house_robber(self):\n self.assertEqual(44, house_robber([1, 2, 16, 3, 15, 3, 12, 1]))\n\n\nclass TestJobScheduling(unittest.TestCase):\n def test_job_scheduling(self):\n job1, job2 = Job(1, 3, 2), Job(2, 3, 4)\n self.assertEqual(4, schedule([job1, job2]))\n\n\nclass TestKnapsack(unittest.TestCase):\n def test_get_maximum_value(self):\n item1, item2, item3 = Item(60, 10), Item(100, 20), Item(120, 30)\n self.assertEqual(220, get_maximum_value([item1, item2, item3], 50))\n\n item1, item2, item3, item4 = Item(60, 5), Item(50, 3), Item(70, 4), Item(30, 2)\n self.assertEqual(80, get_maximum_value([item1, item2, item3, item4],\n 5))\n\n\nclass TestLongestIncreasingSubsequence(unittest.TestCase):\n def test_longest_increasing_subsequence(self):\n sequence = [1, 101, 10, 2, 3, 100, 4, 6, 2]\n self.assertEqual(5, longest_increasing_subsequence(sequence))\n\n\nclass TestLongestIncreasingSubsequenceOptimized(unittest.TestCase):\n def test_longest_increasing_subsequence_optimized(self):\n sequence = [1, 101, 10, 2, 3, 100, 4, 6, 2]\n self.assertEqual(5, longest_increasing_subsequence(sequence))\n\n\nclass TestLongestIncreasingSubsequenceOptimized2(unittest.TestCase):\n def test_longest_increasing_subsequence_optimized2(self):\n sequence = [1, 101, 10, 2, 3, 100, 4, 6, 2]\n self.assertEqual(5, longest_increasing_subsequence(sequence))\n\n\nclass TestIntDivide(unittest.TestCase):\n def test_int_divide(self):\n self.assertEqual(5, int_divide(4))\n self.assertEqual(42, int_divide(10))\n self.assertEqual(204226, int_divide(50))\n\n\nclass Test_dp_K_Factor(unittest.TestCase):\n def test_kfactor(self):\n # Test 1\n n1 = 4\n k1 = 1\n self.assertEqual(find_k_factor(n1, k1), 1)\n\n # Test 2\n n2 = 7\n k2 = 1\n self.assertEqual(find_k_factor(n2, k2), 70302)\n\n # Test 3\n n3 = 10\n k3 = 2\n self.assertEqual(find_k_factor(n3, k3), 74357)\n\n # Test 4\n n4 = 8\n k4 = 2\n self.assertEqual(find_k_factor(n4, k4), 53)\n\n # Test 5\n n5 = 9\n k5 = 1\n self.assertEqual(find_k_factor(n5, k5), 71284044)\n\n\nclass TestPlantingTrees(unittest.TestCase):\n def test_simple(self):\n # arrange\n trees = [0, 1, 10, 10]\n L = 10\n W = 1\n\n # act\n res = planting_trees(trees, L, W)\n\n # assert\n self.assertEqual(res, 2.414213562373095)\n\n def test_simple2(self):\n # arrange\n trees = [0, 3, 5, 5, 6, 9]\n L = 10\n W = 1\n\n # act\n res = planting_trees(trees, L, W)\n\n # assert\n self.assertEqual(res, 9.28538328578604)\n \nclass TestRegexMatching(unittest.TestCase):\n def test_none_0(self):\n s = \"\"\n p = \"\"\n self.assertTrue(regex_matching.is_match(s, p))\n\n def test_none_1(self):\n s = \"\"\n p = \"a\"\n self.assertFalse(regex_matching.is_match(s, p))\n\n def test_no_symbol_equal(self):\n s = \"abcd\"\n p = \"abcd\"\n self.assertTrue(regex_matching.is_match(s, p))\n\n def test_no_symbol_not_equal_0(self):\n s = \"abcd\"\n p = \"efgh\"\n self.assertFalse(regex_matching.is_match(s, p))\n\n def test_no_symbol_not_equal_1(self):\n s = \"ab\"\n p = \"abb\"\n self.assertFalse(regex_matching.is_match(s, p))\n\n def test_symbol_0(self):\n s = \"\"\n p = \"a*\"\n self.assertTrue(regex_matching.is_match(s, p))\n\n def test_symbol_1(self):\n s = \"a\"\n p = \"ab*\"\n self.assertTrue(regex_matching.is_match(s, p))\n\n def test_symbol_2(self):\n # E.g.\n # s a b b\n # p 1 0 0 0\n # a 0 1 0 0\n # b 0 0 1 0\n # * 0 1 1 1\n s = \"abb\"\n p = \"ab*\"\n self.assertTrue(regex_matching.is_match(s, p))\n\n\nif __name__ == '__main__':\n unittest.main()\n"} +{"Prompt":"Test for the file tarjan.py Arguments: unittest type description Graph from https:en.wikipedia.orgwikiFile:Scc.png Graph from https:en.wikipedia.orgwikiTarjan27sstronglyconnectedcomponentsalgorithmmediaFile:Tarjan27sAlgorithmAnimation.gif Test for the file maximumflow.py Arguments: unittest type description Test for the file def maximumflowbfs.py Arguments: unittest type description Test for the file def maximumflowdfs.py Arguments: unittest type description Class for testing different cases for connected components in graph Test Function that test the different cases of count connected components 20 15 3 4 output 3 adjacency list representation of graph input : output : 0 input : 0 2 3 4 output : 4","Completions":"from algorithms.graph import Tarjan\nfrom algorithms.graph import check_bipartite\nfrom algorithms.graph.dijkstra import Dijkstra\nfrom algorithms.graph import ford_fulkerson\nfrom algorithms.graph import edmonds_karp\nfrom algorithms.graph import dinic\nfrom algorithms.graph import maximum_flow_bfs\nfrom algorithms.graph import maximum_flow_dfs\nfrom algorithms.graph import all_pairs_shortest_path\nfrom algorithms.graph import bellman_ford\nfrom algorithms.graph import count_connected_number_of_component\nfrom algorithms.graph import prims_minimum_spanning\nfrom algorithms.graph import check_digraph_strongly_connected\nfrom algorithms.graph import cycle_detection\nfrom algorithms.graph import find_path\nfrom algorithms.graph import path_between_two_vertices_in_digraph\n\nimport unittest\n\n\nclass TestTarjan(unittest.TestCase):\n \"\"\"\n Test for the file tarjan.py\n\n Arguments:\n unittest {[type]} -- [description]\n \"\"\"\n\n def test_tarjan_example_1(self):\n # Graph from https:\/\/en.wikipedia.org\/wiki\/File:Scc.png\n example = {\n 'A': ['B'],\n 'B': ['C', 'E', 'F'],\n 'C': ['D', 'G'],\n 'D': ['C', 'H'],\n 'E': ['A', 'F'],\n 'F': ['G'],\n 'G': ['F'],\n 'H': ['D', 'G']\n }\n\n g = Tarjan(example)\n self.assertEqual(g.sccs, [['F', 'G'], ['C', 'D', 'H'],\n ['A', 'B', 'E']])\n\n def test_tarjan_example_2(self):\n # Graph from https:\/\/en.wikipedia.org\/wiki\/Tarjan%27s_strongly_connected_components_algorithm#\/media\/File:Tarjan%27s_Algorithm_Animation.gif\n example = {\n 'A': ['E'],\n 'B': ['A'],\n 'C': ['B', 'D'],\n 'D': ['C'],\n 'E': ['B'],\n 'F': ['B', 'E', 'G'],\n 'G': ['F', 'C'],\n 'H': ['G', 'H', 'D']\n }\n\n g = Tarjan(example)\n self.assertEqual(g.sccs, [['A', 'B', 'E'], ['C', 'D'], ['F', 'G'],\n ['H']])\n\n\nclass TestCheckBipartite(unittest.TestCase):\n def test_check_bipartite(self):\n adj_list_1 = [[0, 0, 1], [0, 0, 1], [1, 1, 0]]\n self.assertEqual(True, check_bipartite(adj_list_1))\n adj_list_2 = [[0, 1, 0, 1], [1, 0, 1, 0], [0, 1, 0, 1], [1, 0, 1, 0]]\n self.assertEqual(True, check_bipartite(adj_list_2))\n adj_list_3 = [[0, 1, 0, 0], [1, 0, 1, 1], [0, 1, 0, 1], [0, 1, 1, 0]]\n self.assertEqual(False, check_bipartite(adj_list_3))\n\n\nclass TestDijkstra(unittest.TestCase):\n def test_dijkstra(self):\n g = Dijkstra(9)\n g.graph = [[0, 4, 0, 0, 0, 0, 0, 8, 0],\n [4, 0, 8, 0, 0, 0, 0, 11, 0],\n [0, 8, 0, 7, 0, 4, 0, 0, 2],\n [0, 0, 7, 0, 9, 14, 0, 0, 0],\n [0, 0, 0, 9, 0, 10, 0, 0, 0],\n [0, 0, 4, 14, 10, 0, 2, 0, 0],\n [0, 0, 0, 0, 0, 2, 0, 1, 6],\n [8, 11, 0, 0, 0, 0, 1, 0, 7],\n [0, 0, 2, 0, 0, 0, 6, 7, 0]]\n\n self.assertEqual(g.dijkstra(0), [0, 4, 12, 19, 21, 11, 9, 8, 14])\n\n\nclass TestMaximumFlow(unittest.TestCase):\n \"\"\"\n Test for the file maximum_flow.py\n\n Arguments:\n unittest {[type]} -- [description]\n \"\"\"\n def test_ford_fulkerson(self):\n capacity = [\n [0, 10, 10, 0, 0, 0, 0],\n [0, 0, 2, 0, 4, 8, 0],\n [0, 0, 0, 0, 0, 9, 0],\n [0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 10],\n [0, 0, 0, 0, 6, 0, 10],\n [0, 0, 0, 0, 0, 0, 0]\n ]\n self.assertEqual(19, ford_fulkerson(capacity, 0, 6))\n\n def test_edmonds_karp(self):\n capacity = [\n [0, 10, 10, 0, 0, 0, 0],\n [0, 0, 2, 0, 4, 8, 0],\n [0, 0, 0, 0, 0, 9, 0],\n [0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 10],\n [0, 0, 0, 0, 6, 0, 10],\n [0, 0, 0, 0, 0, 0, 0]\n ]\n self.assertEqual(19, edmonds_karp(capacity, 0, 6))\n\n def dinic(self):\n capacity = [\n [0, 10, 10, 0, 0, 0, 0],\n [0, 0, 2, 0, 4, 8, 0],\n [0, 0, 0, 0, 0, 9, 0],\n [0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 10],\n [0, 0, 0, 0, 6, 0, 10],\n [0, 0, 0, 0, 0, 0, 0]\n ]\n self.assertEqual(19, dinic(capacity, 0, 6))\n\n\nclass TestMaximum_Flow_Bfs(unittest.TestCase):\n\n \"\"\"\n Test for the file def maximum_flow_bfs.py\n Arguments:\n unittest {[type]} -- [description]\n \"\"\"\n def test_maximum_flow_bfs(self):\n graph = [\n [0, 16, 13, 0, 0, 0],\n [0, 0, 10, 12, 0, 0],\n [0, 4, 0, 0, 14, 0],\n [0, 0, 9, 0, 0, 20],\n [0, 0, 0, 7, 0, 4],\n [0, 0, 0, 0, 0, 0]\n ]\n maximum_flow = maximum_flow_bfs(graph)\n\n self.assertEqual(maximum_flow, 23)\n\n\nclass TestMaximum_Flow_Dfs(unittest.TestCase):\n\n \"\"\"\n Test for the file def maximum_flow_dfs.py\n Arguments:\n unittest {[type]} -- [description]\n \"\"\"\n def test_maximum_flow_dfs(self):\n graph = [\n [0, 16, 13, 0, 0, 0],\n [0, 0, 10, 12, 0, 0],\n [0, 4, 0, 0, 14, 0],\n [0, 0, 9, 0, 0, 20],\n [0, 0, 0, 7, 0, 4],\n [0, 0, 0, 0, 0, 0]\n ]\n maximum_flow = maximum_flow_dfs(graph)\n\n self.assertEqual(maximum_flow, 23)\n\n\nclass TestAll_Pairs_Shortest_Path(unittest.TestCase):\n def test_all_pairs_shortest_path(self):\n graph = [[0, 0.1, 0.101, 0.142, 0.277],\n [0.465, 0, 0.191, 0.192, 0.587],\n [0.245, 0.554, 0, 0.333, 0.931],\n [1.032, 0.668, 0.656, 0, 0.151],\n [0.867, 0.119, 0.352, 0.398, 0]]\n result = all_pairs_shortest_path(graph)\n\n self.assertEqual(result, [\n [0, 0.1, 0.101, 0.142, 0.277],\n [0.436, 0, 0.191, 0.192,\n 0.34299999999999997],\n [0.245, 0.345, 0, 0.333, 0.484],\n [0.706, 0.27, 0.46099999999999997, 0,\n 0.151],\n [0.5549999999999999, 0.119, 0.31, 0.311,\n 0],\n ])\n\n\nclass TestBellmanFord(unittest.TestCase):\n def test_bellman_ford(self):\n graph1 = {\n 'a': {'b': 6, 'e': 7},\n 'b': {'c': 5, 'd': -4, 'e': 8},\n 'c': {'b': -2},\n 'd': {'a': 2, 'c': 7},\n 'e': {'b': -3}\n }\n self.assertEqual(True, bellman_ford(graph1, 'a'))\n graph2 = {\n 'a': {'d': 3, 'e': 4},\n 'b': {'a': 7, 'e': 2},\n 'c': {'a': 12, 'd': 9, 'e': 11},\n 'd': {'c': 5, 'e': 11},\n 'e': {'a': 7, 'b': 5, 'd': 1}\n }\n self.assertEqual(True, bellman_ford(graph2, 'a'))\n\n\nclass TestConnectedComponentInGraph(unittest.TestCase):\n \"\"\"\n Class for testing different cases for connected components in graph\n \"\"\"\n def test_count_connected_components(self):\n \"\"\"\n Test Function that test the different cases of count connected\n components\n 2----------0 1--------5 3\n |\n |\n 4\n output = 3\n \"\"\"\n expected_result = 3\n # adjacency list representation of graph\n l = [[2],\n [5],\n [0,4],\n [],\n [2],\n [1]]\n\n size = 5\n result = count_connected_number_of_component.count_components(l, size)\n self.assertEqual(result, expected_result)\n\n def test_connected_components_with_empty_graph(self):\n\n \"\"\"\n input :\n output : 0\n \"\"\"\n l = [[]]\n expected_result = 0\n size = 0\n result = count_connected_number_of_component.count_components(l, size)\n self.assertEqual(result, expected_result)\n\n def test_connected_components_without_edges_graph(self):\n \"\"\"\n input : 0 2 3 4\n output : 4\n \"\"\"\n l = [[0], [], [2], [3], [4]]\n size = 4\n expected_result = 4\n result = count_connected_number_of_component.count_components(l, size)\n self.assertEqual(result, expected_result)\n\n\nclass PrimsMinimumSpanning(unittest.TestCase):\n def test_prim_spanning(self):\n graph1 = {\n 1: [[3, 2], [8, 3]],\n 2: [[3, 1], [5, 4]],\n 3: [[8, 1], [2, 4], [4, 5]],\n 4: [[5, 2], [2, 3], [6, 5]],\n 5: [[4, 3], [6, 4]]\n }\n self.assertEqual(14, prims_minimum_spanning(graph1))\n graph2 = {\n 1: [[7, 2], [6, 4]],\n 2: [[7, 1], [9, 4], [6, 3]],\n 3: [[8, 4], [6, 2]],\n 4: [[6, 1], [9, 2], [8, 3]]\n }\n self.assertEqual(19, prims_minimum_spanning(graph2))\n\nclass TestDigraphStronglyConnected(unittest.TestCase):\n def test_digraph_strongly_connected(self):\n g1 = check_digraph_strongly_connected.Graph(5)\n g1.add_edge(0, 1)\n g1.add_edge(1, 2)\n g1.add_edge(2, 3)\n g1.add_edge(3, 0)\n g1.add_edge(2, 4)\n g1.add_edge(4, 2)\n self.assertTrue(g1.is_strongly_connected())\n\n g2 = check_digraph_strongly_connected.Graph(4)\n g2.add_edge(0, 1)\n g2.add_edge(1, 2)\n g2.add_edge(2, 3)\n self.assertFalse(g2.is_strongly_connected())\n\nclass TestCycleDetection(unittest.TestCase):\n def test_cycle_detection_with_cycle(self):\n graph = {'A': ['B', 'C'],\n 'B': ['D'],\n 'C': ['F'],\n 'D': ['E', 'F'],\n 'E': ['B'],\n 'F': []}\n self.assertTrue(cycle_detection.contains_cycle(graph))\n\n def test_cycle_detection_with_no_cycle(self):\n graph = {'A': ['B', 'C'],\n 'B': ['D', 'E'],\n 'C': ['F'],\n 'D': ['E'],\n 'E': [],\n 'F': []}\n self.assertFalse(cycle_detection.contains_cycle(graph))\n\nclass TestFindPath(unittest.TestCase):\n def test_find_all_paths(self):\n graph = {'A': ['B', 'C'],\n 'B': ['C', 'D'],\n 'C': ['D', 'F'],\n 'D': ['C'],\n 'E': ['F'],\n 'F': ['C']}\n\n paths = find_path.find_all_path(graph, 'A', 'F')\n print(paths)\n self.assertEqual(sorted(paths), sorted([\n ['A', 'C', 'F'],\n ['A', 'B', 'C', 'F'],\n ['A', 'B', 'D', 'C', 'F'],\n ]))\n\nclass TestPathBetweenTwoVertices(unittest.TestCase):\n def test_node_is_reachable(self):\n g = path_between_two_vertices_in_digraph.Graph(4)\n g.add_edge(0, 1)\n g.add_edge(0, 2)\n g.add_edge(1, 2)\n g.add_edge(2, 0)\n g.add_edge(2, 3)\n g.add_edge(3, 3)\n\n self.assertTrue(g.is_reachable(1, 3))\n self.assertFalse(g.is_reachable(3, 1))\n\n"} +{"Prompt":"Test suite for the binaryheap data structures Before insert 2: 0, 4, 50, 7, 55, 90, 87 After insert: 0, 2, 50, 4, 55, 90, 87, 7 Before removemin : 0, 4, 50, 7, 55, 90, 87 After removemin: 7, 50, 87, 55, 90 Test return value Expect output","Completions":"from algorithms.heap import (\n BinaryHeap,\n get_skyline,\n max_sliding_window,\n k_closest\n)\n\nimport unittest\n\n\nclass TestBinaryHeap(unittest.TestCase):\n \"\"\"\n Test suite for the binary_heap data structures\n \"\"\"\n\n def setUp(self):\n self.min_heap = BinaryHeap()\n self.min_heap.insert(4)\n self.min_heap.insert(50)\n self.min_heap.insert(7)\n self.min_heap.insert(55)\n self.min_heap.insert(90)\n self.min_heap.insert(87)\n\n def test_insert(self):\n # Before insert 2: [0, 4, 50, 7, 55, 90, 87]\n # After insert: [0, 2, 50, 4, 55, 90, 87, 7]\n self.min_heap.insert(2)\n self.assertEqual([0, 2, 50, 4, 55, 90, 87, 7],\n self.min_heap.heap)\n self.assertEqual(7, self.min_heap.current_size)\n\n def test_remove_min(self):\n ret = self.min_heap.remove_min()\n # Before remove_min : [0, 4, 50, 7, 55, 90, 87]\n # After remove_min: [7, 50, 87, 55, 90]\n # Test return value\n self.assertEqual(4, ret)\n self.assertEqual([0, 7, 50, 87, 55, 90],\n self.min_heap.heap)\n self.assertEqual(5, self.min_heap.current_size)\n\n\nclass TestSuite(unittest.TestCase):\n def test_get_skyline(self):\n buildings = [[2, 9, 10], [3, 7, 15], [5, 12, 12],\n [15, 20, 10], [19, 24, 8]]\n # Expect output\n output = [[2, 10], [3, 15], [7, 12], [12, 0], [15, 10],\n [20, 8], [24, 0]]\n self.assertEqual(output, get_skyline(buildings))\n\n def test_max_sliding_window(self):\n nums = [1, 3, -1, -3, 5, 3, 6, 7]\n self.assertEqual([3, 3, 5, 5, 6, 7], max_sliding_window(nums, 3))\n\n def test_k_closest_points(self):\n points = [(1, 0), (2, 3), (5, 2), (1, 1), (2, 8), (10, 2),\n (-1, 0), (-2, -2)]\n self.assertEqual([(-1, 0), (1, 0)], k_closest(points, 2))\n self.assertEqual([(1, 1), (-1, 0), (1, 0)], k_closest(points, 3))\n self.assertEqual([(-2, -2), (1, 1), (1, 0),\n (-1, 0)], k_closest(points, 4))\n self.assertEqual([(10, 2), (2, 8), (5, 2), (-2, -2), (2, 3),\n (1, 0), (-1, 0), (1, 1)], k_closest(points, 8))\n\n\nif __name__ == \"__main__\":\n unittest.main()\n"} +{"Prompt":"Test for the Iterative Segment Tree data structure Test all possible segments in the tree :param arr: array to test :param fnc: function of the segment tpree Test all possible segments in the tree with updates :param arr: array to test :param fnc: function of the segment tree :param upd: updates to test","Completions":"from algorithms.tree.segment_tree.iterative_segment_tree import SegmentTree\nfrom functools import reduce\n\nimport unittest\n\n\ndef gcd(a, b):\n if b == 0:\n return a\n return gcd(b, a % b)\n\n\nclass TestSegmentTree(unittest.TestCase):\n \"\"\"\n Test for the Iterative Segment Tree data structure\n \"\"\"\n\n def test_segment_tree_creation(self):\n arr = [2, 4, 3, 6, 8, 9, 3]\n max_segment_tree = SegmentTree(arr, max)\n min_segment_tree = SegmentTree(arr, min)\n sum_segment_tree = SegmentTree(arr, lambda a, b: a + b)\n gcd_segment_tree = SegmentTree(arr, gcd)\n self.assertEqual(max_segment_tree.tree,\n [None, 9, 8, 9, 4, 8, 9, 2, 4, 3, 6, 8, 9, 3])\n self.assertEqual(min_segment_tree.tree,\n [None, 2, 3, 2, 3, 6, 3, 2, 4, 3, 6, 8, 9, 3])\n self.assertEqual(sum_segment_tree.tree,\n [None, 35, 21, 14, 7, 14, 12, 2, 4, 3, 6, 8, 9, 3])\n self.assertEqual(gcd_segment_tree.tree,\n [None, 1, 1, 1, 1, 2, 3, 2, 4, 3, 6, 8, 9, 3])\n\n def test_max_segment_tree(self):\n arr = [-1, 1, 10, 2, 9, -3, 8, 4, 7, 5, 6, 0]\n self.__test_all_segments(arr, max)\n\n def test_min_segment_tree(self):\n arr = [1, 10, -2, 9, -3, 8, 4, -7, 5, 6, 11, -12]\n self.__test_all_segments(arr, min)\n\n def test_sum_segment_tree(self):\n arr = [1, 10, 2, 9, 3, 8, 4, 7, 5, 6, -11, -12]\n self.__test_all_segments(arr, lambda a, b: a + b)\n\n def test_gcd_segment_tree(self):\n arr = [1, 10, 2, 9, 3, 8, 4, 7, 5, 6, 11, 12, 14]\n self.__test_all_segments(arr, gcd)\n\n def test_max_segment_tree_with_updates(self):\n arr = [-1, 1, 10, 2, 9, -3, 8, 4, 7, 5, 6, 0]\n updates = {0: 1, 1: 2, 2: 3, 3: 4, 4: 5, 5: 6, 6: 7, 7: 8, 8: 9,\n 9: 10, 10: 11, 11: 12}\n self.__test_all_segments_with_updates(arr, max, updates)\n\n def test_min_segment_tree_with_updates(self):\n arr = [1, 10, -2, 9, -3, 8, 4, -7, 5, 6, 11, -12]\n updates = {0: 7, 1: 2, 2: 6, 3: -14, 4: 5, 5: 4, 6: 7, 7: -10, 8: 9,\n 9: 10, 10: 12, 11: 1}\n self.__test_all_segments_with_updates(arr, min, updates)\n\n def test_sum_segment_tree_with_updates(self):\n arr = [1, 10, 2, 9, 3, 8, 4, 7, 5, 6, -11, -12]\n updates = {0: 12, 1: 11, 2: 10, 3: 9, 4: 8, 5: 7, 6: 6, 7: 5, 8: 4,\n 9: 3, 10: 2, 11: 1}\n self.__test_all_segments_with_updates(arr, lambda a, b: a + b, updates)\n\n def test_gcd_segment_tree_with_updates(self):\n arr = [1, 10, 2, 9, 3, 8, 4, 7, 5, 6, 11, 12, 14]\n updates = {0: 4, 1: 2, 2: 3, 3: 9, 4: 21, 5: 7, 6: 4, 7: 4, 8: 2,\n 9: 5, 10: 17, 11: 12, 12: 3}\n self.__test_all_segments_with_updates(arr, gcd, updates)\n\n def __test_all_segments(self, arr, fnc):\n \"\"\"\n Test all possible segments in the tree\n :param arr: array to test\n :param fnc: function of the segment tpree\n \"\"\"\n segment_tree = SegmentTree(arr, fnc)\n self.__test_segments_helper(segment_tree, fnc, arr)\n\n def __test_all_segments_with_updates(self, arr, fnc, upd):\n \"\"\"\n Test all possible segments in the tree with updates\n :param arr: array to test\n :param fnc: function of the segment tree\n :param upd: updates to test\n \"\"\"\n segment_tree = SegmentTree(arr, fnc)\n for index, value in upd.items():\n arr[index] = value\n segment_tree.update(index, value)\n self.__test_segments_helper(segment_tree, fnc, arr)\n\n def __test_segments_helper(self, seg_tree, fnc, arr):\n for i in range(0, len(arr)):\n for j in range(i, len(arr)):\n range_value = reduce(fnc, arr[i:j + 1])\n self.assertEqual(seg_tree.query(i, j), range_value)\n"} +{"Prompt":"Convert from linked list Node to list for testing list test for palindrome head 2 2 2 4 9 head 1 2 8 4 6 Test case: middle case. Expect output: 0 4 Test case: taking out the front node Expect output: 2 3 4 Test case: removing all the nodes Expect output : 2 1 4 3 Given 12345NULL K 2. Expect output: 45123NULL. create linked list A B C D E C create linked list 1 2 3 4 Input: head1:124, head2: 134 Output: 112344 Test recursive","Completions":"import unittest\n\nfrom algorithms.linkedlist import (\n reverse_list, reverse_list_recursive,\n is_sorted,\n remove_range,\n swap_pairs,\n rotate_right,\n is_cyclic,\n merge_two_list, merge_two_list_recur,\n is_palindrome, is_palindrome_stack, is_palindrome_dict,\n RandomListNode, copy_random_pointer_v1, copy_random_pointer_v2\n)\n\n\nclass Node(object):\n def __init__(self, x):\n self.val = x\n self.next = None\n\n\n# Convert from linked list Node to list for testing\ndef convert(head):\n ret = []\n if head:\n current = head\n while current:\n ret.append(current.val)\n current = current.next\n return ret\n\n\nclass TestSuite(unittest.TestCase):\n def setUp(self):\n # list test for palindrome\n self.l = Node('A')\n self.l.next = Node('B')\n self.l.next.next = Node('C')\n self.l.next.next.next = Node('B')\n self.l.next.next.next.next = Node('A')\n\n self.l1 = Node('A')\n self.l1.next = Node('B')\n self.l1.next.next = Node('C')\n self.l1.next.next.next = Node('B')\n\n def test_reverse_list(self):\n head = Node(1)\n head.next = Node(2)\n head.next.next = Node(3)\n head.next.next.next = Node(4)\n self.assertEqual([4, 3, 2, 1], convert(reverse_list(head)))\n head = Node(1)\n head.next = Node(2)\n head.next.next = Node(3)\n head.next.next.next = Node(4)\n self.assertEqual([4, 3, 2, 1], convert(reverse_list_recursive(head)))\n\n def test_is_sorted(self):\n head = Node(-2)\n head.next = Node(2)\n head.next.next = Node(2)\n head.next.next.next = Node(4)\n head.next.next.next.next = Node(9)\n # head -> -2 -> 2 -> 2 -> 4 -> 9\n self.assertTrue(is_sorted(head))\n head = Node(1)\n head.next = Node(2)\n head.next.next = Node(8)\n head.next.next.next = Node(4)\n head.next.next.next.next = Node(6)\n # head -> 1 -> 2 -> 8 -> 4 -> 6\n self.assertFalse(is_sorted(head))\n\n def test_remove_range(self):\n # Test case: middle case.\n head = Node(0)\n head.next = Node(1)\n head.next.next = Node(2)\n head.next.next.next = Node(3)\n head.next.next.next.next = Node(4)\n # Expect output: 0 4\n self.assertEqual([0, 4], convert(remove_range(head, 1, 3)))\n\n # Test case: taking out the front node\n head = Node(0)\n head.next = Node(1)\n head.next.next = Node(2)\n head.next.next.next = Node(3)\n head.next.next.next.next = Node(4)\n # Expect output: 2 3 4\n self.assertEqual([2, 3, 4], convert(remove_range(head, 0, 1)))\n\n # Test case: removing all the nodes\n head = Node(0)\n head.next = Node(1)\n head.next.next = Node(2)\n head.next.next.next = Node(3)\n head.next.next.next.next = Node(4)\n self.assertEqual([], convert(remove_range(head, 0, 7)))\n\n def test_swap_in_pairs(self):\n head = Node(1)\n head.next = Node(2)\n head.next.next = Node(3)\n head.next.next.next = Node(4)\n # Expect output : 2 --> 1 --> 4 --> 3\n self.assertEqual([2, 1, 4, 3], convert(swap_pairs(head)))\n\n def test_rotate_right(self):\n # Given 1->2->3->4->5->NULL\n head = Node(1)\n head.next = Node(2)\n head.next.next = Node(3)\n head.next.next.next = Node(4)\n head.next.next.next.next = Node(5)\n # K = 2. Expect output: 4->5->1->2->3->NULL.\n self.assertEqual([4, 5, 1, 2, 3], convert(rotate_right(head, 2)))\n\n def test_is_cyclic(self):\n # create linked list => A -> B -> C -> D -> E -> C\n head = Node('A')\n head.next = Node('B')\n curr = head.next\n cyclic_node = Node('C')\n curr.next = cyclic_node\n curr = curr.next\n curr.next = Node('D')\n curr = curr.next\n curr.next = Node('E')\n curr = curr.next\n curr.next = cyclic_node\n self.assertTrue(is_cyclic(head))\n\n # create linked list 1 -> 2 -> 3 -> 4\n head = Node(1)\n curr = head\n for i in range(2, 6):\n curr.next = Node(i)\n curr = curr.next\n self.assertFalse(is_cyclic(head))\n\n def test_merge_two_list(self):\n \"\"\"\n Input: head1:1->2->4, head2: 1->3->4\n Output: 1->1->2->3->4->4\n \"\"\"\n head1 = Node(1)\n head1.next = Node(2)\n head1.next.next = Node(4)\n head2 = Node(1)\n head2.next = Node(3)\n head2.next.next = Node(4)\n self.assertEqual([1, 1, 2, 3, 4, 4],\n convert(merge_two_list(head1, head2)))\n # Test recursive\n head1 = Node(1)\n head1.next = Node(2)\n head1.next.next = Node(4)\n head2 = Node(1)\n head2.next = Node(3)\n head2.next.next = Node(4)\n self.assertEqual([1, 1, 2, 3, 4, 4],\n convert(merge_two_list_recur(head1, head2)))\n\n def test_is_palindrome(self):\n self.assertTrue(is_palindrome(self.l))\n self.assertFalse(is_palindrome(self.l1))\n\n def test_is_palindrome_stack(self):\n self.assertTrue(is_palindrome_stack(self.l))\n self.assertFalse(is_palindrome_stack(self.l1))\n\n def test_is_palindrome_dict(self):\n self.assertTrue(is_palindrome_dict(self.l))\n self.assertFalse(is_palindrome_dict(self.l1))\n\n def test_solution_0(self):\n self._init_random_list_nodes()\n result = copy_random_pointer_v1(self.random_list_node1)\n self._assert_is_a_copy(result)\n\n def test_solution_1(self):\n self._init_random_list_nodes()\n result = copy_random_pointer_v2(self.random_list_node1)\n self._assert_is_a_copy(result)\n\n def _assert_is_a_copy(self, result):\n self.assertEqual(5, result.next.next.next.next.label)\n self.assertEqual(4, result.next.next.next.label)\n self.assertEqual(3, result.next.next.label)\n self.assertEqual(2, result.next.label)\n self.assertEqual(1, result.label)\n self.assertEqual(3, result.next.next.next.next.random.label)\n self.assertIsNone(result.next.next.next.random)\n self.assertEqual(2, result.next.next.random.label)\n self.assertEqual(5, result.next.random.label)\n self.assertEqual(4, result.random.label)\n\n def _init_random_list_nodes(self):\n self.random_list_node1 = RandomListNode(1)\n random_list_node2 = RandomListNode(2)\n random_list_node3 = RandomListNode(3)\n random_list_node4 = RandomListNode(4)\n random_list_node5 = RandomListNode(5)\n\n self.random_list_node1.next, self.random_list_node1.random = random_list_node2, random_list_node4\n random_list_node2.next, random_list_node2.random = random_list_node3, random_list_node5\n random_list_node3.next, random_list_node3.random = random_list_node4, random_list_node2\n random_list_node4.next = random_list_node5\n random_list_node5.random = random_list_node3\n\n\nif __name__ == \"__main__\":\n unittest.main()\n"} +{"Prompt":"and does not search forever","Completions":"from algorithms.map import (\n HashTable, ResizableHashTable,\n SeparateChainingHashTable,\n word_pattern,\n is_isomorphic,\n is_anagram,\n longest_palindromic_subsequence,\n)\n\nimport unittest\n\n\nclass TestHashTable(unittest.TestCase):\n def test_one_entry(self):\n m = HashTable(10)\n m.put(1, '1')\n self.assertEqual('1', m.get(1))\n\n def test_add_entry_bigger_than_table_size(self):\n m = HashTable(10)\n m.put(11, '1')\n self.assertEqual('1', m.get(11))\n\n def test_get_none_if_key_missing_and_hash_collision(self):\n m = HashTable(10)\n m.put(1, '1')\n self.assertEqual(None, m.get(11))\n\n def test_two_entries_with_same_hash(self):\n m = HashTable(10)\n m.put(1, '1')\n m.put(11, '11')\n self.assertEqual('1', m.get(1))\n self.assertEqual('11', m.get(11))\n\n def test_get_on_full_table_does_halts(self):\n # and does not search forever\n m = HashTable(10)\n for i in range(10, 20):\n m.put(i, i)\n self.assertEqual(None, m.get(1))\n\n def test_delete_key(self):\n m = HashTable(10)\n for i in range(5):\n m.put(i, i**2)\n m.del_(1)\n self.assertEqual(None, m.get(1))\n self.assertEqual(4, m.get(2))\n\n def test_delete_key_and_reassign(self):\n m = HashTable(10)\n m.put(1, 1)\n del m[1]\n m.put(1, 2)\n self.assertEqual(2, m.get(1))\n\n def test_assigning_to_full_table_throws_error(self):\n m = HashTable(3)\n m.put(1, 1)\n m.put(2, 2)\n m.put(3, 3)\n with self.assertRaises(ValueError):\n m.put(4, 4)\n\n def test_len_trivial(self):\n m = HashTable(10)\n self.assertEqual(0, len(m))\n for i in range(10):\n m.put(i, i)\n self.assertEqual(i + 1, len(m))\n\n def test_len_after_deletions(self):\n m = HashTable(10)\n m.put(1, 1)\n self.assertEqual(1, len(m))\n m.del_(1)\n self.assertEqual(0, len(m))\n m.put(11, 42)\n self.assertEqual(1, len(m))\n\n def test_resizable_hash_table(self):\n m = ResizableHashTable()\n self.assertEqual(ResizableHashTable.MIN_SIZE, m.size)\n for i in range(ResizableHashTable.MIN_SIZE):\n m.put(i, 'foo')\n self.assertEqual(ResizableHashTable.MIN_SIZE * 2, m.size)\n self.assertEqual('foo', m.get(1))\n self.assertEqual('foo', m.get(3))\n self.assertEqual('foo', m.get(ResizableHashTable.MIN_SIZE - 1))\n\n def test_fill_up_the_limit(self):\n m = HashTable(10)\n for i in range(10):\n m.put(i, i**2)\n for i in range(10):\n self.assertEqual(i**2, m.get(i))\n\n\nclass TestSeparateChainingHashTable(unittest.TestCase):\n def test_one_entry(self):\n m = SeparateChainingHashTable(10)\n m.put(1, '1')\n self.assertEqual('1', m.get(1))\n\n def test_two_entries_with_same_hash(self):\n m = SeparateChainingHashTable(10)\n m.put(1, '1')\n m.put(11, '11')\n self.assertEqual('1', m.get(1))\n self.assertEqual('11', m.get(11))\n\n def test_len_trivial(self):\n m = SeparateChainingHashTable(10)\n self.assertEqual(0, len(m))\n for i in range(10):\n m.put(i, i)\n self.assertEqual(i + 1, len(m))\n\n def test_len_after_deletions(self):\n m = SeparateChainingHashTable(10)\n m.put(1, 1)\n self.assertEqual(1, len(m))\n m.del_(1)\n self.assertEqual(0, len(m))\n m.put(11, 42)\n self.assertEqual(1, len(m))\n\n def test_delete_key(self):\n m = SeparateChainingHashTable(10)\n for i in range(5):\n m.put(i, i**2)\n m.del_(1)\n self.assertEqual(None, m.get(1))\n self.assertEqual(4, m.get(2))\n\n def test_delete_key_and_reassign(self):\n m = SeparateChainingHashTable(10)\n m.put(1, 1)\n del m[1]\n m.put(1, 2)\n self.assertEqual(2, m.get(1))\n\n def test_add_entry_bigger_than_table_size(self):\n m = SeparateChainingHashTable(10)\n m.put(11, '1')\n self.assertEqual('1', m.get(11))\n\n def test_get_none_if_key_missing_and_hash_collision(self):\n m = SeparateChainingHashTable(10)\n m.put(1, '1')\n self.assertEqual(None, m.get(11))\n\n\nclass TestWordPattern(unittest.TestCase):\n def test_word_pattern(self):\n self.assertTrue(word_pattern(\"abba\", \"dog cat cat dog\"))\n self.assertFalse(word_pattern(\"abba\", \"dog cat cat fish\"))\n self.assertFalse(word_pattern(\"abba\", \"dog dog dog dog\"))\n self.assertFalse(word_pattern(\"aaaa\", \"dog cat cat dog\"))\n\n\nclass TestIsSomorphic(unittest.TestCase):\n def test_is_isomorphic(self):\n self.assertTrue(is_isomorphic(\"egg\", \"add\"))\n self.assertFalse(is_isomorphic(\"foo\", \"bar\"))\n self.assertTrue(is_isomorphic(\"paper\", \"title\"))\n\n\nclass TestLongestPalindromicSubsequence(unittest.TestCase):\n def test_longest_palindromic_subsequence_is_correct(self):\n self.assertEqual(3, longest_palindromic_subsequence('BBABCBCAB'))\n self.assertEqual(4, longest_palindromic_subsequence('abbaeae'))\n self.assertEqual(7, longest_palindromic_subsequence('babbbababaa'))\n self.assertEqual(4, longest_palindromic_subsequence('daccandeeja'))\n\n def test_longest_palindromic_subsequence_is_incorrect(self):\n self.assertNotEqual(4, longest_palindromic_subsequence('BBABCBCAB'))\n self.assertNotEqual(5, longest_palindromic_subsequence('abbaeae'))\n self.assertNotEqual(2, longest_palindromic_subsequence('babbbababaa'))\n self.assertNotEqual(1, longest_palindromic_subsequence('daccandeeja'))\n\n\nclass TestIsAnagram(unittest.TestCase):\n def test_is_anagram(self):\n self.assertTrue(is_anagram(\"anagram\", \"nagaram\"))\n self.assertFalse(is_anagram(\"rat\", \"car\"))\n\n\nif __name__ == \"__main__\":\n unittest.main()\n"} +{"Prompt":"Test for the file power.py Arguments: unittest type description Test for the file baseconversion.py Arguments: unittest type description Test for the file decimaltobinaryip.py Arguments: unittest type description summary Test for the file eulertotient.py Arguments: unittest type description summary Test for the file extendedgcd.py Arguments: unittest type description summary Test for the file gcd.py Arguments: unittest type description summary Test for the file generatestrobogrammatic.py Arguments: unittest type description summary Test for the file isstrobogrammatic.py Arguments: unittest type description summary Test for the file modularExponential.py Arguments: unittest type description checks if x xinv 1 mod m summary Test for the file modularExponential.py Arguments: unittest type description summary Test for the file nextperfectsquare.py Arguments: unittest type description summary Test for the file primessieveoferatosthenes.py Arguments: unittest type description summary Test for the file primetest.py Arguments: unittest type description checks all prime numbers between 2 up to 100. Between 2 up to 100 exists 25 prime numbers! summary Test for the file pythagoras.py Arguments: unittest type description summary Test for the file rabinmiller.py Arguments: unittest type description summary Test for the file rsa.py Arguments: unittest type description def testkeygeneratorself: this test takes a while! for i in range100: printstep 0.formati n, e, d generatekey26 data 2 en encryptdata, e, n dec decrypten, d, n self.assertEqualdata,dec summary Test for the file combination.py Arguments: unittest type description summary Test for the file factorial.py Arguments: unittest type description summary Test for the file hailstone.py Arguments: unittest type description summary Test for the file cosinesimilarity.py Arguments: unittest type description summary Test for the file findprimitiverootsimple.py Arguments: unittest type description summary Test for the file findordersimple.py Arguments: unittest type description summary Test for the file krishnamurthynumber.py Arguments: unittest type description summary Test for the file findordersimple.py Arguments: unittest type description summary Test for the file diffiehellmankeyexchange.py Arguments: unittest type description summary Test for the file numdigits.py Arguments: unittest type description summary Test for the file numperfectsquares.py Arguments: unittest type description Example which should give the answer 143 which is the smallest possible x that solves the system of equations Example which should give the answer 3383 which is the smallest possible x that solves the system of equations There should be an exception when all numbers in num are not pairwise coprime summary Test for the file fft.py Arguments: unittest type description abscomplex returns the magnitude","Completions":"from algorithms.maths import (\n power, power_recur,\n int_to_base, base_to_int,\n decimal_to_binary_ip,\n euler_totient,\n extended_gcd,\n factorial, factorial_recur,\n gcd, lcm, trailing_zero, gcd_bit,\n gen_strobogrammatic, strobogrammatic_in_range,\n is_strobogrammatic, is_strobogrammatic2,\n modular_inverse,\n modular_exponential,\n find_next_square, find_next_square2,\n prime_check,\n get_primes,\n pythagoras,\n is_prime,\n encrypt, decrypt,\n combination, combination_memo,\n hailstone,\n cosine_similarity,\n magic_number,\n find_order,\n find_primitive_root,\n num_digits,\n diffie_hellman_key_exchange, krishnamurthy_number,\n num_perfect_squares,\n chinese_remainder_theorem,\n fft\n)\n\nimport unittest\nimport pytest\n\n\nclass TestPower(unittest.TestCase):\n \"\"\"\n Test for the file power.py\n\n Arguments:\n unittest {[type]} -- [description]\n \"\"\"\n\n def test_power(self):\n self.assertEqual(8, power(2, 3))\n self.assertEqual(1, power(5, 0))\n self.assertEqual(0, power(10, 3, 5))\n self.assertEqual(280380, power(2265, 1664, 465465))\n\n def test_power_recur(self):\n self.assertEqual(8, power_recur(2, 3))\n self.assertEqual(1, power_recur(5, 0))\n self.assertEqual(0, power_recur(10, 3, 5))\n self.assertEqual(280380, power_recur(2265, 1664, 465465))\n\n\nclass TestBaseConversion(unittest.TestCase):\n \"\"\"\n Test for the file base_conversion.py\n\n Arguments:\n unittest {[type]} -- [description]\n \"\"\"\n\n def test_int_to_base(self):\n self.assertEqual(\"101\", int_to_base(5, 2))\n self.assertEqual(\"0\", int_to_base(0, 2))\n self.assertEqual(\"FF\", int_to_base(255, 16))\n\n def test_base_to_int(self):\n self.assertEqual(5, base_to_int(\"101\", 2))\n self.assertEqual(0, base_to_int(\"0\", 2))\n self.assertEqual(255, base_to_int(\"FF\", 16))\n\n\nclass TestDecimalToBinaryIP(unittest.TestCase):\n \"\"\"\n Test for the file decimal_to_binary_ip.py\n\n Arguments:\n unittest {[type]} -- [description]\n \"\"\"\n\n def test_decimal_to_binary_ip(self):\n self.assertEqual(\"00000000.00000000.00000000.00000000\",\n decimal_to_binary_ip(\"0.0.0.0\"))\n self.assertEqual(\"11111111.11111111.11111111.11111111\",\n decimal_to_binary_ip(\"255.255.255.255\"))\n self.assertEqual(\"11000000.10101000.00000000.00000001\",\n decimal_to_binary_ip(\"192.168.0.1\"))\n\n\nclass TestEulerTotient(unittest.TestCase):\n \"\"\"[summary]\n Test for the file euler_totient.py\n\n Arguments:\n unittest {[type]} -- [description]\n \"\"\"\n\n def test_euler_totient(self):\n self.assertEqual(4, euler_totient(8))\n self.assertEqual(12, euler_totient(21))\n self.assertEqual(311040, euler_totient(674614))\n self.assertEqual(2354352, euler_totient(3435145))\n\n\nclass TestExtendedGcd(unittest.TestCase):\n \"\"\"[summary]\n Test for the file extended_gcd.py\n\n Arguments:\n unittest {[type]} -- [description]\n \"\"\"\n\n def test_extended_gcd(self):\n self.assertEqual((0, 1, 2), extended_gcd(8, 2))\n self.assertEqual((0, 1, 17), extended_gcd(13, 17))\n\n\nclass TestGcd(unittest.TestCase):\n \"\"\"[summary]\n Test for the file gcd.py\n\n Arguments:\n unittest {[type]} -- [description]\n \"\"\"\n\n def test_gcd(self):\n self.assertEqual(4, gcd(8, 12))\n self.assertEqual(1, gcd(13, 17))\n\n def test_gcd_non_integer_input(self):\n with pytest.raises(ValueError,\n match=r\"Input arguments are not integers\"):\n gcd(1.0, 5)\n gcd(5, 6.7)\n gcd(33.8649, 6.12312312)\n\n def test_gcd_zero_input(self):\n with pytest.raises(ValueError,\n match=r\"One or more input arguments equals zero\"):\n gcd(0, 12)\n gcd(12, 0)\n gcd(0, 0)\n\n def test_gcd_negative_input(self):\n self.assertEqual(1, gcd(-13, -17))\n self.assertEqual(4, gcd(-8, 12))\n self.assertEqual(8, gcd(24, -16))\n\n def test_lcm(self):\n self.assertEqual(24, lcm(8, 12))\n self.assertEqual(5767, lcm(73, 79))\n\n def test_lcm_negative_numbers(self):\n self.assertEqual(24, lcm(-8, -12))\n self.assertEqual(5767, lcm(73, -79))\n self.assertEqual(1, lcm(-1, 1))\n\n def test_lcm_zero_input(self):\n with pytest.raises(ValueError,\n match=r\"One or more input arguments equals zero\"):\n lcm(0, 12)\n lcm(12, 0)\n lcm(0, 0)\n\n def test_trailing_zero(self):\n self.assertEqual(1, trailing_zero(34))\n self.assertEqual(3, trailing_zero(40))\n\n def test_gcd_bit(self):\n self.assertEqual(4, gcd_bit(8, 12))\n self.assertEqual(1, gcd(13, 17))\n\n\nclass TestGenerateStroboGrammatic(unittest.TestCase):\n \"\"\"[summary]\n Test for the file generate_strobogrammatic.py\n\n Arguments:\n unittest {[type]} -- [description]\n \"\"\"\n\n def test_gen_strobomatic(self):\n self.assertEqual(['88', '11', '96', '69'], gen_strobogrammatic(2))\n\n def test_strobogrammatic_in_range(self):\n self.assertEqual(4, strobogrammatic_in_range(\"10\", \"100\"))\n\n\nclass TestIsStrobogrammatic(unittest.TestCase):\n \"\"\"[summary]\n Test for the file is_strobogrammatic.py\n\n Arguments:\n unittest {[type]} -- [description]\n \"\"\"\n\n def test_is_strobogrammatic(self):\n self.assertTrue(is_strobogrammatic(\"69\"))\n self.assertFalse(is_strobogrammatic(\"14\"))\n\n def test_is_strobogrammatic2(self):\n self.assertTrue(is_strobogrammatic2(\"69\"))\n self.assertFalse(is_strobogrammatic2(\"14\"))\n\n\nclass TestModularInverse(unittest.TestCase):\n \"\"\"[summary]\n Test for the file modular_Exponential.py\n\n Arguments:\n unittest {[type]} -- [description]\n \"\"\"\n\n def test_modular_inverse(self):\n # checks if x * x_inv == 1 (mod m)\n self.assertEqual(1, 2 * modular_inverse.modular_inverse(2, 19) % 19)\n self.assertEqual(1, 53 * modular_inverse.modular_inverse(53, 91) % 91)\n self.assertEqual(1, 2 * modular_inverse.modular_inverse(2, 1000000007)\n % 1000000007)\n self.assertRaises(ValueError, modular_inverse.modular_inverse, 2, 20)\n\n\nclass TestModularExponential(unittest.TestCase):\n \"\"\"[summary]\n Test for the file modular_Exponential.py\n\n Arguments:\n unittest {[type]} -- [description]\n \"\"\"\n\n def test_modular_exponential(self):\n self.assertEqual(1, modular_exponential(5, 117, 19))\n self.assertEqual(pow(1243, 65321, 10 ** 9 + 7),\n modular_exponential(1243, 65321, 10 ** 9 + 7))\n self.assertEqual(1, modular_exponential(12, 0, 78))\n self.assertRaises(ValueError, modular_exponential, 12, -2, 455)\n\n\nclass TestNextPerfectSquare(unittest.TestCase):\n \"\"\"[summary]\n Test for the file next_perfect_square.py\n\n Arguments:\n unittest {[type]} -- [description]\n \"\"\"\n\n def test_find_next_square(self):\n self.assertEqual(36, find_next_square(25))\n self.assertEqual(1, find_next_square(0))\n\n def test_find_next_square2(self):\n self.assertEqual(36, find_next_square2(25))\n self.assertEqual(1, find_next_square2(0))\n\n\nclass TestPrimesSieveOfEratosthenes(unittest.TestCase):\n \"\"\"[summary]\n Test for the file primes_sieve_of_eratosthenes.py\n\n Arguments:\n unittest {[type]} -- [description]\n \"\"\"\n\n def test_primes(self):\n self.assertListEqual([2, 3, 5, 7], get_primes(7))\n self.assertRaises(ValueError, get_primes, -42)\n\n\nclass TestPrimeTest(unittest.TestCase):\n \"\"\"[summary]\n Test for the file prime_test.py\n\n Arguments:\n unittest {[type]} -- [description]\n \"\"\"\n\n def test_prime_test(self):\n \"\"\"\n checks all prime numbers between 2 up to 100.\n Between 2 up to 100 exists 25 prime numbers!\n \"\"\"\n counter = 0\n for i in range(2, 101):\n if prime_check(i):\n counter += 1\n self.assertEqual(25, counter)\n\n\nclass TestPythagoras(unittest.TestCase):\n \"\"\"[summary]\n Test for the file pythagoras.py\n\n Arguments:\n unittest {[type]} -- [description]\n \"\"\"\n\n def test_pythagoras(self):\n self.assertEqual(\"Hypotenuse = 3.605551275463989\",\n pythagoras(3, 2, \"?\"))\n\n\nclass TestRabinMiller(unittest.TestCase):\n \"\"\"[summary]\n Test for the file rabin_miller.py\n\n Arguments:\n unittest {[type]} -- [description]\n \"\"\"\n\n def test_is_prime(self):\n self.assertTrue(is_prime(7, 2))\n self.assertTrue(is_prime(13, 11))\n self.assertFalse(is_prime(6, 2))\n\n\nclass TestRSA(unittest.TestCase):\n \"\"\"[summary]\n Test for the file rsa.py\n\n Arguments:\n unittest {[type]} -- [description]\n \"\"\"\n\n def test_encrypt_decrypt(self):\n self.assertEqual(7, decrypt(encrypt(7, 23, 143), 47, 143))\n\n # def test_key_generator(self): # this test takes a while!\n # for i in range(100):\n # print(\"step {0}\".format(i))\n # n, e, d = generate_key(26)\n # data = 2\n # en = encrypt(data, e, n)\n # dec = decrypt(en, d, n)\n # self.assertEqual(data,dec)\n\n\nclass TestCombination(unittest.TestCase):\n \"\"\"[summary]\n Test for the file combination.py\n\n Arguments:\n unittest {[type]} -- [description]\n \"\"\"\n\n def test_combination(self):\n self.assertEqual(10, combination(5, 2))\n self.assertEqual(252, combination(10, 5))\n\n def test_combination_memo(self):\n self.assertEqual(10272278170, combination_memo(50, 10))\n self.assertEqual(847660528, combination_memo(40, 10))\n\n\nclass TestFactorial(unittest.TestCase):\n \"\"\"[summary]\n Test for the file factorial.py\n\n Arguments:\n unittest {[type]} -- [description]\n \"\"\"\n\n def test_factorial(self):\n self.assertEqual(1, factorial(0))\n self.assertEqual(120, factorial(5))\n self.assertEqual(3628800, factorial(10))\n self.assertEqual(637816310, factorial(34521, 10 ** 9 + 7))\n self.assertRaises(ValueError, factorial, -42)\n self.assertRaises(ValueError, factorial, 42, -1)\n\n def test_factorial_recur(self):\n self.assertEqual(1, factorial_recur(0))\n self.assertEqual(120, factorial_recur(5))\n self.assertEqual(3628800, factorial_recur(10))\n self.assertEqual(637816310, factorial_recur(34521, 10 ** 9 + 7))\n self.assertRaises(ValueError, factorial_recur, -42)\n self.assertRaises(ValueError, factorial_recur, 42, -1)\n\n\nclass TestHailstone(unittest.TestCase):\n \"\"\"[summary]\n Test for the file hailstone.py\n\n Arguments:\n unittest {[type]} -- [description]\n \"\"\"\n\n def test_hailstone(self):\n self.assertEqual([8, 4, 2, 1], hailstone.hailstone(8))\n self.assertEqual([10, 5, 16, 8, 4, 2, 1], hailstone.hailstone(10))\n\n\nclass TestCosineSimilarity(unittest.TestCase):\n \"\"\"[summary]\n Test for the file cosine_similarity.py\n\n Arguments:\n unittest {[type]} -- [description]\n \"\"\"\n\n def test_cosine_similarity(self):\n vec_a = [1, 1, 1]\n vec_b = [-1, -1, -1]\n vec_c = [1, 2, -1]\n self.assertAlmostEqual(cosine_similarity(vec_a, vec_a), 1)\n self.assertAlmostEqual(cosine_similarity(vec_a, vec_b), -1)\n self.assertAlmostEqual(cosine_similarity(vec_a, vec_c), 0.4714045208)\n\n\nclass TestFindPrimitiveRoot(unittest.TestCase):\n \"\"\"[summary]\n Test for the file find_primitive_root_simple.py\n\n Arguments:\n unittest {[type]} -- [description]\n \"\"\"\n\n def test_find_primitive_root_simple(self):\n self.assertListEqual([0], find_primitive_root(1))\n self.assertListEqual([2, 3], find_primitive_root(5))\n self.assertListEqual([], find_primitive_root(24))\n self.assertListEqual([2, 5, 13, 15, 17, 18, 19, 20, 22, 24, 32, 35],\n find_primitive_root(37))\n\n\nclass TestFindOrder(unittest.TestCase):\n \"\"\"[summary]\n Test for the file find_order_simple.py\n\n Arguments:\n unittest {[type]} -- [description]\n \"\"\"\n\n def test_find_order_simple(self):\n self.assertEqual(1, find_order(1, 1))\n self.assertEqual(6, find_order(3, 7))\n self.assertEqual(-1, find_order(128, 256))\n self.assertEqual(352, find_order(3, 353))\n\n\nclass TestKrishnamurthyNumber(unittest.TestCase):\n \"\"\"[summary]\n Test for the file krishnamurthy_number.py\n\n Arguments:\n unittest {[type]} -- [description]\n \"\"\"\n\n def test_krishnamurthy_number(self):\n self.assertFalse(krishnamurthy_number(0))\n self.assertTrue(krishnamurthy_number(2))\n self.assertTrue(krishnamurthy_number(1))\n self.assertTrue(krishnamurthy_number(145))\n self.assertTrue(krishnamurthy_number(40585))\n\n\nclass TestMagicNumber(unittest.TestCase):\n \"\"\"[summary]\n Test for the file find_order_simple.py\n\n Arguments:\n unittest {[type]} -- [description]\n \"\"\"\n\n def test_magic_number(self):\n self.assertTrue(magic_number(50113))\n self.assertTrue(magic_number(1234))\n self.assertTrue(magic_number(100))\n self.assertTrue(magic_number(199))\n self.assertFalse(magic_number(2000))\n self.assertFalse(magic_number(500000))\n\n\nclass TestDiffieHellmanKeyExchange(unittest.TestCase):\n \"\"\"[summary]\n Test for the file diffie_hellman_key_exchange.py\n\n Arguments:\n unittest {[type]} -- [description]\n \"\"\"\n\n def test_find_order_simple(self):\n self.assertFalse(diffie_hellman_key_exchange(3, 6))\n self.assertTrue(diffie_hellman_key_exchange(3, 353))\n self.assertFalse(diffie_hellman_key_exchange(5, 211))\n self.assertTrue(diffie_hellman_key_exchange(11, 971))\n\n\nclass TestNumberOfDigits(unittest.TestCase):\n \"\"\"[summary]\n Test for the file num_digits.py\n\n Arguments:\n unittest {[type]} -- [description]\n \"\"\"\n def test_num_digits(self):\n self.assertEqual(2, num_digits(12))\n self.assertEqual(5, num_digits(99999))\n self.assertEqual(1, num_digits(8))\n self.assertEqual(1, num_digits(0))\n self.assertEqual(1, num_digits(-5))\n self.assertEqual(3, num_digits(-254))\n\n\n\nclass TestNumberOfPerfectSquares(unittest.TestCase):\n \"\"\"[summary]\n Test for the file num_perfect_squares.py\n\n Arguments:\n unittest {[type]} -- [description]\n \"\"\"\n def test_num_perfect_squares(self):\n self.assertEqual(4,num_perfect_squares(31))\n self.assertEqual(3,num_perfect_squares(12))\n self.assertEqual(2,num_perfect_squares(13))\n self.assertEqual(2,num_perfect_squares(10))\n self.assertEqual(4,num_perfect_squares(1500)) \n self.assertEqual(2,num_perfect_squares(1548524521))\n self.assertEqual(3,num_perfect_squares(9999999993))\n self.assertEqual(1,num_perfect_squares(9))\n\n\nclass TestChineseRemainderSolver(unittest.TestCase):\n def test_k_three(self):\n # Example which should give the answer 143\n # which is the smallest possible x that\n # solves the system of equations\n num = [3, 7, 10]\n rem = [2, 3, 3]\n self.assertEqual(chinese_remainder_theorem.\n solve_chinese_remainder(num, rem), 143)\n\n def test_k_five(self):\n # Example which should give the answer 3383\n # which is the smallest possible x that\n # solves the system of equations\n num = [3, 5, 7, 11, 26]\n rem = [2, 3, 2, 6, 3]\n self.assertEqual(chinese_remainder_theorem.\n solve_chinese_remainder(num, rem), 3383)\n\n def test_exception_non_coprime(self):\n # There should be an exception when all\n # numbers in num are not pairwise coprime\n num = [3, 7, 10, 14]\n rem = [2, 3, 3, 1]\n with self.assertRaises(Exception):\n chinese_remainder_theorem.solve_chinese_remainder(num, rem)\n\n def test_empty_lists(self):\n num = []\n rem = []\n with self.assertRaises(Exception):\n chinese_remainder_theorem.solve_chinese_remainder(num, rem)\n\n\nclass TestFFT(unittest.TestCase):\n \"\"\"[summary]\n Test for the file fft.py\n\n Arguments:\n unittest {[type]} -- [description]\n \"\"\"\n def test_real_numbers(self):\n x = [1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0]\n y = [4.000, 2.613, 0.000, 1.082, 0.000, 1.082, 0.000, 2.613]\n # abs(complex) returns the magnitude\n result = [float(\"%.3f\" % abs(f)) for f in fft.fft(x)]\n self.assertEqual(result, y)\n \n def test_all_zero(self):\n x = [0.0, 0.0, 0.0, 0.0]\n y = [0.0, 0.0, 0.0, 0.0]\n result = [float(\"%.1f\" % abs(f)) for f in fft.fft(x)]\n self.assertEqual(result, y)\n \n def test_all_ones(self):\n x = [1.0, 1.0, 1.0, 1.0]\n y = [4.0, 0.0, 0.0, 0.0]\n result = [float(\"%.1f\" % abs(f)) for f in fft.fft(x)]\n self.assertEqual(result, y)\n\n def test_complex_numbers(self):\n x = [2.0+2j, 1.0+3j, 3.0+1j, 2.0+2j]\n real = [8.0, 0.0, 2.0, -2.0]\n imag = [8.0, 2.0, -2.0, 0.0]\n realResult = [float(\"%.1f\" % f.real) for f in fft.fft(x)]\n imagResult = [float(\"%.1f\" % f.imag) for f in fft.fft(x)]\n self.assertEqual(real, realResult)\n self.assertEqual(imag, imagResult)\n \n\nif __name__ == \"__main__\":\n unittest.main()\n"} +{"Prompt":"summary Test for the file copytransform.py Arguments: unittest type description summary Test for the file croutmatrixdecomposition.py Arguments: unittest type description summary Test for the file choleskymatrixdecomposition.py Arguments: unittest type description example taken from https:ece.uwaterloo.cadwharderNumericalAnalysis04LinearAlgebracholesky summary Test for the file matrixinversion.py Arguments: unittest type description summary Test for the file matrixexponentiation.py Arguments: unittest type description summary Test for the file multiply.py Arguments: unittest type description summary Test for the file rotateimage.py Arguments: unittest type description summary Test for the file sparsedotvector.py Arguments: unittest type description summary Test for the file spiraltraversal.py Arguments: unittest type description summary Test for the file sudokuvalidator.py Arguments: unittest type description summary Test for the file sumsubsquares.py Arguments: unittest type description","Completions":"from algorithms.matrix import (\n bomb_enemy,\n copy_transform,\n crout_matrix_decomposition,\n cholesky_matrix_decomposition,\n matrix_exponentiation,\n matrix_inversion,\n multiply,\n rotate_image,\n sparse_dot_vector,\n spiral_traversal,\n sudoku_validator,\n sum_sub_squares,\n sort_matrix_diagonally\n)\nimport unittest\n\n\nclass TestBombEnemy(unittest.TestCase):\n def test_3x4(self):\n grid1 = [\n [\"0\", \"E\", \"0\", \"0\"],\n [\"E\", \"0\", \"W\", \"E\"],\n [\"0\", \"E\", \"0\", \"0\"]\n ]\n self.assertEqual(3, bomb_enemy.max_killed_enemies(grid1))\n\n grid1 = [\n [\"0\", \"E\", \"0\", \"E\"],\n [\"E\", \"E\", \"E\", \"0\"],\n [\"E\", \"0\", \"W\", \"E\"],\n [\"0\", \"E\", \"0\", \"0\"]\n ]\n grid2 = [\n [\"0\", \"0\", \"0\", \"E\"],\n [\"E\", \"0\", \"0\", \"0\"],\n [\"E\", \"0\", \"W\", \"E\"],\n [\"0\", \"E\", \"0\", \"0\"]\n ]\n self.assertEqual(5, bomb_enemy.max_killed_enemies(grid1))\n self.assertEqual(3, bomb_enemy.max_killed_enemies(grid2))\n\n\nclass TestCopyTransform(unittest.TestCase):\n \"\"\"[summary]\n Test for the file copy_transform.py\n\n Arguments:\n unittest {[type]} -- [description]\n \"\"\"\n\n def test_copy_transform(self):\n self.assertEqual(copy_transform.rotate_clockwise(\n [[1, 2, 3], [4, 5, 6], [7, 8, 9]]),\n [[7, 4, 1], [8, 5, 2], [9, 6, 3]])\n\n self.assertEqual(copy_transform.rotate_counterclockwise(\n [[1, 2, 3], [4, 5, 6], [7, 8, 9]]),\n [[3, 6, 9], [2, 5, 8], [1, 4, 7]])\n\n self.assertEqual(copy_transform.top_left_invert(\n [[1, 2, 3], [4, 5, 6], [7, 8, 9]]),\n [[1, 4, 7], [2, 5, 8], [3, 6, 9]])\n\n self.assertEqual(copy_transform.bottom_left_invert(\n [[1, 2, 3], [4, 5, 6], [7, 8, 9]]),\n [[9, 6, 3], [8, 5, 2], [7, 4, 1]])\n\n\nclass TestCroutMatrixDecomposition(unittest.TestCase):\n \"\"\"[summary]\n Test for the file crout_matrix_decomposition.py\n\n Arguments:\n unittest {[type]} -- [description]\n \"\"\"\n\n def test_crout_matrix_decomposition(self):\n self.assertEqual(([[9.0, 0.0], [7.0, 0.0]],\n [[1.0, 1.0], [0.0, 1.0]]),\n crout_matrix_decomposition.crout_matrix_decomposition(\n [[9, 9], [7, 7]]))\n\n self.assertEqual(([[1.0, 0.0, 0.0],\n [3.0, -2.0, 0.0],\n [6.0, -5.0, 0.0]],\n [[1.0, 2.0, 3.0],\n [0.0, 1.0, 2.0],\n [0.0, 0.0, 1.0]]),\n crout_matrix_decomposition.crout_matrix_decomposition(\n [[1, 2, 3], [3, 4, 5], [6, 7, 8]]))\n\n self.assertEqual(([[2.0, 0, 0, 0],\n [4.0, -1.0, 0, 0],\n [6.0, -2.0, 2.0, 0],\n [8.0, -3.0, 3.0, 0.0]],\n [[1.0, 0.5, 1.5, 0.5],\n [0, 1.0, 2.0, 1.0],\n [0, 0, 1.0, 0.0],\n [0, 0, 0, 1.0]]),\n crout_matrix_decomposition.crout_matrix_decomposition(\n [[2, 1, 3, 1], [4, 1, 4, 1], [6, 1, 7, 1],\n [8, 1, 9, 1]]))\n\n\nclass TestCholeskyMatrixDecomposition(unittest.TestCase):\n \"\"\"[summary]\n Test for the file cholesky_matrix_decomposition.py\n\n Arguments:\n unittest {[type]} -- [description]\n \"\"\"\n\n def test_cholesky_matrix_decomposition(self):\n self.assertEqual([[2.0, 0.0, 0.0],\n [6.0, 1.0, 0.0],\n [-8.0, 5.0, 3.0]],\n cholesky_matrix_decomposition.cholesky_decomposition(\n [[4, 12, -16], [12, 37, -43], [-16, -43, 98]]))\n\n self.assertEqual(None,\n cholesky_matrix_decomposition.cholesky_decomposition(\n [[4, 12, -8], [12, 4, -43], [-16, -1, 32]]))\n\n self.assertEqual(None,\n cholesky_matrix_decomposition.cholesky_decomposition(\n [[4, 12, -16], [12, 37, -43], [-16, -43, 98],\n [1, 2, 3]]))\n\n # example taken from https:\/\/ece.uwaterloo.ca\/~dwharder\/NumericalAnalysis\/04LinearAlgebra\/cholesky\/\n self.assertEqual([[2.23606797749979, 0.0, 0.0, 0.0],\n [0.5366563145999494, 2.389979079406345, 0.0, 0.0],\n [0.13416407864998736, -0.19749126846635062,\n 2.818332343581848, 0.0],\n [-0.2683281572999747, 0.43682390737048743,\n 0.64657701271919, 3.052723872310221]],\n cholesky_matrix_decomposition.cholesky_decomposition(\n [[5, 1.2, 0.3, -0.6], [1.2, 6, -0.4, 0.9],\n [0.3, -0.4, 8, 1.7], [-0.6, 0.9, 1.7, 10]]))\n\n\nclass TestInversion(unittest.TestCase):\n \"\"\"[summary]\n Test for the file matrix_inversion.py\n\n Arguments:\n unittest {[type]} -- [description]\n \"\"\"\n\n def test_inversion(self):\n from fractions import Fraction\n\n m1 = [[1, 1], [1, 2]]\n self.assertEqual(matrix_inversion.invert_matrix(m1),\n [[2, -1], [-1, 1]])\n\n m2 = [[1, 2], [3, 4, 5]]\n self.assertEqual(matrix_inversion.invert_matrix(m2), [[-1]])\n\n m3 = [[1, 1, 1, 1], [2, 2, 2, 2]]\n self.assertEqual(matrix_inversion.invert_matrix(m3), [[-2]])\n\n m4 = [[1]]\n self.assertEqual(matrix_inversion.invert_matrix(m4), [[-3]])\n\n m5 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]\n self.assertEqual(matrix_inversion.invert_matrix(m5), [[-4]])\n\n m6 = [[3, 5, 1], [2, 5, 0], [1, 9, 8]]\n self.assertEqual(matrix_inversion.invert_matrix(m6),\n [[Fraction(40, 53),\n Fraction(-31, 53),\n Fraction(-5, 53)],\n [Fraction(-16, 53),\n Fraction(23, 53),\n Fraction(2, 53)],\n [Fraction(13, 53),\n Fraction(-22, 53),\n Fraction(5, 53)]])\n\n\nclass TestMatrixExponentiation(unittest.TestCase):\n \"\"\"[summary]\n Test for the file matrix_exponentiation.py\n\n Arguments:\n unittest {[type]} -- [description]\n \"\"\"\n\n def test_matrix_exponentiation(self):\n mat = [[1, 0, 2], [2, 1, 0], [0, 2, 1]]\n\n self.assertEqual(matrix_exponentiation.matrix_exponentiation(mat, 0),\n [[1, 0, 0], [0, 1, 0], [0, 0, 1]])\n\n self.assertEqual(matrix_exponentiation.matrix_exponentiation(mat, 1),\n [[1, 0, 2], [2, 1, 0], [0, 2, 1]])\n\n self.assertEqual(matrix_exponentiation.matrix_exponentiation(mat, 2),\n [[1, 4, 4], [4, 1, 4], [4, 4, 1]])\n\n self.assertEqual(matrix_exponentiation.matrix_exponentiation(mat, 5),\n [[81, 72, 90], [90, 81, 72], [72, 90, 81]])\n\n\nclass TestMultiply(unittest.TestCase):\n \"\"\"[summary]\n Test for the file multiply.py\n\n Arguments:\n unittest {[type]} -- [description]\n \"\"\"\n\n def test_multiply(self):\n self.assertEqual(multiply.multiply(\n [[1, 2, 3], [2, 1, 1]], [[1], [2], [3]]), [[14], [7]])\n\n\nclass TestRotateImage(unittest.TestCase):\n \"\"\"[summary]\n Test for the file rotate_image.py\n\n Arguments:\n unittest {[type]} -- [description]\n \"\"\"\n\n def test_rotate_image(self):\n self.assertEqual(rotate_image.rotate(\n [[1, 2, 3], [4, 5, 6], [7, 8, 9]]),\n [[7, 4, 1], [8, 5, 2], [9, 6, 3]])\n\n\nclass TestSparseDotVector(unittest.TestCase):\n \"\"\"[summary]\n Test for the file sparse_dot_vector.py\n\n Arguments:\n unittest {[type]} -- [description]\n \"\"\"\n\n def test_sparse_dot_vector(self):\n self.assertEqual(sparse_dot_vector.\n dot_product(sparse_dot_vector.\n vector_to_index_value_list([1., 2., 3.]),\n sparse_dot_vector.\n vector_to_index_value_list([0., 2., 2.])),\n 10)\n\n\nclass TestSpiralTraversal(unittest.TestCase):\n \"\"\"[summary]\n Test for the file spiral_traversal.py\n\n Arguments:\n unittest {[type]} -- [description]\n \"\"\"\n\n def test_spiral_traversal(self):\n self.assertEqual(spiral_traversal.spiral_traversal(\n [[1, 2, 3], [4, 5, 6], [7, 8, 9]]), [1, 2, 3, 6, 9, 8, 7, 4, 5])\n\n\nclass TestSudokuValidator(unittest.TestCase):\n \"\"\"[summary]\n Test for the file sudoku_validator.py\n\n Arguments:\n unittest {[type]} -- [description]\n \"\"\"\n\n def test_sudoku_validator(self):\n self.assertTrue(\n sudoku_validator.valid_solution(\n [\n [5, 3, 4, 6, 7, 8, 9, 1, 2],\n [6, 7, 2, 1, 9, 5, 3, 4, 8],\n [1, 9, 8, 3, 4, 2, 5, 6, 7],\n [8, 5, 9, 7, 6, 1, 4, 2, 3],\n [4, 2, 6, 8, 5, 3, 7, 9, 1],\n [7, 1, 3, 9, 2, 4, 8, 5, 6],\n [9, 6, 1, 5, 3, 7, 2, 8, 4],\n [2, 8, 7, 4, 1, 9, 6, 3, 5],\n [3, 4, 5, 2, 8, 6, 1, 7, 9]\n ]))\n\n self.assertTrue(\n sudoku_validator.valid_solution_hashtable(\n [\n [5, 3, 4, 6, 7, 8, 9, 1, 2],\n [6, 7, 2, 1, 9, 5, 3, 4, 8],\n [1, 9, 8, 3, 4, 2, 5, 6, 7],\n [8, 5, 9, 7, 6, 1, 4, 2, 3],\n [4, 2, 6, 8, 5, 3, 7, 9, 1],\n [7, 1, 3, 9, 2, 4, 8, 5, 6],\n [9, 6, 1, 5, 3, 7, 2, 8, 4],\n [2, 8, 7, 4, 1, 9, 6, 3, 5],\n [3, 4, 5, 2, 8, 6, 1, 7, 9]\n ]))\n\n self.assertTrue(\n sudoku_validator.valid_solution_set(\n [\n [5, 3, 4, 6, 7, 8, 9, 1, 2],\n [6, 7, 2, 1, 9, 5, 3, 4, 8],\n [1, 9, 8, 3, 4, 2, 5, 6, 7],\n [8, 5, 9, 7, 6, 1, 4, 2, 3],\n [4, 2, 6, 8, 5, 3, 7, 9, 1],\n [7, 1, 3, 9, 2, 4, 8, 5, 6],\n [9, 6, 1, 5, 3, 7, 2, 8, 4],\n [2, 8, 7, 4, 1, 9, 6, 3, 5],\n [3, 4, 5, 2, 8, 6, 1, 7, 9]\n ]))\n\n self.assertFalse(\n sudoku_validator.valid_solution(\n [\n [5, 3, 4, 6, 7, 8, 9, 1, 2],\n [6, 7, 2, 1, 9, 0, 3, 4, 9],\n [1, 0, 0, 3, 4, 2, 5, 6, 0],\n [8, 5, 9, 7, 6, 1, 0, 2, 0],\n [4, 2, 6, 8, 5, 3, 7, 9, 1],\n [7, 1, 3, 9, 2, 4, 8, 5, 6],\n [9, 0, 1, 5, 3, 7, 2, 1, 4],\n [2, 8, 7, 4, 1, 9, 6, 3, 5],\n [3, 0, 0, 4, 8, 1, 1, 7, 9]\n ]))\n\n self.assertFalse(\n sudoku_validator.valid_solution_hashtable(\n [\n [5, 3, 4, 6, 7, 8, 9, 1, 2],\n [6, 7, 2, 1, 9, 0, 3, 4, 9],\n [1, 0, 0, 3, 4, 2, 5, 6, 0],\n [8, 5, 9, 7, 6, 1, 0, 2, 0],\n [4, 2, 6, 8, 5, 3, 7, 9, 1],\n [7, 1, 3, 9, 2, 4, 8, 5, 6],\n [9, 0, 1, 5, 3, 7, 2, 1, 4],\n [2, 8, 7, 4, 1, 9, 6, 3, 5],\n [3, 0, 0, 4, 8, 1, 1, 7, 9]\n ]))\n\n self.assertFalse(\n sudoku_validator.valid_solution_set(\n [\n [5, 3, 4, 6, 7, 8, 9, 1, 2],\n [6, 7, 2, 1, 9, 0, 3, 4, 9],\n [1, 0, 0, 3, 4, 2, 5, 6, 0],\n [8, 5, 9, 7, 6, 1, 0, 2, 0],\n [4, 2, 6, 8, 5, 3, 7, 9, 1],\n [7, 1, 3, 9, 2, 4, 8, 5, 6],\n [9, 0, 1, 5, 3, 7, 2, 1, 4],\n [2, 8, 7, 4, 1, 9, 6, 3, 5],\n [3, 0, 0, 4, 8, 1, 1, 7, 9]\n ]))\n\n\nclass TestSumSubSquares(unittest.TestCase):\n \"\"\"[summary]\n Test for the file sum_sub_squares.py\n\n Arguments:\n unittest {[type]} -- [description]\n \"\"\"\n\n def test_sum_sub_squares(self):\n mat = [[1, 1, 1, 1, 1],\n [2, 2, 2, 2, 2],\n [3, 3, 3, 3, 3],\n [4, 4, 4, 4, 4],\n [5, 5, 5, 5, 5]]\n self.assertEqual(sum_sub_squares.sum_sub_squares(mat, 3),\n [[18, 18, 18], [27, 27, 27], [36, 36, 36]])\n\n\nclass TestSortMatrixDiagonally(unittest.TestCase):\n def test_sort_diagonally(self):\n mat = [\n [3, 3, 1, 1],\n [2, 2, 1, 2],\n [1, 1, 1, 2]\n ]\n\n self.assertEqual(sort_matrix_diagonally.sort_diagonally(mat), [\n [1, 1, 1, 1],\n [1, 2, 2, 2],\n [1, 2, 3, 3]\n ])\n\n\nif __name__ == \"__main__\":\n unittest.main()\n"} +{"Prompt":"train set for the ANDfunction train set for light or dark colors ANDfunction darklight color test","Completions":"from algorithms.ml.nearest_neighbor import (\n distance,\n nearest_neighbor\n)\n\nimport unittest\n\n\nclass TestML(unittest.TestCase):\n def setUp(self):\n # train set for the AND-function\n self.trainSetAND = {(0, 0): 0, (0, 1): 0, (1, 0): 0, (1, 1): 1}\n\n # train set for light or dark colors\n self.trainSetLight = {(11, 98, 237): 'L', (3, 39, 96): 'D',\n (242, 226, 12): 'L', (99, 93, 4): 'D',\n (232, 62, 32): 'L', (119, 28, 11): 'D',\n (25, 214, 47): 'L', (89, 136, 247): 'L',\n (21, 34, 63): 'D', (237, 99, 120): 'L',\n (73, 33, 39): 'D'}\n\n def test_nearest_neighbor(self):\n # AND-function\n self.assertEqual(nearest_neighbor((1, 1), self.trainSetAND), 1)\n self.assertEqual(nearest_neighbor((0, 1), self.trainSetAND), 0)\n\n # dark\/light color test\n self.assertEqual(nearest_neighbor((31, 242, 164),\n self.trainSetLight), 'L')\n self.assertEqual(nearest_neighbor((13, 94, 64),\n self.trainSetLight), 'D')\n self.assertEqual(nearest_neighbor((230, 52, 239),\n self.trainSetLight), 'L')\n\n def test_distance(self):\n self.assertAlmostEqual(distance((1, 2, 3), (1, 0, -1)), 4.47, 2)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n"} +{"Prompt":"Monomials with different underlying variables or even different power of those variables must not be added! Additive inverses of each other should produce the zero monomial. Zero monomial Zero monomial Zero monomial Coefficient float. Coefficient 0 so should equal the zero monomial. The constant term cannot be added to any monomial that has any variables. Any literal cannot be added to a Monomial. However, a monomial can be added to any int, float, Fraction, or Monomial. So 2 Monomial is raises TypeError but Monomial 2 may work fine! Any constant added to a zero monomial produces a monomial. Monomials with different underlying variables or even different power of those variables must not be subtracted! Additive inverses of each other should produce the zero monomial. Zero monomial Zero monomial Zero monomial Coefficient int. Coefficient float. The constant term cannot be added to any monomial that has any variables. Any literal cannot be added to a Monomial. However, a monomial can be added to any int, float, Fraction, or Monomial. So 2 Monomial is raises TypeError but Monomial 2 may work fine! Any constant added to a zero monomial produces a monomial. Usual multiplication. The positive and negative powers of the same variable should cancel out. A coefficient of zero should make the product zero. Zero monomial any int, float, Fraction, or Monomial Zero monomial Test usual float multiplication. The Zero monomial is not invertible. Check some inverses. Doesn't matter if the coefficient is Fraction or float. Both should be treated as same. Should work fine without variables too! Any monomial divided by the Zero Monomial should raise a ValueError. Test some usual cases. Test with int. Test with float. Test with Fraction. Test with a complete substitution map. Test with a more than complete substitution map. Should raise a ValueError if not enough variables are supplied! The zero monomial always gives zero upon substitution. Any variable with zero power should not exist in the set of variables. The zero monomial should output empty set. A monomial should produce its copy with same underlying variable dictionary and same coefficient. The zero monomial is identified and always clones to itself.","Completions":"from algorithms.maths.polynomial import Monomial\nfrom fractions import Fraction\nimport math\n\n\nimport unittest\n\n\nclass TestSuite(unittest.TestCase):\n\n\tdef setUp(self):\n\t\tself.m1 = Monomial({})\n\t\tself.m2 = Monomial({1: 1}, 2)\n\t\tself.m3 = Monomial({1: 2, 2: -1}, 1.5)\n\t\tself.m4 = Monomial({1: 1, 2: 2, 3: -2}, 3)\n\t\tself.m5 = Monomial({2: 1, 3: 0}, Fraction(2, 3))\n\t\tself.m6 = Monomial({1: 0, 2: 0, 3: 0}, -2.27)\n\t\tself.m7 = Monomial({1: 2, 7: 2}, -math.pi)\n\t\tself.m8 = Monomial({150: 5, 170: 2, 10000: 3}, 0)\n\t\tself.m9 = 2\n\t\tself.m10 = math.pi\n\t\tself.m11 = Fraction(3, 8)\n\t\tself.m12 = 0\n\t\tself.m13 = Monomial({1: 1}, -2)\n\t\tself.m14 = Monomial({1: 2}, 3)\n\t\tself.m15 = Monomial({1: 1}, 3)\n\t\tself.m16 = Monomial({1: 2, 7: 2}, math.pi)\n\t\tself.m17 = Monomial({1: -1})\n\n\tdef test_monomial_addition(self):\n\n\t\t# Monomials with different underlying variables or\n\t\t# even different power of those variables must not be added!\n\t\tself.assertRaises(ValueError, lambda x, y: x + y, self.m1, self.m2)\n\t\tself.assertRaises(ValueError, lambda x, y: x + y, self.m2, self.m3)\n\t\tself.assertRaises(ValueError, lambda x, y: x + y, self.m2, self.m14)\n\n\t\t# Additive inverses of each other should produce the zero monomial.\n\t\tself.assertEqual(self.m13 + self.m2, self.m1)\n\n\t\t# Zero monomial + Zero monomial = Zero monomial\n\t\tself.assertEqual(self.m1 + self.m1, self.m1)\n\n\t\t# Coefficient float.\n\t\tself.assertEqual(self.m7 + self.m7, Monomial({1: 2, 7: 2},\n\t\t -2 * math.pi))\n\n\t\t# Coefficient 0 so should equal the zero monomial.\n\t\tself.assertEqual(self.m8, self.m1)\n\n\t\t# The constant term cannot be added to any monomial\n\t\t# that has any variables.\n\t\tself.assertRaises(ValueError, lambda x, y: x + y, self.m2, self.m9)\n\n\t\t# Any literal cannot be added to a Monomial. However, a monomial\n\t\t# can be added to any int, float, Fraction, or Monomial.\n\n\t\t# So 2 + Monomial is raises TypeError but Monomial + 2 may work fine!\n\t\tself.assertRaises(TypeError, lambda x, y: x + y, self.m9, self.m2)\n\n\t\t# Any constant added to a zero monomial produces\n\t\t# a monomial.\n\t\tself.assertEqual(self.m1 + self.m9, Monomial({}, 2))\n\t\tself.assertEqual(self.m1 + self.m12, Monomial({}, 0))\n\n\t\treturn\n\n\tdef test_monomial_subtraction(self):\n\n\t\t# Monomials with different underlying variables or\n\t\t# even different power of those variables must not be subtracted!\n\t\tself.assertRaises(ValueError, lambda x, y: x - y, self.m1, self.m2)\n\t\tself.assertRaises(ValueError, lambda x, y: x - y, self.m2, self.m3)\n\t\tself.assertRaises(ValueError, lambda x, y: x - y, self.m2, self.m14)\n\n\t\t# Additive inverses of each other should produce the zero monomial.\n\t\tself.assertEqual(self.m2 - self.m2, self.m1)\n\t\tself.assertEqual(self.m2 - self.m2, Monomial({}, 0))\n\n\t\t# Zero monomial - Zero monomial = Zero monomial\n\t\tself.assertEqual(self.m1 - self.m1, self.m1)\n\n\t\t# Coefficient int.\n\t\tself.assertEqual(self.m2 - self.m15, Monomial({1: 1}, -1))\n\n\t\t# Coefficient float.\n\t\tself.assertEqual(self.m16 - self.m7, Monomial({1: 2, 7: 2},\n\t\t 2 * math.pi))\n\n\t\t# The constant term cannot be added to any monomial\n\t\t# that has any variables.\n\t\tself.assertRaises(ValueError, lambda x, y: x - y, self.m2, self.m9)\n\n\t\t# Any literal cannot be added to a Monomial. However, a monomial\n\t\t# can be added to any int, float, Fraction, or Monomial.\n\n\t\t# So 2 + Monomial is raises TypeError but Monomial + 2 may work fine!\n\t\tself.assertRaises(TypeError, lambda x, y: x - y, self.m9, self.m2)\n\n\t\t# Any constant added to a zero monomial produces\n\t\t# a monomial.\n\t\tself.assertEqual(self.m1 - self.m9, Monomial({}, -2))\n\t\tself.assertEqual(self.m1 - self.m12, Monomial({}, 0))\n\n\t\treturn\n\n\tdef test_monomial_multiplication(self):\n\n\t\t# Usual multiplication.\n\t\t# The positive and negative powers of the same variable\n\t\t# should cancel out.\n\t\tself.assertEqual(self.m2 * self.m13, Monomial({1: 2}, -4))\n\t\tself.assertEqual(self.m2 * self.m17, Monomial({}, 2))\n\n\t\t# A coefficient of zero should make the product zero.\n\t\t# Zero monomial * any int, float, Fraction, or Monomial = Zero monomial\n\t\tself.assertEqual(self.m8 * self.m5, self.m1)\n\t\tself.assertEqual(self.m1 * self.m2, self.m1)\n\n\t\t# Test usual float multiplication.\n\t\tself.assertEqual(self.m7 * self.m3, Monomial({1: 4, 2: -1, 7: 2},\n\t\t -1.5*math.pi))\n\n\t\treturn\n\n\tdef test_monomial_inverse(self):\n\n\t\t# The Zero monomial is not invertible.\n\t\tself.assertRaises(ValueError, lambda x: x.inverse(), self.m1)\n\t\tself.assertRaises(ValueError, lambda x: x.inverse(), self.m8)\n\t\tself.assertRaises(ValueError, lambda x: x.inverse(),\n\t\t Monomial({}, self.m12))\n\n\t\t# Check some inverses.\n\t\tself.assertEqual(self.m7.inverse(), Monomial({1: -2, 7: -2}, -1 \/ math.pi))\n\n\t\t# Doesn't matter if the coefficient is Fraction or float.\n\t\t# Both should be treated as same.\n\t\tself.assertEqual(self.m5.inverse(), Monomial({2: -1}, Fraction(3, 2)))\n\t\tself.assertEqual(self.m5.inverse(), Monomial({2: -1}, 1.5))\n\n\t\t# Should work fine without variables too!\n\t\tself.assertTrue(self.m6.inverse(), Monomial({}, Fraction(-100, 227)))\n\t\tself.assertEqual(self.m6.inverse(), Monomial({}, -1\/2.27))\n\t\treturn\n\n\tdef test_monomial_division(self):\n\t\t# Any monomial divided by the Zero Monomial should raise a ValueError.\n\t\tself.assertRaises(ValueError, lambda x, y: x.__truediv__(y),\n\t\t self.m2, self.m1)\n\t\tself.assertRaises(ValueError, lambda x, y: x.__truediv__(y),\n\t\t self.m2, self.m8)\n\t\tself.assertRaises(ValueError, lambda x, y: x.__truediv__(y),\n\t\t self.m2, self.m12)\n\n\t\t# Test some usual cases.\n\t\tself.assertEqual(self.m7 \/ self.m3, Monomial({2: 1, 7: 2},\n\t\t -2 * math.pi \/ 3))\n\t\tself.assertEqual(self.m14 \/ self.m13, Monomial({1: 1}) * Fraction(-3, 2))\n\n\t\treturn\n\n\tdef test_monomial_substitution(self):\n\t\t# Test with int.\n\t\tself.assertAlmostEqual(self.m7.substitute(2), -16 * math.pi, delta=1e-9)\n\t\t# Test with float.\n\t\tself.assertAlmostEqual(self.m7.substitute(1.5), (1.5 ** 4) * -math.pi,\n\t\t delta=1e-9)\n\t\t# Test with Fraction.\n\t\tself.assertAlmostEqual(self.m7.substitute(Fraction(-1, 2)),\n\t\t (Fraction(-1, 2) ** 4)*-math.pi, delta=1e-9)\n\t\t# Test with a complete substitution map.\n\t\tself.assertAlmostEqual(self.m7.substitute({1: 3, 7: 0}),\n\t\t (3 ** 2) * (0 ** 2) * -math.pi, delta=1e-9)\n\t\t# Test with a more than complete substitution map.\n\t\tself.assertAlmostEqual(self.m7.substitute({1: 3, 7: 0, 2: 2}),\n\t\t (3 ** 2) * (0 ** 2) * -math.pi, delta=1e-9)\n\n\t\t# Should raise a ValueError if not enough variables are supplied!\n\t\tself.assertRaises(ValueError, lambda x, y: x.substitute(y), self.m7,\n\t\t {1: 3, 2: 2})\n\t\tself.assertRaises(ValueError, lambda x, y: x.substitute(y), self.m7,\n\t\t {2: 2})\n\n\t\t# The zero monomial always gives zero upon substitution.\n\t\tself.assertEqual(self.m8.substitute(2), 0)\n\t\tself.assertEqual(self.m8.substitute({1231: 2, 1: 2}), 0)\n\n\t\treturn\n\n\tdef test_monomial_all_variables(self):\n\n\t\t# Any variable with zero power should not exist in the set\n\t\t# of variables.\n\t\tself.assertEqual(self.m5.all_variables(), {2})\n\t\tself.assertEqual(self.m6.all_variables(), set())\n\n\t\t# The zero monomial should output empty set.\n\t\tself.assertEqual(self.m8.all_variables(), set())\n\n\t\treturn\n\n\tdef test_monomial_clone(self):\n\n\t\t# A monomial should produce its copy\n\t\t# with same underlying variable dictionary\n\t\t# and same coefficient.\n\t\tself.assertEqual(self.m3, self.m3.clone())\n\n\t\t# The zero monomial is identified and\n\t\t# always clones to itself.\n\t\tself.assertEqual(self.m1, self.m8.clone())\n\t\tself.assertEqual(self.m1, self.m1.clone())\n\t\tself.assertEqual(self.m8, self.m1.clone())\n\t\tself.assertEqual(self.m8, self.m8.clone())\n\t\treturn\n\n\nif __name__ == '__main__':\n\tunittest.main()\n"} +{"Prompt":"The zero polynomials should add up to itselves only. Additive inverses should add up to the zero polynomial. Like terms should combine. The order of monomials should not matter. Another typical computation. Should raise a ValueError if the divisor is not a monomial or a polynomial with only one term. The zero polynomial has no variables. The total variables are the union of the variables from the monomials. The monomials with coefficient 0 should be dropped. Anything substitued in the zero polynomial should evaluate to 0. Should raise a ValueError if not enough variables are supplied. Should work fine if a complete subsitution map is provided. Should work fine if more than enough substitutions are provided. The zero polynomial always clones to itself. The polynomial should clone nicely. The monomial with a zero coefficient should be dropped in the clone.","Completions":"from algorithms.maths.polynomial import (\n\tPolynomial,\n\tMonomial\n)\nfrom fractions import Fraction\nimport math\n\n\nimport unittest\n\nclass TestSuite(unittest.TestCase):\n\n\tdef setUp(self):\n\t\tself.p0 = Polynomial([\n\t\t\tMonomial({})\n\t\t])\n\t\tself.p1 = Polynomial([\n\t\t\tMonomial({}), Monomial({})\n\t\t])\n\t\tself.p2 = Polynomial([\n\t\t\tMonomial({1: 1}, 2)\n\t\t])\n\t\tself.p3 = Polynomial([\n\t\t\tMonomial({1: 1}, 2),\n\t\t\tMonomial({1: 2, 2: -1}, 1.5)\n\t\t])\n\t\tself.p4 = Polynomial([\n\t\t\tMonomial({2: 1, 3: 0}, Fraction(2, 3)),\n\t\t\tMonomial({1: -1, 3: 2}, math.pi),\n\t\t\tMonomial({1: -1, 3: 2}, 1)\n\t\t])\n\t\tself.p5 = Polynomial([\n\t\t\tMonomial({150: 5, 170: 2, 10000:3}, 0),\n\t\t\tMonomial({1: -1, 3: 2}, 1),\t\n\t\t])\n\t\tself.p6 = Polynomial([\n\t\t\t2,\n\t\t\t-3,\n\t\t\tFraction(1, 7),\n\t\t\t2**math.pi,\n\t\t\tMonomial({2: 3, 3: 1}, 1.25)\n\t\t])\n\t\tself.p7 = Polynomial([\n\t\t\tMonomial({1: 1}, -2),\n\t\t\tMonomial({1: 2, 2: -1}, -1.5)\n\t\t])\n\n\t\tself.m1 = Monomial({1: 2, 2: 3}, -1)\n\n\t\treturn\n\n\tdef test_polynomial_addition(self):\n\t\t\n\t\t# The zero polynomials should add up to\n\t\t# itselves only.\n\t\tself.assertEqual(self.p0 + self.p1, self.p0)\n\t\tself.assertEqual(self.p0 + self.p1, self.p1)\n\t\t\n\t\t# Additive inverses should add up to the\n\t\t# zero polynomial.\n\t\tself.assertEqual(self.p3 + self.p7, self.p0)\n\t\tself.assertEqual(self.p3 + self.p7, self.p1)\n\n\t\t# Like terms should combine.\n\t\t# The order of monomials should not matter.\n\t\tself.assertEqual(self.p2 + self.p3, Polynomial([\n\t\t\tMonomial({1: 1}, 4),\n\t\t\tMonomial({1: 2, 2: -1}, 1.5)\n\t\t]))\n\t\tself.assertEqual(self.p2 + self.p3, Polynomial([\n\t\t\tMonomial({1: 2, 2: -1}, 1.5),\n\t\t\tMonomial({1: 1}, 4),\n\t\t]))\n\n\t\t# Another typical computation.\n\t\tself.assertEqual(self.p5 + self.p6, Polynomial([\n\t\t\tMonomial({}, 7.96783496993343),\n\t\t\tMonomial({2: 3, 3: 1}, 1.25),\n\t\t\tMonomial({1: -1, 3: 2})\n\t\t]))\n\n\t\treturn\n\n\tdef test_polynomial_subtraction(self):\n\n\t\tself.assertEqual(self.p3 - self.p2, Polynomial([\n\t\t\tMonomial({1: 2, 2: -1}, 1.5)\n\t\t]))\n\n\t\tself.assertEqual(self.p3 - self.p3, Polynomial([]))\n\n\t\tself.assertEqual(self.p2 - self.p3, Polynomial([\n\t\t\tMonomial({1: 2, 2: -1}, -1.5)\n\t\t]))\n\n\t\tpass\n\n\tdef test_polynomial_multiplication(self):\n\t\tself.assertEqual(self.p0 * self.p2, Polynomial([]))\n\t\tself.assertEqual(self.p1 * self.p2, Polynomial([]))\n\n\t\tself.assertEqual(self.p2 * self.p3, Polynomial([\n\t\t\tMonomial({1: 2}, 4),\n\t\t\tMonomial({1: 3, 2: -1}, Fraction(3, 1))\n\t\t]))\n\t\treturn\n\n\tdef test_polynomial_division(self):\n\n\t\t# Should raise a ValueError if the divisor is not a monomial\n\t\t# or a polynomial with only one term.\n\t\tself.assertRaises(ValueError, lambda x, y: x \/ y, self.p5, self.p3)\n\t\tself.assertRaises(ValueError, lambda x, y: x \/ y, self.p6, self.p4)\n\n\t\tself.assertEqual(self.p3 \/ self.p2, Polynomial([\n\t\t\tMonomial({}, 1),\n\t\t\tMonomial({1: 1, 2: -1}, 0.75)\n\t\t]))\n\t\tself.assertEqual(self.p7 \/ self.m1, Polynomial([\n\t\t\tMonomial({1: -1, 2: -3}, 2),\n\t\t\tMonomial({1: 0, 2: -4}, 1.5)\n\t\t]))\n\t\tself.assertEqual(self.p7 \/ self.m1, Polynomial([\n\t\t\tMonomial({1: -1, 2: -3}, 2),\n\t\t\tMonomial({2: -4}, 1.5)\n\t\t]))\n\t\treturn\n\n\tdef test_polynomial_variables(self):\n\t\t# The zero polynomial has no variables.\n\n\t\tself.assertEqual(self.p0.variables(), set())\n\t\tself.assertEqual(self.p1.variables(), set())\n\n\t\t# The total variables are the union of the variables\n\t\t# from the monomials.\n\t\tself.assertEqual(self.p4.variables(), {1, 2, 3})\n\n\t\t# The monomials with coefficient 0 should be dropped.\n\t\tself.assertEqual(self.p5.variables(), {1, 3})\n\t\treturn\n\n\tdef test_polynomial_subs(self):\n\t\t# Anything substitued in the zero polynomial\n\t\t# should evaluate to 0.\n\t\tself.assertEqual(self.p1.subs(2), 0)\n\t\tself.assertEqual(self.p0.subs(-101231), 0)\n\n\t\t# Should raise a ValueError if not enough variables are supplied.\n\t\tself.assertRaises(ValueError, lambda x, y: x.subs(y), self.p4, {1: 3, 2: 2})\n\t\tself.assertRaises(ValueError, lambda x, y: x.subs(y), self.p4, {})\n\n\t\t# Should work fine if a complete subsitution map is provided.\n\t\tself.assertAlmostEqual(self.p4.subs({1: 1, 2: 1, 3: 1}), (1 + math.pi + Fraction(2, 3)), delta=1e-9)\n\t\t# Should work fine if more than enough substitutions are provided.\n\t\tself.assertAlmostEqual(self.p4.subs({1: 1, 2: 1, 3: 1, 4: 1}), (1 + math.pi + Fraction(2, 3)), delta=1e-9)\n\t\treturn\n\n\tdef test_polynomial_clone(self):\n\n\t\t# The zero polynomial always clones to itself.\n\t\tself.assertEqual(self.p0.clone(), self.p0)\n\t\tself.assertEqual(self.p1.clone(), self.p0)\n\t\tself.assertEqual(self.p0.clone(), self.p1)\n\t\tself.assertEqual(self.p1.clone(), self.p1)\n\n\t\t# The polynomial should clone nicely.\n\t\tself.assertEqual(self.p4.clone(), self.p4)\n\n\t\t# The monomial with a zero coefficient should be dropped\n\t\t# in the clone.\n\t\tself.assertEqual(self.p5.clone(), Polynomial([\n\t\t\tMonomial({1: -1, 3: 2}, 1)\n\t\t]))\n\t\treturn"} +{"Prompt":"Test suite for the Queue data structures. test iter test len test isempty test peek test dequeue test iter test len test isempty test peek test dequeue Test suite for the PriorityQueue data structures.","Completions":"import unittest\n\nfrom algorithms.queues import (\n ArrayQueue, LinkedListQueue,\n max_sliding_window,\n reconstruct_queue,\n PriorityQueue\n)\n\n\nclass TestQueue(unittest.TestCase):\n \"\"\"\n Test suite for the Queue data structures.\n \"\"\"\n\n def test_ArrayQueue(self):\n queue = ArrayQueue()\n queue.enqueue(1)\n queue.enqueue(2)\n queue.enqueue(3)\n\n # test __iter__()\n it = iter(queue)\n self.assertEqual(1, next(it))\n self.assertEqual(2, next(it))\n self.assertEqual(3, next(it))\n self.assertRaises(StopIteration, next, it)\n\n # test __len__()\n self.assertEqual(3, len(queue))\n\n # test is_empty()\n self.assertFalse(queue.is_empty())\n\n # test peek()\n self.assertEqual(1, queue.peek())\n\n # test dequeue()\n self.assertEqual(1, queue.dequeue())\n self.assertEqual(2, queue.dequeue())\n self.assertEqual(3, queue.dequeue())\n\n self.assertTrue(queue.is_empty())\n\n def test_LinkedListQueue(self):\n queue = LinkedListQueue()\n queue.enqueue(1)\n queue.enqueue(2)\n queue.enqueue(3)\n\n # test __iter__()\n it = iter(queue)\n self.assertEqual(1, next(it))\n self.assertEqual(2, next(it))\n self.assertEqual(3, next(it))\n self.assertRaises(StopIteration, next, it)\n\n # test __len__()\n self.assertEqual(3, len(queue))\n\n # test is_empty()\n self.assertFalse(queue.is_empty())\n\n # test peek()\n self.assertEqual(1, queue.peek())\n\n # test dequeue()\n self.assertEqual(1, queue.dequeue())\n self.assertEqual(2, queue.dequeue())\n self.assertEqual(3, queue.dequeue())\n\n self.assertTrue(queue.is_empty())\n\n\nclass TestSuite(unittest.TestCase):\n def test_max_sliding_window(self):\n array = [1, 3, -1, -3, 5, 3, 6, 7]\n self.assertEqual(max_sliding_window(array, k=5), [5, 5, 6, 7])\n self.assertEqual(max_sliding_window(array, k=3), [3, 3, 5, 5, 6, 7])\n self.assertEqual(max_sliding_window(array, k=7), [6, 7])\n\n array = [8, 5, 10, 7, 9, 4, 15, 12, 90, 13]\n self.assertEqual(max_sliding_window(array, k=4),\n [10, 10, 10, 15, 15, 90, 90])\n self.assertEqual(max_sliding_window(array, k=7), [15, 15, 90, 90])\n self.assertEqual(max_sliding_window(array, k=2),\n [8, 10, 10, 9, 9, 15, 15, 90, 90])\n\n def test_reconstruct_queue(self):\n self.assertEqual([[5, 0], [7, 0], [5, 2], [6, 1], [4, 4], [7, 1]],\n reconstruct_queue([[7, 0], [4, 4], [7, 1], [5, 0],\n [6, 1], [5, 2]]))\n\n\nclass TestPriorityQueue(unittest.TestCase):\n \"\"\"Test suite for the PriorityQueue data structures.\n \"\"\"\n\n def test_PriorityQueue(self):\n queue = PriorityQueue([3, 4, 1, 6])\n self.assertEqual(4, queue.size())\n self.assertEqual(1, queue.pop())\n self.assertEqual(3, queue.size())\n queue.push(2)\n self.assertEqual(4, queue.size())\n self.assertEqual(2, queue.pop())\n\n\nif __name__ == \"__main__\":\n unittest.main()\n"} +{"Prompt":"Test binarysearchrecur test twosum test twosum1 test twosum2 Test find min using recursion","Completions":"from algorithms.search import (\n binary_search, binary_search_recur,\n ternary_search,\n first_occurrence,\n last_occurrence,\n linear_search,\n search_insert,\n two_sum, two_sum1, two_sum2,\n search_range,\n find_min_rotate, find_min_rotate_recur,\n search_rotate, search_rotate_recur,\n jump_search,\n next_greatest_letter, next_greatest_letter_v1, next_greatest_letter_v2,\n interpolation_search\n)\n\nimport unittest\n\n\nclass TestSuite(unittest.TestCase):\n\n def test_first_occurrence(self):\n def helper(array, query):\n idx = array.index(query) if query in array else None\n return idx\n array = [1, 1, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 6, 6, 6]\n self.assertEqual(first_occurrence(array, 1), helper(array, 1))\n self.assertEqual(first_occurrence(array, 3), helper(array, 3))\n self.assertEqual(first_occurrence(array, 5), helper(array, 5))\n self.assertEqual(first_occurrence(array, 6), helper(array, 6))\n self.assertEqual(first_occurrence(array, 7), helper(array, 7))\n self.assertEqual(first_occurrence(array, -1), helper(array, -1))\n\n def test_binary_search(self):\n array = [1, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 6]\n self.assertEqual(10, binary_search(array, 5))\n self.assertEqual(11, binary_search(array, 6))\n self.assertEqual(None, binary_search(array, 7))\n self.assertEqual(None, binary_search(array, -1))\n # Test binary_search_recur\n self.assertEqual(10, binary_search_recur(array, 0, 11, 5))\n self.assertEqual(11, binary_search_recur(array, 0, 11, 6))\n self.assertEqual(-1, binary_search_recur(array, 0, 11, 7))\n self.assertEqual(-1, binary_search_recur(array, 0, 11, -1))\n\n def test_ternary_search(self):\n array = [1, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 6]\n self.assertEqual(10, ternary_search(0, 11, 5, array))\n self.assertEqual(3, ternary_search(0, 10, 3, array))\n self.assertEqual(-1, ternary_search(0, 10, 5, array))\n self.assertEqual(-1, ternary_search(0, 11, 7, array))\n self.assertEqual(-1, ternary_search(0, 11, -1, array))\n\n def test_last_occurrence(self):\n array = [1, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 6, 6, 6]\n self.assertEqual(5, last_occurrence(array, 3))\n self.assertEqual(10, last_occurrence(array, 5))\n self.assertEqual(None, last_occurrence(array, 7))\n self.assertEqual(0, last_occurrence(array, 1))\n self.assertEqual(13, last_occurrence(array, 6))\n\n def test_linear_search(self):\n array = [1, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 6, 6, 6]\n self.assertEqual(6, linear_search(array, 4))\n self.assertEqual(10, linear_search(array, 5))\n self.assertEqual(-1, linear_search(array, 7))\n self.assertEqual(-1, linear_search(array, -1))\n\n def test_search_insert(self):\n array = [1, 3, 5, 6]\n self.assertEqual(2, search_insert(array, 5))\n self.assertEqual(1, search_insert(array, 2))\n self.assertEqual(4, search_insert(array, 7))\n self.assertEqual(0, search_insert(array, 0))\n\n def test_two_sum(self):\n array = [2, 7, 11, 15]\n # test two_sum\n self.assertEqual([1, 2], two_sum(array, 9))\n self.assertEqual([2, 4], two_sum(array, 22))\n # test two_sum1\n self.assertEqual([1, 2], two_sum1(array, 9))\n self.assertEqual([2, 4], two_sum1(array, 22))\n # test two_sum2\n self.assertEqual([1, 2], two_sum2(array, 9))\n self.assertEqual([2, 4], two_sum2(array, 22))\n\n def test_search_range(self):\n array = [5, 7, 7, 8, 8, 8, 10]\n self.assertEqual([3, 5], search_range(array, 8))\n self.assertEqual([1, 2], search_range(array, 7))\n self.assertEqual([-1, -1], search_range(array, 11))\n\n array = [5, 7, 7, 7, 7, 8, 8, 8, 8, 10]\n self.assertEqual([5, 8], search_range(array, 8))\n self.assertEqual([1, 4], search_range(array, 7))\n self.assertEqual([-1, -1], search_range(array, 11))\n\n def test_find_min_rotate(self):\n array = [4, 5, 6, 7, 0, 1, 2]\n self.assertEqual(0, find_min_rotate(array))\n array = [10, 20, -1, 0, 1, 2, 3, 4, 5]\n self.assertEqual(-1, find_min_rotate(array))\n # Test find min using recursion\n array = [4, 5, 6, 7, 0, 1, 2]\n self.assertEqual(0, find_min_rotate_recur(array, 0, 6))\n array = [10, 20, -1, 0, 1, 2, 3, 4, 5]\n self.assertEqual(-1, find_min_rotate_recur(array, 0, 8))\n\n def test_search_rotate(self):\n array = [15, 16, 19, 20, 25, 1, 3, 4, 5, 7, 10, 14]\n self.assertEqual(8, search_rotate(array, 5))\n self.assertEqual(-1, search_rotate(array, 9))\n self.assertEqual(8, search_rotate_recur(array, 0, 11, 5))\n self.assertEqual(-1, search_rotate_recur(array, 0, 11, 9))\n\n def test_jump_search(self):\n array = [1, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 6]\n self.assertEqual(10, jump_search(array, 5))\n self.assertEqual(2, jump_search(array, 3))\n self.assertEqual(-1, jump_search(array, 7))\n self.assertEqual(-1, jump_search(array, -1))\n\n def test_next_greatest_letter(self):\n letters = [\"c\", \"f\", \"j\"]\n target = \"a\"\n self.assertEqual(\"c\", next_greatest_letter(letters, target))\n self.assertEqual(\"c\", next_greatest_letter_v1(letters, target))\n self.assertEqual(\"c\", next_greatest_letter_v2(letters, target))\n letters = [\"c\", \"f\", \"j\"]\n target = \"d\"\n self.assertEqual(\"f\", next_greatest_letter(letters, target))\n self.assertEqual(\"f\", next_greatest_letter_v1(letters, target))\n self.assertEqual(\"f\", next_greatest_letter_v2(letters, target))\n letters = [\"c\", \"f\", \"j\"]\n target = \"j\"\n self.assertEqual(\"c\", next_greatest_letter(letters, target))\n self.assertEqual(\"c\", next_greatest_letter_v1(letters, target))\n self.assertEqual(\"c\", next_greatest_letter_v2(letters, target))\n\n def test_interpolation_search(self):\n array = [0, 3, 5, 5, 9, 12, 12, 15, 16, 19, 20]\n self.assertEqual(1, interpolation_search(array, 3))\n self.assertEqual(2, interpolation_search(array, 5))\n self.assertEqual(6, interpolation_search(array, 12))\n self.assertEqual(-1, interpolation_search(array, 22))\n self.assertEqual(-1, interpolation_search(array, -10))\n self.assertEqual(10, interpolation_search(array, 20))\n\n\nif __name__ == '__main__':\n\n unittest.main()\n"} +{"Prompt":"Helper function to check if the given array is sorted. :param array: Array to check if sorted :return: True if sorted in ascending order, else False printres","Completions":"from algorithms.sort import (\n bitonic_sort,\n bogo_sort,\n bubble_sort,\n comb_sort,\n counting_sort,\n cycle_sort,\n exchange_sort,\n max_heap_sort, min_heap_sort,\n merge_sort,\n pancake_sort,\n pigeonhole_sort,\n quick_sort,\n selection_sort,\n bucket_sort,\n shell_sort,\n radix_sort,\n gnome_sort,\n cocktail_shaker_sort,\n top_sort, top_sort_recursive\n)\n\nimport unittest\n\n\ndef is_sorted(array):\n \"\"\"\n Helper function to check if the given array is sorted.\n :param array: Array to check if sorted\n :return: True if sorted in ascending order, else False\n \"\"\"\n for i in range(len(array) - 1):\n if array[i] > array[i + 1]:\n return False\n\n return True\n\n\nclass TestSuite(unittest.TestCase):\n def test_bogo_sort(self):\n self.assertTrue(is_sorted(bogo_sort([1, 23, 5])))\n\n def test_bitonic_sort(self):\n self.assertTrue(is_sorted(bitonic_sort([1, 3, 2, 5, 65,\n 23, 57, 1232])))\n\n def test_bubble_sort(self):\n self.assertTrue(is_sorted(bubble_sort([1, 3, 2, 5, 65, 23, 57, 1232])))\n\n def test_comb_sort(self):\n self.assertTrue(is_sorted(comb_sort([1, 3, 2, 5, 65, 23, 57, 1232])))\n\n def test_counting_sort(self):\n self.assertTrue(is_sorted(counting_sort([1, 3, 2, 5, 65,\n 23, 57, 1232])))\n\n def test_cycle_sort(self):\n self.assertTrue(is_sorted(cycle_sort([1, 3, 2, 5, 65, 23, 57, 1232])))\n\n def test_exchange_sort(self):\n self.assertTrue(is_sorted(exchange_sort([1, 3, 2, 5, 65,\n 23, 57, 1232])))\n\n def test_heap_sort(self):\n self.assertTrue(is_sorted(max_heap_sort([1, 3, 2, 5, 65,\n 23, 57, 1232])))\n\n self.assertTrue(is_sorted(min_heap_sort([1, 3, 2, 5, 65,\n 23, 57, 1232])))\n\n def test_insertion_sort(self):\n self.assertTrue(is_sorted(bitonic_sort([1, 3, 2, 5, 65,\n 23, 57, 1232])))\n\n def test_merge_sort(self):\n self.assertTrue(is_sorted(merge_sort([1, 3, 2, 5, 65, 23, 57, 1232])))\n\n def test_pancake_sort(self):\n self.assertTrue(is_sorted(pancake_sort([1, 3, 2, 5, 65,\n 23, 57, 1232])))\n\n def test_pigeonhole_sort(self):\n self.assertTrue(is_sorted(pigeonhole_sort([1, 5, 65, 23, 57, 1232])))\n\n def test_quick_sort(self):\n self.assertTrue(is_sorted(quick_sort([1, 3, 2, 5, 65, 23, 57, 1232])))\n\n def test_selection_sort(self):\n self.assertTrue(is_sorted(selection_sort([1, 3, 2, 5, 65,\n 23, 57, 1232])))\n\n def test_bucket_sort(self):\n self.assertTrue(is_sorted(bucket_sort([1, 3, 2, 5, 65, 23, 57, 1232])))\n\n def test_shell_sort(self):\n self.assertTrue(is_sorted(shell_sort([1, 3, 2, 5, 65, 23, 57, 1232])))\n\n def test_radix_sort(self):\n self.assertTrue(is_sorted(radix_sort([1, 3, 2, 5, 65, 23, 57, 1232])))\n\n def test_gnome_sort(self):\n self.assertTrue(is_sorted(gnome_sort([1, 3, 2, 5, 65, 23, 57, 1232])))\n\n def test_cocktail_shaker_sort(self):\n self.assertTrue(is_sorted(cocktail_shaker_sort([1, 3, 2, 5, 65,\n 23, 57, 1232])))\n\n\nclass TestTopSort(unittest.TestCase):\n def setUp(self):\n self.depGraph = {\n \"a\": [\"b\"],\n \"b\": [\"c\"],\n \"c\": ['e'],\n 'e': ['g'],\n \"d\": [],\n \"f\": [\"e\", \"d\"],\n \"g\": []\n }\n\n def test_topsort(self):\n res = top_sort_recursive(self.depGraph)\n # print(res)\n self.assertTrue(res.index('g') < res.index('e'))\n res = top_sort(self.depGraph)\n self.assertTrue(res.index('g') < res.index('e'))\n\n\nif __name__ == \"__main__\":\n unittest.main()\n"} +{"Prompt":"Test case: bottom 6, 3, 5, 1, 2, 4 top Test case: bottom 2, 8, 3, 6, 7, 3 top Test case: 2 smallest value 2, 8, 3, 7, 3 Test case: bottom 3, 7, 1, 14, 9 top Test case: even number of values in stack bottom 3, 8, 17, 9, 1, 10 top Test case: odd number of values in stack bottom 3, 8, 17, 9, 1 top test iter test len test str test isempty test peek test pop test iter test len test str test isempty test peek test pop","Completions":"from algorithms.stack import (\n first_is_consecutive, second_is_consecutive,\n is_sorted,\n remove_min,\n first_stutter, second_stutter,\n first_switch_pairs, second_switch_pairs,\n is_valid,\n simplify_path,\n ArrayStack, LinkedListStack,\n OrderedStack\n)\n\nimport unittest\n\n\nclass TestSuite(unittest.TestCase):\n def test_is_consecutive(self):\n self.assertTrue(first_is_consecutive([3, 4, 5, 6, 7]))\n self.assertFalse(first_is_consecutive([3, 4, 6, 7]))\n self.assertFalse(first_is_consecutive([3, 2, 1]))\n\n self.assertTrue(second_is_consecutive([3, 4, 5, 6, 7]))\n self.assertFalse(second_is_consecutive([3, 4, 6, 7]))\n self.assertFalse(second_is_consecutive([3, 2, 1]))\n\n def test_is_sorted(self):\n # Test case: bottom [6, 3, 5, 1, 2, 4] top\n self.assertFalse(is_sorted([6, 3, 5, 1, 2, 4]))\n self.assertTrue(is_sorted([1, 2, 3, 4, 5, 6]))\n self.assertFalse(is_sorted([3, 4, 7, 8, 5, 6]))\n\n def test_remove_min(self):\n # Test case: bottom [2, 8, 3, -6, 7, 3] top\n self.assertEqual([2, 8, 3, 7, 3], remove_min([2, 8, 3, -6, 7, 3]))\n # Test case: 2 smallest value [2, 8, 3, 7, 3]\n self.assertEqual([4, 8, 7], remove_min([4, 8, 3, 7, 3]))\n\n def test_stutter(self):\n # Test case: bottom [3, 7, 1, 14, 9] top\n self.assertEqual([3, 3, 7, 7, 1, 1, 14, 14, 9, 9],\n first_stutter([3, 7, 1, 14, 9]))\n self.assertEqual([3, 3, 7, 7, 1, 1, 14, 14, 9, 9],\n second_stutter([3, 7, 1, 14, 9]))\n\n def test_switch_pairs(self):\n # Test case: even number of values in stack\n # bottom [3, 8, 17, 9, 1, 10] top\n self.assertEqual([8, 3, 9, 17, 10, 1],\n first_switch_pairs([3, 8, 17, 9, 1, 10]))\n self.assertEqual([8, 3, 9, 17, 10, 1],\n second_switch_pairs([3, 8, 17, 9, 1, 10]))\n # Test case: odd number of values in stack\n # bottom [3, 8, 17, 9, 1] top\n self.assertEqual([8, 3, 9, 17, 1],\n first_switch_pairs([3, 8, 17, 9, 1]))\n self.assertEqual([8, 3, 9, 17, 1],\n second_switch_pairs([3, 8, 17, 9, 1]))\n\n def test_is_valid_parenthesis(self):\n\n self.assertTrue(is_valid(\"[]\"))\n self.assertTrue(is_valid(\"[]()[]\"))\n self.assertFalse(is_valid(\"[[[]]\"))\n self.assertTrue(is_valid(\"{([])}\"))\n self.assertFalse(is_valid(\"(}\"))\n\n def test_simplify_path(self):\n p = '\/my\/name\/is\/..\/\/keon'\n self.assertEqual('\/my\/name\/keon', simplify_path(p))\n\n\nclass TestStack(unittest.TestCase):\n def test_ArrayStack(self):\n stack = ArrayStack()\n stack.push(1)\n stack.push(2)\n stack.push(3)\n\n # test __iter__()\n it = iter(stack)\n self.assertEqual(3, next(it))\n self.assertEqual(2, next(it))\n self.assertEqual(1, next(it))\n self.assertRaises(StopIteration, next, it)\n\n # test __len__()\n self.assertEqual(3, len(stack))\n\n # test __str__()\n self.assertEqual(str(stack), \"Top-> 3 2 1\")\n\n # test is_empty()\n self.assertFalse(stack.is_empty())\n\n # test peek()\n self.assertEqual(3, stack.peek())\n\n # test pop()\n self.assertEqual(3, stack.pop())\n self.assertEqual(2, stack.pop())\n self.assertEqual(1, stack.pop())\n\n self.assertTrue(stack.is_empty())\n\n def test_LinkedListStack(self):\n stack = LinkedListStack()\n\n stack.push(1)\n stack.push(2)\n stack.push(3)\n\n # test __iter__()\n it = iter(stack)\n self.assertEqual(3, next(it))\n self.assertEqual(2, next(it))\n self.assertEqual(1, next(it))\n self.assertRaises(StopIteration, next, it)\n\n # test __len__()\n self.assertEqual(3, len(stack))\n\n # test __str__()\n self.assertEqual(str(stack), \"Top-> 3 2 1\")\n\n # test is_empty()\n self.assertFalse(stack.is_empty())\n\n # test peek()\n self.assertEqual(3, stack.peek())\n\n # test pop()\n self.assertEqual(3, stack.pop())\n self.assertEqual(2, stack.pop())\n self.assertEqual(1, stack.pop())\n\n self.assertTrue(stack.is_empty())\n\n\nclass TestOrderedStack(unittest.TestCase):\n def test_OrderedStack(self):\n stack = OrderedStack()\n self.assertTrue(stack.is_empty())\n stack.push(1)\n stack.push(4)\n stack.push(3)\n stack.push(6)\n \"bottom - > 1 3 4 6 \"\n self.assertEqual(6, stack.pop())\n self.assertEqual(4, stack.peek())\n self.assertEqual(3, stack.size())\n\n\nif __name__ == \"__main__\":\n unittest.main()\n"} +{"Prompt":"Bitsum sum of sign is inccorect","Completions":"from algorithms.streaming.misra_gries import (\n misras_gries,\n)\nfrom algorithms.streaming import (\n one_sparse\n)\nimport unittest\n\n\nclass TestMisraGreis(unittest.TestCase):\n def test_misra_correct(self):\n self.assertEqual({'4': 5}, misras_gries([1, 4, 4, 4, 5, 4, 4]))\n self.assertEqual({'1': 4}, misras_gries([0, 0, 0, 1, 1, 1, 1]))\n self.assertEqual({'0': 4, '1': 3}, misras_gries([0, 0, 0, 0, 1, 1,\n 1, 2, 2], 3))\n\n def test_misra_incorrect(self):\n self.assertEqual(None, misras_gries([1, 2, 5, 4, 5, 4, 4, 5, 4, 4, 5]))\n self.assertEqual(None, misras_gries([0, 0, 0, 2, 1, 1, 1]))\n self.assertEqual(None, misras_gries([0, 0, 0, 1, 1, 1]))\n\n\nclass TestOneSparse(unittest.TestCase):\n def test_one_sparse_correct(self):\n self.assertEqual(4, one_sparse([(4, '+'), (2, '+'), (2, '-'),\n (4, '+'), (3, '+'), (3, '-')]))\n self.assertEqual(2, one_sparse([(2, '+'), (2, '+'), (2, '+'),\n (2, '+'), (2, '+'), (2, '+'),\n (2, '+')]))\n\n def test_one_sparse_incorrect(self):\n self.assertEqual(None, one_sparse([(2, '+'), (2, '+'), (2, '+'),\n (2, '+'), (2, '+'), (2, '+'),\n (1, '+')])) # Two values remaining\n self.assertEqual(None, one_sparse([(2, '+'), (2, '+'),\n (2, '+'), (2, '+'),\n (2, '-'), (2, '-'), (2, '-'),\n (2, '-')])) # No values remaining\n # Bitsum sum of sign is inccorect\n self.assertEqual(None, one_sparse([(2, '+'), (2, '+'),\n (4, '+'), (4, '+')]))\n"} +{"Prompt":"summary Test for the file addbinary.py Arguments: unittest type description summary Test for the file breakingbad.py Arguments: unittest type description summary Test for the file decodestring.py Arguments: unittest type description summary Test for the file deletereoccurring.py Arguments: unittest type description summary Test for the file domainextractor.py Arguments: unittest type description summary Test for the file encodedecode.py Arguments: unittest type description summary Test for the file groupanagrams.py Arguments: unittest type description summary Test for the file inttoroman.py Arguments: unittest type description summary Test for the file ispalindrome.py Arguments: unittest type description 'Otto' is a old german name. 'Otto' is a old german name. 'Otto' is a old german name. 'Otto' is a old german name. 'Otto' is a old german name. summary Test for the file isrotated.py Arguments: unittest type description summary Test for the file licensenumber.py Arguments: unittest type description summary Test for the file makesentence.py Arguments: unittest type description summary Test for the file mergestringchecker.py Arguments: unittest type description summary Test for the file multiplystrings.py Arguments: unittest type description summary Test for the file oneeditdistance.py Arguments: unittest type description summary Test for the file rabinkarp.py Arguments: unittest type description summary Test for the file reversestring.py Arguments: unittest type description summary Test for the file reversevowel.py Arguments: unittest type description summary Test for the file reversewords.py Arguments: unittest type description summary Test for the file romantoint.py Arguments: unittest type description class TestStripUrlParamsunittest.TestCase: summary Test for the file stripurlsparams.py Arguments: unittest type description def teststripurlparams1self: self.assertEqualstripurlparams1www.saadbenn.com?a1b2a2, www.saadbenn.com?a1b2 self.assertEqualstripurlparams1www.saadbenn.com?a1b2, 'b', www.saadbenn.com?a1 def teststripurlparams2self: self.assertEqualstripurlparams2www.saadbenn.com?a1b2a2, www.saadbenn.com?a1b2 self.assertEqualstripurlparams2www.saadbenn.com?a1b2, 'b', www.saadbenn.com?a1 def teststripurlparams3self: self.assertEqualstripurlparams3www.saadbenn.com?a1b2a2, www.saadbenn.com?a1b2 self.assertEqualstripurlparams3www.saadbenn.com?a1b2, 'b', www.saadbenn.com?a1 summary Test for the file validatecoordinates.py Arguments: unittest type description summary Test for the file wordsquares.py Arguments: unittest type description Test first solution Test second solution Test third solution summary Test for the file atbashcipher.py Arguments: unittest type description summary Test for the file longestpalindromicsubstring.py Arguments: unittest type description summary Test for the file knuthmorrispratt.py Arguments: unittest type description summary Test for the file panagram.py Arguments: unittest type description Arrange Act Assert Arrange Act Assert Arrange Act Assert Arrange Act Assert Arrange Act Assert Arrange Act Assert Arrange Act Assert summary Tests for the fizzbuzz method in file fizzbuzz.py Testing that n 0 returns a Value Error Testing that a string returns a Type Error. Testing a base case, n 3 Testing a base case, n 5 Testing a base case, n 15 i.e. mod 3 and 5","Completions":"from algorithms.strings import (\n add_binary,\n match_symbol, match_symbol_1, bracket,\n decode_string,\n delete_reoccurring_characters,\n domain_name_1, domain_name_2,\n encode, decode,\n group_anagrams,\n int_to_roman,\n is_palindrome, is_palindrome_reverse,\n is_palindrome_two_pointer, is_palindrome_stack, is_palindrome_deque,\n is_rotated, is_rotated_v1,\n license_number,\n make_sentence,\n is_merge_recursive, is_merge_iterative,\n multiply,\n is_one_edit, is_one_edit2,\n rabin_karp,\n ultra_pythonic, iterative, recursive, pythonic,\n reverse_vowel,\n reverse_words,\n roman_to_int,\n is_valid_coordinates_0,\n word_squares,\n convert_morse_word, unique_morse,\n judge_circle,\n strong_password,\n caesar_cipher,\n check_pangram,\n contain_string,\n count_binary_substring,\n repeat_string,\n text_justification,\n min_distance,\n min_distance_dp,\n longest_common_prefix_v1, longest_common_prefix_v2,\n longest_common_prefix_v3,\n rotate, rotate_alt,\n first_unique_char,\n repeat_substring,\n atbash,\n longest_palindrome,\n knuth_morris_pratt,\n panagram,\n fizzbuzz\n)\n\nimport unittest\n\n\nclass TestAddBinary(unittest.TestCase):\n \"\"\"[summary]\n Test for the file add_binary.py\n\n Arguments:\n unittest {[type]} -- [description]\n \"\"\"\n\n def test_add_binary(self):\n self.assertEqual(\"100\", add_binary(\"11\", \"1\"))\n self.assertEqual(\"101\", add_binary(\"100\", \"1\"))\n self.assertEqual(\"10\", add_binary(\"1\", \"1\"))\n\n\nclass TestBreakingBad(unittest.TestCase):\n \"\"\"[summary]\n Test for the file breaking_bad.py\n\n Arguments:\n unittest {[type]} -- [description]\n \"\"\"\n\n def setUp(self):\n self.words = ['Amazon', 'Microsoft', 'Google']\n self.symbols = ['i', 'Am', 'cro', 'le', 'abc']\n self.result = ['M[i]crosoft', '[Am]azon', 'Mi[cro]soft', 'Goog[le]']\n\n def test_match_symbol(self):\n self.assertEqual(self.result, match_symbol(self.words, self.symbols))\n\n def test_match_symbol_1(self):\n self.assertEqual(['[Am]azon', 'Mi[cro]soft', 'Goog[le]'],\n match_symbol_1(self.words, self.symbols))\n\n def test_bracket(self):\n self.assertEqual(('[Am]azon', 'Mi[cro]soft', 'Goog[le]'),\n bracket(self.words, self.symbols))\n self.assertEqual(('Amazon', 'Microsoft', 'Google'),\n bracket(self.words, ['thisshouldnotmatch']))\n self.assertEqual(('Amazon', 'M[i]crosoft', 'Google'),\n bracket(self.words, ['i', 'i']))\n\n\nclass TestDecodeString(unittest.TestCase):\n \"\"\"[summary]\n Test for the file decode_string.py\n\n Arguments:\n unittest {[type]} -- [description]\n \"\"\"\n\n def test_decode_string(self):\n self.assertEqual(\"aaabcbc\", decode_string(\"3[a]2[bc]\"))\n self.assertEqual(\"accaccacc\", decode_string(\"3[a2[c]]\"))\n\n\nclass TestDeleteReoccurring(unittest.TestCase):\n \"\"\"[summary]\n Test for the file delete_reoccurring.py\n\n Arguments:\n unittest {[type]} -- [description]\n \"\"\"\n\n def test_delete_reoccurring_characters(self):\n self.assertEqual(\"abc\", delete_reoccurring_characters(\"aaabcccc\"))\n\n\nclass TestDomainExtractor(unittest.TestCase):\n \"\"\"[summary]\n Test for the file domain_extractor.py\n\n Arguments:\n unittest {[type]} -- [description]\n \"\"\"\n\n def test_valid(self):\n self.assertEqual(domain_name_1(\"https:\/\/github.com\/SaadBenn\"),\n \"github\")\n\n def test_invalid(self):\n self.assertEqual(domain_name_2(\"http:\/\/google.com\"), \"google\")\n\n\nclass TestEncodeDecode(unittest.TestCase):\n \"\"\"[summary]\n Test for the file encode_decode.py\n\n Arguments:\n unittest {[type]} -- [description]\n \"\"\"\n\n def test_encode(self):\n self.assertEqual(\"4:keon2:is7:awesome\", encode(\"keon is awesome\"))\n\n def test_decode(self):\n self.assertEqual(['keon', 'is', 'awesome'],\n decode(\"4:keon2:is7:awesome\"))\n\n\nclass TestGroupAnagrams(unittest.TestCase):\n \"\"\"[summary]\n Test for the file group_anagrams.py\n\n Arguments:\n unittest {[type]} -- [description]\n \"\"\"\n\n def test_group_anagrams(self):\n self.assertEqual([['eat', 'tea', 'ate'], ['tan', 'nat'], ['bat']], \\\n group_anagrams([\"eat\", \"tea\", \"tan\", \"ate\", \"nat\",\n \"bat\"]))\n\n\nclass TestIntToRoman(unittest.TestCase):\n \"\"\"[summary]\n Test for the file int_to_roman.py\n\n Arguments:\n unittest {[type]} -- [description]\n \"\"\"\n\n def test_int_to_roman(self):\n self.assertEqual(\"DCXLIV\", int_to_roman(644))\n self.assertEqual(\"I\", int_to_roman(1))\n self.assertEqual(\"MMMCMXCIX\", int_to_roman(3999))\n\n\nclass TestIsPalindrome(unittest.TestCase):\n \"\"\"[summary]\n Test for the file is_palindrome.py\n\n Arguments:\n unittest {[type]} -- [description]\n \"\"\"\n\n def test_is_palindrome(self):\n # 'Otto' is a old german name.\n self.assertTrue(is_palindrome(\"Otto\"))\n self.assertFalse(is_palindrome(\"house\"))\n\n def test_is_palindrome_reverse(self):\n # 'Otto' is a old german name.\n self.assertTrue(is_palindrome_reverse(\"Otto\"))\n self.assertFalse(is_palindrome_reverse(\"house\"))\n\n def test_is_palindrome_two_pointer(self):\n # 'Otto' is a old german name.\n self.assertTrue(is_palindrome_two_pointer(\"Otto\"))\n self.assertFalse(is_palindrome_two_pointer(\"house\"))\n\n def test_is_palindrome_stack(self):\n # 'Otto' is a old german name.\n self.assertTrue(is_palindrome_stack(\"Otto\"))\n self.assertFalse(is_palindrome_stack(\"house\"))\n\n def test_is_palindrome_deque(self):\n # 'Otto' is a old german name.\n self.assertTrue(is_palindrome_deque(\"Otto\"))\n self.assertFalse(is_palindrome_deque(\"house\"))\n\n\nclass TestIsRotated(unittest.TestCase):\n \"\"\"[summary]\n Test for the file is_rotated.py\n\n Arguments:\n unittest {[type]} -- [description]\n \"\"\"\n\n def test_is_rotated(self):\n self.assertTrue(is_rotated(\"hello\", \"hello\"))\n self.assertTrue(is_rotated(\"hello\", \"llohe\"))\n self.assertFalse(is_rotated(\"hello\", \"helol\"))\n self.assertFalse(is_rotated(\"hello\", \"lloh\"))\n self.assertTrue(is_rotated(\"\", \"\"))\n\n def test_is_rotated_v1(self):\n self.assertTrue(is_rotated_v1(\"hello\", \"hello\"))\n self.assertTrue(is_rotated_v1(\"hello\", \"llohe\"))\n self.assertFalse(is_rotated_v1(\"hello\", \"helol\"))\n self.assertFalse(is_rotated_v1(\"hello\", \"lloh\"))\n self.assertTrue(is_rotated_v1(\"\", \"\"))\n\n\nclass TestRotated(unittest.TestCase):\n def test_rotate(self):\n self.assertEqual(\"llohe\", rotate(\"hello\", 2))\n self.assertEqual(\"hello\", rotate(\"hello\", 5))\n self.assertEqual(\"elloh\", rotate(\"hello\", 6))\n self.assertEqual(\"llohe\", rotate(\"hello\", 7))\n\n def test_rotate_alt(self):\n self.assertEqual(\"llohe\", rotate_alt(\"hello\", 2))\n self.assertEqual(\"hello\", rotate_alt(\"hello\", 5))\n self.assertEqual(\"elloh\", rotate_alt(\"hello\", 6))\n self.assertEqual(\"llohe\", rotate_alt(\"hello\", 7))\n\n\nclass TestLicenseNumber(unittest.TestCase):\n \"\"\"[summary]\n Test for the file license_number.py\n\n Arguments:\n unittest {[type]} -- [description]\n \"\"\"\n\n def test_license_number(self):\n self.assertEqual(\"a-b-c-d-f-d-d-f\", license_number(\"a-bc-dfd-df\", 1))\n self.assertEqual(\"ab-cd-fd-df\", license_number(\"a-bc-dfd-df\", 2))\n self.assertEqual(\"ab-cdf-ddf\", license_number(\"a-bc-dfd-df\", 3))\n self.assertEqual(\"abcd-fddf\", license_number(\"a-bc-dfd-df\", 4))\n self.assertEqual(\"abc-dfddf\", license_number(\"a-bc-dfd-df\", 5))\n\n\nclass TestMakeSentence(unittest.TestCase):\n \"\"\"[summary]\n Test for the file make_sentence.py\n\n Arguments:\n unittest {[type]} -- [description]\n \"\"\"\n\n def test_make_sentence(self):\n dictionarys = [\"\", \"app\", \"let\", \"t\", \"apple\", \"applet\"]\n word = \"applet\"\n self.assertTrue(make_sentence(word, dictionarys))\n\n\nclass TestMergeStringChecker(unittest.TestCase):\n \"\"\"[summary]\n Test for the file merge_string_checker.py\n\n Arguments:\n unittest {[type]} -- [description]\n \"\"\"\n\n def test_is_merge_recursive(self):\n self.assertTrue(is_merge_recursive(\"codewars\", \"cdw\", \"oears\"))\n\n def test_is_merge_iterative(self):\n self.assertTrue(is_merge_iterative(\"codewars\", \"cdw\", \"oears\"))\n\n\nclass TestMultiplyStrings(unittest.TestCase):\n \"\"\"[summary]\n Test for the file multiply_strings.py\n\n Arguments:\n unittest {[type]} -- [description]\n \"\"\"\n\n def test_multiply(self):\n self.assertEqual(\"23\", multiply(\"1\", \"23\"))\n self.assertEqual(\"529\", multiply(\"23\", \"23\"))\n self.assertEqual(\"0\", multiply(\"0\", \"23\"))\n self.assertEqual(\"1000000\", multiply(\"100\", \"10000\"))\n\n\nclass TestOneEditDistance(unittest.TestCase):\n \"\"\"[summary]\n Test for the file one_edit_distance.py\n\n Arguments:\n unittest {[type]} -- [description]\n \"\"\"\n\n def test_is_one_edit(self):\n self.assertTrue(is_one_edit(\"abc\", \"abd\"))\n self.assertFalse(is_one_edit(\"abc\", \"aed\"))\n self.assertFalse(is_one_edit(\"abcd\", \"abcd\"))\n\n def test_is_one_edit2(self):\n self.assertTrue(is_one_edit2(\"abc\", \"abd\"))\n self.assertFalse(is_one_edit2(\"abc\", \"aed\"))\n self.assertFalse(is_one_edit2(\"abcd\", \"abcd\"))\n\n\nclass TestRabinKarp(unittest.TestCase):\n \"\"\"[summary]\n Test for the file rabin_karp.py\n\n Arguments:\n unittest {[type]} -- [description]\n \"\"\"\n\n def test_rabin_karp(self):\n self.assertEqual(3, rabin_karp(\"abc\", \"zsnabckfkd\"))\n self.assertEqual(None, rabin_karp(\"abc\", \"zsnajkskfkd\"))\n\n\nclass TestReverseString(unittest.TestCase):\n \"\"\"[summary]\n Test for the file reverse_string.py\n\n Arguments:\n unittest {[type]} -- [description]\n \"\"\"\n\n def test_recursive(self):\n self.assertEqual(\"ereht olleh\", recursive(\"hello there\"))\n\n def test_iterative(self):\n self.assertEqual(\"ereht olleh\", iterative(\"hello there\"))\n\n def test_pythonic(self):\n self.assertEqual(\"ereht olleh\", pythonic(\"hello there\"))\n\n def test_ultra_pythonic(self):\n self.assertEqual(\"ereht olleh\", ultra_pythonic(\"hello there\"))\n\n\nclass TestReverseVowel(unittest.TestCase):\n \"\"\"[summary]\n Test for the file reverse_vowel.py\n\n Arguments:\n unittest {[type]} -- [description]\n \"\"\"\n\n def test_reverse_vowel(self):\n self.assertEqual(\"holle\", reverse_vowel(\"hello\"))\n\n\nclass TestReverseWords(unittest.TestCase):\n \"\"\"[summary]\n Test for the file reverse_words.py\n\n Arguments:\n unittest {[type]} -- [description]\n \"\"\"\n\n def test_reverse_words(self):\n self.assertEqual(\"pizza like I and kim keon am I\", \\\n reverse_words(\"I am keon kim and I like pizza\"))\n\n\nclass TestRomanToInt(unittest.TestCase):\n \"\"\"[summary]\n Test for the file roman_to_int.py\n\n Arguments:\n unittest {[type]} -- [description]\n \"\"\"\n\n def test_roman_to_int(self):\n self.assertEqual(621, roman_to_int(\"DCXXI\"))\n self.assertEqual(1, roman_to_int(\"I\"))\n self.assertEqual(3999, roman_to_int(\"MMMCMXCIX\"))\n\n\n# class TestStripUrlParams(unittest.TestCase):\n# \"\"\"[summary]\n# Test for the file strip_urls_params.py\n\n# Arguments:\n# unittest {[type]} -- [description]\n# \"\"\"\n\n# def test_strip_url_params1(self):\n# self.assertEqual(strip_url_params1(\"www.saadbenn.com?a=1&b=2&a=2\"),\n# \"www.saadbenn.com?a=1&b=2\")\n# self.assertEqual(strip_url_params1(\"www.saadbenn.com?a=1&b=2\",\n# ['b']), \"www.saadbenn.com?a=1\")\n# def test_strip_url_params2(self):\n# self.assertEqual(strip_url_params2(\"www.saadbenn.com?a=1&b=2&a=2\"),\n# \"www.saadbenn.com?a=1&b=2\")\n# self.assertEqual(strip_url_params2(\"www.saadbenn.com?a=1&b=2\",\n# 'b']), \"www.saadbenn.com?a=1\")\n# def test_strip_url_params3(self):\n# self.assertEqual(strip_url_params3(\"www.saadbenn.com?a=1&b=2&a=2\"),\n# \"www.saadbenn.com?a=1&b=2\")\n# self.assertEqual(strip_url_params3(\"www.saadbenn.com?a=1&b=2\",\n# ['b']), \"www.saadbenn.com?a=1\")\n\n\nclass TestValidateCoordinates(unittest.TestCase):\n \"\"\"[summary]\n Test for the file validate_coordinates.py\n\n Arguments:\n unittest {[type]} -- [description]\n \"\"\"\n\n def test_valid(self):\n valid_coordinates = [\"-23, 25\", \"4, -3\", \"90, 180\", \"-90, -180\"]\n for coordinate in valid_coordinates:\n self.assertTrue(is_valid_coordinates_0(coordinate))\n\n def test_invalid(self):\n invalid_coordinates = [\"23.234, - 23.4234\", \"99.234, 12.324\",\n \"6.325624, 43.34345.345\", \"0, 1,2\",\n \"23.245, 1e1\"]\n for coordinate in invalid_coordinates:\n self.assertFalse(is_valid_coordinates_0(coordinate))\n\n\nclass TestWordSquares(unittest.TestCase):\n \"\"\"[summary]\n Test for the file word_squares.py\n\n Arguments:\n unittest {[type]} -- [description]\n \"\"\"\n\n def test_word_squares(self):\n self.assertEqual([['wall', 'area', 'lead', 'lady'], ['ball', 'area',\n 'lead', 'lady']], \\\n word_squares([\"area\", \"lead\", \"wall\",\n \"lady\", \"ball\"]))\n\n\nclass TestUniqueMorse(unittest.TestCase):\n def test_convert_morse_word(self):\n self.assertEqual(\"--...-.\", convert_morse_word(\"gin\"))\n self.assertEqual(\"--...--.\", convert_morse_word(\"msg\"))\n\n def test_unique_morse(self):\n self.assertEqual(2, unique_morse([\"gin\", \"zen\", \"gig\", \"msg\"]))\n\n\nclass TestJudgeCircle(unittest.TestCase):\n def test_judge_circle(self):\n self.assertTrue(judge_circle(\"UDLRUD\"))\n self.assertFalse(judge_circle(\"LLRU\"))\n\n\nclass TestStrongPassword(unittest.TestCase):\n def test_strong_password(self):\n self.assertEqual(3, strong_password(3, \"Ab1\"))\n self.assertEqual(1, strong_password(11, \"#Algorithms\"))\n\n\nclass TestCaesarCipher(unittest.TestCase):\n def test_caesar_cipher(self):\n self.assertEqual(\"Lipps_Asvph!\", caesar_cipher(\"Hello_World!\", 4))\n self.assertEqual(\"okffng-Qwvb\", caesar_cipher(\"middle-Outz\", 2))\n\n\nclass TestCheckPangram(unittest.TestCase):\n def test_check_pangram(self):\n self.assertTrue(check_pangram(\"The quick brown fox jumps over the lazy dog\"))\n self.assertFalse(check_pangram(\"The quick brown fox\"))\n\n\nclass TestContainString(unittest.TestCase):\n def test_contain_string(self):\n self.assertEqual(-1, contain_string(\"mississippi\", \"issipi\"))\n self.assertEqual(0, contain_string(\"Hello World\", \"\"))\n self.assertEqual(2, contain_string(\"hello\", \"ll\"))\n\n\nclass TestCountBinarySubstring(unittest.TestCase):\n def test_count_binary_substring(self):\n self.assertEqual(6, count_binary_substring(\"00110011\"))\n self.assertEqual(4, count_binary_substring(\"10101\"))\n self.assertEqual(3, count_binary_substring(\"00110\"))\n\n\nclass TestCountBinarySubstring(unittest.TestCase):\n def test_repeat_string(self):\n self.assertEqual(3, repeat_string(\"abcd\", \"cdabcdab\"))\n self.assertEqual(4, repeat_string(\"bb\", \"bbbbbbb\"))\n\n\nclass TestTextJustification(unittest.TestCase):\n def test_text_justification(self):\n self.assertEqual([\"This is an\",\n \"example of text\",\n \"justification. \"],\n text_justification([\"This\", \"is\", \"an\", \"example\",\n \"of\", \"text\",\n \"justification.\"], 16)\n )\n\n self.assertEqual([\"What must be\",\n \"acknowledgment \",\n \"shall be \"],\n text_justification([\"What\", \"must\", \"be\",\n \"acknowledgment\", \"shall\",\n \"be\"], 16)\n )\n\n\nclass TestMinDistance(unittest.TestCase):\n def test_min_distance(self):\n self.assertEqual(2, min_distance(\"sea\", \"eat\"))\n self.assertEqual(6, min_distance(\"abAlgocrithmf\", \"Algorithmmd\"))\n self.assertEqual(4, min_distance(\"acbbd\", \"aabcd\"))\n\nclass TestMinDistanceDP(unittest.TestCase):\n def test_min_distance(self):\n self.assertEqual(2, min_distance_dp(\"sea\", \"eat\"))\n self.assertEqual(6, min_distance_dp(\"abAlgocrithmf\", \"Algorithmmd\"))\n self.assertEqual(4, min_distance(\"acbbd\", \"aabcd\"))\n\n\nclass TestLongestCommonPrefix(unittest.TestCase):\n def test_longest_common_prefix(self):\n # Test first solution\n self.assertEqual(\"fl\", longest_common_prefix_v1([\"flower\", \"flow\",\n \"flight\"]))\n self.assertEqual(\"\", longest_common_prefix_v1([\"dog\", \"racecar\",\n \"car\"]))\n # Test second solution\n self.assertEqual(\"fl\", longest_common_prefix_v2([\"flower\", \"flow\",\n \"flight\"]))\n self.assertEqual(\"\", longest_common_prefix_v2([\"dog\", \"racecar\",\n \"car\"]))\n # Test third solution\n self.assertEqual(\"fl\", longest_common_prefix_v3([\"flower\", \"flow\",\n \"flight\"]))\n self.assertEqual(\"\", longest_common_prefix_v3([\"dog\", \"racecar\",\n \"car\"]))\n\n\nclass TestFirstUniqueChar(unittest.TestCase):\n def test_first_unique_char(self):\n self.assertEqual(0, first_unique_char(\"leetcode\"))\n self.assertEqual(2, first_unique_char(\"loveleetcode\"))\n\n\nclass TestRepeatSubstring(unittest.TestCase):\n def test_repeat_substring(self):\n self.assertTrue(repeat_substring(\"abab\"))\n self.assertFalse(repeat_substring(\"aba\"))\n self.assertTrue(repeat_substring(\"abcabcabcabc\"))\n\n\nclass TestAtbashCipher(unittest.TestCase):\n \"\"\"[summary]\n Test for the file atbash_cipher.py\n\n Arguments:\n unittest {[type]} -- [description]\n \"\"\"\n\n def test_atbash_cipher(self):\n self.assertEqual(\"zyxwvutsrqponml\", atbash(\"abcdefghijklmno\"))\n self.assertEqual(\"KbgslM\", atbash(\"PythoN\"))\n self.assertEqual(\"AttaCK at DawN\", atbash(\"ZggzXP zg WzdM\"))\n self.assertEqual(\"ZggzXP zg WzdM\", atbash(\"AttaCK at DawN\"))\n\n\nclass TestLongestPalindromicSubstring(unittest.TestCase):\n \"\"\"[summary]\n Test for the file longest_palindromic_substring.py\n Arguments:\n unittest {[type]} -- [description]\n \"\"\"\n def test_longest_palindromic_substring(self):\n self.assertEqual(\"bb\", longest_palindrome(\"cbbd\"))\n self.assertEqual(\"abba\", longest_palindrome(\"abba\"))\n self.assertEqual(\"asdadsa\", longest_palindrome(\"dasdasdasdasdasdadsa\"))\n self.assertEqual(\"abba\", longest_palindrome(\"cabba\"))\n\n\nclass TestKnuthMorrisPratt(unittest.TestCase):\n \"\"\"[summary]\n Test for the file knuth_morris_pratt.py\n\n\n Arguments:\n unittest {[type]} -- [description]\n \"\"\"\n\n def test_knuth_morris_pratt(self):\n self.assertEqual([0, 1, 2, 3, 4], knuth_morris_pratt(\"aaaaaaa\", \"aaa\"))\n self.assertEqual([0, 4], knuth_morris_pratt(\"abcdabc\", \"abc\"))\n self.assertEqual([], knuth_morris_pratt(\"aabcdaab\", \"aba\"))\n self.assertEqual([0, 4], knuth_morris_pratt([0,0,1,1,0,0,1,0], [0,0]))\n\n\nclass TestPanagram(unittest.TestCase):\n \"\"\"[summary]\n Test for the file panagram.py\n\n Arguments:\n unittest {[type]} -- [description]\n \"\"\"\n\n def test_empty_string(self):\n # Arrange\n string = \"\"\n\n # Act\n res = panagram(string)\n\n # Assert\n self.assertEqual(False, res)\n\n def test_single_word_non_panagram(self):\n # Arrange\n string = \"sentence\"\n\n # Act\n res = panagram(string)\n\n # Assert\n self.assertEqual(False, res)\n\n def test_fox_panagram_no_spaces(self):\n # Arrange\n string = \"thequickbrownfoxjumpsoverthelazydog\"\n\n # Act\n res = panagram(string)\n\n # Assert\n self.assertEqual(True, res)\n\n def test_fox_panagram_mixed_case(self):\n # Arrange\n string = \"theqUiCkbrOwnfOxjUMPSOVErThELAzYDog\"\n\n # Act\n res = panagram(string)\n\n # Assert\n self.assertEqual(True, res)\n\n def test_whitespace_punctuation(self):\n # Arrange\n string = \"\\n\\t\\r,.-_!?\"\n\n # Act\n res = panagram(string)\n\n # Assert\n self.assertEqual(False, res)\n\n def test_fox_panagram(self):\n # Arrange\n string = \"the quick brown fox jumps over the lazy dog\"\n\n # Act\n res = panagram(string)\n\n # Assert\n self.assertEqual(True, res)\n\n def test_swedish_panagram(self):\n # Arrange\n string = \"Yxm\u00f6rdaren Julia Blomqvist p\u00e5 f\u00e4ktning i Schweiz\"\n\n # Act\n res = panagram(string)\n\n # Assert\n self.assertEqual(True, res)\n\n\nclass TestFizzbuzz(unittest.TestCase):\n \"\"\"[summary]\n Tests for the fizzbuzz method in file fizzbuzz.py\n \"\"\"\n def test_fizzbuzz(self):\n # Testing that n < 0 returns a Value Error\n self.assertRaises(ValueError, fizzbuzz.fizzbuzz, -2)\n\n # Testing that a string returns a Type Error.\n self.assertRaises(TypeError, fizzbuzz.fizzbuzz, \"hello\")\n\n # Testing a base case, n = 3\n result = fizzbuzz.fizzbuzz(3)\n expected = [1, 2, \"Fizz\"]\n self.assertEqual(result, expected)\n\n # Testing a base case, n = 5\n result = fizzbuzz.fizzbuzz(5)\n expected = [1, 2, \"Fizz\", 4, \"Buzz\"]\n self.assertEqual(result, expected)\n\n # Testing a base case, n = 15 i.e. mod 3 and 5\n result = fizzbuzz.fizzbuzz(15)\n expected = [1, 2, \"Fizz\", 4, \"Buzz\", \"Fizz\", 7, 8, \"Fizz\", \"Buzz\", 11,\n \"Fizz\", 13, 14, \"FizzBuzz\"]\n self.assertEqual(result, expected)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n"} +{"Prompt":"Test 1 Test 2 Test 3","Completions":"from algorithms.tree.traversal import (\n preorder,\n preorder_rec,\n postorder,\n postorder_rec,\n inorder,\n inorder_rec\n)\nfrom algorithms.tree.b_tree import BTree\n\nfrom algorithms.tree import construct_tree_postorder_preorder as ctpp\n\nfrom algorithms.tree.fenwick_tree.fenwick_tree import Fenwick_Tree\n\nimport unittest\n\n\nclass Node:\n\n def __init__(self, val, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\n\nclass TestTraversal(unittest.TestCase):\n\n def test_preorder(self):\n tree = create_tree()\n self.assertEqual([100, 50, 25, 75, 150, 125, 175], preorder(tree))\n self.assertEqual([100, 50, 25, 75, 150, 125, 175], preorder_rec(tree))\n\n def test_postorder(self):\n tree = create_tree()\n self.assertEqual([25, 75, 50, 125, 175, 150, 100], postorder(tree))\n self.assertEqual([25, 75, 50, 125, 175, 150, 100], postorder_rec(tree))\n\n def test_inorder(self):\n tree = create_tree()\n self.assertEqual([25, 50, 75, 100, 125, 150, 175], inorder(tree))\n self.assertEqual([25, 50, 75, 100, 125, 150, 175], inorder_rec(tree))\n\n\ndef create_tree():\n n1 = Node(100)\n n2 = Node(50)\n n3 = Node(150)\n n4 = Node(25)\n n5 = Node(75)\n n6 = Node(125)\n n7 = Node(175)\n n1.left, n1.right = n2, n3\n n2.left, n2.right = n4, n5\n n3.left, n3.right = n6, n7\n return n1\n\n\nclass TestBTree(unittest.TestCase):\n\n @classmethod\n def setUpClass(cls):\n import random\n random.seed(18719)\n cls.random = random\n cls.range = 10000\n\n def setUp(self):\n self.keys_to_insert = [self.random.randrange(-self.range, self.range)\n for i in range(self.range)]\n\n def test_insertion_and_find_even_degree(self):\n btree = BTree(4)\n for i in self.keys_to_insert:\n btree.insert_key(i)\n\n for i in range(100):\n key = self.random.choice(self.keys_to_insert)\n self.assertTrue(btree.find(key))\n\n def test_insertion_and_find_odd_degree(self):\n btree = BTree(3)\n for i in self.keys_to_insert:\n btree.insert_key(i)\n\n for i in range(100):\n key = self.random.choice(self.keys_to_insert)\n self.assertTrue(btree.find(key))\n\n def test_deletion_even_degree(self):\n btree = BTree(4)\n key_list = set(self.keys_to_insert)\n for i in key_list:\n btree.insert_key(i)\n\n for key in key_list:\n btree.remove_key(key)\n self.assertFalse(btree.find(key))\n\n self.assertEqual(btree.root.keys, [])\n self.assertEqual(btree.root.children, [])\n\n def test_deletion_odd_degree(self):\n btree = BTree(3)\n key_list = set(self.keys_to_insert)\n for i in key_list:\n btree.insert_key(i)\n\n for key in key_list:\n btree.remove_key(key)\n self.assertFalse(btree.find(key))\n\n self.assertEqual(btree.root.keys, [])\n self.assertEqual(btree.root.children, [])\n\n\nclass TestConstructTreePreorderPostorder(unittest.TestCase):\n def test_construct_tree(self):\n\n # Test 1\n ctpp.pre_index = 0\n pre1 = [1, 2, 4, 8, 9, 5, 3, 6, 7]\n post1 = [8, 9, 4, 5, 2, 6, 7, 3, 1]\n size1 = len(pre1)\n\n self.assertEqual(ctpp.construct_tree(pre1, post1, size1),\n [8, 4, 9, 2, 5, 1, 6, 3, 7])\n\n # Test 2\n ctpp.pre_index = 0\n pre2 = [1, 2, 4, 5, 3, 6, 7]\n post2 = [4, 5, 2, 6, 7, 3, 1]\n size2 = len(pre2)\n\n self.assertEqual(ctpp.construct_tree(pre2, post2, size2),\n [4, 2, 5, 1, 6, 3, 7])\n\n # Test 3\n ctpp.pre_index = 0\n pre3 = [12, 7, 16, 21, 5, 1, 9]\n post3 = [16, 21, 7, 1, 9, 5, 12]\n size3 = len(pre3)\n\n self.assertEqual(ctpp.construct_tree(pre3, post3, size3),\n [16, 7, 21, 12, 1, 5, 9])\n\n\nclass TestFenwickTree(unittest.TestCase):\n def test_construct_tree_with_update_1(self):\n freq = [2, 1, 1, 3, 2, 3, 4, 5, 6, 7, 8, 9]\n ft = Fenwick_Tree(freq)\n bit_tree = ft.construct()\n self.assertEqual(12, ft.get_sum(bit_tree, 5))\n\n freq[3] += 6\n ft.update_bit(bit_tree, 3, 6)\n self.assertEqual(18, ft.get_sum(bit_tree, 5))\n\n def test_construct_tree_with_update_2(self):\n freq = [1, 2, 3, 4, 5]\n ft = Fenwick_Tree(freq)\n bit_tree = ft.construct()\n self.assertEqual(10, ft.get_sum(bit_tree, 3))\n\n freq[3] -= 5\n ft.update_bit(bit_tree, 3, -5)\n self.assertEqual(5, ft.get_sum(bit_tree, 3))\n\n def test_construct_tree_with_update_3(self):\n freq = [2, 1, 4, 6, -1, 5, -32, 0, 1]\n ft = Fenwick_Tree(freq)\n bit_tree = ft.construct()\n self.assertEqual(12, ft.get_sum(bit_tree, 4))\n\n freq[2] += 11\n ft.update_bit(bit_tree, 2, 11)\n self.assertEqual(23, ft.get_sum(bit_tree, 4))\n\n\nif __name__ == '__main__':\n unittest.main()\n"} +{"Prompt":"Test full path relative Test full path with expanding user filename Test url path Test file path","Completions":"from algorithms.unix import (\n join_with_slash,\n full_path,\n split,\n simplify_path_v1, simplify_path_v2\n)\nimport os\nimport unittest\n\n\nclass TestUnixPath(unittest.TestCase):\n def test_join_with_slash(self):\n self.assertEqual(\"path\/to\/dir\/file\",\n join_with_slash(\"path\/to\/dir\/\", \"file\"))\n self.assertEqual(\"path\/to\/dir\/file\",\n join_with_slash(\"path\/to\/dir\", \"file\"))\n self.assertEqual(\"http:\/\/algorithms\/part\",\n join_with_slash(\"http:\/\/algorithms\", \"part\"))\n self.assertEqual(\"http:\/\/algorithms\/part\",\n join_with_slash(\"http:\/\/algorithms\/\", \"part\"))\n\n def test_full_path(self):\n file_name = \"file_name\"\n # Test full path relative\n expect_path = \"{}\/{}\".format(os.getcwd(), file_name)\n self.assertEqual(expect_path, full_path(file_name))\n # Test full path with expanding user\n # ~\/file_name\n expect_path = \"{}\/{}\".format(os.path.expanduser('~'), file_name)\n self.assertEqual(expect_path, full_path(\"~\/{}\".format(file_name)))\n\n def test_split(self):\n # Test url path\n path = \"https:\/\/algorithms\/unix\/test.py\"\n expect_result = split(path)\n self.assertEqual(\"https:\/\/algorithms\/unix\", expect_result[0])\n self.assertEqual(\"test.py\", expect_result[1])\n # Test file path\n path = \"algorithms\/unix\/test.py\"\n expect_result = split(path)\n self.assertEqual(\"algorithms\/unix\", expect_result[0])\n self.assertEqual(\"test.py\", expect_result[1])\n\n def test_simplify_path(self):\n self.assertEqual(\"\/\", simplify_path_v1(\"\/..\/\"))\n self.assertEqual(\"\/home\/foo\", simplify_path_v1(\"\/home\/\/foo\/\"))\n self.assertEqual(\"\/\", simplify_path_v2(\"\/..\/\"))\n self.assertEqual(\"\/home\/foo\", simplify_path_v2(\"\/home\/\/foo\/\"))\n"} +{"Prompt":"Create 2ndorder IIR filters with Butterworth design. Code based on https:webaudio.github.ioAudioEQCookbookaudioeqcookbook.html Alternatively you can use scipy.signal.butter, which should yield the same results. Creates a lowpass filter filter makelowpass1000, 48000 filter.acoeffs filter.bcoeffs doctest: NORMALIZEWHITESPACE 1.0922959556412573, 1.9828897227476208, 0.9077040443587427, 0.004277569313094809, 0.008555138626189618, 0.004277569313094809 Creates a highpass filter filter makehighpass1000, 48000 filter.acoeffs filter.bcoeffs doctest: NORMALIZEWHITESPACE 1.0922959556412573, 1.9828897227476208, 0.9077040443587427, 0.9957224306869052, 1.9914448613738105, 0.9957224306869052 Creates a bandpass filter filter makebandpass1000, 48000 filter.acoeffs filter.bcoeffs doctest: NORMALIZEWHITESPACE 1.0922959556412573, 1.9828897227476208, 0.9077040443587427, 0.06526309611002579, 0, 0.06526309611002579 Creates an allpass filter filter makeallpass1000, 48000 filter.acoeffs filter.bcoeffs doctest: NORMALIZEWHITESPACE 1.0922959556412573, 1.9828897227476208, 0.9077040443587427, 0.9077040443587427, 1.9828897227476208, 1.0922959556412573 Creates a peak filter filter makepeak1000, 48000, 6 filter.acoeffs filter.bcoeffs doctest: NORMALIZEWHITESPACE 1.0653405327119334, 1.9828897227476208, 0.9346594672880666, 1.1303715025601122, 1.9828897227476208, 0.8696284974398878 Creates a lowshelf filter filter makelowshelf1000, 48000, 6 filter.acoeffs filter.bcoeffs doctest: NORMALIZEWHITESPACE 3.0409336710888786, 5.608870992220748, 2.602157875636628, 3.139954022810743, 5.591841778072785, 2.5201667380627257 Creates a highshelf filter filter makehighshelf1000, 48000, 6 filter.acoeffs filter.bcoeffs doctest: NORMALIZEWHITESPACE 2.2229172136088806, 3.9587208137297303, 1.7841414181566304, 4.295432981120543, 7.922740859457287, 3.6756456963725253","Completions":"from math import cos, sin, sqrt, tau\n\nfrom audio_filters.iir_filter import IIRFilter\n\n\"\"\"\nCreate 2nd-order IIR filters with Butterworth design.\n\nCode based on https:\/\/webaudio.github.io\/Audio-EQ-Cookbook\/audio-eq-cookbook.html\nAlternatively you can use scipy.signal.butter, which should yield the same results.\n\"\"\"\n\n\ndef make_lowpass(\n frequency: int, samplerate: int, q_factor: float = 1 \/ sqrt(2) # noqa: B008\n) -> IIRFilter:\n \"\"\"\n Creates a low-pass filter\n\n >>> filter = make_lowpass(1000, 48000)\n >>> filter.a_coeffs + filter.b_coeffs # doctest: +NORMALIZE_WHITESPACE\n [1.0922959556412573, -1.9828897227476208, 0.9077040443587427, 0.004277569313094809,\n 0.008555138626189618, 0.004277569313094809]\n \"\"\"\n w0 = tau * frequency \/ samplerate\n _sin = sin(w0)\n _cos = cos(w0)\n alpha = _sin \/ (2 * q_factor)\n\n b0 = (1 - _cos) \/ 2\n b1 = 1 - _cos\n\n a0 = 1 + alpha\n a1 = -2 * _cos\n a2 = 1 - alpha\n\n filt = IIRFilter(2)\n filt.set_coefficients([a0, a1, a2], [b0, b1, b0])\n return filt\n\n\ndef make_highpass(\n frequency: int, samplerate: int, q_factor: float = 1 \/ sqrt(2) # noqa: B008\n) -> IIRFilter:\n \"\"\"\n Creates a high-pass filter\n\n >>> filter = make_highpass(1000, 48000)\n >>> filter.a_coeffs + filter.b_coeffs # doctest: +NORMALIZE_WHITESPACE\n [1.0922959556412573, -1.9828897227476208, 0.9077040443587427, 0.9957224306869052,\n -1.9914448613738105, 0.9957224306869052]\n \"\"\"\n w0 = tau * frequency \/ samplerate\n _sin = sin(w0)\n _cos = cos(w0)\n alpha = _sin \/ (2 * q_factor)\n\n b0 = (1 + _cos) \/ 2\n b1 = -1 - _cos\n\n a0 = 1 + alpha\n a1 = -2 * _cos\n a2 = 1 - alpha\n\n filt = IIRFilter(2)\n filt.set_coefficients([a0, a1, a2], [b0, b1, b0])\n return filt\n\n\ndef make_bandpass(\n frequency: int, samplerate: int, q_factor: float = 1 \/ sqrt(2) # noqa: B008\n) -> IIRFilter:\n \"\"\"\n Creates a band-pass filter\n\n >>> filter = make_bandpass(1000, 48000)\n >>> filter.a_coeffs + filter.b_coeffs # doctest: +NORMALIZE_WHITESPACE\n [1.0922959556412573, -1.9828897227476208, 0.9077040443587427, 0.06526309611002579,\n 0, -0.06526309611002579]\n \"\"\"\n w0 = tau * frequency \/ samplerate\n _sin = sin(w0)\n _cos = cos(w0)\n alpha = _sin \/ (2 * q_factor)\n\n b0 = _sin \/ 2\n b1 = 0\n b2 = -b0\n\n a0 = 1 + alpha\n a1 = -2 * _cos\n a2 = 1 - alpha\n\n filt = IIRFilter(2)\n filt.set_coefficients([a0, a1, a2], [b0, b1, b2])\n return filt\n\n\ndef make_allpass(\n frequency: int, samplerate: int, q_factor: float = 1 \/ sqrt(2) # noqa: B008\n) -> IIRFilter:\n \"\"\"\n Creates an all-pass filter\n\n >>> filter = make_allpass(1000, 48000)\n >>> filter.a_coeffs + filter.b_coeffs # doctest: +NORMALIZE_WHITESPACE\n [1.0922959556412573, -1.9828897227476208, 0.9077040443587427, 0.9077040443587427,\n -1.9828897227476208, 1.0922959556412573]\n \"\"\"\n w0 = tau * frequency \/ samplerate\n _sin = sin(w0)\n _cos = cos(w0)\n alpha = _sin \/ (2 * q_factor)\n\n b0 = 1 - alpha\n b1 = -2 * _cos\n b2 = 1 + alpha\n\n filt = IIRFilter(2)\n filt.set_coefficients([b2, b1, b0], [b0, b1, b2])\n return filt\n\n\ndef make_peak(\n frequency: int,\n samplerate: int,\n gain_db: float,\n q_factor: float = 1 \/ sqrt(2), # noqa: B008\n) -> IIRFilter:\n \"\"\"\n Creates a peak filter\n\n >>> filter = make_peak(1000, 48000, 6)\n >>> filter.a_coeffs + filter.b_coeffs # doctest: +NORMALIZE_WHITESPACE\n [1.0653405327119334, -1.9828897227476208, 0.9346594672880666, 1.1303715025601122,\n -1.9828897227476208, 0.8696284974398878]\n \"\"\"\n w0 = tau * frequency \/ samplerate\n _sin = sin(w0)\n _cos = cos(w0)\n alpha = _sin \/ (2 * q_factor)\n big_a = 10 ** (gain_db \/ 40)\n\n b0 = 1 + alpha * big_a\n b1 = -2 * _cos\n b2 = 1 - alpha * big_a\n a0 = 1 + alpha \/ big_a\n a1 = -2 * _cos\n a2 = 1 - alpha \/ big_a\n\n filt = IIRFilter(2)\n filt.set_coefficients([a0, a1, a2], [b0, b1, b2])\n return filt\n\n\ndef make_lowshelf(\n frequency: int,\n samplerate: int,\n gain_db: float,\n q_factor: float = 1 \/ sqrt(2), # noqa: B008\n) -> IIRFilter:\n \"\"\"\n Creates a low-shelf filter\n\n >>> filter = make_lowshelf(1000, 48000, 6)\n >>> filter.a_coeffs + filter.b_coeffs # doctest: +NORMALIZE_WHITESPACE\n [3.0409336710888786, -5.608870992220748, 2.602157875636628, 3.139954022810743,\n -5.591841778072785, 2.5201667380627257]\n \"\"\"\n w0 = tau * frequency \/ samplerate\n _sin = sin(w0)\n _cos = cos(w0)\n alpha = _sin \/ (2 * q_factor)\n big_a = 10 ** (gain_db \/ 40)\n pmc = (big_a + 1) - (big_a - 1) * _cos\n ppmc = (big_a + 1) + (big_a - 1) * _cos\n mpc = (big_a - 1) - (big_a + 1) * _cos\n pmpc = (big_a - 1) + (big_a + 1) * _cos\n aa2 = 2 * sqrt(big_a) * alpha\n\n b0 = big_a * (pmc + aa2)\n b1 = 2 * big_a * mpc\n b2 = big_a * (pmc - aa2)\n a0 = ppmc + aa2\n a1 = -2 * pmpc\n a2 = ppmc - aa2\n\n filt = IIRFilter(2)\n filt.set_coefficients([a0, a1, a2], [b0, b1, b2])\n return filt\n\n\ndef make_highshelf(\n frequency: int,\n samplerate: int,\n gain_db: float,\n q_factor: float = 1 \/ sqrt(2), # noqa: B008\n) -> IIRFilter:\n \"\"\"\n Creates a high-shelf filter\n\n >>> filter = make_highshelf(1000, 48000, 6)\n >>> filter.a_coeffs + filter.b_coeffs # doctest: +NORMALIZE_WHITESPACE\n [2.2229172136088806, -3.9587208137297303, 1.7841414181566304, 4.295432981120543,\n -7.922740859457287, 3.6756456963725253]\n \"\"\"\n w0 = tau * frequency \/ samplerate\n _sin = sin(w0)\n _cos = cos(w0)\n alpha = _sin \/ (2 * q_factor)\n big_a = 10 ** (gain_db \/ 40)\n pmc = (big_a + 1) - (big_a - 1) * _cos\n ppmc = (big_a + 1) + (big_a - 1) * _cos\n mpc = (big_a - 1) - (big_a + 1) * _cos\n pmpc = (big_a - 1) + (big_a + 1) * _cos\n aa2 = 2 * sqrt(big_a) * alpha\n\n b0 = big_a * (ppmc + aa2)\n b1 = -2 * big_a * pmpc\n b2 = big_a * (ppmc - aa2)\n a0 = pmc + aa2\n a1 = 2 * mpc\n a2 = pmc - aa2\n\n filt = IIRFilter(2)\n filt.set_coefficients([a0, a1, a2], [b0, b1, b2])\n return filt\n"} +{"Prompt":"def initself, order: int None: self.order order a0 ... ak self.acoeffs 1.0 0.0 order b0 ... bk self.bcoeffs 1.0 0.0 order xn1 ... xnk self.inputhistory 0.0 self.order yn1 ... ynk self.outputhistory 0.0 self.order def setcoefficientsself, acoeffs: listfloat, bcoeffs: listfloat None: if lenacoeffs self.order: acoeffs 1.0, acoeffs if lenacoeffs ! self.order 1: msg fExpected acoeffs to have self.order 1 elements ffor self.orderorder filter, got lenacoeffs raise ValueErrormsg if lenbcoeffs ! self.order 1: msg fExpected bcoeffs to have self.order 1 elements ffor self.orderorder filter, got lenacoeffs raise ValueErrormsg self.acoeffs acoeffs self.bcoeffs bcoeffs def processself, sample: float float: result 0.0 Start at index 1 and do index 0 at the end. for i in range1, self.order 1: result self.bcoeffsi self.inputhistoryi 1 self.acoeffsi self.outputhistoryi 1 result result self.bcoeffs0 sample self.acoeffs0 self.inputhistory1: self.inputhistory:1 self.outputhistory1: self.outputhistory:1 self.inputhistory0 sample self.outputhistory0 result return result","Completions":"from __future__ import annotations\n\n\nclass IIRFilter:\n r\"\"\"\n N-Order IIR filter\n Assumes working with float samples normalized on [-1, 1]\n\n ---\n\n Implementation details:\n Based on the 2nd-order function from\n https:\/\/en.wikipedia.org\/wiki\/Digital_biquad_filter,\n this generalized N-order function was made.\n\n Using the following transfer function\n H(z)=\\frac{b_{0}+b_{1}z^{-1}+b_{2}z^{-2}+...+b_{k}z^{-k}}{a_{0}+a_{1}z^{-1}+a_{2}z^{-2}+...+a_{k}z^{-k}}\n we can rewrite this to\n y[n]={\\frac{1}{a_{0}}}\\left(\\left(b_{0}x[n]+b_{1}x[n-1]+b_{2}x[n-2]+...+b_{k}x[n-k]\\right)-\\left(a_{1}y[n-1]+a_{2}y[n-2]+...+a_{k}y[n-k]\\right)\\right)\n \"\"\"\n\n def __init__(self, order: int) -> None:\n self.order = order\n\n # a_{0} ... a_{k}\n self.a_coeffs = [1.0] + [0.0] * order\n # b_{0} ... b_{k}\n self.b_coeffs = [1.0] + [0.0] * order\n\n # x[n-1] ... x[n-k]\n self.input_history = [0.0] * self.order\n # y[n-1] ... y[n-k]\n self.output_history = [0.0] * self.order\n\n def set_coefficients(self, a_coeffs: list[float], b_coeffs: list[float]) -> None:\n \"\"\"\n Set the coefficients for the IIR filter. These should both be of size order + 1.\n a_0 may be left out, and it will use 1.0 as default value.\n\n This method works well with scipy's filter design functions\n >>> # Make a 2nd-order 1000Hz butterworth lowpass filter\n >>> import scipy.signal\n >>> b_coeffs, a_coeffs = scipy.signal.butter(2, 1000,\n ... btype='lowpass',\n ... fs=48000)\n >>> filt = IIRFilter(2)\n >>> filt.set_coefficients(a_coeffs, b_coeffs)\n \"\"\"\n if len(a_coeffs) < self.order:\n a_coeffs = [1.0, *a_coeffs]\n\n if len(a_coeffs) != self.order + 1:\n msg = (\n f\"Expected a_coeffs to have {self.order + 1} elements \"\n f\"for {self.order}-order filter, got {len(a_coeffs)}\"\n )\n raise ValueError(msg)\n\n if len(b_coeffs) != self.order + 1:\n msg = (\n f\"Expected b_coeffs to have {self.order + 1} elements \"\n f\"for {self.order}-order filter, got {len(a_coeffs)}\"\n )\n raise ValueError(msg)\n\n self.a_coeffs = a_coeffs\n self.b_coeffs = b_coeffs\n\n def process(self, sample: float) -> float:\n \"\"\"\n Calculate y[n]\n\n >>> filt = IIRFilter(2)\n >>> filt.process(0)\n 0.0\n \"\"\"\n result = 0.0\n\n # Start at index 1 and do index 0 at the end.\n for i in range(1, self.order + 1):\n result += (\n self.b_coeffs[i] * self.input_history[i - 1]\n - self.a_coeffs[i] * self.output_history[i - 1]\n )\n\n result = (result + self.b_coeffs[0] * sample) \/ self.a_coeffs[0]\n\n self.input_history[1:] = self.input_history[:-1]\n self.output_history[1:] = self.output_history[:-1]\n\n self.input_history[0] = sample\n self.output_history[0] = result\n\n return result\n"} +{"Prompt":"Calculate yn issubclassFilterType, Protocol True Get bounds for printing fft results import numpy array numpy.linspace20.0, 20.0, 1000 getboundsarray, 1000 20, 20 Show frequency response of a filter from audiofilters.iirfilter import IIRFilter filt IIRFilter4 showfrequencyresponsefilt, 48000 Frequencies on log scale from 24 to nyquist frequency Display within reasonable bounds Show phase response of a filter from audiofilters.iirfilter import IIRFilter filt IIRFilter4 showphaseresponsefilt, 48000 Frequencies on log scale from 24 to nyquist frequency","Completions":"from __future__ import annotations\n\nfrom math import pi\nfrom typing import Protocol\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\nclass FilterType(Protocol):\n def process(self, sample: float) -> float:\n \"\"\"\n Calculate y[n]\n\n >>> issubclass(FilterType, Protocol)\n True\n \"\"\"\n return 0.0\n\n\ndef get_bounds(\n fft_results: np.ndarray, samplerate: int\n) -> tuple[int | float, int | float]:\n \"\"\"\n Get bounds for printing fft results\n\n >>> import numpy\n >>> array = numpy.linspace(-20.0, 20.0, 1000)\n >>> get_bounds(array, 1000)\n (-20, 20)\n \"\"\"\n lowest = min([-20, np.min(fft_results[1 : samplerate \/\/ 2 - 1])])\n highest = max([20, np.max(fft_results[1 : samplerate \/\/ 2 - 1])])\n return lowest, highest\n\n\ndef show_frequency_response(filter_type: FilterType, samplerate: int) -> None:\n \"\"\"\n Show frequency response of a filter\n\n >>> from audio_filters.iir_filter import IIRFilter\n >>> filt = IIRFilter(4)\n >>> show_frequency_response(filt, 48000)\n \"\"\"\n\n size = 512\n inputs = [1] + [0] * (size - 1)\n outputs = [filter_type.process(item) for item in inputs]\n\n filler = [0] * (samplerate - size) # zero-padding\n outputs += filler\n fft_out = np.abs(np.fft.fft(outputs))\n fft_db = 20 * np.log10(fft_out)\n\n # Frequencies on log scale from 24 to nyquist frequency\n plt.xlim(24, samplerate \/ 2 - 1)\n plt.xlabel(\"Frequency (Hz)\")\n plt.xscale(\"log\")\n\n # Display within reasonable bounds\n bounds = get_bounds(fft_db, samplerate)\n plt.ylim(max([-80, bounds[0]]), min([80, bounds[1]]))\n plt.ylabel(\"Gain (dB)\")\n\n plt.plot(fft_db)\n plt.show()\n\n\ndef show_phase_response(filter_type: FilterType, samplerate: int) -> None:\n \"\"\"\n Show phase response of a filter\n\n >>> from audio_filters.iir_filter import IIRFilter\n >>> filt = IIRFilter(4)\n >>> show_phase_response(filt, 48000)\n \"\"\"\n\n size = 512\n inputs = [1] + [0] * (size - 1)\n outputs = [filter_type.process(item) for item in inputs]\n\n filler = [0] * (samplerate - size) # zero-padding\n outputs += filler\n fft_out = np.angle(np.fft.fft(outputs))\n\n # Frequencies on log scale from 24 to nyquist frequency\n plt.xlim(24, samplerate \/ 2 - 1)\n plt.xlabel(\"Frequency (Hz)\")\n plt.xscale(\"log\")\n\n plt.ylim(-2 * pi, 2 * pi)\n plt.ylabel(\"Phase shift (Radians)\")\n plt.plot(np.unwrap(fft_out, -2 * pi))\n plt.show()\n"} +{"Prompt":"In this problem, we want to determine all possible combinations of k numbers out of 1 ... n. We use backtracking to solve this problem. Time complexity: OCn,k which is On choose k On!k! n k!, combinationlistsn4, k2 1, 2, 1, 3, 1, 4, 2, 3, 2, 4, 3, 4 generateallcombinationsn4, k2 1, 2, 1, 3, 1, 4, 2, 3, 2, 4, 3, 4 generateallcombinationsn0, k0 generateallcombinationsn10, k1 Traceback most recent call last: ... ValueError: k must not be negative generateallcombinationsn1, k10 Traceback most recent call last: ... ValueError: n must not be negative generateallcombinationsn5, k4 1, 2, 3, 4, 1, 2, 3, 5, 1, 2, 4, 5, 1, 3, 4, 5, 2, 3, 4, 5 from itertools import combinations allgenerateallcombinationsn, k combinationlistsn, k ... for n in range1, 6 for k in range1, 6 True","Completions":"from __future__ import annotations\n\nfrom itertools import combinations\n\n\ndef combination_lists(n: int, k: int) -> list[list[int]]:\n \"\"\"\n >>> combination_lists(n=4, k=2)\n [[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]]\n \"\"\"\n return [list(x) for x in combinations(range(1, n + 1), k)]\n\n\ndef generate_all_combinations(n: int, k: int) -> list[list[int]]:\n \"\"\"\n >>> generate_all_combinations(n=4, k=2)\n [[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]]\n >>> generate_all_combinations(n=0, k=0)\n [[]]\n >>> generate_all_combinations(n=10, k=-1)\n Traceback (most recent call last):\n ...\n ValueError: k must not be negative\n >>> generate_all_combinations(n=-1, k=10)\n Traceback (most recent call last):\n ...\n ValueError: n must not be negative\n >>> generate_all_combinations(n=5, k=4)\n [[1, 2, 3, 4], [1, 2, 3, 5], [1, 2, 4, 5], [1, 3, 4, 5], [2, 3, 4, 5]]\n >>> from itertools import combinations\n >>> all(generate_all_combinations(n, k) == combination_lists(n, k)\n ... for n in range(1, 6) for k in range(1, 6))\n True\n \"\"\"\n if k < 0:\n raise ValueError(\"k must not be negative\")\n if n < 0:\n raise ValueError(\"n must not be negative\")\n\n result: list[list[int]] = []\n create_all_state(1, n, k, [], result)\n return result\n\n\ndef create_all_state(\n increment: int,\n total_number: int,\n level: int,\n current_list: list[int],\n total_list: list[list[int]],\n) -> None:\n if level == 0:\n total_list.append(current_list[:])\n return\n\n for i in range(increment, total_number - level + 2):\n current_list.append(i)\n create_all_state(i + 1, total_number, level - 1, current_list, total_list)\n current_list.pop()\n\n\nif __name__ == \"__main__\":\n from doctest import testmod\n\n testmod()\n print(generate_all_combinations(n=4, k=2))\n tests = ((n, k) for n in range(1, 5) for k in range(1, 5))\n for n, k in tests:\n print(n, k, generate_all_combinations(n, k) == combination_lists(n, k))\n\n print(\"Benchmark:\")\n from timeit import timeit\n\n for func in (\"combination_lists\", \"generate_all_combinations\"):\n print(f\"{func:>25}(): {timeit(f'{func}(n=4, k = 2)', globals=globals())}\")\n"} +{"Prompt":"In this problem, we want to determine all possible permutations of the given sequence. We use backtracking to solve this problem. Time complexity: On! n, where n denotes the length of the given sequence. Creates a state space tree to iterate through each branch using DFS. We know that each state has exactly lensequence index children. It terminates when it reaches the end of the given sequence. remove the comment to take an input from the user printEnter the elements sequence listmapint, input.split","Completions":"from __future__ import annotations\n\n\ndef generate_all_permutations(sequence: list[int | str]) -> None:\n create_state_space_tree(sequence, [], 0, [0 for i in range(len(sequence))])\n\n\ndef create_state_space_tree(\n sequence: list[int | str],\n current_sequence: list[int | str],\n index: int,\n index_used: list[int],\n) -> None:\n \"\"\"\n Creates a state space tree to iterate through each branch using DFS.\n We know that each state has exactly len(sequence) - index children.\n It terminates when it reaches the end of the given sequence.\n \"\"\"\n\n if index == len(sequence):\n print(current_sequence)\n return\n\n for i in range(len(sequence)):\n if not index_used[i]:\n current_sequence.append(sequence[i])\n index_used[i] = True\n create_state_space_tree(sequence, current_sequence, index + 1, index_used)\n current_sequence.pop()\n index_used[i] = False\n\n\n\"\"\"\nremove the comment to take an input from the user\n\nprint(\"Enter the elements\")\nsequence = list(map(int, input().split()))\n\"\"\"\n\nsequence: list[int | str] = [3, 1, 2, 4]\ngenerate_all_permutations(sequence)\n\nsequence_2: list[int | str] = [\"A\", \"B\", \"C\"]\ngenerate_all_permutations(sequence_2)\n"} +{"Prompt":"In this problem, we want to determine all possible subsequences of the given sequence. We use backtracking to solve this problem. Time complexity: O2n, where n denotes the length of the given sequence. Creates a state space tree to iterate through each branch using DFS. We know that each state has exactly two children. It terminates when it reaches the end of the given sequence.","Completions":"from __future__ import annotations\n\nfrom typing import Any\n\n\ndef generate_all_subsequences(sequence: list[Any]) -> None:\n create_state_space_tree(sequence, [], 0)\n\n\ndef create_state_space_tree(\n sequence: list[Any], current_subsequence: list[Any], index: int\n) -> None:\n \"\"\"\n Creates a state space tree to iterate through each branch using DFS.\n We know that each state has exactly two children.\n It terminates when it reaches the end of the given sequence.\n \"\"\"\n\n if index == len(sequence):\n print(current_subsequence)\n return\n\n create_state_space_tree(sequence, current_subsequence, index + 1)\n current_subsequence.append(sequence[index])\n create_state_space_tree(sequence, current_subsequence, index + 1)\n current_subsequence.pop()\n\n\nif __name__ == \"__main__\":\n seq: list[Any] = [3, 1, 2, 4]\n generate_all_subsequences(seq)\n\n seq.clear()\n seq.extend([\"A\", \"B\", \"C\"])\n generate_all_subsequences(seq)\n"} +{"Prompt":"Graph Coloring also called m coloring problem consists of coloring a given graph with at most m colors such that no adjacent vertices are assigned the same color Wikipedia: https:en.wikipedia.orgwikiGraphcoloring For each neighbour check if the coloring constraint is satisfied If any of the neighbours fail the constraint return False If all neighbours validate the constraint return True neighbours 0,1,0,1,0 coloredvertices 0, 2, 1, 2, 0 color 1 validcoloringneighbours, coloredvertices, color True color 2 validcoloringneighbours, coloredvertices, color False Does any neighbour not satisfy the constraints PseudoCode Base Case: 1. Check if coloring is complete 1.1 If complete return True meaning that we successfully colored the graph Recursive Step: 2. Iterates over each color: Check if the current coloring is valid: 2.1. Color given vertex 2.2. Do recursive call, check if this coloring leads to a solution 2.4. if current coloring leads to a solution return 2.5. Uncolor given vertex graph 0, 1, 0, 0, 0, ... 1, 0, 1, 0, 1, ... 0, 1, 0, 1, 0, ... 0, 1, 1, 0, 0, ... 0, 1, 0, 0, 0 maxcolors 3 coloredvertices 0, 1, 0, 0, 0 index 3 utilcolorgraph, maxcolors, coloredvertices, index True maxcolors 2 utilcolorgraph, maxcolors, coloredvertices, index False Base Case Recursive Step Color current vertex Validate coloring Backtrack Wrapper function to call subroutine called utilcolor which will either return True or False. If True is returned coloredvertices list is filled with correct colorings graph 0, 1, 0, 0, 0, ... 1, 0, 1, 0, 1, ... 0, 1, 0, 1, 0, ... 0, 1, 1, 0, 0, ... 0, 1, 0, 0, 0 maxcolors 3 colorgraph, maxcolors 0, 1, 0, 2, 0 maxcolors 2 colorgraph, maxcolors","Completions":"def valid_coloring(\n neighbours: list[int], colored_vertices: list[int], color: int\n) -> bool:\n \"\"\"\n For each neighbour check if the coloring constraint is satisfied\n If any of the neighbours fail the constraint return False\n If all neighbours validate the constraint return True\n\n >>> neighbours = [0,1,0,1,0]\n >>> colored_vertices = [0, 2, 1, 2, 0]\n\n >>> color = 1\n >>> valid_coloring(neighbours, colored_vertices, color)\n True\n\n >>> color = 2\n >>> valid_coloring(neighbours, colored_vertices, color)\n False\n \"\"\"\n # Does any neighbour not satisfy the constraints\n return not any(\n neighbour == 1 and colored_vertices[i] == color\n for i, neighbour in enumerate(neighbours)\n )\n\n\ndef util_color(\n graph: list[list[int]], max_colors: int, colored_vertices: list[int], index: int\n) -> bool:\n \"\"\"\n Pseudo-Code\n\n Base Case:\n 1. Check if coloring is complete\n 1.1 If complete return True (meaning that we successfully colored the graph)\n\n Recursive Step:\n 2. Iterates over each color:\n Check if the current coloring is valid:\n 2.1. Color given vertex\n 2.2. Do recursive call, check if this coloring leads to a solution\n 2.4. if current coloring leads to a solution return\n 2.5. Uncolor given vertex\n\n >>> graph = [[0, 1, 0, 0, 0],\n ... [1, 0, 1, 0, 1],\n ... [0, 1, 0, 1, 0],\n ... [0, 1, 1, 0, 0],\n ... [0, 1, 0, 0, 0]]\n >>> max_colors = 3\n >>> colored_vertices = [0, 1, 0, 0, 0]\n >>> index = 3\n\n >>> util_color(graph, max_colors, colored_vertices, index)\n True\n\n >>> max_colors = 2\n >>> util_color(graph, max_colors, colored_vertices, index)\n False\n \"\"\"\n\n # Base Case\n if index == len(graph):\n return True\n\n # Recursive Step\n for i in range(max_colors):\n if valid_coloring(graph[index], colored_vertices, i):\n # Color current vertex\n colored_vertices[index] = i\n # Validate coloring\n if util_color(graph, max_colors, colored_vertices, index + 1):\n return True\n # Backtrack\n colored_vertices[index] = -1\n return False\n\n\ndef color(graph: list[list[int]], max_colors: int) -> list[int]:\n \"\"\"\n Wrapper function to call subroutine called util_color\n which will either return True or False.\n If True is returned colored_vertices list is filled with correct colorings\n\n >>> graph = [[0, 1, 0, 0, 0],\n ... [1, 0, 1, 0, 1],\n ... [0, 1, 0, 1, 0],\n ... [0, 1, 1, 0, 0],\n ... [0, 1, 0, 0, 0]]\n\n >>> max_colors = 3\n >>> color(graph, max_colors)\n [0, 1, 0, 2, 0]\n\n >>> max_colors = 2\n >>> color(graph, max_colors)\n []\n \"\"\"\n colored_vertices = [-1] * len(graph)\n\n if util_color(graph, max_colors, colored_vertices, 0):\n return colored_vertices\n\n return []\n"} +{"Prompt":"In the Combination Sum problem, we are given a list consisting of distinct integers. We need to find all the combinations whose sum equals to target given. We can use an element more than one. Time complexityAverage Case: On! Constraints: 1 candidates.length 30 2 candidatesi 40 All elements of candidates are distinct. 1 target 40 A recursive function that searches for possible combinations. Backtracks in case of a bigger current combination value than the target value. Parameters previousindex: Last index from the previous search target: The value we need to obtain by summing our integers in the path list. answer: A list of possible combinations path: Current combination candidates: A list of integers we can use. combinationsum2, 3, 5, 8 2, 2, 2, 2, 2, 3, 3, 3, 5 combinationsum2, 3, 6, 7, 7 2, 2, 3, 7 combinationsum8, 2.3, 0, 1 Traceback most recent call last: ... RecursionError: maximum recursion depth exceeded","Completions":"def backtrack(\n candidates: list, path: list, answer: list, target: int, previous_index: int\n) -> None:\n \"\"\"\n A recursive function that searches for possible combinations. Backtracks in case\n of a bigger current combination value than the target value.\n\n Parameters\n ----------\n previous_index: Last index from the previous search\n target: The value we need to obtain by summing our integers in the path list.\n answer: A list of possible combinations\n path: Current combination\n candidates: A list of integers we can use.\n \"\"\"\n if target == 0:\n answer.append(path.copy())\n else:\n for index in range(previous_index, len(candidates)):\n if target >= candidates[index]:\n path.append(candidates[index])\n backtrack(candidates, path, answer, target - candidates[index], index)\n path.pop(len(path) - 1)\n\n\ndef combination_sum(candidates: list, target: int) -> list:\n \"\"\"\n >>> combination_sum([2, 3, 5], 8)\n [[2, 2, 2, 2], [2, 3, 3], [3, 5]]\n >>> combination_sum([2, 3, 6, 7], 7)\n [[2, 2, 3], [7]]\n >>> combination_sum([-8, 2.3, 0], 1)\n Traceback (most recent call last):\n ...\n RecursionError: maximum recursion depth exceeded\n \"\"\"\n path = [] # type: list[int]\n answer = [] # type: list[int]\n backtrack(candidates, path, answer, target, 0)\n return answer\n\n\ndef main() -> None:\n print(combination_sum([-8, 2.3, 0], 1))\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n main()\n"} +{"Prompt":"https:www.geeksforgeeks.orgsolvecrosswordpuzzle Check if a word can be placed at the given position. puzzle ... '', '', '', '', ... '', '', '', '', ... '', '', '', '', ... '', '', '', '' ... isvalidpuzzle, 'word', 0, 0, True True puzzle ... '', '', '', '', ... '', '', '', '', ... '', '', '', '', ... '', '', '', '' ... isvalidpuzzle, 'word', 0, 0, False True Place a word at the given position. puzzle ... '', '', '', '', ... '', '', '', '', ... '', '', '', '', ... '', '', '', '' ... placewordpuzzle, 'word', 0, 0, True puzzle 'w', '', '', '', 'o', '', '', '', 'r', '', '', '', 'd', '', '', '' Remove a word from the given position. puzzle ... 'w', '', '', '', ... 'o', '', '', '', ... 'r', '', '', '', ... 'd', '', '', '' ... removewordpuzzle, 'word', 0, 0, True puzzle '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '' Solve the crossword puzzle using backtracking. puzzle ... '', '', '', '', ... '', '', '', '', ... '', '', '', '', ... '', '', '', '' ... words 'word', 'four', 'more', 'last' solvecrosswordpuzzle, words True puzzle ... '', '', '', '', ... '', '', '', '', ... '', '', '', '', ... '', '', '', '' ... words 'word', 'four', 'more', 'paragraphs' solvecrosswordpuzzle, words False","Completions":"# https:\/\/www.geeksforgeeks.org\/solve-crossword-puzzle\/\n\n\ndef is_valid(\n puzzle: list[list[str]], word: str, row: int, col: int, vertical: bool\n) -> bool:\n \"\"\"\n Check if a word can be placed at the given position.\n\n >>> puzzle = [\n ... ['', '', '', ''],\n ... ['', '', '', ''],\n ... ['', '', '', ''],\n ... ['', '', '', '']\n ... ]\n >>> is_valid(puzzle, 'word', 0, 0, True)\n True\n >>> puzzle = [\n ... ['', '', '', ''],\n ... ['', '', '', ''],\n ... ['', '', '', ''],\n ... ['', '', '', '']\n ... ]\n >>> is_valid(puzzle, 'word', 0, 0, False)\n True\n \"\"\"\n for i in range(len(word)):\n if vertical:\n if row + i >= len(puzzle) or puzzle[row + i][col] != \"\":\n return False\n else:\n if col + i >= len(puzzle[0]) or puzzle[row][col + i] != \"\":\n return False\n return True\n\n\ndef place_word(\n puzzle: list[list[str]], word: str, row: int, col: int, vertical: bool\n) -> None:\n \"\"\"\n Place a word at the given position.\n\n >>> puzzle = [\n ... ['', '', '', ''],\n ... ['', '', '', ''],\n ... ['', '', '', ''],\n ... ['', '', '', '']\n ... ]\n >>> place_word(puzzle, 'word', 0, 0, True)\n >>> puzzle\n [['w', '', '', ''], ['o', '', '', ''], ['r', '', '', ''], ['d', '', '', '']]\n \"\"\"\n for i, char in enumerate(word):\n if vertical:\n puzzle[row + i][col] = char\n else:\n puzzle[row][col + i] = char\n\n\ndef remove_word(\n puzzle: list[list[str]], word: str, row: int, col: int, vertical: bool\n) -> None:\n \"\"\"\n Remove a word from the given position.\n\n >>> puzzle = [\n ... ['w', '', '', ''],\n ... ['o', '', '', ''],\n ... ['r', '', '', ''],\n ... ['d', '', '', '']\n ... ]\n >>> remove_word(puzzle, 'word', 0, 0, True)\n >>> puzzle\n [['', '', '', ''], ['', '', '', ''], ['', '', '', ''], ['', '', '', '']]\n \"\"\"\n for i in range(len(word)):\n if vertical:\n puzzle[row + i][col] = \"\"\n else:\n puzzle[row][col + i] = \"\"\n\n\ndef solve_crossword(puzzle: list[list[str]], words: list[str]) -> bool:\n \"\"\"\n Solve the crossword puzzle using backtracking.\n\n >>> puzzle = [\n ... ['', '', '', ''],\n ... ['', '', '', ''],\n ... ['', '', '', ''],\n ... ['', '', '', '']\n ... ]\n\n >>> words = ['word', 'four', 'more', 'last']\n >>> solve_crossword(puzzle, words)\n True\n >>> puzzle = [\n ... ['', '', '', ''],\n ... ['', '', '', ''],\n ... ['', '', '', ''],\n ... ['', '', '', '']\n ... ]\n >>> words = ['word', 'four', 'more', 'paragraphs']\n >>> solve_crossword(puzzle, words)\n False\n \"\"\"\n for row in range(len(puzzle)):\n for col in range(len(puzzle[0])):\n if puzzle[row][col] == \"\":\n for word in words:\n for vertical in [True, False]:\n if is_valid(puzzle, word, row, col, vertical):\n place_word(puzzle, word, row, col, vertical)\n words.remove(word)\n if solve_crossword(puzzle, words):\n return True\n words.append(word)\n remove_word(puzzle, word, row, col, vertical)\n return False\n return True\n\n\nif __name__ == \"__main__\":\n PUZZLE = [[\"\"] * 3 for _ in range(3)]\n WORDS = [\"cat\", \"dog\", \"car\"]\n\n if solve_crossword(PUZZLE, WORDS):\n print(\"Solution found:\")\n for row in PUZZLE:\n print(\" \".join(row))\n else:\n print(\"No solution found:\")\n"} +{"Prompt":"author: Aayush Soni Given n pairs of parentheses, write a function to generate all combinations of wellformed parentheses. Input: n 2 Output: , Leetcode link: https:leetcode.comproblemsgenerateparenthesesdescription Generate valid combinations of balanced parentheses using recursion. :param partial: A string representing the current combination. :param opencount: An integer representing the count of open parentheses. :param closecount: An integer representing the count of close parentheses. :param n: An integer representing the total number of pairs. :param result: A list to store valid combinations. :return: None This function uses recursion to explore all possible combinations, ensuring that at each step, the parentheses remain balanced. Example: result backtrack, 0, 0, 2, result result '', '' When the combination is complete, add it to the result. If we can add an open parenthesis, do so, and recurse. If we can add a close parenthesis it won't make the combination invalid, do so, and recurse. Generate valid combinations of balanced parentheses for a given n. :param n: An integer representing the number of pairs of parentheses. :return: A list of strings with valid combinations. This function uses a recursive approach to generate the combinations. Time Complexity: O22n In the worst case, we have 22n combinations. Space Complexity: On where 'n' is the number of pairs. Example 1: generateparenthesis3 '', '', '', '', '' Example 2: generateparenthesis1 ''","Completions":"def backtrack(\n partial: str, open_count: int, close_count: int, n: int, result: list[str]\n) -> None:\n \"\"\"\n Generate valid combinations of balanced parentheses using recursion.\n\n :param partial: A string representing the current combination.\n :param open_count: An integer representing the count of open parentheses.\n :param close_count: An integer representing the count of close parentheses.\n :param n: An integer representing the total number of pairs.\n :param result: A list to store valid combinations.\n :return: None\n\n This function uses recursion to explore all possible combinations,\n ensuring that at each step, the parentheses remain balanced.\n\n Example:\n >>> result = []\n >>> backtrack(\"\", 0, 0, 2, result)\n >>> result\n ['(())', '()()']\n \"\"\"\n if len(partial) == 2 * n:\n # When the combination is complete, add it to the result.\n result.append(partial)\n return\n\n if open_count < n:\n # If we can add an open parenthesis, do so, and recurse.\n backtrack(partial + \"(\", open_count + 1, close_count, n, result)\n\n if close_count < open_count:\n # If we can add a close parenthesis (it won't make the combination invalid),\n # do so, and recurse.\n backtrack(partial + \")\", open_count, close_count + 1, n, result)\n\n\ndef generate_parenthesis(n: int) -> list[str]:\n \"\"\"\n Generate valid combinations of balanced parentheses for a given n.\n\n :param n: An integer representing the number of pairs of parentheses.\n :return: A list of strings with valid combinations.\n\n This function uses a recursive approach to generate the combinations.\n\n Time Complexity: O(2^(2n)) - In the worst case, we have 2^(2n) combinations.\n Space Complexity: O(n) - where 'n' is the number of pairs.\n\n Example 1:\n >>> generate_parenthesis(3)\n ['((()))', '(()())', '(())()', '()(())', '()()()']\n\n Example 2:\n >>> generate_parenthesis(1)\n ['()']\n \"\"\"\n\n result: list[str] = []\n backtrack(\"\", 0, 0, n, result)\n return result\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"A Hamiltonian cycle Hamiltonian circuit is a graph cycle through a graph that visits each node exactly once. Determining whether such paths and cycles exist in graphs is the 'Hamiltonian path problem', which is NPcomplete. Wikipedia: https:en.wikipedia.orgwikiHamiltonianpath Checks whether it is possible to add next into path by validating 2 statements 1. There should be path between current and next vertex 2. Next vertex should not be in path If both validations succeed we return True, saying that it is possible to connect this vertices, otherwise we return False Case 1:Use exact graph as in main function, with initialized values graph 0, 1, 0, 1, 0, ... 1, 0, 1, 1, 1, ... 0, 1, 0, 0, 1, ... 1, 1, 0, 0, 1, ... 0, 1, 1, 1, 0 path 0, 1, 1, 1, 1, 0 currind 1 nextver 1 validconnectiongraph, nextver, currind, path True Case 2: Same graph, but trying to connect to node that is already in path path 0, 1, 2, 4, 1, 0 currind 4 nextver 1 validconnectiongraph, nextver, currind, path False 1. Validate that path exists between current and next vertices 2. Validate that next vertex is not already in path PseudoCode Base Case: 1. Check if we visited all of vertices 1.1 If last visited vertex has path to starting vertex return True either return False Recursive Step: 2. Iterate over each vertex Check if next vertex is valid for transiting from current vertex 2.1 Remember next vertex as next transition 2.2 Do recursive call and check if going to this vertex solves problem 2.3 If next vertex leads to solution return True 2.4 Else backtrack, delete remembered vertex Case 1: Use exact graph as in main function, with initialized values graph 0, 1, 0, 1, 0, ... 1, 0, 1, 1, 1, ... 0, 1, 0, 0, 1, ... 1, 1, 0, 0, 1, ... 0, 1, 1, 1, 0 path 0, 1, 1, 1, 1, 0 currind 1 utilhamiltoncyclegraph, path, currind True path 0, 1, 2, 4, 3, 0 Case 2: Use exact graph as in previous case, but in the properties taken from middle of calculation graph 0, 1, 0, 1, 0, ... 1, 0, 1, 1, 1, ... 0, 1, 0, 0, 1, ... 1, 1, 0, 0, 1, ... 0, 1, 1, 1, 0 path 0, 1, 2, 1, 1, 0 currind 3 utilhamiltoncyclegraph, path, currind True path 0, 1, 2, 4, 3, 0 Base Case return whether path exists between current and starting vertices Recursive Step Insert current vertex into path as next transition Validate created path Backtrack Initialize path with 1, indicating that we have not visited them yet path 1 lengraph 1 initialize start and end of path with starting index path0 path1 startindex evaluate and if we find answer return path either return empty array return path if utilhamiltoncyclegraph, path, 1 else","Completions":"def valid_connection(\n graph: list[list[int]], next_ver: int, curr_ind: int, path: list[int]\n) -> bool:\n \"\"\"\n Checks whether it is possible to add next into path by validating 2 statements\n 1. There should be path between current and next vertex\n 2. Next vertex should not be in path\n If both validations succeed we return True, saying that it is possible to connect\n this vertices, otherwise we return False\n\n Case 1:Use exact graph as in main function, with initialized values\n >>> graph = [[0, 1, 0, 1, 0],\n ... [1, 0, 1, 1, 1],\n ... [0, 1, 0, 0, 1],\n ... [1, 1, 0, 0, 1],\n ... [0, 1, 1, 1, 0]]\n >>> path = [0, -1, -1, -1, -1, 0]\n >>> curr_ind = 1\n >>> next_ver = 1\n >>> valid_connection(graph, next_ver, curr_ind, path)\n True\n\n Case 2: Same graph, but trying to connect to node that is already in path\n >>> path = [0, 1, 2, 4, -1, 0]\n >>> curr_ind = 4\n >>> next_ver = 1\n >>> valid_connection(graph, next_ver, curr_ind, path)\n False\n \"\"\"\n\n # 1. Validate that path exists between current and next vertices\n if graph[path[curr_ind - 1]][next_ver] == 0:\n return False\n\n # 2. Validate that next vertex is not already in path\n return not any(vertex == next_ver for vertex in path)\n\n\ndef util_hamilton_cycle(graph: list[list[int]], path: list[int], curr_ind: int) -> bool:\n \"\"\"\n Pseudo-Code\n Base Case:\n 1. Check if we visited all of vertices\n 1.1 If last visited vertex has path to starting vertex return True either\n return False\n Recursive Step:\n 2. Iterate over each vertex\n Check if next vertex is valid for transiting from current vertex\n 2.1 Remember next vertex as next transition\n 2.2 Do recursive call and check if going to this vertex solves problem\n 2.3 If next vertex leads to solution return True\n 2.4 Else backtrack, delete remembered vertex\n\n Case 1: Use exact graph as in main function, with initialized values\n >>> graph = [[0, 1, 0, 1, 0],\n ... [1, 0, 1, 1, 1],\n ... [0, 1, 0, 0, 1],\n ... [1, 1, 0, 0, 1],\n ... [0, 1, 1, 1, 0]]\n >>> path = [0, -1, -1, -1, -1, 0]\n >>> curr_ind = 1\n >>> util_hamilton_cycle(graph, path, curr_ind)\n True\n >>> path\n [0, 1, 2, 4, 3, 0]\n\n Case 2: Use exact graph as in previous case, but in the properties taken from\n middle of calculation\n >>> graph = [[0, 1, 0, 1, 0],\n ... [1, 0, 1, 1, 1],\n ... [0, 1, 0, 0, 1],\n ... [1, 1, 0, 0, 1],\n ... [0, 1, 1, 1, 0]]\n >>> path = [0, 1, 2, -1, -1, 0]\n >>> curr_ind = 3\n >>> util_hamilton_cycle(graph, path, curr_ind)\n True\n >>> path\n [0, 1, 2, 4, 3, 0]\n \"\"\"\n\n # Base Case\n if curr_ind == len(graph):\n # return whether path exists between current and starting vertices\n return graph[path[curr_ind - 1]][path[0]] == 1\n\n # Recursive Step\n for next_ver in range(len(graph)):\n if valid_connection(graph, next_ver, curr_ind, path):\n # Insert current vertex into path as next transition\n path[curr_ind] = next_ver\n # Validate created path\n if util_hamilton_cycle(graph, path, curr_ind + 1):\n return True\n # Backtrack\n path[curr_ind] = -1\n return False\n\n\ndef hamilton_cycle(graph: list[list[int]], start_index: int = 0) -> list[int]:\n r\"\"\"\n Wrapper function to call subroutine called util_hamilton_cycle,\n which will either return array of vertices indicating hamiltonian cycle\n or an empty list indicating that hamiltonian cycle was not found.\n Case 1:\n Following graph consists of 5 edges.\n If we look closely, we can see that there are multiple Hamiltonian cycles.\n For example one result is when we iterate like:\n (0)->(1)->(2)->(4)->(3)->(0)\n\n (0)---(1)---(2)\n | \/ \\ |\n | \/ \\ |\n | \/ \\ |\n |\/ \\|\n (3)---------(4)\n >>> graph = [[0, 1, 0, 1, 0],\n ... [1, 0, 1, 1, 1],\n ... [0, 1, 0, 0, 1],\n ... [1, 1, 0, 0, 1],\n ... [0, 1, 1, 1, 0]]\n >>> hamilton_cycle(graph)\n [0, 1, 2, 4, 3, 0]\n\n Case 2:\n Same Graph as it was in Case 1, changed starting index from default to 3\n\n (0)---(1)---(2)\n | \/ \\ |\n | \/ \\ |\n | \/ \\ |\n |\/ \\|\n (3)---------(4)\n >>> graph = [[0, 1, 0, 1, 0],\n ... [1, 0, 1, 1, 1],\n ... [0, 1, 0, 0, 1],\n ... [1, 1, 0, 0, 1],\n ... [0, 1, 1, 1, 0]]\n >>> hamilton_cycle(graph, 3)\n [3, 0, 1, 2, 4, 3]\n\n Case 3:\n Following Graph is exactly what it was before, but edge 3-4 is removed.\n Result is that there is no Hamiltonian Cycle anymore.\n\n (0)---(1)---(2)\n | \/ \\ |\n | \/ \\ |\n | \/ \\ |\n |\/ \\|\n (3) (4)\n >>> graph = [[0, 1, 0, 1, 0],\n ... [1, 0, 1, 1, 1],\n ... [0, 1, 0, 0, 1],\n ... [1, 1, 0, 0, 0],\n ... [0, 1, 1, 0, 0]]\n >>> hamilton_cycle(graph,4)\n []\n \"\"\"\n\n # Initialize path with -1, indicating that we have not visited them yet\n path = [-1] * (len(graph) + 1)\n # initialize start and end of path with starting index\n path[0] = path[-1] = start_index\n # evaluate and if we find answer return path either return empty array\n return path if util_hamilton_cycle(graph, path, 1) else []\n"} +{"Prompt":"Knight Tour Intro: https:www.youtube.comwatch?vabdY3dZFHM Find all the valid positions a knight can move to from the current position. getvalidpos1, 3, 4 2, 1, 0, 1, 3, 2 Check if the board matrix has been completely filled with nonzero values. iscomplete1 True iscomplete1, 2, 3, 0 False Helper function to solve knight tour problem. Find the solution for the knight tour problem for a board of size n. Raises ValueError if the tour cannot be performed for the given size. openknighttour1 1 openknighttour2 Traceback most recent call last: ... ValueError: Open Knight Tour cannot be performed on a board of size 2","Completions":"# Knight Tour Intro: https:\/\/www.youtube.com\/watch?v=ab_dY3dZFHM\n\nfrom __future__ import annotations\n\n\ndef get_valid_pos(position: tuple[int, int], n: int) -> list[tuple[int, int]]:\n \"\"\"\n Find all the valid positions a knight can move to from the current position.\n\n >>> get_valid_pos((1, 3), 4)\n [(2, 1), (0, 1), (3, 2)]\n \"\"\"\n\n y, x = position\n positions = [\n (y + 1, x + 2),\n (y - 1, x + 2),\n (y + 1, x - 2),\n (y - 1, x - 2),\n (y + 2, x + 1),\n (y + 2, x - 1),\n (y - 2, x + 1),\n (y - 2, x - 1),\n ]\n permissible_positions = []\n\n for position in positions:\n y_test, x_test = position\n if 0 <= y_test < n and 0 <= x_test < n:\n permissible_positions.append(position)\n\n return permissible_positions\n\n\ndef is_complete(board: list[list[int]]) -> bool:\n \"\"\"\n Check if the board (matrix) has been completely filled with non-zero values.\n\n >>> is_complete([[1]])\n True\n\n >>> is_complete([[1, 2], [3, 0]])\n False\n \"\"\"\n\n return not any(elem == 0 for row in board for elem in row)\n\n\ndef open_knight_tour_helper(\n board: list[list[int]], pos: tuple[int, int], curr: int\n) -> bool:\n \"\"\"\n Helper function to solve knight tour problem.\n \"\"\"\n\n if is_complete(board):\n return True\n\n for position in get_valid_pos(pos, len(board)):\n y, x = position\n\n if board[y][x] == 0:\n board[y][x] = curr + 1\n if open_knight_tour_helper(board, position, curr + 1):\n return True\n board[y][x] = 0\n\n return False\n\n\ndef open_knight_tour(n: int) -> list[list[int]]:\n \"\"\"\n Find the solution for the knight tour problem for a board of size n. Raises\n ValueError if the tour cannot be performed for the given size.\n\n >>> open_knight_tour(1)\n [[1]]\n\n >>> open_knight_tour(2)\n Traceback (most recent call last):\n ...\n ValueError: Open Knight Tour cannot be performed on a board of size 2\n \"\"\"\n\n board = [[0 for i in range(n)] for j in range(n)]\n\n for i in range(n):\n for j in range(n):\n board[i][j] = 1\n if open_knight_tour_helper(board, (i, j), 1):\n return board\n board[i][j] = 0\n\n msg = f\"Open Knight Tour cannot be performed on a board of size {n}\"\n raise ValueError(msg)\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Determine if a given pattern matches a string using backtracking. pattern: The pattern to match. inputstring: The string to match against the pattern. return: True if the pattern matches the string, False otherwise. matchwordpatternaba, GraphTreesGraph True matchwordpatternxyx, PythonRubyPython True matchwordpatternGG, PythonJavaPython False backtrack0, 0 True backtrack0, 1 True backtrack0, 4 False","Completions":"def match_word_pattern(pattern: str, input_string: str) -> bool:\n \"\"\"\n Determine if a given pattern matches a string using backtracking.\n\n pattern: The pattern to match.\n input_string: The string to match against the pattern.\n return: True if the pattern matches the string, False otherwise.\n\n >>> match_word_pattern(\"aba\", \"GraphTreesGraph\")\n True\n\n >>> match_word_pattern(\"xyx\", \"PythonRubyPython\")\n True\n\n >>> match_word_pattern(\"GG\", \"PythonJavaPython\")\n False\n \"\"\"\n\n def backtrack(pattern_index: int, str_index: int) -> bool:\n \"\"\"\n >>> backtrack(0, 0)\n True\n\n >>> backtrack(0, 1)\n True\n\n >>> backtrack(0, 4)\n False\n \"\"\"\n if pattern_index == len(pattern) and str_index == len(input_string):\n return True\n if pattern_index == len(pattern) or str_index == len(input_string):\n return False\n char = pattern[pattern_index]\n if char in pattern_map:\n mapped_str = pattern_map[char]\n if input_string.startswith(mapped_str, str_index):\n return backtrack(pattern_index + 1, str_index + len(mapped_str))\n else:\n return False\n for end in range(str_index + 1, len(input_string) + 1):\n substr = input_string[str_index:end]\n if substr in str_map:\n continue\n pattern_map[char] = substr\n str_map[substr] = char\n if backtrack(pattern_index + 1, end):\n return True\n del pattern_map[char]\n del str_map[substr]\n return False\n\n pattern_map: dict[str, str] = {}\n str_map: dict[str, str] = {}\n return backtrack(0, 0)\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Minimax helps to achieve maximum score in a game by checking all possible moves depth is current depth in game tree. nodeIndex is index of current node in scores. if move is of maximizer return true else false leaves of game tree is stored in scores height is maximum height of Game tree This function implements the minimax algorithm, which helps achieve the optimal score for a player in a twoplayer game by checking all possible moves. If the player is the maximizer, then the score is maximized. If the player is the minimizer, then the score is minimized. Parameters: depth: Current depth in the game tree. nodeindex: Index of the current node in the scores list. ismax: A boolean indicating whether the current move is for the maximizer True or minimizer False. scores: A list containing the scores of the leaves of the game tree. height: The maximum height of the game tree. Returns: An integer representing the optimal score for the current player. import math scores 90, 23, 6, 33, 21, 65, 123, 34423 height math.loglenscores, 2 minimax0, 0, True, scores, height 65 minimax1, 0, True, scores, height Traceback most recent call last: ... ValueError: Depth cannot be less than 0 minimax0, 0, True, , 2 Traceback most recent call last: ... ValueError: Scores cannot be empty scores 3, 5, 2, 9, 12, 5, 23, 23 height math.loglenscores, 2 minimax0, 0, True, scores, height 12 Base case: If the current depth equals the height of the tree, return the score of the current node. If it's the maximizer's turn, choose the maximum score between the two possible moves. If it's the minimizer's turn, choose the minimum score between the two possible moves. Sample scores and height calculation Calculate and print the optimal value using the minimax algorithm","Completions":"from __future__ import annotations\n\nimport math\n\n\ndef minimax(\n depth: int, node_index: int, is_max: bool, scores: list[int], height: float\n) -> int:\n \"\"\"\n This function implements the minimax algorithm, which helps achieve the optimal\n score for a player in a two-player game by checking all possible moves.\n If the player is the maximizer, then the score is maximized.\n If the player is the minimizer, then the score is minimized.\n\n Parameters:\n - depth: Current depth in the game tree.\n - node_index: Index of the current node in the scores list.\n - is_max: A boolean indicating whether the current move\n is for the maximizer (True) or minimizer (False).\n - scores: A list containing the scores of the leaves of the game tree.\n - height: The maximum height of the game tree.\n\n Returns:\n - An integer representing the optimal score for the current player.\n\n >>> import math\n >>> scores = [90, 23, 6, 33, 21, 65, 123, 34423]\n >>> height = math.log(len(scores), 2)\n >>> minimax(0, 0, True, scores, height)\n 65\n >>> minimax(-1, 0, True, scores, height)\n Traceback (most recent call last):\n ...\n ValueError: Depth cannot be less than 0\n >>> minimax(0, 0, True, [], 2)\n Traceback (most recent call last):\n ...\n ValueError: Scores cannot be empty\n >>> scores = [3, 5, 2, 9, 12, 5, 23, 23]\n >>> height = math.log(len(scores), 2)\n >>> minimax(0, 0, True, scores, height)\n 12\n \"\"\"\n\n if depth < 0:\n raise ValueError(\"Depth cannot be less than 0\")\n if len(scores) == 0:\n raise ValueError(\"Scores cannot be empty\")\n\n # Base case: If the current depth equals the height of the tree,\n # return the score of the current node.\n if depth == height:\n return scores[node_index]\n\n # If it's the maximizer's turn, choose the maximum score\n # between the two possible moves.\n if is_max:\n return max(\n minimax(depth + 1, node_index * 2, False, scores, height),\n minimax(depth + 1, node_index * 2 + 1, False, scores, height),\n )\n\n # If it's the minimizer's turn, choose the minimum score\n # between the two possible moves.\n return min(\n minimax(depth + 1, node_index * 2, True, scores, height),\n minimax(depth + 1, node_index * 2 + 1, True, scores, height),\n )\n\n\ndef main() -> None:\n # Sample scores and height calculation\n scores = [90, 23, 6, 33, 21, 65, 123, 34423]\n height = math.log(len(scores), 2)\n\n # Calculate and print the optimal value using the minimax algorithm\n print(\"Optimal value : \", end=\"\")\n print(minimax(0, 0, True, scores, height))\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n main()\n"} +{"Prompt":"The nqueens problem is of placing N queens on a N N chess board such that no queen can attack any other queens placed on that chess board. This means that one queen cannot have any other queen on its horizontal, vertical and diagonal lines. This function returns a boolean value True if it is safe to place a queen there considering the current state of the board. Parameters: board 2D matrix: The chessboard row, column: Coordinates of the cell on the board Returns: Boolean Value issafe0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1 True issafe1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1 False Check if there is any queen in the same row, column, left upper diagonal, and right upper diagonal This function creates a state space tree and calls the safe function until it receives a False Boolean and terminates that branch and backtracks to the next possible solution branch. If the row number exceeds N, we have a board with a successful combination and that combination is appended to the solution list and the board is printed. For every row, it iterates through each column to check if it is feasible to place a queen there. If all the combinations for that particular branch are successful, the board is reinitialized for the next possible combination. Prints the boards that have a successful combination. Number of queens e.g., n8 for an 8x8 board","Completions":"from __future__ import annotations\n\nsolution = []\n\n\ndef is_safe(board: list[list[int]], row: int, column: int) -> bool:\n \"\"\"\n This function returns a boolean value True if it is safe to place a queen there\n considering the current state of the board.\n\n Parameters:\n board (2D matrix): The chessboard\n row, column: Coordinates of the cell on the board\n\n Returns:\n Boolean Value\n\n >>> is_safe([[0, 0, 0], [0, 0, 0], [0, 0, 0]], 1, 1)\n True\n >>> is_safe([[1, 0, 0], [0, 0, 0], [0, 0, 0]], 1, 1)\n False\n \"\"\"\n\n n = len(board) # Size of the board\n\n # Check if there is any queen in the same row, column,\n # left upper diagonal, and right upper diagonal\n return (\n all(board[i][j] != 1 for i, j in zip(range(row, -1, -1), range(column, n)))\n and all(\n board[i][j] != 1 for i, j in zip(range(row, -1, -1), range(column, -1, -1))\n )\n and all(board[i][j] != 1 for i, j in zip(range(row, n), range(column, n)))\n and all(board[i][j] != 1 for i, j in zip(range(row, n), range(column, -1, -1)))\n )\n\n\ndef solve(board: list[list[int]], row: int) -> bool:\n \"\"\"\n This function creates a state space tree and calls the safe function until it\n receives a False Boolean and terminates that branch and backtracks to the next\n possible solution branch.\n \"\"\"\n if row >= len(board):\n \"\"\"\n If the row number exceeds N, we have a board with a successful combination\n and that combination is appended to the solution list and the board is printed.\n \"\"\"\n solution.append(board)\n printboard(board)\n print()\n return True\n for i in range(len(board)):\n \"\"\"\n For every row, it iterates through each column to check if it is feasible to\n place a queen there.\n If all the combinations for that particular branch are successful, the board is\n reinitialized for the next possible combination.\n \"\"\"\n if is_safe(board, row, i):\n board[row][i] = 1\n solve(board, row + 1)\n board[row][i] = 0\n return False\n\n\ndef printboard(board: list[list[int]]) -> None:\n \"\"\"\n Prints the boards that have a successful combination.\n \"\"\"\n for i in range(len(board)):\n for j in range(len(board)):\n if board[i][j] == 1:\n print(\"Q\", end=\" \") # Queen is present\n else:\n print(\".\", end=\" \") # Empty cell\n print()\n\n\n# Number of queens (e.g., n=8 for an 8x8 board)\nn = 8\nboard = [[0 for i in range(n)] for j in range(n)]\nsolve(board, 0)\nprint(\"The total number of solutions are:\", len(solution))\n"} +{"Prompt":"from future import annotations def depthfirstsearch possibleboard: listint, diagonalrightcollisions: listint, diagonalleftcollisions: listint, boards: listliststr, n: int, None: Get next row in the current board possibleboard to fill it with a queen row lenpossibleboard If row is equal to the size of the board it means there are a queen in each row in the current board possibleboard if row n: We convert the variable possibleboard that looks like this: 1, 3, 0, 2 to this: '. Q . . ', '. . . Q ', 'Q . . . ', '. . Q . ' boards.append. i Q . n 1 i for i in possibleboard return We iterate each column in the row to find all possible results in each row for col in rangen: We apply that we learned previously. First we check that in the current board possibleboard there are not other same value because if there is it means that there are a collision in vertical. Then we apply the two formulas we learned before: 45: y x b or 45: row col b 135: y x b or row col b. And we verify if the results of this two formulas not exist in their variables respectively. diagonalrightcollisions, diagonalleftcollisions If any or these are True it means there is a collision so we continue to the next value in the for loop. if col in possibleboard or row col in diagonalrightcollisions or row col in diagonalleftcollisions : continue If it is False we call dfs function again and we update the inputs depthfirstsearch possibleboard, col, diagonalrightcollisions, row col, diagonalleftcollisions, row col, boards, n, def nqueenssolutionn: int None: boards: listliststr depthfirstsearch, , , boards, n Print all the boards for board in boards: for column in board: printcolumn print printlenboards, solutions were found. if name main: import doctest doctest.testmod nqueenssolution4","Completions":"r\"\"\"\nProblem:\n\nThe n queens problem is: placing N queens on a N * N chess board such that no queen\ncan attack any other queens placed on that chess board. This means that one queen\ncannot have any other queen on its horizontal, vertical and diagonal lines.\n\nSolution:\n\nTo solve this problem we will use simple math. First we know the queen can move in all\nthe possible ways, we can simplify it in this: vertical, horizontal, diagonal left and\n diagonal right.\n\nWe can visualize it like this:\n\nleft diagonal = \\\nright diagonal = \/\n\nOn a chessboard vertical movement could be the rows and horizontal movement could be\nthe columns.\n\nIn programming we can use an array, and in this array each index could be the rows and\neach value in the array could be the column. For example:\n\n . Q . . We have this chessboard with one queen in each column and each queen\n . . . Q can't attack to each other.\n Q . . . The array for this example would look like this: [1, 3, 0, 2]\n . . Q .\n\nSo if we use an array and we verify that each value in the array is different to each\nother we know that at least the queens can't attack each other in horizontal and\nvertical.\n\nAt this point we have it halfway completed and we will treat the chessboard as a\nCartesian plane. Hereinafter we are going to remember basic math, so in the school we\nlearned this formula:\n\n Slope of a line:\n\n y2 - y1\n m = ----------\n x2 - x1\n\nThis formula allow us to get the slope. For the angles 45\u00ba (right diagonal) and 135\u00ba\n(left diagonal) this formula gives us m = 1, and m = -1 respectively.\n\nSee::\nhttps:\/\/www.enotes.com\/homework-help\/write-equation-line-that-hits-origin-45-degree-1474860\n\nThen we have this other formula:\n\nSlope intercept:\n\ny = mx + b\n\nb is where the line crosses the Y axis (to get more information see:\nhttps:\/\/www.mathsisfun.com\/y_intercept.html), if we change the formula to solve for b\nwe would have:\n\ny - mx = b\n\nAnd since we already have the m values for the angles 45\u00ba and 135\u00ba, this formula would\nlook like this:\n\n45\u00ba: y - (1)x = b\n45\u00ba: y - x = b\n\n135\u00ba: y - (-1)x = b\n135\u00ba: y + x = b\n\ny = row\nx = column\n\nApplying these two formulas we can check if a queen in some position is being attacked\nfor another one or vice versa.\n\n\"\"\"\nfrom __future__ import annotations\n\n\ndef depth_first_search(\n possible_board: list[int],\n diagonal_right_collisions: list[int],\n diagonal_left_collisions: list[int],\n boards: list[list[str]],\n n: int,\n) -> None:\n \"\"\"\n >>> boards = []\n >>> depth_first_search([], [], [], boards, 4)\n >>> for board in boards:\n ... print(board)\n ['. Q . . ', '. . . Q ', 'Q . . . ', '. . Q . ']\n ['. . Q . ', 'Q . . . ', '. . . Q ', '. Q . . ']\n \"\"\"\n\n # Get next row in the current board (possible_board) to fill it with a queen\n row = len(possible_board)\n\n # If row is equal to the size of the board it means there are a queen in each row in\n # the current board (possible_board)\n if row == n:\n # We convert the variable possible_board that looks like this: [1, 3, 0, 2] to\n # this: ['. Q . . ', '. . . Q ', 'Q . . . ', '. . Q . ']\n boards.append([\". \" * i + \"Q \" + \". \" * (n - 1 - i) for i in possible_board])\n return\n\n # We iterate each column in the row to find all possible results in each row\n for col in range(n):\n # We apply that we learned previously. First we check that in the current board\n # (possible_board) there are not other same value because if there is it means\n # that there are a collision in vertical. Then we apply the two formulas we\n # learned before:\n #\n # 45\u00ba: y - x = b or 45: row - col = b\n # 135\u00ba: y + x = b or row + col = b.\n #\n # And we verify if the results of this two formulas not exist in their variables\n # respectively. (diagonal_right_collisions, diagonal_left_collisions)\n #\n # If any or these are True it means there is a collision so we continue to the\n # next value in the for loop.\n if (\n col in possible_board\n or row - col in diagonal_right_collisions\n or row + col in diagonal_left_collisions\n ):\n continue\n\n # If it is False we call dfs function again and we update the inputs\n depth_first_search(\n [*possible_board, col],\n [*diagonal_right_collisions, row - col],\n [*diagonal_left_collisions, row + col],\n boards,\n n,\n )\n\n\ndef n_queens_solution(n: int) -> None:\n boards: list[list[str]] = []\n depth_first_search([], [], [], boards, n)\n\n # Print all the boards\n for board in boards:\n for column in board:\n print(column)\n print(\"\")\n\n print(len(boards), \"solutions were found.\")\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n n_queens_solution(4)\n"} +{"Prompt":"Problem source: https:www.hackerrank.comchallengesthepowersumproblem Find the number of ways that a given integer X, can be expressed as the sum of the Nth powers of unique, natural numbers. For example, if X13 and N2. We have to find all combinations of unique squares adding up to 13. The only solution is 2232. Constraints: 1X1000, 2N10. backtrack13, 2, 1, 0, 0 0, 1 backtrack10, 2, 1, 0, 0 0, 1 backtrack10, 3, 1, 0, 0 0, 0 backtrack20, 2, 1, 0, 0 0, 1 backtrack15, 10, 1, 0, 0 0, 0 backtrack16, 2, 1, 0, 0 0, 1 backtrack20, 1, 1, 0, 0 0, 64 If the sum of the powers is equal to neededsum, then we have a solution. If the sum of the powers is less than neededsum, then continue adding powers. If the power of i is less than neededsum, then try with the next power. solve13, 2 1 solve10, 2 1 solve10, 3 0 solve20, 2 1 solve15, 10 0 solve16, 2 1 solve20, 1 Traceback most recent call last: ... ValueError: Invalid input neededsum must be between 1 and 1000, power between 2 and 10. solve10, 5 Traceback most recent call last: ... ValueError: Invalid input neededsum must be between 1 and 1000, power between 2 and 10.","Completions":"def backtrack(\n needed_sum: int,\n power: int,\n current_number: int,\n current_sum: int,\n solutions_count: int,\n) -> tuple[int, int]:\n \"\"\"\n >>> backtrack(13, 2, 1, 0, 0)\n (0, 1)\n >>> backtrack(10, 2, 1, 0, 0)\n (0, 1)\n >>> backtrack(10, 3, 1, 0, 0)\n (0, 0)\n >>> backtrack(20, 2, 1, 0, 0)\n (0, 1)\n >>> backtrack(15, 10, 1, 0, 0)\n (0, 0)\n >>> backtrack(16, 2, 1, 0, 0)\n (0, 1)\n >>> backtrack(20, 1, 1, 0, 0)\n (0, 64)\n \"\"\"\n if current_sum == needed_sum:\n # If the sum of the powers is equal to needed_sum, then we have a solution.\n solutions_count += 1\n return current_sum, solutions_count\n\n i_to_n = current_number**power\n if current_sum + i_to_n <= needed_sum:\n # If the sum of the powers is less than needed_sum, then continue adding powers.\n current_sum += i_to_n\n current_sum, solutions_count = backtrack(\n needed_sum, power, current_number + 1, current_sum, solutions_count\n )\n current_sum -= i_to_n\n if i_to_n < needed_sum:\n # If the power of i is less than needed_sum, then try with the next power.\n current_sum, solutions_count = backtrack(\n needed_sum, power, current_number + 1, current_sum, solutions_count\n )\n return current_sum, solutions_count\n\n\ndef solve(needed_sum: int, power: int) -> int:\n \"\"\"\n >>> solve(13, 2)\n 1\n >>> solve(10, 2)\n 1\n >>> solve(10, 3)\n 0\n >>> solve(20, 2)\n 1\n >>> solve(15, 10)\n 0\n >>> solve(16, 2)\n 1\n >>> solve(20, 1)\n Traceback (most recent call last):\n ...\n ValueError: Invalid input\n needed_sum must be between 1 and 1000, power between 2 and 10.\n >>> solve(-10, 5)\n Traceback (most recent call last):\n ...\n ValueError: Invalid input\n needed_sum must be between 1 and 1000, power between 2 and 10.\n \"\"\"\n if not (1 <= needed_sum <= 1000 and 2 <= power <= 10):\n raise ValueError(\n \"Invalid input\\n\"\n \"needed_sum must be between 1 and 1000, power between 2 and 10.\"\n )\n\n return backtrack(needed_sum, power, 1, 0, 0)[1] # Return the solutions_count\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"This method solves the rat in maze problem. Parameters : maze: A two dimensional matrix of zeros and ones. sourcerow: The row index of the starting point. sourcecolumn: The column index of the starting point. destinationrow: The row index of the destination point. destinationcolumn: The column index of the destination point. Returns: solution: A 2D matrix representing the solution path if it exists. Raises: ValueError: If no solution exists or if the source or destination coordinates are invalid. Description: This method navigates through a maze represented as an n by n matrix, starting from a specified source cell and aiming to reach a destination cell. The maze consists of walls 1s and open paths 0s. By providing custom row and column values, the source and destination cells can be adjusted. maze 0, 1, 0, 1, 1, ... 0, 0, 0, 0, 0, ... 1, 0, 1, 0, 1, ... 0, 0, 1, 0, 0, ... 1, 0, 0, 1, 0 solvemazemaze,0,0,lenmaze1,lenmaze1 doctest: NORMALIZEWHITESPACE 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 0 Note: In the output maze, the zeros 0s represent one of the possible paths from the source to the destination. maze 0, 1, 0, 1, 1, ... 0, 0, 0, 0, 0, ... 0, 0, 0, 0, 1, ... 0, 0, 0, 0, 0, ... 0, 0, 0, 0, 0 solvemazemaze,0,0,lenmaze1,lenmaze1 doctest: NORMALIZEWHITESPACE 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0 maze 0, 0, 0, ... 0, 1, 0, ... 1, 0, 0 solvemazemaze,0,0,lenmaze1,lenmaze1 doctest: NORMALIZEWHITESPACE 0, 0, 0, 1, 1, 0, 1, 1, 0 maze 1, 0, 0, ... 0, 1, 0, ... 1, 0, 0 solvemazemaze,0,1,lenmaze1,lenmaze1 doctest: NORMALIZEWHITESPACE 1, 0, 0, 1, 1, 0, 1, 1, 0 maze 1, 1, 0, 0, 1, 0, 0, 1, ... 1, 0, 1, 0, 0, 1, 1, 1, ... 0, 1, 0, 1, 0, 0, 1, 0, ... 1, 1, 1, 0, 0, 1, 0, 1, ... 0, 1, 0, 0, 1, 0, 1, 1, ... 0, 0, 0, 1, 1, 1, 0, 1, ... 0, 1, 0, 1, 0, 1, 1, 1, ... 1, 1, 0, 0, 0, 0, 0, 1 solvemazemaze,0,2,lenmaze1,2 doctest: NORMALIZEWHITESPACE 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1 maze 1, 0, 0, ... 0, 1, 1, ... 1, 0, 1 solvemazemaze,0,1,lenmaze1,lenmaze1 Traceback most recent call last: ... ValueError: No solution exists! maze 0, 0, ... 1, 1 solvemazemaze,0,0,lenmaze1,lenmaze1 Traceback most recent call last: ... ValueError: No solution exists! maze 0, 1, ... 1, 0 solvemazemaze,2,0,lenmaze1,lenmaze1 Traceback most recent call last: ... ValueError: Invalid source or destination coordinates maze 1, 0, 0, ... 0, 1, 0, ... 1, 0, 0 solvemazemaze,0,1,lenmaze,lenmaze1 Traceback most recent call last: ... ValueError: Invalid source or destination coordinates Check if source and destination coordinates are Invalid. We need to create solution object to save path. This method is recursive starting from i, j and going in one of four directions: up, down, left, right. If a path is found to destination it returns True otherwise it returns False. Parameters maze: A two dimensional matrix of zeros and ones. i, j : coordinates of matrix solutions: A two dimensional matrix of solutions. Returns: Boolean if path is found True, Otherwise False. Final check point. check for already visited and block points. check visited check for directions","Completions":"from __future__ import annotations\n\n\ndef solve_maze(\n maze: list[list[int]],\n source_row: int,\n source_column: int,\n destination_row: int,\n destination_column: int,\n) -> list[list[int]]:\n \"\"\"\n This method solves the \"rat in maze\" problem.\n Parameters :\n - maze: A two dimensional matrix of zeros and ones.\n - source_row: The row index of the starting point.\n - source_column: The column index of the starting point.\n - destination_row: The row index of the destination point.\n - destination_column: The column index of the destination point.\n Returns:\n - solution: A 2D matrix representing the solution path if it exists.\n Raises:\n - ValueError: If no solution exists or if the source or\n destination coordinates are invalid.\n Description:\n This method navigates through a maze represented as an n by n matrix,\n starting from a specified source cell and\n aiming to reach a destination cell.\n The maze consists of walls (1s) and open paths (0s).\n By providing custom row and column values, the source and destination\n cells can be adjusted.\n >>> maze = [[0, 1, 0, 1, 1],\n ... [0, 0, 0, 0, 0],\n ... [1, 0, 1, 0, 1],\n ... [0, 0, 1, 0, 0],\n ... [1, 0, 0, 1, 0]]\n >>> solve_maze(maze,0,0,len(maze)-1,len(maze)-1) # doctest: +NORMALIZE_WHITESPACE\n [[0, 1, 1, 1, 1],\n [0, 0, 0, 0, 1],\n [1, 1, 1, 0, 1],\n [1, 1, 1, 0, 0],\n [1, 1, 1, 1, 0]]\n\n Note:\n In the output maze, the zeros (0s) represent one of the possible\n paths from the source to the destination.\n\n >>> maze = [[0, 1, 0, 1, 1],\n ... [0, 0, 0, 0, 0],\n ... [0, 0, 0, 0, 1],\n ... [0, 0, 0, 0, 0],\n ... [0, 0, 0, 0, 0]]\n >>> solve_maze(maze,0,0,len(maze)-1,len(maze)-1) # doctest: +NORMALIZE_WHITESPACE\n [[0, 1, 1, 1, 1],\n [0, 1, 1, 1, 1],\n [0, 1, 1, 1, 1],\n [0, 1, 1, 1, 1],\n [0, 0, 0, 0, 0]]\n\n >>> maze = [[0, 0, 0],\n ... [0, 1, 0],\n ... [1, 0, 0]]\n >>> solve_maze(maze,0,0,len(maze)-1,len(maze)-1) # doctest: +NORMALIZE_WHITESPACE\n [[0, 0, 0],\n [1, 1, 0],\n [1, 1, 0]]\n\n >>> maze = [[1, 0, 0],\n ... [0, 1, 0],\n ... [1, 0, 0]]\n >>> solve_maze(maze,0,1,len(maze)-1,len(maze)-1) # doctest: +NORMALIZE_WHITESPACE\n [[1, 0, 0],\n [1, 1, 0],\n [1, 1, 0]]\n\n >>> maze = [[1, 1, 0, 0, 1, 0, 0, 1],\n ... [1, 0, 1, 0, 0, 1, 1, 1],\n ... [0, 1, 0, 1, 0, 0, 1, 0],\n ... [1, 1, 1, 0, 0, 1, 0, 1],\n ... [0, 1, 0, 0, 1, 0, 1, 1],\n ... [0, 0, 0, 1, 1, 1, 0, 1],\n ... [0, 1, 0, 1, 0, 1, 1, 1],\n ... [1, 1, 0, 0, 0, 0, 0, 1]]\n >>> solve_maze(maze,0,2,len(maze)-1,2) # doctest: +NORMALIZE_WHITESPACE\n [[1, 1, 0, 0, 1, 1, 1, 1],\n [1, 1, 1, 0, 0, 1, 1, 1],\n [1, 1, 1, 1, 0, 1, 1, 1],\n [1, 1, 1, 0, 0, 1, 1, 1],\n [1, 1, 0, 0, 1, 1, 1, 1],\n [1, 1, 0, 1, 1, 1, 1, 1],\n [1, 1, 0, 1, 1, 1, 1, 1],\n [1, 1, 0, 1, 1, 1, 1, 1]]\n >>> maze = [[1, 0, 0],\n ... [0, 1, 1],\n ... [1, 0, 1]]\n >>> solve_maze(maze,0,1,len(maze)-1,len(maze)-1)\n Traceback (most recent call last):\n ...\n ValueError: No solution exists!\n\n >>> maze = [[0, 0],\n ... [1, 1]]\n >>> solve_maze(maze,0,0,len(maze)-1,len(maze)-1)\n Traceback (most recent call last):\n ...\n ValueError: No solution exists!\n\n >>> maze = [[0, 1],\n ... [1, 0]]\n >>> solve_maze(maze,2,0,len(maze)-1,len(maze)-1)\n Traceback (most recent call last):\n ...\n ValueError: Invalid source or destination coordinates\n\n >>> maze = [[1, 0, 0],\n ... [0, 1, 0],\n ... [1, 0, 0]]\n >>> solve_maze(maze,0,1,len(maze),len(maze)-1)\n Traceback (most recent call last):\n ...\n ValueError: Invalid source or destination coordinates\n \"\"\"\n size = len(maze)\n # Check if source and destination coordinates are Invalid.\n if not (0 <= source_row <= size - 1 and 0 <= source_column <= size - 1) or (\n not (0 <= destination_row <= size - 1 and 0 <= destination_column <= size - 1)\n ):\n raise ValueError(\"Invalid source or destination coordinates\")\n # We need to create solution object to save path.\n solutions = [[1 for _ in range(size)] for _ in range(size)]\n solved = run_maze(\n maze, source_row, source_column, destination_row, destination_column, solutions\n )\n if solved:\n return solutions\n else:\n raise ValueError(\"No solution exists!\")\n\n\ndef run_maze(\n maze: list[list[int]],\n i: int,\n j: int,\n destination_row: int,\n destination_column: int,\n solutions: list[list[int]],\n) -> bool:\n \"\"\"\n This method is recursive starting from (i, j) and going in one of four directions:\n up, down, left, right.\n If a path is found to destination it returns True otherwise it returns False.\n Parameters\n maze: A two dimensional matrix of zeros and ones.\n i, j : coordinates of matrix\n solutions: A two dimensional matrix of solutions.\n Returns:\n Boolean if path is found True, Otherwise False.\n \"\"\"\n size = len(maze)\n # Final check point.\n if i == destination_row and j == destination_column and maze[i][j] == 0:\n solutions[i][j] = 0\n return True\n\n lower_flag = (not i < 0) and (not j < 0) # Check lower bounds\n upper_flag = (i < size) and (j < size) # Check upper bounds\n\n if lower_flag and upper_flag:\n # check for already visited and block points.\n block_flag = (solutions[i][j]) and (not maze[i][j])\n if block_flag:\n # check visited\n solutions[i][j] = 0\n\n # check for directions\n if (\n run_maze(maze, i + 1, j, destination_row, destination_column, solutions)\n or run_maze(\n maze, i, j + 1, destination_row, destination_column, solutions\n )\n or run_maze(\n maze, i - 1, j, destination_row, destination_column, solutions\n )\n or run_maze(\n maze, i, j - 1, destination_row, destination_column, solutions\n )\n ):\n return True\n\n solutions[i][j] = 1\n return False\n return False\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod(optionflags=doctest.NORMALIZE_WHITESPACE)\n"} +{"Prompt":"Given a partially filled 99 2D array, the objective is to fill a 99 square grid with digits numbered 1 to 9, so that every row, column, and and each of the nine 33 subgrids contains all of the digits. This can be solved using Backtracking and is similar to nqueens. We check to see if a cell is safe or not and recursively call the function on the next column to see if it returns True. if yes, we have solved the puzzle. else, we backtrack and place another number in that cell and repeat this process. assigning initial values to the grid a grid with no solution This function checks the grid to see if each row, column, and the 3x3 subgrids contain the digit 'n'. It returns False if it is not 'safe' a duplicate digit is found else returns True if it is 'safe' This function finds an empty location so that we can assign a number for that particular row and column. Takes a partially filledin grid and attempts to assign values to all unassigned locations in such a way to meet the requirements for Sudoku solution nonduplication across rows, columns, and boxes sudokuinitialgrid doctest: NORMALIZEWHITESPACE 3, 1, 6, 5, 7, 8, 4, 9, 2, 5, 2, 9, 1, 3, 4, 7, 6, 8, 4, 8, 7, 6, 2, 9, 5, 3, 1, 2, 6, 3, 4, 1, 5, 9, 8, 7, 9, 7, 4, 8, 6, 3, 1, 2, 5, 8, 5, 1, 7, 9, 2, 6, 4, 3, 1, 3, 8, 9, 4, 7, 2, 5, 6, 6, 9, 2, 3, 5, 1, 8, 7, 4, 7, 4, 5, 2, 8, 6, 3, 1, 9 sudokunosolution is None True If the location is None, then the grid is solved. A function to print the solution in the form of a 9x9 grid make a copy of grid so that you can compare with the unmodified grid","Completions":"from __future__ import annotations\n\nMatrix = list[list[int]]\n\n# assigning initial values to the grid\ninitial_grid: Matrix = [\n [3, 0, 6, 5, 0, 8, 4, 0, 0],\n [5, 2, 0, 0, 0, 0, 0, 0, 0],\n [0, 8, 7, 0, 0, 0, 0, 3, 1],\n [0, 0, 3, 0, 1, 0, 0, 8, 0],\n [9, 0, 0, 8, 6, 3, 0, 0, 5],\n [0, 5, 0, 0, 9, 0, 6, 0, 0],\n [1, 3, 0, 0, 0, 0, 2, 5, 0],\n [0, 0, 0, 0, 0, 0, 0, 7, 4],\n [0, 0, 5, 2, 0, 6, 3, 0, 0],\n]\n\n# a grid with no solution\nno_solution: Matrix = [\n [5, 0, 6, 5, 0, 8, 4, 0, 3],\n [5, 2, 0, 0, 0, 0, 0, 0, 2],\n [1, 8, 7, 0, 0, 0, 0, 3, 1],\n [0, 0, 3, 0, 1, 0, 0, 8, 0],\n [9, 0, 0, 8, 6, 3, 0, 0, 5],\n [0, 5, 0, 0, 9, 0, 6, 0, 0],\n [1, 3, 0, 0, 0, 0, 2, 5, 0],\n [0, 0, 0, 0, 0, 0, 0, 7, 4],\n [0, 0, 5, 2, 0, 6, 3, 0, 0],\n]\n\n\ndef is_safe(grid: Matrix, row: int, column: int, n: int) -> bool:\n \"\"\"\n This function checks the grid to see if each row,\n column, and the 3x3 subgrids contain the digit 'n'.\n It returns False if it is not 'safe' (a duplicate digit\n is found) else returns True if it is 'safe'\n \"\"\"\n for i in range(9):\n if n in {grid[row][i], grid[i][column]}:\n return False\n\n for i in range(3):\n for j in range(3):\n if grid[(row - row % 3) + i][(column - column % 3) + j] == n:\n return False\n\n return True\n\n\ndef find_empty_location(grid: Matrix) -> tuple[int, int] | None:\n \"\"\"\n This function finds an empty location so that we can assign a number\n for that particular row and column.\n \"\"\"\n for i in range(9):\n for j in range(9):\n if grid[i][j] == 0:\n return i, j\n return None\n\n\ndef sudoku(grid: Matrix) -> Matrix | None:\n \"\"\"\n Takes a partially filled-in grid and attempts to assign values to\n all unassigned locations in such a way to meet the requirements\n for Sudoku solution (non-duplication across rows, columns, and boxes)\n\n >>> sudoku(initial_grid) # doctest: +NORMALIZE_WHITESPACE\n [[3, 1, 6, 5, 7, 8, 4, 9, 2],\n [5, 2, 9, 1, 3, 4, 7, 6, 8],\n [4, 8, 7, 6, 2, 9, 5, 3, 1],\n [2, 6, 3, 4, 1, 5, 9, 8, 7],\n [9, 7, 4, 8, 6, 3, 1, 2, 5],\n [8, 5, 1, 7, 9, 2, 6, 4, 3],\n [1, 3, 8, 9, 4, 7, 2, 5, 6],\n [6, 9, 2, 3, 5, 1, 8, 7, 4],\n [7, 4, 5, 2, 8, 6, 3, 1, 9]]\n >>> sudoku(no_solution) is None\n True\n \"\"\"\n if location := find_empty_location(grid):\n row, column = location\n else:\n # If the location is ``None``, then the grid is solved.\n return grid\n\n for digit in range(1, 10):\n if is_safe(grid, row, column, digit):\n grid[row][column] = digit\n\n if sudoku(grid) is not None:\n return grid\n\n grid[row][column] = 0\n\n return None\n\n\ndef print_solution(grid: Matrix) -> None:\n \"\"\"\n A function to print the solution in the form\n of a 9x9 grid\n \"\"\"\n for row in grid:\n for cell in row:\n print(cell, end=\" \")\n print()\n\n\nif __name__ == \"__main__\":\n # make a copy of grid so that you can compare with the unmodified grid\n for example_grid in (initial_grid, no_solution):\n print(\"\\nExample grid:\\n\" + \"=\" * 20)\n print_solution(example_grid)\n print(\"\\nExample grid solution:\")\n solution = sudoku(example_grid)\n if solution is not None:\n print_solution(solution)\n else:\n print(\"Cannot find a solution.\")\n"} +{"Prompt":"The sumofsubsetsproblem states that a set of nonnegative integers, and a value M, determine all possible subsets of the given set whose summation sum equal to given M. Summation of the chosen numbers must be equal to given number M and one number can be used only once. Creates a state space tree to iterate through each branch using DFS. It terminates the branching of a node when any of the two conditions given below satisfy. This algorithm follows depthfistsearch and backtracks when the node is not branchable. remove the comment to take an input from the user printEnter the elements nums listmapint, input.split printEnter maxsum sum maxsum intinput","Completions":"from __future__ import annotations\n\n\ndef generate_sum_of_subsets_soln(nums: list[int], max_sum: int) -> list[list[int]]:\n result: list[list[int]] = []\n path: list[int] = []\n num_index = 0\n remaining_nums_sum = sum(nums)\n create_state_space_tree(nums, max_sum, num_index, path, result, remaining_nums_sum)\n return result\n\n\ndef create_state_space_tree(\n nums: list[int],\n max_sum: int,\n num_index: int,\n path: list[int],\n result: list[list[int]],\n remaining_nums_sum: int,\n) -> None:\n \"\"\"\n Creates a state space tree to iterate through each branch using DFS.\n It terminates the branching of a node when any of the two conditions\n given below satisfy.\n This algorithm follows depth-fist-search and backtracks when the node is not\n branchable.\n\n \"\"\"\n if sum(path) > max_sum or (remaining_nums_sum + sum(path)) < max_sum:\n return\n if sum(path) == max_sum:\n result.append(path)\n return\n for index in range(num_index, len(nums)):\n create_state_space_tree(\n nums,\n max_sum,\n index + 1,\n [*path, nums[index]],\n result,\n remaining_nums_sum - nums[index],\n )\n\n\n\"\"\"\nremove the comment to take an input from the user\n\nprint(\"Enter the elements\")\nnums = list(map(int, input().split()))\nprint(\"Enter max_sum sum\")\nmax_sum = int(input())\n\n\"\"\"\nnums = [3, 34, 4, 12, 5, 2]\nmax_sum = 9\nresult = generate_sum_of_subsets_soln(nums, max_sum)\nprint(*result)\n"} +{"Prompt":"Author : Alexander Pantyukhin Date : November 24, 2022 Task: Given an m x n grid of characters board and a string word, return true if word exists in the grid. The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once. Example: Matrix: ABCE SFCS ADEE Word: ABCCED Result: True Implementation notes: Use backtracking approach. At each point, check all neighbors to try to find the next letter of the word. leetcode: https:leetcode.comproblemswordsearch Returns the hash key of matrix indexes. getpointkey10, 20, 1, 0 200 Return True if it's possible to search the word suffix starting from the wordindex. exitswordA, B, 0, 0, 0, set False wordexistsA,B,C,E,S,F,C,S,A,D,E,E, ABCCED True wordexistsA,B,C,E,S,F,C,S,A,D,E,E, SEE True wordexistsA,B,C,E,S,F,C,S,A,D,E,E, ABCB False wordexistsA, A True wordexistsB, A, A, A, A, A, A, B, A, ABB False wordexistsA, 123 Traceback most recent call last: ... ValueError: The word parameter should be a string of length greater than 0. wordexistsA, Traceback most recent call last: ... ValueError: The word parameter should be a string of length greater than 0. wordexists, AB Traceback most recent call last: ... ValueError: The board should be a non empty matrix of single chars strings. wordexists, AB Traceback most recent call last: ... ValueError: The board should be a non empty matrix of single chars strings. wordexistsA, 21, AB Traceback most recent call last: ... ValueError: The board should be a non empty matrix of single chars strings. Validate board Validate word","Completions":"def get_point_key(len_board: int, len_board_column: int, row: int, column: int) -> int:\n \"\"\"\n Returns the hash key of matrix indexes.\n\n >>> get_point_key(10, 20, 1, 0)\n 200\n \"\"\"\n\n return len_board * len_board_column * row + column\n\n\ndef exits_word(\n board: list[list[str]],\n word: str,\n row: int,\n column: int,\n word_index: int,\n visited_points_set: set[int],\n) -> bool:\n \"\"\"\n Return True if it's possible to search the word suffix\n starting from the word_index.\n\n >>> exits_word([[\"A\"]], \"B\", 0, 0, 0, set())\n False\n \"\"\"\n\n if board[row][column] != word[word_index]:\n return False\n\n if word_index == len(word) - 1:\n return True\n\n traverts_directions = [(0, 1), (0, -1), (-1, 0), (1, 0)]\n len_board = len(board)\n len_board_column = len(board[0])\n for direction in traverts_directions:\n next_i = row + direction[0]\n next_j = column + direction[1]\n if not (0 <= next_i < len_board and 0 <= next_j < len_board_column):\n continue\n\n key = get_point_key(len_board, len_board_column, next_i, next_j)\n if key in visited_points_set:\n continue\n\n visited_points_set.add(key)\n if exits_word(board, word, next_i, next_j, word_index + 1, visited_points_set):\n return True\n\n visited_points_set.remove(key)\n\n return False\n\n\ndef word_exists(board: list[list[str]], word: str) -> bool:\n \"\"\"\n >>> word_exists([[\"A\",\"B\",\"C\",\"E\"],[\"S\",\"F\",\"C\",\"S\"],[\"A\",\"D\",\"E\",\"E\"]], \"ABCCED\")\n True\n >>> word_exists([[\"A\",\"B\",\"C\",\"E\"],[\"S\",\"F\",\"C\",\"S\"],[\"A\",\"D\",\"E\",\"E\"]], \"SEE\")\n True\n >>> word_exists([[\"A\",\"B\",\"C\",\"E\"],[\"S\",\"F\",\"C\",\"S\"],[\"A\",\"D\",\"E\",\"E\"]], \"ABCB\")\n False\n >>> word_exists([[\"A\"]], \"A\")\n True\n >>> word_exists([[\"B\", \"A\", \"A\"], [\"A\", \"A\", \"A\"], [\"A\", \"B\", \"A\"]], \"ABB\")\n False\n >>> word_exists([[\"A\"]], 123)\n Traceback (most recent call last):\n ...\n ValueError: The word parameter should be a string of length greater than 0.\n >>> word_exists([[\"A\"]], \"\")\n Traceback (most recent call last):\n ...\n ValueError: The word parameter should be a string of length greater than 0.\n >>> word_exists([[]], \"AB\")\n Traceback (most recent call last):\n ...\n ValueError: The board should be a non empty matrix of single chars strings.\n >>> word_exists([], \"AB\")\n Traceback (most recent call last):\n ...\n ValueError: The board should be a non empty matrix of single chars strings.\n >>> word_exists([[\"A\"], [21]], \"AB\")\n Traceback (most recent call last):\n ...\n ValueError: The board should be a non empty matrix of single chars strings.\n \"\"\"\n\n # Validate board\n board_error_message = (\n \"The board should be a non empty matrix of single chars strings.\"\n )\n\n len_board = len(board)\n if not isinstance(board, list) or len(board) == 0:\n raise ValueError(board_error_message)\n\n for row in board:\n if not isinstance(row, list) or len(row) == 0:\n raise ValueError(board_error_message)\n\n for item in row:\n if not isinstance(item, str) or len(item) != 1:\n raise ValueError(board_error_message)\n\n # Validate word\n if not isinstance(word, str) or len(word) == 0:\n raise ValueError(\n \"The word parameter should be a string of length greater than 0.\"\n )\n\n len_board_column = len(board[0])\n for i in range(len_board):\n for j in range(len_board_column):\n if exits_word(\n board, word, i, j, 0, {get_point_key(len_board, len_board_column, i, j)}\n ):\n return True\n\n return False\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"https:www.tutorialspoint.compython3bitwiseoperatorsexample.htm Take in 2 integers, convert them to binary, return a binary number that is the result of a binary and operation on the integers provided. binaryand25, 32 '0b000000' binaryand37, 50 '0b100000' binaryand21, 30 '0b10100' binaryand58, 73 '0b0001000' binaryand0, 255 '0b00000000' binaryand256, 256 '0b100000000' binaryand0, 1 Traceback most recent call last: ... ValueError: the value of both inputs must be positive binaryand0, 1.1 Traceback most recent call last: ... TypeError: 'float' object cannot be interpreted as an integer binaryand0, 1 Traceback most recent call last: ... TypeError: '' not supported between instances of 'str' and 'int'","Completions":"# https:\/\/www.tutorialspoint.com\/python3\/bitwise_operators_example.htm\n\n\ndef binary_and(a: int, b: int) -> str:\n \"\"\"\n Take in 2 integers, convert them to binary,\n return a binary number that is the\n result of a binary and operation on the integers provided.\n\n >>> binary_and(25, 32)\n '0b000000'\n >>> binary_and(37, 50)\n '0b100000'\n >>> binary_and(21, 30)\n '0b10100'\n >>> binary_and(58, 73)\n '0b0001000'\n >>> binary_and(0, 255)\n '0b00000000'\n >>> binary_and(256, 256)\n '0b100000000'\n >>> binary_and(0, -1)\n Traceback (most recent call last):\n ...\n ValueError: the value of both inputs must be positive\n >>> binary_and(0, 1.1)\n Traceback (most recent call last):\n ...\n TypeError: 'float' object cannot be interpreted as an integer\n >>> binary_and(\"0\", \"1\")\n Traceback (most recent call last):\n ...\n TypeError: '<' not supported between instances of 'str' and 'int'\n \"\"\"\n if a < 0 or b < 0:\n raise ValueError(\"the value of both inputs must be positive\")\n\n a_binary = str(bin(a))[2:] # remove the leading \"0b\"\n b_binary = str(bin(b))[2:] # remove the leading \"0b\"\n\n max_len = max(len(a_binary), len(b_binary))\n\n return \"0b\" + \"\".join(\n str(int(char_a == \"1\" and char_b == \"1\"))\n for char_a, char_b in zip(a_binary.zfill(max_len), b_binary.zfill(max_len))\n )\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Find binary coded decimal bcd of integer base 10. Each digit of the number is represented by a 4bit binary. Example: binarycodeddecimal2 '0b0000' binarycodeddecimal1 '0b0000' binarycodeddecimal0 '0b0000' binarycodeddecimal3 '0b0011' binarycodeddecimal2 '0b0010' binarycodeddecimal12 '0b00010010' binarycodeddecimal987 '0b100110000111'","Completions":"def binary_coded_decimal(number: int) -> str:\n \"\"\"\n Find binary coded decimal (bcd) of integer base 10.\n Each digit of the number is represented by a 4-bit binary.\n Example:\n >>> binary_coded_decimal(-2)\n '0b0000'\n >>> binary_coded_decimal(-1)\n '0b0000'\n >>> binary_coded_decimal(0)\n '0b0000'\n >>> binary_coded_decimal(3)\n '0b0011'\n >>> binary_coded_decimal(2)\n '0b0010'\n >>> binary_coded_decimal(12)\n '0b00010010'\n >>> binary_coded_decimal(987)\n '0b100110000111'\n \"\"\"\n return \"0b\" + \"\".join(\n str(bin(int(digit)))[2:].zfill(4) for digit in str(max(0, number))\n )\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Take in 1 integer, return a number that is the number of 1's in binary representation of that number. binarycountsetbits25 3 binarycountsetbits36 2 binarycountsetbits16 1 binarycountsetbits58 4 binarycountsetbits4294967295 32 binarycountsetbits0 0 binarycountsetbits10 Traceback most recent call last: ... ValueError: Input value must be a positive integer binarycountsetbits0.8 Traceback most recent call last: ... TypeError: Input value must be a 'int' type binarycountsetbits0 Traceback most recent call last: ... TypeError: '' not supported between instances of 'str' and 'int'","Completions":"def binary_count_setbits(a: int) -> int:\n \"\"\"\n Take in 1 integer, return a number that is\n the number of 1's in binary representation of that number.\n\n >>> binary_count_setbits(25)\n 3\n >>> binary_count_setbits(36)\n 2\n >>> binary_count_setbits(16)\n 1\n >>> binary_count_setbits(58)\n 4\n >>> binary_count_setbits(4294967295)\n 32\n >>> binary_count_setbits(0)\n 0\n >>> binary_count_setbits(-10)\n Traceback (most recent call last):\n ...\n ValueError: Input value must be a positive integer\n >>> binary_count_setbits(0.8)\n Traceback (most recent call last):\n ...\n TypeError: Input value must be a 'int' type\n >>> binary_count_setbits(\"0\")\n Traceback (most recent call last):\n ...\n TypeError: '<' not supported between instances of 'str' and 'int'\n \"\"\"\n if a < 0:\n raise ValueError(\"Input value must be a positive integer\")\n elif isinstance(a, float):\n raise TypeError(\"Input value must be a 'int' type\")\n return bin(a).count(\"1\")\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Take in 1 integer, return a number that is the number of trailing zeros in binary representation of that number. binarycounttrailingzeros25 0 binarycounttrailingzeros36 2 binarycounttrailingzeros16 4 binarycounttrailingzeros58 1 binarycounttrailingzeros4294967296 32 binarycounttrailingzeros0 0 binarycounttrailingzeros10 Traceback most recent call last: ... ValueError: Input value must be a positive integer binarycounttrailingzeros0.8 Traceback most recent call last: ... TypeError: Input value must be a 'int' type binarycounttrailingzeros0 Traceback most recent call last: ... TypeError: '' not supported between instances of 'str' and 'int'","Completions":"from math import log2\n\n\ndef binary_count_trailing_zeros(a: int) -> int:\n \"\"\"\n Take in 1 integer, return a number that is\n the number of trailing zeros in binary representation of that number.\n\n >>> binary_count_trailing_zeros(25)\n 0\n >>> binary_count_trailing_zeros(36)\n 2\n >>> binary_count_trailing_zeros(16)\n 4\n >>> binary_count_trailing_zeros(58)\n 1\n >>> binary_count_trailing_zeros(4294967296)\n 32\n >>> binary_count_trailing_zeros(0)\n 0\n >>> binary_count_trailing_zeros(-10)\n Traceback (most recent call last):\n ...\n ValueError: Input value must be a positive integer\n >>> binary_count_trailing_zeros(0.8)\n Traceback (most recent call last):\n ...\n TypeError: Input value must be a 'int' type\n >>> binary_count_trailing_zeros(\"0\")\n Traceback (most recent call last):\n ...\n TypeError: '<' not supported between instances of 'str' and 'int'\n \"\"\"\n if a < 0:\n raise ValueError(\"Input value must be a positive integer\")\n elif isinstance(a, float):\n raise TypeError(\"Input value must be a 'int' type\")\n return 0 if (a == 0) else int(log2(a & -a))\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"https:www.tutorialspoint.compython3bitwiseoperatorsexample.htm Take in 2 integers, convert them to binary, and return a binary number that is the result of a binary or operation on the integers provided. binaryor25, 32 '0b111001' binaryor37, 50 '0b110111' binaryor21, 30 '0b11111' binaryor58, 73 '0b1111011' binaryor0, 255 '0b11111111' binaryor0, 256 '0b100000000' binaryor0, 1 Traceback most recent call last: ... ValueError: the value of both inputs must be positive binaryor0, 1.1 Traceback most recent call last: ... TypeError: 'float' object cannot be interpreted as an integer binaryor0, 1 Traceback most recent call last: ... TypeError: '' not supported between instances of 'str' and 'int'","Completions":"# https:\/\/www.tutorialspoint.com\/python3\/bitwise_operators_example.htm\n\n\ndef binary_or(a: int, b: int) -> str:\n \"\"\"\n Take in 2 integers, convert them to binary, and return a binary number that is the\n result of a binary or operation on the integers provided.\n\n >>> binary_or(25, 32)\n '0b111001'\n >>> binary_or(37, 50)\n '0b110111'\n >>> binary_or(21, 30)\n '0b11111'\n >>> binary_or(58, 73)\n '0b1111011'\n >>> binary_or(0, 255)\n '0b11111111'\n >>> binary_or(0, 256)\n '0b100000000'\n >>> binary_or(0, -1)\n Traceback (most recent call last):\n ...\n ValueError: the value of both inputs must be positive\n >>> binary_or(0, 1.1)\n Traceback (most recent call last):\n ...\n TypeError: 'float' object cannot be interpreted as an integer\n >>> binary_or(\"0\", \"1\")\n Traceback (most recent call last):\n ...\n TypeError: '<' not supported between instances of 'str' and 'int'\n \"\"\"\n if a < 0 or b < 0:\n raise ValueError(\"the value of both inputs must be positive\")\n a_binary = str(bin(a))[2:] # remove the leading \"0b\"\n b_binary = str(bin(b))[2:]\n max_len = max(len(a_binary), len(b_binary))\n return \"0b\" + \"\".join(\n str(int(\"1\" in (char_a, char_b)))\n for char_a, char_b in zip(a_binary.zfill(max_len), b_binary.zfill(max_len))\n )\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Information on binary shifts: https:docs.python.org3librarystdtypes.htmlbitwiseoperationsonintegertypes https:www.interviewcake.comconceptjavabitshift Take in 2 positive integers. 'number' is the integer to be logically left shifted 'shiftamount' times. i.e. number shiftamount Return the shifted binary representation. logicalleftshift0, 1 '0b00' logicalleftshift1, 1 '0b10' logicalleftshift1, 5 '0b100000' logicalleftshift17, 2 '0b1000100' logicalleftshift1983, 4 '0b111101111110000' logicalleftshift1, 1 Traceback most recent call last: ... ValueError: both inputs must be positive integers Take in positive 2 integers. 'number' is the integer to be logically right shifted 'shiftamount' times. i.e. number shiftamount Return the shifted binary representation. logicalrightshift0, 1 '0b0' logicalrightshift1, 1 '0b0' logicalrightshift1, 5 '0b0' logicalrightshift17, 2 '0b100' logicalrightshift1983, 4 '0b1111011' logicalrightshift1, 1 Traceback most recent call last: ... ValueError: both inputs must be positive integers Take in 2 integers. 'number' is the integer to be arithmetically right shifted 'shiftamount' times. i.e. number shiftamount Return the shifted binary representation. arithmeticrightshift0, 1 '0b00' arithmeticrightshift1, 1 '0b00' arithmeticrightshift1, 1 '0b11' arithmeticrightshift17, 2 '0b000100' arithmeticrightshift17, 2 '0b111011' arithmeticrightshift1983, 4 '0b111110000100'","Completions":"# Information on binary shifts:\n# https:\/\/docs.python.org\/3\/library\/stdtypes.html#bitwise-operations-on-integer-types\n# https:\/\/www.interviewcake.com\/concept\/java\/bit-shift\n\n\ndef logical_left_shift(number: int, shift_amount: int) -> str:\n \"\"\"\n Take in 2 positive integers.\n 'number' is the integer to be logically left shifted 'shift_amount' times.\n i.e. (number << shift_amount)\n Return the shifted binary representation.\n\n >>> logical_left_shift(0, 1)\n '0b00'\n >>> logical_left_shift(1, 1)\n '0b10'\n >>> logical_left_shift(1, 5)\n '0b100000'\n >>> logical_left_shift(17, 2)\n '0b1000100'\n >>> logical_left_shift(1983, 4)\n '0b111101111110000'\n >>> logical_left_shift(1, -1)\n Traceback (most recent call last):\n ...\n ValueError: both inputs must be positive integers\n \"\"\"\n if number < 0 or shift_amount < 0:\n raise ValueError(\"both inputs must be positive integers\")\n\n binary_number = str(bin(number))\n binary_number += \"0\" * shift_amount\n return binary_number\n\n\ndef logical_right_shift(number: int, shift_amount: int) -> str:\n \"\"\"\n Take in positive 2 integers.\n 'number' is the integer to be logically right shifted 'shift_amount' times.\n i.e. (number >>> shift_amount)\n Return the shifted binary representation.\n\n >>> logical_right_shift(0, 1)\n '0b0'\n >>> logical_right_shift(1, 1)\n '0b0'\n >>> logical_right_shift(1, 5)\n '0b0'\n >>> logical_right_shift(17, 2)\n '0b100'\n >>> logical_right_shift(1983, 4)\n '0b1111011'\n >>> logical_right_shift(1, -1)\n Traceback (most recent call last):\n ...\n ValueError: both inputs must be positive integers\n \"\"\"\n if number < 0 or shift_amount < 0:\n raise ValueError(\"both inputs must be positive integers\")\n\n binary_number = str(bin(number))[2:]\n if shift_amount >= len(binary_number):\n return \"0b0\"\n shifted_binary_number = binary_number[: len(binary_number) - shift_amount]\n return \"0b\" + shifted_binary_number\n\n\ndef arithmetic_right_shift(number: int, shift_amount: int) -> str:\n \"\"\"\n Take in 2 integers.\n 'number' is the integer to be arithmetically right shifted 'shift_amount' times.\n i.e. (number >> shift_amount)\n Return the shifted binary representation.\n\n >>> arithmetic_right_shift(0, 1)\n '0b00'\n >>> arithmetic_right_shift(1, 1)\n '0b00'\n >>> arithmetic_right_shift(-1, 1)\n '0b11'\n >>> arithmetic_right_shift(17, 2)\n '0b000100'\n >>> arithmetic_right_shift(-17, 2)\n '0b111011'\n >>> arithmetic_right_shift(-1983, 4)\n '0b111110000100'\n \"\"\"\n if number >= 0: # Get binary representation of positive number\n binary_number = \"0\" + str(bin(number)).strip(\"-\")[2:]\n else: # Get binary (2's complement) representation of negative number\n binary_number_length = len(bin(number)[3:]) # Find 2's complement of number\n binary_number = bin(abs(number) - (1 << binary_number_length))[3:]\n binary_number = (\n \"1\" + \"0\" * (binary_number_length - len(binary_number)) + binary_number\n )\n\n if shift_amount >= len(binary_number):\n return \"0b\" + binary_number[0] * len(binary_number)\n return (\n \"0b\"\n + binary_number[0] * shift_amount\n + binary_number[: len(binary_number) - shift_amount]\n )\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Information on 2's complement: https:en.wikipedia.orgwikiTwo27scomplement Take in a negative integer 'number'. Return the two's complement representation of 'number'. twoscomplement0 '0b0' twoscomplement1 '0b11' twoscomplement5 '0b1011' twoscomplement17 '0b101111' twoscomplement207 '0b100110001' twoscomplement1 Traceback most recent call last: ... ValueError: input must be a negative integer","Completions":"# Information on 2's complement: https:\/\/en.wikipedia.org\/wiki\/Two%27s_complement\n\n\ndef twos_complement(number: int) -> str:\n \"\"\"\n Take in a negative integer 'number'.\n Return the two's complement representation of 'number'.\n\n >>> twos_complement(0)\n '0b0'\n >>> twos_complement(-1)\n '0b11'\n >>> twos_complement(-5)\n '0b1011'\n >>> twos_complement(-17)\n '0b101111'\n >>> twos_complement(-207)\n '0b100110001'\n >>> twos_complement(1)\n Traceback (most recent call last):\n ...\n ValueError: input must be a negative integer\n \"\"\"\n if number > 0:\n raise ValueError(\"input must be a negative integer\")\n binary_number_length = len(bin(number)[3:])\n twos_complement_number = bin(abs(number) - (1 << binary_number_length))[3:]\n twos_complement_number = (\n (\n \"1\"\n + \"0\" * (binary_number_length - len(twos_complement_number))\n + twos_complement_number\n )\n if number < 0\n else \"0\"\n )\n return \"0b\" + twos_complement_number\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"https:www.tutorialspoint.compython3bitwiseoperatorsexample.htm Take in 2 integers, convert them to binary, return a binary number that is the result of a binary xor operation on the integers provided. binaryxor25, 32 '0b111001' binaryxor37, 50 '0b010111' binaryxor21, 30 '0b01011' binaryxor58, 73 '0b1110011' binaryxor0, 255 '0b11111111' binaryxor256, 256 '0b000000000' binaryxor0, 1 Traceback most recent call last: ... ValueError: the value of both inputs must be positive binaryxor0, 1.1 Traceback most recent call last: ... TypeError: 'float' object cannot be interpreted as an integer binaryxor0, 1 Traceback most recent call last: ... TypeError: '' not supported between instances of 'str' and 'int'","Completions":"# https:\/\/www.tutorialspoint.com\/python3\/bitwise_operators_example.htm\n\n\ndef binary_xor(a: int, b: int) -> str:\n \"\"\"\n Take in 2 integers, convert them to binary,\n return a binary number that is the\n result of a binary xor operation on the integers provided.\n\n >>> binary_xor(25, 32)\n '0b111001'\n >>> binary_xor(37, 50)\n '0b010111'\n >>> binary_xor(21, 30)\n '0b01011'\n >>> binary_xor(58, 73)\n '0b1110011'\n >>> binary_xor(0, 255)\n '0b11111111'\n >>> binary_xor(256, 256)\n '0b000000000'\n >>> binary_xor(0, -1)\n Traceback (most recent call last):\n ...\n ValueError: the value of both inputs must be positive\n >>> binary_xor(0, 1.1)\n Traceback (most recent call last):\n ...\n TypeError: 'float' object cannot be interpreted as an integer\n >>> binary_xor(\"0\", \"1\")\n Traceback (most recent call last):\n ...\n TypeError: '<' not supported between instances of 'str' and 'int'\n \"\"\"\n if a < 0 or b < 0:\n raise ValueError(\"the value of both inputs must be positive\")\n\n a_binary = str(bin(a))[2:] # remove the leading \"0b\"\n b_binary = str(bin(b))[2:] # remove the leading \"0b\"\n\n max_len = max(len(a_binary), len(b_binary))\n\n return \"0b\" + \"\".join(\n str(int(char_a != char_b))\n for char_a, char_b in zip(a_binary.zfill(max_len), b_binary.zfill(max_len))\n )\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Calculates the sum of two nonnegative integers using bitwise operators Wikipedia explanation: https:en.wikipedia.orgwikiBinarynumber bitwiseadditionrecursive4, 5 9 bitwiseadditionrecursive8, 9 17 bitwiseadditionrecursive0, 4 4 bitwiseadditionrecursive4.5, 9 Traceback most recent call last: ... TypeError: Both arguments MUST be integers! bitwiseadditionrecursive'4', 9 Traceback most recent call last: ... TypeError: Both arguments MUST be integers! bitwiseadditionrecursive'4.5', 9 Traceback most recent call last: ... TypeError: Both arguments MUST be integers! bitwiseadditionrecursive1, 9 Traceback most recent call last: ... ValueError: Both arguments MUST be nonnegative! bitwiseadditionrecursive1, 9 Traceback most recent call last: ... ValueError: Both arguments MUST be nonnegative!","Completions":"def bitwise_addition_recursive(number: int, other_number: int) -> int:\n \"\"\"\n >>> bitwise_addition_recursive(4, 5)\n 9\n >>> bitwise_addition_recursive(8, 9)\n 17\n >>> bitwise_addition_recursive(0, 4)\n 4\n >>> bitwise_addition_recursive(4.5, 9)\n Traceback (most recent call last):\n ...\n TypeError: Both arguments MUST be integers!\n >>> bitwise_addition_recursive('4', 9)\n Traceback (most recent call last):\n ...\n TypeError: Both arguments MUST be integers!\n >>> bitwise_addition_recursive('4.5', 9)\n Traceback (most recent call last):\n ...\n TypeError: Both arguments MUST be integers!\n >>> bitwise_addition_recursive(-1, 9)\n Traceback (most recent call last):\n ...\n ValueError: Both arguments MUST be non-negative!\n >>> bitwise_addition_recursive(1, -9)\n Traceback (most recent call last):\n ...\n ValueError: Both arguments MUST be non-negative!\n \"\"\"\n\n if not isinstance(number, int) or not isinstance(other_number, int):\n raise TypeError(\"Both arguments MUST be integers!\")\n\n if number < 0 or other_number < 0:\n raise ValueError(\"Both arguments MUST be non-negative!\")\n\n bitwise_sum = number ^ other_number\n carry = number & other_number\n\n if carry == 0:\n return bitwise_sum\n\n return bitwise_addition_recursive(bitwise_sum, carry << 1)\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Count the number of set bits in a 32 bit integer using Brian Kernighan's way. Ref https:graphics.stanford.eduseanderbithacks.htmlCountBitsSetKernighan get1scount25 3 get1scount37 3 get1scount21 3 get1scount58 4 get1scount0 0 get1scount256 1 get1scount1 Traceback most recent call last: ... ValueError: Input must be a nonnegative integer get1scount0.8 Traceback most recent call last: ... ValueError: Input must be a nonnegative integer get1scount25 Traceback most recent call last: ... ValueError: Input must be a nonnegative integer This way we arrive at next set bit next 1 instead of looping through each bit and checking for 1s hence the loop won't run 32 times it will only run the number of 1 times","Completions":"def get_1s_count(number: int) -> int:\n \"\"\"\n Count the number of set bits in a 32 bit integer using Brian Kernighan's way.\n Ref - https:\/\/graphics.stanford.edu\/~seander\/bithacks.html#CountBitsSetKernighan\n >>> get_1s_count(25)\n 3\n >>> get_1s_count(37)\n 3\n >>> get_1s_count(21)\n 3\n >>> get_1s_count(58)\n 4\n >>> get_1s_count(0)\n 0\n >>> get_1s_count(256)\n 1\n >>> get_1s_count(-1)\n Traceback (most recent call last):\n ...\n ValueError: Input must be a non-negative integer\n >>> get_1s_count(0.8)\n Traceback (most recent call last):\n ...\n ValueError: Input must be a non-negative integer\n >>> get_1s_count(\"25\")\n Traceback (most recent call last):\n ...\n ValueError: Input must be a non-negative integer\n \"\"\"\n if not isinstance(number, int) or number < 0:\n raise ValueError(\"Input must be a non-negative integer\")\n\n count = 0\n while number:\n # This way we arrive at next set bit (next 1) instead of looping\n # through each bit and checking for 1s hence the\n # loop won't run 32 times it will only run the number of `1` times\n number &= number - 1\n count += 1\n return count\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Count the number of set bits in a 32 bit integer getsetbitscountusingbriankernighansalgorithm25 3 getsetbitscountusingbriankernighansalgorithm37 3 getsetbitscountusingbriankernighansalgorithm21 3 getsetbitscountusingbriankernighansalgorithm58 4 getsetbitscountusingbriankernighansalgorithm0 0 getsetbitscountusingbriankernighansalgorithm256 1 getsetbitscountusingbriankernighansalgorithm1 Traceback most recent call last: ... ValueError: the value of input must not be negative Count the number of set bits in a 32 bit integer getsetbitscountusingmodulooperator25 3 getsetbitscountusingmodulooperator37 3 getsetbitscountusingmodulooperator21 3 getsetbitscountusingmodulooperator58 4 getsetbitscountusingmodulooperator0 0 getsetbitscountusingmodulooperator256 1 getsetbitscountusingmodulooperator1 Traceback most recent call last: ... ValueError: the value of input must not be negative Benchmark code for comparing 2 functions, with different length int values. Brian Kernighan's algorithm is consistently faster than using modulooperator.","Completions":"from timeit import timeit\n\n\ndef get_set_bits_count_using_brian_kernighans_algorithm(number: int) -> int:\n \"\"\"\n Count the number of set bits in a 32 bit integer\n >>> get_set_bits_count_using_brian_kernighans_algorithm(25)\n 3\n >>> get_set_bits_count_using_brian_kernighans_algorithm(37)\n 3\n >>> get_set_bits_count_using_brian_kernighans_algorithm(21)\n 3\n >>> get_set_bits_count_using_brian_kernighans_algorithm(58)\n 4\n >>> get_set_bits_count_using_brian_kernighans_algorithm(0)\n 0\n >>> get_set_bits_count_using_brian_kernighans_algorithm(256)\n 1\n >>> get_set_bits_count_using_brian_kernighans_algorithm(-1)\n Traceback (most recent call last):\n ...\n ValueError: the value of input must not be negative\n \"\"\"\n if number < 0:\n raise ValueError(\"the value of input must not be negative\")\n result = 0\n while number:\n number &= number - 1\n result += 1\n return result\n\n\ndef get_set_bits_count_using_modulo_operator(number: int) -> int:\n \"\"\"\n Count the number of set bits in a 32 bit integer\n >>> get_set_bits_count_using_modulo_operator(25)\n 3\n >>> get_set_bits_count_using_modulo_operator(37)\n 3\n >>> get_set_bits_count_using_modulo_operator(21)\n 3\n >>> get_set_bits_count_using_modulo_operator(58)\n 4\n >>> get_set_bits_count_using_modulo_operator(0)\n 0\n >>> get_set_bits_count_using_modulo_operator(256)\n 1\n >>> get_set_bits_count_using_modulo_operator(-1)\n Traceback (most recent call last):\n ...\n ValueError: the value of input must not be negative\n \"\"\"\n if number < 0:\n raise ValueError(\"the value of input must not be negative\")\n result = 0\n while number:\n if number % 2 == 1:\n result += 1\n number >>= 1\n return result\n\n\ndef benchmark() -> None:\n \"\"\"\n Benchmark code for comparing 2 functions, with different length int values.\n Brian Kernighan's algorithm is consistently faster than using modulo_operator.\n \"\"\"\n\n def do_benchmark(number: int) -> None:\n setup = \"import __main__ as z\"\n print(f\"Benchmark when {number = }:\")\n print(f\"{get_set_bits_count_using_modulo_operator(number) = }\")\n timing = timeit(\n f\"z.get_set_bits_count_using_modulo_operator({number})\", setup=setup\n )\n print(f\"timeit() runs in {timing} seconds\")\n print(f\"{get_set_bits_count_using_brian_kernighans_algorithm(number) = }\")\n timing = timeit(\n f\"z.get_set_bits_count_using_brian_kernighans_algorithm({number})\",\n setup=setup,\n )\n print(f\"timeit() runs in {timing} seconds\")\n\n for number in (25, 37, 58, 0):\n do_benchmark(number)\n print()\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n benchmark()\n"} +{"Prompt":"Find excess3 code of integer base 10. Add 3 to all digits in a decimal number then convert to a binarycoded decimal. https:en.wikipedia.orgwikiExcess3 excess3code0 '0b0011' excess3code3 '0b0110' excess3code2 '0b0101' excess3code20 '0b01010011' excess3code120 '0b010001010011'","Completions":"def excess_3_code(number: int) -> str:\n \"\"\"\n Find excess-3 code of integer base 10.\n Add 3 to all digits in a decimal number then convert to a binary-coded decimal.\n https:\/\/en.wikipedia.org\/wiki\/Excess-3\n\n >>> excess_3_code(0)\n '0b0011'\n >>> excess_3_code(3)\n '0b0110'\n >>> excess_3_code(2)\n '0b0101'\n >>> excess_3_code(20)\n '0b01010011'\n >>> excess_3_code(120)\n '0b010001010011'\n \"\"\"\n num = \"\"\n for digit in str(max(0, number)):\n num += str(bin(int(digit) + 3))[2:].zfill(4)\n return \"0b\" + num\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Find the largest power of two that is less than or equal to a given integer. https:stackoverflow.comquestions1322510 findpreviouspoweroftwoi for i in range18 0, 1, 2, 2, 4, 4, 4, 4, 8, 8, 8, 8, 8, 8, 8, 8, 16, 16 findpreviouspoweroftwo5 Traceback most recent call last: ... ValueError: Input must be a nonnegative integer findpreviouspoweroftwo10.5 Traceback most recent call last: ... ValueError: Input must be a nonnegative integer","Completions":"def find_previous_power_of_two(number: int) -> int:\n \"\"\"\n Find the largest power of two that is less than or equal to a given integer.\n https:\/\/stackoverflow.com\/questions\/1322510\n\n >>> [find_previous_power_of_two(i) for i in range(18)]\n [0, 1, 2, 2, 4, 4, 4, 4, 8, 8, 8, 8, 8, 8, 8, 8, 16, 16]\n >>> find_previous_power_of_two(-5)\n Traceback (most recent call last):\n ...\n ValueError: Input must be a non-negative integer\n >>> find_previous_power_of_two(10.5)\n Traceback (most recent call last):\n ...\n ValueError: Input must be a non-negative integer\n \"\"\"\n if not isinstance(number, int) or number < 0:\n raise ValueError(\"Input must be a non-negative integer\")\n if number == 0:\n return 0\n power = 1\n while power <= number:\n power <<= 1 # Equivalent to multiplying by 2\n return power >> 1 if number > 1 else 1\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Takes in an integer n and returns a nbit gray code sequence An nbit gray code sequence is a sequence of 2n integers where: a Every integer is between 0,2n 1 inclusive b The sequence begins with 0 c An integer appears at most one times in the sequence dThe binary representation of every pair of integers differ by exactly one bit e The binary representation of first and last bit also differ by exactly one bit graycode2 0, 1, 3, 2 graycode1 0, 1 graycode3 0, 1, 3, 2, 6, 7, 5, 4 graycode1 Traceback most recent call last: ... ValueError: The given input must be positive graycode10.6 Traceback most recent call last: ... TypeError: unsupported operand types for : 'int' and 'float' bit count represents no. of bits in the gray code get the generated string sequence convert them to integers Will output the nbit grey sequence as a string of bits graycodesequencestring2 '00', '01', '11', '10' graycodesequencestring1 '0', '1' The approach is a recursive one Base case achieved when either n 0 or n1 1 n is equivalent to 2n recursive answer will generate answer for n1 bits append 0 to first half of the smaller sequence generated append 1 to second half ... start from the end of the list","Completions":"def gray_code(bit_count: int) -> list:\n \"\"\"\n Takes in an integer n and returns a n-bit\n gray code sequence\n An n-bit gray code sequence is a sequence of 2^n\n integers where:\n\n a) Every integer is between [0,2^n -1] inclusive\n b) The sequence begins with 0\n c) An integer appears at most one times in the sequence\n d)The binary representation of every pair of integers differ\n by exactly one bit\n e) The binary representation of first and last bit also\n differ by exactly one bit\n\n >>> gray_code(2)\n [0, 1, 3, 2]\n\n >>> gray_code(1)\n [0, 1]\n\n >>> gray_code(3)\n [0, 1, 3, 2, 6, 7, 5, 4]\n\n >>> gray_code(-1)\n Traceback (most recent call last):\n ...\n ValueError: The given input must be positive\n\n >>> gray_code(10.6)\n Traceback (most recent call last):\n ...\n TypeError: unsupported operand type(s) for <<: 'int' and 'float'\n \"\"\"\n\n # bit count represents no. of bits in the gray code\n if bit_count < 0:\n raise ValueError(\"The given input must be positive\")\n\n # get the generated string sequence\n sequence = gray_code_sequence_string(bit_count)\n #\n # convert them to integers\n for i in range(len(sequence)):\n sequence[i] = int(sequence[i], 2)\n\n return sequence\n\n\ndef gray_code_sequence_string(bit_count: int) -> list:\n \"\"\"\n Will output the n-bit grey sequence as a\n string of bits\n\n >>> gray_code_sequence_string(2)\n ['00', '01', '11', '10']\n\n >>> gray_code_sequence_string(1)\n ['0', '1']\n \"\"\"\n\n # The approach is a recursive one\n # Base case achieved when either n = 0 or n=1\n if bit_count == 0:\n return [\"0\"]\n\n if bit_count == 1:\n return [\"0\", \"1\"]\n\n seq_len = 1 << bit_count # defines the length of the sequence\n # 1<< n is equivalent to 2^n\n\n # recursive answer will generate answer for n-1 bits\n smaller_sequence = gray_code_sequence_string(bit_count - 1)\n\n sequence = []\n\n # append 0 to first half of the smaller sequence generated\n for i in range(seq_len \/\/ 2):\n generated_no = \"0\" + smaller_sequence[i]\n sequence.append(generated_no)\n\n # append 1 to second half ... start from the end of the list\n for i in reversed(range(seq_len \/\/ 2)):\n generated_no = \"1\" + smaller_sequence[i]\n sequence.append(generated_no)\n\n return sequence\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Returns position of the highest set bit of a number. Ref https:graphics.stanford.eduseanderbithacks.htmlIntegerLogObvious gethighestsetbitposition25 5 gethighestsetbitposition37 6 gethighestsetbitposition1 1 gethighestsetbitposition4 3 gethighestsetbitposition0 0 gethighestsetbitposition0.8 Traceback most recent call last: ... TypeError: Input value must be an 'int' type","Completions":"def get_highest_set_bit_position(number: int) -> int:\n \"\"\"\n Returns position of the highest set bit of a number.\n Ref - https:\/\/graphics.stanford.edu\/~seander\/bithacks.html#IntegerLogObvious\n >>> get_highest_set_bit_position(25)\n 5\n >>> get_highest_set_bit_position(37)\n 6\n >>> get_highest_set_bit_position(1)\n 1\n >>> get_highest_set_bit_position(4)\n 3\n >>> get_highest_set_bit_position(0)\n 0\n >>> get_highest_set_bit_position(0.8)\n Traceback (most recent call last):\n ...\n TypeError: Input value must be an 'int' type\n \"\"\"\n if not isinstance(number, int):\n raise TypeError(\"Input value must be an 'int' type\")\n\n position = 0\n while number:\n position += 1\n number >>= 1\n\n return position\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Reference: https:www.geeksforgeeks.orgpositionofrightmostsetbit Take in a positive integer 'number'. Returns the zerobased index of first set bit in that 'number' from right. Returns 1, If no set bit found. getindexofrightmostsetbit0 1 getindexofrightmostsetbit5 0 getindexofrightmostsetbit36 2 getindexofrightmostsetbit8 3 getindexofrightmostsetbit18 Traceback most recent call last: ... ValueError: Input must be a nonnegative integer getindexofrightmostsetbit'test' Traceback most recent call last: ... ValueError: Input must be a nonnegative integer getindexofrightmostsetbit1.25 Traceback most recent call last: ... ValueError: Input must be a nonnegative integer Finding the index of rightmost set bit has some very peculiar usecases, especially in finding missing orand repeating numbers in a list of positive integers.","Completions":"# Reference: https:\/\/www.geeksforgeeks.org\/position-of-rightmost-set-bit\/\n\n\ndef get_index_of_rightmost_set_bit(number: int) -> int:\n \"\"\"\n Take in a positive integer 'number'.\n Returns the zero-based index of first set bit in that 'number' from right.\n Returns -1, If no set bit found.\n\n >>> get_index_of_rightmost_set_bit(0)\n -1\n >>> get_index_of_rightmost_set_bit(5)\n 0\n >>> get_index_of_rightmost_set_bit(36)\n 2\n >>> get_index_of_rightmost_set_bit(8)\n 3\n >>> get_index_of_rightmost_set_bit(-18)\n Traceback (most recent call last):\n ...\n ValueError: Input must be a non-negative integer\n >>> get_index_of_rightmost_set_bit('test')\n Traceback (most recent call last):\n ...\n ValueError: Input must be a non-negative integer\n >>> get_index_of_rightmost_set_bit(1.25)\n Traceback (most recent call last):\n ...\n ValueError: Input must be a non-negative integer\n \"\"\"\n\n if not isinstance(number, int) or number < 0:\n raise ValueError(\"Input must be a non-negative integer\")\n\n intermediate = number & ~(number - 1)\n index = 0\n while intermediate:\n intermediate >>= 1\n index += 1\n return index - 1\n\n\nif __name__ == \"__main__\":\n \"\"\"\n Finding the index of rightmost set bit has some very peculiar use-cases,\n especially in finding missing or\/and repeating numbers in a list of\n positive integers.\n \"\"\"\n import doctest\n\n doctest.testmod(verbose=True)\n"} +{"Prompt":"return true if the input integer is even Explanation: Lets take a look at the following decimal to binary conversions 2 10 14 1110 100 1100100 3 11 13 1101 101 1100101 from the above examples we can observe that for all the odd integers there is always 1 set bit at the end also, 1 in binary can be represented as 001, 00001, or 0000001 so for any odd integer n n1 is always equals 1 else the integer is even iseven1 False iseven4 True iseven9 False iseven15 False iseven40 True iseven100 True iseven101 False","Completions":"def is_even(number: int) -> bool:\n \"\"\"\n return true if the input integer is even\n Explanation: Lets take a look at the following decimal to binary conversions\n 2 => 10\n 14 => 1110\n 100 => 1100100\n 3 => 11\n 13 => 1101\n 101 => 1100101\n from the above examples we can observe that\n for all the odd integers there is always 1 set bit at the end\n also, 1 in binary can be represented as 001, 00001, or 0000001\n so for any odd integer n => n&1 is always equals 1 else the integer is even\n\n >>> is_even(1)\n False\n >>> is_even(4)\n True\n >>> is_even(9)\n False\n >>> is_even(15)\n False\n >>> is_even(40)\n True\n >>> is_even(100)\n True\n >>> is_even(101)\n False\n \"\"\"\n return number & 1 == 0\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Author : Alexander Pantyukhin Date : November 1, 2022 Task: Given a positive int number. Return True if this number is power of 2 or False otherwise. Implementation notes: Use bit manipulation. For example if the number is the power of two it's bits representation: n 0..100..00 n 1 0..011..11 n n 1 no intersections 0 Return True if this number is power of 2 or False otherwise. ispoweroftwo0 True ispoweroftwo1 True ispoweroftwo2 True ispoweroftwo4 True ispoweroftwo6 False ispoweroftwo8 True ispoweroftwo17 False ispoweroftwo1 Traceback most recent call last: ... ValueError: number must not be negative ispoweroftwo1.2 Traceback most recent call last: ... TypeError: unsupported operand types for : 'float' and 'float' Test all powers of 2 from 0 to 10,000 allispoweroftwoint2 i for i in range10000 True","Completions":"def is_power_of_two(number: int) -> bool:\n \"\"\"\n Return True if this number is power of 2 or False otherwise.\n\n >>> is_power_of_two(0)\n True\n >>> is_power_of_two(1)\n True\n >>> is_power_of_two(2)\n True\n >>> is_power_of_two(4)\n True\n >>> is_power_of_two(6)\n False\n >>> is_power_of_two(8)\n True\n >>> is_power_of_two(17)\n False\n >>> is_power_of_two(-1)\n Traceback (most recent call last):\n ...\n ValueError: number must not be negative\n >>> is_power_of_two(1.2)\n Traceback (most recent call last):\n ...\n TypeError: unsupported operand type(s) for &: 'float' and 'float'\n\n # Test all powers of 2 from 0 to 10,000\n >>> all(is_power_of_two(int(2 ** i)) for i in range(10000))\n True\n \"\"\"\n if number < 0:\n raise ValueError(\"number must not be negative\")\n return number & (number - 1) == 0\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Author : Naman Sharma Date : October 2, 2023 Task: To Find the largest power of 2 less than or equal to a given number. Implementation notes: Use bit manipulation. We start from 1 left shift the set bit to check if res1number. Each left bit shift represents a pow of 2. For example: number: 15 res: 1 0b1 2 0b10 4 0b100 8 0b1000 16 0b10000 Exit Return the largest power of two less than or equal to a number. largestpowoftwolenum0 0 largestpowoftwolenum1 1 largestpowoftwolenum1 0 largestpowoftwolenum3 2 largestpowoftwolenum15 8 largestpowoftwolenum99 64 largestpowoftwolenum178 128 largestpowoftwolenum999999 524288 largestpowoftwolenum99.9 Traceback most recent call last: ... TypeError: Input value must be a 'int' type","Completions":"def largest_pow_of_two_le_num(number: int) -> int:\n \"\"\"\n Return the largest power of two less than or equal to a number.\n\n >>> largest_pow_of_two_le_num(0)\n 0\n >>> largest_pow_of_two_le_num(1)\n 1\n >>> largest_pow_of_two_le_num(-1)\n 0\n >>> largest_pow_of_two_le_num(3)\n 2\n >>> largest_pow_of_two_le_num(15)\n 8\n >>> largest_pow_of_two_le_num(99)\n 64\n >>> largest_pow_of_two_le_num(178)\n 128\n >>> largest_pow_of_two_le_num(999999)\n 524288\n >>> largest_pow_of_two_le_num(99.9)\n Traceback (most recent call last):\n ...\n TypeError: Input value must be a 'int' type\n \"\"\"\n if isinstance(number, float):\n raise TypeError(\"Input value must be a 'int' type\")\n if number <= 0:\n return 0\n res = 1\n while (res << 1) <= number:\n res <<= 1\n return res\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Finds the missing number in a list of consecutive integers. Args: nums: A list of integers. Returns: The missing number. Example: findmissingnumber0, 1, 3, 4 2 findmissingnumber4, 3, 1, 0 2 findmissingnumber4, 3, 1, 0 2 findmissingnumber2, 2, 1, 3, 0 1 findmissingnumber1, 3, 4, 5, 6 2 findmissingnumber6, 5, 4, 2, 1 3 findmissingnumber6, 1, 5, 3, 4 2","Completions":"def find_missing_number(nums: list[int]) -> int:\n \"\"\"\n Finds the missing number in a list of consecutive integers.\n\n Args:\n nums: A list of integers.\n\n Returns:\n The missing number.\n\n Example:\n >>> find_missing_number([0, 1, 3, 4])\n 2\n >>> find_missing_number([4, 3, 1, 0])\n 2\n >>> find_missing_number([-4, -3, -1, 0])\n -2\n >>> find_missing_number([-2, 2, 1, 3, 0])\n -1\n >>> find_missing_number([1, 3, 4, 5, 6])\n 2\n >>> find_missing_number([6, 5, 4, 2, 1])\n 3\n >>> find_missing_number([6, 1, 5, 3, 4])\n 2\n \"\"\"\n low = min(nums)\n high = max(nums)\n missing_number = high\n\n for i in range(low, high):\n missing_number ^= i ^ nums[i - low]\n\n return missing_number\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Author : Alexander Pantyukhin Date : November 30, 2022 Task: Given two int numbers. Return True these numbers have opposite signs or False otherwise. Implementation notes: Use bit manipulation. Use XOR for two numbers. Return True if numbers have opposite signs False otherwise. differentsigns1, 1 True differentsigns1, 1 False differentsigns1000000000000000000000000000, 1000000000000000000000000000 True differentsigns1000000000000000000000000000, 1000000000000000000000000000 True differentsigns50, 278 False differentsigns0, 2 False differentsigns2, 0 False","Completions":"def different_signs(num1: int, num2: int) -> bool:\n \"\"\"\n Return True if numbers have opposite signs False otherwise.\n\n >>> different_signs(1, -1)\n True\n >>> different_signs(1, 1)\n False\n >>> different_signs(1000000000000000000000000000, -1000000000000000000000000000)\n True\n >>> different_signs(-1000000000000000000000000000, 1000000000000000000000000000)\n True\n >>> different_signs(50, 278)\n False\n >>> different_signs(0, 2)\n False\n >>> different_signs(2, 0)\n False\n \"\"\"\n return num1 ^ num2 < 0\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Task: Given a positive int number. Return True if this number is power of 4 or False otherwise. Implementation notes: Use bit manipulation. For example if the number is the power of 2 it's bits representation: n 0..100..00 n 1 0..011..11 n n 1 no intersections 0 If the number is a power of 4 then it should be a power of 2 and the set bit should be at an odd position. Return True if this number is power of 4 or False otherwise. powerof40 Traceback most recent call last: ... ValueError: number must be positive powerof41 True powerof42 False powerof44 True powerof46 False powerof48 False powerof417 False powerof464 True powerof41 Traceback most recent call last: ... ValueError: number must be positive powerof41.2 Traceback most recent call last: ... TypeError: number must be an integer","Completions":"def power_of_4(number: int) -> bool:\n \"\"\"\n Return True if this number is power of 4 or False otherwise.\n\n >>> power_of_4(0)\n Traceback (most recent call last):\n ...\n ValueError: number must be positive\n >>> power_of_4(1)\n True\n >>> power_of_4(2)\n False\n >>> power_of_4(4)\n True\n >>> power_of_4(6)\n False\n >>> power_of_4(8)\n False\n >>> power_of_4(17)\n False\n >>> power_of_4(64)\n True\n >>> power_of_4(-1)\n Traceback (most recent call last):\n ...\n ValueError: number must be positive\n >>> power_of_4(1.2)\n Traceback (most recent call last):\n ...\n TypeError: number must be an integer\n\n \"\"\"\n if not isinstance(number, int):\n raise TypeError(\"number must be an integer\")\n if number <= 0:\n raise ValueError(\"number must be positive\")\n if number & (number - 1) == 0:\n c = 0\n while number:\n c += 1\n number >>= 1\n return c % 2 == 1\n else:\n return False\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"return the bit string of an integer getreversebitstring9 '10010000000000000000000000000000' getreversebitstring43 '11010100000000000000000000000000' getreversebitstring2873 '10011100110100000000000000000000' getreversebitstringthis is not a number Traceback most recent call last: ... TypeError: operation can not be conducted on a object of type str Take in an 32 bit integer, reverse its bits, return a string of reverse bits result of a reversebit and operation on the integer provided. reversebit25 '00000000000000000000000000011001' reversebit37 '00000000000000000000000000100101' reversebit21 '00000000000000000000000000010101' reversebit58 '00000000000000000000000000111010' reversebit0 '00000000000000000000000000000000' reversebit256 '00000000000000000000000100000000' reversebit1 Traceback most recent call last: ... ValueError: the value of input must be positive reversebit1.1 Traceback most recent call last: ... TypeError: Input value must be a 'int' type reversebit0 Traceback most recent call last: ... TypeError: '' not supported between instances of 'str' and 'int' iterator over 1 to 32,since we are dealing with 32 bit integer left shift the bits by unity get the end bit right shift the bits by unity add that bit to our ans","Completions":"def get_reverse_bit_string(number: int) -> str:\n \"\"\"\n return the bit string of an integer\n\n >>> get_reverse_bit_string(9)\n '10010000000000000000000000000000'\n >>> get_reverse_bit_string(43)\n '11010100000000000000000000000000'\n >>> get_reverse_bit_string(2873)\n '10011100110100000000000000000000'\n >>> get_reverse_bit_string(\"this is not a number\")\n Traceback (most recent call last):\n ...\n TypeError: operation can not be conducted on a object of type str\n \"\"\"\n if not isinstance(number, int):\n msg = (\n \"operation can not be conducted on a object of type \"\n f\"{type(number).__name__}\"\n )\n raise TypeError(msg)\n bit_string = \"\"\n for _ in range(32):\n bit_string += str(number % 2)\n number = number >> 1\n return bit_string\n\n\ndef reverse_bit(number: int) -> str:\n \"\"\"\n Take in an 32 bit integer, reverse its bits,\n return a string of reverse bits\n\n result of a reverse_bit and operation on the integer provided.\n\n >>> reverse_bit(25)\n '00000000000000000000000000011001'\n >>> reverse_bit(37)\n '00000000000000000000000000100101'\n >>> reverse_bit(21)\n '00000000000000000000000000010101'\n >>> reverse_bit(58)\n '00000000000000000000000000111010'\n >>> reverse_bit(0)\n '00000000000000000000000000000000'\n >>> reverse_bit(256)\n '00000000000000000000000100000000'\n >>> reverse_bit(-1)\n Traceback (most recent call last):\n ...\n ValueError: the value of input must be positive\n\n >>> reverse_bit(1.1)\n Traceback (most recent call last):\n ...\n TypeError: Input value must be a 'int' type\n\n >>> reverse_bit(\"0\")\n Traceback (most recent call last):\n ...\n TypeError: '<' not supported between instances of 'str' and 'int'\n \"\"\"\n if number < 0:\n raise ValueError(\"the value of input must be positive\")\n elif isinstance(number, float):\n raise TypeError(\"Input value must be a 'int' type\")\n elif isinstance(number, str):\n raise TypeError(\"'<' not supported between instances of 'str' and 'int'\")\n result = 0\n # iterator over [1 to 32],since we are dealing with 32 bit integer\n for _ in range(1, 33):\n # left shift the bits by unity\n result = result << 1\n # get the end bit\n end_bit = number % 2\n # right shift the bits by unity\n number = number >> 1\n # add that bit to our ans\n result = result | end_bit\n return get_reverse_bit_string(result)\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"!usrbinenv python3 Provide the functionality to manipulate a single bit. def setbitnumber: int, position: int int: return number 1 position def clearbitnumber: int, position: int int: return number 1 position def flipbitnumber: int, position: int int: return number 1 position def isbitsetnumber: int, position: int bool: return number position 1 1 def getbitnumber: int, position: int int: return intnumber 1 position ! 0 if name main: import doctest doctest.testmod","Completions":"#!\/usr\/bin\/env python3\n\n\"\"\"Provide the functionality to manipulate a single bit.\"\"\"\n\n\ndef set_bit(number: int, position: int) -> int:\n \"\"\"\n Set the bit at position to 1.\n\n Details: perform bitwise or for given number and X.\n Where X is a number with all the bits \u2013 zeroes and bit on given\n position \u2013 one.\n\n >>> set_bit(0b1101, 1) # 0b1111\n 15\n >>> set_bit(0b0, 5) # 0b100000\n 32\n >>> set_bit(0b1111, 1) # 0b1111\n 15\n \"\"\"\n return number | (1 << position)\n\n\ndef clear_bit(number: int, position: int) -> int:\n \"\"\"\n Set the bit at position to 0.\n\n Details: perform bitwise and for given number and X.\n Where X is a number with all the bits \u2013 ones and bit on given\n position \u2013 zero.\n\n >>> clear_bit(0b10010, 1) # 0b10000\n 16\n >>> clear_bit(0b0, 5) # 0b0\n 0\n \"\"\"\n return number & ~(1 << position)\n\n\ndef flip_bit(number: int, position: int) -> int:\n \"\"\"\n Flip the bit at position.\n\n Details: perform bitwise xor for given number and X.\n Where X is a number with all the bits \u2013 zeroes and bit on given\n position \u2013 one.\n\n >>> flip_bit(0b101, 1) # 0b111\n 7\n >>> flip_bit(0b101, 0) # 0b100\n 4\n \"\"\"\n return number ^ (1 << position)\n\n\ndef is_bit_set(number: int, position: int) -> bool:\n \"\"\"\n Is the bit at position set?\n\n Details: Shift the bit at position to be the first (smallest) bit.\n Then check if the first bit is set by anding the shifted number with 1.\n\n >>> is_bit_set(0b1010, 0)\n False\n >>> is_bit_set(0b1010, 1)\n True\n >>> is_bit_set(0b1010, 2)\n False\n >>> is_bit_set(0b1010, 3)\n True\n >>> is_bit_set(0b0, 17)\n False\n \"\"\"\n return ((number >> position) & 1) == 1\n\n\ndef get_bit(number: int, position: int) -> int:\n \"\"\"\n Get the bit at the given position\n\n Details: perform bitwise and for the given number and X,\n Where X is a number with all the bits \u2013 zeroes and bit on given position \u2013 one.\n If the result is not equal to 0, then the bit on the given position is 1, else 0.\n\n >>> get_bit(0b1010, 0)\n 0\n >>> get_bit(0b1010, 1)\n 1\n >>> get_bit(0b1010, 2)\n 0\n >>> get_bit(0b1010, 3)\n 1\n \"\"\"\n return int((number & (1 << position)) != 0)\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"printshowbits0, 0xFFFF 0: 00000000 65535: 1111111111111111 1. We use bitwise AND operations to separate the even bits 0, 2, 4, 6, etc. and odd bits 1, 3, 5, 7, etc. in the input number. 2. We then rightshift the even bits by 1 position and leftshift the odd bits by 1 position to swap them. 3. Finally, we combine the swapped even and odd bits using a bitwise OR operation to obtain the final result. printshowbits0, swapoddevenbits0 0: 00000000 0: 00000000 printshowbits1, swapoddevenbits1 1: 00000001 2: 00000010 printshowbits2, swapoddevenbits2 2: 00000010 1: 00000001 printshowbits3, swapoddevenbits3 3: 00000011 3: 00000011 printshowbits4, swapoddevenbits4 4: 00000100 8: 00001000 printshowbits5, swapoddevenbits5 5: 00000101 10: 00001010 printshowbits6, swapoddevenbits6 6: 00000110 9: 00001001 printshowbits23, swapoddevenbits23 23: 00010111 43: 00101011 Get all even bits 0xAAAAAAAA is a 32bit number with all even bits set to 1 Get all odd bits 0x55555555 is a 32bit number with all odd bits set to 1 Right shift even bits and left shift odd bits and swap them","Completions":"def show_bits(before: int, after: int) -> str:\n \"\"\"\n >>> print(show_bits(0, 0xFFFF))\n 0: 00000000\n 65535: 1111111111111111\n \"\"\"\n return f\"{before:>5}: {before:08b}\\n{after:>5}: {after:08b}\"\n\n\ndef swap_odd_even_bits(num: int) -> int:\n \"\"\"\n 1. We use bitwise AND operations to separate the even bits (0, 2, 4, 6, etc.) and\n odd bits (1, 3, 5, 7, etc.) in the input number.\n 2. We then right-shift the even bits by 1 position and left-shift the odd bits by\n 1 position to swap them.\n 3. Finally, we combine the swapped even and odd bits using a bitwise OR operation\n to obtain the final result.\n >>> print(show_bits(0, swap_odd_even_bits(0)))\n 0: 00000000\n 0: 00000000\n >>> print(show_bits(1, swap_odd_even_bits(1)))\n 1: 00000001\n 2: 00000010\n >>> print(show_bits(2, swap_odd_even_bits(2)))\n 2: 00000010\n 1: 00000001\n >>> print(show_bits(3, swap_odd_even_bits(3)))\n 3: 00000011\n 3: 00000011\n >>> print(show_bits(4, swap_odd_even_bits(4)))\n 4: 00000100\n 8: 00001000\n >>> print(show_bits(5, swap_odd_even_bits(5)))\n 5: 00000101\n 10: 00001010\n >>> print(show_bits(6, swap_odd_even_bits(6)))\n 6: 00000110\n 9: 00001001\n >>> print(show_bits(23, swap_odd_even_bits(23)))\n 23: 00010111\n 43: 00101011\n \"\"\"\n # Get all even bits - 0xAAAAAAAA is a 32-bit number with all even bits set to 1\n even_bits = num & 0xAAAAAAAA\n\n # Get all odd bits - 0x55555555 is a 32-bit number with all odd bits set to 1\n odd_bits = num & 0x55555555\n\n # Right shift even bits and left shift odd bits and swap them\n return even_bits >> 1 | odd_bits << 1\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n for i in (-1, 0, 1, 2, 3, 4, 23, 24):\n print(show_bits(i, swap_odd_even_bits(i)), \"\\n\")\n"} +{"Prompt":"Diophantine Equation : Given integers a,b,c at least one of a and b ! 0, the diophantine equation ax by c has a solution where x and y are integers iff greatestcommondivisora,b divides c. GCD Greatest Common Divisor or HCF Highest Common Factor diophantine10,6,14 7.0, 14.0 diophantine391,299,69 9.0, 12.0 But above equation has one more solution i.e., x 4, y 5. That's why we need diophantine all solution function. Lemma : if nab and gcda,n 1, then nb. Finding All solutions of Diophantine Equations: Theorem : Let gcda,b d, a dp, b dq. If x0,y0 is a solution of Diophantine Equation ax by c. ax0 by0 c, then all the solutions have the form ax0 tq by0 tp c, where t is an arbitrary integer. n is the number of solution you want, n 2 by default diophantineallsoln10, 6, 14 7.0 14.0 4.0 9.0 diophantineallsoln10, 6, 14, 4 7.0 14.0 4.0 9.0 1.0 4.0 2.0 1.0 diophantineallsoln391, 299, 69, n 4 9.0 12.0 22.0 29.0 35.0 46.0 48.0 63.0 Extended Euclid's Algorithm : If d divides a and b and d ax by for integers x and y, then d gcda,b extendedgcd10, 6 2, 1, 2 extendedgcd7, 5 1, 2, 3","Completions":"from __future__ import annotations\n\nfrom maths.greatest_common_divisor import greatest_common_divisor\n\n\ndef diophantine(a: int, b: int, c: int) -> tuple[float, float]:\n \"\"\"\n Diophantine Equation : Given integers a,b,c ( at least one of a and b != 0), the\n diophantine equation a*x + b*y = c has a solution (where x and y are integers)\n iff greatest_common_divisor(a,b) divides c.\n\n GCD ( Greatest Common Divisor ) or HCF ( Highest Common Factor )\n\n >>> diophantine(10,6,14)\n (-7.0, 14.0)\n\n >>> diophantine(391,299,-69)\n (9.0, -12.0)\n\n But above equation has one more solution i.e., x = -4, y = 5.\n That's why we need diophantine all solution function.\n\n \"\"\"\n\n assert (\n c % greatest_common_divisor(a, b) == 0\n ) # greatest_common_divisor(a,b) is in maths directory\n (d, x, y) = extended_gcd(a, b) # extended_gcd(a,b) function implemented below\n r = c \/ d\n return (r * x, r * y)\n\n\ndef diophantine_all_soln(a: int, b: int, c: int, n: int = 2) -> None:\n \"\"\"\n Lemma : if n|ab and gcd(a,n) = 1, then n|b.\n\n Finding All solutions of Diophantine Equations:\n\n Theorem : Let gcd(a,b) = d, a = d*p, b = d*q. If (x0,y0) is a solution of\n Diophantine Equation a*x + b*y = c. a*x0 + b*y0 = c, then all the\n solutions have the form a(x0 + t*q) + b(y0 - t*p) = c,\n where t is an arbitrary integer.\n\n n is the number of solution you want, n = 2 by default\n\n >>> diophantine_all_soln(10, 6, 14)\n -7.0 14.0\n -4.0 9.0\n\n >>> diophantine_all_soln(10, 6, 14, 4)\n -7.0 14.0\n -4.0 9.0\n -1.0 4.0\n 2.0 -1.0\n\n >>> diophantine_all_soln(391, 299, -69, n = 4)\n 9.0 -12.0\n 22.0 -29.0\n 35.0 -46.0\n 48.0 -63.0\n\n \"\"\"\n (x0, y0) = diophantine(a, b, c) # Initial value\n d = greatest_common_divisor(a, b)\n p = a \/\/ d\n q = b \/\/ d\n\n for i in range(n):\n x = x0 + i * q\n y = y0 - i * p\n print(x, y)\n\n\ndef extended_gcd(a: int, b: int) -> tuple[int, int, int]:\n \"\"\"\n Extended Euclid's Algorithm : If d divides a and b and d = a*x + b*y for integers\n x and y, then d = gcd(a,b)\n\n >>> extended_gcd(10, 6)\n (2, -1, 2)\n\n >>> extended_gcd(7, 5)\n (1, -2, 3)\n\n \"\"\"\n assert a >= 0\n assert b >= 0\n\n if b == 0:\n d, x, y = a, 1, 0\n else:\n (d, p, q) = extended_gcd(b, a % b)\n x = q\n y = p - q * (a \/\/ b)\n\n assert a % d == 0\n assert b % d == 0\n assert d == a * x + b * y\n\n return (d, x, y)\n\n\nif __name__ == \"__main__\":\n from doctest import testmod\n\n testmod(name=\"diophantine\", verbose=True)\n testmod(name=\"diophantine_all_soln\", verbose=True)\n testmod(name=\"extended_gcd\", verbose=True)\n testmod(name=\"greatest_common_divisor\", verbose=True)\n"} +{"Prompt":"An AND Gate is a logic gate in boolean algebra which results to 1 True if both the inputs are 1, and 0 False otherwise. Following is the truth table of an AND Gate: Input 1 Input 2 Output 0 0 0 0 1 0 1 0 0 1 1 1 Refer https:www.geeksforgeeks.orglogicgatesinpython Calculate AND of the input values andgate0, 0 0 andgate0, 1 0 andgate1, 0 0 andgate1, 1 1","Completions":"def and_gate(input_1: int, input_2: int) -> int:\n \"\"\"\n Calculate AND of the input values\n\n >>> and_gate(0, 0)\n 0\n >>> and_gate(0, 1)\n 0\n >>> and_gate(1, 0)\n 0\n >>> and_gate(1, 1)\n 1\n \"\"\"\n return int(input_1 and input_2)\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"An IMPLY Gate is a logic gate in boolean algebra which results to 1 if either input 1 is 0, or if input 1 is 1, then the output is 1 only if input 2 is 1. It is true if input 1 implies input 2. Following is the truth table of an IMPLY Gate: Input 1 Input 2 Output 0 0 1 0 1 1 1 0 0 1 1 1 Refer https:en.wikipedia.orgwikiIMPLYgate Calculate IMPLY of the input values implygate0, 0 1 implygate0, 1 1 implygate1, 0 0 implygate1, 1 1","Completions":"def imply_gate(input_1: int, input_2: int) -> int:\n \"\"\"\n Calculate IMPLY of the input values\n\n >>> imply_gate(0, 0)\n 1\n >>> imply_gate(0, 1)\n 1\n >>> imply_gate(1, 0)\n 0\n >>> imply_gate(1, 1)\n 1\n \"\"\"\n return int(input_1 == 0 or input_2 == 1)\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"https:en.wikipedia.orgwikiKarnaughmap https:www.allaboutcircuits.comtechnicalarticleskarnaughmapbooleanalgebraicsimplificationtechnique Simplify the Karnaugh map. simplifykmapkmap0, 1, 1, 1 A'B AB' AB simplifykmapkmap0, 0, 0, 0 '' simplifykmapkmap0, 1, 1, 1 A'B AB' AB simplifykmapkmap0, 1, 1, 2 A'B AB' AB simplifykmapkmap0, 1, 1, 1.1 A'B AB' AB simplifykmapkmap0, 1, 1, 'a' A'B AB' AB Main function to create and simplify a KMap. main 0, 1 1, 1 Simplified Expression: A'B AB' AB Manually generate the product of 0, 1 and 0, 1","Completions":"def simplify_kmap(kmap: list[list[int]]) -> str:\n \"\"\"\n Simplify the Karnaugh map.\n >>> simplify_kmap(kmap=[[0, 1], [1, 1]])\n \"A'B + AB' + AB\"\n >>> simplify_kmap(kmap=[[0, 0], [0, 0]])\n ''\n >>> simplify_kmap(kmap=[[0, 1], [1, -1]])\n \"A'B + AB' + AB\"\n >>> simplify_kmap(kmap=[[0, 1], [1, 2]])\n \"A'B + AB' + AB\"\n >>> simplify_kmap(kmap=[[0, 1], [1, 1.1]])\n \"A'B + AB' + AB\"\n >>> simplify_kmap(kmap=[[0, 1], [1, 'a']])\n \"A'B + AB' + AB\"\n \"\"\"\n simplified_f = []\n for a, row in enumerate(kmap):\n for b, item in enumerate(row):\n if item:\n term = (\"A\" if a else \"A'\") + (\"B\" if b else \"B'\")\n simplified_f.append(term)\n return \" + \".join(simplified_f)\n\n\ndef main() -> None:\n \"\"\"\n Main function to create and simplify a K-Map.\n\n >>> main()\n [0, 1]\n [1, 1]\n Simplified Expression:\n A'B + AB' + AB\n \"\"\"\n kmap = [[0, 1], [1, 1]]\n\n # Manually generate the product of [0, 1] and [0, 1]\n\n for row in kmap:\n print(row)\n\n print(\"Simplified Expression:\")\n print(simplify_kmap(kmap))\n\n\nif __name__ == \"__main__\":\n main()\n print(f\"{simplify_kmap(kmap=[[0, 1], [1, 1]]) = }\")\n"} +{"Prompt":"Implement a 2to1 Multiplexer. :param input0: The first input value 0 or 1. :param input1: The second input value 0 or 1. :param select: The select signal 0 or 1 to choose between input0 and input1. :return: The output based on the select signal. input1 if select else input0. https:www.electrically4u.comsolvedproblemsonmultiplexer https:en.wikipedia.orgwikiMultiplexer mux0, 1, 0 0 mux0, 1, 1 1 mux1, 0, 0 1 mux1, 0, 1 0 mux2, 1, 0 Traceback most recent call last: ... ValueError: Inputs and select signal must be 0 or 1 mux0, 1, 0 Traceback most recent call last: ... ValueError: Inputs and select signal must be 0 or 1 mux0, 1, 1.1 Traceback most recent call last: ... ValueError: Inputs and select signal must be 0 or 1","Completions":"def mux(input0: int, input1: int, select: int) -> int:\n \"\"\"\n Implement a 2-to-1 Multiplexer.\n\n :param input0: The first input value (0 or 1).\n :param input1: The second input value (0 or 1).\n :param select: The select signal (0 or 1) to choose between input0 and input1.\n :return: The output based on the select signal. input1 if select else input0.\n\n https:\/\/www.electrically4u.com\/solved-problems-on-multiplexer\n https:\/\/en.wikipedia.org\/wiki\/Multiplexer\n\n >>> mux(0, 1, 0)\n 0\n >>> mux(0, 1, 1)\n 1\n >>> mux(1, 0, 0)\n 1\n >>> mux(1, 0, 1)\n 0\n >>> mux(2, 1, 0)\n Traceback (most recent call last):\n ...\n ValueError: Inputs and select signal must be 0 or 1\n >>> mux(0, -1, 0)\n Traceback (most recent call last):\n ...\n ValueError: Inputs and select signal must be 0 or 1\n >>> mux(0, 1, 1.1)\n Traceback (most recent call last):\n ...\n ValueError: Inputs and select signal must be 0 or 1\n \"\"\"\n if all(i in (0, 1) for i in (input0, input1, select)):\n return input1 if select else input0\n raise ValueError(\"Inputs and select signal must be 0 or 1\")\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"A NAND Gate is a logic gate in boolean algebra which results to 0 False if both the inputs are 1, and 1 True otherwise. It's similar to adding a NOT gate along with an AND gate. Following is the truth table of a NAND Gate: Input 1 Input 2 Output 0 0 1 0 1 1 1 0 1 1 1 0 Refer https:www.geeksforgeeks.orglogicgatesinpython Calculate NAND of the input values nandgate0, 0 1 nandgate0, 1 1 nandgate1, 0 1 nandgate1, 1 0","Completions":"def nand_gate(input_1: int, input_2: int) -> int:\n \"\"\"\n Calculate NAND of the input values\n >>> nand_gate(0, 0)\n 1\n >>> nand_gate(0, 1)\n 1\n >>> nand_gate(1, 0)\n 1\n >>> nand_gate(1, 1)\n 0\n \"\"\"\n return int(not (input_1 and input_2))\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"An NIMPLY Gate is a logic gate in boolean algebra which results to 0 if either input 1 is 0, or if input 1 is 1, then it is 0 only if input 2 is 1. It is false if input 1 implies input 2. It is the negated form of imply Following is the truth table of an NIMPLY Gate: Input 1 Input 2 Output 0 0 0 0 1 0 1 0 1 1 1 0 Refer https:en.wikipedia.orgwikiNIMPLYgate Calculate NIMPLY of the input values nimplygate0, 0 0 nimplygate0, 1 0 nimplygate1, 0 1 nimplygate1, 1 0","Completions":"def nimply_gate(input_1: int, input_2: int) -> int:\n \"\"\"\n Calculate NIMPLY of the input values\n\n >>> nimply_gate(0, 0)\n 0\n >>> nimply_gate(0, 1)\n 0\n >>> nimply_gate(1, 0)\n 1\n >>> nimply_gate(1, 1)\n 0\n \"\"\"\n return int(input_1 == 1 and input_2 == 0)\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"A NOR Gate is a logic gate in boolean algebra which results in false0 if any of the inputs is 1, and True1 if all inputs are 0. Following is the truth table of a NOR Gate: Truth Table of NOR Gate: Input 1 Input 2 Output 0 0 1 0 1 0 1 0 0 1 1 0 Code provided by Akshaj Vishwanathan https:www.geeksforgeeks.orglogicgatesinpython norgate0, 0 1 norgate0, 1 0 norgate1, 0 0 norgate1, 1 0 norgate0.0, 0.0 1 norgate0, 7 0 printtruthtablenorgate Truth Table of NOR Gate: Input 1 Input 2 Output 0 0 1 0 1 0 1 0 0 1 1 0 maketablerowOne, Two, Three ' One Two Three '","Completions":"from collections.abc import Callable\n\n\ndef nor_gate(input_1: int, input_2: int) -> int:\n \"\"\"\n >>> nor_gate(0, 0)\n 1\n >>> nor_gate(0, 1)\n 0\n >>> nor_gate(1, 0)\n 0\n >>> nor_gate(1, 1)\n 0\n >>> nor_gate(0.0, 0.0)\n 1\n >>> nor_gate(0, -7)\n 0\n \"\"\"\n return int(input_1 == input_2 == 0)\n\n\ndef truth_table(func: Callable) -> str:\n \"\"\"\n >>> print(truth_table(nor_gate))\n Truth Table of NOR Gate:\n | Input 1 | Input 2 | Output |\n | 0 | 0 | 1 |\n | 0 | 1 | 0 |\n | 1 | 0 | 0 |\n | 1 | 1 | 0 |\n \"\"\"\n\n def make_table_row(items: list | tuple) -> str:\n \"\"\"\n >>> make_table_row((\"One\", \"Two\", \"Three\"))\n '| One | Two | Three |'\n \"\"\"\n return f\"| {' | '.join(f'{item:^8}' for item in items)} |\"\n\n return \"\\n\".join(\n (\n \"Truth Table of NOR Gate:\",\n make_table_row((\"Input 1\", \"Input 2\", \"Output\")),\n *[make_table_row((i, j, func(i, j))) for i in (0, 1) for j in (0, 1)],\n )\n )\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n print(truth_table(nor_gate))\n"} +{"Prompt":"A NOT Gate is a logic gate in boolean algebra which results to 0 False if the input is high, and 1 True if the input is low. Following is the truth table of a XOR Gate: Input Output 0 1 1 0 Refer https:www.geeksforgeeks.orglogicgatesinpython Calculate NOT of the input values notgate0 1 notgate1 0","Completions":"def not_gate(input_1: int) -> int:\n \"\"\"\n Calculate NOT of the input values\n >>> not_gate(0)\n 1\n >>> not_gate(1)\n 0\n \"\"\"\n\n return 1 if input_1 == 0 else 0\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"An OR Gate is a logic gate in boolean algebra which results to 0 False if both the inputs are 0, and 1 True otherwise. Following is the truth table of an AND Gate: Input 1 Input 2 Output 0 0 0 0 1 1 1 0 1 1 1 1 Refer https:www.geeksforgeeks.orglogicgatesinpython Calculate OR of the input values orgate0, 0 0 orgate0, 1 1 orgate1, 0 1 orgate1, 1 1","Completions":"def or_gate(input_1: int, input_2: int) -> int:\n \"\"\"\n Calculate OR of the input values\n >>> or_gate(0, 0)\n 0\n >>> or_gate(0, 1)\n 1\n >>> or_gate(1, 0)\n 1\n >>> or_gate(1, 1)\n 1\n \"\"\"\n return int((input_1, input_2).count(1) != 0)\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"comparestring'0010','0110' '010' comparestring'0110','1101' False check'0.00.01.5' '0.00.01.5' decimaltobinary3,1.5 '0.00.01.5' isfortable'1','011',2 True isfortable'01','001',1 False selection1,'0.00.01.5' '0.00.01.5' selection1,'0.00.01.5' '0.00.01.5' primeimplicantchart'0.00.01.5','0.00.01.5' 1","Completions":"from __future__ import annotations\n\nfrom collections.abc import Sequence\nfrom typing import Literal\n\n\ndef compare_string(string1: str, string2: str) -> str | Literal[False]:\n \"\"\"\n >>> compare_string('0010','0110')\n '0_10'\n\n >>> compare_string('0110','1101')\n False\n \"\"\"\n list1 = list(string1)\n list2 = list(string2)\n count = 0\n for i in range(len(list1)):\n if list1[i] != list2[i]:\n count += 1\n list1[i] = \"_\"\n if count > 1:\n return False\n else:\n return \"\".join(list1)\n\n\ndef check(binary: list[str]) -> list[str]:\n \"\"\"\n >>> check(['0.00.01.5'])\n ['0.00.01.5']\n \"\"\"\n pi = []\n while True:\n check1 = [\"$\"] * len(binary)\n temp = []\n for i in range(len(binary)):\n for j in range(i + 1, len(binary)):\n k = compare_string(binary[i], binary[j])\n if k is False:\n check1[i] = \"*\"\n check1[j] = \"*\"\n temp.append(\"X\")\n for i in range(len(binary)):\n if check1[i] == \"$\":\n pi.append(binary[i])\n if len(temp) == 0:\n return pi\n binary = list(set(temp))\n\n\ndef decimal_to_binary(no_of_variable: int, minterms: Sequence[float]) -> list[str]:\n \"\"\"\n >>> decimal_to_binary(3,[1.5])\n ['0.00.01.5']\n \"\"\"\n temp = []\n for minterm in minterms:\n string = \"\"\n for _ in range(no_of_variable):\n string = str(minterm % 2) + string\n minterm \/\/= 2\n temp.append(string)\n return temp\n\n\ndef is_for_table(string1: str, string2: str, count: int) -> bool:\n \"\"\"\n >>> is_for_table('__1','011',2)\n True\n\n >>> is_for_table('01_','001',1)\n False\n \"\"\"\n list1 = list(string1)\n list2 = list(string2)\n count_n = sum(item1 != item2 for item1, item2 in zip(list1, list2))\n return count_n == count\n\n\ndef selection(chart: list[list[int]], prime_implicants: list[str]) -> list[str]:\n \"\"\"\n >>> selection([[1]],['0.00.01.5'])\n ['0.00.01.5']\n\n >>> selection([[1]],['0.00.01.5'])\n ['0.00.01.5']\n \"\"\"\n temp = []\n select = [0] * len(chart)\n for i in range(len(chart[0])):\n count = sum(row[i] == 1 for row in chart)\n if count == 1:\n rem = max(j for j, row in enumerate(chart) if row[i] == 1)\n select[rem] = 1\n for i, item in enumerate(select):\n if item != 1:\n continue\n for j in range(len(chart[0])):\n if chart[i][j] != 1:\n continue\n for row in chart:\n row[j] = 0\n temp.append(prime_implicants[i])\n while True:\n counts = [chart[i].count(1) for i in range(len(chart))]\n max_n = max(counts)\n rem = counts.index(max_n)\n\n if max_n == 0:\n return temp\n\n temp.append(prime_implicants[rem])\n\n for j in range(len(chart[0])):\n if chart[rem][j] != 1:\n continue\n for i in range(len(chart)):\n chart[i][j] = 0\n\n\ndef prime_implicant_chart(\n prime_implicants: list[str], binary: list[str]\n) -> list[list[int]]:\n \"\"\"\n >>> prime_implicant_chart(['0.00.01.5'],['0.00.01.5'])\n [[1]]\n \"\"\"\n chart = [[0 for x in range(len(binary))] for x in range(len(prime_implicants))]\n for i in range(len(prime_implicants)):\n count = prime_implicants[i].count(\"_\")\n for j in range(len(binary)):\n if is_for_table(prime_implicants[i], binary[j], count):\n chart[i][j] = 1\n\n return chart\n\n\ndef main() -> None:\n no_of_variable = int(input(\"Enter the no. of variables\\n\"))\n minterms = [\n float(x)\n for x in input(\n \"Enter the decimal representation of Minterms 'Spaces Separated'\\n\"\n ).split()\n ]\n binary = decimal_to_binary(no_of_variable, minterms)\n\n prime_implicants = check(binary)\n print(\"Prime Implicants are:\")\n print(prime_implicants)\n chart = prime_implicant_chart(prime_implicants, binary)\n\n essential_prime_implicants = selection(chart, prime_implicants)\n print(\"Essential Prime Implicants are:\")\n print(essential_prime_implicants)\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n main()\n"} +{"Prompt":"A XNOR Gate is a logic gate in boolean algebra which results to 0 False if both the inputs are different, and 1 True, if the inputs are same. It's similar to adding a NOT gate to an XOR gate Following is the truth table of a XNOR Gate: Input 1 Input 2 Output 0 0 1 0 1 0 1 0 0 1 1 1 Refer https:www.geeksforgeeks.orglogicgatesinpython Calculate XOR of the input values xnorgate0, 0 1 xnorgate0, 1 0 xnorgate1, 0 0 xnorgate1, 1 1","Completions":"def xnor_gate(input_1: int, input_2: int) -> int:\n \"\"\"\n Calculate XOR of the input values\n >>> xnor_gate(0, 0)\n 1\n >>> xnor_gate(0, 1)\n 0\n >>> xnor_gate(1, 0)\n 0\n >>> xnor_gate(1, 1)\n 1\n \"\"\"\n return 1 if input_1 == input_2 else 0\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"A XOR Gate is a logic gate in boolean algebra which results to 1 True if only one of the two inputs is 1, and 0 False if an even number of inputs are 1. Following is the truth table of a XOR Gate: Input 1 Input 2 Output 0 0 0 0 1 1 1 0 1 1 1 0 Refer https:www.geeksforgeeks.orglogicgatesinpython calculate xor of the input values xorgate0, 0 0 xorgate0, 1 1 xorgate1, 0 1 xorgate1, 1 0","Completions":"def xor_gate(input_1: int, input_2: int) -> int:\n \"\"\"\n calculate xor of the input values\n\n >>> xor_gate(0, 0)\n 0\n >>> xor_gate(0, 1)\n 1\n >>> xor_gate(1, 0)\n 1\n >>> xor_gate(1, 1)\n 0\n \"\"\"\n return (input_1, input_2).count(0) % 2\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Conway's Game of Life implemented in Python. https:en.wikipedia.orgwikiConway27sGameofLife Define glider example Define blinker example Generates the next generation for a given state of Conway's Game of Life. newgenerationBLINKER 0, 0, 0, 1, 1, 1, 0, 0, 0 Get the number of live neighbours Rules of the game of life excerpt from Wikipedia: 1. Any live cell with two or three live neighbours survives. 2. Any dead cell with three live neighbours becomes a live cell. 3. All other live cells die in the next generation. Similarly, all other dead cells stay dead. Generates a list of images of subsequent Game of Life states. Create output image Save cells to image Save image","Completions":"from __future__ import annotations\n\nfrom PIL import Image\n\n# Define glider example\nGLIDER = [\n [0, 1, 0, 0, 0, 0, 0, 0],\n [0, 0, 1, 0, 0, 0, 0, 0],\n [1, 1, 1, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0],\n]\n\n# Define blinker example\nBLINKER = [[0, 1, 0], [0, 1, 0], [0, 1, 0]]\n\n\ndef new_generation(cells: list[list[int]]) -> list[list[int]]:\n \"\"\"\n Generates the next generation for a given state of Conway's Game of Life.\n >>> new_generation(BLINKER)\n [[0, 0, 0], [1, 1, 1], [0, 0, 0]]\n \"\"\"\n next_generation = []\n for i in range(len(cells)):\n next_generation_row = []\n for j in range(len(cells[i])):\n # Get the number of live neighbours\n neighbour_count = 0\n if i > 0 and j > 0:\n neighbour_count += cells[i - 1][j - 1]\n if i > 0:\n neighbour_count += cells[i - 1][j]\n if i > 0 and j < len(cells[i]) - 1:\n neighbour_count += cells[i - 1][j + 1]\n if j > 0:\n neighbour_count += cells[i][j - 1]\n if j < len(cells[i]) - 1:\n neighbour_count += cells[i][j + 1]\n if i < len(cells) - 1 and j > 0:\n neighbour_count += cells[i + 1][j - 1]\n if i < len(cells) - 1:\n neighbour_count += cells[i + 1][j]\n if i < len(cells) - 1 and j < len(cells[i]) - 1:\n neighbour_count += cells[i + 1][j + 1]\n\n # Rules of the game of life (excerpt from Wikipedia):\n # 1. Any live cell with two or three live neighbours survives.\n # 2. Any dead cell with three live neighbours becomes a live cell.\n # 3. All other live cells die in the next generation.\n # Similarly, all other dead cells stay dead.\n alive = cells[i][j] == 1\n if (\n (alive and 2 <= neighbour_count <= 3)\n or not alive\n and neighbour_count == 3\n ):\n next_generation_row.append(1)\n else:\n next_generation_row.append(0)\n\n next_generation.append(next_generation_row)\n return next_generation\n\n\ndef generate_images(cells: list[list[int]], frames: int) -> list[Image.Image]:\n \"\"\"\n Generates a list of images of subsequent Game of Life states.\n \"\"\"\n images = []\n for _ in range(frames):\n # Create output image\n img = Image.new(\"RGB\", (len(cells[0]), len(cells)))\n pixels = img.load()\n\n # Save cells to image\n for x in range(len(cells)):\n for y in range(len(cells[0])):\n colour = 255 - cells[y][x] * 255\n pixels[x, y] = (colour, colour, colour)\n\n # Save image\n images.append(img)\n cells = new_generation(cells)\n return images\n\n\nif __name__ == \"__main__\":\n images = generate_images(GLIDER, 16)\n images[0].save(\"out.gif\", save_all=True, append_images=images[1:])\n"} +{"Prompt":"Conway's Game Of Life, Author Anurag Kumarmailto:anuragkumarak95gmail.com Requirements: numpy random time matplotlib Python: 3.5 Usage: python3 gameoflife canvassize:int GameOfLife Rules: 1. Any live cell with fewer than two live neighbours dies, as if caused by underpopulation. 2. Any live cell with two or three live neighbours lives on to the next generation. 3. Any live cell with more than three live neighbours dies, as if by overpopulation. 4. Any dead cell with exactly three live neighbours be comes a live cell, as if by reproduction. This function runs the rules of game through all points, and changes their status accordingly.in the same canvas Args: canvas : canvas of population to run the rules on. returns: canvas of population after one step finding dead or alive neighbours count. handling duplicate entry for focus pt. running the rules of game here. main working structure of this module. do nothing.","Completions":"import random\nimport sys\n\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom matplotlib.colors import ListedColormap\n\nusage_doc = \"Usage of script: script_name \"\n\nchoice = [0] * 100 + [1] * 10\nrandom.shuffle(choice)\n\n\ndef create_canvas(size: int) -> list[list[bool]]:\n canvas = [[False for i in range(size)] for j in range(size)]\n return canvas\n\n\ndef seed(canvas: list[list[bool]]) -> None:\n for i, row in enumerate(canvas):\n for j, _ in enumerate(row):\n canvas[i][j] = bool(random.getrandbits(1))\n\n\ndef run(canvas: list[list[bool]]) -> list[list[bool]]:\n \"\"\"\n This function runs the rules of game through all points, and changes their\n status accordingly.(in the same canvas)\n @Args:\n --\n canvas : canvas of population to run the rules on.\n\n @returns:\n --\n canvas of population after one step\n \"\"\"\n current_canvas = np.array(canvas)\n next_gen_canvas = np.array(create_canvas(current_canvas.shape[0]))\n for r, row in enumerate(current_canvas):\n for c, pt in enumerate(row):\n next_gen_canvas[r][c] = __judge_point(\n pt, current_canvas[r - 1 : r + 2, c - 1 : c + 2]\n )\n\n return next_gen_canvas.tolist()\n\n\ndef __judge_point(pt: bool, neighbours: list[list[bool]]) -> bool:\n dead = 0\n alive = 0\n # finding dead or alive neighbours count.\n for i in neighbours:\n for status in i:\n if status:\n alive += 1\n else:\n dead += 1\n\n # handling duplicate entry for focus pt.\n if pt:\n alive -= 1\n else:\n dead -= 1\n\n # running the rules of game here.\n state = pt\n if pt:\n if alive < 2:\n state = False\n elif alive in {2, 3}:\n state = True\n elif alive > 3:\n state = False\n else:\n if alive == 3:\n state = True\n\n return state\n\n\nif __name__ == \"__main__\":\n if len(sys.argv) != 2:\n raise Exception(usage_doc)\n\n canvas_size = int(sys.argv[1])\n # main working structure of this module.\n c = create_canvas(canvas_size)\n seed(c)\n fig, ax = plt.subplots()\n fig.show()\n cmap = ListedColormap([\"w\", \"k\"])\n try:\n while True:\n c = run(c)\n ax.matshow(c, cmap=cmap)\n fig.canvas.draw()\n ax.cla()\n except KeyboardInterrupt:\n # do nothing.\n pass\n"} +{"Prompt":"Langton's ant https:en.wikipedia.orgwikiLangton27sant https:upload.wikimedia.orgwikipediacommons009LangtonsAntAnimated.gif Represents the main LangonsAnt algorithm. la LangtonsAnt2, 2 la.board True, True, True, True la.antposition 1, 1 Each square is either True or False where True is white and False is black Initially pointing left similar to the wikipedia image 0 0 1 90 2 180 3 270 Performs three tasks: 1. The ant turns either clockwise or anticlockwise according to the colour of the square that it is currently on. If the square is white, the ant turns clockwise, and if the square is black the ant turns anticlockwise 2. The ant moves one square in the direction that it is currently facing 3. The square the ant was previously on is inverted White Black and Black White If display is True, the board will also be displayed on the axes la LangtonsAnt2, 2 la.moveantNone, True, 0 la.board True, True, True, False la.moveantNone, True, 0 la.board True, False, True, False Turn clockwise or anticlockwise according to colour of square The square is white so turn 90 clockwise The square is black so turn 90 anticlockwise Move ant Flip colour of square Display the board on the axes Displays the board without delay in a matplotlib plot to visually understand and track the ant. LangtonsAntWIDTH, HEIGHT Assign animation to a variable to prevent it from getting garbage collected","Completions":"from functools import partial\n\nfrom matplotlib import pyplot as plt\nfrom matplotlib.animation import FuncAnimation\n\nWIDTH = 80\nHEIGHT = 80\n\n\nclass LangtonsAnt:\n \"\"\"\n Represents the main LangonsAnt algorithm.\n\n >>> la = LangtonsAnt(2, 2)\n >>> la.board\n [[True, True], [True, True]]\n >>> la.ant_position\n (1, 1)\n \"\"\"\n\n def __init__(self, width: int, height: int) -> None:\n # Each square is either True or False where True is white and False is black\n self.board = [[True] * width for _ in range(height)]\n self.ant_position: tuple[int, int] = (width \/\/ 2, height \/\/ 2)\n\n # Initially pointing left (similar to the wikipedia image)\n # (0 = 0\u00b0 | 1 = 90\u00b0 | 2 = 180 \u00b0 | 3 = 270\u00b0)\n self.ant_direction: int = 3\n\n def move_ant(self, axes: plt.Axes | None, display: bool, _frame: int) -> None:\n \"\"\"\n Performs three tasks:\n 1. The ant turns either clockwise or anti-clockwise according to the colour\n of the square that it is currently on. If the square is white, the ant\n turns clockwise, and if the square is black the ant turns anti-clockwise\n 2. The ant moves one square in the direction that it is currently facing\n 3. The square the ant was previously on is inverted (White -> Black and\n Black -> White)\n\n If display is True, the board will also be displayed on the axes\n\n >>> la = LangtonsAnt(2, 2)\n >>> la.move_ant(None, True, 0)\n >>> la.board\n [[True, True], [True, False]]\n >>> la.move_ant(None, True, 0)\n >>> la.board\n [[True, False], [True, False]]\n \"\"\"\n directions = {\n 0: (-1, 0), # 0\u00b0\n 1: (0, 1), # 90\u00b0\n 2: (1, 0), # 180\u00b0\n 3: (0, -1), # 270\u00b0\n }\n x, y = self.ant_position\n\n # Turn clockwise or anti-clockwise according to colour of square\n if self.board[x][y] is True:\n # The square is white so turn 90\u00b0 clockwise\n self.ant_direction = (self.ant_direction + 1) % 4\n else:\n # The square is black so turn 90\u00b0 anti-clockwise\n self.ant_direction = (self.ant_direction - 1) % 4\n\n # Move ant\n move_x, move_y = directions[self.ant_direction]\n self.ant_position = (x + move_x, y + move_y)\n\n # Flip colour of square\n self.board[x][y] = not self.board[x][y]\n\n if display and axes:\n # Display the board on the axes\n axes.get_xaxis().set_ticks([])\n axes.get_yaxis().set_ticks([])\n axes.imshow(self.board, cmap=\"gray\", interpolation=\"nearest\")\n\n def display(self, frames: int = 100_000) -> None:\n \"\"\"\n Displays the board without delay in a matplotlib plot\n to visually understand and track the ant.\n\n >>> _ = LangtonsAnt(WIDTH, HEIGHT)\n \"\"\"\n fig, ax = plt.subplots()\n # Assign animation to a variable to prevent it from getting garbage collected\n self.animation = FuncAnimation(\n fig, partial(self.move_ant, ax, True), frames=frames, interval=1\n )\n plt.show()\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n\n LangtonsAnt(WIDTH, HEIGHT).display()\n"} +{"Prompt":"Simulate the evolution of a highway with only one road that is a loop. The highway is divided in cells, each cell can have at most one car in it. The highway is a loop so when a car comes to one end, it will come out on the other. Each car is represented by its speed from 0 to 5. Some information about speed: 1 means that the cell on the highway is empty 0 to 5 are the speed of the cars with 0 being the lowest and 5 the highest highway: listint Where every position and speed of every car will be stored probability The probability that a driver will slow down initialspeed The speed of the cars a the start frequency How many cells there are between two cars at the start maxspeed The maximum speed a car can go to numberofcells How many cell are there in the highway numberofupdate How many times will the position be updated More information here: https:en.wikipedia.orgwikiNagelE28093Schreckenbergmodel Examples for doctest: simulateconstructhighway6, 3, 0, 2, 0, 2 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 simulateconstructhighway5, 2, 2, 3, 0, 2 0, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1 Build the highway following the parameters given constructhighway10, 2, 6 6, 1, 6, 1, 6, 1, 6, 1, 6, 1 constructhighway10, 10, 2 2, 1, 1, 1, 1, 1, 1, 1, 1, 1 Get the distance between a car at index carindex and the next car getdistance6, 1, 6, 1, 6, 2 1 getdistance2, 1, 1, 1, 3, 1, 0, 1, 3, 2, 0 3 getdistance1, 1, 1, 1, 2, 1, 1, 1, 3, 1 4 Here if the car is near the end of the highway Update the speed of the cars update1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 3, 0.0, 5 1, 1, 1, 1, 1, 3, 1, 1, 1, 1, 4 update1, 1, 2, 1, 1, 1, 1, 3, 0.0, 5 1, 1, 3, 1, 1, 1, 1, 1 Beforce calculations, the highway is empty Add 1 to the current speed of the car and cap the speed Number of empty cell before the next car We can't have the car causing an accident Randomly, a driver will slow down The main function, it will simulate the evolution of the highway simulate1, 2, 1, 1, 1, 3, 2, 0.0, 3 1, 2, 1, 1, 1, 3, 1, 1, 1, 2, 1, 0, 1, 1, 1, 0, 1, 1 simulate1, 2, 1, 3, 4, 0.0, 3 1, 2, 1, 3, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0 Change the position based on the speed with to create the loop Commit the change of position","Completions":"from random import randint, random\n\n\ndef construct_highway(\n number_of_cells: int,\n frequency: int,\n initial_speed: int,\n random_frequency: bool = False,\n random_speed: bool = False,\n max_speed: int = 5,\n) -> list:\n \"\"\"\n Build the highway following the parameters given\n >>> construct_highway(10, 2, 6)\n [[6, -1, 6, -1, 6, -1, 6, -1, 6, -1]]\n >>> construct_highway(10, 10, 2)\n [[2, -1, -1, -1, -1, -1, -1, -1, -1, -1]]\n \"\"\"\n\n highway = [[-1] * number_of_cells] # Create a highway without any car\n i = 0\n initial_speed = max(initial_speed, 0)\n while i < number_of_cells:\n highway[0][i] = (\n randint(0, max_speed) if random_speed else initial_speed\n ) # Place the cars\n i += (\n randint(1, max_speed * 2) if random_frequency else frequency\n ) # Arbitrary number, may need tuning\n return highway\n\n\ndef get_distance(highway_now: list, car_index: int) -> int:\n \"\"\"\n Get the distance between a car (at index car_index) and the next car\n >>> get_distance([6, -1, 6, -1, 6], 2)\n 1\n >>> get_distance([2, -1, -1, -1, 3, 1, 0, 1, 3, 2], 0)\n 3\n >>> get_distance([-1, -1, -1, -1, 2, -1, -1, -1, 3], -1)\n 4\n \"\"\"\n\n distance = 0\n cells = highway_now[car_index + 1 :]\n for cell in range(len(cells)): # May need a better name for this\n if cells[cell] != -1: # If the cell is not empty then\n return distance # we have the distance we wanted\n distance += 1\n # Here if the car is near the end of the highway\n return distance + get_distance(highway_now, -1)\n\n\ndef update(highway_now: list, probability: float, max_speed: int) -> list:\n \"\"\"\n Update the speed of the cars\n >>> update([-1, -1, -1, -1, -1, 2, -1, -1, -1, -1, 3], 0.0, 5)\n [-1, -1, -1, -1, -1, 3, -1, -1, -1, -1, 4]\n >>> update([-1, -1, 2, -1, -1, -1, -1, 3], 0.0, 5)\n [-1, -1, 3, -1, -1, -1, -1, 1]\n \"\"\"\n\n number_of_cells = len(highway_now)\n # Beforce calculations, the highway is empty\n next_highway = [-1] * number_of_cells\n\n for car_index in range(number_of_cells):\n if highway_now[car_index] != -1:\n # Add 1 to the current speed of the car and cap the speed\n next_highway[car_index] = min(highway_now[car_index] + 1, max_speed)\n # Number of empty cell before the next car\n dn = get_distance(highway_now, car_index) - 1\n # We can't have the car causing an accident\n next_highway[car_index] = min(next_highway[car_index], dn)\n if random() < probability:\n # Randomly, a driver will slow down\n next_highway[car_index] = max(next_highway[car_index] - 1, 0)\n return next_highway\n\n\ndef simulate(\n highway: list, number_of_update: int, probability: float, max_speed: int\n) -> list:\n \"\"\"\n The main function, it will simulate the evolution of the highway\n >>> simulate([[-1, 2, -1, -1, -1, 3]], 2, 0.0, 3)\n [[-1, 2, -1, -1, -1, 3], [-1, -1, -1, 2, -1, 0], [1, -1, -1, 0, -1, -1]]\n >>> simulate([[-1, 2, -1, 3]], 4, 0.0, 3)\n [[-1, 2, -1, 3], [-1, 0, -1, 0], [-1, 0, -1, 0], [-1, 0, -1, 0], [-1, 0, -1, 0]]\n \"\"\"\n\n number_of_cells = len(highway[0])\n\n for i in range(number_of_update):\n next_speeds_calculated = update(highway[i], probability, max_speed)\n real_next_speeds = [-1] * number_of_cells\n\n for car_index in range(number_of_cells):\n speed = next_speeds_calculated[car_index]\n if speed != -1:\n # Change the position based on the speed (with % to create the loop)\n index = (car_index + speed) % number_of_cells\n # Commit the change of position\n real_next_speeds[index] = speed\n highway.append(real_next_speeds)\n\n return highway\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Return an image of 16 generations of onedimensional cellular automata based on a given ruleset number https:mathworld.wolfram.comElementaryCellularAutomaton.html Define the first generation of cells fmt: off fmt: on formatruleset11100 0, 0, 0, 1, 1, 1, 0, 0 formatruleset0 0, 0, 0, 0, 0, 0, 0, 0 formatruleset11111111 1, 1, 1, 1, 1, 1, 1, 1 Get the neighbors of each cell Handle neighbours outside bounds by using 0 as their value Define a new cell and add it to the new generation Convert the cells into a greyscale PIL.Image.Image and return it to the caller. from random import random cells random for w in range31 for h in range16 img generateimagecells isinstanceimg, Image.Image True img.width, img.height 31, 16 Create the output image Generates image Uncomment to save the image img.savefrulerulenum.png","Completions":"from __future__ import annotations\n\nfrom PIL import Image\n\n# Define the first generation of cells\n# fmt: off\nCELLS = [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]\n# fmt: on\n\n\ndef format_ruleset(ruleset: int) -> list[int]:\n \"\"\"\n >>> format_ruleset(11100)\n [0, 0, 0, 1, 1, 1, 0, 0]\n >>> format_ruleset(0)\n [0, 0, 0, 0, 0, 0, 0, 0]\n >>> format_ruleset(11111111)\n [1, 1, 1, 1, 1, 1, 1, 1]\n \"\"\"\n return [int(c) for c in f\"{ruleset:08}\"[:8]]\n\n\ndef new_generation(cells: list[list[int]], rule: list[int], time: int) -> list[int]:\n population = len(cells[0]) # 31\n next_generation = []\n for i in range(population):\n # Get the neighbors of each cell\n # Handle neighbours outside bounds by using 0 as their value\n left_neighbor = 0 if i == 0 else cells[time][i - 1]\n right_neighbor = 0 if i == population - 1 else cells[time][i + 1]\n # Define a new cell and add it to the new generation\n situation = 7 - int(f\"{left_neighbor}{cells[time][i]}{right_neighbor}\", 2)\n next_generation.append(rule[situation])\n return next_generation\n\n\ndef generate_image(cells: list[list[int]]) -> Image.Image:\n \"\"\"\n Convert the cells into a greyscale PIL.Image.Image and return it to the caller.\n >>> from random import random\n >>> cells = [[random() for w in range(31)] for h in range(16)]\n >>> img = generate_image(cells)\n >>> isinstance(img, Image.Image)\n True\n >>> img.width, img.height\n (31, 16)\n \"\"\"\n # Create the output image\n img = Image.new(\"RGB\", (len(cells[0]), len(cells)))\n pixels = img.load()\n # Generates image\n for w in range(img.width):\n for h in range(img.height):\n color = 255 - int(255 * cells[h][w])\n pixels[w, h] = (color, color, color)\n return img\n\n\nif __name__ == \"__main__\":\n rule_num = bin(int(input(\"Rule:\\n\").strip()))[2:]\n rule = format_ruleset(int(rule_num))\n for time in range(16):\n CELLS.append(new_generation(CELLS, rule, time))\n img = generate_image(CELLS)\n # Uncomment to save the image\n # img.save(f\"rule_{rule_num}.png\")\n img.show()\n"} +{"Prompt":"WaTor algorithm 1984 https:en.wikipedia.orgwikiWaTor https:beltoforion.deenwator https:beltoforion.deenwatorimageswatormedium.webm This solution aims to completely remove any systematic approach to the WaTor planet, and utilise fully random methods. The constants are a working set that allows the WaTor planet to result in one of the three possible results. The initial energy value of predator entities The energy value provided when consuming prey The number of entities to delete from the unbalanced side Represents an entity either prey or predator. e EntityTrue, coords0, 0 e.prey True e.coords 0, 0 e.alive True The row, col pos of the entity e EntityTrue, coords0, 0 e.resetreproductiontime e.remainingreproductiontime PREYREPRODUCTIONTIME True e EntityFalse, coords0, 0 e.resetreproductiontime e.remainingreproductiontime PREDATORREPRODUCTIONTIME True EntitypreyTrue, coords1, 1 EntitypreyTrue, coords1, 1, remainingreproductiontime5 EntitypreyFalse, coords2, 1 doctest: NORMALIZEWHITESPACE EntitypreyFalse, coords2, 1, remainingreproductiontime20, energyvalue15 Represents the main WaTor algorithm. :attr timepassed: A function that is called every time time passes a chronon in order to visually display the new WaTor planet. The timepassed function can block using time.sleep to slow the algorithm progression. wt WaTor10, 15 wt.width 10 wt.height 15 lenwt.planet 15 lenwt.planet0 10 lenwt.getentities PREDATORINITIALCOUNT PREYINITIALCOUNT True Populate planet with predators and prey randomly Ease of access for testing wt WaTorWIDTH, HEIGHT planet ... None, None, None, ... None, EntityTrue, coords1, 1, None ... wt.setplanetplanet wt.planet planet True wt.width 3 wt.height 2 Adds an entity, making sure the entity does not override another entity wt WaTorWIDTH, HEIGHT wt.setplanetNone, None, None, None wt.addentityTrue lenwt.getentities 1 wt.addentityFalse lenwt.getentities 2 Returns a list of all the entities within the planet. wt WaTorWIDTH, HEIGHT lenwt.getentities PREDATORINITIALCOUNT PREYINITIALCOUNT True Balances predators and preys so that prey can not dominate the predators, blocking up space for them to reproduce. wt WaTorWIDTH, HEIGHT for i in range2000: ... row, col i HEIGHT, i WIDTH ... wt.planetrowcol EntityTrue, coordsrow, col entities lenwt.getentities wt.balancepredatorsandprey lenwt.getentities entities False Returns all the prey entities around N, S, E, W a predator entity. Subtly different to the trytomovetounoccupied square. wt WaTorWIDTH, HEIGHT wt.setplanet ... None, EntityTrue, 0, 1, None, ... None, EntityFalse, 1, 1, None, ... None, EntityTrue, 2, 1, None wt.getsurroundingprey ... EntityFalse, 1, 1 doctest: NORMALIZEWHITESPACE EntitypreyTrue, coords0, 1, remainingreproductiontime5, EntitypreyTrue, coords2, 1, remainingreproductiontime5 wt.setplanetEntityFalse, 0, 0 wt.getsurroundingpreyEntityFalse, 0, 0 wt.setplanet ... EntityTrue, 0, 0, EntityFalse, 1, 0, EntityFalse, 2, 0, ... None, EntityFalse, 1, 1, EntityTrue, 2, 1, ... None, None, None wt.getsurroundingpreyEntityFalse, 1, 0 EntitypreyTrue, coords0, 0, remainingreproductiontime5 Attempts to move to an unoccupied neighbouring square in either of the four directions North, South, East, West. If the move was successful and the remainingreproduction time is equal to 0, then a new prey or predator can also be created in the previous square. :param directionorders: Ordered list like priority queue depicting order to attempt to move. Removes any systematic approach of checking neighbouring squares. planet ... None, None, None, ... None, EntityTrue, coords1, 1, None, ... None, None, None ... wt WaTorWIDTH, HEIGHT wt.setplanetplanet wt.moveandreproduceEntityTrue, coords1, 1, directionordersN wt.planet doctest: NORMALIZEWHITESPACE None, EntitypreyTrue, coords0, 1, remainingreproductiontime4, None, None, None, None, None, None, None wt.planet00 EntityTrue, coords0, 0 wt.moveandreproduceEntityTrue, coords0, 1, ... directionordersN, W, E, S wt.planet doctest: NORMALIZEWHITESPACE EntitypreyTrue, coords0, 0, remainingreproductiontime5, None, EntitypreyTrue, coords0, 2, remainingreproductiontime4, None, None, None, None, None, None wt.planet01 wt.planet02 wt.planet02 None wt.moveandreproduceEntityTrue, coords0, 1, ... directionordersN, W, S, E wt.planet doctest: NORMALIZEWHITESPACE EntitypreyTrue, coords0, 0, remainingreproductiontime5, None, None, None, EntitypreyTrue, coords1, 1, remainingreproductiontime4, None, None, None, None wt WaTorWIDTH, HEIGHT reproducableentity EntityFalse, coords0, 1 reproducableentity.remainingreproductiontime 0 wt.planet None, reproducableentity wt.moveandreproducereproducableentity, ... directionordersN, W, S, E wt.planet doctest: NORMALIZEWHITESPACE EntitypreyFalse, coords0, 0, remainingreproductiontime20, energyvalue15, EntitypreyFalse, coords0, 1, remainingreproductiontime20, energyvalue15 Weight adjacent locations Move entity to empty adjacent square 2. See if it possible to reproduce in previous square Check if the entities on the planet is less than the max limit Reproduce in previous square Performs the actions for a prey entity For prey the rules are: 1. At each chronon, a prey moves randomly to one of the adjacent unoccupied squares. If there are no free squares, no movement takes place. 2. Once a prey has survived a certain number of chronons it may reproduce. This is done as it moves to a neighbouring square, leaving behind a new prey in its old position. Its reproduction time is also reset to zero. wt WaTorWIDTH, HEIGHT reproducableentity EntityTrue, coords0, 1 reproducableentity.remainingreproductiontime 0 wt.planet None, reproducableentity wt.performpreyactionsreproducableentity, ... directionordersN, W, S, E wt.planet doctest: NORMALIZEWHITESPACE EntitypreyTrue, coords0, 0, remainingreproductiontime5, EntitypreyTrue, coords0, 1, remainingreproductiontime5 Performs the actions for a predator entity :param occupiedbypreycoords: Move to this location if there is prey there For predators the rules are: 1. At each chronon, a predator moves randomly to an adjacent square occupied by a prey. If there is none, the predator moves to a random adjacent unoccupied square. If there are no free squares, no movement takes place. 2. At each chronon, each predator is deprived of a unit of energy. 3. Upon reaching zero energy, a predator dies. 4. If a predator moves to a square occupied by a prey, it eats the prey and earns a certain amount of energy. 5. Once a predator has survived a certain number of chronons it may reproduce in exactly the same way as the prey. wt WaTorWIDTH, HEIGHT wt.setplanetEntityTrue, coords0, 0, EntityFalse, coords0, 1 wt.performpredatoractionsEntityFalse, coords0, 1, 0, 0, wt.planet doctest: NORMALIZEWHITESPACE EntitypreyFalse, coords0, 0, remainingreproductiontime20, energyvalue19, None 3. If the entity has 0 energy, it will die 1. Move to entity if possible Kill the prey Move onto prey 4. Eats the prey and earns energy 5. If it has survived the certain number of chronons it will also reproduce in this function 2. Each chronon, the predator is deprived of a unit of energy Emulate time passing by looping iterationcount times wt WaTorWIDTH, HEIGHT wt.runiterationcountPREDATORINITIALENERGYVALUE 1 lenlistfilterlambda entity: entity.prey is False, ... wt.getentities PREDATORINITIALCOUNT True Generate list of all entities in order to randomly pop an entity at a time to simulate true randomness This removes the systematic approach of iterating through each entity width by height Create list of surrounding prey Again, randomly shuffle directions Balance out the predators and prey Call timepassed function for WaTor planet visualisation in a terminal or a graph. Visually displays the WaTor planet using an ascii code in terminal to clear and reprint the WaTor planet at intervals. Uses ascii colour codes to colourfully display the predators and prey. 0x60f197 Prey 0xfffff Predator x wt WaTor30, 30 wt.setplanet ... EntityTrue, coords0, 0, EntityFalse, coords0, 1, None, ... EntityFalse, coords1, 0, None, EntityFalse, coords1, 2, ... None, EntityTrue, coords2, 1, None ... visualisewt, 0, colourFalse doctest: NORMALIZEWHITESPACE x . x . x . . BLANKLINE Iteration: 0 Prey count: 2 Predator count: 3 Iterate over every entity in the planet Block the thread to be able to visualise seeing the algorithm","Completions":"from collections.abc import Callable\nfrom random import randint, shuffle\nfrom time import sleep\nfrom typing import Literal\n\nWIDTH = 50 # Width of the Wa-Tor planet\nHEIGHT = 50 # Height of the Wa-Tor planet\n\nPREY_INITIAL_COUNT = 30 # The initial number of prey entities\nPREY_REPRODUCTION_TIME = 5 # The chronons before reproducing\n\nPREDATOR_INITIAL_COUNT = 50 # The initial number of predator entities\n# The initial energy value of predator entities\nPREDATOR_INITIAL_ENERGY_VALUE = 15\n# The energy value provided when consuming prey\nPREDATOR_FOOD_VALUE = 5\nPREDATOR_REPRODUCTION_TIME = 20 # The chronons before reproducing\n\nMAX_ENTITIES = 500 # The max number of organisms on the board\n# The number of entities to delete from the unbalanced side\nDELETE_UNBALANCED_ENTITIES = 50\n\n\nclass Entity:\n \"\"\"\n Represents an entity (either prey or predator).\n\n >>> e = Entity(True, coords=(0, 0))\n >>> e.prey\n True\n >>> e.coords\n (0, 0)\n >>> e.alive\n True\n \"\"\"\n\n def __init__(self, prey: bool, coords: tuple[int, int]) -> None:\n self.prey = prey\n # The (row, col) pos of the entity\n self.coords = coords\n\n self.remaining_reproduction_time = (\n PREY_REPRODUCTION_TIME if prey else PREDATOR_REPRODUCTION_TIME\n )\n self.energy_value = None if prey is True else PREDATOR_INITIAL_ENERGY_VALUE\n self.alive = True\n\n def reset_reproduction_time(self) -> None:\n \"\"\"\n >>> e = Entity(True, coords=(0, 0))\n >>> e.reset_reproduction_time()\n >>> e.remaining_reproduction_time == PREY_REPRODUCTION_TIME\n True\n >>> e = Entity(False, coords=(0, 0))\n >>> e.reset_reproduction_time()\n >>> e.remaining_reproduction_time == PREDATOR_REPRODUCTION_TIME\n True\n \"\"\"\n self.remaining_reproduction_time = (\n PREY_REPRODUCTION_TIME if self.prey is True else PREDATOR_REPRODUCTION_TIME\n )\n\n def __repr__(self) -> str:\n \"\"\"\n >>> Entity(prey=True, coords=(1, 1))\n Entity(prey=True, coords=(1, 1), remaining_reproduction_time=5)\n >>> Entity(prey=False, coords=(2, 1)) # doctest: +NORMALIZE_WHITESPACE\n Entity(prey=False, coords=(2, 1),\n remaining_reproduction_time=20, energy_value=15)\n \"\"\"\n repr_ = (\n f\"Entity(prey={self.prey}, coords={self.coords}, \"\n f\"remaining_reproduction_time={self.remaining_reproduction_time}\"\n )\n if self.energy_value is not None:\n repr_ += f\", energy_value={self.energy_value}\"\n return f\"{repr_})\"\n\n\nclass WaTor:\n \"\"\"\n Represents the main Wa-Tor algorithm.\n\n :attr time_passed: A function that is called every time\n time passes (a chronon) in order to visually display\n the new Wa-Tor planet. The time_passed function can block\n using time.sleep to slow the algorithm progression.\n\n >>> wt = WaTor(10, 15)\n >>> wt.width\n 10\n >>> wt.height\n 15\n >>> len(wt.planet)\n 15\n >>> len(wt.planet[0])\n 10\n >>> len(wt.get_entities()) == PREDATOR_INITIAL_COUNT + PREY_INITIAL_COUNT\n True\n \"\"\"\n\n time_passed: Callable[[\"WaTor\", int], None] | None\n\n def __init__(self, width: int, height: int) -> None:\n self.width = width\n self.height = height\n self.time_passed = None\n\n self.planet: list[list[Entity | None]] = [[None] * width for _ in range(height)]\n\n # Populate planet with predators and prey randomly\n for _ in range(PREY_INITIAL_COUNT):\n self.add_entity(prey=True)\n for _ in range(PREDATOR_INITIAL_COUNT):\n self.add_entity(prey=False)\n self.set_planet(self.planet)\n\n def set_planet(self, planet: list[list[Entity | None]]) -> None:\n \"\"\"\n Ease of access for testing\n\n >>> wt = WaTor(WIDTH, HEIGHT)\n >>> planet = [\n ... [None, None, None],\n ... [None, Entity(True, coords=(1, 1)), None]\n ... ]\n >>> wt.set_planet(planet)\n >>> wt.planet == planet\n True\n >>> wt.width\n 3\n >>> wt.height\n 2\n \"\"\"\n self.planet = planet\n self.width = len(planet[0])\n self.height = len(planet)\n\n def add_entity(self, prey: bool) -> None:\n \"\"\"\n Adds an entity, making sure the entity does\n not override another entity\n\n >>> wt = WaTor(WIDTH, HEIGHT)\n >>> wt.set_planet([[None, None], [None, None]])\n >>> wt.add_entity(True)\n >>> len(wt.get_entities())\n 1\n >>> wt.add_entity(False)\n >>> len(wt.get_entities())\n 2\n \"\"\"\n while True:\n row, col = randint(0, self.height - 1), randint(0, self.width - 1)\n if self.planet[row][col] is None:\n self.planet[row][col] = Entity(prey=prey, coords=(row, col))\n return\n\n def get_entities(self) -> list[Entity]:\n \"\"\"\n Returns a list of all the entities within the planet.\n\n >>> wt = WaTor(WIDTH, HEIGHT)\n >>> len(wt.get_entities()) == PREDATOR_INITIAL_COUNT + PREY_INITIAL_COUNT\n True\n \"\"\"\n return [entity for column in self.planet for entity in column if entity]\n\n def balance_predators_and_prey(self) -> None:\n \"\"\"\n Balances predators and preys so that prey\n can not dominate the predators, blocking up\n space for them to reproduce.\n\n >>> wt = WaTor(WIDTH, HEIGHT)\n >>> for i in range(2000):\n ... row, col = i \/\/ HEIGHT, i % WIDTH\n ... wt.planet[row][col] = Entity(True, coords=(row, col))\n >>> entities = len(wt.get_entities())\n >>> wt.balance_predators_and_prey()\n >>> len(wt.get_entities()) == entities\n False\n \"\"\"\n entities = self.get_entities()\n shuffle(entities)\n\n if len(entities) >= MAX_ENTITIES - MAX_ENTITIES \/ 10:\n prey = [entity for entity in entities if entity.prey]\n predators = [entity for entity in entities if not entity.prey]\n\n prey_count, predator_count = len(prey), len(predators)\n\n entities_to_purge = (\n prey[:DELETE_UNBALANCED_ENTITIES]\n if prey_count > predator_count\n else predators[:DELETE_UNBALANCED_ENTITIES]\n )\n for entity in entities_to_purge:\n self.planet[entity.coords[0]][entity.coords[1]] = None\n\n def get_surrounding_prey(self, entity: Entity) -> list[Entity]:\n \"\"\"\n Returns all the prey entities around (N, S, E, W) a predator entity.\n\n Subtly different to the try_to_move_to_unoccupied square.\n\n >>> wt = WaTor(WIDTH, HEIGHT)\n >>> wt.set_planet([\n ... [None, Entity(True, (0, 1)), None],\n ... [None, Entity(False, (1, 1)), None],\n ... [None, Entity(True, (2, 1)), None]])\n >>> wt.get_surrounding_prey(\n ... Entity(False, (1, 1))) # doctest: +NORMALIZE_WHITESPACE\n [Entity(prey=True, coords=(0, 1), remaining_reproduction_time=5),\n Entity(prey=True, coords=(2, 1), remaining_reproduction_time=5)]\n >>> wt.set_planet([[Entity(False, (0, 0))]])\n >>> wt.get_surrounding_prey(Entity(False, (0, 0)))\n []\n >>> wt.set_planet([\n ... [Entity(True, (0, 0)), Entity(False, (1, 0)), Entity(False, (2, 0))],\n ... [None, Entity(False, (1, 1)), Entity(True, (2, 1))],\n ... [None, None, None]])\n >>> wt.get_surrounding_prey(Entity(False, (1, 0)))\n [Entity(prey=True, coords=(0, 0), remaining_reproduction_time=5)]\n \"\"\"\n row, col = entity.coords\n adjacent: list[tuple[int, int]] = [\n (row - 1, col), # North\n (row + 1, col), # South\n (row, col - 1), # West\n (row, col + 1), # East\n ]\n\n return [\n ent\n for r, c in adjacent\n if 0 <= r < self.height\n and 0 <= c < self.width\n and (ent := self.planet[r][c]) is not None\n and ent.prey\n ]\n\n def move_and_reproduce(\n self, entity: Entity, direction_orders: list[Literal[\"N\", \"E\", \"S\", \"W\"]]\n ) -> None:\n \"\"\"\n Attempts to move to an unoccupied neighbouring square\n in either of the four directions (North, South, East, West).\n If the move was successful and the remaining_reproduction time is\n equal to 0, then a new prey or predator can also be created\n in the previous square.\n\n :param direction_orders: Ordered list (like priority queue) depicting\n order to attempt to move. Removes any systematic\n approach of checking neighbouring squares.\n\n >>> planet = [\n ... [None, None, None],\n ... [None, Entity(True, coords=(1, 1)), None],\n ... [None, None, None]\n ... ]\n >>> wt = WaTor(WIDTH, HEIGHT)\n >>> wt.set_planet(planet)\n >>> wt.move_and_reproduce(Entity(True, coords=(1, 1)), direction_orders=[\"N\"])\n >>> wt.planet # doctest: +NORMALIZE_WHITESPACE\n [[None, Entity(prey=True, coords=(0, 1), remaining_reproduction_time=4), None],\n [None, None, None],\n [None, None, None]]\n >>> wt.planet[0][0] = Entity(True, coords=(0, 0))\n >>> wt.move_and_reproduce(Entity(True, coords=(0, 1)),\n ... direction_orders=[\"N\", \"W\", \"E\", \"S\"])\n >>> wt.planet # doctest: +NORMALIZE_WHITESPACE\n [[Entity(prey=True, coords=(0, 0), remaining_reproduction_time=5), None,\n Entity(prey=True, coords=(0, 2), remaining_reproduction_time=4)],\n [None, None, None],\n [None, None, None]]\n >>> wt.planet[0][1] = wt.planet[0][2]\n >>> wt.planet[0][2] = None\n >>> wt.move_and_reproduce(Entity(True, coords=(0, 1)),\n ... direction_orders=[\"N\", \"W\", \"S\", \"E\"])\n >>> wt.planet # doctest: +NORMALIZE_WHITESPACE\n [[Entity(prey=True, coords=(0, 0), remaining_reproduction_time=5), None, None],\n [None, Entity(prey=True, coords=(1, 1), remaining_reproduction_time=4), None],\n [None, None, None]]\n\n >>> wt = WaTor(WIDTH, HEIGHT)\n >>> reproducable_entity = Entity(False, coords=(0, 1))\n >>> reproducable_entity.remaining_reproduction_time = 0\n >>> wt.planet = [[None, reproducable_entity]]\n >>> wt.move_and_reproduce(reproducable_entity,\n ... direction_orders=[\"N\", \"W\", \"S\", \"E\"])\n >>> wt.planet # doctest: +NORMALIZE_WHITESPACE\n [[Entity(prey=False, coords=(0, 0),\n remaining_reproduction_time=20, energy_value=15),\n Entity(prey=False, coords=(0, 1), remaining_reproduction_time=20,\n energy_value=15)]]\n \"\"\"\n row, col = coords = entity.coords\n\n adjacent_squares: dict[Literal[\"N\", \"E\", \"S\", \"W\"], tuple[int, int]] = {\n \"N\": (row - 1, col), # North\n \"S\": (row + 1, col), # South\n \"W\": (row, col - 1), # West\n \"E\": (row, col + 1), # East\n }\n # Weight adjacent locations\n adjacent: list[tuple[int, int]] = []\n for order in direction_orders:\n adjacent.append(adjacent_squares[order])\n\n for r, c in adjacent:\n if (\n 0 <= r < self.height\n and 0 <= c < self.width\n and self.planet[r][c] is None\n ):\n # Move entity to empty adjacent square\n self.planet[r][c] = entity\n self.planet[row][col] = None\n entity.coords = (r, c)\n break\n\n # (2.) See if it possible to reproduce in previous square\n if coords != entity.coords and entity.remaining_reproduction_time <= 0:\n # Check if the entities on the planet is less than the max limit\n if len(self.get_entities()) < MAX_ENTITIES:\n # Reproduce in previous square\n self.planet[row][col] = Entity(prey=entity.prey, coords=coords)\n entity.reset_reproduction_time()\n else:\n entity.remaining_reproduction_time -= 1\n\n def perform_prey_actions(\n self, entity: Entity, direction_orders: list[Literal[\"N\", \"E\", \"S\", \"W\"]]\n ) -> None:\n \"\"\"\n Performs the actions for a prey entity\n\n For prey the rules are:\n 1. At each chronon, a prey moves randomly to one of the adjacent unoccupied\n squares. If there are no free squares, no movement takes place.\n 2. Once a prey has survived a certain number of chronons it may reproduce.\n This is done as it moves to a neighbouring square,\n leaving behind a new prey in its old position.\n Its reproduction time is also reset to zero.\n\n >>> wt = WaTor(WIDTH, HEIGHT)\n >>> reproducable_entity = Entity(True, coords=(0, 1))\n >>> reproducable_entity.remaining_reproduction_time = 0\n >>> wt.planet = [[None, reproducable_entity]]\n >>> wt.perform_prey_actions(reproducable_entity,\n ... direction_orders=[\"N\", \"W\", \"S\", \"E\"])\n >>> wt.planet # doctest: +NORMALIZE_WHITESPACE\n [[Entity(prey=True, coords=(0, 0), remaining_reproduction_time=5),\n Entity(prey=True, coords=(0, 1), remaining_reproduction_time=5)]]\n \"\"\"\n self.move_and_reproduce(entity, direction_orders)\n\n def perform_predator_actions(\n self,\n entity: Entity,\n occupied_by_prey_coords: tuple[int, int] | None,\n direction_orders: list[Literal[\"N\", \"E\", \"S\", \"W\"]],\n ) -> None:\n \"\"\"\n Performs the actions for a predator entity\n\n :param occupied_by_prey_coords: Move to this location if there is prey there\n\n For predators the rules are:\n 1. At each chronon, a predator moves randomly to an adjacent square occupied\n by a prey. If there is none, the predator moves to a random adjacent\n unoccupied square. If there are no free squares, no movement takes place.\n 2. At each chronon, each predator is deprived of a unit of energy.\n 3. Upon reaching zero energy, a predator dies.\n 4. If a predator moves to a square occupied by a prey,\n it eats the prey and earns a certain amount of energy.\n 5. Once a predator has survived a certain number of chronons\n it may reproduce in exactly the same way as the prey.\n\n >>> wt = WaTor(WIDTH, HEIGHT)\n >>> wt.set_planet([[Entity(True, coords=(0, 0)), Entity(False, coords=(0, 1))]])\n >>> wt.perform_predator_actions(Entity(False, coords=(0, 1)), (0, 0), [])\n >>> wt.planet # doctest: +NORMALIZE_WHITESPACE\n [[Entity(prey=False, coords=(0, 0),\n remaining_reproduction_time=20, energy_value=19), None]]\n \"\"\"\n assert entity.energy_value is not None # [type checking]\n\n # (3.) If the entity has 0 energy, it will die\n if entity.energy_value == 0:\n self.planet[entity.coords[0]][entity.coords[1]] = None\n return\n\n # (1.) Move to entity if possible\n if occupied_by_prey_coords is not None:\n # Kill the prey\n prey = self.planet[occupied_by_prey_coords[0]][occupied_by_prey_coords[1]]\n assert prey is not None\n prey.alive = False\n\n # Move onto prey\n self.planet[occupied_by_prey_coords[0]][occupied_by_prey_coords[1]] = entity\n self.planet[entity.coords[0]][entity.coords[1]] = None\n\n entity.coords = occupied_by_prey_coords\n # (4.) Eats the prey and earns energy\n entity.energy_value += PREDATOR_FOOD_VALUE\n else:\n # (5.) If it has survived the certain number of chronons it will also\n # reproduce in this function\n self.move_and_reproduce(entity, direction_orders)\n\n # (2.) Each chronon, the predator is deprived of a unit of energy\n entity.energy_value -= 1\n\n def run(self, *, iteration_count: int) -> None:\n \"\"\"\n Emulate time passing by looping iteration_count times\n\n >>> wt = WaTor(WIDTH, HEIGHT)\n >>> wt.run(iteration_count=PREDATOR_INITIAL_ENERGY_VALUE - 1)\n >>> len(list(filter(lambda entity: entity.prey is False,\n ... wt.get_entities()))) >= PREDATOR_INITIAL_COUNT\n True\n \"\"\"\n for iter_num in range(iteration_count):\n # Generate list of all entities in order to randomly\n # pop an entity at a time to simulate true randomness\n # This removes the systematic approach of iterating\n # through each entity width by height\n all_entities = self.get_entities()\n\n for __ in range(len(all_entities)):\n entity = all_entities.pop(randint(0, len(all_entities) - 1))\n if entity.alive is False:\n continue\n\n directions: list[Literal[\"N\", \"E\", \"S\", \"W\"]] = [\"N\", \"E\", \"S\", \"W\"]\n shuffle(directions) # Randomly shuffle directions\n\n if entity.prey:\n self.perform_prey_actions(entity, directions)\n else:\n # Create list of surrounding prey\n surrounding_prey = self.get_surrounding_prey(entity)\n surrounding_prey_coords = None\n\n if surrounding_prey:\n # Again, randomly shuffle directions\n shuffle(surrounding_prey)\n surrounding_prey_coords = surrounding_prey[0].coords\n\n self.perform_predator_actions(\n entity, surrounding_prey_coords, directions\n )\n\n # Balance out the predators and prey\n self.balance_predators_and_prey()\n\n if self.time_passed is not None:\n # Call time_passed function for Wa-Tor planet\n # visualisation in a terminal or a graph.\n self.time_passed(self, iter_num)\n\n\ndef visualise(wt: WaTor, iter_number: int, *, colour: bool = True) -> None:\n \"\"\"\n Visually displays the Wa-Tor planet using\n an ascii code in terminal to clear and re-print\n the Wa-Tor planet at intervals.\n\n Uses ascii colour codes to colourfully display\n the predators and prey.\n\n (0x60f197) Prey = #\n (0xfffff) Predator = x\n\n >>> wt = WaTor(30, 30)\n >>> wt.set_planet([\n ... [Entity(True, coords=(0, 0)), Entity(False, coords=(0, 1)), None],\n ... [Entity(False, coords=(1, 0)), None, Entity(False, coords=(1, 2))],\n ... [None, Entity(True, coords=(2, 1)), None]\n ... ])\n >>> visualise(wt, 0, colour=False) # doctest: +NORMALIZE_WHITESPACE\n # x .\n x . x\n . # .\n \n Iteration: 0 | Prey count: 2 | Predator count: 3 |\n \"\"\"\n if colour:\n __import__(\"os\").system(\"\")\n print(\"\\x1b[0;0H\\x1b[2J\\x1b[?25l\")\n\n reprint = \"\\x1b[0;0H\" if colour else \"\"\n ansi_colour_end = \"\\x1b[0m \" if colour else \" \"\n\n planet = wt.planet\n output = \"\"\n\n # Iterate over every entity in the planet\n for row in planet:\n for entity in row:\n if entity is None:\n output += \" . \"\n else:\n if colour is True:\n output += (\n \"\\x1b[38;2;96;241;151m\"\n if entity.prey\n else \"\\x1b[38;2;255;255;15m\"\n )\n output += f\" {'#' if entity.prey else 'x'}{ansi_colour_end}\"\n\n output += \"\\n\"\n\n entities = wt.get_entities()\n prey_count = sum(entity.prey for entity in entities)\n\n print(\n f\"{output}\\n Iteration: {iter_number} | Prey count: {prey_count} | \"\n f\"Predator count: {len(entities) - prey_count} | {reprint}\"\n )\n # Block the thread to be able to visualise seeing the algorithm\n sleep(0.05)\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n\n wt = WaTor(WIDTH, HEIGHT)\n wt.time_passed = visualise\n wt.run(iteration_count=100_000)\n"} +{"Prompt":"Convert a string of characters to a sequence of numbers corresponding to the character's position in the alphabet. https:www.dcode.frletternumbercipher http:bestcodes.weebly.coma1z26.html encodemyname 13, 25, 14, 1, 13, 5 decode13, 25, 14, 1, 13, 5 'myname'","Completions":"from __future__ import annotations\n\n\ndef encode(plain: str) -> list[int]:\n \"\"\"\n >>> encode(\"myname\")\n [13, 25, 14, 1, 13, 5]\n \"\"\"\n return [ord(elem) - 96 for elem in plain]\n\n\ndef decode(encoded: list[int]) -> str:\n \"\"\"\n >>> decode([13, 25, 14, 1, 13, 5])\n 'myname'\n \"\"\"\n return \"\".join(chr(elem + 96) for elem in encoded)\n\n\ndef main() -> None:\n encoded = encode(input(\"-> \").strip().lower())\n print(\"Encoded: \", encoded)\n print(\"Decoded:\", decode(encoded))\n\n\nif __name__ == \"__main__\":\n main()\n"} +{"Prompt":"encryptmessage4545, 'The affine cipher is a type of monoalphabetic ' ... 'substitution cipher.' 'VLp MMIpHLGpvp pFsHpxMpyxIx JHL OFpvuOvFFuFxIpHLGi' decryptmessage4545, 'VLp MMIpHLGpvp pFsHpxMpyxIx JHL OFpvuOvFFuF' ... 'xIpHLGi' 'The affine cipher is a type of monoalphabetic substitution cipher.' key getrandomkey msg This is a test! decryptmessagekey, encryptmessagekey, msg msg True main","Completions":"import random\nimport sys\n\nfrom maths.greatest_common_divisor import gcd_by_iterative\n\nfrom . import cryptomath_module as cryptomath\n\nSYMBOLS = (\n r\"\"\" !\"#$%&'()*+,-.\/0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`\"\"\"\n r\"\"\"abcdefghijklmnopqrstuvwxyz{|}~\"\"\"\n)\n\n\ndef check_keys(key_a: int, key_b: int, mode: str) -> None:\n if mode == \"encrypt\":\n if key_a == 1:\n sys.exit(\n \"The affine cipher becomes weak when key \"\n \"A is set to 1. Choose different key\"\n )\n if key_b == 0:\n sys.exit(\n \"The affine cipher becomes weak when key \"\n \"B is set to 0. Choose different key\"\n )\n if key_a < 0 or key_b < 0 or key_b > len(SYMBOLS) - 1:\n sys.exit(\n \"Key A must be greater than 0 and key B must \"\n f\"be between 0 and {len(SYMBOLS) - 1}.\"\n )\n if gcd_by_iterative(key_a, len(SYMBOLS)) != 1:\n sys.exit(\n f\"Key A {key_a} and the symbol set size {len(SYMBOLS)} \"\n \"are not relatively prime. Choose a different key.\"\n )\n\n\ndef encrypt_message(key: int, message: str) -> str:\n \"\"\"\n >>> encrypt_message(4545, 'The affine cipher is a type of monoalphabetic '\n ... 'substitution cipher.')\n 'VL}p MM{I}p~{HL}Gp{vp pFsH}pxMpyxIx JHL O}F{~pvuOvF{FuF{xIp~{HL}Gi'\n \"\"\"\n key_a, key_b = divmod(key, len(SYMBOLS))\n check_keys(key_a, key_b, \"encrypt\")\n cipher_text = \"\"\n for symbol in message:\n if symbol in SYMBOLS:\n sym_index = SYMBOLS.find(symbol)\n cipher_text += SYMBOLS[(sym_index * key_a + key_b) % len(SYMBOLS)]\n else:\n cipher_text += symbol\n return cipher_text\n\n\ndef decrypt_message(key: int, message: str) -> str:\n \"\"\"\n >>> decrypt_message(4545, 'VL}p MM{I}p~{HL}Gp{vp pFsH}pxMpyxIx JHL O}F{~pvuOvF{FuF'\n ... '{xIp~{HL}Gi')\n 'The affine cipher is a type of monoalphabetic substitution cipher.'\n \"\"\"\n key_a, key_b = divmod(key, len(SYMBOLS))\n check_keys(key_a, key_b, \"decrypt\")\n plain_text = \"\"\n mod_inverse_of_key_a = cryptomath.find_mod_inverse(key_a, len(SYMBOLS))\n for symbol in message:\n if symbol in SYMBOLS:\n sym_index = SYMBOLS.find(symbol)\n plain_text += SYMBOLS[\n (sym_index - key_b) * mod_inverse_of_key_a % len(SYMBOLS)\n ]\n else:\n plain_text += symbol\n return plain_text\n\n\ndef get_random_key() -> int:\n while True:\n key_b = random.randint(2, len(SYMBOLS))\n key_b = random.randint(2, len(SYMBOLS))\n if gcd_by_iterative(key_b, len(SYMBOLS)) == 1 and key_b % len(SYMBOLS) != 0:\n return key_b * len(SYMBOLS) + key_b\n\n\ndef main() -> None:\n \"\"\"\n >>> key = get_random_key()\n >>> msg = \"This is a test!\"\n >>> decrypt_message(key, encrypt_message(key, msg)) == msg\n True\n \"\"\"\n message = input(\"Enter message: \").strip()\n key = int(input(\"Enter key [2000 - 9000]: \").strip())\n mode = input(\"Encrypt\/Decrypt [E\/D]: \").strip().lower()\n\n if mode.startswith(\"e\"):\n mode = \"encrypt\"\n translated = encrypt_message(key, message)\n elif mode.startswith(\"d\"):\n mode = \"decrypt\"\n translated = decrypt_message(key, message)\n print(f\"\\n{mode.title()}ed text: \\n{translated}\")\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n # main()\n"} +{"Prompt":"https:en.wikipedia.orgwikiAtbash import string def atbashslowsequence: str str: output for i in sequence: extract ordi if 65 extract 90: output chr155 extract elif 97 extract 122: output chr219 extract else: output i return output def atbashsequence: str str: letters string.asciiletters lettersreversed string.asciilowercase::1 string.asciiuppercase::1 return .join lettersreversedletters.indexc if c in letters else c for c in sequence def benchmark None:","Completions":"import string\n\n\ndef atbash_slow(sequence: str) -> str:\n \"\"\"\n >>> atbash_slow(\"ABCDEFG\")\n 'ZYXWVUT'\n\n >>> atbash_slow(\"aW;;123BX\")\n 'zD;;123YC'\n \"\"\"\n output = \"\"\n for i in sequence:\n extract = ord(i)\n if 65 <= extract <= 90:\n output += chr(155 - extract)\n elif 97 <= extract <= 122:\n output += chr(219 - extract)\n else:\n output += i\n return output\n\n\ndef atbash(sequence: str) -> str:\n \"\"\"\n >>> atbash(\"ABCDEFG\")\n 'ZYXWVUT'\n\n >>> atbash(\"aW;;123BX\")\n 'zD;;123YC'\n \"\"\"\n letters = string.ascii_letters\n letters_reversed = string.ascii_lowercase[::-1] + string.ascii_uppercase[::-1]\n return \"\".join(\n letters_reversed[letters.index(c)] if c in letters else c for c in sequence\n )\n\n\ndef benchmark() -> None:\n \"\"\"Let's benchmark our functions side-by-side...\"\"\"\n from timeit import timeit\n\n print(\"Running performance benchmarks...\")\n setup = \"from string import printable ; from __main__ import atbash, atbash_slow\"\n print(f\"> atbash_slow(): {timeit('atbash_slow(printable)', setup=setup)} seconds\")\n print(f\"> atbash(): {timeit('atbash(printable)', setup=setup)} seconds\")\n\n\nif __name__ == \"__main__\":\n for example in (\"ABCDEFGH\", \"123GGjj\", \"testStringtest\", \"with space\"):\n print(f\"{example} encrypted in atbash: {atbash(example)}\")\n benchmark()\n"} +{"Prompt":"https:en.wikipedia.orgwikiAutokeycipher An autokey cipher also known as the autoclave cipher is a cipher that incorporates the message the plaintext into the key. The key is generated from the message in some automated fashion, sometimes by selecting certain letters from the text or, more commonly, by adding a short primer key to the front of the message. Encrypt a given plaintext string and key string, returning the encrypted ciphertext. encrypthello world, coffee 'jsqqs avvwo' encryptcoffee is good as python, TheAlgorithms 'vvjfpk wj ohvp su ddylsv' encryptcoffee is good as python, 2 Traceback most recent call last: ... TypeError: key must be a string encrypt, TheAlgorithms Traceback most recent call last: ... ValueError: plaintext is empty Decrypt a given ciphertext string and key string, returning the decrypted ciphertext. decryptjsqqs avvwo, coffee 'hello world' decryptvvjfpk wj ohvp su ddylsv, TheAlgorithms 'coffee is good as python' decryptvvjfpk wj ohvp su ddylsv, Traceback most recent call last: ... ValueError: key is empty decrypt527.26, TheAlgorithms Traceback most recent call last: ... TypeError: ciphertext must be a string","Completions":"def encrypt(plaintext: str, key: str) -> str:\n \"\"\"\n Encrypt a given plaintext (string) and key (string), returning the\n encrypted ciphertext.\n >>> encrypt(\"hello world\", \"coffee\")\n 'jsqqs avvwo'\n >>> encrypt(\"coffee is good as python\", \"TheAlgorithms\")\n 'vvjfpk wj ohvp su ddylsv'\n >>> encrypt(\"coffee is good as python\", 2)\n Traceback (most recent call last):\n ...\n TypeError: key must be a string\n >>> encrypt(\"\", \"TheAlgorithms\")\n Traceback (most recent call last):\n ...\n ValueError: plaintext is empty\n \"\"\"\n if not isinstance(plaintext, str):\n raise TypeError(\"plaintext must be a string\")\n if not isinstance(key, str):\n raise TypeError(\"key must be a string\")\n\n if not plaintext:\n raise ValueError(\"plaintext is empty\")\n if not key:\n raise ValueError(\"key is empty\")\n\n key += plaintext\n plaintext = plaintext.lower()\n key = key.lower()\n plaintext_iterator = 0\n key_iterator = 0\n ciphertext = \"\"\n while plaintext_iterator < len(plaintext):\n if (\n ord(plaintext[plaintext_iterator]) < 97\n or ord(plaintext[plaintext_iterator]) > 122\n ):\n ciphertext += plaintext[plaintext_iterator]\n plaintext_iterator += 1\n elif ord(key[key_iterator]) < 97 or ord(key[key_iterator]) > 122:\n key_iterator += 1\n else:\n ciphertext += chr(\n (\n (ord(plaintext[plaintext_iterator]) - 97 + ord(key[key_iterator]))\n - 97\n )\n % 26\n + 97\n )\n key_iterator += 1\n plaintext_iterator += 1\n return ciphertext\n\n\ndef decrypt(ciphertext: str, key: str) -> str:\n \"\"\"\n Decrypt a given ciphertext (string) and key (string), returning the decrypted\n ciphertext.\n >>> decrypt(\"jsqqs avvwo\", \"coffee\")\n 'hello world'\n >>> decrypt(\"vvjfpk wj ohvp su ddylsv\", \"TheAlgorithms\")\n 'coffee is good as python'\n >>> decrypt(\"vvjfpk wj ohvp su ddylsv\", \"\")\n Traceback (most recent call last):\n ...\n ValueError: key is empty\n >>> decrypt(527.26, \"TheAlgorithms\")\n Traceback (most recent call last):\n ...\n TypeError: ciphertext must be a string\n \"\"\"\n if not isinstance(ciphertext, str):\n raise TypeError(\"ciphertext must be a string\")\n if not isinstance(key, str):\n raise TypeError(\"key must be a string\")\n\n if not ciphertext:\n raise ValueError(\"ciphertext is empty\")\n if not key:\n raise ValueError(\"key is empty\")\n\n key = key.lower()\n ciphertext_iterator = 0\n key_iterator = 0\n plaintext = \"\"\n while ciphertext_iterator < len(ciphertext):\n if (\n ord(ciphertext[ciphertext_iterator]) < 97\n or ord(ciphertext[ciphertext_iterator]) > 122\n ):\n plaintext += ciphertext[ciphertext_iterator]\n else:\n plaintext += chr(\n (ord(ciphertext[ciphertext_iterator]) - ord(key[key_iterator])) % 26\n + 97\n )\n key += chr(\n (ord(ciphertext[ciphertext_iterator]) - ord(key[key_iterator])) % 26\n + 97\n )\n key_iterator += 1\n ciphertext_iterator += 1\n return plaintext\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n operation = int(input(\"Type 1 to encrypt or 2 to decrypt:\"))\n if operation == 1:\n plaintext = input(\"Typeplaintext to be encrypted:\\n\")\n key = input(\"Type the key:\\n\")\n print(encrypt(plaintext, key))\n elif operation == 2:\n ciphertext = input(\"Type the ciphertext to be decrypted:\\n\")\n key = input(\"Type the key:\\n\")\n print(decrypt(ciphertext, key))\n decrypt(\"jsqqs avvwo\", \"coffee\")\n"} +{"Prompt":"Program to encode and decode Baconian or Bacon's Cipher Wikipedia reference : https:en.wikipedia.orgwikiBacon27scipher Encodes to Baconian cipher encodehello 'AABBBAABAAABABAABABAABBAB' encodehello world 'AABBBAABAAABABAABABAABBAB BABAAABBABBAAAAABABAAAABB' encodehello world! Traceback most recent call last: ... Exception: encode accepts only letters of the alphabet and spaces Decodes from Baconian cipher decodeAABBBAABAAABABAABABAABBAB BABAAABBABBAAAAABABAAAABB 'hello world' decodeAABBBAABAAABABAABABAABBAB 'hello' decodeAABBBAABAAABABAABABAABBAB BABAAABBABBAAAAABABAAAABB! Traceback most recent call last: ... Exception: decode accepts only 'A', 'B' and spaces","Completions":"encode_dict = {\n \"a\": \"AAAAA\",\n \"b\": \"AAAAB\",\n \"c\": \"AAABA\",\n \"d\": \"AAABB\",\n \"e\": \"AABAA\",\n \"f\": \"AABAB\",\n \"g\": \"AABBA\",\n \"h\": \"AABBB\",\n \"i\": \"ABAAA\",\n \"j\": \"BBBAA\",\n \"k\": \"ABAAB\",\n \"l\": \"ABABA\",\n \"m\": \"ABABB\",\n \"n\": \"ABBAA\",\n \"o\": \"ABBAB\",\n \"p\": \"ABBBA\",\n \"q\": \"ABBBB\",\n \"r\": \"BAAAA\",\n \"s\": \"BAAAB\",\n \"t\": \"BAABA\",\n \"u\": \"BAABB\",\n \"v\": \"BBBAB\",\n \"w\": \"BABAA\",\n \"x\": \"BABAB\",\n \"y\": \"BABBA\",\n \"z\": \"BABBB\",\n \" \": \" \",\n}\n\n\ndecode_dict = {value: key for key, value in encode_dict.items()}\n\n\ndef encode(word: str) -> str:\n \"\"\"\n Encodes to Baconian cipher\n\n >>> encode(\"hello\")\n 'AABBBAABAAABABAABABAABBAB'\n >>> encode(\"hello world\")\n 'AABBBAABAAABABAABABAABBAB BABAAABBABBAAAAABABAAAABB'\n >>> encode(\"hello world!\")\n Traceback (most recent call last):\n ...\n Exception: encode() accepts only letters of the alphabet and spaces\n \"\"\"\n encoded = \"\"\n for letter in word.lower():\n if letter.isalpha() or letter == \" \":\n encoded += encode_dict[letter]\n else:\n raise Exception(\"encode() accepts only letters of the alphabet and spaces\")\n return encoded\n\n\ndef decode(coded: str) -> str:\n \"\"\"\n Decodes from Baconian cipher\n\n >>> decode(\"AABBBAABAAABABAABABAABBAB BABAAABBABBAAAAABABAAAABB\")\n 'hello world'\n >>> decode(\"AABBBAABAAABABAABABAABBAB\")\n 'hello'\n >>> decode(\"AABBBAABAAABABAABABAABBAB BABAAABBABBAAAAABABAAAABB!\")\n Traceback (most recent call last):\n ...\n Exception: decode() accepts only 'A', 'B' and spaces\n \"\"\"\n if set(coded) - {\"A\", \"B\", \" \"} != set():\n raise Exception(\"decode() accepts only 'A', 'B' and spaces\")\n decoded = \"\"\n for word in coded.split():\n while len(word) != 0:\n decoded += decode_dict[word[:5]]\n word = word[5:]\n decoded += \" \"\n return decoded.strip()\n\n\nif __name__ == \"__main__\":\n from doctest import testmod\n\n testmod()\n"} +{"Prompt":"Encodes the given bytes into base16. base16encodeb'Hello World!' '48656C6C6F20576F726C6421' base16encodeb'HELLO WORLD!' '48454C4C4F20574F524C4421' base16encodeb'' '' Turn the data into a list of integers where each integer is a byte, Then turn each byte into its hexadecimal representation, make sure it is uppercase, and then join everything together and return it. Decodes the given base16 encoded data into bytes. base16decode'48656C6C6F20576F726C6421' b'Hello World!' base16decode'48454C4C4F20574F524C4421' b'HELLO WORLD!' base16decode'' b'' base16decode'486' Traceback most recent call last: ... ValueError: Base16 encoded data is invalid: Data does not have an even number of hex digits. base16decode'48656c6c6f20576f726c6421' Traceback most recent call last: ... ValueError: Base16 encoded data is invalid: Data is not uppercase hex or it contains invalid characters. base16decode'This is not base64 encoded data.' Traceback most recent call last: ... ValueError: Base16 encoded data is invalid: Data is not uppercase hex or it contains invalid characters. Check data validity, following RFC3548 https:www.ietf.orgrfcrfc3548.txt Base16 encoded data is invalid: Data does not have an even number of hex digits. Check the character set the standard base16 alphabet is uppercase according to RFC3548 section 6 if not setdata set0123456789ABCDEF: raise ValueError For every two hexadecimal digits a byte, turn it into an integer. Then, string the result together into bytes, and return it.","Completions":"def base16_encode(data: bytes) -> str:\n \"\"\"\n Encodes the given bytes into base16.\n\n >>> base16_encode(b'Hello World!')\n '48656C6C6F20576F726C6421'\n >>> base16_encode(b'HELLO WORLD!')\n '48454C4C4F20574F524C4421'\n >>> base16_encode(b'')\n ''\n \"\"\"\n # Turn the data into a list of integers (where each integer is a byte),\n # Then turn each byte into its hexadecimal representation, make sure\n # it is uppercase, and then join everything together and return it.\n return \"\".join([hex(byte)[2:].zfill(2).upper() for byte in list(data)])\n\n\ndef base16_decode(data: str) -> bytes:\n \"\"\"\n Decodes the given base16 encoded data into bytes.\n\n >>> base16_decode('48656C6C6F20576F726C6421')\n b'Hello World!'\n >>> base16_decode('48454C4C4F20574F524C4421')\n b'HELLO WORLD!'\n >>> base16_decode('')\n b''\n >>> base16_decode('486')\n Traceback (most recent call last):\n ...\n ValueError: Base16 encoded data is invalid:\n Data does not have an even number of hex digits.\n >>> base16_decode('48656c6c6f20576f726c6421')\n Traceback (most recent call last):\n ...\n ValueError: Base16 encoded data is invalid:\n Data is not uppercase hex or it contains invalid characters.\n >>> base16_decode('This is not base64 encoded data.')\n Traceback (most recent call last):\n ...\n ValueError: Base16 encoded data is invalid:\n Data is not uppercase hex or it contains invalid characters.\n \"\"\"\n # Check data validity, following RFC3548\n # https:\/\/www.ietf.org\/rfc\/rfc3548.txt\n if (len(data) % 2) != 0:\n raise ValueError(\n \"\"\"Base16 encoded data is invalid:\nData does not have an even number of hex digits.\"\"\"\n )\n # Check the character set - the standard base16 alphabet\n # is uppercase according to RFC3548 section 6\n if not set(data) <= set(\"0123456789ABCDEF\"):\n raise ValueError(\n \"\"\"Base16 encoded data is invalid:\nData is not uppercase hex or it contains invalid characters.\"\"\"\n )\n # For every two hexadecimal digits (= a byte), turn it into an integer.\n # Then, string the result together into bytes, and return it.\n return bytes(int(data[i] + data[i + 1], 16) for i in range(0, len(data), 2))\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Base32 encoding and decoding https:en.wikipedia.orgwikiBase32 base32encodebHello World! b'JBSWY3DPEBLW64TMMQQQ' base32encodeb123456 b'GEZDGNBVGY' base32encodebsome long complex string b'ONXW2ZJANRXW4ZZAMNXW24DMMV4CA43UOJUW4ZY' base32decodeb'JBSWY3DPEBLW64TMMQQQ' b'Hello World!' base32decodeb'GEZDGNBVGY' b'123456' base32decodeb'ONXW2ZJANRXW4ZZAMNXW24DMMV4CA43UOJUW4ZY' b'some long complex string'","Completions":"B32_CHARSET = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567\"\n\n\ndef base32_encode(data: bytes) -> bytes:\n \"\"\"\n >>> base32_encode(b\"Hello World!\")\n b'JBSWY3DPEBLW64TMMQQQ===='\n >>> base32_encode(b\"123456\")\n b'GEZDGNBVGY======'\n >>> base32_encode(b\"some long complex string\")\n b'ONXW2ZJANRXW4ZZAMNXW24DMMV4CA43UOJUW4ZY='\n \"\"\"\n binary_data = \"\".join(bin(ord(d))[2:].zfill(8) for d in data.decode(\"utf-8\"))\n binary_data = binary_data.ljust(5 * ((len(binary_data) \/\/ 5) + 1), \"0\")\n b32_chunks = map(\"\".join, zip(*[iter(binary_data)] * 5))\n b32_result = \"\".join(B32_CHARSET[int(chunk, 2)] for chunk in b32_chunks)\n return bytes(b32_result.ljust(8 * ((len(b32_result) \/\/ 8) + 1), \"=\"), \"utf-8\")\n\n\ndef base32_decode(data: bytes) -> bytes:\n \"\"\"\n >>> base32_decode(b'JBSWY3DPEBLW64TMMQQQ====')\n b'Hello World!'\n >>> base32_decode(b'GEZDGNBVGY======')\n b'123456'\n >>> base32_decode(b'ONXW2ZJANRXW4ZZAMNXW24DMMV4CA43UOJUW4ZY=')\n b'some long complex string'\n \"\"\"\n binary_chunks = \"\".join(\n bin(B32_CHARSET.index(_d))[2:].zfill(5)\n for _d in data.decode(\"utf-8\").strip(\"=\")\n )\n binary_data = list(map(\"\".join, zip(*[iter(binary_chunks)] * 8)))\n return bytes(\"\".join([chr(int(_d, 2)) for _d in binary_data]), \"utf-8\")\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Encodes data according to RFC4648. The data is first transformed to binary and appended with binary digits so that its length becomes a multiple of 6, then each 6 binary digits will match a character in the B64CHARSET string. The number of appended binary digits would later determine how many signs should be added, the padding. For every 2 binary digits added, a sign is added in the output. We can add any binary digits to make it a multiple of 6, for instance, consider the following example: AA 0010100100101001 001010 010010 1001 As can be seen above, 2 more binary digits should be added, so there's 4 possibilities here: 00, 01, 10 or 11. That being said, Base64 encoding can be used in Steganography to hide data in these appended digits. from base64 import b64encode a bThis pull request is part of Hacktoberfest20! b bhttps:tools.ietf.orghtmlrfc4648 c bA base64encodea b64encodea True base64encodeb b64encodeb True base64encodec b64encodec True base64encodeabc Traceback most recent call last: ... TypeError: a byteslike object is required, not 'str' Make sure the supplied data is a byteslike object The padding that will be added later Append binarystream with arbitrary binary digits 0's by default to make its length a multiple of 6. Encode every 6 binary digits to their corresponding Base64 character Decodes data according to RFC4648. This does the reverse operation of base64encode. We first transform the encoded data back to a binary stream, take off the previously appended binary digits according to the padding, at this point we would have a binary stream whose length is multiple of 8, the last step is to convert every 8 bits to a byte. from base64 import b64decode a VGhpcyBwdWxsIHJlcXVlc3QgaXMgcGFydCBvZiBIYWNrdG9iZXJmZXN0MjAh b aHR0cHM6Ly90b29scy5pZXRmLm9yZy9odG1sL3JmYzQ2NDg c QQ base64decodea b64decodea True base64decodeb b64decodeb True base64decodec b64decodec True base64decodeabc Traceback most recent call last: ... AssertionError: Incorrect padding Make sure encodeddata is either a string or a byteslike object In case encodeddata is a byteslike object, make sure it contains only ASCII characters so we convert it to a string object Check if the encoded string contains non base64 characters Check the padding Remove padding if there is one","Completions":"B64_CHARSET = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+\/\"\n\n\ndef base64_encode(data: bytes) -> bytes:\n \"\"\"Encodes data according to RFC4648.\n\n The data is first transformed to binary and appended with binary digits so that its\n length becomes a multiple of 6, then each 6 binary digits will match a character in\n the B64_CHARSET string. The number of appended binary digits would later determine\n how many \"=\" signs should be added, the padding.\n For every 2 binary digits added, a \"=\" sign is added in the output.\n We can add any binary digits to make it a multiple of 6, for instance, consider the\n following example:\n \"AA\" -> 0010100100101001 -> 001010 010010 1001\n As can be seen above, 2 more binary digits should be added, so there's 4\n possibilities here: 00, 01, 10 or 11.\n That being said, Base64 encoding can be used in Steganography to hide data in these\n appended digits.\n\n >>> from base64 import b64encode\n >>> a = b\"This pull request is part of Hacktoberfest20!\"\n >>> b = b\"https:\/\/tools.ietf.org\/html\/rfc4648\"\n >>> c = b\"A\"\n >>> base64_encode(a) == b64encode(a)\n True\n >>> base64_encode(b) == b64encode(b)\n True\n >>> base64_encode(c) == b64encode(c)\n True\n >>> base64_encode(\"abc\")\n Traceback (most recent call last):\n ...\n TypeError: a bytes-like object is required, not 'str'\n \"\"\"\n # Make sure the supplied data is a bytes-like object\n if not isinstance(data, bytes):\n msg = f\"a bytes-like object is required, not '{data.__class__.__name__}'\"\n raise TypeError(msg)\n\n binary_stream = \"\".join(bin(byte)[2:].zfill(8) for byte in data)\n\n padding_needed = len(binary_stream) % 6 != 0\n\n if padding_needed:\n # The padding that will be added later\n padding = b\"=\" * ((6 - len(binary_stream) % 6) \/\/ 2)\n\n # Append binary_stream with arbitrary binary digits (0's by default) to make its\n # length a multiple of 6.\n binary_stream += \"0\" * (6 - len(binary_stream) % 6)\n else:\n padding = b\"\"\n\n # Encode every 6 binary digits to their corresponding Base64 character\n return (\n \"\".join(\n B64_CHARSET[int(binary_stream[index : index + 6], 2)]\n for index in range(0, len(binary_stream), 6)\n ).encode()\n + padding\n )\n\n\ndef base64_decode(encoded_data: str) -> bytes:\n \"\"\"Decodes data according to RFC4648.\n\n This does the reverse operation of base64_encode.\n We first transform the encoded data back to a binary stream, take off the\n previously appended binary digits according to the padding, at this point we\n would have a binary stream whose length is multiple of 8, the last step is\n to convert every 8 bits to a byte.\n\n >>> from base64 import b64decode\n >>> a = \"VGhpcyBwdWxsIHJlcXVlc3QgaXMgcGFydCBvZiBIYWNrdG9iZXJmZXN0MjAh\"\n >>> b = \"aHR0cHM6Ly90b29scy5pZXRmLm9yZy9odG1sL3JmYzQ2NDg=\"\n >>> c = \"QQ==\"\n >>> base64_decode(a) == b64decode(a)\n True\n >>> base64_decode(b) == b64decode(b)\n True\n >>> base64_decode(c) == b64decode(c)\n True\n >>> base64_decode(\"abc\")\n Traceback (most recent call last):\n ...\n AssertionError: Incorrect padding\n \"\"\"\n # Make sure encoded_data is either a string or a bytes-like object\n if not isinstance(encoded_data, bytes) and not isinstance(encoded_data, str):\n msg = (\n \"argument should be a bytes-like object or ASCII string, \"\n f\"not '{encoded_data.__class__.__name__}'\"\n )\n raise TypeError(msg)\n\n # In case encoded_data is a bytes-like object, make sure it contains only\n # ASCII characters so we convert it to a string object\n if isinstance(encoded_data, bytes):\n try:\n encoded_data = encoded_data.decode(\"utf-8\")\n except UnicodeDecodeError:\n raise ValueError(\"base64 encoded data should only contain ASCII characters\")\n\n padding = encoded_data.count(\"=\")\n\n # Check if the encoded string contains non base64 characters\n if padding:\n assert all(\n char in B64_CHARSET for char in encoded_data[:-padding]\n ), \"Invalid base64 character(s) found.\"\n else:\n assert all(\n char in B64_CHARSET for char in encoded_data\n ), \"Invalid base64 character(s) found.\"\n\n # Check the padding\n assert len(encoded_data) % 4 == 0 and padding < 3, \"Incorrect padding\"\n\n if padding:\n # Remove padding if there is one\n encoded_data = encoded_data[:-padding]\n\n binary_stream = \"\".join(\n bin(B64_CHARSET.index(char))[2:].zfill(6) for char in encoded_data\n )[: -padding * 2]\n else:\n binary_stream = \"\".join(\n bin(B64_CHARSET.index(char))[2:].zfill(6) for char in encoded_data\n )\n\n data = [\n int(binary_stream[index : index + 8], 2)\n for index in range(0, len(binary_stream), 8)\n ]\n\n return bytes(data)\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Base85 Ascii85 encoding and decoding https:en.wikipedia.orgwikiAscii85 ascii85encodeb b'' ascii85encodeb12345 b'0etOA2' ascii85encodebbase 85 b'UXh?24' ascii85decodeb b'' ascii85decodeb0etOA2 b'12345' ascii85decodebUXh?24 b'base 85'","Completions":"def _base10_to_85(d: int) -> str:\n return \"\".join(chr(d % 85 + 33)) + _base10_to_85(d \/\/ 85) if d > 0 else \"\"\n\n\ndef _base85_to_10(digits: list) -> int:\n return sum(char * 85**i for i, char in enumerate(reversed(digits)))\n\n\ndef ascii85_encode(data: bytes) -> bytes:\n \"\"\"\n >>> ascii85_encode(b\"\")\n b''\n >>> ascii85_encode(b\"12345\")\n b'0etOA2#'\n >>> ascii85_encode(b\"base 85\")\n b'@UX=h+?24'\n \"\"\"\n binary_data = \"\".join(bin(ord(d))[2:].zfill(8) for d in data.decode(\"utf-8\"))\n null_values = (32 * ((len(binary_data) \/\/ 32) + 1) - len(binary_data)) \/\/ 8\n binary_data = binary_data.ljust(32 * ((len(binary_data) \/\/ 32) + 1), \"0\")\n b85_chunks = [int(_s, 2) for _s in map(\"\".join, zip(*[iter(binary_data)] * 32))]\n result = \"\".join(_base10_to_85(chunk)[::-1] for chunk in b85_chunks)\n return bytes(result[:-null_values] if null_values % 4 != 0 else result, \"utf-8\")\n\n\ndef ascii85_decode(data: bytes) -> bytes:\n \"\"\"\n >>> ascii85_decode(b\"\")\n b''\n >>> ascii85_decode(b\"0etOA2#\")\n b'12345'\n >>> ascii85_decode(b\"@UX=h+?24\")\n b'base 85'\n \"\"\"\n null_values = 5 * ((len(data) \/\/ 5) + 1) - len(data)\n binary_data = data.decode(\"utf-8\") + \"u\" * null_values\n b85_chunks = map(\"\".join, zip(*[iter(binary_data)] * 5))\n b85_segments = [[ord(_s) - 33 for _s in chunk] for chunk in b85_chunks]\n results = [bin(_base85_to_10(chunk))[2::].zfill(32) for chunk in b85_segments]\n char_chunks = [\n [chr(int(_s, 2)) for _s in map(\"\".join, zip(*[iter(r)] * 8))] for r in results\n ]\n result = \"\".join(\"\".join(char) for char in char_chunks)\n offset = int(null_values % 5 == 0)\n return bytes(result[: offset - null_values], \"utf-8\")\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Author: Mohit Radadiya This function generates the key in a cyclic manner until it's length isn't equal to the length of original text generatekeyTHE GERMAN ATTACK,SECRET 'SECRETSECRETSECRE' This function returns the encrypted text generated with the help of the key ciphertextTHE GERMAN ATTACK,SECRETSECRETSECRE 'BDC PAYUWL JPAIYI' This function decrypts the encrypted text and returns the original text originaltextBDC PAYUWL JPAIYI,SECRETSECRETSECRE 'THE GERMAN ATTACK'","Completions":"from string import ascii_uppercase\n\ndict1 = {char: i for i, char in enumerate(ascii_uppercase)}\ndict2 = dict(enumerate(ascii_uppercase))\n\n\n# This function generates the key in\n# a cyclic manner until it's length isn't\n# equal to the length of original text\ndef generate_key(message: str, key: str) -> str:\n \"\"\"\n >>> generate_key(\"THE GERMAN ATTACK\",\"SECRET\")\n 'SECRETSECRETSECRE'\n \"\"\"\n x = len(message)\n i = 0\n while True:\n if x == i:\n i = 0\n if len(key) == len(message):\n break\n key += key[i]\n i += 1\n return key\n\n\n# This function returns the encrypted text\n# generated with the help of the key\ndef cipher_text(message: str, key_new: str) -> str:\n \"\"\"\n >>> cipher_text(\"THE GERMAN ATTACK\",\"SECRETSECRETSECRE\")\n 'BDC PAYUWL JPAIYI'\n \"\"\"\n cipher_text = \"\"\n i = 0\n for letter in message:\n if letter == \" \":\n cipher_text += \" \"\n else:\n x = (dict1[letter] - dict1[key_new[i]]) % 26\n i += 1\n cipher_text += dict2[x]\n return cipher_text\n\n\n# This function decrypts the encrypted text\n# and returns the original text\ndef original_text(cipher_text: str, key_new: str) -> str:\n \"\"\"\n >>> original_text(\"BDC PAYUWL JPAIYI\",\"SECRETSECRETSECRE\")\n 'THE GERMAN ATTACK'\n \"\"\"\n or_txt = \"\"\n i = 0\n for letter in cipher_text:\n if letter == \" \":\n or_txt += \" \"\n else:\n x = (dict1[letter] + dict1[key_new[i]] + 26) % 26\n i += 1\n or_txt += dict2[x]\n return or_txt\n\n\ndef main() -> None:\n message = \"THE GERMAN ATTACK\"\n key = \"SECRET\"\n key_new = generate_key(message, key)\n s = cipher_text(message, key_new)\n print(f\"Encrypted Text = {s}\")\n print(f\"Original Text = {original_text(s, key_new)}\")\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n main()\n"} +{"Prompt":"!usrbinenv python3 The Bifid Cipher uses a Polybius Square to encipher a message in a way that makes it fairly difficult to decipher without knowing the secret. https:www.braingle.combrainteaserscodesbifid.php Return the pair of numbers that represents the given letter in the polybius square np.arrayequalBifidCipher.lettertonumbers'a', 1,1 True np.arrayequalBifidCipher.lettertonumbers'u', 4,5 True Return the letter corresponding to the position index1, index2 in the polybius square BifidCipher.numberstoletter4, 5 u True BifidCipher.numberstoletter1, 1 a True Return the encoded version of message according to the polybius cipher BifidCipher.encode'testmessage' 'qtltbdxrxlk' True BifidCipher.encode'Test Message' 'qtltbdxrxlk' True BifidCipher.encode'test j' BifidCipher.encode'test i' True Return the decoded version of message according to the polybius cipher BifidCipher.decode'qtltbdxrxlk' 'testmessage' True","Completions":"#!\/usr\/bin\/env python3\n\n\"\"\"\nThe Bifid Cipher uses a Polybius Square to encipher a message in a way that\nmakes it fairly difficult to decipher without knowing the secret.\n\nhttps:\/\/www.braingle.com\/brainteasers\/codes\/bifid.php\n\"\"\"\n\nimport numpy as np\n\nSQUARE = [\n [\"a\", \"b\", \"c\", \"d\", \"e\"],\n [\"f\", \"g\", \"h\", \"i\", \"k\"],\n [\"l\", \"m\", \"n\", \"o\", \"p\"],\n [\"q\", \"r\", \"s\", \"t\", \"u\"],\n [\"v\", \"w\", \"x\", \"y\", \"z\"],\n]\n\n\nclass BifidCipher:\n def __init__(self) -> None:\n self.SQUARE = np.array(SQUARE)\n\n def letter_to_numbers(self, letter: str) -> np.ndarray:\n \"\"\"\n Return the pair of numbers that represents the given letter in the\n polybius square\n\n >>> np.array_equal(BifidCipher().letter_to_numbers('a'), [1,1])\n True\n\n >>> np.array_equal(BifidCipher().letter_to_numbers('u'), [4,5])\n True\n \"\"\"\n index1, index2 = np.where(letter == self.SQUARE)\n indexes = np.concatenate([index1 + 1, index2 + 1])\n return indexes\n\n def numbers_to_letter(self, index1: int, index2: int) -> str:\n \"\"\"\n Return the letter corresponding to the position [index1, index2] in\n the polybius square\n\n >>> BifidCipher().numbers_to_letter(4, 5) == \"u\"\n True\n\n >>> BifidCipher().numbers_to_letter(1, 1) == \"a\"\n True\n \"\"\"\n letter = self.SQUARE[index1 - 1, index2 - 1]\n return letter\n\n def encode(self, message: str) -> str:\n \"\"\"\n Return the encoded version of message according to the polybius cipher\n\n >>> BifidCipher().encode('testmessage') == 'qtltbdxrxlk'\n True\n\n >>> BifidCipher().encode('Test Message') == 'qtltbdxrxlk'\n True\n\n >>> BifidCipher().encode('test j') == BifidCipher().encode('test i')\n True\n \"\"\"\n message = message.lower()\n message = message.replace(\" \", \"\")\n message = message.replace(\"j\", \"i\")\n\n first_step = np.empty((2, len(message)))\n for letter_index in range(len(message)):\n numbers = self.letter_to_numbers(message[letter_index])\n\n first_step[0, letter_index] = numbers[0]\n first_step[1, letter_index] = numbers[1]\n\n second_step = first_step.reshape(2 * len(message))\n encoded_message = \"\"\n for numbers_index in range(len(message)):\n index1 = int(second_step[numbers_index * 2])\n index2 = int(second_step[(numbers_index * 2) + 1])\n letter = self.numbers_to_letter(index1, index2)\n encoded_message = encoded_message + letter\n\n return encoded_message\n\n def decode(self, message: str) -> str:\n \"\"\"\n Return the decoded version of message according to the polybius cipher\n\n >>> BifidCipher().decode('qtltbdxrxlk') == 'testmessage'\n True\n \"\"\"\n message = message.lower()\n message.replace(\" \", \"\")\n first_step = np.empty(2 * len(message))\n for letter_index in range(len(message)):\n numbers = self.letter_to_numbers(message[letter_index])\n first_step[letter_index * 2] = numbers[0]\n first_step[letter_index * 2 + 1] = numbers[1]\n\n second_step = first_step.reshape((2, len(message)))\n decoded_message = \"\"\n for numbers_index in range(len(message)):\n index1 = int(second_step[0, numbers_index])\n index2 = int(second_step[1, numbers_index])\n letter = self.numbers_to_letter(index1, index2)\n decoded_message = decoded_message + letter\n\n return decoded_message\n"} +{"Prompt":"decrypt'TMDETUX PMDVU' Decryption using Key 0: TMDETUX PMDVU Decryption using Key 1: SLCDSTW OLCUT Decryption using Key 2: RKBCRSV NKBTS Decryption using Key 3: QJABQRU MJASR Decryption using Key 4: PIZAPQT LIZRQ Decryption using Key 5: OHYZOPS KHYQP Decryption using Key 6: NGXYNOR JGXPO Decryption using Key 7: MFWXMNQ IFWON Decryption using Key 8: LEVWLMP HEVNM Decryption using Key 9: KDUVKLO GDUML Decryption using Key 10: JCTUJKN FCTLK Decryption using Key 11: IBSTIJM EBSKJ Decryption using Key 12: HARSHIL DARJI Decryption using Key 13: GZQRGHK CZQIH Decryption using Key 14: FYPQFGJ BYPHG Decryption using Key 15: EXOPEFI AXOGF Decryption using Key 16: DWNODEH ZWNFE Decryption using Key 17: CVMNCDG YVMED Decryption using Key 18: BULMBCF XULDC Decryption using Key 19: ATKLABE WTKCB Decryption using Key 20: ZSJKZAD VSJBA Decryption using Key 21: YRIJYZC URIAZ Decryption using Key 22: XQHIXYB TQHZY Decryption using Key 23: WPGHWXA SPGYX Decryption using Key 24: VOFGVWZ ROFXW Decryption using Key 25: UNEFUVY QNEWV","Completions":"import string\n\n\ndef decrypt(message: str) -> None:\n \"\"\"\n >>> decrypt('TMDETUX PMDVU')\n Decryption using Key #0: TMDETUX PMDVU\n Decryption using Key #1: SLCDSTW OLCUT\n Decryption using Key #2: RKBCRSV NKBTS\n Decryption using Key #3: QJABQRU MJASR\n Decryption using Key #4: PIZAPQT LIZRQ\n Decryption using Key #5: OHYZOPS KHYQP\n Decryption using Key #6: NGXYNOR JGXPO\n Decryption using Key #7: MFWXMNQ IFWON\n Decryption using Key #8: LEVWLMP HEVNM\n Decryption using Key #9: KDUVKLO GDUML\n Decryption using Key #10: JCTUJKN FCTLK\n Decryption using Key #11: IBSTIJM EBSKJ\n Decryption using Key #12: HARSHIL DARJI\n Decryption using Key #13: GZQRGHK CZQIH\n Decryption using Key #14: FYPQFGJ BYPHG\n Decryption using Key #15: EXOPEFI AXOGF\n Decryption using Key #16: DWNODEH ZWNFE\n Decryption using Key #17: CVMNCDG YVMED\n Decryption using Key #18: BULMBCF XULDC\n Decryption using Key #19: ATKLABE WTKCB\n Decryption using Key #20: ZSJKZAD VSJBA\n Decryption using Key #21: YRIJYZC URIAZ\n Decryption using Key #22: XQHIXYB TQHZY\n Decryption using Key #23: WPGHWXA SPGYX\n Decryption using Key #24: VOFGVWZ ROFXW\n Decryption using Key #25: UNEFUVY QNEWV\n \"\"\"\n for key in range(len(string.ascii_uppercase)):\n translated = \"\"\n for symbol in message:\n if symbol in string.ascii_uppercase:\n num = string.ascii_uppercase.find(symbol)\n num = num - key\n if num < 0:\n num = num + len(string.ascii_uppercase)\n translated = translated + string.ascii_uppercase[num]\n else:\n translated = translated + symbol\n print(f\"Decryption using Key #{key}: {translated}\")\n\n\ndef main() -> None:\n message = input(\"Encrypted message: \")\n message = message.upper()\n decrypt(message)\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n main()\n"} +{"Prompt":"encrypt Encodes a given string with the caesar cipher and returns the encoded message Parameters: inputstring: the plaintext that needs to be encoded key: the number of letters to shift the message by Optional: alphabet None: the alphabet used to encode the cipher, if not specified, the standard english alphabet with upper and lowercase letters is used Returns: A string containing the encoded ciphertext More on the caesar cipher The caesar cipher is named after Julius Caesar who used it when sending secret military messages to his troops. This is a simple substitution cipher where every character in the plaintext is shifted by a certain number known as the key or shift. Example: Say we have the following message: Hello, captain And our alphabet is made up of lower and uppercase letters: abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ And our shift is 2 We can then encode the message, one letter at a time. H would become J, since J is two letters away, and so on. If the shift is ever two large, or our letter is at the end of the alphabet, we just start at the beginning Z would shift to a then b and so on. Our final message would be Jgnnq, ecrvckp Further reading https:en.m.wikipedia.orgwikiCaesarcipher Doctests encrypt'The quick brown fox jumps over the lazy dog', 8 'bpm yCqks jzwEv nwF rCuxA wDmz Bpm tiHG lwo' encrypt'A very large key', 8000 's nWjq dSjYW cWq' encrypt'a lowercase alphabet', 5, 'abcdefghijklmnopqrstuvwxyz' 'f qtbjwhfxj fqumfgjy' Set default alphabet to lower and upper case english chars The final result string Append without encryption if character is not in the alphabet Get the index of the new key and make sure it isn't too large Append the encoded character to the alphabet decrypt Decodes a given string of ciphertext and returns the decoded plaintext Parameters: inputstring: the ciphertext that needs to be decoded key: the number of letters to shift the message backwards by to decode Optional: alphabet None: the alphabet used to decode the cipher, if not specified, the standard english alphabet with upper and lowercase letters is used Returns: A string containing the decoded plaintext More on the caesar cipher The caesar cipher is named after Julius Caesar who used it when sending secret military messages to his troops. This is a simple substitution cipher where very character in the plaintext is shifted by a certain number known as the key or shift. Please keep in mind, here we will be focused on decryption. Example: Say we have the following ciphertext: Jgnnq, ecrvckp And our alphabet is made up of lower and uppercase letters: abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ And our shift is 2 To decode the message, we would do the same thing as encoding, but in reverse. The first letter, J would become H remember: we are decoding because H is two letters in reverse to the left of J. We would continue doing this. A letter like a would shift back to the end of the alphabet, and would become Z or Y and so on. Our final message would be Hello, captain Further reading https:en.m.wikipedia.orgwikiCaesarcipher Doctests decrypt'bpm yCqks jzwEv nwF rCuxA wDmz Bpm tiHG lwo', 8 'The quick brown fox jumps over the lazy dog' decrypt's nWjq dSjYW cWq', 8000 'A very large key' decrypt'f qtbjwhfxj fqumfgjy', 5, 'abcdefghijklmnopqrstuvwxyz' 'a lowercase alphabet' Turn on decode mode by making the key negative bruteforce Returns all the possible combinations of keys and the decoded strings in the form of a dictionary Parameters: inputstring: the ciphertext that needs to be used during bruteforce Optional: alphabet: None: the alphabet used to decode the cipher, if not specified, the standard english alphabet with upper and lowercase letters is used More about brute force Brute force is when a person intercepts a message or password, not knowing the key and tries every single combination. This is easy with the caesar cipher since there are only all the letters in the alphabet. The more complex the cipher, the larger amount of time it will take to do brute force Ex: Say we have a 5 letter alphabet abcde, for simplicity and we intercepted the following message: dbc we could then just write out every combination: ecd... and so on, until we reach a combination that makes sense: cab Further reading https:en.wikipedia.orgwikiBruteforce Doctests bruteforcejFyuMy xIH'N vLONy zILwy Gy!20 Please don't brute force me! bruteforce1 Traceback most recent call last: TypeError: 'int' object is not iterable Set default alphabet to lower and upper case english chars To store data on all the combinations Cycle through each combination Decrypt the message and store the result in the data get user input run functions based on what the user chose","Completions":"from __future__ import annotations\n\nfrom string import ascii_letters\n\n\ndef encrypt(input_string: str, key: int, alphabet: str | None = None) -> str:\n \"\"\"\n encrypt\n =======\n Encodes a given string with the caesar cipher and returns the encoded\n message\n\n Parameters:\n -----------\n * input_string: the plain-text that needs to be encoded\n * key: the number of letters to shift the message by\n\n Optional:\n * alphabet (None): the alphabet used to encode the cipher, if not\n specified, the standard english alphabet with upper and lowercase\n letters is used\n\n Returns:\n * A string containing the encoded cipher-text\n\n More on the caesar cipher\n =========================\n The caesar cipher is named after Julius Caesar who used it when sending\n secret military messages to his troops. This is a simple substitution cipher\n where every character in the plain-text is shifted by a certain number known\n as the \"key\" or \"shift\".\n\n Example:\n Say we have the following message:\n \"Hello, captain\"\n\n And our alphabet is made up of lower and uppercase letters:\n \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n\n And our shift is \"2\"\n\n We can then encode the message, one letter at a time. \"H\" would become \"J\",\n since \"J\" is two letters away, and so on. If the shift is ever two large, or\n our letter is at the end of the alphabet, we just start at the beginning\n (\"Z\" would shift to \"a\" then \"b\" and so on).\n\n Our final message would be \"Jgnnq, ecrvckp\"\n\n Further reading\n ===============\n * https:\/\/en.m.wikipedia.org\/wiki\/Caesar_cipher\n\n Doctests\n ========\n >>> encrypt('The quick brown fox jumps over the lazy dog', 8)\n 'bpm yCqks jzwEv nwF rCuxA wDmz Bpm tiHG lwo'\n\n >>> encrypt('A very large key', 8000)\n 's nWjq dSjYW cWq'\n\n >>> encrypt('a lowercase alphabet', 5, 'abcdefghijklmnopqrstuvwxyz')\n 'f qtbjwhfxj fqumfgjy'\n \"\"\"\n # Set default alphabet to lower and upper case english chars\n alpha = alphabet or ascii_letters\n\n # The final result string\n result = \"\"\n\n for character in input_string:\n if character not in alpha:\n # Append without encryption if character is not in the alphabet\n result += character\n else:\n # Get the index of the new key and make sure it isn't too large\n new_key = (alpha.index(character) + key) % len(alpha)\n\n # Append the encoded character to the alphabet\n result += alpha[new_key]\n\n return result\n\n\ndef decrypt(input_string: str, key: int, alphabet: str | None = None) -> str:\n \"\"\"\n decrypt\n =======\n Decodes a given string of cipher-text and returns the decoded plain-text\n\n Parameters:\n -----------\n * input_string: the cipher-text that needs to be decoded\n * key: the number of letters to shift the message backwards by to decode\n\n Optional:\n * alphabet (None): the alphabet used to decode the cipher, if not\n specified, the standard english alphabet with upper and lowercase\n letters is used\n\n Returns:\n * A string containing the decoded plain-text\n\n More on the caesar cipher\n =========================\n The caesar cipher is named after Julius Caesar who used it when sending\n secret military messages to his troops. This is a simple substitution cipher\n where very character in the plain-text is shifted by a certain number known\n as the \"key\" or \"shift\". Please keep in mind, here we will be focused on\n decryption.\n\n Example:\n Say we have the following cipher-text:\n \"Jgnnq, ecrvckp\"\n\n And our alphabet is made up of lower and uppercase letters:\n \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n\n And our shift is \"2\"\n\n To decode the message, we would do the same thing as encoding, but in\n reverse. The first letter, \"J\" would become \"H\" (remember: we are decoding)\n because \"H\" is two letters in reverse (to the left) of \"J\". We would\n continue doing this. A letter like \"a\" would shift back to the end of\n the alphabet, and would become \"Z\" or \"Y\" and so on.\n\n Our final message would be \"Hello, captain\"\n\n Further reading\n ===============\n * https:\/\/en.m.wikipedia.org\/wiki\/Caesar_cipher\n\n Doctests\n ========\n >>> decrypt('bpm yCqks jzwEv nwF rCuxA wDmz Bpm tiHG lwo', 8)\n 'The quick brown fox jumps over the lazy dog'\n\n >>> decrypt('s nWjq dSjYW cWq', 8000)\n 'A very large key'\n\n >>> decrypt('f qtbjwhfxj fqumfgjy', 5, 'abcdefghijklmnopqrstuvwxyz')\n 'a lowercase alphabet'\n \"\"\"\n # Turn on decode mode by making the key negative\n key *= -1\n\n return encrypt(input_string, key, alphabet)\n\n\ndef brute_force(input_string: str, alphabet: str | None = None) -> dict[int, str]:\n \"\"\"\n brute_force\n ===========\n Returns all the possible combinations of keys and the decoded strings in the\n form of a dictionary\n\n Parameters:\n -----------\n * input_string: the cipher-text that needs to be used during brute-force\n\n Optional:\n * alphabet: (None): the alphabet used to decode the cipher, if not\n specified, the standard english alphabet with upper and lowercase\n letters is used\n\n More about brute force\n ======================\n Brute force is when a person intercepts a message or password, not knowing\n the key and tries every single combination. This is easy with the caesar\n cipher since there are only all the letters in the alphabet. The more\n complex the cipher, the larger amount of time it will take to do brute force\n\n Ex:\n Say we have a 5 letter alphabet (abcde), for simplicity and we intercepted the\n following message:\n\n \"dbc\"\n\n we could then just write out every combination:\n ecd... and so on, until we reach a combination that makes sense:\n \"cab\"\n\n Further reading\n ===============\n * https:\/\/en.wikipedia.org\/wiki\/Brute_force\n\n Doctests\n ========\n >>> brute_force(\"jFyuMy xIH'N vLONy zILwy Gy!\")[20]\n \"Please don't brute force me!\"\n\n >>> brute_force(1)\n Traceback (most recent call last):\n TypeError: 'int' object is not iterable\n \"\"\"\n # Set default alphabet to lower and upper case english chars\n alpha = alphabet or ascii_letters\n\n # To store data on all the combinations\n brute_force_data = {}\n\n # Cycle through each combination\n for key in range(1, len(alpha) + 1):\n # Decrypt the message and store the result in the data\n brute_force_data[key] = decrypt(input_string, key, alpha)\n\n return brute_force_data\n\n\nif __name__ == \"__main__\":\n while True:\n print(f'\\n{\"-\" * 10}\\n Menu\\n{\"-\" * 10}')\n print(*[\"1.Encrypt\", \"2.Decrypt\", \"3.BruteForce\", \"4.Quit\"], sep=\"\\n\")\n\n # get user input\n choice = input(\"\\nWhat would you like to do?: \").strip() or \"4\"\n\n # run functions based on what the user chose\n if choice not in (\"1\", \"2\", \"3\", \"4\"):\n print(\"Invalid choice, please enter a valid choice\")\n elif choice == \"1\":\n input_string = input(\"Please enter the string to be encrypted: \")\n key = int(input(\"Please enter off-set: \").strip())\n\n print(encrypt(input_string, key))\n elif choice == \"2\":\n input_string = input(\"Please enter the string to be decrypted: \")\n key = int(input(\"Please enter off-set: \").strip())\n\n print(decrypt(input_string, key))\n elif choice == \"3\":\n input_string = input(\"Please enter the string to be decrypted: \")\n brute_force_data = brute_force(input_string)\n\n for key, value in brute_force_data.items():\n print(f\"Key: {key} | Message: {value}\")\n\n elif choice == \"4\":\n print(\"Goodbye.\")\n break\n"} +{"Prompt":"!usrbinenv python3 Basic Usage Arguments: ciphertext str: the text to decode encoded with the caesar cipher Optional Arguments: cipheralphabet list: the alphabet used for the cipher each letter is a string separated by commas frequenciesdict dict: a dictionary of word frequencies where keys are the letters and values are a percentage representation of the frequency as a decimalfloat casesensitive bool: a boolean value: True if the case matters during decryption, False if it doesn't Returns: A tuple in the form of: mostlikelycipher, mostlikelycipherchisquaredvalue, decodedmostlikelycipher where... mostlikelycipher is an integer representing the shift of the smallest chisquared statistic most likely key mostlikelycipherchisquaredvalue is a float representing the chisquared statistic of the most likely shift decodedmostlikelycipher is a string with the decoded cipher decoded by the mostlikelycipher key The Chisquared test The caesar cipher The caesar cipher is a very insecure encryption algorithm, however it has been used since Julius Caesar. The cipher is a simple substitution cipher where each character in the plain text is replaced by a character in the alphabet a certain number of characters after the original character. The number of characters away is called the shift or key. For example: Plain text: hello Key: 1 Cipher text: ifmmp each letter in hello has been shifted one to the right in the eng. alphabet As you can imagine, this doesn't provide lots of security. In fact decrypting ciphertext by bruteforce is extremely easy even by hand. However one way to do that is the chisquared test. The chisquared test Each letter in the english alphabet has a frequency, or the amount of times it shows up compared to other letters usually expressed as a decimal representing the percentage likelihood. The most common letter in the english language is e with a frequency of 0.11162 or 11.162. The test is completed in the following fashion. 1. The ciphertext is decoded in a brute force way every combination of the 26 possible combinations 2. For every combination, for each letter in the combination, the average amount of times the letter should appear the message is calculated by multiplying the total number of characters by the frequency of the letter For example: In a message of 100 characters, e should appear around 11.162 times. 3. Then, to calculate the margin of error the amount of times the letter SHOULD appear with the amount of times the letter DOES appear, we use the chisquared test. The following formula is used: Let: n be the number of times the letter actually appears p be the predicted value of the number of times the letter should appear see 2 let v be the chisquared test result referred to here as chisquared valuestatistic n p2 v p 4. Each chi squared value for each letter is then added up to the total. The total is the chisquared statistic for that encryption key. 5. The encryption key with the lowest chisquared value is the most likely to be the decoded answer. Further Reading http:practicalcryptography.comcryptanalysistextcharacterisationchisquared statistic https:en.wikipedia.orgwikiLetterfrequency https:en.wikipedia.orgwikiChisquaredtest https:en.m.wikipedia.orgwikiCaesarcipher Doctests decryptcaesarwithchisquared ... 'dof pz aol jhlzhy jpwoly zv wvwbshy? pa pz avv lhzf av jyhjr!' ... doctest: NORMALIZEWHITESPACE 7, 3129.228005747531, 'why is the caesar cipher so popular? it is too easy to crack!' decryptcaesarwithchisquared'crybd cdbsxq' 10, 233.35343938980898, 'short string' decryptcaesarwithchisquared'Crybd Cdbsxq', casesensitiveTrue 10, 233.35343938980898, 'Short String' decryptcaesarwithchisquared12 Traceback most recent call last: AttributeError: 'int' object has no attribute 'lower' If the argument is None or the user provided an empty dictionary Frequencies of letters in the english language how much they show up Custom frequencies dictionary Chi squared statistic values cycle through all of the shifts decrypt the message with the shift Try to index the letter in the alphabet Append the character if it isn't in the alphabet Loop through each letter in the decoded message with the shift Get the amount of times the letter occurs in the message Get the excepcted amount of times the letter should appear based on letter frequencies Complete the chi squared statistic formula Add the margin of error to the total chi squared statistic Get the amount of times the letter occurs in the message Get the excepcted amount of times the letter should appear based on letter frequencies Complete the chi squared statistic formula Add the margin of error to the total chi squared statistic Add the data to the chisquaredstatisticvalues dictionary Get the most likely cipher by finding the cipher with the smallest chi squared statistic Get all the data from the most likely cipher key, decoded message Return the data on the most likely shift","Completions":"#!\/usr\/bin\/env python3\nfrom __future__ import annotations\n\n\ndef decrypt_caesar_with_chi_squared(\n ciphertext: str,\n cipher_alphabet: list[str] | None = None,\n frequencies_dict: dict[str, float] | None = None,\n case_sensitive: bool = False,\n) -> tuple[int, float, str]:\n \"\"\"\n Basic Usage\n ===========\n Arguments:\n * ciphertext (str): the text to decode (encoded with the caesar cipher)\n\n Optional Arguments:\n * cipher_alphabet (list): the alphabet used for the cipher (each letter is\n a string separated by commas)\n * frequencies_dict (dict): a dictionary of word frequencies where keys are\n the letters and values are a percentage representation of the frequency as\n a decimal\/float\n * case_sensitive (bool): a boolean value: True if the case matters during\n decryption, False if it doesn't\n\n Returns:\n * A tuple in the form of:\n (\n most_likely_cipher,\n most_likely_cipher_chi_squared_value,\n decoded_most_likely_cipher\n )\n\n where...\n - most_likely_cipher is an integer representing the shift of the smallest\n chi-squared statistic (most likely key)\n - most_likely_cipher_chi_squared_value is a float representing the\n chi-squared statistic of the most likely shift\n - decoded_most_likely_cipher is a string with the decoded cipher\n (decoded by the most_likely_cipher key)\n\n\n The Chi-squared test\n ====================\n\n The caesar cipher\n -----------------\n The caesar cipher is a very insecure encryption algorithm, however it has\n been used since Julius Caesar. The cipher is a simple substitution cipher\n where each character in the plain text is replaced by a character in the\n alphabet a certain number of characters after the original character. The\n number of characters away is called the shift or key. For example:\n\n Plain text: hello\n Key: 1\n Cipher text: ifmmp\n (each letter in hello has been shifted one to the right in the eng. alphabet)\n\n As you can imagine, this doesn't provide lots of security. In fact\n decrypting ciphertext by brute-force is extremely easy even by hand. However\n one way to do that is the chi-squared test.\n\n The chi-squared test\n -------------------\n Each letter in the english alphabet has a frequency, or the amount of times\n it shows up compared to other letters (usually expressed as a decimal\n representing the percentage likelihood). The most common letter in the\n english language is \"e\" with a frequency of 0.11162 or 11.162%. The test is\n completed in the following fashion.\n\n 1. The ciphertext is decoded in a brute force way (every combination of the\n 26 possible combinations)\n 2. For every combination, for each letter in the combination, the average\n amount of times the letter should appear the message is calculated by\n multiplying the total number of characters by the frequency of the letter\n\n For example:\n In a message of 100 characters, e should appear around 11.162 times.\n\n 3. Then, to calculate the margin of error (the amount of times the letter\n SHOULD appear with the amount of times the letter DOES appear), we use\n the chi-squared test. The following formula is used:\n\n Let:\n - n be the number of times the letter actually appears\n - p be the predicted value of the number of times the letter should\n appear (see #2)\n - let v be the chi-squared test result (referred to here as chi-squared\n value\/statistic)\n\n (n - p)^2\n --------- = v\n p\n\n 4. Each chi squared value for each letter is then added up to the total.\n The total is the chi-squared statistic for that encryption key.\n 5. The encryption key with the lowest chi-squared value is the most likely\n to be the decoded answer.\n\n Further Reading\n ================\n\n * http:\/\/practicalcryptography.com\/cryptanalysis\/text-characterisation\/chi-squared-\n statistic\/\n * https:\/\/en.wikipedia.org\/wiki\/Letter_frequency\n * https:\/\/en.wikipedia.org\/wiki\/Chi-squared_test\n * https:\/\/en.m.wikipedia.org\/wiki\/Caesar_cipher\n\n Doctests\n ========\n >>> decrypt_caesar_with_chi_squared(\n ... 'dof pz aol jhlzhy jpwoly zv wvwbshy? pa pz avv lhzf av jyhjr!'\n ... ) # doctest: +NORMALIZE_WHITESPACE\n (7, 3129.228005747531,\n 'why is the caesar cipher so popular? it is too easy to crack!')\n\n >>> decrypt_caesar_with_chi_squared('crybd cdbsxq')\n (10, 233.35343938980898, 'short string')\n\n >>> decrypt_caesar_with_chi_squared('Crybd Cdbsxq', case_sensitive=True)\n (10, 233.35343938980898, 'Short String')\n\n >>> decrypt_caesar_with_chi_squared(12)\n Traceback (most recent call last):\n AttributeError: 'int' object has no attribute 'lower'\n \"\"\"\n alphabet_letters = cipher_alphabet or [chr(i) for i in range(97, 123)]\n\n # If the argument is None or the user provided an empty dictionary\n if not frequencies_dict:\n # Frequencies of letters in the english language (how much they show up)\n frequencies = {\n \"a\": 0.08497,\n \"b\": 0.01492,\n \"c\": 0.02202,\n \"d\": 0.04253,\n \"e\": 0.11162,\n \"f\": 0.02228,\n \"g\": 0.02015,\n \"h\": 0.06094,\n \"i\": 0.07546,\n \"j\": 0.00153,\n \"k\": 0.01292,\n \"l\": 0.04025,\n \"m\": 0.02406,\n \"n\": 0.06749,\n \"o\": 0.07507,\n \"p\": 0.01929,\n \"q\": 0.00095,\n \"r\": 0.07587,\n \"s\": 0.06327,\n \"t\": 0.09356,\n \"u\": 0.02758,\n \"v\": 0.00978,\n \"w\": 0.02560,\n \"x\": 0.00150,\n \"y\": 0.01994,\n \"z\": 0.00077,\n }\n else:\n # Custom frequencies dictionary\n frequencies = frequencies_dict\n\n if not case_sensitive:\n ciphertext = ciphertext.lower()\n\n # Chi squared statistic values\n chi_squared_statistic_values: dict[int, tuple[float, str]] = {}\n\n # cycle through all of the shifts\n for shift in range(len(alphabet_letters)):\n decrypted_with_shift = \"\"\n\n # decrypt the message with the shift\n for letter in ciphertext:\n try:\n # Try to index the letter in the alphabet\n new_key = (alphabet_letters.index(letter.lower()) - shift) % len(\n alphabet_letters\n )\n decrypted_with_shift += (\n alphabet_letters[new_key].upper()\n if case_sensitive and letter.isupper()\n else alphabet_letters[new_key]\n )\n except ValueError:\n # Append the character if it isn't in the alphabet\n decrypted_with_shift += letter\n\n chi_squared_statistic = 0.0\n\n # Loop through each letter in the decoded message with the shift\n for letter in decrypted_with_shift:\n if case_sensitive:\n letter = letter.lower()\n if letter in frequencies:\n # Get the amount of times the letter occurs in the message\n occurrences = decrypted_with_shift.lower().count(letter)\n\n # Get the excepcted amount of times the letter should appear based\n # on letter frequencies\n expected = frequencies[letter] * occurrences\n\n # Complete the chi squared statistic formula\n chi_letter_value = ((occurrences - expected) ** 2) \/ expected\n\n # Add the margin of error to the total chi squared statistic\n chi_squared_statistic += chi_letter_value\n else:\n if letter.lower() in frequencies:\n # Get the amount of times the letter occurs in the message\n occurrences = decrypted_with_shift.count(letter)\n\n # Get the excepcted amount of times the letter should appear based\n # on letter frequencies\n expected = frequencies[letter] * occurrences\n\n # Complete the chi squared statistic formula\n chi_letter_value = ((occurrences - expected) ** 2) \/ expected\n\n # Add the margin of error to the total chi squared statistic\n chi_squared_statistic += chi_letter_value\n\n # Add the data to the chi_squared_statistic_values dictionary\n chi_squared_statistic_values[shift] = (\n chi_squared_statistic,\n decrypted_with_shift,\n )\n\n # Get the most likely cipher by finding the cipher with the smallest chi squared\n # statistic\n def chi_squared_statistic_values_sorting_key(key: int) -> tuple[float, str]:\n return chi_squared_statistic_values[key]\n\n most_likely_cipher: int = min(\n chi_squared_statistic_values,\n key=chi_squared_statistic_values_sorting_key,\n )\n\n # Get all the data from the most likely cipher (key, decoded message)\n (\n most_likely_cipher_chi_squared_value,\n decoded_most_likely_cipher,\n ) = chi_squared_statistic_values[most_likely_cipher]\n\n # Return the data on the most likely shift\n return (\n most_likely_cipher,\n most_likely_cipher_chi_squared_value,\n decoded_most_likely_cipher,\n )\n"} +{"Prompt":"Created by Nathan Damon, bizzfitch on github testmillerrabin Deterministic MillerRabin algorithm for primes 3.32e24. Uses numerical analysis results to return whether or not the passed number is prime. If the passed number is above the upper limit, and allowprobable is True, then a return value of True indicates that n is probably prime. This test does not allow False negatives a return value of False is ALWAYS composite. Parameters n : int The integer to be tested. Since we usually care if a number is prime, n 2 returns False instead of raising a ValueError. allowprobable: bool, default False Whether or not to test n above the upper bound of the deterministic test. Raises ValueError Reference https:en.wikipedia.orgwikiMillerE28093Rabinprimalitytest array bounds provided by analysis then we have our last prime to check break up n 1 into a power of 2 s and remaining odd component essentially, solve for d 2 s n 1 see article for analysis explanation for m this loop will not determine compositeness if pr is False, then the above loop never evaluated to true, and the n MUST be composite Testing a nontrivial ends in 1, 3, 7, 9 composite and a prime in each range. 2047 1373653 25326001 3215031751 2152302898747 3474749660383 341550071728321 3825123056546413051 318665857834031151167461 3317044064679887385961981 upper limit for probabilistic test","Completions":"def miller_rabin(n: int, allow_probable: bool = False) -> bool:\n \"\"\"Deterministic Miller-Rabin algorithm for primes ~< 3.32e24.\n\n Uses numerical analysis results to return whether or not the passed number\n is prime. If the passed number is above the upper limit, and\n allow_probable is True, then a return value of True indicates that n is\n probably prime. This test does not allow False negatives- a return value\n of False is ALWAYS composite.\n\n Parameters\n ----------\n n : int\n The integer to be tested. Since we usually care if a number is prime,\n n < 2 returns False instead of raising a ValueError.\n allow_probable: bool, default False\n Whether or not to test n above the upper bound of the deterministic test.\n\n Raises\n ------\n ValueError\n\n Reference\n ---------\n https:\/\/en.wikipedia.org\/wiki\/Miller%E2%80%93Rabin_primality_test\n \"\"\"\n if n == 2:\n return True\n if not n % 2 or n < 2:\n return False\n if n > 5 and n % 10 not in (1, 3, 7, 9): # can quickly check last digit\n return False\n if n > 3_317_044_064_679_887_385_961_981 and not allow_probable:\n raise ValueError(\n \"Warning: upper bound of deterministic test is exceeded. \"\n \"Pass allow_probable=True to allow probabilistic test. \"\n \"A return value of True indicates a probable prime.\"\n )\n # array bounds provided by analysis\n bounds = [\n 2_047,\n 1_373_653,\n 25_326_001,\n 3_215_031_751,\n 2_152_302_898_747,\n 3_474_749_660_383,\n 341_550_071_728_321,\n 1,\n 3_825_123_056_546_413_051,\n 1,\n 1,\n 318_665_857_834_031_151_167_461,\n 3_317_044_064_679_887_385_961_981,\n ]\n\n primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41]\n for idx, _p in enumerate(bounds, 1):\n if n < _p:\n # then we have our last prime to check\n plist = primes[:idx]\n break\n d, s = n - 1, 0\n # break up n -1 into a power of 2 (s) and\n # remaining odd component\n # essentially, solve for d * 2 ** s == n - 1\n while d % 2 == 0:\n d \/\/= 2\n s += 1\n for prime in plist:\n pr = False\n for r in range(s):\n m = pow(prime, d * 2**r, n)\n # see article for analysis explanation for m\n if (r == 0 and m == 1) or ((m + 1) % n == 0):\n pr = True\n # this loop will not determine compositeness\n break\n if pr:\n continue\n # if pr is False, then the above loop never evaluated to true,\n # and the n MUST be composite\n return False\n return True\n\n\ndef test_miller_rabin() -> None:\n \"\"\"Testing a nontrivial (ends in 1, 3, 7, 9) composite\n and a prime in each range.\n \"\"\"\n assert not miller_rabin(561)\n assert miller_rabin(563)\n # 2047\n\n assert not miller_rabin(838_201)\n assert miller_rabin(838_207)\n # 1_373_653\n\n assert not miller_rabin(17_316_001)\n assert miller_rabin(17_316_017)\n # 25_326_001\n\n assert not miller_rabin(3_078_386_641)\n assert miller_rabin(3_078_386_653)\n # 3_215_031_751\n\n assert not miller_rabin(1_713_045_574_801)\n assert miller_rabin(1_713_045_574_819)\n # 2_152_302_898_747\n\n assert not miller_rabin(2_779_799_728_307)\n assert miller_rabin(2_779_799_728_327)\n # 3_474_749_660_383\n\n assert not miller_rabin(113_850_023_909_441)\n assert miller_rabin(113_850_023_909_527)\n # 341_550_071_728_321\n\n assert not miller_rabin(1_275_041_018_848_804_351)\n assert miller_rabin(1_275_041_018_848_804_391)\n # 3_825_123_056_546_413_051\n\n assert not miller_rabin(79_666_464_458_507_787_791_867)\n assert miller_rabin(79_666_464_458_507_787_791_951)\n # 318_665_857_834_031_151_167_461\n\n assert not miller_rabin(552_840_677_446_647_897_660_333)\n assert miller_rabin(552_840_677_446_647_897_660_359)\n # 3_317_044_064_679_887_385_961_981\n # upper limit for probabilistic test\n\n\nif __name__ == \"__main__\":\n test_miller_rabin()\n"} +{"Prompt":"Find a primitive root modulo modulus, if one exists. Args: modulus : The modulus for which to find a primitive root. Returns: The primitive root if one exists, or None if there is none. Examples: findprimitive7 Modulo 7 has primitive root 3 3 findprimitive11 Modulo 11 has primitive root 2 2 findprimitive8 None Modulo 8 has no primitive root True","Completions":"from __future__ import annotations\n\n\ndef find_primitive(modulus: int) -> int | None:\n \"\"\"\n Find a primitive root modulo modulus, if one exists.\n\n Args:\n modulus : The modulus for which to find a primitive root.\n\n Returns:\n The primitive root if one exists, or None if there is none.\n\n Examples:\n >>> find_primitive(7) # Modulo 7 has primitive root 3\n 3\n >>> find_primitive(11) # Modulo 11 has primitive root 2\n 2\n >>> find_primitive(8) == None # Modulo 8 has no primitive root\n True\n \"\"\"\n for r in range(1, modulus):\n li = []\n for x in range(modulus - 1):\n val = pow(r, x, modulus)\n if val in li:\n break\n li.append(val)\n else:\n return r\n return None\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n\n prime = int(input(\"Enter a prime number q: \"))\n primitive_root = find_primitive(prime)\n if primitive_root is None:\n print(f\"Cannot find the primitive for the value: {primitive_root!r}\")\n else:\n a_private = int(input(\"Enter private key of A: \"))\n a_public = pow(primitive_root, a_private, prime)\n b_private = int(input(\"Enter private key of B: \"))\n b_public = pow(primitive_root, b_private, prime)\n\n a_secret = pow(b_public, a_private, prime)\n b_secret = pow(a_public, b_private, prime)\n\n print(\"The key value generated by A is: \", a_secret)\n print(\"The key value generated by B is: \", b_secret)\n"} +{"Prompt":"RFC 3526 More Modular Exponential MODP DiffieHellman groups for Internet Key Exchange IKE https:tools.ietf.orghtmlrfc3526 1536bit 2048bit 3072bit 4096bit 6144bit 8192bit Class to represent the DiffieHellman key exchange protocol alice DiffieHellman bob DiffieHellman aliceprivate alice.getprivatekey alicepublic alice.generatepublickey bobprivate bob.getprivatekey bobpublic bob.generatepublickey generating shared key using the DH object aliceshared alice.generatesharedkeybobpublic bobshared bob.generatesharedkeyalicepublic assert aliceshared bobshared generating shared key using static methods aliceshared DiffieHellman.generatesharedkeystatic ... aliceprivate, bobpublic ... bobshared DiffieHellman.generatesharedkeystatic ... bobprivate, alicepublic ... assert aliceshared bobshared Current minimum recommendation is 2048 bit group 14 check if the other public key is valid based on NIST SP80056 check if the other public key is valid based on NIST SP80056","Completions":"from binascii import hexlify\nfrom hashlib import sha256\nfrom os import urandom\n\n# RFC 3526 - More Modular Exponential (MODP) Diffie-Hellman groups for\n# Internet Key Exchange (IKE) https:\/\/tools.ietf.org\/html\/rfc3526\n\nprimes = {\n # 1536-bit\n 5: {\n \"prime\": int(\n \"FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1\"\n \"29024E088A67CC74020BBEA63B139B22514A08798E3404DD\"\n \"EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245\"\n \"E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED\"\n \"EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D\"\n \"C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F\"\n \"83655D23DCA3AD961C62F356208552BB9ED529077096966D\"\n \"670C354E4ABC9804F1746C08CA237327FFFFFFFFFFFFFFFF\",\n base=16,\n ),\n \"generator\": 2,\n },\n # 2048-bit\n 14: {\n \"prime\": int(\n \"FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1\"\n \"29024E088A67CC74020BBEA63B139B22514A08798E3404DD\"\n \"EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245\"\n \"E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED\"\n \"EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D\"\n \"C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F\"\n \"83655D23DCA3AD961C62F356208552BB9ED529077096966D\"\n \"670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B\"\n \"E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9\"\n \"DE2BCBF6955817183995497CEA956AE515D2261898FA0510\"\n \"15728E5A8AACAA68FFFFFFFFFFFFFFFF\",\n base=16,\n ),\n \"generator\": 2,\n },\n # 3072-bit\n 15: {\n \"prime\": int(\n \"FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1\"\n \"29024E088A67CC74020BBEA63B139B22514A08798E3404DD\"\n \"EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245\"\n \"E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED\"\n \"EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D\"\n \"C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F\"\n \"83655D23DCA3AD961C62F356208552BB9ED529077096966D\"\n \"670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B\"\n \"E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9\"\n \"DE2BCBF6955817183995497CEA956AE515D2261898FA0510\"\n \"15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64\"\n \"ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7\"\n \"ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B\"\n \"F12FFA06D98A0864D87602733EC86A64521F2B18177B200C\"\n \"BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31\"\n \"43DB5BFCE0FD108E4B82D120A93AD2CAFFFFFFFFFFFFFFFF\",\n base=16,\n ),\n \"generator\": 2,\n },\n # 4096-bit\n 16: {\n \"prime\": int(\n \"FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1\"\n \"29024E088A67CC74020BBEA63B139B22514A08798E3404DD\"\n \"EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245\"\n \"E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED\"\n \"EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D\"\n \"C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F\"\n \"83655D23DCA3AD961C62F356208552BB9ED529077096966D\"\n \"670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B\"\n \"E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9\"\n \"DE2BCBF6955817183995497CEA956AE515D2261898FA0510\"\n \"15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64\"\n \"ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7\"\n \"ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B\"\n \"F12FFA06D98A0864D87602733EC86A64521F2B18177B200C\"\n \"BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31\"\n \"43DB5BFCE0FD108E4B82D120A92108011A723C12A787E6D7\"\n \"88719A10BDBA5B2699C327186AF4E23C1A946834B6150BDA\"\n \"2583E9CA2AD44CE8DBBBC2DB04DE8EF92E8EFC141FBECAA6\"\n \"287C59474E6BC05D99B2964FA090C3A2233BA186515BE7ED\"\n \"1F612970CEE2D7AFB81BDD762170481CD0069127D5B05AA9\"\n \"93B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934063199\"\n \"FFFFFFFFFFFFFFFF\",\n base=16,\n ),\n \"generator\": 2,\n },\n # 6144-bit\n 17: {\n \"prime\": int(\n \"FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08\"\n \"8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B\"\n \"302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9\"\n \"A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6\"\n \"49286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8\"\n \"FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D\"\n \"670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C\"\n \"180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF695581718\"\n \"3995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D\"\n \"04507A33A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7D\"\n \"B3970F85A6E1E4C7ABF5AE8CDB0933D71E8C94E04A25619DCEE3D226\"\n \"1AD2EE6BF12FFA06D98A0864D87602733EC86A64521F2B18177B200C\"\n \"BBE117577A615D6C770988C0BAD946E208E24FA074E5AB3143DB5BFC\"\n \"E0FD108E4B82D120A92108011A723C12A787E6D788719A10BDBA5B26\"\n \"99C327186AF4E23C1A946834B6150BDA2583E9CA2AD44CE8DBBBC2DB\"\n \"04DE8EF92E8EFC141FBECAA6287C59474E6BC05D99B2964FA090C3A2\"\n \"233BA186515BE7ED1F612970CEE2D7AFB81BDD762170481CD0069127\"\n \"D5B05AA993B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934028492\"\n \"36C3FAB4D27C7026C1D4DCB2602646DEC9751E763DBA37BDF8FF9406\"\n \"AD9E530EE5DB382F413001AEB06A53ED9027D831179727B0865A8918\"\n \"DA3EDBEBCF9B14ED44CE6CBACED4BB1BDB7F1447E6CC254B33205151\"\n \"2BD7AF426FB8F401378CD2BF5983CA01C64B92ECF032EA15D1721D03\"\n \"F482D7CE6E74FEF6D55E702F46980C82B5A84031900B1C9E59E7C97F\"\n \"BEC7E8F323A97A7E36CC88BE0F1D45B7FF585AC54BD407B22B4154AA\"\n \"CC8F6D7EBF48E1D814CC5ED20F8037E0A79715EEF29BE32806A1D58B\"\n \"B7C5DA76F550AA3D8A1FBFF0EB19CCB1A313D55CDA56C9EC2EF29632\"\n \"387FE8D76E3C0468043E8F663F4860EE12BF2D5B0B7474D6E694F91E\"\n \"6DCC4024FFFFFFFFFFFFFFFF\",\n base=16,\n ),\n \"generator\": 2,\n },\n # 8192-bit\n 18: {\n \"prime\": int(\n \"FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1\"\n \"29024E088A67CC74020BBEA63B139B22514A08798E3404DD\"\n \"EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245\"\n \"E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED\"\n \"EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D\"\n \"C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F\"\n \"83655D23DCA3AD961C62F356208552BB9ED529077096966D\"\n \"670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B\"\n \"E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9\"\n \"DE2BCBF6955817183995497CEA956AE515D2261898FA0510\"\n \"15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64\"\n \"ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7\"\n \"ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B\"\n \"F12FFA06D98A0864D87602733EC86A64521F2B18177B200C\"\n \"BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31\"\n \"43DB5BFCE0FD108E4B82D120A92108011A723C12A787E6D7\"\n \"88719A10BDBA5B2699C327186AF4E23C1A946834B6150BDA\"\n \"2583E9CA2AD44CE8DBBBC2DB04DE8EF92E8EFC141FBECAA6\"\n \"287C59474E6BC05D99B2964FA090C3A2233BA186515BE7ED\"\n \"1F612970CEE2D7AFB81BDD762170481CD0069127D5B05AA9\"\n \"93B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934028492\"\n \"36C3FAB4D27C7026C1D4DCB2602646DEC9751E763DBA37BD\"\n \"F8FF9406AD9E530EE5DB382F413001AEB06A53ED9027D831\"\n \"179727B0865A8918DA3EDBEBCF9B14ED44CE6CBACED4BB1B\"\n \"DB7F1447E6CC254B332051512BD7AF426FB8F401378CD2BF\"\n \"5983CA01C64B92ECF032EA15D1721D03F482D7CE6E74FEF6\"\n \"D55E702F46980C82B5A84031900B1C9E59E7C97FBEC7E8F3\"\n \"23A97A7E36CC88BE0F1D45B7FF585AC54BD407B22B4154AA\"\n \"CC8F6D7EBF48E1D814CC5ED20F8037E0A79715EEF29BE328\"\n \"06A1D58BB7C5DA76F550AA3D8A1FBFF0EB19CCB1A313D55C\"\n \"DA56C9EC2EF29632387FE8D76E3C0468043E8F663F4860EE\"\n \"12BF2D5B0B7474D6E694F91E6DBE115974A3926F12FEE5E4\"\n \"38777CB6A932DF8CD8BEC4D073B931BA3BC832B68D9DD300\"\n \"741FA7BF8AFC47ED2576F6936BA424663AAB639C5AE4F568\"\n \"3423B4742BF1C978238F16CBE39D652DE3FDB8BEFC848AD9\"\n \"22222E04A4037C0713EB57A81A23F0C73473FC646CEA306B\"\n \"4BCBC8862F8385DDFA9D4B7FA2C087E879683303ED5BDD3A\"\n \"062B3CF5B3A278A66D2A13F83F44F82DDF310EE074AB6A36\"\n \"4597E899A0255DC164F31CC50846851DF9AB48195DED7EA1\"\n \"B1D510BD7EE74D73FAF36BC31ECFA268359046F4EB879F92\"\n \"4009438B481C6CD7889A002ED5EE382BC9190DA6FC026E47\"\n \"9558E4475677E9AA9E3050E2765694DFC81F56E880B96E71\"\n \"60C980DD98EDD3DFFFFFFFFFFFFFFFFF\",\n base=16,\n ),\n \"generator\": 2,\n },\n}\n\n\nclass DiffieHellman:\n \"\"\"\n Class to represent the Diffie-Hellman key exchange protocol\n\n\n >>> alice = DiffieHellman()\n >>> bob = DiffieHellman()\n\n >>> alice_private = alice.get_private_key()\n >>> alice_public = alice.generate_public_key()\n\n >>> bob_private = bob.get_private_key()\n >>> bob_public = bob.generate_public_key()\n\n >>> # generating shared key using the DH object\n >>> alice_shared = alice.generate_shared_key(bob_public)\n >>> bob_shared = bob.generate_shared_key(alice_public)\n\n >>> assert alice_shared == bob_shared\n\n >>> # generating shared key using static methods\n >>> alice_shared = DiffieHellman.generate_shared_key_static(\n ... alice_private, bob_public\n ... )\n >>> bob_shared = DiffieHellman.generate_shared_key_static(\n ... bob_private, alice_public\n ... )\n\n >>> assert alice_shared == bob_shared\n \"\"\"\n\n # Current minimum recommendation is 2048 bit (group 14)\n def __init__(self, group: int = 14) -> None:\n if group not in primes:\n raise ValueError(\"Unsupported Group\")\n self.prime = primes[group][\"prime\"]\n self.generator = primes[group][\"generator\"]\n\n self.__private_key = int(hexlify(urandom(32)), base=16)\n\n def get_private_key(self) -> str:\n return hex(self.__private_key)[2:]\n\n def generate_public_key(self) -> str:\n public_key = pow(self.generator, self.__private_key, self.prime)\n return hex(public_key)[2:]\n\n def is_valid_public_key(self, key: int) -> bool:\n # check if the other public key is valid based on NIST SP800-56\n return (\n 2 <= key <= self.prime - 2\n and pow(key, (self.prime - 1) \/\/ 2, self.prime) == 1\n )\n\n def generate_shared_key(self, other_key_str: str) -> str:\n other_key = int(other_key_str, base=16)\n if not self.is_valid_public_key(other_key):\n raise ValueError(\"Invalid public key\")\n shared_key = pow(other_key, self.__private_key, self.prime)\n return sha256(str(shared_key).encode()).hexdigest()\n\n @staticmethod\n def is_valid_public_key_static(remote_public_key_str: int, prime: int) -> bool:\n # check if the other public key is valid based on NIST SP800-56\n return (\n 2 <= remote_public_key_str <= prime - 2\n and pow(remote_public_key_str, (prime - 1) \/\/ 2, prime) == 1\n )\n\n @staticmethod\n def generate_shared_key_static(\n local_private_key_str: str, remote_public_key_str: str, group: int = 14\n ) -> str:\n local_private_key = int(local_private_key_str, base=16)\n remote_public_key = int(remote_public_key_str, base=16)\n prime = primes[group][\"prime\"]\n if not DiffieHellman.is_valid_public_key_static(remote_public_key, prime):\n raise ValueError(\"Invalid public key\")\n shared_key = pow(remote_public_key, local_private_key, prime)\n return sha256(str(shared_key).encode()).hexdigest()\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"I have written my code naively same as definition of primitive root however every time I run this program, memory exceeded... so I used 4.80 Algorithm in Handbook of Applied CryptographyCRC Press, ISBN : 0849385237, October 1996 and it seems to run nicely!","Completions":"import os\nimport random\nimport sys\n\nfrom . import cryptomath_module as cryptomath\nfrom . import rabin_miller\n\nmin_primitive_root = 3\n\n\n# I have written my code naively same as definition of primitive root\n# however every time I run this program, memory exceeded...\n# so I used 4.80 Algorithm in\n# Handbook of Applied Cryptography(CRC Press, ISBN : 0-8493-8523-7, October 1996)\n# and it seems to run nicely!\ndef primitive_root(p_val: int) -> int:\n print(\"Generating primitive root of p\")\n while True:\n g = random.randrange(3, p_val)\n if pow(g, 2, p_val) == 1:\n continue\n if pow(g, p_val, p_val) == 1:\n continue\n return g\n\n\ndef generate_key(key_size: int) -> tuple[tuple[int, int, int, int], tuple[int, int]]:\n print(\"Generating prime p...\")\n p = rabin_miller.generate_large_prime(key_size) # select large prime number.\n e_1 = primitive_root(p) # one primitive root on modulo p.\n d = random.randrange(3, p) # private_key -> have to be greater than 2 for safety.\n e_2 = cryptomath.find_mod_inverse(pow(e_1, d, p), p)\n\n public_key = (key_size, e_1, e_2, p)\n private_key = (key_size, d)\n\n return public_key, private_key\n\n\ndef make_key_files(name: str, key_size: int) -> None:\n if os.path.exists(f\"{name}_pubkey.txt\") or os.path.exists(f\"{name}_privkey.txt\"):\n print(\"\\nWARNING:\")\n print(\n f'\"{name}_pubkey.txt\" or \"{name}_privkey.txt\" already exists. \\n'\n \"Use a different name or delete these files and re-run this program.\"\n )\n sys.exit()\n\n public_key, private_key = generate_key(key_size)\n print(f\"\\nWriting public key to file {name}_pubkey.txt...\")\n with open(f\"{name}_pubkey.txt\", \"w\") as fo:\n fo.write(f\"{public_key[0]},{public_key[1]},{public_key[2]},{public_key[3]}\")\n\n print(f\"Writing private key to file {name}_privkey.txt...\")\n with open(f\"{name}_privkey.txt\", \"w\") as fo:\n fo.write(f\"{private_key[0]},{private_key[1]}\")\n\n\ndef main() -> None:\n print(\"Making key files...\")\n make_key_files(\"elgamal\", 2048)\n print(\"Key files generation successful\")\n\n\nif __name__ == \"__main__\":\n main()\n"} +{"Prompt":"Wikipedia: https:en.wikipedia.orgwikiEnigmamachine Video explanation: https:youtu.beQwQVMqfoB2E Also check out Numberphile's and Computerphile's videos on this topic This module contains function 'enigma' which emulates the famous Enigma machine from WWII. Module includes: enigma function showcase of function usage 9 randomly generated rotors reflector aka static rotor original alphabet Created by TrapinchO used alphabet from string.asciiuppercase default selection rotors reflector extra rotors Checks if the values can be used for the 'enigma' function validator1,1,1, rotor1, rotor2, rotor3, 'POLAND' 1, 1, 1, 'EGZWVONAHDCLFQMSIPJBYUKXTR', 'FOBHMDKEXQNRAULPGSJVTYICZW', 'ZJXESIUQLHAVRMDOYGTNFWPBKC', 'P': 'O', 'O': 'P', 'L': 'A', 'A': 'L', 'N': 'D', 'D': 'N' :param rotpos: rotorpositon :param rotsel: rotorselection :param pb: plugb validated and transformed :return: rotpos, rotsel, pb Checks if there are 3 unique rotors Checks if rotor positions are valid Validates string and returns dict https:en.wikipedia.orgwikiEnigmamachinePlugboard plugboard'PICTURES' 'P': 'I', 'I': 'P', 'C': 'T', 'T': 'C', 'U': 'R', 'R': 'U', 'E': 'S', 'S': 'E' plugboard'POLAND' 'P': 'O', 'O': 'P', 'L': 'A', 'A': 'L', 'N': 'D', 'D': 'N' In the code, 'pb' stands for 'plugboard' Pairs can be separated by spaces :param pbstring: string containing plugboard setting for the Enigma machine :return: dictionary containing converted pairs tests the input string if it a is type string b has even length so pairs can be made Checks if all characters are unique Created the dictionary The only difference with realworld enigma is that I allowed string input. All characters are converted to uppercase. nonletter symbol are ignored How it works: for every letter in the message Input letter goes into the plugboard. If it is connected to another one, switch it. Letter goes through 3 rotors. Each rotor can be represented as 2 sets of symbol, where one is shuffled. Each symbol from the first set has corresponding symbol in the second set and vice versa. example: ABCDEFGHIJKLMNOPQRSTUVWXYZ e.g. FD and DF VKLEPDBGRNWTFCJOHQAMUZYIXS Symbol then goes through reflector static rotor. There it is switched with paired symbol The reflector can be represented as2 sets, each with half of the alphanet. There are usually 10 pairs of letters. Example: ABCDEFGHIJKLM e.g. E is paired to X ZYXWVUTSRQPON so when E goes in X goes out and vice versa Letter then goes through the rotors again If the letter is connected to plugboard, it is switched. Return the letter enigma'Hello World!', 1, 2, 1, plugb'pictures' 'KORYH JUHHI!' enigma'KORYH, juhhi!', 1, 2, 1, plugb'pictures' 'HELLO, WORLD!' enigma'hello world!', 1, 1, 1, plugb'pictures' 'FPNCZ QWOBU!' enigma'FPNCZ QWOBU', 1, 1, 1, plugb'pictures' 'HELLO WORLD' :param text: input message :param rotorposition: tuple with 3 values in range 1..26 :param rotorselection: tuple with 3 rotors :param plugb: string containing plugboard configuration default '' :return: endecrypted string encryptiondecryption process 1st plugboard rotor ra rotor rb rotor rc reflector this is the reason you don't need another machine to decipher 2nd rotors 2nd plugboard movesresets rotor positions else: pass Error could be also raised raise ValueError 'Invalid symbol'reprsymbol''","Completions":"from __future__ import annotations\n\nRotorPositionT = tuple[int, int, int]\nRotorSelectionT = tuple[str, str, str]\n\n\n# used alphabet --------------------------\n# from string.ascii_uppercase\nabc = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n\n# -------------------------- default selection --------------------------\n# rotors --------------------------\nrotor1 = \"EGZWVONAHDCLFQMSIPJBYUKXTR\"\nrotor2 = \"FOBHMDKEXQNRAULPGSJVTYICZW\"\nrotor3 = \"ZJXESIUQLHAVRMDOYGTNFWPBKC\"\n# reflector --------------------------\nreflector = {\n \"A\": \"N\",\n \"N\": \"A\",\n \"B\": \"O\",\n \"O\": \"B\",\n \"C\": \"P\",\n \"P\": \"C\",\n \"D\": \"Q\",\n \"Q\": \"D\",\n \"E\": \"R\",\n \"R\": \"E\",\n \"F\": \"S\",\n \"S\": \"F\",\n \"G\": \"T\",\n \"T\": \"G\",\n \"H\": \"U\",\n \"U\": \"H\",\n \"I\": \"V\",\n \"V\": \"I\",\n \"J\": \"W\",\n \"W\": \"J\",\n \"K\": \"X\",\n \"X\": \"K\",\n \"L\": \"Y\",\n \"Y\": \"L\",\n \"M\": \"Z\",\n \"Z\": \"M\",\n}\n\n# -------------------------- extra rotors --------------------------\nrotor4 = \"RMDJXFUWGISLHVTCQNKYPBEZOA\"\nrotor5 = \"SGLCPQWZHKXAREONTFBVIYJUDM\"\nrotor6 = \"HVSICLTYKQUBXDWAJZOMFGPREN\"\nrotor7 = \"RZWQHFMVDBKICJLNTUXAGYPSOE\"\nrotor8 = \"LFKIJODBEGAMQPXVUHYSTCZRWN\"\nrotor9 = \"KOAEGVDHXPQZMLFTYWJNBRCIUS\"\n\n\ndef _validator(\n rotpos: RotorPositionT, rotsel: RotorSelectionT, pb: str\n) -> tuple[RotorPositionT, RotorSelectionT, dict[str, str]]:\n \"\"\"\n Checks if the values can be used for the 'enigma' function\n\n >>> _validator((1,1,1), (rotor1, rotor2, rotor3), 'POLAND')\n ((1, 1, 1), ('EGZWVONAHDCLFQMSIPJBYUKXTR', 'FOBHMDKEXQNRAULPGSJVTYICZW', \\\n'ZJXESIUQLHAVRMDOYGTNFWPBKC'), \\\n{'P': 'O', 'O': 'P', 'L': 'A', 'A': 'L', 'N': 'D', 'D': 'N'})\n\n :param rotpos: rotor_positon\n :param rotsel: rotor_selection\n :param pb: plugb -> validated and transformed\n :return: (rotpos, rotsel, pb)\n \"\"\"\n # Checks if there are 3 unique rotors\n\n if (unique_rotsel := len(set(rotsel))) < 3:\n msg = f\"Please use 3 unique rotors (not {unique_rotsel})\"\n raise Exception(msg)\n\n # Checks if rotor positions are valid\n rotorpos1, rotorpos2, rotorpos3 = rotpos\n if not 0 < rotorpos1 <= len(abc):\n msg = f\"First rotor position is not within range of 1..26 ({rotorpos1}\"\n raise ValueError(msg)\n if not 0 < rotorpos2 <= len(abc):\n msg = f\"Second rotor position is not within range of 1..26 ({rotorpos2})\"\n raise ValueError(msg)\n if not 0 < rotorpos3 <= len(abc):\n msg = f\"Third rotor position is not within range of 1..26 ({rotorpos3})\"\n raise ValueError(msg)\n\n # Validates string and returns dict\n pbdict = _plugboard(pb)\n\n return rotpos, rotsel, pbdict\n\n\ndef _plugboard(pbstring: str) -> dict[str, str]:\n \"\"\"\n https:\/\/en.wikipedia.org\/wiki\/Enigma_machine#Plugboard\n\n >>> _plugboard('PICTURES')\n {'P': 'I', 'I': 'P', 'C': 'T', 'T': 'C', 'U': 'R', 'R': 'U', 'E': 'S', 'S': 'E'}\n >>> _plugboard('POLAND')\n {'P': 'O', 'O': 'P', 'L': 'A', 'A': 'L', 'N': 'D', 'D': 'N'}\n\n In the code, 'pb' stands for 'plugboard'\n\n Pairs can be separated by spaces\n :param pbstring: string containing plugboard setting for the Enigma machine\n :return: dictionary containing converted pairs\n \"\"\"\n\n # tests the input string if it\n # a) is type string\n # b) has even length (so pairs can be made)\n if not isinstance(pbstring, str):\n msg = f\"Plugboard setting isn't type string ({type(pbstring)})\"\n raise TypeError(msg)\n elif len(pbstring) % 2 != 0:\n msg = f\"Odd number of symbols ({len(pbstring)})\"\n raise Exception(msg)\n elif pbstring == \"\":\n return {}\n\n pbstring.replace(\" \", \"\")\n\n # Checks if all characters are unique\n tmppbl = set()\n for i in pbstring:\n if i not in abc:\n msg = f\"'{i}' not in list of symbols\"\n raise Exception(msg)\n elif i in tmppbl:\n msg = f\"Duplicate symbol ({i})\"\n raise Exception(msg)\n else:\n tmppbl.add(i)\n del tmppbl\n\n # Created the dictionary\n pb = {}\n for j in range(0, len(pbstring) - 1, 2):\n pb[pbstring[j]] = pbstring[j + 1]\n pb[pbstring[j + 1]] = pbstring[j]\n\n return pb\n\n\ndef enigma(\n text: str,\n rotor_position: RotorPositionT,\n rotor_selection: RotorSelectionT = (rotor1, rotor2, rotor3),\n plugb: str = \"\",\n) -> str:\n \"\"\"\n The only difference with real-world enigma is that I allowed string input.\n All characters are converted to uppercase. (non-letter symbol are ignored)\n How it works:\n (for every letter in the message)\n\n - Input letter goes into the plugboard.\n If it is connected to another one, switch it.\n\n - Letter goes through 3 rotors.\n Each rotor can be represented as 2 sets of symbol, where one is shuffled.\n Each symbol from the first set has corresponding symbol in\n the second set and vice versa.\n\n example:\n | ABCDEFGHIJKLMNOPQRSTUVWXYZ | e.g. F=D and D=F\n | VKLEPDBGRNWTFCJOHQAMUZYIXS |\n\n - Symbol then goes through reflector (static rotor).\n There it is switched with paired symbol\n The reflector can be represented as2 sets, each with half of the alphanet.\n There are usually 10 pairs of letters.\n\n Example:\n | ABCDEFGHIJKLM | e.g. E is paired to X\n | ZYXWVUTSRQPON | so when E goes in X goes out and vice versa\n\n - Letter then goes through the rotors again\n\n - If the letter is connected to plugboard, it is switched.\n\n - Return the letter\n\n >>> enigma('Hello World!', (1, 2, 1), plugb='pictures')\n 'KORYH JUHHI!'\n >>> enigma('KORYH, juhhi!', (1, 2, 1), plugb='pictures')\n 'HELLO, WORLD!'\n >>> enigma('hello world!', (1, 1, 1), plugb='pictures')\n 'FPNCZ QWOBU!'\n >>> enigma('FPNCZ QWOBU', (1, 1, 1), plugb='pictures')\n 'HELLO WORLD'\n\n\n :param text: input message\n :param rotor_position: tuple with 3 values in range 1..26\n :param rotor_selection: tuple with 3 rotors ()\n :param plugb: string containing plugboard configuration (default '')\n :return: en\/decrypted string\n \"\"\"\n\n text = text.upper()\n rotor_position, rotor_selection, plugboard = _validator(\n rotor_position, rotor_selection, plugb.upper()\n )\n\n rotorpos1, rotorpos2, rotorpos3 = rotor_position\n rotor1, rotor2, rotor3 = rotor_selection\n rotorpos1 -= 1\n rotorpos2 -= 1\n rotorpos3 -= 1\n\n result = []\n\n # encryption\/decryption process --------------------------\n for symbol in text:\n if symbol in abc:\n # 1st plugboard --------------------------\n if symbol in plugboard:\n symbol = plugboard[symbol]\n\n # rotor ra --------------------------\n index = abc.index(symbol) + rotorpos1\n symbol = rotor1[index % len(abc)]\n\n # rotor rb --------------------------\n index = abc.index(symbol) + rotorpos2\n symbol = rotor2[index % len(abc)]\n\n # rotor rc --------------------------\n index = abc.index(symbol) + rotorpos3\n symbol = rotor3[index % len(abc)]\n\n # reflector --------------------------\n # this is the reason you don't need another machine to decipher\n\n symbol = reflector[symbol]\n\n # 2nd rotors\n symbol = abc[rotor3.index(symbol) - rotorpos3]\n symbol = abc[rotor2.index(symbol) - rotorpos2]\n symbol = abc[rotor1.index(symbol) - rotorpos1]\n\n # 2nd plugboard\n if symbol in plugboard:\n symbol = plugboard[symbol]\n\n # moves\/resets rotor positions\n rotorpos1 += 1\n if rotorpos1 >= len(abc):\n rotorpos1 = 0\n rotorpos2 += 1\n if rotorpos2 >= len(abc):\n rotorpos2 = 0\n rotorpos3 += 1\n if rotorpos3 >= len(abc):\n rotorpos3 = 0\n\n # else:\n # pass\n # Error could be also raised\n # raise ValueError(\n # 'Invalid symbol('+repr(symbol)+')')\n result.append(symbol)\n\n return \"\".join(result)\n\n\nif __name__ == \"__main__\":\n message = \"This is my Python script that emulates the Enigma machine from WWII.\"\n rotor_pos = (1, 1, 1)\n pb = \"pictures\"\n rotor_sel = (rotor2, rotor4, rotor8)\n en = enigma(message, rotor_pos, rotor_sel, pb)\n\n print(\"Encrypted message:\", en)\n print(\"Decrypted message:\", enigma(en, rotor_pos, rotor_sel, pb))\n"} +{"Prompt":"Python program for the Fractionated Morse Cipher. The Fractionated Morse cipher first converts the plaintext to Morse code, then enciphers fixedsize blocks of Morse code back to letters. This procedure means plaintext letters are mixed into the ciphertext letters, making it more secure than substitution ciphers. http:practicalcryptography.comciphersfractionatedmorsecipher Define possible trigrams of Morse code Create a reverse dictionary for Morse code Encode a plaintext message into Morse code. Args: plaintext: The plaintext message to encode. Returns: The Morse code representation of the plaintext message. Example: encodetomorsedefend the east '..x.x...x.x.x..xxx....x.xx.x.x...x' Encrypt a plaintext message using Fractionated Morse Cipher. Args: plaintext: The plaintext message to encrypt. key: The encryption key. Returns: The encrypted ciphertext. Example: encryptfractionatedmorsedefend the east,Roundtable 'ESOAVVLJRSSTRX' Ensure morsecode length is a multiple of 3 Decrypt a ciphertext message encrypted with Fractionated Morse Cipher. Args: ciphertext: The ciphertext message to decrypt. key: The decryption key. Returns: The decrypted plaintext message. Example: decryptfractionatedmorseESOAVVLJRSSTRX,Roundtable 'DEFEND THE EAST' Example usage of Fractionated Morse Cipher.","Completions":"import string\n\nMORSE_CODE_DICT = {\n \"A\": \".-\",\n \"B\": \"-...\",\n \"C\": \"-.-.\",\n \"D\": \"-..\",\n \"E\": \".\",\n \"F\": \"..-.\",\n \"G\": \"--.\",\n \"H\": \"....\",\n \"I\": \"..\",\n \"J\": \".---\",\n \"K\": \"-.-\",\n \"L\": \".-..\",\n \"M\": \"--\",\n \"N\": \"-.\",\n \"O\": \"---\",\n \"P\": \".--.\",\n \"Q\": \"--.-\",\n \"R\": \".-.\",\n \"S\": \"...\",\n \"T\": \"-\",\n \"U\": \"..-\",\n \"V\": \"...-\",\n \"W\": \".--\",\n \"X\": \"-..-\",\n \"Y\": \"-.--\",\n \"Z\": \"--..\",\n \" \": \"\",\n}\n\n# Define possible trigrams of Morse code\nMORSE_COMBINATIONS = [\n \"...\",\n \"..-\",\n \"..x\",\n \".-.\",\n \".--\",\n \".-x\",\n \".x.\",\n \".x-\",\n \".xx\",\n \"-..\",\n \"-.-\",\n \"-.x\",\n \"--.\",\n \"---\",\n \"--x\",\n \"-x.\",\n \"-x-\",\n \"-xx\",\n \"x..\",\n \"x.-\",\n \"x.x\",\n \"x-.\",\n \"x--\",\n \"x-x\",\n \"xx.\",\n \"xx-\",\n \"xxx\",\n]\n\n# Create a reverse dictionary for Morse code\nREVERSE_DICT = {value: key for key, value in MORSE_CODE_DICT.items()}\n\n\ndef encode_to_morse(plaintext: str) -> str:\n \"\"\"Encode a plaintext message into Morse code.\n\n Args:\n plaintext: The plaintext message to encode.\n\n Returns:\n The Morse code representation of the plaintext message.\n\n Example:\n >>> encode_to_morse(\"defend the east\")\n '-..x.x..-.x.x-.x-..xx-x....x.xx.x.-x...x-'\n \"\"\"\n return \"x\".join([MORSE_CODE_DICT.get(letter.upper(), \"\") for letter in plaintext])\n\n\ndef encrypt_fractionated_morse(plaintext: str, key: str) -> str:\n \"\"\"Encrypt a plaintext message using Fractionated Morse Cipher.\n\n Args:\n plaintext: The plaintext message to encrypt.\n key: The encryption key.\n\n Returns:\n The encrypted ciphertext.\n\n Example:\n >>> encrypt_fractionated_morse(\"defend the east\",\"Roundtable\")\n 'ESOAVVLJRSSTRX'\n\n \"\"\"\n morse_code = encode_to_morse(plaintext)\n key = key.upper() + string.ascii_uppercase\n key = \"\".join(sorted(set(key), key=key.find))\n\n # Ensure morse_code length is a multiple of 3\n padding_length = 3 - (len(morse_code) % 3)\n morse_code += \"x\" * padding_length\n\n fractionated_morse_dict = {v: k for k, v in zip(key, MORSE_COMBINATIONS)}\n fractionated_morse_dict[\"xxx\"] = \"\"\n encrypted_text = \"\".join(\n [\n fractionated_morse_dict[morse_code[i : i + 3]]\n for i in range(0, len(morse_code), 3)\n ]\n )\n return encrypted_text\n\n\ndef decrypt_fractionated_morse(ciphertext: str, key: str) -> str:\n \"\"\"Decrypt a ciphertext message encrypted with Fractionated Morse Cipher.\n\n Args:\n ciphertext: The ciphertext message to decrypt.\n key: The decryption key.\n\n Returns:\n The decrypted plaintext message.\n\n Example:\n >>> decrypt_fractionated_morse(\"ESOAVVLJRSSTRX\",\"Roundtable\")\n 'DEFEND THE EAST'\n \"\"\"\n key = key.upper() + string.ascii_uppercase\n key = \"\".join(sorted(set(key), key=key.find))\n\n inverse_fractionated_morse_dict = dict(zip(key, MORSE_COMBINATIONS))\n morse_code = \"\".join(\n [inverse_fractionated_morse_dict.get(letter, \"\") for letter in ciphertext]\n )\n decrypted_text = \"\".join(\n [REVERSE_DICT[code] for code in morse_code.split(\"x\")]\n ).strip()\n return decrypted_text\n\n\nif __name__ == \"__main__\":\n \"\"\"\n Example usage of Fractionated Morse Cipher.\n \"\"\"\n plaintext = \"defend the east\"\n print(\"Plain Text:\", plaintext)\n key = \"ROUNDTABLE\"\n\n ciphertext = encrypt_fractionated_morse(plaintext, key)\n print(\"Encrypted:\", ciphertext)\n\n decrypted_text = decrypt_fractionated_morse(ciphertext, key)\n print(\"Decrypted:\", decrypted_text)\n"} +{"Prompt":"Hill Cipher: The 'HillCipher' class below implements the Hill Cipher algorithm which uses modern linear algebra techniques to encode and decode text using an encryption key matrix. Algorithm: Let the order of the encryption key be N as it is a square matrix. Your text is divided into batches of length N and converted to numerical vectors by a simple mapping starting with A0 and so on. The key is then multiplied with the newly created batch vector to obtain the encoded vector. After each multiplication modular 36 calculations are performed on the vectors so as to bring the numbers between 0 and 36 and then mapped with their corresponding alphanumerics. While decrypting, the decrypting key is found which is the inverse of the encrypting key modular 36. The same process is repeated for decrypting to get the original message back. Constraints: The determinant of the encryption key matrix must be relatively prime w.r.t 36. Note: This implementation only considers alphanumerics in the text. If the length of the text to be encrypted is not a multiple of the break keythe length of one batch of letters, the last character of the text is added to the text until the length of the text reaches a multiple of the breakkey. So the text after decrypting might be a little different than the original text. References: https:apprendreenligne.netcryptohillHillciph.pdf https:www.youtube.comwatch?vkfmNeskzs2o https:www.youtube.comwatch?v4RhLNDqcjpA This cipher takes alphanumerics into account i.e. a total of 36 characters take x and return x lenkeystring encryptkey is an NxN numpy array hillcipher HillCiphernumpy.array2, 5, 1, 6 hillcipher.replaceletters'T' 19 hillcipher.replaceletters'0' 26 hillcipher HillCiphernumpy.array2, 5, 1, 6 hillcipher.replacedigits19 'T' hillcipher.replacedigits26 '0' hillcipher HillCiphernumpy.array2, 5, 1, 6 hillcipher.checkdeterminant hillcipher HillCiphernumpy.array2, 5, 1, 6 hillcipher.processtext'Testing Hill Cipher' 'TESTINGHILLCIPHERR' hillcipher.processtext'hello' 'HELLOO' hillcipher HillCiphernumpy.array2, 5, 1, 6 hillcipher.encrypt'testing hill cipher' 'WHXYJOLM9C6XT085LL' hillcipher.encrypt'hello' '85FF00' hillcipher HillCiphernumpy.array2, 5, 1, 6 hillcipher.makedecryptkey array 6, 25, 5, 26 hillcipher HillCiphernumpy.array2, 5, 1, 6 hillcipher.decrypt'WHXYJOLM9C6XT085LL' 'TESTINGHILLCIPHERR' hillcipher.decrypt'85FF00' 'HELLOO'","Completions":"import string\n\nimport numpy\n\nfrom maths.greatest_common_divisor import greatest_common_divisor\n\n\nclass HillCipher:\n key_string = string.ascii_uppercase + string.digits\n # This cipher takes alphanumerics into account\n # i.e. a total of 36 characters\n\n # take x and return x % len(key_string)\n modulus = numpy.vectorize(lambda x: x % 36)\n\n to_int = numpy.vectorize(round)\n\n def __init__(self, encrypt_key: numpy.ndarray) -> None:\n \"\"\"\n encrypt_key is an NxN numpy array\n \"\"\"\n self.encrypt_key = self.modulus(encrypt_key) # mod36 calc's on the encrypt key\n self.check_determinant() # validate the determinant of the encryption key\n self.break_key = encrypt_key.shape[0]\n\n def replace_letters(self, letter: str) -> int:\n \"\"\"\n >>> hill_cipher = HillCipher(numpy.array([[2, 5], [1, 6]]))\n >>> hill_cipher.replace_letters('T')\n 19\n >>> hill_cipher.replace_letters('0')\n 26\n \"\"\"\n return self.key_string.index(letter)\n\n def replace_digits(self, num: int) -> str:\n \"\"\"\n >>> hill_cipher = HillCipher(numpy.array([[2, 5], [1, 6]]))\n >>> hill_cipher.replace_digits(19)\n 'T'\n >>> hill_cipher.replace_digits(26)\n '0'\n \"\"\"\n return self.key_string[round(num)]\n\n def check_determinant(self) -> None:\n \"\"\"\n >>> hill_cipher = HillCipher(numpy.array([[2, 5], [1, 6]]))\n >>> hill_cipher.check_determinant()\n \"\"\"\n det = round(numpy.linalg.det(self.encrypt_key))\n\n if det < 0:\n det = det % len(self.key_string)\n\n req_l = len(self.key_string)\n if greatest_common_divisor(det, len(self.key_string)) != 1:\n msg = (\n f\"determinant modular {req_l} of encryption key({det}) \"\n f\"is not co prime w.r.t {req_l}.\\nTry another key.\"\n )\n raise ValueError(msg)\n\n def process_text(self, text: str) -> str:\n \"\"\"\n >>> hill_cipher = HillCipher(numpy.array([[2, 5], [1, 6]]))\n >>> hill_cipher.process_text('Testing Hill Cipher')\n 'TESTINGHILLCIPHERR'\n >>> hill_cipher.process_text('hello')\n 'HELLOO'\n \"\"\"\n chars = [char for char in text.upper() if char in self.key_string]\n\n last = chars[-1]\n while len(chars) % self.break_key != 0:\n chars.append(last)\n\n return \"\".join(chars)\n\n def encrypt(self, text: str) -> str:\n \"\"\"\n >>> hill_cipher = HillCipher(numpy.array([[2, 5], [1, 6]]))\n >>> hill_cipher.encrypt('testing hill cipher')\n 'WHXYJOLM9C6XT085LL'\n >>> hill_cipher.encrypt('hello')\n '85FF00'\n \"\"\"\n text = self.process_text(text.upper())\n encrypted = \"\"\n\n for i in range(0, len(text) - self.break_key + 1, self.break_key):\n batch = text[i : i + self.break_key]\n vec = [self.replace_letters(char) for char in batch]\n batch_vec = numpy.array([vec]).T\n batch_encrypted = self.modulus(self.encrypt_key.dot(batch_vec)).T.tolist()[\n 0\n ]\n encrypted_batch = \"\".join(\n self.replace_digits(num) for num in batch_encrypted\n )\n encrypted += encrypted_batch\n\n return encrypted\n\n def make_decrypt_key(self) -> numpy.ndarray:\n \"\"\"\n >>> hill_cipher = HillCipher(numpy.array([[2, 5], [1, 6]]))\n >>> hill_cipher.make_decrypt_key()\n array([[ 6, 25],\n [ 5, 26]])\n \"\"\"\n det = round(numpy.linalg.det(self.encrypt_key))\n\n if det < 0:\n det = det % len(self.key_string)\n det_inv = None\n for i in range(len(self.key_string)):\n if (det * i) % len(self.key_string) == 1:\n det_inv = i\n break\n\n inv_key = (\n det_inv\n * numpy.linalg.det(self.encrypt_key)\n * numpy.linalg.inv(self.encrypt_key)\n )\n\n return self.to_int(self.modulus(inv_key))\n\n def decrypt(self, text: str) -> str:\n \"\"\"\n >>> hill_cipher = HillCipher(numpy.array([[2, 5], [1, 6]]))\n >>> hill_cipher.decrypt('WHXYJOLM9C6XT085LL')\n 'TESTINGHILLCIPHERR'\n >>> hill_cipher.decrypt('85FF00')\n 'HELLOO'\n \"\"\"\n decrypt_key = self.make_decrypt_key()\n text = self.process_text(text.upper())\n decrypted = \"\"\n\n for i in range(0, len(text) - self.break_key + 1, self.break_key):\n batch = text[i : i + self.break_key]\n vec = [self.replace_letters(char) for char in batch]\n batch_vec = numpy.array([vec]).T\n batch_decrypted = self.modulus(decrypt_key.dot(batch_vec)).T.tolist()[0]\n decrypted_batch = \"\".join(\n self.replace_digits(num) for num in batch_decrypted\n )\n decrypted += decrypted_batch\n\n return decrypted\n\n\ndef main() -> None:\n n = int(input(\"Enter the order of the encryption key: \"))\n hill_matrix = []\n\n print(\"Enter each row of the encryption key with space separated integers\")\n for _ in range(n):\n row = [int(x) for x in input().split()]\n hill_matrix.append(row)\n\n hc = HillCipher(numpy.array(hill_matrix))\n\n print(\"Would you like to encrypt or decrypt some text? (1 or 2)\")\n option = input(\"\\n1. Encrypt\\n2. Decrypt\\n\")\n if option == \"1\":\n text_e = input(\"What text would you like to encrypt?: \")\n print(\"Your encrypted text is:\")\n print(hc.encrypt(text_e))\n elif option == \"2\":\n text_d = input(\"What text would you like to decrypt?: \")\n print(\"Your decrypted text is:\")\n print(hc.decrypt(text_d))\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n\n main()\n"} +{"Prompt":"For keyword: hello H E L O A B C D F G I J K M N P Q R S T U V W X Y Z and map vertically mixedkeywordcollege, UNIVERSITY, True doctest: NORMALIZEWHITESPACE 'A': 'C', 'B': 'A', 'C': 'I', 'D': 'P', 'E': 'U', 'F': 'Z', 'G': 'O', 'H': 'B', 'I': 'J', 'J': 'Q', 'K': 'V', 'L': 'L', 'M': 'D', 'N': 'K', 'O': 'R', 'P': 'W', 'Q': 'E', 'R': 'F', 'S': 'M', 'T': 'S', 'U': 'X', 'V': 'G', 'W': 'H', 'X': 'N', 'Y': 'T', 'Z': 'Y' 'XKJGUFMJST' mixedkeywordcollege, UNIVERSITY, False doctest: NORMALIZEWHITESPACE 'XKJGUFMJST' create a list of unique characters in the keyword their order matters it determines how we will map plaintext characters to the ciphertext the number of those unique characters will determine the number of rows create a shifted version of the alphabet create a modified alphabet by splitting the shifted alphabet into rows map the alphabet characters to the modified alphabet characters going 'vertically' through the modified alphabet consider columns first if current row the last one is too short, break out of loop map current letter to letter in modified alphabet create the encrypted text by mapping the plaintext to the modified alphabet example use","Completions":"from string import ascii_uppercase\n\n\ndef mixed_keyword(\n keyword: str, plaintext: str, verbose: bool = False, alphabet: str = ascii_uppercase\n) -> str:\n \"\"\"\n For keyword: hello\n\n H E L O\n A B C D\n F G I J\n K M N P\n Q R S T\n U V W X\n Y Z\n and map vertically\n\n >>> mixed_keyword(\"college\", \"UNIVERSITY\", True) # doctest: +NORMALIZE_WHITESPACE\n {'A': 'C', 'B': 'A', 'C': 'I', 'D': 'P', 'E': 'U', 'F': 'Z', 'G': 'O', 'H': 'B',\n 'I': 'J', 'J': 'Q', 'K': 'V', 'L': 'L', 'M': 'D', 'N': 'K', 'O': 'R', 'P': 'W',\n 'Q': 'E', 'R': 'F', 'S': 'M', 'T': 'S', 'U': 'X', 'V': 'G', 'W': 'H', 'X': 'N',\n 'Y': 'T', 'Z': 'Y'}\n 'XKJGUFMJST'\n\n >>> mixed_keyword(\"college\", \"UNIVERSITY\", False) # doctest: +NORMALIZE_WHITESPACE\n 'XKJGUFMJST'\n \"\"\"\n keyword = keyword.upper()\n plaintext = plaintext.upper()\n alphabet_set = set(alphabet)\n\n # create a list of unique characters in the keyword - their order matters\n # it determines how we will map plaintext characters to the ciphertext\n unique_chars = []\n for char in keyword:\n if char in alphabet_set and char not in unique_chars:\n unique_chars.append(char)\n # the number of those unique characters will determine the number of rows\n num_unique_chars_in_keyword = len(unique_chars)\n\n # create a shifted version of the alphabet\n shifted_alphabet = unique_chars + [\n char for char in alphabet if char not in unique_chars\n ]\n\n # create a modified alphabet by splitting the shifted alphabet into rows\n modified_alphabet = [\n shifted_alphabet[k : k + num_unique_chars_in_keyword]\n for k in range(0, 26, num_unique_chars_in_keyword)\n ]\n\n # map the alphabet characters to the modified alphabet characters\n # going 'vertically' through the modified alphabet - consider columns first\n mapping = {}\n letter_index = 0\n for column in range(num_unique_chars_in_keyword):\n for row in modified_alphabet:\n # if current row (the last one) is too short, break out of loop\n if len(row) <= column:\n break\n\n # map current letter to letter in modified alphabet\n mapping[alphabet[letter_index]] = row[column]\n letter_index += 1\n\n if verbose:\n print(mapping)\n # create the encrypted text by mapping the plaintext to the modified alphabet\n return \"\".join(mapping[char] if char in mapping else char for char in plaintext)\n\n\nif __name__ == \"__main__\":\n # example use\n print(mixed_keyword(\"college\", \"UNIVERSITY\"))\n"} +{"Prompt":"translatemessageQWERTYUIOPASDFGHJKLZXCVBNM,Hello World,encrypt 'Pcssi Bidsm' loop through each symbol in the message encryptdecrypt the symbol symbol is not in LETTERS, just add it encryptmessageQWERTYUIOPASDFGHJKLZXCVBNM, Hello World 'Pcssi Bidsm' decryptmessageQWERTYUIOPASDFGHJKLZXCVBNM, Hello World 'Itssg Vgksr'","Completions":"from typing import Literal\n\nLETTERS = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n\n\ndef translate_message(\n key: str, message: str, mode: Literal[\"encrypt\", \"decrypt\"]\n) -> str:\n \"\"\"\n >>> translate_message(\"QWERTYUIOPASDFGHJKLZXCVBNM\",\"Hello World\",\"encrypt\")\n 'Pcssi Bidsm'\n \"\"\"\n chars_a = LETTERS if mode == \"decrypt\" else key\n chars_b = key if mode == \"decrypt\" else LETTERS\n translated = \"\"\n # loop through each symbol in the message\n for symbol in message:\n if symbol.upper() in chars_a:\n # encrypt\/decrypt the symbol\n sym_index = chars_a.find(symbol.upper())\n if symbol.isupper():\n translated += chars_b[sym_index].upper()\n else:\n translated += chars_b[sym_index].lower()\n else:\n # symbol is not in LETTERS, just add it\n translated += symbol\n return translated\n\n\ndef encrypt_message(key: str, message: str) -> str:\n \"\"\"\n >>> encrypt_message(\"QWERTYUIOPASDFGHJKLZXCVBNM\", \"Hello World\")\n 'Pcssi Bidsm'\n \"\"\"\n return translate_message(key, message, \"encrypt\")\n\n\ndef decrypt_message(key: str, message: str) -> str:\n \"\"\"\n >>> decrypt_message(\"QWERTYUIOPASDFGHJKLZXCVBNM\", \"Hello World\")\n 'Itssg Vgksr'\n \"\"\"\n return translate_message(key, message, \"decrypt\")\n\n\ndef main() -> None:\n message = \"Hello World\"\n key = \"QWERTYUIOPASDFGHJKLZXCVBNM\"\n mode = \"decrypt\" # set to 'encrypt' or 'decrypt'\n\n if mode == \"encrypt\":\n translated = encrypt_message(key, message)\n elif mode == \"decrypt\":\n translated = decrypt_message(key, message)\n print(f\"Using the key {key}, the {mode}ed message is: {translated}\")\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n main()\n"} +{"Prompt":"!usrbinenv python3 Python program to translate to and from Morse code. https:en.wikipedia.orgwikiMorsecode fmt: off fmt: on encryptSos! '... ... ..' encryptSOS! encryptsos! True decrypt'... ... ..' 'SOS!' s .joinMORSECODEDICT decryptencrypts s True","Completions":"#!\/usr\/bin\/env python3\n\n\"\"\"\nPython program to translate to and from Morse code.\n\nhttps:\/\/en.wikipedia.org\/wiki\/Morse_code\n\"\"\"\n\n# fmt: off\nMORSE_CODE_DICT = {\n \"A\": \".-\", \"B\": \"-...\", \"C\": \"-.-.\", \"D\": \"-..\", \"E\": \".\", \"F\": \"..-.\", \"G\": \"--.\",\n \"H\": \"....\", \"I\": \"..\", \"J\": \".---\", \"K\": \"-.-\", \"L\": \".-..\", \"M\": \"--\", \"N\": \"-.\",\n \"O\": \"---\", \"P\": \".--.\", \"Q\": \"--.-\", \"R\": \".-.\", \"S\": \"...\", \"T\": \"-\", \"U\": \"..-\",\n \"V\": \"...-\", \"W\": \".--\", \"X\": \"-..-\", \"Y\": \"-.--\", \"Z\": \"--..\", \"1\": \".----\",\n \"2\": \"..---\", \"3\": \"...--\", \"4\": \"....-\", \"5\": \".....\", \"6\": \"-....\", \"7\": \"--...\",\n \"8\": \"---..\", \"9\": \"----.\", \"0\": \"-----\", \"&\": \".-...\", \"@\": \".--.-.\",\n \":\": \"---...\", \",\": \"--..--\", \".\": \".-.-.-\", \"'\": \".----.\", '\"': \".-..-.\",\n \"?\": \"..--..\", \"\/\": \"-..-.\", \"=\": \"-...-\", \"+\": \".-.-.\", \"-\": \"-....-\",\n \"(\": \"-.--.\", \")\": \"-.--.-\", \"!\": \"-.-.--\", \" \": \"\/\"\n} # Exclamation mark is not in ITU-R recommendation\n# fmt: on\nREVERSE_DICT = {value: key for key, value in MORSE_CODE_DICT.items()}\n\n\ndef encrypt(message: str) -> str:\n \"\"\"\n >>> encrypt(\"Sos!\")\n '... --- ... -.-.--'\n >>> encrypt(\"SOS!\") == encrypt(\"sos!\")\n True\n \"\"\"\n return \" \".join(MORSE_CODE_DICT[char] for char in message.upper())\n\n\ndef decrypt(message: str) -> str:\n \"\"\"\n >>> decrypt('... --- ... -.-.--')\n 'SOS!'\n \"\"\"\n return \"\".join(REVERSE_DICT[char] for char in message.split())\n\n\ndef main() -> None:\n \"\"\"\n >>> s = \"\".join(MORSE_CODE_DICT)\n >>> decrypt(encrypt(s)) == s\n True\n \"\"\"\n message = \"Morse code here!\"\n print(message)\n message = encrypt(message)\n print(message)\n message = decrypt(message)\n print(message)\n\n\nif __name__ == \"__main__\":\n main()\n"} +{"Prompt":"Function to encrypt text using pseudorandom numbers Onepad.encrypt , Onepad.encrypt , random.seed1 Onepad.encrypt 6969, 69 random.seed1 Onepad.encryptHello 9729, 114756, 4653, 31309, 10492, 69, 292, 33, 131, 61 Onepad.encrypt1 Traceback most recent call last: ... TypeError: 'int' object is not iterable Onepad.encrypt1.1 Traceback most recent call last: ... TypeError: 'float' object is not iterable Function to decrypt text using pseudorandom numbers. Onepad.decrypt, '' Onepad.decrypt35, '' Onepad.decrypt, 35 Traceback most recent call last: ... IndexError: list index out of range random.seed1 Onepad.decrypt9729, 114756, 4653, 31309, 10492, 69, 292, 33, 131, 61 'Hello'","Completions":"import random\n\n\nclass Onepad:\n @staticmethod\n def encrypt(text: str) -> tuple[list[int], list[int]]:\n \"\"\"\n Function to encrypt text using pseudo-random numbers\n >>> Onepad().encrypt(\"\")\n ([], [])\n >>> Onepad().encrypt([])\n ([], [])\n >>> random.seed(1)\n >>> Onepad().encrypt(\" \")\n ([6969], [69])\n >>> random.seed(1)\n >>> Onepad().encrypt(\"Hello\")\n ([9729, 114756, 4653, 31309, 10492], [69, 292, 33, 131, 61])\n >>> Onepad().encrypt(1)\n Traceback (most recent call last):\n ...\n TypeError: 'int' object is not iterable\n >>> Onepad().encrypt(1.1)\n Traceback (most recent call last):\n ...\n TypeError: 'float' object is not iterable\n \"\"\"\n plain = [ord(i) for i in text]\n key = []\n cipher = []\n for i in plain:\n k = random.randint(1, 300)\n c = (i + k) * k\n cipher.append(c)\n key.append(k)\n return cipher, key\n\n @staticmethod\n def decrypt(cipher: list[int], key: list[int]) -> str:\n \"\"\"\n Function to decrypt text using pseudo-random numbers.\n >>> Onepad().decrypt([], [])\n ''\n >>> Onepad().decrypt([35], [])\n ''\n >>> Onepad().decrypt([], [35])\n Traceback (most recent call last):\n ...\n IndexError: list index out of range\n >>> random.seed(1)\n >>> Onepad().decrypt([9729, 114756, 4653, 31309, 10492], [69, 292, 33, 131, 61])\n 'Hello'\n \"\"\"\n plain = []\n for i in range(len(key)):\n p = int((cipher[i] - (key[i]) ** 2) \/ key[i])\n plain.append(chr(p))\n return \"\".join(plain)\n\n\nif __name__ == \"__main__\":\n c, k = Onepad().encrypt(\"Hello\")\n print(c, k)\n print(Onepad().decrypt(c, k))\n"} +{"Prompt":"The permutation cipher, also called the transposition cipher, is a simple encryption technique that rearranges the characters in a message based on a secret key. It divides the message into blocks and applies a permutation to the characters within each block according to the key. The key is a sequence of unique integers that determine the order of character rearrangement. For more info: https:www.nku.educhristensen140220permutation20ciphers.pdf Generate a valid block size that is a factor of the message length. Args: messagelength int: The length of the message. Returns: int: A valid block size. Example: random.seed1 generatevalidblocksize12 3 Generate a random permutation key of a specified block size. Args: blocksize int: The size of each permutation block. Returns: listint: A list containing a random permutation of digits. Example: random.seed0 generatepermutationkey4 2, 0, 1, 3 Encrypt a message using a permutation cipher with block rearrangement using a key. Args: message str: The plaintext message to be encrypted. key listint: The permutation key for decryption. blocksize int: The size of each permutation block. Returns: tuple: A tuple containing the encrypted message and the encryption key. Example: encryptedmessage, key encryptHELLO WORLD decryptedmessage decryptencryptedmessage, key decryptedmessage 'HELLO WORLD' Decrypt an encrypted message using a permutation cipher with block rearrangement. Args: encryptedmessage str: The encrypted message. key listint: The permutation key for decryption. Returns: str: The decrypted plaintext message. Example: encryptedmessage, key encryptHELLO WORLD decryptedmessage decryptencryptedmessage, key decryptedmessage 'HELLO WORLD' Driver function to pass message to get encrypted, then decrypted. Example: main Decrypted message: HELLO WORLD","Completions":"import random\n\n\ndef generate_valid_block_size(message_length: int) -> int:\n \"\"\"\n Generate a valid block size that is a factor of the message length.\n\n Args:\n message_length (int): The length of the message.\n\n Returns:\n int: A valid block size.\n\n Example:\n >>> random.seed(1)\n >>> generate_valid_block_size(12)\n 3\n \"\"\"\n block_sizes = [\n block_size\n for block_size in range(2, message_length + 1)\n if message_length % block_size == 0\n ]\n return random.choice(block_sizes)\n\n\ndef generate_permutation_key(block_size: int) -> list[int]:\n \"\"\"\n Generate a random permutation key of a specified block size.\n\n Args:\n block_size (int): The size of each permutation block.\n\n Returns:\n list[int]: A list containing a random permutation of digits.\n\n Example:\n >>> random.seed(0)\n >>> generate_permutation_key(4)\n [2, 0, 1, 3]\n \"\"\"\n digits = list(range(block_size))\n random.shuffle(digits)\n return digits\n\n\ndef encrypt(\n message: str, key: list[int] | None = None, block_size: int | None = None\n) -> tuple[str, list[int]]:\n \"\"\"\n Encrypt a message using a permutation cipher with block rearrangement using a key.\n\n Args:\n message (str): The plaintext message to be encrypted.\n key (list[int]): The permutation key for decryption.\n block_size (int): The size of each permutation block.\n\n Returns:\n tuple: A tuple containing the encrypted message and the encryption key.\n\n Example:\n >>> encrypted_message, key = encrypt(\"HELLO WORLD\")\n >>> decrypted_message = decrypt(encrypted_message, key)\n >>> decrypted_message\n 'HELLO WORLD'\n \"\"\"\n message = message.upper()\n message_length = len(message)\n\n if key is None or block_size is None:\n block_size = generate_valid_block_size(message_length)\n key = generate_permutation_key(block_size)\n\n encrypted_message = \"\"\n\n for i in range(0, message_length, block_size):\n block = message[i : i + block_size]\n rearranged_block = [block[digit] for digit in key]\n encrypted_message += \"\".join(rearranged_block)\n\n return encrypted_message, key\n\n\ndef decrypt(encrypted_message: str, key: list[int]) -> str:\n \"\"\"\n Decrypt an encrypted message using a permutation cipher with block rearrangement.\n\n Args:\n encrypted_message (str): The encrypted message.\n key (list[int]): The permutation key for decryption.\n\n Returns:\n str: The decrypted plaintext message.\n\n Example:\n >>> encrypted_message, key = encrypt(\"HELLO WORLD\")\n >>> decrypted_message = decrypt(encrypted_message, key)\n >>> decrypted_message\n 'HELLO WORLD'\n \"\"\"\n key_length = len(key)\n decrypted_message = \"\"\n\n for i in range(0, len(encrypted_message), key_length):\n block = encrypted_message[i : i + key_length]\n original_block = [\"\"] * key_length\n for j, digit in enumerate(key):\n original_block[digit] = block[j]\n decrypted_message += \"\".join(original_block)\n\n return decrypted_message\n\n\ndef main() -> None:\n \"\"\"\n Driver function to pass message to get encrypted, then decrypted.\n\n Example:\n >>> main()\n Decrypted message: HELLO WORLD\n \"\"\"\n message = \"HELLO WORLD\"\n encrypted_message, key = encrypt(message)\n\n decrypted_message = decrypt(encrypted_message, key)\n print(f\"Decrypted message: {decrypted_message}\")\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n main()\n"} +{"Prompt":"https:en.wikipedia.orgwikiPlayfaircipherDescription The Playfair cipher was developed by Charles Wheatstone in 1854 It's use was heavily promotedby Lord Playfair, hence its name Some features of the Playfair cipher are: 1 It was the first literal diagram substitution cipher 2 It is a manual symmetric encryption technique 3 It is a multiple letter encryption cipher The implementation in the code below encodes alphabets only. It removes spaces, special characters and numbers from the code. Playfair is no longer used by military forces because of known insecurities and of the advent of automated encryption devices. This cipher is regarded as insecure since before World War I. Prepare the plaintext by upcasing it and separating repeated letters with X's I and J are used interchangeably to allow us to use a 5x5 table 25 letters we're using a list instead of a '2d' array because it makes the math for setting up the table and doing the actual encodingdecoding simpler copy key chars into the table if they are in alphabet ignoring duplicates fill the rest of the table in with the remaining alphabet chars Encode the given plaintext using the Playfair cipher. Takes the plaintext and the key as input and returns the encoded string. encodeHello, MONARCHY 'CFSUPM' encodeattack on the left flank, EMERGENCY 'DQZSBYFSDZFMFNLOHFDRSG' encodeSorry!, SPECIAL 'AVXETX' encodeNumber 1, NUMBER 'UMBENF' encodePhotosynthesis!, THE SUN 'OEMHQHVCHESUKE' Decode the input string using the provided key. decodeBMZFAZRZDH, HAZARD 'FIREHAZARD' decodeHNBWBPQT, AUTOMOBILE 'DRIVINGX' decodeSLYSSAQS, CASTLE 'ATXTACKX'","Completions":"import itertools\nimport string\nfrom collections.abc import Generator, Iterable\n\n\ndef chunker(seq: Iterable[str], size: int) -> Generator[tuple[str, ...], None, None]:\n it = iter(seq)\n while True:\n chunk = tuple(itertools.islice(it, size))\n if not chunk:\n return\n yield chunk\n\n\ndef prepare_input(dirty: str) -> str:\n \"\"\"\n Prepare the plaintext by up-casing it\n and separating repeated letters with X's\n \"\"\"\n\n dirty = \"\".join([c.upper() for c in dirty if c in string.ascii_letters])\n clean = \"\"\n\n if len(dirty) < 2:\n return dirty\n\n for i in range(len(dirty) - 1):\n clean += dirty[i]\n\n if dirty[i] == dirty[i + 1]:\n clean += \"X\"\n\n clean += dirty[-1]\n\n if len(clean) & 1:\n clean += \"X\"\n\n return clean\n\n\ndef generate_table(key: str) -> list[str]:\n # I and J are used interchangeably to allow\n # us to use a 5x5 table (25 letters)\n alphabet = \"ABCDEFGHIKLMNOPQRSTUVWXYZ\"\n # we're using a list instead of a '2d' array because it makes the math\n # for setting up the table and doing the actual encoding\/decoding simpler\n table = []\n\n # copy key chars into the table if they are in `alphabet` ignoring duplicates\n for char in key.upper():\n if char not in table and char in alphabet:\n table.append(char)\n\n # fill the rest of the table in with the remaining alphabet chars\n for char in alphabet:\n if char not in table:\n table.append(char)\n\n return table\n\n\ndef encode(plaintext: str, key: str) -> str:\n \"\"\"\n Encode the given plaintext using the Playfair cipher.\n Takes the plaintext and the key as input and returns the encoded string.\n\n >>> encode(\"Hello\", \"MONARCHY\")\n 'CFSUPM'\n >>> encode(\"attack on the left flank\", \"EMERGENCY\")\n 'DQZSBYFSDZFMFNLOHFDRSG'\n >>> encode(\"Sorry!\", \"SPECIAL\")\n 'AVXETX'\n >>> encode(\"Number 1\", \"NUMBER\")\n 'UMBENF'\n >>> encode(\"Photosynthesis!\", \"THE SUN\")\n 'OEMHQHVCHESUKE'\n \"\"\"\n\n table = generate_table(key)\n plaintext = prepare_input(plaintext)\n ciphertext = \"\"\n\n for char1, char2 in chunker(plaintext, 2):\n row1, col1 = divmod(table.index(char1), 5)\n row2, col2 = divmod(table.index(char2), 5)\n\n if row1 == row2:\n ciphertext += table[row1 * 5 + (col1 + 1) % 5]\n ciphertext += table[row2 * 5 + (col2 + 1) % 5]\n elif col1 == col2:\n ciphertext += table[((row1 + 1) % 5) * 5 + col1]\n ciphertext += table[((row2 + 1) % 5) * 5 + col2]\n else: # rectangle\n ciphertext += table[row1 * 5 + col2]\n ciphertext += table[row2 * 5 + col1]\n\n return ciphertext\n\n\ndef decode(ciphertext: str, key: str) -> str:\n \"\"\"\n Decode the input string using the provided key.\n\n >>> decode(\"BMZFAZRZDH\", \"HAZARD\")\n 'FIREHAZARD'\n >>> decode(\"HNBWBPQT\", \"AUTOMOBILE\")\n 'DRIVINGX'\n >>> decode(\"SLYSSAQS\", \"CASTLE\")\n 'ATXTACKX'\n \"\"\"\n\n table = generate_table(key)\n plaintext = \"\"\n\n for char1, char2 in chunker(ciphertext, 2):\n row1, col1 = divmod(table.index(char1), 5)\n row2, col2 = divmod(table.index(char2), 5)\n\n if row1 == row2:\n plaintext += table[row1 * 5 + (col1 - 1) % 5]\n plaintext += table[row2 * 5 + (col2 - 1) % 5]\n elif col1 == col2:\n plaintext += table[((row1 - 1) % 5) * 5 + col1]\n plaintext += table[((row2 - 1) % 5) * 5 + col2]\n else: # rectangle\n plaintext += table[row1 * 5 + col2]\n plaintext += table[row2 * 5 + col1]\n\n return plaintext\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n\n print(\"Encoded:\", encode(\"BYE AND THANKS\", \"GREETING\"))\n print(\"Decoded:\", decode(\"CXRBANRLBALQ\", \"GREETING\"))\n"} +{"Prompt":"!usrbinenv python3 A Polybius Square is a table that allows someone to translate letters into numbers. https:www.braingle.combrainteaserscodespolybius.php Return the pair of numbers that represents the given letter in the polybius square np.arrayequalPolybiusCipher.lettertonumbers'a', 1,1 True np.arrayequalPolybiusCipher.lettertonumbers'u', 4,5 True Return the letter corresponding to the position index1, index2 in the polybius square PolybiusCipher.numberstoletter4, 5 u True PolybiusCipher.numberstoletter1, 1 a True Return the encoded version of message according to the polybius cipher PolybiusCipher.encodetest message 44154344 32154343112215 True PolybiusCipher.encodeTest Message 44154344 32154343112215 True Return the decoded version of message according to the polybius cipher PolybiusCipher.decode44154344 32154343112215 test message True PolybiusCipher.decode4415434432154343112215 testmessage True","Completions":"#!\/usr\/bin\/env python3\n\n\"\"\"\nA Polybius Square is a table that allows someone to translate letters into numbers.\n\nhttps:\/\/www.braingle.com\/brainteasers\/codes\/polybius.php\n\"\"\"\n\nimport numpy as np\n\nSQUARE = [\n [\"a\", \"b\", \"c\", \"d\", \"e\"],\n [\"f\", \"g\", \"h\", \"i\", \"k\"],\n [\"l\", \"m\", \"n\", \"o\", \"p\"],\n [\"q\", \"r\", \"s\", \"t\", \"u\"],\n [\"v\", \"w\", \"x\", \"y\", \"z\"],\n]\n\n\nclass PolybiusCipher:\n def __init__(self) -> None:\n self.SQUARE = np.array(SQUARE)\n\n def letter_to_numbers(self, letter: str) -> np.ndarray:\n \"\"\"\n Return the pair of numbers that represents the given letter in the\n polybius square\n >>> np.array_equal(PolybiusCipher().letter_to_numbers('a'), [1,1])\n True\n\n >>> np.array_equal(PolybiusCipher().letter_to_numbers('u'), [4,5])\n True\n \"\"\"\n index1, index2 = np.where(letter == self.SQUARE)\n indexes = np.concatenate([index1 + 1, index2 + 1])\n return indexes\n\n def numbers_to_letter(self, index1: int, index2: int) -> str:\n \"\"\"\n Return the letter corresponding to the position [index1, index2] in\n the polybius square\n\n >>> PolybiusCipher().numbers_to_letter(4, 5) == \"u\"\n True\n\n >>> PolybiusCipher().numbers_to_letter(1, 1) == \"a\"\n True\n \"\"\"\n return self.SQUARE[index1 - 1, index2 - 1]\n\n def encode(self, message: str) -> str:\n \"\"\"\n Return the encoded version of message according to the polybius cipher\n\n >>> PolybiusCipher().encode(\"test message\") == \"44154344 32154343112215\"\n True\n\n >>> PolybiusCipher().encode(\"Test Message\") == \"44154344 32154343112215\"\n True\n \"\"\"\n message = message.lower()\n message = message.replace(\"j\", \"i\")\n\n encoded_message = \"\"\n for letter_index in range(len(message)):\n if message[letter_index] != \" \":\n numbers = self.letter_to_numbers(message[letter_index])\n encoded_message = encoded_message + str(numbers[0]) + str(numbers[1])\n elif message[letter_index] == \" \":\n encoded_message = encoded_message + \" \"\n\n return encoded_message\n\n def decode(self, message: str) -> str:\n \"\"\"\n Return the decoded version of message according to the polybius cipher\n\n >>> PolybiusCipher().decode(\"44154344 32154343112215\") == \"test message\"\n True\n\n >>> PolybiusCipher().decode(\"4415434432154343112215\") == \"testmessage\"\n True\n \"\"\"\n message = message.replace(\" \", \" \")\n decoded_message = \"\"\n for numbers_index in range(int(len(message) \/ 2)):\n if message[numbers_index * 2] != \" \":\n index1 = message[numbers_index * 2]\n index2 = message[numbers_index * 2 + 1]\n\n letter = self.numbers_to_letter(int(index1), int(index2))\n decoded_message = decoded_message + letter\n elif message[numbers_index * 2] == \" \":\n decoded_message = decoded_message + \" \"\n\n return decoded_message\n"} +{"Prompt":"generatetable'marvin' doctest: NORMALIZEWHITESPACE 'ABCDEFGHIJKLM', 'UVWXYZNOPQRST', 'ABCDEFGHIJKLM', 'NOPQRSTUVWXYZ', 'ABCDEFGHIJKLM', 'STUVWXYZNOPQR', 'ABCDEFGHIJKLM', 'QRSTUVWXYZNOP', 'ABCDEFGHIJKLM', 'WXYZNOPQRSTUV', 'ABCDEFGHIJKLM', 'UVWXYZNOPQRST' encrypt'marvin', 'jessica' 'QRACRWU' decrypt'marvin', 'QRACRWU' 'JESSICA' getpositiongeneratetable'marvin'0, 'M' 0, 12 char is either in the 0th row or the 1st row getopponentgeneratetable'marvin'0, 'M' 'T' Demo: Enter key: marvin Enter text to encrypt: jessica Encrypted: QRACRWU Decrypted with key: JESSICA","Completions":"alphabet = {\n \"A\": (\"ABCDEFGHIJKLM\", \"NOPQRSTUVWXYZ\"),\n \"B\": (\"ABCDEFGHIJKLM\", \"NOPQRSTUVWXYZ\"),\n \"C\": (\"ABCDEFGHIJKLM\", \"ZNOPQRSTUVWXY\"),\n \"D\": (\"ABCDEFGHIJKLM\", \"ZNOPQRSTUVWXY\"),\n \"E\": (\"ABCDEFGHIJKLM\", \"YZNOPQRSTUVWX\"),\n \"F\": (\"ABCDEFGHIJKLM\", \"YZNOPQRSTUVWX\"),\n \"G\": (\"ABCDEFGHIJKLM\", \"XYZNOPQRSTUVW\"),\n \"H\": (\"ABCDEFGHIJKLM\", \"XYZNOPQRSTUVW\"),\n \"I\": (\"ABCDEFGHIJKLM\", \"WXYZNOPQRSTUV\"),\n \"J\": (\"ABCDEFGHIJKLM\", \"WXYZNOPQRSTUV\"),\n \"K\": (\"ABCDEFGHIJKLM\", \"VWXYZNOPQRSTU\"),\n \"L\": (\"ABCDEFGHIJKLM\", \"VWXYZNOPQRSTU\"),\n \"M\": (\"ABCDEFGHIJKLM\", \"UVWXYZNOPQRST\"),\n \"N\": (\"ABCDEFGHIJKLM\", \"UVWXYZNOPQRST\"),\n \"O\": (\"ABCDEFGHIJKLM\", \"TUVWXYZNOPQRS\"),\n \"P\": (\"ABCDEFGHIJKLM\", \"TUVWXYZNOPQRS\"),\n \"Q\": (\"ABCDEFGHIJKLM\", \"STUVWXYZNOPQR\"),\n \"R\": (\"ABCDEFGHIJKLM\", \"STUVWXYZNOPQR\"),\n \"S\": (\"ABCDEFGHIJKLM\", \"RSTUVWXYZNOPQ\"),\n \"T\": (\"ABCDEFGHIJKLM\", \"RSTUVWXYZNOPQ\"),\n \"U\": (\"ABCDEFGHIJKLM\", \"QRSTUVWXYZNOP\"),\n \"V\": (\"ABCDEFGHIJKLM\", \"QRSTUVWXYZNOP\"),\n \"W\": (\"ABCDEFGHIJKLM\", \"PQRSTUVWXYZNO\"),\n \"X\": (\"ABCDEFGHIJKLM\", \"PQRSTUVWXYZNO\"),\n \"Y\": (\"ABCDEFGHIJKLM\", \"OPQRSTUVWXYZN\"),\n \"Z\": (\"ABCDEFGHIJKLM\", \"OPQRSTUVWXYZN\"),\n}\n\n\ndef generate_table(key: str) -> list[tuple[str, str]]:\n \"\"\"\n >>> generate_table('marvin') # doctest: +NORMALIZE_WHITESPACE\n [('ABCDEFGHIJKLM', 'UVWXYZNOPQRST'), ('ABCDEFGHIJKLM', 'NOPQRSTUVWXYZ'),\n ('ABCDEFGHIJKLM', 'STUVWXYZNOPQR'), ('ABCDEFGHIJKLM', 'QRSTUVWXYZNOP'),\n ('ABCDEFGHIJKLM', 'WXYZNOPQRSTUV'), ('ABCDEFGHIJKLM', 'UVWXYZNOPQRST')]\n \"\"\"\n return [alphabet[char] for char in key.upper()]\n\n\ndef encrypt(key: str, words: str) -> str:\n \"\"\"\n >>> encrypt('marvin', 'jessica')\n 'QRACRWU'\n \"\"\"\n cipher = \"\"\n count = 0\n table = generate_table(key)\n for char in words.upper():\n cipher += get_opponent(table[count], char)\n count = (count + 1) % len(table)\n return cipher\n\n\ndef decrypt(key: str, words: str) -> str:\n \"\"\"\n >>> decrypt('marvin', 'QRACRWU')\n 'JESSICA'\n \"\"\"\n return encrypt(key, words)\n\n\ndef get_position(table: tuple[str, str], char: str) -> tuple[int, int]:\n \"\"\"\n >>> get_position(generate_table('marvin')[0], 'M')\n (0, 12)\n \"\"\"\n # `char` is either in the 0th row or the 1st row\n row = 0 if char in table[0] else 1\n col = table[row].index(char)\n return row, col\n\n\ndef get_opponent(table: tuple[str, str], char: str) -> str:\n \"\"\"\n >>> get_opponent(generate_table('marvin')[0], 'M')\n 'T'\n \"\"\"\n row, col = get_position(table, char.upper())\n if row == 1:\n return table[0][col]\n else:\n return table[1][col] if row == 0 else char\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod() # Fist ensure that all our tests are passing...\n \"\"\"\n Demo:\n\n Enter key: marvin\n Enter text to encrypt: jessica\n Encrypted: QRACRWU\n Decrypted with key: JESSICA\n \"\"\"\n key = input(\"Enter key: \").strip()\n text = input(\"Enter text to encrypt: \").strip()\n cipher_text = encrypt(key, text)\n\n print(f\"Encrypted: {cipher_text}\")\n print(f\"Decrypted with key: {decrypt(key, cipher_text)}\")\n"} +{"Prompt":"Primality Testing with the RabinMiller Algorithm","Completions":"# Primality Testing with the Rabin-Miller Algorithm\n\nimport random\n\n\ndef rabin_miller(num: int) -> bool:\n s = num - 1\n t = 0\n\n while s % 2 == 0:\n s = s \/\/ 2\n t += 1\n\n for _ in range(5):\n a = random.randrange(2, num - 1)\n v = pow(a, s, num)\n if v != 1:\n i = 0\n while v != (num - 1):\n if i == t - 1:\n return False\n else:\n i = i + 1\n v = (v**2) % num\n return True\n\n\ndef is_prime_low_num(num: int) -> bool:\n if num < 2:\n return False\n\n low_primes = [\n 2,\n 3,\n 5,\n 7,\n 11,\n 13,\n 17,\n 19,\n 23,\n 29,\n 31,\n 37,\n 41,\n 43,\n 47,\n 53,\n 59,\n 61,\n 67,\n 71,\n 73,\n 79,\n 83,\n 89,\n 97,\n 101,\n 103,\n 107,\n 109,\n 113,\n 127,\n 131,\n 137,\n 139,\n 149,\n 151,\n 157,\n 163,\n 167,\n 173,\n 179,\n 181,\n 191,\n 193,\n 197,\n 199,\n 211,\n 223,\n 227,\n 229,\n 233,\n 239,\n 241,\n 251,\n 257,\n 263,\n 269,\n 271,\n 277,\n 281,\n 283,\n 293,\n 307,\n 311,\n 313,\n 317,\n 331,\n 337,\n 347,\n 349,\n 353,\n 359,\n 367,\n 373,\n 379,\n 383,\n 389,\n 397,\n 401,\n 409,\n 419,\n 421,\n 431,\n 433,\n 439,\n 443,\n 449,\n 457,\n 461,\n 463,\n 467,\n 479,\n 487,\n 491,\n 499,\n 503,\n 509,\n 521,\n 523,\n 541,\n 547,\n 557,\n 563,\n 569,\n 571,\n 577,\n 587,\n 593,\n 599,\n 601,\n 607,\n 613,\n 617,\n 619,\n 631,\n 641,\n 643,\n 647,\n 653,\n 659,\n 661,\n 673,\n 677,\n 683,\n 691,\n 701,\n 709,\n 719,\n 727,\n 733,\n 739,\n 743,\n 751,\n 757,\n 761,\n 769,\n 773,\n 787,\n 797,\n 809,\n 811,\n 821,\n 823,\n 827,\n 829,\n 839,\n 853,\n 857,\n 859,\n 863,\n 877,\n 881,\n 883,\n 887,\n 907,\n 911,\n 919,\n 929,\n 937,\n 941,\n 947,\n 953,\n 967,\n 971,\n 977,\n 983,\n 991,\n 997,\n ]\n\n if num in low_primes:\n return True\n\n for prime in low_primes:\n if (num % prime) == 0:\n return False\n\n return rabin_miller(num)\n\n\ndef generate_large_prime(keysize: int = 1024) -> int:\n while True:\n num = random.randrange(2 ** (keysize - 1), 2 ** (keysize))\n if is_prime_low_num(num):\n return num\n\n\nif __name__ == \"__main__\":\n num = generate_large_prime()\n print((\"Prime number:\", num))\n print((\"is_prime_low_num:\", is_prime_low_num(num)))\n"} +{"Prompt":"https:en.wikipedia.orgwikiRailfencecipher def encryptinputstring: str, key: int str: tempgrid: listliststr for in rangekey lowest key 1 if key 0: raise ValueErrorHeight of grid can't be 0 or negative if key 1 or leninputstring key: return inputstring for position, character in enumerateinputstring: num position lowest 2 puts it in bounds num minnum, lowest 2 num creates zigzag pattern tempgridnum.appendcharacter grid .joinrow for row in tempgrid outputstring .joingrid return outputstring def decryptinputstring: str, key: int str: grid lowest key 1 if key 0: raise ValueErrorHeight of grid can't be 0 or negative if key 1: return inputstring tempgrid: listliststr for in rangekey generates template for position in rangeleninputstring: num position lowest 2 puts it in bounds num minnum, lowest 2 num creates zigzag pattern tempgridnum.append counter 0 for row in tempgrid: fills in the characters splice inputstringcounter : counter lenrow grid.appendlistsplice counter lenrow outputstring reads as zigzag for position in rangeleninputstring: num position lowest 2 puts it in bounds num minnum, lowest 2 num creates zigzag pattern outputstring gridnum0 gridnum.pop0 return outputstring def bruteforceinputstring: str dictint, str: results for keyguess in range1, leninputstring: tries every key resultskeyguess decryptinputstring, keyguess return results if name main: import doctest doctest.testmod","Completions":"def encrypt(input_string: str, key: int) -> str:\n \"\"\"\n Shuffles the character of a string by placing each of them\n in a grid (the height is dependent on the key) in a zigzag\n formation and reading it left to right.\n\n >>> encrypt(\"Hello World\", 4)\n 'HWe olordll'\n\n >>> encrypt(\"This is a message\", 0)\n Traceback (most recent call last):\n ...\n ValueError: Height of grid can't be 0 or negative\n\n >>> encrypt(b\"This is a byte string\", 5)\n Traceback (most recent call last):\n ...\n TypeError: sequence item 0: expected str instance, int found\n \"\"\"\n temp_grid: list[list[str]] = [[] for _ in range(key)]\n lowest = key - 1\n\n if key <= 0:\n raise ValueError(\"Height of grid can't be 0 or negative\")\n if key == 1 or len(input_string) <= key:\n return input_string\n\n for position, character in enumerate(input_string):\n num = position % (lowest * 2) # puts it in bounds\n num = min(num, lowest * 2 - num) # creates zigzag pattern\n temp_grid[num].append(character)\n grid = [\"\".join(row) for row in temp_grid]\n output_string = \"\".join(grid)\n\n return output_string\n\n\ndef decrypt(input_string: str, key: int) -> str:\n \"\"\"\n Generates a template based on the key and fills it in with\n the characters of the input string and then reading it in\n a zigzag formation.\n\n >>> decrypt(\"HWe olordll\", 4)\n 'Hello World'\n\n >>> decrypt(\"This is a message\", -10)\n Traceback (most recent call last):\n ...\n ValueError: Height of grid can't be 0 or negative\n\n >>> decrypt(\"My key is very big\", 100)\n 'My key is very big'\n \"\"\"\n grid = []\n lowest = key - 1\n\n if key <= 0:\n raise ValueError(\"Height of grid can't be 0 or negative\")\n if key == 1:\n return input_string\n\n temp_grid: list[list[str]] = [[] for _ in range(key)] # generates template\n for position in range(len(input_string)):\n num = position % (lowest * 2) # puts it in bounds\n num = min(num, lowest * 2 - num) # creates zigzag pattern\n temp_grid[num].append(\"*\")\n\n counter = 0\n for row in temp_grid: # fills in the characters\n splice = input_string[counter : counter + len(row)]\n grid.append(list(splice))\n counter += len(row)\n\n output_string = \"\" # reads as zigzag\n for position in range(len(input_string)):\n num = position % (lowest * 2) # puts it in bounds\n num = min(num, lowest * 2 - num) # creates zigzag pattern\n output_string += grid[num][0]\n grid[num].pop(0)\n return output_string\n\n\ndef bruteforce(input_string: str) -> dict[int, str]:\n \"\"\"Uses decrypt function by guessing every key\n\n >>> bruteforce(\"HWe olordll\")[4]\n 'Hello World'\n \"\"\"\n results = {}\n for key_guess in range(1, len(input_string)): # tries every key\n results[key_guess] = decrypt(input_string, key_guess)\n return results\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"https:en.wikipedia.orgwikiROT13 msg My secret bank account number is 17352946 so don't tell anyone!! s dencryptmsg s Zl frperg onax nppbhag ahzore vf 17352946 fb qba'g gryy nalbar!! dencrypts msg True","Completions":"def dencrypt(s: str, n: int = 13) -> str:\n \"\"\"\n https:\/\/en.wikipedia.org\/wiki\/ROT13\n\n >>> msg = \"My secret bank account number is 173-52946 so don't tell anyone!!\"\n >>> s = dencrypt(msg)\n >>> s\n \"Zl frperg onax nppbhag ahzore vf 173-52946 fb qba'g gryy nalbar!!\"\n >>> dencrypt(s) == msg\n True\n \"\"\"\n out = \"\"\n for c in s:\n if \"A\" <= c <= \"Z\":\n out += chr(ord(\"A\") + (ord(c) - ord(\"A\") + n) % 26)\n elif \"a\" <= c <= \"z\":\n out += chr(ord(\"a\") + (ord(c) - ord(\"a\") + n) % 26)\n else:\n out += c\n return out\n\n\ndef main() -> None:\n s0 = input(\"Enter message: \")\n\n s1 = dencrypt(s0, 13)\n print(\"Encryption:\", s1)\n\n s2 = dencrypt(s1, 13)\n print(\"Decryption: \", s2)\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n main()\n"} +{"Prompt":"An RSA prime factor algorithm. The program can efficiently factor RSA prime number given the private key d and public key e. Source: on page 3 of https:crypto.stanford.edudabopapersRSAsurvey.pdf More readable source: https:www.dimgt.com.aursafactorizen.html large number can take minutes to factor, therefore are not included in doctest. This function returns the factors of N, where pqN Return: p, q We call N the RSA modulus, e the encryption exponent, and d the decryption exponent. The pair N, e is the public key. As its name suggests, it is public and is used to encrypt messages. The pair N, d is the secret key or private key and is known only to the recipient of encrypted messages. rsafactor3, 16971, 25777 149, 173 rsafactor7331, 11, 27233 113, 241 rsafactor4021, 13, 17711 89, 199","Completions":"from __future__ import annotations\n\nimport math\nimport random\n\n\ndef rsafactor(d: int, e: int, n: int) -> list[int]:\n \"\"\"\n This function returns the factors of N, where p*q=N\n Return: [p, q]\n\n We call N the RSA modulus, e the encryption exponent, and d the decryption exponent.\n The pair (N, e) is the public key. As its name suggests, it is public and is used to\n encrypt messages.\n The pair (N, d) is the secret key or private key and is known only to the recipient\n of encrypted messages.\n\n >>> rsafactor(3, 16971, 25777)\n [149, 173]\n >>> rsafactor(7331, 11, 27233)\n [113, 241]\n >>> rsafactor(4021, 13, 17711)\n [89, 199]\n \"\"\"\n k = d * e - 1\n p = 0\n q = 0\n while p == 0:\n g = random.randint(2, n - 1)\n t = k\n while True:\n if t % 2 == 0:\n t = t \/\/ 2\n x = (g**t) % n\n y = math.gcd(x - 1, n)\n if x > 1 and y > 1:\n p = y\n q = n \/\/ y\n break # find the correct factors\n else:\n break # t is not divisible by 2, break and choose another g\n return sorted([p, q])\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"random.seed0 for repeatability publickey, privatekey generatekey8 publickey 26569, 239 privatekey 26569, 2855 Generate e that is relatively prime to p 1 q 1 Calculate d that is mod inverse of e","Completions":"import os\nimport random\nimport sys\n\nfrom maths.greatest_common_divisor import gcd_by_iterative\n\nfrom . import cryptomath_module, rabin_miller\n\n\ndef main() -> None:\n print(\"Making key files...\")\n make_key_files(\"rsa\", 1024)\n print(\"Key files generation successful.\")\n\n\ndef generate_key(key_size: int) -> tuple[tuple[int, int], tuple[int, int]]:\n \"\"\"\n >>> random.seed(0) # for repeatability\n >>> public_key, private_key = generate_key(8)\n >>> public_key\n (26569, 239)\n >>> private_key\n (26569, 2855)\n \"\"\"\n p = rabin_miller.generate_large_prime(key_size)\n q = rabin_miller.generate_large_prime(key_size)\n n = p * q\n\n # Generate e that is relatively prime to (p - 1) * (q - 1)\n while True:\n e = random.randrange(2 ** (key_size - 1), 2 ** (key_size))\n if gcd_by_iterative(e, (p - 1) * (q - 1)) == 1:\n break\n\n # Calculate d that is mod inverse of e\n d = cryptomath_module.find_mod_inverse(e, (p - 1) * (q - 1))\n\n public_key = (n, e)\n private_key = (n, d)\n return (public_key, private_key)\n\n\ndef make_key_files(name: str, key_size: int) -> None:\n if os.path.exists(f\"{name}_pubkey.txt\") or os.path.exists(f\"{name}_privkey.txt\"):\n print(\"\\nWARNING:\")\n print(\n f'\"{name}_pubkey.txt\" or \"{name}_privkey.txt\" already exists. \\n'\n \"Use a different name or delete these files and re-run this program.\"\n )\n sys.exit()\n\n public_key, private_key = generate_key(key_size)\n print(f\"\\nWriting public key to file {name}_pubkey.txt...\")\n with open(f\"{name}_pubkey.txt\", \"w\") as out_file:\n out_file.write(f\"{key_size},{public_key[0]},{public_key[1]}\")\n\n print(f\"Writing private key to file {name}_privkey.txt...\")\n with open(f\"{name}_privkey.txt\", \"w\") as out_file:\n out_file.write(f\"{key_size},{private_key[0]},{private_key[1]}\")\n\n\nif __name__ == \"__main__\":\n main()\n"} +{"Prompt":"https:en.wikipedia.orgwikiRunningkeycipher Encrypts the plaintext using the Running Key Cipher. :param key: The running key long piece of text. :param plaintext: The plaintext to be encrypted. :return: The ciphertext. Decrypts the ciphertext using the Running Key Cipher. :param key: The running key long piece of text. :param ciphertext: The ciphertext to be decrypted. :return: The plaintext. key How does the duck know that? said Victor ciphertext runningkeyencryptkey, DEFEND THIS runningkeydecryptkey, ciphertext DEFENDTHIS True","Completions":"def running_key_encrypt(key: str, plaintext: str) -> str:\n \"\"\"\n Encrypts the plaintext using the Running Key Cipher.\n\n :param key: The running key (long piece of text).\n :param plaintext: The plaintext to be encrypted.\n :return: The ciphertext.\n \"\"\"\n plaintext = plaintext.replace(\" \", \"\").upper()\n key = key.replace(\" \", \"\").upper()\n key_length = len(key)\n ciphertext = []\n ord_a = ord(\"A\")\n\n for i, char in enumerate(plaintext):\n p = ord(char) - ord_a\n k = ord(key[i % key_length]) - ord_a\n c = (p + k) % 26\n ciphertext.append(chr(c + ord_a))\n\n return \"\".join(ciphertext)\n\n\ndef running_key_decrypt(key: str, ciphertext: str) -> str:\n \"\"\"\n Decrypts the ciphertext using the Running Key Cipher.\n\n :param key: The running key (long piece of text).\n :param ciphertext: The ciphertext to be decrypted.\n :return: The plaintext.\n \"\"\"\n ciphertext = ciphertext.replace(\" \", \"\").upper()\n key = key.replace(\" \", \"\").upper()\n key_length = len(key)\n plaintext = []\n ord_a = ord(\"A\")\n\n for i, char in enumerate(ciphertext):\n c = ord(char) - ord_a\n k = ord(key[i % key_length]) - ord_a\n p = (c - k) % 26\n plaintext.append(chr(p + ord_a))\n\n return \"\".join(plaintext)\n\n\ndef test_running_key_encrypt() -> None:\n \"\"\"\n >>> key = \"How does the duck know that? said Victor\"\n >>> ciphertext = running_key_encrypt(key, \"DEFEND THIS\")\n >>> running_key_decrypt(key, ciphertext) == \"DEFENDTHIS\"\n True\n \"\"\"\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n test_running_key_encrypt()\n\n plaintext = input(\"Enter the plaintext: \").upper()\n print(f\"\\n{plaintext = }\")\n\n key = \"How does the duck know that? said Victor\"\n encrypted_text = running_key_encrypt(key, plaintext)\n print(f\"{encrypted_text = }\")\n\n decrypted_text = running_key_decrypt(key, encrypted_text)\n print(f\"{decrypted_text = }\")\n"} +{"Prompt":"This algorithm uses the Caesar Cipher algorithm but removes the option to use brute force to decrypt the message. The passcode is a random password from the selection buffer of 1. uppercase letters of the English alphabet 2. lowercase letters of the English alphabet 3. digits from 0 to 9 Using unique characters from the passcode, the normal list of characters, that can be allowed in the plaintext, is pivoted and shuffled. Refer to docstring of makekeylist to learn more about the shuffling. Then, using the passcode, a number is calculated which is used to encrypt the plaintext message with the normal shift cipher method, only in this case, the reference, to look back at while decrypting, is shuffled. Each cipher object can possess an optional argument as passcode, without which a new passcode is generated for that object automatically. cip1 ShuffledShiftCipher'd4usr9TWxw9wMD' cip2 ShuffledShiftCipher Initializes a cipher object with a passcode as it's entity Note: No new passcode is generated if user provides a passcode while creating the object :return: passcode of the cipher object Mutates the list by changing the sign of each alternate element :param iterlist: takes a list iterable :return: the mutated list Creates a random password from the selection buffer of 1. uppercase letters of the English alphabet 2. lowercase letters of the English alphabet 3. digits from 0 to 9 :rtype: list :return: a password of a random length between 10 to 20 Shuffles the ordered character choices by pivoting at breakpoints Breakpoints are the set of characters in the passcode eg: if, ABCDEFGHIJKLMNOPQRSTUVWXYZ are the possible characters and CAMERA is the passcode then, breakpoints A,C,E,M,R sorted set of characters from passcode shuffled parts: A,CB,ED,MLKJIHGF,RQPON,ZYXWVUTS shuffled keylist : ACBEDMLKJIHGFRQPONZYXWVUTS Shuffling only 26 letters of the english alphabet can generate 26! combinations for the shuffled list. In the program we consider, a set of 97 characters including letters, digits, punctuation and whitespaces, thereby creating a possibility of 97! combinations which is a 152 digit number in itself, thus diminishing the possibility of a brute force approach. Moreover, shift keys even introduce a multiple of 26 for a brute force approach for each of the already 97! combinations. keylistoptions contain nearly all printable except few elements from string.whitespace creates points known as breakpoints to break the keylistoptions at those points and pivot each substring algorithm for creating a new shuffled list, keysl, out of keylistoptions checking breakpoints at which to pivot temporary sublist and add it into keysl returning a shuffled keysl to prevent brute force guessing of shift key sum of the mutated list of ascii values of all characters where the mutated list is the one returned by negpos Performs shifting of the encodedmessage w.r.t. the shuffled keylist to create the decodedmessage ssc ShuffledShiftCipher'4PYIXyqeQZr44' ssc.decryptd1z6'5z'5z:z''zp:5:z'. 'Hello, this is a modified Caesar cipher' decoding shift like Caesar cipher algorithm implementing negative shift or reverse shift or left shift Performs shifting of the plaintext w.r.t. the shuffled keylist to create the encodedmessage ssc ShuffledShiftCipher'4PYIXyqeQZr44' ssc.encrypt'Hello, this is a modified Caesar cipher' d1z6'5z'5z:z''zp:5:z'. encoding shift like Caesar cipher algorithm implementing positive shift or forward shift or right shift testendtoend 'Hello, this is a modified Caesar cipher'","Completions":"from __future__ import annotations\n\nimport random\nimport string\n\n\nclass ShuffledShiftCipher:\n \"\"\"\n This algorithm uses the Caesar Cipher algorithm but removes the option to\n use brute force to decrypt the message.\n\n The passcode is a random password from the selection buffer of\n 1. uppercase letters of the English alphabet\n 2. lowercase letters of the English alphabet\n 3. digits from 0 to 9\n\n Using unique characters from the passcode, the normal list of characters,\n that can be allowed in the plaintext, is pivoted and shuffled. Refer to docstring\n of __make_key_list() to learn more about the shuffling.\n\n Then, using the passcode, a number is calculated which is used to encrypt the\n plaintext message with the normal shift cipher method, only in this case, the\n reference, to look back at while decrypting, is shuffled.\n\n Each cipher object can possess an optional argument as passcode, without which a\n new passcode is generated for that object automatically.\n cip1 = ShuffledShiftCipher('d4usr9TWxw9wMD')\n cip2 = ShuffledShiftCipher()\n \"\"\"\n\n def __init__(self, passcode: str | None = None) -> None:\n \"\"\"\n Initializes a cipher object with a passcode as it's entity\n Note: No new passcode is generated if user provides a passcode\n while creating the object\n \"\"\"\n self.__passcode = passcode or self.__passcode_creator()\n self.__key_list = self.__make_key_list()\n self.__shift_key = self.__make_shift_key()\n\n def __str__(self) -> str:\n \"\"\"\n :return: passcode of the cipher object\n \"\"\"\n return \"\".join(self.__passcode)\n\n def __neg_pos(self, iterlist: list[int]) -> list[int]:\n \"\"\"\n Mutates the list by changing the sign of each alternate element\n\n :param iterlist: takes a list iterable\n :return: the mutated list\n\n \"\"\"\n for i in range(1, len(iterlist), 2):\n iterlist[i] *= -1\n return iterlist\n\n def __passcode_creator(self) -> list[str]:\n \"\"\"\n Creates a random password from the selection buffer of\n 1. uppercase letters of the English alphabet\n 2. lowercase letters of the English alphabet\n 3. digits from 0 to 9\n\n :rtype: list\n :return: a password of a random length between 10 to 20\n \"\"\"\n choices = string.ascii_letters + string.digits\n password = [random.choice(choices) for _ in range(random.randint(10, 20))]\n return password\n\n def __make_key_list(self) -> list[str]:\n \"\"\"\n Shuffles the ordered character choices by pivoting at breakpoints\n Breakpoints are the set of characters in the passcode\n\n eg:\n if, ABCDEFGHIJKLMNOPQRSTUVWXYZ are the possible characters\n and CAMERA is the passcode\n then, breakpoints = [A,C,E,M,R] # sorted set of characters from passcode\n shuffled parts: [A,CB,ED,MLKJIHGF,RQPON,ZYXWVUTS]\n shuffled __key_list : ACBEDMLKJIHGFRQPONZYXWVUTS\n\n Shuffling only 26 letters of the english alphabet can generate 26!\n combinations for the shuffled list. In the program we consider, a set of\n 97 characters (including letters, digits, punctuation and whitespaces),\n thereby creating a possibility of 97! combinations (which is a 152 digit number\n in itself), thus diminishing the possibility of a brute force approach.\n Moreover, shift keys even introduce a multiple of 26 for a brute force approach\n for each of the already 97! combinations.\n \"\"\"\n # key_list_options contain nearly all printable except few elements from\n # string.whitespace\n key_list_options = (\n string.ascii_letters + string.digits + string.punctuation + \" \\t\\n\"\n )\n\n keys_l = []\n\n # creates points known as breakpoints to break the key_list_options at those\n # points and pivot each substring\n breakpoints = sorted(set(self.__passcode))\n temp_list: list[str] = []\n\n # algorithm for creating a new shuffled list, keys_l, out of key_list_options\n for i in key_list_options:\n temp_list.extend(i)\n\n # checking breakpoints at which to pivot temporary sublist and add it into\n # keys_l\n if i in breakpoints or i == key_list_options[-1]:\n keys_l.extend(temp_list[::-1])\n temp_list.clear()\n\n # returning a shuffled keys_l to prevent brute force guessing of shift key\n return keys_l\n\n def __make_shift_key(self) -> int:\n \"\"\"\n sum() of the mutated list of ascii values of all characters where the\n mutated list is the one returned by __neg_pos()\n \"\"\"\n num = sum(self.__neg_pos([ord(x) for x in self.__passcode]))\n return num if num > 0 else len(self.__passcode)\n\n def decrypt(self, encoded_message: str) -> str:\n \"\"\"\n Performs shifting of the encoded_message w.r.t. the shuffled __key_list\n to create the decoded_message\n\n >>> ssc = ShuffledShiftCipher('4PYIXyqeQZr44')\n >>> ssc.decrypt(\"d>**-1z6&'5z'5z:z+-='$'>=zp:>5:#z<'.&>#\")\n 'Hello, this is a modified Caesar cipher'\n\n \"\"\"\n decoded_message = \"\"\n\n # decoding shift like Caesar cipher algorithm implementing negative shift or\n # reverse shift or left shift\n for i in encoded_message:\n position = self.__key_list.index(i)\n decoded_message += self.__key_list[\n (position - self.__shift_key) % -len(self.__key_list)\n ]\n\n return decoded_message\n\n def encrypt(self, plaintext: str) -> str:\n \"\"\"\n Performs shifting of the plaintext w.r.t. the shuffled __key_list\n to create the encoded_message\n\n >>> ssc = ShuffledShiftCipher('4PYIXyqeQZr44')\n >>> ssc.encrypt('Hello, this is a modified Caesar cipher')\n \"d>**-1z6&'5z'5z:z+-='$'>=zp:>5:#z<'.&>#\"\n\n \"\"\"\n encoded_message = \"\"\n\n # encoding shift like Caesar cipher algorithm implementing positive shift or\n # forward shift or right shift\n for i in plaintext:\n position = self.__key_list.index(i)\n encoded_message += self.__key_list[\n (position + self.__shift_key) % len(self.__key_list)\n ]\n\n return encoded_message\n\n\ndef test_end_to_end(msg: str = \"Hello, this is a modified Caesar cipher\") -> str:\n \"\"\"\n >>> test_end_to_end()\n 'Hello, this is a modified Caesar cipher'\n \"\"\"\n cip1 = ShuffledShiftCipher()\n return cip1.decrypt(cip1.encrypt(msg))\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Removes duplicate alphabetic characters in a keyword letter is ignored after its first appearance. :param key: Keyword to use :return: String with duplicates removed removeduplicates'Hello World!!' 'Helo Wrd' Returns a cipher map given a keyword. :param key: keyword to use :return: dictionary cipher map Create a list of the letters in the alphabet Remove duplicate characters from key First fill cipher with key characters Then map remaining characters in alphabet to the alphabet from the beginning Ensure we are not mapping letters to letters previously mapped Enciphers a message given a cipher map. :param message: Message to encipher :param ciphermap: Cipher map :return: enciphered string encipher'Hello World!!', createciphermap'Goodbye!!' 'CYJJM VMQJB!!' Deciphers a message given a cipher map :param message: Message to decipher :param ciphermap: Dictionary mapping to use :return: Deciphered string ciphermap createciphermap'Goodbye!!' decipherencipher'Hello World!!', ciphermap, ciphermap 'HELLO WORLD!!' Reverse our cipher mappings Handles IO :return: void","Completions":"def remove_duplicates(key: str) -> str:\n \"\"\"\n Removes duplicate alphabetic characters in a keyword (letter is ignored after its\n first appearance).\n :param key: Keyword to use\n :return: String with duplicates removed\n >>> remove_duplicates('Hello World!!')\n 'Helo Wrd'\n \"\"\"\n\n key_no_dups = \"\"\n for ch in key:\n if ch == \" \" or ch not in key_no_dups and ch.isalpha():\n key_no_dups += ch\n return key_no_dups\n\n\ndef create_cipher_map(key: str) -> dict[str, str]:\n \"\"\"\n Returns a cipher map given a keyword.\n :param key: keyword to use\n :return: dictionary cipher map\n \"\"\"\n # Create a list of the letters in the alphabet\n alphabet = [chr(i + 65) for i in range(26)]\n # Remove duplicate characters from key\n key = remove_duplicates(key.upper())\n offset = len(key)\n # First fill cipher with key characters\n cipher_alphabet = {alphabet[i]: char for i, char in enumerate(key)}\n # Then map remaining characters in alphabet to\n # the alphabet from the beginning\n for i in range(len(cipher_alphabet), 26):\n char = alphabet[i - offset]\n # Ensure we are not mapping letters to letters previously mapped\n while char in key:\n offset -= 1\n char = alphabet[i - offset]\n cipher_alphabet[alphabet[i]] = char\n return cipher_alphabet\n\n\ndef encipher(message: str, cipher_map: dict[str, str]) -> str:\n \"\"\"\n Enciphers a message given a cipher map.\n :param message: Message to encipher\n :param cipher_map: Cipher map\n :return: enciphered string\n >>> encipher('Hello World!!', create_cipher_map('Goodbye!!'))\n 'CYJJM VMQJB!!'\n \"\"\"\n return \"\".join(cipher_map.get(ch, ch) for ch in message.upper())\n\n\ndef decipher(message: str, cipher_map: dict[str, str]) -> str:\n \"\"\"\n Deciphers a message given a cipher map\n :param message: Message to decipher\n :param cipher_map: Dictionary mapping to use\n :return: Deciphered string\n >>> cipher_map = create_cipher_map('Goodbye!!')\n >>> decipher(encipher('Hello World!!', cipher_map), cipher_map)\n 'HELLO WORLD!!'\n \"\"\"\n # Reverse our cipher mappings\n rev_cipher_map = {v: k for k, v in cipher_map.items()}\n return \"\".join(rev_cipher_map.get(ch, ch) for ch in message.upper())\n\n\ndef main() -> None:\n \"\"\"\n Handles I\/O\n :return: void\n \"\"\"\n message = input(\"Enter message to encode or decode: \").strip()\n key = input(\"Enter keyword: \").strip()\n option = input(\"Encipher or decipher? E\/D:\").strip()[0].lower()\n try:\n func = {\"e\": encipher, \"d\": decipher}[option]\n except KeyError:\n raise KeyError(\"invalid input option\")\n cipher_map = create_cipher_map(key)\n print(func(message, cipher_map))\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n main()\n"} +{"Prompt":"encryptmessage'LFWOAYUISVKMNXPBDCRJTQEGHZ', 'Harshil Darji' 'Ilcrism Olcvs' decryptmessage'LFWOAYUISVKMNXPBDCRJTQEGHZ', 'Ilcrism Olcvs' 'Harshil Darji'","Completions":"import random\nimport sys\n\nLETTERS = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n\n\ndef main() -> None:\n message = input(\"Enter message: \")\n key = \"LFWOAYUISVKMNXPBDCRJTQEGHZ\"\n resp = input(\"Encrypt\/Decrypt [e\/d]: \")\n\n check_valid_key(key)\n\n if resp.lower().startswith(\"e\"):\n mode = \"encrypt\"\n translated = encrypt_message(key, message)\n elif resp.lower().startswith(\"d\"):\n mode = \"decrypt\"\n translated = decrypt_message(key, message)\n\n print(f\"\\n{mode.title()}ion: \\n{translated}\")\n\n\ndef check_valid_key(key: str) -> None:\n key_list = list(key)\n letters_list = list(LETTERS)\n key_list.sort()\n letters_list.sort()\n\n if key_list != letters_list:\n sys.exit(\"Error in the key or symbol set.\")\n\n\ndef encrypt_message(key: str, message: str) -> str:\n \"\"\"\n >>> encrypt_message('LFWOAYUISVKMNXPBDCRJTQEGHZ', 'Harshil Darji')\n 'Ilcrism Olcvs'\n \"\"\"\n return translate_message(key, message, \"encrypt\")\n\n\ndef decrypt_message(key: str, message: str) -> str:\n \"\"\"\n >>> decrypt_message('LFWOAYUISVKMNXPBDCRJTQEGHZ', 'Ilcrism Olcvs')\n 'Harshil Darji'\n \"\"\"\n return translate_message(key, message, \"decrypt\")\n\n\ndef translate_message(key: str, message: str, mode: str) -> str:\n translated = \"\"\n chars_a = LETTERS\n chars_b = key\n\n if mode == \"decrypt\":\n chars_a, chars_b = chars_b, chars_a\n\n for symbol in message:\n if symbol.upper() in chars_a:\n sym_index = chars_a.find(symbol.upper())\n if symbol.isupper():\n translated += chars_b[sym_index].upper()\n else:\n translated += chars_b[sym_index].lower()\n else:\n translated += symbol\n\n return translated\n\n\ndef get_random_key() -> str:\n key = list(LETTERS)\n random.shuffle(key)\n return \"\".join(key)\n\n\nif __name__ == \"__main__\":\n main()\n"} +{"Prompt":"In cryptography, the TRANSPOSITION cipher is a method of encryption where the positions of plaintext are shifted a certain numberdetermined by the key that follows a regular system that results in the permuted text, known as the encrypted text. The type of transposition cipher demonstrated under is the ROUTE cipher. Append pipe symbol vertical bar to identify spaces at the end. encryptmessage6, 'Harshil Darji' 'Hlia rDsahrij' decryptmessage6, 'Hlia rDsahrij' 'Harshil Darji'","Completions":"import math\n\n\"\"\"\nIn cryptography, the TRANSPOSITION cipher is a method of encryption where the\npositions of plaintext are shifted a certain number(determined by the key) that\nfollows a regular system that results in the permuted text, known as the encrypted\ntext. The type of transposition cipher demonstrated under is the ROUTE cipher.\n\"\"\"\n\n\ndef main() -> None:\n message = input(\"Enter message: \")\n key = int(input(f\"Enter key [2-{len(message) - 1}]: \"))\n mode = input(\"Encryption\/Decryption [e\/d]: \")\n\n if mode.lower().startswith(\"e\"):\n text = encrypt_message(key, message)\n elif mode.lower().startswith(\"d\"):\n text = decrypt_message(key, message)\n\n # Append pipe symbol (vertical bar) to identify spaces at the end.\n print(f\"Output:\\n{text + '|'}\")\n\n\ndef encrypt_message(key: int, message: str) -> str:\n \"\"\"\n >>> encrypt_message(6, 'Harshil Darji')\n 'Hlia rDsahrij'\n \"\"\"\n cipher_text = [\"\"] * key\n for col in range(key):\n pointer = col\n while pointer < len(message):\n cipher_text[col] += message[pointer]\n pointer += key\n return \"\".join(cipher_text)\n\n\ndef decrypt_message(key: int, message: str) -> str:\n \"\"\"\n >>> decrypt_message(6, 'Hlia rDsahrij')\n 'Harshil Darji'\n \"\"\"\n num_cols = math.ceil(len(message) \/ key)\n num_rows = key\n num_shaded_boxes = (num_cols * num_rows) - len(message)\n plain_text = [\"\"] * num_cols\n col = 0\n row = 0\n\n for symbol in message:\n plain_text[col] += symbol\n col += 1\n\n if (\n (col == num_cols)\n or (col == num_cols - 1)\n and (row >= num_rows - num_shaded_boxes)\n ):\n col = 0\n row += 1\n\n return \"\".join(plain_text)\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n main()\n"} +{"Prompt":"The trifid cipher uses a table to fractionate each plaintext letter into a trigram, mixes the constituents of the trigrams, and then applies the table in reverse to turn these mixed trigrams into ciphertext letters. https:en.wikipedia.orgwikiTrifidcipher fmt: off fmt: off Arrange the triagram value of each letter of 'messagepart' vertically and join them horizontally. encryptpart'ASK', TESTCHARACTERTONUMBER '132111112' Convert each letter of the input string into their respective trigram values, join them and split them into three equal groups of strings which are returned. decryptpart'ABCDE', TESTCHARACTERTONUMBER '11111', '21131', '21122' A helper function that generates the triagrams and assigns each letter of the alphabet to its corresponding triagram and stores this in a dictionary charactertonumber and numbertocharacter after confirming if the alphabet's length is 27. test prepare'I aM a BOy','abCdeFghijkLmnopqrStuVwxYZ' expected 'IAMABOY','ABCDEFGHIJKLMNOPQRSTUVWXYZ', ... TESTCHARACTERTONUMBER, TESTNUMBERTOCHARACTER test expected True Testing with incomplete alphabet prepare'I aM a BOy','abCdeFghijkLmnopqrStuVw' Traceback most recent call last: ... KeyError: 'Length of alphabet has to be 27.' Testing with extra long alphabets prepare'I aM a BOy','abCdeFghijkLmnopqrStuVwxyzzwwtyyujjgfd' Traceback most recent call last: ... KeyError: 'Length of alphabet has to be 27.' Testing with punctuations that are not in the given alphabet prepare'am i a boy?','abCdeFghijkLmnopqrStuVwxYZ' Traceback most recent call last: ... ValueError: Each message character has to be included in alphabet! Testing with numbers prepare500,'abCdeFghijkLmnopqrStuVwxYZ' Traceback most recent call last: ... AttributeError: 'int' object has no attribute 'replace' Validate message and alphabet, set to upper and remove spaces Check length and characters Generate dictionares encryptmessage Encrypts a message using the trifidcipher. Any punctuatuions that would be used should be added to the alphabet. PARAMETERS message: The message you want to encrypt. alphabet optional: The characters to be used for the cipher . period optional: The number of characters you want in a group whilst encrypting. encryptmessage'I am a boy' 'BCDGBQY' encryptmessage' ' '' encryptmessage' aide toi le c iel ta id era ', ... 'FELIXMARDSTBCGHJKNOPQUVWYZ',5 'FMJFVOISSUFTFPUFEQQC' decryptmessage Decrypts a trifidcipher encrypted message . PARAMETERS message: The message you want to decrypt . alphabet optional: The characters used for the cipher. period optional: The number of characters used in grouping when it was encrypted. decryptmessage'BCDGBQY' 'IAMABOY' Decrypting with your own alphabet and period decryptmessage'FMJFVOISSUFTFPUFEQQC','FELIXMARDSTBCGHJKNOPQUVWYZ',5 'AIDETOILECIELTAIDERA'","Completions":"from __future__ import annotations\n\n# fmt: off\nTEST_CHARACTER_TO_NUMBER = {\n \"A\": \"111\", \"B\": \"112\", \"C\": \"113\", \"D\": \"121\", \"E\": \"122\", \"F\": \"123\", \"G\": \"131\",\n \"H\": \"132\", \"I\": \"133\", \"J\": \"211\", \"K\": \"212\", \"L\": \"213\", \"M\": \"221\", \"N\": \"222\",\n \"O\": \"223\", \"P\": \"231\", \"Q\": \"232\", \"R\": \"233\", \"S\": \"311\", \"T\": \"312\", \"U\": \"313\",\n \"V\": \"321\", \"W\": \"322\", \"X\": \"323\", \"Y\": \"331\", \"Z\": \"332\", \"+\": \"333\",\n}\n# fmt: off\n\nTEST_NUMBER_TO_CHARACTER = {val: key for key, val in TEST_CHARACTER_TO_NUMBER.items()}\n\n\ndef __encrypt_part(message_part: str, character_to_number: dict[str, str]) -> str:\n \"\"\"\n Arrange the triagram value of each letter of 'message_part' vertically and join\n them horizontally.\n\n >>> __encrypt_part('ASK', TEST_CHARACTER_TO_NUMBER)\n '132111112'\n \"\"\"\n one, two, three = \"\", \"\", \"\"\n for each in (character_to_number[character] for character in message_part):\n one += each[0]\n two += each[1]\n three += each[2]\n\n return one + two + three\n\n\ndef __decrypt_part(\n message_part: str, character_to_number: dict[str, str]\n) -> tuple[str, str, str]:\n \"\"\"\n Convert each letter of the input string into their respective trigram values, join\n them and split them into three equal groups of strings which are returned.\n\n >>> __decrypt_part('ABCDE', TEST_CHARACTER_TO_NUMBER)\n ('11111', '21131', '21122')\n \"\"\"\n this_part = \"\".join(character_to_number[character] for character in message_part)\n result = []\n tmp = \"\"\n for digit in this_part:\n tmp += digit\n if len(tmp) == len(message_part):\n result.append(tmp)\n tmp = \"\"\n\n return result[0], result[1], result[2]\n\n\ndef __prepare(\n message: str, alphabet: str\n) -> tuple[str, str, dict[str, str], dict[str, str]]:\n \"\"\"\n A helper function that generates the triagrams and assigns each letter of the\n alphabet to its corresponding triagram and stores this in a dictionary\n (\"character_to_number\" and \"number_to_character\") after confirming if the\n alphabet's length is 27.\n\n >>> test = __prepare('I aM a BOy','abCdeFghijkLmnopqrStuVwxYZ+')\n >>> expected = ('IAMABOY','ABCDEFGHIJKLMNOPQRSTUVWXYZ+',\n ... TEST_CHARACTER_TO_NUMBER, TEST_NUMBER_TO_CHARACTER)\n >>> test == expected\n True\n\n Testing with incomplete alphabet\n >>> __prepare('I aM a BOy','abCdeFghijkLmnopqrStuVw')\n Traceback (most recent call last):\n ...\n KeyError: 'Length of alphabet has to be 27.'\n\n Testing with extra long alphabets\n >>> __prepare('I aM a BOy','abCdeFghijkLmnopqrStuVwxyzzwwtyyujjgfd')\n Traceback (most recent call last):\n ...\n KeyError: 'Length of alphabet has to be 27.'\n\n Testing with punctuations that are not in the given alphabet\n >>> __prepare('am i a boy?','abCdeFghijkLmnopqrStuVwxYZ+')\n Traceback (most recent call last):\n ...\n ValueError: Each message character has to be included in alphabet!\n\n Testing with numbers\n >>> __prepare(500,'abCdeFghijkLmnopqrStuVwxYZ+')\n Traceback (most recent call last):\n ...\n AttributeError: 'int' object has no attribute 'replace'\n \"\"\"\n # Validate message and alphabet, set to upper and remove spaces\n alphabet = alphabet.replace(\" \", \"\").upper()\n message = message.replace(\" \", \"\").upper()\n\n # Check length and characters\n if len(alphabet) != 27:\n raise KeyError(\"Length of alphabet has to be 27.\")\n if any(char not in alphabet for char in message):\n raise ValueError(\"Each message character has to be included in alphabet!\")\n\n # Generate dictionares\n character_to_number = dict(zip(alphabet, TEST_CHARACTER_TO_NUMBER.values()))\n number_to_character = {\n number: letter for letter, number in character_to_number.items()\n }\n\n return message, alphabet, character_to_number, number_to_character\n\n\ndef encrypt_message(\n message: str, alphabet: str = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ.\", period: int = 5\n) -> str:\n \"\"\"\n encrypt_message\n ===============\n\n Encrypts a message using the trifid_cipher. Any punctuatuions that\n would be used should be added to the alphabet.\n\n PARAMETERS\n ----------\n\n * message: The message you want to encrypt.\n * alphabet (optional): The characters to be used for the cipher .\n * period (optional): The number of characters you want in a group whilst\n encrypting.\n\n >>> encrypt_message('I am a boy')\n 'BCDGBQY'\n\n >>> encrypt_message(' ')\n ''\n\n >>> encrypt_message(' aide toi le c iel ta id era ',\n ... 'FELIXMARDSTBCGHJKNOPQUVWYZ+',5)\n 'FMJFVOISSUFTFPUFEQQC'\n\n \"\"\"\n message, alphabet, character_to_number, number_to_character = __prepare(\n message, alphabet\n )\n\n encrypted_numeric = \"\"\n for i in range(0, len(message) + 1, period):\n encrypted_numeric += __encrypt_part(\n message[i : i + period], character_to_number\n )\n\n encrypted = \"\"\n for i in range(0, len(encrypted_numeric), 3):\n encrypted += number_to_character[encrypted_numeric[i : i + 3]]\n return encrypted\n\n\ndef decrypt_message(\n message: str, alphabet: str = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ.\", period: int = 5\n) -> str:\n \"\"\"\n decrypt_message\n ===============\n\n Decrypts a trifid_cipher encrypted message .\n\n PARAMETERS\n ----------\n\n * message: The message you want to decrypt .\n * alphabet (optional): The characters used for the cipher.\n * period (optional): The number of characters used in grouping when it\n was encrypted.\n\n >>> decrypt_message('BCDGBQY')\n 'IAMABOY'\n\n Decrypting with your own alphabet and period\n >>> decrypt_message('FMJFVOISSUFTFPUFEQQC','FELIXMARDSTBCGHJKNOPQUVWYZ+',5)\n 'AIDETOILECIELTAIDERA'\n \"\"\"\n message, alphabet, character_to_number, number_to_character = __prepare(\n message, alphabet\n )\n\n decrypted_numeric = []\n for i in range(0, len(message), period):\n a, b, c = __decrypt_part(message[i : i + period], character_to_number)\n\n for j in range(len(a)):\n decrypted_numeric.append(a[j] + b[j] + c[j])\n\n return \"\".join(number_to_character[each] for each in decrypted_numeric)\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n msg = \"DEFEND THE EAST WALL OF THE CASTLE.\"\n encrypted = encrypt_message(msg, \"EPSDUCVWYM.ZLKXNBTFGORIJHAQ\")\n decrypted = decrypt_message(encrypted, \"EPSDUCVWYM.ZLKXNBTFGORIJHAQ\")\n print(f\"Encrypted: {encrypted}\\nDecrypted: {decrypted}\")\n"} +{"Prompt":"vernamencryptHELLO,KEY 'RIJVS' vernamdecryptRIJVS,KEY 'HELLO' Example usage","Completions":"def vernam_encrypt(plaintext: str, key: str) -> str:\n \"\"\"\n >>> vernam_encrypt(\"HELLO\",\"KEY\")\n 'RIJVS'\n \"\"\"\n ciphertext = \"\"\n for i in range(len(plaintext)):\n ct = ord(key[i % len(key)]) - 65 + ord(plaintext[i]) - 65\n while ct > 25:\n ct = ct - 26\n ciphertext += chr(65 + ct)\n return ciphertext\n\n\ndef vernam_decrypt(ciphertext: str, key: str) -> str:\n \"\"\"\n >>> vernam_decrypt(\"RIJVS\",\"KEY\")\n 'HELLO'\n \"\"\"\n decrypted_text = \"\"\n for i in range(len(ciphertext)):\n ct = ord(ciphertext[i]) - ord(key[i % len(key)])\n while ct < 0:\n ct = 26 + ct\n decrypted_text += chr(65 + ct)\n return decrypted_text\n\n\nif __name__ == \"__main__\":\n from doctest import testmod\n\n testmod()\n\n # Example usage\n plaintext = \"HELLO\"\n key = \"KEY\"\n encrypted_text = vernam_encrypt(plaintext, key)\n decrypted_text = vernam_decrypt(encrypted_text, key)\n print(\"\\n\\n\")\n print(\"Plaintext:\", plaintext)\n print(\"Encrypted:\", encrypted_text)\n print(\"Decrypted:\", decrypted_text)\n"} +{"Prompt":"encryptmessage'HDarji', 'This is Harshil Darji from Dharmaj.' 'Akij ra Odrjqqs Gaisq muod Mphumrs.' decryptmessage'HDarji', 'Akij ra Odrjqqs Gaisq muod Mphumrs.' 'This is Harshil Darji from Dharmaj.'","Completions":"LETTERS = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n\n\ndef main() -> None:\n message = input(\"Enter message: \")\n key = input(\"Enter key [alphanumeric]: \")\n mode = input(\"Encrypt\/Decrypt [e\/d]: \")\n\n if mode.lower().startswith(\"e\"):\n mode = \"encrypt\"\n translated = encrypt_message(key, message)\n elif mode.lower().startswith(\"d\"):\n mode = \"decrypt\"\n translated = decrypt_message(key, message)\n\n print(f\"\\n{mode.title()}ed message:\")\n print(translated)\n\n\ndef encrypt_message(key: str, message: str) -> str:\n \"\"\"\n >>> encrypt_message('HDarji', 'This is Harshil Darji from Dharmaj.')\n 'Akij ra Odrjqqs Gaisq muod Mphumrs.'\n \"\"\"\n return translate_message(key, message, \"encrypt\")\n\n\ndef decrypt_message(key: str, message: str) -> str:\n \"\"\"\n >>> decrypt_message('HDarji', 'Akij ra Odrjqqs Gaisq muod Mphumrs.')\n 'This is Harshil Darji from Dharmaj.'\n \"\"\"\n return translate_message(key, message, \"decrypt\")\n\n\ndef translate_message(key: str, message: str, mode: str) -> str:\n translated = []\n key_index = 0\n key = key.upper()\n\n for symbol in message:\n num = LETTERS.find(symbol.upper())\n if num != -1:\n if mode == \"encrypt\":\n num += LETTERS.find(key[key_index])\n elif mode == \"decrypt\":\n num -= LETTERS.find(key[key_index])\n\n num %= len(LETTERS)\n\n if symbol.isupper():\n translated.append(LETTERS[num])\n elif symbol.islower():\n translated.append(LETTERS[num].lower())\n\n key_index += 1\n if key_index == len(key):\n key_index = 0\n else:\n translated.append(symbol)\n return \"\".join(translated)\n\n\nif __name__ == \"__main__\":\n main()\n"} +{"Prompt":"author: Christian Bender date: 21.12.2017 class: XORCipher This class implements the XORcipher algorithm and provides some useful methods for encrypting and decrypting strings and files. Overview about methods encrypt : list of char decrypt : list of char encryptstring : str decryptstring : str encryptfile : boolean decryptfile : boolean simple constructor that receives a key or uses default key 0 private field input: 'content' of type string and 'key' of type int output: encrypted string 'content' as a list of chars if key not passed the method uses the key by the constructor. otherwise key 1 Empty list XORCipher.encrypt, 5 One key XORCipher.encrypthallo welt, 1 'i', '', 'm', 'm', 'n', '!', 'v', 'd', 'm', 'u' Normal key XORCipher.encryptHALLO WELT, 32 'h', 'a', 'l', 'l', 'o', 'x00', 'w', 'e', 'l', 't' Key greater than 255 XORCipher.encrypthallo welt, 256 'h', 'a', 'l', 'l', 'o', ' ', 'w', 'e', 'l', 't' precondition make sure key is an appropriate size input: 'content' of type list and 'key' of type int output: decrypted string 'content' as a list of chars if key not passed the method uses the key by the constructor. otherwise key 1 Empty list XORCipher.decrypt, 5 One key XORCipher.decrypthallo welt, 1 'i', '', 'm', 'm', 'n', '!', 'v', 'd', 'm', 'u' Normal key XORCipher.decryptHALLO WELT, 32 'h', 'a', 'l', 'l', 'o', 'x00', 'w', 'e', 'l', 't' Key greater than 255 XORCipher.decrypthallo welt, 256 'h', 'a', 'l', 'l', 'o', ' ', 'w', 'e', 'l', 't' precondition make sure key is an appropriate size input: 'content' of type string and 'key' of type int output: encrypted string 'content' if key not passed the method uses the key by the constructor. otherwise key 1 Empty list XORCipher.encryptstring, 5 '' One key XORCipher.encryptstringhallo welt, 1 'immn!vdmu' Normal key XORCipher.encryptstringHALLO WELT, 32 'hallox00welt' Key greater than 255 XORCipher.encryptstringhallo welt, 256 'hallo welt' precondition make sure key is an appropriate size This will be returned input: 'content' of type string and 'key' of type int output: decrypted string 'content' if key not passed the method uses the key by the constructor. otherwise key 1 Empty list XORCipher.decryptstring, 5 '' One key XORCipher.decryptstringhallo welt, 1 'immn!vdmu' Normal key XORCipher.decryptstringHALLO WELT, 32 'hallox00welt' Key greater than 255 XORCipher.decryptstringhallo welt, 256 'hallo welt' precondition make sure key is an appropriate size This will be returned input: filename str and a key int output: returns true if encrypt process was successful otherwise false if key not passed the method uses the key by the constructor. otherwise key 1 precondition make sure key is an appropriate size actual encryptprocess input: filename str and a key int output: returns true if decrypt process was successful otherwise false if key not passed the method uses the key by the constructor. otherwise key 1 precondition make sure key is an appropriate size actual encryptprocess Tests crypt XORCipher key 67 test encrypt printcrypt.encrypthallo welt,key test decrypt printcrypt.decryptcrypt.encrypthallo welt,key, key test encryptstring printcrypt.encryptstringhallo welt,key test decryptstring printcrypt.decryptstringcrypt.encryptstringhallo welt,key,key if crypt.encryptfiletest.txt,key: printencrypt successful else: printencrypt unsuccessful if crypt.decryptfileencrypt.out,key: printdecrypt successful else: printdecrypt unsuccessful","Completions":"from __future__ import annotations\n\n\nclass XORCipher:\n def __init__(self, key: int = 0):\n \"\"\"\n simple constructor that receives a key or uses\n default key = 0\n \"\"\"\n\n # private field\n self.__key = key\n\n def encrypt(self, content: str, key: int) -> list[str]:\n \"\"\"\n input: 'content' of type string and 'key' of type int\n output: encrypted string 'content' as a list of chars\n if key not passed the method uses the key by the constructor.\n otherwise key = 1\n\n Empty list\n >>> XORCipher().encrypt(\"\", 5)\n []\n\n One key\n >>> XORCipher().encrypt(\"hallo welt\", 1)\n ['i', '`', 'm', 'm', 'n', '!', 'v', 'd', 'm', 'u']\n\n Normal key\n >>> XORCipher().encrypt(\"HALLO WELT\", 32)\n ['h', 'a', 'l', 'l', 'o', '\\\\x00', 'w', 'e', 'l', 't']\n\n Key greater than 255\n >>> XORCipher().encrypt(\"hallo welt\", 256)\n ['h', 'a', 'l', 'l', 'o', ' ', 'w', 'e', 'l', 't']\n \"\"\"\n\n # precondition\n assert isinstance(key, int)\n assert isinstance(content, str)\n\n key = key or self.__key or 1\n\n # make sure key is an appropriate size\n key %= 256\n\n return [chr(ord(ch) ^ key) for ch in content]\n\n def decrypt(self, content: str, key: int) -> list[str]:\n \"\"\"\n input: 'content' of type list and 'key' of type int\n output: decrypted string 'content' as a list of chars\n if key not passed the method uses the key by the constructor.\n otherwise key = 1\n\n Empty list\n >>> XORCipher().decrypt(\"\", 5)\n []\n\n One key\n >>> XORCipher().decrypt(\"hallo welt\", 1)\n ['i', '`', 'm', 'm', 'n', '!', 'v', 'd', 'm', 'u']\n\n Normal key\n >>> XORCipher().decrypt(\"HALLO WELT\", 32)\n ['h', 'a', 'l', 'l', 'o', '\\\\x00', 'w', 'e', 'l', 't']\n\n Key greater than 255\n >>> XORCipher().decrypt(\"hallo welt\", 256)\n ['h', 'a', 'l', 'l', 'o', ' ', 'w', 'e', 'l', 't']\n \"\"\"\n\n # precondition\n assert isinstance(key, int)\n assert isinstance(content, str)\n\n key = key or self.__key or 1\n\n # make sure key is an appropriate size\n key %= 256\n\n return [chr(ord(ch) ^ key) for ch in content]\n\n def encrypt_string(self, content: str, key: int = 0) -> str:\n \"\"\"\n input: 'content' of type string and 'key' of type int\n output: encrypted string 'content'\n if key not passed the method uses the key by the constructor.\n otherwise key = 1\n\n Empty list\n >>> XORCipher().encrypt_string(\"\", 5)\n ''\n\n One key\n >>> XORCipher().encrypt_string(\"hallo welt\", 1)\n 'i`mmn!vdmu'\n\n Normal key\n >>> XORCipher().encrypt_string(\"HALLO WELT\", 32)\n 'hallo\\\\x00welt'\n\n Key greater than 255\n >>> XORCipher().encrypt_string(\"hallo welt\", 256)\n 'hallo welt'\n \"\"\"\n\n # precondition\n assert isinstance(key, int)\n assert isinstance(content, str)\n\n key = key or self.__key or 1\n\n # make sure key is an appropriate size\n key %= 256\n\n # This will be returned\n ans = \"\"\n\n for ch in content:\n ans += chr(ord(ch) ^ key)\n\n return ans\n\n def decrypt_string(self, content: str, key: int = 0) -> str:\n \"\"\"\n input: 'content' of type string and 'key' of type int\n output: decrypted string 'content'\n if key not passed the method uses the key by the constructor.\n otherwise key = 1\n\n Empty list\n >>> XORCipher().decrypt_string(\"\", 5)\n ''\n\n One key\n >>> XORCipher().decrypt_string(\"hallo welt\", 1)\n 'i`mmn!vdmu'\n\n Normal key\n >>> XORCipher().decrypt_string(\"HALLO WELT\", 32)\n 'hallo\\\\x00welt'\n\n Key greater than 255\n >>> XORCipher().decrypt_string(\"hallo welt\", 256)\n 'hallo welt'\n \"\"\"\n\n # precondition\n assert isinstance(key, int)\n assert isinstance(content, str)\n\n key = key or self.__key or 1\n\n # make sure key is an appropriate size\n key %= 256\n\n # This will be returned\n ans = \"\"\n\n for ch in content:\n ans += chr(ord(ch) ^ key)\n\n return ans\n\n def encrypt_file(self, file: str, key: int = 0) -> bool:\n \"\"\"\n input: filename (str) and a key (int)\n output: returns true if encrypt process was\n successful otherwise false\n if key not passed the method uses the key by the constructor.\n otherwise key = 1\n \"\"\"\n\n # precondition\n assert isinstance(file, str)\n assert isinstance(key, int)\n\n # make sure key is an appropriate size\n key %= 256\n\n try:\n with open(file) as fin, open(\"encrypt.out\", \"w+\") as fout:\n # actual encrypt-process\n for line in fin:\n fout.write(self.encrypt_string(line, key))\n\n except OSError:\n return False\n\n return True\n\n def decrypt_file(self, file: str, key: int) -> bool:\n \"\"\"\n input: filename (str) and a key (int)\n output: returns true if decrypt process was\n successful otherwise false\n if key not passed the method uses the key by the constructor.\n otherwise key = 1\n \"\"\"\n\n # precondition\n assert isinstance(file, str)\n assert isinstance(key, int)\n\n # make sure key is an appropriate size\n key %= 256\n\n try:\n with open(file) as fin, open(\"decrypt.out\", \"w+\") as fout:\n # actual encrypt-process\n for line in fin:\n fout.write(self.decrypt_string(line, key))\n\n except OSError:\n return False\n\n return True\n\n\nif __name__ == \"__main__\":\n from doctest import testmod\n\n testmod()\n\n# Tests\n# crypt = XORCipher()\n# key = 67\n\n# # test encrypt\n# print(crypt.encrypt(\"hallo welt\",key))\n# # test decrypt\n# print(crypt.decrypt(crypt.encrypt(\"hallo welt\",key), key))\n\n# # test encrypt_string\n# print(crypt.encrypt_string(\"hallo welt\",key))\n\n# # test decrypt_string\n# print(crypt.decrypt_string(crypt.encrypt_string(\"hallo welt\",key),key))\n\n# if (crypt.encrypt_file(\"test.txt\",key)):\n# print(\"encrypt successful\")\n# else:\n# print(\"encrypt unsuccessful\")\n\n# if (crypt.decrypt_file(\"encrypt.out\",key)):\n# print(\"decrypt successful\")\n# else:\n# print(\"decrypt unsuccessful\")\n"} +{"Prompt":"https:en.wikipedia.orgwikiBurrowsE28093Wheelertransform The BurrowsWheeler transform BWT, also called blocksorting compression rearranges a character string into runs of similar characters. This is useful for compression, since it tends to be easy to compress a string that has runs of repeated characters by techniques such as movetofront transform and runlength encoding. More importantly, the transformation is reversible, without needing to store any additional data except the position of the first original character. The BWT is thus a free method of improving the efficiency of text compression algorithms, costing only some extra computation. :param s: The string that will be rotated lens times. :return: A list with the rotations. :raises TypeError: If s is not an instance of str. Examples: allrotationsBANANA doctest: NORMALIZEWHITESPACE 'BANANA', 'BANANA', 'ANANAB', 'NANABA', 'ANABAN', 'NABANA', 'ABANAN', 'BANANA' allrotationsaasadacasa doctest: NORMALIZEWHITESPACE 'aasadacasa', 'asadacasaa', 'asadacasaa', 'sadacasaaa', 'adacasaaas', 'dacasaaasa', 'dacasaaasa', 'acasaaasad', 'casaaasada', 'casaaasada', 'asaaasadac', 'saaasadaca', 'aaasadacas' allrotationspanamabanana doctest: NORMALIZEWHITESPACE 'panamabanana', 'anamabananap', 'namabananapa', 'amabananapan', 'mabananapana', 'abananapanam', 'bananapanama', 'ananapanamab', 'nanapanamaba', 'anapanamaban', 'napanamabana', 'apanamabanan' allrotations5 Traceback most recent call last: ... TypeError: The parameter s type must be str. :param s: The string that will be used at bwt algorithm :return: the string composed of the last char of each row of the ordered rotations and the index of the original string at ordered rotations list :raises TypeError: If the s parameter type is not str :raises ValueError: If the s parameter is empty Examples: bwttransformBANANA 'bwtstring': 'BNNAAA', 'idxoriginalstring': 6 bwttransformaasadacasa 'bwtstring': 'aaaadsscaa', 'idxoriginalstring': 3 bwttransformpanamabanana 'bwtstring': 'mnpbnnaaaaaa', 'idxoriginalstring': 11 bwttransform4 Traceback most recent call last: ... TypeError: The parameter s type must be str. bwttransform'' Traceback most recent call last: ... ValueError: The parameter s must not be empty. make a string composed of the last char of each rotation :param bwtstring: The string returned from bwt algorithm execution :param idxoriginalstring: A 0based index of the string that was used to generate bwtstring at ordered rotations list :return: The string used to generate bwtstring when bwt was executed :raises TypeError: If the bwtstring parameter type is not str :raises ValueError: If the bwtstring parameter is empty :raises TypeError: If the idxoriginalstring type is not int or if not possible to cast it to int :raises ValueError: If the idxoriginalstring value is lower than 0 or greater than lenbwtstring 1 reversebwtBNNAAA, 6 'BANANA' reversebwtaaaadsscaa, 3 'aasadacasa' reversebwtmnpbnnaaaaaa, 11 'panamabanana' reversebwt4, 11 Traceback most recent call last: ... TypeError: The parameter bwtstring type must be str. reversebwt, 11 Traceback most recent call last: ... ValueError: The parameter bwtstring must not be empty. reversebwtmnpbnnaaaaaa, asd doctest: NORMALIZEWHITESPACE Traceback most recent call last: ... TypeError: The parameter idxoriginalstring type must be int or passive of cast to int. reversebwtmnpbnnaaaaaa, 1 Traceback most recent call last: ... ValueError: The parameter idxoriginalstring must not be lower than 0. reversebwtmnpbnnaaaaaa, 12 doctest: NORMALIZEWHITESPACE Traceback most recent call last: ... ValueError: The parameter idxoriginalstring must be lower than lenbwtstring. reversebwtmnpbnnaaaaaa, 11.0 'panamabanana' reversebwtmnpbnnaaaaaa, 11.4 'panamabanana'","Completions":"from __future__ import annotations\n\nfrom typing import TypedDict\n\n\nclass BWTTransformDict(TypedDict):\n bwt_string: str\n idx_original_string: int\n\n\ndef all_rotations(s: str) -> list[str]:\n \"\"\"\n :param s: The string that will be rotated len(s) times.\n :return: A list with the rotations.\n :raises TypeError: If s is not an instance of str.\n Examples:\n\n >>> all_rotations(\"^BANANA|\") # doctest: +NORMALIZE_WHITESPACE\n ['^BANANA|', 'BANANA|^', 'ANANA|^B', 'NANA|^BA', 'ANA|^BAN', 'NA|^BANA',\n 'A|^BANAN', '|^BANANA']\n >>> all_rotations(\"a_asa_da_casa\") # doctest: +NORMALIZE_WHITESPACE\n ['a_asa_da_casa', '_asa_da_casaa', 'asa_da_casaa_', 'sa_da_casaa_a',\n 'a_da_casaa_as', '_da_casaa_asa', 'da_casaa_asa_', 'a_casaa_asa_d',\n '_casaa_asa_da', 'casaa_asa_da_', 'asaa_asa_da_c', 'saa_asa_da_ca',\n 'aa_asa_da_cas']\n >>> all_rotations(\"panamabanana\") # doctest: +NORMALIZE_WHITESPACE\n ['panamabanana', 'anamabananap', 'namabananapa', 'amabananapan',\n 'mabananapana', 'abananapanam', 'bananapanama', 'ananapanamab',\n 'nanapanamaba', 'anapanamaban', 'napanamabana', 'apanamabanan']\n >>> all_rotations(5)\n Traceback (most recent call last):\n ...\n TypeError: The parameter s type must be str.\n \"\"\"\n if not isinstance(s, str):\n raise TypeError(\"The parameter s type must be str.\")\n\n return [s[i:] + s[:i] for i in range(len(s))]\n\n\ndef bwt_transform(s: str) -> BWTTransformDict:\n \"\"\"\n :param s: The string that will be used at bwt algorithm\n :return: the string composed of the last char of each row of the ordered\n rotations and the index of the original string at ordered rotations list\n :raises TypeError: If the s parameter type is not str\n :raises ValueError: If the s parameter is empty\n Examples:\n\n >>> bwt_transform(\"^BANANA\")\n {'bwt_string': 'BNN^AAA', 'idx_original_string': 6}\n >>> bwt_transform(\"a_asa_da_casa\")\n {'bwt_string': 'aaaadss_c__aa', 'idx_original_string': 3}\n >>> bwt_transform(\"panamabanana\")\n {'bwt_string': 'mnpbnnaaaaaa', 'idx_original_string': 11}\n >>> bwt_transform(4)\n Traceback (most recent call last):\n ...\n TypeError: The parameter s type must be str.\n >>> bwt_transform('')\n Traceback (most recent call last):\n ...\n ValueError: The parameter s must not be empty.\n \"\"\"\n if not isinstance(s, str):\n raise TypeError(\"The parameter s type must be str.\")\n if not s:\n raise ValueError(\"The parameter s must not be empty.\")\n\n rotations = all_rotations(s)\n rotations.sort() # sort the list of rotations in alphabetically order\n # make a string composed of the last char of each rotation\n response: BWTTransformDict = {\n \"bwt_string\": \"\".join([word[-1] for word in rotations]),\n \"idx_original_string\": rotations.index(s),\n }\n return response\n\n\ndef reverse_bwt(bwt_string: str, idx_original_string: int) -> str:\n \"\"\"\n :param bwt_string: The string returned from bwt algorithm execution\n :param idx_original_string: A 0-based index of the string that was used to\n generate bwt_string at ordered rotations list\n :return: The string used to generate bwt_string when bwt was executed\n :raises TypeError: If the bwt_string parameter type is not str\n :raises ValueError: If the bwt_string parameter is empty\n :raises TypeError: If the idx_original_string type is not int or if not\n possible to cast it to int\n :raises ValueError: If the idx_original_string value is lower than 0 or\n greater than len(bwt_string) - 1\n\n >>> reverse_bwt(\"BNN^AAA\", 6)\n '^BANANA'\n >>> reverse_bwt(\"aaaadss_c__aa\", 3)\n 'a_asa_da_casa'\n >>> reverse_bwt(\"mnpbnnaaaaaa\", 11)\n 'panamabanana'\n >>> reverse_bwt(4, 11)\n Traceback (most recent call last):\n ...\n TypeError: The parameter bwt_string type must be str.\n >>> reverse_bwt(\"\", 11)\n Traceback (most recent call last):\n ...\n ValueError: The parameter bwt_string must not be empty.\n >>> reverse_bwt(\"mnpbnnaaaaaa\", \"asd\") # doctest: +NORMALIZE_WHITESPACE\n Traceback (most recent call last):\n ...\n TypeError: The parameter idx_original_string type must be int or passive\n of cast to int.\n >>> reverse_bwt(\"mnpbnnaaaaaa\", -1)\n Traceback (most recent call last):\n ...\n ValueError: The parameter idx_original_string must not be lower than 0.\n >>> reverse_bwt(\"mnpbnnaaaaaa\", 12) # doctest: +NORMALIZE_WHITESPACE\n Traceback (most recent call last):\n ...\n ValueError: The parameter idx_original_string must be lower than\n len(bwt_string).\n >>> reverse_bwt(\"mnpbnnaaaaaa\", 11.0)\n 'panamabanana'\n >>> reverse_bwt(\"mnpbnnaaaaaa\", 11.4)\n 'panamabanana'\n \"\"\"\n if not isinstance(bwt_string, str):\n raise TypeError(\"The parameter bwt_string type must be str.\")\n if not bwt_string:\n raise ValueError(\"The parameter bwt_string must not be empty.\")\n try:\n idx_original_string = int(idx_original_string)\n except ValueError:\n raise TypeError(\n \"The parameter idx_original_string type must be int or passive\"\n \" of cast to int.\"\n )\n if idx_original_string < 0:\n raise ValueError(\"The parameter idx_original_string must not be lower than 0.\")\n if idx_original_string >= len(bwt_string):\n raise ValueError(\n \"The parameter idx_original_string must be lower than len(bwt_string).\"\n )\n\n ordered_rotations = [\"\"] * len(bwt_string)\n for _ in range(len(bwt_string)):\n for i in range(len(bwt_string)):\n ordered_rotations[i] = bwt_string[i] + ordered_rotations[i]\n ordered_rotations.sort()\n return ordered_rotations[idx_original_string]\n\n\nif __name__ == \"__main__\":\n entry_msg = \"Provide a string that I will generate its BWT transform: \"\n s = input(entry_msg).strip()\n result = bwt_transform(s)\n print(\n f\"Burrows Wheeler transform for string '{s}' results \"\n f\"in '{result['bwt_string']}'\"\n )\n original_string = reverse_bwt(result[\"bwt_string\"], result[\"idx_original_string\"])\n print(\n f\"Reversing Burrows Wheeler transform for entry '{result['bwt_string']}' \"\n f\"we get original string '{original_string}'\"\n )\n"} +{"Prompt":"Read the file and build a dict of all letters and their frequencies, then convert the dict into a list of Letters. Run through the list of Letters and build the min heap for the Huffman Tree. Recursively traverse the Huffman Tree to set each Letter's bitstring dictionary, and return the list of Letters Parse the file, build the tree, then run through the file again, using the letters dictionary to find and print out the bitstring for each letter. pass the file path to the huffman function","Completions":"from __future__ import annotations\n\nimport sys\n\n\nclass Letter:\n def __init__(self, letter: str, freq: int):\n self.letter: str = letter\n self.freq: int = freq\n self.bitstring: dict[str, str] = {}\n\n def __repr__(self) -> str:\n return f\"{self.letter}:{self.freq}\"\n\n\nclass TreeNode:\n def __init__(self, freq: int, left: Letter | TreeNode, right: Letter | TreeNode):\n self.freq: int = freq\n self.left: Letter | TreeNode = left\n self.right: Letter | TreeNode = right\n\n\ndef parse_file(file_path: str) -> list[Letter]:\n \"\"\"\n Read the file and build a dict of all letters and their\n frequencies, then convert the dict into a list of Letters.\n \"\"\"\n chars: dict[str, int] = {}\n with open(file_path) as f:\n while True:\n c = f.read(1)\n if not c:\n break\n chars[c] = chars[c] + 1 if c in chars else 1\n return sorted((Letter(c, f) for c, f in chars.items()), key=lambda x: x.freq)\n\n\ndef build_tree(letters: list[Letter]) -> Letter | TreeNode:\n \"\"\"\n Run through the list of Letters and build the min heap\n for the Huffman Tree.\n \"\"\"\n response: list[Letter | TreeNode] = letters # type: ignore\n while len(response) > 1:\n left = response.pop(0)\n right = response.pop(0)\n total_freq = left.freq + right.freq\n node = TreeNode(total_freq, left, right)\n response.append(node)\n response.sort(key=lambda x: x.freq)\n return response[0]\n\n\ndef traverse_tree(root: Letter | TreeNode, bitstring: str) -> list[Letter]:\n \"\"\"\n Recursively traverse the Huffman Tree to set each\n Letter's bitstring dictionary, and return the list of Letters\n \"\"\"\n if isinstance(root, Letter):\n root.bitstring[root.letter] = bitstring\n return [root]\n treenode: TreeNode = root # type: ignore\n letters = []\n letters += traverse_tree(treenode.left, bitstring + \"0\")\n letters += traverse_tree(treenode.right, bitstring + \"1\")\n return letters\n\n\ndef huffman(file_path: str) -> None:\n \"\"\"\n Parse the file, build the tree, then run through the file\n again, using the letters dictionary to find and print out the\n bitstring for each letter.\n \"\"\"\n letters_list = parse_file(file_path)\n root = build_tree(letters_list)\n letters = {\n k: v for letter in traverse_tree(root, \"\") for k, v in letter.bitstring.items()\n }\n print(f\"Huffman Coding of {file_path}: \")\n with open(file_path) as f:\n while True:\n c = f.read(1)\n if not c:\n break\n print(letters[c], end=\" \")\n print()\n\n\nif __name__ == \"__main__\":\n # pass the file path to the huffman function\n huffman(sys.argv[1])\n"} +{"Prompt":"One of the several implementations of LempelZivWelch compression algorithm https:en.wikipedia.orgwikiLempelE28093ZivE28093Welch Reads given file as bytes and returns them as a long string Adds new strings currstring 0, currstring 1 to the lexicon Compresses given databits using LempelZivWelch compression algorithm and returns the result as a string Adds given file's length in front using Elias gamma coding of the compressed string Writes given towrite string should only consist of 0's and 1's as bytes in the file Reads source file, compresses it and writes the compressed result in destination file","Completions":"import math\nimport os\nimport sys\n\n\ndef read_file_binary(file_path: str) -> str:\n \"\"\"\n Reads given file as bytes and returns them as a long string\n \"\"\"\n result = \"\"\n try:\n with open(file_path, \"rb\") as binary_file:\n data = binary_file.read()\n for dat in data:\n curr_byte = f\"{dat:08b}\"\n result += curr_byte\n return result\n except OSError:\n print(\"File not accessible\")\n sys.exit()\n\n\ndef add_key_to_lexicon(\n lexicon: dict[str, str], curr_string: str, index: int, last_match_id: str\n) -> None:\n \"\"\"\n Adds new strings (curr_string + \"0\", curr_string + \"1\") to the lexicon\n \"\"\"\n lexicon.pop(curr_string)\n lexicon[curr_string + \"0\"] = last_match_id\n\n if math.log2(index).is_integer():\n for curr_key in lexicon:\n lexicon[curr_key] = \"0\" + lexicon[curr_key]\n\n lexicon[curr_string + \"1\"] = bin(index)[2:]\n\n\ndef compress_data(data_bits: str) -> str:\n \"\"\"\n Compresses given data_bits using Lempel\u2013Ziv\u2013Welch compression algorithm\n and returns the result as a string\n \"\"\"\n lexicon = {\"0\": \"0\", \"1\": \"1\"}\n result, curr_string = \"\", \"\"\n index = len(lexicon)\n\n for i in range(len(data_bits)):\n curr_string += data_bits[i]\n if curr_string not in lexicon:\n continue\n\n last_match_id = lexicon[curr_string]\n result += last_match_id\n add_key_to_lexicon(lexicon, curr_string, index, last_match_id)\n index += 1\n curr_string = \"\"\n\n while curr_string != \"\" and curr_string not in lexicon:\n curr_string += \"0\"\n\n if curr_string != \"\":\n last_match_id = lexicon[curr_string]\n result += last_match_id\n\n return result\n\n\ndef add_file_length(source_path: str, compressed: str) -> str:\n \"\"\"\n Adds given file's length in front (using Elias gamma coding) of the compressed\n string\n \"\"\"\n file_length = os.path.getsize(source_path)\n file_length_binary = bin(file_length)[2:]\n length_length = len(file_length_binary)\n\n return \"0\" * (length_length - 1) + file_length_binary + compressed\n\n\ndef write_file_binary(file_path: str, to_write: str) -> None:\n \"\"\"\n Writes given to_write string (should only consist of 0's and 1's) as bytes in the\n file\n \"\"\"\n byte_length = 8\n try:\n with open(file_path, \"wb\") as opened_file:\n result_byte_array = [\n to_write[i : i + byte_length]\n for i in range(0, len(to_write), byte_length)\n ]\n\n if len(result_byte_array[-1]) % byte_length == 0:\n result_byte_array.append(\"10000000\")\n else:\n result_byte_array[-1] += \"1\" + \"0\" * (\n byte_length - len(result_byte_array[-1]) - 1\n )\n\n for elem in result_byte_array:\n opened_file.write(int(elem, 2).to_bytes(1, byteorder=\"big\"))\n except OSError:\n print(\"File not accessible\")\n sys.exit()\n\n\ndef compress(source_path: str, destination_path: str) -> None:\n \"\"\"\n Reads source file, compresses it and writes the compressed result in destination\n file\n \"\"\"\n data_bits = read_file_binary(source_path)\n compressed = compress_data(data_bits)\n compressed = add_file_length(source_path, compressed)\n write_file_binary(destination_path, compressed)\n\n\nif __name__ == \"__main__\":\n compress(sys.argv[1], sys.argv[2])\n"} +{"Prompt":"One of the several implementations of LempelZivWelch decompression algorithm https:en.wikipedia.orgwikiLempelE28093ZivE28093Welch Reads given file as bytes and returns them as a long string Decompresses given databits using LempelZivWelch compression algorithm and returns the result as a string Writes given towrite string should only consist of 0's and 1's as bytes in the file Removes size prefix, that compressed file should have Returns the result Reads source file, decompresses it and writes the result in destination file","Completions":"import math\nimport sys\n\n\ndef read_file_binary(file_path: str) -> str:\n \"\"\"\n Reads given file as bytes and returns them as a long string\n \"\"\"\n result = \"\"\n try:\n with open(file_path, \"rb\") as binary_file:\n data = binary_file.read()\n for dat in data:\n curr_byte = f\"{dat:08b}\"\n result += curr_byte\n return result\n except OSError:\n print(\"File not accessible\")\n sys.exit()\n\n\ndef decompress_data(data_bits: str) -> str:\n \"\"\"\n Decompresses given data_bits using Lempel\u2013Ziv\u2013Welch compression algorithm\n and returns the result as a string\n \"\"\"\n lexicon = {\"0\": \"0\", \"1\": \"1\"}\n result, curr_string = \"\", \"\"\n index = len(lexicon)\n\n for i in range(len(data_bits)):\n curr_string += data_bits[i]\n if curr_string not in lexicon:\n continue\n\n last_match_id = lexicon[curr_string]\n result += last_match_id\n lexicon[curr_string] = last_match_id + \"0\"\n\n if math.log2(index).is_integer():\n new_lex = {}\n for curr_key in list(lexicon):\n new_lex[\"0\" + curr_key] = lexicon.pop(curr_key)\n lexicon = new_lex\n\n lexicon[bin(index)[2:]] = last_match_id + \"1\"\n index += 1\n curr_string = \"\"\n return result\n\n\ndef write_file_binary(file_path: str, to_write: str) -> None:\n \"\"\"\n Writes given to_write string (should only consist of 0's and 1's) as bytes in the\n file\n \"\"\"\n byte_length = 8\n try:\n with open(file_path, \"wb\") as opened_file:\n result_byte_array = [\n to_write[i : i + byte_length]\n for i in range(0, len(to_write), byte_length)\n ]\n\n if len(result_byte_array[-1]) % byte_length == 0:\n result_byte_array.append(\"10000000\")\n else:\n result_byte_array[-1] += \"1\" + \"0\" * (\n byte_length - len(result_byte_array[-1]) - 1\n )\n\n for elem in result_byte_array[:-1]:\n opened_file.write(int(elem, 2).to_bytes(1, byteorder=\"big\"))\n except OSError:\n print(\"File not accessible\")\n sys.exit()\n\n\ndef remove_prefix(data_bits: str) -> str:\n \"\"\"\n Removes size prefix, that compressed file should have\n Returns the result\n \"\"\"\n counter = 0\n for letter in data_bits:\n if letter == \"1\":\n break\n counter += 1\n\n data_bits = data_bits[counter:]\n data_bits = data_bits[counter + 1 :]\n return data_bits\n\n\ndef compress(source_path: str, destination_path: str) -> None:\n \"\"\"\n Reads source file, decompresses it and writes the result in destination file\n \"\"\"\n data_bits = read_file_binary(source_path)\n data_bits = remove_prefix(data_bits)\n decompressed = decompress_data(data_bits)\n write_file_binary(destination_path, decompressed)\n\n\nif __name__ == \"__main__\":\n compress(sys.argv[1], sys.argv[2])\n"} +{"Prompt":"LZ77 compression algorithm lossless data compression published in papers by Abraham Lempel and Jacob Ziv in 1977 also known as LZ1 or slidingwindow compression form the basis for many variations including LZW, LZSS, LZMA and others It uses a sliding window method. Within the sliding window we have: search buffer look ahead buffer lenslidingwindow lensearchbuffer lenlookaheadbuffer LZ77 manages a dictionary that uses triples composed of: Offset into search buffer, it's the distance between the start of a phrase and the beginning of a file. Length of the match, it's the number of characters that make up a phrase. The indicator is represented by a character that is going to be encoded next. As a file is parsed, the dictionary is dynamically updated to reflect the compressed data contents and size. Examples: cabracadabrarrarrad 0, 0, 'c', 0, 0, 'a', 0, 0, 'b', 0, 0, 'r', 3, 1, 'c', 2, 1, 'd', 7, 4, 'r', 3, 5, 'd' ababcbababaa 0, 0, 'a', 0, 0, 'b', 2, 2, 'c', 4, 3, 'a', 2, 2, 'a' aacaacabcabaaac 0, 0, 'a', 1, 1, 'c', 3, 4, 'b', 3, 3, 'a', 1, 2, 'c' Sources: en.wikipedia.orgwikiLZ77andLZ78 Dataclass representing triplet called token consisting of length, offset and indicator. This triplet is used during LZ77 compression. token Token1, 2, c reprtoken '1, 2, c' strtoken '1, 2, c' Class containing compress and decompress methods using LZ77 compression algorithm. Compress the given string text using LZ77 compression algorithm. Args: text: string to be compressed Returns: output: the compressed text as a list of Tokens lz77compressor LZ77Compressor strlz77compressor.compressababcbababaa '0, 0, a, 0, 0, b, 2, 2, c, 4, 3, a, 2, 2, a' strlz77compressor.compressaacaacabcabaaac '0, 0, a, 1, 1, c, 3, 4, b, 3, 3, a, 1, 2, c' while there are still characters in text to compress find the next encoding phrase triplet with offset, length, indicator the next encoding character update the search buffer: add new characters from text into it check if size exceed the max search buffer size, if so, drop the oldest elements update the text append the token to output Convert the list of tokens into an output string. Args: tokens: list containing triplets offset, length, char Returns: output: decompressed text Tests: lz77compressor LZ77Compressor lz77compressor.decompressToken0, 0, 'c', Token0, 0, 'a', ... Token0, 0, 'b', Token0, 0, 'r', Token3, 1, 'c', ... Token2, 1, 'd', Token7, 4, 'r', Token3, 5, 'd' 'cabracadabrarrarrad' lz77compressor.decompressToken0, 0, 'a', Token0, 0, 'b', ... Token2, 2, 'c', Token4, 3, 'a', Token2, 2, 'a' 'ababcbababaa' lz77compressor.decompressToken0, 0, 'a', Token1, 1, 'c', ... Token3, 4, 'b', Token3, 3, 'a', Token1, 2, 'c' 'aacaacabcabaaac' Finds the encoding token for the first character in the text. Tests: lz77compressor LZ77Compressor lz77compressor.findencodingtokenabrarrarrad, abracad.offset 7 lz77compressor.findencodingtokenadabrarrarrad, cabrac.length 1 lz77compressor.findencodingtokenabc, xyz.offset 0 lz77compressor.findencodingtoken, xyz.offset Traceback most recent call last: ... ValueError: We need some text to work with. lz77compressor.findencodingtokenabc, .offset 0 Initialise result parameters to default values if the found length is bigger than the current or if it's equal, which means it's offset is smaller: update offset and length Calculate the longest possible match of text and window characters from textindex in text and windowindex in window. Args: text: description window: sliding window textindex: index of character in text windowindex: index of character in sliding window Returns: The maximum match between text and window, from given indexes. Tests: lz77compressor LZ77Compressor13, 6 lz77compressor.matchlengthfromindexrarrad, adabrar, 0, 4 5 lz77compressor.matchlengthfromindexadabrarrarrad, ... cabrac, 0, 1 1 Initialize compressor class Example","Completions":"from dataclasses import dataclass\n\n__version__ = \"0.1\"\n__author__ = \"Lucia Harcekova\"\n\n\n@dataclass\nclass Token:\n \"\"\"\n Dataclass representing triplet called token consisting of length, offset\n and indicator. This triplet is used during LZ77 compression.\n \"\"\"\n\n offset: int\n length: int\n indicator: str\n\n def __repr__(self) -> str:\n \"\"\"\n >>> token = Token(1, 2, \"c\")\n >>> repr(token)\n '(1, 2, c)'\n >>> str(token)\n '(1, 2, c)'\n \"\"\"\n return f\"({self.offset}, {self.length}, {self.indicator})\"\n\n\nclass LZ77Compressor:\n \"\"\"\n Class containing compress and decompress methods using LZ77 compression algorithm.\n \"\"\"\n\n def __init__(self, window_size: int = 13, lookahead_buffer_size: int = 6) -> None:\n self.window_size = window_size\n self.lookahead_buffer_size = lookahead_buffer_size\n self.search_buffer_size = self.window_size - self.lookahead_buffer_size\n\n def compress(self, text: str) -> list[Token]:\n \"\"\"\n Compress the given string text using LZ77 compression algorithm.\n\n Args:\n text: string to be compressed\n\n Returns:\n output: the compressed text as a list of Tokens\n\n >>> lz77_compressor = LZ77Compressor()\n >>> str(lz77_compressor.compress(\"ababcbababaa\"))\n '[(0, 0, a), (0, 0, b), (2, 2, c), (4, 3, a), (2, 2, a)]'\n >>> str(lz77_compressor.compress(\"aacaacabcabaaac\"))\n '[(0, 0, a), (1, 1, c), (3, 4, b), (3, 3, a), (1, 2, c)]'\n \"\"\"\n\n output = []\n search_buffer = \"\"\n\n # while there are still characters in text to compress\n while text:\n # find the next encoding phrase\n # - triplet with offset, length, indicator (the next encoding character)\n token = self._find_encoding_token(text, search_buffer)\n\n # update the search buffer:\n # - add new characters from text into it\n # - check if size exceed the max search buffer size, if so, drop the\n # oldest elements\n search_buffer += text[: token.length + 1]\n if len(search_buffer) > self.search_buffer_size:\n search_buffer = search_buffer[-self.search_buffer_size :]\n\n # update the text\n text = text[token.length + 1 :]\n\n # append the token to output\n output.append(token)\n\n return output\n\n def decompress(self, tokens: list[Token]) -> str:\n \"\"\"\n Convert the list of tokens into an output string.\n\n Args:\n tokens: list containing triplets (offset, length, char)\n\n Returns:\n output: decompressed text\n\n Tests:\n >>> lz77_compressor = LZ77Compressor()\n >>> lz77_compressor.decompress([Token(0, 0, 'c'), Token(0, 0, 'a'),\n ... Token(0, 0, 'b'), Token(0, 0, 'r'), Token(3, 1, 'c'),\n ... Token(2, 1, 'd'), Token(7, 4, 'r'), Token(3, 5, 'd')])\n 'cabracadabrarrarrad'\n >>> lz77_compressor.decompress([Token(0, 0, 'a'), Token(0, 0, 'b'),\n ... Token(2, 2, 'c'), Token(4, 3, 'a'), Token(2, 2, 'a')])\n 'ababcbababaa'\n >>> lz77_compressor.decompress([Token(0, 0, 'a'), Token(1, 1, 'c'),\n ... Token(3, 4, 'b'), Token(3, 3, 'a'), Token(1, 2, 'c')])\n 'aacaacabcabaaac'\n \"\"\"\n\n output = \"\"\n\n for token in tokens:\n for _ in range(token.length):\n output += output[-token.offset]\n output += token.indicator\n\n return output\n\n def _find_encoding_token(self, text: str, search_buffer: str) -> Token:\n \"\"\"Finds the encoding token for the first character in the text.\n\n Tests:\n >>> lz77_compressor = LZ77Compressor()\n >>> lz77_compressor._find_encoding_token(\"abrarrarrad\", \"abracad\").offset\n 7\n >>> lz77_compressor._find_encoding_token(\"adabrarrarrad\", \"cabrac\").length\n 1\n >>> lz77_compressor._find_encoding_token(\"abc\", \"xyz\").offset\n 0\n >>> lz77_compressor._find_encoding_token(\"\", \"xyz\").offset\n Traceback (most recent call last):\n ...\n ValueError: We need some text to work with.\n >>> lz77_compressor._find_encoding_token(\"abc\", \"\").offset\n 0\n \"\"\"\n\n if not text:\n raise ValueError(\"We need some text to work with.\")\n\n # Initialise result parameters to default values\n length, offset = 0, 0\n\n if not search_buffer:\n return Token(offset, length, text[length])\n\n for i, character in enumerate(search_buffer):\n found_offset = len(search_buffer) - i\n if character == text[0]:\n found_length = self._match_length_from_index(text, search_buffer, 0, i)\n # if the found length is bigger than the current or if it's equal,\n # which means it's offset is smaller: update offset and length\n if found_length >= length:\n offset, length = found_offset, found_length\n\n return Token(offset, length, text[length])\n\n def _match_length_from_index(\n self, text: str, window: str, text_index: int, window_index: int\n ) -> int:\n \"\"\"Calculate the longest possible match of text and window characters from\n text_index in text and window_index in window.\n\n Args:\n text: _description_\n window: sliding window\n text_index: index of character in text\n window_index: index of character in sliding window\n\n Returns:\n The maximum match between text and window, from given indexes.\n\n Tests:\n >>> lz77_compressor = LZ77Compressor(13, 6)\n >>> lz77_compressor._match_length_from_index(\"rarrad\", \"adabrar\", 0, 4)\n 5\n >>> lz77_compressor._match_length_from_index(\"adabrarrarrad\",\n ... \"cabrac\", 0, 1)\n 1\n \"\"\"\n if not text or text[text_index] != window[window_index]:\n return 0\n return 1 + self._match_length_from_index(\n text, window + text[text_index], text_index + 1, window_index + 1\n )\n\n\nif __name__ == \"__main__\":\n from doctest import testmod\n\n testmod()\n # Initialize compressor class\n lz77_compressor = LZ77Compressor(window_size=13, lookahead_buffer_size=6)\n\n # Example\n TEXT = \"cabracadabrarrarrad\"\n compressed_text = lz77_compressor.compress(TEXT)\n print(lz77_compressor.compress(\"ababcbababaa\"))\n decompressed_text = lz77_compressor.decompress(compressed_text)\n assert decompressed_text == TEXT, \"The LZ77 algorithm returned the invalid result.\"\n"} +{"Prompt":"Peak signaltonoise ratio PSNR https:en.wikipedia.orgwikiPeaksignaltonoiseratio Source: https:tutorials.techonical.comhowtocalculatepsnrvalueoftwoimagesusingpython Loading images original image and compressed image Value expected: 29.73dB Value expected: 31.53dB Wikipedia Example","Completions":"import math\nimport os\n\nimport cv2\nimport numpy as np\n\nPIXEL_MAX = 255.0\n\n\ndef peak_signal_to_noise_ratio(original: float, contrast: float) -> float:\n mse = np.mean((original - contrast) ** 2)\n if mse == 0:\n return 100\n\n return 20 * math.log10(PIXEL_MAX \/ math.sqrt(mse))\n\n\ndef main() -> None:\n dir_path = os.path.dirname(os.path.realpath(__file__))\n # Loading images (original image and compressed image)\n original = cv2.imread(os.path.join(dir_path, \"image_data\/original_image.png\"))\n contrast = cv2.imread(os.path.join(dir_path, \"image_data\/compressed_image.png\"), 1)\n\n original2 = cv2.imread(os.path.join(dir_path, \"image_data\/PSNR-example-base.png\"))\n contrast2 = cv2.imread(\n os.path.join(dir_path, \"image_data\/PSNR-example-comp-10.jpg\"), 1\n )\n\n # Value expected: 29.73dB\n print(\"-- First Test --\")\n print(f\"PSNR value is {peak_signal_to_noise_ratio(original, contrast)} dB\")\n\n # # Value expected: 31.53dB (Wikipedia Example)\n print(\"\\n-- Second Test --\")\n print(f\"PSNR value is {peak_signal_to_noise_ratio(original2, contrast2)} dB\")\n\n\nif __name__ == \"__main__\":\n main()\n"} +{"Prompt":"https:en.wikipedia.orgwikiRunlengthencoding Performs Run Length Encoding runlengthencodeAAAABBBCCDAA 'A', 4, 'B', 3, 'C', 2, 'D', 1, 'A', 2 runlengthencodeA 'A', 1 runlengthencodeAA 'A', 2 runlengthencodeAAADDDDDDFFFCCCAAVVVV 'A', 3, 'D', 6, 'F', 3, 'C', 3, 'A', 2, 'V', 4 Performs Run Length Decoding runlengthdecode'A', 4, 'B', 3, 'C', 2, 'D', 1, 'A', 2 'AAAABBBCCDAA' runlengthdecode'A', 1 'A' runlengthdecode'A', 2 'AA' runlengthdecode'A', 3, 'D', 6, 'F', 3, 'C', 3, 'A', 2, 'V', 4 'AAADDDDDDFFFCCCAAVVVV'","Completions":"# https:\/\/en.wikipedia.org\/wiki\/Run-length_encoding\n\n\ndef run_length_encode(text: str) -> list:\n \"\"\"\n Performs Run Length Encoding\n >>> run_length_encode(\"AAAABBBCCDAA\")\n [('A', 4), ('B', 3), ('C', 2), ('D', 1), ('A', 2)]\n >>> run_length_encode(\"A\")\n [('A', 1)]\n >>> run_length_encode(\"AA\")\n [('A', 2)]\n >>> run_length_encode(\"AAADDDDDDFFFCCCAAVVVV\")\n [('A', 3), ('D', 6), ('F', 3), ('C', 3), ('A', 2), ('V', 4)]\n \"\"\"\n encoded = []\n count = 1\n\n for i in range(len(text)):\n if i + 1 < len(text) and text[i] == text[i + 1]:\n count += 1\n else:\n encoded.append((text[i], count))\n count = 1\n\n return encoded\n\n\ndef run_length_decode(encoded: list) -> str:\n \"\"\"\n Performs Run Length Decoding\n >>> run_length_decode([('A', 4), ('B', 3), ('C', 2), ('D', 1), ('A', 2)])\n 'AAAABBBCCDAA'\n >>> run_length_decode([('A', 1)])\n 'A'\n >>> run_length_decode([('A', 2)])\n 'AA'\n >>> run_length_decode([('A', 3), ('D', 6), ('F', 3), ('C', 3), ('A', 2), ('V', 4)])\n 'AAADDDDDDFFFCCCAAVVVV'\n \"\"\"\n return \"\".join(char * length for char, length in encoded)\n\n\nif __name__ == \"__main__\":\n from doctest import testmod\n\n testmod(name=\"run_length_encode\", verbose=True)\n testmod(name=\"run_length_decode\", verbose=True)\n"} +{"Prompt":"Flip image and bounding box for computer vision task https:paperswithcode.commethodrandomhorizontalflip Params Get images list and annotations list from input dir. Update new images and annotations. Save images and annotations in output dir. Get random string code: '7b7ad245cdff75241935e4dd860f3bad' labeldir type: str: Path to label include annotation of images imgdir type: str: Path to folder contain images Return type: list: List of images path and labels imglist type: list: list of all images annolist type: list: list of all annotations of specific image fliptype type: int: 0 is vertical, 1 is horizontal Return: newimgslist type: narray: image after resize newannoslists type: list: list of new annotation after scale pathlist type: list: list the name of image file Automatic generate random 32 characters. Get random string code: '7b7ad245cdff75241935e4dd860f3bad' lenrandomchars32 32","Completions":"import glob\nimport os\nimport random\nfrom string import ascii_lowercase, digits\n\nimport cv2\n\n\"\"\"\nFlip image and bounding box for computer vision task\nhttps:\/\/paperswithcode.com\/method\/randomhorizontalflip\n\"\"\"\n\n# Params\nLABEL_DIR = \"\"\nIMAGE_DIR = \"\"\nOUTPUT_DIR = \"\"\nFLIP_TYPE = 1 # (0 is vertical, 1 is horizontal)\n\n\ndef main() -> None:\n \"\"\"\n Get images list and annotations list from input dir.\n Update new images and annotations.\n Save images and annotations in output dir.\n \"\"\"\n img_paths, annos = get_dataset(LABEL_DIR, IMAGE_DIR)\n print(\"Processing...\")\n new_images, new_annos, paths = update_image_and_anno(img_paths, annos, FLIP_TYPE)\n\n for index, image in enumerate(new_images):\n # Get random string code: '7b7ad245cdff75241935e4dd860f3bad'\n letter_code = random_chars(32)\n file_name = paths[index].split(os.sep)[-1].rsplit(\".\", 1)[0]\n file_root = f\"{OUTPUT_DIR}\/{file_name}_FLIP_{letter_code}\"\n cv2.imwrite(f\"{file_root}.jpg\", image, [cv2.IMWRITE_JPEG_QUALITY, 85])\n print(f\"Success {index+1}\/{len(new_images)} with {file_name}\")\n annos_list = []\n for anno in new_annos[index]:\n obj = f\"{anno[0]} {anno[1]} {anno[2]} {anno[3]} {anno[4]}\"\n annos_list.append(obj)\n with open(f\"{file_root}.txt\", \"w\") as outfile:\n outfile.write(\"\\n\".join(line for line in annos_list))\n\n\ndef get_dataset(label_dir: str, img_dir: str) -> tuple[list, list]:\n \"\"\"\n - label_dir : Path to label include annotation of images\n - img_dir : Path to folder contain images\n Return : List of images path and labels\n \"\"\"\n img_paths = []\n labels = []\n for label_file in glob.glob(os.path.join(label_dir, \"*.txt\")):\n label_name = label_file.split(os.sep)[-1].rsplit(\".\", 1)[0]\n with open(label_file) as in_file:\n obj_lists = in_file.readlines()\n img_path = os.path.join(img_dir, f\"{label_name}.jpg\")\n\n boxes = []\n for obj_list in obj_lists:\n obj = obj_list.rstrip(\"\\n\").split(\" \")\n boxes.append(\n [\n int(obj[0]),\n float(obj[1]),\n float(obj[2]),\n float(obj[3]),\n float(obj[4]),\n ]\n )\n if not boxes:\n continue\n img_paths.append(img_path)\n labels.append(boxes)\n return img_paths, labels\n\n\ndef update_image_and_anno(\n img_list: list, anno_list: list, flip_type: int = 1\n) -> tuple[list, list, list]:\n \"\"\"\n - img_list : list of all images\n - anno_list : list of all annotations of specific image\n - flip_type : 0 is vertical, 1 is horizontal\n Return:\n - new_imgs_list : image after resize\n - new_annos_lists : list of new annotation after scale\n - path_list : list the name of image file\n \"\"\"\n new_annos_lists = []\n path_list = []\n new_imgs_list = []\n for idx in range(len(img_list)):\n new_annos = []\n path = img_list[idx]\n path_list.append(path)\n img_annos = anno_list[idx]\n img = cv2.imread(path)\n if flip_type == 1:\n new_img = cv2.flip(img, flip_type)\n for bbox in img_annos:\n x_center_new = 1 - bbox[1]\n new_annos.append([bbox[0], x_center_new, bbox[2], bbox[3], bbox[4]])\n elif flip_type == 0:\n new_img = cv2.flip(img, flip_type)\n for bbox in img_annos:\n y_center_new = 1 - bbox[2]\n new_annos.append([bbox[0], bbox[1], y_center_new, bbox[3], bbox[4]])\n new_annos_lists.append(new_annos)\n new_imgs_list.append(new_img)\n return new_imgs_list, new_annos_lists, path_list\n\n\ndef random_chars(number_char: int = 32) -> str:\n \"\"\"\n Automatic generate random 32 characters.\n Get random string code: '7b7ad245cdff75241935e4dd860f3bad'\n >>> len(random_chars(32))\n 32\n \"\"\"\n assert number_char > 1, \"The number of character should greater than 1\"\n letter_code = ascii_lowercase + digits\n return \"\".join(random.choice(letter_code) for _ in range(number_char))\n\n\nif __name__ == \"__main__\":\n main()\n print(\"DONE \u2705\")\n"} +{"Prompt":"https:en.wikipedia.orgwikiImagetexture https:en.wikipedia.orgwikiCooccurrencematrixApplicationtoimageanalysis Simple implementation of Root Mean Squared Error for two N dimensional numpy arrays. Examples: rootmeansquareerrornp.array1, 2, 3, np.array1, 2, 3 0.0 rootmeansquareerrornp.array1, 2, 3, np.array2, 2, 2 0.816496580927726 rootmeansquareerrornp.array1, 2, 3, np.array6, 4, 2 3.1622776601683795 Normalizes image in Numpy 2D array format, between ranges 0cap, as to fit uint8 type. Args: image: 2D numpy array representing image as matrix, with values in any range cap: Maximum cap amount for normalization datatype: numpy data type to set output variable to Returns: return 2D numpy array of type uint8, corresponding to limited range matrix Examples: normalizeimagenp.array1, 2, 3, 4, 5, 10, ... cap1.0, datatypenp.float64 array0. , 0.11111111, 0.22222222, 0.33333333, 0.44444444, 1. normalizeimagenp.array4, 4, 3, 1, 7, 2 array127, 127, 85, 0, 255, 42, dtypeuint8 Normalizes a 1D array, between ranges 0cap. Args: array: List containing values to be normalized between cap range. cap: Maximum cap amount for normalization. Returns: return 1D numpy array, corresponding to limited range array Examples: normalizearraynp.array2, 3, 5, 7 array0. , 0.2, 0.6, 1. normalizearraynp.array5, 7, 11, 13 array0. , 0.25, 0.75, 1. Uses luminance weights to transform RGB channel to greyscale, by taking the dot product between the channel and the weights. Example: grayscalenp.array108, 201, 72, 255, 11, 127, ... 56, 56, 56, 128, 255, 107 array158, 97, 56, 200, dtypeuint8 Binarizes a grayscale image based on a given threshold value, setting values to 1 or 0 accordingly. Examples: binarizenp.array128, 255, 101, 156 array1, 1, 0, 1 binarizenp.array0.07, 1, 0.51, 0.3, threshold0.5 array0, 1, 1, 0 Simple image transformation using one of two available filter functions: Erosion and Dilation. Args: image: binarized input image, onto which to apply transformation kind: Can be either 'erosion', in which case the :func:np.max function is called, or 'dilation', when :func:np.min is used instead. kernel: n x n kernel with shape :attr:image.shape, to be used when applying convolution to original image Returns: returns a numpy array with same shape as input image, corresponding to applied binary transformation. Examples: img np.array1, 0.5, 0.2, 0.7 img binarizeimg, threshold0.5 transformimg, 'erosion' array1, 1, 1, 1, dtypeuint8 transformimg, 'dilation' array0, 0, 0, 0, dtypeuint8 Use padded image when applying convolotion to not go out of bounds of the original the image Apply transformation method to the centered section of the image Opening filter, defined as the sequence of erosion and then a dilation filter on the same image. Examples: img np.array1, 0.5, 0.2, 0.7 img binarizeimg, threshold0.5 openingfilterimg array1, 1, 1, 1, dtypeuint8 Opening filter, defined as the sequence of dilation and then erosion filter on the same image. Examples: img np.array1, 0.5, 0.2, 0.7 img binarizeimg, threshold0.5 closingfilterimg array0, 0, 0, 0, dtypeuint8 Apply binary mask, or thresholding based on bit mask value mapping mask is binary. Returns the mapped true value mask and its complementary false value mask. Example: img np.array108, 201, 72, 255, 11, 127, ... 56, 56, 56, 128, 255, 107 gray grayscaleimg binary binarizegray morphological openingfilterbinary binarymaskgray, morphological array1, 1, 1, 1, dtypeuint8, array158, 97, 56, 200, dtypeuint8 Calculate sample cooccurrence matrix based on input image as well as selected coordinates on image. Implementation is made using basic iteration, as function to be performed np.max is nonlinear and therefore not callable on the frequency domain. Example: img np.array108, 201, 72, 255, 11, 127, ... 56, 56, 56, 128, 255, 107 gray grayscaleimg binary binarizegray morphological openingfilterbinary mask1 binarymaskgray, morphological0 matrixconcurrencymask1, 0, 1 array0., 0., 0., 0. Calculates all 8 Haralick descriptors based on cooccurrence input matrix. All descriptors are as follows: Maximum probability, Inverse Difference, Homogeneity, Entropy, Energy, Dissimilarity, Contrast and Correlation Args: matrix: Cooccurrence matrix to use as base for calculating descriptors. Returns: Reverse ordered list of resulting descriptors Example: img np.array108, 201, 72, 255, 11, 127, ... 56, 56, 56, 128, 255, 107 gray grayscaleimg binary binarizegray morphological openingfilterbinary mask1 binarymaskgray, morphological0 concurrency matrixconcurrencymask1, 0, 1 haralickdescriptorsconcurrency 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 Function np.indices could be used for bigger input types, but np.ogrid works just fine Precalculate frequent multiplication and subtraction Calculate numerical value of Maximum Probability Using the definition for each descriptor individually to calculate its matrix Sum values for descriptors ranging from the first one to the last, as all are their respective origin matrix and not the resulting value yet. Calculate all Haralick descriptors for a sequence of different cooccurrence matrices, given input masks and coordinates. Example: img np.array108, 201, 72, 255, 11, 127, ... 56, 56, 56, 128, 255, 107 gray grayscaleimg binary binarizegray morphological openingfilterbinary getdescriptorsbinarymaskgray, morphological, 0, 1 array0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0. Concatenate each individual descriptor into one single list containing sequence of descriptors Simple method for calculating the euclidean distance between two points, with type np.ndarray. Example: a np.array1, 0, 2 b np.array2, 1, 1 euclideana, b 3.3166247903554 Calculate all Euclidean distances between a selected base descriptor and all other Haralick descriptors The resulting comparison is return in decreasing order, showing which descriptor is the most similar to the selected base. Args: descriptors: Haralick descriptors to compare with base index base: Haralick descriptor index to use as base when calculating respective euclidean distance to other descriptors. Returns: Ordered distances between descriptors Example: index 1 img np.array108, 201, 72, 255, 11, 127, ... 56, 56, 56, 128, 255, 107 gray grayscaleimg binary binarizegray morphological openingfilterbinary getdistancesgetdescriptors ... binarymaskgray, morphological, 0, 1, ... index 0, 0.0, 1, 0.0, 2, 0.0, 3, 0.0, 4, 0.0, 5, 0.0, 6, 0.0, 7, 0.0, 8, 0.0, 9, 0.0, 10, 0.0, 11, 0.0, 12, 0.0, 13, 0.0, 14, 0.0, 15, 0.0 Normalize distances between range 0, 1 Index to compare haralick descriptors to Format is the respective filter to apply, can be either 1 for the opening filter or else for the closing Number of images to perform methods on Open given image and calculate morphological filter, respective masks and correspondent Harralick Descriptors. Transform ordered distances array into a sequence of indexes corresponding to original file position Finally, print distances considering the Haralick descriptions from the base file to all other images using the morphology method of choice.","Completions":"import imageio.v2 as imageio\nimport numpy as np\n\n\ndef root_mean_square_error(original: np.ndarray, reference: np.ndarray) -> float:\n \"\"\"Simple implementation of Root Mean Squared Error\n for two N dimensional numpy arrays.\n\n Examples:\n >>> root_mean_square_error(np.array([1, 2, 3]), np.array([1, 2, 3]))\n 0.0\n >>> root_mean_square_error(np.array([1, 2, 3]), np.array([2, 2, 2]))\n 0.816496580927726\n >>> root_mean_square_error(np.array([1, 2, 3]), np.array([6, 4, 2]))\n 3.1622776601683795\n \"\"\"\n return np.sqrt(((original - reference) ** 2).mean())\n\n\ndef normalize_image(\n image: np.ndarray, cap: float = 255.0, data_type: np.dtype = np.uint8\n) -> np.ndarray:\n \"\"\"\n Normalizes image in Numpy 2D array format, between ranges 0-cap,\n as to fit uint8 type.\n\n Args:\n image: 2D numpy array representing image as matrix, with values in any range\n cap: Maximum cap amount for normalization\n data_type: numpy data type to set output variable to\n Returns:\n return 2D numpy array of type uint8, corresponding to limited range matrix\n\n Examples:\n >>> normalize_image(np.array([[1, 2, 3], [4, 5, 10]]),\n ... cap=1.0, data_type=np.float64)\n array([[0. , 0.11111111, 0.22222222],\n [0.33333333, 0.44444444, 1. ]])\n >>> normalize_image(np.array([[4, 4, 3], [1, 7, 2]]))\n array([[127, 127, 85],\n [ 0, 255, 42]], dtype=uint8)\n \"\"\"\n normalized = (image - np.min(image)) \/ (np.max(image) - np.min(image)) * cap\n return normalized.astype(data_type)\n\n\ndef normalize_array(array: np.ndarray, cap: float = 1) -> np.ndarray:\n \"\"\"Normalizes a 1D array, between ranges 0-cap.\n\n Args:\n array: List containing values to be normalized between cap range.\n cap: Maximum cap amount for normalization.\n Returns:\n return 1D numpy array, corresponding to limited range array\n\n Examples:\n >>> normalize_array(np.array([2, 3, 5, 7]))\n array([0. , 0.2, 0.6, 1. ])\n >>> normalize_array(np.array([[5], [7], [11], [13]]))\n array([[0. ],\n [0.25],\n [0.75],\n [1. ]])\n \"\"\"\n diff = np.max(array) - np.min(array)\n return (array - np.min(array)) \/ (1 if diff == 0 else diff) * cap\n\n\ndef grayscale(image: np.ndarray) -> np.ndarray:\n \"\"\"\n Uses luminance weights to transform RGB channel to greyscale, by\n taking the dot product between the channel and the weights.\n\n Example:\n >>> grayscale(np.array([[[108, 201, 72], [255, 11, 127]],\n ... [[56, 56, 56], [128, 255, 107]]]))\n array([[158, 97],\n [ 56, 200]], dtype=uint8)\n \"\"\"\n return np.dot(image[:, :, 0:3], [0.299, 0.587, 0.114]).astype(np.uint8)\n\n\ndef binarize(image: np.ndarray, threshold: float = 127.0) -> np.ndarray:\n \"\"\"\n Binarizes a grayscale image based on a given threshold value,\n setting values to 1 or 0 accordingly.\n\n Examples:\n >>> binarize(np.array([[128, 255], [101, 156]]))\n array([[1, 1],\n [0, 1]])\n >>> binarize(np.array([[0.07, 1], [0.51, 0.3]]), threshold=0.5)\n array([[0, 1],\n [1, 0]])\n \"\"\"\n return np.where(image > threshold, 1, 0)\n\n\ndef transform(\n image: np.ndarray, kind: str, kernel: np.ndarray | None = None\n) -> np.ndarray:\n \"\"\"\n Simple image transformation using one of two available filter functions:\n Erosion and Dilation.\n\n Args:\n image: binarized input image, onto which to apply transformation\n kind: Can be either 'erosion', in which case the :func:np.max\n function is called, or 'dilation', when :func:np.min is used instead.\n kernel: n x n kernel with shape < :attr:image.shape,\n to be used when applying convolution to original image\n\n Returns:\n returns a numpy array with same shape as input image,\n corresponding to applied binary transformation.\n\n Examples:\n >>> img = np.array([[1, 0.5], [0.2, 0.7]])\n >>> img = binarize(img, threshold=0.5)\n >>> transform(img, 'erosion')\n array([[1, 1],\n [1, 1]], dtype=uint8)\n >>> transform(img, 'dilation')\n array([[0, 0],\n [0, 0]], dtype=uint8)\n \"\"\"\n if kernel is None:\n kernel = np.ones((3, 3))\n\n if kind == \"erosion\":\n constant = 1\n apply = np.max\n else:\n constant = 0\n apply = np.min\n\n center_x, center_y = (x \/\/ 2 for x in kernel.shape)\n\n # Use padded image when applying convolotion\n # to not go out of bounds of the original the image\n transformed = np.zeros(image.shape, dtype=np.uint8)\n padded = np.pad(image, 1, \"constant\", constant_values=constant)\n\n for x in range(center_x, padded.shape[0] - center_x):\n for y in range(center_y, padded.shape[1] - center_y):\n center = padded[\n x - center_x : x + center_x + 1, y - center_y : y + center_y + 1\n ]\n # Apply transformation method to the centered section of the image\n transformed[x - center_x, y - center_y] = apply(center[kernel == 1])\n\n return transformed\n\n\ndef opening_filter(image: np.ndarray, kernel: np.ndarray | None = None) -> np.ndarray:\n \"\"\"\n Opening filter, defined as the sequence of\n erosion and then a dilation filter on the same image.\n\n Examples:\n >>> img = np.array([[1, 0.5], [0.2, 0.7]])\n >>> img = binarize(img, threshold=0.5)\n >>> opening_filter(img)\n array([[1, 1],\n [1, 1]], dtype=uint8)\n \"\"\"\n if kernel is None:\n np.ones((3, 3))\n\n return transform(transform(image, \"dilation\", kernel), \"erosion\", kernel)\n\n\ndef closing_filter(image: np.ndarray, kernel: np.ndarray | None = None) -> np.ndarray:\n \"\"\"\n Opening filter, defined as the sequence of\n dilation and then erosion filter on the same image.\n\n Examples:\n >>> img = np.array([[1, 0.5], [0.2, 0.7]])\n >>> img = binarize(img, threshold=0.5)\n >>> closing_filter(img)\n array([[0, 0],\n [0, 0]], dtype=uint8)\n \"\"\"\n if kernel is None:\n kernel = np.ones((3, 3))\n return transform(transform(image, \"erosion\", kernel), \"dilation\", kernel)\n\n\ndef binary_mask(\n image_gray: np.ndarray, image_map: np.ndarray\n) -> tuple[np.ndarray, np.ndarray]:\n \"\"\"\n Apply binary mask, or thresholding based\n on bit mask value (mapping mask is binary).\n\n Returns the mapped true value mask and its complementary false value mask.\n\n Example:\n >>> img = np.array([[[108, 201, 72], [255, 11, 127]],\n ... [[56, 56, 56], [128, 255, 107]]])\n >>> gray = grayscale(img)\n >>> binary = binarize(gray)\n >>> morphological = opening_filter(binary)\n >>> binary_mask(gray, morphological)\n (array([[1, 1],\n [1, 1]], dtype=uint8), array([[158, 97],\n [ 56, 200]], dtype=uint8))\n \"\"\"\n true_mask, false_mask = image_gray.copy(), image_gray.copy()\n true_mask[image_map == 1] = 1\n false_mask[image_map == 0] = 0\n\n return true_mask, false_mask\n\n\ndef matrix_concurrency(image: np.ndarray, coordinate: tuple[int, int]) -> np.ndarray:\n \"\"\"\n Calculate sample co-occurrence matrix based on input image\n as well as selected coordinates on image.\n\n Implementation is made using basic iteration,\n as function to be performed (np.max) is non-linear and therefore\n not callable on the frequency domain.\n\n Example:\n >>> img = np.array([[[108, 201, 72], [255, 11, 127]],\n ... [[56, 56, 56], [128, 255, 107]]])\n >>> gray = grayscale(img)\n >>> binary = binarize(gray)\n >>> morphological = opening_filter(binary)\n >>> mask_1 = binary_mask(gray, morphological)[0]\n >>> matrix_concurrency(mask_1, (0, 1))\n array([[0., 0.],\n [0., 0.]])\n \"\"\"\n matrix = np.zeros([np.max(image) + 1, np.max(image) + 1])\n\n offset_x, offset_y = coordinate\n\n for x in range(1, image.shape[0] - 1):\n for y in range(1, image.shape[1] - 1):\n base_pixel = image[x, y]\n offset_pixel = image[x + offset_x, y + offset_y]\n\n matrix[base_pixel, offset_pixel] += 1\n matrix_sum = np.sum(matrix)\n return matrix \/ (1 if matrix_sum == 0 else matrix_sum)\n\n\ndef haralick_descriptors(matrix: np.ndarray) -> list[float]:\n \"\"\"Calculates all 8 Haralick descriptors based on co-occurrence input matrix.\n All descriptors are as follows:\n Maximum probability, Inverse Difference, Homogeneity, Entropy,\n Energy, Dissimilarity, Contrast and Correlation\n\n Args:\n matrix: Co-occurrence matrix to use as base for calculating descriptors.\n\n Returns:\n Reverse ordered list of resulting descriptors\n\n Example:\n >>> img = np.array([[[108, 201, 72], [255, 11, 127]],\n ... [[56, 56, 56], [128, 255, 107]]])\n >>> gray = grayscale(img)\n >>> binary = binarize(gray)\n >>> morphological = opening_filter(binary)\n >>> mask_1 = binary_mask(gray, morphological)[0]\n >>> concurrency = matrix_concurrency(mask_1, (0, 1))\n >>> haralick_descriptors(concurrency)\n [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]\n \"\"\"\n # Function np.indices could be used for bigger input types,\n # but np.ogrid works just fine\n i, j = np.ogrid[0 : matrix.shape[0], 0 : matrix.shape[1]] # np.indices()\n\n # Pre-calculate frequent multiplication and subtraction\n prod = np.multiply(i, j)\n sub = np.subtract(i, j)\n\n # Calculate numerical value of Maximum Probability\n maximum_prob = np.max(matrix)\n # Using the definition for each descriptor individually to calculate its matrix\n correlation = prod * matrix\n energy = np.power(matrix, 2)\n contrast = matrix * np.power(sub, 2)\n\n dissimilarity = matrix * np.abs(sub)\n inverse_difference = matrix \/ (1 + np.abs(sub))\n homogeneity = matrix \/ (1 + np.power(sub, 2))\n entropy = -(matrix[matrix > 0] * np.log(matrix[matrix > 0]))\n\n # Sum values for descriptors ranging from the first one to the last,\n # as all are their respective origin matrix and not the resulting value yet.\n return [\n maximum_prob,\n correlation.sum(),\n energy.sum(),\n contrast.sum(),\n dissimilarity.sum(),\n inverse_difference.sum(),\n homogeneity.sum(),\n entropy.sum(),\n ]\n\n\ndef get_descriptors(\n masks: tuple[np.ndarray, np.ndarray], coordinate: tuple[int, int]\n) -> np.ndarray:\n \"\"\"\n Calculate all Haralick descriptors for a sequence of\n different co-occurrence matrices, given input masks and coordinates.\n\n Example:\n >>> img = np.array([[[108, 201, 72], [255, 11, 127]],\n ... [[56, 56, 56], [128, 255, 107]]])\n >>> gray = grayscale(img)\n >>> binary = binarize(gray)\n >>> morphological = opening_filter(binary)\n >>> get_descriptors(binary_mask(gray, morphological), (0, 1))\n array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.])\n \"\"\"\n descriptors = np.array(\n [haralick_descriptors(matrix_concurrency(mask, coordinate)) for mask in masks]\n )\n\n # Concatenate each individual descriptor into\n # one single list containing sequence of descriptors\n return np.concatenate(descriptors, axis=None)\n\n\ndef euclidean(point_1: np.ndarray, point_2: np.ndarray) -> np.float32:\n \"\"\"\n Simple method for calculating the euclidean distance between two points,\n with type np.ndarray.\n\n Example:\n >>> a = np.array([1, 0, -2])\n >>> b = np.array([2, -1, 1])\n >>> euclidean(a, b)\n 3.3166247903554\n \"\"\"\n return np.sqrt(np.sum(np.square(point_1 - point_2)))\n\n\ndef get_distances(descriptors: np.ndarray, base: int) -> list[tuple[int, float]]:\n \"\"\"\n Calculate all Euclidean distances between a selected base descriptor\n and all other Haralick descriptors\n The resulting comparison is return in decreasing order,\n showing which descriptor is the most similar to the selected base.\n\n Args:\n descriptors: Haralick descriptors to compare with base index\n base: Haralick descriptor index to use as base when calculating respective\n euclidean distance to other descriptors.\n\n Returns:\n Ordered distances between descriptors\n\n Example:\n >>> index = 1\n >>> img = np.array([[[108, 201, 72], [255, 11, 127]],\n ... [[56, 56, 56], [128, 255, 107]]])\n >>> gray = grayscale(img)\n >>> binary = binarize(gray)\n >>> morphological = opening_filter(binary)\n >>> get_distances(get_descriptors(\n ... binary_mask(gray, morphological), (0, 1)),\n ... index)\n [(0, 0.0), (1, 0.0), (2, 0.0), (3, 0.0), (4, 0.0), (5, 0.0), \\\n(6, 0.0), (7, 0.0), (8, 0.0), (9, 0.0), (10, 0.0), (11, 0.0), (12, 0.0), \\\n(13, 0.0), (14, 0.0), (15, 0.0)]\n \"\"\"\n distances = np.array(\n [euclidean(descriptor, descriptors[base]) for descriptor in descriptors]\n )\n # Normalize distances between range [0, 1]\n normalized_distances: list[float] = normalize_array(distances, 1).tolist()\n enum_distances = list(enumerate(normalized_distances))\n enum_distances.sort(key=lambda tup: tup[1], reverse=True)\n return enum_distances\n\n\nif __name__ == \"__main__\":\n # Index to compare haralick descriptors to\n index = int(input())\n q_value_list = [int(value) for value in input().split()]\n q_value = (q_value_list[0], q_value_list[1])\n\n # Format is the respective filter to apply,\n # can be either 1 for the opening filter or else for the closing\n parameters = {\"format\": int(input()), \"threshold\": int(input())}\n\n # Number of images to perform methods on\n b_number = int(input())\n\n files, descriptors = [], []\n\n for _ in range(b_number):\n file = input().rstrip()\n files.append(file)\n\n # Open given image and calculate morphological filter,\n # respective masks and correspondent Harralick Descriptors.\n image = imageio.imread(file).astype(np.float32)\n gray = grayscale(image)\n threshold = binarize(gray, parameters[\"threshold\"])\n\n morphological = (\n opening_filter(threshold)\n if parameters[\"format\"] == 1\n else closing_filter(threshold)\n )\n masks = binary_mask(gray, morphological)\n descriptors.append(get_descriptors(masks, q_value))\n\n # Transform ordered distances array into a sequence of indexes\n # corresponding to original file position\n distances = get_distances(np.array(descriptors), index)\n indexed_distances = np.array(distances).astype(np.uint8)[:, 0]\n\n # Finally, print distances considering the Haralick descriptions from the base\n # file to all other images using the morphology method of choice.\n print(f\"Query: {files[index]}\")\n print(\"Ranking:\")\n for idx, file_idx in enumerate(indexed_distances):\n print(f\"({idx}) {files[file_idx]}\", end=\"\\n\")\n"} +{"Prompt":"Harris Corner Detector https:en.wikipedia.orgwikiHarrisCornerDetector k : is an empirically determined constant in 0.04,0.06 windowsize : neighbourhoods considered Returns the image with corners identified imgpath : path of the image output : list of the corner positions, image Can change the value","Completions":"import cv2\nimport numpy as np\n\n\"\"\"\nHarris Corner Detector\nhttps:\/\/en.wikipedia.org\/wiki\/Harris_Corner_Detector\n\"\"\"\n\n\nclass HarrisCorner:\n def __init__(self, k: float, window_size: int):\n \"\"\"\n k : is an empirically determined constant in [0.04,0.06]\n window_size : neighbourhoods considered\n \"\"\"\n\n if k in (0.04, 0.06):\n self.k = k\n self.window_size = window_size\n else:\n raise ValueError(\"invalid k value\")\n\n def __str__(self) -> str:\n return str(self.k)\n\n def detect(self, img_path: str) -> tuple[cv2.Mat, list[list[int]]]:\n \"\"\"\n Returns the image with corners identified\n img_path : path of the image\n output : list of the corner positions, image\n \"\"\"\n\n img = cv2.imread(img_path, 0)\n h, w = img.shape\n corner_list: list[list[int]] = []\n color_img = img.copy()\n color_img = cv2.cvtColor(color_img, cv2.COLOR_GRAY2RGB)\n dy, dx = np.gradient(img)\n ixx = dx**2\n iyy = dy**2\n ixy = dx * dy\n k = 0.04\n offset = self.window_size \/\/ 2\n for y in range(offset, h - offset):\n for x in range(offset, w - offset):\n wxx = ixx[\n y - offset : y + offset + 1, x - offset : x + offset + 1\n ].sum()\n wyy = iyy[\n y - offset : y + offset + 1, x - offset : x + offset + 1\n ].sum()\n wxy = ixy[\n y - offset : y + offset + 1, x - offset : x + offset + 1\n ].sum()\n\n det = (wxx * wyy) - (wxy**2)\n trace = wxx + wyy\n r = det - k * (trace**2)\n # Can change the value\n if r > 0.5:\n corner_list.append([x, y, r])\n color_img.itemset((y, x, 0), 0)\n color_img.itemset((y, x, 1), 0)\n color_img.itemset((y, x, 2), 255)\n return color_img, corner_list\n\n\nif __name__ == \"__main__\":\n edge_detect = HarrisCorner(0.04, 3)\n color_img, _ = edge_detect.detect(\"path_to_image\")\n cv2.imwrite(\"detect.png\", color_img)\n"} +{"Prompt":"The HornSchunck method estimates the optical flow for every single pixel of a sequence of images. It works by assuming brightness constancy between two consecutive frames and smoothness in the optical flow. Useful resources: Wikipedia: https:en.wikipedia.orgwikiHornE28093Schunckmethod Paper: http:image.diku.dkimagecanonmaterialHornSchunckOpticalFlow.pdf Warps the pixels of an image into a new image using the horizontal and vertical flows. Pixels that are warped from an invalid location are set to 0. Parameters: image: Grayscale image horizontalflow: Horizontal flow verticalflow: Vertical flow Returns: Warped image warpnp.array0, 1, 2, 0, 3, 0, 2, 2, 2, np.array0, 1, 1, 1, 0, 0, 1, 1, 1, np.array0, 0, 0, 0, 1, 0, 0, 0, 1 array0, 0, 0, 3, 1, 0, 0, 2, 3 Create a grid of all pixel coordinates and subtract the flow to get the target pixels coordinates Find the locations outside of the original image Set pixels at invalid locations to 0 This function performs the HornSchunck algorithm and returns the estimated optical flow. It is assumed that the input images are grayscale and normalized to be in 0, 1. Parameters: image0: First image of the sequence image1: Second image of the sequence alpha: Regularization constant numiter: Number of iterations performed Returns: estimated horizontal vertical flow np.roundhornschuncknp.array0, 0, 2, 0, 0, 2, np.array0, 2, 0, 0, 2, 0, alpha0.1, numiter110. astypenp.int32 array 0, 1, 1, 0, 1, 1, BLANKLINE 0, 0, 0, 0, 0, 0, dtypeint32 Initialize flow Prepare kernels for the calculation of the derivatives and the average velocity Iteratively refine the flow This updates the flow as proposed in the paper Step 12","Completions":"from typing import SupportsIndex\n\nimport numpy as np\nfrom scipy.ndimage import convolve\n\n\ndef warp(\n image: np.ndarray, horizontal_flow: np.ndarray, vertical_flow: np.ndarray\n) -> np.ndarray:\n \"\"\"\n Warps the pixels of an image into a new image using the horizontal and vertical\n flows.\n Pixels that are warped from an invalid location are set to 0.\n\n Parameters:\n image: Grayscale image\n horizontal_flow: Horizontal flow\n vertical_flow: Vertical flow\n\n Returns: Warped image\n\n >>> warp(np.array([[0, 1, 2], [0, 3, 0], [2, 2, 2]]), \\\n np.array([[0, 1, -1], [-1, 0, 0], [1, 1, 1]]), \\\n np.array([[0, 0, 0], [0, 1, 0], [0, 0, 1]]))\n array([[0, 0, 0],\n [3, 1, 0],\n [0, 2, 3]])\n \"\"\"\n flow = np.stack((horizontal_flow, vertical_flow), 2)\n\n # Create a grid of all pixel coordinates and subtract the flow to get the\n # target pixels coordinates\n grid = np.stack(\n np.meshgrid(np.arange(0, image.shape[1]), np.arange(0, image.shape[0])), 2\n )\n grid = np.round(grid - flow).astype(np.int32)\n\n # Find the locations outside of the original image\n invalid = (grid < 0) | (grid >= np.array([image.shape[1], image.shape[0]]))\n grid[invalid] = 0\n\n warped = image[grid[:, :, 1], grid[:, :, 0]]\n\n # Set pixels at invalid locations to 0\n warped[invalid[:, :, 0] | invalid[:, :, 1]] = 0\n\n return warped\n\n\ndef horn_schunck(\n image0: np.ndarray,\n image1: np.ndarray,\n num_iter: SupportsIndex,\n alpha: float | None = None,\n) -> tuple[np.ndarray, np.ndarray]:\n \"\"\"\n This function performs the Horn-Schunck algorithm and returns the estimated\n optical flow. It is assumed that the input images are grayscale and\n normalized to be in [0, 1].\n\n Parameters:\n image0: First image of the sequence\n image1: Second image of the sequence\n alpha: Regularization constant\n num_iter: Number of iterations performed\n\n Returns: estimated horizontal & vertical flow\n\n >>> np.round(horn_schunck(np.array([[0, 0, 2], [0, 0, 2]]), \\\n np.array([[0, 2, 0], [0, 2, 0]]), alpha=0.1, num_iter=110)).\\\n astype(np.int32)\n array([[[ 0, -1, -1],\n [ 0, -1, -1]],\n \n [[ 0, 0, 0],\n [ 0, 0, 0]]], dtype=int32)\n \"\"\"\n if alpha is None:\n alpha = 0.1\n\n # Initialize flow\n horizontal_flow = np.zeros_like(image0)\n vertical_flow = np.zeros_like(image0)\n\n # Prepare kernels for the calculation of the derivatives and the average velocity\n kernel_x = np.array([[-1, 1], [-1, 1]]) * 0.25\n kernel_y = np.array([[-1, -1], [1, 1]]) * 0.25\n kernel_t = np.array([[1, 1], [1, 1]]) * 0.25\n kernel_laplacian = np.array(\n [[1 \/ 12, 1 \/ 6, 1 \/ 12], [1 \/ 6, 0, 1 \/ 6], [1 \/ 12, 1 \/ 6, 1 \/ 12]]\n )\n\n # Iteratively refine the flow\n for _ in range(num_iter):\n warped_image = warp(image0, horizontal_flow, vertical_flow)\n derivative_x = convolve(warped_image, kernel_x) + convolve(image1, kernel_x)\n derivative_y = convolve(warped_image, kernel_y) + convolve(image1, kernel_y)\n derivative_t = convolve(warped_image, kernel_t) + convolve(image1, -kernel_t)\n\n avg_horizontal_velocity = convolve(horizontal_flow, kernel_laplacian)\n avg_vertical_velocity = convolve(vertical_flow, kernel_laplacian)\n\n # This updates the flow as proposed in the paper (Step 12)\n update = (\n derivative_x * avg_horizontal_velocity\n + derivative_y * avg_vertical_velocity\n + derivative_t\n )\n update = update \/ (alpha**2 + derivative_x**2 + derivative_y**2)\n\n horizontal_flow = avg_horizontal_velocity - derivative_x * update\n vertical_flow = avg_vertical_velocity - derivative_y * update\n\n return horizontal_flow, vertical_flow\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Mean thresholding algorithm for image processing https:en.wikipedia.orgwikiThresholdingimageprocessing image: is a grayscale PIL image object","Completions":"from PIL import Image\n\n\"\"\"\nMean thresholding algorithm for image processing\nhttps:\/\/en.wikipedia.org\/wiki\/Thresholding_(image_processing)\n\"\"\"\n\n\ndef mean_threshold(image: Image) -> Image:\n \"\"\"\n image: is a grayscale PIL image object\n \"\"\"\n height, width = image.size\n mean = 0\n pixels = image.load()\n for i in range(width):\n for j in range(height):\n pixel = pixels[j, i]\n mean += pixel\n mean \/\/= width * height\n\n for j in range(width):\n for i in range(height):\n pixels[i, j] = 255 if pixels[i, j] > mean else 0\n return image\n\n\nif __name__ == \"__main__\":\n image = mean_threshold(Image.open(\"path_to_image\").convert(\"L\"))\n image.save(\"output_image_path\")\n"} +{"Prompt":"Source: https:github.comjason9075opencvmosaicdataaug import glob import os import random from string import asciilowercase, digits import cv2 import numpy as np Parameters OUTPUTSIZE 720, 1280 Height, Width SCALERANGE 0.4, 0.6 if height or width lower than this scale, drop it. FILTERTINYSCALE 1 100 LABELDIR IMGDIR OUTPUTDIR NUMBERIMAGES 250 def main None: imgpaths, annos getdatasetLABELDIR, IMGDIR for index in rangeNUMBERIMAGES: idxs random.samplerangelenannos, 4 newimage, newannos, path updateimageandanno imgpaths, annos, idxs, OUTPUTSIZE, SCALERANGE, filterscaleFILTERTINYSCALE, Get random string code: '7b7ad245cdff75241935e4dd860f3bad' lettercode randomchars32 filename path.splitos.sep1.rsplit., 10 fileroot fOUTPUTDIRfilenameMOSAIClettercode cv2.imwriteffileroot.jpg, newimage, cv2.IMWRITEJPEGQUALITY, 85 printfSucceeded index1NUMBERIMAGES with filename annoslist for anno in newannos: width anno3 anno1 height anno4 anno2 xcenter anno1 width 2 ycenter anno2 height 2 obj fanno0 xcenter ycenter width height annoslist.appendobj with openffileroot.txt, w as outfile: outfile.writen.joinline for line in annoslist def getdatasetlabeldir: str, imgdir: str tuplelist, list: imgpaths labels for labelfile in glob.globos.path.joinlabeldir, .txt: labelname labelfile.splitos.sep1.rsplit., 10 with openlabelfile as infile: objlists infile.readlines imgpath os.path.joinimgdir, flabelname.jpg boxes for objlist in objlists: obj objlist.rstripn.split xmin floatobj1 floatobj3 2 ymin floatobj2 floatobj4 2 xmax floatobj1 floatobj3 2 ymax floatobj2 floatobj4 2 boxes.appendintobj0, xmin, ymin, xmax, ymax if not boxes: continue imgpaths.appendimgpath labels.appendboxes return imgpaths, labels def updateimageandanno allimglist: list, allannos: list, idxs: listint, outputsize: tupleint, int, scalerange: tuplefloat, float, filterscale: float 0.0, tuplelist, list, str: outputimg np.zerosoutputsize0, outputsize1, 3, dtypenp.uint8 scalex scalerange0 random.random scalerange1 scalerange0 scaley scalerange0 random.random scalerange1 scalerange0 dividpointx intscalex outputsize1 dividpointy intscaley outputsize0 newanno pathlist for i, index in enumerateidxs: path allimglistindex pathlist.appendpath imgannos allannosindex img cv2.imreadpath if i 0: topleft img cv2.resizeimg, dividpointx, dividpointy outputimg:dividpointy, :dividpointx, : img for bbox in imgannos: xmin bbox1 scalex ymin bbox2 scaley xmax bbox3 scalex ymax bbox4 scaley newanno.appendbbox0, xmin, ymin, xmax, ymax elif i 1: topright img cv2.resizeimg, outputsize1 dividpointx, dividpointy outputimg:dividpointy, dividpointx : outputsize1, : img for bbox in imgannos: xmin scalex bbox1 1 scalex ymin bbox2 scaley xmax scalex bbox3 1 scalex ymax bbox4 scaley newanno.appendbbox0, xmin, ymin, xmax, ymax elif i 2: bottomleft img cv2.resizeimg, dividpointx, outputsize0 dividpointy outputimgdividpointy : outputsize0, :dividpointx, : img for bbox in imgannos: xmin bbox1 scalex ymin scaley bbox2 1 scaley xmax bbox3 scalex ymax scaley bbox4 1 scaley newanno.appendbbox0, xmin, ymin, xmax, ymax else: bottomright img cv2.resize img, outputsize1 dividpointx, outputsize0 dividpointy outputimg dividpointy : outputsize0, dividpointx : outputsize1, : img for bbox in imgannos: xmin scalex bbox1 1 scalex ymin scaley bbox2 1 scaley xmax scalex bbox3 1 scalex ymax scaley bbox4 1 scaley newanno.appendbbox0, xmin, ymin, xmax, ymax Remove bounding box small than scale of filter if filterscale 0: newanno anno for anno in newanno if filterscale anno3 anno1 and filterscale anno4 anno2 return outputimg, newanno, pathlist0 def randomcharsnumberchar: int str: assert numberchar 1, The number of character should greater than 1 lettercode asciilowercase digits return .joinrandom.choicelettercode for in rangenumberchar if name main: main printDONE","Completions":"import glob\nimport os\nimport random\nfrom string import ascii_lowercase, digits\n\nimport cv2\nimport numpy as np\n\n# Parameters\nOUTPUT_SIZE = (720, 1280) # Height, Width\nSCALE_RANGE = (0.4, 0.6) # if height or width lower than this scale, drop it.\nFILTER_TINY_SCALE = 1 \/ 100\nLABEL_DIR = \"\"\nIMG_DIR = \"\"\nOUTPUT_DIR = \"\"\nNUMBER_IMAGES = 250\n\n\ndef main() -> None:\n \"\"\"\n Get images list and annotations list from input dir.\n Update new images and annotations.\n Save images and annotations in output dir.\n \"\"\"\n img_paths, annos = get_dataset(LABEL_DIR, IMG_DIR)\n for index in range(NUMBER_IMAGES):\n idxs = random.sample(range(len(annos)), 4)\n new_image, new_annos, path = update_image_and_anno(\n img_paths,\n annos,\n idxs,\n OUTPUT_SIZE,\n SCALE_RANGE,\n filter_scale=FILTER_TINY_SCALE,\n )\n\n # Get random string code: '7b7ad245cdff75241935e4dd860f3bad'\n letter_code = random_chars(32)\n file_name = path.split(os.sep)[-1].rsplit(\".\", 1)[0]\n file_root = f\"{OUTPUT_DIR}\/{file_name}_MOSAIC_{letter_code}\"\n cv2.imwrite(f\"{file_root}.jpg\", new_image, [cv2.IMWRITE_JPEG_QUALITY, 85])\n print(f\"Succeeded {index+1}\/{NUMBER_IMAGES} with {file_name}\")\n annos_list = []\n for anno in new_annos:\n width = anno[3] - anno[1]\n height = anno[4] - anno[2]\n x_center = anno[1] + width \/ 2\n y_center = anno[2] + height \/ 2\n obj = f\"{anno[0]} {x_center} {y_center} {width} {height}\"\n annos_list.append(obj)\n with open(f\"{file_root}.txt\", \"w\") as outfile:\n outfile.write(\"\\n\".join(line for line in annos_list))\n\n\ndef get_dataset(label_dir: str, img_dir: str) -> tuple[list, list]:\n \"\"\"\n - label_dir : Path to label include annotation of images\n - img_dir : Path to folder contain images\n Return : List of images path and labels\n \"\"\"\n img_paths = []\n labels = []\n for label_file in glob.glob(os.path.join(label_dir, \"*.txt\")):\n label_name = label_file.split(os.sep)[-1].rsplit(\".\", 1)[0]\n with open(label_file) as in_file:\n obj_lists = in_file.readlines()\n img_path = os.path.join(img_dir, f\"{label_name}.jpg\")\n\n boxes = []\n for obj_list in obj_lists:\n obj = obj_list.rstrip(\"\\n\").split(\" \")\n xmin = float(obj[1]) - float(obj[3]) \/ 2\n ymin = float(obj[2]) - float(obj[4]) \/ 2\n xmax = float(obj[1]) + float(obj[3]) \/ 2\n ymax = float(obj[2]) + float(obj[4]) \/ 2\n\n boxes.append([int(obj[0]), xmin, ymin, xmax, ymax])\n if not boxes:\n continue\n img_paths.append(img_path)\n labels.append(boxes)\n return img_paths, labels\n\n\ndef update_image_and_anno(\n all_img_list: list,\n all_annos: list,\n idxs: list[int],\n output_size: tuple[int, int],\n scale_range: tuple[float, float],\n filter_scale: float = 0.0,\n) -> tuple[list, list, str]:\n \"\"\"\n - all_img_list : list of all images\n - all_annos : list of all annotations of specific image\n - idxs : index of image in list\n - output_size : size of output image (Height, Width)\n - scale_range : range of scale image\n - filter_scale : the condition of downscale image and bounding box\n Return:\n - output_img : image after resize\n - new_anno : list of new annotation after scale\n - path[0] : get the name of image file\n \"\"\"\n output_img = np.zeros([output_size[0], output_size[1], 3], dtype=np.uint8)\n scale_x = scale_range[0] + random.random() * (scale_range[1] - scale_range[0])\n scale_y = scale_range[0] + random.random() * (scale_range[1] - scale_range[0])\n divid_point_x = int(scale_x * output_size[1])\n divid_point_y = int(scale_y * output_size[0])\n\n new_anno = []\n path_list = []\n for i, index in enumerate(idxs):\n path = all_img_list[index]\n path_list.append(path)\n img_annos = all_annos[index]\n img = cv2.imread(path)\n if i == 0: # top-left\n img = cv2.resize(img, (divid_point_x, divid_point_y))\n output_img[:divid_point_y, :divid_point_x, :] = img\n for bbox in img_annos:\n xmin = bbox[1] * scale_x\n ymin = bbox[2] * scale_y\n xmax = bbox[3] * scale_x\n ymax = bbox[4] * scale_y\n new_anno.append([bbox[0], xmin, ymin, xmax, ymax])\n elif i == 1: # top-right\n img = cv2.resize(img, (output_size[1] - divid_point_x, divid_point_y))\n output_img[:divid_point_y, divid_point_x : output_size[1], :] = img\n for bbox in img_annos:\n xmin = scale_x + bbox[1] * (1 - scale_x)\n ymin = bbox[2] * scale_y\n xmax = scale_x + bbox[3] * (1 - scale_x)\n ymax = bbox[4] * scale_y\n new_anno.append([bbox[0], xmin, ymin, xmax, ymax])\n elif i == 2: # bottom-left\n img = cv2.resize(img, (divid_point_x, output_size[0] - divid_point_y))\n output_img[divid_point_y : output_size[0], :divid_point_x, :] = img\n for bbox in img_annos:\n xmin = bbox[1] * scale_x\n ymin = scale_y + bbox[2] * (1 - scale_y)\n xmax = bbox[3] * scale_x\n ymax = scale_y + bbox[4] * (1 - scale_y)\n new_anno.append([bbox[0], xmin, ymin, xmax, ymax])\n else: # bottom-right\n img = cv2.resize(\n img, (output_size[1] - divid_point_x, output_size[0] - divid_point_y)\n )\n output_img[\n divid_point_y : output_size[0], divid_point_x : output_size[1], :\n ] = img\n for bbox in img_annos:\n xmin = scale_x + bbox[1] * (1 - scale_x)\n ymin = scale_y + bbox[2] * (1 - scale_y)\n xmax = scale_x + bbox[3] * (1 - scale_x)\n ymax = scale_y + bbox[4] * (1 - scale_y)\n new_anno.append([bbox[0], xmin, ymin, xmax, ymax])\n\n # Remove bounding box small than scale of filter\n if filter_scale > 0:\n new_anno = [\n anno\n for anno in new_anno\n if filter_scale < (anno[3] - anno[1]) and filter_scale < (anno[4] - anno[2])\n ]\n\n return output_img, new_anno, path_list[0]\n\n\ndef random_chars(number_char: int) -> str:\n \"\"\"\n Automatic generate random 32 characters.\n Get random string code: '7b7ad245cdff75241935e4dd860f3bad'\n >>> len(random_chars(32))\n 32\n \"\"\"\n assert number_char > 1, \"The number of character should greater than 1\"\n letter_code = ascii_lowercase + digits\n return \"\".join(random.choice(letter_code) for _ in range(number_char))\n\n\nif __name__ == \"__main__\":\n main()\n print(\"DONE \u2705\")\n"} +{"Prompt":"Source : https:computersciencewiki.orgindex.phpMaxpoolingPooling Importing the libraries Maxpooling Function This function is used to perform maxpooling on the input array of 2D matriximage Args: arr: numpy array size: size of pooling matrix stride: the number of pixels shifts over the input matrix Returns: numpy array of maxpooled matrix Sample Input Output: maxpooling1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16, 2, 2 array 6., 8., 14., 16. maxpooling147, 180, 122,241, 76, 32,126, 13, 157, 2, 1 array241., 180., 241., 157. compute the shape of the output matrix initialize the output matrix with zeros of shape maxpoolshape if the end of the matrix is reached, break if the end of the matrix is reached, break compute the maximum of the pooling matrix shift the pooling matrix by stride of column pixels shift the pooling matrix by stride of row pixels reset the column index to 0 Averagepooling Function This function is used to perform avgpooling on the input array of 2D matriximage Args: arr: numpy array size: size of pooling matrix stride: the number of pixels shifts over the input matrix Returns: numpy array of avgpooled matrix Sample Input Output: avgpooling1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16, 2, 2 array 3., 5., 11., 13. avgpooling147, 180, 122,241, 76, 32,126, 13, 157, 2, 1 array161., 102., 114., 69. compute the shape of the output matrix initialize the output matrix with zeros of shape avgpoolshape if the end of the matrix is reached, break if the end of the matrix is reached, break compute the average of the pooling matrix shift the pooling matrix by stride of column pixels shift the pooling matrix by stride of row pixels reset the column index to 0 Main Function Loading the image Converting the image to numpy array and maxpooling, displaying the result Ensure that the image is a square matrix Converting the image to numpy array and averagepooling, displaying the result Ensure that the image is a square matrix","Completions":"# Source : https:\/\/computersciencewiki.org\/index.php\/Max-pooling_\/_Pooling\n# Importing the libraries\nimport numpy as np\nfrom PIL import Image\n\n\n# Maxpooling Function\ndef maxpooling(arr: np.ndarray, size: int, stride: int) -> np.ndarray:\n \"\"\"\n This function is used to perform maxpooling on the input array of 2D matrix(image)\n Args:\n arr: numpy array\n size: size of pooling matrix\n stride: the number of pixels shifts over the input matrix\n Returns:\n numpy array of maxpooled matrix\n Sample Input Output:\n >>> maxpooling([[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]], 2, 2)\n array([[ 6., 8.],\n [14., 16.]])\n >>> maxpooling([[147, 180, 122],[241, 76, 32],[126, 13, 157]], 2, 1)\n array([[241., 180.],\n [241., 157.]])\n \"\"\"\n arr = np.array(arr)\n if arr.shape[0] != arr.shape[1]:\n raise ValueError(\"The input array is not a square matrix\")\n i = 0\n j = 0\n mat_i = 0\n mat_j = 0\n\n # compute the shape of the output matrix\n maxpool_shape = (arr.shape[0] - size) \/\/ stride + 1\n # initialize the output matrix with zeros of shape maxpool_shape\n updated_arr = np.zeros((maxpool_shape, maxpool_shape))\n\n while i < arr.shape[0]:\n if i + size > arr.shape[0]:\n # if the end of the matrix is reached, break\n break\n while j < arr.shape[1]:\n # if the end of the matrix is reached, break\n if j + size > arr.shape[1]:\n break\n # compute the maximum of the pooling matrix\n updated_arr[mat_i][mat_j] = np.max(arr[i : i + size, j : j + size])\n # shift the pooling matrix by stride of column pixels\n j += stride\n mat_j += 1\n\n # shift the pooling matrix by stride of row pixels\n i += stride\n mat_i += 1\n\n # reset the column index to 0\n j = 0\n mat_j = 0\n\n return updated_arr\n\n\n# Averagepooling Function\ndef avgpooling(arr: np.ndarray, size: int, stride: int) -> np.ndarray:\n \"\"\"\n This function is used to perform avgpooling on the input array of 2D matrix(image)\n Args:\n arr: numpy array\n size: size of pooling matrix\n stride: the number of pixels shifts over the input matrix\n Returns:\n numpy array of avgpooled matrix\n Sample Input Output:\n >>> avgpooling([[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]], 2, 2)\n array([[ 3., 5.],\n [11., 13.]])\n >>> avgpooling([[147, 180, 122],[241, 76, 32],[126, 13, 157]], 2, 1)\n array([[161., 102.],\n [114., 69.]])\n \"\"\"\n arr = np.array(arr)\n if arr.shape[0] != arr.shape[1]:\n raise ValueError(\"The input array is not a square matrix\")\n i = 0\n j = 0\n mat_i = 0\n mat_j = 0\n\n # compute the shape of the output matrix\n avgpool_shape = (arr.shape[0] - size) \/\/ stride + 1\n # initialize the output matrix with zeros of shape avgpool_shape\n updated_arr = np.zeros((avgpool_shape, avgpool_shape))\n\n while i < arr.shape[0]:\n # if the end of the matrix is reached, break\n if i + size > arr.shape[0]:\n break\n while j < arr.shape[1]:\n # if the end of the matrix is reached, break\n if j + size > arr.shape[1]:\n break\n # compute the average of the pooling matrix\n updated_arr[mat_i][mat_j] = int(np.average(arr[i : i + size, j : j + size]))\n # shift the pooling matrix by stride of column pixels\n j += stride\n mat_j += 1\n\n # shift the pooling matrix by stride of row pixels\n i += stride\n mat_i += 1\n # reset the column index to 0\n j = 0\n mat_j = 0\n\n return updated_arr\n\n\n# Main Function\nif __name__ == \"__main__\":\n from doctest import testmod\n\n testmod(name=\"avgpooling\", verbose=True)\n\n # Loading the image\n image = Image.open(\"path_to_image\")\n\n # Converting the image to numpy array and maxpooling, displaying the result\n # Ensure that the image is a square matrix\n\n Image.fromarray(maxpooling(np.array(image), size=3, stride=2)).show()\n\n # Converting the image to numpy array and averagepooling, displaying the result\n # Ensure that the image is a square matrix\n\n Image.fromarray(avgpooling(np.array(image), size=3, stride=2)).show()\n"} +{"Prompt":"Conversion of length units. Available Units: Metre, Kilometre, Megametre, Gigametre, Terametre, Petametre, Exametre, Zettametre, Yottametre USAGE : Import this file into their respective project. Use the function lengthconversion for conversion of length units. Parameters : value : The number of from units you want to convert fromtype : From which type you want to convert totype : To which type you want to convert REFERENCES : Wikipedia reference: https:en.wikipedia.orgwikiMeter Wikipedia reference: https:en.wikipedia.orgwikiKilometer Wikipedia reference: https:en.wikipedia.orgwikiOrdersofmagnitudelength Exponent of the factormeter Conversion between astronomical length units. lengthconversion1, meter, kilometer 0.001 lengthconversion1, meter, megametre 1e06 lengthconversion1, gigametre, meter 1000000000 lengthconversion1, gigametre, terametre 0.001 lengthconversion1, petametre, terametre 1000 lengthconversion1, petametre, exametre 0.001 lengthconversion1, terametre, zettametre 1e09 lengthconversion1, yottametre, zettametre 1000 lengthconversion4, wrongUnit, inch Traceback most recent call last: ... ValueError: Invalid 'fromtype' value: 'wrongUnit'. Conversion abbreviations are: m, km, Mm, Gm, Tm, Pm, Em, Zm, Ym","Completions":"UNIT_SYMBOL = {\n \"meter\": \"m\",\n \"kilometer\": \"km\",\n \"megametre\": \"Mm\",\n \"gigametre\": \"Gm\",\n \"terametre\": \"Tm\",\n \"petametre\": \"Pm\",\n \"exametre\": \"Em\",\n \"zettametre\": \"Zm\",\n \"yottametre\": \"Ym\",\n}\n# Exponent of the factor(meter)\nMETRIC_CONVERSION = {\n \"m\": 0,\n \"km\": 3,\n \"Mm\": 6,\n \"Gm\": 9,\n \"Tm\": 12,\n \"Pm\": 15,\n \"Em\": 18,\n \"Zm\": 21,\n \"Ym\": 24,\n}\n\n\ndef length_conversion(value: float, from_type: str, to_type: str) -> float:\n \"\"\"\n Conversion between astronomical length units.\n\n >>> length_conversion(1, \"meter\", \"kilometer\")\n 0.001\n >>> length_conversion(1, \"meter\", \"megametre\")\n 1e-06\n >>> length_conversion(1, \"gigametre\", \"meter\")\n 1000000000\n >>> length_conversion(1, \"gigametre\", \"terametre\")\n 0.001\n >>> length_conversion(1, \"petametre\", \"terametre\")\n 1000\n >>> length_conversion(1, \"petametre\", \"exametre\")\n 0.001\n >>> length_conversion(1, \"terametre\", \"zettametre\")\n 1e-09\n >>> length_conversion(1, \"yottametre\", \"zettametre\")\n 1000\n >>> length_conversion(4, \"wrongUnit\", \"inch\")\n Traceback (most recent call last):\n ...\n ValueError: Invalid 'from_type' value: 'wrongUnit'.\n Conversion abbreviations are: m, km, Mm, Gm, Tm, Pm, Em, Zm, Ym\n \"\"\"\n\n from_sanitized = from_type.lower().strip(\"s\")\n to_sanitized = to_type.lower().strip(\"s\")\n\n from_sanitized = UNIT_SYMBOL.get(from_sanitized, from_sanitized)\n to_sanitized = UNIT_SYMBOL.get(to_sanitized, to_sanitized)\n\n if from_sanitized not in METRIC_CONVERSION:\n msg = (\n f\"Invalid 'from_type' value: {from_type!r}.\\n\"\n f\"Conversion abbreviations are: {', '.join(METRIC_CONVERSION)}\"\n )\n raise ValueError(msg)\n if to_sanitized not in METRIC_CONVERSION:\n msg = (\n f\"Invalid 'to_type' value: {to_type!r}.\\n\"\n f\"Conversion abbreviations are: {', '.join(METRIC_CONVERSION)}\"\n )\n raise ValueError(msg)\n from_exponent = METRIC_CONVERSION[from_sanitized]\n to_exponent = METRIC_CONVERSION[to_sanitized]\n exponent = 1\n\n if from_exponent > to_exponent:\n exponent = from_exponent - to_exponent\n else:\n exponent = -(to_exponent - from_exponent)\n\n return value * pow(10, exponent)\n\n\nif __name__ == \"__main__\":\n from doctest import testmod\n\n testmod()\n"} +{"Prompt":"Convert a binary value to its decimal equivalent bintodecimal101 5 bintodecimal 1010 10 bintodecimal11101 29 bintodecimal0 0 bintodecimala Traceback most recent call last: ... ValueError: Nonbinary value was passed to the function bintodecimal Traceback most recent call last: ... ValueError: Empty string was passed to the function bintodecimal39 Traceback most recent call last: ... ValueError: Nonbinary value was passed to the function","Completions":"def bin_to_decimal(bin_string: str) -> int:\n \"\"\"\n Convert a binary value to its decimal equivalent\n\n >>> bin_to_decimal(\"101\")\n 5\n >>> bin_to_decimal(\" 1010 \")\n 10\n >>> bin_to_decimal(\"-11101\")\n -29\n >>> bin_to_decimal(\"0\")\n 0\n >>> bin_to_decimal(\"a\")\n Traceback (most recent call last):\n ...\n ValueError: Non-binary value was passed to the function\n >>> bin_to_decimal(\"\")\n Traceback (most recent call last):\n ...\n ValueError: Empty string was passed to the function\n >>> bin_to_decimal(\"39\")\n Traceback (most recent call last):\n ...\n ValueError: Non-binary value was passed to the function\n \"\"\"\n bin_string = str(bin_string).strip()\n if not bin_string:\n raise ValueError(\"Empty string was passed to the function\")\n is_negative = bin_string[0] == \"-\"\n if is_negative:\n bin_string = bin_string[1:]\n if not all(char in \"01\" for char in bin_string):\n raise ValueError(\"Non-binary value was passed to the function\")\n decimal_number = 0\n for char in bin_string:\n decimal_number = 2 * decimal_number + int(char)\n return -decimal_number if is_negative else decimal_number\n\n\nif __name__ == \"__main__\":\n from doctest import testmod\n\n testmod()\n"} +{"Prompt":"Converting a binary string into hexadecimal using Grouping Method bintohexadecimal'101011111' '0x15f' bintohexadecimal' 1010 ' '0x0a' bintohexadecimal'11101' '0x1d' bintohexadecimal'a' Traceback most recent call last: ... ValueError: Nonbinary value was passed to the function bintohexadecimal'' Traceback most recent call last: ... ValueError: Empty string was passed to the function Sanitising parameter Exceptions","Completions":"BITS_TO_HEX = {\n \"0000\": \"0\",\n \"0001\": \"1\",\n \"0010\": \"2\",\n \"0011\": \"3\",\n \"0100\": \"4\",\n \"0101\": \"5\",\n \"0110\": \"6\",\n \"0111\": \"7\",\n \"1000\": \"8\",\n \"1001\": \"9\",\n \"1010\": \"a\",\n \"1011\": \"b\",\n \"1100\": \"c\",\n \"1101\": \"d\",\n \"1110\": \"e\",\n \"1111\": \"f\",\n}\n\n\ndef bin_to_hexadecimal(binary_str: str) -> str:\n \"\"\"\n Converting a binary string into hexadecimal using Grouping Method\n\n >>> bin_to_hexadecimal('101011111')\n '0x15f'\n >>> bin_to_hexadecimal(' 1010 ')\n '0x0a'\n >>> bin_to_hexadecimal('-11101')\n '-0x1d'\n >>> bin_to_hexadecimal('a')\n Traceback (most recent call last):\n ...\n ValueError: Non-binary value was passed to the function\n >>> bin_to_hexadecimal('')\n Traceback (most recent call last):\n ...\n ValueError: Empty string was passed to the function\n \"\"\"\n # Sanitising parameter\n binary_str = str(binary_str).strip()\n\n # Exceptions\n if not binary_str:\n raise ValueError(\"Empty string was passed to the function\")\n is_negative = binary_str[0] == \"-\"\n binary_str = binary_str[1:] if is_negative else binary_str\n if not all(char in \"01\" for char in binary_str):\n raise ValueError(\"Non-binary value was passed to the function\")\n\n binary_str = (\n \"0\" * (4 * (divmod(len(binary_str), 4)[0] + 1) - len(binary_str)) + binary_str\n )\n\n hexadecimal = []\n for x in range(0, len(binary_str), 4):\n hexadecimal.append(BITS_TO_HEX[binary_str[x : x + 4]])\n hexadecimal_str = \"0x\" + \"\".join(hexadecimal)\n\n return \"-\" + hexadecimal_str if is_negative else hexadecimal_str\n\n\nif __name__ == \"__main__\":\n from doctest import testmod\n\n testmod()\n"} +{"Prompt":"The function below will convert any binary string to the octal equivalent. bintooctal1111 '17' bintooctal101010101010011 '52523' bintooctal Traceback most recent call last: ... ValueError: Empty string was passed to the function bintooctala1 Traceback most recent call last: ... ValueError: Nonbinary value was passed to the function","Completions":"def bin_to_octal(bin_string: str) -> str:\n if not all(char in \"01\" for char in bin_string):\n raise ValueError(\"Non-binary value was passed to the function\")\n if not bin_string:\n raise ValueError(\"Empty string was passed to the function\")\n oct_string = \"\"\n while len(bin_string) % 3 != 0:\n bin_string = \"0\" + bin_string\n bin_string_in_3_list = [\n bin_string[index : index + 3]\n for index in range(len(bin_string))\n if index % 3 == 0\n ]\n for bin_group in bin_string_in_3_list:\n oct_val = 0\n for index, val in enumerate(bin_group):\n oct_val += int(2 ** (2 - index) * int(val))\n oct_string += str(oct_val)\n return oct_string\n\n\nif __name__ == \"__main__\":\n from doctest import testmod\n\n testmod()\n"} +{"Prompt":"Convert a positive Decimal Number to Any Other Representation from string import asciiuppercase ALPHABETVALUES strordc 55: c for c in asciiuppercase def decimaltoanynum: int, base: int str: if isinstancenum, float: raise TypeErrorint can't convert nonstring with explicit base if num 0: raise ValueErrorparameter must be positive int if isinstancebase, str: raise TypeError'str' object cannot be interpreted as an integer if isinstancebase, float: raise TypeError'float' object cannot be interpreted as an integer if base in 0, 1: raise ValueErrorbase must be 2 if base 36: raise ValueErrorbase must be 36 newvalue mod 0 div 0 while div ! 1: div, mod divmodnum, base if base 11 and 9 mod 36: actualvalue ALPHABETVALUESstrmod else: actualvalue strmod newvalue actualvalue div num base num div if div 0: return strnewvalue::1 elif div 1: newvalue strdiv return strnewvalue::1 return newvalue::1 if name main: import doctest doctest.testmod for base in range2, 37: for num in range1000: assert intdecimaltoanynum, base, base num, num, base, decimaltoanynum, base, intdecimaltoanynum, base, base,","Completions":"from string import ascii_uppercase\n\nALPHABET_VALUES = {str(ord(c) - 55): c for c in ascii_uppercase}\n\n\ndef decimal_to_any(num: int, base: int) -> str:\n \"\"\"\n Convert a positive integer to another base as str.\n >>> decimal_to_any(0, 2)\n '0'\n >>> decimal_to_any(5, 4)\n '11'\n >>> decimal_to_any(20, 3)\n '202'\n >>> decimal_to_any(58, 16)\n '3A'\n >>> decimal_to_any(243, 17)\n 'E5'\n >>> decimal_to_any(34923, 36)\n 'QY3'\n >>> decimal_to_any(10, 11)\n 'A'\n >>> decimal_to_any(16, 16)\n '10'\n >>> decimal_to_any(36, 36)\n '10'\n >>> # negatives will error\n >>> decimal_to_any(-45, 8) # doctest: +ELLIPSIS\n Traceback (most recent call last):\n ...\n ValueError: parameter must be positive int\n >>> # floats will error\n >>> decimal_to_any(34.4, 6) # doctest: +ELLIPSIS\n Traceback (most recent call last):\n ...\n TypeError: int() can't convert non-string with explicit base\n >>> # a float base will error\n >>> decimal_to_any(5, 2.5) # doctest: +ELLIPSIS\n Traceback (most recent call last):\n ...\n TypeError: 'float' object cannot be interpreted as an integer\n >>> # a str base will error\n >>> decimal_to_any(10, '16') # doctest: +ELLIPSIS\n Traceback (most recent call last):\n ...\n TypeError: 'str' object cannot be interpreted as an integer\n >>> # a base less than 2 will error\n >>> decimal_to_any(7, 0) # doctest: +ELLIPSIS\n Traceback (most recent call last):\n ...\n ValueError: base must be >= 2\n >>> # a base greater than 36 will error\n >>> decimal_to_any(34, 37) # doctest: +ELLIPSIS\n Traceback (most recent call last):\n ...\n ValueError: base must be <= 36\n \"\"\"\n if isinstance(num, float):\n raise TypeError(\"int() can't convert non-string with explicit base\")\n if num < 0:\n raise ValueError(\"parameter must be positive int\")\n if isinstance(base, str):\n raise TypeError(\"'str' object cannot be interpreted as an integer\")\n if isinstance(base, float):\n raise TypeError(\"'float' object cannot be interpreted as an integer\")\n if base in (0, 1):\n raise ValueError(\"base must be >= 2\")\n if base > 36:\n raise ValueError(\"base must be <= 36\")\n new_value = \"\"\n mod = 0\n div = 0\n while div != 1:\n div, mod = divmod(num, base)\n if base >= 11 and 9 < mod < 36:\n actual_value = ALPHABET_VALUES[str(mod)]\n else:\n actual_value = str(mod)\n new_value += actual_value\n div = num \/\/ base\n num = div\n if div == 0:\n return str(new_value[::-1])\n elif div == 1:\n new_value += str(div)\n return str(new_value[::-1])\n\n return new_value[::-1]\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n\n for base in range(2, 37):\n for num in range(1000):\n assert int(decimal_to_any(num, base), base) == num, (\n num,\n base,\n decimal_to_any(num, base),\n int(decimal_to_any(num, base), base),\n )\n"} +{"Prompt":"Convert a Decimal Number to a Binary Number. def decimaltobinaryiterativenum: int str: if isinstancenum, float: raise TypeError'float' object cannot be interpreted as an integer if isinstancenum, str: raise TypeError'str' object cannot be interpreted as an integer if num 0: return 0b0 negative False if num 0: negative True num num binary: listint while num 0: binary.insert0, num 2 num 1 if negative: return 0b .joinstre for e in binary return 0b .joinstre for e in binary def decimaltobinaryrecursivehelperdecimal: int str: decimal intdecimal if decimal in 0, 1: Exit cases for the recursion return strdecimal div, mod divmoddecimal, 2 return decimaltobinaryrecursivehelperdiv strmod def decimaltobinaryrecursivenumber: str str: number strnumber.strip if not number: raise ValueErrorNo input value was provided negative if number.startswith else number number.lstrip if not number.isnumeric: raise ValueErrorInput value is not an integer return fnegative0bdecimaltobinaryrecursivehelperintnumber if name main: import doctest doctest.testmod printdecimaltobinaryrecursiveinputInput a decimal number:","Completions":"def decimal_to_binary_iterative(num: int) -> str:\n \"\"\"\n Convert an Integer Decimal Number to a Binary Number as str.\n >>> decimal_to_binary_iterative(0)\n '0b0'\n >>> decimal_to_binary_iterative(2)\n '0b10'\n >>> decimal_to_binary_iterative(7)\n '0b111'\n >>> decimal_to_binary_iterative(35)\n '0b100011'\n >>> # negatives work too\n >>> decimal_to_binary_iterative(-2)\n '-0b10'\n >>> # other floats will error\n >>> decimal_to_binary_iterative(16.16) # doctest: +ELLIPSIS\n Traceback (most recent call last):\n ...\n TypeError: 'float' object cannot be interpreted as an integer\n >>> # strings will error as well\n >>> decimal_to_binary_iterative('0xfffff') # doctest: +ELLIPSIS\n Traceback (most recent call last):\n ...\n TypeError: 'str' object cannot be interpreted as an integer\n \"\"\"\n\n if isinstance(num, float):\n raise TypeError(\"'float' object cannot be interpreted as an integer\")\n if isinstance(num, str):\n raise TypeError(\"'str' object cannot be interpreted as an integer\")\n\n if num == 0:\n return \"0b0\"\n\n negative = False\n\n if num < 0:\n negative = True\n num = -num\n\n binary: list[int] = []\n while num > 0:\n binary.insert(0, num % 2)\n num >>= 1\n\n if negative:\n return \"-0b\" + \"\".join(str(e) for e in binary)\n\n return \"0b\" + \"\".join(str(e) for e in binary)\n\n\ndef decimal_to_binary_recursive_helper(decimal: int) -> str:\n \"\"\"\n Take a positive integer value and return its binary equivalent.\n >>> decimal_to_binary_recursive_helper(1000)\n '1111101000'\n >>> decimal_to_binary_recursive_helper(\"72\")\n '1001000'\n >>> decimal_to_binary_recursive_helper(\"number\")\n Traceback (most recent call last):\n ...\n ValueError: invalid literal for int() with base 10: 'number'\n \"\"\"\n decimal = int(decimal)\n if decimal in (0, 1): # Exit cases for the recursion\n return str(decimal)\n div, mod = divmod(decimal, 2)\n return decimal_to_binary_recursive_helper(div) + str(mod)\n\n\ndef decimal_to_binary_recursive(number: str) -> str:\n \"\"\"\n Take an integer value and raise ValueError for wrong inputs,\n call the function above and return the output with prefix \"0b\" & \"-0b\"\n for positive and negative integers respectively.\n >>> decimal_to_binary_recursive(0)\n '0b0'\n >>> decimal_to_binary_recursive(40)\n '0b101000'\n >>> decimal_to_binary_recursive(-40)\n '-0b101000'\n >>> decimal_to_binary_recursive(40.8)\n Traceback (most recent call last):\n ...\n ValueError: Input value is not an integer\n >>> decimal_to_binary_recursive(\"forty\")\n Traceback (most recent call last):\n ...\n ValueError: Input value is not an integer\n \"\"\"\n number = str(number).strip()\n if not number:\n raise ValueError(\"No input value was provided\")\n negative = \"-\" if number.startswith(\"-\") else \"\"\n number = number.lstrip(\"-\")\n if not number.isnumeric():\n raise ValueError(\"Input value is not an integer\")\n return f\"{negative}0b{decimal_to_binary_recursive_helper(int(number))}\"\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n\n print(decimal_to_binary_recursive(input(\"Input a decimal number: \")))\n"} +{"Prompt":"Convert Base 10 Decimal Values to Hexadecimal Representations set decimal value for each hexadecimal digit values 0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, 10: a, 11: b, 12: c, 13: d, 14: e, 15: f, def decimaltohexadecimaldecimal: float str: assert isinstancedecimal, int, float assert decimal intdecimal decimal intdecimal hexadecimal negative False if decimal 0: negative True decimal 1 while decimal 0: decimal, remainder divmoddecimal, 16 hexadecimal valuesremainder hexadecimal hexadecimal 0x hexadecimal if negative: hexadecimal hexadecimal return hexadecimal if name main: import doctest doctest.testmod","Completions":"# set decimal value for each hexadecimal digit\nvalues = {\n 0: \"0\",\n 1: \"1\",\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 10: \"a\",\n 11: \"b\",\n 12: \"c\",\n 13: \"d\",\n 14: \"e\",\n 15: \"f\",\n}\n\n\ndef decimal_to_hexadecimal(decimal: float) -> str:\n \"\"\"\n take integer decimal value, return hexadecimal representation as str beginning\n with 0x\n >>> decimal_to_hexadecimal(5)\n '0x5'\n >>> decimal_to_hexadecimal(15)\n '0xf'\n >>> decimal_to_hexadecimal(37)\n '0x25'\n >>> decimal_to_hexadecimal(255)\n '0xff'\n >>> decimal_to_hexadecimal(4096)\n '0x1000'\n >>> decimal_to_hexadecimal(999098)\n '0xf3eba'\n >>> # negatives work too\n >>> decimal_to_hexadecimal(-256)\n '-0x100'\n >>> # floats are acceptable if equivalent to an int\n >>> decimal_to_hexadecimal(17.0)\n '0x11'\n >>> # other floats will error\n >>> decimal_to_hexadecimal(16.16) # doctest: +ELLIPSIS\n Traceback (most recent call last):\n ...\n AssertionError\n >>> # strings will error as well\n >>> decimal_to_hexadecimal('0xfffff') # doctest: +ELLIPSIS\n Traceback (most recent call last):\n ...\n AssertionError\n >>> # results are the same when compared to Python's default hex function\n >>> decimal_to_hexadecimal(-256) == hex(-256)\n True\n \"\"\"\n assert isinstance(decimal, (int, float))\n assert decimal == int(decimal)\n decimal = int(decimal)\n hexadecimal = \"\"\n negative = False\n if decimal < 0:\n negative = True\n decimal *= -1\n while decimal > 0:\n decimal, remainder = divmod(decimal, 16)\n hexadecimal = values[remainder] + hexadecimal\n hexadecimal = \"0x\" + hexadecimal\n if negative:\n hexadecimal = \"-\" + hexadecimal\n return hexadecimal\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Convert a Decimal Number to an Octal Number. import math Modified from: https:github.comTheAlgorithmsJavascriptblobmasterConversionsDecimalToOctal.js def decimaltooctalnum: int str: octal 0 counter 0 while num 0: remainder num 8 octal octal remainder math.floormath.pow10, counter counter 1 num math.floornum 8 basically 8 without remainder if any This formatting removes trailing '.0' from octal. return f0ointoctal def main None:","Completions":"import math\n\n# Modified from:\n# https:\/\/github.com\/TheAlgorithms\/Javascript\/blob\/master\/Conversions\/DecimalToOctal.js\n\n\ndef decimal_to_octal(num: int) -> str:\n \"\"\"Convert a Decimal Number to an Octal Number.\n\n >>> all(decimal_to_octal(i) == oct(i) for i\n ... in (0, 2, 8, 64, 65, 216, 255, 256, 512))\n True\n \"\"\"\n octal = 0\n counter = 0\n while num > 0:\n remainder = num % 8\n octal = octal + (remainder * math.floor(math.pow(10, counter)))\n counter += 1\n num = math.floor(num \/ 8) # basically \/= 8 without remainder if any\n # This formatting removes trailing '.0' from `octal`.\n return f\"0o{int(octal)}\"\n\n\ndef main() -> None:\n \"\"\"Print octal equivalents of decimal numbers.\"\"\"\n print(\"\\n2 in octal is:\")\n print(decimal_to_octal(2)) # = 2\n print(\"\\n8 in octal is:\")\n print(decimal_to_octal(8)) # = 10\n print(\"\\n65 in octal is:\")\n print(decimal_to_octal(65)) # = 101\n print(\"\\n216 in octal is:\")\n print(decimal_to_octal(216)) # = 330\n print(\"\\n512 in octal is:\")\n print(decimal_to_octal(512)) # = 1000\n print(\"\\n\")\n\n\nif __name__ == \"__main__\":\n main()\n"} +{"Prompt":"Conversion of energy units. Available units: joule, kilojoule, megajoule, gigajoule, wattsecond, watthour, kilowatthour, newtonmeter, calorienutr, kilocalorienutr, electronvolt, britishthermalunitit, footpound USAGE : Import this file into their respective project. Use the function energyconversion for conversion of energy units. Parameters : fromtype : From which type you want to convert totype : To which type you want to convert value : the value which you want to convert REFERENCES : Wikipedia reference: https:en.wikipedia.orgwikiUnitsofenergy Wikipedia reference: https:en.wikipedia.orgwikiJoule Wikipedia reference: https:en.wikipedia.orgwikiKilowatthour Wikipedia reference: https:en.wikipedia.orgwikiNewtonmetre Wikipedia reference: https:en.wikipedia.orgwikiCalorie Wikipedia reference: https:en.wikipedia.orgwikiElectronvolt Wikipedia reference: https:en.wikipedia.orgwikiBritishthermalunit Wikipedia reference: https:en.wikipedia.orgwikiFootpoundenergy Unit converter reference: https:www.unitconverters.netenergyconverter.html Conversion of energy units. energyconversionjoule, joule, 1 1.0 energyconversionjoule, kilojoule, 1 0.001 energyconversionjoule, megajoule, 1 1e06 energyconversionjoule, gigajoule, 1 1e09 energyconversionjoule, wattsecond, 1 1.0 energyconversionjoule, watthour, 1 0.0002777777777777778 energyconversionjoule, kilowatthour, 1 2.7777777777777776e07 energyconversionjoule, newtonmeter, 1 1.0 energyconversionjoule, calorienutr, 1 0.00023884589662749592 energyconversionjoule, kilocalorienutr, 1 2.388458966274959e07 energyconversionjoule, electronvolt, 1 6.241509074460763e18 energyconversionjoule, britishthermalunitit, 1 0.0009478171226670134 energyconversionjoule, footpound, 1 0.7375621211696556 energyconversionjoule, megajoule, 1000 0.001 energyconversioncalorienutr, kilocalorienutr, 1000 1.0 energyconversionkilowatthour, joule, 10 36000000.0 energyconversionbritishthermalunitit, footpound, 1 778.1692306784539 energyconversionwatthour, joule, a doctest: ELLIPSIS Traceback most recent call last: ... TypeError: unsupported operand types for : 'str' and 'float' energyconversionwrongunit, joule, 1 doctest: ELLIPSIS Traceback most recent call last: ... ValueError: Incorrect 'fromtype' or 'totype' value: 'wrongunit', 'joule' Valid values are: joule, ... footpound energyconversionjoule, wrongunit, 1 doctest: ELLIPSIS Traceback most recent call last: ... ValueError: Incorrect 'fromtype' or 'totype' value: 'joule', 'wrongunit' Valid values are: joule, ... footpound energyconversion123, abc, 1 doctest: ELLIPSIS Traceback most recent call last: ... ValueError: Incorrect 'fromtype' or 'totype' value: '123', 'abc' Valid values are: joule, ... footpound","Completions":"ENERGY_CONVERSION: dict[str, float] = {\n \"joule\": 1.0,\n \"kilojoule\": 1_000,\n \"megajoule\": 1_000_000,\n \"gigajoule\": 1_000_000_000,\n \"wattsecond\": 1.0,\n \"watthour\": 3_600,\n \"kilowatthour\": 3_600_000,\n \"newtonmeter\": 1.0,\n \"calorie_nutr\": 4_186.8,\n \"kilocalorie_nutr\": 4_186_800.00,\n \"electronvolt\": 1.602_176_634e-19,\n \"britishthermalunit_it\": 1_055.055_85,\n \"footpound\": 1.355_818,\n}\n\n\ndef energy_conversion(from_type: str, to_type: str, value: float) -> float:\n \"\"\"\n Conversion of energy units.\n >>> energy_conversion(\"joule\", \"joule\", 1)\n 1.0\n >>> energy_conversion(\"joule\", \"kilojoule\", 1)\n 0.001\n >>> energy_conversion(\"joule\", \"megajoule\", 1)\n 1e-06\n >>> energy_conversion(\"joule\", \"gigajoule\", 1)\n 1e-09\n >>> energy_conversion(\"joule\", \"wattsecond\", 1)\n 1.0\n >>> energy_conversion(\"joule\", \"watthour\", 1)\n 0.0002777777777777778\n >>> energy_conversion(\"joule\", \"kilowatthour\", 1)\n 2.7777777777777776e-07\n >>> energy_conversion(\"joule\", \"newtonmeter\", 1)\n 1.0\n >>> energy_conversion(\"joule\", \"calorie_nutr\", 1)\n 0.00023884589662749592\n >>> energy_conversion(\"joule\", \"kilocalorie_nutr\", 1)\n 2.388458966274959e-07\n >>> energy_conversion(\"joule\", \"electronvolt\", 1)\n 6.241509074460763e+18\n >>> energy_conversion(\"joule\", \"britishthermalunit_it\", 1)\n 0.0009478171226670134\n >>> energy_conversion(\"joule\", \"footpound\", 1)\n 0.7375621211696556\n >>> energy_conversion(\"joule\", \"megajoule\", 1000)\n 0.001\n >>> energy_conversion(\"calorie_nutr\", \"kilocalorie_nutr\", 1000)\n 1.0\n >>> energy_conversion(\"kilowatthour\", \"joule\", 10)\n 36000000.0\n >>> energy_conversion(\"britishthermalunit_it\", \"footpound\", 1)\n 778.1692306784539\n >>> energy_conversion(\"watthour\", \"joule\", \"a\") # doctest: +ELLIPSIS\n Traceback (most recent call last):\n ...\n TypeError: unsupported operand type(s) for \/: 'str' and 'float'\n >>> energy_conversion(\"wrongunit\", \"joule\", 1) # doctest: +ELLIPSIS\n Traceback (most recent call last):\n ...\n ValueError: Incorrect 'from_type' or 'to_type' value: 'wrongunit', 'joule'\n Valid values are: joule, ... footpound\n >>> energy_conversion(\"joule\", \"wrongunit\", 1) # doctest: +ELLIPSIS\n Traceback (most recent call last):\n ...\n ValueError: Incorrect 'from_type' or 'to_type' value: 'joule', 'wrongunit'\n Valid values are: joule, ... footpound\n >>> energy_conversion(\"123\", \"abc\", 1) # doctest: +ELLIPSIS\n Traceback (most recent call last):\n ...\n ValueError: Incorrect 'from_type' or 'to_type' value: '123', 'abc'\n Valid values are: joule, ... footpound\n \"\"\"\n if to_type not in ENERGY_CONVERSION or from_type not in ENERGY_CONVERSION:\n msg = (\n f\"Incorrect 'from_type' or 'to_type' value: {from_type!r}, {to_type!r}\\n\"\n f\"Valid values are: {', '.join(ENERGY_CONVERSION)}\"\n )\n raise ValueError(msg)\n return value * ENERGY_CONVERSION[from_type] \/ ENERGY_CONVERSION[to_type]\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Given a string columntitle that represents the column title in an Excel sheet, return its corresponding column number. exceltitletocolumnA 1 exceltitletocolumnB 2 exceltitletocolumnAB 28 exceltitletocolumnZ 26","Completions":"def excel_title_to_column(column_title: str) -> int:\n \"\"\"\n Given a string column_title that represents\n the column title in an Excel sheet, return\n its corresponding column number.\n\n >>> excel_title_to_column(\"A\")\n 1\n >>> excel_title_to_column(\"B\")\n 2\n >>> excel_title_to_column(\"AB\")\n 28\n >>> excel_title_to_column(\"Z\")\n 26\n \"\"\"\n assert column_title.isupper()\n answer = 0\n index = len(column_title) - 1\n power = 0\n\n while index >= 0:\n value = (ord(column_title[index]) - 64) * pow(26, power)\n answer += value\n power += 1\n index -= 1\n\n return answer\n\n\nif __name__ == \"__main__\":\n from doctest import testmod\n\n testmod()\n"} +{"Prompt":"Convert a hexadecimal value to its binary equivalent https:stackoverflow.comquestions1425493converthextobinary Here, we have used the bitwise right shift operator: Shifts the bits of the number to the right and fills 0 on voids left as a result. Similar effect as of dividing the number with some power of two. Example: a 10 a 1 5 hextobinAC 10101100 hextobin9A4 100110100100 hextobin 12f 100101111 hextobinFfFf 1111111111111111 hextobinfFfF 1111111111111111 hextobinFf Traceback most recent call last: ... ValueError: Invalid value was passed to the function hextobin Traceback most recent call last: ... ValueError: No value was passed to the function","Completions":"def hex_to_bin(hex_num: str) -> int:\n \"\"\"\n Convert a hexadecimal value to its binary equivalent\n #https:\/\/stackoverflow.com\/questions\/1425493\/convert-hex-to-binary\n Here, we have used the bitwise right shift operator: >>\n Shifts the bits of the number to the right and fills 0 on voids left as a result.\n Similar effect as of dividing the number with some power of two.\n Example:\n a = 10\n a >> 1 = 5\n\n >>> hex_to_bin(\"AC\")\n 10101100\n >>> hex_to_bin(\"9A4\")\n 100110100100\n >>> hex_to_bin(\" 12f \")\n 100101111\n >>> hex_to_bin(\"FfFf\")\n 1111111111111111\n >>> hex_to_bin(\"-fFfF\")\n -1111111111111111\n >>> hex_to_bin(\"F-f\")\n Traceback (most recent call last):\n ...\n ValueError: Invalid value was passed to the function\n >>> hex_to_bin(\"\")\n Traceback (most recent call last):\n ...\n ValueError: No value was passed to the function\n \"\"\"\n\n hex_num = hex_num.strip()\n if not hex_num:\n raise ValueError(\"No value was passed to the function\")\n\n is_negative = hex_num[0] == \"-\"\n if is_negative:\n hex_num = hex_num[1:]\n\n try:\n int_num = int(hex_num, 16)\n except ValueError:\n raise ValueError(\"Invalid value was passed to the function\")\n\n bin_str = \"\"\n while int_num > 0:\n bin_str = str(int_num % 2) + bin_str\n int_num >>= 1\n\n return int((\"-\" + bin_str) if is_negative else bin_str)\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Convert a hexadecimal value to its decimal equivalent https:www.programiz.compythonprogrammingmethodsbuiltinhex hextodecimala 10 hextodecimal12f 303 hextodecimal 12f 303 hextodecimalFfFf 65535 hextodecimalFf 255 hextodecimalFf Traceback most recent call last: ... ValueError: Nonhexadecimal value was passed to the function hextodecimal Traceback most recent call last: ... ValueError: Empty string was passed to the function hextodecimal12m Traceback most recent call last: ... ValueError: Nonhexadecimal value was passed to the function","Completions":"hex_table = {hex(i)[2:]: i for i in range(16)} # Use [:2] to strip off the leading '0x'\n\n\ndef hex_to_decimal(hex_string: str) -> int:\n \"\"\"\n Convert a hexadecimal value to its decimal equivalent\n #https:\/\/www.programiz.com\/python-programming\/methods\/built-in\/hex\n\n >>> hex_to_decimal(\"a\")\n 10\n >>> hex_to_decimal(\"12f\")\n 303\n >>> hex_to_decimal(\" 12f \")\n 303\n >>> hex_to_decimal(\"FfFf\")\n 65535\n >>> hex_to_decimal(\"-Ff\")\n -255\n >>> hex_to_decimal(\"F-f\")\n Traceback (most recent call last):\n ...\n ValueError: Non-hexadecimal value was passed to the function\n >>> hex_to_decimal(\"\")\n Traceback (most recent call last):\n ...\n ValueError: Empty string was passed to the function\n >>> hex_to_decimal(\"12m\")\n Traceback (most recent call last):\n ...\n ValueError: Non-hexadecimal value was passed to the function\n \"\"\"\n hex_string = hex_string.strip().lower()\n if not hex_string:\n raise ValueError(\"Empty string was passed to the function\")\n is_negative = hex_string[0] == \"-\"\n if is_negative:\n hex_string = hex_string[1:]\n if not all(char in hex_table for char in hex_string):\n raise ValueError(\"Non-hexadecimal value was passed to the function\")\n decimal_number = 0\n for char in hex_string:\n decimal_number = 16 * decimal_number + hex_table[char]\n return -decimal_number if is_negative else decimal_number\n\n\nif __name__ == \"__main__\":\n from doctest import testmod\n\n testmod()\n"} +{"Prompt":"https:www.geeksforgeeks.orgconvertipaddresstointegerandviceversa Convert an IPv4 address to its decimal representation. Args: ipaddress: A string representing an IPv4 address e.g., 192.168.0.1. Returns: int: The decimal representation of the IP address. ipv4todecimal192.168.0.1 3232235521 ipv4todecimal10.0.0.255 167772415 ipv4todecimal10.0.255 Traceback most recent call last: ... ValueError: Invalid IPv4 address format ipv4todecimal10.0.0.256 Traceback most recent call last: ... ValueError: Invalid IPv4 octet 256 altipv4todecimal192.168.0.1 3232235521 altipv4todecimal10.0.0.255 167772415 Convert a decimal representation of an IP address to its IPv4 format. Args: decimalipv4: An integer representing the decimal IP address. Returns: The IPv4 representation of the decimal IP address. decimaltoipv43232235521 '192.168.0.1' decimaltoipv4167772415 '10.0.0.255' decimaltoipv41 Traceback most recent call last: ... ValueError: Invalid decimal IPv4 address","Completions":"# https:\/\/www.geeksforgeeks.org\/convert-ip-address-to-integer-and-vice-versa\/\n\n\ndef ipv4_to_decimal(ipv4_address: str) -> int:\n \"\"\"\n Convert an IPv4 address to its decimal representation.\n\n Args:\n ip_address: A string representing an IPv4 address (e.g., \"192.168.0.1\").\n\n Returns:\n int: The decimal representation of the IP address.\n\n >>> ipv4_to_decimal(\"192.168.0.1\")\n 3232235521\n >>> ipv4_to_decimal(\"10.0.0.255\")\n 167772415\n >>> ipv4_to_decimal(\"10.0.255\")\n Traceback (most recent call last):\n ...\n ValueError: Invalid IPv4 address format\n >>> ipv4_to_decimal(\"10.0.0.256\")\n Traceback (most recent call last):\n ...\n ValueError: Invalid IPv4 octet 256\n \"\"\"\n\n octets = [int(octet) for octet in ipv4_address.split(\".\")]\n if len(octets) != 4:\n raise ValueError(\"Invalid IPv4 address format\")\n\n decimal_ipv4 = 0\n for octet in octets:\n if not 0 <= octet <= 255:\n raise ValueError(f\"Invalid IPv4 octet {octet}\") # noqa: EM102\n decimal_ipv4 = (decimal_ipv4 << 8) + int(octet)\n\n return decimal_ipv4\n\n\ndef alt_ipv4_to_decimal(ipv4_address: str) -> int:\n \"\"\"\n >>> alt_ipv4_to_decimal(\"192.168.0.1\")\n 3232235521\n >>> alt_ipv4_to_decimal(\"10.0.0.255\")\n 167772415\n \"\"\"\n return int(\"0x\" + \"\".join(f\"{int(i):02x}\" for i in ipv4_address.split(\".\")), 16)\n\n\ndef decimal_to_ipv4(decimal_ipv4: int) -> str:\n \"\"\"\n Convert a decimal representation of an IP address to its IPv4 format.\n\n Args:\n decimal_ipv4: An integer representing the decimal IP address.\n\n Returns:\n The IPv4 representation of the decimal IP address.\n\n >>> decimal_to_ipv4(3232235521)\n '192.168.0.1'\n >>> decimal_to_ipv4(167772415)\n '10.0.0.255'\n >>> decimal_to_ipv4(-1)\n Traceback (most recent call last):\n ...\n ValueError: Invalid decimal IPv4 address\n \"\"\"\n\n if not (0 <= decimal_ipv4 <= 4294967295):\n raise ValueError(\"Invalid decimal IPv4 address\")\n\n ip_parts = []\n for _ in range(4):\n ip_parts.append(str(decimal_ipv4 & 255))\n decimal_ipv4 >>= 8\n\n return \".\".join(reversed(ip_parts))\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Conversion of length units. Available Units: Metre,Kilometre,Feet,Inch,Centimeter,Yard,Foot,Mile,Millimeter USAGE : Import this file into their respective project. Use the function lengthconversion for conversion of length units. Parameters : value : The number of from units you want to convert fromtype : From which type you want to convert totype : To which type you want to convert REFERENCES : Wikipedia reference: https:en.wikipedia.orgwikiMeter Wikipedia reference: https:en.wikipedia.orgwikiKilometer Wikipedia reference: https:en.wikipedia.orgwikiFeet Wikipedia reference: https:en.wikipedia.orgwikiInch Wikipedia reference: https:en.wikipedia.orgwikiCentimeter Wikipedia reference: https:en.wikipedia.orgwikiYard Wikipedia reference: https:en.wikipedia.orgwikiFoot Wikipedia reference: https:en.wikipedia.orgwikiMile Wikipedia reference: https:en.wikipedia.orgwikiMillimeter Conversion between length units. lengthconversion4, METER, FEET 13.12336 lengthconversion4, M, FT 13.12336 lengthconversion1, meter, kilometer 0.001 lengthconversion1, kilometer, inch 39370.1 lengthconversion3, kilometer, mile 1.8641130000000001 lengthconversion2, feet, meter 0.6096 lengthconversion4, feet, yard 1.333329312 lengthconversion1, inch, meter 0.0254 lengthconversion2, inch, mile 3.15656468e05 lengthconversion2, centimeter, millimeter 20.0 lengthconversion2, centimeter, yard 0.0218722 lengthconversion4, yard, meter 3.6576 lengthconversion4, yard, kilometer 0.0036576 lengthconversion3, foot, meter 0.9144000000000001 lengthconversion3, foot, inch 36.00001944 lengthconversion4, mile, kilometer 6.43736 lengthconversion2, miles, InChEs 126719.753468 lengthconversion3, millimeter, centimeter 0.3 lengthconversion3, mm, in 0.1181103 lengthconversion4, wrongUnit, inch Traceback most recent call last: ... ValueError: Invalid 'fromtype' value: 'wrongUnit'. Conversion abbreviations are: mm, cm, m, km, in, ft, yd, mi","Completions":"from typing import NamedTuple\n\n\nclass FromTo(NamedTuple):\n from_factor: float\n to_factor: float\n\n\nTYPE_CONVERSION = {\n \"millimeter\": \"mm\",\n \"centimeter\": \"cm\",\n \"meter\": \"m\",\n \"kilometer\": \"km\",\n \"inch\": \"in\",\n \"inche\": \"in\", # Trailing 's' has been stripped off\n \"feet\": \"ft\",\n \"foot\": \"ft\",\n \"yard\": \"yd\",\n \"mile\": \"mi\",\n}\n\nMETRIC_CONVERSION = {\n \"mm\": FromTo(0.001, 1000),\n \"cm\": FromTo(0.01, 100),\n \"m\": FromTo(1, 1),\n \"km\": FromTo(1000, 0.001),\n \"in\": FromTo(0.0254, 39.3701),\n \"ft\": FromTo(0.3048, 3.28084),\n \"yd\": FromTo(0.9144, 1.09361),\n \"mi\": FromTo(1609.34, 0.000621371),\n}\n\n\ndef length_conversion(value: float, from_type: str, to_type: str) -> float:\n \"\"\"\n Conversion between length units.\n\n >>> length_conversion(4, \"METER\", \"FEET\")\n 13.12336\n >>> length_conversion(4, \"M\", \"FT\")\n 13.12336\n >>> length_conversion(1, \"meter\", \"kilometer\")\n 0.001\n >>> length_conversion(1, \"kilometer\", \"inch\")\n 39370.1\n >>> length_conversion(3, \"kilometer\", \"mile\")\n 1.8641130000000001\n >>> length_conversion(2, \"feet\", \"meter\")\n 0.6096\n >>> length_conversion(4, \"feet\", \"yard\")\n 1.333329312\n >>> length_conversion(1, \"inch\", \"meter\")\n 0.0254\n >>> length_conversion(2, \"inch\", \"mile\")\n 3.15656468e-05\n >>> length_conversion(2, \"centimeter\", \"millimeter\")\n 20.0\n >>> length_conversion(2, \"centimeter\", \"yard\")\n 0.0218722\n >>> length_conversion(4, \"yard\", \"meter\")\n 3.6576\n >>> length_conversion(4, \"yard\", \"kilometer\")\n 0.0036576\n >>> length_conversion(3, \"foot\", \"meter\")\n 0.9144000000000001\n >>> length_conversion(3, \"foot\", \"inch\")\n 36.00001944\n >>> length_conversion(4, \"mile\", \"kilometer\")\n 6.43736\n >>> length_conversion(2, \"miles\", \"InChEs\")\n 126719.753468\n >>> length_conversion(3, \"millimeter\", \"centimeter\")\n 0.3\n >>> length_conversion(3, \"mm\", \"in\")\n 0.1181103\n >>> length_conversion(4, \"wrongUnit\", \"inch\")\n Traceback (most recent call last):\n ...\n ValueError: Invalid 'from_type' value: 'wrongUnit'.\n Conversion abbreviations are: mm, cm, m, km, in, ft, yd, mi\n \"\"\"\n new_from = from_type.lower().rstrip(\"s\")\n new_from = TYPE_CONVERSION.get(new_from, new_from)\n new_to = to_type.lower().rstrip(\"s\")\n new_to = TYPE_CONVERSION.get(new_to, new_to)\n if new_from not in METRIC_CONVERSION:\n msg = (\n f\"Invalid 'from_type' value: {from_type!r}.\\n\"\n f\"Conversion abbreviations are: {', '.join(METRIC_CONVERSION)}\"\n )\n raise ValueError(msg)\n if new_to not in METRIC_CONVERSION:\n msg = (\n f\"Invalid 'to_type' value: {to_type!r}.\\n\"\n f\"Conversion abbreviations are: {', '.join(METRIC_CONVERSION)}\"\n )\n raise ValueError(msg)\n return (\n value\n * METRIC_CONVERSION[new_from].from_factor\n * METRIC_CONVERSION[new_to].to_factor\n )\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Functions useful for doing molecular chemistry: molaritytonormality molestopressure molestovolume pressureandvolumetotemperature Convert molarity to normality. Volume is taken in litres. Wikipedia reference: https:en.wikipedia.orgwikiEquivalentconcentration Wikipedia reference: https:en.wikipedia.orgwikiMolarconcentration molaritytonormality2, 3.1, 0.31 20 molaritytonormality4, 11.4, 5.7 8 Convert moles to pressure. Ideal gas laws are used. Temperature is taken in kelvin. Volume is taken in litres. Pressure has atm as SI unit. Wikipedia reference: https:en.wikipedia.orgwikiGaslaws Wikipedia reference: https:en.wikipedia.orgwikiPressure Wikipedia reference: https:en.wikipedia.orgwikiTemperature molestopressure0.82, 3, 300 90 molestopressure8.2, 5, 200 10 Convert moles to volume. Ideal gas laws are used. Temperature is taken in kelvin. Volume is taken in litres. Pressure has atm as SI unit. Wikipedia reference: https:en.wikipedia.orgwikiGaslaws Wikipedia reference: https:en.wikipedia.orgwikiPressure Wikipedia reference: https:en.wikipedia.orgwikiTemperature molestovolume0.82, 3, 300 90 molestovolume8.2, 5, 200 10 Convert pressure and volume to temperature. Ideal gas laws are used. Temperature is taken in kelvin. Volume is taken in litres. Pressure has atm as SI unit. Wikipedia reference: https:en.wikipedia.orgwikiGaslaws Wikipedia reference: https:en.wikipedia.orgwikiPressure Wikipedia reference: https:en.wikipedia.orgwikiTemperature pressureandvolumetotemperature0.82, 1, 2 20 pressureandvolumetotemperature8.2, 5, 3 60","Completions":"def molarity_to_normality(nfactor: int, moles: float, volume: float) -> float:\n \"\"\"\n Convert molarity to normality.\n Volume is taken in litres.\n\n Wikipedia reference: https:\/\/en.wikipedia.org\/wiki\/Equivalent_concentration\n Wikipedia reference: https:\/\/en.wikipedia.org\/wiki\/Molar_concentration\n\n >>> molarity_to_normality(2, 3.1, 0.31)\n 20\n >>> molarity_to_normality(4, 11.4, 5.7)\n 8\n \"\"\"\n return round(float(moles \/ volume) * nfactor)\n\n\ndef moles_to_pressure(volume: float, moles: float, temperature: float) -> float:\n \"\"\"\n Convert moles to pressure.\n Ideal gas laws are used.\n Temperature is taken in kelvin.\n Volume is taken in litres.\n Pressure has atm as SI unit.\n\n Wikipedia reference: https:\/\/en.wikipedia.org\/wiki\/Gas_laws\n Wikipedia reference: https:\/\/en.wikipedia.org\/wiki\/Pressure\n Wikipedia reference: https:\/\/en.wikipedia.org\/wiki\/Temperature\n\n >>> moles_to_pressure(0.82, 3, 300)\n 90\n >>> moles_to_pressure(8.2, 5, 200)\n 10\n \"\"\"\n return round(float((moles * 0.0821 * temperature) \/ (volume)))\n\n\ndef moles_to_volume(pressure: float, moles: float, temperature: float) -> float:\n \"\"\"\n Convert moles to volume.\n Ideal gas laws are used.\n Temperature is taken in kelvin.\n Volume is taken in litres.\n Pressure has atm as SI unit.\n\n Wikipedia reference: https:\/\/en.wikipedia.org\/wiki\/Gas_laws\n Wikipedia reference: https:\/\/en.wikipedia.org\/wiki\/Pressure\n Wikipedia reference: https:\/\/en.wikipedia.org\/wiki\/Temperature\n\n >>> moles_to_volume(0.82, 3, 300)\n 90\n >>> moles_to_volume(8.2, 5, 200)\n 10\n \"\"\"\n return round(float((moles * 0.0821 * temperature) \/ (pressure)))\n\n\ndef pressure_and_volume_to_temperature(\n pressure: float, moles: float, volume: float\n) -> float:\n \"\"\"\n Convert pressure and volume to temperature.\n Ideal gas laws are used.\n Temperature is taken in kelvin.\n Volume is taken in litres.\n Pressure has atm as SI unit.\n\n Wikipedia reference: https:\/\/en.wikipedia.org\/wiki\/Gas_laws\n Wikipedia reference: https:\/\/en.wikipedia.org\/wiki\/Pressure\n Wikipedia reference: https:\/\/en.wikipedia.org\/wiki\/Temperature\n\n >>> pressure_and_volume_to_temperature(0.82, 1, 2)\n 20\n >>> pressure_and_volume_to_temperature(8.2, 5, 3)\n 60\n \"\"\"\n return round(float((pressure * volume) \/ (0.0821 * moles)))\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Author: Bama Charan Chhandogi https:github.comBamaCharanChhandogi Description: Convert a Octal number to Binary. References for better understanding: https:en.wikipedia.orgwikiBinarynumber https:en.wikipedia.orgwikiOctal Convert an Octal number to Binary. octaltobinary17 '001111' octaltobinary7 '111' octaltobinaryAv Traceback most recent call last: ... ValueError: Nonoctal value was passed to the function octaltobinary Traceback most recent call last: ... ValueError: Nonoctal value was passed to the function octaltobinary Traceback most recent call last: ... ValueError: Empty string was passed to the function","Completions":"def octal_to_binary(octal_number: str) -> str:\n \"\"\"\n Convert an Octal number to Binary.\n\n >>> octal_to_binary(\"17\")\n '001111'\n >>> octal_to_binary(\"7\")\n '111'\n >>> octal_to_binary(\"Av\")\n Traceback (most recent call last):\n ...\n ValueError: Non-octal value was passed to the function\n >>> octal_to_binary(\"@#\")\n Traceback (most recent call last):\n ...\n ValueError: Non-octal value was passed to the function\n >>> octal_to_binary(\"\")\n Traceback (most recent call last):\n ...\n ValueError: Empty string was passed to the function\n \"\"\"\n if not octal_number:\n raise ValueError(\"Empty string was passed to the function\")\n\n binary_number = \"\"\n octal_digits = \"01234567\"\n for digit in octal_number:\n if digit not in octal_digits:\n raise ValueError(\"Non-octal value was passed to the function\")\n\n binary_digit = \"\"\n value = int(digit)\n for _ in range(3):\n binary_digit = str(value % 2) + binary_digit\n value \/\/= 2\n binary_number += binary_digit\n\n return binary_number\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Convert a octal value to its decimal equivalent octtodecimal Traceback most recent call last: ... ValueError: Empty string was passed to the function octtodecimal Traceback most recent call last: ... ValueError: Nonoctal value was passed to the function octtodecimale Traceback most recent call last: ... ValueError: Nonoctal value was passed to the function octtodecimal8 Traceback most recent call last: ... ValueError: Nonoctal value was passed to the function octtodecimale Traceback most recent call last: ... ValueError: Nonoctal value was passed to the function octtodecimal8 Traceback most recent call last: ... ValueError: Nonoctal value was passed to the function octtodecimal1 1 octtodecimal1 1 octtodecimal12 10 octtodecimal 12 10 octtodecimal45 37 octtodecimal Traceback most recent call last: ... ValueError: Nonoctal value was passed to the function octtodecimal0 0 octtodecimal4055 2093 octtodecimal20Fm Traceback most recent call last: ... ValueError: Nonoctal value was passed to the function octtodecimal Traceback most recent call last: ... ValueError: Empty string was passed to the function octtodecimal19 Traceback most recent call last: ... ValueError: Nonoctal value was passed to the function","Completions":"def oct_to_decimal(oct_string: str) -> int:\n \"\"\"\n Convert a octal value to its decimal equivalent\n\n >>> oct_to_decimal(\"\")\n Traceback (most recent call last):\n ...\n ValueError: Empty string was passed to the function\n >>> oct_to_decimal(\"-\")\n Traceback (most recent call last):\n ...\n ValueError: Non-octal value was passed to the function\n >>> oct_to_decimal(\"e\")\n Traceback (most recent call last):\n ...\n ValueError: Non-octal value was passed to the function\n >>> oct_to_decimal(\"8\")\n Traceback (most recent call last):\n ...\n ValueError: Non-octal value was passed to the function\n >>> oct_to_decimal(\"-e\")\n Traceback (most recent call last):\n ...\n ValueError: Non-octal value was passed to the function\n >>> oct_to_decimal(\"-8\")\n Traceback (most recent call last):\n ...\n ValueError: Non-octal value was passed to the function\n >>> oct_to_decimal(\"1\")\n 1\n >>> oct_to_decimal(\"-1\")\n -1\n >>> oct_to_decimal(\"12\")\n 10\n >>> oct_to_decimal(\" 12 \")\n 10\n >>> oct_to_decimal(\"-45\")\n -37\n >>> oct_to_decimal(\"-\")\n Traceback (most recent call last):\n ...\n ValueError: Non-octal value was passed to the function\n >>> oct_to_decimal(\"0\")\n 0\n >>> oct_to_decimal(\"-4055\")\n -2093\n >>> oct_to_decimal(\"2-0Fm\")\n Traceback (most recent call last):\n ...\n ValueError: Non-octal value was passed to the function\n >>> oct_to_decimal(\"\")\n Traceback (most recent call last):\n ...\n ValueError: Empty string was passed to the function\n >>> oct_to_decimal(\"19\")\n Traceback (most recent call last):\n ...\n ValueError: Non-octal value was passed to the function\n \"\"\"\n oct_string = str(oct_string).strip()\n if not oct_string:\n raise ValueError(\"Empty string was passed to the function\")\n is_negative = oct_string[0] == \"-\"\n if is_negative:\n oct_string = oct_string[1:]\n if not oct_string.isdigit() or not all(0 <= int(char) <= 7 for char in oct_string):\n raise ValueError(\"Non-octal value was passed to the function\")\n decimal_number = 0\n for char in oct_string:\n decimal_number = 8 * decimal_number + int(char)\n if is_negative:\n decimal_number = -decimal_number\n return decimal_number\n\n\nif __name__ == \"__main__\":\n from doctest import testmod\n\n testmod()\n"} +{"Prompt":"Convert an Octal number to Hexadecimal number. For more information: https:en.wikipedia.orgwikiOctal octaltohex100 '0x40' octaltohex235 '0x9D' octaltohex17 Traceback most recent call last: ... TypeError: Expected a string as input octaltohexAv Traceback most recent call last: ... ValueError: Not a Valid Octal Number octaltohex Traceback most recent call last: ... ValueError: Empty string was passed to the function Main Tests","Completions":"def octal_to_hex(octal: str) -> str:\n \"\"\"\n Convert an Octal number to Hexadecimal number.\n For more information: https:\/\/en.wikipedia.org\/wiki\/Octal\n\n >>> octal_to_hex(\"100\")\n '0x40'\n >>> octal_to_hex(\"235\")\n '0x9D'\n >>> octal_to_hex(17)\n Traceback (most recent call last):\n ...\n TypeError: Expected a string as input\n >>> octal_to_hex(\"Av\")\n Traceback (most recent call last):\n ...\n ValueError: Not a Valid Octal Number\n >>> octal_to_hex(\"\")\n Traceback (most recent call last):\n ...\n ValueError: Empty string was passed to the function\n \"\"\"\n\n if not isinstance(octal, str):\n raise TypeError(\"Expected a string as input\")\n if octal.startswith(\"0o\"):\n octal = octal[2:]\n if octal == \"\":\n raise ValueError(\"Empty string was passed to the function\")\n if any(char not in \"01234567\" for char in octal):\n raise ValueError(\"Not a Valid Octal Number\")\n\n decimal = 0\n for char in octal:\n decimal <<= 3\n decimal |= int(char)\n\n hex_char = \"0123456789ABCDEF\"\n\n revhex = \"\"\n while decimal:\n revhex += hex_char[decimal & 15]\n decimal >>= 4\n\n return \"0x\" + revhex[::-1]\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n\n nums = [\"030\", \"100\", \"247\", \"235\", \"007\"]\n\n ## Main Tests\n\n for num in nums:\n hexadecimal = octal_to_hex(num)\n expected = \"0x\" + hex(int(num, 8))[2:].upper()\n\n assert hexadecimal == expected\n\n print(f\"Hex of '0o{num}' is: {hexadecimal}\")\n print(f\"Expected was: {expected}\")\n print(\"---\")\n"} +{"Prompt":"Convert International System of Units SI and Binary prefixes Wikipedia reference: https:en.wikipedia.orgwikiBinaryprefix Wikipedia reference: https:en.wikipedia.orgwikiInternationalSystemofUnits convertsiprefix1, SIUnit.giga, SIUnit.mega 1000 convertsiprefix1, SIUnit.mega, SIUnit.giga 0.001 convertsiprefix1, SIUnit.kilo, SIUnit.kilo 1 convertsiprefix1, 'giga', 'mega' 1000 convertsiprefix1, 'gIGa', 'mEGa' 1000 Wikipedia reference: https:en.wikipedia.orgwikiMetricprefix convertbinaryprefix1, BinaryUnit.giga, BinaryUnit.mega 1024 convertbinaryprefix1, BinaryUnit.mega, BinaryUnit.giga 0.0009765625 convertbinaryprefix1, BinaryUnit.kilo, BinaryUnit.kilo 1 convertbinaryprefix1, 'giga', 'mega' 1024 convertbinaryprefix1, 'gIGa', 'mEGa' 1024","Completions":"from __future__ import annotations\n\nfrom enum import Enum\n\n\nclass SIUnit(Enum):\n yotta = 24\n zetta = 21\n exa = 18\n peta = 15\n tera = 12\n giga = 9\n mega = 6\n kilo = 3\n hecto = 2\n deca = 1\n deci = -1\n centi = -2\n milli = -3\n micro = -6\n nano = -9\n pico = -12\n femto = -15\n atto = -18\n zepto = -21\n yocto = -24\n\n\nclass BinaryUnit(Enum):\n yotta = 8\n zetta = 7\n exa = 6\n peta = 5\n tera = 4\n giga = 3\n mega = 2\n kilo = 1\n\n\ndef convert_si_prefix(\n known_amount: float,\n known_prefix: str | SIUnit,\n unknown_prefix: str | SIUnit,\n) -> float:\n \"\"\"\n Wikipedia reference: https:\/\/en.wikipedia.org\/wiki\/Binary_prefix\n Wikipedia reference: https:\/\/en.wikipedia.org\/wiki\/International_System_of_Units\n >>> convert_si_prefix(1, SIUnit.giga, SIUnit.mega)\n 1000\n >>> convert_si_prefix(1, SIUnit.mega, SIUnit.giga)\n 0.001\n >>> convert_si_prefix(1, SIUnit.kilo, SIUnit.kilo)\n 1\n >>> convert_si_prefix(1, 'giga', 'mega')\n 1000\n >>> convert_si_prefix(1, 'gIGa', 'mEGa')\n 1000\n \"\"\"\n if isinstance(known_prefix, str):\n known_prefix = SIUnit[known_prefix.lower()]\n if isinstance(unknown_prefix, str):\n unknown_prefix = SIUnit[unknown_prefix.lower()]\n unknown_amount: float = known_amount * (\n 10 ** (known_prefix.value - unknown_prefix.value)\n )\n return unknown_amount\n\n\ndef convert_binary_prefix(\n known_amount: float,\n known_prefix: str | BinaryUnit,\n unknown_prefix: str | BinaryUnit,\n) -> float:\n \"\"\"\n Wikipedia reference: https:\/\/en.wikipedia.org\/wiki\/Metric_prefix\n >>> convert_binary_prefix(1, BinaryUnit.giga, BinaryUnit.mega)\n 1024\n >>> convert_binary_prefix(1, BinaryUnit.mega, BinaryUnit.giga)\n 0.0009765625\n >>> convert_binary_prefix(1, BinaryUnit.kilo, BinaryUnit.kilo)\n 1\n >>> convert_binary_prefix(1, 'giga', 'mega')\n 1024\n >>> convert_binary_prefix(1, 'gIGa', 'mEGa')\n 1024\n \"\"\"\n if isinstance(known_prefix, str):\n known_prefix = BinaryUnit[known_prefix.lower()]\n if isinstance(unknown_prefix, str):\n unknown_prefix = BinaryUnit[unknown_prefix.lower()]\n unknown_amount: float = known_amount * (\n 2 ** ((known_prefix.value - unknown_prefix.value) * 10)\n )\n return unknown_amount\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Author: Manuel Di Lullo https:github.commanueldilullo Description: Convert a number to use the correct SI or Binary unit prefix. Inspired by prefixconversion.py file in this repository by lancepyles URL: https:en.wikipedia.orgwikiMetricprefixListofSIprefixes URL: https:en.wikipedia.orgwikiBinaryprefix Create a generic variable that can be 'Enum', or any subclass. Returns a dictionary with only the elements of this enum that has a positive value from itertools import islice positive SIUnit.getpositive inc iterpositive.items dictisliceinc, lenpositive 2 'yotta': 24, 'zetta': 21, 'exa': 18, 'peta': 15, 'tera': 12 dictinc 'giga': 9, 'mega': 6, 'kilo': 3, 'hecto': 2, 'deca': 1 Returns a dictionary with only the elements of this enum that has a negative value example from itertools import islice negative SIUnit.getnegative inc iternegative.items dictisliceinc, lennegative 2 'deci': 1, 'centi': 2, 'milli': 3, 'micro': 6, 'nano': 9 dictinc 'pico': 12, 'femto': 15, 'atto': 18, 'zepto': 21, 'yocto': 24 Function that converts a number to his version with SI prefix input value an integer example: addsiprefix10000 '10.0 kilo' Function that converts a number to his version with Binary prefix input value an integer example: addbinaryprefix65536 '64.0 kilo'","Completions":"from __future__ import annotations\n\nfrom enum import Enum, unique\nfrom typing import TypeVar\n\n# Create a generic variable that can be 'Enum', or any subclass.\nT = TypeVar(\"T\", bound=\"Enum\")\n\n\n@unique\nclass BinaryUnit(Enum):\n yotta = 80\n zetta = 70\n exa = 60\n peta = 50\n tera = 40\n giga = 30\n mega = 20\n kilo = 10\n\n\n@unique\nclass SIUnit(Enum):\n yotta = 24\n zetta = 21\n exa = 18\n peta = 15\n tera = 12\n giga = 9\n mega = 6\n kilo = 3\n hecto = 2\n deca = 1\n deci = -1\n centi = -2\n milli = -3\n micro = -6\n nano = -9\n pico = -12\n femto = -15\n atto = -18\n zepto = -21\n yocto = -24\n\n @classmethod\n def get_positive(cls: type[T]) -> dict:\n \"\"\"\n Returns a dictionary with only the elements of this enum\n that has a positive value\n >>> from itertools import islice\n >>> positive = SIUnit.get_positive()\n >>> inc = iter(positive.items())\n >>> dict(islice(inc, len(positive) \/\/ 2))\n {'yotta': 24, 'zetta': 21, 'exa': 18, 'peta': 15, 'tera': 12}\n >>> dict(inc)\n {'giga': 9, 'mega': 6, 'kilo': 3, 'hecto': 2, 'deca': 1}\n \"\"\"\n return {unit.name: unit.value for unit in cls if unit.value > 0}\n\n @classmethod\n def get_negative(cls: type[T]) -> dict:\n \"\"\"\n Returns a dictionary with only the elements of this enum\n that has a negative value\n @example\n >>> from itertools import islice\n >>> negative = SIUnit.get_negative()\n >>> inc = iter(negative.items())\n >>> dict(islice(inc, len(negative) \/\/ 2))\n {'deci': -1, 'centi': -2, 'milli': -3, 'micro': -6, 'nano': -9}\n >>> dict(inc)\n {'pico': -12, 'femto': -15, 'atto': -18, 'zepto': -21, 'yocto': -24}\n \"\"\"\n return {unit.name: unit.value for unit in cls if unit.value < 0}\n\n\ndef add_si_prefix(value: float) -> str:\n \"\"\"\n Function that converts a number to his version with SI prefix\n @input value (an integer)\n @example:\n >>> add_si_prefix(10000)\n '10.0 kilo'\n \"\"\"\n prefixes = SIUnit.get_positive() if value > 0 else SIUnit.get_negative()\n for name_prefix, value_prefix in prefixes.items():\n numerical_part = value \/ (10**value_prefix)\n if numerical_part > 1:\n return f\"{numerical_part!s} {name_prefix}\"\n return str(value)\n\n\ndef add_binary_prefix(value: float) -> str:\n \"\"\"\n Function that converts a number to his version with Binary prefix\n @input value (an integer)\n @example:\n >>> add_binary_prefix(65536)\n '64.0 kilo'\n \"\"\"\n for prefix in BinaryUnit:\n numerical_part = value \/ (2**prefix.value)\n if numerical_part > 1:\n return f\"{numerical_part!s} {prefix.name}\"\n return str(value)\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Conversion of pressure units. Available Units: Pascal,Bar,Kilopascal,Megapascal,psipound per square inch, inHgin mercury column,torr,atm USAGE : Import this file into their respective project. Use the function pressureconversion for conversion of pressure units. Parameters : value : The number of from units you want to convert fromtype : From which type you want to convert totype : To which type you want to convert REFERENCES : Wikipedia reference: https:en.wikipedia.orgwikiPascalunit Wikipedia reference: https:en.wikipedia.orgwikiPoundpersquareinch Wikipedia reference: https:en.wikipedia.orgwikiInchofmercury Wikipedia reference: https:en.wikipedia.orgwikiTorr https:en.wikipedia.orgwikiStandardatmosphereunit https:msestudent.comwhataretheunitsofpressure https:www.unitconverters.netpressureconverter.html Conversion between pressure units. pressureconversion4, atm, pascal 405300 pressureconversion1, pascal, psi 0.00014401981999999998 pressureconversion1, bar, atm 0.986923 pressureconversion3, kilopascal, bar 0.029999991892499998 pressureconversion2, megapascal, psi 290.074434314 pressureconversion4, psi, torr 206.85984 pressureconversion1, inHg, atm 0.0334211 pressureconversion1, torr, psi 0.019336718261000002 pressureconversion4, wrongUnit, atm Traceback most recent call last: ... ValueError: Invalid 'fromtype' value: 'wrongUnit' Supported values are: atm, pascal, bar, kilopascal, megapascal, psi, inHg, torr","Completions":"from typing import NamedTuple\n\n\nclass FromTo(NamedTuple):\n from_factor: float\n to_factor: float\n\n\nPRESSURE_CONVERSION = {\n \"atm\": FromTo(1, 1),\n \"pascal\": FromTo(0.0000098, 101325),\n \"bar\": FromTo(0.986923, 1.01325),\n \"kilopascal\": FromTo(0.00986923, 101.325),\n \"megapascal\": FromTo(9.86923, 0.101325),\n \"psi\": FromTo(0.068046, 14.6959),\n \"inHg\": FromTo(0.0334211, 29.9213),\n \"torr\": FromTo(0.00131579, 760),\n}\n\n\ndef pressure_conversion(value: float, from_type: str, to_type: str) -> float:\n \"\"\"\n Conversion between pressure units.\n >>> pressure_conversion(4, \"atm\", \"pascal\")\n 405300\n >>> pressure_conversion(1, \"pascal\", \"psi\")\n 0.00014401981999999998\n >>> pressure_conversion(1, \"bar\", \"atm\")\n 0.986923\n >>> pressure_conversion(3, \"kilopascal\", \"bar\")\n 0.029999991892499998\n >>> pressure_conversion(2, \"megapascal\", \"psi\")\n 290.074434314\n >>> pressure_conversion(4, \"psi\", \"torr\")\n 206.85984\n >>> pressure_conversion(1, \"inHg\", \"atm\")\n 0.0334211\n >>> pressure_conversion(1, \"torr\", \"psi\")\n 0.019336718261000002\n >>> pressure_conversion(4, \"wrongUnit\", \"atm\")\n Traceback (most recent call last):\n ...\n ValueError: Invalid 'from_type' value: 'wrongUnit' Supported values are:\n atm, pascal, bar, kilopascal, megapascal, psi, inHg, torr\n \"\"\"\n if from_type not in PRESSURE_CONVERSION:\n raise ValueError(\n f\"Invalid 'from_type' value: {from_type!r} Supported values are:\\n\"\n + \", \".join(PRESSURE_CONVERSION)\n )\n if to_type not in PRESSURE_CONVERSION:\n raise ValueError(\n f\"Invalid 'to_type' value: {to_type!r}. Supported values are:\\n\"\n + \", \".join(PRESSURE_CONVERSION)\n )\n return (\n value\n * PRESSURE_CONVERSION[from_type].from_factor\n * PRESSURE_CONVERSION[to_type].to_factor\n )\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Simple RGB to CMYK conversion. Returns percentages of CMYK paint. https:www.programmingalgorithms.comalgorithmrgbtocmyk Note: this is a very popular algorithm that converts colors linearly and gives only approximate results. Actual preparation for printing requires advanced color conversion considering the color profiles and parameters of the target device. rgbtocmyk255, 200, a Traceback most recent call last: ... ValueError: Expected int, found class 'int', class 'int', class 'str' rgbtocmyk255, 255, 999 Traceback most recent call last: ... ValueError: Expected int of the range 0..255 rgbtocmyk255, 255, 255 white 0, 0, 0, 0 rgbtocmyk128, 128, 128 gray 0, 0, 0, 50 rgbtocmyk0, 0, 0 black 0, 0, 0, 100 rgbtocmyk255, 0, 0 red 0, 100, 100, 0 rgbtocmyk0, 255, 0 green 100, 0, 100, 0 rgbtocmyk0, 0, 255 blue 100, 100, 0, 0 changing range from 0..255 to 0..1","Completions":"def rgb_to_cmyk(r_input: int, g_input: int, b_input: int) -> tuple[int, int, int, int]:\n \"\"\"\n Simple RGB to CMYK conversion. Returns percentages of CMYK paint.\n https:\/\/www.programmingalgorithms.com\/algorithm\/rgb-to-cmyk\/\n\n Note: this is a very popular algorithm that converts colors linearly and gives\n only approximate results. Actual preparation for printing requires advanced color\n conversion considering the color profiles and parameters of the target device.\n\n >>> rgb_to_cmyk(255, 200, \"a\")\n Traceback (most recent call last):\n ...\n ValueError: Expected int, found (, , )\n\n >>> rgb_to_cmyk(255, 255, 999)\n Traceback (most recent call last):\n ...\n ValueError: Expected int of the range 0..255\n\n >>> rgb_to_cmyk(255, 255, 255) # white\n (0, 0, 0, 0)\n\n >>> rgb_to_cmyk(128, 128, 128) # gray\n (0, 0, 0, 50)\n\n >>> rgb_to_cmyk(0, 0, 0) # black\n (0, 0, 0, 100)\n\n >>> rgb_to_cmyk(255, 0, 0) # red\n (0, 100, 100, 0)\n\n >>> rgb_to_cmyk(0, 255, 0) # green\n (100, 0, 100, 0)\n\n >>> rgb_to_cmyk(0, 0, 255) # blue\n (100, 100, 0, 0)\n \"\"\"\n\n if (\n not isinstance(r_input, int)\n or not isinstance(g_input, int)\n or not isinstance(b_input, int)\n ):\n msg = f\"Expected int, found {type(r_input), type(g_input), type(b_input)}\"\n raise ValueError(msg)\n\n if not 0 <= r_input < 256 or not 0 <= g_input < 256 or not 0 <= b_input < 256:\n raise ValueError(\"Expected int of the range 0..255\")\n\n # changing range from 0..255 to 0..1\n r = r_input \/ 255\n g = g_input \/ 255\n b = b_input \/ 255\n\n k = 1 - max(r, g, b)\n\n if k == 1: # pure black\n return 0, 0, 0, 100\n\n c = round(100 * (1 - r - k) \/ (1 - k))\n m = round(100 * (1 - g - k) \/ (1 - k))\n y = round(100 * (1 - b - k) \/ (1 - k))\n k = round(100 * k)\n\n return c, m, y, k\n\n\nif __name__ == \"__main__\":\n from doctest import testmod\n\n testmod()\n"} +{"Prompt":"The RGB color model is an additive color model in which red, green, and blue light are added together in various ways to reproduce a broad array of colors. The name of the model comes from the initials of the three additive primary colors, red, green, and blue. Meanwhile, the HSV representation models how colors appear under light. In it, colors are represented using three components: hue, saturation and brightnessvalue. This file provides functions for converting colors from one representation to the other. description adapted from https:en.wikipedia.orgwikiRGBcolormodel and https:en.wikipedia.orgwikiHSLandHSV. Conversion from the HSVrepresentation to the RGBrepresentation. Expected RGBvalues taken from https:www.rapidtables.comconvertcolorhsvtorgb.html hsvtorgb0, 0, 0 0, 0, 0 hsvtorgb0, 0, 1 255, 255, 255 hsvtorgb0, 1, 1 255, 0, 0 hsvtorgb60, 1, 1 255, 255, 0 hsvtorgb120, 1, 1 0, 255, 0 hsvtorgb240, 1, 1 0, 0, 255 hsvtorgb300, 1, 1 255, 0, 255 hsvtorgb180, 0.5, 0.5 64, 128, 128 hsvtorgb234, 0.14, 0.88 193, 196, 224 hsvtorgb330, 0.75, 0.5 128, 32, 80 Conversion from the RGBrepresentation to the HSVrepresentation. The tested values are the reverse values from the hsvtorgbdoctests. Function approximatelyequalhsv is needed because of small deviations due to rounding for the RGBvalues. approximatelyequalhsvrgbtohsv0, 0, 0, 0, 0, 0 True approximatelyequalhsvrgbtohsv255, 255, 255, 0, 0, 1 True approximatelyequalhsvrgbtohsv255, 0, 0, 0, 1, 1 True approximatelyequalhsvrgbtohsv255, 255, 0, 60, 1, 1 True approximatelyequalhsvrgbtohsv0, 255, 0, 120, 1, 1 True approximatelyequalhsvrgbtohsv0, 0, 255, 240, 1, 1 True approximatelyequalhsvrgbtohsv255, 0, 255, 300, 1, 1 True approximatelyequalhsvrgbtohsv64, 128, 128, 180, 0.5, 0.5 True approximatelyequalhsvrgbtohsv193, 196, 224, 234, 0.14, 0.88 True approximatelyequalhsvrgbtohsv128, 32, 80, 330, 0.75, 0.5 True Utilityfunction to check that two hsvcolors are approximately equal approximatelyequalhsv0, 0, 0, 0, 0, 0 True approximatelyequalhsv180, 0.5, 0.3, 179.9999, 0.500001, 0.30001 True approximatelyequalhsv0, 0, 0, 1, 0, 0 False approximatelyequalhsv180, 0.5, 0.3, 179.9999, 0.6, 0.30001 False","Completions":"def hsv_to_rgb(hue: float, saturation: float, value: float) -> list[int]:\n \"\"\"\n Conversion from the HSV-representation to the RGB-representation.\n Expected RGB-values taken from\n https:\/\/www.rapidtables.com\/convert\/color\/hsv-to-rgb.html\n\n >>> hsv_to_rgb(0, 0, 0)\n [0, 0, 0]\n >>> hsv_to_rgb(0, 0, 1)\n [255, 255, 255]\n >>> hsv_to_rgb(0, 1, 1)\n [255, 0, 0]\n >>> hsv_to_rgb(60, 1, 1)\n [255, 255, 0]\n >>> hsv_to_rgb(120, 1, 1)\n [0, 255, 0]\n >>> hsv_to_rgb(240, 1, 1)\n [0, 0, 255]\n >>> hsv_to_rgb(300, 1, 1)\n [255, 0, 255]\n >>> hsv_to_rgb(180, 0.5, 0.5)\n [64, 128, 128]\n >>> hsv_to_rgb(234, 0.14, 0.88)\n [193, 196, 224]\n >>> hsv_to_rgb(330, 0.75, 0.5)\n [128, 32, 80]\n \"\"\"\n if hue < 0 or hue > 360:\n raise Exception(\"hue should be between 0 and 360\")\n\n if saturation < 0 or saturation > 1:\n raise Exception(\"saturation should be between 0 and 1\")\n\n if value < 0 or value > 1:\n raise Exception(\"value should be between 0 and 1\")\n\n chroma = value * saturation\n hue_section = hue \/ 60\n second_largest_component = chroma * (1 - abs(hue_section % 2 - 1))\n match_value = value - chroma\n\n if hue_section >= 0 and hue_section <= 1:\n red = round(255 * (chroma + match_value))\n green = round(255 * (second_largest_component + match_value))\n blue = round(255 * (match_value))\n elif hue_section > 1 and hue_section <= 2:\n red = round(255 * (second_largest_component + match_value))\n green = round(255 * (chroma + match_value))\n blue = round(255 * (match_value))\n elif hue_section > 2 and hue_section <= 3:\n red = round(255 * (match_value))\n green = round(255 * (chroma + match_value))\n blue = round(255 * (second_largest_component + match_value))\n elif hue_section > 3 and hue_section <= 4:\n red = round(255 * (match_value))\n green = round(255 * (second_largest_component + match_value))\n blue = round(255 * (chroma + match_value))\n elif hue_section > 4 and hue_section <= 5:\n red = round(255 * (second_largest_component + match_value))\n green = round(255 * (match_value))\n blue = round(255 * (chroma + match_value))\n else:\n red = round(255 * (chroma + match_value))\n green = round(255 * (match_value))\n blue = round(255 * (second_largest_component + match_value))\n\n return [red, green, blue]\n\n\ndef rgb_to_hsv(red: int, green: int, blue: int) -> list[float]:\n \"\"\"\n Conversion from the RGB-representation to the HSV-representation.\n The tested values are the reverse values from the hsv_to_rgb-doctests.\n Function \"approximately_equal_hsv\" is needed because of small deviations due to\n rounding for the RGB-values.\n\n >>> approximately_equal_hsv(rgb_to_hsv(0, 0, 0), [0, 0, 0])\n True\n >>> approximately_equal_hsv(rgb_to_hsv(255, 255, 255), [0, 0, 1])\n True\n >>> approximately_equal_hsv(rgb_to_hsv(255, 0, 0), [0, 1, 1])\n True\n >>> approximately_equal_hsv(rgb_to_hsv(255, 255, 0), [60, 1, 1])\n True\n >>> approximately_equal_hsv(rgb_to_hsv(0, 255, 0), [120, 1, 1])\n True\n >>> approximately_equal_hsv(rgb_to_hsv(0, 0, 255), [240, 1, 1])\n True\n >>> approximately_equal_hsv(rgb_to_hsv(255, 0, 255), [300, 1, 1])\n True\n >>> approximately_equal_hsv(rgb_to_hsv(64, 128, 128), [180, 0.5, 0.5])\n True\n >>> approximately_equal_hsv(rgb_to_hsv(193, 196, 224), [234, 0.14, 0.88])\n True\n >>> approximately_equal_hsv(rgb_to_hsv(128, 32, 80), [330, 0.75, 0.5])\n True\n \"\"\"\n if red < 0 or red > 255:\n raise Exception(\"red should be between 0 and 255\")\n\n if green < 0 or green > 255:\n raise Exception(\"green should be between 0 and 255\")\n\n if blue < 0 or blue > 255:\n raise Exception(\"blue should be between 0 and 255\")\n\n float_red = red \/ 255\n float_green = green \/ 255\n float_blue = blue \/ 255\n value = max(float_red, float_green, float_blue)\n chroma = value - min(float_red, float_green, float_blue)\n saturation = 0 if value == 0 else chroma \/ value\n\n if chroma == 0:\n hue = 0.0\n elif value == float_red:\n hue = 60 * (0 + (float_green - float_blue) \/ chroma)\n elif value == float_green:\n hue = 60 * (2 + (float_blue - float_red) \/ chroma)\n else:\n hue = 60 * (4 + (float_red - float_green) \/ chroma)\n\n hue = (hue + 360) % 360\n\n return [hue, saturation, value]\n\n\ndef approximately_equal_hsv(hsv_1: list[float], hsv_2: list[float]) -> bool:\n \"\"\"\n Utility-function to check that two hsv-colors are approximately equal\n\n >>> approximately_equal_hsv([0, 0, 0], [0, 0, 0])\n True\n >>> approximately_equal_hsv([180, 0.5, 0.3], [179.9999, 0.500001, 0.30001])\n True\n >>> approximately_equal_hsv([0, 0, 0], [1, 0, 0])\n False\n >>> approximately_equal_hsv([180, 0.5, 0.3], [179.9999, 0.6, 0.30001])\n False\n \"\"\"\n check_hue = abs(hsv_1[0] - hsv_2[0]) < 0.2\n check_saturation = abs(hsv_1[1] - hsv_2[1]) < 0.002\n check_value = abs(hsv_1[2] - hsv_2[2]) < 0.002\n\n return check_hue and check_saturation and check_value\n"} +{"Prompt":"LeetCode No. 13 Roman to Integer Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999. https:en.wikipedia.orgwikiRomannumerals tests III: 3, CLIV: 154, MIX: 1009, MMD: 2500, MMMCMXCIX: 3999 allromantointkey value for key, value in tests.items True Given a integer, convert it to an roman numeral. https:en.wikipedia.orgwikiRomannumerals tests III: 3, CLIV: 154, MIX: 1009, MMD: 2500, MMMCMXCIX: 3999 allinttoromanvalue key for key, value in tests.items True","Completions":"ROMAN = [\n (1000, \"M\"),\n (900, \"CM\"),\n (500, \"D\"),\n (400, \"CD\"),\n (100, \"C\"),\n (90, \"XC\"),\n (50, \"L\"),\n (40, \"XL\"),\n (10, \"X\"),\n (9, \"IX\"),\n (5, \"V\"),\n (4, \"IV\"),\n (1, \"I\"),\n]\n\n\ndef roman_to_int(roman: str) -> int:\n \"\"\"\n LeetCode No. 13 Roman to Integer\n Given a roman numeral, convert it to an integer.\n Input is guaranteed to be within the range from 1 to 3999.\n https:\/\/en.wikipedia.org\/wiki\/Roman_numerals\n >>> tests = {\"III\": 3, \"CLIV\": 154, \"MIX\": 1009, \"MMD\": 2500, \"MMMCMXCIX\": 3999}\n >>> all(roman_to_int(key) == value for key, value in tests.items())\n True\n \"\"\"\n vals = {\"I\": 1, \"V\": 5, \"X\": 10, \"L\": 50, \"C\": 100, \"D\": 500, \"M\": 1000}\n total = 0\n place = 0\n while place < len(roman):\n if (place + 1 < len(roman)) and (vals[roman[place]] < vals[roman[place + 1]]):\n total += vals[roman[place + 1]] - vals[roman[place]]\n place += 2\n else:\n total += vals[roman[place]]\n place += 1\n return total\n\n\ndef int_to_roman(number: int) -> str:\n \"\"\"\n Given a integer, convert it to an roman numeral.\n https:\/\/en.wikipedia.org\/wiki\/Roman_numerals\n >>> tests = {\"III\": 3, \"CLIV\": 154, \"MIX\": 1009, \"MMD\": 2500, \"MMMCMXCIX\": 3999}\n >>> all(int_to_roman(value) == key for key, value in tests.items())\n True\n \"\"\"\n result = []\n for arabic, roman in ROMAN:\n (factor, number) = divmod(number, arabic)\n result.append(roman * factor)\n if number == 0:\n break\n return \"\".join(result)\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Convert speed units https:en.wikipedia.orgwikiKilometresperhour https:en.wikipedia.orgwikiMilesperhour https:en.wikipedia.orgwikiKnotunit https:en.wikipedia.orgwikiMetrepersecond Convert speed from one unit to another using the speedchart above. kmh: 1.0, ms: 3.6, mph: 1.609344, knot: 1.852, convertspeed100, kmh, ms 27.778 convertspeed100, kmh, mph 62.137 convertspeed100, kmh, knot 53.996 convertspeed100, ms, kmh 360.0 convertspeed100, ms, mph 223.694 convertspeed100, ms, knot 194.384 convertspeed100, mph, kmh 160.934 convertspeed100, mph, ms 44.704 convertspeed100, mph, knot 86.898 convertspeed100, knot, kmh 185.2 convertspeed100, knot, ms 51.444 convertspeed100, knot, mph 115.078","Completions":"speed_chart: dict[str, float] = {\n \"km\/h\": 1.0,\n \"m\/s\": 3.6,\n \"mph\": 1.609344,\n \"knot\": 1.852,\n}\n\nspeed_chart_inverse: dict[str, float] = {\n \"km\/h\": 1.0,\n \"m\/s\": 0.277777778,\n \"mph\": 0.621371192,\n \"knot\": 0.539956803,\n}\n\n\ndef convert_speed(speed: float, unit_from: str, unit_to: str) -> float:\n \"\"\"\n Convert speed from one unit to another using the speed_chart above.\n\n \"km\/h\": 1.0,\n \"m\/s\": 3.6,\n \"mph\": 1.609344,\n \"knot\": 1.852,\n\n >>> convert_speed(100, \"km\/h\", \"m\/s\")\n 27.778\n >>> convert_speed(100, \"km\/h\", \"mph\")\n 62.137\n >>> convert_speed(100, \"km\/h\", \"knot\")\n 53.996\n >>> convert_speed(100, \"m\/s\", \"km\/h\")\n 360.0\n >>> convert_speed(100, \"m\/s\", \"mph\")\n 223.694\n >>> convert_speed(100, \"m\/s\", \"knot\")\n 194.384\n >>> convert_speed(100, \"mph\", \"km\/h\")\n 160.934\n >>> convert_speed(100, \"mph\", \"m\/s\")\n 44.704\n >>> convert_speed(100, \"mph\", \"knot\")\n 86.898\n >>> convert_speed(100, \"knot\", \"km\/h\")\n 185.2\n >>> convert_speed(100, \"knot\", \"m\/s\")\n 51.444\n >>> convert_speed(100, \"knot\", \"mph\")\n 115.078\n \"\"\"\n if unit_to not in speed_chart or unit_from not in speed_chart_inverse:\n msg = (\n f\"Incorrect 'from_type' or 'to_type' value: {unit_from!r}, {unit_to!r}\\n\"\n f\"Valid values are: {', '.join(speed_chart_inverse)}\"\n )\n raise ValueError(msg)\n return round(speed * speed_chart[unit_from] * speed_chart_inverse[unit_to], 3)\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Convert between different units of temperature def celsiustofahrenheitcelsius: float, ndigits: int 2 float: return roundfloatcelsius 9 5 32, ndigits def celsiustokelvincelsius: float, ndigits: int 2 float: return roundfloatcelsius 273.15, ndigits def celsiustorankinecelsius: float, ndigits: int 2 float: return roundfloatcelsius 9 5 491.67, ndigits def fahrenheittocelsiusfahrenheit: float, ndigits: int 2 float: return roundfloatfahrenheit 32 5 9, ndigits def fahrenheittokelvinfahrenheit: float, ndigits: int 2 float: return roundfloatfahrenheit 32 5 9 273.15, ndigits def fahrenheittorankinefahrenheit: float, ndigits: int 2 float: return roundfloatfahrenheit 459.67, ndigits def kelvintocelsiuskelvin: float, ndigits: int 2 float: return roundfloatkelvin 273.15, ndigits def kelvintofahrenheitkelvin: float, ndigits: int 2 float: return roundfloatkelvin 273.15 9 5 32, ndigits def kelvintorankinekelvin: float, ndigits: int 2 float: return roundfloatkelvin 9 5, ndigits def rankinetocelsiusrankine: float, ndigits: int 2 float: return roundfloatrankine 491.67 5 9, ndigits def rankinetofahrenheitrankine: float, ndigits: int 2 float: return roundfloatrankine 459.67, ndigits def rankinetokelvinrankine: float, ndigits: int 2 float: return roundfloatrankine 5 9, ndigits def reaumurtokelvinreaumur: float, ndigits: int 2 float: return roundfloatreaumur 1.25 273.15, ndigits def reaumurtofahrenheitreaumur: float, ndigits: int 2 float: return roundfloatreaumur 2.25 32, ndigits def reaumurtocelsiusreaumur: float, ndigits: int 2 float: return roundfloatreaumur 1.25, ndigits def reaumurtorankinereaumur: float, ndigits: int 2 float: return roundfloatreaumur 2.25 32 459.67, ndigits if name main: import doctest doctest.testmod","Completions":"def celsius_to_fahrenheit(celsius: float, ndigits: int = 2) -> float:\n \"\"\"\n Convert a given value from Celsius to Fahrenheit and round it to 2 decimal places.\n Wikipedia reference: https:\/\/en.wikipedia.org\/wiki\/Celsius\n Wikipedia reference: https:\/\/en.wikipedia.org\/wiki\/Fahrenheit\n\n >>> celsius_to_fahrenheit(273.354, 3)\n 524.037\n >>> celsius_to_fahrenheit(273.354, 0)\n 524.0\n >>> celsius_to_fahrenheit(-40.0)\n -40.0\n >>> celsius_to_fahrenheit(-20.0)\n -4.0\n >>> celsius_to_fahrenheit(0)\n 32.0\n >>> celsius_to_fahrenheit(20)\n 68.0\n >>> celsius_to_fahrenheit(\"40\")\n 104.0\n >>> celsius_to_fahrenheit(\"celsius\")\n Traceback (most recent call last):\n ...\n ValueError: could not convert string to float: 'celsius'\n \"\"\"\n return round((float(celsius) * 9 \/ 5) + 32, ndigits)\n\n\ndef celsius_to_kelvin(celsius: float, ndigits: int = 2) -> float:\n \"\"\"\n Convert a given value from Celsius to Kelvin and round it to 2 decimal places.\n Wikipedia reference: https:\/\/en.wikipedia.org\/wiki\/Celsius\n Wikipedia reference: https:\/\/en.wikipedia.org\/wiki\/Kelvin\n\n >>> celsius_to_kelvin(273.354, 3)\n 546.504\n >>> celsius_to_kelvin(273.354, 0)\n 547.0\n >>> celsius_to_kelvin(0)\n 273.15\n >>> celsius_to_kelvin(20.0)\n 293.15\n >>> celsius_to_kelvin(\"40\")\n 313.15\n >>> celsius_to_kelvin(\"celsius\")\n Traceback (most recent call last):\n ...\n ValueError: could not convert string to float: 'celsius'\n \"\"\"\n return round(float(celsius) + 273.15, ndigits)\n\n\ndef celsius_to_rankine(celsius: float, ndigits: int = 2) -> float:\n \"\"\"\n Convert a given value from Celsius to Rankine and round it to 2 decimal places.\n Wikipedia reference: https:\/\/en.wikipedia.org\/wiki\/Celsius\n Wikipedia reference: https:\/\/en.wikipedia.org\/wiki\/Rankine_scale\n\n >>> celsius_to_rankine(273.354, 3)\n 983.707\n >>> celsius_to_rankine(273.354, 0)\n 984.0\n >>> celsius_to_rankine(0)\n 491.67\n >>> celsius_to_rankine(20.0)\n 527.67\n >>> celsius_to_rankine(\"40\")\n 563.67\n >>> celsius_to_rankine(\"celsius\")\n Traceback (most recent call last):\n ...\n ValueError: could not convert string to float: 'celsius'\n \"\"\"\n return round((float(celsius) * 9 \/ 5) + 491.67, ndigits)\n\n\ndef fahrenheit_to_celsius(fahrenheit: float, ndigits: int = 2) -> float:\n \"\"\"\n Convert a given value from Fahrenheit to Celsius and round it to 2 decimal places.\n Wikipedia reference: https:\/\/en.wikipedia.org\/wiki\/Fahrenheit\n Wikipedia reference: https:\/\/en.wikipedia.org\/wiki\/Celsius\n\n >>> fahrenheit_to_celsius(273.354, 3)\n 134.086\n >>> fahrenheit_to_celsius(273.354, 0)\n 134.0\n >>> fahrenheit_to_celsius(0)\n -17.78\n >>> fahrenheit_to_celsius(20.0)\n -6.67\n >>> fahrenheit_to_celsius(40.0)\n 4.44\n >>> fahrenheit_to_celsius(60)\n 15.56\n >>> fahrenheit_to_celsius(80)\n 26.67\n >>> fahrenheit_to_celsius(\"100\")\n 37.78\n >>> fahrenheit_to_celsius(\"fahrenheit\")\n Traceback (most recent call last):\n ...\n ValueError: could not convert string to float: 'fahrenheit'\n \"\"\"\n return round((float(fahrenheit) - 32) * 5 \/ 9, ndigits)\n\n\ndef fahrenheit_to_kelvin(fahrenheit: float, ndigits: int = 2) -> float:\n \"\"\"\n Convert a given value from Fahrenheit to Kelvin and round it to 2 decimal places.\n Wikipedia reference: https:\/\/en.wikipedia.org\/wiki\/Fahrenheit\n Wikipedia reference: https:\/\/en.wikipedia.org\/wiki\/Kelvin\n\n >>> fahrenheit_to_kelvin(273.354, 3)\n 407.236\n >>> fahrenheit_to_kelvin(273.354, 0)\n 407.0\n >>> fahrenheit_to_kelvin(0)\n 255.37\n >>> fahrenheit_to_kelvin(20.0)\n 266.48\n >>> fahrenheit_to_kelvin(40.0)\n 277.59\n >>> fahrenheit_to_kelvin(60)\n 288.71\n >>> fahrenheit_to_kelvin(80)\n 299.82\n >>> fahrenheit_to_kelvin(\"100\")\n 310.93\n >>> fahrenheit_to_kelvin(\"fahrenheit\")\n Traceback (most recent call last):\n ...\n ValueError: could not convert string to float: 'fahrenheit'\n \"\"\"\n return round(((float(fahrenheit) - 32) * 5 \/ 9) + 273.15, ndigits)\n\n\ndef fahrenheit_to_rankine(fahrenheit: float, ndigits: int = 2) -> float:\n \"\"\"\n Convert a given value from Fahrenheit to Rankine and round it to 2 decimal places.\n Wikipedia reference: https:\/\/en.wikipedia.org\/wiki\/Fahrenheit\n Wikipedia reference: https:\/\/en.wikipedia.org\/wiki\/Rankine_scale\n\n >>> fahrenheit_to_rankine(273.354, 3)\n 733.024\n >>> fahrenheit_to_rankine(273.354, 0)\n 733.0\n >>> fahrenheit_to_rankine(0)\n 459.67\n >>> fahrenheit_to_rankine(20.0)\n 479.67\n >>> fahrenheit_to_rankine(40.0)\n 499.67\n >>> fahrenheit_to_rankine(60)\n 519.67\n >>> fahrenheit_to_rankine(80)\n 539.67\n >>> fahrenheit_to_rankine(\"100\")\n 559.67\n >>> fahrenheit_to_rankine(\"fahrenheit\")\n Traceback (most recent call last):\n ...\n ValueError: could not convert string to float: 'fahrenheit'\n \"\"\"\n return round(float(fahrenheit) + 459.67, ndigits)\n\n\ndef kelvin_to_celsius(kelvin: float, ndigits: int = 2) -> float:\n \"\"\"\n Convert a given value from Kelvin to Celsius and round it to 2 decimal places.\n Wikipedia reference: https:\/\/en.wikipedia.org\/wiki\/Kelvin\n Wikipedia reference: https:\/\/en.wikipedia.org\/wiki\/Celsius\n\n >>> kelvin_to_celsius(273.354, 3)\n 0.204\n >>> kelvin_to_celsius(273.354, 0)\n 0.0\n >>> kelvin_to_celsius(273.15)\n 0.0\n >>> kelvin_to_celsius(300)\n 26.85\n >>> kelvin_to_celsius(\"315.5\")\n 42.35\n >>> kelvin_to_celsius(\"kelvin\")\n Traceback (most recent call last):\n ...\n ValueError: could not convert string to float: 'kelvin'\n \"\"\"\n return round(float(kelvin) - 273.15, ndigits)\n\n\ndef kelvin_to_fahrenheit(kelvin: float, ndigits: int = 2) -> float:\n \"\"\"\n Convert a given value from Kelvin to Fahrenheit and round it to 2 decimal places.\n Wikipedia reference: https:\/\/en.wikipedia.org\/wiki\/Kelvin\n Wikipedia reference: https:\/\/en.wikipedia.org\/wiki\/Fahrenheit\n\n >>> kelvin_to_fahrenheit(273.354, 3)\n 32.367\n >>> kelvin_to_fahrenheit(273.354, 0)\n 32.0\n >>> kelvin_to_fahrenheit(273.15)\n 32.0\n >>> kelvin_to_fahrenheit(300)\n 80.33\n >>> kelvin_to_fahrenheit(\"315.5\")\n 108.23\n >>> kelvin_to_fahrenheit(\"kelvin\")\n Traceback (most recent call last):\n ...\n ValueError: could not convert string to float: 'kelvin'\n \"\"\"\n return round(((float(kelvin) - 273.15) * 9 \/ 5) + 32, ndigits)\n\n\ndef kelvin_to_rankine(kelvin: float, ndigits: int = 2) -> float:\n \"\"\"\n Convert a given value from Kelvin to Rankine and round it to 2 decimal places.\n Wikipedia reference: https:\/\/en.wikipedia.org\/wiki\/Kelvin\n Wikipedia reference: https:\/\/en.wikipedia.org\/wiki\/Rankine_scale\n\n >>> kelvin_to_rankine(273.354, 3)\n 492.037\n >>> kelvin_to_rankine(273.354, 0)\n 492.0\n >>> kelvin_to_rankine(0)\n 0.0\n >>> kelvin_to_rankine(20.0)\n 36.0\n >>> kelvin_to_rankine(\"40\")\n 72.0\n >>> kelvin_to_rankine(\"kelvin\")\n Traceback (most recent call last):\n ...\n ValueError: could not convert string to float: 'kelvin'\n \"\"\"\n return round((float(kelvin) * 9 \/ 5), ndigits)\n\n\ndef rankine_to_celsius(rankine: float, ndigits: int = 2) -> float:\n \"\"\"\n Convert a given value from Rankine to Celsius and round it to 2 decimal places.\n Wikipedia reference: https:\/\/en.wikipedia.org\/wiki\/Rankine_scale\n Wikipedia reference: https:\/\/en.wikipedia.org\/wiki\/Celsius\n\n >>> rankine_to_celsius(273.354, 3)\n -121.287\n >>> rankine_to_celsius(273.354, 0)\n -121.0\n >>> rankine_to_celsius(273.15)\n -121.4\n >>> rankine_to_celsius(300)\n -106.48\n >>> rankine_to_celsius(\"315.5\")\n -97.87\n >>> rankine_to_celsius(\"rankine\")\n Traceback (most recent call last):\n ...\n ValueError: could not convert string to float: 'rankine'\n \"\"\"\n return round((float(rankine) - 491.67) * 5 \/ 9, ndigits)\n\n\ndef rankine_to_fahrenheit(rankine: float, ndigits: int = 2) -> float:\n \"\"\"\n Convert a given value from Rankine to Fahrenheit and round it to 2 decimal places.\n Wikipedia reference: https:\/\/en.wikipedia.org\/wiki\/Rankine_scale\n Wikipedia reference: https:\/\/en.wikipedia.org\/wiki\/Fahrenheit\n\n >>> rankine_to_fahrenheit(273.15)\n -186.52\n >>> rankine_to_fahrenheit(300)\n -159.67\n >>> rankine_to_fahrenheit(\"315.5\")\n -144.17\n >>> rankine_to_fahrenheit(\"rankine\")\n Traceback (most recent call last):\n ...\n ValueError: could not convert string to float: 'rankine'\n \"\"\"\n return round(float(rankine) - 459.67, ndigits)\n\n\ndef rankine_to_kelvin(rankine: float, ndigits: int = 2) -> float:\n \"\"\"\n Convert a given value from Rankine to Kelvin and round it to 2 decimal places.\n Wikipedia reference: https:\/\/en.wikipedia.org\/wiki\/Rankine_scale\n Wikipedia reference: https:\/\/en.wikipedia.org\/wiki\/Kelvin\n\n >>> rankine_to_kelvin(0)\n 0.0\n >>> rankine_to_kelvin(20.0)\n 11.11\n >>> rankine_to_kelvin(\"40\")\n 22.22\n >>> rankine_to_kelvin(\"rankine\")\n Traceback (most recent call last):\n ...\n ValueError: could not convert string to float: 'rankine'\n \"\"\"\n return round((float(rankine) * 5 \/ 9), ndigits)\n\n\ndef reaumur_to_kelvin(reaumur: float, ndigits: int = 2) -> float:\n \"\"\"\n Convert a given value from reaumur to Kelvin and round it to 2 decimal places.\n Reference:- http:\/\/www.csgnetwork.com\/temp2conv.html\n\n >>> reaumur_to_kelvin(0)\n 273.15\n >>> reaumur_to_kelvin(20.0)\n 298.15\n >>> reaumur_to_kelvin(40)\n 323.15\n >>> reaumur_to_kelvin(\"reaumur\")\n Traceback (most recent call last):\n ...\n ValueError: could not convert string to float: 'reaumur'\n \"\"\"\n return round((float(reaumur) * 1.25 + 273.15), ndigits)\n\n\ndef reaumur_to_fahrenheit(reaumur: float, ndigits: int = 2) -> float:\n \"\"\"\n Convert a given value from reaumur to fahrenheit and round it to 2 decimal places.\n Reference:- http:\/\/www.csgnetwork.com\/temp2conv.html\n\n >>> reaumur_to_fahrenheit(0)\n 32.0\n >>> reaumur_to_fahrenheit(20.0)\n 77.0\n >>> reaumur_to_fahrenheit(40)\n 122.0\n >>> reaumur_to_fahrenheit(\"reaumur\")\n Traceback (most recent call last):\n ...\n ValueError: could not convert string to float: 'reaumur'\n \"\"\"\n return round((float(reaumur) * 2.25 + 32), ndigits)\n\n\ndef reaumur_to_celsius(reaumur: float, ndigits: int = 2) -> float:\n \"\"\"\n Convert a given value from reaumur to celsius and round it to 2 decimal places.\n Reference:- http:\/\/www.csgnetwork.com\/temp2conv.html\n\n >>> reaumur_to_celsius(0)\n 0.0\n >>> reaumur_to_celsius(20.0)\n 25.0\n >>> reaumur_to_celsius(40)\n 50.0\n >>> reaumur_to_celsius(\"reaumur\")\n Traceback (most recent call last):\n ...\n ValueError: could not convert string to float: 'reaumur'\n \"\"\"\n return round((float(reaumur) * 1.25), ndigits)\n\n\ndef reaumur_to_rankine(reaumur: float, ndigits: int = 2) -> float:\n \"\"\"\n Convert a given value from reaumur to rankine and round it to 2 decimal places.\n Reference:- http:\/\/www.csgnetwork.com\/temp2conv.html\n\n >>> reaumur_to_rankine(0)\n 491.67\n >>> reaumur_to_rankine(20.0)\n 536.67\n >>> reaumur_to_rankine(40)\n 581.67\n >>> reaumur_to_rankine(\"reaumur\")\n Traceback (most recent call last):\n ...\n ValueError: could not convert string to float: 'reaumur'\n \"\"\"\n return round((float(reaumur) * 2.25 + 32 + 459.67), ndigits)\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"A unit of time is any particular time interval, used as a standard way of measuring or expressing duration. The base unit of time in the International System of Units SI, and by extension most of the Western world, is the second, defined as about 9 billion oscillations of the caesium atom. https:en.wikipedia.orgwikiUnitoftime Convert time from one unit to another using the timechart above. converttime3600, seconds, hours 1.0 converttime3500, Seconds, Hours 0.972 converttime1, DaYs, hours 24.0 converttime120, minutes, SeCoNdS 7200.0 converttime2, WEEKS, days 14.0 converttime0.5, hours, MINUTES 30.0 converttime3600, seconds, hours Traceback most recent call last: ... ValueError: 'timevalue' must be a nonnegative number. converttimeHello, hours, minutes Traceback most recent call last: ... ValueError: 'timevalue' must be a nonnegative number. converttime0, 1, 2, weeks, days Traceback most recent call last: ... ValueError: 'timevalue' must be a nonnegative number. converttime1, cool, century doctest: ELLIPSIS Traceback most recent call last: ... ValueError: Invalid unit cool is not in seconds, minutes, hours, days, weeks, ... converttime1, seconds, hot doctest: ELLIPSIS Traceback most recent call last: ... ValueError: Invalid unit hot is not in seconds, minutes, hours, days, weeks, ...","Completions":"time_chart: dict[str, float] = {\n \"seconds\": 1.0,\n \"minutes\": 60.0, # 1 minute = 60 sec\n \"hours\": 3600.0, # 1 hour = 60 minutes = 3600 seconds\n \"days\": 86400.0, # 1 day = 24 hours = 1440 min = 86400 sec\n \"weeks\": 604800.0, # 1 week=7d=168hr=10080min = 604800 sec\n \"months\": 2629800.0, # Approximate value for a month in seconds\n \"years\": 31557600.0, # Approximate value for a year in seconds\n}\n\ntime_chart_inverse: dict[str, float] = {\n key: 1 \/ value for key, value in time_chart.items()\n}\n\n\ndef convert_time(time_value: float, unit_from: str, unit_to: str) -> float:\n \"\"\"\n Convert time from one unit to another using the time_chart above.\n\n >>> convert_time(3600, \"seconds\", \"hours\")\n 1.0\n >>> convert_time(3500, \"Seconds\", \"Hours\")\n 0.972\n >>> convert_time(1, \"DaYs\", \"hours\")\n 24.0\n >>> convert_time(120, \"minutes\", \"SeCoNdS\")\n 7200.0\n >>> convert_time(2, \"WEEKS\", \"days\")\n 14.0\n >>> convert_time(0.5, \"hours\", \"MINUTES\")\n 30.0\n >>> convert_time(-3600, \"seconds\", \"hours\")\n Traceback (most recent call last):\n ...\n ValueError: 'time_value' must be a non-negative number.\n >>> convert_time(\"Hello\", \"hours\", \"minutes\")\n Traceback (most recent call last):\n ...\n ValueError: 'time_value' must be a non-negative number.\n >>> convert_time([0, 1, 2], \"weeks\", \"days\")\n Traceback (most recent call last):\n ...\n ValueError: 'time_value' must be a non-negative number.\n >>> convert_time(1, \"cool\", \"century\") # doctest: +ELLIPSIS\n Traceback (most recent call last):\n ...\n ValueError: Invalid unit cool is not in seconds, minutes, hours, days, weeks, ...\n >>> convert_time(1, \"seconds\", \"hot\") # doctest: +ELLIPSIS\n Traceback (most recent call last):\n ...\n ValueError: Invalid unit hot is not in seconds, minutes, hours, days, weeks, ...\n \"\"\"\n if not isinstance(time_value, (int, float)) or time_value < 0:\n msg = \"'time_value' must be a non-negative number.\"\n raise ValueError(msg)\n\n unit_from = unit_from.lower()\n unit_to = unit_to.lower()\n if unit_from not in time_chart or unit_to not in time_chart:\n invalid_unit = unit_from if unit_from not in time_chart else unit_to\n msg = f\"Invalid unit {invalid_unit} is not in {', '.join(time_chart)}.\"\n raise ValueError(msg)\n\n return round(\n time_value * time_chart[unit_from] * time_chart_inverse[unit_to],\n 3,\n )\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n print(f\"{convert_time(3600,'seconds', 'hours') = :,}\")\n print(f\"{convert_time(360, 'days', 'months') = :,}\")\n print(f\"{convert_time(360, 'months', 'years') = :,}\")\n print(f\"{convert_time(1, 'years', 'seconds') = :,}\")\n"} +{"Prompt":"Conversion of volume units. Available Units: Cubic metre,Litre,KiloLitre,Gallon,Cubic yard,Cubic foot,cup USAGE : Import this file into their respective project. Use the function lengthconversion for conversion of volume units. Parameters : value : The number of from units you want to convert fromtype : From which type you want to convert totype : To which type you want to convert REFERENCES : Wikipedia reference: https:en.wikipedia.orgwikiCubicmetre Wikipedia reference: https:en.wikipedia.orgwikiLitre Wikipedia reference: https:en.wiktionary.orgwikikilolitre Wikipedia reference: https:en.wikipedia.orgwikiGallon Wikipedia reference: https:en.wikipedia.orgwikiCubicyard Wikipedia reference: https:en.wikipedia.orgwikiCubicfoot Wikipedia reference: https:en.wikipedia.orgwikiCupunit Conversion between volume units. volumeconversion4, cubic meter, litre 4000 volumeconversion1, litre, gallon 0.264172 volumeconversion1, kilolitre, cubic meter 1 volumeconversion3, gallon, cubic yard 0.017814279 volumeconversion2, cubic yard, litre 1529.1 volumeconversion4, cubic foot, cup 473.396 volumeconversion1, cup, kilolitre 0.000236588 volumeconversion4, wrongUnit, litre Traceback most recent call last: ... ValueError: Invalid 'fromtype' value: 'wrongUnit' Supported values are: cubic meter, litre, kilolitre, gallon, cubic yard, cubic foot, cup","Completions":"from typing import NamedTuple\n\n\nclass FromTo(NamedTuple):\n from_factor: float\n to_factor: float\n\n\nMETRIC_CONVERSION = {\n \"cubic meter\": FromTo(1, 1),\n \"litre\": FromTo(0.001, 1000),\n \"kilolitre\": FromTo(1, 1),\n \"gallon\": FromTo(0.00454, 264.172),\n \"cubic yard\": FromTo(0.76455, 1.30795),\n \"cubic foot\": FromTo(0.028, 35.3147),\n \"cup\": FromTo(0.000236588, 4226.75),\n}\n\n\ndef volume_conversion(value: float, from_type: str, to_type: str) -> float:\n \"\"\"\n Conversion between volume units.\n >>> volume_conversion(4, \"cubic meter\", \"litre\")\n 4000\n >>> volume_conversion(1, \"litre\", \"gallon\")\n 0.264172\n >>> volume_conversion(1, \"kilolitre\", \"cubic meter\")\n 1\n >>> volume_conversion(3, \"gallon\", \"cubic yard\")\n 0.017814279\n >>> volume_conversion(2, \"cubic yard\", \"litre\")\n 1529.1\n >>> volume_conversion(4, \"cubic foot\", \"cup\")\n 473.396\n >>> volume_conversion(1, \"cup\", \"kilolitre\")\n 0.000236588\n >>> volume_conversion(4, \"wrongUnit\", \"litre\")\n Traceback (most recent call last):\n ...\n ValueError: Invalid 'from_type' value: 'wrongUnit' Supported values are:\n cubic meter, litre, kilolitre, gallon, cubic yard, cubic foot, cup\n \"\"\"\n if from_type not in METRIC_CONVERSION:\n raise ValueError(\n f\"Invalid 'from_type' value: {from_type!r} Supported values are:\\n\"\n + \", \".join(METRIC_CONVERSION)\n )\n if to_type not in METRIC_CONVERSION:\n raise ValueError(\n f\"Invalid 'to_type' value: {to_type!r}. Supported values are:\\n\"\n + \", \".join(METRIC_CONVERSION)\n )\n return (\n value\n * METRIC_CONVERSION[from_type].from_factor\n * METRIC_CONVERSION[to_type].to_factor\n )\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Conversion of weight units. author Anubhav Solanki license MIT version 1.1.0 maintainer Anubhav Solanki email anubhavsolanki0gmail.com USAGE : Import this file into their respective project. Use the function weightconversion for conversion of weight units. Parameters : fromtype : From which type you want to convert totype : To which type you want to convert value : the value which you want to convert REFERENCES : Wikipedia reference: https:en.wikipedia.orgwikiKilogram Wikipedia reference: https:en.wikipedia.orgwikiGram Wikipedia reference: https:en.wikipedia.orgwikiMillimetre Wikipedia reference: https:en.wikipedia.orgwikiTonne Wikipedia reference: https:en.wikipedia.orgwikiLongton Wikipedia reference: https:en.wikipedia.orgwikiShortton Wikipedia reference: https:en.wikipedia.orgwikiPound Wikipedia reference: https:en.wikipedia.orgwikiOunce Wikipedia reference: https:en.wikipedia.orgwikiFinenessKarat Wikipedia reference: https:en.wikipedia.orgwikiDaltonunit Wikipedia reference: https:en.wikipedia.orgwikiStoneunit Conversion of weight unit with the help of KILOGRAMCHART kilogram : 1, gram : pow10, 3, milligram : pow10, 6, metricton : pow10, 3, longton : 0.0009842073, shortton : 0.0011023122, pound : 2.2046244202, stone: 0.1574731728, ounce : 35.273990723, carrat : 5000, atomicmassunit : 6.022136652E26 weightconversionkilogram,kilogram,4 4 weightconversionkilogram,gram,1 1000 weightconversionkilogram,milligram,4 4000000 weightconversionkilogram,metricton,4 0.004 weightconversionkilogram,longton,3 0.0029526219 weightconversionkilogram,shortton,1 0.0011023122 weightconversionkilogram,pound,4 8.8184976808 weightconversionkilogram,stone,5 0.7873658640000001 weightconversionkilogram,ounce,4 141.095962892 weightconversionkilogram,carrat,3 15000 weightconversionkilogram,atomicmassunit,1 6.022136652e26 weightconversiongram,kilogram,1 0.001 weightconversiongram,gram,3 3.0 weightconversiongram,milligram,2 2000.0 weightconversiongram,metricton,4 4e06 weightconversiongram,longton,3 2.9526219e06 weightconversiongram,shortton,3 3.3069366000000003e06 weightconversiongram,pound,3 0.0066138732606 weightconversiongram,stone,4 0.0006298926912000001 weightconversiongram,ounce,1 0.035273990723 weightconversiongram,carrat,2 10.0 weightconversiongram,atomicmassunit,1 6.022136652e23 weightconversionmilligram,kilogram,1 1e06 weightconversionmilligram,gram,2 0.002 weightconversionmilligram,milligram,3 3.0 weightconversionmilligram,metricton,3 3e09 weightconversionmilligram,longton,3 2.9526219e09 weightconversionmilligram,shortton,1 1.1023122e09 weightconversionmilligram,pound,3 6.6138732605999995e06 weightconversionmilligram,ounce,2 7.054798144599999e05 weightconversionmilligram,carrat,1 0.005 weightconversionmilligram,atomicmassunit,1 6.022136652e20 weightconversionmetricton,kilogram,2 2000 weightconversionmetricton,gram,2 2000000 weightconversionmetricton,milligram,3 3000000000 weightconversionmetricton,metricton,2 2.0 weightconversionmetricton,longton,3 2.9526219 weightconversionmetricton,shortton,2 2.2046244 weightconversionmetricton,pound,3 6613.8732606 weightconversionmetricton,ounce,4 141095.96289199998 weightconversionmetricton,carrat,4 20000000 weightconversionmetricton,atomicmassunit,1 6.022136652e29 weightconversionlongton,kilogram,4 4064.18432 weightconversionlongton,gram,4 4064184.32 weightconversionlongton,milligram,3 3048138240.0 weightconversionlongton,metricton,4 4.06418432 weightconversionlongton,longton,3 2.999999907217152 weightconversionlongton,shortton,1 1.119999989746176 weightconversionlongton,pound,3 6720.000000049448 weightconversionlongton,ounce,1 35840.000000060514 weightconversionlongton,carrat,4 20320921.599999998 weightconversionlongton,atomicmassunit,4 2.4475073353955697e30 weightconversionshortton,kilogram,3 2721.5519999999997 weightconversionshortton,gram,3 2721552.0 weightconversionshortton,milligram,1 907184000.0 weightconversionshortton,metricton,4 3.628736 weightconversionshortton,longton,3 2.6785713457296 weightconversionshortton,shortton,3 2.9999999725344 weightconversionshortton,pound,2 4000.0000000294335 weightconversionshortton,ounce,4 128000.00000021611 weightconversionshortton,carrat,4 18143680.0 weightconversionshortton,atomicmassunit,1 5.463186016507968e29 weightconversionpound,kilogram,4 1.814368 weightconversionpound,gram,2 907.184 weightconversionpound,milligram,3 1360776.0 weightconversionpound,metricton,3 0.001360776 weightconversionpound,longton,2 0.0008928571152432 weightconversionpound,shortton,1 0.0004999999954224 weightconversionpound,pound,3 3.0000000000220752 weightconversionpound,ounce,1 16.000000000027015 weightconversionpound,carrat,1 2267.96 weightconversionpound,atomicmassunit,4 1.0926372033015936e27 weightconversionstone,kilogram,5 31.751450000000002 weightconversionstone,gram,2 12700.58 weightconversionstone,milligram,3 19050870.0 weightconversionstone,metricton,3 0.01905087 weightconversionstone,longton,3 0.018750005325351003 weightconversionstone,shortton,3 0.021000006421614002 weightconversionstone,pound,2 28.00000881870372 weightconversionstone,ounce,1 224.00007054835967 weightconversionstone,carrat,2 63502.9 weightconversionounce,kilogram,3 0.0850485 weightconversionounce,gram,3 85.0485 weightconversionounce,milligram,4 113398.0 weightconversionounce,metricton,4 0.000113398 weightconversionounce,longton,4 0.0001116071394054 weightconversionounce,shortton,4 0.0001249999988556 weightconversionounce,pound,1 0.0625000000004599 weightconversionounce,ounce,2 2.000000000003377 weightconversionounce,carrat,1 141.7475 weightconversionounce,atomicmassunit,1 1.70724563015874e25 weightconversioncarrat,kilogram,1 0.0002 weightconversioncarrat,gram,4 0.8 weightconversioncarrat,milligram,2 400.0 weightconversioncarrat,metricton,2 4.0000000000000003e07 weightconversioncarrat,longton,3 5.9052438e07 weightconversioncarrat,shortton,4 8.818497600000002e07 weightconversioncarrat,pound,1 0.00044092488404000004 weightconversioncarrat,ounce,2 0.0141095962892 weightconversioncarrat,carrat,4 4.0 weightconversioncarrat,atomicmassunit,4 4.8177093216e23 weightconversionatomicmassunit,kilogram,4 6.642160796e27 weightconversionatomicmassunit,gram,2 3.321080398e24 weightconversionatomicmassunit,milligram,2 3.3210803980000002e21 weightconversionatomicmassunit,metricton,3 4.9816205970000004e30 weightconversionatomicmassunit,longton,3 4.9029473573977584e30 weightconversionatomicmassunit,shortton,1 1.830433719948128e30 weightconversionatomicmassunit,pound,3 1.0982602420317504e26 weightconversionatomicmassunit,ounce,2 1.1714775914938915e25 weightconversionatomicmassunit,carrat,2 1.660540199e23 weightconversionatomicmassunit,atomicmassunit,2 1.999999998903455","Completions":"KILOGRAM_CHART: dict[str, float] = {\n \"kilogram\": 1,\n \"gram\": pow(10, 3),\n \"milligram\": pow(10, 6),\n \"metric-ton\": pow(10, -3),\n \"long-ton\": 0.0009842073,\n \"short-ton\": 0.0011023122,\n \"pound\": 2.2046244202,\n \"stone\": 0.1574731728,\n \"ounce\": 35.273990723,\n \"carrat\": 5000,\n \"atomic-mass-unit\": 6.022136652e26,\n}\n\nWEIGHT_TYPE_CHART: dict[str, float] = {\n \"kilogram\": 1,\n \"gram\": pow(10, -3),\n \"milligram\": pow(10, -6),\n \"metric-ton\": pow(10, 3),\n \"long-ton\": 1016.04608,\n \"short-ton\": 907.184,\n \"pound\": 0.453592,\n \"stone\": 6.35029,\n \"ounce\": 0.0283495,\n \"carrat\": 0.0002,\n \"atomic-mass-unit\": 1.660540199e-27,\n}\n\n\ndef weight_conversion(from_type: str, to_type: str, value: float) -> float:\n \"\"\"\n Conversion of weight unit with the help of KILOGRAM_CHART\n\n \"kilogram\" : 1,\n \"gram\" : pow(10, 3),\n \"milligram\" : pow(10, 6),\n \"metric-ton\" : pow(10, -3),\n \"long-ton\" : 0.0009842073,\n \"short-ton\" : 0.0011023122,\n \"pound\" : 2.2046244202,\n \"stone\": 0.1574731728,\n \"ounce\" : 35.273990723,\n \"carrat\" : 5000,\n \"atomic-mass-unit\" : 6.022136652E+26\n\n >>> weight_conversion(\"kilogram\",\"kilogram\",4)\n 4\n >>> weight_conversion(\"kilogram\",\"gram\",1)\n 1000\n >>> weight_conversion(\"kilogram\",\"milligram\",4)\n 4000000\n >>> weight_conversion(\"kilogram\",\"metric-ton\",4)\n 0.004\n >>> weight_conversion(\"kilogram\",\"long-ton\",3)\n 0.0029526219\n >>> weight_conversion(\"kilogram\",\"short-ton\",1)\n 0.0011023122\n >>> weight_conversion(\"kilogram\",\"pound\",4)\n 8.8184976808\n >>> weight_conversion(\"kilogram\",\"stone\",5)\n 0.7873658640000001\n >>> weight_conversion(\"kilogram\",\"ounce\",4)\n 141.095962892\n >>> weight_conversion(\"kilogram\",\"carrat\",3)\n 15000\n >>> weight_conversion(\"kilogram\",\"atomic-mass-unit\",1)\n 6.022136652e+26\n >>> weight_conversion(\"gram\",\"kilogram\",1)\n 0.001\n >>> weight_conversion(\"gram\",\"gram\",3)\n 3.0\n >>> weight_conversion(\"gram\",\"milligram\",2)\n 2000.0\n >>> weight_conversion(\"gram\",\"metric-ton\",4)\n 4e-06\n >>> weight_conversion(\"gram\",\"long-ton\",3)\n 2.9526219e-06\n >>> weight_conversion(\"gram\",\"short-ton\",3)\n 3.3069366000000003e-06\n >>> weight_conversion(\"gram\",\"pound\",3)\n 0.0066138732606\n >>> weight_conversion(\"gram\",\"stone\",4)\n 0.0006298926912000001\n >>> weight_conversion(\"gram\",\"ounce\",1)\n 0.035273990723\n >>> weight_conversion(\"gram\",\"carrat\",2)\n 10.0\n >>> weight_conversion(\"gram\",\"atomic-mass-unit\",1)\n 6.022136652e+23\n >>> weight_conversion(\"milligram\",\"kilogram\",1)\n 1e-06\n >>> weight_conversion(\"milligram\",\"gram\",2)\n 0.002\n >>> weight_conversion(\"milligram\",\"milligram\",3)\n 3.0\n >>> weight_conversion(\"milligram\",\"metric-ton\",3)\n 3e-09\n >>> weight_conversion(\"milligram\",\"long-ton\",3)\n 2.9526219e-09\n >>> weight_conversion(\"milligram\",\"short-ton\",1)\n 1.1023122e-09\n >>> weight_conversion(\"milligram\",\"pound\",3)\n 6.6138732605999995e-06\n >>> weight_conversion(\"milligram\",\"ounce\",2)\n 7.054798144599999e-05\n >>> weight_conversion(\"milligram\",\"carrat\",1)\n 0.005\n >>> weight_conversion(\"milligram\",\"atomic-mass-unit\",1)\n 6.022136652e+20\n >>> weight_conversion(\"metric-ton\",\"kilogram\",2)\n 2000\n >>> weight_conversion(\"metric-ton\",\"gram\",2)\n 2000000\n >>> weight_conversion(\"metric-ton\",\"milligram\",3)\n 3000000000\n >>> weight_conversion(\"metric-ton\",\"metric-ton\",2)\n 2.0\n >>> weight_conversion(\"metric-ton\",\"long-ton\",3)\n 2.9526219\n >>> weight_conversion(\"metric-ton\",\"short-ton\",2)\n 2.2046244\n >>> weight_conversion(\"metric-ton\",\"pound\",3)\n 6613.8732606\n >>> weight_conversion(\"metric-ton\",\"ounce\",4)\n 141095.96289199998\n >>> weight_conversion(\"metric-ton\",\"carrat\",4)\n 20000000\n >>> weight_conversion(\"metric-ton\",\"atomic-mass-unit\",1)\n 6.022136652e+29\n >>> weight_conversion(\"long-ton\",\"kilogram\",4)\n 4064.18432\n >>> weight_conversion(\"long-ton\",\"gram\",4)\n 4064184.32\n >>> weight_conversion(\"long-ton\",\"milligram\",3)\n 3048138240.0\n >>> weight_conversion(\"long-ton\",\"metric-ton\",4)\n 4.06418432\n >>> weight_conversion(\"long-ton\",\"long-ton\",3)\n 2.999999907217152\n >>> weight_conversion(\"long-ton\",\"short-ton\",1)\n 1.119999989746176\n >>> weight_conversion(\"long-ton\",\"pound\",3)\n 6720.000000049448\n >>> weight_conversion(\"long-ton\",\"ounce\",1)\n 35840.000000060514\n >>> weight_conversion(\"long-ton\",\"carrat\",4)\n 20320921.599999998\n >>> weight_conversion(\"long-ton\",\"atomic-mass-unit\",4)\n 2.4475073353955697e+30\n >>> weight_conversion(\"short-ton\",\"kilogram\",3)\n 2721.5519999999997\n >>> weight_conversion(\"short-ton\",\"gram\",3)\n 2721552.0\n >>> weight_conversion(\"short-ton\",\"milligram\",1)\n 907184000.0\n >>> weight_conversion(\"short-ton\",\"metric-ton\",4)\n 3.628736\n >>> weight_conversion(\"short-ton\",\"long-ton\",3)\n 2.6785713457296\n >>> weight_conversion(\"short-ton\",\"short-ton\",3)\n 2.9999999725344\n >>> weight_conversion(\"short-ton\",\"pound\",2)\n 4000.0000000294335\n >>> weight_conversion(\"short-ton\",\"ounce\",4)\n 128000.00000021611\n >>> weight_conversion(\"short-ton\",\"carrat\",4)\n 18143680.0\n >>> weight_conversion(\"short-ton\",\"atomic-mass-unit\",1)\n 5.463186016507968e+29\n >>> weight_conversion(\"pound\",\"kilogram\",4)\n 1.814368\n >>> weight_conversion(\"pound\",\"gram\",2)\n 907.184\n >>> weight_conversion(\"pound\",\"milligram\",3)\n 1360776.0\n >>> weight_conversion(\"pound\",\"metric-ton\",3)\n 0.001360776\n >>> weight_conversion(\"pound\",\"long-ton\",2)\n 0.0008928571152432\n >>> weight_conversion(\"pound\",\"short-ton\",1)\n 0.0004999999954224\n >>> weight_conversion(\"pound\",\"pound\",3)\n 3.0000000000220752\n >>> weight_conversion(\"pound\",\"ounce\",1)\n 16.000000000027015\n >>> weight_conversion(\"pound\",\"carrat\",1)\n 2267.96\n >>> weight_conversion(\"pound\",\"atomic-mass-unit\",4)\n 1.0926372033015936e+27\n >>> weight_conversion(\"stone\",\"kilogram\",5)\n 31.751450000000002\n >>> weight_conversion(\"stone\",\"gram\",2)\n 12700.58\n >>> weight_conversion(\"stone\",\"milligram\",3)\n 19050870.0\n >>> weight_conversion(\"stone\",\"metric-ton\",3)\n 0.01905087\n >>> weight_conversion(\"stone\",\"long-ton\",3)\n 0.018750005325351003\n >>> weight_conversion(\"stone\",\"short-ton\",3)\n 0.021000006421614002\n >>> weight_conversion(\"stone\",\"pound\",2)\n 28.00000881870372\n >>> weight_conversion(\"stone\",\"ounce\",1)\n 224.00007054835967\n >>> weight_conversion(\"stone\",\"carrat\",2)\n 63502.9\n >>> weight_conversion(\"ounce\",\"kilogram\",3)\n 0.0850485\n >>> weight_conversion(\"ounce\",\"gram\",3)\n 85.0485\n >>> weight_conversion(\"ounce\",\"milligram\",4)\n 113398.0\n >>> weight_conversion(\"ounce\",\"metric-ton\",4)\n 0.000113398\n >>> weight_conversion(\"ounce\",\"long-ton\",4)\n 0.0001116071394054\n >>> weight_conversion(\"ounce\",\"short-ton\",4)\n 0.0001249999988556\n >>> weight_conversion(\"ounce\",\"pound\",1)\n 0.0625000000004599\n >>> weight_conversion(\"ounce\",\"ounce\",2)\n 2.000000000003377\n >>> weight_conversion(\"ounce\",\"carrat\",1)\n 141.7475\n >>> weight_conversion(\"ounce\",\"atomic-mass-unit\",1)\n 1.70724563015874e+25\n >>> weight_conversion(\"carrat\",\"kilogram\",1)\n 0.0002\n >>> weight_conversion(\"carrat\",\"gram\",4)\n 0.8\n >>> weight_conversion(\"carrat\",\"milligram\",2)\n 400.0\n >>> weight_conversion(\"carrat\",\"metric-ton\",2)\n 4.0000000000000003e-07\n >>> weight_conversion(\"carrat\",\"long-ton\",3)\n 5.9052438e-07\n >>> weight_conversion(\"carrat\",\"short-ton\",4)\n 8.818497600000002e-07\n >>> weight_conversion(\"carrat\",\"pound\",1)\n 0.00044092488404000004\n >>> weight_conversion(\"carrat\",\"ounce\",2)\n 0.0141095962892\n >>> weight_conversion(\"carrat\",\"carrat\",4)\n 4.0\n >>> weight_conversion(\"carrat\",\"atomic-mass-unit\",4)\n 4.8177093216e+23\n >>> weight_conversion(\"atomic-mass-unit\",\"kilogram\",4)\n 6.642160796e-27\n >>> weight_conversion(\"atomic-mass-unit\",\"gram\",2)\n 3.321080398e-24\n >>> weight_conversion(\"atomic-mass-unit\",\"milligram\",2)\n 3.3210803980000002e-21\n >>> weight_conversion(\"atomic-mass-unit\",\"metric-ton\",3)\n 4.9816205970000004e-30\n >>> weight_conversion(\"atomic-mass-unit\",\"long-ton\",3)\n 4.9029473573977584e-30\n >>> weight_conversion(\"atomic-mass-unit\",\"short-ton\",1)\n 1.830433719948128e-30\n >>> weight_conversion(\"atomic-mass-unit\",\"pound\",3)\n 1.0982602420317504e-26\n >>> weight_conversion(\"atomic-mass-unit\",\"ounce\",2)\n 1.1714775914938915e-25\n >>> weight_conversion(\"atomic-mass-unit\",\"carrat\",2)\n 1.660540199e-23\n >>> weight_conversion(\"atomic-mass-unit\",\"atomic-mass-unit\",2)\n 1.999999998903455\n \"\"\"\n if to_type not in KILOGRAM_CHART or from_type not in WEIGHT_TYPE_CHART:\n msg = (\n f\"Invalid 'from_type' or 'to_type' value: {from_type!r}, {to_type!r}\\n\"\n f\"Supported values are: {', '.join(WEIGHT_TYPE_CHART)}\"\n )\n raise ValueError(msg)\n return value * KILOGRAM_CHART[to_type] * WEIGHT_TYPE_CHART[from_type]\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Find the Equilibrium Index of an Array. Reference: https:www.geeksforgeeks.orgequilibriumindexofanarray Python doctest can be run with the following command: python m doctest v equilibriumindex.py Given a sequence arr of size n, this function returns an equilibrium index if any or 1 if no equilibrium index exists. The equilibrium index of an array is an index such that the sum of elements at lower indexes is equal to the sum of elements at higher indexes. Example Input: arr 7, 1, 5, 2, 4, 3, 0 Output: 3 Find the equilibrium index of an array. Args: arr listint: The input array of integers. Returns: int: The equilibrium index or 1 if no equilibrium index exists. Examples: equilibriumindex7, 1, 5, 2, 4, 3, 0 3 equilibriumindex1, 2, 3, 4, 5 1 equilibriumindex1, 1, 1, 1, 1 2 equilibriumindex2, 4, 6, 8, 10, 3 1","Completions":"def equilibrium_index(arr: list[int]) -> int:\n \"\"\"\n Find the equilibrium index of an array.\n\n Args:\n arr (list[int]): The input array of integers.\n\n Returns:\n int: The equilibrium index or -1 if no equilibrium index exists.\n\n Examples:\n >>> equilibrium_index([-7, 1, 5, 2, -4, 3, 0])\n 3\n >>> equilibrium_index([1, 2, 3, 4, 5])\n -1\n >>> equilibrium_index([1, 1, 1, 1, 1])\n 2\n >>> equilibrium_index([2, 4, 6, 8, 10, 3])\n -1\n \"\"\"\n total_sum = sum(arr)\n left_sum = 0\n\n for i, value in enumerate(arr):\n total_sum -= value\n if left_sum == total_sum:\n return i\n left_sum += value\n\n return -1\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Given a list of integers, return elements a, b, c such that a b c 0. Args: nums: list of integers Returns: list of lists of integers where sumeachlist 0 Examples: findtripletswith0sum1, 0, 1, 2, 1, 4 1, 1, 2, 1, 0, 1 findtripletswith0sum findtripletswith0sum0, 0, 0 0, 0, 0 findtripletswith0sum1, 2, 3, 0, 1, 2, 3 3, 0, 3, 3, 1, 2, 2, 1, 3, 2, 0, 2, 1, 0, 1 Function for finding the triplets with a given sum in the array using hashing. Given a list of integers, return elements a, b, c such that a b c 0. Args: nums: list of integers Returns: list of lists of integers where sumeachlist 0 Examples: findtripletswith0sumhashing1, 0, 1, 2, 1, 4 1, 0, 1, 1, 1, 2 findtripletswith0sumhashing findtripletswith0sumhashing0, 0, 0 0, 0, 0 findtripletswith0sumhashing1, 2, 3, 0, 1, 2, 3 1, 0, 1, 3, 1, 2, 2, 0, 2, 2, 1, 3, 3, 0, 3 Time complexity: ON2 Auxiliary Space: ON Initialize the final output array with blank. Set the initial element as arri. to store second elements that can complement the final sum. current sum needed for reaching the target sum Traverse the subarray arri1:. required value for the second element Verify if the desired value exists in the set. finding triplet elements combination. Include the current element in the set for subsequent complement verification. Return all the triplet combinations.","Completions":"from itertools import combinations\n\n\ndef find_triplets_with_0_sum(nums: list[int]) -> list[list[int]]:\n \"\"\"\n Given a list of integers, return elements a, b, c such that a + b + c = 0.\n Args:\n nums: list of integers\n Returns:\n list of lists of integers where sum(each_list) == 0\n Examples:\n >>> find_triplets_with_0_sum([-1, 0, 1, 2, -1, -4])\n [[-1, -1, 2], [-1, 0, 1]]\n >>> find_triplets_with_0_sum([])\n []\n >>> find_triplets_with_0_sum([0, 0, 0])\n [[0, 0, 0]]\n >>> find_triplets_with_0_sum([1, 2, 3, 0, -1, -2, -3])\n [[-3, 0, 3], [-3, 1, 2], [-2, -1, 3], [-2, 0, 2], [-1, 0, 1]]\n \"\"\"\n return [\n list(x)\n for x in sorted({abc for abc in combinations(sorted(nums), 3) if not sum(abc)})\n ]\n\n\ndef find_triplets_with_0_sum_hashing(arr: list[int]) -> list[list[int]]:\n \"\"\"\n Function for finding the triplets with a given sum in the array using hashing.\n\n Given a list of integers, return elements a, b, c such that a + b + c = 0.\n\n Args:\n nums: list of integers\n Returns:\n list of lists of integers where sum(each_list) == 0\n Examples:\n >>> find_triplets_with_0_sum_hashing([-1, 0, 1, 2, -1, -4])\n [[-1, 0, 1], [-1, -1, 2]]\n >>> find_triplets_with_0_sum_hashing([])\n []\n >>> find_triplets_with_0_sum_hashing([0, 0, 0])\n [[0, 0, 0]]\n >>> find_triplets_with_0_sum_hashing([1, 2, 3, 0, -1, -2, -3])\n [[-1, 0, 1], [-3, 1, 2], [-2, 0, 2], [-2, -1, 3], [-3, 0, 3]]\n\n Time complexity: O(N^2)\n Auxiliary Space: O(N)\n\n \"\"\"\n target_sum = 0\n\n # Initialize the final output array with blank.\n output_arr = []\n\n # Set the initial element as arr[i].\n for index, item in enumerate(arr[:-2]):\n # to store second elements that can complement the final sum.\n set_initialize = set()\n\n # current sum needed for reaching the target sum\n current_sum = target_sum - item\n\n # Traverse the subarray arr[i+1:].\n for other_item in arr[index + 1 :]:\n # required value for the second element\n required_value = current_sum - other_item\n\n # Verify if the desired value exists in the set.\n if required_value in set_initialize:\n # finding triplet elements combination.\n combination_array = sorted([item, other_item, required_value])\n if combination_array not in output_arr:\n output_arr.append(combination_array)\n\n # Include the current element in the set\n # for subsequent complement verification.\n set_initialize.add(other_item)\n\n # Return all the triplet combinations.\n return output_arr\n\n\nif __name__ == \"__main__\":\n from doctest import testmod\n\n testmod()\n"} +{"Prompt":"Retrieves the value of an 0indexed 1D index from a 2D array. There are two ways to retrieve values: 1. Index2DArrayIteratormatrix Iteratorint This iterator allows you to iterate through a 2D array by passing in the matrix and calling nextyouriterator. You can also use the iterator in a loop. Examples: listIndex2DArrayIteratormatrix setIndex2DArrayIteratormatrix tupleIndex2DArrayIteratormatrix sumIndex2DArrayIteratormatrix 5 in Index2DArrayIteratormatrix 2. index2darrayin1darray: listint, index: int int This function allows you to provide a 2D array and a 0indexed 1D integer index, and retrieves the integer value at that index. Python doctests can be run using this command: python3 m doctest v index2darrayin1d.py tupleIndex2DArrayIterator5, 523, 1, 34, 0 5, 523, 1, 34, 0 tupleIndex2DArrayIterator5, 523, 1, 34, 0 5, 523, 1, 34, 0 tupleIndex2DArrayIterator5, 523, 1, 34, 0 5, 523, 1, 34, 0 t Index2DArrayIterator5, 2, 25, 23, 14, 5, 324, 1, 0 tuplet 5, 2, 25, 23, 14, 5, 324, 1, 0 listt 5, 2, 25, 23, 14, 5, 324, 1, 0 sortedt 1, 0, 2, 5, 5, 14, 23, 25, 324 tuplet3 23 sumt 397 1 in t True t iterIndex2DArrayIterator5, 523, 1, 34, 0 nextt 5 nextt 523 Retrieves the value of the onedimensional index from a twodimensional array. Args: array: A 2D array of integers where all rows are the same size and all columns are the same size. index: A 1D index. Returns: int: The 0indexed value of the 1D index in the array. Examples: index2darrayin1d0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 5 5 index2darrayin1d0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 1 Traceback most recent call last: ... ValueError: index out of range index2darrayin1d0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 Traceback most recent call last: ... ValueError: index out of range index2darrayin1d, 0 Traceback most recent call last: ... ValueError: no items in array","Completions":"from collections.abc import Iterator\nfrom dataclasses import dataclass\n\n\n@dataclass\nclass Index2DArrayIterator:\n matrix: list[list[int]]\n\n def __iter__(self) -> Iterator[int]:\n \"\"\"\n >>> tuple(Index2DArrayIterator([[5], [-523], [-1], [34], [0]]))\n (5, -523, -1, 34, 0)\n >>> tuple(Index2DArrayIterator([[5, -523, -1], [34, 0]]))\n (5, -523, -1, 34, 0)\n >>> tuple(Index2DArrayIterator([[5, -523, -1, 34, 0]]))\n (5, -523, -1, 34, 0)\n >>> t = Index2DArrayIterator([[5, 2, 25], [23, 14, 5], [324, -1, 0]])\n >>> tuple(t)\n (5, 2, 25, 23, 14, 5, 324, -1, 0)\n >>> list(t)\n [5, 2, 25, 23, 14, 5, 324, -1, 0]\n >>> sorted(t)\n [-1, 0, 2, 5, 5, 14, 23, 25, 324]\n >>> tuple(t)[3]\n 23\n >>> sum(t)\n 397\n >>> -1 in t\n True\n >>> t = iter(Index2DArrayIterator([[5], [-523], [-1], [34], [0]]))\n >>> next(t)\n 5\n >>> next(t)\n -523\n \"\"\"\n for row in self.matrix:\n yield from row\n\n\ndef index_2d_array_in_1d(array: list[list[int]], index: int) -> int:\n \"\"\"\n Retrieves the value of the one-dimensional index from a two-dimensional array.\n\n Args:\n array: A 2D array of integers where all rows are the same size and all\n columns are the same size.\n index: A 1D index.\n\n Returns:\n int: The 0-indexed value of the 1D index in the array.\n\n Examples:\n >>> index_2d_array_in_1d([[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]], 5)\n 5\n >>> index_2d_array_in_1d([[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]], -1)\n Traceback (most recent call last):\n ...\n ValueError: index out of range\n >>> index_2d_array_in_1d([[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]], 12)\n Traceback (most recent call last):\n ...\n ValueError: index out of range\n >>> index_2d_array_in_1d([[]], 0)\n Traceback (most recent call last):\n ...\n ValueError: no items in array\n \"\"\"\n rows = len(array)\n cols = len(array[0])\n\n if rows == 0 or cols == 0:\n raise ValueError(\"no items in array\")\n\n if index < 0 or index >= rows * cols:\n raise ValueError(\"index out of range\")\n\n return array[index \/\/ cols][index % cols]\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Given an array of integers and an integer k, find the kth largest element in the array. https:stackoverflow.comquestions251781 Partitions list based on the pivot element. This function rearranges the elements in the input list 'elements' such that all elements greater than or equal to the chosen pivot are on the right side of the pivot, and all elements smaller than the pivot are on the left side. Args: arr: The list to be partitioned low: The lower index of the list high: The higher index of the list Returns: int: The index of pivot element after partitioning Examples: partition3, 1, 4, 5, 9, 2, 6, 5, 3, 5, 0, 9 4 partition7, 1, 4, 5, 9, 2, 6, 5, 8, 0, 8 1 partition'apple', 'cherry', 'date', 'banana', 0, 3 2 partition3.1, 1.2, 5.6, 4.7, 0, 3 1 Finds the kth largest element in a list. Should deliver similar results to: python def kthlargestelementarr, position: return sortedarrposition Args: nums: The list of numbers. k: The position of the desired kth largest element. Returns: int: The kth largest element. Examples: kthlargestelement3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 3 5 kthlargestelement2, 5, 6, 1, 9, 3, 8, 4, 7, 3, 5, 1 9 kthlargestelement2, 5, 6, 1, 9, 3, 8, 4, 7, 3, 5, 2 Traceback most recent call last: ... ValueError: Invalid value of 'position' kthlargestelement9, 1, 3, 6, 7, 9, 8, 4, 2, 4, 9, 110 Traceback most recent call last: ... ValueError: Invalid value of 'position' kthlargestelement1, 2, 4, 3, 5, 9, 7, 6, 5, 9, 3, 0 Traceback most recent call last: ... ValueError: Invalid value of 'position' kthlargestelement'apple', 'cherry', 'date', 'banana', 2 'cherry' kthlargestelement3.1, 1.2, 5.6, 4.7,7.9,5,0, 2 5.6 kthlargestelement2, 5, 4, 1, 1 1 kthlargestelement, 1 1 kthlargestelement3.1, 1.2, 5.6, 4.7, 7.9, 5, 0, 1.5 Traceback most recent call last: ... ValueError: The position should be an integer kthlargestelement4, 6, 1, 2, 4 Traceback most recent call last: ... TypeError: 'tuple' object does not support item assignment","Completions":"def partition(arr: list[int], low: int, high: int) -> int:\n \"\"\"\n Partitions list based on the pivot element.\n\n This function rearranges the elements in the input list 'elements' such that\n all elements greater than or equal to the chosen pivot are on the right side\n of the pivot, and all elements smaller than the pivot are on the left side.\n\n Args:\n arr: The list to be partitioned\n low: The lower index of the list\n high: The higher index of the list\n\n Returns:\n int: The index of pivot element after partitioning\n\n Examples:\n >>> partition([3, 1, 4, 5, 9, 2, 6, 5, 3, 5], 0, 9)\n 4\n >>> partition([7, 1, 4, 5, 9, 2, 6, 5, 8], 0, 8)\n 1\n >>> partition(['apple', 'cherry', 'date', 'banana'], 0, 3)\n 2\n >>> partition([3.1, 1.2, 5.6, 4.7], 0, 3)\n 1\n \"\"\"\n pivot = arr[high]\n i = low - 1\n for j in range(low, high):\n if arr[j] >= pivot:\n i += 1\n arr[i], arr[j] = arr[j], arr[i]\n arr[i + 1], arr[high] = arr[high], arr[i + 1]\n return i + 1\n\n\ndef kth_largest_element(arr: list[int], position: int) -> int:\n \"\"\"\n Finds the kth largest element in a list.\n Should deliver similar results to:\n ```python\n def kth_largest_element(arr, position):\n return sorted(arr)[-position]\n ```\n\n Args:\n nums: The list of numbers.\n k: The position of the desired kth largest element.\n\n Returns:\n int: The kth largest element.\n\n Examples:\n >>> kth_largest_element([3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5], 3)\n 5\n >>> kth_largest_element([2, 5, 6, 1, 9, 3, 8, 4, 7, 3, 5], 1)\n 9\n >>> kth_largest_element([2, 5, 6, 1, 9, 3, 8, 4, 7, 3, 5], -2)\n Traceback (most recent call last):\n ...\n ValueError: Invalid value of 'position'\n >>> kth_largest_element([9, 1, 3, 6, 7, 9, 8, 4, 2, 4, 9], 110)\n Traceback (most recent call last):\n ...\n ValueError: Invalid value of 'position'\n >>> kth_largest_element([1, 2, 4, 3, 5, 9, 7, 6, 5, 9, 3], 0)\n Traceback (most recent call last):\n ...\n ValueError: Invalid value of 'position'\n >>> kth_largest_element(['apple', 'cherry', 'date', 'banana'], 2)\n 'cherry'\n >>> kth_largest_element([3.1, 1.2, 5.6, 4.7,7.9,5,0], 2)\n 5.6\n >>> kth_largest_element([-2, -5, -4, -1], 1)\n -1\n >>> kth_largest_element([], 1)\n -1\n >>> kth_largest_element([3.1, 1.2, 5.6, 4.7, 7.9, 5, 0], 1.5)\n Traceback (most recent call last):\n ...\n ValueError: The position should be an integer\n >>> kth_largest_element((4, 6, 1, 2), 4)\n Traceback (most recent call last):\n ...\n TypeError: 'tuple' object does not support item assignment\n \"\"\"\n if not arr:\n return -1\n if not isinstance(position, int):\n raise ValueError(\"The position should be an integer\")\n if not 1 <= position <= len(arr):\n raise ValueError(\"Invalid value of 'position'\")\n low, high = 0, len(arr) - 1\n while low <= high:\n if low > len(arr) - 1 or high < 0:\n return -1\n pivot_index = partition(arr, low, high)\n if pivot_index == position - 1:\n return arr[pivot_index]\n elif pivot_index > position - 1:\n high = pivot_index - 1\n else:\n low = pivot_index + 1\n return -1\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"https:www.enjoyalgorithms.comblogmedianoftwosortedarrays Find the median of two arrays. Args: nums1: The first array. nums2: The second array. Returns: The median of the two arrays. Examples: findmediansortedarrays1, 3, 2 2.0 findmediansortedarrays1, 2, 3, 4 2.5 findmediansortedarrays0, 0, 0, 0 0.0 findmediansortedarrays, Traceback most recent call last: ... ValueError: Both input arrays are empty. findmediansortedarrays, 1 1.0 findmediansortedarrays1000, 1000 0.0 findmediansortedarrays1.1, 2.2, 3.3, 4.4 2.75 Merge the arrays into a single sorted array. If the total number of elements is even, calculate the average of the two middle elements as the median.","Completions":"def find_median_sorted_arrays(nums1: list[int], nums2: list[int]) -> float:\n \"\"\"\n Find the median of two arrays.\n\n Args:\n nums1: The first array.\n nums2: The second array.\n\n Returns:\n The median of the two arrays.\n\n Examples:\n >>> find_median_sorted_arrays([1, 3], [2])\n 2.0\n\n >>> find_median_sorted_arrays([1, 2], [3, 4])\n 2.5\n\n >>> find_median_sorted_arrays([0, 0], [0, 0])\n 0.0\n\n >>> find_median_sorted_arrays([], [])\n Traceback (most recent call last):\n ...\n ValueError: Both input arrays are empty.\n\n >>> find_median_sorted_arrays([], [1])\n 1.0\n\n >>> find_median_sorted_arrays([-1000], [1000])\n 0.0\n\n >>> find_median_sorted_arrays([-1.1, -2.2], [-3.3, -4.4])\n -2.75\n \"\"\"\n if not nums1 and not nums2:\n raise ValueError(\"Both input arrays are empty.\")\n\n # Merge the arrays into a single sorted array.\n merged = sorted(nums1 + nums2)\n total = len(merged)\n\n if total % 2 == 1: # If the total number of elements is odd\n return float(merged[total \/\/ 2]) # then return the middle element\n\n # If the total number of elements is even, calculate\n # the average of the two middle elements as the median.\n middle1 = merged[total \/\/ 2 - 1]\n middle2 = merged[total \/\/ 2]\n return (float(middle1) + float(middle2)) \/ 2.0\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"https:leetcode.comproblemsmonotonicarray Check if a list is monotonic. ismonotonic1, 2, 2, 3 True ismonotonic6, 5, 4, 4 True ismonotonic1, 3, 2 False Test the function with your examples Test the function with your examples","Completions":"# https:\/\/leetcode.com\/problems\/monotonic-array\/\ndef is_monotonic(nums: list[int]) -> bool:\n \"\"\"\n Check if a list is monotonic.\n\n >>> is_monotonic([1, 2, 2, 3])\n True\n >>> is_monotonic([6, 5, 4, 4])\n True\n >>> is_monotonic([1, 3, 2])\n False\n \"\"\"\n return all(nums[i] <= nums[i + 1] for i in range(len(nums) - 1)) or all(\n nums[i] >= nums[i + 1] for i in range(len(nums) - 1)\n )\n\n\n# Test the function with your examples\nif __name__ == \"__main__\":\n # Test the function with your examples\n print(is_monotonic([1, 2, 2, 3])) # Output: True\n print(is_monotonic([6, 5, 4, 4])) # Output: True\n print(is_monotonic([1, 3, 2])) # Output: False\n"} +{"Prompt":"!usrbinenv python3 Given an array of integers and an integer reqsum, find the number of pairs of array elements whose sum is equal to reqsum. https:practice.geeksforgeeks.orgproblemscountpairswithgivensum50220 Return the no. of pairs with sum sum pairswithsum1, 5, 7, 1, 6 2 pairswithsum1, 1, 1, 1, 1, 1, 1, 1, 2 28 pairswithsum1, 7, 6, 2, 5, 4, 3, 1, 9, 8, 7 4","Completions":"#!\/usr\/bin\/env python3\n\n\"\"\"\nGiven an array of integers and an integer req_sum, find the number of pairs of array\nelements whose sum is equal to req_sum.\n\nhttps:\/\/practice.geeksforgeeks.org\/problems\/count-pairs-with-given-sum5022\/0\n\"\"\"\nfrom itertools import combinations\n\n\ndef pairs_with_sum(arr: list, req_sum: int) -> int:\n \"\"\"\n Return the no. of pairs with sum \"sum\"\n >>> pairs_with_sum([1, 5, 7, 1], 6)\n 2\n >>> pairs_with_sum([1, 1, 1, 1, 1, 1, 1, 1], 2)\n 28\n >>> pairs_with_sum([1, 7, 6, 2, 5, 4, 3, 1, 9, 8], 7)\n 4\n \"\"\"\n return len([1 for a, b in combinations(arr, 2) if a + b == req_sum])\n\n\nif __name__ == \"__main__\":\n from doctest import testmod\n\n testmod()\n"} +{"Prompt":"Return all permutations. permuterecursive1, 2, 3 3, 2, 1, 2, 3, 1, 1, 3, 2, 3, 1, 2, 2, 1, 3, 1, 2, 3 Return all permutations of the given list. permutebacktrack1, 2, 3 1, 2, 3, 1, 3, 2, 2, 1, 3, 2, 3, 1, 3, 2, 1, 3, 1, 2","Completions":"def permute_recursive(nums: list[int]) -> list[list[int]]:\n \"\"\"\n Return all permutations.\n\n >>> permute_recursive([1, 2, 3])\n [[3, 2, 1], [2, 3, 1], [1, 3, 2], [3, 1, 2], [2, 1, 3], [1, 2, 3]]\n \"\"\"\n result: list[list[int]] = []\n if len(nums) == 0:\n return [[]]\n for _ in range(len(nums)):\n n = nums.pop(0)\n permutations = permute_recursive(nums.copy())\n for perm in permutations:\n perm.append(n)\n result.extend(permutations)\n nums.append(n)\n return result\n\n\ndef permute_backtrack(nums: list[int]) -> list[list[int]]:\n \"\"\"\n Return all permutations of the given list.\n\n >>> permute_backtrack([1, 2, 3])\n [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 2, 1], [3, 1, 2]]\n \"\"\"\n\n def backtrack(start: int) -> None:\n if start == len(nums) - 1:\n output.append(nums[:])\n else:\n for i in range(start, len(nums)):\n nums[start], nums[i] = nums[i], nums[start]\n backtrack(start + 1)\n nums[start], nums[i] = nums[i], nums[start] # backtrack\n\n output: list[list[int]] = []\n backtrack(0)\n return output\n\n\nif __name__ == \"__main__\":\n import doctest\n\n result = permute_backtrack([1, 2, 3])\n print(result)\n doctest.testmod()\n"} +{"Prompt":"Author : Alexander Pantyukhin Date : November 3, 2022 Implement the class of prefix sum with useful functions based on it. The function returns the sum of array from the start to the end indexes. Runtime : O1 Space: O1 PrefixSum1,2,3.getsum0, 2 6 PrefixSum1,2,3.getsum1, 2 5 PrefixSum1,2,3.getsum2, 2 3 PrefixSum1,2,3.getsum2, 3 Traceback most recent call last: ... IndexError: list index out of range The function returns True if array contains the targetsum, False otherwise. Runtime : On Space: On PrefixSum1,2,3.containssum6 True PrefixSum1,2,3.containssum5 True PrefixSum1,2,3.containssum3 True PrefixSum1,2,3.containssum4 False PrefixSum1,2,3.containssum7 False PrefixSum1,2,3.containssum2 True","Completions":"class PrefixSum:\n def __init__(self, array: list[int]) -> None:\n len_array = len(array)\n self.prefix_sum = [0] * len_array\n\n if len_array > 0:\n self.prefix_sum[0] = array[0]\n\n for i in range(1, len_array):\n self.prefix_sum[i] = self.prefix_sum[i - 1] + array[i]\n\n def get_sum(self, start: int, end: int) -> int:\n \"\"\"\n The function returns the sum of array from the start to the end indexes.\n Runtime : O(1)\n Space: O(1)\n\n >>> PrefixSum([1,2,3]).get_sum(0, 2)\n 6\n >>> PrefixSum([1,2,3]).get_sum(1, 2)\n 5\n >>> PrefixSum([1,2,3]).get_sum(2, 2)\n 3\n >>> PrefixSum([1,2,3]).get_sum(2, 3)\n Traceback (most recent call last):\n ...\n IndexError: list index out of range\n \"\"\"\n if start == 0:\n return self.prefix_sum[end]\n\n return self.prefix_sum[end] - self.prefix_sum[start - 1]\n\n def contains_sum(self, target_sum: int) -> bool:\n \"\"\"\n The function returns True if array contains the target_sum,\n False otherwise.\n\n Runtime : O(n)\n Space: O(n)\n\n >>> PrefixSum([1,2,3]).contains_sum(6)\n True\n >>> PrefixSum([1,2,3]).contains_sum(5)\n True\n >>> PrefixSum([1,2,3]).contains_sum(3)\n True\n >>> PrefixSum([1,2,3]).contains_sum(4)\n False\n >>> PrefixSum([1,2,3]).contains_sum(7)\n False\n >>> PrefixSum([1,-2,3]).contains_sum(2)\n True\n \"\"\"\n\n sums = {0}\n for sum_item in self.prefix_sum:\n if sum_item - target_sum in sums:\n return True\n\n sums.add(sum_item)\n\n return False\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Calculate the Product Sum from a Special Array. reference: https:dev.tosfrasicaalgorithmsproductsumfromanarraydc6 Python doctests can be run with the following command: python m doctest v productsum.py Calculate the product sum of a special array which can contain integers or nested arrays. The product sum is obtained by adding all elements and multiplying by their respective depths. For example, in the array x, y, the product sum is x y. In the array x, y, z, the product sum is x 2 y z. In the array x, y, z, the product sum is x 2 y 3z. Example Input: 5, 2, 7, 1, 3, 6, 13, 8, 4 Output: 12 Recursively calculates the product sum of an array. The product sum of an array is defined as the sum of its elements multiplied by their respective depths. If an element is a list, its product sum is calculated recursively by multiplying the sum of its elements with its depth plus one. Args: arr: The array of integers and nested lists. depth: The current depth level. Returns: int: The product sum of the array. Examples: productsum1, 2, 3, 1 6 productsum1, 2, 3, 4, 2 8 productsum1, 2, 3, 1 6 productsum1, 2, 3, 0 0 productsum1, 2, 3, 7 42 productsum1, 2, 3, 7 42 productsum1, 2, 3, 7 42 productsum1, 1, 1 0 productsum1, 2, 1 1 productsum3.5, 1, 0.5, 1 1.5 Calculates the product sum of an array. Args: array ListUnionint, List: The array of integers and nested lists. Returns: int: The product sum of the array. Examples: productsumarray1, 2, 3 6 productsumarray1, 2, 3 11 productsumarray1, 2, 3, 4 47 productsumarray0 0 productsumarray3.5, 1, 0.5 1.5 productsumarray1, 2 1","Completions":"def product_sum(arr: list[int | list], depth: int) -> int:\n \"\"\"\n Recursively calculates the product sum of an array.\n\n The product sum of an array is defined as the sum of its elements multiplied by\n their respective depths. If an element is a list, its product sum is calculated\n recursively by multiplying the sum of its elements with its depth plus one.\n\n Args:\n arr: The array of integers and nested lists.\n depth: The current depth level.\n\n Returns:\n int: The product sum of the array.\n\n Examples:\n >>> product_sum([1, 2, 3], 1)\n 6\n >>> product_sum([-1, 2, [-3, 4]], 2)\n 8\n >>> product_sum([1, 2, 3], -1)\n -6\n >>> product_sum([1, 2, 3], 0)\n 0\n >>> product_sum([1, 2, 3], 7)\n 42\n >>> product_sum((1, 2, 3), 7)\n 42\n >>> product_sum({1, 2, 3}, 7)\n 42\n >>> product_sum([1, -1], 1)\n 0\n >>> product_sum([1, -2], 1)\n -1\n >>> product_sum([-3.5, [1, [0.5]]], 1)\n 1.5\n\n \"\"\"\n total_sum = 0\n for ele in arr:\n total_sum += product_sum(ele, depth + 1) if isinstance(ele, list) else ele\n return total_sum * depth\n\n\ndef product_sum_array(array: list[int | list]) -> int:\n \"\"\"\n Calculates the product sum of an array.\n\n Args:\n array (List[Union[int, List]]): The array of integers and nested lists.\n\n Returns:\n int: The product sum of the array.\n\n Examples:\n >>> product_sum_array([1, 2, 3])\n 6\n >>> product_sum_array([1, [2, 3]])\n 11\n >>> product_sum_array([1, [2, [3, 4]]])\n 47\n >>> product_sum_array([0])\n 0\n >>> product_sum_array([-3.5, [1, [0.5]]])\n 1.5\n >>> product_sum_array([1, -2])\n -1\n\n \"\"\"\n return product_sum(array, 1)\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Sparse table is a data structure that allows answering range queries on a static number list, i.e. the elements do not change throughout all the queries. The implementation below will solve the problem of Range Minimum Query: Finding the minimum value of a subset L..R of a static number list. Overall time complexity: Onlogn Overall space complexity: Onlogn Wikipedia link: https:en.wikipedia.orgwikiRangeminimumquery Precompute range minimum queries with power of two length and store the precomputed values in a table. buildsparsetable8, 1, 0, 3, 4, 9, 3 8, 1, 0, 3, 4, 9, 3, 1, 0, 0, 3, 4, 3, 0, 0, 0, 0, 3, 0, 0, 0 buildsparsetable3, 1, 9 3, 1, 9, 1, 1, 0 buildsparsetable Traceback most recent call last: ... ValueError: empty number list not allowed Initialise sparsetable sparsetableji represents the minimum value of the subset of length 2 j of numberlist, starting from index i. smallest power of 2 subset length that fully covers numberlist minimum of subset of length 1 is that value itself compute the minimum value for all intervals with size 2 j while subset starting from i still have at least 2 j elements split range i, i 2 j and find minimum of 2 halves querybuildsparsetable8, 1, 0, 3, 4, 9, 3, 0, 4 0 querybuildsparsetable8, 1, 0, 3, 4, 9, 3, 4, 6 3 querybuildsparsetable3, 1, 9, 2, 2 9 querybuildsparsetable3, 1, 9, 0, 1 1 querybuildsparsetable8, 1, 0, 3, 4, 9, 3, 0, 11 Traceback most recent call last: ... IndexError: list index out of range querybuildsparsetable, 0, 0 Traceback most recent call last: ... ValueError: empty number list not allowed highest subset length of power of 2 that is within range leftbound, rightbound minimum of 2 overlapping smaller subsets: leftbound, leftbound 2 j 1 and rightbound 2 j 1, rightbound","Completions":"from math import log2\n\n\ndef build_sparse_table(number_list: list[int]) -> list[list[int]]:\n \"\"\"\n Precompute range minimum queries with power of two length and store the precomputed\n values in a table.\n\n >>> build_sparse_table([8, 1, 0, 3, 4, 9, 3])\n [[8, 1, 0, 3, 4, 9, 3], [1, 0, 0, 3, 4, 3, 0], [0, 0, 0, 3, 0, 0, 0]]\n >>> build_sparse_table([3, 1, 9])\n [[3, 1, 9], [1, 1, 0]]\n >>> build_sparse_table([])\n Traceback (most recent call last):\n ...\n ValueError: empty number list not allowed\n \"\"\"\n if not number_list:\n raise ValueError(\"empty number list not allowed\")\n\n length = len(number_list)\n # Initialise sparse_table -- sparse_table[j][i] represents the minimum value of the\n # subset of length (2 ** j) of number_list, starting from index i.\n\n # smallest power of 2 subset length that fully covers number_list\n row = int(log2(length)) + 1\n sparse_table = [[0 for i in range(length)] for j in range(row)]\n\n # minimum of subset of length 1 is that value itself\n for i, value in enumerate(number_list):\n sparse_table[0][i] = value\n j = 1\n\n # compute the minimum value for all intervals with size (2 ** j)\n while (1 << j) <= length:\n i = 0\n # while subset starting from i still have at least (2 ** j) elements\n while (i + (1 << j) - 1) < length:\n # split range [i, i + 2 ** j] and find minimum of 2 halves\n sparse_table[j][i] = min(\n sparse_table[j - 1][i + (1 << (j - 1))], sparse_table[j - 1][i]\n )\n i += 1\n j += 1\n return sparse_table\n\n\ndef query(sparse_table: list[list[int]], left_bound: int, right_bound: int) -> int:\n \"\"\"\n >>> query(build_sparse_table([8, 1, 0, 3, 4, 9, 3]), 0, 4)\n 0\n >>> query(build_sparse_table([8, 1, 0, 3, 4, 9, 3]), 4, 6)\n 3\n >>> query(build_sparse_table([3, 1, 9]), 2, 2)\n 9\n >>> query(build_sparse_table([3, 1, 9]), 0, 1)\n 1\n >>> query(build_sparse_table([8, 1, 0, 3, 4, 9, 3]), 0, 11)\n Traceback (most recent call last):\n ...\n IndexError: list index out of range\n >>> query(build_sparse_table([]), 0, 0)\n Traceback (most recent call last):\n ...\n ValueError: empty number list not allowed\n \"\"\"\n if left_bound < 0 or right_bound >= len(sparse_table[0]):\n raise IndexError(\"list index out of range\")\n\n # highest subset length of power of 2 that is within range [left_bound, right_bound]\n j = int(log2(right_bound - left_bound + 1))\n\n # minimum of 2 overlapping smaller subsets:\n # [left_bound, left_bound + 2 ** j - 1] and [right_bound - 2 ** j + 1, right_bound]\n return min(sparse_table[j][right_bound - (1 << j) + 1], sparse_table[j][left_bound])\n\n\nif __name__ == \"__main__\":\n from doctest import testmod\n\n testmod()\n print(f\"{query(build_sparse_table([3, 1, 9]), 2, 2) = }\")\n"} +{"Prompt":"Please do not modify this file! It is published at https:norvig.comsudoku.html with only minimal changes to work with modern versions of Python. If you have improvements, please make them in a separate file. fmt: off fmt: on Convert grid to a dict of possible values, square: digits, or return False if a contradiction is detected. To start, every square can be any digit; then assign values from the grid. values s: digits for s in squares for s, d in gridvaluesgrid.items: if d in digits and not assignvalues, s, d: return False Fail if we can't assign d to square s. return values def gridvaluesgrid: Convert grid into a dict of square: char with '0' or '.' for empties. chars c for c in grid if c in digits or c in 0. assert lenchars 81 return dictzipsquares, chars def assignvalues, s, d: Eliminate d from valuess; propagate when values or places 2. Return values, except return False if a contradiction is detected. if d not in valuess: return values Already eliminated valuess valuess.replaced, 1 If a square s is reduced to one value d2, then eliminate d2 from the peers. if lenvaluess 0: return False Contradiction: removed last value elif lenvaluess 1: d2 valuess if not alleliminatevalues, s2, d2 for s2 in peerss: return False 2 If a unit u is reduced to only one place for a value d, then put it there. for u in unitss: dplaces s for s in u if d in valuess if lendplaces 0: return False Contradiction: no place for this value elif lendplaces 1: d can only be in one place in unit; assign it there if not assignvalues, dplaces0, d: return False return values def displayvalues: Display these values as a 2D grid. width 1 maxlenvaluess for s in squares line .join width 3 3 for r in rows: print .join valuesr c.centerwidth if c in 36 else for c in cols if r in CF: printline print def solvegrid: return searchparsegridgrid def someseq: Return some element of seq that is true. for e in seq: if e: return e return False def searchvalues: Using depthfirst search and propagation, try all possible values. if values is False: return False Failed earlier if alllenvaluess 1 for s in squares: return values Solved! Chose the unfilled square s with the fewest possibilities n, s minlenvaluess, s for s in squares if lenvaluess 1 return somesearchassignvalues.copy, s, d for d in valuess def solveallgrids, name, showif0.0: Display puzzles that take long enough Make a random puzzle with N or more assignments. Restart on contradictions. Note the resulting puzzle is not guaranteed to be solvable, but empirically about 99.8 of them are solvable. Some have multiple solutions. values s: digits for s in squares for s in shuffledsquares: if not assignvalues, s, random.choicevaluess: break ds valuess for s in squares if lenvaluess 1 if lends assignments and lensetds 8: return .joinvaluess if lenvaluess 1 else . for s in squares return randompuzzleassignments Give up and make a new puzzle def shuffledseq: Return a randomly shuffled copy of the input sequence. seq listseq random.shuffleseq return seq grid1 003020600900305001001806400008102900700000008006708200002609500800203009005010300 grid2 4.....8.5.3..........7......2.....6.....8.4......1.......6.3.7.5..2.....1.4...... hard1 .....6....59.....82....8....45........3........6..3.54...325..6.................. if name main: test solveallfromfileeasy50.txt, '', easy, None solveallfromfiletop95.txt, hard, None solveallfromfilehardest.txt, hardest, None solveallrandompuzzle for in range99, random, 100.0 for puzzle in grid1, grid2: , hard1: Takes 22 sec to solve on my M1 Mac. displayparsegridpuzzle start time.monotonic solvepuzzle t time.monotonic start printSolved: .5f sec t","Completions":"import random\nimport time\n\n\ndef cross(items_a, items_b):\n \"Cross product of elements in A and elements in B.\"\n return [a + b for a in items_a for b in items_b]\n\n\ndigits = \"123456789\"\nrows = \"ABCDEFGHI\"\ncols = digits\nsquares = cross(rows, cols)\nunitlist = (\n [cross(rows, c) for c in cols]\n + [cross(r, cols) for r in rows]\n + [cross(rs, cs) for rs in (\"ABC\", \"DEF\", \"GHI\") for cs in (\"123\", \"456\", \"789\")]\n)\nunits = {s: [u for u in unitlist if s in u] for s in squares}\npeers = {s: set(sum(units[s], [])) - {s} for s in squares}\n\n\ndef test():\n \"A set of unit tests.\"\n assert len(squares) == 81\n assert len(unitlist) == 27\n assert all(len(units[s]) == 3 for s in squares)\n assert all(len(peers[s]) == 20 for s in squares)\n assert units[\"C2\"] == [\n [\"A2\", \"B2\", \"C2\", \"D2\", \"E2\", \"F2\", \"G2\", \"H2\", \"I2\"],\n [\"C1\", \"C2\", \"C3\", \"C4\", \"C5\", \"C6\", \"C7\", \"C8\", \"C9\"],\n [\"A1\", \"A2\", \"A3\", \"B1\", \"B2\", \"B3\", \"C1\", \"C2\", \"C3\"],\n ]\n # fmt: off\n assert peers[\"C2\"] == {\n \"A2\", \"B2\", \"D2\", \"E2\", \"F2\", \"G2\", \"H2\", \"I2\", \"C1\", \"C3\",\n \"C4\", \"C5\", \"C6\", \"C7\", \"C8\", \"C9\", \"A1\", \"A3\", \"B1\", \"B3\"\n }\n # fmt: on\n print(\"All tests pass.\")\n\n\ndef parse_grid(grid):\n \"\"\"Convert grid to a dict of possible values, {square: digits}, or\n return False if a contradiction is detected.\"\"\"\n ## To start, every square can be any digit; then assign values from the grid.\n values = {s: digits for s in squares}\n for s, d in grid_values(grid).items():\n if d in digits and not assign(values, s, d):\n return False ## (Fail if we can't assign d to square s.)\n return values\n\n\ndef grid_values(grid):\n \"Convert grid into a dict of {square: char} with '0' or '.' for empties.\"\n chars = [c for c in grid if c in digits or c in \"0.\"]\n assert len(chars) == 81\n return dict(zip(squares, chars))\n\n\ndef assign(values, s, d):\n \"\"\"Eliminate all the other values (except d) from values[s] and propagate.\n Return values, except return False if a contradiction is detected.\"\"\"\n other_values = values[s].replace(d, \"\")\n if all(eliminate(values, s, d2) for d2 in other_values):\n return values\n else:\n return False\n\n\ndef eliminate(values, s, d):\n \"\"\"Eliminate d from values[s]; propagate when values or places <= 2.\n Return values, except return False if a contradiction is detected.\"\"\"\n if d not in values[s]:\n return values ## Already eliminated\n values[s] = values[s].replace(d, \"\")\n ## (1) If a square s is reduced to one value d2, then eliminate d2 from the peers.\n if len(values[s]) == 0:\n return False ## Contradiction: removed last value\n elif len(values[s]) == 1:\n d2 = values[s]\n if not all(eliminate(values, s2, d2) for s2 in peers[s]):\n return False\n ## (2) If a unit u is reduced to only one place for a value d, then put it there.\n for u in units[s]:\n dplaces = [s for s in u if d in values[s]]\n if len(dplaces) == 0:\n return False ## Contradiction: no place for this value\n elif len(dplaces) == 1:\n # d can only be in one place in unit; assign it there\n if not assign(values, dplaces[0], d):\n return False\n return values\n\n\ndef display(values):\n \"Display these values as a 2-D grid.\"\n width = 1 + max(len(values[s]) for s in squares)\n line = \"+\".join([\"-\" * (width * 3)] * 3)\n for r in rows:\n print(\n \"\".join(\n values[r + c].center(width) + (\"|\" if c in \"36\" else \"\") for c in cols\n )\n )\n if r in \"CF\":\n print(line)\n print()\n\n\ndef solve(grid):\n return search(parse_grid(grid))\n\n\ndef some(seq):\n \"Return some element of seq that is true.\"\n for e in seq:\n if e:\n return e\n return False\n\n\ndef search(values):\n \"Using depth-first search and propagation, try all possible values.\"\n if values is False:\n return False ## Failed earlier\n if all(len(values[s]) == 1 for s in squares):\n return values ## Solved!\n ## Chose the unfilled square s with the fewest possibilities\n n, s = min((len(values[s]), s) for s in squares if len(values[s]) > 1)\n return some(search(assign(values.copy(), s, d)) for d in values[s])\n\n\ndef solve_all(grids, name=\"\", showif=0.0):\n \"\"\"Attempt to solve a sequence of grids. Report results.\n When showif is a number of seconds, display puzzles that take longer.\n When showif is None, don't display any puzzles.\"\"\"\n\n def time_solve(grid):\n start = time.monotonic()\n values = solve(grid)\n t = time.monotonic() - start\n ## Display puzzles that take long enough\n if showif is not None and t > showif:\n display(grid_values(grid))\n if values:\n display(values)\n print(\"(%.5f seconds)\\n\" % t)\n return (t, solved(values))\n\n times, results = zip(*[time_solve(grid) for grid in grids])\n if (n := len(grids)) > 1:\n print(\n \"Solved %d of %d %s puzzles (avg %.2f secs (%d Hz), max %.2f secs).\"\n % (sum(results), n, name, sum(times) \/ n, n \/ sum(times), max(times))\n )\n\n\ndef solved(values):\n \"A puzzle is solved if each unit is a permutation of the digits 1 to 9.\"\n\n def unitsolved(unit):\n return {values[s] for s in unit} == set(digits)\n\n return values is not False and all(unitsolved(unit) for unit in unitlist)\n\n\ndef from_file(filename, sep=\"\\n\"):\n \"Parse a file into a list of strings, separated by sep.\"\n return open(filename).read().strip().split(sep) # noqa: SIM115\n\n\ndef random_puzzle(assignments=17):\n \"\"\"Make a random puzzle with N or more assignments. Restart on contradictions.\n Note the resulting puzzle is not guaranteed to be solvable, but empirically\n about 99.8% of them are solvable. Some have multiple solutions.\"\"\"\n values = {s: digits for s in squares}\n for s in shuffled(squares):\n if not assign(values, s, random.choice(values[s])):\n break\n ds = [values[s] for s in squares if len(values[s]) == 1]\n if len(ds) >= assignments and len(set(ds)) >= 8:\n return \"\".join(values[s] if len(values[s]) == 1 else \".\" for s in squares)\n return random_puzzle(assignments) ## Give up and make a new puzzle\n\n\ndef shuffled(seq):\n \"Return a randomly shuffled copy of the input sequence.\"\n seq = list(seq)\n random.shuffle(seq)\n return seq\n\n\ngrid1 = (\n \"003020600900305001001806400008102900700000008006708200002609500800203009005010300\"\n)\ngrid2 = (\n \"4.....8.5.3..........7......2.....6.....8.4......1.......6.3.7.5..2.....1.4......\"\n)\nhard1 = (\n \".....6....59.....82....8....45........3........6..3.54...325..6..................\"\n)\n\nif __name__ == \"__main__\":\n test()\n # solve_all(from_file(\"easy50.txt\", '========'), \"easy\", None)\n # solve_all(from_file(\"top95.txt\"), \"hard\", None)\n # solve_all(from_file(\"hardest.txt\"), \"hardest\", None)\n solve_all([random_puzzle() for _ in range(99)], \"random\", 100.0)\n for puzzle in (grid1, grid2): # , hard1): # Takes 22 sec to solve on my M1 Mac.\n display(parse_grid(puzzle))\n start = time.monotonic()\n solve(puzzle)\n t = time.monotonic() - start\n print(\"Solved: %.5f sec\" % t)\n"} +{"Prompt":"Implementation of an autobalanced binary tree! For doctests run following command: python3 m doctest v avltree.py For testing run: python avltree.py printleft rotation node:, node.getdata ret node.getleft assert ret is not None node.setleftret.getright ret.setrightnode h1 mymaxgetheightnode.getright, getheightnode.getleft 1 node.setheighth1 h2 mymaxgetheightret.getright, getheightret.getleft 1 ret.setheighth2 return ret def leftrotationnode: MyNode MyNode: printright rotation node:, node.getdata ret node.getright assert ret is not None node.setrightret.getleft ret.setleftnode h1 mymaxgetheightnode.getright, getheightnode.getleft 1 node.setheighth1 h2 mymaxgetheightret.getright, getheightret.getleft 1 ret.setheighth2 return ret def lrrotationnode: MyNode MyNode: r A A Br B C LR Br C RR B A Bl Br B UB Bl UB C UB Bl RR rightrotation LR leftrotation An AVL tree doctest Examples: t AVLtree t.insert4 insert:4 printstrt.replace n,n 4 t.insert2 insert:2 printstrt.replace n,n.replace n,n 4 2 t.insert3 insert:3 right rotation node: 2 left rotation node: 4 printstrt.replace n,n.replace n,n 3 2 4 t.getheight 2 t.delnode3 delete:3 printstrt.replace n,n.replace n,n 4 2","Completions":"from __future__ import annotations\n\nimport math\nimport random\nfrom typing import Any\n\n\nclass MyQueue:\n def __init__(self) -> None:\n self.data: list[Any] = []\n self.head: int = 0\n self.tail: int = 0\n\n def is_empty(self) -> bool:\n return self.head == self.tail\n\n def push(self, data: Any) -> None:\n self.data.append(data)\n self.tail = self.tail + 1\n\n def pop(self) -> Any:\n ret = self.data[self.head]\n self.head = self.head + 1\n return ret\n\n def count(self) -> int:\n return self.tail - self.head\n\n def print_queue(self) -> None:\n print(self.data)\n print(\"**************\")\n print(self.data[self.head : self.tail])\n\n\nclass MyNode:\n def __init__(self, data: Any) -> None:\n self.data = data\n self.left: MyNode | None = None\n self.right: MyNode | None = None\n self.height: int = 1\n\n def get_data(self) -> Any:\n return self.data\n\n def get_left(self) -> MyNode | None:\n return self.left\n\n def get_right(self) -> MyNode | None:\n return self.right\n\n def get_height(self) -> int:\n return self.height\n\n def set_data(self, data: Any) -> None:\n self.data = data\n\n def set_left(self, node: MyNode | None) -> None:\n self.left = node\n\n def set_right(self, node: MyNode | None) -> None:\n self.right = node\n\n def set_height(self, height: int) -> None:\n self.height = height\n\n\ndef get_height(node: MyNode | None) -> int:\n if node is None:\n return 0\n return node.get_height()\n\n\ndef my_max(a: int, b: int) -> int:\n if a > b:\n return a\n return b\n\n\ndef right_rotation(node: MyNode) -> MyNode:\n r\"\"\"\n A B\n \/ \\ \/ \\\n B C Bl A\n \/ \\ --> \/ \/ \\\n Bl Br UB Br C\n \/\n UB\n UB = unbalanced node\n \"\"\"\n print(\"left rotation node:\", node.get_data())\n ret = node.get_left()\n assert ret is not None\n node.set_left(ret.get_right())\n ret.set_right(node)\n h1 = my_max(get_height(node.get_right()), get_height(node.get_left())) + 1\n node.set_height(h1)\n h2 = my_max(get_height(ret.get_right()), get_height(ret.get_left())) + 1\n ret.set_height(h2)\n return ret\n\n\ndef left_rotation(node: MyNode) -> MyNode:\n \"\"\"\n a mirror symmetry rotation of the left_rotation\n \"\"\"\n print(\"right rotation node:\", node.get_data())\n ret = node.get_right()\n assert ret is not None\n node.set_right(ret.get_left())\n ret.set_left(node)\n h1 = my_max(get_height(node.get_right()), get_height(node.get_left())) + 1\n node.set_height(h1)\n h2 = my_max(get_height(ret.get_right()), get_height(ret.get_left())) + 1\n ret.set_height(h2)\n return ret\n\n\ndef lr_rotation(node: MyNode) -> MyNode:\n r\"\"\"\n A A Br\n \/ \\ \/ \\ \/ \\\n B C LR Br C RR B A\n \/ \\ --> \/ \\ --> \/ \/ \\\n Bl Br B UB Bl UB C\n \\ \/\n UB Bl\n RR = right_rotation LR = left_rotation\n \"\"\"\n left_child = node.get_left()\n assert left_child is not None\n node.set_left(left_rotation(left_child))\n return right_rotation(node)\n\n\ndef rl_rotation(node: MyNode) -> MyNode:\n right_child = node.get_right()\n assert right_child is not None\n node.set_right(right_rotation(right_child))\n return left_rotation(node)\n\n\ndef insert_node(node: MyNode | None, data: Any) -> MyNode | None:\n if node is None:\n return MyNode(data)\n if data < node.get_data():\n node.set_left(insert_node(node.get_left(), data))\n if (\n get_height(node.get_left()) - get_height(node.get_right()) == 2\n ): # an unbalance detected\n left_child = node.get_left()\n assert left_child is not None\n if (\n data < left_child.get_data()\n ): # new node is the left child of the left child\n node = right_rotation(node)\n else:\n node = lr_rotation(node)\n else:\n node.set_right(insert_node(node.get_right(), data))\n if get_height(node.get_right()) - get_height(node.get_left()) == 2:\n right_child = node.get_right()\n assert right_child is not None\n if data < right_child.get_data():\n node = rl_rotation(node)\n else:\n node = left_rotation(node)\n h1 = my_max(get_height(node.get_right()), get_height(node.get_left())) + 1\n node.set_height(h1)\n return node\n\n\ndef get_right_most(root: MyNode) -> Any:\n while True:\n right_child = root.get_right()\n if right_child is None:\n break\n root = right_child\n return root.get_data()\n\n\ndef get_left_most(root: MyNode) -> Any:\n while True:\n left_child = root.get_left()\n if left_child is None:\n break\n root = left_child\n return root.get_data()\n\n\ndef del_node(root: MyNode, data: Any) -> MyNode | None:\n left_child = root.get_left()\n right_child = root.get_right()\n if root.get_data() == data:\n if left_child is not None and right_child is not None:\n temp_data = get_left_most(right_child)\n root.set_data(temp_data)\n root.set_right(del_node(right_child, temp_data))\n elif left_child is not None:\n root = left_child\n elif right_child is not None:\n root = right_child\n else:\n return None\n elif root.get_data() > data:\n if left_child is None:\n print(\"No such data\")\n return root\n else:\n root.set_left(del_node(left_child, data))\n else: # root.get_data() < data\n if right_child is None:\n return root\n else:\n root.set_right(del_node(right_child, data))\n\n if get_height(right_child) - get_height(left_child) == 2:\n assert right_child is not None\n if get_height(right_child.get_right()) > get_height(right_child.get_left()):\n root = left_rotation(root)\n else:\n root = rl_rotation(root)\n elif get_height(right_child) - get_height(left_child) == -2:\n assert left_child is not None\n if get_height(left_child.get_left()) > get_height(left_child.get_right()):\n root = right_rotation(root)\n else:\n root = lr_rotation(root)\n height = my_max(get_height(root.get_right()), get_height(root.get_left())) + 1\n root.set_height(height)\n return root\n\n\nclass AVLtree:\n \"\"\"\n An AVL tree doctest\n Examples:\n >>> t = AVLtree()\n >>> t.insert(4)\n insert:4\n >>> print(str(t).replace(\" \\\\n\",\"\\\\n\"))\n 4\n *************************************\n >>> t.insert(2)\n insert:2\n >>> print(str(t).replace(\" \\\\n\",\"\\\\n\").replace(\" \\\\n\",\"\\\\n\"))\n 4\n 2 *\n *************************************\n >>> t.insert(3)\n insert:3\n right rotation node: 2\n left rotation node: 4\n >>> print(str(t).replace(\" \\\\n\",\"\\\\n\").replace(\" \\\\n\",\"\\\\n\"))\n 3\n 2 4\n *************************************\n >>> t.get_height()\n 2\n >>> t.del_node(3)\n delete:3\n >>> print(str(t).replace(\" \\\\n\",\"\\\\n\").replace(\" \\\\n\",\"\\\\n\"))\n 4\n 2 *\n *************************************\n \"\"\"\n\n def __init__(self) -> None:\n self.root: MyNode | None = None\n\n def get_height(self) -> int:\n return get_height(self.root)\n\n def insert(self, data: Any) -> None:\n print(\"insert:\" + str(data))\n self.root = insert_node(self.root, data)\n\n def del_node(self, data: Any) -> None:\n print(\"delete:\" + str(data))\n if self.root is None:\n print(\"Tree is empty!\")\n return\n self.root = del_node(self.root, data)\n\n def __str__(\n self,\n ) -> str: # a level traversale, gives a more intuitive look on the tree\n output = \"\"\n q = MyQueue()\n q.push(self.root)\n layer = self.get_height()\n if layer == 0:\n return output\n cnt = 0\n while not q.is_empty():\n node = q.pop()\n space = \" \" * int(math.pow(2, layer - 1))\n output += space\n if node is None:\n output += \"*\"\n q.push(None)\n q.push(None)\n else:\n output += str(node.get_data())\n q.push(node.get_left())\n q.push(node.get_right())\n output += space\n cnt = cnt + 1\n for i in range(100):\n if cnt == math.pow(2, i) - 1:\n layer = layer - 1\n if layer == 0:\n output += \"\\n*************************************\"\n return output\n output += \"\\n\"\n break\n output += \"\\n*************************************\"\n return output\n\n\ndef _test() -> None:\n import doctest\n\n doctest.testmod()\n\n\nif __name__ == \"__main__\":\n _test()\n t = AVLtree()\n lst = list(range(10))\n random.shuffle(lst)\n for i in lst:\n t.insert(i)\n print(str(t))\n random.shuffle(lst)\n for i in lst:\n t.del_node(i)\n print(str(t))\n"} +{"Prompt":"Return a small binary tree with 3 nodes. binarytree BinaryTree.smalltree lenbinarytree 3 listbinarytree 1, 2, 3 Return a medium binary tree with 3 nodes. binarytree BinaryTree.mediumtree lenbinarytree 7 listbinarytree 1, 2, 3, 4, 5, 6, 7 Returns the depth of the tree BinaryTreeNode1.depth 1 BinaryTree.smalltree.depth 2 BinaryTree.mediumtree.depth 4 Returns True if the tree is full BinaryTreeNode1.isfull True BinaryTree.smalltree.isfull True BinaryTree.mediumtree.isfull False","Completions":"from __future__ import annotations\n\nfrom collections.abc import Iterator\nfrom dataclasses import dataclass\n\n\n@dataclass\nclass Node:\n data: int\n left: Node | None = None\n right: Node | None = None\n\n def __iter__(self) -> Iterator[int]:\n if self.left:\n yield from self.left\n yield self.data\n if self.right:\n yield from self.right\n\n def __len__(self) -> int:\n return sum(1 for _ in self)\n\n def is_full(self) -> bool:\n if not self or (not self.left and not self.right):\n return True\n if self.left and self.right:\n return self.left.is_full() and self.right.is_full()\n return False\n\n\n@dataclass\nclass BinaryTree:\n root: Node\n\n def __iter__(self) -> Iterator[int]:\n return iter(self.root)\n\n def __len__(self) -> int:\n return len(self.root)\n\n @classmethod\n def small_tree(cls) -> BinaryTree:\n \"\"\"\n Return a small binary tree with 3 nodes.\n >>> binary_tree = BinaryTree.small_tree()\n >>> len(binary_tree)\n 3\n >>> list(binary_tree)\n [1, 2, 3]\n \"\"\"\n binary_tree = BinaryTree(Node(2))\n binary_tree.root.left = Node(1)\n binary_tree.root.right = Node(3)\n return binary_tree\n\n @classmethod\n def medium_tree(cls) -> BinaryTree:\n \"\"\"\n Return a medium binary tree with 3 nodes.\n >>> binary_tree = BinaryTree.medium_tree()\n >>> len(binary_tree)\n 7\n >>> list(binary_tree)\n [1, 2, 3, 4, 5, 6, 7]\n \"\"\"\n binary_tree = BinaryTree(Node(4))\n binary_tree.root.left = two = Node(2)\n two.left = Node(1)\n two.right = Node(3)\n binary_tree.root.right = five = Node(5)\n five.right = six = Node(6)\n six.right = Node(7)\n return binary_tree\n\n def depth(self) -> int:\n \"\"\"\n Returns the depth of the tree\n\n >>> BinaryTree(Node(1)).depth()\n 1\n >>> BinaryTree.small_tree().depth()\n 2\n >>> BinaryTree.medium_tree().depth()\n 4\n \"\"\"\n return self._depth(self.root)\n\n def _depth(self, node: Node | None) -> int: # noqa: UP007\n if not node:\n return 0\n return 1 + max(self._depth(node.left), self._depth(node.right))\n\n def is_full(self) -> bool:\n \"\"\"\n Returns True if the tree is full\n\n >>> BinaryTree(Node(1)).is_full()\n True\n >>> BinaryTree.small_tree().is_full()\n True\n >>> BinaryTree.medium_tree().is_full()\n False\n \"\"\"\n return self.root.is_full()\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"from future import annotations from collections.abc import Iterable, Iterator from dataclasses import dataclass from typing import Any, Self dataclass class Node: value: int left: Node None None right: Node None None parent: Node None None Added in order to delete a node easier def iterself Iteratorint: yield from self.left or yield self.value yield from self.right or def reprself str: from pprint import pformat if self.left is None and self.right is None: return strself.value return pformatfself.value: self.left, self.right, indent1 property def isrightself bool: return boolself.parent and self is self.parent.right dataclass class BinarySearchTree: root: Node None None def boolself bool: return boolself.root def iterself Iteratorint: yield from self.root or def strself str: return strself.root def reassignnodesself, node: Node, newchildren: Node None None: if newchildren is not None: reset its kids newchildren.parent node.parent if node.parent is not None: reset its parent if node.isright: If it is the right child node.parent.right newchildren else: node.parent.left newchildren else: self.root newchildren def emptyself bool: return not self.root def insertself, value None: newnode Nodevalue create a new Node if self.empty: if Tree is empty self.root newnode set its root else: Tree is not empty parentnode self.root from root if parentnode is None: return while True: While we don't get to a leaf if value parentnode.value: We go left if parentnode.left is None: parentnode.left newnode We insert the new node in a leaf break else: parentnode parentnode.left else: if parentnode.right is None: parentnode.right newnode break else: parentnode parentnode.right newnode.parent parentnode def insertself, values Self: for value in values: self.insertvalue return self def searchself, value Node None: if self.empty: raise IndexErrorWarning: Tree is empty! please use another. else: node self.root use lazy evaluation here to avoid NoneType Attribute error while node is not None and node.value is not value: node node.left if value node.value else node.right return node def getmaxself, node: Node None None Node None: if node is None: if self.root is None: return None node self.root if not self.empty: while node.right is not None: node node.right return node def getminself, node: Node None None Node None: if node is None: node self.root if self.root is None: return None if not self.empty: node self.root while node.left is not None: node node.left return node def removeself, value: int None: Look for the node with that label node self.searchvalue if node is None: msg fValue value not found raise ValueErrormsg if node.left is None and node.right is None: If it has no children self.reassignnodesnode, None elif node.left is None: Has only right children self.reassignnodesnode, node.right elif node.right is None: Has only left children self.reassignnodesnode, node.left else: predecessor self.getmax node.left Gets the max value of the left branch self.removepredecessor.value type: ignore node.value predecessor.value type: ignore Assigns the value to the node to delete and keep tree structure def preordertraverseself, node: Node None Iterable: if node is not None: yield node Preorder Traversal yield from self.preordertraversenode.left yield from self.preordertraversenode.right def traversaltreeself, traversalfunctionNone Any: if traversalfunction is None: return self.preordertraverseself.root else: return traversalfunctionself.root def inorderself, arr: list, node: Node None None: Return the kth smallest element in a binary search tree arr: listint self.inorderarr, node append all values to list using inorder traversal return arrk 1 def inordercurrnode: Node None listNode: nodelist if currnode is not None: nodelist inordercurrnode.left currnode inordercurrnode.right return nodelist def postordercurrnode: Node None listNode: nodelist if currnode is not None: nodelist postordercurrnode.left postordercurrnode.right currnode return nodelist if name main: import doctest doctest.testmodverboseTrue","Completions":"r\"\"\"\nA binary search Tree\n\nExample\n 8\n \/ \\\n 3 10\n \/ \\ \\\n 1 6 14\n \/ \\ \/\n 4 7 13\n\n>>> t = BinarySearchTree().insert(8, 3, 6, 1, 10, 14, 13, 4, 7)\n>>> print(\" \".join(repr(i.value) for i in t.traversal_tree()))\n8 3 1 6 4 7 10 14 13\n\n>>> tuple(i.value for i in t.traversal_tree(inorder))\n(1, 3, 4, 6, 7, 8, 10, 13, 14)\n>>> tuple(t)\n(1, 3, 4, 6, 7, 8, 10, 13, 14)\n>>> t.find_kth_smallest(3, t.root)\n4\n>>> tuple(t)[3-1]\n4\n\n>>> print(\" \".join(repr(i.value) for i in t.traversal_tree(postorder)))\n1 4 7 6 3 13 14 10 8\n>>> t.remove(20)\nTraceback (most recent call last):\n ...\nValueError: Value 20 not found\n>>> BinarySearchTree().search(6)\nTraceback (most recent call last):\n ...\nIndexError: Warning: Tree is empty! please use another.\n\nOther example:\n\n>>> testlist = (8, 3, 6, 1, 10, 14, 13, 4, 7)\n>>> t = BinarySearchTree()\n>>> for i in testlist:\n... t.insert(i) # doctest: +ELLIPSIS\nBinarySearchTree(root=8)\nBinarySearchTree(root={'8': (3, None)})\nBinarySearchTree(root={'8': ({'3': (None, 6)}, None)})\nBinarySearchTree(root={'8': ({'3': (1, 6)}, None)})\nBinarySearchTree(root={'8': ({'3': (1, 6)}, 10)})\nBinarySearchTree(root={'8': ({'3': (1, 6)}, {'10': (None, 14)})})\nBinarySearchTree(root={'8': ({'3': (1, 6)}, {'10': (None, {'14': (13, None)})})})\nBinarySearchTree(root={'8': ({'3': (1, {'6': (4, None)})}, {'10': (None, {'14': ...\nBinarySearchTree(root={'8': ({'3': (1, {'6': (4, 7)})}, {'10': (None, {'14': (13, ...\n\nPrints all the elements of the list in order traversal\n>>> print(t)\n{'8': ({'3': (1, {'6': (4, 7)})}, {'10': (None, {'14': (13, None)})})}\n\nTest existence\n>>> t.search(6) is not None\nTrue\n>>> 6 in t\nTrue\n>>> t.search(-1) is not None\nFalse\n>>> -1 in t\nFalse\n\n>>> t.search(6).is_right\nTrue\n>>> t.search(1).is_right\nFalse\n\n>>> t.get_max().value\n14\n>>> max(t)\n14\n>>> t.get_min().value\n1\n>>> min(t)\n1\n>>> t.empty()\nFalse\n>>> not t\nFalse\n>>> for i in testlist:\n... t.remove(i)\n>>> t.empty()\nTrue\n>>> not t\nTrue\n\"\"\"\nfrom __future__ import annotations\n\nfrom collections.abc import Iterable, Iterator\nfrom dataclasses import dataclass\nfrom typing import Any, Self\n\n\n@dataclass\nclass Node:\n value: int\n left: Node | None = None\n right: Node | None = None\n parent: Node | None = None # Added in order to delete a node easier\n\n def __iter__(self) -> Iterator[int]:\n \"\"\"\n >>> list(Node(0))\n [0]\n >>> list(Node(0, Node(-1), Node(1), None))\n [-1, 0, 1]\n \"\"\"\n yield from self.left or []\n yield self.value\n yield from self.right or []\n\n def __repr__(self) -> str:\n from pprint import pformat\n\n if self.left is None and self.right is None:\n return str(self.value)\n return pformat({f\"{self.value}\": (self.left, self.right)}, indent=1)\n\n @property\n def is_right(self) -> bool:\n return bool(self.parent and self is self.parent.right)\n\n\n@dataclass\nclass BinarySearchTree:\n root: Node | None = None\n\n def __bool__(self) -> bool:\n return bool(self.root)\n\n def __iter__(self) -> Iterator[int]:\n yield from self.root or []\n\n def __str__(self) -> str:\n \"\"\"\n Return a string of all the Nodes using in order traversal\n \"\"\"\n return str(self.root)\n\n def __reassign_nodes(self, node: Node, new_children: Node | None) -> None:\n if new_children is not None: # reset its kids\n new_children.parent = node.parent\n if node.parent is not None: # reset its parent\n if node.is_right: # If it is the right child\n node.parent.right = new_children\n else:\n node.parent.left = new_children\n else:\n self.root = new_children\n\n def empty(self) -> bool:\n \"\"\"\n Returns True if the tree does not have any element(s).\n False if the tree has element(s).\n\n >>> BinarySearchTree().empty()\n True\n >>> BinarySearchTree().insert(1).empty()\n False\n >>> BinarySearchTree().insert(8, 3, 6, 1, 10, 14, 13, 4, 7).empty()\n False\n \"\"\"\n return not self.root\n\n def __insert(self, value) -> None:\n \"\"\"\n Insert a new node in Binary Search Tree with value label\n \"\"\"\n new_node = Node(value) # create a new Node\n if self.empty(): # if Tree is empty\n self.root = new_node # set its root\n else: # Tree is not empty\n parent_node = self.root # from root\n if parent_node is None:\n return\n while True: # While we don't get to a leaf\n if value < parent_node.value: # We go left\n if parent_node.left is None:\n parent_node.left = new_node # We insert the new node in a leaf\n break\n else:\n parent_node = parent_node.left\n else:\n if parent_node.right is None:\n parent_node.right = new_node\n break\n else:\n parent_node = parent_node.right\n new_node.parent = parent_node\n\n def insert(self, *values) -> Self:\n for value in values:\n self.__insert(value)\n return self\n\n def search(self, value) -> Node | None:\n \"\"\"\n >>> tree = BinarySearchTree().insert(10, 20, 30, 40, 50)\n >>> tree.search(10)\n {'10': (None, {'20': (None, {'30': (None, {'40': (None, 50)})})})}\n >>> tree.search(20)\n {'20': (None, {'30': (None, {'40': (None, 50)})})}\n >>> tree.search(30)\n {'30': (None, {'40': (None, 50)})}\n >>> tree.search(40)\n {'40': (None, 50)}\n >>> tree.search(50)\n 50\n >>> tree.search(5) is None # element not present\n True\n >>> tree.search(0) is None # element not present\n True\n >>> tree.search(-5) is None # element not present\n True\n >>> BinarySearchTree().search(10)\n Traceback (most recent call last):\n ...\n IndexError: Warning: Tree is empty! please use another.\n \"\"\"\n\n if self.empty():\n raise IndexError(\"Warning: Tree is empty! please use another.\")\n else:\n node = self.root\n # use lazy evaluation here to avoid NoneType Attribute error\n while node is not None and node.value is not value:\n node = node.left if value < node.value else node.right\n return node\n\n def get_max(self, node: Node | None = None) -> Node | None:\n \"\"\"\n We go deep on the right branch\n\n >>> BinarySearchTree().insert(10, 20, 30, 40, 50).get_max()\n 50\n >>> BinarySearchTree().insert(-5, -1, 0.1, -0.3, -4.5).get_max()\n {'0.1': (-0.3, None)}\n >>> BinarySearchTree().insert(1, 78.3, 30, 74.0, 1).get_max()\n {'78.3': ({'30': (1, 74.0)}, None)}\n >>> BinarySearchTree().insert(1, 783, 30, 740, 1).get_max()\n {'783': ({'30': (1, 740)}, None)}\n \"\"\"\n if node is None:\n if self.root is None:\n return None\n node = self.root\n\n if not self.empty():\n while node.right is not None:\n node = node.right\n return node\n\n def get_min(self, node: Node | None = None) -> Node | None:\n \"\"\"\n We go deep on the left branch\n\n >>> BinarySearchTree().insert(10, 20, 30, 40, 50).get_min()\n {'10': (None, {'20': (None, {'30': (None, {'40': (None, 50)})})})}\n >>> BinarySearchTree().insert(-5, -1, 0, -0.3, -4.5).get_min()\n {'-5': (None, {'-1': (-4.5, {'0': (-0.3, None)})})}\n >>> BinarySearchTree().insert(1, 78.3, 30, 74.0, 1).get_min()\n {'1': (None, {'78.3': ({'30': (1, 74.0)}, None)})}\n >>> BinarySearchTree().insert(1, 783, 30, 740, 1).get_min()\n {'1': (None, {'783': ({'30': (1, 740)}, None)})}\n \"\"\"\n if node is None:\n node = self.root\n if self.root is None:\n return None\n if not self.empty():\n node = self.root\n while node.left is not None:\n node = node.left\n return node\n\n def remove(self, value: int) -> None:\n # Look for the node with that label\n node = self.search(value)\n if node is None:\n msg = f\"Value {value} not found\"\n raise ValueError(msg)\n\n if node.left is None and node.right is None: # If it has no children\n self.__reassign_nodes(node, None)\n elif node.left is None: # Has only right children\n self.__reassign_nodes(node, node.right)\n elif node.right is None: # Has only left children\n self.__reassign_nodes(node, node.left)\n else:\n predecessor = self.get_max(\n node.left\n ) # Gets the max value of the left branch\n self.remove(predecessor.value) # type: ignore\n node.value = (\n predecessor.value # type: ignore\n ) # Assigns the value to the node to delete and keep tree structure\n\n def preorder_traverse(self, node: Node | None) -> Iterable:\n if node is not None:\n yield node # Preorder Traversal\n yield from self.preorder_traverse(node.left)\n yield from self.preorder_traverse(node.right)\n\n def traversal_tree(self, traversal_function=None) -> Any:\n \"\"\"\n This function traversal the tree.\n You can pass a function to traversal the tree as needed by client code\n \"\"\"\n if traversal_function is None:\n return self.preorder_traverse(self.root)\n else:\n return traversal_function(self.root)\n\n def inorder(self, arr: list, node: Node | None) -> None:\n \"\"\"Perform an inorder traversal and append values of the nodes to\n a list named arr\"\"\"\n if node:\n self.inorder(arr, node.left)\n arr.append(node.value)\n self.inorder(arr, node.right)\n\n def find_kth_smallest(self, k: int, node: Node) -> int:\n \"\"\"Return the kth smallest element in a binary search tree\"\"\"\n arr: list[int] = []\n self.inorder(arr, node) # append all values to list using inorder traversal\n return arr[k - 1]\n\n\ndef inorder(curr_node: Node | None) -> list[Node]:\n \"\"\"\n inorder (left, self, right)\n \"\"\"\n node_list = []\n if curr_node is not None:\n node_list = inorder(curr_node.left) + [curr_node] + inorder(curr_node.right)\n return node_list\n\n\ndef postorder(curr_node: Node | None) -> list[Node]:\n \"\"\"\n postOrder (left, right, self)\n \"\"\"\n node_list = []\n if curr_node is not None:\n node_list = postorder(curr_node.left) + postorder(curr_node.right) + [curr_node]\n return node_list\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod(verbose=True)\n"} +{"Prompt":"This is a python3 implementation of binary search tree using recursion To run tests: python m unittest binarysearchtreerecursive.py To run an example: python binarysearchtreerecursive.py Empties the tree t BinarySearchTree assert t.root is None t.put8 assert t.root is not None Checks if the tree is empty t BinarySearchTree t.isempty True t.put8 t.isempty False Put a new node in the tree t BinarySearchTree t.put8 assert t.root.parent is None assert t.root.label 8 t.put10 assert t.root.right.parent t.root assert t.root.right.label 10 t.put3 assert t.root.left.parent t.root assert t.root.left.label 3 Searches a node in the tree t BinarySearchTree t.put8 t.put10 node t.search8 assert node.label 8 node t.search3 Traceback most recent call last: ... ValueError: Node with label 3 does not exist Removes a node in the tree t BinarySearchTree t.put8 t.put10 t.remove8 assert t.root.label 10 t.remove3 Traceback most recent call last: ... ValueError: Node with label 3 does not exist Checks if a node exists in the tree t BinarySearchTree t.put8 t.put10 t.exists8 True t.exists3 False Gets the max label inserted in the tree t BinarySearchTree t.getmaxlabel Traceback most recent call last: ... ValueError: Binary search tree is empty t.put8 t.put10 t.getmaxlabel 10 Gets the min label inserted in the tree t BinarySearchTree t.getminlabel Traceback most recent call last: ... ValueError: Binary search tree is empty t.put8 t.put10 t.getminlabel 8 Return the inorder traversal of the tree t BinarySearchTree i.label for i in t.inordertraversal t.put8 t.put10 t.put9 i.label for i in t.inordertraversal 8, 9, 10 Return the preorder traversal of the tree t BinarySearchTree i.label for i in t.preordertraversal t.put8 t.put10 t.put9 i.label for i in t.preordertraversal 8, 10, 9 t BinarySearchTree t.put8 t.put3 t.put6 t.put1 t.put10 t.put14 t.put13 t.put4 t.put7 t.put5 return t def testputself None: t BinarySearchTree assert t.isempty t.put8 r 8 assert t.root.right is not None assert t.root.right.parent t.root assert t.root.right.label 10 t.put3 r 8 3 10 assert t.root.left.right is not None assert t.root.left.right.parent t.root.left assert t.root.left.right.label 6 t.put1 r 8 3 10 1 6 assert t.root is not None assert t.root.right is not None assert t.root.right.right is not None assert t.root.right.right.right is None assert t.root.right.right.left is None t.remove7 r 8 3 10 1 6 14 4 5 assert t.root.left.left is not None assert t.root.left.right.right is not None assert t.root.left.left.label 1 assert t.root.left.right.label 4 assert t.root.left.right.right.label 5 assert t.root.left.right.left is None assert t.root.left.left.parent t.root.left assert t.root.left.right.parent t.root.left t.remove3 r 8 4 10 1 5 14 assert t.root.left is not None assert t.root.left.left is not None assert t.root.left.label 5 assert t.root.left.right is None assert t.root.left.left.label 1 assert t.root.left.parent t.root assert t.root.left.left.parent t.root.left def testremove2self None: t self.getbinarysearchtree t.remove3 r 8 4 10 1 6 14 5 7 13 t BinarySearchTree t.put8 t.put3 t.put6 t.put1 t.put10 t.put14 t.put13 t.put4 t.put7 t.put5 print printLabel 6 exists:, t.exists6 printLabel 13 exists:, t.exists13 printLabel 1 exists:, t.exists1 printLabel 12 exists:, t.exists12 Prints all the elements of the list in inorder traversal inordertraversalnodes i.label for i in t.inordertraversal printInorder traversal:, inordertraversalnodes Prints all the elements of the list in preorder traversal preordertraversalnodes i.label for i in t.preordertraversal printPreorder traversal:, preordertraversalnodes printMax. label:, t.getmaxlabel printMin. label:, t.getminlabel Delete elements printnDeleting elements 13, 10, 8, 3, 6, 14 print t.remove13 t.remove10 t.remove8 t.remove3 t.remove6 t.remove14 Prints all the elements of the list in inorder traversal after delete inordertraversalnodes i.label for i in t.inordertraversal printInorder traversal after delete:, inordertraversalnodes Prints all the elements of the list in preorder traversal after delete preordertraversalnodes i.label for i in t.preordertraversal printPreorder traversal after delete:, preordertraversalnodes printMax. label:, t.getmaxlabel printMin. label:, t.getminlabel if name main: binarysearchtreeexample","Completions":"from __future__ import annotations\n\nimport unittest\nfrom collections.abc import Iterator\n\nimport pytest\n\n\nclass Node:\n def __init__(self, label: int, parent: Node | None) -> None:\n self.label = label\n self.parent = parent\n self.left: Node | None = None\n self.right: Node | None = None\n\n\nclass BinarySearchTree:\n def __init__(self) -> None:\n self.root: Node | None = None\n\n def empty(self) -> None:\n \"\"\"\n Empties the tree\n\n >>> t = BinarySearchTree()\n >>> assert t.root is None\n >>> t.put(8)\n >>> assert t.root is not None\n \"\"\"\n self.root = None\n\n def is_empty(self) -> bool:\n \"\"\"\n Checks if the tree is empty\n\n >>> t = BinarySearchTree()\n >>> t.is_empty()\n True\n >>> t.put(8)\n >>> t.is_empty()\n False\n \"\"\"\n return self.root is None\n\n def put(self, label: int) -> None:\n \"\"\"\n Put a new node in the tree\n\n >>> t = BinarySearchTree()\n >>> t.put(8)\n >>> assert t.root.parent is None\n >>> assert t.root.label == 8\n\n >>> t.put(10)\n >>> assert t.root.right.parent == t.root\n >>> assert t.root.right.label == 10\n\n >>> t.put(3)\n >>> assert t.root.left.parent == t.root\n >>> assert t.root.left.label == 3\n \"\"\"\n self.root = self._put(self.root, label)\n\n def _put(self, node: Node | None, label: int, parent: Node | None = None) -> Node:\n if node is None:\n node = Node(label, parent)\n else:\n if label < node.label:\n node.left = self._put(node.left, label, node)\n elif label > node.label:\n node.right = self._put(node.right, label, node)\n else:\n msg = f\"Node with label {label} already exists\"\n raise ValueError(msg)\n\n return node\n\n def search(self, label: int) -> Node:\n \"\"\"\n Searches a node in the tree\n\n >>> t = BinarySearchTree()\n >>> t.put(8)\n >>> t.put(10)\n >>> node = t.search(8)\n >>> assert node.label == 8\n\n >>> node = t.search(3)\n Traceback (most recent call last):\n ...\n ValueError: Node with label 3 does not exist\n \"\"\"\n return self._search(self.root, label)\n\n def _search(self, node: Node | None, label: int) -> Node:\n if node is None:\n msg = f\"Node with label {label} does not exist\"\n raise ValueError(msg)\n else:\n if label < node.label:\n node = self._search(node.left, label)\n elif label > node.label:\n node = self._search(node.right, label)\n\n return node\n\n def remove(self, label: int) -> None:\n \"\"\"\n Removes a node in the tree\n\n >>> t = BinarySearchTree()\n >>> t.put(8)\n >>> t.put(10)\n >>> t.remove(8)\n >>> assert t.root.label == 10\n\n >>> t.remove(3)\n Traceback (most recent call last):\n ...\n ValueError: Node with label 3 does not exist\n \"\"\"\n node = self.search(label)\n if node.right and node.left:\n lowest_node = self._get_lowest_node(node.right)\n lowest_node.left = node.left\n lowest_node.right = node.right\n node.left.parent = lowest_node\n if node.right:\n node.right.parent = lowest_node\n self._reassign_nodes(node, lowest_node)\n elif not node.right and node.left:\n self._reassign_nodes(node, node.left)\n elif node.right and not node.left:\n self._reassign_nodes(node, node.right)\n else:\n self._reassign_nodes(node, None)\n\n def _reassign_nodes(self, node: Node, new_children: Node | None) -> None:\n if new_children:\n new_children.parent = node.parent\n\n if node.parent:\n if node.parent.right == node:\n node.parent.right = new_children\n else:\n node.parent.left = new_children\n else:\n self.root = new_children\n\n def _get_lowest_node(self, node: Node) -> Node:\n if node.left:\n lowest_node = self._get_lowest_node(node.left)\n else:\n lowest_node = node\n self._reassign_nodes(node, node.right)\n\n return lowest_node\n\n def exists(self, label: int) -> bool:\n \"\"\"\n Checks if a node exists in the tree\n\n >>> t = BinarySearchTree()\n >>> t.put(8)\n >>> t.put(10)\n >>> t.exists(8)\n True\n\n >>> t.exists(3)\n False\n \"\"\"\n try:\n self.search(label)\n return True\n except ValueError:\n return False\n\n def get_max_label(self) -> int:\n \"\"\"\n Gets the max label inserted in the tree\n\n >>> t = BinarySearchTree()\n >>> t.get_max_label()\n Traceback (most recent call last):\n ...\n ValueError: Binary search tree is empty\n\n >>> t.put(8)\n >>> t.put(10)\n >>> t.get_max_label()\n 10\n \"\"\"\n if self.root is None:\n raise ValueError(\"Binary search tree is empty\")\n\n node = self.root\n while node.right is not None:\n node = node.right\n\n return node.label\n\n def get_min_label(self) -> int:\n \"\"\"\n Gets the min label inserted in the tree\n\n >>> t = BinarySearchTree()\n >>> t.get_min_label()\n Traceback (most recent call last):\n ...\n ValueError: Binary search tree is empty\n\n >>> t.put(8)\n >>> t.put(10)\n >>> t.get_min_label()\n 8\n \"\"\"\n if self.root is None:\n raise ValueError(\"Binary search tree is empty\")\n\n node = self.root\n while node.left is not None:\n node = node.left\n\n return node.label\n\n def inorder_traversal(self) -> Iterator[Node]:\n \"\"\"\n Return the inorder traversal of the tree\n\n >>> t = BinarySearchTree()\n >>> [i.label for i in t.inorder_traversal()]\n []\n\n >>> t.put(8)\n >>> t.put(10)\n >>> t.put(9)\n >>> [i.label for i in t.inorder_traversal()]\n [8, 9, 10]\n \"\"\"\n return self._inorder_traversal(self.root)\n\n def _inorder_traversal(self, node: Node | None) -> Iterator[Node]:\n if node is not None:\n yield from self._inorder_traversal(node.left)\n yield node\n yield from self._inorder_traversal(node.right)\n\n def preorder_traversal(self) -> Iterator[Node]:\n \"\"\"\n Return the preorder traversal of the tree\n\n >>> t = BinarySearchTree()\n >>> [i.label for i in t.preorder_traversal()]\n []\n\n >>> t.put(8)\n >>> t.put(10)\n >>> t.put(9)\n >>> [i.label for i in t.preorder_traversal()]\n [8, 10, 9]\n \"\"\"\n return self._preorder_traversal(self.root)\n\n def _preorder_traversal(self, node: Node | None) -> Iterator[Node]:\n if node is not None:\n yield node\n yield from self._preorder_traversal(node.left)\n yield from self._preorder_traversal(node.right)\n\n\nclass BinarySearchTreeTest(unittest.TestCase):\n @staticmethod\n def _get_binary_search_tree() -> BinarySearchTree:\n r\"\"\"\n 8\n \/ \\\n 3 10\n \/ \\ \\\n 1 6 14\n \/ \\ \/\n 4 7 13\n \\\n 5\n \"\"\"\n t = BinarySearchTree()\n t.put(8)\n t.put(3)\n t.put(6)\n t.put(1)\n t.put(10)\n t.put(14)\n t.put(13)\n t.put(4)\n t.put(7)\n t.put(5)\n\n return t\n\n def test_put(self) -> None:\n t = BinarySearchTree()\n assert t.is_empty()\n\n t.put(8)\n r\"\"\"\n 8\n \"\"\"\n assert t.root is not None\n assert t.root.parent is None\n assert t.root.label == 8\n\n t.put(10)\n r\"\"\"\n 8\n \\\n 10\n \"\"\"\n assert t.root.right is not None\n assert t.root.right.parent == t.root\n assert t.root.right.label == 10\n\n t.put(3)\n r\"\"\"\n 8\n \/ \\\n 3 10\n \"\"\"\n assert t.root.left is not None\n assert t.root.left.parent == t.root\n assert t.root.left.label == 3\n\n t.put(6)\n r\"\"\"\n 8\n \/ \\\n 3 10\n \\\n 6\n \"\"\"\n assert t.root.left.right is not None\n assert t.root.left.right.parent == t.root.left\n assert t.root.left.right.label == 6\n\n t.put(1)\n r\"\"\"\n 8\n \/ \\\n 3 10\n \/ \\\n 1 6\n \"\"\"\n assert t.root.left.left is not None\n assert t.root.left.left.parent == t.root.left\n assert t.root.left.left.label == 1\n\n with pytest.raises(ValueError):\n t.put(1)\n\n def test_search(self) -> None:\n t = self._get_binary_search_tree()\n\n node = t.search(6)\n assert node.label == 6\n\n node = t.search(13)\n assert node.label == 13\n\n with pytest.raises(ValueError):\n t.search(2)\n\n def test_remove(self) -> None:\n t = self._get_binary_search_tree()\n\n t.remove(13)\n r\"\"\"\n 8\n \/ \\\n 3 10\n \/ \\ \\\n 1 6 14\n \/ \\\n 4 7\n \\\n 5\n \"\"\"\n assert t.root is not None\n assert t.root.right is not None\n assert t.root.right.right is not None\n assert t.root.right.right.right is None\n assert t.root.right.right.left is None\n\n t.remove(7)\n r\"\"\"\n 8\n \/ \\\n 3 10\n \/ \\ \\\n 1 6 14\n \/\n 4\n \\\n 5\n \"\"\"\n assert t.root.left is not None\n assert t.root.left.right is not None\n assert t.root.left.right.left is not None\n assert t.root.left.right.right is None\n assert t.root.left.right.left.label == 4\n\n t.remove(6)\n r\"\"\"\n 8\n \/ \\\n 3 10\n \/ \\ \\\n 1 4 14\n \\\n 5\n \"\"\"\n assert t.root.left.left is not None\n assert t.root.left.right.right is not None\n assert t.root.left.left.label == 1\n assert t.root.left.right.label == 4\n assert t.root.left.right.right.label == 5\n assert t.root.left.right.left is None\n assert t.root.left.left.parent == t.root.left\n assert t.root.left.right.parent == t.root.left\n\n t.remove(3)\n r\"\"\"\n 8\n \/ \\\n 4 10\n \/ \\ \\\n 1 5 14\n \"\"\"\n assert t.root is not None\n assert t.root.left.label == 4\n assert t.root.left.right.label == 5\n assert t.root.left.left.label == 1\n assert t.root.left.parent == t.root\n assert t.root.left.left.parent == t.root.left\n assert t.root.left.right.parent == t.root.left\n\n t.remove(4)\n r\"\"\"\n 8\n \/ \\\n 5 10\n \/ \\\n 1 14\n \"\"\"\n assert t.root.left is not None\n assert t.root.left.left is not None\n assert t.root.left.label == 5\n assert t.root.left.right is None\n assert t.root.left.left.label == 1\n assert t.root.left.parent == t.root\n assert t.root.left.left.parent == t.root.left\n\n def test_remove_2(self) -> None:\n t = self._get_binary_search_tree()\n\n t.remove(3)\n r\"\"\"\n 8\n \/ \\\n 4 10\n \/ \\ \\\n 1 6 14\n \/ \\ \/\n 5 7 13\n \"\"\"\n assert t.root is not None\n assert t.root.left is not None\n assert t.root.left.left is not None\n assert t.root.left.right is not None\n assert t.root.left.right.left is not None\n assert t.root.left.right.right is not None\n assert t.root.left.label == 4\n assert t.root.left.right.label == 6\n assert t.root.left.left.label == 1\n assert t.root.left.right.right.label == 7\n assert t.root.left.right.left.label == 5\n assert t.root.left.parent == t.root\n assert t.root.left.right.parent == t.root.left\n assert t.root.left.left.parent == t.root.left\n assert t.root.left.right.left.parent == t.root.left.right\n\n def test_empty(self) -> None:\n t = self._get_binary_search_tree()\n t.empty()\n assert t.root is None\n\n def test_is_empty(self) -> None:\n t = self._get_binary_search_tree()\n assert not t.is_empty()\n\n t.empty()\n assert t.is_empty()\n\n def test_exists(self) -> None:\n t = self._get_binary_search_tree()\n\n assert t.exists(6)\n assert not t.exists(-1)\n\n def test_get_max_label(self) -> None:\n t = self._get_binary_search_tree()\n\n assert t.get_max_label() == 14\n\n t.empty()\n with pytest.raises(ValueError):\n t.get_max_label()\n\n def test_get_min_label(self) -> None:\n t = self._get_binary_search_tree()\n\n assert t.get_min_label() == 1\n\n t.empty()\n with pytest.raises(ValueError):\n t.get_min_label()\n\n def test_inorder_traversal(self) -> None:\n t = self._get_binary_search_tree()\n\n inorder_traversal_nodes = [i.label for i in t.inorder_traversal()]\n assert inorder_traversal_nodes == [1, 3, 4, 5, 6, 7, 8, 10, 13, 14]\n\n def test_preorder_traversal(self) -> None:\n t = self._get_binary_search_tree()\n\n preorder_traversal_nodes = [i.label for i in t.preorder_traversal()]\n assert preorder_traversal_nodes == [8, 3, 1, 6, 4, 5, 7, 10, 14, 13]\n\n\ndef binary_search_tree_example() -> None:\n r\"\"\"\n Example\n 8\n \/ \\\n 3 10\n \/ \\ \\\n 1 6 14\n \/ \\ \/\n 4 7 13\n \\\n 5\n\n Example After Deletion\n 4\n \/ \\\n 1 7\n \\\n 5\n\n \"\"\"\n\n t = BinarySearchTree()\n t.put(8)\n t.put(3)\n t.put(6)\n t.put(1)\n t.put(10)\n t.put(14)\n t.put(13)\n t.put(4)\n t.put(7)\n t.put(5)\n\n print(\n \"\"\"\n 8\n \/ \\\\\n 3 10\n \/ \\\\ \\\\\n 1 6 14\n \/ \\\\ \/\n 4 7 13\n \\\\\n 5\n \"\"\"\n )\n\n print(\"Label 6 exists:\", t.exists(6))\n print(\"Label 13 exists:\", t.exists(13))\n print(\"Label -1 exists:\", t.exists(-1))\n print(\"Label 12 exists:\", t.exists(12))\n\n # Prints all the elements of the list in inorder traversal\n inorder_traversal_nodes = [i.label for i in t.inorder_traversal()]\n print(\"Inorder traversal:\", inorder_traversal_nodes)\n\n # Prints all the elements of the list in preorder traversal\n preorder_traversal_nodes = [i.label for i in t.preorder_traversal()]\n print(\"Preorder traversal:\", preorder_traversal_nodes)\n\n print(\"Max. label:\", t.get_max_label())\n print(\"Min. label:\", t.get_min_label())\n\n # Delete elements\n print(\"\\nDeleting elements 13, 10, 8, 3, 6, 14\")\n print(\n \"\"\"\n 4\n \/ \\\\\n 1 7\n \\\\\n 5\n \"\"\"\n )\n t.remove(13)\n t.remove(10)\n t.remove(8)\n t.remove(3)\n t.remove(6)\n t.remove(14)\n\n # Prints all the elements of the list in inorder traversal after delete\n inorder_traversal_nodes = [i.label for i in t.inorder_traversal()]\n print(\"Inorder traversal after delete:\", inorder_traversal_nodes)\n\n # Prints all the elements of the list in preorder traversal after delete\n preorder_traversal_nodes = [i.label for i in t.preorder_traversal()]\n print(\"Preorder traversal after delete:\", preorder_traversal_nodes)\n\n print(\"Max. label:\", t.get_max_label())\n print(\"Min. label:\", t.get_min_label())\n\n\nif __name__ == \"__main__\":\n binary_search_tree_example()\n"} +{"Prompt":"Problem Description: Given a binary tree, return its mirror. binarytreemirror 1: 2,3, 2: 4,5, 3: 6,7, 7: 8,9, 1 1: 3, 2, 2: 5, 4, 3: 7, 6, 7: 9, 8 binarytreemirror 1: 2,3, 2: 4,5, 3: 6,7, 4: 10,11, 1 1: 3, 2, 2: 5, 4, 3: 7, 6, 4: 11, 10 binarytreemirror 1: 2,3, 2: 4,5, 3: 6,7, 4: 10,11, 5 Traceback most recent call last: ... ValueError: root 5 is not present in the binarytree binarytreemirror, 5 Traceback most recent call last: ... ValueError: binary tree cannot be empty","Completions":"def binary_tree_mirror_dict(binary_tree_mirror_dictionary: dict, root: int):\n if not root or root not in binary_tree_mirror_dictionary:\n return\n left_child, right_child = binary_tree_mirror_dictionary[root][:2]\n binary_tree_mirror_dictionary[root] = [right_child, left_child]\n binary_tree_mirror_dict(binary_tree_mirror_dictionary, left_child)\n binary_tree_mirror_dict(binary_tree_mirror_dictionary, right_child)\n\n\ndef binary_tree_mirror(binary_tree: dict, root: int = 1) -> dict:\n \"\"\"\n >>> binary_tree_mirror({ 1: [2,3], 2: [4,5], 3: [6,7], 7: [8,9]}, 1)\n {1: [3, 2], 2: [5, 4], 3: [7, 6], 7: [9, 8]}\n >>> binary_tree_mirror({ 1: [2,3], 2: [4,5], 3: [6,7], 4: [10,11]}, 1)\n {1: [3, 2], 2: [5, 4], 3: [7, 6], 4: [11, 10]}\n >>> binary_tree_mirror({ 1: [2,3], 2: [4,5], 3: [6,7], 4: [10,11]}, 5)\n Traceback (most recent call last):\n ...\n ValueError: root 5 is not present in the binary_tree\n >>> binary_tree_mirror({}, 5)\n Traceback (most recent call last):\n ...\n ValueError: binary tree cannot be empty\n \"\"\"\n if not binary_tree:\n raise ValueError(\"binary tree cannot be empty\")\n if root not in binary_tree:\n msg = f\"root {root} is not present in the binary_tree\"\n raise ValueError(msg)\n binary_tree_mirror_dictionary = dict(binary_tree)\n binary_tree_mirror_dict(binary_tree_mirror_dictionary, root)\n return binary_tree_mirror_dictionary\n\n\nif __name__ == \"__main__\":\n binary_tree = {1: [2, 3], 2: [4, 5], 3: [6, 7], 7: [8, 9]}\n print(f\"Binary tree: {binary_tree}\")\n binary_tree_mirror_dictionary = binary_tree_mirror(binary_tree, 5)\n print(f\"Binary tree mirror: {binary_tree_mirror_dictionary}\")\n"} +{"Prompt":"Sum of all nodes in a binary tree. Python implementation: On time complexity Recurses through :meth:depthfirstsearch with each element. On space complexity At any point in time maximum number of stack frames that could be in memory is n A Node has a value variable and pointers to Nodes to its left and right. def initself, tree: Node None: self.tree tree def depthfirstsearchself, node: Node None int: if node is None: return 0 return node.value self.depthfirstsearchnode.left self.depthfirstsearchnode.right def iterself Iteratorint: yield self.depthfirstsearchself.tree if name main: import doctest doctest.testmod","Completions":"from __future__ import annotations\n\nfrom collections.abc import Iterator\n\n\nclass Node:\n \"\"\"\n A Node has a value variable and pointers to Nodes to its left and right.\n \"\"\"\n\n def __init__(self, value: int) -> None:\n self.value = value\n self.left: Node | None = None\n self.right: Node | None = None\n\n\nclass BinaryTreeNodeSum:\n r\"\"\"\n The below tree looks like this\n 10\n \/ \\\n 5 -3\n \/ \/ \\\n 12 8 0\n\n >>> tree = Node(10)\n >>> sum(BinaryTreeNodeSum(tree))\n 10\n\n >>> tree.left = Node(5)\n >>> sum(BinaryTreeNodeSum(tree))\n 15\n\n >>> tree.right = Node(-3)\n >>> sum(BinaryTreeNodeSum(tree))\n 12\n\n >>> tree.left.left = Node(12)\n >>> sum(BinaryTreeNodeSum(tree))\n 24\n\n >>> tree.right.left = Node(8)\n >>> tree.right.right = Node(0)\n >>> sum(BinaryTreeNodeSum(tree))\n 32\n \"\"\"\n\n def __init__(self, tree: Node) -> None:\n self.tree = tree\n\n def depth_first_search(self, node: Node | None) -> int:\n if node is None:\n return 0\n return node.value + (\n self.depth_first_search(node.left) + self.depth_first_search(node.right)\n )\n\n def __iter__(self) -> Iterator[int]:\n yield self.depth_first_search(self.tree)\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Given the root of a binary tree and an integer target, find the number of paths where the sum of the values along the path equals target. Leetcode reference: https:leetcode.comproblemspathsumiii A Node has value variable and pointers to Nodes to its left and right. target: int def initself None: self.paths 0 def depthfirstsearchself, node: Node None, pathsum: int None: if node is None: return if pathsum self.target: self.paths 1 if node.left: self.depthfirstsearchnode.left, pathsum node.left.value if node.right: self.depthfirstsearchnode.right, pathsum node.right.value def pathsumself, node: Node None, target: int None None int: if node is None: return 0 if target is not None: self.target target self.depthfirstsearchnode, node.value self.pathsumnode.left self.pathsumnode.right return self.paths if name main: import doctest doctest.testmod","Completions":"from __future__ import annotations\n\n\nclass Node:\n \"\"\"\n A Node has value variable and pointers to Nodes to its left and right.\n \"\"\"\n\n def __init__(self, value: int) -> None:\n self.value = value\n self.left: Node | None = None\n self.right: Node | None = None\n\n\nclass BinaryTreePathSum:\n r\"\"\"\n The below tree looks like this\n 10\n \/ \\\n 5 -3\n \/ \\ \\\n 3 2 11\n \/ \\ \\\n 3 -2 1\n\n\n >>> tree = Node(10)\n >>> tree.left = Node(5)\n >>> tree.right = Node(-3)\n >>> tree.left.left = Node(3)\n >>> tree.left.right = Node(2)\n >>> tree.right.right = Node(11)\n >>> tree.left.left.left = Node(3)\n >>> tree.left.left.right = Node(-2)\n >>> tree.left.right.right = Node(1)\n\n >>> BinaryTreePathSum().path_sum(tree, 8)\n 3\n >>> BinaryTreePathSum().path_sum(tree, 7)\n 2\n >>> tree.right.right = Node(10)\n >>> BinaryTreePathSum().path_sum(tree, 8)\n 2\n \"\"\"\n\n target: int\n\n def __init__(self) -> None:\n self.paths = 0\n\n def depth_first_search(self, node: Node | None, path_sum: int) -> None:\n if node is None:\n return\n\n if path_sum == self.target:\n self.paths += 1\n\n if node.left:\n self.depth_first_search(node.left, path_sum + node.left.value)\n if node.right:\n self.depth_first_search(node.right, path_sum + node.right.value)\n\n def path_sum(self, node: Node | None, target: int | None = None) -> int:\n if node is None:\n return 0\n if target is not None:\n self.target = target\n\n self.depth_first_search(node, node.value)\n self.path_sum(node.left)\n self.path_sum(node.right)\n\n return self.paths\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"https:en.wikipedia.orgwikiTreetraversal tree Node1 tree.left Node2 tree.right Node3 tree.left.left Node4 tree.left.right Node5 return tree def preorderroot: Node None Generatorint, None, None: if not root: return yield root.data yield from preorderroot.left yield from preorderroot.right def postorderroot: Node None Generatorint, None, None: if not root: return yield from postorderroot.left yield from postorderroot.right yield root.data def inorderroot: Node None Generatorint, None, None: if not root: return yield from inorderroot.left yield root.data yield from inorderroot.right def reverseinorderroot: Node None Generatorint, None, None: if not root: return yield from reverseinorderroot.right yield root.data yield from reverseinorderroot.left def heightroot: Node None int: return maxheightroot.left, heightroot.right 1 if root else 0 def levelorderroot: Node None Generatorint, None, None: if root is None: return processqueue dequeroot while processqueue: node processqueue.popleft yield node.data if node.left: processqueue.appendnode.left if node.right: processqueue.appendnode.right def getnodesfromlefttoright root: Node None, level: int Generatorint, None, None: def populateoutputroot: Node None, level: int Generatorint, None, None: if not root: return if level 1: yield root.data elif level 1: yield from populateoutputroot.left, level 1 yield from populateoutputroot.right, level 1 yield from populateoutputroot, level def getnodesfromrighttoleft root: Node None, level: int Generatorint, None, None: def populateoutputroot: Node None, level: int Generatorint, None, None: if root is None: return if level 1: yield root.data elif level 1: yield from populateoutputroot.right, level 1 yield from populateoutputroot.left, level 1 yield from populateoutputroot, level def zigzagroot: Node None Generatorint, None, None: if root is None: return flag 0 heighttree heightroot for h in range1, heighttree 1: if not flag: yield from getnodesfromlefttorightroot, h flag 1 else: yield from getnodesfromrighttoleftroot, h flag 0 def main None: Main function for testing. Create binary tree. root maketree All Traversals of the binary are as follows: printfInorder Traversal: listinorderroot printfReverse Inorder Traversal: listreverseinorderroot printfPreorder Traversal: listpreorderroot printfPostorder Traversal: listpostorderroot, n printfHeight of Tree: heightroot, n printComplete Level Order Traversal: printflistlevelorderroot n printLevelwise order Traversal: for level in range1, heightroot 1: printfLevel level:, listgetnodesfromlefttorightroot, levellevel printnZigZag order Traversal: printflistzigzagroot if name main: import doctest doctest.testmod main","Completions":"from __future__ import annotations\n\nfrom collections import deque\nfrom collections.abc import Generator\nfrom dataclasses import dataclass\n\n\n# https:\/\/en.wikipedia.org\/wiki\/Tree_traversal\n@dataclass\nclass Node:\n data: int\n left: Node | None = None\n right: Node | None = None\n\n\ndef make_tree() -> Node | None:\n r\"\"\"\n The below tree\n 1\n \/ \\\n 2 3\n \/ \\\n 4 5\n \"\"\"\n tree = Node(1)\n tree.left = Node(2)\n tree.right = Node(3)\n tree.left.left = Node(4)\n tree.left.right = Node(5)\n return tree\n\n\ndef preorder(root: Node | None) -> Generator[int, None, None]:\n \"\"\"\n Pre-order traversal visits root node, left subtree, right subtree.\n >>> list(preorder(make_tree()))\n [1, 2, 4, 5, 3]\n \"\"\"\n if not root:\n return\n yield root.data\n yield from preorder(root.left)\n yield from preorder(root.right)\n\n\ndef postorder(root: Node | None) -> Generator[int, None, None]:\n \"\"\"\n Post-order traversal visits left subtree, right subtree, root node.\n >>> list(postorder(make_tree()))\n [4, 5, 2, 3, 1]\n \"\"\"\n if not root:\n return\n yield from postorder(root.left)\n yield from postorder(root.right)\n yield root.data\n\n\ndef inorder(root: Node | None) -> Generator[int, None, None]:\n \"\"\"\n In-order traversal visits left subtree, root node, right subtree.\n >>> list(inorder(make_tree()))\n [4, 2, 5, 1, 3]\n \"\"\"\n if not root:\n return\n yield from inorder(root.left)\n yield root.data\n yield from inorder(root.right)\n\n\ndef reverse_inorder(root: Node | None) -> Generator[int, None, None]:\n \"\"\"\n Reverse in-order traversal visits right subtree, root node, left subtree.\n >>> list(reverse_inorder(make_tree()))\n [3, 1, 5, 2, 4]\n \"\"\"\n if not root:\n return\n yield from reverse_inorder(root.right)\n yield root.data\n yield from reverse_inorder(root.left)\n\n\ndef height(root: Node | None) -> int:\n \"\"\"\n Recursive function for calculating the height of the binary tree.\n >>> height(None)\n 0\n >>> height(make_tree())\n 3\n \"\"\"\n return (max(height(root.left), height(root.right)) + 1) if root else 0\n\n\ndef level_order(root: Node | None) -> Generator[int, None, None]:\n \"\"\"\n Returns a list of nodes value from a whole binary tree in Level Order Traverse.\n Level Order traverse: Visit nodes of the tree level-by-level.\n \"\"\"\n\n if root is None:\n return\n\n process_queue = deque([root])\n\n while process_queue:\n node = process_queue.popleft()\n yield node.data\n\n if node.left:\n process_queue.append(node.left)\n if node.right:\n process_queue.append(node.right)\n\n\ndef get_nodes_from_left_to_right(\n root: Node | None, level: int\n) -> Generator[int, None, None]:\n \"\"\"\n Returns a list of nodes value from a particular level:\n Left to right direction of the binary tree.\n \"\"\"\n\n def populate_output(root: Node | None, level: int) -> Generator[int, None, None]:\n if not root:\n return\n if level == 1:\n yield root.data\n elif level > 1:\n yield from populate_output(root.left, level - 1)\n yield from populate_output(root.right, level - 1)\n\n yield from populate_output(root, level)\n\n\ndef get_nodes_from_right_to_left(\n root: Node | None, level: int\n) -> Generator[int, None, None]:\n \"\"\"\n Returns a list of nodes value from a particular level:\n Right to left direction of the binary tree.\n \"\"\"\n\n def populate_output(root: Node | None, level: int) -> Generator[int, None, None]:\n if root is None:\n return\n if level == 1:\n yield root.data\n elif level > 1:\n yield from populate_output(root.right, level - 1)\n yield from populate_output(root.left, level - 1)\n\n yield from populate_output(root, level)\n\n\ndef zigzag(root: Node | None) -> Generator[int, None, None]:\n \"\"\"\n ZigZag traverse:\n Returns a list of nodes value from left to right and right to left, alternatively.\n \"\"\"\n if root is None:\n return\n\n flag = 0\n height_tree = height(root)\n\n for h in range(1, height_tree + 1):\n if not flag:\n yield from get_nodes_from_left_to_right(root, h)\n flag = 1\n else:\n yield from get_nodes_from_right_to_left(root, h)\n flag = 0\n\n\ndef main() -> None: # Main function for testing.\n # Create binary tree.\n root = make_tree()\n\n # All Traversals of the binary are as follows:\n print(f\"In-order Traversal: {list(inorder(root))}\")\n print(f\"Reverse In-order Traversal: {list(reverse_inorder(root))}\")\n print(f\"Pre-order Traversal: {list(preorder(root))}\")\n print(f\"Post-order Traversal: {list(postorder(root))}\", \"\\n\")\n\n print(f\"Height of Tree: {height(root)}\", \"\\n\")\n\n print(\"Complete Level Order Traversal: \")\n print(f\"{list(level_order(root))} \\n\")\n\n print(\"Level-wise order Traversal: \")\n\n for level in range(1, height(root) + 1):\n print(f\"Level {level}:\", list(get_nodes_from_left_to_right(root, level=level)))\n\n print(\"\\nZigZag order Traversal: \")\n print(f\"{list(zigzag(root))}\")\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n main()\n"} +{"Prompt":"The diameterwidth of a tree is defined as the number of nodes on the longest path between two end nodes. root Node1 root.depth 1 root.left Node2 root.depth 2 root.left.depth 1 root.right Node3 root.depth 2 root Node1 root.diameter 1 root.left Node2 root.diameter 2 root.left.diameter 1 root.right Node3 root.diameter 3 printfroot.diameter 4 printfroot.left.diameter 3 printfroot.right.diameter 1","Completions":"from __future__ import annotations\n\nfrom dataclasses import dataclass\n\n\n@dataclass\nclass Node:\n data: int\n left: Node | None = None\n right: Node | None = None\n\n def depth(self) -> int:\n \"\"\"\n >>> root = Node(1)\n >>> root.depth()\n 1\n >>> root.left = Node(2)\n >>> root.depth()\n 2\n >>> root.left.depth()\n 1\n >>> root.right = Node(3)\n >>> root.depth()\n 2\n \"\"\"\n left_depth = self.left.depth() if self.left else 0\n right_depth = self.right.depth() if self.right else 0\n return max(left_depth, right_depth) + 1\n\n def diameter(self) -> int:\n \"\"\"\n >>> root = Node(1)\n >>> root.diameter()\n 1\n >>> root.left = Node(2)\n >>> root.diameter()\n 2\n >>> root.left.diameter()\n 1\n >>> root.right = Node(3)\n >>> root.diameter()\n 3\n \"\"\"\n left_depth = self.left.depth() if self.left else 0\n right_depth = self.right.depth() if self.right else 0\n return left_depth + right_depth + 1\n\n\nif __name__ == \"__main__\":\n from doctest import testmod\n\n testmod()\n root = Node(1)\n root.left = Node(2)\n root.right = Node(3)\n root.left.left = Node(4)\n root.left.right = Node(5)\n r\"\"\"\n Constructed binary tree is\n 1\n \/ \\\n 2\t 3\n \/ \\\n 4\t 5\n \"\"\"\n print(f\"{root.diameter() = }\") # 4\n print(f\"{root.left.diameter() = }\") # 3\n print(f\"{root.right.diameter() = }\") # 1\n"} +{"Prompt":"from future import annotations from collections import defaultdict from dataclasses import dataclass dataclass class TreeNode: val: int left: TreeNode None None right: TreeNode None None def maketree TreeNode: return TreeNode3, TreeNode9, TreeNode20, TreeNode15, TreeNode7 def binarytreerightsideviewroot: TreeNode listint: r Function returns the right side view of binary tree. 3 3 9 20 20 15 7 7 binarytreerightsideviewmaketree 3, 20, 7 binarytreerightsideviewNone A depth first search preorder traversal to append the values at right side of tree. def depthfirstsearch root: TreeNode None, depth: int, leftview: listint None: if not root: return if depth lenleftview: leftview.appendroot.val depthfirstsearchroot.left, depth 1, leftview depthfirstsearchroot.right, depth 1, leftview leftview: list if not root: return leftview depthfirstsearchroot, 0, leftview return leftview def binarytreetopsideviewroot: TreeNode listint: r Function returns the top side view of binary tree. 9 3 20 7 3 9 20 15 7 binarytreetopsideviewmaketree 9, 3, 20, 7 binarytreetopsideviewNone A breadth first search traversal with defaultdict ds to append the values of tree from top view from collections import defaultdict def breadthfirstsearchroot: TreeNode, bottomview: listint None: queue root, 0 lookup defaultdictlist while queue: first queue.pop0 node, hd first lookuphd.appendnode.val if node.left: queue.appendnode.left, hd 1 if node.right: queue.appendnode.right, hd 1 for pair in sortedlookup.items, keylambda each: each0: bottomview.appendpair11 bottomview: list if not root: return bottomview breadthfirstsearchroot, bottomview return bottomview if name main: import doctest doctest.testmod","Completions":"r\"\"\"\nProblem: Given root of a binary tree, return the:\n1. binary-tree-right-side-view\n2. binary-tree-left-side-view\n3. binary-tree-top-side-view\n4. binary-tree-bottom-side-view\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom collections import defaultdict\nfrom dataclasses import dataclass\n\n\n@dataclass\nclass TreeNode:\n val: int\n left: TreeNode | None = None\n right: TreeNode | None = None\n\n\ndef make_tree() -> TreeNode:\n \"\"\"\n >>> make_tree().val\n 3\n \"\"\"\n return TreeNode(3, TreeNode(9), TreeNode(20, TreeNode(15), TreeNode(7)))\n\n\ndef binary_tree_right_side_view(root: TreeNode) -> list[int]:\n r\"\"\"\n Function returns the right side view of binary tree.\n\n 3 <- 3\n \/ \\\n 9 20 <- 20\n \/ \\\n 15 7 <- 7\n\n >>> binary_tree_right_side_view(make_tree())\n [3, 20, 7]\n >>> binary_tree_right_side_view(None)\n []\n \"\"\"\n\n def depth_first_search(\n root: TreeNode | None, depth: int, right_view: list[int]\n ) -> None:\n \"\"\"\n A depth first search preorder traversal to append the values at\n right side of tree.\n \"\"\"\n if not root:\n return\n\n if depth == len(right_view):\n right_view.append(root.val)\n\n depth_first_search(root.right, depth + 1, right_view)\n depth_first_search(root.left, depth + 1, right_view)\n\n right_view: list = []\n if not root:\n return right_view\n\n depth_first_search(root, 0, right_view)\n return right_view\n\n\ndef binary_tree_left_side_view(root: TreeNode) -> list[int]:\n r\"\"\"\n Function returns the left side view of binary tree.\n\n 3 -> 3\n \/ \\\n 9 -> 9 20\n \/ \\\n 15 -> 15 7\n\n >>> binary_tree_left_side_view(make_tree())\n [3, 9, 15]\n >>> binary_tree_left_side_view(None)\n []\n \"\"\"\n\n def depth_first_search(\n root: TreeNode | None, depth: int, left_view: list[int]\n ) -> None:\n \"\"\"\n A depth first search preorder traversal to append the values\n at left side of tree.\n \"\"\"\n if not root:\n return\n\n if depth == len(left_view):\n left_view.append(root.val)\n\n depth_first_search(root.left, depth + 1, left_view)\n depth_first_search(root.right, depth + 1, left_view)\n\n left_view: list = []\n if not root:\n return left_view\n\n depth_first_search(root, 0, left_view)\n return left_view\n\n\ndef binary_tree_top_side_view(root: TreeNode) -> list[int]:\n r\"\"\"\n Function returns the top side view of binary tree.\n\n 9 3 20 7\n \u2b07 \u2b07 \u2b07 \u2b07\n\n 3\n \/ \\\n 9 20\n \/ \\\n 15 7\n\n >>> binary_tree_top_side_view(make_tree())\n [9, 3, 20, 7]\n >>> binary_tree_top_side_view(None)\n []\n \"\"\"\n\n def breadth_first_search(root: TreeNode, top_view: list[int]) -> None:\n \"\"\"\n A breadth first search traversal with defaultdict ds to append\n the values of tree from top view\n \"\"\"\n queue = [(root, 0)]\n lookup = defaultdict(list)\n\n while queue:\n first = queue.pop(0)\n node, hd = first\n\n lookup[hd].append(node.val)\n\n if node.left:\n queue.append((node.left, hd - 1))\n if node.right:\n queue.append((node.right, hd + 1))\n\n for pair in sorted(lookup.items(), key=lambda each: each[0]):\n top_view.append(pair[1][0])\n\n top_view: list = []\n if not root:\n return top_view\n\n breadth_first_search(root, top_view)\n return top_view\n\n\ndef binary_tree_bottom_side_view(root: TreeNode) -> list[int]:\n r\"\"\"\n Function returns the bottom side view of binary tree\n\n 3\n \/ \\\n 9 20\n \/ \\\n 15 7\n \u2191 \u2191 \u2191 \u2191\n 9 15 20 7\n\n >>> binary_tree_bottom_side_view(make_tree())\n [9, 15, 20, 7]\n >>> binary_tree_bottom_side_view(None)\n []\n \"\"\"\n from collections import defaultdict\n\n def breadth_first_search(root: TreeNode, bottom_view: list[int]) -> None:\n \"\"\"\n A breadth first search traversal with defaultdict ds to append\n the values of tree from bottom view\n \"\"\"\n queue = [(root, 0)]\n lookup = defaultdict(list)\n\n while queue:\n first = queue.pop(0)\n node, hd = first\n lookup[hd].append(node.val)\n\n if node.left:\n queue.append((node.left, hd - 1))\n if node.right:\n queue.append((node.right, hd + 1))\n\n for pair in sorted(lookup.items(), key=lambda each: each[0]):\n bottom_view.append(pair[1][-1])\n\n bottom_view: list = []\n if not root:\n return bottom_view\n\n breadth_first_search(root, bottom_view)\n return bottom_view\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Author : Alexander Pantyukhin Date : November 7, 2022 Task: You are given a tree root of a binary tree with n nodes, where each node has node.data coins. There are exactly n coins in whole tree. In one move, we may choose two adjacent nodes and move one coin from one node to another. A move may be from parent to child, or from child to parent. Return the minimum number of moves required to make every node have exactly one coin. Example 1: 3 0 0 Result: 2 Example 2: 0 3 0 Result 3 leetcode: https:leetcode.comproblemsdistributecoinsinbinarytree Implementation notes: User depthfirst search approach. Let n is the number of nodes in tree Runtime: On Space: O1 distributecoinsTreeNode3, TreeNode0, TreeNode0 2 distributecoinsTreeNode0, TreeNode3, TreeNode0 3 distributecoinsTreeNode0, TreeNode0, TreeNode3 3 distributecoinsNone 0 distributecoinsTreeNode0, TreeNode0, TreeNode0 Traceback most recent call last: ... ValueError: The nodes number should be same as the number of coins distributecoinsTreeNode0, TreeNode1, TreeNode1 Traceback most recent call last: ... ValueError: The nodes number should be same as the number of coins Validation countnodesNone 0 countcoinsNone 0 Main calculation getdistribNone namedtupleCoinsDistribResult, 0 2","Completions":"from __future__ import annotations\n\nfrom dataclasses import dataclass\nfrom typing import NamedTuple\n\n\n@dataclass\nclass TreeNode:\n data: int\n left: TreeNode | None = None\n right: TreeNode | None = None\n\n\nclass CoinsDistribResult(NamedTuple):\n moves: int\n excess: int\n\n\ndef distribute_coins(root: TreeNode | None) -> int:\n \"\"\"\n >>> distribute_coins(TreeNode(3, TreeNode(0), TreeNode(0)))\n 2\n >>> distribute_coins(TreeNode(0, TreeNode(3), TreeNode(0)))\n 3\n >>> distribute_coins(TreeNode(0, TreeNode(0), TreeNode(3)))\n 3\n >>> distribute_coins(None)\n 0\n >>> distribute_coins(TreeNode(0, TreeNode(0), TreeNode(0)))\n Traceback (most recent call last):\n ...\n ValueError: The nodes number should be same as the number of coins\n >>> distribute_coins(TreeNode(0, TreeNode(1), TreeNode(1)))\n Traceback (most recent call last):\n ...\n ValueError: The nodes number should be same as the number of coins\n \"\"\"\n\n if root is None:\n return 0\n\n # Validation\n def count_nodes(node: TreeNode | None) -> int:\n \"\"\"\n >>> count_nodes(None)\n 0\n \"\"\"\n if node is None:\n return 0\n\n return count_nodes(node.left) + count_nodes(node.right) + 1\n\n def count_coins(node: TreeNode | None) -> int:\n \"\"\"\n >>> count_coins(None)\n 0\n \"\"\"\n if node is None:\n return 0\n\n return count_coins(node.left) + count_coins(node.right) + node.data\n\n if count_nodes(root) != count_coins(root):\n raise ValueError(\"The nodes number should be same as the number of coins\")\n\n # Main calculation\n def get_distrib(node: TreeNode | None) -> CoinsDistribResult:\n \"\"\"\n >>> get_distrib(None)\n namedtuple(\"CoinsDistribResult\", \"0 2\")\n \"\"\"\n\n if node is None:\n return CoinsDistribResult(0, 1)\n\n left_distrib_moves, left_distrib_excess = get_distrib(node.left)\n right_distrib_moves, right_distrib_excess = get_distrib(node.right)\n\n coins_to_left = 1 - left_distrib_excess\n coins_to_right = 1 - right_distrib_excess\n\n result_moves = (\n left_distrib_moves\n + right_distrib_moves\n + abs(coins_to_left)\n + abs(coins_to_right)\n )\n result_excess = node.data - coins_to_left - coins_to_right\n\n return CoinsDistribResult(result_moves, result_excess)\n\n return get_distrib(root)[0]\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Fenwick Tree More info: https:en.wikipedia.orgwikiFenwicktree Constructor for the Fenwick tree Parameters: arr list: list of elements to initialize the tree with optional size int: size of the Fenwick tree if arr is None Initialize the Fenwick tree with arr in ON Parameters: arr list: list of elements to initialize the tree with Returns: None a 1, 2, 3, 4, 5 f1 FenwickTreea f2 FenwickTreesizelena for index, value in enumeratea: ... f2.addindex, value f1.tree f2.tree True Get the Normal Array of the Fenwick tree in ON Returns: list: Normal Array of the Fenwick tree a i for i in range128 f FenwickTreea f.getarray a True Add a value to index in Olg N Parameters: index int: index to add value to value int: value to add to index Returns: None f FenwickTree1, 2, 3, 4, 5 f.add0, 1 f.add1, 2 f.add2, 3 f.add3, 4 f.add4, 5 f.getarray 2, 4, 6, 8, 10 Set the value of index in Olg N Parameters: index int: index to set value to value int: value to set in index Returns: None f FenwickTree5, 4, 3, 2, 1 f.update0, 1 f.update1, 2 f.update2, 3 f.update3, 4 f.update4, 5 f.getarray 1, 2, 3, 4, 5 Prefix sum of all elements in 0, right in Olg N Parameters: right int: right bound of the query exclusive Returns: int: sum of all elements in 0, right a i for i in range128 f FenwickTreea res True for i in rangelena: ... res res and f.prefixi suma:i res True Query the sum of all elements in left, right in Olg N Parameters: left int: left bound of the query inclusive right int: right bound of the query exclusive Returns: int: sum of all elements in left, right a i for i in range128 f FenwickTreea res True for i in rangelena: ... for j in rangei 1, lena: ... res res and f.queryi, j sumai:j res True Get value at index in Olg N Parameters: index int: index to get the value Returns: int: Value of element at index a i for i in range128 f FenwickTreea res True for i in rangelena: ... res res and f.geti ai res True Find the largest index with prefixi value in Olg N NOTE: Requires that all values are nonnegative! Parameters: value int: value to find the largest index of Returns: 1: if value is smaller than all elements in prefix sum int: largest index with prefixi value f FenwickTree1, 2, 0, 3, 0, 5 f.rankquery0 1 f.rankquery2 0 f.rankquery1 0 f.rankquery3 2 f.rankquery5 2 f.rankquery6 4 f.rankquery11 5","Completions":"from copy import deepcopy\n\n\nclass FenwickTree:\n \"\"\"\n Fenwick Tree\n\n More info: https:\/\/en.wikipedia.org\/wiki\/Fenwick_tree\n \"\"\"\n\n def __init__(self, arr: list[int] | None = None, size: int | None = None) -> None:\n \"\"\"\n Constructor for the Fenwick tree\n\n Parameters:\n arr (list): list of elements to initialize the tree with (optional)\n size (int): size of the Fenwick tree (if arr is None)\n \"\"\"\n\n if arr is None and size is not None:\n self.size = size\n self.tree = [0] * size\n elif arr is not None:\n self.init(arr)\n else:\n raise ValueError(\"Either arr or size must be specified\")\n\n def init(self, arr: list[int]) -> None:\n \"\"\"\n Initialize the Fenwick tree with arr in O(N)\n\n Parameters:\n arr (list): list of elements to initialize the tree with\n\n Returns:\n None\n\n >>> a = [1, 2, 3, 4, 5]\n >>> f1 = FenwickTree(a)\n >>> f2 = FenwickTree(size=len(a))\n >>> for index, value in enumerate(a):\n ... f2.add(index, value)\n >>> f1.tree == f2.tree\n True\n \"\"\"\n self.size = len(arr)\n self.tree = deepcopy(arr)\n for i in range(1, self.size):\n j = self.next_(i)\n if j < self.size:\n self.tree[j] += self.tree[i]\n\n def get_array(self) -> list[int]:\n \"\"\"\n Get the Normal Array of the Fenwick tree in O(N)\n\n Returns:\n list: Normal Array of the Fenwick tree\n\n >>> a = [i for i in range(128)]\n >>> f = FenwickTree(a)\n >>> f.get_array() == a\n True\n \"\"\"\n arr = self.tree[:]\n for i in range(self.size - 1, 0, -1):\n j = self.next_(i)\n if j < self.size:\n arr[j] -= arr[i]\n return arr\n\n @staticmethod\n def next_(index: int) -> int:\n return index + (index & (-index))\n\n @staticmethod\n def prev(index: int) -> int:\n return index - (index & (-index))\n\n def add(self, index: int, value: int) -> None:\n \"\"\"\n Add a value to index in O(lg N)\n\n Parameters:\n index (int): index to add value to\n value (int): value to add to index\n\n Returns:\n None\n\n >>> f = FenwickTree([1, 2, 3, 4, 5])\n >>> f.add(0, 1)\n >>> f.add(1, 2)\n >>> f.add(2, 3)\n >>> f.add(3, 4)\n >>> f.add(4, 5)\n >>> f.get_array()\n [2, 4, 6, 8, 10]\n \"\"\"\n if index == 0:\n self.tree[0] += value\n return\n while index < self.size:\n self.tree[index] += value\n index = self.next_(index)\n\n def update(self, index: int, value: int) -> None:\n \"\"\"\n Set the value of index in O(lg N)\n\n Parameters:\n index (int): index to set value to\n value (int): value to set in index\n\n Returns:\n None\n\n >>> f = FenwickTree([5, 4, 3, 2, 1])\n >>> f.update(0, 1)\n >>> f.update(1, 2)\n >>> f.update(2, 3)\n >>> f.update(3, 4)\n >>> f.update(4, 5)\n >>> f.get_array()\n [1, 2, 3, 4, 5]\n \"\"\"\n self.add(index, value - self.get(index))\n\n def prefix(self, right: int) -> int:\n \"\"\"\n Prefix sum of all elements in [0, right) in O(lg N)\n\n Parameters:\n right (int): right bound of the query (exclusive)\n\n Returns:\n int: sum of all elements in [0, right)\n\n >>> a = [i for i in range(128)]\n >>> f = FenwickTree(a)\n >>> res = True\n >>> for i in range(len(a)):\n ... res = res and f.prefix(i) == sum(a[:i])\n >>> res\n True\n \"\"\"\n if right == 0:\n return 0\n result = self.tree[0]\n right -= 1 # make right inclusive\n while right > 0:\n result += self.tree[right]\n right = self.prev(right)\n return result\n\n def query(self, left: int, right: int) -> int:\n \"\"\"\n Query the sum of all elements in [left, right) in O(lg N)\n\n Parameters:\n left (int): left bound of the query (inclusive)\n right (int): right bound of the query (exclusive)\n\n Returns:\n int: sum of all elements in [left, right)\n\n >>> a = [i for i in range(128)]\n >>> f = FenwickTree(a)\n >>> res = True\n >>> for i in range(len(a)):\n ... for j in range(i + 1, len(a)):\n ... res = res and f.query(i, j) == sum(a[i:j])\n >>> res\n True\n \"\"\"\n return self.prefix(right) - self.prefix(left)\n\n def get(self, index: int) -> int:\n \"\"\"\n Get value at index in O(lg N)\n\n Parameters:\n index (int): index to get the value\n\n Returns:\n int: Value of element at index\n\n >>> a = [i for i in range(128)]\n >>> f = FenwickTree(a)\n >>> res = True\n >>> for i in range(len(a)):\n ... res = res and f.get(i) == a[i]\n >>> res\n True\n \"\"\"\n return self.query(index, index + 1)\n\n def rank_query(self, value: int) -> int:\n \"\"\"\n Find the largest index with prefix(i) <= value in O(lg N)\n NOTE: Requires that all values are non-negative!\n\n Parameters:\n value (int): value to find the largest index of\n\n Returns:\n -1: if value is smaller than all elements in prefix sum\n int: largest index with prefix(i) <= value\n\n >>> f = FenwickTree([1, 2, 0, 3, 0, 5])\n >>> f.rank_query(0)\n -1\n >>> f.rank_query(2)\n 0\n >>> f.rank_query(1)\n 0\n >>> f.rank_query(3)\n 2\n >>> f.rank_query(5)\n 2\n >>> f.rank_query(6)\n 4\n >>> f.rank_query(11)\n 5\n \"\"\"\n value -= self.tree[0]\n if value < 0:\n return -1\n\n j = 1 # Largest power of 2 <= size\n while j * 2 < self.size:\n j *= 2\n\n i = 0\n\n while j > 0:\n if i + j < self.size and self.tree[i + j] <= value:\n value -= self.tree[i + j]\n i += j\n j \/\/= 2\n return i\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Binary Tree Flattening Algorithm This code defines an algorithm to flatten a binary tree into a linked list represented using the right pointers of the tree nodes. It uses inplace flattening and demonstrates the flattening process along with a display function to visualize the flattened linked list. https:www.geeksforgeeks.orgflattenabinarytreeintolinkedlist Author: Arunkumar A Date: 04092023 A TreeNode has data variable and pointers to TreeNode objects for its left and right children. Build and return a sample binary tree. Returns: TreeNode: The root of the binary tree. Examples: root buildtree root.data 1 root.left.data 2 root.right.data 5 root.left.left.data 3 root.left.right.data 4 root.right.right.data 6 Flatten a binary tree into a linked list inplace, where the linked list is represented using the right pointers of the tree nodes. Args: root TreeNode: The root of the binary tree to be flattened. Examples: root TreeNode1 root.left TreeNode2 root.right TreeNode5 root.left.left TreeNode3 root.left.right TreeNode4 root.right.right TreeNode6 flattenroot root.data 1 root.right.right is None False root.right.right TreeNode3 root.right.right.right is None True Flatten the left subtree Save the right subtree Make the left subtree the new right subtree Find the end of the new right subtree Append the original right subtree to the end Flatten the updated right subtree Display the flattened linked list. Args: root TreeNode None: The root of the flattened linked list. Examples: root TreeNode1 root.right TreeNode2 root.right.right TreeNode3 displaylinkedlistroot 1 2 3 root None displaylinkedlistroot","Completions":"from __future__ import annotations\n\n\nclass TreeNode:\n \"\"\"\n A TreeNode has data variable and pointers to TreeNode objects\n for its left and right children.\n \"\"\"\n\n def __init__(self, data: int) -> None:\n self.data = data\n self.left: TreeNode | None = None\n self.right: TreeNode | None = None\n\n\ndef build_tree() -> TreeNode:\n \"\"\"\n Build and return a sample binary tree.\n\n Returns:\n TreeNode: The root of the binary tree.\n\n Examples:\n >>> root = build_tree()\n >>> root.data\n 1\n >>> root.left.data\n 2\n >>> root.right.data\n 5\n >>> root.left.left.data\n 3\n >>> root.left.right.data\n 4\n >>> root.right.right.data\n 6\n \"\"\"\n root = TreeNode(1)\n root.left = TreeNode(2)\n root.right = TreeNode(5)\n root.left.left = TreeNode(3)\n root.left.right = TreeNode(4)\n root.right.right = TreeNode(6)\n return root\n\n\ndef flatten(root: TreeNode | None) -> None:\n \"\"\"\n Flatten a binary tree into a linked list in-place, where the linked list is\n represented using the right pointers of the tree nodes.\n\n Args:\n root (TreeNode): The root of the binary tree to be flattened.\n\n Examples:\n >>> root = TreeNode(1)\n >>> root.left = TreeNode(2)\n >>> root.right = TreeNode(5)\n >>> root.left.left = TreeNode(3)\n >>> root.left.right = TreeNode(4)\n >>> root.right.right = TreeNode(6)\n >>> flatten(root)\n >>> root.data\n 1\n >>> root.right.right is None\n False\n >>> root.right.right = TreeNode(3)\n >>> root.right.right.right is None\n True\n \"\"\"\n if not root:\n return\n\n # Flatten the left subtree\n flatten(root.left)\n\n # Save the right subtree\n right_subtree = root.right\n\n # Make the left subtree the new right subtree\n root.right = root.left\n root.left = None\n\n # Find the end of the new right subtree\n current = root\n while current.right:\n current = current.right\n\n # Append the original right subtree to the end\n current.right = right_subtree\n\n # Flatten the updated right subtree\n flatten(right_subtree)\n\n\ndef display_linked_list(root: TreeNode | None) -> None:\n \"\"\"\n Display the flattened linked list.\n\n Args:\n root (TreeNode | None): The root of the flattened linked list.\n\n Examples:\n >>> root = TreeNode(1)\n >>> root.right = TreeNode(2)\n >>> root.right.right = TreeNode(3)\n >>> display_linked_list(root)\n 1 2 3\n >>> root = None\n >>> display_linked_list(root)\n\n \"\"\"\n current = root\n while current:\n if current.right is None:\n print(current.data, end=\"\")\n break\n print(current.data, end=\" \")\n current = current.right\n\n\nif __name__ == \"__main__\":\n print(\"Flattened Linked List:\")\n root = build_tree()\n flatten(root)\n display_linked_list(root)\n"} +{"Prompt":"In a binary search tree BST: The floor of key 'k' is the maximum value that is smaller than or equal to 'k'. The ceiling of key 'k' is the minimum value that is greater than or equal to 'k'. Reference: https:bit.ly46uB0a2 Author : Arunkumar Date : 14th October 2023 Find the floor and ceiling values for a given key in a Binary Search Tree BST. Args: root: The root of the binary search tree. key: The key for which to find the floor and ceiling. Returns: A tuple containing the floor and ceiling values, respectively. Examples: root Node10 root.left Node5 root.right Node20 root.left.left Node3 root.left.right Node7 root.right.left Node15 root.right.right Node25 tupleroot 3, 5, 7, 10, 15, 20, 25 floorceilingroot, 8 7, 10 floorceilingroot, 14 10, 15 floorceilingroot, 1 None, 3 floorceilingroot, 30 25, None","Completions":"from __future__ import annotations\n\nfrom collections.abc import Iterator\nfrom dataclasses import dataclass\n\n\n@dataclass\nclass Node:\n key: int\n left: Node | None = None\n right: Node | None = None\n\n def __iter__(self) -> Iterator[int]:\n if self.left:\n yield from self.left\n yield self.key\n if self.right:\n yield from self.right\n\n def __len__(self) -> int:\n return sum(1 for _ in self)\n\n\ndef floor_ceiling(root: Node | None, key: int) -> tuple[int | None, int | None]:\n \"\"\"\n Find the floor and ceiling values for a given key in a Binary Search Tree (BST).\n\n Args:\n root: The root of the binary search tree.\n key: The key for which to find the floor and ceiling.\n\n Returns:\n A tuple containing the floor and ceiling values, respectively.\n\n Examples:\n >>> root = Node(10)\n >>> root.left = Node(5)\n >>> root.right = Node(20)\n >>> root.left.left = Node(3)\n >>> root.left.right = Node(7)\n >>> root.right.left = Node(15)\n >>> root.right.right = Node(25)\n >>> tuple(root)\n (3, 5, 7, 10, 15, 20, 25)\n >>> floor_ceiling(root, 8)\n (7, 10)\n >>> floor_ceiling(root, 14)\n (10, 15)\n >>> floor_ceiling(root, -1)\n (None, 3)\n >>> floor_ceiling(root, 30)\n (25, None)\n \"\"\"\n floor_val = None\n ceiling_val = None\n\n while root:\n if root.key == key:\n floor_val = root.key\n ceiling_val = root.key\n break\n\n if key < root.key:\n ceiling_val = root.key\n root = root.left\n else:\n floor_val = root.key\n root = root.right\n\n return floor_val, ceiling_val\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Illustrate how to implement inorder traversal in binary search tree. Author: Gurneet Singh https:www.geeksforgeeks.orgtreetraversalsinorderpreorderandpostorder Defining the structure of BinaryTreeNode def initself, data: int None: self.data data self.leftchild: BinaryTreeNode None None self.rightchild: BinaryTreeNode None None def insertnode: BinaryTreeNode None, newvalue: int BinaryTreeNode None: if node is None: node BinaryTreeNodenewvalue return node binary search tree is not empty, so we will insert it into the tree if newvalue is less than value of data in node, add it to left subtree and proceed recursively if newvalue node.data: node.leftchild insertnode.leftchild, newvalue else: if newvalue is greater than value of data in node, add it to right subtree and proceed recursively node.rightchild insertnode.rightchild, newvalue return node def inordernode: None BinaryTreeNode listint: if node is None,return if node: inorderarray inordernode.leftchild inorderarray inorderarray, node.data inorderarray inorderarray inordernode.rightchild else: inorderarray return inorderarray def maketree BinaryTreeNode None: root insertNone, 15 insertroot, 10 insertroot, 25 insertroot, 6 insertroot, 14 insertroot, 20 insertroot, 60 return root def main None: main function root maketree printPrinting values of binary search tree in Inorder Traversal. inorderroot if name main: import doctest doctest.testmod main","Completions":"class BinaryTreeNode:\n \"\"\"Defining the structure of BinaryTreeNode\"\"\"\n\n def __init__(self, data: int) -> None:\n self.data = data\n self.left_child: BinaryTreeNode | None = None\n self.right_child: BinaryTreeNode | None = None\n\n\ndef insert(node: BinaryTreeNode | None, new_value: int) -> BinaryTreeNode | None:\n \"\"\"\n If the binary search tree is empty, make a new node and declare it as root.\n >>> node_a = BinaryTreeNode(12345)\n >>> node_b = insert(node_a, 67890)\n >>> node_a.left_child == node_b.left_child\n True\n >>> node_a.right_child == node_b.right_child\n True\n >>> node_a.data == node_b.data\n True\n \"\"\"\n if node is None:\n node = BinaryTreeNode(new_value)\n return node\n\n # binary search tree is not empty,\n # so we will insert it into the tree\n # if new_value is less than value of data in node,\n # add it to left subtree and proceed recursively\n if new_value < node.data:\n node.left_child = insert(node.left_child, new_value)\n else:\n # if new_value is greater than value of data in node,\n # add it to right subtree and proceed recursively\n node.right_child = insert(node.right_child, new_value)\n return node\n\n\ndef inorder(node: None | BinaryTreeNode) -> list[int]: # if node is None,return\n \"\"\"\n >>> inorder(make_tree())\n [6, 10, 14, 15, 20, 25, 60]\n \"\"\"\n if node:\n inorder_array = inorder(node.left_child)\n inorder_array = [*inorder_array, node.data]\n inorder_array = inorder_array + inorder(node.right_child)\n else:\n inorder_array = []\n return inorder_array\n\n\ndef make_tree() -> BinaryTreeNode | None:\n root = insert(None, 15)\n insert(root, 10)\n insert(root, 25)\n insert(root, 6)\n insert(root, 14)\n insert(root, 20)\n insert(root, 60)\n return root\n\n\ndef main() -> None:\n # main function\n root = make_tree()\n print(\"Printing values of binary search tree in Inorder Traversal.\")\n inorder(root)\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n main()\n"} +{"Prompt":"Given the root of a binary tree, determine if it is a valid binary search tree BST. A valid binary search tree is defined as follows: The left subtree of a node contains only nodes with keys less than the node's key. The right subtree of a node contains only nodes with keys greater than the node's key. Both the left and right subtrees must also be binary search trees. In effect, a binary tree is a valid BST if its nodes are sorted in ascending order. leetcode: https:leetcode.comproblemsvalidatebinarysearchtree If n is the number of nodes in the tree then: Runtime: On Space: O1 root Nodedata2.1 listroot 2.1 root.leftNodedata2.0 listroot 2.0, 2.1 root.rightNodedata2.2 listroot 2.0, 2.1, 2.2 Nodedata'abc'.issorted True Nodedata2, ... leftNodedata1.999, ... rightNodedata3.issorted True Nodedata0, ... leftNodedata0, ... rightNodedata0.issorted True Nodedata0, ... leftNodedata11, ... rightNodedata3.issorted True Nodedata5, ... leftNodedata1, ... rightNodedata4, leftNodedata3.issorted False Nodedata'a', ... leftNodedata1, ... rightNodedata4, leftNodedata3.issorted Traceback most recent call last: ... TypeError: '' not supported between instances of 'str' and 'int' Nodedata2, ... leftNode, ... rightNodedata4, leftNodedata3.issorted Traceback most recent call last: ... TypeError: '' not supported between instances of 'int' and 'list'","Completions":"from __future__ import annotations\n\nfrom collections.abc import Iterator\nfrom dataclasses import dataclass\n\n\n@dataclass\nclass Node:\n data: float\n left: Node | None = None\n right: Node | None = None\n\n def __iter__(self) -> Iterator[float]:\n \"\"\"\n >>> root = Node(data=2.1)\n >>> list(root)\n [2.1]\n >>> root.left=Node(data=2.0)\n >>> list(root)\n [2.0, 2.1]\n >>> root.right=Node(data=2.2)\n >>> list(root)\n [2.0, 2.1, 2.2]\n \"\"\"\n if self.left:\n yield from self.left\n yield self.data\n if self.right:\n yield from self.right\n\n @property\n def is_sorted(self) -> bool:\n \"\"\"\n >>> Node(data='abc').is_sorted\n True\n >>> Node(data=2,\n ... left=Node(data=1.999),\n ... right=Node(data=3)).is_sorted\n True\n >>> Node(data=0,\n ... left=Node(data=0),\n ... right=Node(data=0)).is_sorted\n True\n >>> Node(data=0,\n ... left=Node(data=-11),\n ... right=Node(data=3)).is_sorted\n True\n >>> Node(data=5,\n ... left=Node(data=1),\n ... right=Node(data=4, left=Node(data=3))).is_sorted\n False\n >>> Node(data='a',\n ... left=Node(data=1),\n ... right=Node(data=4, left=Node(data=3))).is_sorted\n Traceback (most recent call last):\n ...\n TypeError: '<' not supported between instances of 'str' and 'int'\n >>> Node(data=2,\n ... left=Node([]),\n ... right=Node(data=4, left=Node(data=3))).is_sorted\n Traceback (most recent call last):\n ...\n TypeError: '<' not supported between instances of 'int' and 'list'\n \"\"\"\n if self.left and (self.data < self.left.data or not self.left.is_sorted):\n return False\n if self.right and (self.data > self.right.data or not self.right.is_sorted):\n return False\n return True\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n tree = Node(data=2.1, left=Node(data=2.0), right=Node(data=2.2))\n print(f\"Tree {list(tree)} is sorted: {tree.is_sorted = }.\")\n assert tree.right\n tree.right.data = 2.0\n print(f\"Tree {list(tree)} is sorted: {tree.is_sorted = }.\")\n tree.right.data = 2.1\n print(f\"Tree {list(tree)} is sorted: {tree.is_sorted = }.\")\n"} +{"Prompt":"Is a binary tree a sum tree where the value of every nonleaf node is equal to the sum of the values of its left and right subtrees? https:www.geeksforgeeks.orgcheckifagivenbinarytreeissumtree root Node2 listroot 2 root.left Node1 tupleroot 1, 2 root Node2 lenroot 1 root.left Node1 lenroot 2 root Node3 root.issumnode True root.left Node1 root.issumnode False root.right Node2 root.issumnode True listBinaryTree.buildatree 1, 2, 7, 11, 15, 29, 35, 40 lenBinaryTree.buildatree 8 Returns a string representation of the inorder traversal of the binary tree. strlistBinaryTree.buildatree '1, 2, 7, 11, 15, 29, 35, 40' BinaryTree.buildatree.issumtree False BinaryTree.buildasumtree.issumtree True tree BinaryTreeNode11 root tree.root root.left Node2 root.right Node29 root.left.left Node1 root.left.right Node7 root.right.left Node15 root.right.right Node40 root.right.right.left Node35 return tree classmethod def buildasumtreecls BinaryTree: r Create a binary tree with the specified structure: 26 10 3 4 6 3 listBinaryTree.buildasumtree 4, 10, 6, 26, 3, 3","Completions":"from __future__ import annotations\n\nfrom collections.abc import Iterator\nfrom dataclasses import dataclass\n\n\n@dataclass\nclass Node:\n data: int\n left: Node | None = None\n right: Node | None = None\n\n def __iter__(self) -> Iterator[int]:\n \"\"\"\n >>> root = Node(2)\n >>> list(root)\n [2]\n >>> root.left = Node(1)\n >>> tuple(root)\n (1, 2)\n \"\"\"\n if self.left:\n yield from self.left\n yield self.data\n if self.right:\n yield from self.right\n\n def __len__(self) -> int:\n \"\"\"\n >>> root = Node(2)\n >>> len(root)\n 1\n >>> root.left = Node(1)\n >>> len(root)\n 2\n \"\"\"\n return sum(1 for _ in self)\n\n @property\n def is_sum_node(self) -> bool:\n \"\"\"\n >>> root = Node(3)\n >>> root.is_sum_node\n True\n >>> root.left = Node(1)\n >>> root.is_sum_node\n False\n >>> root.right = Node(2)\n >>> root.is_sum_node\n True\n \"\"\"\n if not self.left and not self.right:\n return True # leaf nodes are considered sum nodes\n left_sum = sum(self.left) if self.left else 0\n right_sum = sum(self.right) if self.right else 0\n return all(\n (\n self.data == left_sum + right_sum,\n self.left.is_sum_node if self.left else True,\n self.right.is_sum_node if self.right else True,\n )\n )\n\n\n@dataclass\nclass BinaryTree:\n root: Node\n\n def __iter__(self) -> Iterator[int]:\n \"\"\"\n >>> list(BinaryTree.build_a_tree())\n [1, 2, 7, 11, 15, 29, 35, 40]\n \"\"\"\n return iter(self.root)\n\n def __len__(self) -> int:\n \"\"\"\n >>> len(BinaryTree.build_a_tree())\n 8\n \"\"\"\n return len(self.root)\n\n def __str__(self) -> str:\n \"\"\"\n Returns a string representation of the inorder traversal of the binary tree.\n\n >>> str(list(BinaryTree.build_a_tree()))\n '[1, 2, 7, 11, 15, 29, 35, 40]'\n \"\"\"\n return str(list(self))\n\n @property\n def is_sum_tree(self) -> bool:\n \"\"\"\n >>> BinaryTree.build_a_tree().is_sum_tree\n False\n >>> BinaryTree.build_a_sum_tree().is_sum_tree\n True\n \"\"\"\n return self.root.is_sum_node\n\n @classmethod\n def build_a_tree(cls) -> BinaryTree:\n r\"\"\"\n Create a binary tree with the specified structure:\n 11\n \/ \\\n 2 29\n \/ \\ \/ \\\n 1 7 15 40\n \\\n 35\n >>> list(BinaryTree.build_a_tree())\n [1, 2, 7, 11, 15, 29, 35, 40]\n \"\"\"\n tree = BinaryTree(Node(11))\n root = tree.root\n root.left = Node(2)\n root.right = Node(29)\n root.left.left = Node(1)\n root.left.right = Node(7)\n root.right.left = Node(15)\n root.right.right = Node(40)\n root.right.right.left = Node(35)\n return tree\n\n @classmethod\n def build_a_sum_tree(cls) -> BinaryTree:\n r\"\"\"\n Create a binary tree with the specified structure:\n 26\n \/ \\\n 10 3\n \/ \\ \\\n 4 6 3\n >>> list(BinaryTree.build_a_sum_tree())\n [4, 10, 6, 26, 3, 3]\n \"\"\"\n tree = BinaryTree(Node(26))\n root = tree.root\n root.left = Node(10)\n root.right = Node(3)\n root.left.left = Node(4)\n root.left.right = Node(6)\n root.right.right = Node(3)\n return tree\n\n\nif __name__ == \"__main__\":\n from doctest import testmod\n\n testmod()\n tree = BinaryTree.build_a_tree()\n print(f\"{tree} has {len(tree)} nodes and {tree.is_sum_tree = }.\")\n tree = BinaryTree.build_a_sum_tree()\n print(f\"{tree} has {len(tree)} nodes and {tree.is_sum_tree = }.\")\n"} +{"Prompt":"approximate the overall size of segment tree with given value create array to store lazy update segmenttree SegmentTree15 segmenttree.left1 2 segmenttree.left2 4 segmenttree.left12 24 segmenttree SegmentTree15 segmenttree.right1 3 segmenttree.right2 5 segmenttree.right12 25 update with Olg n Normal segment tree without lazy update will take Onlg n for each update update1, 1, size, a, b, v for update val v to a,b query with Olg n query1, 1, size, a, b for query max of a,b A 1, 2, 4, 7, 3, 5, 6, 11, 20, 9, 14, 15, 5, 2, 8 segmenttree SegmentTree15 segmenttree.build1, 1, 15, A segmenttree.query1, 1, 15, 4, 6 7 segmenttree.query1, 1, 15, 7, 11 14 segmenttree.query1, 1, 15, 7, 12 15","Completions":"from __future__ import annotations\n\nimport math\n\n\nclass SegmentTree:\n def __init__(self, size: int) -> None:\n self.size = size\n # approximate the overall size of segment tree with given value\n self.segment_tree = [0 for i in range(4 * size)]\n # create array to store lazy update\n self.lazy = [0 for i in range(4 * size)]\n self.flag = [0 for i in range(4 * size)] # flag for lazy update\n\n def left(self, idx: int) -> int:\n \"\"\"\n >>> segment_tree = SegmentTree(15)\n >>> segment_tree.left(1)\n 2\n >>> segment_tree.left(2)\n 4\n >>> segment_tree.left(12)\n 24\n \"\"\"\n return idx * 2\n\n def right(self, idx: int) -> int:\n \"\"\"\n >>> segment_tree = SegmentTree(15)\n >>> segment_tree.right(1)\n 3\n >>> segment_tree.right(2)\n 5\n >>> segment_tree.right(12)\n 25\n \"\"\"\n return idx * 2 + 1\n\n def build(\n self, idx: int, left_element: int, right_element: int, a: list[int]\n ) -> None:\n if left_element == right_element:\n self.segment_tree[idx] = a[left_element - 1]\n else:\n mid = (left_element + right_element) \/\/ 2\n self.build(self.left(idx), left_element, mid, a)\n self.build(self.right(idx), mid + 1, right_element, a)\n self.segment_tree[idx] = max(\n self.segment_tree[self.left(idx)], self.segment_tree[self.right(idx)]\n )\n\n def update(\n self, idx: int, left_element: int, right_element: int, a: int, b: int, val: int\n ) -> bool:\n \"\"\"\n update with O(lg n) (Normal segment tree without lazy update will take O(nlg n)\n for each update)\n\n update(1, 1, size, a, b, v) for update val v to [a,b]\n \"\"\"\n if self.flag[idx] is True:\n self.segment_tree[idx] = self.lazy[idx]\n self.flag[idx] = False\n if left_element != right_element:\n self.lazy[self.left(idx)] = self.lazy[idx]\n self.lazy[self.right(idx)] = self.lazy[idx]\n self.flag[self.left(idx)] = True\n self.flag[self.right(idx)] = True\n\n if right_element < a or left_element > b:\n return True\n if left_element >= a and right_element <= b:\n self.segment_tree[idx] = val\n if left_element != right_element:\n self.lazy[self.left(idx)] = val\n self.lazy[self.right(idx)] = val\n self.flag[self.left(idx)] = True\n self.flag[self.right(idx)] = True\n return True\n mid = (left_element + right_element) \/\/ 2\n self.update(self.left(idx), left_element, mid, a, b, val)\n self.update(self.right(idx), mid + 1, right_element, a, b, val)\n self.segment_tree[idx] = max(\n self.segment_tree[self.left(idx)], self.segment_tree[self.right(idx)]\n )\n return True\n\n # query with O(lg n)\n def query(\n self, idx: int, left_element: int, right_element: int, a: int, b: int\n ) -> int | float:\n \"\"\"\n query(1, 1, size, a, b) for query max of [a,b]\n >>> A = [1, 2, -4, 7, 3, -5, 6, 11, -20, 9, 14, 15, 5, 2, -8]\n >>> segment_tree = SegmentTree(15)\n >>> segment_tree.build(1, 1, 15, A)\n >>> segment_tree.query(1, 1, 15, 4, 6)\n 7\n >>> segment_tree.query(1, 1, 15, 7, 11)\n 14\n >>> segment_tree.query(1, 1, 15, 7, 12)\n 15\n \"\"\"\n if self.flag[idx] is True:\n self.segment_tree[idx] = self.lazy[idx]\n self.flag[idx] = False\n if left_element != right_element:\n self.lazy[self.left(idx)] = self.lazy[idx]\n self.lazy[self.right(idx)] = self.lazy[idx]\n self.flag[self.left(idx)] = True\n self.flag[self.right(idx)] = True\n if right_element < a or left_element > b:\n return -math.inf\n if left_element >= a and right_element <= b:\n return self.segment_tree[idx]\n mid = (left_element + right_element) \/\/ 2\n q1 = self.query(self.left(idx), left_element, mid, a, b)\n q2 = self.query(self.right(idx), mid + 1, right_element, a, b)\n return max(q1, q2)\n\n def __str__(self) -> str:\n return str([self.query(1, 1, self.size, i, i) for i in range(1, self.size + 1)])\n\n\nif __name__ == \"__main__\":\n A = [1, 2, -4, 7, 3, -5, 6, 11, -20, 9, 14, 15, 5, 2, -8]\n size = 15\n segt = SegmentTree(size)\n segt.build(1, 1, size, A)\n print(segt.query(1, 1, size, 4, 6))\n print(segt.query(1, 1, size, 7, 11))\n print(segt.query(1, 1, size, 7, 12))\n segt.update(1, 1, size, 1, 3, 111)\n print(segt.query(1, 1, size, 1, 15))\n segt.update(1, 1, size, 7, 8, 235)\n print(segt)\n"} +{"Prompt":"https:en.wikipedia.orgwikiLowestcommonancestor https:en.wikipedia.orgwikiBreadthfirstsearch Return a tuple b, a when given two integers a and b swap2,3 3, 2 swap3,4 4, 3 swap67, 12 12, 67 creating sparse table which saves each nodes 2ith parent returns lca of node u,v u must be deeper in the tree than v making depth of u same as depth of v at the same depth if uv that mean lca is found moving both nodes upwards till lca in found returning longest common ancestor of u,v runs a breadth first search from root node of the tree sets every nodes direct parent parent of root node is set to 0 calculates depth of each node from root node initializing with 0 initializing with 1 which means every node is unvisited","Completions":"# https:\/\/en.wikipedia.org\/wiki\/Lowest_common_ancestor\n# https:\/\/en.wikipedia.org\/wiki\/Breadth-first_search\n\nfrom __future__ import annotations\n\nfrom queue import Queue\n\n\ndef swap(a: int, b: int) -> tuple[int, int]:\n \"\"\"\n Return a tuple (b, a) when given two integers a and b\n >>> swap(2,3)\n (3, 2)\n >>> swap(3,4)\n (4, 3)\n >>> swap(67, 12)\n (12, 67)\n \"\"\"\n a ^= b\n b ^= a\n a ^= b\n return a, b\n\n\ndef create_sparse(max_node: int, parent: list[list[int]]) -> list[list[int]]:\n \"\"\"\n creating sparse table which saves each nodes 2^i-th parent\n \"\"\"\n j = 1\n while (1 << j) < max_node:\n for i in range(1, max_node + 1):\n parent[j][i] = parent[j - 1][parent[j - 1][i]]\n j += 1\n return parent\n\n\n# returns lca of node u,v\ndef lowest_common_ancestor(\n u: int, v: int, level: list[int], parent: list[list[int]]\n) -> int:\n # u must be deeper in the tree than v\n if level[u] < level[v]:\n u, v = swap(u, v)\n # making depth of u same as depth of v\n for i in range(18, -1, -1):\n if level[u] - (1 << i) >= level[v]:\n u = parent[i][u]\n # at the same depth if u==v that mean lca is found\n if u == v:\n return u\n # moving both nodes upwards till lca in found\n for i in range(18, -1, -1):\n if parent[i][u] not in [0, parent[i][v]]:\n u, v = parent[i][u], parent[i][v]\n # returning longest common ancestor of u,v\n return parent[0][u]\n\n\n# runs a breadth first search from root node of the tree\ndef breadth_first_search(\n level: list[int],\n parent: list[list[int]],\n max_node: int,\n graph: dict[int, list[int]],\n root: int = 1,\n) -> tuple[list[int], list[list[int]]]:\n \"\"\"\n sets every nodes direct parent\n parent of root node is set to 0\n calculates depth of each node from root node\n \"\"\"\n level[root] = 0\n q: Queue[int] = Queue(maxsize=max_node)\n q.put(root)\n while q.qsize() != 0:\n u = q.get()\n for v in graph[u]:\n if level[v] == -1:\n level[v] = level[u] + 1\n q.put(v)\n parent[0][v] = u\n return level, parent\n\n\ndef main() -> None:\n max_node = 13\n # initializing with 0\n parent = [[0 for _ in range(max_node + 10)] for _ in range(20)]\n # initializing with -1 which means every node is unvisited\n level = [-1 for _ in range(max_node + 10)]\n graph: dict[int, list[int]] = {\n 1: [2, 3, 4],\n 2: [5],\n 3: [6, 7],\n 4: [8],\n 5: [9, 10],\n 6: [11],\n 7: [],\n 8: [12, 13],\n 9: [],\n 10: [],\n 11: [],\n 12: [],\n 13: [],\n }\n level, parent = breadth_first_search(level, parent, max_node, graph, 1)\n parent = create_sparse(max_node, parent)\n print(\"LCA of node 1 and 3 is: \", lowest_common_ancestor(1, 3, level, parent))\n print(\"LCA of node 5 and 6 is: \", lowest_common_ancestor(5, 6, level, parent))\n print(\"LCA of node 7 and 11 is: \", lowest_common_ancestor(7, 11, level, parent))\n print(\"LCA of node 6 and 7 is: \", lowest_common_ancestor(6, 7, level, parent))\n print(\"LCA of node 4 and 12 is: \", lowest_common_ancestor(4, 12, level, parent))\n print(\"LCA of node 8 and 8 is: \", lowest_common_ancestor(8, 8, level, parent))\n\n\nif __name__ == \"__main__\":\n main()\n"} +{"Prompt":"Maximum Fenwick Tree More info: https:cpalgorithms.comdatastructuresfenwick.html ft MaxFenwickTree5 ft.query0, 5 0 ft.update4, 100 ft.query0, 5 100 ft.update4, 0 ft.update2, 20 ft.query0, 5 20 ft.update4, 10 ft.query2, 5 20 ft.query1, 5 20 ft.update2, 0 ft.query0, 5 10 ft MaxFenwickTree10000 ft.update255, 30 ft.query0, 10000 30 ft MaxFenwickTree6 ft.update5, 1 ft.query5, 6 1 ft MaxFenwickTree6 ft.update0, 1000 ft.query0, 1 1000 Create empty Maximum Fenwick Tree with specified size Parameters: size: size of Array Returns: None Get next index in O1 Get previous index in O1 Set index to value in Olg2 N Parameters: index: index to update value: value to set Returns: None Answer the query of maximum range l, r in Olg2 N Parameters: left: left index of query range inclusive right: right index of query range exclusive Returns: Maximum value of range left, right","Completions":"class MaxFenwickTree:\n \"\"\"\n Maximum Fenwick Tree\n\n More info: https:\/\/cp-algorithms.com\/data_structures\/fenwick.html\n ---------\n >>> ft = MaxFenwickTree(5)\n >>> ft.query(0, 5)\n 0\n >>> ft.update(4, 100)\n >>> ft.query(0, 5)\n 100\n >>> ft.update(4, 0)\n >>> ft.update(2, 20)\n >>> ft.query(0, 5)\n 20\n >>> ft.update(4, 10)\n >>> ft.query(2, 5)\n 20\n >>> ft.query(1, 5)\n 20\n >>> ft.update(2, 0)\n >>> ft.query(0, 5)\n 10\n >>> ft = MaxFenwickTree(10000)\n >>> ft.update(255, 30)\n >>> ft.query(0, 10000)\n 30\n >>> ft = MaxFenwickTree(6)\n >>> ft.update(5, 1)\n >>> ft.query(5, 6)\n 1\n >>> ft = MaxFenwickTree(6)\n >>> ft.update(0, 1000)\n >>> ft.query(0, 1)\n 1000\n \"\"\"\n\n def __init__(self, size: int) -> None:\n \"\"\"\n Create empty Maximum Fenwick Tree with specified size\n\n Parameters:\n size: size of Array\n\n Returns:\n None\n \"\"\"\n self.size = size\n self.arr = [0] * size\n self.tree = [0] * size\n\n @staticmethod\n def get_next(index: int) -> int:\n \"\"\"\n Get next index in O(1)\n \"\"\"\n return index | (index + 1)\n\n @staticmethod\n def get_prev(index: int) -> int:\n \"\"\"\n Get previous index in O(1)\n \"\"\"\n return (index & (index + 1)) - 1\n\n def update(self, index: int, value: int) -> None:\n \"\"\"\n Set index to value in O(lg^2 N)\n\n Parameters:\n index: index to update\n value: value to set\n\n Returns:\n None\n \"\"\"\n self.arr[index] = value\n while index < self.size:\n current_left_border = self.get_prev(index) + 1\n if current_left_border == index:\n self.tree[index] = value\n else:\n self.tree[index] = max(value, current_left_border, index)\n index = self.get_next(index)\n\n def query(self, left: int, right: int) -> int:\n \"\"\"\n Answer the query of maximum range [l, r) in O(lg^2 N)\n\n Parameters:\n left: left index of query range (inclusive)\n right: right index of query range (exclusive)\n\n Returns:\n Maximum value of range [left, right)\n \"\"\"\n right -= 1 # Because of right is exclusive\n result = 0\n while left <= right:\n current_left = self.get_prev(right)\n if left <= current_left:\n result = max(result, self.tree[right])\n right = current_left\n else:\n result = max(result, self.arr[right])\n right -= 1\n return result\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"!usrlocalbinpython3 Problem Description: Given two binary tree, return the merged tree. The rule for merging is that if two nodes overlap, then put the value sum of both nodes to the new value of the merged node. Otherwise, the NOT null node will be used as the node of new tree. A binary node has value variable and pointers to its left and right node. Returns root node of the merged tree. tree1 Node5 tree1.left Node6 tree1.right Node7 tree1.left.left Node2 tree2 Node4 tree2.left Node5 tree2.right Node8 tree2.left.right Node1 tree2.right.right Node4 mergedtree mergetwobinarytreestree1, tree2 printpreordermergedtree 9 11 2 1 15 4 Print preorder traversal of the tree. root Node1 root.left Node2 root.right Node3 printpreorderroot 1 2 3 printpreorderroot.right 3","Completions":"#!\/usr\/local\/bin\/python3\n\"\"\"\nProblem Description: Given two binary tree, return the merged tree.\nThe rule for merging is that if two nodes overlap, then put the value sum of\nboth nodes to the new value of the merged node. Otherwise, the NOT null node\nwill be used as the node of new tree.\n\"\"\"\nfrom __future__ import annotations\n\n\nclass Node:\n \"\"\"\n A binary node has value variable and pointers to its left and right node.\n \"\"\"\n\n def __init__(self, value: int = 0) -> None:\n self.value = value\n self.left: Node | None = None\n self.right: Node | None = None\n\n\ndef merge_two_binary_trees(tree1: Node | None, tree2: Node | None) -> Node | None:\n \"\"\"\n Returns root node of the merged tree.\n\n >>> tree1 = Node(5)\n >>> tree1.left = Node(6)\n >>> tree1.right = Node(7)\n >>> tree1.left.left = Node(2)\n >>> tree2 = Node(4)\n >>> tree2.left = Node(5)\n >>> tree2.right = Node(8)\n >>> tree2.left.right = Node(1)\n >>> tree2.right.right = Node(4)\n >>> merged_tree = merge_two_binary_trees(tree1, tree2)\n >>> print_preorder(merged_tree)\n 9\n 11\n 2\n 1\n 15\n 4\n \"\"\"\n if tree1 is None:\n return tree2\n if tree2 is None:\n return tree1\n\n tree1.value = tree1.value + tree2.value\n tree1.left = merge_two_binary_trees(tree1.left, tree2.left)\n tree1.right = merge_two_binary_trees(tree1.right, tree2.right)\n return tree1\n\n\ndef print_preorder(root: Node | None) -> None:\n \"\"\"\n Print pre-order traversal of the tree.\n\n >>> root = Node(1)\n >>> root.left = Node(2)\n >>> root.right = Node(3)\n >>> print_preorder(root)\n 1\n 2\n 3\n >>> print_preorder(root.right)\n 3\n \"\"\"\n if root:\n print(root.value)\n print_preorder(root.left)\n print_preorder(root.right)\n\n\nif __name__ == \"__main__\":\n tree1 = Node(1)\n tree1.left = Node(2)\n tree1.right = Node(3)\n tree1.left.left = Node(4)\n\n tree2 = Node(2)\n tree2.left = Node(4)\n tree2.right = Node(6)\n tree2.left.right = Node(9)\n tree2.right.right = Node(5)\n\n print(\"Tree1 is: \")\n print_preorder(tree1)\n print(\"Tree2 is: \")\n print_preorder(tree2)\n merged_tree = merge_two_binary_trees(tree1, tree2)\n print(\"Merged Tree is: \")\n print_preorder(merged_tree)\n"} +{"Prompt":"Given the root of a binary tree, mirror the tree, and return its root. Leetcode problem reference: https:leetcode.comproblemsmirrorbinarytree A Node has value variable and pointers to Nodes to its left and right. Mirror the binary tree rooted at this node by swapping left and right children. tree Node0 listtree 0 listtree.mirror 0 tree Node1, Node0, Node3, Node2, Node4, None, Node5 tupletree 0, 1, 2, 3, 4, 5 tupletree.mirror 5, 4, 3, 2, 1, 0 tree Node1 tree.left Node2 tree.right Node3 tree.left.left Node4 tree.left.right Node5 tree.right.left Node6 tree.right.right Node7 return tree def maketreenine Node: r Return a binary tree with 9 nodes that looks like this: 1 2 3 4 5 6 7 8 9 treenine maketreenine lentreenine 9 listtreenine 7, 4, 8, 2, 5, 9, 1, 3, 6 trees zero: Node0, seven: maketreeseven, nine: maketreenine for name, tree in trees.items: printf The name tree: tupletree 0, 4, 2, 5, 1, 6, 3, 7 7, 4, 8, 2, 5, 9, 1, 3, 6 printfMirror of name tree: tupletree.mirror 0, 7, 3, 6, 1, 5, 2, 4 6, 3, 1, 9, 5, 2, 8, 4, 7 if name main: import doctest doctest.testmod main","Completions":"from __future__ import annotations\n\nfrom collections.abc import Iterator\nfrom dataclasses import dataclass\n\n\n@dataclass\nclass Node:\n \"\"\"\n A Node has value variable and pointers to Nodes to its left and right.\n \"\"\"\n\n value: int\n left: Node | None = None\n right: Node | None = None\n\n def __iter__(self) -> Iterator[int]:\n if self.left:\n yield from self.left\n yield self.value\n if self.right:\n yield from self.right\n\n def __len__(self) -> int:\n return sum(1 for _ in self)\n\n def mirror(self) -> Node:\n \"\"\"\n Mirror the binary tree rooted at this node by swapping left and right children.\n\n >>> tree = Node(0)\n >>> list(tree)\n [0]\n >>> list(tree.mirror())\n [0]\n >>> tree = Node(1, Node(0), Node(3, Node(2), Node(4, None, Node(5))))\n >>> tuple(tree)\n (0, 1, 2, 3, 4, 5)\n >>> tuple(tree.mirror())\n (5, 4, 3, 2, 1, 0)\n \"\"\"\n self.left, self.right = self.right, self.left\n if self.left:\n self.left.mirror()\n if self.right:\n self.right.mirror()\n return self\n\n\ndef make_tree_seven() -> Node:\n r\"\"\"\n Return a binary tree with 7 nodes that looks like this:\n 1\n \/ \\\n 2 3\n \/ \\ \/ \\\n 4 5 6 7\n\n >>> tree_seven = make_tree_seven()\n >>> len(tree_seven)\n 7\n >>> list(tree_seven)\n [4, 2, 5, 1, 6, 3, 7]\n \"\"\"\n tree = Node(1)\n tree.left = Node(2)\n tree.right = Node(3)\n tree.left.left = Node(4)\n tree.left.right = Node(5)\n tree.right.left = Node(6)\n tree.right.right = Node(7)\n return tree\n\n\ndef make_tree_nine() -> Node:\n r\"\"\"\n Return a binary tree with 9 nodes that looks like this:\n 1\n \/ \\\n 2 3\n \/ \\ \\\n 4 5 6\n \/ \\ \\\n 7 8 9\n\n >>> tree_nine = make_tree_nine()\n >>> len(tree_nine)\n 9\n >>> list(tree_nine)\n [7, 4, 8, 2, 5, 9, 1, 3, 6]\n \"\"\"\n tree = Node(1)\n tree.left = Node(2)\n tree.right = Node(3)\n tree.left.left = Node(4)\n tree.left.right = Node(5)\n tree.right.right = Node(6)\n tree.left.left.left = Node(7)\n tree.left.left.right = Node(8)\n tree.left.right.right = Node(9)\n return tree\n\n\ndef main() -> None:\n r\"\"\"\n Mirror binary trees with the given root and returns the root\n\n >>> tree = make_tree_nine()\n >>> tuple(tree)\n (7, 4, 8, 2, 5, 9, 1, 3, 6)\n >>> tuple(tree.mirror())\n (6, 3, 1, 9, 5, 2, 8, 4, 7)\n\n nine_tree:\n 1\n \/ \\\n 2 3\n \/ \\ \\\n 4 5 6\n \/ \\ \\\n 7 8 9\n\n The mirrored tree looks like this:\n 1\n \/ \\\n 3 2\n \/ \/ \\\n 6 5 4\n \/ \/ \\\n 9 8 7\n \"\"\"\n trees = {\"zero\": Node(0), \"seven\": make_tree_seven(), \"nine\": make_tree_nine()}\n for name, tree in trees.items():\n print(f\" The {name} tree: {tuple(tree)}\")\n # (0,)\n # (4, 2, 5, 1, 6, 3, 7)\n # (7, 4, 8, 2, 5, 9, 1, 3, 6)\n print(f\"Mirror of {name} tree: {tuple(tree.mirror())}\")\n # (0,)\n # (7, 3, 6, 1, 5, 2, 4)\n # (6, 3, 1, 9, 5, 2, 8, 4, 7)\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n main()\n"} +{"Prompt":"A nonrecursive Segment Tree implementation with range query and single element update, works virtually with any list of the same type of elements with a commutative combiner. Explanation: https:www.geeksforgeeks.orgiterativesegmenttreerangeminimumquery https:www.geeksforgeeks.orgsegmenttreeefficientimplementation SegmentTree1, 2, 3, lambda a, b: a b.query0, 2 6 SegmentTree3, 1, 2, min.query0, 2 1 SegmentTree2, 3, 1, max.query0, 2 3 st SegmentTree1, 5, 7, 1, 6, lambda a, b: a b st.update1, 1 st.update2, 3 st.query1, 2 2 st.query1, 1 1 st.update4, 1 st.query3, 4 0 st SegmentTree1, 2, 3, 3, 2, 1, 1, 1, 1, lambda a, b: ai bi for i ... in rangelena st.query0, 1 4, 4, 4 st.query1, 2 4, 3, 2 st.update1, 1, 1, 1 st.query1, 2 0, 0, 0 st.query0, 2 1, 2, 3 Segment Tree constructor, it works just with commutative combiner. :param arr: list of elements for the segment tree :param fnc: commutative function for combine two elements SegmentTree'a', 'b', 'c', lambda a, b: f'ab'.query0, 2 'abc' SegmentTree1, 2, 2, 3, 3, 4, ... lambda a, b: a0 b0, a1 b1.query0, 2 6, 9 Update an element in logN time :param p: position to be update :param v: new value st SegmentTree3, 1, 2, 4, min st.query0, 3 1 st.update2, 1 st.query0, 3 1 Get range query value in logN time :param l: left element index :param r: right element index :return: element combined in the range l, r st SegmentTree1, 2, 3, 4, lambda a, b: a b st.query0, 2 6 st.query1, 2 5 st.query0, 3 10 st.query2, 3 7 Test all possible segments","Completions":"from __future__ import annotations\n\nfrom collections.abc import Callable\nfrom typing import Any, Generic, TypeVar\n\nT = TypeVar(\"T\")\n\n\nclass SegmentTree(Generic[T]):\n def __init__(self, arr: list[T], fnc: Callable[[T, T], T]) -> None:\n \"\"\"\n Segment Tree constructor, it works just with commutative combiner.\n :param arr: list of elements for the segment tree\n :param fnc: commutative function for combine two elements\n\n >>> SegmentTree(['a', 'b', 'c'], lambda a, b: f'{a}{b}').query(0, 2)\n 'abc'\n >>> SegmentTree([(1, 2), (2, 3), (3, 4)],\n ... lambda a, b: (a[0] + b[0], a[1] + b[1])).query(0, 2)\n (6, 9)\n \"\"\"\n any_type: Any | T = None\n\n self.N: int = len(arr)\n self.st: list[T] = [any_type for _ in range(self.N)] + arr\n self.fn = fnc\n self.build()\n\n def build(self) -> None:\n for p in range(self.N - 1, 0, -1):\n self.st[p] = self.fn(self.st[p * 2], self.st[p * 2 + 1])\n\n def update(self, p: int, v: T) -> None:\n \"\"\"\n Update an element in log(N) time\n :param p: position to be update\n :param v: new value\n\n >>> st = SegmentTree([3, 1, 2, 4], min)\n >>> st.query(0, 3)\n 1\n >>> st.update(2, -1)\n >>> st.query(0, 3)\n -1\n \"\"\"\n p += self.N\n self.st[p] = v\n while p > 1:\n p = p \/\/ 2\n self.st[p] = self.fn(self.st[p * 2], self.st[p * 2 + 1])\n\n def query(self, l: int, r: int) -> T | None: # noqa: E741\n \"\"\"\n Get range query value in log(N) time\n :param l: left element index\n :param r: right element index\n :return: element combined in the range [l, r]\n\n >>> st = SegmentTree([1, 2, 3, 4], lambda a, b: a + b)\n >>> st.query(0, 2)\n 6\n >>> st.query(1, 2)\n 5\n >>> st.query(0, 3)\n 10\n >>> st.query(2, 3)\n 7\n \"\"\"\n l, r = l + self.N, r + self.N\n\n res: T | None = None\n while l <= r:\n if l % 2 == 1:\n res = self.st[l] if res is None else self.fn(res, self.st[l])\n if r % 2 == 0:\n res = self.st[r] if res is None else self.fn(res, self.st[r])\n l, r = (l + 1) \/\/ 2, (r - 1) \/\/ 2\n return res\n\n\nif __name__ == \"__main__\":\n from functools import reduce\n\n test_array = [1, 10, -2, 9, -3, 8, 4, -7, 5, 6, 11, -12]\n\n test_updates = {\n 0: 7,\n 1: 2,\n 2: 6,\n 3: -14,\n 4: 5,\n 5: 4,\n 6: 7,\n 7: -10,\n 8: 9,\n 9: 10,\n 10: 12,\n 11: 1,\n }\n\n min_segment_tree = SegmentTree(test_array, min)\n max_segment_tree = SegmentTree(test_array, max)\n sum_segment_tree = SegmentTree(test_array, lambda a, b: a + b)\n\n def test_all_segments() -> None:\n \"\"\"\n Test all possible segments\n \"\"\"\n for i in range(len(test_array)):\n for j in range(i, len(test_array)):\n min_range = reduce(min, test_array[i : j + 1])\n max_range = reduce(max, test_array[i : j + 1])\n sum_range = reduce(lambda a, b: a + b, test_array[i : j + 1])\n assert min_range == min_segment_tree.query(i, j)\n assert max_range == max_segment_tree.query(i, j)\n assert sum_range == sum_segment_tree.query(i, j)\n\n test_all_segments()\n\n for index, value in test_updates.items():\n test_array[index] = value\n min_segment_tree.update(index, value)\n max_segment_tree.update(index, value)\n sum_segment_tree.update(index, value)\n test_all_segments()\n"} +{"Prompt":"Hey, we are going to find an exciting number called Catalan number which is use to find the number of possible binary search trees from tree of a given number of nodes. We will use the formula: tn SUMMATIONi 1 to nti1tni Further details at Wikipedia: https:en.wikipedia.orgwikiCatalannumber Our Contribution: Basically we Create the 2 function: 1. catalannumbernodecount: int int Returns the number of possible binary search trees for n nodes. 2. binarytreecountnodecount: int int Returns the number of possible binary trees for n nodes. Since Here we Find the Binomial Coefficient: https:en.wikipedia.orgwikiBinomialcoefficient Cn,k n! k!nk! :param n: 2 times of Number of nodes :param k: Number of nodes :return: Integer Value binomialcoefficient4, 2 6 Since Cn, k Cn, nk Calculate Cn,k We can find Catalan number many ways but here we use Binomial Coefficient because it does the job in On return the Catalan number of n using 2nCnn1. :param n: number of nodes :return: Catalan number of n nodes catalannumber5 42 catalannumber6 132 Return the factorial of a number. :param n: Number to find the Factorial of. :return: Factorial of n. import math allfactoriali math.factoriali for i in range10 True factorial5 doctest: ELLIPSIS Traceback most recent call last: ... ValueError: factorial not defined for negative values Return the number of possible of binary trees. :param n: number of nodes :return: Number of possible binary trees binarytreecount5 5040 binarytreecount6 95040","Completions":"\"\"\"\nOur Contribution:\nBasically we Create the 2 function:\n 1. catalan_number(node_count: int) -> int\n Returns the number of possible binary search trees for n nodes.\n 2. binary_tree_count(node_count: int) -> int\n Returns the number of possible binary trees for n nodes.\n\"\"\"\n\n\ndef binomial_coefficient(n: int, k: int) -> int:\n \"\"\"\n Since Here we Find the Binomial Coefficient:\n https:\/\/en.wikipedia.org\/wiki\/Binomial_coefficient\n C(n,k) = n! \/ k!(n-k)!\n :param n: 2 times of Number of nodes\n :param k: Number of nodes\n :return: Integer Value\n\n >>> binomial_coefficient(4, 2)\n 6\n \"\"\"\n result = 1 # To kept the Calculated Value\n # Since C(n, k) = C(n, n-k)\n if k > (n - k):\n k = n - k\n # Calculate C(n,k)\n for i in range(k):\n result *= n - i\n result \/\/= i + 1\n return result\n\n\ndef catalan_number(node_count: int) -> int:\n \"\"\"\n We can find Catalan number many ways but here we use Binomial Coefficient because it\n does the job in O(n)\n\n return the Catalan number of n using 2nCn\/(n+1).\n :param n: number of nodes\n :return: Catalan number of n nodes\n\n >>> catalan_number(5)\n 42\n >>> catalan_number(6)\n 132\n \"\"\"\n return binomial_coefficient(2 * node_count, node_count) \/\/ (node_count + 1)\n\n\ndef factorial(n: int) -> int:\n \"\"\"\n Return the factorial of a number.\n :param n: Number to find the Factorial of.\n :return: Factorial of n.\n\n >>> import math\n >>> all(factorial(i) == math.factorial(i) for i in range(10))\n True\n >>> factorial(-5) # doctest: +ELLIPSIS\n Traceback (most recent call last):\n ...\n ValueError: factorial() not defined for negative values\n \"\"\"\n if n < 0:\n raise ValueError(\"factorial() not defined for negative values\")\n result = 1\n for i in range(1, n + 1):\n result *= i\n return result\n\n\ndef binary_tree_count(node_count: int) -> int:\n \"\"\"\n Return the number of possible of binary trees.\n :param n: number of nodes\n :return: Number of possible binary trees\n\n >>> binary_tree_count(5)\n 5040\n >>> binary_tree_count(6)\n 95040\n \"\"\"\n return catalan_number(node_count) * factorial(node_count)\n\n\nif __name__ == \"__main__\":\n node_count = int(input(\"Enter the number of nodes: \").strip() or 0)\n if node_count <= 0:\n raise ValueError(\"We need some nodes to work with.\")\n print(\n f\"Given {node_count} nodes, there are {binary_tree_count(node_count)} \"\n f\"binary trees and {catalan_number(node_count)} binary search trees.\"\n )\n"} +{"Prompt":"psfblack : true ruff : passed A RedBlack tree, which is a selfbalancing BST binary search tree. This tree has similar performance to AVL trees, but the balancing is less strict, so it will perform faster for writingdeleting nodes and slower for reading in the average case, though, because they're both balanced binary search trees, both will get the same asymptotic performance. To read more about them, https:en.wikipedia.orgwikiRedblacktree Unless otherwise specified, all asymptotic runtimes are specified in terms of the size of the tree. Initialize a new RedBlack Tree node with the given values: label: The value associated with this node color: 0 if black, 1 if red parent: The parent to this node left: This node's left child right: This node's right child Here are functions which are specific to redblack trees Rotate the subtree rooted at this node to the left and returns the new root to this subtree. Performing one rotation can be done in O1. Rotate the subtree rooted at this node to the right and returns the new root to this subtree. Performing one rotation can be done in O1. Inserts label into the subtree rooted at self, performs any rotations necessary to maintain balance, and then returns the new root to this subtree likely self. This is guaranteed to run in Ologn time. Only possible with an empty tree Repair the coloring from inserting into a tree. if self.parent is None: This node is the root, so it just needs to be black self.color 0 elif colorself.parent 0: If the parent is black, then it just needs to be red self.color 1 else: uncle self.parent.sibling if coloruncle 0: if self.isleft and self.parent.isright: self.parent.rotateright if self.right: self.right.insertrepair elif self.isright and self.parent.isleft: self.parent.rotateleft if self.left: self.left.insertrepair elif self.isleft: if self.grandparent: self.grandparent.rotateright self.parent.color 0 if self.parent.right: self.parent.right.color 1 else: if self.grandparent: self.grandparent.rotateleft self.parent.color 0 if self.parent.left: self.parent.left.color 1 else: self.parent.color 0 if uncle and self.grandparent: uncle.color 0 self.grandparent.color 1 self.grandparent.insertrepair def removeself, label: int RedBlackTree: noqa: PLR0912 It's easier to balance a node with at most one child, so we replace this node with the greatest one less than it and remove that. This node has at most one nonNone child, so we don't need to replace This node is red, and its child is black The only way this happens to a node with one child is if both children are None leaves. We can just remove this node and call it a day. The node is black This node and its child are black The tree is now empty This node is black and its child is red Move the child node here and make it black Repair the coloring of the tree that may have been messed up. if self.parent is None or self.sibling is None or self.parent.sibling is None or self.grandparent is None : return if colorself.sibling 1: self.sibling.color 0 self.parent.color 1 if self.isleft: self.parent.rotateleft else: self.parent.rotateright if colorself.parent 0 and colorself.sibling 0 and colorself.sibling.left 0 and colorself.sibling.right 0 : self.sibling.color 1 self.parent.removerepair return if colorself.parent 1 and colorself.sibling 0 and colorself.sibling.left 0 and colorself.sibling.right 0 : self.sibling.color 1 self.parent.color 0 return if self.isleft and colorself.sibling 0 and colorself.sibling.right 0 and colorself.sibling.left 1 : self.sibling.rotateright self.sibling.color 0 if self.sibling.right: self.sibling.right.color 1 if self.isright and colorself.sibling 0 and colorself.sibling.right 1 and colorself.sibling.left 0 : self.sibling.rotateleft self.sibling.color 0 if self.sibling.left: self.sibling.left.color 1 if self.isleft and colorself.sibling 0 and colorself.sibling.right 1 : self.parent.rotateleft self.grandparent.color self.parent.color self.parent.color 0 self.parent.sibling.color 0 if self.isright and colorself.sibling 0 and colorself.sibling.left 1 : self.parent.rotateright self.grandparent.color self.parent.color self.parent.color 0 self.parent.sibling.color 0 def checkcolorpropertiesself bool: I assume property 1 to hold because there is nothing that can make the color be anything other than 0 or 1. Property 2 if self.color: The root was red printProperty 2 return False Property 3 does not need to be checked, because None is assumed to be black and is all the leaves. Property 4 if not self.checkcoloring: printProperty 4 return False Property 5 if self.blackheight is None: printProperty 5 return False All properties were met return True def checkcoloringself bool: if self.color 1 and 1 in colorself.left, colorself.right: return False if self.left and not self.left.checkcoloring: return False if self.right and not self.right.checkcoloring: return False return True def blackheightself int None: if self is None or self.left is None or self.right is None: If we're already at a leaf, there is no path return 1 left RedBlackTree.blackheightself.left right RedBlackTree.blackheightself.right if left is None or right is None: There are issues with coloring below children nodes return None if left ! right: The two children have unequal depths return None Return the black depth of children, plus one if this node is black return left 1 self.color Here are functions which are general to all binary search trees def containsself, label: int bool: return self.searchlabel is not None def searchself, label: int RedBlackTree None: if self.label label: return self elif self.label is not None and label self.label: if self.right is None: return None else: return self.right.searchlabel else: if self.left is None: return None else: return self.left.searchlabel def floorself, label: int int None: Returns the smallest element in this tree which is at least label. This method is guaranteed to run in Ologn time. Returns the largest element in this tree. This method is guaranteed to run in Ologn time. Go as far right as possible Returns the smallest element in this tree. This method is guaranteed to run in Ologn time. Go as far left as possible Get the current node's grandparent, or None if it doesn't exist. if self.parent is None: return None else: return self.parent.parent property def siblingself RedBlackTree None: Returns true iff this node is the left child of its parent. if self.parent is None: return False return self.parent.left is self.parent.left is self def isrightself bool: Return the number of nodes in this tree. Test if two trees are equal. if not isinstanceother, RedBlackTree: return NotImplemented if self.label other.label: return self.left other.left and self.right other.right else: return False def colornode: RedBlackTree None int: Code for testing the various functions of the redblack tree. Test that the rotateleft and rotateright functions work. Make a tree to test on tree RedBlackTree0 tree.left RedBlackTree10, parenttree tree.right RedBlackTree10, parenttree tree.left.left RedBlackTree20, parenttree.left tree.left.right RedBlackTree5, parenttree.left tree.right.left RedBlackTree5, parenttree.right tree.right.right RedBlackTree20, parenttree.right Make the right rotation leftrot RedBlackTree10 leftrot.left RedBlackTree0, parentleftrot leftrot.left.left RedBlackTree10, parentleftrot.left leftrot.left.right RedBlackTree5, parentleftrot.left leftrot.left.left.left RedBlackTree20, parentleftrot.left.left leftrot.left.left.right RedBlackTree5, parentleftrot.left.left leftrot.right RedBlackTree20, parentleftrot tree tree.rotateleft if tree ! leftrot: return False tree tree.rotateright tree tree.rotateright Make the left rotation rightrot RedBlackTree10 rightrot.left RedBlackTree20, parentrightrot rightrot.right RedBlackTree0, parentrightrot rightrot.right.left RedBlackTree5, parentrightrot.right rightrot.right.right RedBlackTree10, parentrightrot.right rightrot.right.right.left RedBlackTree5, parentrightrot.right.right rightrot.right.right.right RedBlackTree20, parentrightrot.right.right if tree ! rightrot: return False return True def testinsertionspeed bool: tree RedBlackTree1 for i in range300000: tree tree.inserti return True def testinsert bool: tree RedBlackTree0 tree.insert8 tree.insert8 tree.insert4 tree.insert12 tree.insert10 tree.insert11 ans RedBlackTree0, 0 ans.left RedBlackTree8, 0, ans ans.right RedBlackTree8, 1, ans ans.right.left RedBlackTree4, 0, ans.right ans.right.right RedBlackTree11, 0, ans.right ans.right.right.left RedBlackTree10, 1, ans.right.right ans.right.right.right RedBlackTree12, 1, ans.right.right return tree ans def testinsertandsearch bool: Found something not in there Didn't find something in there Test the insert and delete method of the tree, verifying the insertion and removal of elements, and the balancing of the tree. Tests the floor and ceiling functions in the tree. tree RedBlackTree0 tree.insert16 tree.insert16 tree.insert8 tree.insert24 tree.insert20 tree.insert22 tuples 20, None, 16, 10, 16, 0, 8, 8, 8, 50, 24, None for val, floor, ceil in tuples: if tree.floorval ! floor or tree.ceilval ! ceil: return False return True def testminmax bool: Tests the three different tree traversal functions. tree RedBlackTree0 tree tree.insert16 tree.insert16 tree.insert8 tree.insert24 tree.insert20 tree.insert22 if listtree.inordertraverse ! 16, 0, 8, 16, 20, 22, 24: return False if listtree.preordertraverse ! 0, 16, 16, 8, 22, 20, 24: return False if listtree.postordertraverse ! 16, 8, 20, 24, 22, 16, 0: return False return True def testtreechaining bool: pytests","Completions":"from __future__ import annotations\n\nfrom collections.abc import Iterator\n\n\nclass RedBlackTree:\n \"\"\"\n A Red-Black tree, which is a self-balancing BST (binary search\n tree).\n This tree has similar performance to AVL trees, but the balancing is\n less strict, so it will perform faster for writing\/deleting nodes\n and slower for reading in the average case, though, because they're\n both balanced binary search trees, both will get the same asymptotic\n performance.\n To read more about them, https:\/\/en.wikipedia.org\/wiki\/Red\u2013black_tree\n Unless otherwise specified, all asymptotic runtimes are specified in\n terms of the size of the tree.\n \"\"\"\n\n def __init__(\n self,\n label: int | None = None,\n color: int = 0,\n parent: RedBlackTree | None = None,\n left: RedBlackTree | None = None,\n right: RedBlackTree | None = None,\n ) -> None:\n \"\"\"Initialize a new Red-Black Tree node with the given values:\n label: The value associated with this node\n color: 0 if black, 1 if red\n parent: The parent to this node\n left: This node's left child\n right: This node's right child\n \"\"\"\n self.label = label\n self.parent = parent\n self.left = left\n self.right = right\n self.color = color\n\n # Here are functions which are specific to red-black trees\n\n def rotate_left(self) -> RedBlackTree:\n \"\"\"Rotate the subtree rooted at this node to the left and\n returns the new root to this subtree.\n Performing one rotation can be done in O(1).\n \"\"\"\n parent = self.parent\n right = self.right\n if right is None:\n return self\n self.right = right.left\n if self.right:\n self.right.parent = self\n self.parent = right\n right.left = self\n if parent is not None:\n if parent.left == self:\n parent.left = right\n else:\n parent.right = right\n right.parent = parent\n return right\n\n def rotate_right(self) -> RedBlackTree:\n \"\"\"Rotate the subtree rooted at this node to the right and\n returns the new root to this subtree.\n Performing one rotation can be done in O(1).\n \"\"\"\n if self.left is None:\n return self\n parent = self.parent\n left = self.left\n self.left = left.right\n if self.left:\n self.left.parent = self\n self.parent = left\n left.right = self\n if parent is not None:\n if parent.right is self:\n parent.right = left\n else:\n parent.left = left\n left.parent = parent\n return left\n\n def insert(self, label: int) -> RedBlackTree:\n \"\"\"Inserts label into the subtree rooted at self, performs any\n rotations necessary to maintain balance, and then returns the\n new root to this subtree (likely self).\n This is guaranteed to run in O(log(n)) time.\n \"\"\"\n if self.label is None:\n # Only possible with an empty tree\n self.label = label\n return self\n if self.label == label:\n return self\n elif self.label > label:\n if self.left:\n self.left.insert(label)\n else:\n self.left = RedBlackTree(label, 1, self)\n self.left._insert_repair()\n else:\n if self.right:\n self.right.insert(label)\n else:\n self.right = RedBlackTree(label, 1, self)\n self.right._insert_repair()\n return self.parent or self\n\n def _insert_repair(self) -> None:\n \"\"\"Repair the coloring from inserting into a tree.\"\"\"\n if self.parent is None:\n # This node is the root, so it just needs to be black\n self.color = 0\n elif color(self.parent) == 0:\n # If the parent is black, then it just needs to be red\n self.color = 1\n else:\n uncle = self.parent.sibling\n if color(uncle) == 0:\n if self.is_left() and self.parent.is_right():\n self.parent.rotate_right()\n if self.right:\n self.right._insert_repair()\n elif self.is_right() and self.parent.is_left():\n self.parent.rotate_left()\n if self.left:\n self.left._insert_repair()\n elif self.is_left():\n if self.grandparent:\n self.grandparent.rotate_right()\n self.parent.color = 0\n if self.parent.right:\n self.parent.right.color = 1\n else:\n if self.grandparent:\n self.grandparent.rotate_left()\n self.parent.color = 0\n if self.parent.left:\n self.parent.left.color = 1\n else:\n self.parent.color = 0\n if uncle and self.grandparent:\n uncle.color = 0\n self.grandparent.color = 1\n self.grandparent._insert_repair()\n\n def remove(self, label: int) -> RedBlackTree: # noqa: PLR0912\n \"\"\"Remove label from this tree.\"\"\"\n if self.label == label:\n if self.left and self.right:\n # It's easier to balance a node with at most one child,\n # so we replace this node with the greatest one less than\n # it and remove that.\n value = self.left.get_max()\n if value is not None:\n self.label = value\n self.left.remove(value)\n else:\n # This node has at most one non-None child, so we don't\n # need to replace\n child = self.left or self.right\n if self.color == 1:\n # This node is red, and its child is black\n # The only way this happens to a node with one child\n # is if both children are None leaves.\n # We can just remove this node and call it a day.\n if self.parent:\n if self.is_left():\n self.parent.left = None\n else:\n self.parent.right = None\n else:\n # The node is black\n if child is None:\n # This node and its child are black\n if self.parent is None:\n # The tree is now empty\n return RedBlackTree(None)\n else:\n self._remove_repair()\n if self.is_left():\n self.parent.left = None\n else:\n self.parent.right = None\n self.parent = None\n else:\n # This node is black and its child is red\n # Move the child node here and make it black\n self.label = child.label\n self.left = child.left\n self.right = child.right\n if self.left:\n self.left.parent = self\n if self.right:\n self.right.parent = self\n elif self.label is not None and self.label > label:\n if self.left:\n self.left.remove(label)\n else:\n if self.right:\n self.right.remove(label)\n return self.parent or self\n\n def _remove_repair(self) -> None:\n \"\"\"Repair the coloring of the tree that may have been messed up.\"\"\"\n if (\n self.parent is None\n or self.sibling is None\n or self.parent.sibling is None\n or self.grandparent is None\n ):\n return\n if color(self.sibling) == 1:\n self.sibling.color = 0\n self.parent.color = 1\n if self.is_left():\n self.parent.rotate_left()\n else:\n self.parent.rotate_right()\n if (\n color(self.parent) == 0\n and color(self.sibling) == 0\n and color(self.sibling.left) == 0\n and color(self.sibling.right) == 0\n ):\n self.sibling.color = 1\n self.parent._remove_repair()\n return\n if (\n color(self.parent) == 1\n and color(self.sibling) == 0\n and color(self.sibling.left) == 0\n and color(self.sibling.right) == 0\n ):\n self.sibling.color = 1\n self.parent.color = 0\n return\n if (\n self.is_left()\n and color(self.sibling) == 0\n and color(self.sibling.right) == 0\n and color(self.sibling.left) == 1\n ):\n self.sibling.rotate_right()\n self.sibling.color = 0\n if self.sibling.right:\n self.sibling.right.color = 1\n if (\n self.is_right()\n and color(self.sibling) == 0\n and color(self.sibling.right) == 1\n and color(self.sibling.left) == 0\n ):\n self.sibling.rotate_left()\n self.sibling.color = 0\n if self.sibling.left:\n self.sibling.left.color = 1\n if (\n self.is_left()\n and color(self.sibling) == 0\n and color(self.sibling.right) == 1\n ):\n self.parent.rotate_left()\n self.grandparent.color = self.parent.color\n self.parent.color = 0\n self.parent.sibling.color = 0\n if (\n self.is_right()\n and color(self.sibling) == 0\n and color(self.sibling.left) == 1\n ):\n self.parent.rotate_right()\n self.grandparent.color = self.parent.color\n self.parent.color = 0\n self.parent.sibling.color = 0\n\n def check_color_properties(self) -> bool:\n \"\"\"Check the coloring of the tree, and return True iff the tree\n is colored in a way which matches these five properties:\n (wording stolen from wikipedia article)\n 1. Each node is either red or black.\n 2. The root node is black.\n 3. All leaves are black.\n 4. If a node is red, then both its children are black.\n 5. Every path from any node to all of its descendent NIL nodes\n has the same number of black nodes.\n This function runs in O(n) time, because properties 4 and 5 take\n that long to check.\n \"\"\"\n # I assume property 1 to hold because there is nothing that can\n # make the color be anything other than 0 or 1.\n # Property 2\n if self.color:\n # The root was red\n print(\"Property 2\")\n return False\n # Property 3 does not need to be checked, because None is assumed\n # to be black and is all the leaves.\n # Property 4\n if not self.check_coloring():\n print(\"Property 4\")\n return False\n # Property 5\n if self.black_height() is None:\n print(\"Property 5\")\n return False\n # All properties were met\n return True\n\n def check_coloring(self) -> bool:\n \"\"\"A helper function to recursively check Property 4 of a\n Red-Black Tree. See check_color_properties for more info.\n \"\"\"\n if self.color == 1 and 1 in (color(self.left), color(self.right)):\n return False\n if self.left and not self.left.check_coloring():\n return False\n if self.right and not self.right.check_coloring():\n return False\n return True\n\n def black_height(self) -> int | None:\n \"\"\"Returns the number of black nodes from this node to the\n leaves of the tree, or None if there isn't one such value (the\n tree is color incorrectly).\n \"\"\"\n if self is None or self.left is None or self.right is None:\n # If we're already at a leaf, there is no path\n return 1\n left = RedBlackTree.black_height(self.left)\n right = RedBlackTree.black_height(self.right)\n if left is None or right is None:\n # There are issues with coloring below children nodes\n return None\n if left != right:\n # The two children have unequal depths\n return None\n # Return the black depth of children, plus one if this node is\n # black\n return left + (1 - self.color)\n\n # Here are functions which are general to all binary search trees\n\n def __contains__(self, label: int) -> bool:\n \"\"\"Search through the tree for label, returning True iff it is\n found somewhere in the tree.\n Guaranteed to run in O(log(n)) time.\n \"\"\"\n return self.search(label) is not None\n\n def search(self, label: int) -> RedBlackTree | None:\n \"\"\"Search through the tree for label, returning its node if\n it's found, and None otherwise.\n This method is guaranteed to run in O(log(n)) time.\n \"\"\"\n if self.label == label:\n return self\n elif self.label is not None and label > self.label:\n if self.right is None:\n return None\n else:\n return self.right.search(label)\n else:\n if self.left is None:\n return None\n else:\n return self.left.search(label)\n\n def floor(self, label: int) -> int | None:\n \"\"\"Returns the largest element in this tree which is at most label.\n This method is guaranteed to run in O(log(n)) time.\"\"\"\n if self.label == label:\n return self.label\n elif self.label is not None and self.label > label:\n if self.left:\n return self.left.floor(label)\n else:\n return None\n else:\n if self.right:\n attempt = self.right.floor(label)\n if attempt is not None:\n return attempt\n return self.label\n\n def ceil(self, label: int) -> int | None:\n \"\"\"Returns the smallest element in this tree which is at least label.\n This method is guaranteed to run in O(log(n)) time.\n \"\"\"\n if self.label == label:\n return self.label\n elif self.label is not None and self.label < label:\n if self.right:\n return self.right.ceil(label)\n else:\n return None\n else:\n if self.left:\n attempt = self.left.ceil(label)\n if attempt is not None:\n return attempt\n return self.label\n\n def get_max(self) -> int | None:\n \"\"\"Returns the largest element in this tree.\n This method is guaranteed to run in O(log(n)) time.\n \"\"\"\n if self.right:\n # Go as far right as possible\n return self.right.get_max()\n else:\n return self.label\n\n def get_min(self) -> int | None:\n \"\"\"Returns the smallest element in this tree.\n This method is guaranteed to run in O(log(n)) time.\n \"\"\"\n if self.left:\n # Go as far left as possible\n return self.left.get_min()\n else:\n return self.label\n\n @property\n def grandparent(self) -> RedBlackTree | None:\n \"\"\"Get the current node's grandparent, or None if it doesn't exist.\"\"\"\n if self.parent is None:\n return None\n else:\n return self.parent.parent\n\n @property\n def sibling(self) -> RedBlackTree | None:\n \"\"\"Get the current node's sibling, or None if it doesn't exist.\"\"\"\n if self.parent is None:\n return None\n elif self.parent.left is self:\n return self.parent.right\n else:\n return self.parent.left\n\n def is_left(self) -> bool:\n \"\"\"Returns true iff this node is the left child of its parent.\"\"\"\n if self.parent is None:\n return False\n return self.parent.left is self.parent.left is self\n\n def is_right(self) -> bool:\n \"\"\"Returns true iff this node is the right child of its parent.\"\"\"\n if self.parent is None:\n return False\n return self.parent.right is self\n\n def __bool__(self) -> bool:\n return True\n\n def __len__(self) -> int:\n \"\"\"\n Return the number of nodes in this tree.\n \"\"\"\n ln = 1\n if self.left:\n ln += len(self.left)\n if self.right:\n ln += len(self.right)\n return ln\n\n def preorder_traverse(self) -> Iterator[int | None]:\n yield self.label\n if self.left:\n yield from self.left.preorder_traverse()\n if self.right:\n yield from self.right.preorder_traverse()\n\n def inorder_traverse(self) -> Iterator[int | None]:\n if self.left:\n yield from self.left.inorder_traverse()\n yield self.label\n if self.right:\n yield from self.right.inorder_traverse()\n\n def postorder_traverse(self) -> Iterator[int | None]:\n if self.left:\n yield from self.left.postorder_traverse()\n if self.right:\n yield from self.right.postorder_traverse()\n yield self.label\n\n def __repr__(self) -> str:\n from pprint import pformat\n\n if self.left is None and self.right is None:\n return f\"'{self.label} {(self.color and 'red') or 'blk'}'\"\n return pformat(\n {\n f\"{self.label} {(self.color and 'red') or 'blk'}\": (\n self.left,\n self.right,\n )\n },\n indent=1,\n )\n\n def __eq__(self, other: object) -> bool:\n \"\"\"Test if two trees are equal.\"\"\"\n if not isinstance(other, RedBlackTree):\n return NotImplemented\n if self.label == other.label:\n return self.left == other.left and self.right == other.right\n else:\n return False\n\n\ndef color(node: RedBlackTree | None) -> int:\n \"\"\"Returns the color of a node, allowing for None leaves.\"\"\"\n if node is None:\n return 0\n else:\n return node.color\n\n\n\"\"\"\nCode for testing the various\nfunctions of the red-black tree.\n\"\"\"\n\n\ndef test_rotations() -> bool:\n \"\"\"Test that the rotate_left and rotate_right functions work.\"\"\"\n # Make a tree to test on\n tree = RedBlackTree(0)\n tree.left = RedBlackTree(-10, parent=tree)\n tree.right = RedBlackTree(10, parent=tree)\n tree.left.left = RedBlackTree(-20, parent=tree.left)\n tree.left.right = RedBlackTree(-5, parent=tree.left)\n tree.right.left = RedBlackTree(5, parent=tree.right)\n tree.right.right = RedBlackTree(20, parent=tree.right)\n # Make the right rotation\n left_rot = RedBlackTree(10)\n left_rot.left = RedBlackTree(0, parent=left_rot)\n left_rot.left.left = RedBlackTree(-10, parent=left_rot.left)\n left_rot.left.right = RedBlackTree(5, parent=left_rot.left)\n left_rot.left.left.left = RedBlackTree(-20, parent=left_rot.left.left)\n left_rot.left.left.right = RedBlackTree(-5, parent=left_rot.left.left)\n left_rot.right = RedBlackTree(20, parent=left_rot)\n tree = tree.rotate_left()\n if tree != left_rot:\n return False\n tree = tree.rotate_right()\n tree = tree.rotate_right()\n # Make the left rotation\n right_rot = RedBlackTree(-10)\n right_rot.left = RedBlackTree(-20, parent=right_rot)\n right_rot.right = RedBlackTree(0, parent=right_rot)\n right_rot.right.left = RedBlackTree(-5, parent=right_rot.right)\n right_rot.right.right = RedBlackTree(10, parent=right_rot.right)\n right_rot.right.right.left = RedBlackTree(5, parent=right_rot.right.right)\n right_rot.right.right.right = RedBlackTree(20, parent=right_rot.right.right)\n if tree != right_rot:\n return False\n return True\n\n\ndef test_insertion_speed() -> bool:\n \"\"\"Test that the tree balances inserts to O(log(n)) by doing a lot\n of them.\n \"\"\"\n tree = RedBlackTree(-1)\n for i in range(300000):\n tree = tree.insert(i)\n return True\n\n\ndef test_insert() -> bool:\n \"\"\"Test the insert() method of the tree correctly balances, colors,\n and inserts.\n \"\"\"\n tree = RedBlackTree(0)\n tree.insert(8)\n tree.insert(-8)\n tree.insert(4)\n tree.insert(12)\n tree.insert(10)\n tree.insert(11)\n ans = RedBlackTree(0, 0)\n ans.left = RedBlackTree(-8, 0, ans)\n ans.right = RedBlackTree(8, 1, ans)\n ans.right.left = RedBlackTree(4, 0, ans.right)\n ans.right.right = RedBlackTree(11, 0, ans.right)\n ans.right.right.left = RedBlackTree(10, 1, ans.right.right)\n ans.right.right.right = RedBlackTree(12, 1, ans.right.right)\n return tree == ans\n\n\ndef test_insert_and_search() -> bool:\n \"\"\"Tests searching through the tree for values.\"\"\"\n tree = RedBlackTree(0)\n tree.insert(8)\n tree.insert(-8)\n tree.insert(4)\n tree.insert(12)\n tree.insert(10)\n tree.insert(11)\n if 5 in tree or -6 in tree or -10 in tree or 13 in tree:\n # Found something not in there\n return False\n if not (11 in tree and 12 in tree and -8 in tree and 0 in tree):\n # Didn't find something in there\n return False\n return True\n\n\ndef test_insert_delete() -> bool:\n \"\"\"Test the insert() and delete() method of the tree, verifying the\n insertion and removal of elements, and the balancing of the tree.\n \"\"\"\n tree = RedBlackTree(0)\n tree = tree.insert(-12)\n tree = tree.insert(8)\n tree = tree.insert(-8)\n tree = tree.insert(15)\n tree = tree.insert(4)\n tree = tree.insert(12)\n tree = tree.insert(10)\n tree = tree.insert(9)\n tree = tree.insert(11)\n tree = tree.remove(15)\n tree = tree.remove(-12)\n tree = tree.remove(9)\n if not tree.check_color_properties():\n return False\n if list(tree.inorder_traverse()) != [-8, 0, 4, 8, 10, 11, 12]:\n return False\n return True\n\n\ndef test_floor_ceil() -> bool:\n \"\"\"Tests the floor and ceiling functions in the tree.\"\"\"\n tree = RedBlackTree(0)\n tree.insert(-16)\n tree.insert(16)\n tree.insert(8)\n tree.insert(24)\n tree.insert(20)\n tree.insert(22)\n tuples = [(-20, None, -16), (-10, -16, 0), (8, 8, 8), (50, 24, None)]\n for val, floor, ceil in tuples:\n if tree.floor(val) != floor or tree.ceil(val) != ceil:\n return False\n return True\n\n\ndef test_min_max() -> bool:\n \"\"\"Tests the min and max functions in the tree.\"\"\"\n tree = RedBlackTree(0)\n tree.insert(-16)\n tree.insert(16)\n tree.insert(8)\n tree.insert(24)\n tree.insert(20)\n tree.insert(22)\n if tree.get_max() != 22 or tree.get_min() != -16:\n return False\n return True\n\n\ndef test_tree_traversal() -> bool:\n \"\"\"Tests the three different tree traversal functions.\"\"\"\n tree = RedBlackTree(0)\n tree = tree.insert(-16)\n tree.insert(16)\n tree.insert(8)\n tree.insert(24)\n tree.insert(20)\n tree.insert(22)\n if list(tree.inorder_traverse()) != [-16, 0, 8, 16, 20, 22, 24]:\n return False\n if list(tree.preorder_traverse()) != [0, -16, 16, 8, 22, 20, 24]:\n return False\n if list(tree.postorder_traverse()) != [-16, 8, 20, 24, 22, 16, 0]:\n return False\n return True\n\n\ndef test_tree_chaining() -> bool:\n \"\"\"Tests the three different tree chaining functions.\"\"\"\n tree = RedBlackTree(0)\n tree = tree.insert(-16).insert(16).insert(8).insert(24).insert(20).insert(22)\n if list(tree.inorder_traverse()) != [-16, 0, 8, 16, 20, 22, 24]:\n return False\n if list(tree.preorder_traverse()) != [0, -16, 16, 8, 22, 20, 24]:\n return False\n if list(tree.postorder_traverse()) != [-16, 8, 20, 24, 22, 16, 0]:\n return False\n return True\n\n\ndef print_results(msg: str, passes: bool) -> None:\n print(str(msg), \"works!\" if passes else \"doesn't work :(\")\n\n\ndef pytests() -> None:\n assert test_rotations()\n assert test_insert()\n assert test_insert_and_search()\n assert test_insert_delete()\n assert test_floor_ceil()\n assert test_tree_traversal()\n assert test_tree_chaining()\n\n\ndef main() -> None:\n \"\"\"\n >>> pytests()\n \"\"\"\n print_results(\"Rotating right and left\", test_rotations())\n print_results(\"Inserting\", test_insert())\n print_results(\"Searching\", test_insert_and_search())\n print_results(\"Deleting\", test_insert_delete())\n print_results(\"Floor and ceil\", test_floor_ceil())\n print_results(\"Tree traversal\", test_tree_traversal())\n print_results(\"Tree traversal\", test_tree_chaining())\n print(\"Testing tree balancing...\")\n print(\"This should only be a few seconds.\")\n test_insertion_speed()\n print(\"Done!\")\n\n\nif __name__ == \"__main__\":\n main()\n"} +{"Prompt":"Returns the left child index for a given index in a binary tree. s SegmentTree1, 2, 3 s.left1 2 s.left2 4 Returns the right child index for a given index in a binary tree. s SegmentTree1, 2, 3 s.right1 3 s.right2 5 Update the values in the segment tree in the range a,b with the given value. s SegmentTree1, 2, 3, 4, 5 s.update2, 4, 10 True s.query1, 5 10 update1, 1, N, a, b, v for update val v to a,b Query the maximum value in the range a,b. s SegmentTree1, 2, 3, 4, 5 s.query1, 3 3 s.query1, 5 5 query1, 1, N, a, b for query max of a,b","Completions":"import math\n\n\nclass SegmentTree:\n def __init__(self, a):\n self.A = a\n self.N = len(self.A)\n self.st = [0] * (\n 4 * self.N\n ) # approximate the overall size of segment tree with array N\n if self.N:\n self.build(1, 0, self.N - 1)\n\n def left(self, idx):\n \"\"\"\n Returns the left child index for a given index in a binary tree.\n\n >>> s = SegmentTree([1, 2, 3])\n >>> s.left(1)\n 2\n >>> s.left(2)\n 4\n \"\"\"\n return idx * 2\n\n def right(self, idx):\n \"\"\"\n Returns the right child index for a given index in a binary tree.\n\n >>> s = SegmentTree([1, 2, 3])\n >>> s.right(1)\n 3\n >>> s.right(2)\n 5\n \"\"\"\n return idx * 2 + 1\n\n def build(self, idx, l, r): # noqa: E741\n if l == r:\n self.st[idx] = self.A[l]\n else:\n mid = (l + r) \/\/ 2\n self.build(self.left(idx), l, mid)\n self.build(self.right(idx), mid + 1, r)\n self.st[idx] = max(self.st[self.left(idx)], self.st[self.right(idx)])\n\n def update(self, a, b, val):\n \"\"\"\n Update the values in the segment tree in the range [a,b] with the given value.\n\n >>> s = SegmentTree([1, 2, 3, 4, 5])\n >>> s.update(2, 4, 10)\n True\n >>> s.query(1, 5)\n 10\n \"\"\"\n return self.update_recursive(1, 0, self.N - 1, a - 1, b - 1, val)\n\n def update_recursive(self, idx, l, r, a, b, val): # noqa: E741\n \"\"\"\n update(1, 1, N, a, b, v) for update val v to [a,b]\n \"\"\"\n if r < a or l > b:\n return True\n if l == r:\n self.st[idx] = val\n return True\n mid = (l + r) \/\/ 2\n self.update_recursive(self.left(idx), l, mid, a, b, val)\n self.update_recursive(self.right(idx), mid + 1, r, a, b, val)\n self.st[idx] = max(self.st[self.left(idx)], self.st[self.right(idx)])\n return True\n\n def query(self, a, b):\n \"\"\"\n Query the maximum value in the range [a,b].\n\n >>> s = SegmentTree([1, 2, 3, 4, 5])\n >>> s.query(1, 3)\n 3\n >>> s.query(1, 5)\n 5\n \"\"\"\n return self.query_recursive(1, 0, self.N - 1, a - 1, b - 1)\n\n def query_recursive(self, idx, l, r, a, b): # noqa: E741\n \"\"\"\n query(1, 1, N, a, b) for query max of [a,b]\n \"\"\"\n if r < a or l > b:\n return -math.inf\n if l >= a and r <= b:\n return self.st[idx]\n mid = (l + r) \/\/ 2\n q1 = self.query_recursive(self.left(idx), l, mid, a, b)\n q2 = self.query_recursive(self.right(idx), mid + 1, r, a, b)\n return max(q1, q2)\n\n def show_data(self):\n show_list = []\n for i in range(1, N + 1):\n show_list += [self.query(i, i)]\n print(show_list)\n\n\nif __name__ == \"__main__\":\n A = [1, 2, -4, 7, 3, -5, 6, 11, -20, 9, 14, 15, 5, 2, -8]\n N = 15\n segt = SegmentTree(A)\n print(segt.query(4, 6))\n print(segt.query(7, 11))\n print(segt.query(7, 12))\n segt.update(1, 3, 111)\n print(segt.query(1, 15))\n segt.update(7, 8, 235)\n segt.show_data()\n"} +{"Prompt":"Segmenttree creates a segment tree with a given array and function, allowing queries to be done later in logN time function takes 2 values and returns a same type value import operator numarr SegmentTree2, 1, 5, 3, 4, operator.add tuplenumarr.traverse doctest: NORMALIZEWHITESPACE SegmentTreeNodestart0, end4, val15, SegmentTreeNodestart0, end2, val8, SegmentTreeNodestart3, end4, val7, SegmentTreeNodestart0, end1, val3, SegmentTreeNodestart2, end2, val5, SegmentTreeNodestart3, end3, val3, SegmentTreeNodestart4, end4, val4, SegmentTreeNodestart0, end0, val2, SegmentTreeNodestart1, end1, val1 numarr.update1, 5 tuplenumarr.traverse doctest: NORMALIZEWHITESPACE SegmentTreeNodestart0, end4, val19, SegmentTreeNodestart0, end2, val12, SegmentTreeNodestart3, end4, val7, SegmentTreeNodestart0, end1, val7, SegmentTreeNodestart2, end2, val5, SegmentTreeNodestart3, end3, val3, SegmentTreeNodestart4, end4, val4, SegmentTreeNodestart0, end0, val2, SegmentTreeNodestart1, end1, val5 numarr.queryrange3, 4 7 numarr.queryrange2, 2 5 numarr.queryrange1, 3 13 maxarr SegmentTree2, 1, 5, 3, 4, max for node in maxarr.traverse: ... printnode ... SegmentTreeNodestart0, end4, val5 SegmentTreeNodestart0, end2, val5 SegmentTreeNodestart3, end4, val4 SegmentTreeNodestart0, end1, val2 SegmentTreeNodestart2, end2, val5 SegmentTreeNodestart3, end3, val3 SegmentTreeNodestart4, end4, val4 SegmentTreeNodestart0, end0, val2 SegmentTreeNodestart1, end1, val1 maxarr.update1, 5 for node in maxarr.traverse: ... printnode ... SegmentTreeNodestart0, end4, val5 SegmentTreeNodestart0, end2, val5 SegmentTreeNodestart3, end4, val4 SegmentTreeNodestart0, end1, val5 SegmentTreeNodestart2, end2, val5 SegmentTreeNodestart3, end3, val3 SegmentTreeNodestart4, end4, val4 SegmentTreeNodestart0, end0, val2 SegmentTreeNodestart1, end1, val5 maxarr.queryrange3, 4 4 maxarr.queryrange2, 2 5 maxarr.queryrange1, 3 5 minarr SegmentTree2, 1, 5, 3, 4, min for node in minarr.traverse: ... printnode ... SegmentTreeNodestart0, end4, val1 SegmentTreeNodestart0, end2, val1 SegmentTreeNodestart3, end4, val3 SegmentTreeNodestart0, end1, val1 SegmentTreeNodestart2, end2, val5 SegmentTreeNodestart3, end3, val3 SegmentTreeNodestart4, end4, val4 SegmentTreeNodestart0, end0, val2 SegmentTreeNodestart1, end1, val1 minarr.update1, 5 for node in minarr.traverse: ... printnode ... SegmentTreeNodestart0, end4, val2 SegmentTreeNodestart0, end2, val2 SegmentTreeNodestart3, end4, val3 SegmentTreeNodestart0, end1, val2 SegmentTreeNodestart2, end2, val5 SegmentTreeNodestart3, end3, val3 SegmentTreeNodestart4, end4, val4 SegmentTreeNodestart0, end0, val2 SegmentTreeNodestart1, end1, val5 minarr.queryrange3, 4 3 minarr.queryrange2, 2 5 minarr.queryrange1, 3 3 Update an element in logN time :param i: position to be update :param val: new value import operator numarr SegmentTree2, 1, 5, 3, 4, operator.add numarr.update1, 5 numarr.queryrange1, 3 13 Get range query value in logN time :param i: left element index :param j: right element index :return: element combined in the range i, j import operator numarr SegmentTree2, 1, 5, 3, 4, operator.add numarr.update1, 5 numarr.queryrange3, 4 7 numarr.queryrange2, 2 5 numarr.queryrange1, 3 13 range in left child tree range in left child tree and right child tree range in right child tree","Completions":"from collections.abc import Sequence\nfrom queue import Queue\n\n\nclass SegmentTreeNode:\n def __init__(self, start, end, val, left=None, right=None):\n self.start = start\n self.end = end\n self.val = val\n self.mid = (start + end) \/\/ 2\n self.left = left\n self.right = right\n\n def __repr__(self):\n return f\"SegmentTreeNode(start={self.start}, end={self.end}, val={self.val})\"\n\n\nclass SegmentTree:\n \"\"\"\n >>> import operator\n >>> num_arr = SegmentTree([2, 1, 5, 3, 4], operator.add)\n >>> tuple(num_arr.traverse()) # doctest: +NORMALIZE_WHITESPACE\n (SegmentTreeNode(start=0, end=4, val=15),\n SegmentTreeNode(start=0, end=2, val=8),\n SegmentTreeNode(start=3, end=4, val=7),\n SegmentTreeNode(start=0, end=1, val=3),\n SegmentTreeNode(start=2, end=2, val=5),\n SegmentTreeNode(start=3, end=3, val=3),\n SegmentTreeNode(start=4, end=4, val=4),\n SegmentTreeNode(start=0, end=0, val=2),\n SegmentTreeNode(start=1, end=1, val=1))\n >>>\n >>> num_arr.update(1, 5)\n >>> tuple(num_arr.traverse()) # doctest: +NORMALIZE_WHITESPACE\n (SegmentTreeNode(start=0, end=4, val=19),\n SegmentTreeNode(start=0, end=2, val=12),\n SegmentTreeNode(start=3, end=4, val=7),\n SegmentTreeNode(start=0, end=1, val=7),\n SegmentTreeNode(start=2, end=2, val=5),\n SegmentTreeNode(start=3, end=3, val=3),\n SegmentTreeNode(start=4, end=4, val=4),\n SegmentTreeNode(start=0, end=0, val=2),\n SegmentTreeNode(start=1, end=1, val=5))\n >>>\n >>> num_arr.query_range(3, 4)\n 7\n >>> num_arr.query_range(2, 2)\n 5\n >>> num_arr.query_range(1, 3)\n 13\n >>>\n >>> max_arr = SegmentTree([2, 1, 5, 3, 4], max)\n >>> for node in max_arr.traverse():\n ... print(node)\n ...\n SegmentTreeNode(start=0, end=4, val=5)\n SegmentTreeNode(start=0, end=2, val=5)\n SegmentTreeNode(start=3, end=4, val=4)\n SegmentTreeNode(start=0, end=1, val=2)\n SegmentTreeNode(start=2, end=2, val=5)\n SegmentTreeNode(start=3, end=3, val=3)\n SegmentTreeNode(start=4, end=4, val=4)\n SegmentTreeNode(start=0, end=0, val=2)\n SegmentTreeNode(start=1, end=1, val=1)\n >>>\n >>> max_arr.update(1, 5)\n >>> for node in max_arr.traverse():\n ... print(node)\n ...\n SegmentTreeNode(start=0, end=4, val=5)\n SegmentTreeNode(start=0, end=2, val=5)\n SegmentTreeNode(start=3, end=4, val=4)\n SegmentTreeNode(start=0, end=1, val=5)\n SegmentTreeNode(start=2, end=2, val=5)\n SegmentTreeNode(start=3, end=3, val=3)\n SegmentTreeNode(start=4, end=4, val=4)\n SegmentTreeNode(start=0, end=0, val=2)\n SegmentTreeNode(start=1, end=1, val=5)\n >>>\n >>> max_arr.query_range(3, 4)\n 4\n >>> max_arr.query_range(2, 2)\n 5\n >>> max_arr.query_range(1, 3)\n 5\n >>>\n >>> min_arr = SegmentTree([2, 1, 5, 3, 4], min)\n >>> for node in min_arr.traverse():\n ... print(node)\n ...\n SegmentTreeNode(start=0, end=4, val=1)\n SegmentTreeNode(start=0, end=2, val=1)\n SegmentTreeNode(start=3, end=4, val=3)\n SegmentTreeNode(start=0, end=1, val=1)\n SegmentTreeNode(start=2, end=2, val=5)\n SegmentTreeNode(start=3, end=3, val=3)\n SegmentTreeNode(start=4, end=4, val=4)\n SegmentTreeNode(start=0, end=0, val=2)\n SegmentTreeNode(start=1, end=1, val=1)\n >>>\n >>> min_arr.update(1, 5)\n >>> for node in min_arr.traverse():\n ... print(node)\n ...\n SegmentTreeNode(start=0, end=4, val=2)\n SegmentTreeNode(start=0, end=2, val=2)\n SegmentTreeNode(start=3, end=4, val=3)\n SegmentTreeNode(start=0, end=1, val=2)\n SegmentTreeNode(start=2, end=2, val=5)\n SegmentTreeNode(start=3, end=3, val=3)\n SegmentTreeNode(start=4, end=4, val=4)\n SegmentTreeNode(start=0, end=0, val=2)\n SegmentTreeNode(start=1, end=1, val=5)\n >>>\n >>> min_arr.query_range(3, 4)\n 3\n >>> min_arr.query_range(2, 2)\n 5\n >>> min_arr.query_range(1, 3)\n 3\n >>>\n \"\"\"\n\n def __init__(self, collection: Sequence, function):\n self.collection = collection\n self.fn = function\n if self.collection:\n self.root = self._build_tree(0, len(collection) - 1)\n\n def update(self, i, val):\n \"\"\"\n Update an element in log(N) time\n :param i: position to be update\n :param val: new value\n >>> import operator\n >>> num_arr = SegmentTree([2, 1, 5, 3, 4], operator.add)\n >>> num_arr.update(1, 5)\n >>> num_arr.query_range(1, 3)\n 13\n \"\"\"\n self._update_tree(self.root, i, val)\n\n def query_range(self, i, j):\n \"\"\"\n Get range query value in log(N) time\n :param i: left element index\n :param j: right element index\n :return: element combined in the range [i, j]\n >>> import operator\n >>> num_arr = SegmentTree([2, 1, 5, 3, 4], operator.add)\n >>> num_arr.update(1, 5)\n >>> num_arr.query_range(3, 4)\n 7\n >>> num_arr.query_range(2, 2)\n 5\n >>> num_arr.query_range(1, 3)\n 13\n >>>\n \"\"\"\n return self._query_range(self.root, i, j)\n\n def _build_tree(self, start, end):\n if start == end:\n return SegmentTreeNode(start, end, self.collection[start])\n mid = (start + end) \/\/ 2\n left = self._build_tree(start, mid)\n right = self._build_tree(mid + 1, end)\n return SegmentTreeNode(start, end, self.fn(left.val, right.val), left, right)\n\n def _update_tree(self, node, i, val):\n if node.start == i and node.end == i:\n node.val = val\n return\n if i <= node.mid:\n self._update_tree(node.left, i, val)\n else:\n self._update_tree(node.right, i, val)\n node.val = self.fn(node.left.val, node.right.val)\n\n def _query_range(self, node, i, j):\n if node.start == i and node.end == j:\n return node.val\n\n if i <= node.mid:\n if j <= node.mid:\n # range in left child tree\n return self._query_range(node.left, i, j)\n else:\n # range in left child tree and right child tree\n return self.fn(\n self._query_range(node.left, i, node.mid),\n self._query_range(node.right, node.mid + 1, j),\n )\n else:\n # range in right child tree\n return self._query_range(node.right, i, j)\n\n def traverse(self):\n if self.root is not None:\n queue = Queue()\n queue.put(self.root)\n while not queue.empty():\n node = queue.get()\n yield node\n\n if node.left is not None:\n queue.put(node.left)\n\n if node.right is not None:\n queue.put(node.right)\n\n\nif __name__ == \"__main__\":\n import operator\n\n for fn in [operator.add, max, min]:\n print(\"*\" * 50)\n arr = SegmentTree([2, 1, 5, 3, 4], fn)\n for node in arr.traverse():\n print(node)\n print()\n\n arr.update(1, 5)\n for node in arr.traverse():\n print(node)\n print()\n\n print(arr.query_range(3, 4)) # 7\n print(arr.query_range(2, 2)) # 5\n print(arr.query_range(1, 3)) # 13\n print()\n"} +{"Prompt":"A binary tree node has a value, left child, and right child. Props: value: The value of the node. left: The left child of the node. right: The right child of the node. Iterate through the tree in preorder. Returns: An iterator of the tree nodes. listTreeNode1 1,null,null tupleTreeNode1, TreeNode2, TreeNode3 1,2,null,null,3,null,null, 2,null,null, 3,null,null Count the number of nodes in the tree. Returns: The number of nodes in the tree. lenTreeNode1 1 lenTreeNode1, TreeNode2, TreeNode3 3 Represent the tree as a string. Returns: A string representation of the tree. reprTreeNode1 '1,null,null' reprTreeNode1, TreeNode2, TreeNode3 '1,2,null,null,3,null,null' reprTreeNode1, TreeNode2, TreeNode3, TreeNode4, TreeNode5 '1,2,null,null,3,4,null,null,5,null,null' reprTreeNode.fivetree '1,2,null,null,3,4,null,null,5,null,null' Deserialize a string to a binary tree. Args: datastr: The serialized string. Returns: The root of the binary tree. root TreeNode.fivetree serialzeddata reprroot deserialized deserializeserialzeddata root deserialized True root is deserialized two separate trees False root.right.right.value 6 root deserialized False serialzeddata reprroot deserialized deserializeserialzeddata root deserialized True deserialize Traceback most recent call last: ... ValueError: Data cannot be empty. Split the serialized string by a comma to get node values Get the next value from the list","Completions":"from __future__ import annotations\n\nfrom collections.abc import Iterator\nfrom dataclasses import dataclass\n\n\n@dataclass\nclass TreeNode:\n \"\"\"\n A binary tree node has a value, left child, and right child.\n\n Props:\n value: The value of the node.\n left: The left child of the node.\n right: The right child of the node.\n \"\"\"\n\n value: int = 0\n left: TreeNode | None = None\n right: TreeNode | None = None\n\n def __post_init__(self):\n if not isinstance(self.value, int):\n raise TypeError(\"Value must be an integer.\")\n\n def __iter__(self) -> Iterator[TreeNode]:\n \"\"\"\n Iterate through the tree in preorder.\n\n Returns:\n An iterator of the tree nodes.\n\n >>> list(TreeNode(1))\n [1,null,null]\n >>> tuple(TreeNode(1, TreeNode(2), TreeNode(3)))\n (1,2,null,null,3,null,null, 2,null,null, 3,null,null)\n \"\"\"\n yield self\n yield from self.left or ()\n yield from self.right or ()\n\n def __len__(self) -> int:\n \"\"\"\n Count the number of nodes in the tree.\n\n Returns:\n The number of nodes in the tree.\n\n >>> len(TreeNode(1))\n 1\n >>> len(TreeNode(1, TreeNode(2), TreeNode(3)))\n 3\n \"\"\"\n return sum(1 for _ in self)\n\n def __repr__(self) -> str:\n \"\"\"\n Represent the tree as a string.\n\n Returns:\n A string representation of the tree.\n\n >>> repr(TreeNode(1))\n '1,null,null'\n >>> repr(TreeNode(1, TreeNode(2), TreeNode(3)))\n '1,2,null,null,3,null,null'\n >>> repr(TreeNode(1, TreeNode(2), TreeNode(3, TreeNode(4), TreeNode(5))))\n '1,2,null,null,3,4,null,null,5,null,null'\n \"\"\"\n return f\"{self.value},{self.left!r},{self.right!r}\".replace(\"None\", \"null\")\n\n @classmethod\n def five_tree(cls) -> TreeNode:\n \"\"\"\n >>> repr(TreeNode.five_tree())\n '1,2,null,null,3,4,null,null,5,null,null'\n \"\"\"\n root = TreeNode(1)\n root.left = TreeNode(2)\n root.right = TreeNode(3)\n root.right.left = TreeNode(4)\n root.right.right = TreeNode(5)\n return root\n\n\ndef deserialize(data: str) -> TreeNode | None:\n \"\"\"\n Deserialize a string to a binary tree.\n\n Args:\n data(str): The serialized string.\n\n Returns:\n The root of the binary tree.\n\n >>> root = TreeNode.five_tree()\n >>> serialzed_data = repr(root)\n >>> deserialized = deserialize(serialzed_data)\n >>> root == deserialized\n True\n >>> root is deserialized # two separate trees\n False\n >>> root.right.right.value = 6\n >>> root == deserialized\n False\n >>> serialzed_data = repr(root)\n >>> deserialized = deserialize(serialzed_data)\n >>> root == deserialized\n True\n >>> deserialize(\"\")\n Traceback (most recent call last):\n ...\n ValueError: Data cannot be empty.\n \"\"\"\n\n if not data:\n raise ValueError(\"Data cannot be empty.\")\n\n # Split the serialized string by a comma to get node values\n nodes = data.split(\",\")\n\n def build_tree() -> TreeNode | None:\n # Get the next value from the list\n value = nodes.pop(0)\n\n if value == \"null\":\n return None\n\n node = TreeNode(int(value))\n node.left = build_tree() # Recursively build left subtree\n node.right = build_tree() # Recursively build right subtree\n return node\n\n return build_tree()\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Given the root of a binary tree, check whether it is a mirror of itself i.e., symmetric around its center. Leetcode reference: https:leetcode.comproblemssymmetrictree A Node has data variable and pointers to Nodes to its left and right. root Node1 root.left Node2 root.right Node2 root.left.left Node3 root.left.right Node4 root.right.left Node4 root.right.right Node3 return root def makeasymmetrictree Node: r Create a asymmetric tree for testing. The tree looks like this: 1 2 2 3 4 3 4 Test cases for issymmetrictree function issymmetrictreemakesymmetrictree True issymmetrictreemakeasymmetrictree False tree1 makesymmetrictree tree1.right.right Node3 ismirrortree1.left, tree1.right True tree2 makeasymmetrictree ismirrortree2.left, tree2.right False Both sides are empty, which is symmetric. One side is empty while the other is not, which is not symmetric. The values match, so check the subtree","Completions":"from __future__ import annotations\n\nfrom dataclasses import dataclass\n\n\n@dataclass\nclass Node:\n \"\"\"\n A Node has data variable and pointers to Nodes to its left and right.\n \"\"\"\n\n data: int\n left: Node | None = None\n right: Node | None = None\n\n\ndef make_symmetric_tree() -> Node:\n r\"\"\"\n Create a symmetric tree for testing.\n The tree looks like this:\n 1\n \/ \\\n 2 2\n \/ \\ \/ \\\n 3 4 4 3\n \"\"\"\n root = Node(1)\n root.left = Node(2)\n root.right = Node(2)\n root.left.left = Node(3)\n root.left.right = Node(4)\n root.right.left = Node(4)\n root.right.right = Node(3)\n return root\n\n\ndef make_asymmetric_tree() -> Node:\n r\"\"\"\n Create a asymmetric tree for testing.\n The tree looks like this:\n 1\n \/ \\\n 2 2\n \/ \\ \/ \\\n 3 4 3 4\n \"\"\"\n root = Node(1)\n root.left = Node(2)\n root.right = Node(2)\n root.left.left = Node(3)\n root.left.right = Node(4)\n root.right.left = Node(3)\n root.right.right = Node(4)\n return root\n\n\ndef is_symmetric_tree(tree: Node) -> bool:\n \"\"\"\n Test cases for is_symmetric_tree function\n >>> is_symmetric_tree(make_symmetric_tree())\n True\n >>> is_symmetric_tree(make_asymmetric_tree())\n False\n \"\"\"\n if tree:\n return is_mirror(tree.left, tree.right)\n return True # An empty tree is considered symmetric.\n\n\ndef is_mirror(left: Node | None, right: Node | None) -> bool:\n \"\"\"\n >>> tree1 = make_symmetric_tree()\n >>> tree1.right.right = Node(3)\n >>> is_mirror(tree1.left, tree1.right)\n True\n >>> tree2 = make_asymmetric_tree()\n >>> is_mirror(tree2.left, tree2.right)\n False\n \"\"\"\n if left is None and right is None:\n # Both sides are empty, which is symmetric.\n return True\n if left is None or right is None:\n # One side is empty while the other is not, which is not symmetric.\n return False\n if left.data == right.data:\n # The values match, so check the subtree\n return is_mirror(left.left, right.right) and is_mirror(left.right, right.left)\n return False\n\n\nif __name__ == \"__main__\":\n from doctest import testmod\n\n testmod()\n"} +{"Prompt":"Treap's node Treap is a binary tree by value and heap by priority We split current tree into 2 trees with value: Left tree contains all values less than split value. Right tree contains all values greater or equal, than split value Right tree's root will be current node. Now we splitwith the same value current node's left son Left tree: left part of that split Right tree's left son: right part of that split Just symmetric to previous case We merge 2 trees into one. Note: all left tree's values must be less than all right tree's Left will be root because it has more priority Now we need to merge left's right son and right tree Symmetric as well Insert element Split current tree with a value into left, right, Insert new node into the middle Merge left, node, right into root Erase element Split all nodes with values less into left, Split all nodes with values greater into right. Merge left, right Just recursive print of a tree Commands: value to add value into treap value to erase all nodes with value root interacttreapNone, 1 inorderroot 1, root interacttreaproot, 3 5 17 19 2 16 4 0 inorderroot 0,1,2,3,4,5,16,17,19, root interacttreaproot, 4 4 4 inorderroot 0,1,2,3,4,4,4,4,5,16,17,19, root interacttreaproot, 0 inorderroot 1,2,3,4,4,4,4,5,16,17,19, root interacttreaproot, 4 inorderroot 1,2,3,5,16,17,19, root interacttreaproot, 0 Unknown command After each command, program prints treap root None print enter numbers to create a tree, value to add value into treap, value to erase all nodes with value. 'q' to quit. args input while args ! q: root interacttreaproot, args printroot args input printgood by! if name main: import doctest doctest.testmod main","Completions":"from __future__ import annotations\n\nfrom random import random\n\n\nclass Node:\n \"\"\"\n Treap's node\n Treap is a binary tree by value and heap by priority\n \"\"\"\n\n def __init__(self, value: int | None = None):\n self.value = value\n self.prior = random()\n self.left: Node | None = None\n self.right: Node | None = None\n\n def __repr__(self) -> str:\n from pprint import pformat\n\n if self.left is None and self.right is None:\n return f\"'{self.value}: {self.prior:.5}'\"\n else:\n return pformat(\n {f\"{self.value}: {self.prior:.5}\": (self.left, self.right)}, indent=1\n )\n\n def __str__(self) -> str:\n value = str(self.value) + \" \"\n left = str(self.left or \"\")\n right = str(self.right or \"\")\n return value + left + right\n\n\ndef split(root: Node | None, value: int) -> tuple[Node | None, Node | None]:\n \"\"\"\n We split current tree into 2 trees with value:\n\n Left tree contains all values less than split value.\n Right tree contains all values greater or equal, than split value\n \"\"\"\n if root is None: # None tree is split into 2 Nones\n return None, None\n elif root.value is None:\n return None, None\n else:\n if value < root.value:\n \"\"\"\n Right tree's root will be current node.\n Now we split(with the same value) current node's left son\n Left tree: left part of that split\n Right tree's left son: right part of that split\n \"\"\"\n left, root.left = split(root.left, value)\n return left, root\n else:\n \"\"\"\n Just symmetric to previous case\n \"\"\"\n root.right, right = split(root.right, value)\n return root, right\n\n\ndef merge(left: Node | None, right: Node | None) -> Node | None:\n \"\"\"\n We merge 2 trees into one.\n Note: all left tree's values must be less than all right tree's\n \"\"\"\n if (not left) or (not right): # If one node is None, return the other\n return left or right\n elif left.prior < right.prior:\n \"\"\"\n Left will be root because it has more priority\n Now we need to merge left's right son and right tree\n \"\"\"\n left.right = merge(left.right, right)\n return left\n else:\n \"\"\"\n Symmetric as well\n \"\"\"\n right.left = merge(left, right.left)\n return right\n\n\ndef insert(root: Node | None, value: int) -> Node | None:\n \"\"\"\n Insert element\n\n Split current tree with a value into left, right,\n Insert new node into the middle\n Merge left, node, right into root\n \"\"\"\n node = Node(value)\n left, right = split(root, value)\n return merge(merge(left, node), right)\n\n\ndef erase(root: Node | None, value: int) -> Node | None:\n \"\"\"\n Erase element\n\n Split all nodes with values less into left,\n Split all nodes with values greater into right.\n Merge left, right\n \"\"\"\n left, right = split(root, value - 1)\n _, right = split(right, value)\n return merge(left, right)\n\n\ndef inorder(root: Node | None) -> None:\n \"\"\"\n Just recursive print of a tree\n \"\"\"\n if not root: # None\n return\n else:\n inorder(root.left)\n print(root.value, end=\",\")\n inorder(root.right)\n\n\ndef interact_treap(root: Node | None, args: str) -> Node | None:\n \"\"\"\n Commands:\n + value to add value into treap\n - value to erase all nodes with value\n\n >>> root = interact_treap(None, \"+1\")\n >>> inorder(root)\n 1,\n >>> root = interact_treap(root, \"+3 +5 +17 +19 +2 +16 +4 +0\")\n >>> inorder(root)\n 0,1,2,3,4,5,16,17,19,\n >>> root = interact_treap(root, \"+4 +4 +4\")\n >>> inorder(root)\n 0,1,2,3,4,4,4,4,5,16,17,19,\n >>> root = interact_treap(root, \"-0\")\n >>> inorder(root)\n 1,2,3,4,4,4,4,5,16,17,19,\n >>> root = interact_treap(root, \"-4\")\n >>> inorder(root)\n 1,2,3,5,16,17,19,\n >>> root = interact_treap(root, \"=0\")\n Unknown command\n \"\"\"\n for arg in args.split():\n if arg[0] == \"+\":\n root = insert(root, int(arg[1:]))\n\n elif arg[0] == \"-\":\n root = erase(root, int(arg[1:]))\n\n else:\n print(\"Unknown command\")\n\n return root\n\n\ndef main() -> None:\n \"\"\"After each command, program prints treap\"\"\"\n root = None\n print(\n \"enter numbers to create a tree, + value to add value into treap, \"\n \"- value to erase all nodes with value. 'q' to quit. \"\n )\n\n args = input()\n while args != \"q\":\n root = interact_treap(root, args)\n print(root)\n args = input()\n\n print(\"good by!\")\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n main()\n"} +{"Prompt":"Wavelet tree is a datastructure designed to efficiently answer various range queries for arrays. Wavelets trees are different from other binary trees in the sense that the nodes are split based on the actual values of the elements and not on indices, such as the with segment trees or fenwick trees. You can read more about them here: 1. https:users.dcc.uchile.cljperezpapersioiconf16.pdf 2. https:www.youtube.comwatch?v4aSv9PcecDwt811s 3. https:www.youtube.comwatch?vCybAgVFMMct1178s node Nodelength27 reprnode 'Nodeminvalue1 maxvalue1' reprnode strnode True Builds the tree for arr and returns the root of the constructed tree buildtreetestarray Nodeminvalue0 maxvalue9 Leaf node case where the node contains only one unique value Take the mean of min and max element of arr as the pivot and partition arr into leftarr and rightarr with all elements pivot in the leftarr and the rest in rightarr, maintaining the order of the elements, then recursively build trees for leftarr and rightarr Returns the number of occurrences of num in interval 0, index in the list root buildtreetestarray ranktillindexroot, 6, 6 1 ranktillindexroot, 2, 0 1 ranktillindexroot, 1, 10 2 ranktillindexroot, 17, 7 0 ranktillindexroot, 0, 9 1 Leaf node cases go the left subtree and map index to the left subtree go to the right subtree and map index to the right subtree Returns the number of occurrences of num in interval start, end in the list root buildtreetestarray rankroot, 6, 3, 13 2 rankroot, 2, 0, 19 4 rankroot, 9, 2 ,2 0 rankroot, 0, 5, 10 2 Returns the index'th smallest element in interval start, end in the list index is 0indexed root buildtreetestarray quantileroot, 2, 2, 5 5 quantileroot, 5, 2, 13 4 quantileroot, 0, 6, 6 8 quantileroot, 4, 2, 5 1 Leaf node case Number of elements in the left subtree in interval start, end Returns the number of elements in range startnum, endnum in interval start, end in the list root buildtreetestarray rangecountingroot, 1, 10, 3, 7 3 rangecountingroot, 2, 2, 1, 4 1 rangecountingroot, 0, 19, 0, 100 20 rangecountingroot, 1, 0, 1, 100 0 rangecountingroot, 0, 17, 100, 1 0","Completions":"from __future__ import annotations\n\ntest_array = [2, 1, 4, 5, 6, 0, 8, 9, 1, 2, 0, 6, 4, 2, 0, 6, 5, 3, 2, 7]\n\n\nclass Node:\n def __init__(self, length: int) -> None:\n self.minn: int = -1\n self.maxx: int = -1\n self.map_left: list[int] = [-1] * length\n self.left: Node | None = None\n self.right: Node | None = None\n\n def __repr__(self) -> str:\n \"\"\"\n >>> node = Node(length=27)\n >>> repr(node)\n 'Node(min_value=-1 max_value=-1)'\n >>> repr(node) == str(node)\n True\n \"\"\"\n return f\"Node(min_value={self.minn} max_value={self.maxx})\"\n\n\ndef build_tree(arr: list[int]) -> Node | None:\n \"\"\"\n Builds the tree for arr and returns the root\n of the constructed tree\n\n >>> build_tree(test_array)\n Node(min_value=0 max_value=9)\n \"\"\"\n root = Node(len(arr))\n root.minn, root.maxx = min(arr), max(arr)\n # Leaf node case where the node contains only one unique value\n if root.minn == root.maxx:\n return root\n \"\"\"\n Take the mean of min and max element of arr as the pivot and\n partition arr into left_arr and right_arr with all elements <= pivot in the\n left_arr and the rest in right_arr, maintaining the order of the elements,\n then recursively build trees for left_arr and right_arr\n \"\"\"\n pivot = (root.minn + root.maxx) \/\/ 2\n\n left_arr: list[int] = []\n right_arr: list[int] = []\n\n for index, num in enumerate(arr):\n if num <= pivot:\n left_arr.append(num)\n else:\n right_arr.append(num)\n root.map_left[index] = len(left_arr)\n root.left = build_tree(left_arr)\n root.right = build_tree(right_arr)\n return root\n\n\ndef rank_till_index(node: Node | None, num: int, index: int) -> int:\n \"\"\"\n Returns the number of occurrences of num in interval [0, index] in the list\n\n >>> root = build_tree(test_array)\n >>> rank_till_index(root, 6, 6)\n 1\n >>> rank_till_index(root, 2, 0)\n 1\n >>> rank_till_index(root, 1, 10)\n 2\n >>> rank_till_index(root, 17, 7)\n 0\n >>> rank_till_index(root, 0, 9)\n 1\n \"\"\"\n if index < 0 or node is None:\n return 0\n # Leaf node cases\n if node.minn == node.maxx:\n return index + 1 if node.minn == num else 0\n pivot = (node.minn + node.maxx) \/\/ 2\n if num <= pivot:\n # go the left subtree and map index to the left subtree\n return rank_till_index(node.left, num, node.map_left[index] - 1)\n else:\n # go to the right subtree and map index to the right subtree\n return rank_till_index(node.right, num, index - node.map_left[index])\n\n\ndef rank(node: Node | None, num: int, start: int, end: int) -> int:\n \"\"\"\n Returns the number of occurrences of num in interval [start, end] in the list\n\n >>> root = build_tree(test_array)\n >>> rank(root, 6, 3, 13)\n 2\n >>> rank(root, 2, 0, 19)\n 4\n >>> rank(root, 9, 2 ,2)\n 0\n >>> rank(root, 0, 5, 10)\n 2\n \"\"\"\n if start > end:\n return 0\n rank_till_end = rank_till_index(node, num, end)\n rank_before_start = rank_till_index(node, num, start - 1)\n return rank_till_end - rank_before_start\n\n\ndef quantile(node: Node | None, index: int, start: int, end: int) -> int:\n \"\"\"\n Returns the index'th smallest element in interval [start, end] in the list\n index is 0-indexed\n\n >>> root = build_tree(test_array)\n >>> quantile(root, 2, 2, 5)\n 5\n >>> quantile(root, 5, 2, 13)\n 4\n >>> quantile(root, 0, 6, 6)\n 8\n >>> quantile(root, 4, 2, 5)\n -1\n \"\"\"\n if index > (end - start) or start > end or node is None:\n return -1\n # Leaf node case\n if node.minn == node.maxx:\n return node.minn\n # Number of elements in the left subtree in interval [start, end]\n num_elements_in_left_tree = node.map_left[end] - (\n node.map_left[start - 1] if start else 0\n )\n if num_elements_in_left_tree > index:\n return quantile(\n node.left,\n index,\n (node.map_left[start - 1] if start else 0),\n node.map_left[end] - 1,\n )\n else:\n return quantile(\n node.right,\n index - num_elements_in_left_tree,\n start - (node.map_left[start - 1] if start else 0),\n end - node.map_left[end],\n )\n\n\ndef range_counting(\n node: Node | None, start: int, end: int, start_num: int, end_num: int\n) -> int:\n \"\"\"\n Returns the number of elements in range [start_num, end_num]\n in interval [start, end] in the list\n\n >>> root = build_tree(test_array)\n >>> range_counting(root, 1, 10, 3, 7)\n 3\n >>> range_counting(root, 2, 2, 1, 4)\n 1\n >>> range_counting(root, 0, 19, 0, 100)\n 20\n >>> range_counting(root, 1, 0, 1, 100)\n 0\n >>> range_counting(root, 0, 17, 100, 1)\n 0\n \"\"\"\n if (\n start > end\n or node is None\n or start_num > end_num\n or node.minn > end_num\n or node.maxx < start_num\n ):\n return 0\n if start_num <= node.minn and node.maxx <= end_num:\n return end - start + 1\n left = range_counting(\n node.left,\n (node.map_left[start - 1] if start else 0),\n node.map_left[end] - 1,\n start_num,\n end_num,\n )\n right = range_counting(\n node.right,\n start - (node.map_left[start - 1] if start else 0),\n end - node.map_left[end],\n start_num,\n end_num,\n )\n return left + right\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Implements a disjoint set using Lists and some added heuristics for efficiency Union by Rank Heuristic and Path Compression Initialize with a list of the number of items in each set and with rank 1 for each set Merge two sets together using Union by rank heuristic Return True if successful Merge two disjoint sets A DisjointSet1, 1, 1 A.merge1, 2 True A.merge0, 2 True A.merge0, 1 False Find the Parent of a given set A DisjointSet1, 1, 1 A.merge1, 2 True A.getparent0 0 A.getparent1 2","Completions":"class DisjointSet:\n def __init__(self, set_counts: list) -> None:\n \"\"\"\n Initialize with a list of the number of items in each set\n and with rank = 1 for each set\n \"\"\"\n self.set_counts = set_counts\n self.max_set = max(set_counts)\n num_sets = len(set_counts)\n self.ranks = [1] * num_sets\n self.parents = list(range(num_sets))\n\n def merge(self, src: int, dst: int) -> bool:\n \"\"\"\n Merge two sets together using Union by rank heuristic\n Return True if successful\n Merge two disjoint sets\n >>> A = DisjointSet([1, 1, 1])\n >>> A.merge(1, 2)\n True\n >>> A.merge(0, 2)\n True\n >>> A.merge(0, 1)\n False\n \"\"\"\n src_parent = self.get_parent(src)\n dst_parent = self.get_parent(dst)\n\n if src_parent == dst_parent:\n return False\n\n if self.ranks[dst_parent] >= self.ranks[src_parent]:\n self.set_counts[dst_parent] += self.set_counts[src_parent]\n self.set_counts[src_parent] = 0\n self.parents[src_parent] = dst_parent\n if self.ranks[dst_parent] == self.ranks[src_parent]:\n self.ranks[dst_parent] += 1\n joined_set_size = self.set_counts[dst_parent]\n else:\n self.set_counts[src_parent] += self.set_counts[dst_parent]\n self.set_counts[dst_parent] = 0\n self.parents[dst_parent] = src_parent\n joined_set_size = self.set_counts[src_parent]\n\n self.max_set = max(self.max_set, joined_set_size)\n return True\n\n def get_parent(self, disj_set: int) -> int:\n \"\"\"\n Find the Parent of a given set\n >>> A = DisjointSet([1, 1, 1])\n >>> A.merge(1, 2)\n True\n >>> A.get_parent(0)\n 0\n >>> A.get_parent(1)\n 2\n \"\"\"\n if self.parents[disj_set] == disj_set:\n return disj_set\n self.parents[disj_set] = self.get_parent(self.parents[disj_set])\n return self.parents[disj_set]\n"} +{"Prompt":"Disjoint set. Reference: https:en.wikipedia.orgwikiDisjointsetdatastructure Make x as a set. rank is the distance from x to its' parent root's rank is 0 Union of two sets. set with bigger rank should be parent, so that the disjoint set tree will be more flat. Return the parent of x Return a Python Standard Library set that contains i. testdisjointset","Completions":"class Node:\n def __init__(self, data: int) -> None:\n self.data = data\n self.rank: int\n self.parent: Node\n\n\ndef make_set(x: Node) -> None:\n \"\"\"\n Make x as a set.\n \"\"\"\n # rank is the distance from x to its' parent\n # root's rank is 0\n x.rank = 0\n x.parent = x\n\n\ndef union_set(x: Node, y: Node) -> None:\n \"\"\"\n Union of two sets.\n set with bigger rank should be parent, so that the\n disjoint set tree will be more flat.\n \"\"\"\n x, y = find_set(x), find_set(y)\n if x == y:\n return\n\n elif x.rank > y.rank:\n y.parent = x\n else:\n x.parent = y\n if x.rank == y.rank:\n y.rank += 1\n\n\ndef find_set(x: Node) -> Node:\n \"\"\"\n Return the parent of x\n \"\"\"\n if x != x.parent:\n x.parent = find_set(x.parent)\n return x.parent\n\n\ndef find_python_set(node: Node) -> set:\n \"\"\"\n Return a Python Standard Library set that contains i.\n \"\"\"\n sets = ({0, 1, 2}, {3, 4, 5})\n for s in sets:\n if node.data in s:\n return s\n msg = f\"{node.data} is not in {sets}\"\n raise ValueError(msg)\n\n\ndef test_disjoint_set() -> None:\n \"\"\"\n >>> test_disjoint_set()\n \"\"\"\n vertex = [Node(i) for i in range(6)]\n for v in vertex:\n make_set(v)\n\n union_set(vertex[0], vertex[1])\n union_set(vertex[1], vertex[2])\n union_set(vertex[3], vertex[4])\n union_set(vertex[3], vertex[5])\n\n for node0 in vertex:\n for node1 in vertex:\n if find_python_set(node0).isdisjoint(find_python_set(node1)):\n assert find_set(node0) != find_set(node1)\n else:\n assert find_set(node0) == find_set(node1)\n\n\nif __name__ == \"__main__\":\n test_disjoint_set()\n"} +{"Prompt":"See https:en.wikipedia.orgwikiBloomfilter The use of this data structure is to test membership in a set. Compared to Python's builtin set it is more spaceefficient. In the following example, only 8 bits of memory will be used: bloom Bloomsize8 Initially, the filter contains all zeros: bloom.bitstring '00000000' When an element is added, two bits are set to 1 since there are 2 hash functions in this implementation: Titanic in bloom False bloom.addTitanic bloom.bitstring '01100000' Titanic in bloom True However, sometimes only one bit is added because both hash functions return the same value bloom.addAvatar Avatar in bloom True bloom.formathashAvatar '00000100' bloom.bitstring '01100100' Not added elements should return False ... notpresentfilms The Godfather, Interstellar, Parasite, Pulp Fiction ... film: bloom.formathashfilm for film in notpresentfilms ... doctest: NORMALIZEWHITESPACE 'The Godfather': '00000101', 'Interstellar': '00000011', 'Parasite': '00010010', 'Pulp Fiction': '10000100' anyfilm in bloom for film in notpresentfilms False but sometimes there are false positives: Ratatouille in bloom True bloom.formathashRatatouille '01100000' The probability increases with the number of elements added. The probability decreases with the number of bits in the bitarray. bloom.estimatederrorrate 0.140625 bloom.addThe Godfather bloom.estimatederrorrate 0.25 bloom.bitstring '01100101'","Completions":"from hashlib import md5, sha256\n\nHASH_FUNCTIONS = (sha256, md5)\n\n\nclass Bloom:\n def __init__(self, size: int = 8) -> None:\n self.bitarray = 0b0\n self.size = size\n\n def add(self, value: str) -> None:\n h = self.hash_(value)\n self.bitarray |= h\n\n def exists(self, value: str) -> bool:\n h = self.hash_(value)\n return (h & self.bitarray) == h\n\n def __contains__(self, other: str) -> bool:\n return self.exists(other)\n\n def format_bin(self, bitarray: int) -> str:\n res = bin(bitarray)[2:]\n return res.zfill(self.size)\n\n @property\n def bitstring(self) -> str:\n return self.format_bin(self.bitarray)\n\n def hash_(self, value: str) -> int:\n res = 0b0\n for func in HASH_FUNCTIONS:\n position = (\n int.from_bytes(func(value.encode()).digest(), \"little\") % self.size\n )\n res |= 2**position\n return res\n\n def format_hash(self, value: str) -> str:\n return self.format_bin(self.hash_(value))\n\n @property\n def estimated_error_rate(self) -> float:\n n_ones = bin(self.bitarray).count(\"1\")\n return (n_ones \/ self.size) ** len(HASH_FUNCTIONS)\n"} +{"Prompt":"!usrbinenv python3 Double hashing is a collision resolving technique in Open Addressed Hash tables. Double hashing uses the idea of applying a second hash function to key when a collision occurs. The advantage of Double hashing is that it is one of the best form of probing, producing a uniform distribution of records throughout a hash table. This technique does not yield any clusters. It is one of effective method for resolving collisions. Double hashing can be done using: hash1key i hash2key TABLESIZE Where hash1 and hash2 are hash functions and TABLESIZE is size of hash table. Reference: https:en.wikipedia.orgwikiDoublehashing Hash Table example with open addressing and Double Hash Examples: 1. Try to add three data elements when the size is three dh DoubleHash3 dh.insertdata10 dh.insertdata20 dh.insertdata30 dh.keys 1: 10, 2: 20, 0: 30 2. Try to add three data elements when the size is two dh DoubleHash2 dh.insertdata10 dh.insertdata20 dh.insertdata30 dh.keys 10: 10, 9: 20, 8: 30 3. Try to add three data elements when the size is four dh DoubleHash4 dh.insertdata10 dh.insertdata20 dh.insertdata30 dh.keys 9: 20, 10: 10, 8: 30","Completions":"#!\/usr\/bin\/env python3\n\"\"\"\nDouble hashing is a collision resolving technique in Open Addressed Hash tables.\nDouble hashing uses the idea of applying a second hash function to key when a collision\noccurs. The advantage of Double hashing is that it is one of the best form of probing,\nproducing a uniform distribution of records throughout a hash table. This technique\ndoes not yield any clusters. It is one of effective method for resolving collisions.\n\nDouble hashing can be done using: (hash1(key) + i * hash2(key)) % TABLE_SIZE\nWhere hash1() and hash2() are hash functions and TABLE_SIZE is size of hash table.\n\nReference: https:\/\/en.wikipedia.org\/wiki\/Double_hashing\n\"\"\"\nfrom .hash_table import HashTable\nfrom .number_theory.prime_numbers import is_prime, next_prime\n\n\nclass DoubleHash(HashTable):\n \"\"\"\n Hash Table example with open addressing and Double Hash\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n def __hash_function_2(self, value, data):\n next_prime_gt = (\n next_prime(value % self.size_table)\n if not is_prime(value % self.size_table)\n else value % self.size_table\n ) # gt = bigger than\n return next_prime_gt - (data % next_prime_gt)\n\n def __hash_double_function(self, key, data, increment):\n return (increment * self.__hash_function_2(key, data)) % self.size_table\n\n def _collision_resolution(self, key, data=None):\n \"\"\"\n Examples:\n\n 1. Try to add three data elements when the size is three\n >>> dh = DoubleHash(3)\n >>> dh.insert_data(10)\n >>> dh.insert_data(20)\n >>> dh.insert_data(30)\n >>> dh.keys()\n {1: 10, 2: 20, 0: 30}\n\n 2. Try to add three data elements when the size is two\n >>> dh = DoubleHash(2)\n >>> dh.insert_data(10)\n >>> dh.insert_data(20)\n >>> dh.insert_data(30)\n >>> dh.keys()\n {10: 10, 9: 20, 8: 30}\n\n 3. Try to add three data elements when the size is four\n >>> dh = DoubleHash(4)\n >>> dh.insert_data(10)\n >>> dh.insert_data(20)\n >>> dh.insert_data(30)\n >>> dh.keys()\n {9: 20, 10: 10, 8: 30}\n \"\"\"\n i = 1\n new_key = self.hash_function(data)\n\n while self.values[new_key] is not None and self.values[new_key] != key:\n new_key = (\n self.__hash_double_function(key, data, i)\n if self.balanced_factor() >= self.lim_charge\n else None\n )\n if new_key is None:\n break\n else:\n i += 1\n\n return new_key\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Hash map with open addressing. https:en.wikipedia.orgwikiHashtable Another hash map implementation, with a good explanation. Modern Dictionaries by Raymond Hettinger https:www.youtube.comwatch?vp33CVV29OG8 Hash map with open addressing. Get next index. Implements linear open addressing. HashMap5.getnextind3 4 HashMap5.getnextind5 1 HashMap5.getnextind6 2 HashMap5.getnextind9 0 Try to add value to the bucket. If bucket is empty or key is the same, does insert and return True. If bucket has another key or deleted placeholder, that means that we need to check next bucket. Return true if we have reached safe capacity. So we need to increase the number of buckets to avoid collisions. hm HashMap2 hm.additem1, 10 hm.additem2, 20 hm.isfull True HashMap2.isfull False Return true if we need twice fewer buckets when we have now. if lenself.buckets self.initialblocksize: return False limit lenself.buckets self.capacityfactor 2 return lenself limit def resizeself, newsize: int None: oldbuckets self.buckets self.buckets None newsize self.len 0 for item in oldbuckets: if item: self.additemitem.key, item.val def sizeupself None: self.resizelenself.buckets 2 def sizedownself None: self.resizelenself.buckets 2 def iteratebucketsself, key: KEY Iteratorint: ind self.getbucketindexkey for in rangelenself.buckets: yield ind ind self.getnextindind def additemself, key: KEY, val: VAL None: for ind in self.iteratebucketskey: if self.trysetind, key, val: break def setitemself, key: KEY, val: VAL None: if self.isfull: self.sizeup self.additemkey, val def delitemself, key: KEY None: Trying to remove a nonexisting item for ind in self.iteratebucketskey: item self.bucketsind if item is None: raise KeyErrorkey if item is deleted: continue if item.key key: self.bucketsind deleted self.len 1 break if self.issparse: self.sizedown def getitemself, key: KEY VAL: for ind in self.iteratebucketskey: item self.bucketsind if item is None: break if item is deleted: continue if item.key key: return item.val raise KeyErrorkey def lenself int: return self.len def iterself IteratorKEY: yield from item.key for item in self.buckets if item def reprself str: valstring , .join fitem.key: item.val for item in self.buckets if item return fHashMapvalstring if name main: import doctest doctest.testmod","Completions":"from collections.abc import Iterator, MutableMapping\nfrom dataclasses import dataclass\nfrom typing import Generic, TypeVar\n\nKEY = TypeVar(\"KEY\")\nVAL = TypeVar(\"VAL\")\n\n\n@dataclass(frozen=True, slots=True)\nclass _Item(Generic[KEY, VAL]):\n key: KEY\n val: VAL\n\n\nclass _DeletedItem(_Item):\n def __init__(self) -> None:\n super().__init__(None, None)\n\n def __bool__(self) -> bool:\n return False\n\n\n_deleted = _DeletedItem()\n\n\nclass HashMap(MutableMapping[KEY, VAL]):\n \"\"\"\n Hash map with open addressing.\n \"\"\"\n\n def __init__(\n self, initial_block_size: int = 8, capacity_factor: float = 0.75\n ) -> None:\n self._initial_block_size = initial_block_size\n self._buckets: list[_Item | None] = [None] * initial_block_size\n assert 0.0 < capacity_factor < 1.0\n self._capacity_factor = capacity_factor\n self._len = 0\n\n def _get_bucket_index(self, key: KEY) -> int:\n return hash(key) % len(self._buckets)\n\n def _get_next_ind(self, ind: int) -> int:\n \"\"\"\n Get next index.\n\n Implements linear open addressing.\n >>> HashMap(5)._get_next_ind(3)\n 4\n >>> HashMap(5)._get_next_ind(5)\n 1\n >>> HashMap(5)._get_next_ind(6)\n 2\n >>> HashMap(5)._get_next_ind(9)\n 0\n \"\"\"\n return (ind + 1) % len(self._buckets)\n\n def _try_set(self, ind: int, key: KEY, val: VAL) -> bool:\n \"\"\"\n Try to add value to the bucket.\n\n If bucket is empty or key is the same, does insert and return True.\n\n If bucket has another key or deleted placeholder,\n that means that we need to check next bucket.\n \"\"\"\n stored = self._buckets[ind]\n if not stored:\n self._buckets[ind] = _Item(key, val)\n self._len += 1\n return True\n elif stored.key == key:\n self._buckets[ind] = _Item(key, val)\n return True\n else:\n return False\n\n def _is_full(self) -> bool:\n \"\"\"\n Return true if we have reached safe capacity.\n\n So we need to increase the number of buckets to avoid collisions.\n\n >>> hm = HashMap(2)\n >>> hm._add_item(1, 10)\n >>> hm._add_item(2, 20)\n >>> hm._is_full()\n True\n >>> HashMap(2)._is_full()\n False\n \"\"\"\n limit = len(self._buckets) * self._capacity_factor\n return len(self) >= int(limit)\n\n def _is_sparse(self) -> bool:\n \"\"\"Return true if we need twice fewer buckets when we have now.\"\"\"\n if len(self._buckets) <= self._initial_block_size:\n return False\n limit = len(self._buckets) * self._capacity_factor \/ 2\n return len(self) < limit\n\n def _resize(self, new_size: int) -> None:\n old_buckets = self._buckets\n self._buckets = [None] * new_size\n self._len = 0\n for item in old_buckets:\n if item:\n self._add_item(item.key, item.val)\n\n def _size_up(self) -> None:\n self._resize(len(self._buckets) * 2)\n\n def _size_down(self) -> None:\n self._resize(len(self._buckets) \/\/ 2)\n\n def _iterate_buckets(self, key: KEY) -> Iterator[int]:\n ind = self._get_bucket_index(key)\n for _ in range(len(self._buckets)):\n yield ind\n ind = self._get_next_ind(ind)\n\n def _add_item(self, key: KEY, val: VAL) -> None:\n \"\"\"\n Try to add 3 elements when the size is 5\n >>> hm = HashMap(5)\n >>> hm._add_item(1, 10)\n >>> hm._add_item(2, 20)\n >>> hm._add_item(3, 30)\n >>> hm\n HashMap(1: 10, 2: 20, 3: 30)\n\n Try to add 3 elements when the size is 5\n >>> hm = HashMap(5)\n >>> hm._add_item(-5, 10)\n >>> hm._add_item(6, 30)\n >>> hm._add_item(-7, 20)\n >>> hm\n HashMap(-5: 10, 6: 30, -7: 20)\n\n Try to add 3 elements when size is 1\n >>> hm = HashMap(1)\n >>> hm._add_item(10, 13.2)\n >>> hm._add_item(6, 5.26)\n >>> hm._add_item(7, 5.155)\n >>> hm\n HashMap(10: 13.2)\n\n Trying to add an element with a key that is a floating point value\n >>> hm = HashMap(5)\n >>> hm._add_item(1.5, 10)\n >>> hm\n HashMap(1.5: 10)\n\n 5. Trying to add an item with the same key\n >>> hm = HashMap(5)\n >>> hm._add_item(1, 10)\n >>> hm._add_item(1, 20)\n >>> hm\n HashMap(1: 20)\n \"\"\"\n for ind in self._iterate_buckets(key):\n if self._try_set(ind, key, val):\n break\n\n def __setitem__(self, key: KEY, val: VAL) -> None:\n \"\"\"\n 1. Changing value of item whose key is present\n >>> hm = HashMap(5)\n >>> hm._add_item(1, 10)\n >>> hm.__setitem__(1, 20)\n >>> hm\n HashMap(1: 20)\n\n 2. Changing value of item whose key is not present\n >>> hm = HashMap(5)\n >>> hm._add_item(1, 10)\n >>> hm.__setitem__(0, 20)\n >>> hm\n HashMap(0: 20, 1: 10)\n\n 3. Changing the value of the same item multiple times\n >>> hm = HashMap(5)\n >>> hm._add_item(1, 10)\n >>> hm.__setitem__(1, 20)\n >>> hm.__setitem__(1, 30)\n >>> hm\n HashMap(1: 30)\n \"\"\"\n if self._is_full():\n self._size_up()\n\n self._add_item(key, val)\n\n def __delitem__(self, key: KEY) -> None:\n \"\"\"\n >>> hm = HashMap(5)\n >>> hm._add_item(1, 10)\n >>> hm._add_item(2, 20)\n >>> hm._add_item(3, 30)\n >>> hm.__delitem__(3)\n >>> hm\n HashMap(1: 10, 2: 20)\n >>> hm = HashMap(5)\n >>> hm._add_item(-5, 10)\n >>> hm._add_item(6, 30)\n >>> hm._add_item(-7, 20)\n >>> hm.__delitem__(-5)\n >>> hm\n HashMap(6: 30, -7: 20)\n\n # Trying to remove a non-existing item\n >>> hm = HashMap(5)\n >>> hm._add_item(1, 10)\n >>> hm._add_item(2, 20)\n >>> hm._add_item(3, 30)\n >>> hm.__delitem__(4)\n Traceback (most recent call last):\n ...\n KeyError: 4\n \"\"\"\n for ind in self._iterate_buckets(key):\n item = self._buckets[ind]\n if item is None:\n raise KeyError(key)\n if item is _deleted:\n continue\n if item.key == key:\n self._buckets[ind] = _deleted\n self._len -= 1\n break\n if self._is_sparse():\n self._size_down()\n\n def __getitem__(self, key: KEY) -> VAL:\n \"\"\"\n Returns the item at the given key\n\n >>> hm = HashMap(5)\n >>> hm._add_item(1, 10)\n >>> hm.__getitem__(1)\n 10\n\n >>> hm = HashMap(5)\n >>> hm._add_item(10, -10)\n >>> hm._add_item(20, -20)\n >>> hm.__getitem__(20)\n -20\n\n >>> hm = HashMap(5)\n >>> hm._add_item(-1, 10)\n >>> hm.__getitem__(-1)\n 10\n \"\"\"\n for ind in self._iterate_buckets(key):\n item = self._buckets[ind]\n if item is None:\n break\n if item is _deleted:\n continue\n if item.key == key:\n return item.val\n raise KeyError(key)\n\n def __len__(self) -> int:\n \"\"\"\n Returns the number of items present in hashmap\n\n >>> hm = HashMap(5)\n >>> hm._add_item(1, 10)\n >>> hm._add_item(2, 20)\n >>> hm._add_item(3, 30)\n >>> hm.__len__()\n 3\n\n >>> hm = HashMap(5)\n >>> hm.__len__()\n 0\n \"\"\"\n return self._len\n\n def __iter__(self) -> Iterator[KEY]:\n yield from (item.key for item in self._buckets if item)\n\n def __repr__(self) -> str:\n val_string = \", \".join(\n f\"{item.key}: {item.val}\" for item in self._buckets if item\n )\n return f\"HashMap({val_string})\"\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"!usrbinenv python3 Basic Hash Table example with open addressing and linear probing The keys function returns a dictionary containing the key value pairs. key being the index number in hash table and value being the data value. Examples: 1. creating HashTable with size 10 and inserting 3 elements ht HashTable10 ht.insertdata10 ht.insertdata20 ht.insertdata30 ht.keys 0: 10, 1: 20, 2: 30 2. creating HashTable with size 5 and inserting 5 elements ht HashTable5 ht.insertdata5 ht.insertdata4 ht.insertdata3 ht.insertdata2 ht.insertdata1 ht.keys 0: 5, 4: 4, 3: 3, 2: 2, 1: 1 Generates hash for the given key value Examples: Creating HashTable with size 5 ht HashTable5 ht.hashfunction10 0 ht.hashfunction20 0 ht.hashfunction4 4 ht.hashfunction18 3 ht.hashfunction18 2 ht.hashfunction18.5 3.5 ht.hashfunction0 0 ht.hashfunction0 0 bulkinsert is used for entering more than one element at a time in the HashTable. Examples: 1. ht HashTable5 ht.bulkinsert10,20,30 step 1 0, 1, 2, 3, 4 10, None, None, None, None step 2 0, 1, 2, 3, 4 10, 20, None, None, None step 3 0, 1, 2, 3, 4 10, 20, 30, None, None 2. ht HashTable5 ht.bulkinsert5,4,3,2,1 step 1 0, 1, 2, 3, 4 5, None, None, None, None step 2 0, 1, 2, 3, 4 5, None, None, None, 4 step 3 0, 1, 2, 3, 4 5, None, None, 3, 4 step 4 0, 1, 2, 3, 4 5, None, 2, 3, 4 step 5 0, 1, 2, 3, 4 5, 1, 2, 3, 4 setvalue functions allows to update value at a particular hash Examples: 1. setvalue in HashTable of size 5 ht HashTable5 ht.insertdata10 ht.insertdata20 ht.insertdata30 ht.setvalue0,15 ht.keys 0: 15, 1: 20, 2: 30 2. setvalue in HashTable of size 2 ht HashTable2 ht.insertdata17 ht.insertdata18 ht.insertdata99 ht.setvalue3,15 ht.keys 3: 15, 2: 17, 4: 99 3. setvalue in HashTable when hash is not present ht HashTable2 ht.insertdata17 ht.insertdata18 ht.insertdata99 ht.setvalue0,15 ht.keys 3: 18, 2: 17, 4: 99, 0: 15 4. setvalue in HashTable when multiple hash are not present ht HashTable2 ht.insertdata17 ht.insertdata18 ht.insertdata99 ht.setvalue0,15 ht.setvalue1,20 ht.keys 3: 18, 2: 17, 4: 99, 0: 15, 1: 20 This method is a type of open addressing which is used for handling collision. In this implementation the concept of linear probing has been used. The hash table is searched sequentially from the original location of the hash, if the new hashlocation we get is already occupied we check for the next hashlocation. references: https:en.wikipedia.orgwikiLinearprobing Examples: 1. The collision will be with keys 18 99, so new hash will be created for 99 ht HashTable3 ht.insertdata17 ht.insertdata18 ht.insertdata99 ht.keys 2: 17, 0: 18, 1: 99 2. The collision will be with keys 17 101, so new hash will be created for 101 ht HashTable4 ht.insertdata17 ht.insertdata18 ht.insertdata99 ht.insertdata101 ht.keys 1: 17, 2: 18, 3: 99, 0: 101 2. The collision will be with all keys, so new hash will be created for all ht HashTable1 ht.insertdata17 ht.insertdata18 ht.insertdata99 ht.keys 2: 17, 3: 18, 4: 99 3. Trying to insert float key in hash ht HashTable1 ht.insertdata17 ht.insertdata18 ht.insertdata99.99 Traceback most recent call last: ... TypeError: list indices must be integers or slices, not float insertdata is used for inserting a single element at a time in the HashTable. Examples: ht HashTable3 ht.insertdata5 ht.keys 2: 5 ht HashTable5 ht.insertdata30 ht.insertdata50 ht.keys 0: 30, 1: 50","Completions":"#!\/usr\/bin\/env python3\nfrom .number_theory.prime_numbers import next_prime\n\n\nclass HashTable:\n \"\"\"\n Basic Hash Table example with open addressing and linear probing\n \"\"\"\n\n def __init__(\n self,\n size_table: int,\n charge_factor: int | None = None,\n lim_charge: float | None = None,\n ) -> None:\n self.size_table = size_table\n self.values = [None] * self.size_table\n self.lim_charge = 0.75 if lim_charge is None else lim_charge\n self.charge_factor = 1 if charge_factor is None else charge_factor\n self.__aux_list: list = []\n self._keys: dict = {}\n\n def keys(self):\n \"\"\"\n The keys function returns a dictionary containing the key value pairs.\n key being the index number in hash table and value being the data value.\n\n Examples:\n 1. creating HashTable with size 10 and inserting 3 elements\n >>> ht = HashTable(10)\n >>> ht.insert_data(10)\n >>> ht.insert_data(20)\n >>> ht.insert_data(30)\n >>> ht.keys()\n {0: 10, 1: 20, 2: 30}\n\n 2. creating HashTable with size 5 and inserting 5 elements\n >>> ht = HashTable(5)\n >>> ht.insert_data(5)\n >>> ht.insert_data(4)\n >>> ht.insert_data(3)\n >>> ht.insert_data(2)\n >>> ht.insert_data(1)\n >>> ht.keys()\n {0: 5, 4: 4, 3: 3, 2: 2, 1: 1}\n \"\"\"\n return self._keys\n\n def balanced_factor(self):\n return sum(1 for slot in self.values if slot is not None) \/ (\n self.size_table * self.charge_factor\n )\n\n def hash_function(self, key):\n \"\"\"\n Generates hash for the given key value\n\n Examples:\n\n Creating HashTable with size 5\n >>> ht = HashTable(5)\n >>> ht.hash_function(10)\n 0\n >>> ht.hash_function(20)\n 0\n >>> ht.hash_function(4)\n 4\n >>> ht.hash_function(18)\n 3\n >>> ht.hash_function(-18)\n 2\n >>> ht.hash_function(18.5)\n 3.5\n >>> ht.hash_function(0)\n 0\n >>> ht.hash_function(-0)\n 0\n \"\"\"\n return key % self.size_table\n\n def _step_by_step(self, step_ord):\n print(f\"step {step_ord}\")\n print(list(range(len(self.values))))\n print(self.values)\n\n def bulk_insert(self, values):\n \"\"\"\n bulk_insert is used for entering more than one element at a time\n in the HashTable.\n\n Examples:\n 1.\n >>> ht = HashTable(5)\n >>> ht.bulk_insert((10,20,30))\n step 1\n [0, 1, 2, 3, 4]\n [10, None, None, None, None]\n step 2\n [0, 1, 2, 3, 4]\n [10, 20, None, None, None]\n step 3\n [0, 1, 2, 3, 4]\n [10, 20, 30, None, None]\n\n 2.\n >>> ht = HashTable(5)\n >>> ht.bulk_insert([5,4,3,2,1])\n step 1\n [0, 1, 2, 3, 4]\n [5, None, None, None, None]\n step 2\n [0, 1, 2, 3, 4]\n [5, None, None, None, 4]\n step 3\n [0, 1, 2, 3, 4]\n [5, None, None, 3, 4]\n step 4\n [0, 1, 2, 3, 4]\n [5, None, 2, 3, 4]\n step 5\n [0, 1, 2, 3, 4]\n [5, 1, 2, 3, 4]\n \"\"\"\n i = 1\n self.__aux_list = values\n for value in values:\n self.insert_data(value)\n self._step_by_step(i)\n i += 1\n\n def _set_value(self, key, data):\n \"\"\"\n _set_value functions allows to update value at a particular hash\n\n Examples:\n 1. _set_value in HashTable of size 5\n >>> ht = HashTable(5)\n >>> ht.insert_data(10)\n >>> ht.insert_data(20)\n >>> ht.insert_data(30)\n >>> ht._set_value(0,15)\n >>> ht.keys()\n {0: 15, 1: 20, 2: 30}\n\n 2. _set_value in HashTable of size 2\n >>> ht = HashTable(2)\n >>> ht.insert_data(17)\n >>> ht.insert_data(18)\n >>> ht.insert_data(99)\n >>> ht._set_value(3,15)\n >>> ht.keys()\n {3: 15, 2: 17, 4: 99}\n\n 3. _set_value in HashTable when hash is not present\n >>> ht = HashTable(2)\n >>> ht.insert_data(17)\n >>> ht.insert_data(18)\n >>> ht.insert_data(99)\n >>> ht._set_value(0,15)\n >>> ht.keys()\n {3: 18, 2: 17, 4: 99, 0: 15}\n\n 4. _set_value in HashTable when multiple hash are not present\n >>> ht = HashTable(2)\n >>> ht.insert_data(17)\n >>> ht.insert_data(18)\n >>> ht.insert_data(99)\n >>> ht._set_value(0,15)\n >>> ht._set_value(1,20)\n >>> ht.keys()\n {3: 18, 2: 17, 4: 99, 0: 15, 1: 20}\n \"\"\"\n self.values[key] = data\n self._keys[key] = data\n\n def _collision_resolution(self, key, data=None):\n \"\"\"\n This method is a type of open addressing which is used for handling collision.\n\n In this implementation the concept of linear probing has been used.\n\n The hash table is searched sequentially from the original location of the\n hash, if the new hash\/location we get is already occupied we check for the next\n hash\/location.\n\n references:\n - https:\/\/en.wikipedia.org\/wiki\/Linear_probing\n\n Examples:\n 1. The collision will be with keys 18 & 99, so new hash will be created for 99\n >>> ht = HashTable(3)\n >>> ht.insert_data(17)\n >>> ht.insert_data(18)\n >>> ht.insert_data(99)\n >>> ht.keys()\n {2: 17, 0: 18, 1: 99}\n\n 2. The collision will be with keys 17 & 101, so new hash\n will be created for 101\n >>> ht = HashTable(4)\n >>> ht.insert_data(17)\n >>> ht.insert_data(18)\n >>> ht.insert_data(99)\n >>> ht.insert_data(101)\n >>> ht.keys()\n {1: 17, 2: 18, 3: 99, 0: 101}\n\n 2. The collision will be with all keys, so new hash will be created for all\n >>> ht = HashTable(1)\n >>> ht.insert_data(17)\n >>> ht.insert_data(18)\n >>> ht.insert_data(99)\n >>> ht.keys()\n {2: 17, 3: 18, 4: 99}\n\n 3. Trying to insert float key in hash\n >>> ht = HashTable(1)\n >>> ht.insert_data(17)\n >>> ht.insert_data(18)\n >>> ht.insert_data(99.99)\n Traceback (most recent call last):\n ...\n TypeError: list indices must be integers or slices, not float\n \"\"\"\n new_key = self.hash_function(key + 1)\n\n while self.values[new_key] is not None and self.values[new_key] != key:\n if self.values.count(None) > 0:\n new_key = self.hash_function(new_key + 1)\n else:\n new_key = None\n break\n\n return new_key\n\n def rehashing(self):\n survivor_values = [value for value in self.values if value is not None]\n self.size_table = next_prime(self.size_table, factor=2)\n self._keys.clear()\n self.values = [None] * self.size_table # hell's pointers D: don't DRY ;\/\n for value in survivor_values:\n self.insert_data(value)\n\n def insert_data(self, data):\n \"\"\"\n insert_data is used for inserting a single element at a time in the HashTable.\n\n Examples:\n\n >>> ht = HashTable(3)\n >>> ht.insert_data(5)\n >>> ht.keys()\n {2: 5}\n >>> ht = HashTable(5)\n >>> ht.insert_data(30)\n >>> ht.insert_data(50)\n >>> ht.keys()\n {0: 30, 1: 50}\n \"\"\"\n key = self.hash_function(data)\n\n if self.values[key] is None:\n self._set_value(key, data)\n\n elif self.values[key] == data:\n pass\n\n else:\n collision_resolution = self._collision_resolution(key, data)\n if collision_resolution is not None:\n self._set_value(collision_resolution, data)\n else:\n self.rehashing()\n self.insert_data(data)\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"!usrbinenv python3 module to operations with prime numbers Checks to see if a number is a prime in Osqrtn. A number is prime if it has exactly two factors: 1 and itself. isprime0 False isprime1 False isprime2 True isprime3 True isprime27 False isprime87 False isprime563 True isprime2999 True isprime67483 False precondition 2 and 3 are primes Negatives, 0, 1 and all even numbers are not primes","Completions":"#!\/usr\/bin\/env python3\n\"\"\"\n module to operations with prime numbers\n\"\"\"\n\nimport math\n\n\ndef is_prime(number: int) -> bool:\n \"\"\"Checks to see if a number is a prime in O(sqrt(n)).\n\n A number is prime if it has exactly two factors: 1 and itself.\n\n >>> is_prime(0)\n False\n >>> is_prime(1)\n False\n >>> is_prime(2)\n True\n >>> is_prime(3)\n True\n >>> is_prime(27)\n False\n >>> is_prime(87)\n False\n >>> is_prime(563)\n True\n >>> is_prime(2999)\n True\n >>> is_prime(67483)\n False\n \"\"\"\n\n # precondition\n assert isinstance(number, int) and (\n number >= 0\n ), \"'number' must been an int and positive\"\n\n if 1 < number < 4:\n # 2 and 3 are primes\n return True\n elif number < 2 or not number % 2:\n # Negatives, 0, 1 and all even numbers are not primes\n return False\n\n odd_numbers = range(3, int(math.sqrt(number) + 1), 2)\n return not any(not number % i for i in odd_numbers)\n\n\ndef next_prime(value, factor=1, **kwargs):\n value = factor * value\n first_value_val = value\n\n while not is_prime(value):\n value += 1 if not (\"desc\" in kwargs and kwargs[\"desc\"] is True) else -1\n\n if value == first_value_val:\n return next_prime(value + 1, **kwargs)\n return value\n"} +{"Prompt":"!usrbinenv python3 Basic Hash Table example with open addressing using Quadratic Probing Quadratic probing is an open addressing scheme used for resolving collisions in hash table. It works by taking the original hash index and adding successive values of an arbitrary quadratic polynomial until open slot is found. Hash 1, Hash 2, Hash 3 .... Hash n reference: https:en.wikipedia.orgwikiQuadraticprobing e.g: 1. Create hash table with size 7 qp QuadraticProbing7 qp.insertdata90 qp.insertdata340 qp.insertdata24 qp.insertdata45 qp.insertdata99 qp.insertdata73 qp.insertdata7 qp.keys 11: 45, 14: 99, 7: 24, 0: 340, 5: 73, 6: 90, 8: 7 2. Create hash table with size 8 qp QuadraticProbing8 qp.insertdata0 qp.insertdata999 qp.insertdata111 qp.keys 0: 0, 7: 999, 3: 111 3. Try to add three data elements when the size is two qp QuadraticProbing2 qp.insertdata0 qp.insertdata999 qp.insertdata111 qp.keys 0: 0, 4: 999, 1: 111 4. Try to add three data elements when the size is one qp QuadraticProbing1 qp.insertdata0 qp.insertdata999 qp.insertdata111 qp.keys 4: 999, 1: 111","Completions":"#!\/usr\/bin\/env python3\n\nfrom .hash_table import HashTable\n\n\nclass QuadraticProbing(HashTable):\n \"\"\"\n Basic Hash Table example with open addressing using Quadratic Probing\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n def _collision_resolution(self, key, data=None):\n \"\"\"\n Quadratic probing is an open addressing scheme used for resolving\n collisions in hash table.\n\n It works by taking the original hash index and adding successive\n values of an arbitrary quadratic polynomial until open slot is found.\n\n Hash + 1\u00b2, Hash + 2\u00b2, Hash + 3\u00b2 .... Hash + n\u00b2\n\n reference:\n - https:\/\/en.wikipedia.org\/wiki\/Quadratic_probing\n e.g:\n 1. Create hash table with size 7\n >>> qp = QuadraticProbing(7)\n >>> qp.insert_data(90)\n >>> qp.insert_data(340)\n >>> qp.insert_data(24)\n >>> qp.insert_data(45)\n >>> qp.insert_data(99)\n >>> qp.insert_data(73)\n >>> qp.insert_data(7)\n >>> qp.keys()\n {11: 45, 14: 99, 7: 24, 0: 340, 5: 73, 6: 90, 8: 7}\n\n 2. Create hash table with size 8\n >>> qp = QuadraticProbing(8)\n >>> qp.insert_data(0)\n >>> qp.insert_data(999)\n >>> qp.insert_data(111)\n >>> qp.keys()\n {0: 0, 7: 999, 3: 111}\n\n 3. Try to add three data elements when the size is two\n >>> qp = QuadraticProbing(2)\n >>> qp.insert_data(0)\n >>> qp.insert_data(999)\n >>> qp.insert_data(111)\n >>> qp.keys()\n {0: 0, 4: 999, 1: 111}\n\n 4. Try to add three data elements when the size is one\n >>> qp = QuadraticProbing(1)\n >>> qp.insert_data(0)\n >>> qp.insert_data(999)\n >>> qp.insert_data(111)\n >>> qp.keys()\n {4: 999, 1: 111}\n \"\"\"\n\n i = 1\n new_key = self.hash_function(key + i * i)\n\n while self.values[new_key] is not None and self.values[new_key] != key:\n i += 1\n new_key = (\n self.hash_function(key + i * i)\n if not self.balanced_factor() >= self.lim_charge\n else None\n )\n\n if new_key is None:\n break\n\n return new_key\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Binomial Heap Reference: Advanced Data Structures, Peter Brass Node in a doublylinked binomial tree, containing: value size of left subtree link to left, right and parent nodes Number of nodes in left subtree Inplace merge of two binomial trees of equal size. Returns the root of the resulting tree 31 def initself, bottomrootNone, minnodeNone, heapsize0: self.size heapsize self.bottomroot bottomroot self.minnode minnode def mergeheapsself, other: Empty heaps corner cases if other.size 0: return None if self.size 0: self.size other.size self.bottomroot other.bottomroot self.minnode other.minnode return None Update size self.size self.size other.size Update min.node if self.minnode.val other.minnode.val: self.minnode other.minnode Merge Order roots by leftsubtreesize combinedrootslist i, j self.bottomroot, other.bottomroot while i or j: if i and not j or i.lefttreesize j.lefttreesize: combinedrootslist.appendi, True i i.parent else: combinedrootslist.appendj, False j j.parent Insert links between them for i in rangelencombinedrootslist 1: if combinedrootslisti1 ! combinedrootslisti 11: combinedrootslisti0.parent combinedrootslisti 10 combinedrootslisti 10.left combinedrootslisti0 Consecutively merge roots with same lefttreesize i combinedrootslist00 while i.parent: if i.lefttreesize i.parent.lefttreesize and not i.parent.parent or i.lefttreesize i.parent.lefttreesize and i.lefttreesize ! i.parent.parent.lefttreesize : Neighbouring Nodes previousnode i.left nextnode i.parent.parent Merging trees i i.mergetreesi.parent Updating links i.left previousnode i.parent nextnode if previousnode: previousnode.parent i if nextnode: nextnode.left i else: i i.parent Updating self.bottomroot while i.left: i i.left self.bottomroot i Update other other.size self.size other.bottomroot self.bottomroot other.minnode self.minnode Return the merged heap return self def insertself, val: if self.size 0: self.bottomroot Nodeval self.size 1 self.minnode self.bottomroot else: Create new node newnode Nodeval Update size self.size 1 update minnode if val self.minnode.val: self.minnode newnode Put newnode as a bottomroot in heap self.bottomroot.left newnode newnode.parent self.bottomroot self.bottomroot newnode Consecutively merge roots with same lefttreesize while self.bottomroot.parent and self.bottomroot.lefttreesize self.bottomroot.parent.lefttreesize : Next node nextnode self.bottomroot.parent.parent Merge self.bottomroot self.bottomroot.mergetreesself.bottomroot.parent Update Links self.bottomroot.parent nextnode self.bottomroot.left None if nextnode: nextnode.left self.bottomroot def peekself: return self.minnode.val def isemptyself: return self.size 0 def deleteminself: assert not self.isEmpty, Empty Heap Save minimal value minvalue self.minnode.val Last element in heap corner case if self.size 1: Update size self.size 0 Update bottom root self.bottomroot None Update minnode self.minnode None return minvalue No right subtree corner case The structure of the tree implies that this should be the bottom root and there is at least one other root if self.minnode.right is None: Update size self.size 1 Update bottom root self.bottomroot self.bottomroot.parent self.bottomroot.left None Update minnode self.minnode self.bottomroot i self.bottomroot.parent while i: if i.val self.minnode.val: self.minnode i i i.parent return minvalue General case Find the BinomialHeap of the right subtree of minnode bottomofnew self.minnode.right bottomofnew.parent None minofnew bottomofnew sizeofnew 1 Size, minnode and bottomroot while bottomofnew.left: sizeofnew sizeofnew 2 1 bottomofnew bottomofnew.left if bottomofnew.val minofnew.val: minofnew bottomofnew Corner case of single root on top left path if not self.minnode.left and not self.minnode.parent: self.size sizeofnew self.bottomroot bottomofnew self.minnode minofnew printSingle root, multiple nodes case return minvalue Remaining cases Construct heap of right subtree newheap BinomialHeap bottomrootbottomofnew, minnodeminofnew, heapsizesizeofnew Update size self.size self.size 1 sizeofnew Neighbour nodes previousnode self.minnode.left nextnode self.minnode.parent Initialize new bottomroot and minnode self.minnode previousnode or nextnode self.bottomroot nextnode Update links of previousnode and search below for new minnode and bottomroot if previousnode: previousnode.parent nextnode Update bottomroot and search for minnode below self.bottomroot previousnode self.minnode previousnode while self.bottomroot.left: self.bottomroot self.bottomroot.left if self.bottomroot.val self.minnode.val: self.minnode self.bottomroot if nextnode: nextnode.left previousnode Search for new minnode above minnode i nextnode while i: if i.val self.minnode.val: self.minnode i i i.parent Merge heaps self.mergeheapsnewheap return minvalue def preorderself: Find top root toproot self.bottomroot while toproot.parent: toproot toproot.parent preorder heappreorder self.traversaltoproot, heappreorder return heappreorder def traversalself, currnode, preorder, level0: if currnode: preorder.appendcurrnode.val, level self.traversalcurrnode.left, preorder, level 1 self.traversalcurrnode.right, preorder, level 1 else: preorder.append, level def strself: if self.isempty: return preorderheap self.preorder return n.join level strvalue for value, level in preorderheap Unit Tests if name main: import doctest doctest.testmod","Completions":"class Node:\n \"\"\"\n Node in a doubly-linked binomial tree, containing:\n - value\n - size of left subtree\n - link to left, right and parent nodes\n \"\"\"\n\n def __init__(self, val):\n self.val = val\n # Number of nodes in left subtree\n self.left_tree_size = 0\n self.left = None\n self.right = None\n self.parent = None\n\n def merge_trees(self, other):\n \"\"\"\n In-place merge of two binomial trees of equal size.\n Returns the root of the resulting tree\n \"\"\"\n assert self.left_tree_size == other.left_tree_size, \"Unequal Sizes of Blocks\"\n\n if self.val < other.val:\n other.left = self.right\n other.parent = None\n if self.right:\n self.right.parent = other\n self.right = other\n self.left_tree_size = self.left_tree_size * 2 + 1\n return self\n else:\n self.left = other.right\n self.parent = None\n if other.right:\n other.right.parent = self\n other.right = self\n other.left_tree_size = other.left_tree_size * 2 + 1\n return other\n\n\nclass BinomialHeap:\n r\"\"\"\n Min-oriented priority queue implemented with the Binomial Heap data\n structure implemented with the BinomialHeap class. It supports:\n - Insert element in a heap with n elements: Guaranteed logn, amoratized 1\n - Merge (meld) heaps of size m and n: O(logn + logm)\n - Delete Min: O(logn)\n - Peek (return min without deleting it): O(1)\n\n Example:\n\n Create a random permutation of 30 integers to be inserted and 19 of them deleted\n >>> import numpy as np\n >>> permutation = np.random.permutation(list(range(30)))\n\n Create a Heap and insert the 30 integers\n __init__() test\n >>> first_heap = BinomialHeap()\n\n 30 inserts - insert() test\n >>> for number in permutation:\n ... first_heap.insert(number)\n\n Size test\n >>> first_heap.size\n 30\n\n Deleting - delete() test\n >>> [first_heap.delete_min() for _ in range(20)]\n [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]\n\n Create a new Heap\n >>> second_heap = BinomialHeap()\n >>> vals = [17, 20, 31, 34]\n >>> for value in vals:\n ... second_heap.insert(value)\n\n\n The heap should have the following structure:\n\n 17\n \/ \\\n # 31\n \/ \\\n 20 34\n \/ \\ \/ \\\n # # # #\n\n preOrder() test\n >>> \" \".join(str(x) for x in second_heap.pre_order())\n \"(17, 0) ('#', 1) (31, 1) (20, 2) ('#', 3) ('#', 3) (34, 2) ('#', 3) ('#', 3)\"\n\n printing Heap - __str__() test\n >>> print(second_heap)\n 17\n -#\n -31\n --20\n ---#\n ---#\n --34\n ---#\n ---#\n\n mergeHeaps() test\n >>>\n >>> merged = second_heap.merge_heaps(first_heap)\n >>> merged.peek()\n 17\n\n values in merged heap; (merge is inplace)\n >>> results = []\n >>> while not first_heap.is_empty():\n ... results.append(first_heap.delete_min())\n >>> results\n [17, 20, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 31, 34]\n \"\"\"\n\n def __init__(self, bottom_root=None, min_node=None, heap_size=0):\n self.size = heap_size\n self.bottom_root = bottom_root\n self.min_node = min_node\n\n def merge_heaps(self, other):\n \"\"\"\n In-place merge of two binomial heaps.\n Both of them become the resulting merged heap\n \"\"\"\n\n # Empty heaps corner cases\n if other.size == 0:\n return None\n if self.size == 0:\n self.size = other.size\n self.bottom_root = other.bottom_root\n self.min_node = other.min_node\n return None\n # Update size\n self.size = self.size + other.size\n\n # Update min.node\n if self.min_node.val > other.min_node.val:\n self.min_node = other.min_node\n # Merge\n\n # Order roots by left_subtree_size\n combined_roots_list = []\n i, j = self.bottom_root, other.bottom_root\n while i or j:\n if i and ((not j) or i.left_tree_size < j.left_tree_size):\n combined_roots_list.append((i, True))\n i = i.parent\n else:\n combined_roots_list.append((j, False))\n j = j.parent\n # Insert links between them\n for i in range(len(combined_roots_list) - 1):\n if combined_roots_list[i][1] != combined_roots_list[i + 1][1]:\n combined_roots_list[i][0].parent = combined_roots_list[i + 1][0]\n combined_roots_list[i + 1][0].left = combined_roots_list[i][0]\n # Consecutively merge roots with same left_tree_size\n i = combined_roots_list[0][0]\n while i.parent:\n if (\n (i.left_tree_size == i.parent.left_tree_size) and (not i.parent.parent)\n ) or (\n i.left_tree_size == i.parent.left_tree_size\n and i.left_tree_size != i.parent.parent.left_tree_size\n ):\n # Neighbouring Nodes\n previous_node = i.left\n next_node = i.parent.parent\n\n # Merging trees\n i = i.merge_trees(i.parent)\n\n # Updating links\n i.left = previous_node\n i.parent = next_node\n if previous_node:\n previous_node.parent = i\n if next_node:\n next_node.left = i\n else:\n i = i.parent\n # Updating self.bottom_root\n while i.left:\n i = i.left\n self.bottom_root = i\n\n # Update other\n other.size = self.size\n other.bottom_root = self.bottom_root\n other.min_node = self.min_node\n\n # Return the merged heap\n return self\n\n def insert(self, val):\n \"\"\"\n insert a value in the heap\n \"\"\"\n if self.size == 0:\n self.bottom_root = Node(val)\n self.size = 1\n self.min_node = self.bottom_root\n else:\n # Create new node\n new_node = Node(val)\n\n # Update size\n self.size += 1\n\n # update min_node\n if val < self.min_node.val:\n self.min_node = new_node\n # Put new_node as a bottom_root in heap\n self.bottom_root.left = new_node\n new_node.parent = self.bottom_root\n self.bottom_root = new_node\n\n # Consecutively merge roots with same left_tree_size\n while (\n self.bottom_root.parent\n and self.bottom_root.left_tree_size\n == self.bottom_root.parent.left_tree_size\n ):\n # Next node\n next_node = self.bottom_root.parent.parent\n\n # Merge\n self.bottom_root = self.bottom_root.merge_trees(self.bottom_root.parent)\n\n # Update Links\n self.bottom_root.parent = next_node\n self.bottom_root.left = None\n if next_node:\n next_node.left = self.bottom_root\n\n def peek(self):\n \"\"\"\n return min element without deleting it\n \"\"\"\n return self.min_node.val\n\n def is_empty(self):\n return self.size == 0\n\n def delete_min(self):\n \"\"\"\n delete min element and return it\n \"\"\"\n # assert not self.isEmpty(), \"Empty Heap\"\n\n # Save minimal value\n min_value = self.min_node.val\n\n # Last element in heap corner case\n if self.size == 1:\n # Update size\n self.size = 0\n\n # Update bottom root\n self.bottom_root = None\n\n # Update min_node\n self.min_node = None\n\n return min_value\n # No right subtree corner case\n # The structure of the tree implies that this should be the bottom root\n # and there is at least one other root\n if self.min_node.right is None:\n # Update size\n self.size -= 1\n\n # Update bottom root\n self.bottom_root = self.bottom_root.parent\n self.bottom_root.left = None\n\n # Update min_node\n self.min_node = self.bottom_root\n i = self.bottom_root.parent\n while i:\n if i.val < self.min_node.val:\n self.min_node = i\n i = i.parent\n return min_value\n # General case\n # Find the BinomialHeap of the right subtree of min_node\n bottom_of_new = self.min_node.right\n bottom_of_new.parent = None\n min_of_new = bottom_of_new\n size_of_new = 1\n\n # Size, min_node and bottom_root\n while bottom_of_new.left:\n size_of_new = size_of_new * 2 + 1\n bottom_of_new = bottom_of_new.left\n if bottom_of_new.val < min_of_new.val:\n min_of_new = bottom_of_new\n # Corner case of single root on top left path\n if (not self.min_node.left) and (not self.min_node.parent):\n self.size = size_of_new\n self.bottom_root = bottom_of_new\n self.min_node = min_of_new\n # print(\"Single root, multiple nodes case\")\n return min_value\n # Remaining cases\n # Construct heap of right subtree\n new_heap = BinomialHeap(\n bottom_root=bottom_of_new, min_node=min_of_new, heap_size=size_of_new\n )\n\n # Update size\n self.size = self.size - 1 - size_of_new\n\n # Neighbour nodes\n previous_node = self.min_node.left\n next_node = self.min_node.parent\n\n # Initialize new bottom_root and min_node\n self.min_node = previous_node or next_node\n self.bottom_root = next_node\n\n # Update links of previous_node and search below for new min_node and\n # bottom_root\n if previous_node:\n previous_node.parent = next_node\n\n # Update bottom_root and search for min_node below\n self.bottom_root = previous_node\n self.min_node = previous_node\n while self.bottom_root.left:\n self.bottom_root = self.bottom_root.left\n if self.bottom_root.val < self.min_node.val:\n self.min_node = self.bottom_root\n if next_node:\n next_node.left = previous_node\n\n # Search for new min_node above min_node\n i = next_node\n while i:\n if i.val < self.min_node.val:\n self.min_node = i\n i = i.parent\n # Merge heaps\n self.merge_heaps(new_heap)\n\n return min_value\n\n def pre_order(self):\n \"\"\"\n Returns the Pre-order representation of the heap including\n values of nodes plus their level distance from the root;\n Empty nodes appear as #\n \"\"\"\n # Find top root\n top_root = self.bottom_root\n while top_root.parent:\n top_root = top_root.parent\n # preorder\n heap_pre_order = []\n self.__traversal(top_root, heap_pre_order)\n return heap_pre_order\n\n def __traversal(self, curr_node, preorder, level=0):\n \"\"\"\n Pre-order traversal of nodes\n \"\"\"\n if curr_node:\n preorder.append((curr_node.val, level))\n self.__traversal(curr_node.left, preorder, level + 1)\n self.__traversal(curr_node.right, preorder, level + 1)\n else:\n preorder.append((\"#\", level))\n\n def __str__(self):\n \"\"\"\n Overwriting str for a pre-order print of nodes in heap;\n Performance is poor, so use only for small examples\n \"\"\"\n if self.is_empty():\n return \"\"\n preorder_heap = self.pre_order()\n\n return \"\\n\".join((\"-\" * level + str(value)) for value, level in preorder_heap)\n\n\n# Unit Tests\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"A Max Heap Implementation unsorted 103, 9, 1, 7, 11, 15, 25, 201, 209, 107, 5 h Heap h.buildmaxheapunsorted h 209, 201, 25, 103, 107, 15, 1, 9, 7, 11, 5 h.extractmax 209 h 201, 107, 25, 103, 11, 15, 1, 9, 7, 5 h.insert100 h 201, 107, 25, 103, 100, 15, 1, 9, 7, 5, 11 h.heapsort h 1, 5, 7, 9, 11, 15, 25, 100, 103, 107, 201 returns the parent index based on the given child index h Heap h.buildmaxheap103, 9, 1, 7, 11, 15, 25, 201, 209, 107, 5 h 209, 201, 25, 103, 107, 15, 1, 9, 7, 11, 5 h.parentindex1 returns none if index is 0 h.parentindex0 returns none if index is 0 h.parentindex1 0 h.parentindex2 0 h.parentindex3 1 h.parentindex4 1 h.parentindex5 2 h.parentindex10.5 4.0 h.parentindex209.0 104.0 h.parentindexTest Traceback most recent call last: ... TypeError: '' not supported between instances of 'str' and 'int' return the left child index if the left child exists. if not, return None. return the right child index if the right child exists. if not, return None. correct a single violation of the heap property in a subtree's root. It is the function that is responsible for restoring the property of Max heap i.e the maximum element is always at top. check which child is larger than its parent if violation indeed exists swap to fix the violation fix the subsequent violation recursively if any build max heap from an unsorted array h Heap h.buildmaxheap20,40,50,20,10 h 50, 40, 20, 20, 10 h Heap h.buildmaxheap1,2,3,4,5,6,7,8,9,0 h 9, 8, 7, 4, 5, 6, 3, 2, 1, 0 h Heap h.buildmaxheap514,5,61,57,8,99,105 h 514, 57, 105, 5, 8, 99, 61 h Heap h.buildmaxheap514,5,61.6,57,8,9.9,105 h 514, 57, 105, 5, 8, 9.9, 61.6 maxheapify from right to left but exclude leaves last level get and remove max from heap h Heap h.buildmaxheap20,40,50,20,10 h.extractmax 50 h Heap h.buildmaxheap514,5,61,57,8,99,105 h.extractmax 514 h Heap h.buildmaxheap1,2,3,4,5,6,7,8,9,0 h.extractmax 9 insert a new value into the max heap h Heap h.insert10 h 10 h Heap h.insert10 h.insert10 h 10, 10 h Heap h.insert10 h.insert10.1 h 10.1, 10 h Heap h.insert0.1 h.insert0 h.insert9 h.insert5 h 9, 5, 0.1, 0 run doc test demo","Completions":"from __future__ import annotations\n\nfrom abc import abstractmethod\nfrom collections.abc import Iterable\nfrom typing import Generic, Protocol, TypeVar\n\n\nclass Comparable(Protocol):\n @abstractmethod\n def __lt__(self: T, other: T) -> bool:\n pass\n\n @abstractmethod\n def __gt__(self: T, other: T) -> bool:\n pass\n\n @abstractmethod\n def __eq__(self: T, other: object) -> bool:\n pass\n\n\nT = TypeVar(\"T\", bound=Comparable)\n\n\nclass Heap(Generic[T]):\n \"\"\"A Max Heap Implementation\n\n >>> unsorted = [103, 9, 1, 7, 11, 15, 25, 201, 209, 107, 5]\n >>> h = Heap()\n >>> h.build_max_heap(unsorted)\n >>> h\n [209, 201, 25, 103, 107, 15, 1, 9, 7, 11, 5]\n >>>\n >>> h.extract_max()\n 209\n >>> h\n [201, 107, 25, 103, 11, 15, 1, 9, 7, 5]\n >>>\n >>> h.insert(100)\n >>> h\n [201, 107, 25, 103, 100, 15, 1, 9, 7, 5, 11]\n >>>\n >>> h.heap_sort()\n >>> h\n [1, 5, 7, 9, 11, 15, 25, 100, 103, 107, 201]\n \"\"\"\n\n def __init__(self) -> None:\n self.h: list[T] = []\n self.heap_size: int = 0\n\n def __repr__(self) -> str:\n return str(self.h)\n\n def parent_index(self, child_idx: int) -> int | None:\n \"\"\"\n returns the parent index based on the given child index\n\n >>> h = Heap()\n >>> h.build_max_heap([103, 9, 1, 7, 11, 15, 25, 201, 209, 107, 5])\n >>> h\n [209, 201, 25, 103, 107, 15, 1, 9, 7, 11, 5]\n\n >>> h.parent_index(-1) # returns none if index is <=0\n\n >>> h.parent_index(0) # returns none if index is <=0\n\n >>> h.parent_index(1)\n 0\n >>> h.parent_index(2)\n 0\n >>> h.parent_index(3)\n 1\n >>> h.parent_index(4)\n 1\n >>> h.parent_index(5)\n 2\n >>> h.parent_index(10.5)\n 4.0\n >>> h.parent_index(209.0)\n 104.0\n >>> h.parent_index(\"Test\")\n Traceback (most recent call last):\n ...\n TypeError: '>' not supported between instances of 'str' and 'int'\n \"\"\"\n if child_idx > 0:\n return (child_idx - 1) \/\/ 2\n return None\n\n def left_child_idx(self, parent_idx: int) -> int | None:\n \"\"\"\n return the left child index if the left child exists.\n if not, return None.\n \"\"\"\n left_child_index = 2 * parent_idx + 1\n if left_child_index < self.heap_size:\n return left_child_index\n return None\n\n def right_child_idx(self, parent_idx: int) -> int | None:\n \"\"\"\n return the right child index if the right child exists.\n if not, return None.\n \"\"\"\n right_child_index = 2 * parent_idx + 2\n if right_child_index < self.heap_size:\n return right_child_index\n return None\n\n def max_heapify(self, index: int) -> None:\n \"\"\"\n correct a single violation of the heap property in a subtree's root.\n\n It is the function that is responsible for restoring the property\n of Max heap i.e the maximum element is always at top.\n \"\"\"\n if index < self.heap_size:\n violation: int = index\n left_child = self.left_child_idx(index)\n right_child = self.right_child_idx(index)\n # check which child is larger than its parent\n if left_child is not None and self.h[left_child] > self.h[violation]:\n violation = left_child\n if right_child is not None and self.h[right_child] > self.h[violation]:\n violation = right_child\n # if violation indeed exists\n if violation != index:\n # swap to fix the violation\n self.h[violation], self.h[index] = self.h[index], self.h[violation]\n # fix the subsequent violation recursively if any\n self.max_heapify(violation)\n\n def build_max_heap(self, collection: Iterable[T]) -> None:\n \"\"\"\n build max heap from an unsorted array\n\n >>> h = Heap()\n >>> h.build_max_heap([20,40,50,20,10])\n >>> h\n [50, 40, 20, 20, 10]\n\n >>> h = Heap()\n >>> h.build_max_heap([1,2,3,4,5,6,7,8,9,0])\n >>> h\n [9, 8, 7, 4, 5, 6, 3, 2, 1, 0]\n\n >>> h = Heap()\n >>> h.build_max_heap([514,5,61,57,8,99,105])\n >>> h\n [514, 57, 105, 5, 8, 99, 61]\n\n >>> h = Heap()\n >>> h.build_max_heap([514,5,61.6,57,8,9.9,105])\n >>> h\n [514, 57, 105, 5, 8, 9.9, 61.6]\n \"\"\"\n self.h = list(collection)\n self.heap_size = len(self.h)\n if self.heap_size > 1:\n # max_heapify from right to left but exclude leaves (last level)\n for i in range(self.heap_size \/\/ 2 - 1, -1, -1):\n self.max_heapify(i)\n\n def extract_max(self) -> T:\n \"\"\"\n get and remove max from heap\n\n >>> h = Heap()\n >>> h.build_max_heap([20,40,50,20,10])\n >>> h.extract_max()\n 50\n\n >>> h = Heap()\n >>> h.build_max_heap([514,5,61,57,8,99,105])\n >>> h.extract_max()\n 514\n\n >>> h = Heap()\n >>> h.build_max_heap([1,2,3,4,5,6,7,8,9,0])\n >>> h.extract_max()\n 9\n \"\"\"\n if self.heap_size >= 2:\n me = self.h[0]\n self.h[0] = self.h.pop(-1)\n self.heap_size -= 1\n self.max_heapify(0)\n return me\n elif self.heap_size == 1:\n self.heap_size -= 1\n return self.h.pop(-1)\n else:\n raise Exception(\"Empty heap\")\n\n def insert(self, value: T) -> None:\n \"\"\"\n insert a new value into the max heap\n\n >>> h = Heap()\n >>> h.insert(10)\n >>> h\n [10]\n\n >>> h = Heap()\n >>> h.insert(10)\n >>> h.insert(10)\n >>> h\n [10, 10]\n\n >>> h = Heap()\n >>> h.insert(10)\n >>> h.insert(10.1)\n >>> h\n [10.1, 10]\n\n >>> h = Heap()\n >>> h.insert(0.1)\n >>> h.insert(0)\n >>> h.insert(9)\n >>> h.insert(5)\n >>> h\n [9, 5, 0.1, 0]\n \"\"\"\n self.h.append(value)\n idx = (self.heap_size - 1) \/\/ 2\n self.heap_size += 1\n while idx >= 0:\n self.max_heapify(idx)\n idx = (idx - 1) \/\/ 2\n\n def heap_sort(self) -> None:\n size = self.heap_size\n for j in range(size - 1, 0, -1):\n self.h[0], self.h[j] = self.h[j], self.h[0]\n self.heap_size -= 1\n self.max_heapify(0)\n self.heap_size = size\n\n\nif __name__ == \"__main__\":\n import doctest\n\n # run doc test\n doctest.testmod()\n\n # demo\n for unsorted in [\n [0],\n [2],\n [3, 5],\n [5, 3],\n [5, 5],\n [0, 0, 0, 0],\n [1, 1, 1, 1],\n [2, 2, 3, 5],\n [0, 2, 2, 3, 5],\n [2, 5, 3, 0, 2, 3, 0, 3],\n [6, 1, 2, 7, 9, 3, 4, 5, 10, 8],\n [103, 9, 1, 7, 11, 15, 25, 201, 209, 107, 5],\n [-45, -2, -5],\n ]:\n print(f\"unsorted array: {unsorted}\")\n\n heap: Heap[int] = Heap()\n heap.build_max_heap(unsorted)\n print(f\"after build heap: {heap}\")\n\n print(f\"max value: {heap.extract_max()}\")\n print(f\"after max value removed: {heap}\")\n\n heap.insert(100)\n print(f\"after new value 100 inserted: {heap}\")\n\n heap.heap_sort()\n print(f\"heap-sorted array: {heap}\\n\")\n"} +{"Prompt":"A generic Heap class, can be used as min or max by passing the key function accordingly. Stores actual heap items. Stores indexes of each item for supporting updates and deletion. Stores current size of heap. Stores function used to evaluate the score of an item on which basis ordering will be done. Returns parent index of given index if exists else None return inti 1 2 if i 0 else None def leftself, i: int int None: Returns rightchildindex of given index if exists else None right int2 i 2 return right if 0 right self.size else None def swapself, i: int, j: int None: First update the indexes of the items in index map. Then swap the items in the list. Compares the two items using default comparison return self.arri1 self.arrj1 def getvalidparentself, i: int int: left self.lefti right self.righti validparent i if left is not None and not self.cmpleft, validparent: validparent left if right is not None and not self.cmpright, validparent: validparent right return validparent def heapifyupself, index: int None: Fixes the heap in downward direction of given index validparent self.getvalidparentindex while validparent ! index: self.swapindex, validparent index, validparent validparent, self.getvalidparentvalidparent def updateitemself, item: int, itemvalue: int None: Make sure heap is right in both up and down direction. Ideally only one of them will make any change. Deletes given item from heap if present if item not in self.posmap: return index self.posmapitem del self.posmapitem self.arrindex self.arrself.size 1 self.posmapself.arrself.size 10 index self.size 1 Make sure heap is right in both up and down direction. Ideally only one of them will make any change so no performance loss in calling both. if self.size index: self.heapifyupindex self.heapifydownindex def insertitemself, item: int, itemvalue: int None: Returns top item tuple Calculated value, item from heap if present return self.arr0 if self.size else None def extracttopself tuple None: topitemtuple self.gettop if topitemtuple: self.deleteitemtopitemtuple0 return topitemtuple def testheap None: if name main: import doctest doctest.testmod","Completions":"from collections.abc import Callable\n\n\nclass Heap:\n \"\"\"\n A generic Heap class, can be used as min or max by passing the key function\n accordingly.\n \"\"\"\n\n def __init__(self, key: Callable | None = None) -> None:\n # Stores actual heap items.\n self.arr: list = []\n # Stores indexes of each item for supporting updates and deletion.\n self.pos_map: dict = {}\n # Stores current size of heap.\n self.size = 0\n # Stores function used to evaluate the score of an item on which basis ordering\n # will be done.\n self.key = key or (lambda x: x)\n\n def _parent(self, i: int) -> int | None:\n \"\"\"Returns parent index of given index if exists else None\"\"\"\n return int((i - 1) \/ 2) if i > 0 else None\n\n def _left(self, i: int) -> int | None:\n \"\"\"Returns left-child-index of given index if exists else None\"\"\"\n left = int(2 * i + 1)\n return left if 0 < left < self.size else None\n\n def _right(self, i: int) -> int | None:\n \"\"\"Returns right-child-index of given index if exists else None\"\"\"\n right = int(2 * i + 2)\n return right if 0 < right < self.size else None\n\n def _swap(self, i: int, j: int) -> None:\n \"\"\"Performs changes required for swapping two elements in the heap\"\"\"\n # First update the indexes of the items in index map.\n self.pos_map[self.arr[i][0]], self.pos_map[self.arr[j][0]] = (\n self.pos_map[self.arr[j][0]],\n self.pos_map[self.arr[i][0]],\n )\n # Then swap the items in the list.\n self.arr[i], self.arr[j] = self.arr[j], self.arr[i]\n\n def _cmp(self, i: int, j: int) -> bool:\n \"\"\"Compares the two items using default comparison\"\"\"\n return self.arr[i][1] < self.arr[j][1]\n\n def _get_valid_parent(self, i: int) -> int:\n \"\"\"\n Returns index of valid parent as per desired ordering among given index and\n both it's children\n \"\"\"\n left = self._left(i)\n right = self._right(i)\n valid_parent = i\n\n if left is not None and not self._cmp(left, valid_parent):\n valid_parent = left\n if right is not None and not self._cmp(right, valid_parent):\n valid_parent = right\n\n return valid_parent\n\n def _heapify_up(self, index: int) -> None:\n \"\"\"Fixes the heap in upward direction of given index\"\"\"\n parent = self._parent(index)\n while parent is not None and not self._cmp(index, parent):\n self._swap(index, parent)\n index, parent = parent, self._parent(parent)\n\n def _heapify_down(self, index: int) -> None:\n \"\"\"Fixes the heap in downward direction of given index\"\"\"\n valid_parent = self._get_valid_parent(index)\n while valid_parent != index:\n self._swap(index, valid_parent)\n index, valid_parent = valid_parent, self._get_valid_parent(valid_parent)\n\n def update_item(self, item: int, item_value: int) -> None:\n \"\"\"Updates given item value in heap if present\"\"\"\n if item not in self.pos_map:\n return\n index = self.pos_map[item]\n self.arr[index] = [item, self.key(item_value)]\n # Make sure heap is right in both up and down direction.\n # Ideally only one of them will make any change.\n self._heapify_up(index)\n self._heapify_down(index)\n\n def delete_item(self, item: int) -> None:\n \"\"\"Deletes given item from heap if present\"\"\"\n if item not in self.pos_map:\n return\n index = self.pos_map[item]\n del self.pos_map[item]\n self.arr[index] = self.arr[self.size - 1]\n self.pos_map[self.arr[self.size - 1][0]] = index\n self.size -= 1\n # Make sure heap is right in both up and down direction. Ideally only one\n # of them will make any change- so no performance loss in calling both.\n if self.size > index:\n self._heapify_up(index)\n self._heapify_down(index)\n\n def insert_item(self, item: int, item_value: int) -> None:\n \"\"\"Inserts given item with given value in heap\"\"\"\n arr_len = len(self.arr)\n if arr_len == self.size:\n self.arr.append([item, self.key(item_value)])\n else:\n self.arr[self.size] = [item, self.key(item_value)]\n self.pos_map[item] = self.size\n self.size += 1\n self._heapify_up(self.size - 1)\n\n def get_top(self) -> tuple | None:\n \"\"\"Returns top item tuple (Calculated value, item) from heap if present\"\"\"\n return self.arr[0] if self.size else None\n\n def extract_top(self) -> tuple | None:\n \"\"\"\n Return top item tuple (Calculated value, item) from heap and removes it as well\n if present\n \"\"\"\n top_item_tuple = self.get_top()\n if top_item_tuple:\n self.delete_item(top_item_tuple[0])\n return top_item_tuple\n\n\ndef test_heap() -> None:\n \"\"\"\n >>> h = Heap() # Max-heap\n >>> h.insert_item(5, 34)\n >>> h.insert_item(6, 31)\n >>> h.insert_item(7, 37)\n >>> h.get_top()\n [7, 37]\n >>> h.extract_top()\n [7, 37]\n >>> h.extract_top()\n [5, 34]\n >>> h.extract_top()\n [6, 31]\n >>> h = Heap(key=lambda x: -x) # Min heap\n >>> h.insert_item(5, 34)\n >>> h.insert_item(6, 31)\n >>> h.insert_item(7, 37)\n >>> h.get_top()\n [6, -31]\n >>> h.extract_top()\n [6, -31]\n >>> h.extract_top()\n [5, -34]\n >>> h.extract_top()\n [7, -37]\n >>> h.insert_item(8, 45)\n >>> h.insert_item(9, 40)\n >>> h.insert_item(10, 50)\n >>> h.get_top()\n [9, -40]\n >>> h.update_item(10, 30)\n >>> h.get_top()\n [10, -30]\n >>> h.delete_item(10)\n >>> h.get_top()\n [9, -40]\n \"\"\"\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"A maxheap implementation in Python binaryheap BinaryHeap binaryheap.insert6 binaryheap.insert10 binaryheap.insert15 binaryheap.insert12 binaryheap.pop 15 binaryheap.pop 12 binaryheap.getlist 10, 6 lenbinaryheap 2 Swap the element up temporary self.heapi while i 2 0: if self.heapi self.heapi 2: self.heapi self.heapi 2 self.heapi 2 temporary i 2 def insertself, value: int None: Swap the element down while self.size 2 i: if 2 i 1 self.size: biggerchild 2 i else: if self.heap2 i self.heap2 i 1: biggerchild 2 i else: biggerchild 2 i 1 temporary self.heapi if self.heapi self.heapbiggerchild: self.heapi self.heapbiggerchild self.heapbiggerchild temporary i biggerchild def popself int: Length of the array return self.size if name main: import doctest doctest.testmod create an instance of BinaryHeap binaryheap BinaryHeap binaryheap.insert6 binaryheap.insert10 binaryheap.insert15 binaryheap.insert12 pop rootmaxvalues because it is max heap printbinaryheap.pop 15 printbinaryheap.pop 12 get the list and size after operations printbinaryheap.getlist printlenbinaryheap","Completions":"class BinaryHeap:\n \"\"\"\n A max-heap implementation in Python\n >>> binary_heap = BinaryHeap()\n >>> binary_heap.insert(6)\n >>> binary_heap.insert(10)\n >>> binary_heap.insert(15)\n >>> binary_heap.insert(12)\n >>> binary_heap.pop()\n 15\n >>> binary_heap.pop()\n 12\n >>> binary_heap.get_list\n [10, 6]\n >>> len(binary_heap)\n 2\n \"\"\"\n\n def __init__(self):\n self.__heap = [0]\n self.__size = 0\n\n def __swap_up(self, i: int) -> None:\n \"\"\"Swap the element up\"\"\"\n temporary = self.__heap[i]\n while i \/\/ 2 > 0:\n if self.__heap[i] > self.__heap[i \/\/ 2]:\n self.__heap[i] = self.__heap[i \/\/ 2]\n self.__heap[i \/\/ 2] = temporary\n i \/\/= 2\n\n def insert(self, value: int) -> None:\n \"\"\"Insert new element\"\"\"\n self.__heap.append(value)\n self.__size += 1\n self.__swap_up(self.__size)\n\n def __swap_down(self, i: int) -> None:\n \"\"\"Swap the element down\"\"\"\n while self.__size >= 2 * i:\n if 2 * i + 1 > self.__size:\n bigger_child = 2 * i\n else:\n if self.__heap[2 * i] > self.__heap[2 * i + 1]:\n bigger_child = 2 * i\n else:\n bigger_child = 2 * i + 1\n temporary = self.__heap[i]\n if self.__heap[i] < self.__heap[bigger_child]:\n self.__heap[i] = self.__heap[bigger_child]\n self.__heap[bigger_child] = temporary\n i = bigger_child\n\n def pop(self) -> int:\n \"\"\"Pop the root element\"\"\"\n max_value = self.__heap[1]\n self.__heap[1] = self.__heap[self.__size]\n self.__size -= 1\n self.__heap.pop()\n self.__swap_down(1)\n return max_value\n\n @property\n def get_list(self):\n return self.__heap[1:]\n\n def __len__(self):\n \"\"\"Length of the array\"\"\"\n return self.__size\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n # create an instance of BinaryHeap\n binary_heap = BinaryHeap()\n binary_heap.insert(6)\n binary_heap.insert(10)\n binary_heap.insert(15)\n binary_heap.insert(12)\n # pop root(max-values because it is max heap)\n print(binary_heap.pop()) # 15\n print(binary_heap.pop()) # 12\n # get the list and size after operations\n print(binary_heap.get_list)\n print(len(binary_heap))\n"} +{"Prompt":"Min heap data structure with decrease key functionality in Ologn time r NodeR, 1 b NodeB, 6 a NodeA, 3 x NodeX, 1 e NodeE, 4 printb NodeB, 6 myMinHeap MinHeapr, b, a, x, e myMinHeap.decreasekeyb, 17 printb NodeB, 17 myMinHeapB 17 this is minheapify method USAGE Use one of these two ways to generate MinHeap Generating MinHeap from array Generating MinHeap by Insert method myMinHeap.inserta myMinHeap.insertb myMinHeap.insertx myMinHeap.insertr myMinHeap.inserte Before After","Completions":"# Min heap data structure\n# with decrease key functionality - in O(log(n)) time\n\n\nclass Node:\n def __init__(self, name, val):\n self.name = name\n self.val = val\n\n def __str__(self):\n return f\"{self.__class__.__name__}({self.name}, {self.val})\"\n\n def __lt__(self, other):\n return self.val < other.val\n\n\nclass MinHeap:\n \"\"\"\n >>> r = Node(\"R\", -1)\n >>> b = Node(\"B\", 6)\n >>> a = Node(\"A\", 3)\n >>> x = Node(\"X\", 1)\n >>> e = Node(\"E\", 4)\n >>> print(b)\n Node(B, 6)\n >>> myMinHeap = MinHeap([r, b, a, x, e])\n >>> myMinHeap.decrease_key(b, -17)\n >>> print(b)\n Node(B, -17)\n >>> myMinHeap[\"B\"]\n -17\n \"\"\"\n\n def __init__(self, array):\n self.idx_of_element = {}\n self.heap_dict = {}\n self.heap = self.build_heap(array)\n\n def __getitem__(self, key):\n return self.get_value(key)\n\n def get_parent_idx(self, idx):\n return (idx - 1) \/\/ 2\n\n def get_left_child_idx(self, idx):\n return idx * 2 + 1\n\n def get_right_child_idx(self, idx):\n return idx * 2 + 2\n\n def get_value(self, key):\n return self.heap_dict[key]\n\n def build_heap(self, array):\n last_idx = len(array) - 1\n start_from = self.get_parent_idx(last_idx)\n\n for idx, i in enumerate(array):\n self.idx_of_element[i] = idx\n self.heap_dict[i.name] = i.val\n\n for i in range(start_from, -1, -1):\n self.sift_down(i, array)\n return array\n\n # this is min-heapify method\n def sift_down(self, idx, array):\n while True:\n l = self.get_left_child_idx(idx) # noqa: E741\n r = self.get_right_child_idx(idx)\n\n smallest = idx\n if l < len(array) and array[l] < array[idx]:\n smallest = l\n if r < len(array) and array[r] < array[smallest]:\n smallest = r\n\n if smallest != idx:\n array[idx], array[smallest] = array[smallest], array[idx]\n (\n self.idx_of_element[array[idx]],\n self.idx_of_element[array[smallest]],\n ) = (\n self.idx_of_element[array[smallest]],\n self.idx_of_element[array[idx]],\n )\n idx = smallest\n else:\n break\n\n def sift_up(self, idx):\n p = self.get_parent_idx(idx)\n while p >= 0 and self.heap[p] > self.heap[idx]:\n self.heap[p], self.heap[idx] = self.heap[idx], self.heap[p]\n self.idx_of_element[self.heap[p]], self.idx_of_element[self.heap[idx]] = (\n self.idx_of_element[self.heap[idx]],\n self.idx_of_element[self.heap[p]],\n )\n idx = p\n p = self.get_parent_idx(idx)\n\n def peek(self):\n return self.heap[0]\n\n def remove(self):\n self.heap[0], self.heap[-1] = self.heap[-1], self.heap[0]\n self.idx_of_element[self.heap[0]], self.idx_of_element[self.heap[-1]] = (\n self.idx_of_element[self.heap[-1]],\n self.idx_of_element[self.heap[0]],\n )\n\n x = self.heap.pop()\n del self.idx_of_element[x]\n self.sift_down(0, self.heap)\n return x\n\n def insert(self, node):\n self.heap.append(node)\n self.idx_of_element[node] = len(self.heap) - 1\n self.heap_dict[node.name] = node.val\n self.sift_up(len(self.heap) - 1)\n\n def is_empty(self):\n return len(self.heap) == 0\n\n def decrease_key(self, node, new_value):\n assert (\n self.heap[self.idx_of_element[node]].val > new_value\n ), \"newValue must be less that current value\"\n node.val = new_value\n self.heap_dict[node.name] = new_value\n self.sift_up(self.idx_of_element[node])\n\n\n# USAGE\n\nr = Node(\"R\", -1)\nb = Node(\"B\", 6)\na = Node(\"A\", 3)\nx = Node(\"X\", 1)\ne = Node(\"E\", 4)\n\n# Use one of these two ways to generate Min-Heap\n\n# Generating Min-Heap from array\nmy_min_heap = MinHeap([r, b, a, x, e])\n\n# Generating Min-Heap by Insert method\n# myMinHeap.insert(a)\n# myMinHeap.insert(b)\n# myMinHeap.insert(x)\n# myMinHeap.insert(r)\n# myMinHeap.insert(e)\n\n# Before\nprint(\"Min Heap - before decrease key\")\nfor i in my_min_heap.heap:\n print(i)\n\nprint(\"Min Heap - After decrease key of node [B -> -17]\")\nmy_min_heap.decrease_key(b, -17)\n\n# After\nfor i in my_min_heap.heap:\n print(i)\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"!usrbinenv python3 One node of the randomized heap. Contains the value and references to two children. Return the value of the node. rhn RandomizedHeapNode10 rhn.value 10 rhn RandomizedHeapNode10 rhn.value 10 Merge 2 nodes together. rhn1 RandomizedHeapNode10 rhn2 RandomizedHeapNode20 RandomizedHeapNode.mergerhn1, rhn2.value 10 rhn1 RandomizedHeapNode20 rhn2 RandomizedHeapNode10 RandomizedHeapNode.mergerhn1, rhn2.value 10 rhn1 RandomizedHeapNode5 rhn2 RandomizedHeapNode0 RandomizedHeapNode.mergerhn1, rhn2.value 0 A data structure that allows inserting a new value and to pop the smallest values. Both operations take OlogN time where N is the size of the structure. Wiki: https:en.wikipedia.orgwikiRandomizedmeldableheap RandomizedHeap2, 3, 1, 5, 1, 7.tosortedlist 1, 1, 2, 3, 5, 7 rh RandomizedHeap rh.pop Traceback most recent call last: ... IndexError: Can't get top element for the empty heap. rh.insert1 rh.insert1 rh.insert0 rh.tosortedlist 1, 0, 1 rh RandomizedHeap3, 1, 3, 7 rh.tosortedlist 1, 3, 3, 7 Insert the value into the heap. rh RandomizedHeap rh.insert3 rh.insert1 rh.insert3 rh.insert7 rh.tosortedlist 1, 3, 3, 7 Pop the smallest value from the heap and return it. rh RandomizedHeap3, 1, 3, 7 rh.pop 1 rh.pop 3 rh.pop 3 rh.pop 7 rh.pop Traceback most recent call last: ... IndexError: Can't get top element for the empty heap. Return the smallest value from the heap. rh RandomizedHeap rh.insert3 rh.top 3 rh.insert1 rh.top 1 rh.insert3 rh.top 1 rh.insert7 rh.top 1 Clear the heap. rh RandomizedHeap3, 1, 3, 7 rh.clear rh.pop Traceback most recent call last: ... IndexError: Can't get top element for the empty heap. Returns sorted list containing all the values in the heap. rh RandomizedHeap3, 1, 3, 7 rh.tosortedlist 1, 3, 3, 7 Check if the heap is not empty. rh RandomizedHeap boolrh False rh.insert1 boolrh True rh.clear boolrh False","Completions":"#!\/usr\/bin\/env python3\n\nfrom __future__ import annotations\n\nimport random\nfrom collections.abc import Iterable\nfrom typing import Any, Generic, TypeVar\n\nT = TypeVar(\"T\", bound=bool)\n\n\nclass RandomizedHeapNode(Generic[T]):\n \"\"\"\n One node of the randomized heap. Contains the value and references to\n two children.\n \"\"\"\n\n def __init__(self, value: T) -> None:\n self._value: T = value\n self.left: RandomizedHeapNode[T] | None = None\n self.right: RandomizedHeapNode[T] | None = None\n\n @property\n def value(self) -> T:\n \"\"\"\n Return the value of the node.\n\n >>> rhn = RandomizedHeapNode(10)\n >>> rhn.value\n 10\n >>> rhn = RandomizedHeapNode(-10)\n >>> rhn.value\n -10\n \"\"\"\n return self._value\n\n @staticmethod\n def merge(\n root1: RandomizedHeapNode[T] | None, root2: RandomizedHeapNode[T] | None\n ) -> RandomizedHeapNode[T] | None:\n \"\"\"\n Merge 2 nodes together.\n\n >>> rhn1 = RandomizedHeapNode(10)\n >>> rhn2 = RandomizedHeapNode(20)\n >>> RandomizedHeapNode.merge(rhn1, rhn2).value\n 10\n\n >>> rhn1 = RandomizedHeapNode(20)\n >>> rhn2 = RandomizedHeapNode(10)\n >>> RandomizedHeapNode.merge(rhn1, rhn2).value\n 10\n\n >>> rhn1 = RandomizedHeapNode(5)\n >>> rhn2 = RandomizedHeapNode(0)\n >>> RandomizedHeapNode.merge(rhn1, rhn2).value\n 0\n \"\"\"\n if not root1:\n return root2\n\n if not root2:\n return root1\n\n if root1.value > root2.value:\n root1, root2 = root2, root1\n\n if random.choice([True, False]):\n root1.left, root1.right = root1.right, root1.left\n\n root1.left = RandomizedHeapNode.merge(root1.left, root2)\n\n return root1\n\n\nclass RandomizedHeap(Generic[T]):\n \"\"\"\n A data structure that allows inserting a new value and to pop the smallest\n values. Both operations take O(logN) time where N is the size of the\n structure.\n Wiki: https:\/\/en.wikipedia.org\/wiki\/Randomized_meldable_heap\n\n >>> RandomizedHeap([2, 3, 1, 5, 1, 7]).to_sorted_list()\n [1, 1, 2, 3, 5, 7]\n\n >>> rh = RandomizedHeap()\n >>> rh.pop()\n Traceback (most recent call last):\n ...\n IndexError: Can't get top element for the empty heap.\n\n >>> rh.insert(1)\n >>> rh.insert(-1)\n >>> rh.insert(0)\n >>> rh.to_sorted_list()\n [-1, 0, 1]\n \"\"\"\n\n def __init__(self, data: Iterable[T] | None = ()) -> None:\n \"\"\"\n >>> rh = RandomizedHeap([3, 1, 3, 7])\n >>> rh.to_sorted_list()\n [1, 3, 3, 7]\n \"\"\"\n self._root: RandomizedHeapNode[T] | None = None\n\n if data:\n for item in data:\n self.insert(item)\n\n def insert(self, value: T) -> None:\n \"\"\"\n Insert the value into the heap.\n\n >>> rh = RandomizedHeap()\n >>> rh.insert(3)\n >>> rh.insert(1)\n >>> rh.insert(3)\n >>> rh.insert(7)\n >>> rh.to_sorted_list()\n [1, 3, 3, 7]\n \"\"\"\n self._root = RandomizedHeapNode.merge(self._root, RandomizedHeapNode(value))\n\n def pop(self) -> T | None:\n \"\"\"\n Pop the smallest value from the heap and return it.\n\n >>> rh = RandomizedHeap([3, 1, 3, 7])\n >>> rh.pop()\n 1\n >>> rh.pop()\n 3\n >>> rh.pop()\n 3\n >>> rh.pop()\n 7\n >>> rh.pop()\n Traceback (most recent call last):\n ...\n IndexError: Can't get top element for the empty heap.\n \"\"\"\n\n result = self.top()\n\n if self._root is None:\n return None\n\n self._root = RandomizedHeapNode.merge(self._root.left, self._root.right)\n\n return result\n\n def top(self) -> T:\n \"\"\"\n Return the smallest value from the heap.\n\n >>> rh = RandomizedHeap()\n >>> rh.insert(3)\n >>> rh.top()\n 3\n >>> rh.insert(1)\n >>> rh.top()\n 1\n >>> rh.insert(3)\n >>> rh.top()\n 1\n >>> rh.insert(7)\n >>> rh.top()\n 1\n \"\"\"\n if not self._root:\n raise IndexError(\"Can't get top element for the empty heap.\")\n return self._root.value\n\n def clear(self) -> None:\n \"\"\"\n Clear the heap.\n\n >>> rh = RandomizedHeap([3, 1, 3, 7])\n >>> rh.clear()\n >>> rh.pop()\n Traceback (most recent call last):\n ...\n IndexError: Can't get top element for the empty heap.\n \"\"\"\n self._root = None\n\n def to_sorted_list(self) -> list[Any]:\n \"\"\"\n Returns sorted list containing all the values in the heap.\n\n >>> rh = RandomizedHeap([3, 1, 3, 7])\n >>> rh.to_sorted_list()\n [1, 3, 3, 7]\n \"\"\"\n result = []\n while self:\n result.append(self.pop())\n\n return result\n\n def __bool__(self) -> bool:\n \"\"\"\n Check if the heap is not empty.\n\n >>> rh = RandomizedHeap()\n >>> bool(rh)\n False\n >>> rh.insert(1)\n >>> bool(rh)\n True\n >>> rh.clear()\n >>> bool(rh)\n False\n \"\"\"\n return self._root is not None\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"!usrbinenv python3 One node of the skew heap. Contains the value and references to two children. Return the value of the node. return self.value staticmethod def merge root1: SkewNodeT None, root2: SkewNodeT None SkewNodeT None: A data structure that allows inserting a new value and to pop the smallest values. Both operations take OlogN time where N is the size of the structure. Wiki: https:en.wikipedia.orgwikiSkewheap Visualization: https:www.cs.usfca.edugallesvisualizationSkewHeap.html listSkewHeap2, 3, 1, 5, 1, 7 1, 1, 2, 3, 5, 7 sh SkewHeap sh.pop Traceback most recent call last: ... IndexError: Can't get top element for the empty heap. sh.insert1 sh.insert1 sh.insert0 listsh 1, 0, 1 sh SkewHeap3, 1, 3, 7 listsh 1, 3, 3, 7 Check if the heap is not empty. sh SkewHeap boolsh False sh.insert1 boolsh True sh.clear boolsh False Returns sorted list containing all the values in the heap. sh SkewHeap3, 1, 3, 7 listsh 1, 3, 3, 7 Pushing items back to the heap not to clear it. Insert the value into the heap. sh SkewHeap sh.insert3 sh.insert1 sh.insert3 sh.insert7 listsh 1, 3, 3, 7 Pop the smallest value from the heap and return it. sh SkewHeap3, 1, 3, 7 sh.pop 1 sh.pop 3 sh.pop 3 sh.pop 7 sh.pop Traceback most recent call last: ... IndexError: Can't get top element for the empty heap. Return the smallest value from the heap. sh SkewHeap sh.insert3 sh.top 3 sh.insert1 sh.top 1 sh.insert3 sh.top 1 sh.insert7 sh.top 1 Clear the heap. sh SkewHeap3, 1, 3, 7 sh.clear sh.pop Traceback most recent call last: ... IndexError: Can't get top element for the empty heap.","Completions":"#!\/usr\/bin\/env python3\n\nfrom __future__ import annotations\n\nfrom collections.abc import Iterable, Iterator\nfrom typing import Any, Generic, TypeVar\n\nT = TypeVar(\"T\", bound=bool)\n\n\nclass SkewNode(Generic[T]):\n \"\"\"\n One node of the skew heap. Contains the value and references to\n two children.\n \"\"\"\n\n def __init__(self, value: T) -> None:\n self._value: T = value\n self.left: SkewNode[T] | None = None\n self.right: SkewNode[T] | None = None\n\n @property\n def value(self) -> T:\n \"\"\"Return the value of the node.\"\"\"\n return self._value\n\n @staticmethod\n def merge(\n root1: SkewNode[T] | None, root2: SkewNode[T] | None\n ) -> SkewNode[T] | None:\n \"\"\"Merge 2 nodes together.\"\"\"\n if not root1:\n return root2\n\n if not root2:\n return root1\n\n if root1.value > root2.value:\n root1, root2 = root2, root1\n\n result = root1\n temp = root1.right\n result.right = root1.left\n result.left = SkewNode.merge(temp, root2)\n\n return result\n\n\nclass SkewHeap(Generic[T]):\n \"\"\"\n A data structure that allows inserting a new value and to pop the smallest\n values. Both operations take O(logN) time where N is the size of the\n structure.\n Wiki: https:\/\/en.wikipedia.org\/wiki\/Skew_heap\n Visualization: https:\/\/www.cs.usfca.edu\/~galles\/visualization\/SkewHeap.html\n\n >>> list(SkewHeap([2, 3, 1, 5, 1, 7]))\n [1, 1, 2, 3, 5, 7]\n\n >>> sh = SkewHeap()\n >>> sh.pop()\n Traceback (most recent call last):\n ...\n IndexError: Can't get top element for the empty heap.\n\n >>> sh.insert(1)\n >>> sh.insert(-1)\n >>> sh.insert(0)\n >>> list(sh)\n [-1, 0, 1]\n \"\"\"\n\n def __init__(self, data: Iterable[T] | None = ()) -> None:\n \"\"\"\n >>> sh = SkewHeap([3, 1, 3, 7])\n >>> list(sh)\n [1, 3, 3, 7]\n \"\"\"\n self._root: SkewNode[T] | None = None\n if data:\n for item in data:\n self.insert(item)\n\n def __bool__(self) -> bool:\n \"\"\"\n Check if the heap is not empty.\n\n >>> sh = SkewHeap()\n >>> bool(sh)\n False\n >>> sh.insert(1)\n >>> bool(sh)\n True\n >>> sh.clear()\n >>> bool(sh)\n False\n \"\"\"\n return self._root is not None\n\n def __iter__(self) -> Iterator[T]:\n \"\"\"\n Returns sorted list containing all the values in the heap.\n\n >>> sh = SkewHeap([3, 1, 3, 7])\n >>> list(sh)\n [1, 3, 3, 7]\n \"\"\"\n result: list[Any] = []\n while self:\n result.append(self.pop())\n\n # Pushing items back to the heap not to clear it.\n for item in result:\n self.insert(item)\n\n return iter(result)\n\n def insert(self, value: T) -> None:\n \"\"\"\n Insert the value into the heap.\n\n >>> sh = SkewHeap()\n >>> sh.insert(3)\n >>> sh.insert(1)\n >>> sh.insert(3)\n >>> sh.insert(7)\n >>> list(sh)\n [1, 3, 3, 7]\n \"\"\"\n self._root = SkewNode.merge(self._root, SkewNode(value))\n\n def pop(self) -> T | None:\n \"\"\"\n Pop the smallest value from the heap and return it.\n\n >>> sh = SkewHeap([3, 1, 3, 7])\n >>> sh.pop()\n 1\n >>> sh.pop()\n 3\n >>> sh.pop()\n 3\n >>> sh.pop()\n 7\n >>> sh.pop()\n Traceback (most recent call last):\n ...\n IndexError: Can't get top element for the empty heap.\n \"\"\"\n result = self.top()\n self._root = (\n SkewNode.merge(self._root.left, self._root.right) if self._root else None\n )\n\n return result\n\n def top(self) -> T:\n \"\"\"\n Return the smallest value from the heap.\n\n >>> sh = SkewHeap()\n >>> sh.insert(3)\n >>> sh.top()\n 3\n >>> sh.insert(1)\n >>> sh.top()\n 1\n >>> sh.insert(3)\n >>> sh.top()\n 1\n >>> sh.insert(7)\n >>> sh.top()\n 1\n \"\"\"\n if not self._root:\n raise IndexError(\"Can't get top element for the empty heap.\")\n return self._root.value\n\n def clear(self) -> None:\n \"\"\"\n Clear the heap.\n\n >>> sh = SkewHeap([3, 1, 3, 7])\n >>> sh.clear()\n >>> sh.pop()\n Traceback (most recent call last):\n ...\n IndexError: Can't get top element for the empty heap.\n \"\"\"\n self._root = None\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Linked Lists consists of Nodes. Nodes contain data and also may link to other nodes: Head Node: First node, the address of the head node gives us access of the complete list Last node: points to null Add an item to the LinkedList at the specified position. Default position is 0 the head. Args: item Any: The item to add to the LinkedList. position int, optional: The position at which to add the item. Defaults to 0. Raises: ValueError: If the position is negative or out of bounds. linkedlist LinkedList linkedlist.add1 linkedlist.add2 linkedlist.add3 linkedlist.add4, 2 printlinkedlist 3 2 4 1 Test adding to a negative position linkedlist.add5, 3 Traceback most recent call last: ... ValueError: Position must be nonnegative Test adding to an outofbounds position linkedlist.add5,7 Traceback most recent call last: ... ValueError: Out of bounds linkedlist.add5, 4 printlinkedlist 3 2 4 1 5 Switched 'self.isempty' to 'self.head is None' because mypy was considering the possibility that 'self.head' can be None in below else part and giving error linkedlist LinkedList linkedlist.add23 linkedlist.add14 linkedlist.add9 printlinkedlist 9 14 23 linkedlist LinkedList lenlinkedlist 0 linkedlist.adda lenlinkedlist 1 linkedlist.addb lenlinkedlist 2 linkedlist.remove lenlinkedlist 1 linkedlist.remove lenlinkedlist 0","Completions":"from __future__ import annotations\n\nfrom typing import Any\n\n\nclass Node:\n def __init__(self, item: Any, next: Any) -> None: # noqa: A002\n self.item = item\n self.next = next\n\n\nclass LinkedList:\n def __init__(self) -> None:\n self.head: Node | None = None\n self.size = 0\n\n def add(self, item: Any, position: int = 0) -> None:\n \"\"\"\n Add an item to the LinkedList at the specified position.\n Default position is 0 (the head).\n\n Args:\n item (Any): The item to add to the LinkedList.\n position (int, optional): The position at which to add the item.\n Defaults to 0.\n\n Raises:\n ValueError: If the position is negative or out of bounds.\n\n >>> linked_list = LinkedList()\n >>> linked_list.add(1)\n >>> linked_list.add(2)\n >>> linked_list.add(3)\n >>> linked_list.add(4, 2)\n >>> print(linked_list)\n 3 --> 2 --> 4 --> 1\n\n # Test adding to a negative position\n >>> linked_list.add(5, -3)\n Traceback (most recent call last):\n ...\n ValueError: Position must be non-negative\n\n # Test adding to an out-of-bounds position\n >>> linked_list.add(5,7)\n Traceback (most recent call last):\n ...\n ValueError: Out of bounds\n >>> linked_list.add(5, 4)\n >>> print(linked_list)\n 3 --> 2 --> 4 --> 1 --> 5\n \"\"\"\n if position < 0:\n raise ValueError(\"Position must be non-negative\")\n\n if position == 0 or self.head is None:\n new_node = Node(item, self.head)\n self.head = new_node\n else:\n current = self.head\n for _ in range(position - 1):\n current = current.next\n if current is None:\n raise ValueError(\"Out of bounds\")\n new_node = Node(item, current.next)\n current.next = new_node\n self.size += 1\n\n def remove(self) -> Any:\n # Switched 'self.is_empty()' to 'self.head is None'\n # because mypy was considering the possibility that 'self.head'\n # can be None in below else part and giving error\n if self.head is None:\n return None\n else:\n item = self.head.item\n self.head = self.head.next\n self.size -= 1\n return item\n\n def is_empty(self) -> bool:\n return self.head is None\n\n def __str__(self) -> str:\n \"\"\"\n >>> linked_list = LinkedList()\n >>> linked_list.add(23)\n >>> linked_list.add(14)\n >>> linked_list.add(9)\n >>> print(linked_list)\n 9 --> 14 --> 23\n \"\"\"\n if self.is_empty():\n return \"\"\n else:\n iterate = self.head\n item_str = \"\"\n item_list: list[str] = []\n while iterate:\n item_list.append(str(iterate.item))\n iterate = iterate.next\n\n item_str = \" --> \".join(item_list)\n\n return item_str\n\n def __len__(self) -> int:\n \"\"\"\n >>> linked_list = LinkedList()\n >>> len(linked_list)\n 0\n >>> linked_list.add(\"a\")\n >>> len(linked_list)\n 1\n >>> linked_list.add(\"b\")\n >>> len(linked_list)\n 2\n >>> _ = linked_list.remove()\n >>> len(linked_list)\n 1\n >>> _ = linked_list.remove()\n >>> len(linked_list)\n 0\n \"\"\"\n return self.size\n"} +{"Prompt":"Iterate through all nodes in the Circular Linked List yielding their data. Yields: The data of each node in the linked list. Get the length number of nodes in the Circular Linked List. Generate a string representation of the Circular Linked List. Returns: A string of the format 12....N. Insert a node with the given data at the end of the Circular Linked List. Insert a node with the given data at the beginning of the Circular Linked List. Insert the data of the node at the nth pos in the Circular Linked List. Args: index: The index at which the data should be inserted. data: The data to be inserted. Raises: IndexError: If the index is out of range. Delete and return the data of the node at the front of the Circular Linked List. Raises: IndexError: If the list is empty. Delete and return the data of the node at the end of the Circular Linked List. Returns: Any: The data of the deleted node. Raises: IndexError: If the index is out of range. Delete and return the data of the node at the nth pos in Circular Linked List. Args: index int: The index of the node to be deleted. Defaults to 0. Returns: Any: The data of the deleted node. Raises: IndexError: If the index is out of range. Check if the Circular Linked List is empty. Returns: bool: True if the list is empty, False otherwise. Test cases for the CircularLinkedList class. testcircularlinkedlist","Completions":"from __future__ import annotations\n\nfrom collections.abc import Iterator\nfrom dataclasses import dataclass\nfrom typing import Any\n\n\n@dataclass\nclass Node:\n data: Any\n next_node: Node | None = None\n\n\n@dataclass\nclass CircularLinkedList:\n head: Node | None = None # Reference to the head (first node)\n tail: Node | None = None # Reference to the tail (last node)\n\n def __iter__(self) -> Iterator[Any]:\n \"\"\"\n Iterate through all nodes in the Circular Linked List yielding their data.\n Yields:\n The data of each node in the linked list.\n \"\"\"\n node = self.head\n while node:\n yield node.data\n node = node.next_node\n if node == self.head:\n break\n\n def __len__(self) -> int:\n \"\"\"\n Get the length (number of nodes) in the Circular Linked List.\n \"\"\"\n return sum(1 for _ in self)\n\n def __repr__(self) -> str:\n \"\"\"\n Generate a string representation of the Circular Linked List.\n Returns:\n A string of the format \"1->2->....->N\".\n \"\"\"\n return \"->\".join(str(item) for item in iter(self))\n\n def insert_tail(self, data: Any) -> None:\n \"\"\"\n Insert a node with the given data at the end of the Circular Linked List.\n \"\"\"\n self.insert_nth(len(self), data)\n\n def insert_head(self, data: Any) -> None:\n \"\"\"\n Insert a node with the given data at the beginning of the Circular Linked List.\n \"\"\"\n self.insert_nth(0, data)\n\n def insert_nth(self, index: int, data: Any) -> None:\n \"\"\"\n Insert the data of the node at the nth pos in the Circular Linked List.\n Args:\n index: The index at which the data should be inserted.\n data: The data to be inserted.\n\n Raises:\n IndexError: If the index is out of range.\n \"\"\"\n if index < 0 or index > len(self):\n raise IndexError(\"list index out of range.\")\n new_node: Node = Node(data)\n if self.head is None:\n new_node.next_node = new_node # First node points to itself\n self.tail = self.head = new_node\n elif index == 0: # Insert at the head\n new_node.next_node = self.head\n assert self.tail is not None # List is not empty, tail exists\n self.head = self.tail.next_node = new_node\n else:\n temp: Node | None = self.head\n for _ in range(index - 1):\n assert temp is not None\n temp = temp.next_node\n assert temp is not None\n new_node.next_node = temp.next_node\n temp.next_node = new_node\n if index == len(self) - 1: # Insert at the tail\n self.tail = new_node\n\n def delete_front(self) -> Any:\n \"\"\"\n Delete and return the data of the node at the front of the Circular Linked List.\n Raises:\n IndexError: If the list is empty.\n \"\"\"\n return self.delete_nth(0)\n\n def delete_tail(self) -> Any:\n \"\"\"\n Delete and return the data of the node at the end of the Circular Linked List.\n Returns:\n Any: The data of the deleted node.\n Raises:\n IndexError: If the index is out of range.\n \"\"\"\n return self.delete_nth(len(self) - 1)\n\n def delete_nth(self, index: int = 0) -> Any:\n \"\"\"\n Delete and return the data of the node at the nth pos in Circular Linked List.\n Args:\n index (int): The index of the node to be deleted. Defaults to 0.\n Returns:\n Any: The data of the deleted node.\n Raises:\n IndexError: If the index is out of range.\n \"\"\"\n if not 0 <= index < len(self):\n raise IndexError(\"list index out of range.\")\n\n assert self.head is not None\n assert self.tail is not None\n delete_node: Node = self.head\n if self.head == self.tail: # Just one node\n self.head = self.tail = None\n elif index == 0: # Delete head node\n assert self.tail.next_node is not None\n self.tail.next_node = self.tail.next_node.next_node\n self.head = self.head.next_node\n else:\n temp: Node | None = self.head\n for _ in range(index - 1):\n assert temp is not None\n temp = temp.next_node\n assert temp is not None\n assert temp.next_node is not None\n delete_node = temp.next_node\n temp.next_node = temp.next_node.next_node\n if index == len(self) - 1: # Delete at tail\n self.tail = temp\n return delete_node.data\n\n def is_empty(self) -> bool:\n \"\"\"\n Check if the Circular Linked List is empty.\n Returns:\n bool: True if the list is empty, False otherwise.\n \"\"\"\n return len(self) == 0\n\n\ndef test_circular_linked_list() -> None:\n \"\"\"\n Test cases for the CircularLinkedList class.\n >>> test_circular_linked_list()\n \"\"\"\n circular_linked_list = CircularLinkedList()\n assert len(circular_linked_list) == 0\n assert circular_linked_list.is_empty() is True\n assert str(circular_linked_list) == \"\"\n\n try:\n circular_linked_list.delete_front()\n raise AssertionError # This should not happen\n except IndexError:\n assert True # This should happen\n\n try:\n circular_linked_list.delete_tail()\n raise AssertionError # This should not happen\n except IndexError:\n assert True # This should happen\n\n try:\n circular_linked_list.delete_nth(-1)\n raise AssertionError\n except IndexError:\n assert True\n\n try:\n circular_linked_list.delete_nth(0)\n raise AssertionError\n except IndexError:\n assert True\n\n assert circular_linked_list.is_empty() is True\n for i in range(5):\n assert len(circular_linked_list) == i\n circular_linked_list.insert_nth(i, i + 1)\n assert str(circular_linked_list) == \"->\".join(str(i) for i in range(1, 6))\n\n circular_linked_list.insert_tail(6)\n assert str(circular_linked_list) == \"->\".join(str(i) for i in range(1, 7))\n circular_linked_list.insert_head(0)\n assert str(circular_linked_list) == \"->\".join(str(i) for i in range(7))\n\n assert circular_linked_list.delete_front() == 0\n assert circular_linked_list.delete_tail() == 6\n assert str(circular_linked_list) == \"->\".join(str(i) for i in range(1, 6))\n assert circular_linked_list.delete_nth(2) == 3\n\n circular_linked_list.insert_nth(2, 3)\n assert str(circular_linked_list) == \"->\".join(str(i) for i in range(1, 6))\n\n assert circular_linked_list.is_empty() is False\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Implementing Deque using DoublyLinkedList ... Operations: 1. insertion in the front O1 2. insertion in the end O1 3. remove from the front O1 4. remove from the end O1 A Private class to be inherited class Node: slots prev, data, next def initself, linkp, element, linkn: self.prev linkp self.data element self.next linkn def hasnextandprevself: return f Prev self.prev is not None, Next self.next is not None def initself: self.header self.NodeNone, None, None self.trailer self.NodeNone, None, None self.header.next self.trailer self.trailer.prev self.header self.size 0 def lenself: return self.size def isemptyself: return self.len 0 def insertself, predecessor, e, successor: Create newnode by setting it's prev.link header setting it's next.link trailer newnode self.Nodepredecessor, e, successor predecessor.next newnode successor.prev newnode self.size 1 return self def deleteself, node: predecessor node.prev successor node.next predecessor.next successor successor.prev predecessor self.size 1 temp node.data node.prev node.next node.data None del node return temp class LinkedDequeDoublyLinkedBase: def firstself: if self.isempty: raise ExceptionList is empty return self.header.next.data def lastself: if self.isempty: raise ExceptionList is empty return self.trailer.prev.data DEque Insert Operations At the front, At the end def addfirstself, element: return self.insertself.header, element, self.header.next def addlastself, element: return self.insertself.trailer.prev, element, self.trailer DEqueu Remove Operations At the front, At the end def removefirstself: if self.isempty: raise IndexErrorremovefirst from empty list return self.deleteself.header.next def removelastself: if self.isempty: raise IndexErrorremovefirst from empty list return self.deleteself.trailer.prev","Completions":"class _DoublyLinkedBase:\n \"\"\"A Private class (to be inherited)\"\"\"\n\n class _Node:\n __slots__ = \"_prev\", \"_data\", \"_next\"\n\n def __init__(self, link_p, element, link_n):\n self._prev = link_p\n self._data = element\n self._next = link_n\n\n def has_next_and_prev(self):\n return (\n f\" Prev -> {self._prev is not None}, Next -> {self._next is not None}\"\n )\n\n def __init__(self):\n self._header = self._Node(None, None, None)\n self._trailer = self._Node(None, None, None)\n self._header._next = self._trailer\n self._trailer._prev = self._header\n self._size = 0\n\n def __len__(self):\n return self._size\n\n def is_empty(self):\n return self.__len__() == 0\n\n def _insert(self, predecessor, e, successor):\n # Create new_node by setting it's prev.link -> header\n # setting it's next.link -> trailer\n new_node = self._Node(predecessor, e, successor)\n predecessor._next = new_node\n successor._prev = new_node\n self._size += 1\n return self\n\n def _delete(self, node):\n predecessor = node._prev\n successor = node._next\n\n predecessor._next = successor\n successor._prev = predecessor\n self._size -= 1\n temp = node._data\n node._prev = node._next = node._data = None\n del node\n return temp\n\n\nclass LinkedDeque(_DoublyLinkedBase):\n def first(self):\n \"\"\"return first element\n >>> d = LinkedDeque()\n >>> d.add_first('A').first()\n 'A'\n >>> d.add_first('B').first()\n 'B'\n \"\"\"\n if self.is_empty():\n raise Exception(\"List is empty\")\n return self._header._next._data\n\n def last(self):\n \"\"\"return last element\n >>> d = LinkedDeque()\n >>> d.add_last('A').last()\n 'A'\n >>> d.add_last('B').last()\n 'B'\n \"\"\"\n if self.is_empty():\n raise Exception(\"List is empty\")\n return self._trailer._prev._data\n\n # DEque Insert Operations (At the front, At the end)\n\n def add_first(self, element):\n \"\"\"insertion in the front\n >>> LinkedDeque().add_first('AV').first()\n 'AV'\n \"\"\"\n return self._insert(self._header, element, self._header._next)\n\n def add_last(self, element):\n \"\"\"insertion in the end\n >>> LinkedDeque().add_last('B').last()\n 'B'\n \"\"\"\n return self._insert(self._trailer._prev, element, self._trailer)\n\n # DEqueu Remove Operations (At the front, At the end)\n\n def remove_first(self):\n \"\"\"removal from the front\n >>> d = LinkedDeque()\n >>> d.is_empty()\n True\n >>> d.remove_first()\n Traceback (most recent call last):\n ...\n IndexError: remove_first from empty list\n >>> d.add_first('A') # doctest: +ELLIPSIS\n >> d.remove_first()\n 'A'\n >>> d.is_empty()\n True\n \"\"\"\n if self.is_empty():\n raise IndexError(\"remove_first from empty list\")\n return self._delete(self._header._next)\n\n def remove_last(self):\n \"\"\"removal in the end\n >>> d = LinkedDeque()\n >>> d.is_empty()\n True\n >>> d.remove_last()\n Traceback (most recent call last):\n ...\n IndexError: remove_first from empty list\n >>> d.add_first('A') # doctest: +ELLIPSIS\n >> d.remove_last()\n 'A'\n >>> d.is_empty()\n True\n \"\"\"\n if self.is_empty():\n raise IndexError(\"remove_first from empty list\")\n return self._delete(self._trailer._prev)\n"} +{"Prompt":"https:en.wikipedia.orgwikiDoublylinkedlist linkedlist DoublyLinkedList linkedlist.insertathead'b' linkedlist.insertathead'a' linkedlist.insertattail'c' tuplelinkedlist 'a', 'b', 'c' linkedlist DoublyLinkedList linkedlist.insertattail'a' linkedlist.insertattail'b' linkedlist.insertattail'c' strlinkedlist 'abc' linkedlist DoublyLinkedList for i in range0, 5: ... linkedlist.insertatnthi, i 1 lenlinkedlist 5 True linkedlist DoublyLinkedList linkedlist.insertatnth1, 666 Traceback most recent call last: .... IndexError: list index out of range linkedlist.insertatnth1, 666 Traceback most recent call last: .... IndexError: list index out of range linkedlist.insertatnth0, 2 linkedlist.insertatnth0, 1 linkedlist.insertatnth2, 4 linkedlist.insertatnth2, 3 strlinkedlist '1234' linkedlist.insertatnth5, 5 Traceback most recent call last: .... IndexError: list index out of range linkedlist DoublyLinkedList linkedlist.deleteatnth0 Traceback most recent call last: .... IndexError: list index out of range for i in range0, 5: ... linkedlist.insertatnthi, i 1 linkedlist.deleteatnth0 1 True linkedlist.deleteatnth3 5 True linkedlist.deleteatnth1 3 True strlinkedlist '24' linkedlist.deleteatnth2 Traceback most recent call last: .... IndexError: list index out of range linkedlist DoublyLinkedList linkedlist.isempty True linkedlist.insertattail1 linkedlist.isempty False testdoublylinkedlist","Completions":"class Node:\n def __init__(self, data):\n self.data = data\n self.previous = None\n self.next = None\n\n def __str__(self):\n return f\"{self.data}\"\n\n\nclass DoublyLinkedList:\n def __init__(self):\n self.head = None\n self.tail = None\n\n def __iter__(self):\n \"\"\"\n >>> linked_list = DoublyLinkedList()\n >>> linked_list.insert_at_head('b')\n >>> linked_list.insert_at_head('a')\n >>> linked_list.insert_at_tail('c')\n >>> tuple(linked_list)\n ('a', 'b', 'c')\n \"\"\"\n node = self.head\n while node:\n yield node.data\n node = node.next\n\n def __str__(self):\n \"\"\"\n >>> linked_list = DoublyLinkedList()\n >>> linked_list.insert_at_tail('a')\n >>> linked_list.insert_at_tail('b')\n >>> linked_list.insert_at_tail('c')\n >>> str(linked_list)\n 'a->b->c'\n \"\"\"\n return \"->\".join([str(item) for item in self])\n\n def __len__(self):\n \"\"\"\n >>> linked_list = DoublyLinkedList()\n >>> for i in range(0, 5):\n ... linked_list.insert_at_nth(i, i + 1)\n >>> len(linked_list) == 5\n True\n \"\"\"\n return sum(1 for _ in self)\n\n def insert_at_head(self, data):\n self.insert_at_nth(0, data)\n\n def insert_at_tail(self, data):\n self.insert_at_nth(len(self), data)\n\n def insert_at_nth(self, index: int, data):\n \"\"\"\n >>> linked_list = DoublyLinkedList()\n >>> linked_list.insert_at_nth(-1, 666)\n Traceback (most recent call last):\n ....\n IndexError: list index out of range\n >>> linked_list.insert_at_nth(1, 666)\n Traceback (most recent call last):\n ....\n IndexError: list index out of range\n >>> linked_list.insert_at_nth(0, 2)\n >>> linked_list.insert_at_nth(0, 1)\n >>> linked_list.insert_at_nth(2, 4)\n >>> linked_list.insert_at_nth(2, 3)\n >>> str(linked_list)\n '1->2->3->4'\n >>> linked_list.insert_at_nth(5, 5)\n Traceback (most recent call last):\n ....\n IndexError: list index out of range\n \"\"\"\n length = len(self)\n\n if not 0 <= index <= length:\n raise IndexError(\"list index out of range\")\n new_node = Node(data)\n if self.head is None:\n self.head = self.tail = new_node\n elif index == 0:\n self.head.previous = new_node\n new_node.next = self.head\n self.head = new_node\n elif index == length:\n self.tail.next = new_node\n new_node.previous = self.tail\n self.tail = new_node\n else:\n temp = self.head\n for _ in range(index):\n temp = temp.next\n temp.previous.next = new_node\n new_node.previous = temp.previous\n new_node.next = temp\n temp.previous = new_node\n\n def delete_head(self):\n return self.delete_at_nth(0)\n\n def delete_tail(self):\n return self.delete_at_nth(len(self) - 1)\n\n def delete_at_nth(self, index: int):\n \"\"\"\n >>> linked_list = DoublyLinkedList()\n >>> linked_list.delete_at_nth(0)\n Traceback (most recent call last):\n ....\n IndexError: list index out of range\n >>> for i in range(0, 5):\n ... linked_list.insert_at_nth(i, i + 1)\n >>> linked_list.delete_at_nth(0) == 1\n True\n >>> linked_list.delete_at_nth(3) == 5\n True\n >>> linked_list.delete_at_nth(1) == 3\n True\n >>> str(linked_list)\n '2->4'\n >>> linked_list.delete_at_nth(2)\n Traceback (most recent call last):\n ....\n IndexError: list index out of range\n \"\"\"\n length = len(self)\n\n if not 0 <= index <= length - 1:\n raise IndexError(\"list index out of range\")\n delete_node = self.head # default first node\n if length == 1:\n self.head = self.tail = None\n elif index == 0:\n self.head = self.head.next\n self.head.previous = None\n elif index == length - 1:\n delete_node = self.tail\n self.tail = self.tail.previous\n self.tail.next = None\n else:\n temp = self.head\n for _ in range(index):\n temp = temp.next\n delete_node = temp\n temp.next.previous = temp.previous\n temp.previous.next = temp.next\n return delete_node.data\n\n def delete(self, data) -> str:\n current = self.head\n\n while current.data != data: # Find the position to delete\n if current.next:\n current = current.next\n else: # We have reached the end an no value matches\n raise ValueError(\"No data matching given value\")\n\n if current == self.head:\n self.delete_head()\n\n elif current == self.tail:\n self.delete_tail()\n\n else: # Before: 1 <--> 2(current) <--> 3\n current.previous.next = current.next # 1 --> 3\n current.next.previous = current.previous # 1 <--> 3\n return data\n\n def is_empty(self):\n \"\"\"\n >>> linked_list = DoublyLinkedList()\n >>> linked_list.is_empty()\n True\n >>> linked_list.insert_at_tail(1)\n >>> linked_list.is_empty()\n False\n \"\"\"\n return len(self) == 0\n\n\ndef test_doubly_linked_list() -> None:\n \"\"\"\n >>> test_doubly_linked_list()\n \"\"\"\n linked_list = DoublyLinkedList()\n assert linked_list.is_empty() is True\n assert str(linked_list) == \"\"\n\n try:\n linked_list.delete_head()\n raise AssertionError # This should not happen.\n except IndexError:\n assert True # This should happen.\n\n try:\n linked_list.delete_tail()\n raise AssertionError # This should not happen.\n except IndexError:\n assert True # This should happen.\n\n for i in range(10):\n assert len(linked_list) == i\n linked_list.insert_at_nth(i, i + 1)\n assert str(linked_list) == \"->\".join(str(i) for i in range(1, 11))\n\n linked_list.insert_at_head(0)\n linked_list.insert_at_tail(11)\n assert str(linked_list) == \"->\".join(str(i) for i in range(12))\n\n assert linked_list.delete_head() == 0\n assert linked_list.delete_at_nth(9) == 10\n assert linked_list.delete_tail() == 11\n assert len(linked_list) == 9\n assert str(linked_list) == \"->\".join(str(i) for i in range(1, 10))\n\n\nif __name__ == \"__main__\":\n from doctest import testmod\n\n testmod()\n"} +{"Prompt":"A linked list is similar to an array, it holds values. However, links in a linked list do not have indexes. This is an example of a double ended, doubly linked list. Each link references the next link and the previous one. A Doubly Linked List DLL contains an extra pointer, typically called previous pointer, together with next pointer and data which are there in singly linked list. Advantages over SLL It can be traversed in both forward and backward direction. Delete operation is more efficient newlinkedlist LinkedList newlinkedlist.getheaddata is None True newlinkedlist.gettaildata is None True newlinkedlist.isempty True newlinkedlist.insert10 newlinkedlist.getheaddata 10 newlinkedlist.gettaildata 10 newlinkedlist.insertatpositionposition3, value20 newlinkedlist.getheaddata 10 newlinkedlist.gettaildata 20 newlinkedlist.setheadNode1000 newlinkedlist.getheaddata 1000 newlinkedlist.gettaildata 20 newlinkedlist.settailNode2000 newlinkedlist.getheaddata 1000 newlinkedlist.gettaildata 2000 for value in newlinkedlist: ... printvalue 1000 10 20 2000 newlinkedlist.isempty False for value in newlinkedlist: ... printvalue 1000 10 20 2000 10 in newlinkedlist True newlinkedlist.deletevaluevalue10 10 in newlinkedlist False newlinkedlist.deletevaluevalue2000 newlinkedlist.gettaildata 20 newlinkedlist.deletevaluevalue1000 newlinkedlist.gettaildata 20 newlinkedlist.getheaddata 20 for value in newlinkedlist: ... printvalue 20 newlinkedlist.deletevaluevalue20 for value in newlinkedlist: ... printvalue for value in range1,10: ... newlinkedlist.insertvaluevalue for value in newlinkedlist: ... printvalue 1 2 3 4 5 6 7 8 9","Completions":"class Node:\n def __init__(self, data: int, previous=None, next_node=None):\n self.data = data\n self.previous = previous\n self.next = next_node\n\n def __str__(self) -> str:\n return f\"{self.data}\"\n\n def get_data(self) -> int:\n return self.data\n\n def get_next(self):\n return self.next\n\n def get_previous(self):\n return self.previous\n\n\nclass LinkedListIterator:\n def __init__(self, head):\n self.current = head\n\n def __iter__(self):\n return self\n\n def __next__(self):\n if not self.current:\n raise StopIteration\n else:\n value = self.current.get_data()\n self.current = self.current.get_next()\n return value\n\n\nclass LinkedList:\n def __init__(self):\n self.head = None # First node in list\n self.tail = None # Last node in list\n\n def __str__(self):\n current = self.head\n nodes = []\n while current is not None:\n nodes.append(current.get_data())\n current = current.get_next()\n return \" \".join(str(node) for node in nodes)\n\n def __contains__(self, value: int):\n current = self.head\n while current:\n if current.get_data() == value:\n return True\n current = current.get_next()\n return False\n\n def __iter__(self):\n return LinkedListIterator(self.head)\n\n def get_head_data(self):\n if self.head:\n return self.head.get_data()\n return None\n\n def get_tail_data(self):\n if self.tail:\n return self.tail.get_data()\n return None\n\n def set_head(self, node: Node) -> None:\n if self.head is None:\n self.head = node\n self.tail = node\n else:\n self.insert_before_node(self.head, node)\n\n def set_tail(self, node: Node) -> None:\n if self.head is None:\n self.set_head(node)\n else:\n self.insert_after_node(self.tail, node)\n\n def insert(self, value: int) -> None:\n node = Node(value)\n if self.head is None:\n self.set_head(node)\n else:\n self.set_tail(node)\n\n def insert_before_node(self, node: Node, node_to_insert: Node) -> None:\n node_to_insert.next = node\n node_to_insert.previous = node.previous\n\n if node.get_previous() is None:\n self.head = node_to_insert\n else:\n node.previous.next = node_to_insert\n\n node.previous = node_to_insert\n\n def insert_after_node(self, node: Node, node_to_insert: Node) -> None:\n node_to_insert.previous = node\n node_to_insert.next = node.next\n\n if node.get_next() is None:\n self.tail = node_to_insert\n else:\n node.next.previous = node_to_insert\n\n node.next = node_to_insert\n\n def insert_at_position(self, position: int, value: int) -> None:\n current_position = 1\n new_node = Node(value)\n node = self.head\n while node:\n if current_position == position:\n self.insert_before_node(node, new_node)\n return\n current_position += 1\n node = node.next\n self.insert_after_node(self.tail, new_node)\n\n def get_node(self, item: int) -> Node:\n node = self.head\n while node:\n if node.get_data() == item:\n return node\n node = node.get_next()\n raise Exception(\"Node not found\")\n\n def delete_value(self, value):\n if (node := self.get_node(value)) is not None:\n if node == self.head:\n self.head = self.head.get_next()\n\n if node == self.tail:\n self.tail = self.tail.get_previous()\n\n self.remove_node_pointers(node)\n\n @staticmethod\n def remove_node_pointers(node: Node) -> None:\n if node.get_next():\n node.next.previous = node.previous\n\n if node.get_previous():\n node.previous.next = node.next\n\n node.next = None\n node.previous = None\n\n def is_empty(self):\n return self.head is None\n\n\ndef create_linked_list() -> None:\n \"\"\"\n >>> new_linked_list = LinkedList()\n >>> new_linked_list.get_head_data() is None\n True\n >>> new_linked_list.get_tail_data() is None\n True\n >>> new_linked_list.is_empty()\n True\n >>> new_linked_list.insert(10)\n >>> new_linked_list.get_head_data()\n 10\n >>> new_linked_list.get_tail_data()\n 10\n >>> new_linked_list.insert_at_position(position=3, value=20)\n >>> new_linked_list.get_head_data()\n 10\n >>> new_linked_list.get_tail_data()\n 20\n >>> new_linked_list.set_head(Node(1000))\n >>> new_linked_list.get_head_data()\n 1000\n >>> new_linked_list.get_tail_data()\n 20\n >>> new_linked_list.set_tail(Node(2000))\n >>> new_linked_list.get_head_data()\n 1000\n >>> new_linked_list.get_tail_data()\n 2000\n >>> for value in new_linked_list:\n ... print(value)\n 1000\n 10\n 20\n 2000\n >>> new_linked_list.is_empty()\n False\n >>> for value in new_linked_list:\n ... print(value)\n 1000\n 10\n 20\n 2000\n >>> 10 in new_linked_list\n True\n >>> new_linked_list.delete_value(value=10)\n >>> 10 in new_linked_list\n False\n >>> new_linked_list.delete_value(value=2000)\n >>> new_linked_list.get_tail_data()\n 20\n >>> new_linked_list.delete_value(value=1000)\n >>> new_linked_list.get_tail_data()\n 20\n >>> new_linked_list.get_head_data()\n 20\n >>> for value in new_linked_list:\n ... print(value)\n 20\n >>> new_linked_list.delete_value(value=20)\n >>> for value in new_linked_list:\n ... print(value)\n >>> for value in range(1,10):\n ... new_linked_list.insert(value=value)\n >>> for value in new_linked_list:\n ... print(value)\n 1\n 2\n 3\n 4\n 5\n 6\n 7\n 8\n 9\n \"\"\"\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Floyd's cycle detection algorithm is a popular algorithm used to detect cycles in a linked list. It uses two pointers, a slow pointer and a fast pointer, to traverse the linked list. The slow pointer moves one node at a time while the fast pointer moves two nodes at a time. If there is a cycle in the linked list, the fast pointer will eventually catch up to the slow pointer and they will meet at the same node. If there is no cycle, the fast pointer will reach the end of the linked list and the algorithm will terminate. For more information: https:en.wikipedia.orgwikiCycledetectionFloyd'stortoiseandhare A class representing a node in a singly linked list. A class representing a singly linked list. Iterates through the linked list. Returns: Iterator: An iterator over the linked list. Examples: linkedlist LinkedList listlinkedlist linkedlist.addnode1 tuplelinkedlist 1, Avoid infinite loop in there's a cycle Adds a new node to the end of the linked list. Args: data Any: The data to be stored in the new node. Examples: linkedlist LinkedList linkedlist.addnode1 linkedlist.addnode2 linkedlist.addnode3 linkedlist.addnode4 tuplelinkedlist 1, 2, 3, 4 Detects if there is a cycle in the linked list using Floyd's cycle detection algorithm. Returns: bool: True if there is a cycle, False otherwise. Examples: linkedlist LinkedList linkedlist.addnode1 linkedlist.addnode2 linkedlist.addnode3 linkedlist.addnode4 linkedlist.detectcycle False Create a cycle in the linked list linkedlist.head.nextnode.nextnode.nextnode linkedlist.head.nextnode linkedlist.detectcycle True Create a cycle in the linked list It first checks if the head, nextnode, and nextnode.nextnode attributes of the linked list are not None to avoid any potential type errors.","Completions":"from collections.abc import Iterator\nfrom dataclasses import dataclass\nfrom typing import Any, Self\n\n\n@dataclass\nclass Node:\n \"\"\"\n A class representing a node in a singly linked list.\n \"\"\"\n\n data: Any\n next_node: Self | None = None\n\n\n@dataclass\nclass LinkedList:\n \"\"\"\n A class representing a singly linked list.\n \"\"\"\n\n head: Node | None = None\n\n def __iter__(self) -> Iterator:\n \"\"\"\n Iterates through the linked list.\n\n Returns:\n Iterator: An iterator over the linked list.\n\n Examples:\n >>> linked_list = LinkedList()\n >>> list(linked_list)\n []\n >>> linked_list.add_node(1)\n >>> tuple(linked_list)\n (1,)\n \"\"\"\n visited = []\n node = self.head\n while node:\n # Avoid infinite loop in there's a cycle\n if node in visited:\n return\n visited.append(node)\n yield node.data\n node = node.next_node\n\n def add_node(self, data: Any) -> None:\n \"\"\"\n Adds a new node to the end of the linked list.\n\n Args:\n data (Any): The data to be stored in the new node.\n\n Examples:\n >>> linked_list = LinkedList()\n >>> linked_list.add_node(1)\n >>> linked_list.add_node(2)\n >>> linked_list.add_node(3)\n >>> linked_list.add_node(4)\n >>> tuple(linked_list)\n (1, 2, 3, 4)\n \"\"\"\n new_node = Node(data)\n\n if self.head is None:\n self.head = new_node\n return\n\n current_node = self.head\n while current_node.next_node is not None:\n current_node = current_node.next_node\n\n current_node.next_node = new_node\n\n def detect_cycle(self) -> bool:\n \"\"\"\n Detects if there is a cycle in the linked list using\n Floyd's cycle detection algorithm.\n\n Returns:\n bool: True if there is a cycle, False otherwise.\n\n Examples:\n >>> linked_list = LinkedList()\n >>> linked_list.add_node(1)\n >>> linked_list.add_node(2)\n >>> linked_list.add_node(3)\n >>> linked_list.add_node(4)\n\n >>> linked_list.detect_cycle()\n False\n\n # Create a cycle in the linked list\n >>> linked_list.head.next_node.next_node.next_node = linked_list.head.next_node\n\n >>> linked_list.detect_cycle()\n True\n \"\"\"\n if self.head is None:\n return False\n\n slow_pointer: Node | None = self.head\n fast_pointer: Node | None = self.head\n\n while fast_pointer is not None and fast_pointer.next_node is not None:\n slow_pointer = slow_pointer.next_node if slow_pointer else None\n fast_pointer = fast_pointer.next_node.next_node\n if slow_pointer == fast_pointer:\n return True\n\n return False\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n\n linked_list = LinkedList()\n linked_list.add_node(1)\n linked_list.add_node(2)\n linked_list.add_node(3)\n linked_list.add_node(4)\n\n # Create a cycle in the linked list\n # It first checks if the head, next_node, and next_node.next_node attributes of the\n # linked list are not None to avoid any potential type errors.\n if (\n linked_list.head\n and linked_list.head.next_node\n and linked_list.head.next_node.next_node\n ):\n linked_list.head.next_node.next_node.next_node = linked_list.head.next_node\n\n has_cycle = linked_list.detect_cycle()\n print(has_cycle) # Output: True\n"} +{"Prompt":"Recursive Prorgam to create a Linked List from a sequence and print a string representation of it. Returns a visual representation of the node and all its following nodes. stringrep temp self while temp: stringrep ftemp.data temp temp.next stringrep END return stringrep def makelinkedlistelementslist: if elementslist is empty Set first element as Head Loop through elements from position 1","Completions":"# Recursive Prorgam to create a Linked List from a sequence and\n# print a string representation of it.\n\n\nclass Node:\n def __init__(self, data=None):\n self.data = data\n self.next = None\n\n def __repr__(self):\n \"\"\"Returns a visual representation of the node and all its following nodes.\"\"\"\n string_rep = \"\"\n temp = self\n while temp:\n string_rep += f\"<{temp.data}> ---> \"\n temp = temp.next\n string_rep += \"\"\n return string_rep\n\n\ndef make_linked_list(elements_list):\n \"\"\"Creates a Linked List from the elements of the given sequence\n (list\/tuple) and returns the head of the Linked List.\"\"\"\n\n # if elements_list is empty\n if not elements_list:\n raise Exception(\"The Elements List is empty\")\n\n # Set first element as Head\n head = Node(elements_list[0])\n current = head\n # Loop through elements from position 1\n for data in elements_list[1:]:\n current.next = Node(data)\n current = current.next\n return head\n\n\nlist_data = [1, 3, 5, 32, 44, 12, 43]\nprint(f\"List: {list_data}\")\nprint(\"Creating Linked List from List.\")\nlinked_list = make_linked_list(list_data)\nprint(\"Linked List:\")\nprint(linked_list)\n"} +{"Prompt":"A loop is when the exact same Node appears more than once in a linked list. rootnode Node1 rootnode.nextnode Node2 rootnode.nextnode.nextnode Node3 rootnode.nextnode.nextnode.nextnode Node4 rootnode.hasloop False rootnode.nextnode.nextnode.nextnode rootnode.nextnode rootnode.hasloop True","Completions":"from __future__ import annotations\n\nfrom typing import Any\n\n\nclass ContainsLoopError(Exception):\n pass\n\n\nclass Node:\n def __init__(self, data: Any) -> None:\n self.data: Any = data\n self.next_node: Node | None = None\n\n def __iter__(self):\n node = self\n visited = []\n while node:\n if node in visited:\n raise ContainsLoopError\n visited.append(node)\n yield node.data\n node = node.next_node\n\n @property\n def has_loop(self) -> bool:\n \"\"\"\n A loop is when the exact same Node appears more than once in a linked list.\n >>> root_node = Node(1)\n >>> root_node.next_node = Node(2)\n >>> root_node.next_node.next_node = Node(3)\n >>> root_node.next_node.next_node.next_node = Node(4)\n >>> root_node.has_loop\n False\n >>> root_node.next_node.next_node.next_node = root_node.next_node\n >>> root_node.has_loop\n True\n \"\"\"\n try:\n list(self)\n return False\n except ContainsLoopError:\n return True\n\n\nif __name__ == \"__main__\":\n root_node = Node(1)\n root_node.next_node = Node(2)\n root_node.next_node.next_node = Node(3)\n root_node.next_node.next_node.next_node = Node(4)\n print(root_node.has_loop) # False\n root_node.next_node.next_node.next_node = root_node.next_node\n print(root_node.has_loop) # True\n\n root_node = Node(5)\n root_node.next_node = Node(6)\n root_node.next_node.next_node = Node(5)\n root_node.next_node.next_node.next_node = Node(6)\n print(root_node.has_loop) # False\n\n root_node = Node(1)\n print(root_node.has_loop) # False\n"} +{"Prompt":"Check if a linked list is a palindrome. Args: head: The head of the linked list. Returns: bool: True if the linked list is a palindrome, False otherwise. Examples: ispalindromeNone True ispalindromeListNode1 True ispalindromeListNode1, ListNode2 False ispalindromeListNode1, ListNode2, ListNode1 True ispalindromeListNode1, ListNode2, ListNode2, ListNode1 True split the list to two parts slow will always be defined, adding this check to resolve mypy static check reverse the second part compare two parts second part has the same or one less node Check if a linked list is a palindrome using a stack. Args: head ListNode: The head of the linked list. Returns: bool: True if the linked list is a palindrome, False otherwise. Examples: ispalindromestackNone True ispalindromestackListNode1 True ispalindromestackListNode1, ListNode2 False ispalindromestackListNode1, ListNode2, ListNode1 True ispalindromestackListNode1, ListNode2, ListNode2, ListNode1 True 1. Get the midpoint slow slow will always be defined, adding this check to resolve mypy static check 2. Push the second half into the stack 3. Comparison Check if a linked list is a palindrome using a dictionary. Args: head ListNode: The head of the linked list. Returns: bool: True if the linked list is a palindrome, False otherwise. Examples: ispalindromedictNone True ispalindromedictListNode1 True ispalindromedictListNode1, ListNode2 False ispalindromedictListNode1, ListNode2, ListNode1 True ispalindromedictListNode1, ListNode2, ListNode2, ListNode1 True ispalindromedict ... ListNode ... 1, ListNode2, ListNode1, ListNode3, ListNode2, ListNode1 ... ... False","Completions":"from __future__ import annotations\n\nfrom dataclasses import dataclass\n\n\n@dataclass\nclass ListNode:\n val: int = 0\n next_node: ListNode | None = None\n\n\ndef is_palindrome(head: ListNode | None) -> bool:\n \"\"\"\n Check if a linked list is a palindrome.\n\n Args:\n head: The head of the linked list.\n\n Returns:\n bool: True if the linked list is a palindrome, False otherwise.\n\n Examples:\n >>> is_palindrome(None)\n True\n\n >>> is_palindrome(ListNode(1))\n True\n\n >>> is_palindrome(ListNode(1, ListNode(2)))\n False\n\n >>> is_palindrome(ListNode(1, ListNode(2, ListNode(1))))\n True\n\n >>> is_palindrome(ListNode(1, ListNode(2, ListNode(2, ListNode(1)))))\n True\n \"\"\"\n if not head:\n return True\n # split the list to two parts\n fast: ListNode | None = head.next_node\n slow: ListNode | None = head\n while fast and fast.next_node:\n fast = fast.next_node.next_node\n slow = slow.next_node if slow else None\n if slow:\n # slow will always be defined,\n # adding this check to resolve mypy static check\n second = slow.next_node\n slow.next_node = None # Don't forget here! But forget still works!\n # reverse the second part\n node: ListNode | None = None\n while second:\n nxt = second.next_node\n second.next_node = node\n node = second\n second = nxt\n # compare two parts\n # second part has the same or one less node\n while node and head:\n if node.val != head.val:\n return False\n node = node.next_node\n head = head.next_node\n return True\n\n\ndef is_palindrome_stack(head: ListNode | None) -> bool:\n \"\"\"\n Check if a linked list is a palindrome using a stack.\n\n Args:\n head (ListNode): The head of the linked list.\n\n Returns:\n bool: True if the linked list is a palindrome, False otherwise.\n\n Examples:\n >>> is_palindrome_stack(None)\n True\n\n >>> is_palindrome_stack(ListNode(1))\n True\n\n >>> is_palindrome_stack(ListNode(1, ListNode(2)))\n False\n\n >>> is_palindrome_stack(ListNode(1, ListNode(2, ListNode(1))))\n True\n\n >>> is_palindrome_stack(ListNode(1, ListNode(2, ListNode(2, ListNode(1)))))\n True\n \"\"\"\n if not head or not head.next_node:\n return True\n\n # 1. Get the midpoint (slow)\n slow: ListNode | None = head\n fast: ListNode | None = head\n while fast and fast.next_node:\n fast = fast.next_node.next_node\n slow = slow.next_node if slow else None\n\n # slow will always be defined,\n # adding this check to resolve mypy static check\n if slow:\n stack = [slow.val]\n\n # 2. Push the second half into the stack\n while slow.next_node:\n slow = slow.next_node\n stack.append(slow.val)\n\n # 3. Comparison\n cur: ListNode | None = head\n while stack and cur:\n if stack.pop() != cur.val:\n return False\n cur = cur.next_node\n\n return True\n\n\ndef is_palindrome_dict(head: ListNode | None) -> bool:\n \"\"\"\n Check if a linked list is a palindrome using a dictionary.\n\n Args:\n head (ListNode): The head of the linked list.\n\n Returns:\n bool: True if the linked list is a palindrome, False otherwise.\n\n Examples:\n >>> is_palindrome_dict(None)\n True\n\n >>> is_palindrome_dict(ListNode(1))\n True\n\n >>> is_palindrome_dict(ListNode(1, ListNode(2)))\n False\n\n >>> is_palindrome_dict(ListNode(1, ListNode(2, ListNode(1))))\n True\n\n >>> is_palindrome_dict(ListNode(1, ListNode(2, ListNode(2, ListNode(1)))))\n True\n\n >>> is_palindrome_dict(\n ... ListNode(\n ... 1, ListNode(2, ListNode(1, ListNode(3, ListNode(2, ListNode(1)))))\n ... )\n ... )\n False\n \"\"\"\n if not head or not head.next_node:\n return True\n d: dict[int, list[int]] = {}\n pos = 0\n while head:\n if head.val in d:\n d[head.val].append(pos)\n else:\n d[head.val] = [pos]\n head = head.next_node\n pos += 1\n checksum = pos - 1\n middle = 0\n for v in d.values():\n if len(v) % 2 != 0:\n middle += 1\n else:\n step = 0\n for i in range(len(v)):\n if v[i] + v[len(v) - 1 - step] != checksum:\n return False\n step += 1\n if middle > 1:\n return False\n return True\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Algorithm that merges two sorted linked lists into one sorted linked list. tupleSortedLinkedListtestdataodd tuplesortedtestdataodd True tupleSortedLinkedListtestdataeven tuplesortedtestdataeven True for i in range3: ... lenSortedLinkedListrangei i True True True lenSortedLinkedListtestdataodd 8 strSortedLinkedList '' strSortedLinkedListtestdataodd '11 1 0 1 3 5 7 9' strSortedLinkedListtestdataeven '2 0 2 3 4 6 8 10' SSL SortedLinkedList merged mergelistsSSLtestdataodd, SSLtestdataeven lenmerged 16 strmerged '11 2 1 0 0 1 2 3 3 4 5 6 7 8 9 10' listmerged listsortedtestdataodd testdataeven True","Completions":"from __future__ import annotations\n\nfrom collections.abc import Iterable, Iterator\nfrom dataclasses import dataclass\n\ntest_data_odd = (3, 9, -11, 0, 7, 5, 1, -1)\ntest_data_even = (4, 6, 2, 0, 8, 10, 3, -2)\n\n\n@dataclass\nclass Node:\n data: int\n next_node: Node | None\n\n\nclass SortedLinkedList:\n def __init__(self, ints: Iterable[int]) -> None:\n self.head: Node | None = None\n for i in sorted(ints, reverse=True):\n self.head = Node(i, self.head)\n\n def __iter__(self) -> Iterator[int]:\n \"\"\"\n >>> tuple(SortedLinkedList(test_data_odd)) == tuple(sorted(test_data_odd))\n True\n >>> tuple(SortedLinkedList(test_data_even)) == tuple(sorted(test_data_even))\n True\n \"\"\"\n node = self.head\n while node:\n yield node.data\n node = node.next_node\n\n def __len__(self) -> int:\n \"\"\"\n >>> for i in range(3):\n ... len(SortedLinkedList(range(i))) == i\n True\n True\n True\n >>> len(SortedLinkedList(test_data_odd))\n 8\n \"\"\"\n return sum(1 for _ in self)\n\n def __str__(self) -> str:\n \"\"\"\n >>> str(SortedLinkedList([]))\n ''\n >>> str(SortedLinkedList(test_data_odd))\n '-11 -> -1 -> 0 -> 1 -> 3 -> 5 -> 7 -> 9'\n >>> str(SortedLinkedList(test_data_even))\n '-2 -> 0 -> 2 -> 3 -> 4 -> 6 -> 8 -> 10'\n \"\"\"\n return \" -> \".join([str(node) for node in self])\n\n\ndef merge_lists(\n sll_one: SortedLinkedList, sll_two: SortedLinkedList\n) -> SortedLinkedList:\n \"\"\"\n >>> SSL = SortedLinkedList\n >>> merged = merge_lists(SSL(test_data_odd), SSL(test_data_even))\n >>> len(merged)\n 16\n >>> str(merged)\n '-11 -> -2 -> -1 -> 0 -> 0 -> 1 -> 2 -> 3 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> 10'\n >>> list(merged) == list(sorted(test_data_odd + test_data_even))\n True\n \"\"\"\n return SortedLinkedList(list(sll_one) + list(sll_two))\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n SSL = SortedLinkedList\n print(merge_lists(SSL(test_data_odd), SSL(test_data_even)))\n"} +{"Prompt":"link LinkedList link.middleelement No element found. link.push5 5 link.push6 6 link.push8 8 link.push8 8 link.push10 10 link.push12 12 link.push17 17 link.push7 7 link.push3 3 link.push20 20 link.push20 20 link.middleelement 12","Completions":"from __future__ import annotations\n\n\nclass Node:\n def __init__(self, data: int) -> None:\n self.data = data\n self.next = None\n\n\nclass LinkedList:\n def __init__(self):\n self.head = None\n\n def push(self, new_data: int) -> int:\n new_node = Node(new_data)\n new_node.next = self.head\n self.head = new_node\n return self.head.data\n\n def middle_element(self) -> int | None:\n \"\"\"\n >>> link = LinkedList()\n >>> link.middle_element()\n No element found.\n >>> link.push(5)\n 5\n >>> link.push(6)\n 6\n >>> link.push(8)\n 8\n >>> link.push(8)\n 8\n >>> link.push(10)\n 10\n >>> link.push(12)\n 12\n >>> link.push(17)\n 17\n >>> link.push(7)\n 7\n >>> link.push(3)\n 3\n >>> link.push(20)\n 20\n >>> link.push(-20)\n -20\n >>> link.middle_element()\n 12\n >>>\n \"\"\"\n slow_pointer = self.head\n fast_pointer = self.head\n if self.head:\n while fast_pointer and fast_pointer.next:\n fast_pointer = fast_pointer.next.next\n slow_pointer = slow_pointer.next\n return slow_pointer.data\n else:\n print(\"No element found.\")\n return None\n\n\nif __name__ == \"__main__\":\n link = LinkedList()\n for _ in range(int(input().strip())):\n data = int(input().strip())\n link.push(data)\n print(link.middle_element())\n"} +{"Prompt":"A class to represent a Linked List. Use a tail pointer to speed up the append operation. Initialize a LinkedList with the head node set to None. linkedlist LinkedList linkedlist.head, linkedlist.tail None, None Iterate the LinkedList yielding each Node's data. linkedlist LinkedList items 1, 2, 3, 4, 5 linkedlist.extenditems tuplelinkedlist items True Returns a string representation of the LinkedList. linkedlist LinkedList strlinkedlist '' linkedlist.append1 strlinkedlist '1' linkedlist.extend2, 3, 4, 5 strlinkedlist '1 2 3 4 5' Appends a new node with the given data to the end of the LinkedList. linkedlist LinkedList strlinkedlist '' linkedlist.append1 strlinkedlist '1' linkedlist.append2 strlinkedlist '1 2' Appends each item to the end of the LinkedList. linkedlist LinkedList linkedlist.extend strlinkedlist '' linkedlist.extend1, 2 strlinkedlist '1 2' linkedlist.extend3,4 strlinkedlist '1 2 3 4' Creates a Linked List from the elements of the given sequence listtuple and returns the head of the Linked List. makelinkedlist Traceback most recent call last: ... Exception: The Elements List is empty makelinkedlist7 7 makelinkedlist'abc' abc makelinkedlist7, 25 7 25 Prints the elements of the given Linked List in reverse order inreverseLinkedList '' inreversemakelinkedlist69, 88, 73 '73 88 69'","Completions":"from __future__ import annotations\n\nfrom collections.abc import Iterable, Iterator\nfrom dataclasses import dataclass\n\n\n@dataclass\nclass Node:\n data: int\n next_node: Node | None = None\n\n\nclass LinkedList:\n \"\"\"A class to represent a Linked List.\n Use a tail pointer to speed up the append() operation.\n \"\"\"\n\n def __init__(self) -> None:\n \"\"\"Initialize a LinkedList with the head node set to None.\n >>> linked_list = LinkedList()\n >>> (linked_list.head, linked_list.tail)\n (None, None)\n \"\"\"\n self.head: Node | None = None\n self.tail: Node | None = None # Speeds up the append() operation\n\n def __iter__(self) -> Iterator[int]:\n \"\"\"Iterate the LinkedList yielding each Node's data.\n >>> linked_list = LinkedList()\n >>> items = (1, 2, 3, 4, 5)\n >>> linked_list.extend(items)\n >>> tuple(linked_list) == items\n True\n \"\"\"\n node = self.head\n while node:\n yield node.data\n node = node.next_node\n\n def __repr__(self) -> str:\n \"\"\"Returns a string representation of the LinkedList.\n >>> linked_list = LinkedList()\n >>> str(linked_list)\n ''\n >>> linked_list.append(1)\n >>> str(linked_list)\n '1'\n >>> linked_list.extend([2, 3, 4, 5])\n >>> str(linked_list)\n '1 -> 2 -> 3 -> 4 -> 5'\n \"\"\"\n return \" -> \".join([str(data) for data in self])\n\n def append(self, data: int) -> None:\n \"\"\"Appends a new node with the given data to the end of the LinkedList.\n >>> linked_list = LinkedList()\n >>> str(linked_list)\n ''\n >>> linked_list.append(1)\n >>> str(linked_list)\n '1'\n >>> linked_list.append(2)\n >>> str(linked_list)\n '1 -> 2'\n \"\"\"\n if self.tail:\n self.tail.next_node = self.tail = Node(data)\n else:\n self.head = self.tail = Node(data)\n\n def extend(self, items: Iterable[int]) -> None:\n \"\"\"Appends each item to the end of the LinkedList.\n >>> linked_list = LinkedList()\n >>> linked_list.extend([])\n >>> str(linked_list)\n ''\n >>> linked_list.extend([1, 2])\n >>> str(linked_list)\n '1 -> 2'\n >>> linked_list.extend([3,4])\n >>> str(linked_list)\n '1 -> 2 -> 3 -> 4'\n \"\"\"\n for item in items:\n self.append(item)\n\n\ndef make_linked_list(elements_list: Iterable[int]) -> LinkedList:\n \"\"\"Creates a Linked List from the elements of the given sequence\n (list\/tuple) and returns the head of the Linked List.\n >>> make_linked_list([])\n Traceback (most recent call last):\n ...\n Exception: The Elements List is empty\n >>> make_linked_list([7])\n 7\n >>> make_linked_list(['abc'])\n abc\n >>> make_linked_list([7, 25])\n 7 -> 25\n \"\"\"\n if not elements_list:\n raise Exception(\"The Elements List is empty\")\n\n linked_list = LinkedList()\n linked_list.extend(elements_list)\n return linked_list\n\n\ndef in_reverse(linked_list: LinkedList) -> str:\n \"\"\"Prints the elements of the given Linked List in reverse order\n >>> in_reverse(LinkedList())\n ''\n >>> in_reverse(make_linked_list([69, 88, 73]))\n '73 <- 88 <- 69'\n \"\"\"\n return \" <- \".join(str(line) for line in reversed(tuple(linked_list)))\n\n\nif __name__ == \"__main__\":\n from doctest import testmod\n\n testmod()\n linked_list = make_linked_list((14, 52, 14, 12, 43))\n print(f\"Linked List: {linked_list}\")\n print(f\"Reverse List: {in_reverse(linked_list)}\")\n"} +{"Prompt":"ints listLinkedListints ints True ints tuplerange5 tupleLinkedListints ints True for i in range3: ... lenLinkedListrangei i True True True lenLinkedListabcdefgh 8 strLinkedList '' strLinkedListrange5 '0 1 2 3 4' ll LinkedList1, 2 tuplell 1, 2 ll.append3 tuplell 1, 2, 3 ll.append4 tuplell 1, 2, 3, 4 lenll 4 reverse nodes within groups of size k ll LinkedList1, 2, 3, 4, 5 ll.reverseknodes2 tuplell 2, 1, 4, 3, 5 strll '2 1 4 3 5'","Completions":"from __future__ import annotations\n\nfrom collections.abc import Iterable, Iterator\nfrom dataclasses import dataclass\n\n\n@dataclass\nclass Node:\n data: int\n next_node: Node | None = None\n\n\nclass LinkedList:\n def __init__(self, ints: Iterable[int]) -> None:\n self.head: Node | None = None\n for i in ints:\n self.append(i)\n\n def __iter__(self) -> Iterator[int]:\n \"\"\"\n >>> ints = []\n >>> list(LinkedList(ints)) == ints\n True\n >>> ints = tuple(range(5))\n >>> tuple(LinkedList(ints)) == ints\n True\n \"\"\"\n node = self.head\n while node:\n yield node.data\n node = node.next_node\n\n def __len__(self) -> int:\n \"\"\"\n >>> for i in range(3):\n ... len(LinkedList(range(i))) == i\n True\n True\n True\n >>> len(LinkedList(\"abcdefgh\"))\n 8\n \"\"\"\n return sum(1 for _ in self)\n\n def __str__(self) -> str:\n \"\"\"\n >>> str(LinkedList([]))\n ''\n >>> str(LinkedList(range(5)))\n '0 -> 1 -> 2 -> 3 -> 4'\n \"\"\"\n return \" -> \".join([str(node) for node in self])\n\n def append(self, data: int) -> None:\n \"\"\"\n >>> ll = LinkedList([1, 2])\n >>> tuple(ll)\n (1, 2)\n >>> ll.append(3)\n >>> tuple(ll)\n (1, 2, 3)\n >>> ll.append(4)\n >>> tuple(ll)\n (1, 2, 3, 4)\n >>> len(ll)\n 4\n \"\"\"\n if not self.head:\n self.head = Node(data)\n return\n node = self.head\n while node.next_node:\n node = node.next_node\n node.next_node = Node(data)\n\n def reverse_k_nodes(self, group_size: int) -> None:\n \"\"\"\n reverse nodes within groups of size k\n >>> ll = LinkedList([1, 2, 3, 4, 5])\n >>> ll.reverse_k_nodes(2)\n >>> tuple(ll)\n (2, 1, 4, 3, 5)\n >>> str(ll)\n '2 -> 1 -> 4 -> 3 -> 5'\n \"\"\"\n if self.head is None or self.head.next_node is None:\n return\n\n length = len(self)\n dummy_head = Node(0)\n dummy_head.next_node = self.head\n previous_node = dummy_head\n\n while length >= group_size:\n current_node = previous_node.next_node\n assert current_node\n next_node = current_node.next_node\n for _ in range(1, group_size):\n assert next_node, current_node\n current_node.next_node = next_node.next_node\n assert previous_node\n next_node.next_node = previous_node.next_node\n previous_node.next_node = next_node\n next_node = current_node.next_node\n previous_node = current_node\n length -= group_size\n self.head = dummy_head.next_node\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n ll = LinkedList([1, 2, 3, 4, 5])\n print(f\"Original Linked List: {ll}\")\n k = 2\n ll.reverse_k_nodes(k)\n print(f\"After reversing groups of size {k}: {ll}\")\n"} +{"Prompt":"Print the entire linked list iteratively. This function prints the elements of a linked list separated by ''. Parameters: head Node None: The head of the linked list to be printed, or None if the linked list is empty. head insertnodeNone, 0 head insertnodehead, 2 head insertnodehead, 1 printlinkedlisthead 021 head insertnodehead, 4 head insertnodehead, 5 printlinkedlisthead 02145 Insert a new node at the end of a linked list and return the new head. Parameters: head Node None: The head of the linked list. data int: The data to be inserted into the new node. Returns: Node: The new head of the linked list. head insertnodeNone, 10 head insertnodehead, 9 head insertnodehead, 8 printlinkedlisthead 1098 If the linked list is empty, the newnode becomes the head Rotate a linked list to the right by places times. Parameters: head: The head of the linked list. places: The number of places to rotate. Returns: Node: The head of the rotated linked list. rotatetotherightNone, places1 Traceback most recent call last: ... ValueError: The linked list is empty. head insertnodeNone, 1 rotatetotherighthead, places1 head True head insertnodeNone, 1 head insertnodehead, 2 head insertnodehead, 3 head insertnodehead, 4 head insertnodehead, 5 newhead rotatetotherighthead, places2 printlinkedlistnewhead 45123 Check if the list is empty or has only one element Calculate the length of the linked list Adjust the value of places to avoid places longer than the list. Find the new head position after rotation. Traverse to the new head position Update pointers to perform rotation","Completions":"from __future__ import annotations\n\nfrom dataclasses import dataclass\n\n\n@dataclass\nclass Node:\n data: int\n next_node: Node | None = None\n\n\ndef print_linked_list(head: Node | None) -> None:\n \"\"\"\n Print the entire linked list iteratively.\n\n This function prints the elements of a linked list separated by '->'.\n\n Parameters:\n head (Node | None): The head of the linked list to be printed,\n or None if the linked list is empty.\n\n >>> head = insert_node(None, 0)\n >>> head = insert_node(head, 2)\n >>> head = insert_node(head, 1)\n >>> print_linked_list(head)\n 0->2->1\n >>> head = insert_node(head, 4)\n >>> head = insert_node(head, 5)\n >>> print_linked_list(head)\n 0->2->1->4->5\n \"\"\"\n if head is None:\n return\n while head.next_node is not None:\n print(head.data, end=\"->\")\n head = head.next_node\n print(head.data)\n\n\ndef insert_node(head: Node | None, data: int) -> Node:\n \"\"\"\n Insert a new node at the end of a linked list and return the new head.\n\n Parameters:\n head (Node | None): The head of the linked list.\n data (int): The data to be inserted into the new node.\n\n Returns:\n Node: The new head of the linked list.\n\n >>> head = insert_node(None, 10)\n >>> head = insert_node(head, 9)\n >>> head = insert_node(head, 8)\n >>> print_linked_list(head)\n 10->9->8\n \"\"\"\n new_node = Node(data)\n # If the linked list is empty, the new_node becomes the head\n if head is None:\n return new_node\n\n temp_node = head\n while temp_node.next_node:\n temp_node = temp_node.next_node\n\n temp_node.next_node = new_node # type: ignore\n return head\n\n\ndef rotate_to_the_right(head: Node, places: int) -> Node:\n \"\"\"\n Rotate a linked list to the right by places times.\n\n Parameters:\n head: The head of the linked list.\n places: The number of places to rotate.\n\n Returns:\n Node: The head of the rotated linked list.\n\n >>> rotate_to_the_right(None, places=1)\n Traceback (most recent call last):\n ...\n ValueError: The linked list is empty.\n >>> head = insert_node(None, 1)\n >>> rotate_to_the_right(head, places=1) == head\n True\n >>> head = insert_node(None, 1)\n >>> head = insert_node(head, 2)\n >>> head = insert_node(head, 3)\n >>> head = insert_node(head, 4)\n >>> head = insert_node(head, 5)\n >>> new_head = rotate_to_the_right(head, places=2)\n >>> print_linked_list(new_head)\n 4->5->1->2->3\n \"\"\"\n # Check if the list is empty or has only one element\n if not head:\n raise ValueError(\"The linked list is empty.\")\n\n if head.next_node is None:\n return head\n\n # Calculate the length of the linked list\n length = 1\n temp_node = head\n while temp_node.next_node is not None:\n length += 1\n temp_node = temp_node.next_node\n\n # Adjust the value of places to avoid places longer than the list.\n places %= length\n\n if places == 0:\n return head # As no rotation is needed.\n\n # Find the new head position after rotation.\n new_head_index = length - places\n\n # Traverse to the new head position\n temp_node = head\n for _ in range(new_head_index - 1):\n assert temp_node.next_node\n temp_node = temp_node.next_node\n\n # Update pointers to perform rotation\n assert temp_node.next_node\n new_head = temp_node.next_node\n temp_node.next_node = None\n temp_node = new_head\n while temp_node.next_node:\n temp_node = temp_node.next_node\n temp_node.next_node = head\n\n assert new_head\n return new_head\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n head = insert_node(None, 5)\n head = insert_node(head, 1)\n head = insert_node(head, 2)\n head = insert_node(head, 4)\n head = insert_node(head, 3)\n\n print(\"Original list: \", end=\"\")\n print_linked_list(head)\n\n places = 3\n new_head = rotate_to_the_right(head, places)\n\n print(f\"After {places} iterations: \", end=\"\")\n print_linked_list(new_head)\n"} +{"Prompt":"Create and initialize Node class instance. Node20 Node20 NodeHello, world! NodeHello, world! NodeNone NodeNone NodeTrue NodeTrue Get the string representation of this node. Node10.repr 'Node10' reprNode10 'Node10' strNode10 'Node10' Node10 Node10 Create and initialize LinkedList class instance. linkedlist LinkedList linkedlist.head is None True This function is intended for iterators to access and iterate through data inside linked list. linkedlist LinkedList linkedlist.inserttailtail linkedlist.inserttailtail1 linkedlist.inserttailtail2 for node in linkedlist: iter used here. ... node 'tail' 'tail1' 'tail2' Return length of linked list i.e. number of nodes linkedlist LinkedList lenlinkedlist 0 linkedlist.inserttailtail lenlinkedlist 1 linkedlist.insertheadhead lenlinkedlist 2 linkedlist.deletetail lenlinkedlist 1 linkedlist.deletehead lenlinkedlist 0 String representationvisualization of a Linked Lists linkedlist LinkedList linkedlist.inserttail1 linkedlist.inserttail3 linkedlist.repr '1 3' reprlinkedlist '1 3' strlinkedlist '1 3' linkedlist.inserttail5 flinkedlist '1 3 5' Indexing Support. Used to get a node at particular position linkedlist LinkedList for i in range0, 10: ... linkedlist.insertnthi, i allstrlinkedlisti stri for i in range0, 10 True linkedlist10 Traceback most recent call last: ... ValueError: list index out of range. linkedlistlenlinkedlist Traceback most recent call last: ... ValueError: list index out of range. Used to change the data of a particular node linkedlist LinkedList for i in range0, 10: ... linkedlist.insertnthi, i linkedlist0 666 linkedlist0 666 linkedlist5 666 linkedlist5 666 linkedlist10 666 Traceback most recent call last: ... ValueError: list index out of range. linkedlistlenlinkedlist 666 Traceback most recent call last: ... ValueError: list index out of range. Insert data to the end of linked list. linkedlist LinkedList linkedlist.inserttailtail linkedlist tail linkedlist.inserttailtail2 linkedlist tail tail2 linkedlist.inserttailtail3 linkedlist tail tail2 tail3 Insert data to the beginning of linked list. linkedlist LinkedList linkedlist.insertheadhead linkedlist head linkedlist.insertheadhead2 linkedlist head2 head linkedlist.insertheadhead3 linkedlist head3 head2 head Insert data at given index. linkedlist LinkedList linkedlist.inserttailfirst linkedlist.inserttailsecond linkedlist.inserttailthird linkedlist first second third linkedlist.insertnth1, fourth linkedlist first fourth second third linkedlist.insertnth3, fifth linkedlist first fourth second fifth third This method prints every node data. linkedlist LinkedList linkedlist.inserttailfirst linkedlist.inserttailsecond linkedlist.inserttailthird linkedlist first second third Delete the first node and return the node's data. linkedlist LinkedList linkedlist.inserttailfirst linkedlist.inserttailsecond linkedlist.inserttailthird linkedlist first second third linkedlist.deletehead 'first' linkedlist second third linkedlist.deletehead 'second' linkedlist third linkedlist.deletehead 'third' linkedlist.deletehead Traceback most recent call last: ... IndexError: List index out of range. Delete the tail end node and return the node's data. linkedlist LinkedList linkedlist.inserttailfirst linkedlist.inserttailsecond linkedlist.inserttailthird linkedlist first second third linkedlist.deletetail 'third' linkedlist first second linkedlist.deletetail 'second' linkedlist first linkedlist.deletetail 'first' linkedlist.deletetail Traceback most recent call last: ... IndexError: List index out of range. Delete node at given index and return the node's data. linkedlist LinkedList linkedlist.inserttailfirst linkedlist.inserttailsecond linkedlist.inserttailthird linkedlist first second third linkedlist.deletenth1 delete middle 'second' linkedlist first third linkedlist.deletenth5 this raises error Traceback most recent call last: ... IndexError: List index out of range. linkedlist.deletenth1 this also raises error Traceback most recent call last: ... IndexError: List index out of range. Check if linked list is empty. linkedlist LinkedList linkedlist.isempty True linkedlist.insertheadfirst linkedlist.isempty False This reverses the linked list order. linkedlist LinkedList linkedlist.inserttailfirst linkedlist.inserttailsecond linkedlist.inserttailthird linkedlist first second third linkedlist.reverse linkedlist third second first Store the current node's next node. Make the current node's nextnode point backwards Make the previous node be the current node Make the current node the nextnode node to progress iteration Return prev in order to put the head at the end testsinglylinkedlist This section of the test used varying data types for input. testsinglylinkedlist2 Check if it's empty or not Delete the head Delete the tail Delete a node in specific location in linked list Add a Node instance to its head Add None to its tail Reverse the linked list","Completions":"from __future__ import annotations\n\nfrom collections.abc import Iterator\nfrom dataclasses import dataclass\nfrom typing import Any\n\n\n@dataclass\nclass Node:\n \"\"\"\n Create and initialize Node class instance.\n >>> Node(20)\n Node(20)\n >>> Node(\"Hello, world!\")\n Node(Hello, world!)\n >>> Node(None)\n Node(None)\n >>> Node(True)\n Node(True)\n \"\"\"\n\n data: Any\n next_node: Node | None = None\n\n def __repr__(self) -> str:\n \"\"\"\n Get the string representation of this node.\n >>> Node(10).__repr__()\n 'Node(10)'\n >>> repr(Node(10))\n 'Node(10)'\n >>> str(Node(10))\n 'Node(10)'\n >>> Node(10)\n Node(10)\n \"\"\"\n return f\"Node({self.data})\"\n\n\nclass LinkedList:\n def __init__(self):\n \"\"\"\n Create and initialize LinkedList class instance.\n >>> linked_list = LinkedList()\n >>> linked_list.head is None\n True\n \"\"\"\n self.head = None\n\n def __iter__(self) -> Iterator[Any]:\n \"\"\"\n This function is intended for iterators to access\n and iterate through data inside linked list.\n >>> linked_list = LinkedList()\n >>> linked_list.insert_tail(\"tail\")\n >>> linked_list.insert_tail(\"tail_1\")\n >>> linked_list.insert_tail(\"tail_2\")\n >>> for node in linked_list: # __iter__ used here.\n ... node\n 'tail'\n 'tail_1'\n 'tail_2'\n \"\"\"\n node = self.head\n while node:\n yield node.data\n node = node.next_node\n\n def __len__(self) -> int:\n \"\"\"\n Return length of linked list i.e. number of nodes\n >>> linked_list = LinkedList()\n >>> len(linked_list)\n 0\n >>> linked_list.insert_tail(\"tail\")\n >>> len(linked_list)\n 1\n >>> linked_list.insert_head(\"head\")\n >>> len(linked_list)\n 2\n >>> _ = linked_list.delete_tail()\n >>> len(linked_list)\n 1\n >>> _ = linked_list.delete_head()\n >>> len(linked_list)\n 0\n \"\"\"\n return sum(1 for _ in self)\n\n def __repr__(self) -> str:\n \"\"\"\n String representation\/visualization of a Linked Lists\n >>> linked_list = LinkedList()\n >>> linked_list.insert_tail(1)\n >>> linked_list.insert_tail(3)\n >>> linked_list.__repr__()\n '1 -> 3'\n >>> repr(linked_list)\n '1 -> 3'\n >>> str(linked_list)\n '1 -> 3'\n >>> linked_list.insert_tail(5)\n >>> f\"{linked_list}\"\n '1 -> 3 -> 5'\n \"\"\"\n return \" -> \".join([str(item) for item in self])\n\n def __getitem__(self, index: int) -> Any:\n \"\"\"\n Indexing Support. Used to get a node at particular position\n >>> linked_list = LinkedList()\n >>> for i in range(0, 10):\n ... linked_list.insert_nth(i, i)\n >>> all(str(linked_list[i]) == str(i) for i in range(0, 10))\n True\n >>> linked_list[-10]\n Traceback (most recent call last):\n ...\n ValueError: list index out of range.\n >>> linked_list[len(linked_list)]\n Traceback (most recent call last):\n ...\n ValueError: list index out of range.\n \"\"\"\n if not 0 <= index < len(self):\n raise ValueError(\"list index out of range.\")\n for i, node in enumerate(self):\n if i == index:\n return node\n return None\n\n # Used to change the data of a particular node\n def __setitem__(self, index: int, data: Any) -> None:\n \"\"\"\n >>> linked_list = LinkedList()\n >>> for i in range(0, 10):\n ... linked_list.insert_nth(i, i)\n >>> linked_list[0] = 666\n >>> linked_list[0]\n 666\n >>> linked_list[5] = -666\n >>> linked_list[5]\n -666\n >>> linked_list[-10] = 666\n Traceback (most recent call last):\n ...\n ValueError: list index out of range.\n >>> linked_list[len(linked_list)] = 666\n Traceback (most recent call last):\n ...\n ValueError: list index out of range.\n \"\"\"\n if not 0 <= index < len(self):\n raise ValueError(\"list index out of range.\")\n current = self.head\n for _ in range(index):\n current = current.next_node\n current.data = data\n\n def insert_tail(self, data: Any) -> None:\n \"\"\"\n Insert data to the end of linked list.\n >>> linked_list = LinkedList()\n >>> linked_list.insert_tail(\"tail\")\n >>> linked_list\n tail\n >>> linked_list.insert_tail(\"tail_2\")\n >>> linked_list\n tail -> tail_2\n >>> linked_list.insert_tail(\"tail_3\")\n >>> linked_list\n tail -> tail_2 -> tail_3\n \"\"\"\n self.insert_nth(len(self), data)\n\n def insert_head(self, data: Any) -> None:\n \"\"\"\n Insert data to the beginning of linked list.\n >>> linked_list = LinkedList()\n >>> linked_list.insert_head(\"head\")\n >>> linked_list\n head\n >>> linked_list.insert_head(\"head_2\")\n >>> linked_list\n head_2 -> head\n >>> linked_list.insert_head(\"head_3\")\n >>> linked_list\n head_3 -> head_2 -> head\n \"\"\"\n self.insert_nth(0, data)\n\n def insert_nth(self, index: int, data: Any) -> None:\n \"\"\"\n Insert data at given index.\n >>> linked_list = LinkedList()\n >>> linked_list.insert_tail(\"first\")\n >>> linked_list.insert_tail(\"second\")\n >>> linked_list.insert_tail(\"third\")\n >>> linked_list\n first -> second -> third\n >>> linked_list.insert_nth(1, \"fourth\")\n >>> linked_list\n first -> fourth -> second -> third\n >>> linked_list.insert_nth(3, \"fifth\")\n >>> linked_list\n first -> fourth -> second -> fifth -> third\n \"\"\"\n if not 0 <= index <= len(self):\n raise IndexError(\"list index out of range\")\n new_node = Node(data)\n if self.head is None:\n self.head = new_node\n elif index == 0:\n new_node.next_node = self.head # link new_node to head\n self.head = new_node\n else:\n temp = self.head\n for _ in range(index - 1):\n temp = temp.next_node\n new_node.next_node = temp.next_node\n temp.next_node = new_node\n\n def print_list(self) -> None: # print every node data\n \"\"\"\n This method prints every node data.\n >>> linked_list = LinkedList()\n >>> linked_list.insert_tail(\"first\")\n >>> linked_list.insert_tail(\"second\")\n >>> linked_list.insert_tail(\"third\")\n >>> linked_list\n first -> second -> third\n \"\"\"\n print(self)\n\n def delete_head(self) -> Any:\n \"\"\"\n Delete the first node and return the\n node's data.\n >>> linked_list = LinkedList()\n >>> linked_list.insert_tail(\"first\")\n >>> linked_list.insert_tail(\"second\")\n >>> linked_list.insert_tail(\"third\")\n >>> linked_list\n first -> second -> third\n >>> linked_list.delete_head()\n 'first'\n >>> linked_list\n second -> third\n >>> linked_list.delete_head()\n 'second'\n >>> linked_list\n third\n >>> linked_list.delete_head()\n 'third'\n >>> linked_list.delete_head()\n Traceback (most recent call last):\n ...\n IndexError: List index out of range.\n \"\"\"\n return self.delete_nth(0)\n\n def delete_tail(self) -> Any: # delete from tail\n \"\"\"\n Delete the tail end node and return the\n node's data.\n >>> linked_list = LinkedList()\n >>> linked_list.insert_tail(\"first\")\n >>> linked_list.insert_tail(\"second\")\n >>> linked_list.insert_tail(\"third\")\n >>> linked_list\n first -> second -> third\n >>> linked_list.delete_tail()\n 'third'\n >>> linked_list\n first -> second\n >>> linked_list.delete_tail()\n 'second'\n >>> linked_list\n first\n >>> linked_list.delete_tail()\n 'first'\n >>> linked_list.delete_tail()\n Traceback (most recent call last):\n ...\n IndexError: List index out of range.\n \"\"\"\n return self.delete_nth(len(self) - 1)\n\n def delete_nth(self, index: int = 0) -> Any:\n \"\"\"\n Delete node at given index and return the\n node's data.\n >>> linked_list = LinkedList()\n >>> linked_list.insert_tail(\"first\")\n >>> linked_list.insert_tail(\"second\")\n >>> linked_list.insert_tail(\"third\")\n >>> linked_list\n first -> second -> third\n >>> linked_list.delete_nth(1) # delete middle\n 'second'\n >>> linked_list\n first -> third\n >>> linked_list.delete_nth(5) # this raises error\n Traceback (most recent call last):\n ...\n IndexError: List index out of range.\n >>> linked_list.delete_nth(-1) # this also raises error\n Traceback (most recent call last):\n ...\n IndexError: List index out of range.\n \"\"\"\n if not 0 <= index <= len(self) - 1: # test if index is valid\n raise IndexError(\"List index out of range.\")\n delete_node = self.head # default first node\n if index == 0:\n self.head = self.head.next_node\n else:\n temp = self.head\n for _ in range(index - 1):\n temp = temp.next_node\n delete_node = temp.next_node\n temp.next_node = temp.next_node.next_node\n return delete_node.data\n\n def is_empty(self) -> bool:\n \"\"\"\n Check if linked list is empty.\n >>> linked_list = LinkedList()\n >>> linked_list.is_empty()\n True\n >>> linked_list.insert_head(\"first\")\n >>> linked_list.is_empty()\n False\n \"\"\"\n return self.head is None\n\n def reverse(self) -> None:\n \"\"\"\n This reverses the linked list order.\n >>> linked_list = LinkedList()\n >>> linked_list.insert_tail(\"first\")\n >>> linked_list.insert_tail(\"second\")\n >>> linked_list.insert_tail(\"third\")\n >>> linked_list\n first -> second -> third\n >>> linked_list.reverse()\n >>> linked_list\n third -> second -> first\n \"\"\"\n prev = None\n current = self.head\n\n while current:\n # Store the current node's next node.\n next_node = current.next_node\n # Make the current node's next_node point backwards\n current.next_node = prev\n # Make the previous node be the current node\n prev = current\n # Make the current node the next_node node (to progress iteration)\n current = next_node\n # Return prev in order to put the head at the end\n self.head = prev\n\n\ndef test_singly_linked_list() -> None:\n \"\"\"\n >>> test_singly_linked_list()\n \"\"\"\n linked_list = LinkedList()\n assert linked_list.is_empty() is True\n assert str(linked_list) == \"\"\n\n try:\n linked_list.delete_head()\n raise AssertionError # This should not happen.\n except IndexError:\n assert True # This should happen.\n\n try:\n linked_list.delete_tail()\n raise AssertionError # This should not happen.\n except IndexError:\n assert True # This should happen.\n\n for i in range(10):\n assert len(linked_list) == i\n linked_list.insert_nth(i, i + 1)\n assert str(linked_list) == \" -> \".join(str(i) for i in range(1, 11))\n\n linked_list.insert_head(0)\n linked_list.insert_tail(11)\n assert str(linked_list) == \" -> \".join(str(i) for i in range(12))\n\n assert linked_list.delete_head() == 0\n assert linked_list.delete_nth(9) == 10\n assert linked_list.delete_tail() == 11\n assert len(linked_list) == 9\n assert str(linked_list) == \" -> \".join(str(i) for i in range(1, 10))\n\n assert all(linked_list[i] == i + 1 for i in range(9)) is True\n\n for i in range(9):\n linked_list[i] = -i\n assert all(linked_list[i] == -i for i in range(9)) is True\n\n linked_list.reverse()\n assert str(linked_list) == \" -> \".join(str(i) for i in range(-8, 1))\n\n\ndef test_singly_linked_list_2() -> None:\n \"\"\"\n This section of the test used varying data types for input.\n >>> test_singly_linked_list_2()\n \"\"\"\n test_input = [\n -9,\n 100,\n Node(77345112),\n \"dlrow olleH\",\n 7,\n 5555,\n 0,\n -192.55555,\n \"Hello, world!\",\n 77.9,\n Node(10),\n None,\n None,\n 12.20,\n ]\n linked_list = LinkedList()\n\n for i in test_input:\n linked_list.insert_tail(i)\n\n # Check if it's empty or not\n assert linked_list.is_empty() is False\n assert (\n str(linked_list)\n == \"-9 -> 100 -> Node(77345112) -> dlrow olleH -> 7 -> 5555 -> \"\n \"0 -> -192.55555 -> Hello, world! -> 77.9 -> Node(10) -> None -> None -> 12.2\"\n )\n\n # Delete the head\n result = linked_list.delete_head()\n assert result == -9\n assert (\n str(linked_list) == \"100 -> Node(77345112) -> dlrow olleH -> 7 -> 5555 -> 0 -> \"\n \"-192.55555 -> Hello, world! -> 77.9 -> Node(10) -> None -> None -> 12.2\"\n )\n\n # Delete the tail\n result = linked_list.delete_tail()\n assert result == 12.2\n assert (\n str(linked_list) == \"100 -> Node(77345112) -> dlrow olleH -> 7 -> 5555 -> 0 -> \"\n \"-192.55555 -> Hello, world! -> 77.9 -> Node(10) -> None -> None\"\n )\n\n # Delete a node in specific location in linked list\n result = linked_list.delete_nth(10)\n assert result is None\n assert (\n str(linked_list) == \"100 -> Node(77345112) -> dlrow olleH -> 7 -> 5555 -> 0 -> \"\n \"-192.55555 -> Hello, world! -> 77.9 -> Node(10) -> None\"\n )\n\n # Add a Node instance to its head\n linked_list.insert_head(Node(\"Hello again, world!\"))\n assert (\n str(linked_list)\n == \"Node(Hello again, world!) -> 100 -> Node(77345112) -> dlrow olleH -> \"\n \"7 -> 5555 -> 0 -> -192.55555 -> Hello, world! -> 77.9 -> Node(10) -> None\"\n )\n\n # Add None to its tail\n linked_list.insert_tail(None)\n assert (\n str(linked_list)\n == \"Node(Hello again, world!) -> 100 -> Node(77345112) -> dlrow olleH -> 7 -> \"\n \"5555 -> 0 -> -192.55555 -> Hello, world! -> 77.9 -> Node(10) -> None -> None\"\n )\n\n # Reverse the linked list\n linked_list.reverse()\n assert (\n str(linked_list)\n == \"None -> None -> Node(10) -> 77.9 -> Hello, world! -> -192.55555 -> 0 -> \"\n \"5555 -> 7 -> dlrow olleH -> Node(77345112) -> 100 -> Node(Hello again, world!)\"\n )\n\n\ndef main():\n from doctest import testmod\n\n testmod()\n\n linked_list = LinkedList()\n linked_list.insert_head(input(\"Inserting 1st at head \").strip())\n linked_list.insert_head(input(\"Inserting 2nd at head \").strip())\n print(\"\\nPrint list:\")\n linked_list.print_list()\n linked_list.insert_tail(input(\"\\nInserting 1st at tail \").strip())\n linked_list.insert_tail(input(\"Inserting 2nd at tail \").strip())\n print(\"\\nPrint list:\")\n linked_list.print_list()\n print(\"\\nDelete head\")\n linked_list.delete_head()\n print(\"Delete tail\")\n linked_list.delete_tail()\n print(\"\\nPrint list:\")\n linked_list.print_list()\n print(\"\\nReverse linked list\")\n linked_list.reverse()\n print(\"\\nPrint list:\")\n linked_list.print_list()\n print(\"\\nString representation of linked list:\")\n print(linked_list)\n print(\"\\nReading\/changing Node data using indexing:\")\n print(f\"Element at Position 1: {linked_list[1]}\")\n linked_list[1] = input(\"Enter New Value: \").strip()\n print(\"New list:\")\n print(linked_list)\n print(f\"length of linked_list is : {len(linked_list)}\")\n\n\nif __name__ == \"__main__\":\n main()\n"} +{"Prompt":"Based on Skip Lists: A Probabilistic Alternative to Balanced Trees by William Pugh https:epaperpress.comsortsearchdownloadskiplist.pdf :return: Visual representation of Node node NodeKey, 2 reprnode 'NodeKey: 2' :return: Number of forward references node NodeKey, 2 node.level 0 node.forward.appendNodeKey2, 4 node.level 1 node.forward.appendNodeKey3, 6 node.level 2 :return: Visual representation of SkipList skiplist SkipList printskiplist SkipListlevel0 skiplist.insertKey1, Value printskiplist doctest: ELLIPSIS SkipListlevel... root... Key1Key1... None ... skiplist.insertKey2, OtherValue printskiplist doctest: ELLIPSIS SkipListlevel... root... Key1Key1... Key2Key2... None ... :return: Random level from 1, self.maxlevel interval. Higher values are less likely. :param key: Searched key, :return: Tuple with searched node or None if given key is not present and list of nodes that refer if key is present of should refer to given node. Nodes with refer or should refer to output node i node.level When node level is lesser than i decrement i. node.forwardi.key key Jumping to node with key value higher or equal to searched key would result in skipping searched key. Each leftmost node relative to searched node will potentially have to be updated. lennode.forward ! 0 If current node doesn't contain any further references then searched key is not present. node.forward0.key key Next node key should be equal to search key if key is present. :param key: Key to remove from list. skiplist SkipList skiplist.insert2, Two skiplist.insert1, One skiplist.insert3, Three listskiplist 1, 2, 3 skiplist.delete2 listskiplist 1, 3 Remove or replace all references to removed node. :param key: Key to insert. :param value: Value associated with given key. skiplist SkipList skiplist.insert2, Two skiplist.find2 'Two' listskiplist 2 After level increase we have to add additional nodes to head. Change references to pass through new node. :param key: Search key. :return: Value associated with given key or None if given key is not present. skiplist SkipList skiplist.find2 skiplist.insert2, Two skiplist.find2 'Two' skiplist.insert2, Three skiplist.find2 'Three' Repeat test 100 times due to the probabilistic nature of skip list random values random bugs pytests","Completions":"from __future__ import annotations\n\nfrom random import random\nfrom typing import Generic, TypeVar\n\nKT = TypeVar(\"KT\")\nVT = TypeVar(\"VT\")\n\n\nclass Node(Generic[KT, VT]):\n def __init__(self, key: KT | str = \"root\", value: VT | None = None):\n self.key = key\n self.value = value\n self.forward: list[Node[KT, VT]] = []\n\n def __repr__(self) -> str:\n \"\"\"\n :return: Visual representation of Node\n\n >>> node = Node(\"Key\", 2)\n >>> repr(node)\n 'Node(Key: 2)'\n \"\"\"\n\n return f\"Node({self.key}: {self.value})\"\n\n @property\n def level(self) -> int:\n \"\"\"\n :return: Number of forward references\n\n >>> node = Node(\"Key\", 2)\n >>> node.level\n 0\n >>> node.forward.append(Node(\"Key2\", 4))\n >>> node.level\n 1\n >>> node.forward.append(Node(\"Key3\", 6))\n >>> node.level\n 2\n \"\"\"\n\n return len(self.forward)\n\n\nclass SkipList(Generic[KT, VT]):\n def __init__(self, p: float = 0.5, max_level: int = 16):\n self.head: Node[KT, VT] = Node[KT, VT]()\n self.level = 0\n self.p = p\n self.max_level = max_level\n\n def __str__(self) -> str:\n \"\"\"\n :return: Visual representation of SkipList\n\n >>> skip_list = SkipList()\n >>> print(skip_list)\n SkipList(level=0)\n >>> skip_list.insert(\"Key1\", \"Value\")\n >>> print(skip_list) # doctest: +ELLIPSIS\n SkipList(level=...\n [root]--...\n [Key1]--Key1...\n None *...\n >>> skip_list.insert(\"Key2\", \"OtherValue\")\n >>> print(skip_list) # doctest: +ELLIPSIS\n SkipList(level=...\n [root]--...\n [Key1]--Key1...\n [Key2]--Key2...\n None *...\n \"\"\"\n\n items = list(self)\n\n if len(items) == 0:\n return f\"SkipList(level={self.level})\"\n\n label_size = max((len(str(item)) for item in items), default=4)\n label_size = max(label_size, 4) + 4\n\n node = self.head\n lines = []\n\n forwards = node.forward.copy()\n lines.append(f\"[{node.key}]\".ljust(label_size, \"-\") + \"* \" * len(forwards))\n lines.append(\" \" * label_size + \"| \" * len(forwards))\n\n while len(node.forward) != 0:\n node = node.forward[0]\n\n lines.append(\n f\"[{node.key}]\".ljust(label_size, \"-\")\n + \" \".join(str(n.key) if n.key == node.key else \"|\" for n in forwards)\n )\n lines.append(\" \" * label_size + \"| \" * len(forwards))\n forwards[: node.level] = node.forward\n\n lines.append(\"None\".ljust(label_size) + \"* \" * len(forwards))\n return f\"SkipList(level={self.level})\\n\" + \"\\n\".join(lines)\n\n def __iter__(self):\n node = self.head\n\n while len(node.forward) != 0:\n yield node.forward[0].key\n node = node.forward[0]\n\n def random_level(self) -> int:\n \"\"\"\n :return: Random level from [1, self.max_level] interval.\n Higher values are less likely.\n \"\"\"\n\n level = 1\n while random() < self.p and level < self.max_level:\n level += 1\n\n return level\n\n def _locate_node(self, key) -> tuple[Node[KT, VT] | None, list[Node[KT, VT]]]:\n \"\"\"\n :param key: Searched key,\n :return: Tuple with searched node (or None if given key is not present)\n and list of nodes that refer (if key is present) of should refer to\n given node.\n \"\"\"\n\n # Nodes with refer or should refer to output node\n update_vector = []\n\n node = self.head\n\n for i in reversed(range(self.level)):\n # i < node.level - When node level is lesser than `i` decrement `i`.\n # node.forward[i].key < key - Jumping to node with key value higher\n # or equal to searched key would result\n # in skipping searched key.\n while i < node.level and node.forward[i].key < key:\n node = node.forward[i]\n # Each leftmost node (relative to searched node) will potentially have to\n # be updated.\n update_vector.append(node)\n\n update_vector.reverse() # Note that we were inserting values in reverse order.\n\n # len(node.forward) != 0 - If current node doesn't contain any further\n # references then searched key is not present.\n # node.forward[0].key == key - Next node key should be equal to search key\n # if key is present.\n if len(node.forward) != 0 and node.forward[0].key == key:\n return node.forward[0], update_vector\n else:\n return None, update_vector\n\n def delete(self, key: KT):\n \"\"\"\n :param key: Key to remove from list.\n\n >>> skip_list = SkipList()\n >>> skip_list.insert(2, \"Two\")\n >>> skip_list.insert(1, \"One\")\n >>> skip_list.insert(3, \"Three\")\n >>> list(skip_list)\n [1, 2, 3]\n >>> skip_list.delete(2)\n >>> list(skip_list)\n [1, 3]\n \"\"\"\n\n node, update_vector = self._locate_node(key)\n\n if node is not None:\n for i, update_node in enumerate(update_vector):\n # Remove or replace all references to removed node.\n if update_node.level > i and update_node.forward[i].key == key:\n if node.level > i:\n update_node.forward[i] = node.forward[i]\n else:\n update_node.forward = update_node.forward[:i]\n\n def insert(self, key: KT, value: VT):\n \"\"\"\n :param key: Key to insert.\n :param value: Value associated with given key.\n\n >>> skip_list = SkipList()\n >>> skip_list.insert(2, \"Two\")\n >>> skip_list.find(2)\n 'Two'\n >>> list(skip_list)\n [2]\n \"\"\"\n\n node, update_vector = self._locate_node(key)\n if node is not None:\n node.value = value\n else:\n level = self.random_level()\n\n if level > self.level:\n # After level increase we have to add additional nodes to head.\n for _ in range(self.level - 1, level):\n update_vector.append(self.head)\n self.level = level\n\n new_node = Node(key, value)\n\n for i, update_node in enumerate(update_vector[:level]):\n # Change references to pass through new node.\n if update_node.level > i:\n new_node.forward.append(update_node.forward[i])\n\n if update_node.level < i + 1:\n update_node.forward.append(new_node)\n else:\n update_node.forward[i] = new_node\n\n def find(self, key: VT) -> VT | None:\n \"\"\"\n :param key: Search key.\n :return: Value associated with given key or None if given key is not present.\n\n >>> skip_list = SkipList()\n >>> skip_list.find(2)\n >>> skip_list.insert(2, \"Two\")\n >>> skip_list.find(2)\n 'Two'\n >>> skip_list.insert(2, \"Three\")\n >>> skip_list.find(2)\n 'Three'\n \"\"\"\n\n node, _ = self._locate_node(key)\n\n if node is not None:\n return node.value\n\n return None\n\n\ndef test_insert():\n skip_list = SkipList()\n skip_list.insert(\"Key1\", 3)\n skip_list.insert(\"Key2\", 12)\n skip_list.insert(\"Key3\", 41)\n skip_list.insert(\"Key4\", -19)\n\n node = skip_list.head\n all_values = {}\n while node.level != 0:\n node = node.forward[0]\n all_values[node.key] = node.value\n\n assert len(all_values) == 4\n assert all_values[\"Key1\"] == 3\n assert all_values[\"Key2\"] == 12\n assert all_values[\"Key3\"] == 41\n assert all_values[\"Key4\"] == -19\n\n\ndef test_insert_overrides_existing_value():\n skip_list = SkipList()\n skip_list.insert(\"Key1\", 10)\n skip_list.insert(\"Key1\", 12)\n\n skip_list.insert(\"Key5\", 7)\n skip_list.insert(\"Key7\", 10)\n skip_list.insert(\"Key10\", 5)\n\n skip_list.insert(\"Key7\", 7)\n skip_list.insert(\"Key5\", 5)\n skip_list.insert(\"Key10\", 10)\n\n node = skip_list.head\n all_values = {}\n while node.level != 0:\n node = node.forward[0]\n all_values[node.key] = node.value\n\n if len(all_values) != 4:\n print()\n assert len(all_values) == 4\n assert all_values[\"Key1\"] == 12\n assert all_values[\"Key7\"] == 7\n assert all_values[\"Key5\"] == 5\n assert all_values[\"Key10\"] == 10\n\n\ndef test_searching_empty_list_returns_none():\n skip_list = SkipList()\n assert skip_list.find(\"Some key\") is None\n\n\ndef test_search():\n skip_list = SkipList()\n\n skip_list.insert(\"Key2\", 20)\n assert skip_list.find(\"Key2\") == 20\n\n skip_list.insert(\"Some Key\", 10)\n skip_list.insert(\"Key2\", 8)\n skip_list.insert(\"V\", 13)\n\n assert skip_list.find(\"Y\") is None\n assert skip_list.find(\"Key2\") == 8\n assert skip_list.find(\"Some Key\") == 10\n assert skip_list.find(\"V\") == 13\n\n\ndef test_deleting_item_from_empty_list_do_nothing():\n skip_list = SkipList()\n skip_list.delete(\"Some key\")\n\n assert len(skip_list.head.forward) == 0\n\n\ndef test_deleted_items_are_not_founded_by_find_method():\n skip_list = SkipList()\n\n skip_list.insert(\"Key1\", 12)\n skip_list.insert(\"V\", 13)\n skip_list.insert(\"X\", 14)\n skip_list.insert(\"Key2\", 15)\n\n skip_list.delete(\"V\")\n skip_list.delete(\"Key2\")\n\n assert skip_list.find(\"V\") is None\n assert skip_list.find(\"Key2\") is None\n\n\ndef test_delete_removes_only_given_key():\n skip_list = SkipList()\n\n skip_list.insert(\"Key1\", 12)\n skip_list.insert(\"V\", 13)\n skip_list.insert(\"X\", 14)\n skip_list.insert(\"Key2\", 15)\n\n skip_list.delete(\"V\")\n assert skip_list.find(\"V\") is None\n assert skip_list.find(\"X\") == 14\n assert skip_list.find(\"Key1\") == 12\n assert skip_list.find(\"Key2\") == 15\n\n skip_list.delete(\"X\")\n assert skip_list.find(\"V\") is None\n assert skip_list.find(\"X\") is None\n assert skip_list.find(\"Key1\") == 12\n assert skip_list.find(\"Key2\") == 15\n\n skip_list.delete(\"Key1\")\n assert skip_list.find(\"V\") is None\n assert skip_list.find(\"X\") is None\n assert skip_list.find(\"Key1\") is None\n assert skip_list.find(\"Key2\") == 15\n\n skip_list.delete(\"Key2\")\n assert skip_list.find(\"V\") is None\n assert skip_list.find(\"X\") is None\n assert skip_list.find(\"Key1\") is None\n assert skip_list.find(\"Key2\") is None\n\n\ndef test_delete_doesnt_leave_dead_nodes():\n skip_list = SkipList()\n\n skip_list.insert(\"Key1\", 12)\n skip_list.insert(\"V\", 13)\n skip_list.insert(\"X\", 142)\n skip_list.insert(\"Key2\", 15)\n\n skip_list.delete(\"X\")\n\n def traverse_keys(node):\n yield node.key\n for forward_node in node.forward:\n yield from traverse_keys(forward_node)\n\n assert len(set(traverse_keys(skip_list.head))) == 4\n\n\ndef test_iter_always_yields_sorted_values():\n def is_sorted(lst):\n return all(next_item >= item for item, next_item in zip(lst, lst[1:]))\n\n skip_list = SkipList()\n for i in range(10):\n skip_list.insert(i, i)\n assert is_sorted(list(skip_list))\n skip_list.delete(5)\n skip_list.delete(8)\n skip_list.delete(2)\n assert is_sorted(list(skip_list))\n skip_list.insert(-12, -12)\n skip_list.insert(77, 77)\n assert is_sorted(list(skip_list))\n\n\ndef pytests():\n for _ in range(100):\n # Repeat test 100 times due to the probabilistic nature of skip list\n # random values == random bugs\n test_insert()\n test_insert_overrides_existing_value()\n\n test_searching_empty_list_returns_none()\n test_search()\n\n test_deleting_item_from_empty_list_do_nothing()\n test_deleted_items_are_not_founded_by_find_method()\n test_delete_removes_only_given_key()\n test_delete_doesnt_leave_dead_nodes()\n\n test_iter_always_yields_sorted_values()\n\n\ndef main():\n \"\"\"\n >>> pytests()\n \"\"\"\n\n skip_list = SkipList()\n skip_list.insert(2, \"2\")\n skip_list.insert(4, \"4\")\n skip_list.insert(6, \"4\")\n skip_list.insert(4, \"5\")\n skip_list.insert(8, \"4\")\n skip_list.insert(9, \"4\")\n\n skip_list.delete(4)\n\n print(skip_list)\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n main()\n"} +{"Prompt":"linkedlist LinkedList listlinkedlist linkedlist.push0 tuplelinkedlist 0, linkedlist LinkedList lenlinkedlist 0 linkedlist.push0 lenlinkedlist 1 Add a new node with the given data to the beginning of the Linked List. Args: newdata Any: The data to be added to the new node. Returns: None Examples: linkedlist LinkedList linkedlist.push5 linkedlist.push4 linkedlist.push3 linkedlist.push2 linkedlist.push1 listlinkedlist 1, 2, 3, 4, 5 Swap the positions of two nodes in the Linked List based on their data values. Args: nodedata1: Data value of the first node to be swapped. nodedata2: Data value of the second node to be swapped. Note: If either of the specified data values isn't found then, no swapping occurs. Examples: When both values are present in a linked list. linkedlist LinkedList linkedlist.push5 linkedlist.push4 linkedlist.push3 linkedlist.push2 linkedlist.push1 listlinkedlist 1, 2, 3, 4, 5 linkedlist.swapnodes1, 5 tuplelinkedlist 5, 2, 3, 4, 1 When one value is present and the other isn't in the linked list. secondlist LinkedList secondlist.push6 secondlist.push7 secondlist.push8 secondlist.push9 secondlist.swapnodes1, 6 is None True When both values are absent in the linked list. secondlist LinkedList secondlist.push10 secondlist.push9 secondlist.push8 secondlist.push7 secondlist.swapnodes1, 3 is None True When linkedlist is empty. secondlist LinkedList secondlist.swapnodes1, 3 is None True Returns: None Swap the data values of the two nodes Python script that outputs the swap of nodes in a linked list.","Completions":"from __future__ import annotations\n\nfrom collections.abc import Iterator\nfrom dataclasses import dataclass\nfrom typing import Any\n\n\n@dataclass\nclass Node:\n data: Any\n next_node: Node | None = None\n\n\n@dataclass\nclass LinkedList:\n head: Node | None = None\n\n def __iter__(self) -> Iterator:\n \"\"\"\n >>> linked_list = LinkedList()\n >>> list(linked_list)\n []\n >>> linked_list.push(0)\n >>> tuple(linked_list)\n (0,)\n \"\"\"\n node = self.head\n while node:\n yield node.data\n node = node.next_node\n\n def __len__(self) -> int:\n \"\"\"\n >>> linked_list = LinkedList()\n >>> len(linked_list)\n 0\n >>> linked_list.push(0)\n >>> len(linked_list)\n 1\n \"\"\"\n return sum(1 for _ in self)\n\n def push(self, new_data: Any) -> None:\n \"\"\"\n Add a new node with the given data to the beginning of the Linked List.\n\n Args:\n new_data (Any): The data to be added to the new node.\n\n Returns:\n None\n\n Examples:\n >>> linked_list = LinkedList()\n >>> linked_list.push(5)\n >>> linked_list.push(4)\n >>> linked_list.push(3)\n >>> linked_list.push(2)\n >>> linked_list.push(1)\n >>> list(linked_list)\n [1, 2, 3, 4, 5]\n \"\"\"\n new_node = Node(new_data)\n new_node.next_node = self.head\n self.head = new_node\n\n def swap_nodes(self, node_data_1: Any, node_data_2: Any) -> None:\n \"\"\"\n Swap the positions of two nodes in the Linked List based on their data values.\n\n Args:\n node_data_1: Data value of the first node to be swapped.\n node_data_2: Data value of the second node to be swapped.\n\n\n Note:\n If either of the specified data values isn't found then, no swapping occurs.\n\n Examples:\n When both values are present in a linked list.\n >>> linked_list = LinkedList()\n >>> linked_list.push(5)\n >>> linked_list.push(4)\n >>> linked_list.push(3)\n >>> linked_list.push(2)\n >>> linked_list.push(1)\n >>> list(linked_list)\n [1, 2, 3, 4, 5]\n >>> linked_list.swap_nodes(1, 5)\n >>> tuple(linked_list)\n (5, 2, 3, 4, 1)\n\n When one value is present and the other isn't in the linked list.\n >>> second_list = LinkedList()\n >>> second_list.push(6)\n >>> second_list.push(7)\n >>> second_list.push(8)\n >>> second_list.push(9)\n >>> second_list.swap_nodes(1, 6) is None\n True\n\n When both values are absent in the linked list.\n >>> second_list = LinkedList()\n >>> second_list.push(10)\n >>> second_list.push(9)\n >>> second_list.push(8)\n >>> second_list.push(7)\n >>> second_list.swap_nodes(1, 3) is None\n True\n\n When linkedlist is empty.\n >>> second_list = LinkedList()\n >>> second_list.swap_nodes(1, 3) is None\n True\n\n Returns:\n None\n \"\"\"\n if node_data_1 == node_data_2:\n return\n\n node_1 = self.head\n while node_1 and node_1.data != node_data_1:\n node_1 = node_1.next_node\n node_2 = self.head\n while node_2 and node_2.data != node_data_2:\n node_2 = node_2.next_node\n if node_1 is None or node_2 is None:\n return\n # Swap the data values of the two nodes\n node_1.data, node_2.data = node_2.data, node_1.data\n\n\nif __name__ == \"__main__\":\n \"\"\"\n Python script that outputs the swap of nodes in a linked list.\n \"\"\"\n from doctest import testmod\n\n testmod()\n linked_list = LinkedList()\n for i in range(5, 0, -1):\n linked_list.push(i)\n\n print(f\"Original Linked List: {list(linked_list)}\")\n linked_list.swap_nodes(1, 4)\n print(f\"Modified Linked List: {list(linked_list)}\")\n print(\"After swapping the nodes whose data is 1 and 4.\")\n"} +{"Prompt":"Implementation of Circular Queue using Python lists Circular FIFO queue with a fixed capacity def initself, n: int: self.n n self.array None self.n self.front 0 index of the first element self.rear 0 self.size 0 def lenself int: return self.size def isemptyself bool: return self.size 0 def firstself: return False if self.isempty else self.arrayself.front def enqueueself, data: if self.size self.n: raise ExceptionQUEUE IS FULL self.arrayself.rear data self.rear self.rear 1 self.n self.size 1 return self def dequeueself: if self.size 0: raise ExceptionUNDERFLOW temp self.arrayself.front self.arrayself.front None self.front self.front 1 self.n self.size 1 return temp","Completions":"# Implementation of Circular Queue (using Python lists)\n\n\nclass CircularQueue:\n \"\"\"Circular FIFO queue with a fixed capacity\"\"\"\n\n def __init__(self, n: int):\n self.n = n\n self.array = [None] * self.n\n self.front = 0 # index of the first element\n self.rear = 0\n self.size = 0\n\n def __len__(self) -> int:\n \"\"\"\n >>> cq = CircularQueue(5)\n >>> len(cq)\n 0\n >>> cq.enqueue(\"A\") # doctest: +ELLIPSIS\n >> len(cq)\n 1\n \"\"\"\n return self.size\n\n def is_empty(self) -> bool:\n \"\"\"\n >>> cq = CircularQueue(5)\n >>> cq.is_empty()\n True\n >>> cq.enqueue(\"A\").is_empty()\n False\n \"\"\"\n return self.size == 0\n\n def first(self):\n \"\"\"\n >>> cq = CircularQueue(5)\n >>> cq.first()\n False\n >>> cq.enqueue(\"A\").first()\n 'A'\n \"\"\"\n return False if self.is_empty() else self.array[self.front]\n\n def enqueue(self, data):\n \"\"\"\n This function insert an element in the queue using self.rear value as an index\n >>> cq = CircularQueue(5)\n >>> cq.enqueue(\"A\") # doctest: +ELLIPSIS\n >> (cq.size, cq.first())\n (1, 'A')\n >>> cq.enqueue(\"B\") # doctest: +ELLIPSIS\n >> (cq.size, cq.first())\n (2, 'A')\n \"\"\"\n if self.size >= self.n:\n raise Exception(\"QUEUE IS FULL\")\n\n self.array[self.rear] = data\n self.rear = (self.rear + 1) % self.n\n self.size += 1\n return self\n\n def dequeue(self):\n \"\"\"\n This function removes an element from the queue using on self.front value as an\n index\n >>> cq = CircularQueue(5)\n >>> cq.dequeue()\n Traceback (most recent call last):\n ...\n Exception: UNDERFLOW\n >>> cq.enqueue(\"A\").enqueue(\"B\").dequeue()\n 'A'\n >>> (cq.size, cq.first())\n (1, 'B')\n >>> cq.dequeue()\n 'B'\n >>> cq.dequeue()\n Traceback (most recent call last):\n ...\n Exception: UNDERFLOW\n \"\"\"\n if self.size == 0:\n raise Exception(\"UNDERFLOW\")\n\n temp = self.array[self.front]\n self.array[self.front] = None\n self.front = (self.front + 1) % self.n\n self.size -= 1\n return temp\n"} +{"Prompt":"Implementation of Circular Queue using linked lists https:en.wikipedia.orgwikiCircularbuffer Circular FIFO list with the given capacity default queue length : 6 cq CircularQueueLinkedList2 cq.enqueue'a' cq.enqueue'b' cq.enqueue'c' Traceback most recent call last: ... Exception: Full Queue Checks where the queue is empty or not cq CircularQueueLinkedList cq.isempty True cq.enqueue'a' cq.isempty False cq.dequeue 'a' cq.isempty True Returns the first element of the queue cq CircularQueueLinkedList cq.first Traceback most recent call last: ... Exception: Empty Queue cq.enqueue'a' cq.first 'a' cq.dequeue 'a' cq.first Traceback most recent call last: ... Exception: Empty Queue cq.enqueue'b' cq.enqueue'c' cq.first 'b' Saves data at the end of the queue cq CircularQueueLinkedList cq.enqueue'a' cq.enqueue'b' cq.dequeue 'a' cq.dequeue 'b' cq.dequeue Traceback most recent call last: ... Exception: Empty Queue Removes and retrieves the first element of the queue cq CircularQueueLinkedList cq.dequeue Traceback most recent call last: ... Exception: Empty Queue cq.enqueue'a' cq.dequeue 'a' cq.dequeue Traceback most recent call last: ... Exception: Empty Queue","Completions":"# Implementation of Circular Queue using linked lists\n# https:\/\/en.wikipedia.org\/wiki\/Circular_buffer\n\nfrom __future__ import annotations\n\nfrom typing import Any\n\n\nclass CircularQueueLinkedList:\n \"\"\"\n Circular FIFO list with the given capacity (default queue length : 6)\n\n >>> cq = CircularQueueLinkedList(2)\n >>> cq.enqueue('a')\n >>> cq.enqueue('b')\n >>> cq.enqueue('c')\n Traceback (most recent call last):\n ...\n Exception: Full Queue\n \"\"\"\n\n def __init__(self, initial_capacity: int = 6) -> None:\n self.front: Node | None = None\n self.rear: Node | None = None\n self.create_linked_list(initial_capacity)\n\n def create_linked_list(self, initial_capacity: int) -> None:\n current_node = Node()\n self.front = current_node\n self.rear = current_node\n previous_node = current_node\n for _ in range(1, initial_capacity):\n current_node = Node()\n previous_node.next = current_node\n current_node.prev = previous_node\n previous_node = current_node\n previous_node.next = self.front\n self.front.prev = previous_node\n\n def is_empty(self) -> bool:\n \"\"\"\n Checks where the queue is empty or not\n >>> cq = CircularQueueLinkedList()\n >>> cq.is_empty()\n True\n >>> cq.enqueue('a')\n >>> cq.is_empty()\n False\n >>> cq.dequeue()\n 'a'\n >>> cq.is_empty()\n True\n \"\"\"\n\n return (\n self.front == self.rear\n and self.front is not None\n and self.front.data is None\n )\n\n def first(self) -> Any | None:\n \"\"\"\n Returns the first element of the queue\n >>> cq = CircularQueueLinkedList()\n >>> cq.first()\n Traceback (most recent call last):\n ...\n Exception: Empty Queue\n >>> cq.enqueue('a')\n >>> cq.first()\n 'a'\n >>> cq.dequeue()\n 'a'\n >>> cq.first()\n Traceback (most recent call last):\n ...\n Exception: Empty Queue\n >>> cq.enqueue('b')\n >>> cq.enqueue('c')\n >>> cq.first()\n 'b'\n \"\"\"\n self.check_can_perform_operation()\n return self.front.data if self.front else None\n\n def enqueue(self, data: Any) -> None:\n \"\"\"\n Saves data at the end of the queue\n\n >>> cq = CircularQueueLinkedList()\n >>> cq.enqueue('a')\n >>> cq.enqueue('b')\n >>> cq.dequeue()\n 'a'\n >>> cq.dequeue()\n 'b'\n >>> cq.dequeue()\n Traceback (most recent call last):\n ...\n Exception: Empty Queue\n \"\"\"\n if self.rear is None:\n return\n\n self.check_is_full()\n if not self.is_empty():\n self.rear = self.rear.next\n if self.rear:\n self.rear.data = data\n\n def dequeue(self) -> Any:\n \"\"\"\n Removes and retrieves the first element of the queue\n\n >>> cq = CircularQueueLinkedList()\n >>> cq.dequeue()\n Traceback (most recent call last):\n ...\n Exception: Empty Queue\n >>> cq.enqueue('a')\n >>> cq.dequeue()\n 'a'\n >>> cq.dequeue()\n Traceback (most recent call last):\n ...\n Exception: Empty Queue\n \"\"\"\n self.check_can_perform_operation()\n if self.rear is None or self.front is None:\n return None\n if self.front == self.rear:\n data = self.front.data\n self.front.data = None\n return data\n\n old_front = self.front\n self.front = old_front.next\n data = old_front.data\n old_front.data = None\n return data\n\n def check_can_perform_operation(self) -> None:\n if self.is_empty():\n raise Exception(\"Empty Queue\")\n\n def check_is_full(self) -> None:\n if self.rear and self.rear.next == self.front:\n raise Exception(\"Full Queue\")\n\n\nclass Node:\n def __init__(self) -> None:\n self.data: Any | None = None\n self.next: Node | None = None\n self.prev: Node | None = None\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Implementation of double ended queue. Deque data structure. Operations appendval: Any None appendleftval: Any None extenditerable: Iterable None extendleftiterable: Iterable None pop Any popleft Any Observers isempty bool Attributes front: Node front of the deque a.k.a. the first element back: Node back of the element a.k.a. the last element len: int the number of nodes Representation of a node. Contains a value and a pointer to the next node as well as to the previous one. Helper class for iteration. Will be used to implement iteration. Attributes cur: Node the current node of the iteration. ourdeque Deque1, 2, 3 iterator iterourdeque ourdeque Deque1, 2, 3 iterator iterourdeque nextiterator 1 nextiterator 2 nextiterator 3 finished iterating append every value to the deque Adds val to the end of the deque. Time complexity: O1 ourdeque1 Deque1, 2, 3 ourdeque1.append4 ourdeque1 1, 2, 3, 4 ourdeque2 Deque'ab' ourdeque2.append'c' ourdeque2 'a', 'b', 'c' from collections import deque dequecollections1 deque1, 2, 3 dequecollections1.append4 dequecollections1 deque1, 2, 3, 4 dequecollections2 deque'ab' dequecollections2.append'c' dequecollections2 deque'a', 'b', 'c' listourdeque1 listdequecollections1 True listourdeque2 listdequecollections2 True front back connect nodes make sure there were no errors Adds val to the beginning of the deque. Time complexity: O1 ourdeque1 Deque2, 3 ourdeque1.appendleft1 ourdeque1 1, 2, 3 ourdeque2 Deque'bc' ourdeque2.appendleft'a' ourdeque2 'a', 'b', 'c' from collections import deque dequecollections1 deque2, 3 dequecollections1.appendleft1 dequecollections1 deque1, 2, 3 dequecollections2 deque'bc' dequecollections2.appendleft'a' dequecollections2 deque'a', 'b', 'c' listourdeque1 listdequecollections1 True listourdeque2 listdequecollections2 True front back connect nodes make sure there were no errors Appends every value of iterable to the end of the deque. Time complexity: On ourdeque1 Deque1, 2, 3 ourdeque1.extend4, 5 ourdeque1 1, 2, 3, 4, 5 ourdeque2 Deque'ab' ourdeque2.extend'cd' ourdeque2 'a', 'b', 'c', 'd' from collections import deque dequecollections1 deque1, 2, 3 dequecollections1.extend4, 5 dequecollections1 deque1, 2, 3, 4, 5 dequecollections2 deque'ab' dequecollections2.extend'cd' dequecollections2 deque'a', 'b', 'c', 'd' listourdeque1 listdequecollections1 True listourdeque2 listdequecollections2 True Appends every value of iterable to the beginning of the deque. Time complexity: On ourdeque1 Deque1, 2, 3 ourdeque1.extendleft0, 1 ourdeque1 1, 0, 1, 2, 3 ourdeque2 Deque'cd' ourdeque2.extendleft'ba' ourdeque2 'a', 'b', 'c', 'd' from collections import deque dequecollections1 deque1, 2, 3 dequecollections1.extendleft0, 1 dequecollections1 deque1, 0, 1, 2, 3 dequecollections2 deque'cd' dequecollections2.extendleft'ba' dequecollections2 deque'a', 'b', 'c', 'd' listourdeque1 listdequecollections1 True listourdeque2 listdequecollections2 True Removes the last element of the deque and returns it. Time complexity: O1 returns topop.val: the value of the node to pop. ourdeque1 Deque1 ourpopped1 ourdeque1.pop ourpopped1 1 ourdeque1 ourdeque2 Deque1, 2, 3, 15182 ourpopped2 ourdeque2.pop ourpopped2 15182 ourdeque2 1, 2, 3 from collections import deque dequecollections deque1, 2, 3, 15182 collectionspopped dequecollections.pop collectionspopped 15182 dequecollections deque1, 2, 3 listourdeque2 listdequecollections True ourpopped2 collectionspopped True make sure the deque has elements to pop if only one element in the queue: point the front and back to None else remove one element from back drop the last node, python will deallocate memory automatically Removes the first element of the deque and returns it. Time complexity: O1 returns topop.val: the value of the node to pop. ourdeque1 Deque1 ourpopped1 ourdeque1.pop ourpopped1 1 ourdeque1 ourdeque2 Deque15182, 1, 2, 3 ourpopped2 ourdeque2.popleft ourpopped2 15182 ourdeque2 1, 2, 3 from collections import deque dequecollections deque15182, 1, 2, 3 collectionspopped dequecollections.popleft collectionspopped 15182 dequecollections deque1, 2, 3 listourdeque2 listdequecollections True ourpopped2 collectionspopped True make sure the deque has elements to pop if only one element in the queue: point the front and back to None else remove one element from front Checks if the deque is empty. Time complexity: O1 ourdeque Deque1, 2, 3 ourdeque.isempty False ouremptydeque Deque ouremptydeque.isempty True from collections import deque emptydequecollections deque listouremptydeque listemptydequecollections True Implements len function. Returns the length of the deque. Time complexity: O1 ourdeque Deque1, 2, 3 lenourdeque 3 ouremptydeque Deque lenouremptydeque 0 from collections import deque dequecollections deque1, 2, 3 lendequecollections 3 emptydequecollections deque lenemptydequecollections 0 lenouremptydeque lenemptydequecollections True Implements operator. Returns if self is equal to other. Time complexity: On ourdeque1 Deque1, 2, 3 ourdeque2 Deque1, 2, 3 ourdeque1 ourdeque2 True ourdeque3 Deque1, 2 ourdeque1 ourdeque3 False from collections import deque dequecollections1 deque1, 2, 3 dequecollections2 deque1, 2, 3 dequecollections1 dequecollections2 True dequecollections3 deque1, 2 dequecollections1 dequecollections3 False ourdeque1 ourdeque2 dequecollections1 dequecollections2 True ourdeque1 ourdeque3 dequecollections1 dequecollections3 True if the length of the dequeues are not the same, they are not equal compare every value Implements iteration. Time complexity: O1 ourdeque Deque1, 2, 3 for v in ourdeque: ... printv 1 2 3 from collections import deque dequecollections deque1, 2, 3 for v in dequecollections: ... printv 1 2 3 Implements representation of the deque. Represents it as a list, with its values between '' and ''. Time complexity: On ourdeque Deque1, 2, 3 ourdeque 1, 2, 3 append the values in a list to display","Completions":"from __future__ import annotations\n\nfrom collections.abc import Iterable\nfrom dataclasses import dataclass\nfrom typing import Any\n\n\nclass Deque:\n \"\"\"\n Deque data structure.\n Operations\n ----------\n append(val: Any) -> None\n appendleft(val: Any) -> None\n extend(iterable: Iterable) -> None\n extendleft(iterable: Iterable) -> None\n pop() -> Any\n popleft() -> Any\n Observers\n ---------\n is_empty() -> bool\n Attributes\n ----------\n _front: _Node\n front of the deque a.k.a. the first element\n _back: _Node\n back of the element a.k.a. the last element\n _len: int\n the number of nodes\n \"\"\"\n\n __slots__ = (\"_front\", \"_back\", \"_len\")\n\n @dataclass\n class _Node:\n \"\"\"\n Representation of a node.\n Contains a value and a pointer to the next node as well as to the previous one.\n \"\"\"\n\n val: Any = None\n next_node: Deque._Node | None = None\n prev_node: Deque._Node | None = None\n\n class _Iterator:\n \"\"\"\n Helper class for iteration. Will be used to implement iteration.\n Attributes\n ----------\n _cur: _Node\n the current node of the iteration.\n \"\"\"\n\n __slots__ = (\"_cur\",)\n\n def __init__(self, cur: Deque._Node | None) -> None:\n self._cur = cur\n\n def __iter__(self) -> Deque._Iterator:\n \"\"\"\n >>> our_deque = Deque([1, 2, 3])\n >>> iterator = iter(our_deque)\n \"\"\"\n return self\n\n def __next__(self) -> Any:\n \"\"\"\n >>> our_deque = Deque([1, 2, 3])\n >>> iterator = iter(our_deque)\n >>> next(iterator)\n 1\n >>> next(iterator)\n 2\n >>> next(iterator)\n 3\n \"\"\"\n if self._cur is None:\n # finished iterating\n raise StopIteration\n val = self._cur.val\n self._cur = self._cur.next_node\n\n return val\n\n def __init__(self, iterable: Iterable[Any] | None = None) -> None:\n self._front: Any = None\n self._back: Any = None\n self._len: int = 0\n\n if iterable is not None:\n # append every value to the deque\n for val in iterable:\n self.append(val)\n\n def append(self, val: Any) -> None:\n \"\"\"\n Adds val to the end of the deque.\n Time complexity: O(1)\n >>> our_deque_1 = Deque([1, 2, 3])\n >>> our_deque_1.append(4)\n >>> our_deque_1\n [1, 2, 3, 4]\n >>> our_deque_2 = Deque('ab')\n >>> our_deque_2.append('c')\n >>> our_deque_2\n ['a', 'b', 'c']\n >>> from collections import deque\n >>> deque_collections_1 = deque([1, 2, 3])\n >>> deque_collections_1.append(4)\n >>> deque_collections_1\n deque([1, 2, 3, 4])\n >>> deque_collections_2 = deque('ab')\n >>> deque_collections_2.append('c')\n >>> deque_collections_2\n deque(['a', 'b', 'c'])\n >>> list(our_deque_1) == list(deque_collections_1)\n True\n >>> list(our_deque_2) == list(deque_collections_2)\n True\n \"\"\"\n node = self._Node(val, None, None)\n if self.is_empty():\n # front = back\n self._front = self._back = node\n self._len = 1\n else:\n # connect nodes\n self._back.next_node = node\n node.prev_node = self._back\n self._back = node # assign new back to the new node\n\n self._len += 1\n\n # make sure there were no errors\n assert not self.is_empty(), \"Error on appending value.\"\n\n def appendleft(self, val: Any) -> None:\n \"\"\"\n Adds val to the beginning of the deque.\n Time complexity: O(1)\n >>> our_deque_1 = Deque([2, 3])\n >>> our_deque_1.appendleft(1)\n >>> our_deque_1\n [1, 2, 3]\n >>> our_deque_2 = Deque('bc')\n >>> our_deque_2.appendleft('a')\n >>> our_deque_2\n ['a', 'b', 'c']\n >>> from collections import deque\n >>> deque_collections_1 = deque([2, 3])\n >>> deque_collections_1.appendleft(1)\n >>> deque_collections_1\n deque([1, 2, 3])\n >>> deque_collections_2 = deque('bc')\n >>> deque_collections_2.appendleft('a')\n >>> deque_collections_2\n deque(['a', 'b', 'c'])\n >>> list(our_deque_1) == list(deque_collections_1)\n True\n >>> list(our_deque_2) == list(deque_collections_2)\n True\n \"\"\"\n node = self._Node(val, None, None)\n if self.is_empty():\n # front = back\n self._front = self._back = node\n self._len = 1\n else:\n # connect nodes\n node.next_node = self._front\n self._front.prev_node = node\n self._front = node # assign new front to the new node\n\n self._len += 1\n\n # make sure there were no errors\n assert not self.is_empty(), \"Error on appending value.\"\n\n def extend(self, iterable: Iterable[Any]) -> None:\n \"\"\"\n Appends every value of iterable to the end of the deque.\n Time complexity: O(n)\n >>> our_deque_1 = Deque([1, 2, 3])\n >>> our_deque_1.extend([4, 5])\n >>> our_deque_1\n [1, 2, 3, 4, 5]\n >>> our_deque_2 = Deque('ab')\n >>> our_deque_2.extend('cd')\n >>> our_deque_2\n ['a', 'b', 'c', 'd']\n >>> from collections import deque\n >>> deque_collections_1 = deque([1, 2, 3])\n >>> deque_collections_1.extend([4, 5])\n >>> deque_collections_1\n deque([1, 2, 3, 4, 5])\n >>> deque_collections_2 = deque('ab')\n >>> deque_collections_2.extend('cd')\n >>> deque_collections_2\n deque(['a', 'b', 'c', 'd'])\n >>> list(our_deque_1) == list(deque_collections_1)\n True\n >>> list(our_deque_2) == list(deque_collections_2)\n True\n \"\"\"\n for val in iterable:\n self.append(val)\n\n def extendleft(self, iterable: Iterable[Any]) -> None:\n \"\"\"\n Appends every value of iterable to the beginning of the deque.\n Time complexity: O(n)\n >>> our_deque_1 = Deque([1, 2, 3])\n >>> our_deque_1.extendleft([0, -1])\n >>> our_deque_1\n [-1, 0, 1, 2, 3]\n >>> our_deque_2 = Deque('cd')\n >>> our_deque_2.extendleft('ba')\n >>> our_deque_2\n ['a', 'b', 'c', 'd']\n >>> from collections import deque\n >>> deque_collections_1 = deque([1, 2, 3])\n >>> deque_collections_1.extendleft([0, -1])\n >>> deque_collections_1\n deque([-1, 0, 1, 2, 3])\n >>> deque_collections_2 = deque('cd')\n >>> deque_collections_2.extendleft('ba')\n >>> deque_collections_2\n deque(['a', 'b', 'c', 'd'])\n >>> list(our_deque_1) == list(deque_collections_1)\n True\n >>> list(our_deque_2) == list(deque_collections_2)\n True\n \"\"\"\n for val in iterable:\n self.appendleft(val)\n\n def pop(self) -> Any:\n \"\"\"\n Removes the last element of the deque and returns it.\n Time complexity: O(1)\n @returns topop.val: the value of the node to pop.\n >>> our_deque1 = Deque([1])\n >>> our_popped1 = our_deque1.pop()\n >>> our_popped1\n 1\n >>> our_deque1\n []\n\n >>> our_deque2 = Deque([1, 2, 3, 15182])\n >>> our_popped2 = our_deque2.pop()\n >>> our_popped2\n 15182\n >>> our_deque2\n [1, 2, 3]\n\n >>> from collections import deque\n >>> deque_collections = deque([1, 2, 3, 15182])\n >>> collections_popped = deque_collections.pop()\n >>> collections_popped\n 15182\n >>> deque_collections\n deque([1, 2, 3])\n >>> list(our_deque2) == list(deque_collections)\n True\n >>> our_popped2 == collections_popped\n True\n \"\"\"\n # make sure the deque has elements to pop\n assert not self.is_empty(), \"Deque is empty.\"\n\n topop = self._back\n # if only one element in the queue: point the front and back to None\n # else remove one element from back\n if self._front == self._back:\n self._front = None\n self._back = None\n else:\n self._back = self._back.prev_node # set new back\n # drop the last node, python will deallocate memory automatically\n self._back.next_node = None\n\n self._len -= 1\n\n return topop.val\n\n def popleft(self) -> Any:\n \"\"\"\n Removes the first element of the deque and returns it.\n Time complexity: O(1)\n @returns topop.val: the value of the node to pop.\n >>> our_deque1 = Deque([1])\n >>> our_popped1 = our_deque1.pop()\n >>> our_popped1\n 1\n >>> our_deque1\n []\n >>> our_deque2 = Deque([15182, 1, 2, 3])\n >>> our_popped2 = our_deque2.popleft()\n >>> our_popped2\n 15182\n >>> our_deque2\n [1, 2, 3]\n >>> from collections import deque\n >>> deque_collections = deque([15182, 1, 2, 3])\n >>> collections_popped = deque_collections.popleft()\n >>> collections_popped\n 15182\n >>> deque_collections\n deque([1, 2, 3])\n >>> list(our_deque2) == list(deque_collections)\n True\n >>> our_popped2 == collections_popped\n True\n \"\"\"\n # make sure the deque has elements to pop\n assert not self.is_empty(), \"Deque is empty.\"\n\n topop = self._front\n # if only one element in the queue: point the front and back to None\n # else remove one element from front\n if self._front == self._back:\n self._front = None\n self._back = None\n else:\n self._front = self._front.next_node # set new front and drop the first node\n self._front.prev_node = None\n\n self._len -= 1\n\n return topop.val\n\n def is_empty(self) -> bool:\n \"\"\"\n Checks if the deque is empty.\n Time complexity: O(1)\n >>> our_deque = Deque([1, 2, 3])\n >>> our_deque.is_empty()\n False\n >>> our_empty_deque = Deque()\n >>> our_empty_deque.is_empty()\n True\n >>> from collections import deque\n >>> empty_deque_collections = deque()\n >>> list(our_empty_deque) == list(empty_deque_collections)\n True\n \"\"\"\n return self._front is None\n\n def __len__(self) -> int:\n \"\"\"\n Implements len() function. Returns the length of the deque.\n Time complexity: O(1)\n >>> our_deque = Deque([1, 2, 3])\n >>> len(our_deque)\n 3\n >>> our_empty_deque = Deque()\n >>> len(our_empty_deque)\n 0\n >>> from collections import deque\n >>> deque_collections = deque([1, 2, 3])\n >>> len(deque_collections)\n 3\n >>> empty_deque_collections = deque()\n >>> len(empty_deque_collections)\n 0\n >>> len(our_empty_deque) == len(empty_deque_collections)\n True\n \"\"\"\n return self._len\n\n def __eq__(self, other: object) -> bool:\n \"\"\"\n Implements \"==\" operator. Returns if *self* is equal to *other*.\n Time complexity: O(n)\n >>> our_deque_1 = Deque([1, 2, 3])\n >>> our_deque_2 = Deque([1, 2, 3])\n >>> our_deque_1 == our_deque_2\n True\n >>> our_deque_3 = Deque([1, 2])\n >>> our_deque_1 == our_deque_3\n False\n >>> from collections import deque\n >>> deque_collections_1 = deque([1, 2, 3])\n >>> deque_collections_2 = deque([1, 2, 3])\n >>> deque_collections_1 == deque_collections_2\n True\n >>> deque_collections_3 = deque([1, 2])\n >>> deque_collections_1 == deque_collections_3\n False\n >>> (our_deque_1 == our_deque_2) == (deque_collections_1 == deque_collections_2)\n True\n >>> (our_deque_1 == our_deque_3) == (deque_collections_1 == deque_collections_3)\n True\n \"\"\"\n\n if not isinstance(other, Deque):\n return NotImplemented\n\n me = self._front\n oth = other._front\n\n # if the length of the dequeues are not the same, they are not equal\n if len(self) != len(other):\n return False\n\n while me is not None and oth is not None:\n # compare every value\n if me.val != oth.val:\n return False\n me = me.next_node\n oth = oth.next_node\n\n return True\n\n def __iter__(self) -> Deque._Iterator:\n \"\"\"\n Implements iteration.\n Time complexity: O(1)\n >>> our_deque = Deque([1, 2, 3])\n >>> for v in our_deque:\n ... print(v)\n 1\n 2\n 3\n >>> from collections import deque\n >>> deque_collections = deque([1, 2, 3])\n >>> for v in deque_collections:\n ... print(v)\n 1\n 2\n 3\n \"\"\"\n return Deque._Iterator(self._front)\n\n def __repr__(self) -> str:\n \"\"\"\n Implements representation of the deque.\n Represents it as a list, with its values between '[' and ']'.\n Time complexity: O(n)\n >>> our_deque = Deque([1, 2, 3])\n >>> our_deque\n [1, 2, 3]\n \"\"\"\n values_list = []\n aux = self._front\n while aux is not None:\n # append the values in a list to display\n values_list.append(aux.val)\n aux = aux.next_node\n\n return f\"[{', '.join(repr(val) for val in values_list)}]\"\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n dq = Deque([3])\n dq.pop()\n"} +{"Prompt":"A Queue using a linked list like structure from future import annotations from collections.abc import Iterator from typing import Any class Node: def initself, data: Any None: self.data: Any data self.next: Node None None def strself str: return fself.data class LinkedQueue: def initself None: self.front: Node None None self.rear: Node None None def iterself IteratorAny: node self.front while node: yield node.data node node.next def lenself int: return lentupleiterself def strself str: return .joinstritem for item in self def isemptyself bool: return lenself 0 def putself, item: Any None: node Nodeitem if self.isempty: self.front self.rear node else: assert isinstanceself.rear, Node self.rear.next node self.rear node def getself Any: if self.isempty: raise IndexErrordequeue from empty queue assert isinstanceself.front, Node node self.front self.front self.front.next if self.front is None: self.rear None return node.data def clearself None: self.front self.rear None if name main: from doctest import testmod testmod","Completions":"from __future__ import annotations\n\nfrom collections.abc import Iterator\nfrom typing import Any\n\n\nclass Node:\n def __init__(self, data: Any) -> None:\n self.data: Any = data\n self.next: Node | None = None\n\n def __str__(self) -> str:\n return f\"{self.data}\"\n\n\nclass LinkedQueue:\n \"\"\"\n >>> queue = LinkedQueue()\n >>> queue.is_empty()\n True\n >>> queue.put(5)\n >>> queue.put(9)\n >>> queue.put('python')\n >>> queue.is_empty()\n False\n >>> queue.get()\n 5\n >>> queue.put('algorithms')\n >>> queue.get()\n 9\n >>> queue.get()\n 'python'\n >>> queue.get()\n 'algorithms'\n >>> queue.is_empty()\n True\n >>> queue.get()\n Traceback (most recent call last):\n ...\n IndexError: dequeue from empty queue\n \"\"\"\n\n def __init__(self) -> None:\n self.front: Node | None = None\n self.rear: Node | None = None\n\n def __iter__(self) -> Iterator[Any]:\n node = self.front\n while node:\n yield node.data\n node = node.next\n\n def __len__(self) -> int:\n \"\"\"\n >>> queue = LinkedQueue()\n >>> for i in range(1, 6):\n ... queue.put(i)\n >>> len(queue)\n 5\n >>> for i in range(1, 6):\n ... assert len(queue) == 6 - i\n ... _ = queue.get()\n >>> len(queue)\n 0\n \"\"\"\n return len(tuple(iter(self)))\n\n def __str__(self) -> str:\n \"\"\"\n >>> queue = LinkedQueue()\n >>> for i in range(1, 4):\n ... queue.put(i)\n >>> queue.put(\"Python\")\n >>> queue.put(3.14)\n >>> queue.put(True)\n >>> str(queue)\n '1 <- 2 <- 3 <- Python <- 3.14 <- True'\n \"\"\"\n return \" <- \".join(str(item) for item in self)\n\n def is_empty(self) -> bool:\n \"\"\"\n >>> queue = LinkedQueue()\n >>> queue.is_empty()\n True\n >>> for i in range(1, 6):\n ... queue.put(i)\n >>> queue.is_empty()\n False\n \"\"\"\n return len(self) == 0\n\n def put(self, item: Any) -> None:\n \"\"\"\n >>> queue = LinkedQueue()\n >>> queue.get()\n Traceback (most recent call last):\n ...\n IndexError: dequeue from empty queue\n >>> for i in range(1, 6):\n ... queue.put(i)\n >>> str(queue)\n '1 <- 2 <- 3 <- 4 <- 5'\n \"\"\"\n node = Node(item)\n if self.is_empty():\n self.front = self.rear = node\n else:\n assert isinstance(self.rear, Node)\n self.rear.next = node\n self.rear = node\n\n def get(self) -> Any:\n \"\"\"\n >>> queue = LinkedQueue()\n >>> queue.get()\n Traceback (most recent call last):\n ...\n IndexError: dequeue from empty queue\n >>> queue = LinkedQueue()\n >>> for i in range(1, 6):\n ... queue.put(i)\n >>> for i in range(1, 6):\n ... assert queue.get() == i\n >>> len(queue)\n 0\n \"\"\"\n if self.is_empty():\n raise IndexError(\"dequeue from empty queue\")\n assert isinstance(self.front, Node)\n node = self.front\n self.front = self.front.next\n if self.front is None:\n self.rear = None\n return node.data\n\n def clear(self) -> None:\n \"\"\"\n >>> queue = LinkedQueue()\n >>> for i in range(1, 6):\n ... queue.put(i)\n >>> queue.clear()\n >>> len(queue)\n 0\n >>> str(queue)\n ''\n \"\"\"\n self.front = self.rear = None\n\n\nif __name__ == \"__main__\":\n from doctest import testmod\n\n testmod()\n"} +{"Prompt":"Pure Python implementations of a Fixed Priority Queue and an Element Priority Queue using Python lists. Tasks can be added to a Priority Queue at any time and in any order but when Tasks are removed then the Task with the highest priority is removed in FIFO order. In code we will use three levels of priority with priority zero Tasks being the most urgent high priority and priority 2 tasks being the least urgent. Examples fpq FixedPriorityQueue fpq.enqueue0, 10 fpq.enqueue1, 70 fpq.enqueue0, 100 fpq.enqueue2, 1 fpq.enqueue2, 5 fpq.enqueue1, 7 fpq.enqueue2, 4 fpq.enqueue1, 64 fpq.enqueue0, 128 printfpq Priority 0: 10, 100, 128 Priority 1: 70, 7, 64 Priority 2: 1, 5, 4 fpq.dequeue 10 fpq.dequeue 100 fpq.dequeue 128 fpq.dequeue 70 fpq.dequeue 7 printfpq Priority 0: Priority 1: 64 Priority 2: 1, 5, 4 fpq.dequeue 64 fpq.dequeue 1 fpq.dequeue 5 fpq.dequeue 4 fpq.dequeue Traceback most recent call last: ... datastructures.queue.priorityqueueusinglist.UnderFlowError: All queues are empty printfpq Priority 0: Priority 1: Priority 2: Add an element to a queue based on its priority. If the priority is invalid ValueError is raised. If the queue is full an OverFlowError is raised. Return the highest priority element in FIFO order. If the queue is empty then an under flow exception is raised. Element Priority Queue is the same as Fixed Priority Queue except that the value of the element itself is the priority. The rules for priorities are the same the as Fixed Priority Queue. epq ElementPriorityQueue epq.enqueue10 epq.enqueue70 epq.enqueue4 epq.enqueue1 epq.enqueue5 epq.enqueue7 epq.enqueue4 epq.enqueue64 epq.enqueue128 printepq 10, 70, 4, 1, 5, 7, 4, 64, 128 epq.dequeue 1 epq.dequeue 4 epq.dequeue 4 epq.dequeue 5 epq.dequeue 7 epq.dequeue 10 printepq 70, 64, 128 epq.dequeue 64 epq.dequeue 70 epq.dequeue 128 epq.dequeue Traceback most recent call last: ... datastructures.queue.priorityqueueusinglist.UnderFlowError: The queue is empty printepq This function enters the element into the queue If the queue is full an Exception is raised saying Over Flow! Return the highest priority element in FIFO order. If the queue is empty then an under flow exception is raised. Prints all the elements within the Element Priority Queue","Completions":"class OverFlowError(Exception):\n pass\n\n\nclass UnderFlowError(Exception):\n pass\n\n\nclass FixedPriorityQueue:\n \"\"\"\n Tasks can be added to a Priority Queue at any time and in any order but when Tasks\n are removed then the Task with the highest priority is removed in FIFO order. In\n code we will use three levels of priority with priority zero Tasks being the most\n urgent (high priority) and priority 2 tasks being the least urgent.\n\n Examples\n >>> fpq = FixedPriorityQueue()\n >>> fpq.enqueue(0, 10)\n >>> fpq.enqueue(1, 70)\n >>> fpq.enqueue(0, 100)\n >>> fpq.enqueue(2, 1)\n >>> fpq.enqueue(2, 5)\n >>> fpq.enqueue(1, 7)\n >>> fpq.enqueue(2, 4)\n >>> fpq.enqueue(1, 64)\n >>> fpq.enqueue(0, 128)\n >>> print(fpq)\n Priority 0: [10, 100, 128]\n Priority 1: [70, 7, 64]\n Priority 2: [1, 5, 4]\n >>> fpq.dequeue()\n 10\n >>> fpq.dequeue()\n 100\n >>> fpq.dequeue()\n 128\n >>> fpq.dequeue()\n 70\n >>> fpq.dequeue()\n 7\n >>> print(fpq)\n Priority 0: []\n Priority 1: [64]\n Priority 2: [1, 5, 4]\n >>> fpq.dequeue()\n 64\n >>> fpq.dequeue()\n 1\n >>> fpq.dequeue()\n 5\n >>> fpq.dequeue()\n 4\n >>> fpq.dequeue()\n Traceback (most recent call last):\n ...\n data_structures.queue.priority_queue_using_list.UnderFlowError: All queues are empty\n >>> print(fpq)\n Priority 0: []\n Priority 1: []\n Priority 2: []\n \"\"\"\n\n def __init__(self):\n self.queues = [\n [],\n [],\n [],\n ]\n\n def enqueue(self, priority: int, data: int) -> None:\n \"\"\"\n Add an element to a queue based on its priority.\n If the priority is invalid ValueError is raised.\n If the queue is full an OverFlowError is raised.\n \"\"\"\n try:\n if len(self.queues[priority]) >= 100:\n raise OverflowError(\"Maximum queue size is 100\")\n self.queues[priority].append(data)\n except IndexError:\n raise ValueError(\"Valid priorities are 0, 1, and 2\")\n\n def dequeue(self) -> int:\n \"\"\"\n Return the highest priority element in FIFO order.\n If the queue is empty then an under flow exception is raised.\n \"\"\"\n for queue in self.queues:\n if queue:\n return queue.pop(0)\n raise UnderFlowError(\"All queues are empty\")\n\n def __str__(self) -> str:\n return \"\\n\".join(f\"Priority {i}: {q}\" for i, q in enumerate(self.queues))\n\n\nclass ElementPriorityQueue:\n \"\"\"\n Element Priority Queue is the same as Fixed Priority Queue except that the value of\n the element itself is the priority. The rules for priorities are the same the as\n Fixed Priority Queue.\n\n >>> epq = ElementPriorityQueue()\n >>> epq.enqueue(10)\n >>> epq.enqueue(70)\n >>> epq.enqueue(4)\n >>> epq.enqueue(1)\n >>> epq.enqueue(5)\n >>> epq.enqueue(7)\n >>> epq.enqueue(4)\n >>> epq.enqueue(64)\n >>> epq.enqueue(128)\n >>> print(epq)\n [10, 70, 4, 1, 5, 7, 4, 64, 128]\n >>> epq.dequeue()\n 1\n >>> epq.dequeue()\n 4\n >>> epq.dequeue()\n 4\n >>> epq.dequeue()\n 5\n >>> epq.dequeue()\n 7\n >>> epq.dequeue()\n 10\n >>> print(epq)\n [70, 64, 128]\n >>> epq.dequeue()\n 64\n >>> epq.dequeue()\n 70\n >>> epq.dequeue()\n 128\n >>> epq.dequeue()\n Traceback (most recent call last):\n ...\n data_structures.queue.priority_queue_using_list.UnderFlowError: The queue is empty\n >>> print(epq)\n []\n \"\"\"\n\n def __init__(self):\n self.queue = []\n\n def enqueue(self, data: int) -> None:\n \"\"\"\n This function enters the element into the queue\n If the queue is full an Exception is raised saying Over Flow!\n \"\"\"\n if len(self.queue) == 100:\n raise OverFlowError(\"Maximum queue size is 100\")\n self.queue.append(data)\n\n def dequeue(self) -> int:\n \"\"\"\n Return the highest priority element in FIFO order.\n If the queue is empty then an under flow exception is raised.\n \"\"\"\n if not self.queue:\n raise UnderFlowError(\"The queue is empty\")\n else:\n data = min(self.queue)\n self.queue.remove(data)\n return data\n\n def __str__(self) -> str:\n \"\"\"\n Prints all the elements within the Element Priority Queue\n \"\"\"\n return str(self.queue)\n\n\ndef fixed_priority_queue():\n fpq = FixedPriorityQueue()\n fpq.enqueue(0, 10)\n fpq.enqueue(1, 70)\n fpq.enqueue(0, 100)\n fpq.enqueue(2, 1)\n fpq.enqueue(2, 5)\n fpq.enqueue(1, 7)\n fpq.enqueue(2, 4)\n fpq.enqueue(1, 64)\n fpq.enqueue(0, 128)\n print(fpq)\n print(fpq.dequeue())\n print(fpq.dequeue())\n print(fpq.dequeue())\n print(fpq.dequeue())\n print(fpq.dequeue())\n print(fpq)\n print(fpq.dequeue())\n print(fpq.dequeue())\n print(fpq.dequeue())\n print(fpq.dequeue())\n print(fpq.dequeue())\n\n\ndef element_priority_queue():\n epq = ElementPriorityQueue()\n epq.enqueue(10)\n epq.enqueue(70)\n epq.enqueue(100)\n epq.enqueue(1)\n epq.enqueue(5)\n epq.enqueue(7)\n epq.enqueue(4)\n epq.enqueue(64)\n epq.enqueue(128)\n print(epq)\n print(epq.dequeue())\n print(epq.dequeue())\n print(epq.dequeue())\n print(epq.dequeue())\n print(epq.dequeue())\n print(epq)\n print(epq.dequeue())\n print(epq.dequeue())\n print(epq.dequeue())\n print(epq.dequeue())\n print(epq.dequeue())\n\n\nif __name__ == \"__main__\":\n fixed_priority_queue()\n element_priority_queue()\n"} +{"Prompt":"Queue represented by a Python list from collections.abc import Iterable from typing import Generic, TypeVar T TypeVarT class QueueByListGenericT: def initself, iterable: IterableT None None None: self.entries: listT listiterable or def lenself int: return lenself.entries def reprself str: return fQueuetupleself.entries def putself, item: T None: self.entries.appenditem def getself T: if not self.entries: raise IndexErrorQueue is empty return self.entries.pop0 def rotateself, rotation: int None: put self.entries.append get self.entries.pop for in rangerotation: putget0 def getfrontself T: return self.entries0 if name main: from doctest import testmod testmod","Completions":"from collections.abc import Iterable\nfrom typing import Generic, TypeVar\n\n_T = TypeVar(\"_T\")\n\n\nclass QueueByList(Generic[_T]):\n def __init__(self, iterable: Iterable[_T] | None = None) -> None:\n \"\"\"\n >>> QueueByList()\n Queue(())\n >>> QueueByList([10, 20, 30])\n Queue((10, 20, 30))\n >>> QueueByList((i**2 for i in range(1, 4)))\n Queue((1, 4, 9))\n \"\"\"\n self.entries: list[_T] = list(iterable or [])\n\n def __len__(self) -> int:\n \"\"\"\n >>> len(QueueByList())\n 0\n >>> from string import ascii_lowercase\n >>> len(QueueByList(ascii_lowercase))\n 26\n >>> queue = QueueByList()\n >>> for i in range(1, 11):\n ... queue.put(i)\n >>> len(queue)\n 10\n >>> for i in range(2):\n ... queue.get()\n 1\n 2\n >>> len(queue)\n 8\n \"\"\"\n\n return len(self.entries)\n\n def __repr__(self) -> str:\n \"\"\"\n >>> queue = QueueByList()\n >>> queue\n Queue(())\n >>> str(queue)\n 'Queue(())'\n >>> queue.put(10)\n >>> queue\n Queue((10,))\n >>> queue.put(20)\n >>> queue.put(30)\n >>> queue\n Queue((10, 20, 30))\n \"\"\"\n\n return f\"Queue({tuple(self.entries)})\"\n\n def put(self, item: _T) -> None:\n \"\"\"Put `item` to the Queue\n\n >>> queue = QueueByList()\n >>> queue.put(10)\n >>> queue.put(20)\n >>> len(queue)\n 2\n >>> queue\n Queue((10, 20))\n \"\"\"\n\n self.entries.append(item)\n\n def get(self) -> _T:\n \"\"\"\n Get `item` from the Queue\n\n >>> queue = QueueByList((10, 20, 30))\n >>> queue.get()\n 10\n >>> queue.put(40)\n >>> queue.get()\n 20\n >>> queue.get()\n 30\n >>> len(queue)\n 1\n >>> queue.get()\n 40\n >>> queue.get()\n Traceback (most recent call last):\n ...\n IndexError: Queue is empty\n \"\"\"\n\n if not self.entries:\n raise IndexError(\"Queue is empty\")\n return self.entries.pop(0)\n\n def rotate(self, rotation: int) -> None:\n \"\"\"Rotate the items of the Queue `rotation` times\n\n >>> queue = QueueByList([10, 20, 30, 40])\n >>> queue\n Queue((10, 20, 30, 40))\n >>> queue.rotate(1)\n >>> queue\n Queue((20, 30, 40, 10))\n >>> queue.rotate(2)\n >>> queue\n Queue((40, 10, 20, 30))\n \"\"\"\n\n put = self.entries.append\n get = self.entries.pop\n\n for _ in range(rotation):\n put(get(0))\n\n def get_front(self) -> _T:\n \"\"\"Get the front item from the Queue\n\n >>> queue = QueueByList((10, 20, 30))\n >>> queue.get_front()\n 10\n >>> queue\n Queue((10, 20, 30))\n >>> queue.get()\n 10\n >>> queue.get_front()\n 20\n \"\"\"\n\n return self.entries[0]\n\n\nif __name__ == \"__main__\":\n from doctest import testmod\n\n testmod()\n"} +{"Prompt":"Queue implementation using two stacks from collections.abc import Iterable from typing import Generic, TypeVar T TypeVarT class QueueByTwoStacksGenericT: def initself, iterable: IterableT None None None: self.stack1: listT listiterable or self.stack2: listT def lenself int: return lenself.stack1 lenself.stack2 def reprself str: return fQueuetupleself.stack2::1 self.stack1 def putself, item: T None: self.stack1.appenditem def getself T: To reduce number of attribute lookups in while loop. stack1pop self.stack1.pop stack2append self.stack2.append if not self.stack2: while self.stack1: stack2appendstack1pop if not self.stack2: raise IndexErrorQueue is empty return self.stack2.pop if name main: from doctest import testmod testmod","Completions":"from collections.abc import Iterable\nfrom typing import Generic, TypeVar\n\n_T = TypeVar(\"_T\")\n\n\nclass QueueByTwoStacks(Generic[_T]):\n def __init__(self, iterable: Iterable[_T] | None = None) -> None:\n \"\"\"\n >>> QueueByTwoStacks()\n Queue(())\n >>> QueueByTwoStacks([10, 20, 30])\n Queue((10, 20, 30))\n >>> QueueByTwoStacks((i**2 for i in range(1, 4)))\n Queue((1, 4, 9))\n \"\"\"\n self._stack1: list[_T] = list(iterable or [])\n self._stack2: list[_T] = []\n\n def __len__(self) -> int:\n \"\"\"\n >>> len(QueueByTwoStacks())\n 0\n >>> from string import ascii_lowercase\n >>> len(QueueByTwoStacks(ascii_lowercase))\n 26\n >>> queue = QueueByTwoStacks()\n >>> for i in range(1, 11):\n ... queue.put(i)\n ...\n >>> len(queue)\n 10\n >>> for i in range(2):\n ... queue.get()\n 1\n 2\n >>> len(queue)\n 8\n \"\"\"\n\n return len(self._stack1) + len(self._stack2)\n\n def __repr__(self) -> str:\n \"\"\"\n >>> queue = QueueByTwoStacks()\n >>> queue\n Queue(())\n >>> str(queue)\n 'Queue(())'\n >>> queue.put(10)\n >>> queue\n Queue((10,))\n >>> queue.put(20)\n >>> queue.put(30)\n >>> queue\n Queue((10, 20, 30))\n \"\"\"\n return f\"Queue({tuple(self._stack2[::-1] + self._stack1)})\"\n\n def put(self, item: _T) -> None:\n \"\"\"\n Put `item` into the Queue\n\n >>> queue = QueueByTwoStacks()\n >>> queue.put(10)\n >>> queue.put(20)\n >>> len(queue)\n 2\n >>> queue\n Queue((10, 20))\n \"\"\"\n\n self._stack1.append(item)\n\n def get(self) -> _T:\n \"\"\"\n Get `item` from the Queue\n\n >>> queue = QueueByTwoStacks((10, 20, 30))\n >>> queue.get()\n 10\n >>> queue.put(40)\n >>> queue.get()\n 20\n >>> queue.get()\n 30\n >>> len(queue)\n 1\n >>> queue.get()\n 40\n >>> queue.get()\n Traceback (most recent call last):\n ...\n IndexError: Queue is empty\n \"\"\"\n\n # To reduce number of attribute look-ups in `while` loop.\n stack1_pop = self._stack1.pop\n stack2_append = self._stack2.append\n\n if not self._stack2:\n while self._stack1:\n stack2_append(stack1_pop())\n\n if not self._stack2:\n raise IndexError(\"Queue is empty\")\n return self._stack2.pop()\n\n\nif __name__ == \"__main__\":\n from doctest import testmod\n\n testmod()\n"} +{"Prompt":"Queue represented by a pseudo stack represented by a list with pop and append from typing import Any class Queue: def initself: self.stack self.length 0 def strself: printed strself.stack1:1 return printed Dequeues code item requirement: self.length 0 return dequeued item that was dequeued def getself Any: self.rotate1 dequeued self.stackself.length 1 self.stack self.stack:1 self.rotateself.length 1 self.length self.length 1 return dequeued Reports item at the front of self return item at front of self.stack def frontself Any: front self.get self.putfront self.rotateself.length 1 return front","Completions":"from typing import Any\n\n\nclass Queue:\n def __init__(self):\n self.stack = []\n self.length = 0\n\n def __str__(self):\n printed = \"<\" + str(self.stack)[1:-1] + \">\"\n return printed\n\n \"\"\"Enqueues {@code item}\n @param item\n item to enqueue\"\"\"\n\n def put(self, item: Any) -> None:\n self.stack.append(item)\n self.length = self.length + 1\n\n \"\"\"Dequeues {@code item}\n @requirement: |self.length| > 0\n @return dequeued\n item that was dequeued\"\"\"\n\n def get(self) -> Any:\n self.rotate(1)\n dequeued = self.stack[self.length - 1]\n self.stack = self.stack[:-1]\n self.rotate(self.length - 1)\n self.length = self.length - 1\n return dequeued\n\n \"\"\"Rotates the queue {@code rotation} times\n @param rotation\n number of times to rotate queue\"\"\"\n\n def rotate(self, rotation: int) -> None:\n for _ in range(rotation):\n temp = self.stack[0]\n self.stack = self.stack[1:]\n self.put(temp)\n self.length = self.length - 1\n\n \"\"\"Reports item at the front of self\n @return item at front of self.stack\"\"\"\n\n def front(self) -> Any:\n front = self.get()\n self.put(front)\n self.rotate(self.length - 1)\n return front\n\n \"\"\"Returns the length of this.stack\"\"\"\n\n def size(self) -> int:\n return self.length\n"} +{"Prompt":"Use a stack to check if a string of parentheses is balanced. balancedparentheses True balancedparentheses True balancedparentheses False balancedparentheses1234 True balancedparentheses True","Completions":"from .stack import Stack\n\n\ndef balanced_parentheses(parentheses: str) -> bool:\n \"\"\"Use a stack to check if a string of parentheses is balanced.\n >>> balanced_parentheses(\"([]{})\")\n True\n >>> balanced_parentheses(\"[()]{}{[()()]()}\")\n True\n >>> balanced_parentheses(\"[(])\")\n False\n >>> balanced_parentheses(\"1+2*3-4\")\n True\n >>> balanced_parentheses(\"\")\n True\n \"\"\"\n stack: Stack[str] = Stack()\n bracket_pairs = {\"(\": \")\", \"[\": \"]\", \"{\": \"}\"}\n for bracket in parentheses:\n if bracket in bracket_pairs:\n stack.push(bracket)\n elif bracket in (\")\", \"]\", \"}\"):\n if stack.is_empty() or bracket_pairs[stack.pop()] != bracket:\n return False\n return stack.is_empty()\n\n\nif __name__ == \"__main__\":\n from doctest import testmod\n\n testmod()\n\n examples = [\"((()))\", \"((())\", \"(()))\"]\n print(\"Balanced parentheses demonstration:\\n\")\n for example in examples:\n not_str = \"\" if balanced_parentheses(example) else \"not \"\n print(f\"{example} is {not_str}balanced\")\n"} +{"Prompt":"Author: Alexander Joslin GitHub: github.comechoaj Explanation: https:medium.comhaleesammarimplementedinjsdijkstras2stack algorithmforevaluatingmathematicalexpressionsfc0837dae1ea We can use Dijkstra's two stack algorithm to solve an equation such as: 5 4 2 2 3 THESE ARE THE ALGORITHM'S RULES: RULE 1: Scan the expression from left to right. When an operand is encountered, push it onto the operand stack. RULE 2: When an operator is encountered in the expression, push it onto the operator stack. RULE 3: When a left parenthesis is encountered in the expression, ignore it. RULE 4: When a right parenthesis is encountered in the expression, pop an operator off the operator stack. The two operands it must operate on must be the last two operands pushed onto the operand stack. We therefore pop the operand stack twice, perform the operation, and push the result back onto the operand stack so it will be available for use as an operand of the next operator popped off the operator stack. RULE 5: When the entire infix expression has been scanned, the value left on the operand stack represents the value of the expression. NOTE: It only works with whole numbers. DocTests dijkstrastwostackalgorithm5 3 8 dijkstrastwostackalgorithm9 2 9 8 1 5 dijkstrastwostackalgorithm3 2 2 3 2 4 3 3 :param equation: a string :return: result: an integer RULE 1 RULE 2 RULE 4 RULE 5 answer 45","Completions":"__author__ = \"Alexander Joslin\"\n\nimport operator as op\n\nfrom .stack import Stack\n\n\ndef dijkstras_two_stack_algorithm(equation: str) -> int:\n \"\"\"\n DocTests\n >>> dijkstras_two_stack_algorithm(\"(5 + 3)\")\n 8\n >>> dijkstras_two_stack_algorithm(\"((9 - (2 + 9)) + (8 - 1))\")\n 5\n >>> dijkstras_two_stack_algorithm(\"((((3 - 2) - (2 + 3)) + (2 - 4)) + 3)\")\n -3\n\n :param equation: a string\n :return: result: an integer\n \"\"\"\n operators = {\"*\": op.mul, \"\/\": op.truediv, \"+\": op.add, \"-\": op.sub}\n\n operand_stack: Stack[int] = Stack()\n operator_stack: Stack[str] = Stack()\n\n for i in equation:\n if i.isdigit():\n # RULE 1\n operand_stack.push(int(i))\n elif i in operators:\n # RULE 2\n operator_stack.push(i)\n elif i == \")\":\n # RULE 4\n opr = operator_stack.peek()\n operator_stack.pop()\n num1 = operand_stack.peek()\n operand_stack.pop()\n num2 = operand_stack.peek()\n operand_stack.pop()\n\n total = operators[opr](num2, num1)\n operand_stack.push(total)\n\n # RULE 5\n return operand_stack.peek()\n\n\nif __name__ == \"__main__\":\n equation = \"(5 + ((4 * 2) * (2 + 3)))\"\n # answer = 45\n print(f\"{equation} = {dijkstras_two_stack_algorithm(equation)}\")\n"} +{"Prompt":"https:en.wikipedia.orgwikiInfixnotation https:en.wikipedia.orgwikiReversePolishnotation https:en.wikipedia.orgwikiShuntingyardalgorithm Return integer value representing an operator's precedence, or order of operation. https:en.wikipedia.orgwikiOrderofoperations Return the associativity of the operator char. https:en.wikipedia.orgwikiOperatorassociativity infixtopostfix1234 Traceback most recent call last: ... ValueError: Mismatched parentheses infixtopostfix '' infixtopostfix32 '3 2 ' infixtopostfix3456 '3 4 5 6 ' infixtopostfix12345 '1 2 3 4 5 ' infixtopostfixabcdefg 'a b c d e f g ' infixtopostfixxy5z2 'x y 5 z 2 ' infixtopostfix232 '2 3 2 ' Precedences are equal","Completions":"from typing import Literal\n\nfrom .balanced_parentheses import balanced_parentheses\nfrom .stack import Stack\n\nPRECEDENCES: dict[str, int] = {\n \"+\": 1,\n \"-\": 1,\n \"*\": 2,\n \"\/\": 2,\n \"^\": 3,\n}\nASSOCIATIVITIES: dict[str, Literal[\"LR\", \"RL\"]] = {\n \"+\": \"LR\",\n \"-\": \"LR\",\n \"*\": \"LR\",\n \"\/\": \"LR\",\n \"^\": \"RL\",\n}\n\n\ndef precedence(char: str) -> int:\n \"\"\"\n Return integer value representing an operator's precedence, or\n order of operation.\n https:\/\/en.wikipedia.org\/wiki\/Order_of_operations\n \"\"\"\n return PRECEDENCES.get(char, -1)\n\n\ndef associativity(char: str) -> Literal[\"LR\", \"RL\"]:\n \"\"\"\n Return the associativity of the operator `char`.\n https:\/\/en.wikipedia.org\/wiki\/Operator_associativity\n \"\"\"\n return ASSOCIATIVITIES[char]\n\n\ndef infix_to_postfix(expression_str: str) -> str:\n \"\"\"\n >>> infix_to_postfix(\"(1*(2+3)+4))\")\n Traceback (most recent call last):\n ...\n ValueError: Mismatched parentheses\n >>> infix_to_postfix(\"\")\n ''\n >>> infix_to_postfix(\"3+2\")\n '3 2 +'\n >>> infix_to_postfix(\"(3+4)*5-6\")\n '3 4 + 5 * 6 -'\n >>> infix_to_postfix(\"(1+2)*3\/4-5\")\n '1 2 + 3 * 4 \/ 5 -'\n >>> infix_to_postfix(\"a+b*c+(d*e+f)*g\")\n 'a b c * + d e * f + g * +'\n >>> infix_to_postfix(\"x^y\/(5*z)+2\")\n 'x y ^ 5 z * \/ 2 +'\n >>> infix_to_postfix(\"2^3^2\")\n '2 3 2 ^ ^'\n \"\"\"\n if not balanced_parentheses(expression_str):\n raise ValueError(\"Mismatched parentheses\")\n stack: Stack[str] = Stack()\n postfix = []\n for char in expression_str:\n if char.isalpha() or char.isdigit():\n postfix.append(char)\n elif char == \"(\":\n stack.push(char)\n elif char == \")\":\n while not stack.is_empty() and stack.peek() != \"(\":\n postfix.append(stack.pop())\n stack.pop()\n else:\n while True:\n if stack.is_empty():\n stack.push(char)\n break\n\n char_precedence = precedence(char)\n tos_precedence = precedence(stack.peek())\n\n if char_precedence > tos_precedence:\n stack.push(char)\n break\n if char_precedence < tos_precedence:\n postfix.append(stack.pop())\n continue\n # Precedences are equal\n if associativity(char) == \"RL\":\n stack.push(char)\n break\n postfix.append(stack.pop())\n\n while not stack.is_empty():\n postfix.append(stack.pop())\n return \" \".join(postfix)\n\n\nif __name__ == \"__main__\":\n from doctest import testmod\n\n testmod()\n expression = \"a+b*(c^d-e)^(f+g*h)-i\"\n\n print(\"Infix to Postfix Notation demonstration:\\n\")\n print(\"Infix notation: \" + expression)\n print(\"Postfix notation: \" + infix_to_postfix(expression))\n"} +{"Prompt":"Output: Enter an Infix Equation a b c Symbol Stack Postfix c c c b cb cb a cba cba abc Infix abc Prefix infix2postfixabc doctest: NORMALIZEWHITESPACE Symbol Stack Postfix a a a b ab ab c abc abc abc 'abc' infix2postfix1a2b doctest: NORMALIZEWHITESPACE Symbol Stack Postfix 1 1 1 1 1 1 a 1a 1a 1a 2 1a2 1a2 b 1a2b 1a2b 1a2b '1a2b' infix2postfix Symbol Stack Postfix '' infix2postfix Traceback most recent call last: ... ValueError: invalid expression infix2postfix Traceback most recent call last: ... IndexError: list index out of range Print table header for output infix2prefixabc doctest: NORMALIZEWHITESPACE Symbol Stack Postfix c c c b cb cb a cba cba 'abc' infix2prefix1a2b doctest: NORMALIZEWHITESPACE Symbol Stack Postfix b b b 2 b2 b2 b2 a b2a b2a b2a b2a b2a 1 b2a1 b2a1 '1a2b' infix2prefix'' Symbol Stack Postfix '' infix2prefix'' Traceback most recent call last: ... IndexError: list index out of range infix2prefix'' Traceback most recent call last: ... ValueError: invalid expression call infix2postfix on Infix, return reverse of Postfix","Completions":"def infix_2_postfix(infix: str) -> str:\n \"\"\"\n >>> infix_2_postfix(\"a+b^c\") # doctest: +NORMALIZE_WHITESPACE\n Symbol | Stack | Postfix\n ----------------------------\n a | | a\n + | + | a\n b | + | ab\n ^ | +^ | ab\n c | +^ | abc\n | + | abc^\n | | abc^+\n 'abc^+'\n\n >>> infix_2_postfix(\"1*((-a)*2+b)\") # doctest: +NORMALIZE_WHITESPACE\n Symbol | Stack | Postfix\n -------------------------------------------\n 1 | | 1\n * | * | 1\n ( | *( | 1\n ( | *(( | 1\n - | *((- | 1\n a | *((- | 1a\n ) | *( | 1a-\n * | *(* | 1a-\n 2 | *(* | 1a-2\n + | *(+ | 1a-2*\n b | *(+ | 1a-2*b\n ) | * | 1a-2*b+\n | | 1a-2*b+*\n '1a-2*b+*'\n\n >>> infix_2_postfix(\"\")\n Symbol | Stack | Postfix\n ----------------------------\n ''\n\n >>> infix_2_postfix(\"(()\")\n Traceback (most recent call last):\n ...\n ValueError: invalid expression\n\n >>> infix_2_postfix(\"())\")\n Traceback (most recent call last):\n ...\n IndexError: list index out of range\n \"\"\"\n stack = []\n post_fix = []\n priority = {\n \"^\": 3,\n \"*\": 2,\n \"\/\": 2,\n \"%\": 2,\n \"+\": 1,\n \"-\": 1,\n } # Priority of each operator\n print_width = max(len(infix), 7)\n\n # Print table header for output\n print(\n \"Symbol\".center(8),\n \"Stack\".center(print_width),\n \"Postfix\".center(print_width),\n sep=\" | \",\n )\n print(\"-\" * (print_width * 3 + 7))\n\n for x in infix:\n if x.isalpha() or x.isdigit():\n post_fix.append(x) # if x is Alphabet \/ Digit, add it to Postfix\n elif x == \"(\":\n stack.append(x) # if x is \"(\" push to Stack\n elif x == \")\": # if x is \")\" pop stack until \"(\" is encountered\n if len(stack) == 0: # close bracket without open bracket\n raise IndexError(\"list index out of range\")\n\n while stack[-1] != \"(\":\n post_fix.append(stack.pop()) # Pop stack & add the content to Postfix\n stack.pop()\n else:\n if len(stack) == 0:\n stack.append(x) # If stack is empty, push x to stack\n else: # while priority of x is not > priority of element in the stack\n while stack and stack[-1] != \"(\" and priority[x] <= priority[stack[-1]]:\n post_fix.append(stack.pop()) # pop stack & add to Postfix\n stack.append(x) # push x to stack\n\n print(\n x.center(8),\n (\"\".join(stack)).ljust(print_width),\n (\"\".join(post_fix)).ljust(print_width),\n sep=\" | \",\n ) # Output in tabular format\n\n while len(stack) > 0: # while stack is not empty\n if stack[-1] == \"(\": # open bracket with no close bracket\n raise ValueError(\"invalid expression\")\n\n post_fix.append(stack.pop()) # pop stack & add to Postfix\n print(\n \" \".center(8),\n (\"\".join(stack)).ljust(print_width),\n (\"\".join(post_fix)).ljust(print_width),\n sep=\" | \",\n ) # Output in tabular format\n\n return \"\".join(post_fix) # return Postfix as str\n\n\ndef infix_2_prefix(infix: str) -> str:\n \"\"\"\n >>> infix_2_prefix(\"a+b^c\") # doctest: +NORMALIZE_WHITESPACE\n Symbol | Stack | Postfix\n ----------------------------\n c | | c\n ^ | ^ | c\n b | ^ | cb\n + | + | cb^\n a | + | cb^a\n | | cb^a+\n '+a^bc'\n\n >>> infix_2_prefix(\"1*((-a)*2+b)\") # doctest: +NORMALIZE_WHITESPACE\n Symbol | Stack | Postfix\n -------------------------------------------\n ( | ( |\n b | ( | b\n + | (+ | b\n 2 | (+ | b2\n * | (+* | b2\n ( | (+*( | b2\n a | (+*( | b2a\n - | (+*(- | b2a\n ) | (+* | b2a-\n ) | | b2a-*+\n * | * | b2a-*+\n 1 | * | b2a-*+1\n | | b2a-*+1*\n '*1+*-a2b'\n\n >>> infix_2_prefix('')\n Symbol | Stack | Postfix\n ----------------------------\n ''\n\n >>> infix_2_prefix('(()')\n Traceback (most recent call last):\n ...\n IndexError: list index out of range\n\n >>> infix_2_prefix('())')\n Traceback (most recent call last):\n ...\n ValueError: invalid expression\n \"\"\"\n reversed_infix = list(infix[::-1]) # reverse the infix equation\n\n for i in range(len(reversed_infix)):\n if reversed_infix[i] == \"(\":\n reversed_infix[i] = \")\" # change \"(\" to \")\"\n elif reversed_infix[i] == \")\":\n reversed_infix[i] = \"(\" # change \")\" to \"(\"\n\n # call infix_2_postfix on Infix, return reverse of Postfix\n return (infix_2_postfix(\"\".join(reversed_infix)))[::-1]\n\n\nif __name__ == \"__main__\":\n from doctest import testmod\n\n testmod()\n\n Infix = input(\"\\nEnter an Infix Equation = \") # Input an Infix equation\n Infix = \"\".join(Infix.split()) # Remove spaces from the input\n print(\"\\n\\t\", Infix, \"(Infix) -> \", infix_2_prefix(Infix), \"(Prefix)\")\n"} +{"Prompt":"Get the Next Greatest Element NGE for all elements in a list. Maximum element present after the current one which is also greater than the current one. nextgreatestelementslowarr expect True Like nextgreatestelementslow but changes the loops to use enumerate instead of rangelen for the outer loop and for in a slice of arr for the inner loop. nextgreatestelementfastarr expect True Get the Next Greatest Element NGE for all elements in a list. Maximum element present after the current one which is also greater than the current one. A naive way to solve this is to take two loops and check for the next bigger number but that will make the time complexity as On2. The better way to solve this would be to use a stack to keep track of maximum number giving a linear time solution. nextgreatestelementarr expect True","Completions":"from __future__ import annotations\n\narr = [-10, -5, 0, 5, 5.1, 11, 13, 21, 3, 4, -21, -10, -5, -1, 0]\nexpect = [-5, 0, 5, 5.1, 11, 13, 21, -1, 4, -1, -10, -5, -1, 0, -1]\n\n\ndef next_greatest_element_slow(arr: list[float]) -> list[float]:\n \"\"\"\n Get the Next Greatest Element (NGE) for all elements in a list.\n Maximum element present after the current one which is also greater than the\n current one.\n >>> next_greatest_element_slow(arr) == expect\n True\n \"\"\"\n\n result = []\n arr_size = len(arr)\n\n for i in range(arr_size):\n next_element: float = -1\n for j in range(i + 1, arr_size):\n if arr[i] < arr[j]:\n next_element = arr[j]\n break\n result.append(next_element)\n return result\n\n\ndef next_greatest_element_fast(arr: list[float]) -> list[float]:\n \"\"\"\n Like next_greatest_element_slow() but changes the loops to use\n enumerate() instead of range(len()) for the outer loop and\n for in a slice of arr for the inner loop.\n >>> next_greatest_element_fast(arr) == expect\n True\n \"\"\"\n result = []\n for i, outer in enumerate(arr):\n next_item: float = -1\n for inner in arr[i + 1 :]:\n if outer < inner:\n next_item = inner\n break\n result.append(next_item)\n return result\n\n\ndef next_greatest_element(arr: list[float]) -> list[float]:\n \"\"\"\n Get the Next Greatest Element (NGE) for all elements in a list.\n Maximum element present after the current one which is also greater than the\n current one.\n\n A naive way to solve this is to take two loops and check for the next bigger\n number but that will make the time complexity as O(n^2). The better way to solve\n this would be to use a stack to keep track of maximum number giving a linear time\n solution.\n >>> next_greatest_element(arr) == expect\n True\n \"\"\"\n arr_size = len(arr)\n stack: list[float] = []\n result: list[float] = [-1] * arr_size\n\n for index in reversed(range(arr_size)):\n if stack:\n while stack[-1] <= arr[index]:\n stack.pop()\n if not stack:\n break\n if stack:\n result[index] = stack[-1]\n stack.append(arr[index])\n return result\n\n\nif __name__ == \"__main__\":\n from doctest import testmod\n from timeit import timeit\n\n testmod()\n print(next_greatest_element_slow(arr))\n print(next_greatest_element_fast(arr))\n print(next_greatest_element(arr))\n\n setup = (\n \"from __main__ import arr, next_greatest_element_slow, \"\n \"next_greatest_element_fast, next_greatest_element\"\n )\n print(\n \"next_greatest_element_slow():\",\n timeit(\"next_greatest_element_slow(arr)\", setup=setup),\n )\n print(\n \"next_greatest_element_fast():\",\n timeit(\"next_greatest_element_fast(arr)\", setup=setup),\n )\n print(\n \" next_greatest_element():\",\n timeit(\"next_greatest_element(arr)\", setup=setup),\n )\n"} +{"Prompt":"Reverse Polish Nation is also known as Polish postfix notation or simply postfix notation. https:en.wikipedia.orgwikiReversePolishnotation Classic examples of simple stack implementations. Valid operators are , , , . Each operand may be an integer or another expression. Output: Enter a Postfix Equation space separated 5 6 9 Symbol Action Stack 5 push5 5 6 push6 5,6 9 push9 5,6,9 pop9 5,6 pop6 5 push69 5,54 pop54 5 pop5 push554 59 Result 59 Defining valid unary operator symbols operators their respective operation Converts the given data to the appropriate number if it is indeed a number, else returns the data as it is with a False flag. This function also serves as a check of whether the input is a number or not. Parameters token: The data that needs to be converted to the appropriate operator or number. Returns float or str Returns a float if token is a number or a str if token is an operator Evaluate postfix expression using a stack. evaluate0 0.0 evaluate0 0.0 evaluate1 1.0 evaluate1 1.0 evaluate1.1 1.1 evaluate2, 1, , 3, 9.0 evaluate2, 1.9, , 3, 11.7 evaluate2, 1.9, , 3, 0.30000000000000027 evaluate4, 13, 5, , 6.6 evaluate2, , 3, 1.0 evaluate4, 5, , 6, 26.0 evaluate 0 evaluate4, , 6, 7, , 9, 8 Traceback most recent call last: ... ArithmeticError: Input is not a valid postfix expression Parameters postfix: The postfix expression is tokenized into operators and operands and stored as a Python list verbose: Display stack contents while evaluating the expression if verbose is True Returns float The evaluated value Checking the list to find out whether the postfix expression is valid print table header output in tabular format If x is operator If only 1 value is inside the stack and or is encountered then this is unary or case output in tabular format output in tabular format output in tabular format evaluate the 2 values popped from stack push result to stack output in tabular format If everything is executed correctly, the stack will contain only one element which is the result Create a loop so that the user can evaluate postfix expressions multiple times","Completions":"# Defining valid unary operator symbols\nUNARY_OP_SYMBOLS = (\"-\", \"+\")\n\n# operators & their respective operation\nOPERATORS = {\n \"^\": lambda p, q: p**q,\n \"*\": lambda p, q: p * q,\n \"\/\": lambda p, q: p \/ q,\n \"+\": lambda p, q: p + q,\n \"-\": lambda p, q: p - q,\n}\n\n\ndef parse_token(token: str | float) -> float | str:\n \"\"\"\n Converts the given data to the appropriate number if it is indeed a number, else\n returns the data as it is with a False flag. This function also serves as a check\n of whether the input is a number or not.\n\n Parameters\n ----------\n token: The data that needs to be converted to the appropriate operator or number.\n\n Returns\n -------\n float or str\n Returns a float if `token` is a number or a str if `token` is an operator\n \"\"\"\n if token in OPERATORS:\n return token\n try:\n return float(token)\n except ValueError:\n msg = f\"{token} is neither a number nor a valid operator\"\n raise ValueError(msg)\n\n\ndef evaluate(post_fix: list[str], verbose: bool = False) -> float:\n \"\"\"\n Evaluate postfix expression using a stack.\n >>> evaluate([\"0\"])\n 0.0\n >>> evaluate([\"-0\"])\n -0.0\n >>> evaluate([\"1\"])\n 1.0\n >>> evaluate([\"-1\"])\n -1.0\n >>> evaluate([\"-1.1\"])\n -1.1\n >>> evaluate([\"2\", \"1\", \"+\", \"3\", \"*\"])\n 9.0\n >>> evaluate([\"2\", \"1.9\", \"+\", \"3\", \"*\"])\n 11.7\n >>> evaluate([\"2\", \"-1.9\", \"+\", \"3\", \"*\"])\n 0.30000000000000027\n >>> evaluate([\"4\", \"13\", \"5\", \"\/\", \"+\"])\n 6.6\n >>> evaluate([\"2\", \"-\", \"3\", \"+\"])\n 1.0\n >>> evaluate([\"-4\", \"5\", \"*\", \"6\", \"-\"])\n -26.0\n >>> evaluate([])\n 0\n >>> evaluate([\"4\", \"-\", \"6\", \"7\", \"\/\", \"9\", \"8\"])\n Traceback (most recent call last):\n ...\n ArithmeticError: Input is not a valid postfix expression\n\n Parameters\n ----------\n post_fix:\n The postfix expression is tokenized into operators and operands and stored\n as a Python list\n\n verbose:\n Display stack contents while evaluating the expression if verbose is True\n\n Returns\n -------\n float\n The evaluated value\n \"\"\"\n if not post_fix:\n return 0\n # Checking the list to find out whether the postfix expression is valid\n valid_expression = [parse_token(token) for token in post_fix]\n if verbose:\n # print table header\n print(\"Symbol\".center(8), \"Action\".center(12), \"Stack\", sep=\" | \")\n print(\"-\" * (30 + len(post_fix)))\n stack = []\n for x in valid_expression:\n if x not in OPERATORS:\n stack.append(x) # append x to stack\n if verbose:\n # output in tabular format\n print(\n f\"{x}\".rjust(8),\n f\"push({x})\".ljust(12),\n stack,\n sep=\" | \",\n )\n continue\n # If x is operator\n # If only 1 value is inside the stack and + or - is encountered\n # then this is unary + or - case\n if x in UNARY_OP_SYMBOLS and len(stack) < 2:\n b = stack.pop() # pop stack\n if x == \"-\":\n b *= -1 # negate b\n stack.append(b)\n if verbose:\n # output in tabular format\n print(\n \"\".rjust(8),\n f\"pop({b})\".ljust(12),\n stack,\n sep=\" | \",\n )\n print(\n str(x).rjust(8),\n f\"push({x}{b})\".ljust(12),\n stack,\n sep=\" | \",\n )\n continue\n b = stack.pop() # pop stack\n if verbose:\n # output in tabular format\n print(\n \"\".rjust(8),\n f\"pop({b})\".ljust(12),\n stack,\n sep=\" | \",\n )\n\n a = stack.pop() # pop stack\n if verbose:\n # output in tabular format\n print(\n \"\".rjust(8),\n f\"pop({a})\".ljust(12),\n stack,\n sep=\" | \",\n )\n # evaluate the 2 values popped from stack & push result to stack\n stack.append(OPERATORS[x](a, b)) # type: ignore[index]\n if verbose:\n # output in tabular format\n print(\n f\"{x}\".rjust(8),\n f\"push({a}{x}{b})\".ljust(12),\n stack,\n sep=\" | \",\n )\n # If everything is executed correctly, the stack will contain\n # only one element which is the result\n if len(stack) != 1:\n raise ArithmeticError(\"Input is not a valid postfix expression\")\n return float(stack[0])\n\n\nif __name__ == \"__main__\":\n # Create a loop so that the user can evaluate postfix expressions multiple times\n while True:\n expression = input(\"Enter a Postfix Expression (space separated): \").split(\" \")\n prompt = \"Do you want to see stack contents while evaluating? [y\/N]: \"\n verbose = input(prompt).strip().lower() == \"y\"\n output = evaluate(expression, verbose)\n print(\"Result = \", output)\n prompt = \"Do you want to enter another expression? [y\/N]: \"\n if input(prompt).strip().lower() != \"y\":\n break\n"} +{"Prompt":"Python3 program to evaluate a prefix expression. Return True if the given char c is an operand, e.g. it is a number isoperand1 True isoperand False Evaluate a given expression in prefix notation. Asserts that the given expression is valid. evaluate 9 2 6 21 evaluate 10 2 4 1 4.0 iterate over the string in reverse order push operand to stack pop values from stack can calculate the result push the result onto the stack again Driver code","Completions":"calc = {\n \"+\": lambda x, y: x + y,\n \"-\": lambda x, y: x - y,\n \"*\": lambda x, y: x * y,\n \"\/\": lambda x, y: x \/ y,\n}\n\n\ndef is_operand(c):\n \"\"\"\n Return True if the given char c is an operand, e.g. it is a number\n\n >>> is_operand(\"1\")\n True\n >>> is_operand(\"+\")\n False\n \"\"\"\n return c.isdigit()\n\n\ndef evaluate(expression):\n \"\"\"\n Evaluate a given expression in prefix notation.\n Asserts that the given expression is valid.\n\n >>> evaluate(\"+ 9 * 2 6\")\n 21\n >>> evaluate(\"\/ * 10 2 + 4 1 \")\n 4.0\n \"\"\"\n stack = []\n\n # iterate over the string in reverse order\n for c in expression.split()[::-1]:\n # push operand to stack\n if is_operand(c):\n stack.append(int(c))\n\n else:\n # pop values from stack can calculate the result\n # push the result onto the stack again\n o1 = stack.pop()\n o2 = stack.pop()\n stack.append(calc[c](o1, o2))\n\n return stack.pop()\n\n\n# Driver code\nif __name__ == \"__main__\":\n test_expression = \"+ 9 * 2 6\"\n print(evaluate(test_expression))\n\n test_expression = \"\/ * 10 2 + 4 1 \"\n print(evaluate(test_expression))\n"} +{"Prompt":"A stack is an abstract data type that serves as a collection of elements with two principal operations: push and pop. push adds an element to the top of the stack, and pop removes an element from the top of a stack. The order in which elements come off of a stack are Last In, First Out LIFO. https:en.wikipedia.orgwikiStackabstractdatatype Push an element to the top of the stack. S Stack2 stack size 2 S.push10 S.push20 printS 10, 20 S Stack1 stack size 1 S.push10 S.push20 Traceback most recent call last: ... datastructures.stacks.stack.StackOverflowError Pop an element off of the top of the stack. S Stack S.push5 S.push10 S.pop 10 Stack.pop Traceback most recent call last: ... datastructures.stacks.stack.StackUnderflowError Peek at the topmost element of the stack. S Stack S.push5 S.push10 S.peek 10 Stack.peek Traceback most recent call last: ... datastructures.stacks.stack.StackUnderflowError Check if a stack is empty. S Stack S.isempty True S Stack S.push10 S.isempty False S Stack S.isfull False S Stack1 S.push10 S.isfull True Return the size of the stack. S Stack3 S.size 0 S Stack3 S.push10 S.size 1 S Stack3 S.push10 S.push20 S.size 2 Check if item is in stack S Stack3 S.push10 10 in S True S Stack3 S.push10 20 in S False teststack","Completions":"from __future__ import annotations\n\nfrom typing import Generic, TypeVar\n\nT = TypeVar(\"T\")\n\n\nclass StackOverflowError(BaseException):\n pass\n\n\nclass StackUnderflowError(BaseException):\n pass\n\n\nclass Stack(Generic[T]):\n \"\"\"A stack is an abstract data type that serves as a collection of\n elements with two principal operations: push() and pop(). push() adds an\n element to the top of the stack, and pop() removes an element from the top\n of a stack. The order in which elements come off of a stack are\n Last In, First Out (LIFO).\n https:\/\/en.wikipedia.org\/wiki\/Stack_(abstract_data_type)\n \"\"\"\n\n def __init__(self, limit: int = 10):\n self.stack: list[T] = []\n self.limit = limit\n\n def __bool__(self) -> bool:\n return bool(self.stack)\n\n def __str__(self) -> str:\n return str(self.stack)\n\n def push(self, data: T) -> None:\n \"\"\"\n Push an element to the top of the stack.\n\n >>> S = Stack(2) # stack size = 2\n >>> S.push(10)\n >>> S.push(20)\n >>> print(S)\n [10, 20]\n\n >>> S = Stack(1) # stack size = 1\n >>> S.push(10)\n >>> S.push(20)\n Traceback (most recent call last):\n ...\n data_structures.stacks.stack.StackOverflowError\n\n \"\"\"\n if len(self.stack) >= self.limit:\n raise StackOverflowError\n self.stack.append(data)\n\n def pop(self) -> T:\n \"\"\"\n Pop an element off of the top of the stack.\n\n >>> S = Stack()\n >>> S.push(-5)\n >>> S.push(10)\n >>> S.pop()\n 10\n\n >>> Stack().pop()\n Traceback (most recent call last):\n ...\n data_structures.stacks.stack.StackUnderflowError\n \"\"\"\n if not self.stack:\n raise StackUnderflowError\n return self.stack.pop()\n\n def peek(self) -> T:\n \"\"\"\n Peek at the top-most element of the stack.\n\n >>> S = Stack()\n >>> S.push(-5)\n >>> S.push(10)\n >>> S.peek()\n 10\n\n >>> Stack().peek()\n Traceback (most recent call last):\n ...\n data_structures.stacks.stack.StackUnderflowError\n \"\"\"\n if not self.stack:\n raise StackUnderflowError\n return self.stack[-1]\n\n def is_empty(self) -> bool:\n \"\"\"\n Check if a stack is empty.\n\n >>> S = Stack()\n >>> S.is_empty()\n True\n\n >>> S = Stack()\n >>> S.push(10)\n >>> S.is_empty()\n False\n \"\"\"\n return not bool(self.stack)\n\n def is_full(self) -> bool:\n \"\"\"\n >>> S = Stack()\n >>> S.is_full()\n False\n\n >>> S = Stack(1)\n >>> S.push(10)\n >>> S.is_full()\n True\n \"\"\"\n return self.size() == self.limit\n\n def size(self) -> int:\n \"\"\"\n Return the size of the stack.\n\n >>> S = Stack(3)\n >>> S.size()\n 0\n\n >>> S = Stack(3)\n >>> S.push(10)\n >>> S.size()\n 1\n\n >>> S = Stack(3)\n >>> S.push(10)\n >>> S.push(20)\n >>> S.size()\n 2\n \"\"\"\n return len(self.stack)\n\n def __contains__(self, item: T) -> bool:\n \"\"\"\n Check if item is in stack\n\n >>> S = Stack(3)\n >>> S.push(10)\n >>> 10 in S\n True\n\n >>> S = Stack(3)\n >>> S.push(10)\n >>> 20 in S\n False\n \"\"\"\n return item in self.stack\n\n\ndef test_stack() -> None:\n \"\"\"\n >>> test_stack()\n \"\"\"\n stack: Stack[int] = Stack(10)\n assert bool(stack) is False\n assert stack.is_empty() is True\n assert stack.is_full() is False\n assert str(stack) == \"[]\"\n\n try:\n _ = stack.pop()\n raise AssertionError # This should not happen\n except StackUnderflowError:\n assert True # This should happen\n\n try:\n _ = stack.peek()\n raise AssertionError # This should not happen\n except StackUnderflowError:\n assert True # This should happen\n\n for i in range(10):\n assert stack.size() == i\n stack.push(i)\n\n assert bool(stack)\n assert not stack.is_empty()\n assert stack.is_full()\n assert str(stack) == str(list(range(10)))\n assert stack.pop() == 9\n assert stack.peek() == 8\n\n stack.push(100)\n assert str(stack) == str([0, 1, 2, 3, 4, 5, 6, 7, 8, 100])\n\n try:\n stack.push(200)\n raise AssertionError # This should not happen\n except StackOverflowError:\n assert True # This should happen\n\n assert not stack.is_empty()\n assert stack.size() == 10\n\n assert 5 in stack\n assert 55 not in stack\n\n\nif __name__ == \"__main__\":\n test_stack()\n\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"https:www.geeksforgeeks.orgimplementstackusingqueue stack StackWithQueues stack.push1 stack.push2 stack.push3 stack.peek 3 stack.pop 3 stack.peek 2 stack.pop 2 stack.pop 1 stack.peek is None True stack.pop Traceback most recent call last: ... IndexError: pop from an empty deque","Completions":"from __future__ import annotations\n\nfrom collections import deque\nfrom dataclasses import dataclass, field\n\n\n@dataclass\nclass StackWithQueues:\n \"\"\"\n https:\/\/www.geeksforgeeks.org\/implement-stack-using-queue\/\n\n >>> stack = StackWithQueues()\n >>> stack.push(1)\n >>> stack.push(2)\n >>> stack.push(3)\n >>> stack.peek()\n 3\n >>> stack.pop()\n 3\n >>> stack.peek()\n 2\n >>> stack.pop()\n 2\n >>> stack.pop()\n 1\n >>> stack.peek() is None\n True\n >>> stack.pop()\n Traceback (most recent call last):\n ...\n IndexError: pop from an empty deque\n \"\"\"\n\n main_queue: deque[int] = field(default_factory=deque)\n temp_queue: deque[int] = field(default_factory=deque)\n\n def push(self, item: int) -> None:\n self.temp_queue.append(item)\n while self.main_queue:\n self.temp_queue.append(self.main_queue.popleft())\n self.main_queue, self.temp_queue = self.temp_queue, self.main_queue\n\n def pop(self) -> int:\n return self.main_queue.popleft()\n\n def peek(self) -> int | None:\n return self.main_queue[0] if self.main_queue else None\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n\n stack: StackWithQueues | None = StackWithQueues()\n while stack:\n print(\"\\nChoose operation:\")\n print(\"1. Push\")\n print(\"2. Pop\")\n print(\"3. Peek\")\n print(\"4. Quit\")\n\n choice = input(\"Enter choice (1\/2\/3\/4): \")\n\n if choice == \"1\":\n element = int(input(\"Enter an integer to push: \").strip())\n stack.push(element)\n print(f\"{element} pushed onto the stack.\")\n elif choice == \"2\":\n popped_element = stack.pop()\n if popped_element is not None:\n print(f\"Popped element: {popped_element}\")\n else:\n print(\"Stack is empty.\")\n elif choice == \"3\":\n peeked_element = stack.peek()\n if peeked_element is not None:\n print(f\"Top element: {peeked_element}\")\n else:\n print(\"Stack is empty.\")\n elif choice == \"4\":\n del stack\n stack = None\n else:\n print(\"Invalid choice. Please try again.\")\n"} +{"Prompt":"A complete working Python program to demonstrate all stack operations using a doubly linked list stack Stack stack.isempty True stack.printstack stack elements are: for i in range4: ... stack.pushi ... stack.isempty False stack.printstack stack elements are: 3210 stack.top 3 lenstack 4 stack.pop 3 stack.printstack stack elements are: 210 add a Node to the stack if self.head is None: self.head Nodedata else: newnode Nodedata self.head.prev newnode newnode.next self.head newnode.prev None self.head newnode def popself T None: return the top element of the stack return self.head.data if self.head is not None else None def lenself int: temp self.head count 0 while temp is not None: count 1 temp temp.next return count def isemptyself bool: return self.head is None def printstackself None: printstack elements are: temp self.head while temp is not None: printtemp.data, end temp temp.next Code execution starts here if name main: Start with the empty stack stack: Stackint Stack Insert 4 at the beginning. So stack becomes 4None printStack operations using Doubly LinkedList stack.push4 Insert 5 at the beginning. So stack becomes 45None stack.push5 Insert 6 at the beginning. So stack becomes 456None stack.push6 Insert 7 at the beginning. So stack becomes 4567None stack.push7 Print the stack stack.printstack Print the top element printnTop element is , stack.top Print the stack size printSize of the stack is , lenstack pop the top element stack.pop pop the top element stack.pop two elements have now been popped off stack.printstack Print True if the stack is empty else False printnstack is empty:, stack.isempty","Completions":"# A complete working Python program to demonstrate all\n# stack operations using a doubly linked list\n\nfrom __future__ import annotations\n\nfrom typing import Generic, TypeVar\n\nT = TypeVar(\"T\")\n\n\nclass Node(Generic[T]):\n def __init__(self, data: T):\n self.data = data # Assign data\n self.next: Node[T] | None = None # Initialize next as null\n self.prev: Node[T] | None = None # Initialize prev as null\n\n\nclass Stack(Generic[T]):\n \"\"\"\n >>> stack = Stack()\n >>> stack.is_empty()\n True\n >>> stack.print_stack()\n stack elements are:\n >>> for i in range(4):\n ... stack.push(i)\n ...\n >>> stack.is_empty()\n False\n >>> stack.print_stack()\n stack elements are:\n 3->2->1->0->\n >>> stack.top()\n 3\n >>> len(stack)\n 4\n >>> stack.pop()\n 3\n >>> stack.print_stack()\n stack elements are:\n 2->1->0->\n \"\"\"\n\n def __init__(self) -> None:\n self.head: Node[T] | None = None\n\n def push(self, data: T) -> None:\n \"\"\"add a Node to the stack\"\"\"\n if self.head is None:\n self.head = Node(data)\n else:\n new_node = Node(data)\n self.head.prev = new_node\n new_node.next = self.head\n new_node.prev = None\n self.head = new_node\n\n def pop(self) -> T | None:\n \"\"\"pop the top element off the stack\"\"\"\n if self.head is None:\n return None\n else:\n assert self.head is not None\n temp = self.head.data\n self.head = self.head.next\n if self.head is not None:\n self.head.prev = None\n return temp\n\n def top(self) -> T | None:\n \"\"\"return the top element of the stack\"\"\"\n return self.head.data if self.head is not None else None\n\n def __len__(self) -> int:\n temp = self.head\n count = 0\n while temp is not None:\n count += 1\n temp = temp.next\n return count\n\n def is_empty(self) -> bool:\n return self.head is None\n\n def print_stack(self) -> None:\n print(\"stack elements are:\")\n temp = self.head\n while temp is not None:\n print(temp.data, end=\"->\")\n temp = temp.next\n\n\n# Code execution starts here\nif __name__ == \"__main__\":\n # Start with the empty stack\n stack: Stack[int] = Stack()\n\n # Insert 4 at the beginning. So stack becomes 4->None\n print(\"Stack operations using Doubly LinkedList\")\n stack.push(4)\n\n # Insert 5 at the beginning. So stack becomes 4->5->None\n stack.push(5)\n\n # Insert 6 at the beginning. So stack becomes 4->5->6->None\n stack.push(6)\n\n # Insert 7 at the beginning. So stack becomes 4->5->6->7->None\n stack.push(7)\n\n # Print the stack\n stack.print_stack()\n\n # Print the top element\n print(\"\\nTop element is \", stack.top())\n\n # Print the stack size\n print(\"Size of the stack is \", len(stack))\n\n # pop the top element\n stack.pop()\n\n # pop the top element\n stack.pop()\n\n # two elements have now been popped off\n stack.print_stack()\n\n # Print True if the stack is empty else False\n print(\"\\nstack is empty:\", stack.is_empty())\n"} +{"Prompt":"A Stack using a linked list like structure from future import annotations from collections.abc import Iterator from typing import Generic, TypeVar T TypeVarT class NodeGenericT: def initself, data: T: self.data data self.next: NodeT None None def strself str: return fself.data class LinkedStackGenericT: def initself None: self.top: NodeT None None def iterself IteratorT: node self.top while node: yield node.data node node.next def strself str: return .joinstritem for item in self def lenself int: return lentupleiterself def isemptyself bool: return self.top is None def pushself, item: T None: node Nodeitem if not self.isempty: node.next self.top self.top node def popself T: if self.isempty: raise IndexErrorpop from empty stack assert isinstanceself.top, Node popnode self.top self.top self.top.next return popnode.data def peekself T: if self.isempty: raise IndexErrorpeek from empty stack assert self.top is not None return self.top.data def clearself None: self.top None if name main: from doctest import testmod testmod","Completions":"from __future__ import annotations\n\nfrom collections.abc import Iterator\nfrom typing import Generic, TypeVar\n\nT = TypeVar(\"T\")\n\n\nclass Node(Generic[T]):\n def __init__(self, data: T):\n self.data = data\n self.next: Node[T] | None = None\n\n def __str__(self) -> str:\n return f\"{self.data}\"\n\n\nclass LinkedStack(Generic[T]):\n \"\"\"\n Linked List Stack implementing push (to top),\n pop (from top) and is_empty\n\n >>> stack = LinkedStack()\n >>> stack.is_empty()\n True\n >>> stack.push(5)\n >>> stack.push(9)\n >>> stack.push('python')\n >>> stack.is_empty()\n False\n >>> stack.pop()\n 'python'\n >>> stack.push('algorithms')\n >>> stack.pop()\n 'algorithms'\n >>> stack.pop()\n 9\n >>> stack.pop()\n 5\n >>> stack.is_empty()\n True\n >>> stack.pop()\n Traceback (most recent call last):\n ...\n IndexError: pop from empty stack\n \"\"\"\n\n def __init__(self) -> None:\n self.top: Node[T] | None = None\n\n def __iter__(self) -> Iterator[T]:\n node = self.top\n while node:\n yield node.data\n node = node.next\n\n def __str__(self) -> str:\n \"\"\"\n >>> stack = LinkedStack()\n >>> stack.push(\"c\")\n >>> stack.push(\"b\")\n >>> stack.push(\"a\")\n >>> str(stack)\n 'a->b->c'\n \"\"\"\n return \"->\".join([str(item) for item in self])\n\n def __len__(self) -> int:\n \"\"\"\n >>> stack = LinkedStack()\n >>> len(stack) == 0\n True\n >>> stack.push(\"c\")\n >>> stack.push(\"b\")\n >>> stack.push(\"a\")\n >>> len(stack) == 3\n True\n \"\"\"\n return len(tuple(iter(self)))\n\n def is_empty(self) -> bool:\n \"\"\"\n >>> stack = LinkedStack()\n >>> stack.is_empty()\n True\n >>> stack.push(1)\n >>> stack.is_empty()\n False\n \"\"\"\n return self.top is None\n\n def push(self, item: T) -> None:\n \"\"\"\n >>> stack = LinkedStack()\n >>> stack.push(\"Python\")\n >>> stack.push(\"Java\")\n >>> stack.push(\"C\")\n >>> str(stack)\n 'C->Java->Python'\n \"\"\"\n node = Node(item)\n if not self.is_empty():\n node.next = self.top\n self.top = node\n\n def pop(self) -> T:\n \"\"\"\n >>> stack = LinkedStack()\n >>> stack.pop()\n Traceback (most recent call last):\n ...\n IndexError: pop from empty stack\n >>> stack.push(\"c\")\n >>> stack.push(\"b\")\n >>> stack.push(\"a\")\n >>> stack.pop() == 'a'\n True\n >>> stack.pop() == 'b'\n True\n >>> stack.pop() == 'c'\n True\n \"\"\"\n if self.is_empty():\n raise IndexError(\"pop from empty stack\")\n assert isinstance(self.top, Node)\n pop_node = self.top\n self.top = self.top.next\n return pop_node.data\n\n def peek(self) -> T:\n \"\"\"\n >>> stack = LinkedStack()\n >>> stack.push(\"Java\")\n >>> stack.push(\"C\")\n >>> stack.push(\"Python\")\n >>> stack.peek()\n 'Python'\n \"\"\"\n if self.is_empty():\n raise IndexError(\"peek from empty stack\")\n\n assert self.top is not None\n return self.top.data\n\n def clear(self) -> None:\n \"\"\"\n >>> stack = LinkedStack()\n >>> stack.push(\"Java\")\n >>> stack.push(\"C\")\n >>> stack.push(\"Python\")\n >>> str(stack)\n 'Python->C->Java'\n >>> stack.clear()\n >>> len(stack) == 0\n True\n \"\"\"\n self.top = None\n\n\nif __name__ == \"__main__\":\n from doctest import testmod\n\n testmod()\n"} +{"Prompt":"The stock span problem is a financial problem where we have a series of n daily price quotes for a stock and we need to calculate span of stock's price for all n days. The span Si of the stock's price on a given day i is defined as the maximum number of consecutive days just before the given day, for which the price of the stock on the current day is less than or equal to its price on the given day. Create a stack and push index of fist element to it Span value of first element is always 1 Calculate span values for rest of the elements Pop elements from stack while stack is not empty and top of stack is smaller than pricei If stack becomes empty, then pricei is greater than all elements on left of it, i.e. price0, price1, ..pricei1. Else the pricei is greater than elements after top of stack Push this element to stack A utility function to print elements of array Driver program to test above function Fill the span values in array S Print the calculated span values","Completions":"def calculation_span(price, s):\n n = len(price)\n # Create a stack and push index of fist element to it\n st = []\n st.append(0)\n\n # Span value of first element is always 1\n s[0] = 1\n\n # Calculate span values for rest of the elements\n for i in range(1, n):\n # Pop elements from stack while stack is not\n # empty and top of stack is smaller than price[i]\n while len(st) > 0 and price[st[0]] <= price[i]:\n st.pop()\n\n # If stack becomes empty, then price[i] is greater\n # than all elements on left of it, i.e. price[0],\n # price[1], ..price[i-1]. Else the price[i] is\n # greater than elements after top of stack\n s[i] = i + 1 if len(st) <= 0 else (i - st[0])\n\n # Push this element to stack\n st.append(i)\n\n\n# A utility function to print elements of array\ndef print_array(arr, n):\n for i in range(n):\n print(arr[i], end=\" \")\n\n\n# Driver program to test above function\nprice = [10, 4, 5, 90, 120, 80]\nS = [0 for i in range(len(price) + 1)]\n\n# Fill the span values in array S[]\ncalculation_span(price, S)\n\n# Print the calculated span values\nprint_array(S, len(price))\n"} +{"Prompt":"A Radix Tree is a data structure that represents a spaceoptimized trie prefix tree in whicheach node that is the only child is merged with its parent https:en.wikipedia.orgwikiRadixtree Mapping from the first character of the prefix of the node A node will be a leaf if the tree contains its word Compute the common substring of the prefix of the node and a word Args: word str: word to compare Returns: str, str, str: common substring, remaining prefix, remaining word RadixNodemyprefix.matchmystring 'my', 'prefix', 'string' Insert many words in the tree Args: words liststr: list of words RadixNodemyprefix.insertmanymystring, hello Insert a word into the tree Args: word str: word to insert RadixNodemyprefix.insertmystring root RadixNode root.insertmany'myprefix', 'myprefixA', 'myprefixAA' root.printtree myprefix leaf A leaf A leaf Case 1: If the word is the prefix of the node Solution: We set the current node as leaf Case 2: The node has no edges that have a prefix to the word Solution: We create an edge from the current node to a new one containing the word Case 3: The node prefix is equal to the matching Solution: We insert remaining word on the next node Case 4: The word is greater equal to the matching Solution: Create a node in between both nodes, change prefixes and add the new node for the remaining word Returns if the word is on the tree Args: word str: word to check Returns: bool: True if the word appears on the tree RadixNodemyprefix.findmystring False If there is remaining prefix, the word can't be on the tree This applies when the word and the prefix are equal We have word remaining so we check the next node Deletes a word from the tree if it exists Args: word str: word to be deleted Returns: bool: True if the word was found and deleted. False if word is not found RadixNodemyprefix.deletemystring False If there is remaining prefix, the word can't be on the tree We have word remaining so we check the next node If it is not a leaf, we don't have to delete We delete the nodes if no edges go from it We merge the current node with its only child If there is more than 1 edge, we just mark it as nonleaf If there is 1 edge, we merge it with its child Print the tree Args: height int, optional: Height of the printed node pytests","Completions":"class RadixNode:\n def __init__(self, prefix: str = \"\", is_leaf: bool = False) -> None:\n # Mapping from the first character of the prefix of the node\n self.nodes: dict[str, RadixNode] = {}\n\n # A node will be a leaf if the tree contains its word\n self.is_leaf = is_leaf\n\n self.prefix = prefix\n\n def match(self, word: str) -> tuple[str, str, str]:\n \"\"\"Compute the common substring of the prefix of the node and a word\n\n Args:\n word (str): word to compare\n\n Returns:\n (str, str, str): common substring, remaining prefix, remaining word\n\n >>> RadixNode(\"myprefix\").match(\"mystring\")\n ('my', 'prefix', 'string')\n \"\"\"\n x = 0\n for q, w in zip(self.prefix, word):\n if q != w:\n break\n\n x += 1\n\n return self.prefix[:x], self.prefix[x:], word[x:]\n\n def insert_many(self, words: list[str]) -> None:\n \"\"\"Insert many words in the tree\n\n Args:\n words (list[str]): list of words\n\n >>> RadixNode(\"myprefix\").insert_many([\"mystring\", \"hello\"])\n \"\"\"\n for word in words:\n self.insert(word)\n\n def insert(self, word: str) -> None:\n \"\"\"Insert a word into the tree\n\n Args:\n word (str): word to insert\n\n >>> RadixNode(\"myprefix\").insert(\"mystring\")\n\n >>> root = RadixNode()\n >>> root.insert_many(['myprefix', 'myprefixA', 'myprefixAA'])\n >>> root.print_tree()\n - myprefix (leaf)\n -- A (leaf)\n --- A (leaf)\n \"\"\"\n # Case 1: If the word is the prefix of the node\n # Solution: We set the current node as leaf\n if self.prefix == word and not self.is_leaf:\n self.is_leaf = True\n\n # Case 2: The node has no edges that have a prefix to the word\n # Solution: We create an edge from the current node to a new one\n # containing the word\n elif word[0] not in self.nodes:\n self.nodes[word[0]] = RadixNode(prefix=word, is_leaf=True)\n\n else:\n incoming_node = self.nodes[word[0]]\n matching_string, remaining_prefix, remaining_word = incoming_node.match(\n word\n )\n\n # Case 3: The node prefix is equal to the matching\n # Solution: We insert remaining word on the next node\n if remaining_prefix == \"\":\n self.nodes[matching_string[0]].insert(remaining_word)\n\n # Case 4: The word is greater equal to the matching\n # Solution: Create a node in between both nodes, change\n # prefixes and add the new node for the remaining word\n else:\n incoming_node.prefix = remaining_prefix\n\n aux_node = self.nodes[matching_string[0]]\n self.nodes[matching_string[0]] = RadixNode(matching_string, False)\n self.nodes[matching_string[0]].nodes[remaining_prefix[0]] = aux_node\n\n if remaining_word == \"\":\n self.nodes[matching_string[0]].is_leaf = True\n else:\n self.nodes[matching_string[0]].insert(remaining_word)\n\n def find(self, word: str) -> bool:\n \"\"\"Returns if the word is on the tree\n\n Args:\n word (str): word to check\n\n Returns:\n bool: True if the word appears on the tree\n\n >>> RadixNode(\"myprefix\").find(\"mystring\")\n False\n \"\"\"\n incoming_node = self.nodes.get(word[0], None)\n if not incoming_node:\n return False\n else:\n matching_string, remaining_prefix, remaining_word = incoming_node.match(\n word\n )\n # If there is remaining prefix, the word can't be on the tree\n if remaining_prefix != \"\":\n return False\n # This applies when the word and the prefix are equal\n elif remaining_word == \"\":\n return incoming_node.is_leaf\n # We have word remaining so we check the next node\n else:\n return incoming_node.find(remaining_word)\n\n def delete(self, word: str) -> bool:\n \"\"\"Deletes a word from the tree if it exists\n\n Args:\n word (str): word to be deleted\n\n Returns:\n bool: True if the word was found and deleted. False if word is not found\n\n >>> RadixNode(\"myprefix\").delete(\"mystring\")\n False\n \"\"\"\n incoming_node = self.nodes.get(word[0], None)\n if not incoming_node:\n return False\n else:\n matching_string, remaining_prefix, remaining_word = incoming_node.match(\n word\n )\n # If there is remaining prefix, the word can't be on the tree\n if remaining_prefix != \"\":\n return False\n # We have word remaining so we check the next node\n elif remaining_word != \"\":\n return incoming_node.delete(remaining_word)\n else:\n # If it is not a leaf, we don't have to delete\n if not incoming_node.is_leaf:\n return False\n else:\n # We delete the nodes if no edges go from it\n if len(incoming_node.nodes) == 0:\n del self.nodes[word[0]]\n # We merge the current node with its only child\n if len(self.nodes) == 1 and not self.is_leaf:\n merging_node = next(iter(self.nodes.values()))\n self.is_leaf = merging_node.is_leaf\n self.prefix += merging_node.prefix\n self.nodes = merging_node.nodes\n # If there is more than 1 edge, we just mark it as non-leaf\n elif len(incoming_node.nodes) > 1:\n incoming_node.is_leaf = False\n # If there is 1 edge, we merge it with its child\n else:\n merging_node = next(iter(incoming_node.nodes.values()))\n incoming_node.is_leaf = merging_node.is_leaf\n incoming_node.prefix += merging_node.prefix\n incoming_node.nodes = merging_node.nodes\n\n return True\n\n def print_tree(self, height: int = 0) -> None:\n \"\"\"Print the tree\n\n Args:\n height (int, optional): Height of the printed node\n \"\"\"\n if self.prefix != \"\":\n print(\"-\" * height, self.prefix, \" (leaf)\" if self.is_leaf else \"\")\n\n for value in self.nodes.values():\n value.print_tree(height + 1)\n\n\ndef test_trie() -> bool:\n words = \"banana bananas bandana band apple all beast\".split()\n root = RadixNode()\n root.insert_many(words)\n\n assert all(root.find(word) for word in words)\n assert not root.find(\"bandanas\")\n assert not root.find(\"apps\")\n root.delete(\"all\")\n assert not root.find(\"all\")\n root.delete(\"banana\")\n assert not root.find(\"banana\")\n assert root.find(\"bananas\")\n\n return True\n\n\ndef pytests() -> None:\n assert test_trie()\n\n\ndef main() -> None:\n \"\"\"\n >>> pytests()\n \"\"\"\n root = RadixNode()\n words = \"banana bananas bandanas bandana band apple all beast\".split()\n root.insert_many(words)\n\n print(\"Words:\", words)\n print(\"Tree:\")\n root.print_tree()\n\n\nif __name__ == \"__main__\":\n main()\n"} +{"Prompt":"A TriePrefix Tree is a kind of search tree used to provide quick lookup of wordspatterns in a set of words. A basic Trie however has On2 space complexity making it impractical in practice. It however provides Omaxsearchstring, length of longest word lookup time making it an optimal approach when space is not an issue. Inserts a list of words into the Trie :param words: list of string words :return: None Inserts a word into the Trie :param word: word to be inserted :return: None Tries to find word in a Trie :param word: word to look for :return: Returns True if word is found, False otherwise Deletes a word in a Trie :param word: word to delete :return: None If word does not exist If char not in current trie node Flag to check if node can be deleted Prints all the words in a Trie :param node: root node of Trie :param word: Word variable should be empty at start :return: None printwordsroot, pytests","Completions":"class TrieNode:\n def __init__(self) -> None:\n self.nodes: dict[str, TrieNode] = {} # Mapping from char to TrieNode\n self.is_leaf = False\n\n def insert_many(self, words: list[str]) -> None:\n \"\"\"\n Inserts a list of words into the Trie\n :param words: list of string words\n :return: None\n \"\"\"\n for word in words:\n self.insert(word)\n\n def insert(self, word: str) -> None:\n \"\"\"\n Inserts a word into the Trie\n :param word: word to be inserted\n :return: None\n \"\"\"\n curr = self\n for char in word:\n if char not in curr.nodes:\n curr.nodes[char] = TrieNode()\n curr = curr.nodes[char]\n curr.is_leaf = True\n\n def find(self, word: str) -> bool:\n \"\"\"\n Tries to find word in a Trie\n :param word: word to look for\n :return: Returns True if word is found, False otherwise\n \"\"\"\n curr = self\n for char in word:\n if char not in curr.nodes:\n return False\n curr = curr.nodes[char]\n return curr.is_leaf\n\n def delete(self, word: str) -> None:\n \"\"\"\n Deletes a word in a Trie\n :param word: word to delete\n :return: None\n \"\"\"\n\n def _delete(curr: TrieNode, word: str, index: int) -> bool:\n if index == len(word):\n # If word does not exist\n if not curr.is_leaf:\n return False\n curr.is_leaf = False\n return len(curr.nodes) == 0\n char = word[index]\n char_node = curr.nodes.get(char)\n # If char not in current trie node\n if not char_node:\n return False\n # Flag to check if node can be deleted\n delete_curr = _delete(char_node, word, index + 1)\n if delete_curr:\n del curr.nodes[char]\n return len(curr.nodes) == 0\n return delete_curr\n\n _delete(self, word, 0)\n\n\ndef print_words(node: TrieNode, word: str) -> None:\n \"\"\"\n Prints all the words in a Trie\n :param node: root node of Trie\n :param word: Word variable should be empty at start\n :return: None\n \"\"\"\n if node.is_leaf:\n print(word, end=\" \")\n\n for key, value in node.nodes.items():\n print_words(value, word + key)\n\n\ndef test_trie() -> bool:\n words = \"banana bananas bandana band apple all beast\".split()\n root = TrieNode()\n root.insert_many(words)\n # print_words(root, \"\")\n assert all(root.find(word) for word in words)\n assert root.find(\"banana\")\n assert not root.find(\"bandanas\")\n assert not root.find(\"apps\")\n assert root.find(\"apple\")\n assert root.find(\"all\")\n root.delete(\"all\")\n assert not root.find(\"all\")\n root.delete(\"banana\")\n assert not root.find(\"banana\")\n assert root.find(\"bananas\")\n return True\n\n\ndef print_results(msg: str, passes: bool) -> None:\n print(str(msg), \"works!\" if passes else \"doesn't work :(\")\n\n\ndef pytests() -> None:\n assert test_trie()\n\n\ndef main() -> None:\n \"\"\"\n >>> pytests()\n \"\"\"\n print_results(\"Testing trie functionality\", test_trie())\n\n\nif __name__ == \"__main__\":\n main()\n"} +{"Prompt":"Change the brightness of a PIL Image to a given level. Fundamental TransformationOperation that'll be performed on every bit. Load image Change brightness to 100","Completions":"from PIL import Image\n\n\ndef change_brightness(img: Image, level: float) -> Image:\n \"\"\"\n Change the brightness of a PIL Image to a given level.\n \"\"\"\n\n def brightness(c: int) -> float:\n \"\"\"\n Fundamental Transformation\/Operation that'll be performed on\n every bit.\n \"\"\"\n return 128 + level + (c - 128)\n\n if not -255.0 <= level <= 255.0:\n raise ValueError(\"level must be between -255.0 (black) and 255.0 (white)\")\n return img.point(brightness)\n\n\nif __name__ == \"__main__\":\n # Load image\n with Image.open(\"image_data\/lena.jpg\") as img:\n # Change brightness to 100\n brigt_img = change_brightness(img, 100)\n brigt_img.save(\"image_data\/lena_brightness.png\", format=\"png\")\n"} +{"Prompt":"Changing contrast with PIL This algorithm is used in https:noivce.pythonanywhere.com Python web app. psfblack: True ruff : True Function to change contrast Fundamental TransformationOperation that'll be performed on every bit. Load image Change contrast to 170","Completions":"from PIL import Image\n\n\ndef change_contrast(img: Image, level: int) -> Image:\n \"\"\"\n Function to change contrast\n \"\"\"\n factor = (259 * (level + 255)) \/ (255 * (259 - level))\n\n def contrast(c: int) -> int:\n \"\"\"\n Fundamental Transformation\/Operation that'll be performed on\n every bit.\n \"\"\"\n return int(128 + factor * (c - 128))\n\n return img.point(contrast)\n\n\nif __name__ == \"__main__\":\n # Load image\n with Image.open(\"image_data\/lena.jpg\") as img:\n # Change contrast to 170\n cont_img = change_contrast(img, 170)\n cont_img.save(\"image_data\/lena_high_contrast.png\", format=\"png\")\n"} +{"Prompt":"Implemented an algorithm using opencv to convert a colored image into its negative getting number of pixels in the image converting each pixel's color to its negative read original image convert to its negative show result image","Completions":"from cv2 import destroyAllWindows, imread, imshow, waitKey\n\n\ndef convert_to_negative(img):\n # getting number of pixels in the image\n pixel_h, pixel_v = img.shape[0], img.shape[1]\n\n # converting each pixel's color to its negative\n for i in range(pixel_h):\n for j in range(pixel_v):\n img[i][j] = [255, 255, 255] - img[i][j]\n\n return img\n\n\nif __name__ == \"__main__\":\n # read original image\n img = imread(\"image_data\/lena.jpg\", 1)\n\n # convert to its negative\n neg = convert_to_negative(img)\n\n # show result image\n imshow(\"negative of original image\", img)\n waitKey(0)\n destroyAllWindows()\n"} +{"Prompt":"Implementation Burke's algorithm dithering Burke's algorithm is using for converting grayscale image to black and white version Source: Source: https:en.wikipedia.orgwikiDither Note: Best results are given with threshold 12 max greyscale value. This implementation get RGB image and converts it to greyscale in runtime. max greyscale value for FFFFFF error table size 4 columns and 1 row greater than input image because of lack of if statements Burkes.getgreyscale3, 4, 5 4.185 Burkes.getgreyscale0, 0, 0 0.0 Burkes.getgreyscale255, 255, 255 255.0 Formula from https:en.wikipedia.orgwikiHSLandHSV cf Lightness section, and Fig 13c. We use the first of four possible. Burkes error propagation is current pixel: 832 432 232 432 832 432 232 create Burke's instances with original images in greyscale","Completions":"import numpy as np\nfrom cv2 import destroyAllWindows, imread, imshow, waitKey\n\n\nclass Burkes:\n \"\"\"\n Burke's algorithm is using for converting grayscale image to black and white version\n Source: Source: https:\/\/en.wikipedia.org\/wiki\/Dither\n\n Note:\n * Best results are given with threshold= ~1\/2 * max greyscale value.\n * This implementation get RGB image and converts it to greyscale in runtime.\n \"\"\"\n\n def __init__(self, input_img, threshold: int):\n self.min_threshold = 0\n # max greyscale value for #FFFFFF\n self.max_threshold = int(self.get_greyscale(255, 255, 255))\n\n if not self.min_threshold < threshold < self.max_threshold:\n msg = f\"Factor value should be from 0 to {self.max_threshold}\"\n raise ValueError(msg)\n\n self.input_img = input_img\n self.threshold = threshold\n self.width, self.height = self.input_img.shape[1], self.input_img.shape[0]\n\n # error table size (+4 columns and +1 row) greater than input image because of\n # lack of if statements\n self.error_table = [\n [0 for _ in range(self.height + 4)] for __ in range(self.width + 1)\n ]\n self.output_img = np.ones((self.width, self.height, 3), np.uint8) * 255\n\n @classmethod\n def get_greyscale(cls, blue: int, green: int, red: int) -> float:\n \"\"\"\n >>> Burkes.get_greyscale(3, 4, 5)\n 4.185\n >>> Burkes.get_greyscale(0, 0, 0)\n 0.0\n >>> Burkes.get_greyscale(255, 255, 255)\n 255.0\n \"\"\"\n \"\"\"\n Formula from https:\/\/en.wikipedia.org\/wiki\/HSL_and_HSV\n cf Lightness section, and Fig 13c.\n We use the first of four possible.\n \"\"\"\n return 0.114 * blue + 0.587 * green + 0.299 * red\n\n def process(self) -> None:\n for y in range(self.height):\n for x in range(self.width):\n greyscale = int(self.get_greyscale(*self.input_img[y][x]))\n if self.threshold > greyscale + self.error_table[y][x]:\n self.output_img[y][x] = (0, 0, 0)\n current_error = greyscale + self.error_table[y][x]\n else:\n self.output_img[y][x] = (255, 255, 255)\n current_error = greyscale + self.error_table[y][x] - 255\n \"\"\"\n Burkes error propagation (`*` is current pixel):\n\n * 8\/32 4\/32\n 2\/32 4\/32 8\/32 4\/32 2\/32\n \"\"\"\n self.error_table[y][x + 1] += int(8 \/ 32 * current_error)\n self.error_table[y][x + 2] += int(4 \/ 32 * current_error)\n self.error_table[y + 1][x] += int(8 \/ 32 * current_error)\n self.error_table[y + 1][x + 1] += int(4 \/ 32 * current_error)\n self.error_table[y + 1][x + 2] += int(2 \/ 32 * current_error)\n self.error_table[y + 1][x - 1] += int(4 \/ 32 * current_error)\n self.error_table[y + 1][x - 2] += int(2 \/ 32 * current_error)\n\n\nif __name__ == \"__main__\":\n # create Burke's instances with original images in greyscale\n burkes_instances = [\n Burkes(imread(\"image_data\/lena.jpg\", 1), threshold)\n for threshold in (1, 126, 130, 140)\n ]\n\n for burkes in burkes_instances:\n burkes.process()\n\n for burkes in burkes_instances:\n imshow(\n f\"Original image with dithering threshold: {burkes.threshold}\",\n burkes.output_img,\n )\n\n waitKey(0)\n destroyAllWindows()\n"} +{"Prompt":"Nonmaximum suppression. If the edge strength of the current pixel is the largest compared to the other pixels in the mask with the same direction, the value will be preserved. Otherwise, the value will be suppressed. HighLow threshold detection. If an edge pixels gradient value is higher than the high threshold value, it is marked as a strong edge pixel. If an edge pixels gradient value is smaller than the high threshold value and larger than the low threshold value, it is marked as a weak edge pixel. If an edge pixel's value is smaller than the low threshold value, it will be suppressed. Edge tracking. Usually a weak edge pixel caused from true edges will be connected to a strong edge pixel while noise responses are unconnected. As long as there is one strong edge pixel that is involved in its 8connected neighborhood, that weak edge point can be identified as one that should be preserved. gaussianfilter get the gradient and degree by sobelfilter read original image in gray mode canny edge detection","Completions":"import cv2\nimport numpy as np\n\nfrom digital_image_processing.filters.convolve import img_convolve\nfrom digital_image_processing.filters.sobel_filter import sobel_filter\n\nPI = 180\n\n\ndef gen_gaussian_kernel(k_size, sigma):\n center = k_size \/\/ 2\n x, y = np.mgrid[0 - center : k_size - center, 0 - center : k_size - center]\n g = (\n 1\n \/ (2 * np.pi * sigma)\n * np.exp(-(np.square(x) + np.square(y)) \/ (2 * np.square(sigma)))\n )\n return g\n\n\ndef suppress_non_maximum(image_shape, gradient_direction, sobel_grad):\n \"\"\"\n Non-maximum suppression. If the edge strength of the current pixel is the largest\n compared to the other pixels in the mask with the same direction, the value will be\n preserved. Otherwise, the value will be suppressed.\n \"\"\"\n destination = np.zeros(image_shape)\n\n for row in range(1, image_shape[0] - 1):\n for col in range(1, image_shape[1] - 1):\n direction = gradient_direction[row, col]\n\n if (\n 0 <= direction < PI \/ 8\n or 15 * PI \/ 8 <= direction <= 2 * PI\n or 7 * PI \/ 8 <= direction <= 9 * PI \/ 8\n ):\n w = sobel_grad[row, col - 1]\n e = sobel_grad[row, col + 1]\n if sobel_grad[row, col] >= w and sobel_grad[row, col] >= e:\n destination[row, col] = sobel_grad[row, col]\n\n elif (\n PI \/ 8 <= direction < 3 * PI \/ 8\n or 9 * PI \/ 8 <= direction < 11 * PI \/ 8\n ):\n sw = sobel_grad[row + 1, col - 1]\n ne = sobel_grad[row - 1, col + 1]\n if sobel_grad[row, col] >= sw and sobel_grad[row, col] >= ne:\n destination[row, col] = sobel_grad[row, col]\n\n elif (\n 3 * PI \/ 8 <= direction < 5 * PI \/ 8\n or 11 * PI \/ 8 <= direction < 13 * PI \/ 8\n ):\n n = sobel_grad[row - 1, col]\n s = sobel_grad[row + 1, col]\n if sobel_grad[row, col] >= n and sobel_grad[row, col] >= s:\n destination[row, col] = sobel_grad[row, col]\n\n elif (\n 5 * PI \/ 8 <= direction < 7 * PI \/ 8\n or 13 * PI \/ 8 <= direction < 15 * PI \/ 8\n ):\n nw = sobel_grad[row - 1, col - 1]\n se = sobel_grad[row + 1, col + 1]\n if sobel_grad[row, col] >= nw and sobel_grad[row, col] >= se:\n destination[row, col] = sobel_grad[row, col]\n\n return destination\n\n\ndef detect_high_low_threshold(\n image_shape, destination, threshold_low, threshold_high, weak, strong\n):\n \"\"\"\n High-Low threshold detection. If an edge pixel\u2019s gradient value is higher\n than the high threshold value, it is marked as a strong edge pixel. If an\n edge pixel\u2019s gradient value is smaller than the high threshold value and\n larger than the low threshold value, it is marked as a weak edge pixel. If\n an edge pixel's value is smaller than the low threshold value, it will be\n suppressed.\n \"\"\"\n for row in range(1, image_shape[0] - 1):\n for col in range(1, image_shape[1] - 1):\n if destination[row, col] >= threshold_high:\n destination[row, col] = strong\n elif destination[row, col] <= threshold_low:\n destination[row, col] = 0\n else:\n destination[row, col] = weak\n\n\ndef track_edge(image_shape, destination, weak, strong):\n \"\"\"\n Edge tracking. Usually a weak edge pixel caused from true edges will be connected\n to a strong edge pixel while noise responses are unconnected. As long as there is\n one strong edge pixel that is involved in its 8-connected neighborhood, that weak\n edge point can be identified as one that should be preserved.\n \"\"\"\n for row in range(1, image_shape[0]):\n for col in range(1, image_shape[1]):\n if destination[row, col] == weak:\n if 255 in (\n destination[row, col + 1],\n destination[row, col - 1],\n destination[row - 1, col],\n destination[row + 1, col],\n destination[row - 1, col - 1],\n destination[row + 1, col - 1],\n destination[row - 1, col + 1],\n destination[row + 1, col + 1],\n ):\n destination[row, col] = strong\n else:\n destination[row, col] = 0\n\n\ndef canny(image, threshold_low=15, threshold_high=30, weak=128, strong=255):\n # gaussian_filter\n gaussian_out = img_convolve(image, gen_gaussian_kernel(9, sigma=1.4))\n # get the gradient and degree by sobel_filter\n sobel_grad, sobel_theta = sobel_filter(gaussian_out)\n gradient_direction = PI + np.rad2deg(sobel_theta)\n\n destination = suppress_non_maximum(image.shape, gradient_direction, sobel_grad)\n\n detect_high_low_threshold(\n image.shape, destination, threshold_low, threshold_high, weak, strong\n )\n\n track_edge(image.shape, destination, weak, strong)\n\n return destination\n\n\nif __name__ == \"__main__\":\n # read original image in gray mode\n lena = cv2.imread(r\"..\/image_data\/lena.jpg\", 0)\n # canny edge detection\n canny_destination = canny(lena)\n cv2.imshow(\"canny\", canny_destination)\n cv2.waitKey(0)\n"} +{"Prompt":"Implementation of Bilateral filter Inputs: img: A 2d image with values in between 0 and 1 varS: variance in space dimension. varI: variance in Intensity. N: Kernel sizeMust be an odd number Output: img:A 2d zero padded image with values in between 0 and 1 For applying gaussian function for each element in matrix. Creates a gaussian kernel of given dimension.","Completions":"import math\nimport sys\n\nimport cv2\nimport numpy as np\n\n\ndef vec_gaussian(img: np.ndarray, variance: float) -> np.ndarray:\n # For applying gaussian function for each element in matrix.\n sigma = math.sqrt(variance)\n cons = 1 \/ (sigma * math.sqrt(2 * math.pi))\n return cons * np.exp(-((img \/ sigma) ** 2) * 0.5)\n\n\ndef get_slice(img: np.ndarray, x: int, y: int, kernel_size: int) -> np.ndarray:\n half = kernel_size \/\/ 2\n return img[x - half : x + half + 1, y - half : y + half + 1]\n\n\ndef get_gauss_kernel(kernel_size: int, spatial_variance: float) -> np.ndarray:\n # Creates a gaussian kernel of given dimension.\n arr = np.zeros((kernel_size, kernel_size))\n for i in range(kernel_size):\n for j in range(kernel_size):\n arr[i, j] = math.sqrt(\n abs(i - kernel_size \/\/ 2) ** 2 + abs(j - kernel_size \/\/ 2) ** 2\n )\n return vec_gaussian(arr, spatial_variance)\n\n\ndef bilateral_filter(\n img: np.ndarray,\n spatial_variance: float,\n intensity_variance: float,\n kernel_size: int,\n) -> np.ndarray:\n img2 = np.zeros(img.shape)\n gauss_ker = get_gauss_kernel(kernel_size, spatial_variance)\n size_x, size_y = img.shape\n for i in range(kernel_size \/\/ 2, size_x - kernel_size \/\/ 2):\n for j in range(kernel_size \/\/ 2, size_y - kernel_size \/\/ 2):\n img_s = get_slice(img, i, j, kernel_size)\n img_i = img_s - img_s[kernel_size \/\/ 2, kernel_size \/\/ 2]\n img_ig = vec_gaussian(img_i, intensity_variance)\n weights = np.multiply(gauss_ker, img_ig)\n vals = np.multiply(img_s, weights)\n val = np.sum(vals) \/ np.sum(weights)\n img2[i, j] = val\n return img2\n\n\ndef parse_args(args: list) -> tuple:\n filename = args[1] if args[1:] else \"..\/image_data\/lena.jpg\"\n spatial_variance = float(args[2]) if args[2:] else 1.0\n intensity_variance = float(args[3]) if args[3:] else 1.0\n if args[4:]:\n kernel_size = int(args[4])\n kernel_size = kernel_size + abs(kernel_size % 2 - 1)\n else:\n kernel_size = 5\n return filename, spatial_variance, intensity_variance, kernel_size\n\n\nif __name__ == \"__main__\":\n filename, spatial_variance, intensity_variance, kernel_size = parse_args(sys.argv)\n img = cv2.imread(filename, 0)\n cv2.imshow(\"input image\", img)\n\n out = img \/ 255\n out = out.astype(\"float32\")\n out = bilateral_filter(out, spatial_variance, intensity_variance, kernel_size)\n out = out * 255\n out = np.uint8(out)\n cv2.imshow(\"output image\", out)\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n"} +{"Prompt":"Author : lightXu File : convolve.py Time : 201978 0008 16:13 Pads image with the edge values of array. im2col, turn the ksizeksize pixels into a row and np.vstack all rows turn the kernel into shapekk, 1 reshape and get the dst image read original image turn image in gray scale value Laplace operator","Completions":"# @Author : lightXu\n# @File : convolve.py\n# @Time : 2019\/7\/8 0008 \u4e0b\u5348 16:13\nfrom cv2 import COLOR_BGR2GRAY, cvtColor, imread, imshow, waitKey\nfrom numpy import array, dot, pad, ravel, uint8, zeros\n\n\ndef im2col(image, block_size):\n rows, cols = image.shape\n dst_height = cols - block_size[1] + 1\n dst_width = rows - block_size[0] + 1\n image_array = zeros((dst_height * dst_width, block_size[1] * block_size[0]))\n row = 0\n for i in range(dst_height):\n for j in range(dst_width):\n window = ravel(image[i : i + block_size[0], j : j + block_size[1]])\n image_array[row, :] = window\n row += 1\n\n return image_array\n\n\ndef img_convolve(image, filter_kernel):\n height, width = image.shape[0], image.shape[1]\n k_size = filter_kernel.shape[0]\n pad_size = k_size \/\/ 2\n # Pads image with the edge values of array.\n image_tmp = pad(image, pad_size, mode=\"edge\")\n\n # im2col, turn the k_size*k_size pixels into a row and np.vstack all rows\n image_array = im2col(image_tmp, (k_size, k_size))\n\n # turn the kernel into shape(k*k, 1)\n kernel_array = ravel(filter_kernel)\n # reshape and get the dst image\n dst = dot(image_array, kernel_array).reshape(height, width)\n return dst\n\n\nif __name__ == \"__main__\":\n # read original image\n img = imread(r\"..\/image_data\/lena.jpg\")\n # turn image in gray scale value\n gray = cvtColor(img, COLOR_BGR2GRAY)\n # Laplace operator\n Laplace_kernel = array([[0, 1, 0], [1, -4, 1], [0, 1, 0]])\n out = img_convolve(gray, Laplace_kernel).astype(uint8)\n imshow(\"Laplacian\", out)\n waitKey(0)\n"} +{"Prompt":"Implementation of the Gaborfilter https:en.wikipedia.orgwikiGaborfilter :param ksize: The kernelsize of the convolutional filter ksize x ksize :param sigma: standard deviation of the gaussian bell curve :param theta: The orientation of the normal to the parallel stripes of Gabor function. :param lambd: Wavelength of the sinusoidal component. :param gamma: The spatial aspect ratio and specifies the ellipticity of the support of Gabor function. :param psi: The phase offset of the sinusoidal function. gaborfilterkernel3, 8, 0, 10, 0, 0.tolist 0.8027212023735046, 1.0, 0.8027212023735046, 0.8027212023735046, 1.0, 0.8027212023735046, 0.8027212023735046, 1.0, 0.8027212023735046 prepare kernel the kernel size have to be odd each value distance from center degree to radiant get kernel x get kernel y fill kernel read original image turn image in gray scale value Apply multiple Kernel to detect edges ksize 10 sigma 8 lambd 10 gamma 0 psi 0","Completions":"# Implementation of the Gaborfilter\n# https:\/\/en.wikipedia.org\/wiki\/Gabor_filter\nimport numpy as np\nfrom cv2 import COLOR_BGR2GRAY, CV_8UC3, cvtColor, filter2D, imread, imshow, waitKey\n\n\ndef gabor_filter_kernel(\n ksize: int, sigma: int, theta: int, lambd: int, gamma: int, psi: int\n) -> np.ndarray:\n \"\"\"\n :param ksize: The kernelsize of the convolutional filter (ksize x ksize)\n :param sigma: standard deviation of the gaussian bell curve\n :param theta: The orientation of the normal to the parallel stripes\n of Gabor function.\n :param lambd: Wavelength of the sinusoidal component.\n :param gamma: The spatial aspect ratio and specifies the ellipticity\n of the support of Gabor function.\n :param psi: The phase offset of the sinusoidal function.\n\n >>> gabor_filter_kernel(3, 8, 0, 10, 0, 0).tolist()\n [[0.8027212023735046, 1.0, 0.8027212023735046], [0.8027212023735046, 1.0, \\\n0.8027212023735046], [0.8027212023735046, 1.0, 0.8027212023735046]]\n\n \"\"\"\n\n # prepare kernel\n # the kernel size have to be odd\n if (ksize % 2) == 0:\n ksize = ksize + 1\n gabor = np.zeros((ksize, ksize), dtype=np.float32)\n\n # each value\n for y in range(ksize):\n for x in range(ksize):\n # distance from center\n px = x - ksize \/\/ 2\n py = y - ksize \/\/ 2\n\n # degree to radiant\n _theta = theta \/ 180 * np.pi\n cos_theta = np.cos(_theta)\n sin_theta = np.sin(_theta)\n\n # get kernel x\n _x = cos_theta * px + sin_theta * py\n\n # get kernel y\n _y = -sin_theta * px + cos_theta * py\n\n # fill kernel\n gabor[y, x] = np.exp(\n -(_x**2 + gamma**2 * _y**2) \/ (2 * sigma**2)\n ) * np.cos(2 * np.pi * _x \/ lambd + psi)\n\n return gabor\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n # read original image\n img = imread(\"..\/image_data\/lena.jpg\")\n # turn image in gray scale value\n gray = cvtColor(img, COLOR_BGR2GRAY)\n\n # Apply multiple Kernel to detect edges\n out = np.zeros(gray.shape[:2])\n for theta in [0, 30, 60, 90, 120, 150]:\n \"\"\"\n ksize = 10\n sigma = 8\n lambd = 10\n gamma = 0\n psi = 0\n \"\"\"\n kernel_10 = gabor_filter_kernel(10, 8, theta, 10, 0, 0)\n out += filter2D(gray, CV_8UC3, kernel_10)\n out = out \/ out.max() * 255\n out = out.astype(np.uint8)\n\n imshow(\"Original\", gray)\n imshow(\"Gabor filter with 20x20 mask and 6 directions\", out)\n\n waitKey(0)\n"} +{"Prompt":"Implementation of gaussian filter algorithm dst image height and width im2col, turn the ksizeksize pixels into a row and np.vstack all rows turn the kernel into shapekk, 1 reshape and get the dst image read original image turn image in gray scale value get values with two different mask size show result images","Completions":"from itertools import product\n\nfrom cv2 import COLOR_BGR2GRAY, cvtColor, imread, imshow, waitKey\nfrom numpy import dot, exp, mgrid, pi, ravel, square, uint8, zeros\n\n\ndef gen_gaussian_kernel(k_size, sigma):\n center = k_size \/\/ 2\n x, y = mgrid[0 - center : k_size - center, 0 - center : k_size - center]\n g = 1 \/ (2 * pi * sigma) * exp(-(square(x) + square(y)) \/ (2 * square(sigma)))\n return g\n\n\ndef gaussian_filter(image, k_size, sigma):\n height, width = image.shape[0], image.shape[1]\n # dst image height and width\n dst_height = height - k_size + 1\n dst_width = width - k_size + 1\n\n # im2col, turn the k_size*k_size pixels into a row and np.vstack all rows\n image_array = zeros((dst_height * dst_width, k_size * k_size))\n row = 0\n for i, j in product(range(dst_height), range(dst_width)):\n window = ravel(image[i : i + k_size, j : j + k_size])\n image_array[row, :] = window\n row += 1\n\n # turn the kernel into shape(k*k, 1)\n gaussian_kernel = gen_gaussian_kernel(k_size, sigma)\n filter_array = ravel(gaussian_kernel)\n\n # reshape and get the dst image\n dst = dot(image_array, filter_array).reshape(dst_height, dst_width).astype(uint8)\n\n return dst\n\n\nif __name__ == \"__main__\":\n # read original image\n img = imread(r\"..\/image_data\/lena.jpg\")\n # turn image in gray scale value\n gray = cvtColor(img, COLOR_BGR2GRAY)\n\n # get values with two different mask size\n gaussian3x3 = gaussian_filter(gray, 3, sigma=1)\n gaussian5x5 = gaussian_filter(gray, 5, sigma=0.8)\n\n # show result images\n imshow(\"gaussian filter with 3x3 mask\", gaussian3x3)\n imshow(\"gaussian filter with 5x5 mask\", gaussian5x5)\n waitKey()\n"} +{"Prompt":"Author : ojaswani File : laplacianfilter.py Date : 10042023 :param src: the source image, which should be a grayscale or color image. :param ksize: the size of the kernel used to compute the Laplacian filter, which can be 1, 3, 5, or 7. mylaplaciansrcnp.array, ksize0 Traceback most recent call last: ... ValueError: ksize must be in 1, 3, 5, 7 Apply the Laplacian kernel using convolution read original image turn image in gray scale value Applying gaussian filter Apply multiple Kernel to detect edges","Completions":"# @Author : ojas-wani\n# @File : laplacian_filter.py\n# @Date : 10\/04\/2023\n\nimport numpy as np\nfrom cv2 import (\n BORDER_DEFAULT,\n COLOR_BGR2GRAY,\n CV_64F,\n cvtColor,\n filter2D,\n imread,\n imshow,\n waitKey,\n)\n\nfrom digital_image_processing.filters.gaussian_filter import gaussian_filter\n\n\ndef my_laplacian(src: np.ndarray, ksize: int) -> np.ndarray:\n \"\"\"\n :param src: the source image, which should be a grayscale or color image.\n :param ksize: the size of the kernel used to compute the Laplacian filter,\n which can be 1, 3, 5, or 7.\n\n >>> my_laplacian(src=np.array([]), ksize=0)\n Traceback (most recent call last):\n ...\n ValueError: ksize must be in (1, 3, 5, 7)\n \"\"\"\n kernels = {\n 1: np.array([[0, -1, 0], [-1, 4, -1], [0, -1, 0]]),\n 3: np.array([[0, 1, 0], [1, -4, 1], [0, 1, 0]]),\n 5: np.array(\n [\n [0, 0, -1, 0, 0],\n [0, -1, -2, -1, 0],\n [-1, -2, 16, -2, -1],\n [0, -1, -2, -1, 0],\n [0, 0, -1, 0, 0],\n ]\n ),\n 7: np.array(\n [\n [0, 0, 0, -1, 0, 0, 0],\n [0, 0, -2, -3, -2, 0, 0],\n [0, -2, -7, -10, -7, -2, 0],\n [-1, -3, -10, 68, -10, -3, -1],\n [0, -2, -7, -10, -7, -2, 0],\n [0, 0, -2, -3, -2, 0, 0],\n [0, 0, 0, -1, 0, 0, 0],\n ]\n ),\n }\n if ksize not in kernels:\n msg = f\"ksize must be in {tuple(kernels)}\"\n raise ValueError(msg)\n\n # Apply the Laplacian kernel using convolution\n return filter2D(\n src, CV_64F, kernels[ksize], 0, borderType=BORDER_DEFAULT, anchor=(0, 0)\n )\n\n\nif __name__ == \"__main__\":\n # read original image\n img = imread(r\"..\/image_data\/lena.jpg\")\n\n # turn image in gray scale value\n gray = cvtColor(img, COLOR_BGR2GRAY)\n\n # Applying gaussian filter\n blur_image = gaussian_filter(gray, 3, sigma=1)\n\n # Apply multiple Kernel to detect edges\n laplacian_image = my_laplacian(ksize=3, src=blur_image)\n\n imshow(\"Original image\", img)\n imshow(\"Detected edges using laplacian filter\", laplacian_image)\n\n waitKey(0)\n"} +{"Prompt":"Comparing local neighborhood pixel value with threshold value of centre pixel. Exception is required when neighborhood value of a center pixel value is null. i.e. values present at boundaries. :param image: The image we're working with :param xcoordinate: xcoordinate of the pixel :param ycoordinate: The y coordinate of the pixel :param center: center pixel value :return: The value of the pixel is being returned. It takes an image, an x and y coordinate, and returns the decimal value of the local binary patternof the pixel at that coordinate :param image: the image to be processed :param xcoordinate: x coordinate of the pixel :param ycoordinate: the y coordinate of the pixel :return: The decimal value of the binary value of the pixels around the center pixel. skip getneighborspixel if center is null Starting from the top right, assigning value to pixels clockwise Converting the binary value to decimal. Reading the image and converting it to grayscale. Create a numpy array as the same height and width of read image Iterating through the image and calculating the local binary pattern value for each pixel.","Completions":"import cv2\nimport numpy as np\n\n\ndef get_neighbors_pixel(\n image: np.ndarray, x_coordinate: int, y_coordinate: int, center: int\n) -> int:\n \"\"\"\n Comparing local neighborhood pixel value with threshold value of centre pixel.\n Exception is required when neighborhood value of a center pixel value is null.\n i.e. values present at boundaries.\n\n :param image: The image we're working with\n :param x_coordinate: x-coordinate of the pixel\n :param y_coordinate: The y coordinate of the pixel\n :param center: center pixel value\n :return: The value of the pixel is being returned.\n \"\"\"\n\n try:\n return int(image[x_coordinate][y_coordinate] >= center)\n except (IndexError, TypeError):\n return 0\n\n\ndef local_binary_value(image: np.ndarray, x_coordinate: int, y_coordinate: int) -> int:\n \"\"\"\n It takes an image, an x and y coordinate, and returns the\n decimal value of the local binary patternof the pixel\n at that coordinate\n\n :param image: the image to be processed\n :param x_coordinate: x coordinate of the pixel\n :param y_coordinate: the y coordinate of the pixel\n :return: The decimal value of the binary value of the pixels\n around the center pixel.\n \"\"\"\n center = image[x_coordinate][y_coordinate]\n powers = [1, 2, 4, 8, 16, 32, 64, 128]\n\n # skip get_neighbors_pixel if center is null\n if center is None:\n return 0\n\n # Starting from the top right, assigning value to pixels clockwise\n binary_values = [\n get_neighbors_pixel(image, x_coordinate - 1, y_coordinate + 1, center),\n get_neighbors_pixel(image, x_coordinate, y_coordinate + 1, center),\n get_neighbors_pixel(image, x_coordinate - 1, y_coordinate, center),\n get_neighbors_pixel(image, x_coordinate + 1, y_coordinate + 1, center),\n get_neighbors_pixel(image, x_coordinate + 1, y_coordinate, center),\n get_neighbors_pixel(image, x_coordinate + 1, y_coordinate - 1, center),\n get_neighbors_pixel(image, x_coordinate, y_coordinate - 1, center),\n get_neighbors_pixel(image, x_coordinate - 1, y_coordinate - 1, center),\n ]\n\n # Converting the binary value to decimal.\n return sum(\n binary_value * power for binary_value, power in zip(binary_values, powers)\n )\n\n\nif __name__ == \"__main__\":\n # Reading the image and converting it to grayscale.\n image = cv2.imread(\n \"digital_image_processing\/image_data\/lena.jpg\", cv2.IMREAD_GRAYSCALE\n )\n\n # Create a numpy array as the same height and width of read image\n lbp_image = np.zeros((image.shape[0], image.shape[1]))\n\n # Iterating through the image and calculating the\n # local binary pattern value for each pixel.\n for i in range(image.shape[0]):\n for j in range(image.shape[1]):\n lbp_image[i][j] = local_binary_value(image, i, j)\n\n cv2.imshow(\"local binary pattern\", lbp_image)\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n"} +{"Prompt":"Implementation of median filter algorithm :param grayimg: gray image :param mask: mask size :return: image with median filter set image borders copy image size get mask according with mask calculate mask median read original image turn image in gray scale value get values with two different mask size show result images","Completions":"from cv2 import COLOR_BGR2GRAY, cvtColor, imread, imshow, waitKey\nfrom numpy import divide, int8, multiply, ravel, sort, zeros_like\n\n\ndef median_filter(gray_img, mask=3):\n \"\"\"\n :param gray_img: gray image\n :param mask: mask size\n :return: image with median filter\n \"\"\"\n # set image borders\n bd = int(mask \/ 2)\n # copy image size\n median_img = zeros_like(gray_img)\n for i in range(bd, gray_img.shape[0] - bd):\n for j in range(bd, gray_img.shape[1] - bd):\n # get mask according with mask\n kernel = ravel(gray_img[i - bd : i + bd + 1, j - bd : j + bd + 1])\n # calculate mask median\n median = sort(kernel)[int8(divide((multiply(mask, mask)), 2) + 1)]\n median_img[i, j] = median\n return median_img\n\n\nif __name__ == \"__main__\":\n # read original image\n img = imread(\"..\/image_data\/lena.jpg\")\n # turn image in gray scale value\n gray = cvtColor(img, COLOR_BGR2GRAY)\n\n # get values with two different mask size\n median3x3 = median_filter(gray, 3)\n median5x5 = median_filter(gray, 5)\n\n # show result images\n imshow(\"median filter with 3x3 mask\", median3x3)\n imshow(\"median filter with 5x5 mask\", median5x5)\n waitKey(0)\n"} +{"Prompt":"Author : lightXu File : sobelfilter.py Time : 201978 0008 16:26 modify the pix within 0, 255 read original image turn image in gray scale value show result images","Completions":"# @Author : lightXu\n# @File : sobel_filter.py\n# @Time : 2019\/7\/8 0008 \u4e0b\u5348 16:26\nimport numpy as np\nfrom cv2 import COLOR_BGR2GRAY, cvtColor, imread, imshow, waitKey\n\nfrom digital_image_processing.filters.convolve import img_convolve\n\n\ndef sobel_filter(image):\n kernel_x = np.array([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]])\n kernel_y = np.array([[1, 2, 1], [0, 0, 0], [-1, -2, -1]])\n\n dst_x = np.abs(img_convolve(image, kernel_x))\n dst_y = np.abs(img_convolve(image, kernel_y))\n # modify the pix within [0, 255]\n dst_x = dst_x * 255 \/ np.max(dst_x)\n dst_y = dst_y * 255 \/ np.max(dst_y)\n\n dst_xy = np.sqrt((np.square(dst_x)) + (np.square(dst_y)))\n dst_xy = dst_xy * 255 \/ np.max(dst_xy)\n dst = dst_xy.astype(np.uint8)\n\n theta = np.arctan2(dst_y, dst_x)\n return dst, theta\n\n\nif __name__ == \"__main__\":\n # read original image\n img = imread(\"..\/image_data\/lena.jpg\")\n # turn image in gray scale value\n gray = cvtColor(img, COLOR_BGR2GRAY)\n\n sobel_grad, sobel_theta = sobel_filter(gray)\n\n # show result images\n imshow(\"sobel filter\", sobel_grad)\n imshow(\"sobel theta\", sobel_theta)\n waitKey(0)\n"} +{"Prompt":"Created on Fri Sep 28 15:22:29 2018 author: Binish125","Completions":"import copy\nimport os\n\nimport cv2\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\n\nclass ConstantStretch:\n def __init__(self):\n self.img = \"\"\n self.original_image = \"\"\n self.last_list = []\n self.rem = 0\n self.L = 256\n self.sk = 0\n self.k = 0\n self.number_of_rows = 0\n self.number_of_cols = 0\n\n def stretch(self, input_image):\n self.img = cv2.imread(input_image, 0)\n self.original_image = copy.deepcopy(self.img)\n x, _, _ = plt.hist(self.img.ravel(), 256, [0, 256], label=\"x\")\n self.k = np.sum(x)\n for i in range(len(x)):\n prk = x[i] \/ self.k\n self.sk += prk\n last = (self.L - 1) * self.sk\n if self.rem != 0:\n self.rem = int(last % last)\n last = int(last + 1 if self.rem >= 0.5 else last)\n self.last_list.append(last)\n self.number_of_rows = int(np.ma.count(self.img) \/ self.img[1].size)\n self.number_of_cols = self.img[1].size\n for i in range(self.number_of_cols):\n for j in range(self.number_of_rows):\n num = self.img[j][i]\n if num != self.last_list[num]:\n self.img[j][i] = self.last_list[num]\n cv2.imwrite(\"output_data\/output.jpg\", self.img)\n\n def plot_histogram(self):\n plt.hist(self.img.ravel(), 256, [0, 256])\n\n def show_image(self):\n cv2.imshow(\"Output-Image\", self.img)\n cv2.imshow(\"Input-Image\", self.original_image)\n cv2.waitKey(5000)\n cv2.destroyAllWindows()\n\n\nif __name__ == \"__main__\":\n file_path = os.path.join(os.path.basename(__file__), \"image_data\/input.jpg\")\n stretcher = ConstantStretch()\n stretcher.stretch(file_path)\n stretcher.plot_histogram()\n stretcher.show_image()\n"} +{"Prompt":"Author: Joo Gustavo A. Amorim Author email: joaogustavoamorimgmail.com Coding date: jan 2019 pythonblack: True Imports Class implemented to calculus the index Class Summary This algorithm consists in calculating vegetation indices, these indices can be used for precision agriculture for example or remote sensing. There are functions to define the data and to calculate the implemented indices. Vegetation index https:en.wikipedia.orgwikiVegetationIndex A Vegetation Index VI is a spectral transformation of two or more bands designed to enhance the contribution of vegetation properties and allow reliable spatial and temporal intercomparisons of terrestrial photosynthetic activity and canopy structural variations Information about channels Wavelength range for each nir nearinfrared https:www.malvernpanalytical.combrproductstechnologynearinfraredspectroscopy Wavelength Range 700 nm to 2500 nm Red Edge https:en.wikipedia.orgwikiRededge Wavelength Range 680 nm to 730 nm red https:en.wikipedia.orgwikiColor Wavelength Range 635 nm to 700 nm blue https:en.wikipedia.orgwikiColor Wavelength Range 450 nm to 490 nm green https:en.wikipedia.orgwikiColor Wavelength Range 520 nm to 560 nm Implemented index list abbreviationOfIndexName list of channels used ARVI2 red, nir CCCI red, redEdge, nir CVI red, green, nir GLI red, green, blue NDVI red, nir BNDVI blue, nir redEdgeNDVI red, redEdge GNDVI green, nir GBNDVI green, blue, nir GRNDVI red, green, nir RBNDVI red, blue, nir PNDVI red, green, blue, nir ATSAVI red, nir BWDRVI blue, nir CIgreen green, nir CIrededge redEdge, nir CI red, blue CTVI red, nir GDVI green, nir EVI red, blue, nir GEMI red, nir GOSAVI green, nir GSAVI green, nir Hue red, green, blue IVI red, nir IPVI red, nir I red, green, blue RVI red, nir MRVI red, nir MSAVI red, nir NormG red, green, nir NormNIR red, green, nir NormR red, green, nir NGRDI red, green RI red, green S red, green, blue IF red, green, blue DVI red, nir TVI red, nir NDRE redEdge, nir list of all index implemented allIndex ARVI2, CCCI, CVI, GLI, NDVI, BNDVI, redEdgeNDVI, GNDVI, GBNDVI, GRNDVI, RBNDVI, PNDVI, ATSAVI, BWDRVI, CIgreen, CIrededge, CI, CTVI, GDVI, EVI, GEMI, GOSAVI, GSAVI, Hue, IVI, IPVI, I, RVI, MRVI, MSAVI, NormG, NormNIR, NormR, NGRDI, RI, S, IF, DVI, TVI, NDRE list of index with not blue channel notBlueIndex ARVI2, CCCI, CVI, NDVI, redEdgeNDVI, GNDVI, GRNDVI, ATSAVI, CIgreen, CIrededge, CTVI, GDVI, GEMI, GOSAVI, GSAVI, IVI, IPVI, RVI, MRVI, MSAVI, NormG, NormNIR, NormR, NGRDI, RI, DVI, TVI, NDRE list of index just with RGB channels RGBIndex GLI, CI, Hue, I, NGRDI, RI, S, IF performs the calculation of the index with the values instantiated in the class :str index: abbreviation of index name to perform Atmospherically Resistant Vegetation Index 2 https:www.indexdatabase.dedbisingle.php?id396 :return: index 0.181.17self.nirself.redself.nirself.red Canopy Chlorophyll Content Index https:www.indexdatabase.dedbisingle.php?id224 :return: index Chlorophyll vegetation index https:www.indexdatabase.dedbisingle.php?id391 :return: index self.green leaf index https:www.indexdatabase.dedbisingle.php?id375 :return: index Normalized Difference self.nirself.red Normalized Difference Vegetation Index, Calibrated NDVI CDVI https:www.indexdatabase.dedbisingle.php?id58 :return: index Normalized Difference self.nirself.blue self.bluenormalized difference vegetation index https:www.indexdatabase.dedbisingle.php?id135 :return: index Normalized Difference self.rededgeself.red https:www.indexdatabase.dedbisingle.php?id235 :return: index Normalized Difference self.nirself.green self.green NDVI https:www.indexdatabase.dedbisingle.php?id401 :return: index self.greenself.blue NDVI https:www.indexdatabase.dedbisingle.php?id186 :return: index self.greenself.red NDVI https:www.indexdatabase.dedbisingle.php?id185 :return: index self.redself.blue NDVI https:www.indexdatabase.dedbisingle.php?id187 :return: index Pan NDVI https:www.indexdatabase.dedbisingle.php?id188 :return: index Adjusted transformed soiladjusted VI https:www.indexdatabase.dedbisingle.php?id209 :return: index self.bluewide dynamic range vegetation index https:www.indexdatabase.dedbisingle.php?id136 :return: index Chlorophyll Index self.green https:www.indexdatabase.dedbisingle.php?id128 :return: index Chlorophyll Index self.redEdge https:www.indexdatabase.dedbisingle.php?id131 :return: index Coloration Index https:www.indexdatabase.dedbisingle.php?id11 :return: index Corrected Transformed Vegetation Index https:www.indexdatabase.dedbisingle.php?id244 :return: index Difference self.nirself.green self.green Difference Vegetation Index https:www.indexdatabase.dedbisingle.php?id27 :return: index Enhanced Vegetation Index https:www.indexdatabase.dedbisingle.php?id16 :return: index Global Environment Monitoring Index https:www.indexdatabase.dedbisingle.php?id25 :return: index self.green Optimized Soil Adjusted Vegetation Index https:www.indexdatabase.dedbisingle.php?id29 mit Y 0,16 :return: index self.green Soil Adjusted Vegetation Index https:www.indexdatabase.dedbisingle.php?id31 mit N 0,5 :return: index Hue https:www.indexdatabase.dedbisingle.php?id34 :return: index Ideal vegetation index https:www.indexdatabase.dedbisingle.php?id276 bintercept of vegetation line asoil line slope :return: index Infraself.red percentage vegetation index https:www.indexdatabase.dedbisingle.php?id35 :return: index Intensity https:www.indexdatabase.dedbisingle.php?id36 :return: index RatioVegetationIndex http:www.seosproject.eumodulesremotesensingremotesensingc03s01p01.html :return: index Modified Normalized Difference Vegetation Index RVI https:www.indexdatabase.dedbisingle.php?id275 :return: index Modified Soil Adjusted Vegetation Index https:www.indexdatabase.dedbisingle.php?id44 :return: index Norm G https:www.indexdatabase.dedbisingle.php?id50 :return: index Norm self.nir https:www.indexdatabase.dedbisingle.php?id51 :return: index Norm R https:www.indexdatabase.dedbisingle.php?id52 :return: index Normalized Difference self.greenself.red Normalized self.green self.red difference index, Visible Atmospherically Resistant Indices self.green VIself.green https:www.indexdatabase.dedbisingle.php?id390 :return: index Normalized Difference self.redself.green self.redness Index https:www.indexdatabase.dedbisingle.php?id74 :return: index Saturation https:www.indexdatabase.dedbisingle.php?id77 :return: index Shape Index https:www.indexdatabase.dedbisingle.php?id79 :return: index Simple Ratio self.nirself.red Difference Vegetation Index, Vegetation Index Number VIN https:www.indexdatabase.dedbisingle.php?id12 :return: index Transformed Vegetation Index https:www.indexdatabase.dedbisingle.php?id98 :return: index genering a random matrices to test this class red np.ones1000,1000, 1,dtypefloat64 46787 green np.ones1000,1000, 1,dtypefloat64 23487 blue np.ones1000,1000, 1,dtypefloat64 14578 redEdge np.ones1000,1000, 1,dtypefloat64 51045 nir np.ones1000,1000, 1,dtypefloat64 52200 Examples of how to use the class instantiating the class cl IndexCalculation instantiating the class with the values cl indexCalculationredred, greengreen, blueblue, redEdgeredEdge, nirnir how set the values after instantiate the class cl, for update the data or when don't instantiating the class with the values cl.setMatricesredred, greengreen, blueblue, redEdgeredEdge, nirnir calculating the indices for the instantiated values in the class Note: the CCCI index can be changed to any index implemented in the class. indexValueform1 cl.calculationCCCI, redred, greengreen, blueblue, redEdgeredEdge, nirnir.astypenp.float64 indexValueform2 cl.CCCI calculating the index with the values directly you can set just the values preferred note: the calculation function performs the function setMatrices indexValueform3 cl.calculationCCCI, redred, greengreen, blueblue, redEdgeredEdge, nirnir.astypenp.float64 printForm 1: np.array2stringindexValueform1, precision20, separator', ', floatmode'maxprecequal' printForm 2: np.array2stringindexValueform2, precision20, separator', ', floatmode'maxprecequal' printForm 3: np.array2stringindexValueform3, precision20, separator', ', floatmode'maxprecequal' A list of examples results for different type of data at NDVI float16 0.31567383 NDVI red 50, nir 100 float32 0.31578946 NDVI red 50, nir 100 float64 0.3157894736842105 NDVI red 50, nir 100 longdouble 0.3157894736842105 NDVI red 50, nir 100","Completions":"# Author: Jo\u00e3o Gustavo A. Amorim\n# Author email: joaogustavoamorim@gmail.com\n# Coding date: jan 2019\n# python\/black: True\n\n# Imports\nimport numpy as np\n\n\n# Class implemented to calculus the index\nclass IndexCalculation:\n \"\"\"\n # Class Summary\n This algorithm consists in calculating vegetation indices, these\n indices can be used for precision agriculture for example (or remote\n sensing). There are functions to define the data and to calculate the\n implemented indices.\n\n # Vegetation index\n https:\/\/en.wikipedia.org\/wiki\/Vegetation_Index\n A Vegetation Index (VI) is a spectral transformation of two or more bands\n designed to enhance the contribution of vegetation properties and allow\n reliable spatial and temporal inter-comparisons of terrestrial\n photosynthetic activity and canopy structural variations\n\n # Information about channels (Wavelength range for each)\n * nir - near-infrared\n https:\/\/www.malvernpanalytical.com\/br\/products\/technology\/near-infrared-spectroscopy\n Wavelength Range 700 nm to 2500 nm\n * Red Edge\n https:\/\/en.wikipedia.org\/wiki\/Red_edge\n Wavelength Range 680 nm to 730 nm\n * red\n https:\/\/en.wikipedia.org\/wiki\/Color\n Wavelength Range 635 nm to 700 nm\n * blue\n https:\/\/en.wikipedia.org\/wiki\/Color\n Wavelength Range 450 nm to 490 nm\n * green\n https:\/\/en.wikipedia.org\/wiki\/Color\n Wavelength Range 520 nm to 560 nm\n\n\n # Implemented index list\n #\"abbreviationOfIndexName\" -- list of channels used\n\n #\"ARVI2\" -- red, nir\n #\"CCCI\" -- red, redEdge, nir\n #\"CVI\" -- red, green, nir\n #\"GLI\" -- red, green, blue\n #\"NDVI\" -- red, nir\n #\"BNDVI\" -- blue, nir\n #\"redEdgeNDVI\" -- red, redEdge\n #\"GNDVI\" -- green, nir\n #\"GBNDVI\" -- green, blue, nir\n #\"GRNDVI\" -- red, green, nir\n #\"RBNDVI\" -- red, blue, nir\n #\"PNDVI\" -- red, green, blue, nir\n #\"ATSAVI\" -- red, nir\n #\"BWDRVI\" -- blue, nir\n #\"CIgreen\" -- green, nir\n #\"CIrededge\" -- redEdge, nir\n #\"CI\" -- red, blue\n #\"CTVI\" -- red, nir\n #\"GDVI\" -- green, nir\n #\"EVI\" -- red, blue, nir\n #\"GEMI\" -- red, nir\n #\"GOSAVI\" -- green, nir\n #\"GSAVI\" -- green, nir\n #\"Hue\" -- red, green, blue\n #\"IVI\" -- red, nir\n #\"IPVI\" -- red, nir\n #\"I\" -- red, green, blue\n #\"RVI\" -- red, nir\n #\"MRVI\" -- red, nir\n #\"MSAVI\" -- red, nir\n #\"NormG\" -- red, green, nir\n #\"NormNIR\" -- red, green, nir\n #\"NormR\" -- red, green, nir\n #\"NGRDI\" -- red, green\n #\"RI\" -- red, green\n #\"S\" -- red, green, blue\n #\"IF\" -- red, green, blue\n #\"DVI\" -- red, nir\n #\"TVI\" -- red, nir\n #\"NDRE\" -- redEdge, nir\n\n #list of all index implemented\n #allIndex = [\"ARVI2\", \"CCCI\", \"CVI\", \"GLI\", \"NDVI\", \"BNDVI\", \"redEdgeNDVI\",\n \"GNDVI\", \"GBNDVI\", \"GRNDVI\", \"RBNDVI\", \"PNDVI\", \"ATSAVI\",\n \"BWDRVI\", \"CIgreen\", \"CIrededge\", \"CI\", \"CTVI\", \"GDVI\", \"EVI\",\n \"GEMI\", \"GOSAVI\", \"GSAVI\", \"Hue\", \"IVI\", \"IPVI\", \"I\", \"RVI\",\n \"MRVI\", \"MSAVI\", \"NormG\", \"NormNIR\", \"NormR\", \"NGRDI\", \"RI\",\n \"S\", \"IF\", \"DVI\", \"TVI\", \"NDRE\"]\n\n #list of index with not blue channel\n #notBlueIndex = [\"ARVI2\", \"CCCI\", \"CVI\", \"NDVI\", \"redEdgeNDVI\", \"GNDVI\",\n \"GRNDVI\", \"ATSAVI\", \"CIgreen\", \"CIrededge\", \"CTVI\", \"GDVI\",\n \"GEMI\", \"GOSAVI\", \"GSAVI\", \"IVI\", \"IPVI\", \"RVI\", \"MRVI\",\n \"MSAVI\", \"NormG\", \"NormNIR\", \"NormR\", \"NGRDI\", \"RI\", \"DVI\",\n \"TVI\", \"NDRE\"]\n\n #list of index just with RGB channels\n #RGBIndex = [\"GLI\", \"CI\", \"Hue\", \"I\", \"NGRDI\", \"RI\", \"S\", \"IF\"]\n \"\"\"\n\n def __init__(self, red=None, green=None, blue=None, red_edge=None, nir=None):\n self.set_matricies(red=red, green=green, blue=blue, red_edge=red_edge, nir=nir)\n\n def set_matricies(self, red=None, green=None, blue=None, red_edge=None, nir=None):\n if red is not None:\n self.red = red\n if green is not None:\n self.green = green\n if blue is not None:\n self.blue = blue\n if red_edge is not None:\n self.redEdge = red_edge\n if nir is not None:\n self.nir = nir\n return True\n\n def calculation(\n self, index=\"\", red=None, green=None, blue=None, red_edge=None, nir=None\n ):\n \"\"\"\n performs the calculation of the index with the values instantiated in the class\n :str index: abbreviation of index name to perform\n \"\"\"\n self.set_matricies(red=red, green=green, blue=blue, red_edge=red_edge, nir=nir)\n funcs = {\n \"ARVI2\": self.arv12,\n \"CCCI\": self.ccci,\n \"CVI\": self.cvi,\n \"GLI\": self.gli,\n \"NDVI\": self.ndvi,\n \"BNDVI\": self.bndvi,\n \"redEdgeNDVI\": self.red_edge_ndvi,\n \"GNDVI\": self.gndvi,\n \"GBNDVI\": self.gbndvi,\n \"GRNDVI\": self.grndvi,\n \"RBNDVI\": self.rbndvi,\n \"PNDVI\": self.pndvi,\n \"ATSAVI\": self.atsavi,\n \"BWDRVI\": self.bwdrvi,\n \"CIgreen\": self.ci_green,\n \"CIrededge\": self.ci_rededge,\n \"CI\": self.ci,\n \"CTVI\": self.ctvi,\n \"GDVI\": self.gdvi,\n \"EVI\": self.evi,\n \"GEMI\": self.gemi,\n \"GOSAVI\": self.gosavi,\n \"GSAVI\": self.gsavi,\n \"Hue\": self.hue,\n \"IVI\": self.ivi,\n \"IPVI\": self.ipvi,\n \"I\": self.i,\n \"RVI\": self.rvi,\n \"MRVI\": self.mrvi,\n \"MSAVI\": self.m_savi,\n \"NormG\": self.norm_g,\n \"NormNIR\": self.norm_nir,\n \"NormR\": self.norm_r,\n \"NGRDI\": self.ngrdi,\n \"RI\": self.ri,\n \"S\": self.s,\n \"IF\": self._if,\n \"DVI\": self.dvi,\n \"TVI\": self.tvi,\n \"NDRE\": self.ndre,\n }\n\n try:\n return funcs[index]()\n except KeyError:\n print(\"Index not in the list!\")\n return False\n\n def arv12(self):\n \"\"\"\n Atmospherically Resistant Vegetation Index 2\n https:\/\/www.indexdatabase.de\/db\/i-single.php?id=396\n :return: index\n \u22120.18+1.17*(self.nir\u2212self.red)\/(self.nir+self.red)\n \"\"\"\n return -0.18 + (1.17 * ((self.nir - self.red) \/ (self.nir + self.red)))\n\n def ccci(self):\n \"\"\"\n Canopy Chlorophyll Content Index\n https:\/\/www.indexdatabase.de\/db\/i-single.php?id=224\n :return: index\n \"\"\"\n return ((self.nir - self.redEdge) \/ (self.nir + self.redEdge)) \/ (\n (self.nir - self.red) \/ (self.nir + self.red)\n )\n\n def cvi(self):\n \"\"\"\n Chlorophyll vegetation index\n https:\/\/www.indexdatabase.de\/db\/i-single.php?id=391\n :return: index\n \"\"\"\n return self.nir * (self.red \/ (self.green**2))\n\n def gli(self):\n \"\"\"\n self.green leaf index\n https:\/\/www.indexdatabase.de\/db\/i-single.php?id=375\n :return: index\n \"\"\"\n return (2 * self.green - self.red - self.blue) \/ (\n 2 * self.green + self.red + self.blue\n )\n\n def ndvi(self):\n \"\"\"\n Normalized Difference self.nir\/self.red Normalized Difference Vegetation\n Index, Calibrated NDVI - CDVI\n https:\/\/www.indexdatabase.de\/db\/i-single.php?id=58\n :return: index\n \"\"\"\n return (self.nir - self.red) \/ (self.nir + self.red)\n\n def bndvi(self):\n \"\"\"\n Normalized Difference self.nir\/self.blue self.blue-normalized difference\n vegetation index\n https:\/\/www.indexdatabase.de\/db\/i-single.php?id=135\n :return: index\n \"\"\"\n return (self.nir - self.blue) \/ (self.nir + self.blue)\n\n def red_edge_ndvi(self):\n \"\"\"\n Normalized Difference self.rededge\/self.red\n https:\/\/www.indexdatabase.de\/db\/i-single.php?id=235\n :return: index\n \"\"\"\n return (self.redEdge - self.red) \/ (self.redEdge + self.red)\n\n def gndvi(self):\n \"\"\"\n Normalized Difference self.nir\/self.green self.green NDVI\n https:\/\/www.indexdatabase.de\/db\/i-single.php?id=401\n :return: index\n \"\"\"\n return (self.nir - self.green) \/ (self.nir + self.green)\n\n def gbndvi(self):\n \"\"\"\n self.green-self.blue NDVI\n https:\/\/www.indexdatabase.de\/db\/i-single.php?id=186\n :return: index\n \"\"\"\n return (self.nir - (self.green + self.blue)) \/ (\n self.nir + (self.green + self.blue)\n )\n\n def grndvi(self):\n \"\"\"\n self.green-self.red NDVI\n https:\/\/www.indexdatabase.de\/db\/i-single.php?id=185\n :return: index\n \"\"\"\n return (self.nir - (self.green + self.red)) \/ (\n self.nir + (self.green + self.red)\n )\n\n def rbndvi(self):\n \"\"\"\n self.red-self.blue NDVI\n https:\/\/www.indexdatabase.de\/db\/i-single.php?id=187\n :return: index\n \"\"\"\n return (self.nir - (self.blue + self.red)) \/ (self.nir + (self.blue + self.red))\n\n def pndvi(self):\n \"\"\"\n Pan NDVI\n https:\/\/www.indexdatabase.de\/db\/i-single.php?id=188\n :return: index\n \"\"\"\n return (self.nir - (self.green + self.red + self.blue)) \/ (\n self.nir + (self.green + self.red + self.blue)\n )\n\n def atsavi(self, x=0.08, a=1.22, b=0.03):\n \"\"\"\n Adjusted transformed soil-adjusted VI\n https:\/\/www.indexdatabase.de\/db\/i-single.php?id=209\n :return: index\n \"\"\"\n return a * (\n (self.nir - a * self.red - b)\n \/ (a * self.nir + self.red - a * b + x * (1 + a**2))\n )\n\n def bwdrvi(self):\n \"\"\"\n self.blue-wide dynamic range vegetation index\n https:\/\/www.indexdatabase.de\/db\/i-single.php?id=136\n :return: index\n \"\"\"\n return (0.1 * self.nir - self.blue) \/ (0.1 * self.nir + self.blue)\n\n def ci_green(self):\n \"\"\"\n Chlorophyll Index self.green\n https:\/\/www.indexdatabase.de\/db\/i-single.php?id=128\n :return: index\n \"\"\"\n return (self.nir \/ self.green) - 1\n\n def ci_rededge(self):\n \"\"\"\n Chlorophyll Index self.redEdge\n https:\/\/www.indexdatabase.de\/db\/i-single.php?id=131\n :return: index\n \"\"\"\n return (self.nir \/ self.redEdge) - 1\n\n def ci(self):\n \"\"\"\n Coloration Index\n https:\/\/www.indexdatabase.de\/db\/i-single.php?id=11\n :return: index\n \"\"\"\n return (self.red - self.blue) \/ self.red\n\n def ctvi(self):\n \"\"\"\n Corrected Transformed Vegetation Index\n https:\/\/www.indexdatabase.de\/db\/i-single.php?id=244\n :return: index\n \"\"\"\n ndvi = self.ndvi()\n return ((ndvi + 0.5) \/ (abs(ndvi + 0.5))) * (abs(ndvi + 0.5) ** (1 \/ 2))\n\n def gdvi(self):\n \"\"\"\n Difference self.nir\/self.green self.green Difference Vegetation Index\n https:\/\/www.indexdatabase.de\/db\/i-single.php?id=27\n :return: index\n \"\"\"\n return self.nir - self.green\n\n def evi(self):\n \"\"\"\n Enhanced Vegetation Index\n https:\/\/www.indexdatabase.de\/db\/i-single.php?id=16\n :return: index\n \"\"\"\n return 2.5 * (\n (self.nir - self.red) \/ (self.nir + 6 * self.red - 7.5 * self.blue + 1)\n )\n\n def gemi(self):\n \"\"\"\n Global Environment Monitoring Index\n https:\/\/www.indexdatabase.de\/db\/i-single.php?id=25\n :return: index\n \"\"\"\n n = (2 * (self.nir**2 - self.red**2) + 1.5 * self.nir + 0.5 * self.red) \/ (\n self.nir + self.red + 0.5\n )\n return n * (1 - 0.25 * n) - (self.red - 0.125) \/ (1 - self.red)\n\n def gosavi(self, y=0.16):\n \"\"\"\n self.green Optimized Soil Adjusted Vegetation Index\n https:\/\/www.indexdatabase.de\/db\/i-single.php?id=29\n mit Y = 0,16\n :return: index\n \"\"\"\n return (self.nir - self.green) \/ (self.nir + self.green + y)\n\n def gsavi(self, n=0.5):\n \"\"\"\n self.green Soil Adjusted Vegetation Index\n https:\/\/www.indexdatabase.de\/db\/i-single.php?id=31\n mit N = 0,5\n :return: index\n \"\"\"\n return ((self.nir - self.green) \/ (self.nir + self.green + n)) * (1 + n)\n\n def hue(self):\n \"\"\"\n Hue\n https:\/\/www.indexdatabase.de\/db\/i-single.php?id=34\n :return: index\n \"\"\"\n return np.arctan(\n ((2 * self.red - self.green - self.blue) \/ 30.5) * (self.green - self.blue)\n )\n\n def ivi(self, a=None, b=None):\n \"\"\"\n Ideal vegetation index\n https:\/\/www.indexdatabase.de\/db\/i-single.php?id=276\n b=intercept of vegetation line\n a=soil line slope\n :return: index\n \"\"\"\n return (self.nir - b) \/ (a * self.red)\n\n def ipvi(self):\n \"\"\"\n Infraself.red percentage vegetation index\n https:\/\/www.indexdatabase.de\/db\/i-single.php?id=35\n :return: index\n \"\"\"\n return (self.nir \/ ((self.nir + self.red) \/ 2)) * (self.ndvi() + 1)\n\n def i(self):\n \"\"\"\n Intensity\n https:\/\/www.indexdatabase.de\/db\/i-single.php?id=36\n :return: index\n \"\"\"\n return (self.red + self.green + self.blue) \/ 30.5\n\n def rvi(self):\n \"\"\"\n Ratio-Vegetation-Index\n http:\/\/www.seos-project.eu\/modules\/remotesensing\/remotesensing-c03-s01-p01.html\n :return: index\n \"\"\"\n return self.nir \/ self.red\n\n def mrvi(self):\n \"\"\"\n Modified Normalized Difference Vegetation Index RVI\n https:\/\/www.indexdatabase.de\/db\/i-single.php?id=275\n :return: index\n \"\"\"\n return (self.rvi() - 1) \/ (self.rvi() + 1)\n\n def m_savi(self):\n \"\"\"\n Modified Soil Adjusted Vegetation Index\n https:\/\/www.indexdatabase.de\/db\/i-single.php?id=44\n :return: index\n \"\"\"\n return (\n (2 * self.nir + 1)\n - ((2 * self.nir + 1) ** 2 - 8 * (self.nir - self.red)) ** (1 \/ 2)\n ) \/ 2\n\n def norm_g(self):\n \"\"\"\n Norm G\n https:\/\/www.indexdatabase.de\/db\/i-single.php?id=50\n :return: index\n \"\"\"\n return self.green \/ (self.nir + self.red + self.green)\n\n def norm_nir(self):\n \"\"\"\n Norm self.nir\n https:\/\/www.indexdatabase.de\/db\/i-single.php?id=51\n :return: index\n \"\"\"\n return self.nir \/ (self.nir + self.red + self.green)\n\n def norm_r(self):\n \"\"\"\n Norm R\n https:\/\/www.indexdatabase.de\/db\/i-single.php?id=52\n :return: index\n \"\"\"\n return self.red \/ (self.nir + self.red + self.green)\n\n def ngrdi(self):\n \"\"\"\n Normalized Difference self.green\/self.red Normalized self.green self.red\n difference index, Visible Atmospherically Resistant Indices self.green\n (VIself.green)\n https:\/\/www.indexdatabase.de\/db\/i-single.php?id=390\n :return: index\n \"\"\"\n return (self.green - self.red) \/ (self.green + self.red)\n\n def ri(self):\n \"\"\"\n Normalized Difference self.red\/self.green self.redness Index\n https:\/\/www.indexdatabase.de\/db\/i-single.php?id=74\n :return: index\n \"\"\"\n return (self.red - self.green) \/ (self.red + self.green)\n\n def s(self):\n \"\"\"\n Saturation\n https:\/\/www.indexdatabase.de\/db\/i-single.php?id=77\n :return: index\n \"\"\"\n max_value = np.max([np.max(self.red), np.max(self.green), np.max(self.blue)])\n min_value = np.min([np.min(self.red), np.min(self.green), np.min(self.blue)])\n return (max_value - min_value) \/ max_value\n\n def _if(self):\n \"\"\"\n Shape Index\n https:\/\/www.indexdatabase.de\/db\/i-single.php?id=79\n :return: index\n \"\"\"\n return (2 * self.red - self.green - self.blue) \/ (self.green - self.blue)\n\n def dvi(self):\n \"\"\"\n Simple Ratio self.nir\/self.red Difference Vegetation Index, Vegetation Index\n Number (VIN)\n https:\/\/www.indexdatabase.de\/db\/i-single.php?id=12\n :return: index\n \"\"\"\n return self.nir \/ self.red\n\n def tvi(self):\n \"\"\"\n Transformed Vegetation Index\n https:\/\/www.indexdatabase.de\/db\/i-single.php?id=98\n :return: index\n \"\"\"\n return (self.ndvi() + 0.5) ** (1 \/ 2)\n\n def ndre(self):\n return (self.nir - self.redEdge) \/ (self.nir + self.redEdge)\n\n\n\"\"\"\n# genering a random matrices to test this class\nred = np.ones((1000,1000, 1),dtype=\"float64\") * 46787\ngreen = np.ones((1000,1000, 1),dtype=\"float64\") * 23487\nblue = np.ones((1000,1000, 1),dtype=\"float64\") * 14578\nredEdge = np.ones((1000,1000, 1),dtype=\"float64\") * 51045\nnir = np.ones((1000,1000, 1),dtype=\"float64\") * 52200\n\n# Examples of how to use the class\n\n# instantiating the class\ncl = IndexCalculation()\n\n# instantiating the class with the values\n#cl = indexCalculation(red=red, green=green, blue=blue, redEdge=redEdge, nir=nir)\n\n# how set the values after instantiate the class cl, (for update the data or when don't\n# instantiating the class with the values)\ncl.setMatrices(red=red, green=green, blue=blue, redEdge=redEdge, nir=nir)\n\n# calculating the indices for the instantiated values in the class\n # Note: the CCCI index can be changed to any index implemented in the class.\nindexValue_form1 = cl.calculation(\"CCCI\", red=red, green=green, blue=blue,\n redEdge=redEdge, nir=nir).astype(np.float64)\nindexValue_form2 = cl.CCCI()\n\n# calculating the index with the values directly -- you can set just the values\n# preferred note: the *calculation* function performs the function *setMatrices*\nindexValue_form3 = cl.calculation(\"CCCI\", red=red, green=green, blue=blue,\n redEdge=redEdge, nir=nir).astype(np.float64)\n\nprint(\"Form 1: \"+np.array2string(indexValue_form1, precision=20, separator=', ',\n floatmode='maxprec_equal'))\nprint(\"Form 2: \"+np.array2string(indexValue_form2, precision=20, separator=', ',\n floatmode='maxprec_equal'))\nprint(\"Form 3: \"+np.array2string(indexValue_form3, precision=20, separator=', ',\n floatmode='maxprec_equal'))\n\n# A list of examples results for different type of data at NDVI\n# float16 -> 0.31567383 #NDVI (red = 50, nir = 100)\n# float32 -> 0.31578946 #NDVI (red = 50, nir = 100)\n# float64 -> 0.3157894736842105 #NDVI (red = 50, nir = 100)\n# longdouble -> 0.3157894736842105 #NDVI (red = 50, nir = 100)\n\"\"\"\n"} +{"Prompt":"Return gray image from rgb image rgbtograynp.array127, 255, 0 array187.6453 rgbtograynp.array0, 0, 0 array0. rgbtograynp.array2, 4, 1 array3.0598 rgbtograynp.array26, 255, 14, 5, 147, 20, 1, 200, 0 array159.0524, 90.0635, 117.6989 Return binary image from gray image graytobinarynp.array127, 255, 0 arrayFalse, True, False graytobinarynp.array0 arrayFalse graytobinarynp.array26.2409, 4.9315, 1.4729 arrayFalse, False, False graytobinarynp.array26, 255, 14, 5, 147, 20, 1, 200, 0 arrayFalse, True, False, False, True, False, False, True, False Return dilated image dilationnp.arrayTrue, False, True, np.array0, 1, 0 arrayFalse, False, False dilationnp.arrayFalse, False, True, np.array1, 0, 1 arrayFalse, False, False Copy image to padded image Iterate over image apply kernel read original image kernel to be applied Save the output image","Completions":"from pathlib import Path\n\nimport numpy as np\nfrom PIL import Image\n\n\ndef rgb_to_gray(rgb: np.ndarray) -> np.ndarray:\n \"\"\"\n Return gray image from rgb image\n >>> rgb_to_gray(np.array([[[127, 255, 0]]]))\n array([[187.6453]])\n >>> rgb_to_gray(np.array([[[0, 0, 0]]]))\n array([[0.]])\n >>> rgb_to_gray(np.array([[[2, 4, 1]]]))\n array([[3.0598]])\n >>> rgb_to_gray(np.array([[[26, 255, 14], [5, 147, 20], [1, 200, 0]]]))\n array([[159.0524, 90.0635, 117.6989]])\n \"\"\"\n r, g, b = rgb[:, :, 0], rgb[:, :, 1], rgb[:, :, 2]\n return 0.2989 * r + 0.5870 * g + 0.1140 * b\n\n\ndef gray_to_binary(gray: np.ndarray) -> np.ndarray:\n \"\"\"\n Return binary image from gray image\n >>> gray_to_binary(np.array([[127, 255, 0]]))\n array([[False, True, False]])\n >>> gray_to_binary(np.array([[0]]))\n array([[False]])\n >>> gray_to_binary(np.array([[26.2409, 4.9315, 1.4729]]))\n array([[False, False, False]])\n >>> gray_to_binary(np.array([[26, 255, 14], [5, 147, 20], [1, 200, 0]]))\n array([[False, True, False],\n [False, True, False],\n [False, True, False]])\n \"\"\"\n return (gray > 127) & (gray <= 255)\n\n\ndef dilation(image: np.ndarray, kernel: np.ndarray) -> np.ndarray:\n \"\"\"\n Return dilated image\n >>> dilation(np.array([[True, False, True]]), np.array([[0, 1, 0]]))\n array([[False, False, False]])\n >>> dilation(np.array([[False, False, True]]), np.array([[1, 0, 1]]))\n array([[False, False, False]])\n \"\"\"\n output = np.zeros_like(image)\n image_padded = np.zeros(\n (image.shape[0] + kernel.shape[0] - 1, image.shape[1] + kernel.shape[1] - 1)\n )\n\n # Copy image to padded image\n image_padded[kernel.shape[0] - 2 : -1 :, kernel.shape[1] - 2 : -1 :] = image\n\n # Iterate over image & apply kernel\n for x in range(image.shape[1]):\n for y in range(image.shape[0]):\n summation = (\n kernel * image_padded[y : y + kernel.shape[0], x : x + kernel.shape[1]]\n ).sum()\n output[y, x] = int(summation > 0)\n return output\n\n\nif __name__ == \"__main__\":\n # read original image\n lena_path = Path(__file__).resolve().parent \/ \"image_data\" \/ \"lena.jpg\"\n lena = np.array(Image.open(lena_path))\n # kernel to be applied\n structuring_element = np.array([[0, 1, 0], [1, 1, 1], [0, 1, 0]])\n output = dilation(gray_to_binary(rgb_to_gray(lena)), structuring_element)\n # Save the output image\n pil_img = Image.fromarray(output).convert(\"RGB\")\n pil_img.save(\"result_dilation.png\")\n"} +{"Prompt":"Return gray image from rgb image rgbtograynp.array127, 255, 0 array187.6453 rgbtograynp.array0, 0, 0 array0. rgbtograynp.array2, 4, 1 array3.0598 rgbtograynp.array26, 255, 14, 5, 147, 20, 1, 200, 0 array159.0524, 90.0635, 117.6989 Return binary image from gray image graytobinarynp.array127, 255, 0 arrayFalse, True, False graytobinarynp.array0 arrayFalse graytobinarynp.array26.2409, 4.9315, 1.4729 arrayFalse, False, False graytobinarynp.array26, 255, 14, 5, 147, 20, 1, 200, 0 arrayFalse, True, False, False, True, False, False, True, False Return eroded image erosionnp.arrayTrue, True, False, np.array0, 1, 0 arrayFalse, False, False erosionnp.arrayTrue, False, False, np.array1, 1, 0 arrayFalse, False, False Copy image to padded image Iterate over image apply kernel read original image kernel to be applied Apply erosion operation to a binary image Save the output image","Completions":"from pathlib import Path\n\nimport numpy as np\nfrom PIL import Image\n\n\ndef rgb_to_gray(rgb: np.ndarray) -> np.ndarray:\n \"\"\"\n Return gray image from rgb image\n\n >>> rgb_to_gray(np.array([[[127, 255, 0]]]))\n array([[187.6453]])\n >>> rgb_to_gray(np.array([[[0, 0, 0]]]))\n array([[0.]])\n >>> rgb_to_gray(np.array([[[2, 4, 1]]]))\n array([[3.0598]])\n >>> rgb_to_gray(np.array([[[26, 255, 14], [5, 147, 20], [1, 200, 0]]]))\n array([[159.0524, 90.0635, 117.6989]])\n \"\"\"\n r, g, b = rgb[:, :, 0], rgb[:, :, 1], rgb[:, :, 2]\n return 0.2989 * r + 0.5870 * g + 0.1140 * b\n\n\ndef gray_to_binary(gray: np.ndarray) -> np.ndarray:\n \"\"\"\n Return binary image from gray image\n\n >>> gray_to_binary(np.array([[127, 255, 0]]))\n array([[False, True, False]])\n >>> gray_to_binary(np.array([[0]]))\n array([[False]])\n >>> gray_to_binary(np.array([[26.2409, 4.9315, 1.4729]]))\n array([[False, False, False]])\n >>> gray_to_binary(np.array([[26, 255, 14], [5, 147, 20], [1, 200, 0]]))\n array([[False, True, False],\n [False, True, False],\n [False, True, False]])\n \"\"\"\n return (gray > 127) & (gray <= 255)\n\n\ndef erosion(image: np.ndarray, kernel: np.ndarray) -> np.ndarray:\n \"\"\"\n Return eroded image\n\n >>> erosion(np.array([[True, True, False]]), np.array([[0, 1, 0]]))\n array([[False, False, False]])\n >>> erosion(np.array([[True, False, False]]), np.array([[1, 1, 0]]))\n array([[False, False, False]])\n \"\"\"\n output = np.zeros_like(image)\n image_padded = np.zeros(\n (image.shape[0] + kernel.shape[0] - 1, image.shape[1] + kernel.shape[1] - 1)\n )\n\n # Copy image to padded image\n image_padded[kernel.shape[0] - 2 : -1 :, kernel.shape[1] - 2 : -1 :] = image\n\n # Iterate over image & apply kernel\n for x in range(image.shape[1]):\n for y in range(image.shape[0]):\n summation = (\n kernel * image_padded[y : y + kernel.shape[0], x : x + kernel.shape[1]]\n ).sum()\n output[y, x] = int(summation == 5)\n return output\n\n\nif __name__ == \"__main__\":\n # read original image\n lena_path = Path(__file__).resolve().parent \/ \"image_data\" \/ \"lena.jpg\"\n lena = np.array(Image.open(lena_path))\n\n # kernel to be applied\n structuring_element = np.array([[0, 1, 0], [1, 1, 1], [0, 1, 0]])\n\n # Apply erosion operation to a binary image\n output = erosion(gray_to_binary(rgb_to_gray(lena)), structuring_element)\n\n # Save the output image\n pil_img = Image.fromarray(output).convert(\"RGB\")\n pil_img.save(\"result_erosion.png\")\n"} +{"Prompt":"Multiple image resizing techniques import numpy as np from cv2 import destroyAllWindows, imread, imshow, waitKey class NearestNeighbour: def initself, img, dstwidth: int, dstheight: int: if dstwidth 0 or dstheight 0: raise ValueErrorDestination widthheight should be 0 self.img img self.srcw img.shape1 self.srch img.shape0 self.dstw dstwidth self.dsth dstheight self.ratiox self.srcw self.dstw self.ratioy self.srch self.dsth self.output self.outputimg np.onesself.dsth, self.dstw, 3, np.uint8 255 def processself: for i in rangeself.dsth: for j in rangeself.dstw: self.outputij self.imgself.getyiself.getxj def getxself, x: int int: return intself.ratiox x def getyself, y: int int: return intself.ratioy y if name main: dstw, dsth 800, 600 im imreadimagedatalena.jpg, 1 n NearestNeighbourim, dstw, dsth n.process imshow fImage resized from: im.shape1xim.shape0 to dstwxdsth, n.output waitKey0 destroyAllWindows","Completions":"import numpy as np\nfrom cv2 import destroyAllWindows, imread, imshow, waitKey\n\n\nclass NearestNeighbour:\n \"\"\"\n Simplest and fastest version of image resizing.\n Source: https:\/\/en.wikipedia.org\/wiki\/Nearest-neighbor_interpolation\n \"\"\"\n\n def __init__(self, img, dst_width: int, dst_height: int):\n if dst_width < 0 or dst_height < 0:\n raise ValueError(\"Destination width\/height should be > 0\")\n\n self.img = img\n self.src_w = img.shape[1]\n self.src_h = img.shape[0]\n self.dst_w = dst_width\n self.dst_h = dst_height\n\n self.ratio_x = self.src_w \/ self.dst_w\n self.ratio_y = self.src_h \/ self.dst_h\n\n self.output = self.output_img = (\n np.ones((self.dst_h, self.dst_w, 3), np.uint8) * 255\n )\n\n def process(self):\n for i in range(self.dst_h):\n for j in range(self.dst_w):\n self.output[i][j] = self.img[self.get_y(i)][self.get_x(j)]\n\n def get_x(self, x: int) -> int:\n \"\"\"\n Get parent X coordinate for destination X\n :param x: Destination X coordinate\n :return: Parent X coordinate based on `x ratio`\n >>> nn = NearestNeighbour(imread(\"digital_image_processing\/image_data\/lena.jpg\",\n ... 1), 100, 100)\n >>> nn.ratio_x = 0.5\n >>> nn.get_x(4)\n 2\n \"\"\"\n return int(self.ratio_x * x)\n\n def get_y(self, y: int) -> int:\n \"\"\"\n Get parent Y coordinate for destination Y\n :param y: Destination X coordinate\n :return: Parent X coordinate based on `y ratio`\n >>> nn = NearestNeighbour(imread(\"digital_image_processing\/image_data\/lena.jpg\",\n ... 1), 100, 100)\n >>> nn.ratio_y = 0.5\n >>> nn.get_y(4)\n 2\n \"\"\"\n return int(self.ratio_y * y)\n\n\nif __name__ == \"__main__\":\n dst_w, dst_h = 800, 600\n im = imread(\"image_data\/lena.jpg\", 1)\n n = NearestNeighbour(im, dst_w, dst_h)\n n.process()\n\n imshow(\n f\"Image resized from: {im.shape[1]}x{im.shape[0]} to {dst_w}x{dst_h}\", n.output\n )\n waitKey(0)\n destroyAllWindows()\n"} +{"Prompt":"Get image rotation :param img: np.ndarray :param pt1: 3x2 list :param pt2: 3x2 list :param rows: columns image shape :param cols: rows image shape :return: np.ndarray read original image turn image in gray scale value get image shape set different points to rotate image add all rotated images in a list plot different image rotations","Completions":"from pathlib import Path\n\nimport cv2\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\n\ndef get_rotation(\n img: np.ndarray, pt1: np.ndarray, pt2: np.ndarray, rows: int, cols: int\n) -> np.ndarray:\n \"\"\"\n Get image rotation\n :param img: np.ndarray\n :param pt1: 3x2 list\n :param pt2: 3x2 list\n :param rows: columns image shape\n :param cols: rows image shape\n :return: np.ndarray\n \"\"\"\n matrix = cv2.getAffineTransform(pt1, pt2)\n return cv2.warpAffine(img, matrix, (rows, cols))\n\n\nif __name__ == \"__main__\":\n # read original image\n image = cv2.imread(\n str(Path(__file__).resolve().parent.parent \/ \"image_data\" \/ \"lena.jpg\")\n )\n # turn image in gray scale value\n gray_img = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n # get image shape\n img_rows, img_cols = gray_img.shape\n\n # set different points to rotate image\n pts1 = np.array([[50, 50], [200, 50], [50, 200]], np.float32)\n pts2 = np.array([[10, 100], [200, 50], [100, 250]], np.float32)\n pts3 = np.array([[50, 50], [150, 50], [120, 200]], np.float32)\n pts4 = np.array([[10, 100], [80, 50], [180, 250]], np.float32)\n\n # add all rotated images in a list\n images = [\n gray_img,\n get_rotation(gray_img, pts1, pts2, img_rows, img_cols),\n get_rotation(gray_img, pts2, pts3, img_rows, img_cols),\n get_rotation(gray_img, pts2, pts4, img_rows, img_cols),\n ]\n\n # plot different image rotations\n fig = plt.figure(1)\n titles = [\"Original\", \"Rotation 1\", \"Rotation 2\", \"Rotation 3\"]\n for i, image in enumerate(images):\n plt.subplot(2, 2, i + 1), plt.imshow(image, \"gray\")\n plt.title(titles[i])\n plt.axis(\"off\")\n plt.subplots_adjust(left=0.0, bottom=0.05, right=1.0, top=0.95)\n plt.show()\n"} +{"Prompt":"Implemented an algorithm using opencv to tone an image with sepia technique Function create sepia tone. Source: https:en.wikipedia.orgwikiSepiacolor Helper function to create pixel's greyscale representation Src: https:pl.wikipedia.orgwikiYUV Helper function to normalize RGB value return 255 if value 255 return minvalue, 255 for i in rangepixelh: for j in rangepixelv: greyscale inttograyscaleimgij imgij normalizegreyscale, normalizegreyscale factor, normalizegreyscale 2 factor, return img if name main: read original image images percentage: imreadimagedatalena.jpg, 1 for percentage in 10, 20, 30, 40 for percentage, img in images.items: makesepiaimg, percentage for percentage, img in images.items: imshowfOriginal image with sepia factor: percentage, img waitKey0 destroyAllWindows","Completions":"from cv2 import destroyAllWindows, imread, imshow, waitKey\n\n\ndef make_sepia(img, factor: int):\n \"\"\"\n Function create sepia tone.\n Source: https:\/\/en.wikipedia.org\/wiki\/Sepia_(color)\n \"\"\"\n pixel_h, pixel_v = img.shape[0], img.shape[1]\n\n def to_grayscale(blue, green, red):\n \"\"\"\n Helper function to create pixel's greyscale representation\n Src: https:\/\/pl.wikipedia.org\/wiki\/YUV\n \"\"\"\n return 0.2126 * red + 0.587 * green + 0.114 * blue\n\n def normalize(value):\n \"\"\"Helper function to normalize R\/G\/B value -> return 255 if value > 255\"\"\"\n return min(value, 255)\n\n for i in range(pixel_h):\n for j in range(pixel_v):\n greyscale = int(to_grayscale(*img[i][j]))\n img[i][j] = [\n normalize(greyscale),\n normalize(greyscale + factor),\n normalize(greyscale + 2 * factor),\n ]\n\n return img\n\n\nif __name__ == \"__main__\":\n # read original image\n images = {\n percentage: imread(\"image_data\/lena.jpg\", 1) for percentage in (10, 20, 30, 40)\n }\n\n for percentage, img in images.items():\n make_sepia(img, percentage)\n\n for percentage, img in images.items():\n imshow(f\"Original image with sepia (factor: {percentage})\", img)\n\n waitKey(0)\n destroyAllWindows()\n"} +{"Prompt":"PyTest's for Digital Image Processing Test: converttonegative assert negativeimg array for at least one True Test: changecontrast Work around assertion for response canny.gengaussiankernel Assert ambiguous array canny.py assert ambiguous array for all True assert canny array for at least one True filtersgaussianfilter.py laplace diagonals pull request 10161 before: digitalimageprocessingimagedatalena.jpg after: digitalimageprocessingimagedatalenasmall.jpg Reading the image and converting it to grayscale Test for getneighborspixel function return not None Test for localbinarypattern function Create a numpy array as the same height and width of read image Iterating through the image and calculating the local binary pattern value for each pixel.","Completions":"import numpy as np\nfrom cv2 import COLOR_BGR2GRAY, cvtColor, imread\nfrom numpy import array, uint8\nfrom PIL import Image\n\nfrom digital_image_processing import change_contrast as cc\nfrom digital_image_processing import convert_to_negative as cn\nfrom digital_image_processing import sepia as sp\nfrom digital_image_processing.dithering import burkes as bs\nfrom digital_image_processing.edge_detection import canny\nfrom digital_image_processing.filters import convolve as conv\nfrom digital_image_processing.filters import gaussian_filter as gg\nfrom digital_image_processing.filters import local_binary_pattern as lbp\nfrom digital_image_processing.filters import median_filter as med\nfrom digital_image_processing.filters import sobel_filter as sob\nfrom digital_image_processing.resize import resize as rs\n\nimg = imread(r\"digital_image_processing\/image_data\/lena_small.jpg\")\ngray = cvtColor(img, COLOR_BGR2GRAY)\n\n\n# Test: convert_to_negative()\ndef test_convert_to_negative():\n negative_img = cn.convert_to_negative(img)\n # assert negative_img array for at least one True\n assert negative_img.any()\n\n\n# Test: change_contrast()\ndef test_change_contrast():\n with Image.open(\"digital_image_processing\/image_data\/lena_small.jpg\") as img:\n # Work around assertion for response\n assert str(cc.change_contrast(img, 110)).startswith(\n \">> euclidean_distance_sqr([1,2],[2,4])\n 5\n \"\"\"\n return (point1[0] - point2[0]) ** 2 + (point1[1] - point2[1]) ** 2\n\n\ndef column_based_sort(array, column=0):\n \"\"\"\n >>> column_based_sort([(5, 1), (4, 2), (3, 0)], 1)\n [(3, 0), (5, 1), (4, 2)]\n \"\"\"\n return sorted(array, key=lambda x: x[column])\n\n\ndef dis_between_closest_pair(points, points_counts, min_dis=float(\"inf\")):\n \"\"\"\n brute force approach to find distance between closest pair points\n\n Parameters :\n points, points_count, min_dis (list(tuple(int, int)), int, int)\n\n Returns :\n min_dis (float): distance between closest pair of points\n\n >>> dis_between_closest_pair([[1,2],[2,4],[5,7],[8,9],[11,0]],5)\n 5\n\n \"\"\"\n\n for i in range(points_counts - 1):\n for j in range(i + 1, points_counts):\n current_dis = euclidean_distance_sqr(points[i], points[j])\n if current_dis < min_dis:\n min_dis = current_dis\n return min_dis\n\n\ndef dis_between_closest_in_strip(points, points_counts, min_dis=float(\"inf\")):\n \"\"\"\n closest pair of points in strip\n\n Parameters :\n points, points_count, min_dis (list(tuple(int, int)), int, int)\n\n Returns :\n min_dis (float): distance btw closest pair of points in the strip (< min_dis)\n\n >>> dis_between_closest_in_strip([[1,2],[2,4],[5,7],[8,9],[11,0]],5)\n 85\n \"\"\"\n\n for i in range(min(6, points_counts - 1), points_counts):\n for j in range(max(0, i - 6), i):\n current_dis = euclidean_distance_sqr(points[i], points[j])\n if current_dis < min_dis:\n min_dis = current_dis\n return min_dis\n\n\ndef closest_pair_of_points_sqr(points_sorted_on_x, points_sorted_on_y, points_counts):\n \"\"\"divide and conquer approach\n\n Parameters :\n points, points_count (list(tuple(int, int)), int)\n\n Returns :\n (float): distance btw closest pair of points\n\n >>> closest_pair_of_points_sqr([(1, 2), (3, 4)], [(5, 6), (7, 8)], 2)\n 8\n \"\"\"\n\n # base case\n if points_counts <= 3:\n return dis_between_closest_pair(points_sorted_on_x, points_counts)\n\n # recursion\n mid = points_counts \/\/ 2\n closest_in_left = closest_pair_of_points_sqr(\n points_sorted_on_x, points_sorted_on_y[:mid], mid\n )\n closest_in_right = closest_pair_of_points_sqr(\n points_sorted_on_y, points_sorted_on_y[mid:], points_counts - mid\n )\n closest_pair_dis = min(closest_in_left, closest_in_right)\n\n \"\"\"\n cross_strip contains the points, whose Xcoords are at a\n distance(< closest_pair_dis) from mid's Xcoord\n \"\"\"\n\n cross_strip = []\n for point in points_sorted_on_x:\n if abs(point[0] - points_sorted_on_x[mid][0]) < closest_pair_dis:\n cross_strip.append(point)\n\n closest_in_strip = dis_between_closest_in_strip(\n cross_strip, len(cross_strip), closest_pair_dis\n )\n return min(closest_pair_dis, closest_in_strip)\n\n\ndef closest_pair_of_points(points, points_counts):\n \"\"\"\n >>> closest_pair_of_points([(2, 3), (12, 30)], len([(2, 3), (12, 30)]))\n 28.792360097775937\n \"\"\"\n points_sorted_on_x = column_based_sort(points, column=0)\n points_sorted_on_y = column_based_sort(points, column=1)\n return (\n closest_pair_of_points_sqr(\n points_sorted_on_x, points_sorted_on_y, points_counts\n )\n ) ** 0.5\n\n\nif __name__ == \"__main__\":\n points = [(2, 3), (12, 30), (40, 50), (5, 1), (12, 10), (3, 4)]\n print(\"Distance:\", closest_pair_of_points(points, len(points)))\n"} +{"Prompt":"The convex hull problem is problem of finding all the vertices of convex polygon, P of a set of points in a plane such that all the points are either on the vertices of P or inside P. TH convex hull problem has several applications in geometrical problems, computer graphics and game development. Two algorithms have been implemented for the convex hull problem here. 1. A bruteforce algorithm which runs in On3 2. A divideandconquer algorithm which runs in On logn There are other several other algorithms for the convex hull problem which have not been implemented here, yet. Defines a 2d point for use by all convexhull algorithms. Parameters x: an int or a float, the xcoordinate of the 2d point y: an int or a float, the ycoordinate of the 2d point Examples Point1, 2 1.0, 2.0 Point1, 2 1.0, 2.0 Point1, 2 Point0, 1 True Point1, 1 Point1, 1 True Point0.5, 1 Point0.5, 1 False Pointpi, e Traceback most recent call last: ... ValueError: could not convert string to float: 'pi' constructs a list of points from an arraylike object of numbers Arguments listoftuples: arraylike object of type numbers. Acceptable types so far are lists, tuples and sets. Returns points: a list where each item is of type Point. This contains only objects which can be converted into a Point. Examples constructpoints1, 1, 2, 1, 0.3, 4 1.0, 1.0, 2.0, 1.0, 0.3, 4.0 constructpoints1, 2 Ignoring deformed point 1. All points must have at least 2 coordinates. Ignoring deformed point 2. All points must have at least 2 coordinates. constructpoints constructpointsNone validates an input instance before a convexhull algorithms uses it Parameters points: arraylike, the 2d points to validate before using with a convexhull algorithm. The elements of points must be either lists, tuples or Points. Returns points: arraylike, an iterable of all welldefined Points constructed passed in. Exception ValueError: if points is empty or None, or if a wrong data structure like a scalar is passed TypeError: if an iterable but nonindexable object eg. dictionary is passed. The exception to this a set which we'll convert to a list before using Examples validateinput1, 2 1.0, 2.0 validateinput1, 2 1.0, 2.0 validateinputPoint2, 1, Point1, 2 2.0, 1.0, 1.0, 2.0 validateinput Traceback most recent call last: ... ValueError: Expecting a list of points but got validateinput1 Traceback most recent call last: ... ValueError: Expecting an iterable object but got an noniterable type 1 Computes the sign perpendicular distance of a 2d point c from a line segment ab. The sign indicates the direction of c relative to ab. A Positive value means c is above ab to the left, while a negative value means c is below ab to the right. 0 means all three points are on a straight line. As a side note, 0.5 absdet is the area of triangle abc Parameters a: point, the point on the left end of line segment ab b: point, the point on the right end of line segment ab c: point, the point for which the direction and location is desired. Returns det: float, absdet is the distance of c from ab. The sign indicates which side of line segment ab c is. det is computed as axby cxay bxcy aybx cyax bycx Examples detPoint1, 1, Point1, 2, Point1, 5 0.0 detPoint0, 0, Point10, 0, Point0, 10 100.0 detPoint0, 0, Point10, 0, Point0, 10 100.0 Constructs the convex hull of a set of 2D points using a brute force algorithm. The algorithm basically considers all combinations of points i, j and uses the definition of convexity to determine whether i, j is part of the convex hull or not. i, j is part of the convex hull if and only iff there are no points on both sides of the line segment connecting the ij, and there is no point k such that k is on either end of the ij. Runtime: On3 definitely horrible Parameters points: arraylike of object of Points, lists or tuples. The set of 2d points for which the convexhull is needed Returns convexset: list, the convexhull of points sorted in nondecreasing order. See Also convexhullrecursive, Examples convexhullbf0, 0, 1, 0, 10, 1 0.0, 0.0, 1.0, 0.0, 10.0, 1.0 convexhullbf0, 0, 1, 0, 10, 0 0.0, 0.0, 10.0, 0.0 convexhullbf1, 1,1, 1, 0, 0, 0.5, 0.5, 1, 1, 1, 1, ... 0.75, 1 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0 convexhullbf0, 3, 2, 2, 1, 1, 2, 1, 3, 0, 0, 0, 3, 3, ... 2, 1, 2, 4, 1, 3 0.0, 0.0, 0.0, 3.0, 1.0, 3.0, 2.0, 4.0, 3.0, 0.0, 3.0, 3.0 pointi, pointj, pointk all lie on a straight line if pointk is to the left of pointi or it's to the right of pointj, then pointi, pointj cannot be part of the convex hull of A Constructs the convex hull of a set of 2D points using a divideandconquer strategy The algorithm exploits the geometric properties of the problem by repeatedly partitioning the set of points into smaller hulls, and finding the convex hull of these smaller hulls. The union of the convex hull from smaller hulls is the solution to the convex hull of the larger problem. Parameter points: arraylike of object of Points, lists or tuples. The set of 2d points for which the convexhull is needed Runtime: On log n Returns convexset: list, the convexhull of points sorted in nondecreasing order. Examples convexhullrecursive0, 0, 1, 0, 10, 1 0.0, 0.0, 1.0, 0.0, 10.0, 1.0 convexhullrecursive0, 0, 1, 0, 10, 0 0.0, 0.0, 10.0, 0.0 convexhullrecursive1, 1,1, 1, 0, 0, 0.5, 0.5, 1, 1, 1, 1, ... 0.75, 1 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0 convexhullrecursive0, 3, 2, 2, 1, 1, 2, 1, 3, 0, 0, 0, 3, 3, ... 2, 1, 2, 4, 1, 3 0.0, 0.0, 0.0, 3.0, 1.0, 3.0, 2.0, 4.0, 3.0, 0.0, 3.0, 3.0 divide all the points into an upper hull and a lower hull the left most point and the right most point are definitely members of the convex hull by definition. use these two anchors to divide all the points into two hulls, an upper hull and a lower hull. all points to the left above the line joining the extreme points belong to the upper hull all points to the right below the line joining the extreme points below to the lower hull ignore all points on the line joining the extreme points since they cannot be part of the convex hull Parameters points: list or None, the hull of points from which to choose the next convexhull point left: Point, the point to the left of line segment joining left and right right: The point to the right of the line segment joining left and right convexset: set, the current convexhull. The state of convexset gets updated by this function Note For the line segment 'ab', 'a' is on the left and 'b' on the right. but the reverse is true for the line segment 'ba'. Returns Nothing, only updates the state of convexset Constructs the convex hull of a set of 2D points using the melkman algorithm. The algorithm works by iteratively inserting points of a simple polygonal chain meaning that no line segments between two consecutive points cross each other. Sorting the points yields such a polygonal chain. For a detailed description, see http:cgm.cs.mcgill.caathenscs601Melkman.html Runtime: On log n On if points are already sorted in the input Parameters points: arraylike of object of Points, lists or tuples. The set of 2d points for which the convexhull is needed Returns convexset: list, the convexhull of points sorted in nondecreasing order. See Also Examples convexhullmelkman0, 0, 1, 0, 10, 1 0.0, 0.0, 1.0, 0.0, 10.0, 1.0 convexhullmelkman0, 0, 1, 0, 10, 0 0.0, 0.0, 10.0, 0.0 convexhullmelkman1, 1,1, 1, 0, 0, 0.5, 0.5, 1, 1, 1, 1, ... 0.75, 1 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0 convexhullmelkman0, 3, 2, 2, 1, 1, 2, 1, 3, 0, 0, 0, 3, 3, ... 2, 1, 2, 4, 1, 3 0.0, 0.0, 0.0, 3.0, 1.0, 3.0, 2.0, 4.0, 3.0, 0.0, 3.0, 3.0 The point lies within the convex hull convexhull is contains the convex hull in circular order the convex set of points is 0, 0, 0, 3, 1, 3, 2, 4, 3, 0, 3, 3","Completions":"from __future__ import annotations\n\nfrom collections.abc import Iterable\n\n\nclass Point:\n \"\"\"\n Defines a 2-d point for use by all convex-hull algorithms.\n\n Parameters\n ----------\n x: an int or a float, the x-coordinate of the 2-d point\n y: an int or a float, the y-coordinate of the 2-d point\n\n Examples\n --------\n >>> Point(1, 2)\n (1.0, 2.0)\n >>> Point(\"1\", \"2\")\n (1.0, 2.0)\n >>> Point(1, 2) > Point(0, 1)\n True\n >>> Point(1, 1) == Point(1, 1)\n True\n >>> Point(-0.5, 1) == Point(0.5, 1)\n False\n >>> Point(\"pi\", \"e\")\n Traceback (most recent call last):\n ...\n ValueError: could not convert string to float: 'pi'\n \"\"\"\n\n def __init__(self, x, y):\n self.x, self.y = float(x), float(y)\n\n def __eq__(self, other):\n return self.x == other.x and self.y == other.y\n\n def __ne__(self, other):\n return not self == other\n\n def __gt__(self, other):\n if self.x > other.x:\n return True\n elif self.x == other.x:\n return self.y > other.y\n return False\n\n def __lt__(self, other):\n return not self > other\n\n def __ge__(self, other):\n if self.x > other.x:\n return True\n elif self.x == other.x:\n return self.y >= other.y\n return False\n\n def __le__(self, other):\n if self.x < other.x:\n return True\n elif self.x == other.x:\n return self.y <= other.y\n return False\n\n def __repr__(self):\n return f\"({self.x}, {self.y})\"\n\n def __hash__(self):\n return hash(self.x)\n\n\ndef _construct_points(\n list_of_tuples: list[Point] | list[list[float]] | Iterable[list[float]],\n) -> list[Point]:\n \"\"\"\n constructs a list of points from an array-like object of numbers\n\n Arguments\n ---------\n\n list_of_tuples: array-like object of type numbers. Acceptable types so far\n are lists, tuples and sets.\n\n Returns\n --------\n points: a list where each item is of type Point. This contains only objects\n which can be converted into a Point.\n\n Examples\n -------\n >>> _construct_points([[1, 1], [2, -1], [0.3, 4]])\n [(1.0, 1.0), (2.0, -1.0), (0.3, 4.0)]\n >>> _construct_points([1, 2])\n Ignoring deformed point 1. All points must have at least 2 coordinates.\n Ignoring deformed point 2. All points must have at least 2 coordinates.\n []\n >>> _construct_points([])\n []\n >>> _construct_points(None)\n []\n \"\"\"\n\n points: list[Point] = []\n if list_of_tuples:\n for p in list_of_tuples:\n if isinstance(p, Point):\n points.append(p)\n else:\n try:\n points.append(Point(p[0], p[1]))\n except (IndexError, TypeError):\n print(\n f\"Ignoring deformed point {p}. All points\"\n \" must have at least 2 coordinates.\"\n )\n return points\n\n\ndef _validate_input(points: list[Point] | list[list[float]]) -> list[Point]:\n \"\"\"\n validates an input instance before a convex-hull algorithms uses it\n\n Parameters\n ---------\n points: array-like, the 2d points to validate before using with\n a convex-hull algorithm. The elements of points must be either lists, tuples or\n Points.\n\n Returns\n -------\n points: array_like, an iterable of all well-defined Points constructed passed in.\n\n\n Exception\n ---------\n ValueError: if points is empty or None, or if a wrong data structure like a scalar\n is passed\n\n TypeError: if an iterable but non-indexable object (eg. dictionary) is passed.\n The exception to this a set which we'll convert to a list before using\n\n\n Examples\n -------\n >>> _validate_input([[1, 2]])\n [(1.0, 2.0)]\n >>> _validate_input([(1, 2)])\n [(1.0, 2.0)]\n >>> _validate_input([Point(2, 1), Point(-1, 2)])\n [(2.0, 1.0), (-1.0, 2.0)]\n >>> _validate_input([])\n Traceback (most recent call last):\n ...\n ValueError: Expecting a list of points but got []\n >>> _validate_input(1)\n Traceback (most recent call last):\n ...\n ValueError: Expecting an iterable object but got an non-iterable type 1\n \"\"\"\n\n if not hasattr(points, \"__iter__\"):\n msg = f\"Expecting an iterable object but got an non-iterable type {points}\"\n raise ValueError(msg)\n\n if not points:\n msg = f\"Expecting a list of points but got {points}\"\n raise ValueError(msg)\n\n return _construct_points(points)\n\n\ndef _det(a: Point, b: Point, c: Point) -> float:\n \"\"\"\n Computes the sign perpendicular distance of a 2d point c from a line segment\n ab. The sign indicates the direction of c relative to ab.\n A Positive value means c is above ab (to the left), while a negative value\n means c is below ab (to the right). 0 means all three points are on a straight line.\n\n As a side note, 0.5 * abs|det| is the area of triangle abc\n\n Parameters\n ----------\n a: point, the point on the left end of line segment ab\n b: point, the point on the right end of line segment ab\n c: point, the point for which the direction and location is desired.\n\n Returns\n --------\n det: float, abs(det) is the distance of c from ab. The sign\n indicates which side of line segment ab c is. det is computed as\n (a_xb_y + c_xa_y + b_xc_y) - (a_yb_x + c_ya_x + b_yc_x)\n\n Examples\n ----------\n >>> _det(Point(1, 1), Point(1, 2), Point(1, 5))\n 0.0\n >>> _det(Point(0, 0), Point(10, 0), Point(0, 10))\n 100.0\n >>> _det(Point(0, 0), Point(10, 0), Point(0, -10))\n -100.0\n \"\"\"\n\n det = (a.x * b.y + b.x * c.y + c.x * a.y) - (a.y * b.x + b.y * c.x + c.y * a.x)\n return det\n\n\ndef convex_hull_bf(points: list[Point]) -> list[Point]:\n \"\"\"\n Constructs the convex hull of a set of 2D points using a brute force algorithm.\n The algorithm basically considers all combinations of points (i, j) and uses the\n definition of convexity to determine whether (i, j) is part of the convex hull or\n not. (i, j) is part of the convex hull if and only iff there are no points on both\n sides of the line segment connecting the ij, and there is no point k such that k is\n on either end of the ij.\n\n Runtime: O(n^3) - definitely horrible\n\n Parameters\n ---------\n points: array-like of object of Points, lists or tuples.\n The set of 2d points for which the convex-hull is needed\n\n Returns\n ------\n convex_set: list, the convex-hull of points sorted in non-decreasing order.\n\n See Also\n --------\n convex_hull_recursive,\n\n Examples\n ---------\n >>> convex_hull_bf([[0, 0], [1, 0], [10, 1]])\n [(0.0, 0.0), (1.0, 0.0), (10.0, 1.0)]\n >>> convex_hull_bf([[0, 0], [1, 0], [10, 0]])\n [(0.0, 0.0), (10.0, 0.0)]\n >>> convex_hull_bf([[-1, 1],[-1, -1], [0, 0], [0.5, 0.5], [1, -1], [1, 1],\n ... [-0.75, 1]])\n [(-1.0, -1.0), (-1.0, 1.0), (1.0, -1.0), (1.0, 1.0)]\n >>> convex_hull_bf([(0, 3), (2, 2), (1, 1), (2, 1), (3, 0), (0, 0), (3, 3),\n ... (2, -1), (2, -4), (1, -3)])\n [(0.0, 0.0), (0.0, 3.0), (1.0, -3.0), (2.0, -4.0), (3.0, 0.0), (3.0, 3.0)]\n \"\"\"\n\n points = sorted(_validate_input(points))\n n = len(points)\n convex_set = set()\n\n for i in range(n - 1):\n for j in range(i + 1, n):\n points_left_of_ij = points_right_of_ij = False\n ij_part_of_convex_hull = True\n for k in range(n):\n if k not in {i, j}:\n det_k = _det(points[i], points[j], points[k])\n\n if det_k > 0:\n points_left_of_ij = True\n elif det_k < 0:\n points_right_of_ij = True\n else:\n # point[i], point[j], point[k] all lie on a straight line\n # if point[k] is to the left of point[i] or it's to the\n # right of point[j], then point[i], point[j] cannot be\n # part of the convex hull of A\n if points[k] < points[i] or points[k] > points[j]:\n ij_part_of_convex_hull = False\n break\n\n if points_left_of_ij and points_right_of_ij:\n ij_part_of_convex_hull = False\n break\n\n if ij_part_of_convex_hull:\n convex_set.update([points[i], points[j]])\n\n return sorted(convex_set)\n\n\ndef convex_hull_recursive(points: list[Point]) -> list[Point]:\n \"\"\"\n Constructs the convex hull of a set of 2D points using a divide-and-conquer strategy\n The algorithm exploits the geometric properties of the problem by repeatedly\n partitioning the set of points into smaller hulls, and finding the convex hull of\n these smaller hulls. The union of the convex hull from smaller hulls is the\n solution to the convex hull of the larger problem.\n\n Parameter\n ---------\n points: array-like of object of Points, lists or tuples.\n The set of 2d points for which the convex-hull is needed\n\n Runtime: O(n log n)\n\n Returns\n -------\n convex_set: list, the convex-hull of points sorted in non-decreasing order.\n\n Examples\n ---------\n >>> convex_hull_recursive([[0, 0], [1, 0], [10, 1]])\n [(0.0, 0.0), (1.0, 0.0), (10.0, 1.0)]\n >>> convex_hull_recursive([[0, 0], [1, 0], [10, 0]])\n [(0.0, 0.0), (10.0, 0.0)]\n >>> convex_hull_recursive([[-1, 1],[-1, -1], [0, 0], [0.5, 0.5], [1, -1], [1, 1],\n ... [-0.75, 1]])\n [(-1.0, -1.0), (-1.0, 1.0), (1.0, -1.0), (1.0, 1.0)]\n >>> convex_hull_recursive([(0, 3), (2, 2), (1, 1), (2, 1), (3, 0), (0, 0), (3, 3),\n ... (2, -1), (2, -4), (1, -3)])\n [(0.0, 0.0), (0.0, 3.0), (1.0, -3.0), (2.0, -4.0), (3.0, 0.0), (3.0, 3.0)]\n\n \"\"\"\n points = sorted(_validate_input(points))\n n = len(points)\n\n # divide all the points into an upper hull and a lower hull\n # the left most point and the right most point are definitely\n # members of the convex hull by definition.\n # use these two anchors to divide all the points into two hulls,\n # an upper hull and a lower hull.\n\n # all points to the left (above) the line joining the extreme points belong to the\n # upper hull\n # all points to the right (below) the line joining the extreme points below to the\n # lower hull\n # ignore all points on the line joining the extreme points since they cannot be\n # part of the convex hull\n\n left_most_point = points[0]\n right_most_point = points[n - 1]\n\n convex_set = {left_most_point, right_most_point}\n upper_hull = []\n lower_hull = []\n\n for i in range(1, n - 1):\n det = _det(left_most_point, right_most_point, points[i])\n\n if det > 0:\n upper_hull.append(points[i])\n elif det < 0:\n lower_hull.append(points[i])\n\n _construct_hull(upper_hull, left_most_point, right_most_point, convex_set)\n _construct_hull(lower_hull, right_most_point, left_most_point, convex_set)\n\n return sorted(convex_set)\n\n\ndef _construct_hull(\n points: list[Point], left: Point, right: Point, convex_set: set[Point]\n) -> None:\n \"\"\"\n\n Parameters\n ---------\n points: list or None, the hull of points from which to choose the next convex-hull\n point\n left: Point, the point to the left of line segment joining left and right\n right: The point to the right of the line segment joining left and right\n convex_set: set, the current convex-hull. The state of convex-set gets updated by\n this function\n\n Note\n ----\n For the line segment 'ab', 'a' is on the left and 'b' on the right.\n but the reverse is true for the line segment 'ba'.\n\n Returns\n -------\n Nothing, only updates the state of convex-set\n \"\"\"\n if points:\n extreme_point = None\n extreme_point_distance = float(\"-inf\")\n candidate_points = []\n\n for p in points:\n det = _det(left, right, p)\n\n if det > 0:\n candidate_points.append(p)\n\n if det > extreme_point_distance:\n extreme_point_distance = det\n extreme_point = p\n\n if extreme_point:\n _construct_hull(candidate_points, left, extreme_point, convex_set)\n convex_set.add(extreme_point)\n _construct_hull(candidate_points, extreme_point, right, convex_set)\n\n\ndef convex_hull_melkman(points: list[Point]) -> list[Point]:\n \"\"\"\n Constructs the convex hull of a set of 2D points using the melkman algorithm.\n The algorithm works by iteratively inserting points of a simple polygonal chain\n (meaning that no line segments between two consecutive points cross each other).\n Sorting the points yields such a polygonal chain.\n\n For a detailed description, see http:\/\/cgm.cs.mcgill.ca\/~athens\/cs601\/Melkman.html\n\n Runtime: O(n log n) - O(n) if points are already sorted in the input\n\n Parameters\n ---------\n points: array-like of object of Points, lists or tuples.\n The set of 2d points for which the convex-hull is needed\n\n Returns\n ------\n convex_set: list, the convex-hull of points sorted in non-decreasing order.\n\n See Also\n --------\n\n Examples\n ---------\n >>> convex_hull_melkman([[0, 0], [1, 0], [10, 1]])\n [(0.0, 0.0), (1.0, 0.0), (10.0, 1.0)]\n >>> convex_hull_melkman([[0, 0], [1, 0], [10, 0]])\n [(0.0, 0.0), (10.0, 0.0)]\n >>> convex_hull_melkman([[-1, 1],[-1, -1], [0, 0], [0.5, 0.5], [1, -1], [1, 1],\n ... [-0.75, 1]])\n [(-1.0, -1.0), (-1.0, 1.0), (1.0, -1.0), (1.0, 1.0)]\n >>> convex_hull_melkman([(0, 3), (2, 2), (1, 1), (2, 1), (3, 0), (0, 0), (3, 3),\n ... (2, -1), (2, -4), (1, -3)])\n [(0.0, 0.0), (0.0, 3.0), (1.0, -3.0), (2.0, -4.0), (3.0, 0.0), (3.0, 3.0)]\n \"\"\"\n points = sorted(_validate_input(points))\n n = len(points)\n\n convex_hull = points[:2]\n for i in range(2, n):\n det = _det(convex_hull[1], convex_hull[0], points[i])\n if det > 0:\n convex_hull.insert(0, points[i])\n break\n elif det < 0:\n convex_hull.append(points[i])\n break\n else:\n convex_hull[1] = points[i]\n i += 1\n\n for j in range(i, n):\n if (\n _det(convex_hull[0], convex_hull[-1], points[j]) > 0\n and _det(convex_hull[-1], convex_hull[0], points[1]) < 0\n ):\n # The point lies within the convex hull\n continue\n\n convex_hull.insert(0, points[j])\n convex_hull.append(points[j])\n while _det(convex_hull[0], convex_hull[1], convex_hull[2]) >= 0:\n del convex_hull[1]\n while _det(convex_hull[-1], convex_hull[-2], convex_hull[-3]) <= 0:\n del convex_hull[-2]\n\n # `convex_hull` is contains the convex hull in circular order\n return sorted(convex_hull[1:] if len(convex_hull) > 3 else convex_hull)\n\n\ndef main():\n points = [\n (0, 3),\n (2, 2),\n (1, 1),\n (2, 1),\n (3, 0),\n (0, 0),\n (3, 3),\n (2, -1),\n (2, -4),\n (1, -3),\n ]\n # the convex set of points is\n # [(0, 0), (0, 3), (1, -3), (2, -4), (3, 0), (3, 3)]\n results_bf = convex_hull_bf(points)\n\n results_recursive = convex_hull_recursive(points)\n assert results_bf == results_recursive\n\n results_melkman = convex_hull_melkman(points)\n assert results_bf == results_melkman\n\n print(results_bf)\n\n\nif __name__ == \"__main__\":\n main()\n"} +{"Prompt":"Heap's algorithm returns the list of all permutations possible from a list. It minimizes movement by generating each permutation from the previous one by swapping only two elements. More information: https:en.wikipedia.orgwikiHeap27salgorithm. Pure python implementation of the Heap's algorithm recursive version, returning all permutations of a list. heaps heaps0 0, heaps1, 1 1, 1, 1, 1 heaps1, 2, 3 1, 2, 3, 2, 1, 3, 3, 1, 2, 1, 3, 2, 2, 3, 1, 3, 2, 1 from itertools import permutations sortedheaps1,2,3 sortedpermutations1,2,3 True allsortedheapsx sortedpermutationsx ... for x in , 0, 1, 1, 1, 2, 3 True","Completions":"def heaps(arr: list) -> list:\n \"\"\"\n Pure python implementation of the Heap's algorithm (recursive version),\n returning all permutations of a list.\n >>> heaps([])\n [()]\n >>> heaps([0])\n [(0,)]\n >>> heaps([-1, 1])\n [(-1, 1), (1, -1)]\n >>> heaps([1, 2, 3])\n [(1, 2, 3), (2, 1, 3), (3, 1, 2), (1, 3, 2), (2, 3, 1), (3, 2, 1)]\n >>> from itertools import permutations\n >>> sorted(heaps([1,2,3])) == sorted(permutations([1,2,3]))\n True\n >>> all(sorted(heaps(x)) == sorted(permutations(x))\n ... for x in ([], [0], [-1, 1], [1, 2, 3]))\n True\n \"\"\"\n\n if len(arr) <= 1:\n return [tuple(arr)]\n\n res = []\n\n def generate(k: int, arr: list):\n if k == 1:\n res.append(tuple(arr[:]))\n return\n\n generate(k - 1, arr)\n\n for i in range(k - 1):\n if k % 2 == 0: # k is even\n arr[i], arr[k - 1] = arr[k - 1], arr[i]\n else: # k is odd\n arr[0], arr[k - 1] = arr[k - 1], arr[0]\n generate(k - 1, arr)\n\n generate(len(arr), arr)\n return res\n\n\nif __name__ == \"__main__\":\n user_input = input(\"Enter numbers separated by a comma:\\n\").strip()\n arr = [int(item) for item in user_input.split(\",\")]\n print(heaps(arr))\n"} +{"Prompt":"Heap's iterative algorithm returns the list of all permutations possible from a list. It minimizes movement by generating each permutation from the previous one by swapping only two elements. More information: https:en.wikipedia.orgwikiHeap27salgorithm. Pure python implementation of the iterative Heap's algorithm, returning all permutations of a list. heaps heaps0 0, heaps1, 1 1, 1, 1, 1 heaps1, 2, 3 1, 2, 3, 2, 1, 3, 3, 1, 2, 1, 3, 2, 2, 3, 1, 3, 2, 1 from itertools import permutations sortedheaps1,2,3 sortedpermutations1,2,3 True allsortedheapsx sortedpermutationsx ... for x in , 0, 1, 1, 1, 2, 3 True","Completions":"def heaps(arr: list) -> list:\n \"\"\"\n Pure python implementation of the iterative Heap's algorithm,\n returning all permutations of a list.\n >>> heaps([])\n [()]\n >>> heaps([0])\n [(0,)]\n >>> heaps([-1, 1])\n [(-1, 1), (1, -1)]\n >>> heaps([1, 2, 3])\n [(1, 2, 3), (2, 1, 3), (3, 1, 2), (1, 3, 2), (2, 3, 1), (3, 2, 1)]\n >>> from itertools import permutations\n >>> sorted(heaps([1,2,3])) == sorted(permutations([1,2,3]))\n True\n >>> all(sorted(heaps(x)) == sorted(permutations(x))\n ... for x in ([], [0], [-1, 1], [1, 2, 3]))\n True\n \"\"\"\n\n if len(arr) <= 1:\n return [tuple(arr)]\n\n res = []\n\n def generate(n: int, arr: list):\n c = [0] * n\n res.append(tuple(arr))\n\n i = 0\n while i < n:\n if c[i] < i:\n if i % 2 == 0:\n arr[0], arr[i] = arr[i], arr[0]\n else:\n arr[c[i]], arr[i] = arr[i], arr[c[i]]\n res.append(tuple(arr))\n c[i] += 1\n i = 0\n else:\n c[i] = 0\n i += 1\n\n generate(len(arr), arr)\n return res\n\n\nif __name__ == \"__main__\":\n user_input = input(\"Enter numbers separated by a comma:\\n\").strip()\n arr = [int(item) for item in user_input.split(\",\")]\n print(heaps(arr))\n"} +{"Prompt":"Given an arraylike data structure A1..n, how many pairs i, j for all 1 i j n such that Ai Aj? These pairs are called inversions. Counting the number of such inversions in an arraylike object is the important. Among other things, counting inversions can help us determine how close a given array is to being sorted. In this implementation, I provide two algorithms, a divideandconquer algorithm which runs in nlogn and the bruteforce n2 algorithm. Counts the number of inversions using a naive bruteforce algorithm Parameters arr: arr: arraylike, the list containing the items for which the number of inversions is desired. The elements of arr must be comparable. Returns numinversions: The total number of inversions in arr Examples countinversionsbf1, 4, 2, 4, 1 4 countinversionsbf1, 1, 2, 4, 4 0 countinversionsbf 0 Counts the number of inversions using a divideandconquer algorithm Parameters arr: arraylike, the list containing the items for which the number of inversions is desired. The elements of arr must be comparable. Returns C: a sorted copy of arr. numinversions: int, the total number of inversions in 'arr' Examples countinversionsrecursive1, 4, 2, 4, 1 1, 1, 2, 4, 4, 4 countinversionsrecursive1, 1, 2, 4, 4 1, 1, 2, 4, 4, 0 countinversionsrecursive , 0 Counts the inversions across two sorted arrays. And combine the two arrays into one sorted array For all 1 ilenP and for all 1 j lenQ, if Pi Qj, then i, j is a cross inversion Parameters P: arraylike, sorted in nondecreasing order Q: arraylike, sorted in nondecreasing order Returns R: arraylike, a sorted array of the elements of P and Q numinversion: int, the number of inversions across P and Q Examples countcrossinversions1, 2, 3, 0, 2, 5 0, 1, 2, 2, 3, 5, 4 countcrossinversions1, 2, 3, 3, 4, 5 1, 2, 3, 3, 4, 5, 0 if P1 Qj, then Pk Qk for all i k lenP These are all inversions. The claim emerges from the property that P is sorted. this arr has 8 inversions: 10, 2, 10, 1, 10, 5, 10, 5, 10, 2, 2, 1, 5, 2, 5, 2 testing an array with zero inversion a sorted arr1 an empty list should also have zero inversions","Completions":"def count_inversions_bf(arr):\n \"\"\"\n Counts the number of inversions using a naive brute-force algorithm\n Parameters\n ----------\n arr: arr: array-like, the list containing the items for which the number\n of inversions is desired. The elements of `arr` must be comparable.\n Returns\n -------\n num_inversions: The total number of inversions in `arr`\n Examples\n ---------\n >>> count_inversions_bf([1, 4, 2, 4, 1])\n 4\n >>> count_inversions_bf([1, 1, 2, 4, 4])\n 0\n >>> count_inversions_bf([])\n 0\n \"\"\"\n\n num_inversions = 0\n n = len(arr)\n\n for i in range(n - 1):\n for j in range(i + 1, n):\n if arr[i] > arr[j]:\n num_inversions += 1\n\n return num_inversions\n\n\ndef count_inversions_recursive(arr):\n \"\"\"\n Counts the number of inversions using a divide-and-conquer algorithm\n Parameters\n -----------\n arr: array-like, the list containing the items for which the number\n of inversions is desired. The elements of `arr` must be comparable.\n Returns\n -------\n C: a sorted copy of `arr`.\n num_inversions: int, the total number of inversions in 'arr'\n Examples\n --------\n >>> count_inversions_recursive([1, 4, 2, 4, 1])\n ([1, 1, 2, 4, 4], 4)\n >>> count_inversions_recursive([1, 1, 2, 4, 4])\n ([1, 1, 2, 4, 4], 0)\n >>> count_inversions_recursive([])\n ([], 0)\n \"\"\"\n if len(arr) <= 1:\n return arr, 0\n mid = len(arr) \/\/ 2\n p = arr[0:mid]\n q = arr[mid:]\n\n a, inversion_p = count_inversions_recursive(p)\n b, inversions_q = count_inversions_recursive(q)\n c, cross_inversions = _count_cross_inversions(a, b)\n\n num_inversions = inversion_p + inversions_q + cross_inversions\n return c, num_inversions\n\n\ndef _count_cross_inversions(p, q):\n \"\"\"\n Counts the inversions across two sorted arrays.\n And combine the two arrays into one sorted array\n For all 1<= i<=len(P) and for all 1 <= j <= len(Q),\n if P[i] > Q[j], then (i, j) is a cross inversion\n Parameters\n ----------\n P: array-like, sorted in non-decreasing order\n Q: array-like, sorted in non-decreasing order\n Returns\n ------\n R: array-like, a sorted array of the elements of `P` and `Q`\n num_inversion: int, the number of inversions across `P` and `Q`\n Examples\n --------\n >>> _count_cross_inversions([1, 2, 3], [0, 2, 5])\n ([0, 1, 2, 2, 3, 5], 4)\n >>> _count_cross_inversions([1, 2, 3], [3, 4, 5])\n ([1, 2, 3, 3, 4, 5], 0)\n \"\"\"\n\n r = []\n i = j = num_inversion = 0\n while i < len(p) and j < len(q):\n if p[i] > q[j]:\n # if P[1] > Q[j], then P[k] > Q[k] for all i < k <= len(P)\n # These are all inversions. The claim emerges from the\n # property that P is sorted.\n num_inversion += len(p) - i\n r.append(q[j])\n j += 1\n else:\n r.append(p[i])\n i += 1\n\n if i < len(p):\n r.extend(p[i:])\n else:\n r.extend(q[j:])\n\n return r, num_inversion\n\n\ndef main():\n arr_1 = [10, 2, 1, 5, 5, 2, 11]\n\n # this arr has 8 inversions:\n # (10, 2), (10, 1), (10, 5), (10, 5), (10, 2), (2, 1), (5, 2), (5, 2)\n\n num_inversions_bf = count_inversions_bf(arr_1)\n _, num_inversions_recursive = count_inversions_recursive(arr_1)\n\n assert num_inversions_bf == num_inversions_recursive == 8\n\n print(\"number of inversions = \", num_inversions_bf)\n\n # testing an array with zero inversion (a sorted arr_1)\n\n arr_1.sort()\n num_inversions_bf = count_inversions_bf(arr_1)\n _, num_inversions_recursive = count_inversions_recursive(arr_1)\n\n assert num_inversions_bf == num_inversions_recursive == 0\n print(\"number of inversions = \", num_inversions_bf)\n\n # an empty list should also have zero inversions\n arr_1 = []\n num_inversions_bf = count_inversions_bf(arr_1)\n _, num_inversions_recursive = count_inversions_recursive(arr_1)\n\n assert num_inversions_bf == num_inversions_recursive == 0\n print(\"number of inversions = \", num_inversions_bf)\n\n\nif __name__ == \"__main__\":\n main()\n"} +{"Prompt":"Find the kth smallest element in linear time using divide and conquer. Recall we can do this trivially in Onlogn time. Sort the list and access kth element in constant time. This is a divide and conquer algorithm that can find a solution in On time. For more information of this algorithm: https:web.stanford.educlassarchivecscs161cs161.1138lectures08Small08.pdf Choose a random pivot for the list. We can use a more sophisticated algorithm here, such as the medianofmedians algorithm. Return the kth smallest number in lst. kthnumber2, 1, 3, 4, 5, 3 3 kthnumber2, 1, 3, 4, 5, 1 1 kthnumber2, 1, 3, 4, 5, 5 5 kthnumber3, 2, 5, 6, 7, 8, 2 3 kthnumber25, 21, 98, 100, 76, 22, 43, 60, 89, 87, 4 43 pick a pivot and separate into list based on pivot. partition based on pivot linear time if we get lucky, pivot might be the element we want. we can easily see this: small elements smaller than k pivot kth element big elements larger than k pivot is in elements bigger than k pivot is in elements smaller than k","Completions":"from __future__ import annotations\n\nfrom random import choice\n\n\ndef random_pivot(lst):\n \"\"\"\n Choose a random pivot for the list.\n We can use a more sophisticated algorithm here, such as the median-of-medians\n algorithm.\n \"\"\"\n return choice(lst)\n\n\ndef kth_number(lst: list[int], k: int) -> int:\n \"\"\"\n Return the kth smallest number in lst.\n >>> kth_number([2, 1, 3, 4, 5], 3)\n 3\n >>> kth_number([2, 1, 3, 4, 5], 1)\n 1\n >>> kth_number([2, 1, 3, 4, 5], 5)\n 5\n >>> kth_number([3, 2, 5, 6, 7, 8], 2)\n 3\n >>> kth_number([25, 21, 98, 100, 76, 22, 43, 60, 89, 87], 4)\n 43\n \"\"\"\n # pick a pivot and separate into list based on pivot.\n pivot = random_pivot(lst)\n\n # partition based on pivot\n # linear time\n small = [e for e in lst if e < pivot]\n big = [e for e in lst if e > pivot]\n\n # if we get lucky, pivot might be the element we want.\n # we can easily see this:\n # small (elements smaller than k)\n # + pivot (kth element)\n # + big (elements larger than k)\n if len(small) == k - 1:\n return pivot\n # pivot is in elements bigger than k\n elif len(small) < k - 1:\n return kth_number(big, k - len(small) - 1)\n # pivot is in elements smaller than k\n else:\n return kth_number(small, k)\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"We are given an array A1..n of integers, n 1. We want to find a pair of indices i, j such that 1 i j n and Aj Ai is as large as possible. Explanation: https:www.geeksforgeeks.orgmaximumdifferencebetweentwoelements maxdifference5, 11, 2, 1, 7, 9, 0, 7 1, 9 base case split A into half. 2 sub problems, 12 of original size. get min of first and max of second linear time 3 cases, either small1, big1, minfirst, maxsecond, small2, big2 constant comparisons","Completions":"def max_difference(a: list[int]) -> tuple[int, int]:\n \"\"\"\n We are given an array A[1..n] of integers, n >= 1. We want to\n find a pair of indices (i, j) such that\n 1 <= i <= j <= n and A[j] - A[i] is as large as possible.\n\n Explanation:\n https:\/\/www.geeksforgeeks.org\/maximum-difference-between-two-elements\/\n\n >>> max_difference([5, 11, 2, 1, 7, 9, 0, 7])\n (1, 9)\n \"\"\"\n # base case\n if len(a) == 1:\n return a[0], a[0]\n else:\n # split A into half.\n first = a[: len(a) \/\/ 2]\n second = a[len(a) \/\/ 2 :]\n\n # 2 sub problems, 1\/2 of original size.\n small1, big1 = max_difference(first)\n small2, big2 = max_difference(second)\n\n # get min of first and max of second\n # linear time\n min_first = min(first)\n max_second = max(second)\n\n # 3 cases, either (small1, big1),\n # (min_first, max_second), (small2, big2)\n # constant comparisons\n if big2 - small2 > max_second - min_first and big2 - small2 > big1 - small1:\n return small2, big2\n elif big1 - small1 > max_second - min_first:\n return small1, big1\n else:\n return min_first, max_second\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"The maximum subarray problem is the task of finding the continuous subarray that has the maximum sum within a given array of numbers. For example, given the array 2, 1, 3, 4, 1, 2, 1, 5, 4, the contiguous subarray with the maximum sum is 4, 1, 2, 1, which has a sum of 6. This divideandconquer algorithm finds the maximum subarray in On log n time. Solves the maximum subarray problem using divide and conquer. :param arr: the given array of numbers :param low: the start index :param high: the end index :return: the start index of the maximum subarray, the end index of the maximum subarray, and the maximum subarray sum nums 2, 1, 3, 4, 1, 2, 1, 5, 4 maxsubarraynums, 0, lennums 1 3, 6, 6 nums 2, 8, 9 maxsubarraynums, 0, lennums 1 0, 2, 19 nums 0, 0 maxsubarraynums, 0, lennums 1 0, 0, 0 nums 1.0, 0.0, 1.0 maxsubarraynums, 0, lennums 1 2, 2, 1.0 nums 2, 3, 1, 4, 6 maxsubarraynums, 0, lennums 1 2, 2, 1 maxsubarray, 0, 0 None, None, 0 A random simulation of this algorithm.","Completions":"from __future__ import annotations\n\nimport time\nfrom collections.abc import Sequence\nfrom random import randint\n\nfrom matplotlib import pyplot as plt\n\n\ndef max_subarray(\n arr: Sequence[float], low: int, high: int\n) -> tuple[int | None, int | None, float]:\n \"\"\"\n Solves the maximum subarray problem using divide and conquer.\n :param arr: the given array of numbers\n :param low: the start index\n :param high: the end index\n :return: the start index of the maximum subarray, the end index of the\n maximum subarray, and the maximum subarray sum\n\n >>> nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4]\n >>> max_subarray(nums, 0, len(nums) - 1)\n (3, 6, 6)\n >>> nums = [2, 8, 9]\n >>> max_subarray(nums, 0, len(nums) - 1)\n (0, 2, 19)\n >>> nums = [0, 0]\n >>> max_subarray(nums, 0, len(nums) - 1)\n (0, 0, 0)\n >>> nums = [-1.0, 0.0, 1.0]\n >>> max_subarray(nums, 0, len(nums) - 1)\n (2, 2, 1.0)\n >>> nums = [-2, -3, -1, -4, -6]\n >>> max_subarray(nums, 0, len(nums) - 1)\n (2, 2, -1)\n >>> max_subarray([], 0, 0)\n (None, None, 0)\n \"\"\"\n if not arr:\n return None, None, 0\n if low == high:\n return low, high, arr[low]\n\n mid = (low + high) \/\/ 2\n left_low, left_high, left_sum = max_subarray(arr, low, mid)\n right_low, right_high, right_sum = max_subarray(arr, mid + 1, high)\n cross_left, cross_right, cross_sum = max_cross_sum(arr, low, mid, high)\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 return cross_left, cross_right, cross_sum\n\n\ndef max_cross_sum(\n arr: Sequence[float], low: int, mid: int, high: int\n) -> tuple[int, int, float]:\n left_sum, max_left = float(\"-inf\"), -1\n right_sum, max_right = float(\"-inf\"), -1\n\n summ: int | float = 0\n for i in range(mid, low - 1, -1):\n summ += arr[i]\n if summ > left_sum:\n left_sum = summ\n max_left = i\n\n summ = 0\n for i in range(mid + 1, high + 1):\n summ += arr[i]\n if summ > right_sum:\n right_sum = summ\n max_right = i\n\n return max_left, max_right, (left_sum + right_sum)\n\n\ndef time_max_subarray(input_size: int) -> float:\n arr = [randint(1, input_size) for _ in range(input_size)]\n start = time.time()\n max_subarray(arr, 0, input_size - 1)\n end = time.time()\n return end - start\n\n\ndef plot_runtimes() -> None:\n input_sizes = [10, 100, 1000, 10000, 50000, 100000, 200000, 300000, 400000, 500000]\n runtimes = [time_max_subarray(input_size) for input_size in input_sizes]\n print(\"No of Inputs\\t\\tTime Taken\")\n for input_size, runtime in zip(input_sizes, runtimes):\n print(input_size, \"\\t\\t\", runtime)\n plt.plot(input_sizes, runtimes)\n plt.xlabel(\"Number of Inputs\")\n plt.ylabel(\"Time taken in seconds\")\n plt.show()\n\n\nif __name__ == \"__main__\":\n \"\"\"\n A random simulation of this algorithm.\n \"\"\"\n from doctest import testmod\n\n testmod()\n"} +{"Prompt":"Helper function for mergesort. lefthalf 2 righthalf 1 mergelefthalf, righthalf 2, 1 lefthalf 1,2,3 righthalf 4,5,6 mergelefthalf, righthalf 1, 2, 3, 4, 5, 6 lefthalf 2 righthalf 1 mergelefthalf, righthalf 2, 1 lefthalf 12, 15 righthalf 13, 14 mergelefthalf, righthalf 12, 13, 14, 15 lefthalf righthalf mergelefthalf, righthalf Returns a list of sorted array elements using merge sort. from random import shuffle array 2, 3, 10, 11, 99, 100000, 100, 200 shufflearray mergesortarray 200, 10, 2, 3, 11, 99, 100, 100000 shufflearray mergesortarray 200, 10, 2, 3, 11, 99, 100, 100000 array 200 mergesortarray 200 array 2, 3, 10, 11, 99, 100000, 100, 200 shufflearray sortedarray mergesortarray True array 2 mergesortarray 2 array mergesortarray array 10000000, 1, 1111111111, 101111111112, 9000002 sortedarray mergesortarray True the actual formula to calculate the middle element left right left 2 this avoids integer overflow in case of large N Split the array into halves till the array length becomes equal to One merge the arrays of single length returned by mergeSort function and pass them into the merge arrays function which merges the array","Completions":"from __future__ import annotations\n\n\ndef merge(left_half: list, right_half: list) -> list:\n \"\"\"Helper function for mergesort.\n\n >>> left_half = [-2]\n >>> right_half = [-1]\n >>> merge(left_half, right_half)\n [-2, -1]\n\n >>> left_half = [1,2,3]\n >>> right_half = [4,5,6]\n >>> merge(left_half, right_half)\n [1, 2, 3, 4, 5, 6]\n\n >>> left_half = [-2]\n >>> right_half = [-1]\n >>> merge(left_half, right_half)\n [-2, -1]\n\n >>> left_half = [12, 15]\n >>> right_half = [13, 14]\n >>> merge(left_half, right_half)\n [12, 13, 14, 15]\n\n >>> left_half = []\n >>> right_half = []\n >>> merge(left_half, right_half)\n []\n \"\"\"\n sorted_array = [None] * (len(right_half) + len(left_half))\n\n pointer1 = 0 # pointer to current index for left Half\n pointer2 = 0 # pointer to current index for the right Half\n index = 0 # pointer to current index for the sorted array Half\n\n while pointer1 < len(left_half) and pointer2 < len(right_half):\n if left_half[pointer1] < right_half[pointer2]:\n sorted_array[index] = left_half[pointer1]\n pointer1 += 1\n index += 1\n else:\n sorted_array[index] = right_half[pointer2]\n pointer2 += 1\n index += 1\n while pointer1 < len(left_half):\n sorted_array[index] = left_half[pointer1]\n pointer1 += 1\n index += 1\n\n while pointer2 < len(right_half):\n sorted_array[index] = right_half[pointer2]\n pointer2 += 1\n index += 1\n\n return sorted_array\n\n\ndef merge_sort(array: list) -> list:\n \"\"\"Returns a list of sorted array elements using merge sort.\n\n >>> from random import shuffle\n >>> array = [-2, 3, -10, 11, 99, 100000, 100, -200]\n >>> shuffle(array)\n >>> merge_sort(array)\n [-200, -10, -2, 3, 11, 99, 100, 100000]\n\n >>> shuffle(array)\n >>> merge_sort(array)\n [-200, -10, -2, 3, 11, 99, 100, 100000]\n\n >>> array = [-200]\n >>> merge_sort(array)\n [-200]\n\n >>> array = [-2, 3, -10, 11, 99, 100000, 100, -200]\n >>> shuffle(array)\n >>> sorted(array) == merge_sort(array)\n True\n\n >>> array = [-2]\n >>> merge_sort(array)\n [-2]\n\n >>> array = []\n >>> merge_sort(array)\n []\n\n >>> array = [10000000, 1, -1111111111, 101111111112, 9000002]\n >>> sorted(array) == merge_sort(array)\n True\n \"\"\"\n if len(array) <= 1:\n return array\n # the actual formula to calculate the middle element = left + (right - left) \/\/ 2\n # this avoids integer overflow in case of large N\n middle = 0 + (len(array) - 0) \/\/ 2\n\n # Split the array into halves till the array length becomes equal to One\n # merge the arrays of single length returned by mergeSort function and\n # pass them into the merge arrays function which merges the array\n left_half = array[:middle]\n right_half = array[middle:]\n\n return merge(merge_sort(left_half), merge_sort(right_half))\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Finding the peak of a unimodal list using divide and conquer. A unimodal array is defined as follows: array is increasing up to index p, then decreasing afterwards. for p 1 An obvious solution can be performed in On, to find the maximum of the array. From Kleinberg and Tardos. Algorithm Design. Addison Wesley 2006: Chapter 5 Solved Exercise 1 Return the peak value of lst. peak1, 2, 3, 4, 5, 4, 3, 2, 1 5 peak1, 10, 9, 8, 7, 6, 5, 4 10 peak1, 9, 8, 7 9 peak1, 2, 3, 4, 5, 6, 7, 0 7 peak1, 2, 3, 4, 3, 2, 1, 0, 1, 2 4 middle index choose the middle 3 elements if middle element is peak if increasing, recurse on right decreasing","Completions":"from __future__ import annotations\n\n\ndef peak(lst: list[int]) -> int:\n \"\"\"\n Return the peak value of `lst`.\n >>> peak([1, 2, 3, 4, 5, 4, 3, 2, 1])\n 5\n >>> peak([1, 10, 9, 8, 7, 6, 5, 4])\n 10\n >>> peak([1, 9, 8, 7])\n 9\n >>> peak([1, 2, 3, 4, 5, 6, 7, 0])\n 7\n >>> peak([1, 2, 3, 4, 3, 2, 1, 0, -1, -2])\n 4\n \"\"\"\n # middle index\n m = len(lst) \/\/ 2\n\n # choose the middle 3 elements\n three = lst[m - 1 : m + 2]\n\n # if middle element is peak\n if three[1] > three[0] and three[1] > three[2]:\n return three[1]\n\n # if increasing, recurse on right\n elif three[0] < three[2]:\n if len(lst[:m]) == 2:\n m -= 1\n return peak(lst[m:])\n\n # decreasing\n else:\n if len(lst[:m]) == 2:\n m += 1\n return peak(lst[:m])\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Function using divide and conquer to calculate ab. It only works for integer a,b. power4,6 4096 power2,3 8 power2,3 8 power2,3 0.125 power2,3 0.125","Completions":"def actual_power(a: int, b: int):\n \"\"\"\n Function using divide and conquer to calculate a^b.\n It only works for integer a,b.\n \"\"\"\n if b == 0:\n return 1\n if (b % 2) == 0:\n return actual_power(a, int(b \/ 2)) * actual_power(a, int(b \/ 2))\n else:\n return a * actual_power(a, int(b \/ 2)) * actual_power(a, int(b \/ 2))\n\n\ndef power(a: int, b: int) -> float:\n \"\"\"\n >>> power(4,6)\n 4096\n >>> power(2,3)\n 8\n >>> power(-2,3)\n -8\n >>> power(2,-3)\n 0.125\n >>> power(-2,-3)\n -0.125\n \"\"\"\n if b < 0:\n return 1 \/ actual_power(a, b)\n return actual_power(a, b)\n\n\nif __name__ == \"__main__\":\n print(power(-2, -3))\n"} +{"Prompt":"Multiplication only for 2x2 matrices Given an even length matrix, returns the topleft, topright, botleft, botright quadrant. splitmatrix4,3,2,4,2,3,1,1,6,5,4,3,8,4,1,6 4, 3, 2, 3, 2, 4, 1, 1, 6, 5, 8, 4, 4, 3, 1, 6 splitmatrix ... 4,3,2,4,4,3,2,4,2,3,1,1,2,3,1,1,6,5,4,3,6,5,4,3,8,4,1,6,8,4,1,6, ... 4,3,2,4,4,3,2,4,2,3,1,1,2,3,1,1,6,5,4,3,6,5,4,3,8,4,1,6,8,4,1,6 ... doctest: NORMALIZEWHITESPACE 4, 3, 2, 4, 2, 3, 1, 1, 6, 5, 4, 3, 8, 4, 1, 6, 4, 3, 2, 4, 2, 3, 1, 1, 6, 5, 4, 3, 8, 4, 1, 6, 4, 3, 2, 4, 2, 3, 1, 1, 6, 5, 4, 3, 8, 4, 1, 6, 4, 3, 2, 4, 2, 3, 1, 1, 6, 5, 4, 3, 8, 4, 1, 6 Recursive function to calculate the product of two matrices, using the Strassen Algorithm. It only supports square matrices of any size that is a power of 2. construct the new matrix from our 4 quadrants strassen2,1,3,3,4,6,1,4,2,7,6,7, 4,2,3,4,2,1,1,1,8,6,4,2 34, 23, 19, 15, 68, 46, 37, 28, 28, 18, 15, 12, 96, 62, 55, 48 strassen3,7,5,6,9,1,5,3,7,8,1,4,4,5,7, 2,4,5,2,1,7,5,5,7,8 139, 163, 121, 134, 100, 121 Adding zeros to the matrices to convert them both into square matrices of equal dimensions that are a power of 2 Removing the additional zeros","Completions":"from __future__ import annotations\n\nimport math\n\n\ndef default_matrix_multiplication(a: list, b: list) -> list:\n \"\"\"\n Multiplication only for 2x2 matrices\n \"\"\"\n if len(a) != 2 or len(a[0]) != 2 or len(b) != 2 or len(b[0]) != 2:\n raise Exception(\"Matrices are not 2x2\")\n new_matrix = [\n [a[0][0] * b[0][0] + a[0][1] * b[1][0], a[0][0] * b[0][1] + a[0][1] * b[1][1]],\n [a[1][0] * b[0][0] + a[1][1] * b[1][0], a[1][0] * b[0][1] + a[1][1] * b[1][1]],\n ]\n return new_matrix\n\n\ndef matrix_addition(matrix_a: list, matrix_b: list):\n return [\n [matrix_a[row][col] + matrix_b[row][col] for col in range(len(matrix_a[row]))]\n for row in range(len(matrix_a))\n ]\n\n\ndef matrix_subtraction(matrix_a: list, matrix_b: list):\n return [\n [matrix_a[row][col] - matrix_b[row][col] for col in range(len(matrix_a[row]))]\n for row in range(len(matrix_a))\n ]\n\n\ndef split_matrix(a: list) -> tuple[list, list, list, list]:\n \"\"\"\n Given an even length matrix, returns the top_left, top_right, bot_left, bot_right\n quadrant.\n\n >>> split_matrix([[4,3,2,4],[2,3,1,1],[6,5,4,3],[8,4,1,6]])\n ([[4, 3], [2, 3]], [[2, 4], [1, 1]], [[6, 5], [8, 4]], [[4, 3], [1, 6]])\n >>> split_matrix([\n ... [4,3,2,4,4,3,2,4],[2,3,1,1,2,3,1,1],[6,5,4,3,6,5,4,3],[8,4,1,6,8,4,1,6],\n ... [4,3,2,4,4,3,2,4],[2,3,1,1,2,3,1,1],[6,5,4,3,6,5,4,3],[8,4,1,6,8,4,1,6]\n ... ]) # doctest: +NORMALIZE_WHITESPACE\n ([[4, 3, 2, 4], [2, 3, 1, 1], [6, 5, 4, 3], [8, 4, 1, 6]], [[4, 3, 2, 4],\n [2, 3, 1, 1], [6, 5, 4, 3], [8, 4, 1, 6]], [[4, 3, 2, 4], [2, 3, 1, 1],\n [6, 5, 4, 3], [8, 4, 1, 6]], [[4, 3, 2, 4], [2, 3, 1, 1], [6, 5, 4, 3],\n [8, 4, 1, 6]])\n \"\"\"\n if len(a) % 2 != 0 or len(a[0]) % 2 != 0:\n raise Exception(\"Odd matrices are not supported!\")\n\n matrix_length = len(a)\n mid = matrix_length \/\/ 2\n\n top_right = [[a[i][j] for j in range(mid, matrix_length)] for i in range(mid)]\n bot_right = [\n [a[i][j] for j in range(mid, matrix_length)] for i in range(mid, matrix_length)\n ]\n\n top_left = [[a[i][j] for j in range(mid)] for i in range(mid)]\n bot_left = [[a[i][j] for j in range(mid)] for i in range(mid, matrix_length)]\n\n return top_left, top_right, bot_left, bot_right\n\n\ndef matrix_dimensions(matrix: list) -> tuple[int, int]:\n return len(matrix), len(matrix[0])\n\n\ndef print_matrix(matrix: list) -> None:\n print(\"\\n\".join(str(line) for line in matrix))\n\n\ndef actual_strassen(matrix_a: list, matrix_b: list) -> list:\n \"\"\"\n Recursive function to calculate the product of two matrices, using the Strassen\n Algorithm. It only supports square matrices of any size that is a power of 2.\n \"\"\"\n if matrix_dimensions(matrix_a) == (2, 2):\n return default_matrix_multiplication(matrix_a, matrix_b)\n\n a, b, c, d = split_matrix(matrix_a)\n e, f, g, h = split_matrix(matrix_b)\n\n t1 = actual_strassen(a, matrix_subtraction(f, h))\n t2 = actual_strassen(matrix_addition(a, b), h)\n t3 = actual_strassen(matrix_addition(c, d), e)\n t4 = actual_strassen(d, matrix_subtraction(g, e))\n t5 = actual_strassen(matrix_addition(a, d), matrix_addition(e, h))\n t6 = actual_strassen(matrix_subtraction(b, d), matrix_addition(g, h))\n t7 = actual_strassen(matrix_subtraction(a, c), matrix_addition(e, f))\n\n top_left = matrix_addition(matrix_subtraction(matrix_addition(t5, t4), t2), t6)\n top_right = matrix_addition(t1, t2)\n bot_left = matrix_addition(t3, t4)\n bot_right = matrix_subtraction(matrix_subtraction(matrix_addition(t1, t5), t3), t7)\n\n # construct the new matrix from our 4 quadrants\n new_matrix = []\n for i in range(len(top_right)):\n new_matrix.append(top_left[i] + top_right[i])\n for i in range(len(bot_right)):\n new_matrix.append(bot_left[i] + bot_right[i])\n return new_matrix\n\n\ndef strassen(matrix1: list, matrix2: list) -> list:\n \"\"\"\n >>> strassen([[2,1,3],[3,4,6],[1,4,2],[7,6,7]], [[4,2,3,4],[2,1,1,1],[8,6,4,2]])\n [[34, 23, 19, 15], [68, 46, 37, 28], [28, 18, 15, 12], [96, 62, 55, 48]]\n >>> strassen([[3,7,5,6,9],[1,5,3,7,8],[1,4,4,5,7]], [[2,4],[5,2],[1,7],[5,5],[7,8]])\n [[139, 163], [121, 134], [100, 121]]\n \"\"\"\n if matrix_dimensions(matrix1)[1] != matrix_dimensions(matrix2)[0]:\n msg = (\n \"Unable to multiply these matrices, please check the dimensions.\\n\"\n f\"Matrix A: {matrix1}\\n\"\n f\"Matrix B: {matrix2}\"\n )\n raise Exception(msg)\n dimension1 = matrix_dimensions(matrix1)\n dimension2 = matrix_dimensions(matrix2)\n\n if dimension1[0] == dimension1[1] and dimension2[0] == dimension2[1]:\n return [matrix1, matrix2]\n\n maximum = max(*dimension1, *dimension2)\n maxim = int(math.pow(2, math.ceil(math.log2(maximum))))\n new_matrix1 = matrix1\n new_matrix2 = matrix2\n\n # Adding zeros to the matrices to convert them both into square matrices of equal\n # dimensions that are a power of 2\n for i in range(maxim):\n if i < dimension1[0]:\n for _ in range(dimension1[1], maxim):\n new_matrix1[i].append(0)\n else:\n new_matrix1.append([0] * maxim)\n if i < dimension2[0]:\n for _ in range(dimension2[1], maxim):\n new_matrix2[i].append(0)\n else:\n new_matrix2.append([0] * maxim)\n\n final_matrix = actual_strassen(new_matrix1, new_matrix2)\n\n # Removing the additional zeros\n for i in range(maxim):\n if i < dimension1[0]:\n for _ in range(dimension2[1], maxim):\n final_matrix[i].pop()\n else:\n final_matrix.pop()\n return final_matrix\n\n\nif __name__ == \"__main__\":\n matrix1 = [\n [2, 3, 4, 5],\n [6, 4, 3, 1],\n [2, 3, 6, 7],\n [3, 1, 2, 4],\n [2, 3, 4, 5],\n [6, 4, 3, 1],\n [2, 3, 6, 7],\n [3, 1, 2, 4],\n [2, 3, 4, 5],\n [6, 2, 3, 1],\n ]\n matrix2 = [[0, 2, 1, 1], [16, 2, 3, 3], [2, 2, 7, 7], [13, 11, 22, 4]]\n print(strassen(matrix1, matrix2))\n"} +{"Prompt":"https:www.hackerrank.comchallengesabbrproblem You can perform the following operation on some string, : 1. Capitalize zero or more of 's lowercase letters at some index i i.e., make them uppercase. 2. Delete all of the remaining lowercase letters in . Example: adaBcd and bABC daBcd capitalize a and cdABCd remove d ABC abbrdaBcd, ABC True abbrdBcd, ABC False","Completions":"def abbr(a: str, b: str) -> bool:\n \"\"\"\n >>> abbr(\"daBcd\", \"ABC\")\n True\n >>> abbr(\"dBcd\", \"ABC\")\n False\n \"\"\"\n n = len(a)\n m = len(b)\n dp = [[False for _ in range(m + 1)] for _ in range(n + 1)]\n dp[0][0] = True\n for i in range(n):\n for j in range(m + 1):\n if dp[i][j]:\n if j < m and a[i].upper() == b[j]:\n dp[i + 1][j + 1] = True\n if a[i].islower():\n dp[i + 1][j] = True\n return dp[n][m]\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Program to list all the ways a target string can be constructed from the given list of substrings returns the list containing all the possible combinations a stringtarget can be constructed from the given list of substringswordbank allconstructhello, he, l, o 'he', 'l', 'l', 'o' allconstructpurple,purp,p,ur,le,purpl 'purp', 'le', 'p', 'ur', 'p', 'le' create a table seed value iterate through the indices condition slice condition adds the word to every combination the current position holds now,push that combination to the tableilenword combinations are in reverse order so reverse for better output","Completions":"from __future__ import annotations\n\n\ndef all_construct(target: str, word_bank: list[str] | None = None) -> list[list[str]]:\n \"\"\"\n returns the list containing all the possible\n combinations a string(target) can be constructed from\n the given list of substrings(word_bank)\n >>> all_construct(\"hello\", [\"he\", \"l\", \"o\"])\n [['he', 'l', 'l', 'o']]\n >>> all_construct(\"purple\",[\"purp\",\"p\",\"ur\",\"le\",\"purpl\"])\n [['purp', 'le'], ['p', 'ur', 'p', 'le']]\n \"\"\"\n\n word_bank = word_bank or []\n # create a table\n table_size: int = len(target) + 1\n\n table: list[list[list[str]]] = []\n for _ in range(table_size):\n table.append([])\n # seed value\n table[0] = [[]] # because empty string has empty combination\n\n # iterate through the indices\n for i in range(table_size):\n # condition\n if table[i] != []:\n for word in word_bank:\n # slice condition\n if target[i : i + len(word)] == word:\n new_combinations: list[list[str]] = [\n [word, *way] for way in table[i]\n ]\n # adds the word to every combination the current position holds\n # now,push that combination to the table[i+len(word)]\n table[i + len(word)] += new_combinations\n\n # combinations are in reverse order so reverse for better output\n for combination in table[len(target)]:\n combination.reverse()\n\n return table[len(target)]\n\n\nif __name__ == \"__main__\":\n print(all_construct(\"jwajalapa\", [\"jwa\", \"j\", \"w\", \"a\", \"la\", \"lapa\"]))\n print(all_construct(\"rajamati\", [\"s\", \"raj\", \"amat\", \"raja\", \"ma\", \"i\", \"t\"]))\n print(\n all_construct(\n \"hexagonosaurus\",\n [\"h\", \"ex\", \"hex\", \"ag\", \"ago\", \"ru\", \"auru\", \"rus\", \"go\", \"no\", \"o\", \"s\"],\n )\n )\n"} +{"Prompt":"This is a Python implementation for questions involving task assignments between people. Here Bitmasking and DP are used for solving this. Question : We have N tasks and M people. Each person in M can do only certain of these tasks. Also a person can do only one task and a task is performed only by one person. Find the total no of ways in which the tasks can be distributed. DP table will have a dimension of 2MN initially all values are set to 1 finalmask is used to check if all persons are included by setting all bits to 1 if mask self.finalmask all persons are distributed tasks, return 1 if not everyone gets the task and no more tasks are available, return 0 if case already considered Number of ways when we don't this task in the arrangement now assign the tasks one by one to all possible persons and recursively assign for the remaining tasks. if p is already given a task assign this task to p and change the mask value. And recursively assign tasks with the new mask value. save the value. Store the list of persons for each task call the function to fill the DP table, final answer is stored in dp01 the list of tasks that can be done by M persons. For the particular example the tasks can be distributed as 1,2,3, 1,2,4, 1,5,3, 1,5,4, 3,1,4, 3,2,4, 3,5,4, 4,1,3, 4,2,3, 4,5,3 total 10","Completions":"from collections import defaultdict\n\n\nclass AssignmentUsingBitmask:\n def __init__(self, task_performed, total):\n self.total_tasks = total # total no of tasks (N)\n\n # DP table will have a dimension of (2^M)*N\n # initially all values are set to -1\n self.dp = [\n [-1 for i in range(total + 1)] for j in range(2 ** len(task_performed))\n ]\n\n self.task = defaultdict(list) # stores the list of persons for each task\n\n # final_mask is used to check if all persons are included by setting all bits\n # to 1\n self.final_mask = (1 << len(task_performed)) - 1\n\n def count_ways_until(self, mask, task_no):\n # if mask == self.finalmask all persons are distributed tasks, return 1\n if mask == self.final_mask:\n return 1\n\n # if not everyone gets the task and no more tasks are available, return 0\n if task_no > self.total_tasks:\n return 0\n\n # if case already considered\n if self.dp[mask][task_no] != -1:\n return self.dp[mask][task_no]\n\n # Number of ways when we don't this task in the arrangement\n total_ways_util = self.count_ways_until(mask, task_no + 1)\n\n # now assign the tasks one by one to all possible persons and recursively\n # assign for the remaining tasks.\n if task_no in self.task:\n for p in self.task[task_no]:\n # if p is already given a task\n if mask & (1 << p):\n continue\n\n # assign this task to p and change the mask value. And recursively\n # assign tasks with the new mask value.\n total_ways_util += self.count_ways_until(mask | (1 << p), task_no + 1)\n\n # save the value.\n self.dp[mask][task_no] = total_ways_util\n\n return self.dp[mask][task_no]\n\n def count_no_of_ways(self, task_performed):\n # Store the list of persons for each task\n for i in range(len(task_performed)):\n for j in task_performed[i]:\n self.task[j].append(i)\n\n # call the function to fill the DP table, final answer is stored in dp[0][1]\n return self.count_ways_until(0, 1)\n\n\nif __name__ == \"__main__\":\n total_tasks = 5 # total no of tasks (the value of N)\n\n # the list of tasks that can be done by M persons.\n task_performed = [[1, 3, 4], [1, 2, 5], [3, 4]]\n print(\n AssignmentUsingBitmask(task_performed, total_tasks).count_no_of_ways(\n task_performed\n )\n )\n \"\"\"\n For the particular example the tasks can be distributed as\n (1,2,3), (1,2,4), (1,5,3), (1,5,4), (3,1,4),\n (3,2,4), (3,5,4), (4,1,3), (4,2,3), (4,5,3)\n total 10\n \"\"\"\n"} +{"Prompt":"Print all the Catalan numbers from 0 to n, n being the user input. The Catalan numbers are a sequence of positive integers that appear in many counting problems in combinatorics 1. Such problems include counting 2: The number of Dyck words of length 2n The number wellformed expressions with n pairs of parentheses e.g., is valid but is not The number of different ways n 1 factors can be completely parenthesized e.g., for n 2, Cn 2 and abc and abc are the two valid ways to parenthesize. The number of full binary trees with n 1 leaves A Catalan number satisfies the following recurrence relation which we will use in this algorithm 1. C0 C1 1 Cn sumCi.Cni1, from i 0 to n1 In addition, the nth Catalan number can be calculated using the closed form formula below 1: Cn 1 n 1 2n choose n Sources: 1 https:brilliant.orgwikicatalannumbers 2 https:en.wikipedia.orgwikiCatalannumber Return a list of the Catalan number sequence from 0 through upperlimit. catalannumbers5 1, 1, 2, 5, 14, 42 catalannumbers2 1, 1, 2 catalannumbers1 Traceback most recent call last: ValueError: Limit for the Catalan sequence must be 0 Base case: C0 C1 1 Recurrence relation: Ci sumCj.Cij1, from j 0 to i","Completions":"def catalan_numbers(upper_limit: int) -> \"list[int]\":\n \"\"\"\n Return a list of the Catalan number sequence from 0 through `upper_limit`.\n\n >>> catalan_numbers(5)\n [1, 1, 2, 5, 14, 42]\n >>> catalan_numbers(2)\n [1, 1, 2]\n >>> catalan_numbers(-1)\n Traceback (most recent call last):\n ValueError: Limit for the Catalan sequence must be \u2265 0\n \"\"\"\n if upper_limit < 0:\n raise ValueError(\"Limit for the Catalan sequence must be \u2265 0\")\n\n catalan_list = [0] * (upper_limit + 1)\n\n # Base case: C(0) = C(1) = 1\n catalan_list[0] = 1\n if upper_limit > 0:\n catalan_list[1] = 1\n\n # Recurrence relation: C(i) = sum(C(j).C(i-j-1)), from j = 0 to i\n for i in range(2, upper_limit + 1):\n for j in range(i):\n catalan_list[i] += catalan_list[j] * catalan_list[i - j - 1]\n\n return catalan_list\n\n\nif __name__ == \"__main__\":\n print(\"\\n********* Catalan Numbers Using Dynamic Programming ************\\n\")\n print(\"\\n*** Enter -1 at any time to quit ***\")\n print(\"\\nEnter the upper limit (\u2265 0) for the Catalan number sequence: \", end=\"\")\n try:\n while True:\n N = int(input().strip())\n if N < 0:\n print(\"\\n********* Goodbye!! ************\")\n break\n else:\n print(f\"The Catalan numbers from 0 through {N} are:\")\n print(catalan_numbers(N))\n print(\"Try another upper limit for the sequence: \", end=\"\")\n except (NameError, ValueError):\n print(\"\\n********* Invalid input, goodbye! ************\\n\")\n\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"!usrbinenv python3 LeetCdoe No.70: Climbing Stairs Distinct ways to climb a numberofsteps staircase where each time you can either climb 1 or 2 steps. Args: numberofsteps: number of steps on the staircase Returns: Distinct ways to climb a numberofsteps staircase Raises: AssertionError: numberofsteps not positive integer climbstairs3 3 climbstairs1 1 climbstairs7 doctest: ELLIPSIS Traceback most recent call last: ... AssertionError: numberofsteps needs to be positive integer, your input 7","Completions":"#!\/usr\/bin\/env python3\n\n\ndef climb_stairs(number_of_steps: int) -> int:\n \"\"\"\n LeetCdoe No.70: Climbing Stairs\n Distinct ways to climb a number_of_steps staircase where each time you can either\n climb 1 or 2 steps.\n\n Args:\n number_of_steps: number of steps on the staircase\n\n Returns:\n Distinct ways to climb a number_of_steps staircase\n\n Raises:\n AssertionError: number_of_steps not positive integer\n\n >>> climb_stairs(3)\n 3\n >>> climb_stairs(1)\n 1\n >>> climb_stairs(-7) # doctest: +ELLIPSIS\n Traceback (most recent call last):\n ...\n AssertionError: number_of_steps needs to be positive integer, your input -7\n \"\"\"\n assert (\n isinstance(number_of_steps, int) and number_of_steps > 0\n ), f\"number_of_steps needs to be positive integer, your input {number_of_steps}\"\n if number_of_steps == 1:\n return 1\n previous, current = 1, 1\n for _ in range(number_of_steps - 1):\n current, previous = current + previous, current\n return current\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Question: You are given an array of distinct integers and you have to tell how many different ways of selecting the elements from the array are there such that the sum of chosen elements is equal to the target number tar. Example Input: N 3 target 5 array 1, 2, 5 Output: 9 Approach: The basic idea is to go over recursively to find the way such that the sum of chosen elements is tar. For every element, we have two choices 1. Include the element in our set of chosen elements. 2. Dont include the element in our set of chosen elements. Function checks the all possible combinations, and returns the count of possible combination in exponential Time Complexity. combinationsumiv3, 1,2,5, 5 9 Function checks the all possible combinations, and returns the count of possible combination in ON2 Time Complexity as we are using Dynamic programming array here. combinationsumivdparray3, 1,2,5, 5 9 Function checks the all possible combinations with using bottom up approach, and returns the count of possible combination in ON2 Time Complexity as we are using Dynamic programming array here. combinationsumivbottomup3, 1,2,5, 5 9","Completions":"def combination_sum_iv(n: int, array: list[int], target: int) -> int:\n \"\"\"\n Function checks the all possible combinations, and returns the count\n of possible combination in exponential Time Complexity.\n\n >>> combination_sum_iv(3, [1,2,5], 5)\n 9\n \"\"\"\n\n def count_of_possible_combinations(target: int) -> int:\n if target < 0:\n return 0\n if target == 0:\n return 1\n return sum(count_of_possible_combinations(target - item) for item in array)\n\n return count_of_possible_combinations(target)\n\n\ndef combination_sum_iv_dp_array(n: int, array: list[int], target: int) -> int:\n \"\"\"\n Function checks the all possible combinations, and returns the count\n of possible combination in O(N^2) Time Complexity as we are using Dynamic\n programming array here.\n\n >>> combination_sum_iv_dp_array(3, [1,2,5], 5)\n 9\n \"\"\"\n\n def count_of_possible_combinations_with_dp_array(\n target: int, dp_array: list[int]\n ) -> int:\n if target < 0:\n return 0\n if target == 0:\n return 1\n if dp_array[target] != -1:\n return dp_array[target]\n answer = sum(\n count_of_possible_combinations_with_dp_array(target - item, dp_array)\n for item in array\n )\n dp_array[target] = answer\n return answer\n\n dp_array = [-1] * (target + 1)\n return count_of_possible_combinations_with_dp_array(target, dp_array)\n\n\ndef combination_sum_iv_bottom_up(n: int, array: list[int], target: int) -> int:\n \"\"\"\n Function checks the all possible combinations with using bottom up approach,\n and returns the count of possible combination in O(N^2) Time Complexity\n as we are using Dynamic programming array here.\n\n >>> combination_sum_iv_bottom_up(3, [1,2,5], 5)\n 9\n \"\"\"\n\n dp_array = [0] * (target + 1)\n dp_array[0] = 1\n\n for i in range(1, target + 1):\n for j in range(n):\n if i - array[j] >= 0:\n dp_array[i] += dp_array[i - array[j]]\n\n return dp_array[target]\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n n = 3\n target = 5\n array = [1, 2, 5]\n print(combination_sum_iv(n, array, target))\n"} +{"Prompt":"Author : Turfa Auliarachman Date : October 12, 2016 This is a pure Python implementation of Dynamic Programming solution to the edit distance problem. The problem is : Given two strings A and B. Find the minimum number of operations to string B such that A B. The permitted operations are removal, insertion, and substitution. Use : solver EditDistance editDistanceResult solver.solvefirstString, secondString EditDistance.mindisttopdownintention, execution 5 EditDistance.mindisttopdownintention, 9 EditDistance.mindisttopdown, 0 EditDistance.mindistbottomupintention, execution 5 EditDistance.mindistbottomupintention, 9 EditDistance.mindistbottomup, 0","Completions":"class EditDistance:\n \"\"\"\n Use :\n solver = EditDistance()\n editDistanceResult = solver.solve(firstString, secondString)\n \"\"\"\n\n def __init__(self):\n self.word1 = \"\"\n self.word2 = \"\"\n self.dp = []\n\n def __min_dist_top_down_dp(self, m: int, n: int) -> int:\n if m == -1:\n return n + 1\n elif n == -1:\n return m + 1\n elif self.dp[m][n] > -1:\n return self.dp[m][n]\n else:\n if self.word1[m] == self.word2[n]:\n self.dp[m][n] = self.__min_dist_top_down_dp(m - 1, n - 1)\n else:\n insert = self.__min_dist_top_down_dp(m, n - 1)\n delete = self.__min_dist_top_down_dp(m - 1, n)\n replace = self.__min_dist_top_down_dp(m - 1, n - 1)\n self.dp[m][n] = 1 + min(insert, delete, replace)\n\n return self.dp[m][n]\n\n def min_dist_top_down(self, word1: str, word2: str) -> int:\n \"\"\"\n >>> EditDistance().min_dist_top_down(\"intention\", \"execution\")\n 5\n >>> EditDistance().min_dist_top_down(\"intention\", \"\")\n 9\n >>> EditDistance().min_dist_top_down(\"\", \"\")\n 0\n \"\"\"\n self.word1 = word1\n self.word2 = word2\n self.dp = [[-1 for _ in range(len(word2))] for _ in range(len(word1))]\n\n return self.__min_dist_top_down_dp(len(word1) - 1, len(word2) - 1)\n\n def min_dist_bottom_up(self, word1: str, word2: str) -> int:\n \"\"\"\n >>> EditDistance().min_dist_bottom_up(\"intention\", \"execution\")\n 5\n >>> EditDistance().min_dist_bottom_up(\"intention\", \"\")\n 9\n >>> EditDistance().min_dist_bottom_up(\"\", \"\")\n 0\n \"\"\"\n self.word1 = word1\n self.word2 = word2\n m = len(word1)\n n = len(word2)\n self.dp = [[0 for _ in range(n + 1)] for _ in range(m + 1)]\n\n for i in range(m + 1):\n for j in range(n + 1):\n if i == 0: # first string is empty\n self.dp[i][j] = j\n elif j == 0: # second string is empty\n self.dp[i][j] = i\n elif word1[i - 1] == word2[j - 1]: # last characters are equal\n self.dp[i][j] = self.dp[i - 1][j - 1]\n else:\n insert = self.dp[i][j - 1]\n delete = self.dp[i - 1][j]\n replace = self.dp[i - 1][j - 1]\n self.dp[i][j] = 1 + min(insert, delete, replace)\n return self.dp[m][n]\n\n\nif __name__ == \"__main__\":\n solver = EditDistance()\n\n print(\"****************** Testing Edit Distance DP Algorithm ******************\")\n print()\n\n S1 = input(\"Enter the first string: \").strip()\n S2 = input(\"Enter the second string: \").strip()\n\n print()\n print(f\"The minimum edit distance is: {solver.min_dist_top_down(S1, S2)}\")\n print(f\"The minimum edit distance is: {solver.min_dist_bottom_up(S1, S2)}\")\n print()\n print(\"*************** End of Testing Edit Distance DP Algorithm ***************\")\n"} +{"Prompt":"Factorial of a number using memoization factorial7 5040 factorial1 Traceback most recent call last: ... ValueError: Number should not be negative. factoriali for i in range10 1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880","Completions":"# Factorial of a number using memoization\n\nfrom functools import lru_cache\n\n\n@lru_cache\ndef factorial(num: int) -> int:\n \"\"\"\n >>> factorial(7)\n 5040\n >>> factorial(-1)\n Traceback (most recent call last):\n ...\n ValueError: Number should not be negative.\n >>> [factorial(i) for i in range(10)]\n [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880]\n \"\"\"\n if num < 0:\n raise ValueError(\"Number should not be negative.\")\n\n return 1 if num in (0, 1) else num * factorial(num - 1)\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"!usrbinenv python3 This program calculates the nth Fibonacci number in Ologn. It's possible to calculate F1000000 in less than a second. return Fn fibonaccii for i in range13 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144 returns Fn, Fn1 F2n Fn2Fn1 Fn F2n1 Fn12Fn2","Completions":"#!\/usr\/bin\/env python3\n\n\"\"\"\nThis program calculates the nth Fibonacci number in O(log(n)).\nIt's possible to calculate F(1_000_000) in less than a second.\n\"\"\"\nfrom __future__ import annotations\n\nimport sys\n\n\ndef fibonacci(n: int) -> int:\n \"\"\"\n return F(n)\n >>> [fibonacci(i) for i in range(13)]\n [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144]\n \"\"\"\n if n < 0:\n raise ValueError(\"Negative arguments are not supported\")\n return _fib(n)[0]\n\n\n# returns (F(n), F(n-1))\ndef _fib(n: int) -> tuple[int, int]:\n if n == 0: # (F(0), F(1))\n return (0, 1)\n\n # F(2n) = F(n)[2F(n+1) \u2212 F(n)]\n # F(2n+1) = F(n+1)^2+F(n)^2\n a, b = _fib(n \/\/ 2)\n c = a * (b * 2 - a)\n d = a * a + b * b\n return (d, c + d) if n % 2 else (c, d)\n\n\nif __name__ == \"__main__\":\n n = int(sys.argv[1])\n print(f\"fibonacci({n}) is {fibonacci(n)}\")\n"} +{"Prompt":"This is a pure Python implementation of Dynamic Programming solution to the fibonacci sequence problem. Get the Fibonacci number of index. If the number does not exist, calculate all missing numbers leading up to the number of index. Fibonacci.get10 0, 1, 1, 2, 3, 5, 8, 13, 21, 34 Fibonacci.get5 0, 1, 1, 2, 3","Completions":"class Fibonacci:\n def __init__(self) -> None:\n self.sequence = [0, 1]\n\n def get(self, index: int) -> list:\n \"\"\"\n Get the Fibonacci number of `index`. If the number does not exist,\n calculate all missing numbers leading up to the number of `index`.\n\n >>> Fibonacci().get(10)\n [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]\n >>> Fibonacci().get(5)\n [0, 1, 1, 2, 3]\n \"\"\"\n if (difference := index - (len(self.sequence) - 2)) >= 1:\n for _ in range(difference):\n self.sequence.append(self.sequence[-1] + self.sequence[-2])\n return self.sequence[:index]\n\n\ndef main() -> None:\n print(\n \"Fibonacci Series Using Dynamic Programming\\n\",\n \"Enter the index of the Fibonacci number you want to calculate \",\n \"in the prompt below. (To exit enter exit or Ctrl-C)\\n\",\n sep=\"\",\n )\n fibonacci = Fibonacci()\n\n while True:\n prompt: str = input(\">> \")\n if prompt in {\"exit\", \"quit\"}:\n break\n\n try:\n index: int = int(prompt)\n except ValueError:\n print(\"Enter a number or 'exit'\")\n continue\n\n print(fibonacci.get(index))\n\n\nif __name__ == \"__main__\":\n main()\n"} +{"Prompt":"https:en.wikipedia.orgwikiFizzbuzzProgramming Plays FizzBuzz. Prints Fizz if number is a multiple of 3. Prints Buzz if its a multiple of 5. Prints FizzBuzz if its a multiple of both 3 and 5 or 15. Else Prints The Number Itself. fizzbuzz1,7 '1 2 Fizz 4 Buzz Fizz 7 ' fizzbuzz1,0 Traceback most recent call last: ... ValueError: Iterations must be done more than 0 times to play FizzBuzz fizzbuzz5,5 Traceback most recent call last: ... ValueError: starting number must be and integer and be more than 0 fizzbuzz10,5 Traceback most recent call last: ... ValueError: Iterations must be done more than 0 times to play FizzBuzz fizzbuzz1.5,5 Traceback most recent call last: ... ValueError: starting number must be and integer and be more than 0 fizzbuzz1,5.5 Traceback most recent call last: ... ValueError: iterations must be defined as integers starting number must be and integer and be more than 0 if not iterations 1: raise ValueErrorIterations must be done more than 0 times to play FizzBuzz out while number iterations: if number 3 0: out Fizz if number 5 0: out Buzz if 0 not in number 3, number 5: out strnumber printout number 1 out return out if name main: import doctest doctest.testmod","Completions":"# https:\/\/en.wikipedia.org\/wiki\/Fizz_buzz#Programming\n\n\ndef fizz_buzz(number: int, iterations: int) -> str:\n \"\"\"\n Plays FizzBuzz.\n Prints Fizz if number is a multiple of 3.\n Prints Buzz if its a multiple of 5.\n Prints FizzBuzz if its a multiple of both 3 and 5 or 15.\n Else Prints The Number Itself.\n >>> fizz_buzz(1,7)\n '1 2 Fizz 4 Buzz Fizz 7 '\n >>> fizz_buzz(1,0)\n Traceback (most recent call last):\n ...\n ValueError: Iterations must be done more than 0 times to play FizzBuzz\n >>> fizz_buzz(-5,5)\n Traceback (most recent call last):\n ...\n ValueError: starting number must be\n and integer and be more than 0\n >>> fizz_buzz(10,-5)\n Traceback (most recent call last):\n ...\n ValueError: Iterations must be done more than 0 times to play FizzBuzz\n >>> fizz_buzz(1.5,5)\n Traceback (most recent call last):\n ...\n ValueError: starting number must be\n and integer and be more than 0\n >>> fizz_buzz(1,5.5)\n Traceback (most recent call last):\n ...\n ValueError: iterations must be defined as integers\n \"\"\"\n if not isinstance(iterations, int):\n raise ValueError(\"iterations must be defined as integers\")\n if not isinstance(number, int) or not number >= 1:\n raise ValueError(\n \"\"\"starting number must be\n and integer and be more than 0\"\"\"\n )\n if not iterations >= 1:\n raise ValueError(\"Iterations must be done more than 0 times to play FizzBuzz\")\n\n out = \"\"\n while number <= iterations:\n if number % 3 == 0:\n out += \"Fizz\"\n if number % 5 == 0:\n out += \"Buzz\"\n if 0 not in (number % 3, number % 5):\n out += str(number)\n\n # print(out)\n number += 1\n out += \" \"\n return out\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"The number of partitions of a number n into at least k parts equals the number of partitions into exactly k parts plus the number of partitions into at least k1 parts. Subtracting 1 from each part of a partition of n into k parts gives a partition of nk into k parts. These two facts together are used for this algorithm. https:en.wikipedia.orgwikiPartitionnumbertheory https:en.wikipedia.orgwikiPartitionfunctionnumbertheory partition5 7 partition7 15 partition100 190569292 partition1000 24061467864032622473692149727991 partition7 Traceback most recent call last: ... IndexError: list index out of range partition0 Traceback most recent call last: ... IndexError: list assignment index out of range partition7.8 Traceback most recent call last: ... TypeError: 'float' object cannot be interpreted as an integer","Completions":"def partition(m: int) -> int:\n \"\"\"\n >>> partition(5)\n 7\n >>> partition(7)\n 15\n >>> partition(100)\n 190569292\n >>> partition(1_000)\n 24061467864032622473692149727991\n >>> partition(-7)\n Traceback (most recent call last):\n ...\n IndexError: list index out of range\n >>> partition(0)\n Traceback (most recent call last):\n ...\n IndexError: list assignment index out of range\n >>> partition(7.8)\n Traceback (most recent call last):\n ...\n TypeError: 'float' object cannot be interpreted as an integer\n \"\"\"\n memo: list[list[int]] = [[0 for _ in range(m)] for _ in range(m + 1)]\n for i in range(m + 1):\n memo[i][0] = 1\n\n for n in range(m + 1):\n for k in range(1, m):\n memo[n][k] += memo[n][k - 1]\n if n - k > 0:\n memo[n][k] += memo[n - k - 1][k]\n\n return memo[m][m - 1]\n\n\nif __name__ == \"__main__\":\n import sys\n\n if len(sys.argv) == 1:\n try:\n n = int(input(\"Enter a number: \").strip())\n print(partition(n))\n except ValueError:\n print(\"Please enter a number.\")\n else:\n try:\n n = int(sys.argv[1])\n print(partition(n))\n except ValueError:\n print(\"Please pass a number.\")\n"} +{"Prompt":"Author : Syed Faizan 3rd Year Student IIIT Pune github : faizan2700 You are given a bitmask m and you want to efficiently iterate through all of its submasks. The mask s is submask of m if only bits that were included in bitmask are set Args: mask : number which shows mask always integer 0, zero does not have any submasks Returns: allsubmasks : the list of submasks of mask mask s is called submask of mask m if only bits that were included in original mask are set Raises: AssertionError: mask not positive integer listofsubmasks15 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 listofsubmasks13 13, 12, 9, 8, 5, 4, 1 listofsubmasks7 doctest: ELLIPSIS Traceback most recent call last: ... AssertionError: mask needs to be positive integer, your input 7 listofsubmasks0 doctest: ELLIPSIS Traceback most recent call last: ... AssertionError: mask needs to be positive integer, your input 0 first submask iterated will be mask itself then operation will be performed to get other submasks till we reach empty submask that is zero zero is not included in final submasks list","Completions":"from __future__ import annotations\n\n\ndef list_of_submasks(mask: int) -> list[int]:\n \"\"\"\n Args:\n mask : number which shows mask ( always integer > 0, zero does not have any\n submasks )\n\n Returns:\n all_submasks : the list of submasks of mask (mask s is called submask of mask\n m if only bits that were included in original mask are set\n\n Raises:\n AssertionError: mask not positive integer\n\n >>> list_of_submasks(15)\n [15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]\n >>> list_of_submasks(13)\n [13, 12, 9, 8, 5, 4, 1]\n >>> list_of_submasks(-7) # doctest: +ELLIPSIS\n Traceback (most recent call last):\n ...\n AssertionError: mask needs to be positive integer, your input -7\n >>> list_of_submasks(0) # doctest: +ELLIPSIS\n Traceback (most recent call last):\n ...\n AssertionError: mask needs to be positive integer, your input 0\n\n \"\"\"\n\n assert (\n isinstance(mask, int) and mask > 0\n ), f\"mask needs to be positive integer, your input {mask}\"\n\n \"\"\"\n first submask iterated will be mask itself then operation will be performed\n to get other submasks till we reach empty submask that is zero ( zero is not\n included in final submasks list )\n \"\"\"\n all_submasks = []\n submask = mask\n\n while submask:\n all_submasks.append(submask)\n submask = (submask - 1) & mask\n\n return all_submasks\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Given weights and values of n items, put these items in a knapsack of capacity W to get the maximum total value in the knapsack. Note that only the integer weights 01 knapsack problem is solvable using dynamic programming. This code involves the concept of memory functions. Here we solve the subproblems which are needed unlike the below example F is a 2D array with 1s filled up Solves the integer weights knapsack problem returns one of the several possible optimal subsets. Parameters W: int, the total maximum weight for the given knapsack problem. wt: list, the vector of weights for all items where wti is the weight of the ith item. val: list, the vector of values for all items where vali is the value of the ith item Returns optimalval: float, the optimal value for the given knapsack problem exampleoptionalset: set, the indices of one of the optimal subsets which gave rise to the optimal value. Examples knapsackwithexamplesolution10, 1, 3, 5, 2, 10, 20, 100, 22 142, 2, 3, 4 knapsackwithexamplesolution6, 4, 3, 2, 3, 3, 2, 4, 4 8, 3, 4 knapsackwithexamplesolution6, 4, 3, 2, 3, 3, 2, 4 Traceback most recent call last: ... ValueError: The number of weights must be the same as the number of values. But got 4 weights and 3 values Recursively reconstructs one of the optimal subsets given a filled DP table and the vector of weights Parameters dp: list of list, the table of a solved integer weight dynamic programming problem wt: list or tuple, the vector of weights of the items i: int, the index of the item under consideration j: int, the current possible maximum weight optimalset: set, the optimal subset so far. This gets modified by the function. Returns None for the current item i at a maximum weight j to be part of an optimal subset, the optimal value at i, j must be greater than the optimal value at i1, j. where i 1 means considering only the previous items at the given maximum weight Adding test case for knapsack testing the dynamic programming problem with example the optimal subset for the above example are items 3 and 4","Completions":"def mf_knapsack(i, wt, val, j):\n \"\"\"\n This code involves the concept of memory functions. Here we solve the subproblems\n which are needed unlike the below example\n F is a 2D array with -1s filled up\n \"\"\"\n global f # a global dp table for knapsack\n if f[i][j] < 0:\n if j < wt[i - 1]:\n val = mf_knapsack(i - 1, wt, val, j)\n else:\n val = max(\n mf_knapsack(i - 1, wt, val, j),\n mf_knapsack(i - 1, wt, val, j - wt[i - 1]) + val[i - 1],\n )\n f[i][j] = val\n return f[i][j]\n\n\ndef knapsack(w, wt, val, n):\n dp = [[0] * (w + 1) for _ in range(n + 1)]\n\n for i in range(1, n + 1):\n for w_ in range(1, w + 1):\n if wt[i - 1] <= w_:\n dp[i][w_] = max(val[i - 1] + dp[i - 1][w_ - wt[i - 1]], dp[i - 1][w_])\n else:\n dp[i][w_] = dp[i - 1][w_]\n\n return dp[n][w_], dp\n\n\ndef knapsack_with_example_solution(w: int, wt: list, val: list):\n \"\"\"\n Solves the integer weights knapsack problem returns one of\n the several possible optimal subsets.\n\n Parameters\n ---------\n\n W: int, the total maximum weight for the given knapsack problem.\n wt: list, the vector of weights for all items where wt[i] is the weight\n of the i-th item.\n val: list, the vector of values for all items where val[i] is the value\n of the i-th item\n\n Returns\n -------\n optimal_val: float, the optimal value for the given knapsack problem\n example_optional_set: set, the indices of one of the optimal subsets\n which gave rise to the optimal value.\n\n Examples\n -------\n >>> knapsack_with_example_solution(10, [1, 3, 5, 2], [10, 20, 100, 22])\n (142, {2, 3, 4})\n >>> knapsack_with_example_solution(6, [4, 3, 2, 3], [3, 2, 4, 4])\n (8, {3, 4})\n >>> knapsack_with_example_solution(6, [4, 3, 2, 3], [3, 2, 4])\n Traceback (most recent call last):\n ...\n ValueError: The number of weights must be the same as the number of values.\n But got 4 weights and 3 values\n \"\"\"\n if not (isinstance(wt, (list, tuple)) and isinstance(val, (list, tuple))):\n raise ValueError(\n \"Both the weights and values vectors must be either lists or tuples\"\n )\n\n num_items = len(wt)\n if num_items != len(val):\n msg = (\n \"The number of weights must be the same as the number of values.\\n\"\n f\"But got {num_items} weights and {len(val)} values\"\n )\n raise ValueError(msg)\n for i in range(num_items):\n if not isinstance(wt[i], int):\n msg = (\n \"All weights must be integers but got weight of \"\n f\"type {type(wt[i])} at index {i}\"\n )\n raise TypeError(msg)\n\n optimal_val, dp_table = knapsack(w, wt, val, num_items)\n example_optional_set: set = set()\n _construct_solution(dp_table, wt, num_items, w, example_optional_set)\n\n return optimal_val, example_optional_set\n\n\ndef _construct_solution(dp: list, wt: list, i: int, j: int, optimal_set: set):\n \"\"\"\n Recursively reconstructs one of the optimal subsets given\n a filled DP table and the vector of weights\n\n Parameters\n ---------\n\n dp: list of list, the table of a solved integer weight dynamic programming problem\n\n wt: list or tuple, the vector of weights of the items\n i: int, the index of the item under consideration\n j: int, the current possible maximum weight\n optimal_set: set, the optimal subset so far. This gets modified by the function.\n\n Returns\n -------\n None\n\n \"\"\"\n # for the current item i at a maximum weight j to be part of an optimal subset,\n # the optimal value at (i, j) must be greater than the optimal value at (i-1, j).\n # where i - 1 means considering only the previous items at the given maximum weight\n if i > 0 and j > 0:\n if dp[i - 1][j] == dp[i][j]:\n _construct_solution(dp, wt, i - 1, j, optimal_set)\n else:\n optimal_set.add(i)\n _construct_solution(dp, wt, i - 1, j - wt[i - 1], optimal_set)\n\n\nif __name__ == \"__main__\":\n \"\"\"\n Adding test case for knapsack\n \"\"\"\n val = [3, 2, 4, 4]\n wt = [4, 3, 2, 3]\n n = 4\n w = 6\n f = [[0] * (w + 1)] + [[0] + [-1] * (w + 1) for _ in range(n + 1)]\n optimal_solution, _ = knapsack(w, wt, val, n)\n print(optimal_solution)\n print(mf_knapsack(n, wt, val, w)) # switched the n and w\n\n # testing the dynamic programming problem with example\n # the optimal subset for the above example are items 3 and 4\n optimal_solution, optimal_subset = knapsack_with_example_solution(w, wt, val)\n assert optimal_solution == 8\n assert optimal_subset == {3, 4}\n print(\"optimal_value = \", optimal_solution)\n print(\"An optimal subset corresponding to the optimal value\", optimal_subset)\n"} +{"Prompt":"Algorithm to find the biggest subset in the given array such that for any 2 elements x and y in the subset, either x divides y or y divides x. largestdivisiblesubset1, 16, 7, 8, 4 16, 8, 4, 1 largestdivisiblesubset1, 2, 3 2, 1 largestdivisiblesubset1, 2, 3 3 largestdivisiblesubset1, 2, 4, 8 8, 4, 2, 1 largestdivisiblesubset1, 2, 4, 8 8, 4, 2, 1 largestdivisiblesubset1, 1, 1 1, 1, 1 largestdivisiblesubset0, 0, 0 0, 0, 0 largestdivisiblesubset1, 1, 1 1, 1, 1 largestdivisiblesubset Sort the array in ascending order as the sequence does not matter we only have to pick up a subset. Initialize memo with 1s and hash with increasing numbers Iterate through the array Find the maximum length and its corresponding index Reconstruct the divisible subset","Completions":"from __future__ import annotations\n\n\ndef largest_divisible_subset(items: list[int]) -> list[int]:\n \"\"\"\n Algorithm to find the biggest subset in the given array such that for any 2 elements\n x and y in the subset, either x divides y or y divides x.\n >>> largest_divisible_subset([1, 16, 7, 8, 4])\n [16, 8, 4, 1]\n >>> largest_divisible_subset([1, 2, 3])\n [2, 1]\n >>> largest_divisible_subset([-1, -2, -3])\n [-3]\n >>> largest_divisible_subset([1, 2, 4, 8])\n [8, 4, 2, 1]\n >>> largest_divisible_subset((1, 2, 4, 8))\n [8, 4, 2, 1]\n >>> largest_divisible_subset([1, 1, 1])\n [1, 1, 1]\n >>> largest_divisible_subset([0, 0, 0])\n [0, 0, 0]\n >>> largest_divisible_subset([-1, -1, -1])\n [-1, -1, -1]\n >>> largest_divisible_subset([])\n []\n \"\"\"\n # Sort the array in ascending order as the sequence does not matter we only have to\n # pick up a subset.\n items = sorted(items)\n\n number_of_items = len(items)\n\n # Initialize memo with 1s and hash with increasing numbers\n memo = [1] * number_of_items\n hash_array = list(range(number_of_items))\n\n # Iterate through the array\n for i, item in enumerate(items):\n for prev_index in range(i):\n if ((items[prev_index] != 0 and item % items[prev_index]) == 0) and (\n (1 + memo[prev_index]) > memo[i]\n ):\n memo[i] = 1 + memo[prev_index]\n hash_array[i] = prev_index\n\n ans = -1\n last_index = -1\n\n # Find the maximum length and its corresponding index\n for i, memo_item in enumerate(memo):\n if memo_item > ans:\n ans = memo_item\n last_index = i\n\n # Reconstruct the divisible subset\n if last_index == -1:\n return []\n result = [items[last_index]]\n while hash_array[last_index] != last_index:\n last_index = hash_array[last_index]\n result.append(items[last_index])\n\n return result\n\n\nif __name__ == \"__main__\":\n from doctest import testmod\n\n testmod()\n\n items = [1, 16, 7, 8, 4]\n print(\n f\"The longest divisible subset of {items} is {largest_divisible_subset(items)}.\"\n )\n"} +{"Prompt":"LCS Problem Statement: Given two sequences, find the length of longest subsequence present in both of them. A subsequence is a sequence that appears in the same relative order, but not necessarily continuous. Example:abc, abg are subsequences of abcdefgh. Finds the longest common subsequence between two strings. Also returns the The subsequence found Parameters x: str, one of the strings y: str, the other string Returns Lmn: int, the length of the longest subsequence. Also equal to lenseq Seq: str, the subsequence found longestcommonsubsequenceprogramming, gaming 6, 'gaming' longestcommonsubsequencephysics, smartphone 2, 'ph' longestcommonsubsequencecomputer, food 1, 'o' find the length of strings declaring the array for storing the dp values","Completions":"def longest_common_subsequence(x: str, y: str):\n \"\"\"\n Finds the longest common subsequence between two strings. Also returns the\n The subsequence found\n\n Parameters\n ----------\n\n x: str, one of the strings\n y: str, the other string\n\n Returns\n -------\n L[m][n]: int, the length of the longest subsequence. Also equal to len(seq)\n Seq: str, the subsequence found\n\n >>> longest_common_subsequence(\"programming\", \"gaming\")\n (6, 'gaming')\n >>> longest_common_subsequence(\"physics\", \"smartphone\")\n (2, 'ph')\n >>> longest_common_subsequence(\"computer\", \"food\")\n (1, 'o')\n \"\"\"\n # find the length of strings\n\n assert x is not None\n assert y is not None\n\n m = len(x)\n n = len(y)\n\n # declaring the array for storing the dp values\n l = [[0] * (n + 1) for _ in range(m + 1)] # noqa: E741\n\n for i in range(1, m + 1):\n for j in range(1, n + 1):\n match = 1 if x[i - 1] == y[j - 1] else 0\n\n l[i][j] = max(l[i - 1][j], l[i][j - 1], l[i - 1][j - 1] + match)\n\n seq = \"\"\n i, j = m, n\n while i > 0 and j > 0:\n match = 1 if x[i - 1] == y[j - 1] else 0\n\n if l[i][j] == l[i - 1][j - 1] + match:\n if match == 1:\n seq = x[i - 1] + seq\n i -= 1\n j -= 1\n elif l[i][j] == l[i - 1][j]:\n i -= 1\n else:\n j -= 1\n\n return l[m][n], seq\n\n\nif __name__ == \"__main__\":\n a = \"AGGTAB\"\n b = \"GXTXAYB\"\n expected_ln = 4\n expected_subseq = \"GTAB\"\n\n ln, subseq = longest_common_subsequence(a, b)\n print(\"len =\", ln, \", sub-sequence =\", subseq)\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Longest Common Substring Problem Statement: Given two sequences, find the longest common substring present in both of them. A substring is necessarily continuous. Example: abcdef and xabded have two longest common substrings, ab or de. Therefore, algorithm should return any one of them. Finds the longest common substring between two strings. longestcommonsubstring, '' longestcommonsubstringa, '' longestcommonsubstring, a '' longestcommonsubstringa, a 'a' longestcommonsubstringabcdef, bcd 'bcd' longestcommonsubstringabcdef, xabded 'ab' longestcommonsubstringGeeksforGeeks, GeeksQuiz 'Geeks' longestcommonsubstringabcdxyz, xyzabcd 'abcd' longestcommonsubstringzxabcdezy, yzabcdezx 'abcdez' longestcommonsubstringOldSite:GeeksforGeeks.org, NewSite:GeeksQuiz.com 'Site:Geeks' longestcommonsubstring1, 1 Traceback most recent call last: ... ValueError: longestcommonsubstring takes two strings for inputs","Completions":"def longest_common_substring(text1: str, text2: str) -> str:\n \"\"\"\n Finds the longest common substring between two strings.\n >>> longest_common_substring(\"\", \"\")\n ''\n >>> longest_common_substring(\"a\",\"\")\n ''\n >>> longest_common_substring(\"\", \"a\")\n ''\n >>> longest_common_substring(\"a\", \"a\")\n 'a'\n >>> longest_common_substring(\"abcdef\", \"bcd\")\n 'bcd'\n >>> longest_common_substring(\"abcdef\", \"xabded\")\n 'ab'\n >>> longest_common_substring(\"GeeksforGeeks\", \"GeeksQuiz\")\n 'Geeks'\n >>> longest_common_substring(\"abcdxyz\", \"xyzabcd\")\n 'abcd'\n >>> longest_common_substring(\"zxabcdezy\", \"yzabcdezx\")\n 'abcdez'\n >>> longest_common_substring(\"OldSite:GeeksforGeeks.org\", \"NewSite:GeeksQuiz.com\")\n 'Site:Geeks'\n >>> longest_common_substring(1, 1)\n Traceback (most recent call last):\n ...\n ValueError: longest_common_substring() takes two strings for inputs\n \"\"\"\n\n if not (isinstance(text1, str) and isinstance(text2, str)):\n raise ValueError(\"longest_common_substring() takes two strings for inputs\")\n\n text1_length = len(text1)\n text2_length = len(text2)\n\n dp = [[0] * (text2_length + 1) for _ in range(text1_length + 1)]\n ans_index = 0\n ans_length = 0\n\n for i in range(1, text1_length + 1):\n for j in range(1, text2_length + 1):\n if text1[i - 1] == text2[j - 1]:\n dp[i][j] = 1 + dp[i - 1][j - 1]\n if dp[i][j] > ans_length:\n ans_index = i\n ans_length = dp[i][j]\n\n return text1[ans_index - ans_length : ans_index]\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Author : Mehdi ALAOUI This is a pure Python implementation of Dynamic Programming solution to the longest increasing subsequence of a given sequence. The problem is : Given an array, to find the longest and increasing subarray in that given array and return it. Example: 10, 22, 9, 33, 21, 50, 41, 60, 80 as input will return 10, 22, 33, 41, 60, 80 as output Some examples longestsubsequence10, 22, 9, 33, 21, 50, 41, 60, 80 10, 22, 33, 41, 60, 80 longestsubsequence4, 8, 7, 5, 1, 12, 2, 3, 9 1, 2, 3, 9 longestsubsequence9, 8, 7, 6, 5, 7 8 longestsubsequence1, 1, 1 1, 1, 1 longestsubsequence If the array contains only one element, we return it it's the stop condition of recursion Else","Completions":"from __future__ import annotations\n\n\ndef longest_subsequence(array: list[int]) -> list[int]: # This function is recursive\n \"\"\"\n Some examples\n >>> longest_subsequence([10, 22, 9, 33, 21, 50, 41, 60, 80])\n [10, 22, 33, 41, 60, 80]\n >>> longest_subsequence([4, 8, 7, 5, 1, 12, 2, 3, 9])\n [1, 2, 3, 9]\n >>> longest_subsequence([9, 8, 7, 6, 5, 7])\n [8]\n >>> longest_subsequence([1, 1, 1])\n [1, 1, 1]\n >>> longest_subsequence([])\n []\n \"\"\"\n array_length = len(array)\n # If the array contains only one element, we return it (it's the stop condition of\n # recursion)\n if array_length <= 1:\n return array\n # Else\n pivot = array[0]\n is_found = False\n i = 1\n longest_subseq: list[int] = []\n while not is_found and i < array_length:\n if array[i] < pivot:\n is_found = True\n temp_array = [element for element in array[i:] if element >= array[i]]\n temp_array = longest_subsequence(temp_array)\n if len(temp_array) > len(longest_subseq):\n longest_subseq = temp_array\n else:\n i += 1\n\n temp_array = [element for element in array[1:] if element >= pivot]\n temp_array = [pivot, *longest_subsequence(temp_array)]\n if len(temp_array) > len(longest_subseq):\n return temp_array\n else:\n return longest_subseq\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Author: Aravind Kashyap File: lis.py comments: This programme outputs the Longest Strictly Increasing Subsequence in ONLogN Where N is the Number of elements in the list longestincreasingsubsequencelength2, 5, 3, 7, 11, 8, 10, 13, 6 6 longestincreasingsubsequencelength 0 longestincreasingsubsequencelength0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, ... 3, 11, 7, 15 6 longestincreasingsubsequencelength5, 4, 3, 2, 1 1","Completions":"#############################\n# Author: Aravind Kashyap\n# File: lis.py\n# comments: This programme outputs the Longest Strictly Increasing Subsequence in\n# O(NLogN) Where N is the Number of elements in the list\n#############################\nfrom __future__ import annotations\n\n\ndef ceil_index(v, l, r, key): # noqa: E741\n while r - l > 1:\n m = (l + r) \/\/ 2\n if v[m] >= key:\n r = m\n else:\n l = m # noqa: E741\n return r\n\n\ndef longest_increasing_subsequence_length(v: list[int]) -> int:\n \"\"\"\n >>> longest_increasing_subsequence_length([2, 5, 3, 7, 11, 8, 10, 13, 6])\n 6\n >>> longest_increasing_subsequence_length([])\n 0\n >>> longest_increasing_subsequence_length([0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13,\n ... 3, 11, 7, 15])\n 6\n >>> longest_increasing_subsequence_length([5, 4, 3, 2, 1])\n 1\n \"\"\"\n if len(v) == 0:\n return 0\n\n tail = [0] * len(v)\n length = 1\n\n tail[0] = v[0]\n\n for i in range(1, len(v)):\n if v[i] < tail[0]:\n tail[0] = v[i]\n elif v[i] > tail[length - 1]:\n tail[length] = v[i]\n length += 1\n else:\n tail[ceil_index(tail, -1, length - 1, v[i])] = v[i]\n\n return length\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"author: Sanket Kittad Given a string s, find the longest palindromic subsequence's length in s. Input: s bbbab Output: 4 Explanation: One possible longest palindromic subsequence is bbbb. Leetcode link: https:leetcode.comproblemslongestpalindromicsubsequencedescription This function returns the longest palindromic subsequence in a string longestpalindromicsubsequencebbbab 4 longestpalindromicsubsequencebbabcbcab 7 create and initialise dp array If characters at i and j are the same include them in the palindromic subsequence","Completions":"def longest_palindromic_subsequence(input_string: str) -> int:\n \"\"\"\n This function returns the longest palindromic subsequence in a string\n >>> longest_palindromic_subsequence(\"bbbab\")\n 4\n >>> longest_palindromic_subsequence(\"bbabcbcab\")\n 7\n \"\"\"\n n = len(input_string)\n rev = input_string[::-1]\n m = len(rev)\n dp = [[-1] * (m + 1) for i in range(n + 1)]\n for i in range(n + 1):\n dp[i][0] = 0\n for i in range(m + 1):\n dp[0][i] = 0\n\n # create and initialise dp array\n for i in range(1, n + 1):\n for j in range(1, m + 1):\n # If characters at i and j are the same\n # include them in the palindromic subsequence\n if input_string[i - 1] == rev[j - 1]:\n dp[i][j] = 1 + dp[i - 1][j - 1]\n else:\n dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])\n\n return dp[n][m]\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Find the minimum number of multiplications needed to multiply chain of matrices. Reference: https:www.geeksforgeeks.orgmatrixchainmultiplicationdp8 The algorithm has interesting realworld applications. Example: 1. Image transformations in Computer Graphics as images are composed of matrix. 2. Solve complex polynomial equations in the field of algebra using least processing power. 3. Calculate overall impact of macroeconomic decisions as economic equations involve a number of variables. 4. Selfdriving car navigation can be made more accurate as matrix multiplication can accurately determine position and orientation of obstacles in short time. Python doctests can be run with the following command: python m doctest v matrixchainmultiply.py Given a sequence arr that represents chain of 2D matrices such that the dimension of the ith matrix is arri1arri. So suppose arr 40, 20, 30, 10, 30 means we have 4 matrices of dimensions 4020, 2030, 3010 and 1030. matrixchainmultiply returns an integer denoting minimum number of multiplications to multiply the chain. We do not need to perform actual multiplication here. We only need to decide the order in which to perform the multiplication. Hints: 1. Number of multiplications ie cost to multiply 2 matrices of size mp and pn is mpn. 2. Cost of matrix multiplication is associative ie M1M2M3 ! M1M2M3 3. Matrix multiplication is not commutative. So, M1M2 does not mean M2M1 can be done. 4. To determine the required order, we can try different combinations. So, this problem has overlapping subproblems and can be solved using recursion. We use Dynamic Programming for optimal time complexity. Example input: arr 40, 20, 30, 10, 30 output: 26000 Find the minimum number of multiplcations required to multiply the chain of matrices Args: arr: The input array of integers. Returns: Minimum number of multiplications needed to multiply the chain Examples: matrixchainmultiply1, 2, 3, 4, 3 30 matrixchainmultiply10 0 matrixchainmultiply10, 20 0 matrixchainmultiply19, 2, 19 722 matrixchainmultiplylistrange1, 100 323398 matrixchainmultiplylistrange1, 251 2626798 initialising 2D dp matrix we want minimum cost of multiplication of matrices of dimension ik and kj. This cost is arri1arrkarrj. Source: https:en.wikipedia.orgwikiMatrixchainmultiplication The dynamic programming solution is faster than cached the recursive solution and can handle larger inputs. matrixchainorder1, 2, 3, 4, 3 30 matrixchainorder10 0 matrixchainorder10, 20 0 matrixchainorder19, 2, 19 722 matrixchainorderlistrange1, 100 323398 matrixchainorderlistrange1, 251 Max before RecursionError is raised 2626798 printfStarting: msg","Completions":"from collections.abc import Iterator\nfrom contextlib import contextmanager\nfrom functools import cache\nfrom sys import maxsize\n\n\ndef matrix_chain_multiply(arr: list[int]) -> int:\n \"\"\"\n Find the minimum number of multiplcations required to multiply the chain of matrices\n\n Args:\n arr: The input array of integers.\n\n Returns:\n Minimum number of multiplications needed to multiply the chain\n\n Examples:\n >>> matrix_chain_multiply([1, 2, 3, 4, 3])\n 30\n >>> matrix_chain_multiply([10])\n 0\n >>> matrix_chain_multiply([10, 20])\n 0\n >>> matrix_chain_multiply([19, 2, 19])\n 722\n >>> matrix_chain_multiply(list(range(1, 100)))\n 323398\n\n # >>> matrix_chain_multiply(list(range(1, 251)))\n # 2626798\n \"\"\"\n if len(arr) < 2:\n return 0\n # initialising 2D dp matrix\n n = len(arr)\n dp = [[maxsize for j in range(n)] for i in range(n)]\n # we want minimum cost of multiplication of matrices\n # of dimension (i*k) and (k*j). This cost is arr[i-1]*arr[k]*arr[j].\n for i in range(n - 1, 0, -1):\n for j in range(i, n):\n if i == j:\n dp[i][j] = 0\n continue\n for k in range(i, j):\n dp[i][j] = min(\n dp[i][j], dp[i][k] + dp[k + 1][j] + arr[i - 1] * arr[k] * arr[j]\n )\n\n return dp[1][n - 1]\n\n\ndef matrix_chain_order(dims: list[int]) -> int:\n \"\"\"\n Source: https:\/\/en.wikipedia.org\/wiki\/Matrix_chain_multiplication\n The dynamic programming solution is faster than cached the recursive solution and\n can handle larger inputs.\n >>> matrix_chain_order([1, 2, 3, 4, 3])\n 30\n >>> matrix_chain_order([10])\n 0\n >>> matrix_chain_order([10, 20])\n 0\n >>> matrix_chain_order([19, 2, 19])\n 722\n >>> matrix_chain_order(list(range(1, 100)))\n 323398\n\n # >>> matrix_chain_order(list(range(1, 251))) # Max before RecursionError is raised\n # 2626798\n \"\"\"\n\n @cache\n def a(i: int, j: int) -> int:\n return min(\n (a(i, k) + dims[i] * dims[k] * dims[j] + a(k, j) for k in range(i + 1, j)),\n default=0,\n )\n\n return a(0, len(dims) - 1)\n\n\n@contextmanager\ndef elapsed_time(msg: str) -> Iterator:\n # print(f\"Starting: {msg}\")\n from time import perf_counter_ns\n\n start = perf_counter_ns()\n yield\n print(f\"Finished: {msg} in {(perf_counter_ns() - start) \/ 10 ** 9} seconds.\")\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n with elapsed_time(\"matrix_chain_order\"):\n print(f\"{matrix_chain_order(list(range(1, 251))) = }\")\n with elapsed_time(\"matrix_chain_multiply\"):\n print(f\"{matrix_chain_multiply(list(range(1, 251))) = }\")\n with elapsed_time(\"matrix_chain_order\"):\n print(f\"{matrix_chain_order(list(range(1, 251))) = }\")\n with elapsed_time(\"matrix_chain_multiply\"):\n print(f\"{matrix_chain_multiply(list(range(1, 251))) = }\")\n"} +{"Prompt":"Dynamic Programming Implementation of Matrix Chain Multiplication Time Complexity: On3 Space Complexity: On2 Print order of matrix with Ai as Matrix Size of matrix created from above array will be 3035 3515 155 510 1020 2025","Completions":"import sys\n\n\"\"\"\nDynamic Programming\nImplementation of Matrix Chain Multiplication\nTime Complexity: O(n^3)\nSpace Complexity: O(n^2)\n\"\"\"\n\n\ndef matrix_chain_order(array):\n n = len(array)\n matrix = [[0 for x in range(n)] for x in range(n)]\n sol = [[0 for x in range(n)] for x in range(n)]\n\n for chain_length in range(2, n):\n for a in range(1, n - chain_length + 1):\n b = a + chain_length - 1\n\n matrix[a][b] = sys.maxsize\n for c in range(a, b):\n cost = (\n matrix[a][c] + matrix[c + 1][b] + array[a - 1] * array[c] * array[b]\n )\n if cost < matrix[a][b]:\n matrix[a][b] = cost\n sol[a][b] = c\n return matrix, sol\n\n\n# Print order of matrix with Ai as Matrix\ndef print_optiomal_solution(optimal_solution, i, j):\n if i == j:\n print(\"A\" + str(i), end=\" \")\n else:\n print(\"(\", end=\" \")\n print_optiomal_solution(optimal_solution, i, optimal_solution[i][j])\n print_optiomal_solution(optimal_solution, optimal_solution[i][j] + 1, j)\n print(\")\", end=\" \")\n\n\ndef main():\n array = [30, 35, 15, 5, 10, 20, 25]\n n = len(array)\n # Size of matrix created from above array will be\n # 30*35 35*15 15*5 5*10 10*20 20*25\n matrix, optimal_solution = matrix_chain_order(array)\n\n print(\"No. of Operation required: \" + str(matrix[1][n - 1]))\n print_optiomal_solution(optimal_solution, 1, n - 1)\n\n\nif __name__ == \"__main__\":\n main()\n"} +{"Prompt":"Video Explanation: https:www.youtube.comwatch?v6w60Zi1NtL8featureemblogo Find the maximum nonadjacent sum of the integers in the nums input list maximumnonadjacentsum1, 2, 3 4 maximumnonadjacentsum1, 5, 3, 7, 2, 2, 6 18 maximumnonadjacentsum1, 5, 3, 7, 2, 2, 6 0 maximumnonadjacentsum499, 500, 3, 7, 2, 2, 6 500","Completions":"# Video Explanation: https:\/\/www.youtube.com\/watch?v=6w60Zi1NtL8&feature=emb_logo\n\nfrom __future__ import annotations\n\n\ndef maximum_non_adjacent_sum(nums: list[int]) -> int:\n \"\"\"\n Find the maximum non-adjacent sum of the integers in the nums input list\n\n >>> maximum_non_adjacent_sum([1, 2, 3])\n 4\n >>> maximum_non_adjacent_sum([1, 5, 3, 7, 2, 2, 6])\n 18\n >>> maximum_non_adjacent_sum([-1, -5, -3, -7, -2, -2, -6])\n 0\n >>> maximum_non_adjacent_sum([499, 500, -3, -7, -2, -2, -6])\n 500\n \"\"\"\n if not nums:\n return 0\n max_including = nums[0]\n max_excluding = 0\n for num in nums[1:]:\n max_including, max_excluding = (\n max_excluding + num,\n max(max_including, max_excluding),\n )\n return max(max_excluding, max_including)\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Returns the maximum product that can be obtained by multiplying a contiguous subarray of the given integer list nums. Example: maxproductsubarray2, 3, 2, 4 6 maxproductsubarray2, 0, 1 0 maxproductsubarray2, 3, 2, 4, 1 48 maxproductsubarray1 1 maxproductsubarray0 0 maxproductsubarray 0 maxproductsubarray 0 maxproductsubarrayNone 0 maxproductsubarray2, 3, 2, 4.5, 1 Traceback most recent call last: ... ValueError: numbers must be an iterable of integers maxproductsubarrayABC Traceback most recent call last: ... ValueError: numbers must be an iterable of integers update the maximum and minimum subarray products update the maximum product found till now","Completions":"def max_product_subarray(numbers: list[int]) -> int:\n \"\"\"\n Returns the maximum product that can be obtained by multiplying a\n contiguous subarray of the given integer list `nums`.\n\n Example:\n >>> max_product_subarray([2, 3, -2, 4])\n 6\n >>> max_product_subarray((-2, 0, -1))\n 0\n >>> max_product_subarray([2, 3, -2, 4, -1])\n 48\n >>> max_product_subarray([-1])\n -1\n >>> max_product_subarray([0])\n 0\n >>> max_product_subarray([])\n 0\n >>> max_product_subarray(\"\")\n 0\n >>> max_product_subarray(None)\n 0\n >>> max_product_subarray([2, 3, -2, 4.5, -1])\n Traceback (most recent call last):\n ...\n ValueError: numbers must be an iterable of integers\n >>> max_product_subarray(\"ABC\")\n Traceback (most recent call last):\n ...\n ValueError: numbers must be an iterable of integers\n \"\"\"\n if not numbers:\n return 0\n\n if not isinstance(numbers, (list, tuple)) or not all(\n isinstance(number, int) for number in numbers\n ):\n raise ValueError(\"numbers must be an iterable of integers\")\n\n max_till_now = min_till_now = max_prod = numbers[0]\n\n for i in range(1, len(numbers)):\n # update the maximum and minimum subarray products\n number = numbers[i]\n if number < 0:\n max_till_now, min_till_now = min_till_now, max_till_now\n max_till_now = max(number, max_till_now * number)\n min_till_now = min(number, min_till_now * number)\n\n # update the maximum product found till now\n max_prod = max(max_prod, max_till_now)\n\n return max_prod\n"} +{"Prompt":"The maximum subarray sum problem is the task of finding the maximum sum that can be obtained from a contiguous subarray within a given array of numbers. For example, given the array 2, 1, 3, 4, 1, 2, 1, 5, 4, the contiguous subarray with the maximum sum is 4, 1, 2, 1, so the maximum subarray sum is 6. Kadane's algorithm is a simple dynamic programming algorithm that solves the maximum subarray sum problem in On time and O1 space. Reference: https:en.wikipedia.orgwikiMaximumsubarrayproblem Solves the maximum subarray sum problem using Kadane's algorithm. :param arr: the given array of numbers :param allowemptysubarrays: if True, then the algorithm considers empty subarrays maxsubarraysum2, 8, 9 19 maxsubarraysum0, 0 0 maxsubarraysum1.0, 0.0, 1.0 1.0 maxsubarraysum1, 2, 3, 4, 2 10 maxsubarraysum2, 1, 3, 4, 1, 2, 1, 5, 4 6 maxsubarraysum2, 3, 9, 8, 2 8 maxsubarraysum2, 3, 1, 4, 6 1 maxsubarraysum2, 3, 1, 4, 6, allowemptysubarraysTrue 0 maxsubarraysum 0","Completions":"from collections.abc import Sequence\n\n\ndef max_subarray_sum(\n arr: Sequence[float], allow_empty_subarrays: bool = False\n) -> float:\n \"\"\"\n Solves the maximum subarray sum problem using Kadane's algorithm.\n :param arr: the given array of numbers\n :param allow_empty_subarrays: if True, then the algorithm considers empty subarrays\n\n >>> max_subarray_sum([2, 8, 9])\n 19\n >>> max_subarray_sum([0, 0])\n 0\n >>> max_subarray_sum([-1.0, 0.0, 1.0])\n 1.0\n >>> max_subarray_sum([1, 2, 3, 4, -2])\n 10\n >>> max_subarray_sum([-2, 1, -3, 4, -1, 2, 1, -5, 4])\n 6\n >>> max_subarray_sum([2, 3, -9, 8, -2])\n 8\n >>> max_subarray_sum([-2, -3, -1, -4, -6])\n -1\n >>> max_subarray_sum([-2, -3, -1, -4, -6], allow_empty_subarrays=True)\n 0\n >>> max_subarray_sum([])\n 0\n \"\"\"\n if not arr:\n return 0\n\n max_sum = 0 if allow_empty_subarrays else float(\"-inf\")\n curr_sum = 0.0\n for num in arr:\n curr_sum = max(0 if allow_empty_subarrays else num, curr_sum + num)\n max_sum = max(max_sum, curr_sum)\n\n return max_sum\n\n\nif __name__ == \"__main__\":\n from doctest import testmod\n\n testmod()\n\n nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4]\n print(f\"{max_subarray_sum(nums) = }\")\n"} +{"Prompt":"Author : Alexander Pantyukhin Date : October 14, 2022 This is an implementation of the upbottom approach to find edit distance. The implementation was tested on Leetcode: https:leetcode.comproblemseditdistance Levinstein distance Dynamic Programming: up down. mindistanceupbottomintention, execution 5 mindistanceupbottomintention, 9 mindistanceupbottom, 0 mindistanceupbottomzooicoarchaeologist, zoologist 10 if first word index overflows delete all from the second word if second word index overflows delete all from the first word","Completions":"import functools\n\n\ndef min_distance_up_bottom(word1: str, word2: str) -> int:\n \"\"\"\n >>> min_distance_up_bottom(\"intention\", \"execution\")\n 5\n >>> min_distance_up_bottom(\"intention\", \"\")\n 9\n >>> min_distance_up_bottom(\"\", \"\")\n 0\n >>> min_distance_up_bottom(\"zooicoarchaeologist\", \"zoologist\")\n 10\n \"\"\"\n len_word1 = len(word1)\n len_word2 = len(word2)\n\n @functools.cache\n def min_distance(index1: int, index2: int) -> int:\n # if first word index overflows - delete all from the second word\n if index1 >= len_word1:\n return len_word2 - index2\n # if second word index overflows - delete all from the first word\n if index2 >= len_word2:\n return len_word1 - index1\n diff = int(word1[index1] != word2[index2]) # current letters not identical\n return min(\n 1 + min_distance(index1 + 1, index2),\n 1 + min_distance(index1, index2 + 1),\n diff + min_distance(index1 + 1, index2 + 1),\n )\n\n return min_distance(0, 0)\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"You have m types of coins available in infinite quantities where the value of each coins is given in the array SS0,... Sm1 Can you determine number of ways of making change for n units using the given types of coins? https:www.hackerrank.comchallengescoinchangeproblem dpcount1, 2, 3, 4 4 dpcount1, 2, 3, 7 8 dpcount2, 5, 3, 6, 10 5 dpcount10, 99 0 dpcount4, 5, 6, 0 1 dpcount1, 2, 3, 5 0 tablei represents the number of ways to get to amount i There is exactly 1 way to get to zeroYou pick no coins. Pick all coins one by one and update table values after the index greater than or equal to the value of the picked coin","Completions":"def dp_count(s, n):\n \"\"\"\n >>> dp_count([1, 2, 3], 4)\n 4\n >>> dp_count([1, 2, 3], 7)\n 8\n >>> dp_count([2, 5, 3, 6], 10)\n 5\n >>> dp_count([10], 99)\n 0\n >>> dp_count([4, 5, 6], 0)\n 1\n >>> dp_count([1, 2, 3], -5)\n 0\n \"\"\"\n if n < 0:\n return 0\n # table[i] represents the number of ways to get to amount i\n table = [0] * (n + 1)\n\n # There is exactly 1 way to get to zero(You pick no coins).\n table[0] = 1\n\n # Pick all coins one by one and update table[] values\n # after the index greater than or equal to the value of the\n # picked coin\n for coin_val in s:\n for j in range(coin_val, n + 1):\n table[j] += table[j - coin_val]\n\n return table[n]\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Youtube Explanation: https:www.youtube.comwatch?vlBRtnuxggU Find the minimum cost traced by all possible paths from top left to bottom right in a given matrix minimumcostpath2, 1, 3, 1, 4, 2 6 minimumcostpath2, 1, 4, 2, 1, 3, 3, 2, 1 7 preprocessing the first row preprocessing the first column updating the path cost for current position","Completions":"# Youtube Explanation: https:\/\/www.youtube.com\/watch?v=lBRtnuxg-gU\n\nfrom __future__ import annotations\n\n\ndef minimum_cost_path(matrix: list[list[int]]) -> int:\n \"\"\"\n Find the minimum cost traced by all possible paths from top left to bottom right in\n a given matrix\n\n >>> minimum_cost_path([[2, 1], [3, 1], [4, 2]])\n 6\n\n >>> minimum_cost_path([[2, 1, 4], [2, 1, 3], [3, 2, 1]])\n 7\n \"\"\"\n\n # preprocessing the first row\n for i in range(1, len(matrix[0])):\n matrix[0][i] += matrix[0][i - 1]\n\n # preprocessing the first column\n for i in range(1, len(matrix)):\n matrix[i][0] += matrix[i - 1][0]\n\n # updating the path cost for current position\n for i in range(1, len(matrix)):\n for j in range(1, len(matrix[0])):\n matrix[i][j] += min(matrix[i - 1][j], matrix[i][j - 1])\n\n return matrix[-1][-1]\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Partition a set into two subsets such that the difference of subset sums is minimum findmin1, 2, 3, 4, 5 1 findmin5, 5, 5, 5, 5 5 findmin5, 5, 5, 5 0 findmin3 3 findmin 0 findmin1, 2, 3, 4 0 findmin0, 0, 0, 0 0 findmin1, 5, 5, 1 0 findmin1, 5, 5, 1 0 findmin9, 9, 9, 9, 9 9 findmin1, 5, 10, 3 1 findmin1, 0, 1 0 findminrange10, 0, 1 1 findmin1 Traceback most recent call last: IndexError: list assignment index out of range findmin0, 0, 0, 1, 2, 4 Traceback most recent call last: ... IndexError: list assignment index out of range findmin1, 5, 10, 3 Traceback most recent call last: ... IndexError: list assignment index out of range","Completions":"def find_min(numbers: list[int]) -> int:\n \"\"\"\n >>> find_min([1, 2, 3, 4, 5])\n 1\n >>> find_min([5, 5, 5, 5, 5])\n 5\n >>> find_min([5, 5, 5, 5])\n 0\n >>> find_min([3])\n 3\n >>> find_min([])\n 0\n >>> find_min([1, 2, 3, 4])\n 0\n >>> find_min([0, 0, 0, 0])\n 0\n >>> find_min([-1, -5, 5, 1])\n 0\n >>> find_min([-1, -5, 5, 1])\n 0\n >>> find_min([9, 9, 9, 9, 9])\n 9\n >>> find_min([1, 5, 10, 3])\n 1\n >>> find_min([-1, 0, 1])\n 0\n >>> find_min(range(10, 0, -1))\n 1\n >>> find_min([-1])\n Traceback (most recent call last):\n --\n IndexError: list assignment index out of range\n >>> find_min([0, 0, 0, 1, 2, -4])\n Traceback (most recent call last):\n ...\n IndexError: list assignment index out of range\n >>> find_min([-1, -5, -10, -3])\n Traceback (most recent call last):\n ...\n IndexError: list assignment index out of range\n \"\"\"\n n = len(numbers)\n s = sum(numbers)\n\n dp = [[False for x in range(s + 1)] for y in range(n + 1)]\n\n for i in range(n + 1):\n dp[i][0] = True\n\n for i in range(1, s + 1):\n dp[0][i] = False\n\n for i in range(1, n + 1):\n for j in range(1, s + 1):\n dp[i][j] = dp[i - 1][j]\n\n if numbers[i - 1] <= j:\n dp[i][j] = dp[i][j] or dp[i - 1][j - numbers[i - 1]]\n\n for j in range(int(s \/ 2), -1, -1):\n if dp[n][j] is True:\n diff = s - 2 * j\n break\n\n return diff\n\n\nif __name__ == \"__main__\":\n from doctest import testmod\n\n testmod()\n"} +{"Prompt":"Return the length of the shortest contiguous subarray in a list of numbers whose sum is at least target. Reference: https:stackoverflow.comquestions8269916 minimumsubarraysum7, 2, 3, 1, 2, 4, 3 2 minimumsubarraysum7, 2, 3, 1, 2, 4, 3 4 minimumsubarraysum11, 1, 1, 1, 1, 1, 1, 1, 1 0 minimumsubarraysum10, 1, 2, 3, 4, 5, 6, 7 2 minimumsubarraysum5, 1, 1, 1, 1, 1, 5 1 minimumsubarraysum0, 0 minimumsubarraysum0, 1, 2, 3 1 minimumsubarraysum10, 10, 20, 30 1 minimumsubarraysum7, 1, 1, 1, 1, 1, 1, 10 1 minimumsubarraysum6, 0 minimumsubarraysum2, 1, 2, 3 1 minimumsubarraysum6, 0 minimumsubarraysum6, 3, 4, 5 1 minimumsubarraysum8, None 0 minimumsubarraysum2, ABC Traceback most recent call last: ... ValueError: numbers must be an iterable of integers","Completions":"import sys\n\n\ndef minimum_subarray_sum(target: int, numbers: list[int]) -> int:\n \"\"\"\n Return the length of the shortest contiguous subarray in a list of numbers whose sum\n is at least target. Reference: https:\/\/stackoverflow.com\/questions\/8269916\n\n >>> minimum_subarray_sum(7, [2, 3, 1, 2, 4, 3])\n 2\n >>> minimum_subarray_sum(7, [2, 3, -1, 2, 4, -3])\n 4\n >>> minimum_subarray_sum(11, [1, 1, 1, 1, 1, 1, 1, 1])\n 0\n >>> minimum_subarray_sum(10, [1, 2, 3, 4, 5, 6, 7])\n 2\n >>> minimum_subarray_sum(5, [1, 1, 1, 1, 1, 5])\n 1\n >>> minimum_subarray_sum(0, [])\n 0\n >>> minimum_subarray_sum(0, [1, 2, 3])\n 1\n >>> minimum_subarray_sum(10, [10, 20, 30])\n 1\n >>> minimum_subarray_sum(7, [1, 1, 1, 1, 1, 1, 10])\n 1\n >>> minimum_subarray_sum(6, [])\n 0\n >>> minimum_subarray_sum(2, [1, 2, 3])\n 1\n >>> minimum_subarray_sum(-6, [])\n 0\n >>> minimum_subarray_sum(-6, [3, 4, 5])\n 1\n >>> minimum_subarray_sum(8, None)\n 0\n >>> minimum_subarray_sum(2, \"ABC\")\n Traceback (most recent call last):\n ...\n ValueError: numbers must be an iterable of integers\n \"\"\"\n if not numbers:\n return 0\n if target == 0 and target in numbers:\n return 0\n if not isinstance(numbers, (list, tuple)) or not all(\n isinstance(number, int) for number in numbers\n ):\n raise ValueError(\"numbers must be an iterable of integers\")\n\n left = right = curr_sum = 0\n min_len = sys.maxsize\n\n while right < len(numbers):\n curr_sum += numbers[right]\n while curr_sum >= target and left <= right:\n min_len = min(min_len, right - left + 1)\n curr_sum -= numbers[left]\n left += 1\n right += 1\n\n return 0 if min_len == sys.maxsize else min_len\n"} +{"Prompt":"Count the number of minimum squares to represent a number minimumsquarestorepresentanumber25 1 minimumsquarestorepresentanumber37 2 minimumsquarestorepresentanumber21 3 minimumsquarestorepresentanumber58 2 minimumsquarestorepresentanumber1 Traceback most recent call last: ... ValueError: the value of input must not be a negative number minimumsquarestorepresentanumber0 1 minimumsquarestorepresentanumber12.34 Traceback most recent call last: ... ValueError: the value of input must be a natural number","Completions":"import math\nimport sys\n\n\ndef minimum_squares_to_represent_a_number(number: int) -> int:\n \"\"\"\n Count the number of minimum squares to represent a number\n >>> minimum_squares_to_represent_a_number(25)\n 1\n >>> minimum_squares_to_represent_a_number(37)\n 2\n >>> minimum_squares_to_represent_a_number(21)\n 3\n >>> minimum_squares_to_represent_a_number(58)\n 2\n >>> minimum_squares_to_represent_a_number(-1)\n Traceback (most recent call last):\n ...\n ValueError: the value of input must not be a negative number\n >>> minimum_squares_to_represent_a_number(0)\n 1\n >>> minimum_squares_to_represent_a_number(12.34)\n Traceback (most recent call last):\n ...\n ValueError: the value of input must be a natural number\n \"\"\"\n if number != int(number):\n raise ValueError(\"the value of input must be a natural number\")\n if number < 0:\n raise ValueError(\"the value of input must not be a negative number\")\n if number == 0:\n return 1\n answers = [-1] * (number + 1)\n answers[0] = 0\n for i in range(1, number + 1):\n answer = sys.maxsize\n root = int(math.sqrt(i))\n for j in range(1, root + 1):\n current_answer = 1 + answers[i - (j**2)]\n answer = min(answer, current_answer)\n answers[i] = answer\n return answers[number]\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"YouTube Explanation: https:www.youtube.comwatch?vf2xi3c1S95M Given an integer n, return the minimum steps from n to 1 AVAILABLE STEPS: Decrement by 1 if n is divisible by 2, divide by 2 if n is divisible by 3, divide by 3 Example 1: n 10 10 9 3 1 Result: 3 steps Example 2: n 15 15 5 4 2 1 Result: 4 steps Example 3: n 6 6 2 1 Result: 2 step Minimum steps to 1 implemented using tabulation. minstepstoone10 3 minstepstoone15 4 minstepstoone6 2 :param number: :return int: starting position check if out of bounds check if out of bounds","Completions":"from __future__ import annotations\n\n__author__ = \"Alexander Joslin\"\n\n\ndef min_steps_to_one(number: int) -> int:\n \"\"\"\n Minimum steps to 1 implemented using tabulation.\n >>> min_steps_to_one(10)\n 3\n >>> min_steps_to_one(15)\n 4\n >>> min_steps_to_one(6)\n 2\n\n :param number:\n :return int:\n \"\"\"\n\n if number <= 0:\n msg = f\"n must be greater than 0. Got n = {number}\"\n raise ValueError(msg)\n\n table = [number + 1] * (number + 1)\n\n # starting position\n table[1] = 0\n for i in range(1, number):\n table[i + 1] = min(table[i + 1], table[i] + 1)\n # check if out of bounds\n if i * 2 <= number:\n table[i * 2] = min(table[i * 2], table[i] + 1)\n # check if out of bounds\n if i * 3 <= number:\n table[i * 3] = min(table[i * 3], table[i] + 1)\n return table[number]\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Author : Alexander Pantyukhin Date : November 1, 2022 Task: Given a list of days when you need to travel. Each day is integer from 1 to 365. You are able to use tickets for 1 day, 7 days and 30 days. Each ticket has a cost. Find the minimum cost you need to travel every day in the given list of days. Implementation notes: implementation Dynamic Programming up bottom approach. Runtime complexity: On The implementation was tested on the leetcode: https:leetcode.comproblemsminimumcostfortickets Minimum Cost For Tickets Dynamic Programming: up down. mincosttickets1, 4, 6, 7, 8, 20, 2, 7, 15 11 mincosttickets1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 30, 31, 2, 7, 15 17 mincosttickets1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 30, 31, 2, 90, 150 24 mincosttickets2, 2, 90, 150 2 mincosttickets, 2, 90, 150 0 mincosttickets'hello', 2, 90, 150 Traceback most recent call last: ... ValueError: The parameter days should be a list of integers mincosttickets, 'world' Traceback most recent call last: ... ValueError: The parameter costs should be a list of three integers mincosttickets0.25, 2, 3, 4, 5, 6, 7, 8, 9, 10, 30, 31, 2, 90, 150 Traceback most recent call last: ... ValueError: The parameter days should be a list of integers mincosttickets1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 30, 31, 2, 0.9, 150 Traceback most recent call last: ... ValueError: The parameter costs should be a list of three integers mincosttickets1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 30, 31, 2, 90, 150 Traceback most recent call last: ... ValueError: All days elements should be greater than 0 mincosttickets2, 367, 2, 90, 150 Traceback most recent call last: ... ValueError: All days elements should be less than 366 mincosttickets2, 3, 4, 5, 6, 7, 8, 9, 10, 30, 31, Traceback most recent call last: ... ValueError: The parameter costs should be a list of three integers mincosttickets, Traceback most recent call last: ... ValueError: The parameter costs should be a list of three integers mincosttickets2, 3, 4, 5, 6, 7, 8, 9, 10, 30, 31, 1, 2, 3, 4 Traceback most recent call last: ... ValueError: The parameter costs should be a list of three integers Validation","Completions":"import functools\n\n\ndef mincost_tickets(days: list[int], costs: list[int]) -> int:\n \"\"\"\n >>> mincost_tickets([1, 4, 6, 7, 8, 20], [2, 7, 15])\n 11\n\n >>> mincost_tickets([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 30, 31], [2, 7, 15])\n 17\n\n >>> mincost_tickets([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 30, 31], [2, 90, 150])\n 24\n\n >>> mincost_tickets([2], [2, 90, 150])\n 2\n\n >>> mincost_tickets([], [2, 90, 150])\n 0\n\n >>> mincost_tickets('hello', [2, 90, 150])\n Traceback (most recent call last):\n ...\n ValueError: The parameter days should be a list of integers\n\n >>> mincost_tickets([], 'world')\n Traceback (most recent call last):\n ...\n ValueError: The parameter costs should be a list of three integers\n\n >>> mincost_tickets([0.25, 2, 3, 4, 5, 6, 7, 8, 9, 10, 30, 31], [2, 90, 150])\n Traceback (most recent call last):\n ...\n ValueError: The parameter days should be a list of integers\n\n >>> mincost_tickets([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 30, 31], [2, 0.9, 150])\n Traceback (most recent call last):\n ...\n ValueError: The parameter costs should be a list of three integers\n\n >>> mincost_tickets([-1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 30, 31], [2, 90, 150])\n Traceback (most recent call last):\n ...\n ValueError: All days elements should be greater than 0\n\n >>> mincost_tickets([2, 367], [2, 90, 150])\n Traceback (most recent call last):\n ...\n ValueError: All days elements should be less than 366\n\n >>> mincost_tickets([2, 3, 4, 5, 6, 7, 8, 9, 10, 30, 31], [])\n Traceback (most recent call last):\n ...\n ValueError: The parameter costs should be a list of three integers\n\n >>> mincost_tickets([], [])\n Traceback (most recent call last):\n ...\n ValueError: The parameter costs should be a list of three integers\n\n >>> mincost_tickets([2, 3, 4, 5, 6, 7, 8, 9, 10, 30, 31], [1, 2, 3, 4])\n Traceback (most recent call last):\n ...\n ValueError: The parameter costs should be a list of three integers\n \"\"\"\n\n # Validation\n if not isinstance(days, list) or not all(isinstance(day, int) for day in days):\n raise ValueError(\"The parameter days should be a list of integers\")\n\n if len(costs) != 3 or not all(isinstance(cost, int) for cost in costs):\n raise ValueError(\"The parameter costs should be a list of three integers\")\n\n if len(days) == 0:\n return 0\n\n if min(days) <= 0:\n raise ValueError(\"All days elements should be greater than 0\")\n\n if max(days) >= 366:\n raise ValueError(\"All days elements should be less than 366\")\n\n days_set = set(days)\n\n @functools.cache\n def dynamic_programming(index: int) -> int:\n if index > 365:\n return 0\n\n if index not in days_set:\n return dynamic_programming(index + 1)\n\n return min(\n costs[0] + dynamic_programming(index + 1),\n costs[1] + dynamic_programming(index + 7),\n costs[2] + dynamic_programming(index + 30),\n )\n\n return dynamic_programming(1)\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"!usrbinenv python3 This Python program implements an optimal binary search tree abbreviated BST building dynamic programming algorithm that delivers On2 performance. The goal of the optimal BST problem is to build a lowcost BST for a given set of nodes, each with its own key and frequency. The frequency of the node is defined as how many time the node is being searched. The search cost of binary search tree is given by this formula: cost1, n sumi 1 to ndepthnodei 1 nodeifreq where n is number of nodes in the BST. The characteristic of lowcost BSTs is having a faster overall search time than other implementations. The reason for their fast search time is that the nodes with high frequencies will be placed near the root of the tree while the nodes with low frequencies will be placed near the leaves of the tree thus reducing search time in the most frequent instances. Binary Search Tree Node def initself, key, freq: self.key key self.freq freq def strself: return fNodekeyself.key, freqself.freq def printbinarysearchtreeroot, key, i, j, parent, isleft: if i j or i 0 or j lenroot 1: return node rootij if parent 1: root does not have a parent printfkeynode is the root of the binary search tree. elif isleft: printfkeynode is the left child of key parent. else: printfkeynode is the right child of key parent. printbinarysearchtreeroot, key, i, node 1, keynode, True printbinarysearchtreeroot, key, node 1, j, keynode, False def findoptimalbinarysearchtreenodes: Tree nodes must be sorted first, the code below sorts the keys in increasing order and rearrange its frequencies accordingly. nodes.sortkeylambda node: node.key n lennodes keys nodesi.key for i in rangen freqs nodesi.freq for i in rangen This 2D array stores the overall tree cost which's as minimized as possible; for a single key, cost is equal to frequency of the key. dp freqsi if i j else 0 for j in rangen for i in rangen sumij stores the sum of key frequencies between i and j inclusive in nodes array total freqsi if i j else 0 for j in rangen for i in rangen stores tree roots that will be used later for constructing binary search tree root i if i j else 0 for j in rangen for i in rangen for intervallength in range2, n 1: for i in rangen intervallength 1: j i intervallength 1 dpij sys.maxsize set the value to infinity totalij totalij 1 freqsj Apply Knuth's optimization Loop without optimization: for r in rangei, j 1: for r in rangerootij 1, rooti 1j 1: r is a temporal root left dpir 1 if r ! i else 0 optimal cost for left subtree right dpr 1j if r ! j else 0 optimal cost for right subtree cost left totalij right if dpij cost: dpij cost rootij r printBinary search tree nodes: for node in nodes: printnode printfnThe cost of optimal BST for given tree nodes is dp0n 1. printbinarysearchtreeroot, keys, 0, n 1, 1, False def main: A sample binary search tree nodes Nodei, randint1, 50 for i in range10, 0, 1 findoptimalbinarysearchtreenodes if name main: main","Completions":"#!\/usr\/bin\/env python3\n\n# This Python program implements an optimal binary search tree (abbreviated BST)\n# building dynamic programming algorithm that delivers O(n^2) performance.\n#\n# The goal of the optimal BST problem is to build a low-cost BST for a\n# given set of nodes, each with its own key and frequency. The frequency\n# of the node is defined as how many time the node is being searched.\n# The search cost of binary search tree is given by this formula:\n#\n# cost(1, n) = sum{i = 1 to n}((depth(node_i) + 1) * node_i_freq)\n#\n# where n is number of nodes in the BST. The characteristic of low-cost\n# BSTs is having a faster overall search time than other implementations.\n# The reason for their fast search time is that the nodes with high\n# frequencies will be placed near the root of the tree while the nodes\n# with low frequencies will be placed near the leaves of the tree thus\n# reducing search time in the most frequent instances.\nimport sys\nfrom random import randint\n\n\nclass Node:\n \"\"\"Binary Search Tree Node\"\"\"\n\n def __init__(self, key, freq):\n self.key = key\n self.freq = freq\n\n def __str__(self):\n \"\"\"\n >>> str(Node(1, 2))\n 'Node(key=1, freq=2)'\n \"\"\"\n return f\"Node(key={self.key}, freq={self.freq})\"\n\n\ndef print_binary_search_tree(root, key, i, j, parent, is_left):\n \"\"\"\n Recursive function to print a BST from a root table.\n\n >>> key = [3, 8, 9, 10, 17, 21]\n >>> root = [[0, 1, 1, 1, 1, 1], [0, 1, 1, 1, 1, 3], [0, 0, 2, 3, 3, 3], \\\n [0, 0, 0, 3, 3, 3], [0, 0, 0, 0, 4, 5], [0, 0, 0, 0, 0, 5]]\n >>> print_binary_search_tree(root, key, 0, 5, -1, False)\n 8 is the root of the binary search tree.\n 3 is the left child of key 8.\n 10 is the right child of key 8.\n 9 is the left child of key 10.\n 21 is the right child of key 10.\n 17 is the left child of key 21.\n \"\"\"\n if i > j or i < 0 or j > len(root) - 1:\n return\n\n node = root[i][j]\n if parent == -1: # root does not have a parent\n print(f\"{key[node]} is the root of the binary search tree.\")\n elif is_left:\n print(f\"{key[node]} is the left child of key {parent}.\")\n else:\n print(f\"{key[node]} is the right child of key {parent}.\")\n\n print_binary_search_tree(root, key, i, node - 1, key[node], True)\n print_binary_search_tree(root, key, node + 1, j, key[node], False)\n\n\ndef find_optimal_binary_search_tree(nodes):\n \"\"\"\n This function calculates and prints the optimal binary search tree.\n The dynamic programming algorithm below runs in O(n^2) time.\n Implemented from CLRS (Introduction to Algorithms) book.\n https:\/\/en.wikipedia.org\/wiki\/Introduction_to_Algorithms\n\n >>> find_optimal_binary_search_tree([Node(12, 8), Node(10, 34), Node(20, 50), \\\n Node(42, 3), Node(25, 40), Node(37, 30)])\n Binary search tree nodes:\n Node(key=10, freq=34)\n Node(key=12, freq=8)\n Node(key=20, freq=50)\n Node(key=25, freq=40)\n Node(key=37, freq=30)\n Node(key=42, freq=3)\n \n The cost of optimal BST for given tree nodes is 324.\n 20 is the root of the binary search tree.\n 10 is the left child of key 20.\n 12 is the right child of key 10.\n 25 is the right child of key 20.\n 37 is the right child of key 25.\n 42 is the right child of key 37.\n \"\"\"\n # Tree nodes must be sorted first, the code below sorts the keys in\n # increasing order and rearrange its frequencies accordingly.\n nodes.sort(key=lambda node: node.key)\n\n n = len(nodes)\n\n keys = [nodes[i].key for i in range(n)]\n freqs = [nodes[i].freq for i in range(n)]\n\n # This 2D array stores the overall tree cost (which's as minimized as possible);\n # for a single key, cost is equal to frequency of the key.\n dp = [[freqs[i] if i == j else 0 for j in range(n)] for i in range(n)]\n # sum[i][j] stores the sum of key frequencies between i and j inclusive in nodes\n # array\n total = [[freqs[i] if i == j else 0 for j in range(n)] for i in range(n)]\n # stores tree roots that will be used later for constructing binary search tree\n root = [[i if i == j else 0 for j in range(n)] for i in range(n)]\n\n for interval_length in range(2, n + 1):\n for i in range(n - interval_length + 1):\n j = i + interval_length - 1\n\n dp[i][j] = sys.maxsize # set the value to \"infinity\"\n total[i][j] = total[i][j - 1] + freqs[j]\n\n # Apply Knuth's optimization\n # Loop without optimization: for r in range(i, j + 1):\n for r in range(root[i][j - 1], root[i + 1][j] + 1): # r is a temporal root\n left = dp[i][r - 1] if r != i else 0 # optimal cost for left subtree\n right = dp[r + 1][j] if r != j else 0 # optimal cost for right subtree\n cost = left + total[i][j] + right\n\n if dp[i][j] > cost:\n dp[i][j] = cost\n root[i][j] = r\n\n print(\"Binary search tree nodes:\")\n for node in nodes:\n print(node)\n\n print(f\"\\nThe cost of optimal BST for given tree nodes is {dp[0][n - 1]}.\")\n print_binary_search_tree(root, keys, 0, n - 1, -1, False)\n\n\ndef main():\n # A sample binary search tree\n nodes = [Node(i, randint(1, 50)) for i in range(10, 0, -1)]\n find_optimal_binary_search_tree(nodes)\n\n\nif __name__ == \"__main__\":\n main()\n"} +{"Prompt":"Given a string s, partition s such that every substring of the partition is a palindrome. Find the minimum cuts needed for a palindrome partitioning of s. Time Complexity: On2 Space Complexity: On2 For other explanations refer to: https:www.youtube.comwatch?vH8V5hJUGd0 Returns the minimum cuts needed for a palindrome partitioning of string findminimumpartitionsaab 1 findminimumpartitionsaaa 0 findminimumpartitionsababbbabbababa 3","Completions":"def find_minimum_partitions(string: str) -> int:\n \"\"\"\n Returns the minimum cuts needed for a palindrome partitioning of string\n\n >>> find_minimum_partitions(\"aab\")\n 1\n >>> find_minimum_partitions(\"aaa\")\n 0\n >>> find_minimum_partitions(\"ababbbabbababa\")\n 3\n \"\"\"\n length = len(string)\n cut = [0] * length\n is_palindromic = [[False for i in range(length)] for j in range(length)]\n for i, c in enumerate(string):\n mincut = i\n for j in range(i + 1):\n if c == string[j] and (i - j < 2 or is_palindromic[j + 1][i - 1]):\n is_palindromic[j][i] = True\n mincut = min(mincut, 0 if j == 0 else (cut[j - 1] + 1))\n cut[i] = mincut\n return cut[length - 1]\n\n\nif __name__ == \"__main__\":\n s = input(\"Enter the string: \").strip()\n ans = find_minimum_partitions(s)\n print(f\"Minimum number of partitions required for the '{s}' is {ans}\")\n"} +{"Prompt":"Regex matching check if a text matches pattern or not. Pattern: '.' Matches any single character. '' Matches zero or more of the preceding element. More info: https:medium.comtricktheinterviwerregularexpressionmatching9972eb74c03 Recursive matching algorithm. Time complexity: O2 text pattern Space complexity: Recursion depth is Otext pattern. :param text: Text to match. :param pattern: Pattern to match. :return: True if text matches pattern, False otherwise. recursivematch'abc', 'a.c' True recursivematch'abc', 'af.c' True recursivematch'abc', 'a.c' True recursivematch'abc', 'a.cd' False recursivematch'aa', '.' True Dynamic programming matching algorithm. Time complexity: Otext pattern Space complexity: Otext pattern :param text: Text to match. :param pattern: Pattern to match. :return: True if text matches pattern, False otherwise. dpmatch'abc', 'a.c' True dpmatch'abc', 'af.c' True dpmatch'abc', 'a.c' True dpmatch'abc', 'a.cd' False dpmatch'aa', '.' True","Completions":"def recursive_match(text: str, pattern: str) -> bool:\n \"\"\"\n Recursive matching algorithm.\n\n Time complexity: O(2 ^ (|text| + |pattern|))\n Space complexity: Recursion depth is O(|text| + |pattern|).\n\n :param text: Text to match.\n :param pattern: Pattern to match.\n :return: True if text matches pattern, False otherwise.\n\n >>> recursive_match('abc', 'a.c')\n True\n >>> recursive_match('abc', 'af*.c')\n True\n >>> recursive_match('abc', 'a.c*')\n True\n >>> recursive_match('abc', 'a.c*d')\n False\n >>> recursive_match('aa', '.*')\n True\n \"\"\"\n if not pattern:\n return not text\n\n if not text:\n return pattern[-1] == \"*\" and recursive_match(text, pattern[:-2])\n\n if text[-1] == pattern[-1] or pattern[-1] == \".\":\n return recursive_match(text[:-1], pattern[:-1])\n\n if pattern[-1] == \"*\":\n return recursive_match(text[:-1], pattern) or recursive_match(\n text, pattern[:-2]\n )\n\n return False\n\n\ndef dp_match(text: str, pattern: str) -> bool:\n \"\"\"\n Dynamic programming matching algorithm.\n\n Time complexity: O(|text| * |pattern|)\n Space complexity: O(|text| * |pattern|)\n\n :param text: Text to match.\n :param pattern: Pattern to match.\n :return: True if text matches pattern, False otherwise.\n\n >>> dp_match('abc', 'a.c')\n True\n >>> dp_match('abc', 'af*.c')\n True\n >>> dp_match('abc', 'a.c*')\n True\n >>> dp_match('abc', 'a.c*d')\n False\n >>> dp_match('aa', '.*')\n True\n \"\"\"\n m = len(text)\n n = len(pattern)\n dp = [[False for _ in range(n + 1)] for _ in range(m + 1)]\n dp[0][0] = True\n\n for j in range(1, n + 1):\n dp[0][j] = pattern[j - 1] == \"*\" and dp[0][j - 2]\n\n for i in range(1, m + 1):\n for j in range(1, n + 1):\n if pattern[j - 1] in {\".\", text[i - 1]}:\n dp[i][j] = dp[i - 1][j - 1]\n elif pattern[j - 1] == \"*\":\n dp[i][j] = dp[i][j - 2]\n if pattern[j - 2] in {\".\", text[i - 1]}:\n dp[i][j] |= dp[i - 1][j]\n else:\n dp[i][j] = False\n\n return dp[m][n]\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"This module provides two implementations for the rodcutting problem: 1. A naive recursive implementation which has an exponential runtime 2. Two dynamic programming implementations which have quadratic runtime The rodcutting problem is the problem of finding the maximum possible revenue obtainable from a rod of length n given a list of prices for each integral piece of the rod. The maximum revenue can thus be obtained by cutting the rod and selling the pieces separately or not cutting it at all if the price of it is the maximum obtainable. Solves the rodcutting problem via naively without using the benefit of dynamic programming. The results is the same subproblems are solved several times leading to an exponential runtime Runtime: O2n Arguments n: int, the length of the rod prices: list, the prices for each piece of rod. pii is the price for a rod of length i Returns The maximum revenue obtainable for a rod of length n given the list of prices for each piece. Examples naivecutrodrecursive4, 1, 5, 8, 9 10 naivecutrodrecursive10, 1, 5, 8, 9, 10, 17, 17, 20, 24, 30 30 Constructs a topdown dynamic programming solution for the rodcutting problem via memoization. This function serves as a wrapper for topdowncutrodrecursive Runtime: On2 Arguments n: int, the length of the rod prices: list, the prices for each piece of rod. pii is the price for a rod of length i Note For convenience and because Python's lists using 0indexing, lengthmaxrev n 1, to accommodate for the revenue obtainable from a rod of length 0. Returns The maximum revenue obtainable for a rod of length n given the list of prices for each piece. Examples topdowncutrod4, 1, 5, 8, 9 10 topdowncutrod10, 1, 5, 8, 9, 10, 17, 17, 20, 24, 30 30 Constructs a topdown dynamic programming solution for the rodcutting problem via memoization. Runtime: On2 Arguments n: int, the length of the rod prices: list, the prices for each piece of rod. pii is the price for a rod of length i maxrev: list, the computed maximum revenue for a piece of rod. maxrevi is the maximum revenue obtainable for a rod of length i Returns The maximum revenue obtainable for a rod of length n given the list of prices for each piece. Constructs a bottomup dynamic programming solution for the rodcutting problem Runtime: On2 Arguments n: int, the maximum length of the rod. prices: list, the prices for each piece of rod. pii is the price for a rod of length i Returns The maximum revenue obtainable from cutting a rod of length n given the prices for each piece of rod p. Examples bottomupcutrod4, 1, 5, 8, 9 10 bottomupcutrod10, 1, 5, 8, 9, 10, 17, 17, 20, 24, 30 30 lengthmaxrev n 1, to accommodate for the revenue obtainable from a rod of length 0. Basic checks on the arguments to the rodcutting algorithms n: int, the length of the rod prices: list, the price list for each piece of rod. Throws ValueError: if n is negative or there are fewer items in the price list than the length of the rod the best revenue comes from cutting the rod into 6 pieces, each of length 1 resulting in a revenue of 6 6 36.","Completions":"def naive_cut_rod_recursive(n: int, prices: list):\n \"\"\"\n Solves the rod-cutting problem via naively without using the benefit of dynamic\n programming. The results is the same sub-problems are solved several times\n leading to an exponential runtime\n\n Runtime: O(2^n)\n\n Arguments\n -------\n n: int, the length of the rod\n prices: list, the prices for each piece of rod. ``p[i-i]`` is the\n price for a rod of length ``i``\n\n Returns\n -------\n The maximum revenue obtainable for a rod of length n given the list of prices\n for each piece.\n\n Examples\n --------\n >>> naive_cut_rod_recursive(4, [1, 5, 8, 9])\n 10\n >>> naive_cut_rod_recursive(10, [1, 5, 8, 9, 10, 17, 17, 20, 24, 30])\n 30\n \"\"\"\n\n _enforce_args(n, prices)\n if n == 0:\n return 0\n max_revue = float(\"-inf\")\n for i in range(1, n + 1):\n max_revue = max(\n max_revue, prices[i - 1] + naive_cut_rod_recursive(n - i, prices)\n )\n\n return max_revue\n\n\ndef top_down_cut_rod(n: int, prices: list):\n \"\"\"\n Constructs a top-down dynamic programming solution for the rod-cutting\n problem via memoization. This function serves as a wrapper for\n _top_down_cut_rod_recursive\n\n Runtime: O(n^2)\n\n Arguments\n --------\n n: int, the length of the rod\n prices: list, the prices for each piece of rod. ``p[i-i]`` is the\n price for a rod of length ``i``\n\n Note\n ----\n For convenience and because Python's lists using 0-indexing, length(max_rev) =\n n + 1, to accommodate for the revenue obtainable from a rod of length 0.\n\n Returns\n -------\n The maximum revenue obtainable for a rod of length n given the list of prices\n for each piece.\n\n Examples\n -------\n >>> top_down_cut_rod(4, [1, 5, 8, 9])\n 10\n >>> top_down_cut_rod(10, [1, 5, 8, 9, 10, 17, 17, 20, 24, 30])\n 30\n \"\"\"\n _enforce_args(n, prices)\n max_rev = [float(\"-inf\") for _ in range(n + 1)]\n return _top_down_cut_rod_recursive(n, prices, max_rev)\n\n\ndef _top_down_cut_rod_recursive(n: int, prices: list, max_rev: list):\n \"\"\"\n Constructs a top-down dynamic programming solution for the rod-cutting problem\n via memoization.\n\n Runtime: O(n^2)\n\n Arguments\n --------\n n: int, the length of the rod\n prices: list, the prices for each piece of rod. ``p[i-i]`` is the\n price for a rod of length ``i``\n max_rev: list, the computed maximum revenue for a piece of rod.\n ``max_rev[i]`` is the maximum revenue obtainable for a rod of length ``i``\n\n Returns\n -------\n The maximum revenue obtainable for a rod of length n given the list of prices\n for each piece.\n \"\"\"\n if max_rev[n] >= 0:\n return max_rev[n]\n elif n == 0:\n return 0\n else:\n max_revenue = float(\"-inf\")\n for i in range(1, n + 1):\n max_revenue = max(\n max_revenue,\n prices[i - 1] + _top_down_cut_rod_recursive(n - i, prices, max_rev),\n )\n\n max_rev[n] = max_revenue\n\n return max_rev[n]\n\n\ndef bottom_up_cut_rod(n: int, prices: list):\n \"\"\"\n Constructs a bottom-up dynamic programming solution for the rod-cutting problem\n\n Runtime: O(n^2)\n\n Arguments\n ----------\n n: int, the maximum length of the rod.\n prices: list, the prices for each piece of rod. ``p[i-i]`` is the\n price for a rod of length ``i``\n\n Returns\n -------\n The maximum revenue obtainable from cutting a rod of length n given\n the prices for each piece of rod p.\n\n Examples\n -------\n >>> bottom_up_cut_rod(4, [1, 5, 8, 9])\n 10\n >>> bottom_up_cut_rod(10, [1, 5, 8, 9, 10, 17, 17, 20, 24, 30])\n 30\n \"\"\"\n _enforce_args(n, prices)\n\n # length(max_rev) = n + 1, to accommodate for the revenue obtainable from a rod of\n # length 0.\n max_rev = [float(\"-inf\") for _ in range(n + 1)]\n max_rev[0] = 0\n\n for i in range(1, n + 1):\n max_revenue_i = max_rev[i]\n for j in range(1, i + 1):\n max_revenue_i = max(max_revenue_i, prices[j - 1] + max_rev[i - j])\n\n max_rev[i] = max_revenue_i\n\n return max_rev[n]\n\n\ndef _enforce_args(n: int, prices: list):\n \"\"\"\n Basic checks on the arguments to the rod-cutting algorithms\n\n n: int, the length of the rod\n prices: list, the price list for each piece of rod.\n\n Throws ValueError:\n\n if n is negative or there are fewer items in the price list than the length of\n the rod\n \"\"\"\n if n < 0:\n msg = f\"n must be greater than or equal to 0. Got n = {n}\"\n raise ValueError(msg)\n\n if n > len(prices):\n msg = (\n \"Each integral piece of rod must have a corresponding price. \"\n f\"Got n = {n} but length of prices = {len(prices)}\"\n )\n raise ValueError(msg)\n\n\ndef main():\n prices = [6, 10, 12, 15, 20, 23]\n n = len(prices)\n\n # the best revenue comes from cutting the rod into 6 pieces, each\n # of length 1 resulting in a revenue of 6 * 6 = 36.\n expected_max_revenue = 36\n\n max_rev_top_down = top_down_cut_rod(n, prices)\n max_rev_bottom_up = bottom_up_cut_rod(n, prices)\n max_rev_naive = naive_cut_rod_recursive(n, prices)\n\n assert expected_max_revenue == max_rev_top_down\n assert max_rev_top_down == max_rev_bottom_up\n assert max_rev_bottom_up == max_rev_naive\n\n\nif __name__ == \"__main__\":\n main()\n"} +{"Prompt":"https:en.wikipedia.orgwikiSmithE28093Watermanalgorithm The SmithWaterman algorithm is a dynamic programming algorithm used for sequence alignment. It is particularly useful for finding similarities between two sequences, such as DNA or protein sequences. In this implementation, gaps are penalized linearly, meaning that the score is reduced by a fixed amount for each gap introduced in the alignment. However, it's important to note that the SmithWaterman algorithm supports other gap penalty methods as well. Calculate the score for a character pair based on whether they match or mismatch. Returns 1 if the characters match, 1 if they mismatch, and 2 if either of the characters is a gap. scorefunction'A', 'A' 1 scorefunction'A', 'C' 1 scorefunction'', 'A' 2 scorefunction'A', '' 2 scorefunction'', '' 2 Perform the SmithWaterman local sequence alignment algorithm. Returns a 2D list representing the score matrix. Each value in the matrix corresponds to the score of the best local alignment ending at that point. smithwaterman'ACAC', 'CA' 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 2, 0, 1, 0 smithwaterman'acac', 'ca' 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 2, 0, 1, 0 smithwaterman'ACAC', 'ca' 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 2, 0, 1, 0 smithwaterman'acac', 'CA' 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 2, 0, 1, 0 smithwaterman'ACAC', '' 0, 0, 0, 0, 0 smithwaterman'', 'CA' 0, 0, 0 smithwaterman'ACAC', 'CA' 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 2, 0, 1, 0 smithwaterman'acac', 'ca' 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 2, 0, 1, 0 smithwaterman'ACAC', 'ca' 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 2, 0, 1, 0 smithwaterman'acac', 'CA' 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 2, 0, 1, 0 smithwaterman'ACAC', '' 0, 0, 0, 0, 0 smithwaterman'', 'CA' 0, 0, 0 smithwaterman'AGT', 'AGT' 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 2, 0, 0, 0, 0, 3 smithwaterman'AGT', 'GTA' 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 2, 0 smithwaterman'AGT', 'GTC' 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 2, 0 smithwaterman'AGT', 'G' 0, 0, 0, 0, 0, 1, 0, 0 smithwaterman'G', 'AGT' 0, 0, 0, 0, 0, 0, 1, 0 smithwaterman'AGT', 'AGTCT' 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 3, 1, 1 smithwaterman'AGTCT', 'AGT' 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 2, 0, 0, 0, 0, 3, 0, 0, 0, 1, 0, 0, 0, 1 smithwaterman'AGTCT', 'GTC' 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 2, 0, 0, 0, 0, 3, 0, 0, 1, 1 make both query and subject uppercase Initialize score matrix Calculate scores for each cell Take maximum score make both query and subject uppercase query query.upper subject subject.upper find the indices of the maximum value in the score matrix maxvalue floatinf imax jmax 0 for i, row in enumeratescore: for j, value in enumeraterow: if value maxvalue: maxvalue value imax, jmax i, j Traceback logic to find optimal alignment i imax j jmax align1 align2 gap scorefunction, guard against empty query or subject if i 0 or j 0: return while i 0 and j 0: if scoreij scorei 1j 1 scorefunction queryi 1, subjectj 1 : optimal path is a diagonal take both letters align1 queryi 1 align1 align2 subjectj 1 align2 i 1 j 1 elif scoreij scorei 1j gap: optimal path is a vertical align1 queryi 1 align1 align2 falign2 i 1 else: optimal path is a horizontal align1 falign1 align2 subjectj 1 align2 j 1 return falign1nalign2 if name main: query HEAGAWGHEE subject PAWHEAE score smithwatermanquery, subject, match1, mismatch1, gap2 printtracebackscore, query, subject","Completions":"def score_function(\n source_char: str,\n target_char: str,\n match: int = 1,\n mismatch: int = -1,\n gap: int = -2,\n) -> int:\n \"\"\"\n Calculate the score for a character pair based on whether they match or mismatch.\n Returns 1 if the characters match, -1 if they mismatch, and -2 if either of the\n characters is a gap.\n >>> score_function('A', 'A')\n 1\n >>> score_function('A', 'C')\n -1\n >>> score_function('-', 'A')\n -2\n >>> score_function('A', '-')\n -2\n >>> score_function('-', '-')\n -2\n \"\"\"\n if \"-\" in (source_char, target_char):\n return gap\n return match if source_char == target_char else mismatch\n\n\ndef smith_waterman(\n query: str,\n subject: str,\n match: int = 1,\n mismatch: int = -1,\n gap: int = -2,\n) -> list[list[int]]:\n \"\"\"\n Perform the Smith-Waterman local sequence alignment algorithm.\n Returns a 2D list representing the score matrix. Each value in the matrix\n corresponds to the score of the best local alignment ending at that point.\n >>> smith_waterman('ACAC', 'CA')\n [[0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 0, 2], [0, 1, 0]]\n >>> smith_waterman('acac', 'ca')\n [[0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 0, 2], [0, 1, 0]]\n >>> smith_waterman('ACAC', 'ca')\n [[0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 0, 2], [0, 1, 0]]\n >>> smith_waterman('acac', 'CA')\n [[0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 0, 2], [0, 1, 0]]\n >>> smith_waterman('ACAC', '')\n [[0], [0], [0], [0], [0]]\n >>> smith_waterman('', 'CA')\n [[0, 0, 0]]\n >>> smith_waterman('ACAC', 'CA')\n [[0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 0, 2], [0, 1, 0]]\n\n >>> smith_waterman('acac', 'ca')\n [[0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 0, 2], [0, 1, 0]]\n\n >>> smith_waterman('ACAC', 'ca')\n [[0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 0, 2], [0, 1, 0]]\n\n >>> smith_waterman('acac', 'CA')\n [[0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 0, 2], [0, 1, 0]]\n\n >>> smith_waterman('ACAC', '')\n [[0], [0], [0], [0], [0]]\n\n >>> smith_waterman('', 'CA')\n [[0, 0, 0]]\n\n >>> smith_waterman('AGT', 'AGT')\n [[0, 0, 0, 0], [0, 1, 0, 0], [0, 0, 2, 0], [0, 0, 0, 3]]\n\n >>> smith_waterman('AGT', 'GTA')\n [[0, 0, 0, 0], [0, 0, 0, 1], [0, 1, 0, 0], [0, 0, 2, 0]]\n\n >>> smith_waterman('AGT', 'GTC')\n [[0, 0, 0, 0], [0, 0, 0, 0], [0, 1, 0, 0], [0, 0, 2, 0]]\n\n >>> smith_waterman('AGT', 'G')\n [[0, 0], [0, 0], [0, 1], [0, 0]]\n\n >>> smith_waterman('G', 'AGT')\n [[0, 0, 0, 0], [0, 0, 1, 0]]\n\n >>> smith_waterman('AGT', 'AGTCT')\n [[0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0], [0, 0, 2, 0, 0, 0], [0, 0, 0, 3, 1, 1]]\n\n >>> smith_waterman('AGTCT', 'AGT')\n [[0, 0, 0, 0], [0, 1, 0, 0], [0, 0, 2, 0], [0, 0, 0, 3], [0, 0, 0, 1], [0, 0, 0, 1]]\n\n >>> smith_waterman('AGTCT', 'GTC')\n [[0, 0, 0, 0], [0, 0, 0, 0], [0, 1, 0, 0], [0, 0, 2, 0], [0, 0, 0, 3], [0, 0, 1, 1]]\n \"\"\"\n # make both query and subject uppercase\n query = query.upper()\n subject = subject.upper()\n\n # Initialize score matrix\n m = len(query)\n n = len(subject)\n score = [[0] * (n + 1) for _ in range(m + 1)]\n kwargs = {\"match\": match, \"mismatch\": mismatch, \"gap\": gap}\n\n for i in range(1, m + 1):\n for j in range(1, n + 1):\n # Calculate scores for each cell\n match = score[i - 1][j - 1] + score_function(\n query[i - 1], subject[j - 1], **kwargs\n )\n delete = score[i - 1][j] + gap\n insert = score[i][j - 1] + gap\n\n # Take maximum score\n score[i][j] = max(0, match, delete, insert)\n\n return score\n\n\ndef traceback(score: list[list[int]], query: str, subject: str) -> str:\n r\"\"\"\n Perform traceback to find the optimal local alignment.\n Starts from the highest scoring cell in the matrix and traces back recursively\n until a 0 score is found. Returns the alignment strings.\n >>> traceback([[0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 0, 2], [0, 1, 0]], 'ACAC', 'CA')\n 'CA\\nCA'\n >>> traceback([[0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 0, 2], [0, 1, 0]], 'acac', 'ca')\n 'CA\\nCA'\n >>> traceback([[0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 0, 2], [0, 1, 0]], 'ACAC', 'ca')\n 'CA\\nCA'\n >>> traceback([[0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 0, 2], [0, 1, 0]], 'acac', 'CA')\n 'CA\\nCA'\n >>> traceback([[0, 0, 0]], 'ACAC', '')\n ''\n \"\"\"\n # make both query and subject uppercase\n query = query.upper()\n subject = subject.upper()\n # find the indices of the maximum value in the score matrix\n max_value = float(\"-inf\")\n i_max = j_max = 0\n for i, row in enumerate(score):\n for j, value in enumerate(row):\n if value > max_value:\n max_value = value\n i_max, j_max = i, j\n # Traceback logic to find optimal alignment\n i = i_max\n j = j_max\n align1 = \"\"\n align2 = \"\"\n gap = score_function(\"-\", \"-\")\n # guard against empty query or subject\n if i == 0 or j == 0:\n return \"\"\n while i > 0 and j > 0:\n if score[i][j] == score[i - 1][j - 1] + score_function(\n query[i - 1], subject[j - 1]\n ):\n # optimal path is a diagonal take both letters\n align1 = query[i - 1] + align1\n align2 = subject[j - 1] + align2\n i -= 1\n j -= 1\n elif score[i][j] == score[i - 1][j] + gap:\n # optimal path is a vertical\n align1 = query[i - 1] + align1\n align2 = f\"-{align2}\"\n i -= 1\n else:\n # optimal path is a horizontal\n align1 = f\"-{align1}\"\n align2 = subject[j - 1] + align2\n j -= 1\n\n return f\"{align1}\\n{align2}\"\n\n\nif __name__ == \"__main__\":\n query = \"HEAGAWGHEE\"\n subject = \"PAWHEAE\"\n\n score = smith_waterman(query, subject, match=1, mismatch=-1, gap=-2)\n print(traceback(score, query, subject))\n"} +{"Prompt":"Compute nelement combinations from a given list using dynamic programming. Args: elements: The list of elements from which combinations will be generated. n: The number of elements in each combination. Returns: A list of tuples, each representing a combination of n elements. subsetcombinationselements10, 20, 30, 40, n2 10, 20, 10, 30, 10, 40, 20, 30, 20, 40, 30, 40 subsetcombinationselements1, 2, 3, n1 1,, 2,, 3, subsetcombinationselements1, 2, 3, n3 1, 2, 3 subsetcombinationselements42, n1 42, subsetcombinationselements6, 7, 8, 9, n4 6, 7, 8, 9 subsetcombinationselements10, 20, 30, 40, 50, n0 subsetcombinationselements1, 2, 3, 4, n2 1, 2, 1, 3, 1, 4, 2, 3, 2, 4, 3, 4 subsetcombinationselements1, 'apple', 3.14, n2 1, 'apple', 1, 3.14, 'apple', 3.14 subsetcombinationselements'single', n0 subsetcombinationselements, n9 from itertools import combinations allsubsetcombinationsitems, n listcombinationsitems, n ... for items, n in ... 10, 20, 30, 40, 2, 1, 2, 3, 1, 1, 2, 3, 3, 42, 1, ... 6, 7, 8, 9, 4, 10, 20, 30, 40, 50, 1, 1, 2, 3, 4, 2, ... 1, 'apple', 3.14, 2, 'single', 0, , 9 True","Completions":"def subset_combinations(elements: list[int], n: int) -> list:\n \"\"\"\n Compute n-element combinations from a given list using dynamic programming.\n Args:\n elements: The list of elements from which combinations will be generated.\n n: The number of elements in each combination.\n Returns:\n A list of tuples, each representing a combination of n elements.\n >>> subset_combinations(elements=[10, 20, 30, 40], n=2)\n [(10, 20), (10, 30), (10, 40), (20, 30), (20, 40), (30, 40)]\n >>> subset_combinations(elements=[1, 2, 3], n=1)\n [(1,), (2,), (3,)]\n >>> subset_combinations(elements=[1, 2, 3], n=3)\n [(1, 2, 3)]\n >>> subset_combinations(elements=[42], n=1)\n [(42,)]\n >>> subset_combinations(elements=[6, 7, 8, 9], n=4)\n [(6, 7, 8, 9)]\n >>> subset_combinations(elements=[10, 20, 30, 40, 50], n=0)\n [()]\n >>> subset_combinations(elements=[1, 2, 3, 4], n=2)\n [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]\n >>> subset_combinations(elements=[1, 'apple', 3.14], n=2)\n [(1, 'apple'), (1, 3.14), ('apple', 3.14)]\n >>> subset_combinations(elements=['single'], n=0)\n [()]\n >>> subset_combinations(elements=[], n=9)\n []\n >>> from itertools import combinations\n >>> all(subset_combinations(items, n) == list(combinations(items, n))\n ... for items, n in (\n ... ([10, 20, 30, 40], 2), ([1, 2, 3], 1), ([1, 2, 3], 3), ([42], 1),\n ... ([6, 7, 8, 9], 4), ([10, 20, 30, 40, 50], 1), ([1, 2, 3, 4], 2),\n ... ([1, 'apple', 3.14], 2), (['single'], 0), ([], 9)))\n True\n \"\"\"\n r = len(elements)\n if n > r:\n return []\n\n dp: list[list[tuple]] = [[] for _ in range(r + 1)]\n\n dp[0].append(())\n\n for i in range(1, r + 1):\n for j in range(i, 0, -1):\n for prev_combination in dp[j - 1]:\n dp[j].append(tuple(prev_combination) + (elements[i - 1],))\n\n try:\n return sorted(dp[n])\n except TypeError:\n return dp[n]\n\n\nif __name__ == \"__main__\":\n from doctest import testmod\n\n testmod()\n print(f\"{subset_combinations(elements=[10, 20, 30, 40], n=2) = }\")\n"} +{"Prompt":"issumsubset2, 4, 6, 8, 5 False issumsubset2, 4, 6, 8, 14 True a subset value says 1 if that subset sum can be formed else 0 initially no subsets can be formed hence False0 for each arr value, a sum of zero0 can be formed by not taking any element hence True1 sum is not zero and set is empty then false","Completions":"def is_sum_subset(arr: list[int], required_sum: int) -> bool:\n \"\"\"\n >>> is_sum_subset([2, 4, 6, 8], 5)\n False\n >>> is_sum_subset([2, 4, 6, 8], 14)\n True\n \"\"\"\n # a subset value says 1 if that subset sum can be formed else 0\n # initially no subsets can be formed hence False\/0\n arr_len = len(arr)\n subset = [[False] * (required_sum + 1) for _ in range(arr_len + 1)]\n\n # for each arr value, a sum of zero(0) can be formed by not taking any element\n # hence True\/1\n for i in range(arr_len + 1):\n subset[i][0] = True\n\n # sum is not zero and set is empty then false\n for i in range(1, required_sum + 1):\n subset[0][i] = False\n\n for i in range(1, arr_len + 1):\n for j in range(1, required_sum + 1):\n if arr[i - 1] > j:\n subset[i][j] = subset[i - 1][j]\n if arr[i - 1] <= j:\n subset[i][j] = subset[i - 1][j] or subset[i - 1][j - arr[i - 1]]\n\n return subset[arr_len][required_sum]\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Given an array of nonnegative integers representing an elevation map where the width of each bar is 1, this program calculates how much rainwater can be trapped. Example height 0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1 Output: 6 This problem can be solved using the concept of DYNAMIC PROGRAMMING. We calculate the maximum height of bars on the left and right of every bar in array. Then iterate over the width of structure and at each index. The amount of water that will be stored is equal to minimum of maximum height of bars on both sides minus height of bar at current position. The trappedrainwater function calculates the total amount of rainwater that can be trapped given an array of bar heights. It uses a dynamic programming approach, determining the maximum height of bars on both sides for each bar, and then computing the trapped water above each bar. The function returns the total trapped water. trappedrainwater0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1 6 trappedrainwater7, 1, 5, 3, 6, 4 9 trappedrainwater7, 1, 5, 3, 6, 1 Traceback most recent call last: ... ValueError: No height can be negative","Completions":"def trapped_rainwater(heights: tuple[int, ...]) -> int:\n \"\"\"\n The trapped_rainwater function calculates the total amount of rainwater that can be\n trapped given an array of bar heights.\n It uses a dynamic programming approach, determining the maximum height of bars on\n both sides for each bar, and then computing the trapped water above each bar.\n The function returns the total trapped water.\n\n >>> trapped_rainwater((0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1))\n 6\n >>> trapped_rainwater((7, 1, 5, 3, 6, 4))\n 9\n >>> trapped_rainwater((7, 1, 5, 3, 6, -1))\n Traceback (most recent call last):\n ...\n ValueError: No height can be negative\n \"\"\"\n if not heights:\n return 0\n if any(h < 0 for h in heights):\n raise ValueError(\"No height can be negative\")\n length = len(heights)\n\n left_max = [0] * length\n left_max[0] = heights[0]\n for i, height in enumerate(heights[1:], start=1):\n left_max[i] = max(height, left_max[i - 1])\n\n right_max = [0] * length\n right_max[-1] = heights[-1]\n for i in range(length - 2, -1, -1):\n right_max[i] = max(heights[i], right_max[i + 1])\n\n return sum(\n min(left, right) - height\n for left, right, height in zip(left_max, right_max, heights)\n )\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n print(f\"{trapped_rainwater((0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1)) = }\")\n print(f\"{trapped_rainwater((7, 1, 5, 3, 6, 4)) = }\")\n"} +{"Prompt":"Tribonacci sequence using Dynamic Programming Given a number, return first n Tribonacci Numbers. tribonacci5 0, 0, 1, 1, 2 tribonacci8 0, 0, 1, 1, 2, 4, 7, 13","Completions":"# Tribonacci sequence using Dynamic Programming\n\n\ndef tribonacci(num: int) -> list[int]:\n \"\"\"\n Given a number, return first n Tribonacci Numbers.\n >>> tribonacci(5)\n [0, 0, 1, 1, 2]\n >>> tribonacci(8)\n [0, 0, 1, 1, 2, 4, 7, 13]\n \"\"\"\n dp = [0] * num\n dp[2] = 1\n\n for i in range(3, num):\n dp[i] = dp[i - 1] + dp[i - 2] + dp[i - 3]\n\n return dp\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Viterbi Algorithm, to find the most likely path of states from the start and the expected output. https:en.wikipedia.orgwikiViterbialgorithm sdafads Wikipedia example observations normal, cold, dizzy states Healthy, Fever startp Healthy: 0.6, Fever: 0.4 transp ... Healthy: Healthy: 0.7, Fever: 0.3, ... Fever: Healthy: 0.4, Fever: 0.6, ... emitp ... Healthy: normal: 0.5, cold: 0.4, dizzy: 0.1, ... Fever: normal: 0.1, cold: 0.3, dizzy: 0.6, ... viterbiobservations, states, startp, transp, emitp 'Healthy', 'Healthy', 'Fever' viterbi, states, startp, transp, emitp Traceback most recent call last: ... ValueError: There's an empty parameter viterbiobservations, , startp, transp, emitp Traceback most recent call last: ... ValueError: There's an empty parameter viterbiobservations, states, , transp, emitp Traceback most recent call last: ... ValueError: There's an empty parameter viterbiobservations, states, startp, , emitp Traceback most recent call last: ... ValueError: There's an empty parameter viterbiobservations, states, startp, transp, Traceback most recent call last: ... ValueError: There's an empty parameter viterbiinvalid, states, startp, transp, emitp Traceback most recent call last: ... ValueError: observationsspace must be a list viterbivalid, 123, states, startp, transp, emitp Traceback most recent call last: ... ValueError: observationsspace must be a list of strings viterbiobservations, invalid, startp, transp, emitp Traceback most recent call last: ... ValueError: statesspace must be a list viterbiobservations, valid, 123, startp, transp, emitp Traceback most recent call last: ... ValueError: statesspace must be a list of strings viterbiobservations, states, invalid, transp, emitp Traceback most recent call last: ... ValueError: initialprobabilities must be a dict viterbiobservations, states, 2:2, transp, emitp Traceback most recent call last: ... ValueError: initialprobabilities all keys must be strings viterbiobservations, states, a:2, transp, emitp Traceback most recent call last: ... ValueError: initialprobabilities all values must be float viterbiobservations, states, startp, invalid, emitp Traceback most recent call last: ... ValueError: transitionprobabilities must be a dict viterbiobservations, states, startp, a:2, emitp Traceback most recent call last: ... ValueError: transitionprobabilities all values must be dict viterbiobservations, states, startp, 2:2:2, emitp Traceback most recent call last: ... ValueError: transitionprobabilities all keys must be strings viterbiobservations, states, startp, a:2:2, emitp Traceback most recent call last: ... ValueError: transitionprobabilities all keys must be strings viterbiobservations, states, startp, a:b:2, emitp Traceback most recent call last: ... ValueError: transitionprobabilities nested dictionary all values must be float viterbiobservations, states, startp, transp, invalid Traceback most recent call last: ... ValueError: emissionprobabilities must be a dict viterbiobservations, states, startp, transp, None Traceback most recent call last: ... ValueError: There's an empty parameter Creates data structures and fill initial step Fills the data structure with the probabilities of different transitions and pointers to previous states Calculates the argmax for probability function Update probabilities and pointers dicts The final observation argmax for given final observation Process pointers backwards observations normal, cold, dizzy states Healthy, Fever startp Healthy: 0.6, Fever: 0.4 transp ... Healthy: Healthy: 0.7, Fever: 0.3, ... Fever: Healthy: 0.4, Fever: 0.6, ... emitp ... Healthy: normal: 0.5, cold: 0.4, dizzy: 0.1, ... Fever: normal: 0.1, cold: 0.3, dizzy: 0.6, ... validationobservations, states, startp, transp, emitp validation, states, startp, transp, emitp Traceback most recent call last: ... ValueError: There's an empty parameter validatenotemptya, b, c:0.5, ... d: e: 0.6, f: g: 0.7 validatenotemptya, b, c:0.5, , f: g: 0.7 Traceback most recent call last: ... ValueError: There's an empty parameter validatenotemptya, b, None, d: e: 0.6, f: g: 0.7 Traceback most recent call last: ... ValueError: There's an empty parameter validatelistsa, b validatelists1234, b Traceback most recent call last: ... ValueError: observationsspace must be a list validatelistsa, 3 Traceback most recent call last: ... ValueError: statesspace must be a list of strings validatelista, mockname validatelista, mockname Traceback most recent call last: ... ValueError: mockname must be a list validatelist0.5, mockname Traceback most recent call last: ... ValueError: mockname must be a list of strings validatedictsc:0.5, d: e: 0.6, f: g: 0.7 validatedictsinvalid, d: e: 0.6, f: g: 0.7 Traceback most recent call last: ... ValueError: initialprobabilities must be a dict validatedictsc:0.5, 2: e: 0.6, f: g: 0.7 Traceback most recent call last: ... ValueError: transitionprobabilities all keys must be strings validatedictsc:0.5, d: e: 0.6, f: 2: 0.7 Traceback most recent call last: ... ValueError: emissionprobabilities all keys must be strings validatedictsc:0.5, d: e: 0.6, f: g: h Traceback most recent call last: ... ValueError: emissionprobabilities nested dictionary all values must be float validatenesteddicta:b: 0.5, mockname validatenesteddictinvalid, mockname Traceback most recent call last: ... ValueError: mockname must be a dict validatenesteddicta: 8, mockname Traceback most recent call last: ... ValueError: mockname all values must be dict validatenesteddicta:2: 0.5, mockname Traceback most recent call last: ... ValueError: mockname all keys must be strings validatenesteddicta:b: 4, mockname Traceback most recent call last: ... ValueError: mockname nested dictionary all values must be float validatedictb: 0.5, mockname, float validatedictinvalid, mockname, float Traceback most recent call last: ... ValueError: mockname must be a dict validatedicta: 8, mockname, dict Traceback most recent call last: ... ValueError: mockname all values must be dict validatedict2: 0.5, mockname,float, True Traceback most recent call last: ... ValueError: mockname all keys must be strings validatedictb: 4, mockname, float,True Traceback most recent call last: ... ValueError: mockname nested dictionary all values must be float","Completions":"from typing import Any\n\n\ndef viterbi(\n observations_space: list,\n states_space: list,\n initial_probabilities: dict,\n transition_probabilities: dict,\n emission_probabilities: dict,\n) -> list:\n \"\"\"\n Viterbi Algorithm, to find the most likely path of\n states from the start and the expected output.\n https:\/\/en.wikipedia.org\/wiki\/Viterbi_algorithm\n sdafads\n Wikipedia example\n >>> observations = [\"normal\", \"cold\", \"dizzy\"]\n >>> states = [\"Healthy\", \"Fever\"]\n >>> start_p = {\"Healthy\": 0.6, \"Fever\": 0.4}\n >>> trans_p = {\n ... \"Healthy\": {\"Healthy\": 0.7, \"Fever\": 0.3},\n ... \"Fever\": {\"Healthy\": 0.4, \"Fever\": 0.6},\n ... }\n >>> emit_p = {\n ... \"Healthy\": {\"normal\": 0.5, \"cold\": 0.4, \"dizzy\": 0.1},\n ... \"Fever\": {\"normal\": 0.1, \"cold\": 0.3, \"dizzy\": 0.6},\n ... }\n >>> viterbi(observations, states, start_p, trans_p, emit_p)\n ['Healthy', 'Healthy', 'Fever']\n\n >>> viterbi((), states, start_p, trans_p, emit_p)\n Traceback (most recent call last):\n ...\n ValueError: There's an empty parameter\n\n >>> viterbi(observations, (), start_p, trans_p, emit_p)\n Traceback (most recent call last):\n ...\n ValueError: There's an empty parameter\n\n >>> viterbi(observations, states, {}, trans_p, emit_p)\n Traceback (most recent call last):\n ...\n ValueError: There's an empty parameter\n\n >>> viterbi(observations, states, start_p, {}, emit_p)\n Traceback (most recent call last):\n ...\n ValueError: There's an empty parameter\n\n >>> viterbi(observations, states, start_p, trans_p, {})\n Traceback (most recent call last):\n ...\n ValueError: There's an empty parameter\n\n >>> viterbi(\"invalid\", states, start_p, trans_p, emit_p)\n Traceback (most recent call last):\n ...\n ValueError: observations_space must be a list\n\n >>> viterbi([\"valid\", 123], states, start_p, trans_p, emit_p)\n Traceback (most recent call last):\n ...\n ValueError: observations_space must be a list of strings\n\n >>> viterbi(observations, \"invalid\", start_p, trans_p, emit_p)\n Traceback (most recent call last):\n ...\n ValueError: states_space must be a list\n\n >>> viterbi(observations, [\"valid\", 123], start_p, trans_p, emit_p)\n Traceback (most recent call last):\n ...\n ValueError: states_space must be a list of strings\n\n >>> viterbi(observations, states, \"invalid\", trans_p, emit_p)\n Traceback (most recent call last):\n ...\n ValueError: initial_probabilities must be a dict\n\n >>> viterbi(observations, states, {2:2}, trans_p, emit_p)\n Traceback (most recent call last):\n ...\n ValueError: initial_probabilities all keys must be strings\n\n >>> viterbi(observations, states, {\"a\":2}, trans_p, emit_p)\n Traceback (most recent call last):\n ...\n ValueError: initial_probabilities all values must be float\n\n >>> viterbi(observations, states, start_p, \"invalid\", emit_p)\n Traceback (most recent call last):\n ...\n ValueError: transition_probabilities must be a dict\n\n >>> viterbi(observations, states, start_p, {\"a\":2}, emit_p)\n Traceback (most recent call last):\n ...\n ValueError: transition_probabilities all values must be dict\n\n >>> viterbi(observations, states, start_p, {2:{2:2}}, emit_p)\n Traceback (most recent call last):\n ...\n ValueError: transition_probabilities all keys must be strings\n\n >>> viterbi(observations, states, start_p, {\"a\":{2:2}}, emit_p)\n Traceback (most recent call last):\n ...\n ValueError: transition_probabilities all keys must be strings\n\n >>> viterbi(observations, states, start_p, {\"a\":{\"b\":2}}, emit_p)\n Traceback (most recent call last):\n ...\n ValueError: transition_probabilities nested dictionary all values must be float\n\n >>> viterbi(observations, states, start_p, trans_p, \"invalid\")\n Traceback (most recent call last):\n ...\n ValueError: emission_probabilities must be a dict\n\n >>> viterbi(observations, states, start_p, trans_p, None)\n Traceback (most recent call last):\n ...\n ValueError: There's an empty parameter\n\n \"\"\"\n _validation(\n observations_space,\n states_space,\n initial_probabilities,\n transition_probabilities,\n emission_probabilities,\n )\n # Creates data structures and fill initial step\n probabilities: dict = {}\n pointers: dict = {}\n for state in states_space:\n observation = observations_space[0]\n probabilities[(state, observation)] = (\n initial_probabilities[state] * emission_probabilities[state][observation]\n )\n pointers[(state, observation)] = None\n\n # Fills the data structure with the probabilities of\n # different transitions and pointers to previous states\n for o in range(1, len(observations_space)):\n observation = observations_space[o]\n prior_observation = observations_space[o - 1]\n for state in states_space:\n # Calculates the argmax for probability function\n arg_max = \"\"\n max_probability = -1\n for k_state in states_space:\n probability = (\n probabilities[(k_state, prior_observation)]\n * transition_probabilities[k_state][state]\n * emission_probabilities[state][observation]\n )\n if probability > max_probability:\n max_probability = probability\n arg_max = k_state\n\n # Update probabilities and pointers dicts\n probabilities[(state, observation)] = (\n probabilities[(arg_max, prior_observation)]\n * transition_probabilities[arg_max][state]\n * emission_probabilities[state][observation]\n )\n\n pointers[(state, observation)] = arg_max\n\n # The final observation\n final_observation = observations_space[len(observations_space) - 1]\n\n # argmax for given final observation\n arg_max = \"\"\n max_probability = -1\n for k_state in states_space:\n probability = probabilities[(k_state, final_observation)]\n if probability > max_probability:\n max_probability = probability\n arg_max = k_state\n last_state = arg_max\n\n # Process pointers backwards\n previous = last_state\n result = []\n for o in range(len(observations_space) - 1, -1, -1):\n result.append(previous)\n previous = pointers[previous, observations_space[o]]\n result.reverse()\n\n return result\n\n\ndef _validation(\n observations_space: Any,\n states_space: Any,\n initial_probabilities: Any,\n transition_probabilities: Any,\n emission_probabilities: Any,\n) -> None:\n \"\"\"\n >>> observations = [\"normal\", \"cold\", \"dizzy\"]\n >>> states = [\"Healthy\", \"Fever\"]\n >>> start_p = {\"Healthy\": 0.6, \"Fever\": 0.4}\n >>> trans_p = {\n ... \"Healthy\": {\"Healthy\": 0.7, \"Fever\": 0.3},\n ... \"Fever\": {\"Healthy\": 0.4, \"Fever\": 0.6},\n ... }\n >>> emit_p = {\n ... \"Healthy\": {\"normal\": 0.5, \"cold\": 0.4, \"dizzy\": 0.1},\n ... \"Fever\": {\"normal\": 0.1, \"cold\": 0.3, \"dizzy\": 0.6},\n ... }\n >>> _validation(observations, states, start_p, trans_p, emit_p)\n\n >>> _validation([], states, start_p, trans_p, emit_p)\n Traceback (most recent call last):\n ...\n ValueError: There's an empty parameter\n \"\"\"\n _validate_not_empty(\n observations_space,\n states_space,\n initial_probabilities,\n transition_probabilities,\n emission_probabilities,\n )\n _validate_lists(observations_space, states_space)\n _validate_dicts(\n initial_probabilities, transition_probabilities, emission_probabilities\n )\n\n\ndef _validate_not_empty(\n observations_space: Any,\n states_space: Any,\n initial_probabilities: Any,\n transition_probabilities: Any,\n emission_probabilities: Any,\n) -> None:\n \"\"\"\n >>> _validate_not_empty([\"a\"], [\"b\"], {\"c\":0.5},\n ... {\"d\": {\"e\": 0.6}}, {\"f\": {\"g\": 0.7}})\n\n >>> _validate_not_empty([\"a\"], [\"b\"], {\"c\":0.5}, {}, {\"f\": {\"g\": 0.7}})\n Traceback (most recent call last):\n ...\n ValueError: There's an empty parameter\n >>> _validate_not_empty([\"a\"], [\"b\"], None, {\"d\": {\"e\": 0.6}}, {\"f\": {\"g\": 0.7}})\n Traceback (most recent call last):\n ...\n ValueError: There's an empty parameter\n \"\"\"\n if not all(\n [\n observations_space,\n states_space,\n initial_probabilities,\n transition_probabilities,\n emission_probabilities,\n ]\n ):\n raise ValueError(\"There's an empty parameter\")\n\n\ndef _validate_lists(observations_space: Any, states_space: Any) -> None:\n \"\"\"\n >>> _validate_lists([\"a\"], [\"b\"])\n\n >>> _validate_lists(1234, [\"b\"])\n Traceback (most recent call last):\n ...\n ValueError: observations_space must be a list\n\n >>> _validate_lists([\"a\"], [3])\n Traceback (most recent call last):\n ...\n ValueError: states_space must be a list of strings\n \"\"\"\n _validate_list(observations_space, \"observations_space\")\n _validate_list(states_space, \"states_space\")\n\n\ndef _validate_list(_object: Any, var_name: str) -> None:\n \"\"\"\n >>> _validate_list([\"a\"], \"mock_name\")\n\n >>> _validate_list(\"a\", \"mock_name\")\n Traceback (most recent call last):\n ...\n ValueError: mock_name must be a list\n >>> _validate_list([0.5], \"mock_name\")\n Traceback (most recent call last):\n ...\n ValueError: mock_name must be a list of strings\n\n \"\"\"\n if not isinstance(_object, list):\n msg = f\"{var_name} must be a list\"\n raise ValueError(msg)\n else:\n for x in _object:\n if not isinstance(x, str):\n msg = f\"{var_name} must be a list of strings\"\n raise ValueError(msg)\n\n\ndef _validate_dicts(\n initial_probabilities: Any,\n transition_probabilities: Any,\n emission_probabilities: Any,\n) -> None:\n \"\"\"\n >>> _validate_dicts({\"c\":0.5}, {\"d\": {\"e\": 0.6}}, {\"f\": {\"g\": 0.7}})\n\n >>> _validate_dicts(\"invalid\", {\"d\": {\"e\": 0.6}}, {\"f\": {\"g\": 0.7}})\n Traceback (most recent call last):\n ...\n ValueError: initial_probabilities must be a dict\n >>> _validate_dicts({\"c\":0.5}, {2: {\"e\": 0.6}}, {\"f\": {\"g\": 0.7}})\n Traceback (most recent call last):\n ...\n ValueError: transition_probabilities all keys must be strings\n >>> _validate_dicts({\"c\":0.5}, {\"d\": {\"e\": 0.6}}, {\"f\": {2: 0.7}})\n Traceback (most recent call last):\n ...\n ValueError: emission_probabilities all keys must be strings\n >>> _validate_dicts({\"c\":0.5}, {\"d\": {\"e\": 0.6}}, {\"f\": {\"g\": \"h\"}})\n Traceback (most recent call last):\n ...\n ValueError: emission_probabilities nested dictionary all values must be float\n \"\"\"\n _validate_dict(initial_probabilities, \"initial_probabilities\", float)\n _validate_nested_dict(transition_probabilities, \"transition_probabilities\")\n _validate_nested_dict(emission_probabilities, \"emission_probabilities\")\n\n\ndef _validate_nested_dict(_object: Any, var_name: str) -> None:\n \"\"\"\n >>> _validate_nested_dict({\"a\":{\"b\": 0.5}}, \"mock_name\")\n\n >>> _validate_nested_dict(\"invalid\", \"mock_name\")\n Traceback (most recent call last):\n ...\n ValueError: mock_name must be a dict\n >>> _validate_nested_dict({\"a\": 8}, \"mock_name\")\n Traceback (most recent call last):\n ...\n ValueError: mock_name all values must be dict\n >>> _validate_nested_dict({\"a\":{2: 0.5}}, \"mock_name\")\n Traceback (most recent call last):\n ...\n ValueError: mock_name all keys must be strings\n >>> _validate_nested_dict({\"a\":{\"b\": 4}}, \"mock_name\")\n Traceback (most recent call last):\n ...\n ValueError: mock_name nested dictionary all values must be float\n \"\"\"\n _validate_dict(_object, var_name, dict)\n for x in _object.values():\n _validate_dict(x, var_name, float, True)\n\n\ndef _validate_dict(\n _object: Any, var_name: str, value_type: type, nested: bool = False\n) -> None:\n \"\"\"\n >>> _validate_dict({\"b\": 0.5}, \"mock_name\", float)\n\n >>> _validate_dict(\"invalid\", \"mock_name\", float)\n Traceback (most recent call last):\n ...\n ValueError: mock_name must be a dict\n >>> _validate_dict({\"a\": 8}, \"mock_name\", dict)\n Traceback (most recent call last):\n ...\n ValueError: mock_name all values must be dict\n >>> _validate_dict({2: 0.5}, \"mock_name\",float, True)\n Traceback (most recent call last):\n ...\n ValueError: mock_name all keys must be strings\n >>> _validate_dict({\"b\": 4}, \"mock_name\", float,True)\n Traceback (most recent call last):\n ...\n ValueError: mock_name nested dictionary all values must be float\n \"\"\"\n if not isinstance(_object, dict):\n msg = f\"{var_name} must be a dict\"\n raise ValueError(msg)\n if not all(isinstance(x, str) for x in _object):\n msg = f\"{var_name} all keys must be strings\"\n raise ValueError(msg)\n if not all(isinstance(x, value_type) for x in _object.values()):\n nested_text = \"nested dictionary \" if nested else \"\"\n msg = f\"{var_name} {nested_text}all values must be {value_type.__name__}\"\n raise ValueError(msg)\n\n\nif __name__ == \"__main__\":\n from doctest import testmod\n\n testmod()\n"} +{"Prompt":"Author : ilyas dahhou Date : Oct 7, 2023 Task: Given an input string and a pattern, implement wildcard pattern matching with support for '?' and '' where: '?' matches any single character. '' matches any sequence of characters including the empty sequence. The matching should cover the entire input string not partial. Runtime complexity: Om n The implementation was tested on the leetcode: https:leetcode.comproblemswildcardmatching ismatch, True ismatchaa, a False ismatchabc, abc True ismatchabc, c True ismatchabc, a True ismatchabc, a True ismatchabc, ?b? True ismatchabc, ? True ismatchabc, ad False ismatchabc, ac? False ismatch'baaabab','baba' False ismatch'baaabab','baab' True ismatch'aa','' True Fill in the first row Fill in the rest of the DP table","Completions":"def is_match(string: str, pattern: str) -> bool:\n \"\"\"\n >>> is_match(\"\", \"\")\n True\n >>> is_match(\"aa\", \"a\")\n False\n >>> is_match(\"abc\", \"abc\")\n True\n >>> is_match(\"abc\", \"*c\")\n True\n >>> is_match(\"abc\", \"a*\")\n True\n >>> is_match(\"abc\", \"*a*\")\n True\n >>> is_match(\"abc\", \"?b?\")\n True\n >>> is_match(\"abc\", \"*?\")\n True\n >>> is_match(\"abc\", \"a*d\")\n False\n >>> is_match(\"abc\", \"a*c?\")\n False\n >>> is_match('baaabab','*****ba*****ba')\n False\n >>> is_match('baaabab','*****ba*****ab')\n True\n >>> is_match('aa','*')\n True\n \"\"\"\n dp = [[False] * (len(pattern) + 1) for _ in string + \"1\"]\n dp[0][0] = True\n # Fill in the first row\n for j, char in enumerate(pattern, 1):\n if char == \"*\":\n dp[0][j] = dp[0][j - 1]\n # Fill in the rest of the DP table\n for i, s_char in enumerate(string, 1):\n for j, p_char in enumerate(pattern, 1):\n if p_char in (s_char, \"?\"):\n dp[i][j] = dp[i - 1][j - 1]\n elif pattern[j - 1] == \"*\":\n dp[i][j] = dp[i - 1][j] or dp[i][j - 1]\n return dp[len(string)][len(pattern)]\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n print(f\"{is_match('baaabab','*****ba*****ab') = }\")\n"} +{"Prompt":"Author : Alexander Pantyukhin Date : December 12, 2022 Task: Given a string and a list of words, return true if the string can be segmented into a spaceseparated sequence of one or more words. Note that the same word may be reused multiple times in the segmentation. Implementation notes: Trie Dynamic programming up down. The Trie will be used to store the words. It will be useful for scanning available words for the current position in the string. Leetcode: https:leetcode.comproblemswordbreakdescription Runtime: On n Space: On Return True if numbers have opposite signs False otherwise. wordbreakapplepenapple, apple,pen True wordbreakcatsandog, cats,dog,sand,and,cat False wordbreakcars, car,ca,rs True wordbreak'abc', False wordbreak123, 'a' Traceback most recent call last: ... ValueError: the string should be not empty string wordbreak'', 'a' Traceback most recent call last: ... ValueError: the string should be not empty string wordbreak'abc', 123 Traceback most recent call last: ... ValueError: the words should be a list of nonempty strings wordbreak'abc', '' Traceback most recent call last: ... ValueError: the words should be a list of nonempty strings Validation Build trie Dynamic programming method string 'a' isbreakable1 True","Completions":"import functools\nfrom typing import Any\n\n\ndef word_break(string: str, words: list[str]) -> bool:\n \"\"\"\n Return True if numbers have opposite signs False otherwise.\n\n >>> word_break(\"applepenapple\", [\"apple\",\"pen\"])\n True\n >>> word_break(\"catsandog\", [\"cats\",\"dog\",\"sand\",\"and\",\"cat\"])\n False\n >>> word_break(\"cars\", [\"car\",\"ca\",\"rs\"])\n True\n >>> word_break('abc', [])\n False\n >>> word_break(123, ['a'])\n Traceback (most recent call last):\n ...\n ValueError: the string should be not empty string\n >>> word_break('', ['a'])\n Traceback (most recent call last):\n ...\n ValueError: the string should be not empty string\n >>> word_break('abc', [123])\n Traceback (most recent call last):\n ...\n ValueError: the words should be a list of non-empty strings\n >>> word_break('abc', [''])\n Traceback (most recent call last):\n ...\n ValueError: the words should be a list of non-empty strings\n \"\"\"\n\n # Validation\n if not isinstance(string, str) or len(string) == 0:\n raise ValueError(\"the string should be not empty string\")\n\n if not isinstance(words, list) or not all(\n isinstance(item, str) and len(item) > 0 for item in words\n ):\n raise ValueError(\"the words should be a list of non-empty strings\")\n\n # Build trie\n trie: dict[str, Any] = {}\n word_keeper_key = \"WORD_KEEPER\"\n\n for word in words:\n trie_node = trie\n for c in word:\n if c not in trie_node:\n trie_node[c] = {}\n\n trie_node = trie_node[c]\n\n trie_node[word_keeper_key] = True\n\n len_string = len(string)\n\n # Dynamic programming method\n @functools.cache\n def is_breakable(index: int) -> bool:\n \"\"\"\n >>> string = 'a'\n >>> is_breakable(1)\n True\n \"\"\"\n if index == len_string:\n return True\n\n trie_node = trie\n for i in range(index, len_string):\n trie_node = trie_node.get(string[i], None)\n\n if trie_node is None:\n return False\n\n if trie_node.get(word_keeper_key, False) and is_breakable(i + 1):\n return True\n\n return False\n\n return is_breakable(0)\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Calculate the apparent power in a singlephase AC circuit. Reference: https:en.wikipedia.orgwikiACpowerApparentpower apparentpower100, 5, 0, 0 5000j apparentpower100, 5, 90, 0 3.061616997868383e14500j apparentpower100, 5, 45, 60 129.40952255126027482.9629131445341j apparentpower200, 10, 30, 90 999.99999999999981732.0508075688776j Convert angles from degrees to radians Convert voltage and current to rectangular form Calculate apparent power","Completions":"import cmath\nimport math\n\n\ndef apparent_power(\n voltage: float, current: float, voltage_angle: float, current_angle: float\n) -> complex:\n \"\"\"\n Calculate the apparent power in a single-phase AC circuit.\n\n Reference: https:\/\/en.wikipedia.org\/wiki\/AC_power#Apparent_power\n\n >>> apparent_power(100, 5, 0, 0)\n (500+0j)\n >>> apparent_power(100, 5, 90, 0)\n (3.061616997868383e-14+500j)\n >>> apparent_power(100, 5, -45, -60)\n (-129.40952255126027-482.9629131445341j)\n >>> apparent_power(200, 10, -30, -90)\n (-999.9999999999998-1732.0508075688776j)\n \"\"\"\n # Convert angles from degrees to radians\n voltage_angle_rad = math.radians(voltage_angle)\n current_angle_rad = math.radians(current_angle)\n\n # Convert voltage and current to rectangular form\n voltage_rect = cmath.rect(voltage, voltage_angle_rad)\n current_rect = cmath.rect(current, current_angle_rad)\n\n # Calculate apparent power\n return voltage_rect * current_rect\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"This function can calculate the Builtin Voltage of a pn junction diode. This is calculated from the given three values. Examples builtinvoltagedonorconc1e17, acceptorconc1e17, intrinsicconc1e10 0.833370010652644 builtinvoltagedonorconc0, acceptorconc1600, intrinsicconc200 Traceback most recent call last: ... ValueError: Donor concentration should be positive builtinvoltagedonorconc1000, acceptorconc0, intrinsicconc1200 Traceback most recent call last: ... ValueError: Acceptor concentration should be positive builtinvoltagedonorconc1000, acceptorconc1000, intrinsicconc0 Traceback most recent call last: ... ValueError: Intrinsic concentration should be positive builtinvoltagedonorconc1000, acceptorconc3000, intrinsicconc2000 Traceback most recent call last: ... ValueError: Donor concentration should be greater than intrinsic concentration builtinvoltagedonorconc3000, acceptorconc1000, intrinsicconc2000 Traceback most recent call last: ... ValueError: Acceptor concentration should be greater than intrinsic concentration","Completions":"from math import log\n\nfrom scipy.constants import Boltzmann, physical_constants\n\nT = 300 # TEMPERATURE (unit = K)\n\n\ndef builtin_voltage(\n donor_conc: float, # donor concentration\n acceptor_conc: float, # acceptor concentration\n intrinsic_conc: float, # intrinsic concentration\n) -> float:\n \"\"\"\n This function can calculate the Builtin Voltage of a pn junction diode.\n This is calculated from the given three values.\n Examples -\n >>> builtin_voltage(donor_conc=1e17, acceptor_conc=1e17, intrinsic_conc=1e10)\n 0.833370010652644\n >>> builtin_voltage(donor_conc=0, acceptor_conc=1600, intrinsic_conc=200)\n Traceback (most recent call last):\n ...\n ValueError: Donor concentration should be positive\n >>> builtin_voltage(donor_conc=1000, acceptor_conc=0, intrinsic_conc=1200)\n Traceback (most recent call last):\n ...\n ValueError: Acceptor concentration should be positive\n >>> builtin_voltage(donor_conc=1000, acceptor_conc=1000, intrinsic_conc=0)\n Traceback (most recent call last):\n ...\n ValueError: Intrinsic concentration should be positive\n >>> builtin_voltage(donor_conc=1000, acceptor_conc=3000, intrinsic_conc=2000)\n Traceback (most recent call last):\n ...\n ValueError: Donor concentration should be greater than intrinsic concentration\n >>> builtin_voltage(donor_conc=3000, acceptor_conc=1000, intrinsic_conc=2000)\n Traceback (most recent call last):\n ...\n ValueError: Acceptor concentration should be greater than intrinsic concentration\n \"\"\"\n\n if donor_conc <= 0:\n raise ValueError(\"Donor concentration should be positive\")\n elif acceptor_conc <= 0:\n raise ValueError(\"Acceptor concentration should be positive\")\n elif intrinsic_conc <= 0:\n raise ValueError(\"Intrinsic concentration should be positive\")\n elif donor_conc <= intrinsic_conc:\n raise ValueError(\n \"Donor concentration should be greater than intrinsic concentration\"\n )\n elif acceptor_conc <= intrinsic_conc:\n raise ValueError(\n \"Acceptor concentration should be greater than intrinsic concentration\"\n )\n else:\n return (\n Boltzmann\n * T\n * log((donor_conc * acceptor_conc) \/ intrinsic_conc**2)\n \/ physical_constants[\"electron volt\"][0]\n )\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"https:farside.ph.utexas.eduteaching316lecturesnode46.html Ceq C1 C2 ... Cn Calculate the equivalent resistance for any number of capacitors in parallel. capacitorparallel5.71389, 12, 3 20.71389 capacitorparallel5.71389, 12, 3 Traceback most recent call last: ... ValueError: Capacitor at index 2 has a negative value! Ceq 1 1C1 1C2 ... 1Cn capacitorseries5.71389, 12, 3 1.6901062252507735 capacitorseries5.71389, 12, 3 Traceback most recent call last: ... ValueError: Capacitor at index 2 has a negative or zero value! capacitorseries5.71389, 12, 0.000 Traceback most recent call last: ... ValueError: Capacitor at index 2 has a negative or zero value!","Completions":"# https:\/\/farside.ph.utexas.edu\/teaching\/316\/lectures\/node46.html\n\nfrom __future__ import annotations\n\n\ndef capacitor_parallel(capacitors: list[float]) -> float:\n \"\"\"\n Ceq = C1 + C2 + ... + Cn\n Calculate the equivalent resistance for any number of capacitors in parallel.\n >>> capacitor_parallel([5.71389, 12, 3])\n 20.71389\n >>> capacitor_parallel([5.71389, 12, -3])\n Traceback (most recent call last):\n ...\n ValueError: Capacitor at index 2 has a negative value!\n \"\"\"\n sum_c = 0.0\n for index, capacitor in enumerate(capacitors):\n if capacitor < 0:\n msg = f\"Capacitor at index {index} has a negative value!\"\n raise ValueError(msg)\n sum_c += capacitor\n return sum_c\n\n\ndef capacitor_series(capacitors: list[float]) -> float:\n \"\"\"\n Ceq = 1\/ (1\/C1 + 1\/C2 + ... + 1\/Cn)\n >>> capacitor_series([5.71389, 12, 3])\n 1.6901062252507735\n >>> capacitor_series([5.71389, 12, -3])\n Traceback (most recent call last):\n ...\n ValueError: Capacitor at index 2 has a negative or zero value!\n >>> capacitor_series([5.71389, 12, 0.000])\n Traceback (most recent call last):\n ...\n ValueError: Capacitor at index 2 has a negative or zero value!\n \"\"\"\n\n first_sum = 0.0\n for index, capacitor in enumerate(capacitors):\n if capacitor <= 0:\n msg = f\"Capacitor at index {index} has a negative or zero value!\"\n raise ValueError(msg)\n first_sum += 1 \/ capacitor\n return 1 \/ first_sum\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"https:en.wikipedia.orgwikiChargecarrierdensity https:www.pveducation.orgpvcdrompnjunctionsequilibriumcarrierconcentration http:www.ece.utep.educoursesee3329ee3329StudyguideToCFundamentalsCarriersconcentrations.html This function can calculate any one of the three 1. Electron Concentration 2, Hole Concentration 3. Intrinsic Concentration given the other two. Examples carrierconcentrationelectronconc25, holeconc100, intrinsicconc0 'intrinsicconc', 50.0 carrierconcentrationelectronconc0, holeconc1600, intrinsicconc200 'electronconc', 25.0 carrierconcentrationelectronconc1000, holeconc0, intrinsicconc1200 'holeconc', 1440.0 carrierconcentrationelectronconc1000, holeconc400, intrinsicconc1200 Traceback most recent call last: ... ValueError: You cannot supply more or less than 2 values carrierconcentrationelectronconc1000, holeconc0, intrinsicconc1200 Traceback most recent call last: ... ValueError: Electron concentration cannot be negative in a semiconductor carrierconcentrationelectronconc0, holeconc400, intrinsicconc1200 Traceback most recent call last: ... ValueError: Hole concentration cannot be negative in a semiconductor carrierconcentrationelectronconc0, holeconc400, intrinsicconc1200 Traceback most recent call last: ... ValueError: Intrinsic concentration cannot be negative in a semiconductor","Completions":"# https:\/\/en.wikipedia.org\/wiki\/Charge_carrier_density\n# https:\/\/www.pveducation.org\/pvcdrom\/pn-junctions\/equilibrium-carrier-concentration\n# http:\/\/www.ece.utep.edu\/courses\/ee3329\/ee3329\/Studyguide\/ToC\/Fundamentals\/Carriers\/concentrations.html\n\nfrom __future__ import annotations\n\n\ndef carrier_concentration(\n electron_conc: float,\n hole_conc: float,\n intrinsic_conc: float,\n) -> tuple:\n \"\"\"\n This function can calculate any one of the three -\n 1. Electron Concentration\n 2, Hole Concentration\n 3. Intrinsic Concentration\n given the other two.\n Examples -\n >>> carrier_concentration(electron_conc=25, hole_conc=100, intrinsic_conc=0)\n ('intrinsic_conc', 50.0)\n >>> carrier_concentration(electron_conc=0, hole_conc=1600, intrinsic_conc=200)\n ('electron_conc', 25.0)\n >>> carrier_concentration(electron_conc=1000, hole_conc=0, intrinsic_conc=1200)\n ('hole_conc', 1440.0)\n >>> carrier_concentration(electron_conc=1000, hole_conc=400, intrinsic_conc=1200)\n Traceback (most recent call last):\n ...\n ValueError: You cannot supply more or less than 2 values\n >>> carrier_concentration(electron_conc=-1000, hole_conc=0, intrinsic_conc=1200)\n Traceback (most recent call last):\n ...\n ValueError: Electron concentration cannot be negative in a semiconductor\n >>> carrier_concentration(electron_conc=0, hole_conc=-400, intrinsic_conc=1200)\n Traceback (most recent call last):\n ...\n ValueError: Hole concentration cannot be negative in a semiconductor\n >>> carrier_concentration(electron_conc=0, hole_conc=400, intrinsic_conc=-1200)\n Traceback (most recent call last):\n ...\n ValueError: Intrinsic concentration cannot be negative in a semiconductor\n \"\"\"\n if (electron_conc, hole_conc, intrinsic_conc).count(0) != 1:\n raise ValueError(\"You cannot supply more or less than 2 values\")\n elif electron_conc < 0:\n raise ValueError(\"Electron concentration cannot be negative in a semiconductor\")\n elif hole_conc < 0:\n raise ValueError(\"Hole concentration cannot be negative in a semiconductor\")\n elif intrinsic_conc < 0:\n raise ValueError(\n \"Intrinsic concentration cannot be negative in a semiconductor\"\n )\n elif electron_conc == 0:\n return (\n \"electron_conc\",\n intrinsic_conc**2 \/ hole_conc,\n )\n elif hole_conc == 0:\n return (\n \"hole_conc\",\n intrinsic_conc**2 \/ electron_conc,\n )\n elif intrinsic_conc == 0:\n return (\n \"intrinsic_conc\",\n (electron_conc * hole_conc) ** 0.5,\n )\n else:\n return (-1, -1)\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"source The ARRL Handbook for Radio Communications https:en.wikipedia.orgwikiRCtimeconstant Description When a capacitor is connected with a potential source AC or DC. It starts to charge at a general speed but when a resistor is connected in the circuit with in series to a capacitor then the capacitor charges slowly means it will take more time than usual. while the capacitor is being charged, the voltage is in exponential function with time. 'resistanceohms capacitancefarads' is called RCtimeconstant which may also be represented as tau. By using this RCtimeconstant we can find the voltage at any time 't' from the initiation of charging a capacitor with the help of the exponential function containing RC. Both at charging and discharging of a capacitor. Find capacitor voltage at any nth second after initiating its charging. Examples chargingcapacitorsourcevoltage.2,resistance.9,capacitance8.4,timesec.5 0.013 chargingcapacitorsourcevoltage2.2,resistance3.5,capacitance2.4,timesec9 1.446 chargingcapacitorsourcevoltage15,resistance200,capacitance20,timesec2 0.007 chargingcapacitor20, 2000, 30pow10,5, 4 19.975 chargingcapacitorsourcevoltage0,resistance10.0,capacitance.30,timesec3 Traceback most recent call last: ... ValueError: Source voltage must be positive. chargingcapacitorsourcevoltage20,resistance2000,capacitance30,timesec4 Traceback most recent call last: ... ValueError: Resistance must be positive. chargingcapacitorsourcevoltage30,resistance1500,capacitance0,timesec4 Traceback most recent call last: ... ValueError: Capacitance must be positive.","Completions":"# source - The ARRL Handbook for Radio Communications\n# https:\/\/en.wikipedia.org\/wiki\/RC_time_constant\n\n\"\"\"\nDescription\n-----------\nWhen a capacitor is connected with a potential source (AC or DC). It starts to charge\nat a general speed but when a resistor is connected in the circuit with in series to\na capacitor then the capacitor charges slowly means it will take more time than usual.\nwhile the capacitor is being charged, the voltage is in exponential function with time.\n\n'resistance(ohms) * capacitance(farads)' is called RC-timeconstant which may also be\nrepresented as \u03c4 (tau). By using this RC-timeconstant we can find the voltage at any\ntime 't' from the initiation of charging a capacitor with the help of the exponential\nfunction containing RC. Both at charging and discharging of a capacitor.\n\"\"\"\nfrom math import exp # value of exp = 2.718281828459\u2026\n\n\ndef charging_capacitor(\n source_voltage: float, # voltage in volts.\n resistance: float, # resistance in ohms.\n capacitance: float, # capacitance in farads.\n time_sec: float, # time in seconds after charging initiation of capacitor.\n) -> float:\n \"\"\"\n Find capacitor voltage at any nth second after initiating its charging.\n\n Examples\n --------\n >>> charging_capacitor(source_voltage=.2,resistance=.9,capacitance=8.4,time_sec=.5)\n 0.013\n\n >>> charging_capacitor(source_voltage=2.2,resistance=3.5,capacitance=2.4,time_sec=9)\n 1.446\n\n >>> charging_capacitor(source_voltage=15,resistance=200,capacitance=20,time_sec=2)\n 0.007\n\n >>> charging_capacitor(20, 2000, 30*pow(10,-5), 4)\n 19.975\n\n >>> charging_capacitor(source_voltage=0,resistance=10.0,capacitance=.30,time_sec=3)\n Traceback (most recent call last):\n ...\n ValueError: Source voltage must be positive.\n\n >>> charging_capacitor(source_voltage=20,resistance=-2000,capacitance=30,time_sec=4)\n Traceback (most recent call last):\n ...\n ValueError: Resistance must be positive.\n\n >>> charging_capacitor(source_voltage=30,resistance=1500,capacitance=0,time_sec=4)\n Traceback (most recent call last):\n ...\n ValueError: Capacitance must be positive.\n \"\"\"\n\n if source_voltage <= 0:\n raise ValueError(\"Source voltage must be positive.\")\n if resistance <= 0:\n raise ValueError(\"Resistance must be positive.\")\n if capacitance <= 0:\n raise ValueError(\"Capacitance must be positive.\")\n return round(source_voltage * (1 - exp(-time_sec \/ (resistance * capacitance))), 3)\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"source The ARRL Handbook for Radio Communications https:en.wikipedia.orgwikiRLcircuit Description Inductor is a passive electronic device which stores energy but unlike capacitor, it stores energy in its 'magnetic field' or 'magnetostatic field'. When inductor is connected to 'DC' current source nothing happens it just works like a wire because it's real effect cannot be seen while 'DC' is connected, its not even going to store energy. Inductor stores energy only when it is working on 'AC' current. Connecting a inductor in series with a resistorwhen R 0 to a 'AC' potential source, from zero to a finite value causes a sudden voltage to induced in inductor which opposes the current. which results in initially slowly current rise. However it would cease if there is no further changes in current. With resistance zero current will never stop rising. 'Resistanceohms Inductancehenrys' is known as RLtimeconstant. It also represents as tau. While the charging of a inductor with a resistor results in a exponential function. when inductor is connected across 'AC' potential source. It starts to store the energy in its 'magnetic field'.with the help 'RLtimeconstant' we can find current at any time in inductor while it is charging. Find inductor current at any nth second after initiating its charging. Examples charginginductorsourcevoltage5.8,resistance1.5,inductance2.3,time2 2.817 charginginductorsourcevoltage8,resistance5,inductance3,time2 1.543 charginginductorsourcevoltage8,resistance5pow10,2,inductance3,time2 0.016 charginginductorsourcevoltage8,resistance100,inductance15,time12 Traceback most recent call last: ... ValueError: Source voltage must be positive. charginginductorsourcevoltage80,resistance15,inductance100,time5 Traceback most recent call last: ... ValueError: Resistance must be positive. charginginductorsourcevoltage12,resistance200,inductance20,time5 Traceback most recent call last: ... ValueError: Inductance must be positive. charginginductorsourcevoltage0,resistance200,inductance20,time5 Traceback most recent call last: ... ValueError: Source voltage must be positive. charginginductorsourcevoltage10,resistance0,inductance20,time5 Traceback most recent call last: ... ValueError: Resistance must be positive. charginginductorsourcevoltage15, resistance25, inductance0, time5 Traceback most recent call last: ... ValueError: Inductance must be positive.","Completions":"# source - The ARRL Handbook for Radio Communications\n# https:\/\/en.wikipedia.org\/wiki\/RL_circuit\n\n\"\"\"\nDescription\n-----------\nInductor is a passive electronic device which stores energy but unlike capacitor, it\nstores energy in its 'magnetic field' or 'magnetostatic field'.\n\nWhen inductor is connected to 'DC' current source nothing happens it just works like a\nwire because it's real effect cannot be seen while 'DC' is connected, its not even\ngoing to store energy. Inductor stores energy only when it is working on 'AC' current.\n\nConnecting a inductor in series with a resistor(when R = 0) to a 'AC' potential source,\nfrom zero to a finite value causes a sudden voltage to induced in inductor which\nopposes the current. which results in initially slowly current rise. However it would\ncease if there is no further changes in current. With resistance zero current will never\nstop rising.\n\n'Resistance(ohms) \/ Inductance(henrys)' is known as RL-timeconstant. It also represents\nas \u03c4 (tau). While the charging of a inductor with a resistor results in\na exponential function.\n\nwhen inductor is connected across 'AC' potential source. It starts to store the energy\nin its 'magnetic field'.with the help 'RL-time-constant' we can find current at any time\nin inductor while it is charging.\n\"\"\"\nfrom math import exp # value of exp = 2.718281828459\u2026\n\n\ndef charging_inductor(\n source_voltage: float, # source_voltage should be in volts.\n resistance: float, # resistance should be in ohms.\n inductance: float, # inductance should be in henrys.\n time: float, # time should in seconds.\n) -> float:\n \"\"\"\n Find inductor current at any nth second after initiating its charging.\n\n Examples\n --------\n >>> charging_inductor(source_voltage=5.8,resistance=1.5,inductance=2.3,time=2)\n 2.817\n\n >>> charging_inductor(source_voltage=8,resistance=5,inductance=3,time=2)\n 1.543\n\n >>> charging_inductor(source_voltage=8,resistance=5*pow(10,2),inductance=3,time=2)\n 0.016\n\n >>> charging_inductor(source_voltage=-8,resistance=100,inductance=15,time=12)\n Traceback (most recent call last):\n ...\n ValueError: Source voltage must be positive.\n\n >>> charging_inductor(source_voltage=80,resistance=-15,inductance=100,time=5)\n Traceback (most recent call last):\n ...\n ValueError: Resistance must be positive.\n\n >>> charging_inductor(source_voltage=12,resistance=200,inductance=-20,time=5)\n Traceback (most recent call last):\n ...\n ValueError: Inductance must be positive.\n\n >>> charging_inductor(source_voltage=0,resistance=200,inductance=20,time=5)\n Traceback (most recent call last):\n ...\n ValueError: Source voltage must be positive.\n\n >>> charging_inductor(source_voltage=10,resistance=0,inductance=20,time=5)\n Traceback (most recent call last):\n ...\n ValueError: Resistance must be positive.\n\n >>> charging_inductor(source_voltage=15, resistance=25, inductance=0, time=5)\n Traceback (most recent call last):\n ...\n ValueError: Inductance must be positive.\n \"\"\"\n\n if source_voltage <= 0:\n raise ValueError(\"Source voltage must be positive.\")\n if resistance <= 0:\n raise ValueError(\"Resistance must be positive.\")\n if inductance <= 0:\n raise ValueError(\"Inductance must be positive.\")\n return round(\n source_voltage \/ resistance * (1 - exp((-time * resistance) \/ inductance)), 3\n )\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"https:en.wikipedia.orgwikiCircularconvolution Circular convolution, also known as cyclic convolution, is a special case of periodic convolution, which is the convolution of two periodic functions that have the same period. Periodic convolution arises, for example, in the context of the discretetime Fourier transform DTFT. In particular, the DTFT of the product of two discrete sequences is the periodic convolution of the DTFTs of the individual sequences. And each DTFT is a periodic summation of a continuous Fourier transform function. Source: https:en.wikipedia.orgwikiCircularconvolution This class stores the first and second signal and performs the circular convolution First signal and second signal are stored as 1D array This function performs the circular convolution of the first and second signal using matrix method Usage: import circularconvolution as cc convolution cc.CircularConvolution convolution.circularconvolution 10, 10, 6, 14 convolution.firstsignal 0.2, 0.4, 0.6, 0.8, 1.0, 1.2, 1.4, 1.6 convolution.secondsignal 0.1, 0.3, 0.5, 0.7, 0.9, 1.1, 1.3, 1.5 convolution.circularconvolution 5.2, 6.0, 6.48, 6.64, 6.48, 6.0, 5.2, 4.08 convolution.firstsignal 1, 1, 2, 2 convolution.secondsignal 0.5, 1, 1, 2, 0.75 convolution.circularconvolution 6.25, 3.0, 1.5, 2.0, 2.75 convolution.firstsignal 1, 1, 2, 3, 1 convolution.secondsignal 1, 2, 3 convolution.circularconvolution 8, 2, 3, 4, 11 create a zero matrix of maxlength x maxlength fills the smaller signal with zeros to make both signals of same length Fills the matrix in the following way assuming 'x' is the signal of length 4 x0, x3, x2, x1, x1, x0, x3, x2, x2, x1, x0, x3, x3, x2, x1, x0 multiply the matrix with the first signal roundingoff to two decimal places","Completions":"# https:\/\/en.wikipedia.org\/wiki\/Circular_convolution\n\n\"\"\"\nCircular convolution, also known as cyclic convolution,\nis a special case of periodic convolution, which is the convolution of two\nperiodic functions that have the same period. Periodic convolution arises,\nfor example, in the context of the discrete-time Fourier transform (DTFT).\nIn particular, the DTFT of the product of two discrete sequences is the periodic\nconvolution of the DTFTs of the individual sequences. And each DTFT is a periodic\nsummation of a continuous Fourier transform function.\n\nSource: https:\/\/en.wikipedia.org\/wiki\/Circular_convolution\n\"\"\"\n\nimport doctest\nfrom collections import deque\n\nimport numpy as np\n\n\nclass CircularConvolution:\n \"\"\"\n This class stores the first and second signal and performs the circular convolution\n \"\"\"\n\n def __init__(self) -> None:\n \"\"\"\n First signal and second signal are stored as 1-D array\n \"\"\"\n\n self.first_signal = [2, 1, 2, -1]\n self.second_signal = [1, 2, 3, 4]\n\n def circular_convolution(self) -> list[float]:\n \"\"\"\n This function performs the circular convolution of the first and second signal\n using matrix method\n\n Usage:\n >>> import circular_convolution as cc\n >>> convolution = cc.CircularConvolution()\n >>> convolution.circular_convolution()\n [10, 10, 6, 14]\n\n >>> convolution.first_signal = [0.2, 0.4, 0.6, 0.8, 1.0, 1.2, 1.4, 1.6]\n >>> convolution.second_signal = [0.1, 0.3, 0.5, 0.7, 0.9, 1.1, 1.3, 1.5]\n >>> convolution.circular_convolution()\n [5.2, 6.0, 6.48, 6.64, 6.48, 6.0, 5.2, 4.08]\n\n >>> convolution.first_signal = [-1, 1, 2, -2]\n >>> convolution.second_signal = [0.5, 1, -1, 2, 0.75]\n >>> convolution.circular_convolution()\n [6.25, -3.0, 1.5, -2.0, -2.75]\n\n >>> convolution.first_signal = [1, -1, 2, 3, -1]\n >>> convolution.second_signal = [1, 2, 3]\n >>> convolution.circular_convolution()\n [8, -2, 3, 4, 11]\n\n \"\"\"\n\n length_first_signal = len(self.first_signal)\n length_second_signal = len(self.second_signal)\n\n max_length = max(length_first_signal, length_second_signal)\n\n # create a zero matrix of max_length x max_length\n matrix = [[0] * max_length for i in range(max_length)]\n\n # fills the smaller signal with zeros to make both signals of same length\n if length_first_signal < length_second_signal:\n self.first_signal += [0] * (max_length - length_first_signal)\n elif length_first_signal > length_second_signal:\n self.second_signal += [0] * (max_length - length_second_signal)\n\n \"\"\"\n Fills the matrix in the following way assuming 'x' is the signal of length 4\n [\n [x[0], x[3], x[2], x[1]],\n [x[1], x[0], x[3], x[2]],\n [x[2], x[1], x[0], x[3]],\n [x[3], x[2], x[1], x[0]]\n ]\n \"\"\"\n for i in range(max_length):\n rotated_signal = deque(self.second_signal)\n rotated_signal.rotate(i)\n for j, item in enumerate(rotated_signal):\n matrix[i][j] += item\n\n # multiply the matrix with the first signal\n final_signal = np.matmul(np.transpose(matrix), np.transpose(self.first_signal))\n\n # rounding-off to two decimal places\n return [round(i, 2) for i in final_signal]\n\n\nif __name__ == \"__main__\":\n doctest.testmod()\n"} +{"Prompt":"https:en.wikipedia.orgwikiCoulomb27slaw Apply Coulomb's Law on any three given values. These can be force, charge1, charge2, or distance, and then in a Python dict return namevalue pair of the zero value. Coulomb's Law states that the magnitude of the electrostatic force of attraction or repulsion between two point charges is directly proportional to the product of the magnitudes of charges and inversely proportional to the square of the distance between them. Reference Coulomb 1785 Premier mmoire sur llectricit et le magntisme, Histoire de lAcadmie Royale des Sciences, pp. 569577. Parameters force : float with units in Newtons charge1 : float with units in Coulombs charge2 : float with units in Coulombs distance : float with units in meters Returns result : dict namevalue pair of the zero value couloumbslawforce0, charge13, charge25, distance2000 'force': 33705.0 couloumbslawforce10, charge13, charge25, distance0 'distance': 116112.01488218177 couloumbslawforce10, charge10, charge25, distance2000 'charge1': 0.0008900756564307966 couloumbslawforce0, charge10, charge25, distance2000 Traceback most recent call last: ... ValueError: One and only one argument must be 0 couloumbslawforce0, charge13, charge25, distance2000 Traceback most recent call last: ... ValueError: Distance cannot be negative","Completions":"# https:\/\/en.wikipedia.org\/wiki\/Coulomb%27s_law\n\nfrom __future__ import annotations\n\nCOULOMBS_CONSTANT = 8.988e9 # units = N * m^s * C^-2\n\n\ndef couloumbs_law(\n force: float, charge1: float, charge2: float, distance: float\n) -> dict[str, float]:\n \"\"\"\n Apply Coulomb's Law on any three given values. These can be force, charge1,\n charge2, or distance, and then in a Python dict return name\/value pair of\n the zero value.\n\n Coulomb's Law states that the magnitude of the electrostatic force of\n attraction or repulsion between two point charges is directly proportional\n to the product of the magnitudes of charges and inversely proportional to\n the square of the distance between them.\n\n Reference\n ----------\n Coulomb (1785) \"Premier m\u00e9moire sur l\u2019\u00e9lectricit\u00e9 et le magn\u00e9tisme,\"\n Histoire de l\u2019Acad\u00e9mie Royale des Sciences, pp. 569\u2013577.\n\n Parameters\n ----------\n force : float with units in Newtons\n\n charge1 : float with units in Coulombs\n\n charge2 : float with units in Coulombs\n\n distance : float with units in meters\n\n Returns\n -------\n result : dict name\/value pair of the zero value\n\n >>> couloumbs_law(force=0, charge1=3, charge2=5, distance=2000)\n {'force': 33705.0}\n\n >>> couloumbs_law(force=10, charge1=3, charge2=5, distance=0)\n {'distance': 116112.01488218177}\n\n >>> couloumbs_law(force=10, charge1=0, charge2=5, distance=2000)\n {'charge1': 0.0008900756564307966}\n\n >>> couloumbs_law(force=0, charge1=0, charge2=5, distance=2000)\n Traceback (most recent call last):\n ...\n ValueError: One and only one argument must be 0\n\n >>> couloumbs_law(force=0, charge1=3, charge2=5, distance=-2000)\n Traceback (most recent call last):\n ...\n ValueError: Distance cannot be negative\n\n \"\"\"\n\n charge_product = abs(charge1 * charge2)\n\n if (force, charge1, charge2, distance).count(0) != 1:\n raise ValueError(\"One and only one argument must be 0\")\n if distance < 0:\n raise ValueError(\"Distance cannot be negative\")\n if force == 0:\n force = COULOMBS_CONSTANT * charge_product \/ (distance**2)\n return {\"force\": force}\n elif charge1 == 0:\n charge1 = abs(force) * (distance**2) \/ (COULOMBS_CONSTANT * charge2)\n return {\"charge1\": charge1}\n elif charge2 == 0:\n charge2 = abs(force) * (distance**2) \/ (COULOMBS_CONSTANT * charge1)\n return {\"charge2\": charge2}\n elif distance == 0:\n distance = (COULOMBS_CONSTANT * charge_product \/ abs(force)) ** 0.5\n return {\"distance\": distance}\n raise ValueError(\"Exactly one argument must be 0\")\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"This function can calculate any one of the three 1. Conductivity 2. Electron Concentration 3. Electron Mobility This is calculated from the other two provided values Examples electricconductivityconductivity25, electronconc100, mobility0 'mobility', 1.5604519068722301e18 electricconductivityconductivity0, electronconc1600, mobility200 'conductivity', 5.12672e14 electricconductivityconductivity1000, electronconc0, mobility1200 'electronconc', 5.201506356240767e18","Completions":"from __future__ import annotations\n\nELECTRON_CHARGE = 1.6021e-19 # units = C\n\n\ndef electric_conductivity(\n conductivity: float,\n electron_conc: float,\n mobility: float,\n) -> tuple[str, float]:\n \"\"\"\n This function can calculate any one of the three -\n 1. Conductivity\n 2. Electron Concentration\n 3. Electron Mobility\n This is calculated from the other two provided values\n Examples -\n >>> electric_conductivity(conductivity=25, electron_conc=100, mobility=0)\n ('mobility', 1.5604519068722301e+18)\n >>> electric_conductivity(conductivity=0, electron_conc=1600, mobility=200)\n ('conductivity', 5.12672e-14)\n >>> electric_conductivity(conductivity=1000, electron_conc=0, mobility=1200)\n ('electron_conc', 5.201506356240767e+18)\n \"\"\"\n if (conductivity, electron_conc, mobility).count(0) != 1:\n raise ValueError(\"You cannot supply more or less than 2 values\")\n elif conductivity < 0:\n raise ValueError(\"Conductivity cannot be negative\")\n elif electron_conc < 0:\n raise ValueError(\"Electron concentration cannot be negative\")\n elif mobility < 0:\n raise ValueError(\"mobility cannot be negative\")\n elif conductivity == 0:\n return (\n \"conductivity\",\n mobility * electron_conc * ELECTRON_CHARGE,\n )\n elif electron_conc == 0:\n return (\n \"electron_conc\",\n conductivity \/ (mobility * ELECTRON_CHARGE),\n )\n else:\n return (\n \"mobility\",\n conductivity \/ (electron_conc * ELECTRON_CHARGE),\n )\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"https:en.m.wikipedia.orgwikiElectricpower This function can calculate any one of the three voltage, current, power, fundamental value of electrical system. examples are below: electricpowervoltage0, current2, power5 Resultname'voltage', value2.5 electricpowervoltage2, current2, power0 Resultname'power', value4.0 electricpowervoltage2, current3, power0 Resultname'power', value6.0 electricpowervoltage2, current4, power2 Traceback most recent call last: ... ValueError: Only one argument must be 0 electricpowervoltage0, current0, power2 Traceback most recent call last: ... ValueError: Only one argument must be 0 electricpowervoltage0, current2, power4 Traceback most recent call last: ... ValueError: Power cannot be negative in any electricalelectronics system electricpowervoltage2.2, current2.2, power0 Resultname'power', value4.84","Completions":"# https:\/\/en.m.wikipedia.org\/wiki\/Electric_power\nfrom __future__ import annotations\n\nfrom typing import NamedTuple\n\n\nclass Result(NamedTuple):\n name: str\n value: float\n\n\ndef electric_power(voltage: float, current: float, power: float) -> tuple:\n \"\"\"\n This function can calculate any one of the three (voltage, current, power),\n fundamental value of electrical system.\n examples are below:\n >>> electric_power(voltage=0, current=2, power=5)\n Result(name='voltage', value=2.5)\n >>> electric_power(voltage=2, current=2, power=0)\n Result(name='power', value=4.0)\n >>> electric_power(voltage=-2, current=3, power=0)\n Result(name='power', value=6.0)\n >>> electric_power(voltage=2, current=4, power=2)\n Traceback (most recent call last):\n ...\n ValueError: Only one argument must be 0\n >>> electric_power(voltage=0, current=0, power=2)\n Traceback (most recent call last):\n ...\n ValueError: Only one argument must be 0\n >>> electric_power(voltage=0, current=2, power=-4)\n Traceback (most recent call last):\n ...\n ValueError: Power cannot be negative in any electrical\/electronics system\n >>> electric_power(voltage=2.2, current=2.2, power=0)\n Result(name='power', value=4.84)\n \"\"\"\n if (voltage, current, power).count(0) != 1:\n raise ValueError(\"Only one argument must be 0\")\n elif power < 0:\n raise ValueError(\n \"Power cannot be negative in any electrical\/electronics system\"\n )\n elif voltage == 0:\n return Result(\"voltage\", power \/ current)\n elif current == 0:\n return Result(\"current\", power \/ voltage)\n elif power == 0:\n return Result(\"power\", float(round(abs(voltage * current), 2)))\n else:\n raise ValueError(\"Exactly one argument must be 0\")\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Electrical impedance is the measure of the opposition that a circuit presents to a current when a voltage is applied. Impedance extends the concept of resistance to alternating current AC circuits. Source: https:en.wikipedia.orgwikiElectricalimpedance Apply Electrical Impedance formula, on any two given electrical values, which can be resistance, reactance, and impedance, and then in a Python dict return namevalue pair of the zero value. electricalimpedance3,4,0 'impedance': 5.0 electricalimpedance0,4,5 'resistance': 3.0 electricalimpedance3,0,5 'reactance': 4.0 electricalimpedance3,4,5 Traceback most recent call last: ... ValueError: One and only one argument must be 0","Completions":"from __future__ import annotations\n\nfrom math import pow, sqrt\n\n\ndef electrical_impedance(\n resistance: float, reactance: float, impedance: float\n) -> dict[str, float]:\n \"\"\"\n Apply Electrical Impedance formula, on any two given electrical values,\n which can be resistance, reactance, and impedance, and then in a Python dict\n return name\/value pair of the zero value.\n\n >>> electrical_impedance(3,4,0)\n {'impedance': 5.0}\n >>> electrical_impedance(0,4,5)\n {'resistance': 3.0}\n >>> electrical_impedance(3,0,5)\n {'reactance': 4.0}\n >>> electrical_impedance(3,4,5)\n Traceback (most recent call last):\n ...\n ValueError: One and only one argument must be 0\n \"\"\"\n if (resistance, reactance, impedance).count(0) != 1:\n raise ValueError(\"One and only one argument must be 0\")\n if resistance == 0:\n return {\"resistance\": sqrt(pow(impedance, 2) - pow(reactance, 2))}\n elif reactance == 0:\n return {\"reactance\": sqrt(pow(impedance, 2) - pow(resistance, 2))}\n elif impedance == 0:\n return {\"impedance\": sqrt(pow(resistance, 2) + pow(reactance, 2))}\n else:\n raise ValueError(\"Exactly one argument must be 0\")\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Calculate the frequency andor duty cycle of an astable 555 timer. https:en.wikipedia.orgwiki555timerICAstable These functions take in the value of the external resistances in ohms and capacitance in Microfarad, and calculates the following: Freq 1.44 R1 2 x R2 x C1 ... in Hz where Freq is the frequency, R1 is the first resistance in ohms, R2 is the second resistance in ohms, C1 is the capacitance in Microfarads. Duty Cycle R1 R2 R1 2 x R2 x 100 ... in where R1 is the first resistance in ohms, R2 is the second resistance in ohms. Usage examples: astablefrequencyresistance145, resistance245, capacitance7 1523.8095238095239 astablefrequencyresistance1356, resistance2234, capacitance976 1.7905459175553078 astablefrequencyresistance12, resistance21, capacitance2 Traceback most recent call last: ... ValueError: All values must be positive astablefrequencyresistance145, resistance245, capacitance0 Traceback most recent call last: ... ValueError: All values must be positive Usage examples: astabledutycycleresistance145, resistance245 66.66666666666666 astabledutycycleresistance1356, resistance2234 71.60194174757282 astabledutycycleresistance12, resistance21 Traceback most recent call last: ... ValueError: All values must be positive astabledutycycleresistance10, resistance20 Traceback most recent call last: ... ValueError: All values must be positive","Completions":"from __future__ import annotations\n\n\"\"\"\n Calculate the frequency and\/or duty cycle of an astable 555 timer.\n * https:\/\/en.wikipedia.org\/wiki\/555_timer_IC#Astable\n\n These functions take in the value of the external resistances (in ohms)\n and capacitance (in Microfarad), and calculates the following:\n\n -------------------------------------\n | Freq = 1.44 \/[( R1+ 2 x R2) x C1] | ... in Hz\n -------------------------------------\n where Freq is the frequency,\n R1 is the first resistance in ohms,\n R2 is the second resistance in ohms,\n C1 is the capacitance in Microfarads.\n\n ------------------------------------------------\n | Duty Cycle = (R1 + R2) \/ (R1 + 2 x R2) x 100 | ... in %\n ------------------------------------------------\n where R1 is the first resistance in ohms,\n R2 is the second resistance in ohms.\n\"\"\"\n\n\ndef astable_frequency(\n resistance_1: float, resistance_2: float, capacitance: float\n) -> float:\n \"\"\"\n Usage examples:\n >>> astable_frequency(resistance_1=45, resistance_2=45, capacitance=7)\n 1523.8095238095239\n >>> astable_frequency(resistance_1=356, resistance_2=234, capacitance=976)\n 1.7905459175553078\n >>> astable_frequency(resistance_1=2, resistance_2=-1, capacitance=2)\n Traceback (most recent call last):\n ...\n ValueError: All values must be positive\n >>> astable_frequency(resistance_1=45, resistance_2=45, capacitance=0)\n Traceback (most recent call last):\n ...\n ValueError: All values must be positive\n \"\"\"\n\n if resistance_1 <= 0 or resistance_2 <= 0 or capacitance <= 0:\n raise ValueError(\"All values must be positive\")\n return (1.44 \/ ((resistance_1 + 2 * resistance_2) * capacitance)) * 10**6\n\n\ndef astable_duty_cycle(resistance_1: float, resistance_2: float) -> float:\n \"\"\"\n Usage examples:\n >>> astable_duty_cycle(resistance_1=45, resistance_2=45)\n 66.66666666666666\n >>> astable_duty_cycle(resistance_1=356, resistance_2=234)\n 71.60194174757282\n >>> astable_duty_cycle(resistance_1=2, resistance_2=-1)\n Traceback (most recent call last):\n ...\n ValueError: All values must be positive\n >>> astable_duty_cycle(resistance_1=0, resistance_2=0)\n Traceback (most recent call last):\n ...\n ValueError: All values must be positive\n \"\"\"\n\n if resistance_1 <= 0 or resistance_2 <= 0:\n raise ValueError(\"All values must be positive\")\n return (resistance_1 + resistance_2) \/ (resistance_1 + 2 * resistance_2) * 100\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"https:en.wikipedia.orgwikiElectricalreactanceInductivereactance Calculate inductive reactance, frequency or inductance from two given electrical properties then return namevalue pair of the zero value in a Python dict. Parameters inductance : float with units in Henries frequency : float with units in Hertz reactance : float with units in Ohms indreactance35e6, 1e3, 0 Traceback most recent call last: ... ValueError: Inductance cannot be negative indreactance35e6, 1e3, 0 Traceback most recent call last: ... ValueError: Frequency cannot be negative indreactance35e6, 0, 1 Traceback most recent call last: ... ValueError: Inductive reactance cannot be negative indreactance0, 10e3, 50 'inductance': 0.0007957747154594767 indreactance35e3, 0, 50 'frequency': 227.36420441699332 indreactance35e6, 1e3, 0 'reactance': 0.2199114857512855","Completions":"# https:\/\/en.wikipedia.org\/wiki\/Electrical_reactance#Inductive_reactance\nfrom __future__ import annotations\n\nfrom math import pi\n\n\ndef ind_reactance(\n inductance: float, frequency: float, reactance: float\n) -> dict[str, float]:\n \"\"\"\n Calculate inductive reactance, frequency or inductance from two given electrical\n properties then return name\/value pair of the zero value in a Python dict.\n\n Parameters\n ----------\n inductance : float with units in Henries\n\n frequency : float with units in Hertz\n\n reactance : float with units in Ohms\n\n >>> ind_reactance(-35e-6, 1e3, 0)\n Traceback (most recent call last):\n ...\n ValueError: Inductance cannot be negative\n\n >>> ind_reactance(35e-6, -1e3, 0)\n Traceback (most recent call last):\n ...\n ValueError: Frequency cannot be negative\n\n >>> ind_reactance(35e-6, 0, -1)\n Traceback (most recent call last):\n ...\n ValueError: Inductive reactance cannot be negative\n\n >>> ind_reactance(0, 10e3, 50)\n {'inductance': 0.0007957747154594767}\n\n >>> ind_reactance(35e-3, 0, 50)\n {'frequency': 227.36420441699332}\n\n >>> ind_reactance(35e-6, 1e3, 0)\n {'reactance': 0.2199114857512855}\n\n \"\"\"\n\n if (inductance, frequency, reactance).count(0) != 1:\n raise ValueError(\"One and only one argument must be 0\")\n if inductance < 0:\n raise ValueError(\"Inductance cannot be negative\")\n if frequency < 0:\n raise ValueError(\"Frequency cannot be negative\")\n if reactance < 0:\n raise ValueError(\"Inductive reactance cannot be negative\")\n if inductance == 0:\n return {\"inductance\": reactance \/ (2 * pi * frequency)}\n elif frequency == 0:\n return {\"frequency\": reactance \/ (2 * pi * inductance)}\n elif reactance == 0:\n return {\"reactance\": 2 * pi * frequency * inductance}\n else:\n raise ValueError(\"Exactly one argument must be 0\")\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"https:en.wikipedia.orgwikiOhm27slaw Apply Ohm's Law, on any two given electrical values, which can be voltage, current, and resistance, and then in a Python dict return namevalue pair of the zero value. ohmslawvoltage10, resistance5, current0 'current': 2.0 ohmslawvoltage0, current0, resistance10 Traceback most recent call last: ... ValueError: One and only one argument must be 0 ohmslawvoltage0, current1, resistance2 Traceback most recent call last: ... ValueError: Resistance cannot be negative ohmslawresistance0, voltage10, current1 'resistance': 10.0 ohmslawvoltage0, current1.5, resistance2 'voltage': 3.0","Completions":"# https:\/\/en.wikipedia.org\/wiki\/Ohm%27s_law\nfrom __future__ import annotations\n\n\ndef ohms_law(voltage: float, current: float, resistance: float) -> dict[str, float]:\n \"\"\"\n Apply Ohm's Law, on any two given electrical values, which can be voltage, current,\n and resistance, and then in a Python dict return name\/value pair of the zero value.\n\n >>> ohms_law(voltage=10, resistance=5, current=0)\n {'current': 2.0}\n >>> ohms_law(voltage=0, current=0, resistance=10)\n Traceback (most recent call last):\n ...\n ValueError: One and only one argument must be 0\n >>> ohms_law(voltage=0, current=1, resistance=-2)\n Traceback (most recent call last):\n ...\n ValueError: Resistance cannot be negative\n >>> ohms_law(resistance=0, voltage=-10, current=1)\n {'resistance': -10.0}\n >>> ohms_law(voltage=0, current=-1.5, resistance=2)\n {'voltage': -3.0}\n \"\"\"\n if (voltage, current, resistance).count(0) != 1:\n raise ValueError(\"One and only one argument must be 0\")\n if resistance < 0:\n raise ValueError(\"Resistance cannot be negative\")\n if voltage == 0:\n return {\"voltage\": float(current * resistance)}\n elif current == 0:\n return {\"current\": voltage \/ resistance}\n elif resistance == 0:\n return {\"resistance\": voltage \/ current}\n else:\n raise ValueError(\"Exactly one argument must be 0\")\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Calculate real power from apparent power and power factor. Examples: realpower100, 0.9 90.0 realpower0, 0.8 0.0 realpower100, 0.9 90.0 Calculate reactive power from apparent power and power factor. Examples: reactivepower100, 0.9 43.58898943540673 reactivepower0, 0.8 0.0 reactivepower100, 0.9 43.58898943540673","Completions":"import math\n\n\ndef real_power(apparent_power: float, power_factor: float) -> float:\n \"\"\"\n Calculate real power from apparent power and power factor.\n\n Examples:\n >>> real_power(100, 0.9)\n 90.0\n >>> real_power(0, 0.8)\n 0.0\n >>> real_power(100, -0.9)\n -90.0\n \"\"\"\n if (\n not isinstance(power_factor, (int, float))\n or power_factor < -1\n or power_factor > 1\n ):\n raise ValueError(\"power_factor must be a valid float value between -1 and 1.\")\n return apparent_power * power_factor\n\n\ndef reactive_power(apparent_power: float, power_factor: float) -> float:\n \"\"\"\n Calculate reactive power from apparent power and power factor.\n\n Examples:\n >>> reactive_power(100, 0.9)\n 43.58898943540673\n >>> reactive_power(0, 0.8)\n 0.0\n >>> reactive_power(100, -0.9)\n 43.58898943540673\n \"\"\"\n if (\n not isinstance(power_factor, (int, float))\n or power_factor < -1\n or power_factor > 1\n ):\n raise ValueError(\"power_factor must be a valid float value between -1 and 1.\")\n return apparent_power * math.sqrt(1 - power_factor**2)\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Title : Calculating the resistance of a n band resistor using the color codes Description : Resistors resist the flow of electrical current.Each one has a value that tells how strongly it resists current flow.This value's unit is the ohm, often noted with the Greek letter omega: . The colored bands on a resistor can tell you everything you need to know about its value and tolerance, as long as you understand how to read them. The order in which the colors are arranged is very important, and each value of resistor has its own unique combination. The color coding for resistors is an international standard that is defined in IEC 60062. The number of bands present in a resistor varies from three to six. These represent significant figures, multiplier, tolerance, reliability, and temperature coefficient Each color used for a type of band has a value assigned to it. It is read from left to right. All resistors will have significant figures and multiplier bands. In a three band resistor first two bands from the left represent significant figures and the third represents the multiplier band. Significant figures The number of significant figures band in a resistor can vary from two to three. Colors and values associated with significant figure bands Black 0, Brown 1, Red 2, Orange 3, Yellow 4, Green 5, Blue 6, Violet 7, Grey 8, White 9 Multiplier There will be one multiplier band in a resistor. It is multiplied with the significant figures obtained from previous bands. Colors and values associated with multiplier band Black 100, Brown 101, Red 102, Orange 103, Yellow 104, Green 105, Blue 106, Violet 107, Grey 108, White 109, Gold 101, Silver 102 Note that multiplier bands use Gold and Silver which are not used for significant figure bands. Tolerance The tolerance band is not always present. It can be seen in four band resistors and above. This is a percentage by which the resistor value can vary. Colors and values associated with tolerance band Brown 1, Red 2, Orange 0.05, Yellow 0.02, Green 0.5,Blue 0.25, Violet 0.1, Grey 0.01, Gold 5, Silver 10 If no color is mentioned then by default tolerance is 20 Note that tolerance band does not use Black and White colors. Temperature Coeffecient Indicates the change in resistance of the component as a function of ambient temperature in terms of ppmK. It is present in six band resistors. Colors and values associated with Temperature coeffecient Black 250 ppmK, Brown 100 ppmK, Red 50 ppmK, Orange 15 ppmK, Yellow 25 ppmK, Green 20 ppmK, Blue 10 ppmK, Violet 5 ppmK, Grey 1 ppmK Note that temperature coeffecient band does not use White, Gold, Silver colors. Sources : https:www.calculator.netresistorcalculator.html https:learn.parallax.comsupportreferenceresistorcolorcodes https:byjus.comphysicsresistorcolourcodes Function returns the digit associated with the color. Function takes a list containing colors as input and returns digits as string getsignificantdigits'Black','Blue' '06' getsignificantdigits'Aqua','Blue' Traceback most recent call last: ... ValueError: Aqua is not a valid color for significant figure bands Function returns the multiplier value associated with the color. Function takes color as input and returns multiplier value getmultiplier'Gold' 0.1 getmultiplier'Ivory' Traceback most recent call last: ... ValueError: Ivory is not a valid color for multiplier band Function returns the tolerance value associated with the color. Function takes color as input and returns tolerance value. gettolerance'Green' 0.5 gettolerance'Indigo' Traceback most recent call last: ... ValueError: Indigo is not a valid color for tolerance band Function returns the temperature coeffecient value associated with the color. Function takes color as input and returns temperature coeffecient value. gettemperaturecoeffecient'Yellow' 25 gettemperaturecoeffecient'Cyan' Traceback most recent call last: ... ValueError: Cyan is not a valid color for temperature coeffecient band Function returns the number of bands of a given type in a resistor with n bands Function takes totalnumberofbands and typeofband as input and returns number of bands belonging to that type in the given resistor getbandtypecount3,'significant' 2 getbandtypecount2,'significant' Traceback most recent call last: ... ValueError: 2 is not a valid number of bands getbandtypecount3,'sign' Traceback most recent call last: ... ValueError: sign is not valid for a 3 band resistor getbandtypecount3,'tolerance' Traceback most recent call last: ... ValueError: tolerance is not valid for a 3 band resistor getbandtypecount5,'tempcoeffecient' Traceback most recent call last: ... ValueError: tempcoeffecient is not valid for a 5 band resistor Function checks if the input provided is valid or not. Function takes numberofbands and colors as input and returns True if it is valid checkvalidity3, Black,Blue,Orange True checkvalidity4, Black,Blue,Orange Traceback most recent call last: ... ValueError: Expecting 4 colors, provided 3 colors checkvalidity3, Cyan,Red,Yellow Traceback most recent call last: ... ValueError: Cyan is not a valid color Function calculates the total resistance of the resistor using the color codes. Function takes numberofbands, colorcodelist as input and returns resistance calculateresistance3, Black,Blue,Orange 'resistance': '6000 20 ' calculateresistance4, Orange,Green,Blue,Gold 'resistance': '35000000 5 ' calculateresistance5, Violet,Brown,Grey,Silver,Green 'resistance': '7.18 0.5 ' calculateresistance6, Red,Green,Blue,Yellow,Orange,Grey 'resistance': '2560000 0.05 1 ppmK' calculateresistance0, Violet,Brown,Grey,Silver,Green Traceback most recent call last: ... ValueError: Invalid number of bands. Resistor bands must be 3 to 6 calculateresistance4, Violet,Brown,Grey,Silver,Green Traceback most recent call last: ... ValueError: Expecting 4 colors, provided 5 colors calculateresistance4, Violet,Silver,Brown,Grey Traceback most recent call last: ... ValueError: Silver is not a valid color for significant figure bands calculateresistance4, Violet,Blue,Lime,Grey Traceback most recent call last: ... ValueError: Lime is not a valid color","Completions":"valid_colors: list = [\n \"Black\",\n \"Brown\",\n \"Red\",\n \"Orange\",\n \"Yellow\",\n \"Green\",\n \"Blue\",\n \"Violet\",\n \"Grey\",\n \"White\",\n \"Gold\",\n \"Silver\",\n]\n\nsignificant_figures_color_values: dict[str, int] = {\n \"Black\": 0,\n \"Brown\": 1,\n \"Red\": 2,\n \"Orange\": 3,\n \"Yellow\": 4,\n \"Green\": 5,\n \"Blue\": 6,\n \"Violet\": 7,\n \"Grey\": 8,\n \"White\": 9,\n}\n\nmultiplier_color_values: dict[str, float] = {\n \"Black\": 10**0,\n \"Brown\": 10**1,\n \"Red\": 10**2,\n \"Orange\": 10**3,\n \"Yellow\": 10**4,\n \"Green\": 10**5,\n \"Blue\": 10**6,\n \"Violet\": 10**7,\n \"Grey\": 10**8,\n \"White\": 10**9,\n \"Gold\": 10**-1,\n \"Silver\": 10**-2,\n}\n\ntolerance_color_values: dict[str, float] = {\n \"Brown\": 1,\n \"Red\": 2,\n \"Orange\": 0.05,\n \"Yellow\": 0.02,\n \"Green\": 0.5,\n \"Blue\": 0.25,\n \"Violet\": 0.1,\n \"Grey\": 0.01,\n \"Gold\": 5,\n \"Silver\": 10,\n}\n\ntemperature_coeffecient_color_values: dict[str, int] = {\n \"Black\": 250,\n \"Brown\": 100,\n \"Red\": 50,\n \"Orange\": 15,\n \"Yellow\": 25,\n \"Green\": 20,\n \"Blue\": 10,\n \"Violet\": 5,\n \"Grey\": 1,\n}\n\nband_types: dict[int, dict[str, int]] = {\n 3: {\"significant\": 2, \"multiplier\": 1},\n 4: {\"significant\": 2, \"multiplier\": 1, \"tolerance\": 1},\n 5: {\"significant\": 3, \"multiplier\": 1, \"tolerance\": 1},\n 6: {\"significant\": 3, \"multiplier\": 1, \"tolerance\": 1, \"temp_coeffecient\": 1},\n}\n\n\ndef get_significant_digits(colors: list) -> str:\n \"\"\"\n Function returns the digit associated with the color. Function takes a\n list containing colors as input and returns digits as string\n\n >>> get_significant_digits(['Black','Blue'])\n '06'\n\n >>> get_significant_digits(['Aqua','Blue'])\n Traceback (most recent call last):\n ...\n ValueError: Aqua is not a valid color for significant figure bands\n\n \"\"\"\n digit = \"\"\n for color in colors:\n if color not in significant_figures_color_values:\n msg = f\"{color} is not a valid color for significant figure bands\"\n raise ValueError(msg)\n digit = digit + str(significant_figures_color_values[color])\n return str(digit)\n\n\ndef get_multiplier(color: str) -> float:\n \"\"\"\n Function returns the multiplier value associated with the color.\n Function takes color as input and returns multiplier value\n\n >>> get_multiplier('Gold')\n 0.1\n\n >>> get_multiplier('Ivory')\n Traceback (most recent call last):\n ...\n ValueError: Ivory is not a valid color for multiplier band\n\n \"\"\"\n if color not in multiplier_color_values:\n msg = f\"{color} is not a valid color for multiplier band\"\n raise ValueError(msg)\n return multiplier_color_values[color]\n\n\ndef get_tolerance(color: str) -> float:\n \"\"\"\n Function returns the tolerance value associated with the color.\n Function takes color as input and returns tolerance value.\n\n >>> get_tolerance('Green')\n 0.5\n\n >>> get_tolerance('Indigo')\n Traceback (most recent call last):\n ...\n ValueError: Indigo is not a valid color for tolerance band\n\n \"\"\"\n if color not in tolerance_color_values:\n msg = f\"{color} is not a valid color for tolerance band\"\n raise ValueError(msg)\n return tolerance_color_values[color]\n\n\ndef get_temperature_coeffecient(color: str) -> int:\n \"\"\"\n Function returns the temperature coeffecient value associated with the color.\n Function takes color as input and returns temperature coeffecient value.\n\n >>> get_temperature_coeffecient('Yellow')\n 25\n\n >>> get_temperature_coeffecient('Cyan')\n Traceback (most recent call last):\n ...\n ValueError: Cyan is not a valid color for temperature coeffecient band\n\n \"\"\"\n if color not in temperature_coeffecient_color_values:\n msg = f\"{color} is not a valid color for temperature coeffecient band\"\n raise ValueError(msg)\n return temperature_coeffecient_color_values[color]\n\n\ndef get_band_type_count(total_number_of_bands: int, type_of_band: str) -> int:\n \"\"\"\n Function returns the number of bands of a given type in a resistor with n bands\n Function takes total_number_of_bands and type_of_band as input and returns\n number of bands belonging to that type in the given resistor\n\n >>> get_band_type_count(3,'significant')\n 2\n\n >>> get_band_type_count(2,'significant')\n Traceback (most recent call last):\n ...\n ValueError: 2 is not a valid number of bands\n\n >>> get_band_type_count(3,'sign')\n Traceback (most recent call last):\n ...\n ValueError: sign is not valid for a 3 band resistor\n\n >>> get_band_type_count(3,'tolerance')\n Traceback (most recent call last):\n ...\n ValueError: tolerance is not valid for a 3 band resistor\n\n >>> get_band_type_count(5,'temp_coeffecient')\n Traceback (most recent call last):\n ...\n ValueError: temp_coeffecient is not valid for a 5 band resistor\n\n \"\"\"\n if total_number_of_bands not in band_types:\n msg = f\"{total_number_of_bands} is not a valid number of bands\"\n raise ValueError(msg)\n if type_of_band not in band_types[total_number_of_bands]:\n msg = f\"{type_of_band} is not valid for a {total_number_of_bands} band resistor\"\n raise ValueError(msg)\n return band_types[total_number_of_bands][type_of_band]\n\n\ndef check_validity(number_of_bands: int, colors: list) -> bool:\n \"\"\"\n Function checks if the input provided is valid or not.\n Function takes number_of_bands and colors as input and returns\n True if it is valid\n\n >>> check_validity(3, [\"Black\",\"Blue\",\"Orange\"])\n True\n\n >>> check_validity(4, [\"Black\",\"Blue\",\"Orange\"])\n Traceback (most recent call last):\n ...\n ValueError: Expecting 4 colors, provided 3 colors\n\n >>> check_validity(3, [\"Cyan\",\"Red\",\"Yellow\"])\n Traceback (most recent call last):\n ...\n ValueError: Cyan is not a valid color\n\n \"\"\"\n if number_of_bands >= 3 and number_of_bands <= 6:\n if number_of_bands == len(colors):\n for color in colors:\n if color not in valid_colors:\n msg = f\"{color} is not a valid color\"\n raise ValueError(msg)\n return True\n else:\n msg = f\"Expecting {number_of_bands} colors, provided {len(colors)} colors\"\n raise ValueError(msg)\n else:\n msg = \"Invalid number of bands. Resistor bands must be 3 to 6\"\n raise ValueError(msg)\n\n\ndef calculate_resistance(number_of_bands: int, color_code_list: list) -> dict:\n \"\"\"\n Function calculates the total resistance of the resistor using the color codes.\n Function takes number_of_bands, color_code_list as input and returns\n resistance\n\n >>> calculate_resistance(3, [\"Black\",\"Blue\",\"Orange\"])\n {'resistance': '6000\u03a9 \u00b120% '}\n\n >>> calculate_resistance(4, [\"Orange\",\"Green\",\"Blue\",\"Gold\"])\n {'resistance': '35000000\u03a9 \u00b15% '}\n\n >>> calculate_resistance(5, [\"Violet\",\"Brown\",\"Grey\",\"Silver\",\"Green\"])\n {'resistance': '7.18\u03a9 \u00b10.5% '}\n\n >>> calculate_resistance(6, [\"Red\",\"Green\",\"Blue\",\"Yellow\",\"Orange\",\"Grey\"])\n {'resistance': '2560000\u03a9 \u00b10.05% 1 ppm\/K'}\n\n >>> calculate_resistance(0, [\"Violet\",\"Brown\",\"Grey\",\"Silver\",\"Green\"])\n Traceback (most recent call last):\n ...\n ValueError: Invalid number of bands. Resistor bands must be 3 to 6\n\n >>> calculate_resistance(4, [\"Violet\",\"Brown\",\"Grey\",\"Silver\",\"Green\"])\n Traceback (most recent call last):\n ...\n ValueError: Expecting 4 colors, provided 5 colors\n\n >>> calculate_resistance(4, [\"Violet\",\"Silver\",\"Brown\",\"Grey\"])\n Traceback (most recent call last):\n ...\n ValueError: Silver is not a valid color for significant figure bands\n\n >>> calculate_resistance(4, [\"Violet\",\"Blue\",\"Lime\",\"Grey\"])\n Traceback (most recent call last):\n ...\n ValueError: Lime is not a valid color\n\n \"\"\"\n is_valid = check_validity(number_of_bands, color_code_list)\n if is_valid:\n number_of_significant_bands = get_band_type_count(\n number_of_bands, \"significant\"\n )\n significant_colors = color_code_list[:number_of_significant_bands]\n significant_digits = int(get_significant_digits(significant_colors))\n multiplier_color = color_code_list[number_of_significant_bands]\n multiplier = get_multiplier(multiplier_color)\n if number_of_bands == 3:\n tolerance_color = None\n else:\n tolerance_color = color_code_list[number_of_significant_bands + 1]\n tolerance = (\n 20 if tolerance_color is None else get_tolerance(str(tolerance_color))\n )\n if number_of_bands != 6:\n temperature_coeffecient_color = None\n else:\n temperature_coeffecient_color = color_code_list[\n number_of_significant_bands + 2\n ]\n temperature_coeffecient = (\n 0\n if temperature_coeffecient_color is None\n else get_temperature_coeffecient(str(temperature_coeffecient_color))\n )\n resisitance = significant_digits * multiplier\n if temperature_coeffecient == 0:\n answer = f\"{resisitance}\u03a9 \u00b1{tolerance}% \"\n else:\n answer = f\"{resisitance}\u03a9 \u00b1{tolerance}% {temperature_coeffecient} ppm\/K\"\n return {\"resistance\": answer}\n else:\n raise ValueError(\"Input is invalid\")\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"https:byjus.comequivalentresistanceformula Req 1 1R1 1R2 ... 1Rn resistorparallel3.21389, 2, 3 0.8737571620498019 resistorparallel3.21389, 2, 3 Traceback most recent call last: ... ValueError: Resistor at index 2 has a negative or zero value! resistorparallel3.21389, 2, 0.000 Traceback most recent call last: ... ValueError: Resistor at index 2 has a negative or zero value! Req R1 R2 ... Rn Calculate the equivalent resistance for any number of resistors in parallel. resistorseries3.21389, 2, 3 8.21389 resistorseries3.21389, 2, 3 Traceback most recent call last: ... ValueError: Resistor at index 2 has a negative value!","Completions":"# https:\/\/byjus.com\/equivalent-resistance-formula\/\n\nfrom __future__ import annotations\n\n\ndef resistor_parallel(resistors: list[float]) -> float:\n \"\"\"\n Req = 1\/ (1\/R1 + 1\/R2 + ... + 1\/Rn)\n\n >>> resistor_parallel([3.21389, 2, 3])\n 0.8737571620498019\n >>> resistor_parallel([3.21389, 2, -3])\n Traceback (most recent call last):\n ...\n ValueError: Resistor at index 2 has a negative or zero value!\n >>> resistor_parallel([3.21389, 2, 0.000])\n Traceback (most recent call last):\n ...\n ValueError: Resistor at index 2 has a negative or zero value!\n \"\"\"\n\n first_sum = 0.00\n index = 0\n for resistor in resistors:\n if resistor <= 0:\n msg = f\"Resistor at index {index} has a negative or zero value!\"\n raise ValueError(msg)\n first_sum += 1 \/ float(resistor)\n index += 1\n return 1 \/ first_sum\n\n\ndef resistor_series(resistors: list[float]) -> float:\n \"\"\"\n Req = R1 + R2 + ... + Rn\n\n Calculate the equivalent resistance for any number of resistors in parallel.\n\n >>> resistor_series([3.21389, 2, 3])\n 8.21389\n >>> resistor_series([3.21389, 2, -3])\n Traceback (most recent call last):\n ...\n ValueError: Resistor at index 2 has a negative value!\n \"\"\"\n sum_r = 0.00\n index = 0\n for resistor in resistors:\n sum_r += resistor\n if resistor < 0:\n msg = f\"Resistor at index {index} has a negative value!\"\n raise ValueError(msg)\n index += 1\n return sum_r\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"https:en.wikipedia.orgwikiLCcircuit An LC circuit, also called a resonant circuit, tank circuit, or tuned circuit, is an electric circuit consisting of an inductor, represented by the letter L, and a capacitor, represented by the letter C, connected together. The circuit can act as an electrical resonator, an electrical analogue of a tuning fork, storing energy oscillating at the circuit's resonant frequency. Source: https:en.wikipedia.orgwikiLCcircuit This function can calculate the resonant frequency of LC circuit, for the given value of inductance and capacitnace. Examples are given below: resonantfrequencyinductance10, capacitance5 'Resonant frequency', 0.022507907903927652 resonantfrequencyinductance0, capacitance5 Traceback most recent call last: ... ValueError: Inductance cannot be 0 or negative resonantfrequencyinductance10, capacitance0 Traceback most recent call last: ... ValueError: Capacitance cannot be 0 or negative","Completions":"# https:\/\/en.wikipedia.org\/wiki\/LC_circuit\n\n\"\"\"An LC circuit, also called a resonant circuit, tank circuit, or tuned circuit,\nis an electric circuit consisting of an inductor, represented by the letter L,\nand a capacitor, represented by the letter C, connected together.\nThe circuit can act as an electrical resonator, an electrical analogue of a\ntuning fork, storing energy oscillating at the circuit's resonant frequency.\nSource: https:\/\/en.wikipedia.org\/wiki\/LC_circuit\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom math import pi, sqrt\n\n\ndef resonant_frequency(inductance: float, capacitance: float) -> tuple:\n \"\"\"\n This function can calculate the resonant frequency of LC circuit,\n for the given value of inductance and capacitnace.\n\n Examples are given below:\n >>> resonant_frequency(inductance=10, capacitance=5)\n ('Resonant frequency', 0.022507907903927652)\n >>> resonant_frequency(inductance=0, capacitance=5)\n Traceback (most recent call last):\n ...\n ValueError: Inductance cannot be 0 or negative\n >>> resonant_frequency(inductance=10, capacitance=0)\n Traceback (most recent call last):\n ...\n ValueError: Capacitance cannot be 0 or negative\n \"\"\"\n\n if inductance <= 0:\n raise ValueError(\"Inductance cannot be 0 or negative\")\n\n elif capacitance <= 0:\n raise ValueError(\"Capacitance cannot be 0 or negative\")\n\n else:\n return (\n \"Resonant frequency\",\n float(1 \/ (2 * pi * (sqrt(inductance * capacitance)))),\n )\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"https:en.wikipedia.orgwikiWheatstonebridge This function can calculate the unknown resistance in an wheatstone network, given that the three other resistances in the network are known. The formula to calculate the same is: RxR2R1R3 Usage examples: wheatstonesolverresistance12, resistance24, resistance35 10.0 wheatstonesolverresistance1356, resistance2234, resistance3976 641.5280898876405 wheatstonesolverresistance12, resistance21, resistance32 Traceback most recent call last: ... ValueError: All resistance values must be positive wheatstonesolverresistance10, resistance20, resistance32 Traceback most recent call last: ... ValueError: All resistance values must be positive","Completions":"# https:\/\/en.wikipedia.org\/wiki\/Wheatstone_bridge\nfrom __future__ import annotations\n\n\ndef wheatstone_solver(\n resistance_1: float, resistance_2: float, resistance_3: float\n) -> float:\n \"\"\"\n This function can calculate the unknown resistance in an wheatstone network,\n given that the three other resistances in the network are known.\n The formula to calculate the same is:\n\n ---------------\n |Rx=(R2\/R1)*R3|\n ---------------\n\n Usage examples:\n >>> wheatstone_solver(resistance_1=2, resistance_2=4, resistance_3=5)\n 10.0\n >>> wheatstone_solver(resistance_1=356, resistance_2=234, resistance_3=976)\n 641.5280898876405\n >>> wheatstone_solver(resistance_1=2, resistance_2=-1, resistance_3=2)\n Traceback (most recent call last):\n ...\n ValueError: All resistance values must be positive\n >>> wheatstone_solver(resistance_1=0, resistance_2=0, resistance_3=2)\n Traceback (most recent call last):\n ...\n ValueError: All resistance values must be positive\n \"\"\"\n\n if resistance_1 <= 0 or resistance_2 <= 0 or resistance_3 <= 0:\n raise ValueError(\"All resistance values must be positive\")\n else:\n return float((resistance_2 \/ resistance_1) * resistance_3)\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"initialization invoke ensurance","Completions":"from unittest.mock import Mock, patch\n\nfrom file_transfer.send_file import send_file\n\n\n@patch(\"socket.socket\")\n@patch(\"builtins.open\")\ndef test_send_file_running_as_expected(file, sock):\n # ===== initialization =====\n conn = Mock()\n sock.return_value.accept.return_value = conn, Mock()\n f = iter([1, None])\n file.return_value.__enter__.return_value.read.side_effect = lambda _: next(f)\n\n # ===== invoke =====\n send_file(filename=\"mytext.txt\", testing=True)\n\n # ===== ensurance =====\n sock.assert_called_once()\n sock.return_value.bind.assert_called_once()\n sock.return_value.listen.assert_called_once()\n sock.return_value.accept.assert_called_once()\n conn.recv.assert_called_once()\n\n file.return_value.__enter__.assert_called_once()\n file.return_value.__enter__.return_value.read.assert_called()\n\n conn.send.assert_called_once()\n conn.close.assert_called_once()\n sock.return_value.shutdown.assert_called_once()\n sock.return_value.close.assert_called_once()\n"} +{"Prompt":"Program to calculate the amortization amount per month, given Principal borrowed Rate of interest per annum Years to repay the loan Wikipedia Reference: https:en.wikipedia.orgwikiEquatedmonthlyinstallment Formula for amortization amount per month: A p r 1 rn 1 rn 1 where p is the principal, r is the rate of interest per month and n is the number of payments equatedmonthlyinstallments25000, 0.12, 3 830.3577453212793 equatedmonthlyinstallments25000, 0.12, 10 358.67737100646826 equatedmonthlyinstallments0, 0.12, 3 Traceback most recent call last: ... Exception: Principal borrowed must be 0 equatedmonthlyinstallments25000, 1, 3 Traceback most recent call last: ... Exception: Rate of interest must be 0 equatedmonthlyinstallments25000, 0.12, 0 Traceback most recent call last: ... Exception: Years to repay must be an integer 0 Yearly rate is divided by 12 to get monthly rate Years to repay is multiplied by 12 to get number of payments as payment is monthly","Completions":"def equated_monthly_installments(\n principal: float, rate_per_annum: float, years_to_repay: int\n) -> float:\n \"\"\"\n Formula for amortization amount per month:\n A = p * r * (1 + r)^n \/ ((1 + r)^n - 1)\n where p is the principal, r is the rate of interest per month\n and n is the number of payments\n\n >>> equated_monthly_installments(25000, 0.12, 3)\n 830.3577453212793\n >>> equated_monthly_installments(25000, 0.12, 10)\n 358.67737100646826\n >>> equated_monthly_installments(0, 0.12, 3)\n Traceback (most recent call last):\n ...\n Exception: Principal borrowed must be > 0\n >>> equated_monthly_installments(25000, -1, 3)\n Traceback (most recent call last):\n ...\n Exception: Rate of interest must be >= 0\n >>> equated_monthly_installments(25000, 0.12, 0)\n Traceback (most recent call last):\n ...\n Exception: Years to repay must be an integer > 0\n \"\"\"\n if principal <= 0:\n raise Exception(\"Principal borrowed must be > 0\")\n if rate_per_annum < 0:\n raise Exception(\"Rate of interest must be >= 0\")\n if years_to_repay <= 0 or not isinstance(years_to_repay, int):\n raise Exception(\"Years to repay must be an integer > 0\")\n\n # Yearly rate is divided by 12 to get monthly rate\n rate_per_month = rate_per_annum \/ 12\n\n # Years to repay is multiplied by 12 to get number of payments as payment is monthly\n number_of_payments = years_to_repay * 12\n\n return (\n principal\n * rate_per_month\n * (1 + rate_per_month) ** number_of_payments\n \/ ((1 + rate_per_month) ** number_of_payments - 1)\n )\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Calculate the exponential moving average EMA on the series of stock prices. Wikipedia Reference: https:en.wikipedia.orgwikiExponentialsmoothing https:www.investopedia.comtermseema.asptocwhatisanexponential movingaverageema Exponential moving average is used in finance to analyze changes stock prices. EMA is used in conjunction with Simple moving average SMA, EMA reacts to the changes in the value quicker than SMA, which is one of the advantages of using EMA. Yields exponential moving averages of the given stock prices. tupleexponentialmovingaverageiter2, 5, 3, 8.2, 6, 9, 10, 3 2, 3.5, 3.25, 5.725, 5.8625, 7.43125, 8.715625 :param stockprices: A stream of stock prices :param windowsize: The number of stock prices that will trigger a new calculation of the exponential average windowsize 0 :return: Yields a sequence of exponential moving averages Formula: st alpha xt 1 alpha stprev Where, st : Exponential moving average at timestamp t xt : stock price in from the stock prices at timestamp t stprev : Exponential moving average at timestamp t1 alpha : 21 windowsize smoothing factor Exponential moving average EMA is a rule of thumb technique for smoothing time series data using an exponential window function. Calculating smoothing factor Exponential average at timestamp t Assigning simple moving average till the windowsize for the first time is reached Calculating exponential moving average based on current timestamp data point and previous exponential average value","Completions":"from collections.abc import Iterator\n\n\ndef exponential_moving_average(\n stock_prices: Iterator[float], window_size: int\n) -> Iterator[float]:\n \"\"\"\n Yields exponential moving averages of the given stock prices.\n >>> tuple(exponential_moving_average(iter([2, 5, 3, 8.2, 6, 9, 10]), 3))\n (2, 3.5, 3.25, 5.725, 5.8625, 7.43125, 8.715625)\n\n :param stock_prices: A stream of stock prices\n :param window_size: The number of stock prices that will trigger a new calculation\n of the exponential average (window_size > 0)\n :return: Yields a sequence of exponential moving averages\n\n Formula:\n\n st = alpha * xt + (1 - alpha) * st_prev\n\n Where,\n st : Exponential moving average at timestamp t\n xt : stock price in from the stock prices at timestamp t\n st_prev : Exponential moving average at timestamp t-1\n alpha : 2\/(1 + window_size) - smoothing factor\n\n Exponential moving average (EMA) is a rule of thumb technique for\n smoothing time series data using an exponential window function.\n \"\"\"\n\n if window_size <= 0:\n raise ValueError(\"window_size must be > 0\")\n\n # Calculating smoothing factor\n alpha = 2 \/ (1 + window_size)\n\n # Exponential average at timestamp t\n moving_average = 0.0\n\n for i, stock_price in enumerate(stock_prices):\n if i <= window_size:\n # Assigning simple moving average till the window_size for the first time\n # is reached\n moving_average = (moving_average + stock_price) * 0.5 if i else stock_price\n else:\n # Calculating exponential moving average based on current timestamp data\n # point and previous exponential average value\n moving_average = (alpha * stock_price) + ((1 - alpha) * moving_average)\n yield moving_average\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n\n stock_prices = [2.0, 5, 3, 8.2, 6, 9, 10]\n window_size = 3\n result = tuple(exponential_moving_average(iter(stock_prices), window_size))\n print(f\"{stock_prices = }\")\n print(f\"{window_size = }\")\n print(f\"{result = }\")\n"} +{"Prompt":"https:www.investopedia.com simpleinterest18000.0, 0.06, 3 3240.0 simpleinterest0.5, 0.06, 3 0.09 simpleinterest18000.0, 0.01, 10 1800.0 simpleinterest18000.0, 0.0, 3 0.0 simpleinterest5500.0, 0.01, 100 5500.0 simpleinterest10000.0, 0.06, 3 Traceback most recent call last: ... ValueError: dailyinterestrate must be 0 simpleinterest10000.0, 0.06, 3 Traceback most recent call last: ... ValueError: principal must be 0 simpleinterest5500.0, 0.01, 5 Traceback most recent call last: ... ValueError: daysbetweenpayments must be 0 compoundinterest10000.0, 0.05, 3 1576.2500000000014 compoundinterest10000.0, 0.05, 1 500.00000000000045 compoundinterest0.5, 0.05, 3 0.07881250000000006 compoundinterest10000.0, 0.06, 4 Traceback most recent call last: ... ValueError: numberofcompoundingperiods must be 0 compoundinterest10000.0, 3.5, 3.0 Traceback most recent call last: ... ValueError: nominalannualinterestratepercentage must be 0 compoundinterest5500.0, 0.01, 5 Traceback most recent call last: ... ValueError: principal must be 0 aprinterest10000.0, 0.05, 3 1618.223072263547 aprinterest10000.0, 0.05, 1 512.6749646744732 aprinterest0.5, 0.05, 3 0.08091115361317736 aprinterest10000.0, 0.06, 4 Traceback most recent call last: ... ValueError: numberofyears must be 0 aprinterest10000.0, 3.5, 3.0 Traceback most recent call last: ... ValueError: nominalannualpercentagerate must be 0 aprinterest5500.0, 0.01, 5 Traceback most recent call last: ... ValueError: principal must be 0","Completions":"# https:\/\/www.investopedia.com\n\nfrom __future__ import annotations\n\n\ndef simple_interest(\n principal: float, daily_interest_rate: float, days_between_payments: float\n) -> float:\n \"\"\"\n >>> simple_interest(18000.0, 0.06, 3)\n 3240.0\n >>> simple_interest(0.5, 0.06, 3)\n 0.09\n >>> simple_interest(18000.0, 0.01, 10)\n 1800.0\n >>> simple_interest(18000.0, 0.0, 3)\n 0.0\n >>> simple_interest(5500.0, 0.01, 100)\n 5500.0\n >>> simple_interest(10000.0, -0.06, 3)\n Traceback (most recent call last):\n ...\n ValueError: daily_interest_rate must be >= 0\n >>> simple_interest(-10000.0, 0.06, 3)\n Traceback (most recent call last):\n ...\n ValueError: principal must be > 0\n >>> simple_interest(5500.0, 0.01, -5)\n Traceback (most recent call last):\n ...\n ValueError: days_between_payments must be > 0\n \"\"\"\n if days_between_payments <= 0:\n raise ValueError(\"days_between_payments must be > 0\")\n if daily_interest_rate < 0:\n raise ValueError(\"daily_interest_rate must be >= 0\")\n if principal <= 0:\n raise ValueError(\"principal must be > 0\")\n return principal * daily_interest_rate * days_between_payments\n\n\ndef compound_interest(\n principal: float,\n nominal_annual_interest_rate_percentage: float,\n number_of_compounding_periods: float,\n) -> float:\n \"\"\"\n >>> compound_interest(10000.0, 0.05, 3)\n 1576.2500000000014\n >>> compound_interest(10000.0, 0.05, 1)\n 500.00000000000045\n >>> compound_interest(0.5, 0.05, 3)\n 0.07881250000000006\n >>> compound_interest(10000.0, 0.06, -4)\n Traceback (most recent call last):\n ...\n ValueError: number_of_compounding_periods must be > 0\n >>> compound_interest(10000.0, -3.5, 3.0)\n Traceback (most recent call last):\n ...\n ValueError: nominal_annual_interest_rate_percentage must be >= 0\n >>> compound_interest(-5500.0, 0.01, 5)\n Traceback (most recent call last):\n ...\n ValueError: principal must be > 0\n \"\"\"\n if number_of_compounding_periods <= 0:\n raise ValueError(\"number_of_compounding_periods must be > 0\")\n if nominal_annual_interest_rate_percentage < 0:\n raise ValueError(\"nominal_annual_interest_rate_percentage must be >= 0\")\n if principal <= 0:\n raise ValueError(\"principal must be > 0\")\n\n return principal * (\n (1 + nominal_annual_interest_rate_percentage) ** number_of_compounding_periods\n - 1\n )\n\n\ndef apr_interest(\n principal: float,\n nominal_annual_percentage_rate: float,\n number_of_years: float,\n) -> float:\n \"\"\"\n >>> apr_interest(10000.0, 0.05, 3)\n 1618.223072263547\n >>> apr_interest(10000.0, 0.05, 1)\n 512.6749646744732\n >>> apr_interest(0.5, 0.05, 3)\n 0.08091115361317736\n >>> apr_interest(10000.0, 0.06, -4)\n Traceback (most recent call last):\n ...\n ValueError: number_of_years must be > 0\n >>> apr_interest(10000.0, -3.5, 3.0)\n Traceback (most recent call last):\n ...\n ValueError: nominal_annual_percentage_rate must be >= 0\n >>> apr_interest(-5500.0, 0.01, 5)\n Traceback (most recent call last):\n ...\n ValueError: principal must be > 0\n \"\"\"\n if number_of_years <= 0:\n raise ValueError(\"number_of_years must be > 0\")\n if nominal_annual_percentage_rate < 0:\n raise ValueError(\"nominal_annual_percentage_rate must be >= 0\")\n if principal <= 0:\n raise ValueError(\"principal must be > 0\")\n\n return compound_interest(\n principal, nominal_annual_percentage_rate \/ 365, number_of_years * 365\n )\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Reference: https:www.investopedia.comtermsppresentvalue.asp An algorithm that calculates the present value of a stream of yearly cash flows given... 1. The discount rate as a decimal, not a percent 2. An array of cash flows, with the index of the cash flow being the associated year Note: This algorithm assumes that cash flows are paid at the end of the specified year presentvalue0.13, 10, 20.70, 293, 297 4.69 presentvalue0.07, 109129.39, 30923.23, 15098.93, 29734,39 42739.63 presentvalue0.07, 109129.39, 30923.23, 15098.93, 29734,39 175519.15 presentvalue1, 109129.39, 30923.23, 15098.93, 29734,39 Traceback most recent call last: ... ValueError: Discount rate cannot be negative presentvalue0.03, Traceback most recent call last: ... ValueError: Cash flows list cannot be empty","Completions":"def present_value(discount_rate: float, cash_flows: list[float]) -> float:\n \"\"\"\n >>> present_value(0.13, [10, 20.70, -293, 297])\n 4.69\n >>> present_value(0.07, [-109129.39, 30923.23, 15098.93, 29734,39])\n -42739.63\n >>> present_value(0.07, [109129.39, 30923.23, 15098.93, 29734,39])\n 175519.15\n >>> present_value(-1, [109129.39, 30923.23, 15098.93, 29734,39])\n Traceback (most recent call last):\n ...\n ValueError: Discount rate cannot be negative\n >>> present_value(0.03, [])\n Traceback (most recent call last):\n ...\n ValueError: Cash flows list cannot be empty\n \"\"\"\n if discount_rate < 0:\n raise ValueError(\"Discount rate cannot be negative\")\n if not cash_flows:\n raise ValueError(\"Cash flows list cannot be empty\")\n present_value = sum(\n cash_flow \/ ((1 + discount_rate) ** i) for i, cash_flow in enumerate(cash_flows)\n )\n return round(present_value, ndigits=2)\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Calculate price plus tax of a good or service given its price and a tax rate. priceplustax100, 0.25 125.0 priceplustax125.50, 0.05 131.775","Completions":"def price_plus_tax(price: float, tax_rate: float) -> float:\n \"\"\"\n >>> price_plus_tax(100, 0.25)\n 125.0\n >>> price_plus_tax(125.50, 0.05)\n 131.775\n \"\"\"\n return price * (1 + tax_rate)\n\n\nif __name__ == \"__main__\":\n print(f\"{price_plus_tax(100, 0.25) = }\")\n print(f\"{price_plus_tax(125.50, 0.05) = }\")\n"} +{"Prompt":"The Simple Moving Average SMA is a statistical calculation used to analyze data points by creating a constantly updated average price over a specific time period. In finance, SMA is often used in time series analysis to smooth out price data and identify trends. Reference: https:en.wikipedia.orgwikiMovingaverage Calculate the simple moving average SMA for some given time series data. :param data: A list of numerical data points. :param windowsize: An integer representing the size of the SMA window. :return: A list of SMA values with the same length as the input data. Examples: sma simplemovingaverage10, 12, 15, 13, 14, 16, 18, 17, 19, 21, 3 roundvalue, 2 if value is not None else None for value in sma None, None, 12.33, 13.33, 14.0, 14.33, 16.0, 17.0, 18.0, 19.0 simplemovingaverage10, 12, 15, 5 None, None, None simplemovingaverage10, 12, 15, 13, 14, 16, 18, 17, 19, 21, 0 Traceback most recent call last: ... ValueError: Window size must be a positive integer Example data replace with your own time series data Specify the window size for the SMA Calculate the Simple Moving Average Print the SMA values","Completions":"from collections.abc import Sequence\n\n\ndef simple_moving_average(\n data: Sequence[float], window_size: int\n) -> list[float | None]:\n \"\"\"\n Calculate the simple moving average (SMA) for some given time series data.\n\n :param data: A list of numerical data points.\n :param window_size: An integer representing the size of the SMA window.\n :return: A list of SMA values with the same length as the input data.\n\n Examples:\n >>> sma = simple_moving_average([10, 12, 15, 13, 14, 16, 18, 17, 19, 21], 3)\n >>> [round(value, 2) if value is not None else None for value in sma]\n [None, None, 12.33, 13.33, 14.0, 14.33, 16.0, 17.0, 18.0, 19.0]\n >>> simple_moving_average([10, 12, 15], 5)\n [None, None, None]\n >>> simple_moving_average([10, 12, 15, 13, 14, 16, 18, 17, 19, 21], 0)\n Traceback (most recent call last):\n ...\n ValueError: Window size must be a positive integer\n \"\"\"\n if window_size < 1:\n raise ValueError(\"Window size must be a positive integer\")\n\n sma: list[float | None] = []\n\n for i in range(len(data)):\n if i < window_size - 1:\n sma.append(None) # SMA not available for early data points\n else:\n window = data[i - window_size + 1 : i + 1]\n sma_value = sum(window) \/ window_size\n sma.append(sma_value)\n return sma\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n\n # Example data (replace with your own time series data)\n data = [10, 12, 15, 13, 14, 16, 18, 17, 19, 21]\n\n # Specify the window size for the SMA\n window_size = 3\n\n # Calculate the Simple Moving Average\n sma_values = simple_moving_average(data, window_size)\n\n # Print the SMA values\n print(\"Simple Moving Average (SMA) Values:\")\n for i, value in enumerate(sma_values):\n if value is not None:\n print(f\"Day {i + 1}: {value:.2f}\")\n else:\n print(f\"Day {i + 1}: Not enough data for SMA\")\n"} +{"Prompt":"Author Alexandre De Zotti Draws Julia sets of quadratic polynomials and exponential maps. More specifically, this iterates the function a fixed number of times then plots whether the absolute value of the last iterate is greater than a fixed threshold named escape radius. For the exponential map this is not really an escape radius but rather a convenient way to approximate the Julia set with bounded orbits. The examples presented here are: The Cauliflower Julia set, see e.g. https:en.wikipedia.orgwikiFile:Juliaz22B0,25.png Other examples from https:en.wikipedia.orgwikiJuliaset An exponential map Julia set, ambiantly homeomorphic to the examples in https:www.math.univtoulouse.frcheritatGalIIgalery.html and https:ddd.uab.catpubpubmat02141493v43n102141493v43n1p27.pdf Remark: Some overflow runtime warnings are suppressed. This is because of the way the iteration loop is implemented, using numpy's efficient computations. Overflows and infinites are replaced after each step by a large number. Evaluate ez c. evalexponential0, 0 1.0 absevalexponential1, numpy.pi1.j 1e15 True absevalexponential1.j, 011.j 1e15 True evalquadraticpolynomial0, 2 4 evalquadraticpolynomial1, 1 0 roundevalquadraticpolynomial1.j, 0.imag 1 roundevalquadraticpolynomial1.j, 0.real 0 Create a grid of complex values of size nbpixelsnbpixels with real and imaginary parts ranging from windowsize to windowsize inclusive. Returns a numpy array. preparegrid1,3 array1.1.j, 1.0.j, 1.1.j, 0.1.j, 0.0.j, 0.1.j, 1.1.j, 1.0.j, 1.1.j Iterate the function evalfunction exactly nbiterations times. The first argument of the function is a parameter which is contained in functionparams. The variable z0 is an array that contains the initial values to iterate from. This function returns the final iterates. iteratefunctionevalquadraticpolynomial, 0, 3, numpy.array0,1,2.shape 3, numpy.rounditeratefunctionevalquadraticpolynomial, ... 0, ... 3, ... numpy.array0,1,20 0j numpy.rounditeratefunctionevalquadraticpolynomial, ... 0, ... 3, ... numpy.array0,1,21 10j numpy.rounditeratefunctionevalquadraticpolynomial, ... 0, ... 3, ... numpy.array0,1,22 2560j Plots of whether the absolute value of zfinal is greater than the value of escaperadius. Adds the functionlabel and functionparams to the title. showresults'80', 0, 1, numpy.array0,1,.5,.4,2,1.1,.2,1,1.3 Ignore some overflow and invalid value warnings. ignoreoverflowwarnings","Completions":"import warnings\nfrom collections.abc import Callable\nfrom typing import Any\n\nimport numpy\nfrom matplotlib import pyplot\n\nc_cauliflower = 0.25 + 0.0j\nc_polynomial_1 = -0.4 + 0.6j\nc_polynomial_2 = -0.1 + 0.651j\nc_exponential = -2.0\nnb_iterations = 56\nwindow_size = 2.0\nnb_pixels = 666\n\n\ndef eval_exponential(c_parameter: complex, z_values: numpy.ndarray) -> numpy.ndarray:\n \"\"\"\n Evaluate $e^z + c$.\n >>> eval_exponential(0, 0)\n 1.0\n >>> abs(eval_exponential(1, numpy.pi*1.j)) < 1e-15\n True\n >>> abs(eval_exponential(1.j, 0)-1-1.j) < 1e-15\n True\n \"\"\"\n return numpy.exp(z_values) + c_parameter\n\n\ndef eval_quadratic_polynomial(\n c_parameter: complex, z_values: numpy.ndarray\n) -> numpy.ndarray:\n \"\"\"\n >>> eval_quadratic_polynomial(0, 2)\n 4\n >>> eval_quadratic_polynomial(-1, 1)\n 0\n >>> round(eval_quadratic_polynomial(1.j, 0).imag)\n 1\n >>> round(eval_quadratic_polynomial(1.j, 0).real)\n 0\n \"\"\"\n return z_values * z_values + c_parameter\n\n\ndef prepare_grid(window_size: float, nb_pixels: int) -> numpy.ndarray:\n \"\"\"\n Create a grid of complex values of size nb_pixels*nb_pixels with real and\n imaginary parts ranging from -window_size to window_size (inclusive).\n Returns a numpy array.\n\n >>> prepare_grid(1,3)\n array([[-1.-1.j, -1.+0.j, -1.+1.j],\n [ 0.-1.j, 0.+0.j, 0.+1.j],\n [ 1.-1.j, 1.+0.j, 1.+1.j]])\n \"\"\"\n x = numpy.linspace(-window_size, window_size, nb_pixels)\n x = x.reshape((nb_pixels, 1))\n y = numpy.linspace(-window_size, window_size, nb_pixels)\n y = y.reshape((1, nb_pixels))\n return x + 1.0j * y\n\n\ndef iterate_function(\n eval_function: Callable[[Any, numpy.ndarray], numpy.ndarray],\n function_params: Any,\n nb_iterations: int,\n z_0: numpy.ndarray,\n infinity: float | None = None,\n) -> numpy.ndarray:\n \"\"\"\n Iterate the function \"eval_function\" exactly nb_iterations times.\n The first argument of the function is a parameter which is contained in\n function_params. The variable z_0 is an array that contains the initial\n values to iterate from.\n This function returns the final iterates.\n\n >>> iterate_function(eval_quadratic_polynomial, 0, 3, numpy.array([0,1,2])).shape\n (3,)\n >>> numpy.round(iterate_function(eval_quadratic_polynomial,\n ... 0,\n ... 3,\n ... numpy.array([0,1,2]))[0])\n 0j\n >>> numpy.round(iterate_function(eval_quadratic_polynomial,\n ... 0,\n ... 3,\n ... numpy.array([0,1,2]))[1])\n (1+0j)\n >>> numpy.round(iterate_function(eval_quadratic_polynomial,\n ... 0,\n ... 3,\n ... numpy.array([0,1,2]))[2])\n (256+0j)\n \"\"\"\n\n z_n = z_0.astype(\"complex64\")\n for _ in range(nb_iterations):\n z_n = eval_function(function_params, z_n)\n if infinity is not None:\n numpy.nan_to_num(z_n, copy=False, nan=infinity)\n z_n[abs(z_n) == numpy.inf] = infinity\n return z_n\n\n\ndef show_results(\n function_label: str,\n function_params: Any,\n escape_radius: float,\n z_final: numpy.ndarray,\n) -> None:\n \"\"\"\n Plots of whether the absolute value of z_final is greater than\n the value of escape_radius. Adds the function_label and function_params to\n the title.\n\n >>> show_results('80', 0, 1, numpy.array([[0,1,.5],[.4,2,1.1],[.2,1,1.3]]))\n \"\"\"\n\n abs_z_final = (abs(z_final)).transpose()\n abs_z_final[:, :] = abs_z_final[::-1, :]\n pyplot.matshow(abs_z_final < escape_radius)\n pyplot.title(f\"Julia set of ${function_label}$, $c={function_params}$\")\n pyplot.show()\n\n\ndef ignore_overflow_warnings() -> None:\n \"\"\"\n Ignore some overflow and invalid value warnings.\n\n >>> ignore_overflow_warnings()\n \"\"\"\n warnings.filterwarnings(\n \"ignore\", category=RuntimeWarning, message=\"overflow encountered in multiply\"\n )\n warnings.filterwarnings(\n \"ignore\",\n category=RuntimeWarning,\n message=\"invalid value encountered in multiply\",\n )\n warnings.filterwarnings(\n \"ignore\", category=RuntimeWarning, message=\"overflow encountered in absolute\"\n )\n warnings.filterwarnings(\n \"ignore\", category=RuntimeWarning, message=\"overflow encountered in exp\"\n )\n\n\nif __name__ == \"__main__\":\n z_0 = prepare_grid(window_size, nb_pixels)\n\n ignore_overflow_warnings() # See file header for explanations\n\n nb_iterations = 24\n escape_radius = 2 * abs(c_cauliflower) + 1\n z_final = iterate_function(\n eval_quadratic_polynomial,\n c_cauliflower,\n nb_iterations,\n z_0,\n infinity=1.1 * escape_radius,\n )\n show_results(\"z^2+c\", c_cauliflower, escape_radius, z_final)\n\n nb_iterations = 64\n escape_radius = 2 * abs(c_polynomial_1) + 1\n z_final = iterate_function(\n eval_quadratic_polynomial,\n c_polynomial_1,\n nb_iterations,\n z_0,\n infinity=1.1 * escape_radius,\n )\n show_results(\"z^2+c\", c_polynomial_1, escape_radius, z_final)\n\n nb_iterations = 161\n escape_radius = 2 * abs(c_polynomial_2) + 1\n z_final = iterate_function(\n eval_quadratic_polynomial,\n c_polynomial_2,\n nb_iterations,\n z_0,\n infinity=1.1 * escape_radius,\n )\n show_results(\"z^2+c\", c_polynomial_2, escape_radius, z_final)\n\n nb_iterations = 12\n escape_radius = 10000.0\n z_final = iterate_function(\n eval_exponential,\n c_exponential,\n nb_iterations,\n z_0 + 2,\n infinity=1.0e10,\n )\n show_results(\"e^z+c\", c_exponential, escape_radius, z_final)\n"} +{"Prompt":"Description The Koch snowflake is a fractal curve and one of the earliest fractals to have been described. The Koch snowflake can be built up iteratively, in a sequence of stages. The first stage is an equilateral triangle, and each successive stage is formed by adding outward bends to each side of the previous stage, making smaller equilateral triangles. This can be achieved through the following steps for each line: 1. divide the line segment into three segments of equal length. 2. draw an equilateral triangle that has the middle segment from step 1 as its base and points outward. 3. remove the line segment that is the base of the triangle from step 2. description adapted from https:en.wikipedia.orgwikiKochsnowflake for a more detailed explanation and an implementation in the Processing language, see https:natureofcode.combookchapter8fractals 84thekochcurveandthearraylisttechnique Requirements pip: matplotlib numpy initial triangle of Koch snowflake uncomment for simple Koch curve instead of Koch snowflake INITIALVECTORS VECTOR1, VECTOR3 Go through the number of iterations determined by the argument steps. Be careful with high values above 5 since the time to calculate increases exponentially. iteratenumpy.array0, 0, numpy.array1, 0, 1 array0, 0, array0.33333333, 0. , array0.5 , 0.28867513, array0.66666667, 0. , array1, 0 Loops through each pair of adjacent vectors. Each line between two adjacent vectors is divided into 4 segments by adding 3 additional vectors inbetween the original two vectors. The vector in the middle is constructed through a 60 degree rotation so it is bent outwards. iterationstepnumpy.array0, 0, numpy.array1, 0 array0, 0, array0.33333333, 0. , array0.5 , 0.28867513, array0.66666667, 0. , array1, 0 Standard rotation of a 2D vector with a rotation matrix see https:en.wikipedia.orgwikiRotationmatrix rotatenumpy.array1, 0, 60 array0.5 , 0.8660254 rotatenumpy.array1, 0, 90 array6.123234e17, 1.000000e00 Utility function to plot the vectors using matplotlib.pyplot No doctest was implemented since this function does not have a return value avoid stretched display of graph matplotlib.pyplot.plot takes a list of all xcoordinates and a list of all ycoordinates as inputs, which are constructed from the vectorlist using zip","Completions":"from __future__ import annotations\n\nimport matplotlib.pyplot as plt # type: ignore\nimport numpy\n\n# initial triangle of Koch snowflake\nVECTOR_1 = numpy.array([0, 0])\nVECTOR_2 = numpy.array([0.5, 0.8660254])\nVECTOR_3 = numpy.array([1, 0])\nINITIAL_VECTORS = [VECTOR_1, VECTOR_2, VECTOR_3, VECTOR_1]\n\n# uncomment for simple Koch curve instead of Koch snowflake\n# INITIAL_VECTORS = [VECTOR_1, VECTOR_3]\n\n\ndef iterate(initial_vectors: list[numpy.ndarray], steps: int) -> list[numpy.ndarray]:\n \"\"\"\n Go through the number of iterations determined by the argument \"steps\".\n Be careful with high values (above 5) since the time to calculate increases\n exponentially.\n >>> iterate([numpy.array([0, 0]), numpy.array([1, 0])], 1)\n [array([0, 0]), array([0.33333333, 0. ]), array([0.5 , \\\n0.28867513]), array([0.66666667, 0. ]), array([1, 0])]\n \"\"\"\n vectors = initial_vectors\n for _ in range(steps):\n vectors = iteration_step(vectors)\n return vectors\n\n\ndef iteration_step(vectors: list[numpy.ndarray]) -> list[numpy.ndarray]:\n \"\"\"\n Loops through each pair of adjacent vectors. Each line between two adjacent\n vectors is divided into 4 segments by adding 3 additional vectors in-between\n the original two vectors. The vector in the middle is constructed through a\n 60 degree rotation so it is bent outwards.\n >>> iteration_step([numpy.array([0, 0]), numpy.array([1, 0])])\n [array([0, 0]), array([0.33333333, 0. ]), array([0.5 , \\\n0.28867513]), array([0.66666667, 0. ]), array([1, 0])]\n \"\"\"\n new_vectors = []\n for i, start_vector in enumerate(vectors[:-1]):\n end_vector = vectors[i + 1]\n new_vectors.append(start_vector)\n difference_vector = end_vector - start_vector\n new_vectors.append(start_vector + difference_vector \/ 3)\n new_vectors.append(\n start_vector + difference_vector \/ 3 + rotate(difference_vector \/ 3, 60)\n )\n new_vectors.append(start_vector + difference_vector * 2 \/ 3)\n new_vectors.append(vectors[-1])\n return new_vectors\n\n\ndef rotate(vector: numpy.ndarray, angle_in_degrees: float) -> numpy.ndarray:\n \"\"\"\n Standard rotation of a 2D vector with a rotation matrix\n (see https:\/\/en.wikipedia.org\/wiki\/Rotation_matrix )\n >>> rotate(numpy.array([1, 0]), 60)\n array([0.5 , 0.8660254])\n >>> rotate(numpy.array([1, 0]), 90)\n array([6.123234e-17, 1.000000e+00])\n \"\"\"\n theta = numpy.radians(angle_in_degrees)\n c, s = numpy.cos(theta), numpy.sin(theta)\n rotation_matrix = numpy.array(((c, -s), (s, c)))\n return numpy.dot(rotation_matrix, vector)\n\n\ndef plot(vectors: list[numpy.ndarray]) -> None:\n \"\"\"\n Utility function to plot the vectors using matplotlib.pyplot\n No doctest was implemented since this function does not have a return value\n \"\"\"\n # avoid stretched display of graph\n axes = plt.gca()\n axes.set_aspect(\"equal\")\n\n # matplotlib.pyplot.plot takes a list of all x-coordinates and a list of all\n # y-coordinates as inputs, which are constructed from the vector-list using\n # zip()\n x_coordinates, y_coordinates = zip(*vectors)\n plt.plot(x_coordinates, y_coordinates)\n plt.show()\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n\n processed_vectors = iterate(INITIAL_VECTORS, 5)\n plot(processed_vectors)\n"} +{"Prompt":"The Mandelbrot set is the set of complex numbers c for which the series zn1 zn zn c does not diverge, i.e. remains bounded. Thus, a complex number c is a member of the Mandelbrot set if, when starting with z0 0 and applying the iteration repeatedly, the absolute value of zn remains bounded for all n 0. Complex numbers can be written as a bi: a is the real component, usually drawn on the xaxis, and bi is the imaginary component, usually drawn on the yaxis. Most visualizations of the Mandelbrot set use a colorcoding to indicate after how many steps in the series the numbers outside the set diverge. Images of the Mandelbrot set exhibit an elaborate and infinitely complicated boundary that reveals progressively everfiner recursive detail at increasing magnifications, making the boundary of the Mandelbrot set a fractal curve. description adapted from https:en.wikipedia.orgwikiMandelbrotset see also https:en.wikipedia.orgwikiPlottingalgorithmsfortheMandelbrotset Return the relative distance stepmaxstep after which the complex number constituted by this xypair diverges. Members of the Mandelbrot set do not diverge so their distance is 1. getdistance0, 0, 50 1.0 getdistance0.5, 0.5, 50 0.061224489795918366 getdistance2, 0, 50 0.0 divergence happens for all complex number with an absolute value greater than 4 Blackwhite colorcoding that ignores the relative distance. The Mandelbrot set is black, everything else is white. getblackandwhitergb0 255, 255, 255 getblackandwhitergb0.5 255, 255, 255 getblackandwhitergb1 0, 0, 0 Colorcoding taking the relative distance into account. The Mandelbrot set is black. getcolorcodedrgb0 255, 0, 0 getcolorcodedrgb0.5 0, 255, 255 getcolorcodedrgb1 0, 0, 0 Function to generate the image of the Mandelbrot set. Two types of coordinates are used: imagecoordinates that refer to the pixels and figurecoordinates that refer to the complex numbers inside and outside the Mandelbrot set. The figurecoordinates in the arguments of this function determine which section of the Mandelbrot set is viewed. The main area of the Mandelbrot set is roughly between 1.5 x 0.5 and 1 y 1 in the figurecoordinates. Commenting out tests that slow down pytest... 13.35s call fractalsmandelbrot.py::mandelbrot.getimage getimage.load0,0 255, 0, 0 getimageusedistancecolorcoding False.load0,0 255, 255, 255 loop through the imagecoordinates determine the figurecoordinates based on the imagecoordinates color the corresponding pixel based on the selected coloringfunction colored version, full figure uncomment for colored version, different section, zoomed in img getimagefigurecenterx 0.6, figurecentery 0.4, figurewidth 0.8 uncomment for black and white version, full figure img getimageusedistancecolorcoding False uncomment to save the image img.savemandelbrot.png","Completions":"import colorsys\n\nfrom PIL import Image # type: ignore\n\n\ndef get_distance(x: float, y: float, max_step: int) -> float:\n \"\"\"\n Return the relative distance (= step\/max_step) after which the complex number\n constituted by this x-y-pair diverges. Members of the Mandelbrot set do not\n diverge so their distance is 1.\n\n >>> get_distance(0, 0, 50)\n 1.0\n >>> get_distance(0.5, 0.5, 50)\n 0.061224489795918366\n >>> get_distance(2, 0, 50)\n 0.0\n \"\"\"\n a = x\n b = y\n for step in range(max_step): # noqa: B007\n a_new = a * a - b * b + x\n b = 2 * a * b + y\n a = a_new\n\n # divergence happens for all complex number with an absolute value\n # greater than 4\n if a * a + b * b > 4:\n break\n return step \/ (max_step - 1)\n\n\ndef get_black_and_white_rgb(distance: float) -> tuple:\n \"\"\"\n Black&white color-coding that ignores the relative distance. The Mandelbrot\n set is black, everything else is white.\n\n >>> get_black_and_white_rgb(0)\n (255, 255, 255)\n >>> get_black_and_white_rgb(0.5)\n (255, 255, 255)\n >>> get_black_and_white_rgb(1)\n (0, 0, 0)\n \"\"\"\n if distance == 1:\n return (0, 0, 0)\n else:\n return (255, 255, 255)\n\n\ndef get_color_coded_rgb(distance: float) -> tuple:\n \"\"\"\n Color-coding taking the relative distance into account. The Mandelbrot set\n is black.\n\n >>> get_color_coded_rgb(0)\n (255, 0, 0)\n >>> get_color_coded_rgb(0.5)\n (0, 255, 255)\n >>> get_color_coded_rgb(1)\n (0, 0, 0)\n \"\"\"\n if distance == 1:\n return (0, 0, 0)\n else:\n return tuple(round(i * 255) for i in colorsys.hsv_to_rgb(distance, 1, 1))\n\n\ndef get_image(\n image_width: int = 800,\n image_height: int = 600,\n figure_center_x: float = -0.6,\n figure_center_y: float = 0,\n figure_width: float = 3.2,\n max_step: int = 50,\n use_distance_color_coding: bool = True,\n) -> Image.Image:\n \"\"\"\n Function to generate the image of the Mandelbrot set. Two types of coordinates\n are used: image-coordinates that refer to the pixels and figure-coordinates\n that refer to the complex numbers inside and outside the Mandelbrot set. The\n figure-coordinates in the arguments of this function determine which section\n of the Mandelbrot set is viewed. The main area of the Mandelbrot set is\n roughly between \"-1.5 < x < 0.5\" and \"-1 < y < 1\" in the figure-coordinates.\n\n Commenting out tests that slow down pytest...\n # 13.35s call fractals\/mandelbrot.py::mandelbrot.get_image\n # >>> get_image().load()[0,0]\n (255, 0, 0)\n # >>> get_image(use_distance_color_coding = False).load()[0,0]\n (255, 255, 255)\n \"\"\"\n img = Image.new(\"RGB\", (image_width, image_height))\n pixels = img.load()\n\n # loop through the image-coordinates\n for image_x in range(image_width):\n for image_y in range(image_height):\n # determine the figure-coordinates based on the image-coordinates\n figure_height = figure_width \/ image_width * image_height\n figure_x = figure_center_x + (image_x \/ image_width - 0.5) * figure_width\n figure_y = figure_center_y + (image_y \/ image_height - 0.5) * figure_height\n\n distance = get_distance(figure_x, figure_y, max_step)\n\n # color the corresponding pixel based on the selected coloring-function\n if use_distance_color_coding:\n pixels[image_x, image_y] = get_color_coded_rgb(distance)\n else:\n pixels[image_x, image_y] = get_black_and_white_rgb(distance)\n\n return img\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n\n # colored version, full figure\n img = get_image()\n\n # uncomment for colored version, different section, zoomed in\n # img = get_image(figure_center_x = -0.6, figure_center_y = -0.4,\n # figure_width = 0.8)\n\n # uncomment for black and white version, full figure\n # img = get_image(use_distance_color_coding = False)\n\n # uncomment to save the image\n # img.save(\"mandelbrot.png\")\n\n img.show()\n"} +{"Prompt":"Author Anurag Kumar anuragkumarak95gmail.com gitanuragkumarak95 Simple example of fractal generation using recursion. What is the Sierpiski Triangle? The Sierpiski triangle sometimes spelled Sierpinski, also called the Sierpiski gasket or Sierpiski sieve, is a fractal attractive fixed set with the overall shape of an equilateral triangle, subdivided recursively into smaller equilateral triangles. Originally constructed as a curve, this is one of the basic examples of selfsimilar setsthat is, it is a mathematically generated pattern that is reproducible at any magnification or reduction. It is named after the Polish mathematician Wacaw Sierpiski, but appeared as a decorative pattern many centuries before the work of Sierpiski. Usage: python sierpinskitriangle.py int:depthforfractal Credits: The above description is taken from https:en.wikipedia.orgwikiSierpiC584skitriangle This code was written by editing the code from https:www.riannetrujillo.comblogpythonfractal Find the midpoint of two points getmid0, 0, 2, 2 1.0, 1.0 getmid3, 3, 3, 3 0.0, 0.0 getmid1, 0, 3, 2 2.0, 1.0 getmid0, 0, 1, 1 0.5, 0.5 getmid0, 0, 0, 0 0.0, 0.0 Recursively draw the Sierpinski triangle given the vertices of the triangle and the recursion depth","Completions":"import sys\nimport turtle\n\n\ndef get_mid(p1: tuple[float, float], p2: tuple[float, float]) -> tuple[float, float]:\n \"\"\"\n Find the midpoint of two points\n\n >>> get_mid((0, 0), (2, 2))\n (1.0, 1.0)\n >>> get_mid((-3, -3), (3, 3))\n (0.0, 0.0)\n >>> get_mid((1, 0), (3, 2))\n (2.0, 1.0)\n >>> get_mid((0, 0), (1, 1))\n (0.5, 0.5)\n >>> get_mid((0, 0), (0, 0))\n (0.0, 0.0)\n \"\"\"\n return (p1[0] + p2[0]) \/ 2, (p1[1] + p2[1]) \/ 2\n\n\ndef triangle(\n vertex1: tuple[float, float],\n vertex2: tuple[float, float],\n vertex3: tuple[float, float],\n depth: int,\n) -> None:\n \"\"\"\n Recursively draw the Sierpinski triangle given the vertices of the triangle\n and the recursion depth\n \"\"\"\n my_pen.up()\n my_pen.goto(vertex1[0], vertex1[1])\n my_pen.down()\n my_pen.goto(vertex2[0], vertex2[1])\n my_pen.goto(vertex3[0], vertex3[1])\n my_pen.goto(vertex1[0], vertex1[1])\n\n if depth == 0:\n return\n\n triangle(vertex1, get_mid(vertex1, vertex2), get_mid(vertex1, vertex3), depth - 1)\n triangle(vertex2, get_mid(vertex1, vertex2), get_mid(vertex2, vertex3), depth - 1)\n triangle(vertex3, get_mid(vertex3, vertex2), get_mid(vertex1, vertex3), depth - 1)\n\n\nif __name__ == \"__main__\":\n if len(sys.argv) != 2:\n raise ValueError(\n \"Correct format for using this script: \"\n \"python fractals.py \"\n )\n my_pen = turtle.Turtle()\n my_pen.ht()\n my_pen.speed(5)\n my_pen.pencolor(\"red\")\n\n vertices = [(-175, -125), (0, 175), (175, -125)] # vertices of triangle\n triangle(vertices[0], vertices[1], vertices[2], int(sys.argv[1]))\n turtle.Screen().exitonclick()\n"} +{"Prompt":"By Shreya123714 https:en.wikipedia.orgwikiFuzzyset A class for representing and manipulating triangular fuzzy sets. Attributes: name: The name or label of the fuzzy set. leftboundary: The left boundary of the fuzzy set. peak: The peak central value of the fuzzy set. rightboundary: The right boundary of the fuzzy set. Methods: membershipx: Calculate the membership value of an input 'x' in the fuzzy set. unionother: Calculate the union of this fuzzy set with another fuzzy set. intersectionother: Calculate the intersection of this fuzzy set with another. complement: Calculate the complement negation of this fuzzy set. plot: Plot the membership function of the fuzzy set. sheru FuzzySetSheru, 0.4, 1, 0.6 sheru FuzzySetname'Sheru', leftboundary0.4, peak1, rightboundary0.6 strsheru 'Sheru: 0.4, 1, 0.6' siya FuzzySetSiya, 0.5, 1, 0.7 siya FuzzySetname'Siya', leftboundary0.5, peak1, rightboundary0.7 Complement Operation sheru.complement FuzzySetname'Sheru', leftboundary0.4, peak0.6, rightboundary0 siya.complement doctest: NORMALIZEWHITESPACE FuzzySetname'Siya', leftboundary0.30000000000000004, peak0.5, rightboundary0 Intersection Operation siya.intersectionsheru FuzzySetname'Siya Sheru', leftboundary0.5, peak0.6, rightboundary1.0 Membership Operation sheru.membership0.5 0.16666666666666663 sheru.membership0.6 0.0 Union Operations siya.unionsheru FuzzySetname'Siya Sheru', leftboundary0.4, peak0.7, rightboundary1.0 FuzzySetfuzzyset, 0.1, 0.2, 0.3 FuzzySetname'fuzzyset', leftboundary0.1, peak0.2, rightboundary0.3 Calculate the complement negation of this fuzzy set. Returns: FuzzySet: A new fuzzy set representing the complement. FuzzySetfuzzyset, 0.1, 0.2, 0.3.complement FuzzySetname'fuzzyset', leftboundary0.7, peak0.9, rightboundary0.8 Calculate the intersection of this fuzzy set with another fuzzy set. Args: other: Another fuzzy set to intersect with. Returns: A new fuzzy set representing the intersection. FuzzySeta, 0.1, 0.2, 0.3.intersectionFuzzySetb, 0.4, 0.5, 0.6 FuzzySetname'a b', leftboundary0.4, peak0.3, rightboundary0.35 Calculate the membership value of an input 'x' in the fuzzy set. Returns: The membership value of 'x' in the fuzzy set. a FuzzySeta, 0.1, 0.2, 0.3 a.membership0.09 0.0 a.membership0.1 0.0 a.membership0.11 0.09999999999999995 a.membership0.4 0.0 FuzzySetA, 0, 0.5, 1.membership0.1 0.2 FuzzySetB, 0.2, 0.7, 1.membership0.6 0.8 Calculate the union of this fuzzy set with another fuzzy set. Args: other FuzzySet: Another fuzzy set to union with. Returns: FuzzySet: A new fuzzy set representing the union. FuzzySeta, 0.1, 0.2, 0.3.unionFuzzySetb, 0.4, 0.5, 0.6 FuzzySetname'a b', leftboundary0.1, peak0.6, rightboundary0.35 Plot the membership function of the fuzzy set.","Completions":"from __future__ import annotations\n\nfrom dataclasses import dataclass\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\n@dataclass\nclass FuzzySet:\n \"\"\"\n A class for representing and manipulating triangular fuzzy sets.\n Attributes:\n name: The name or label of the fuzzy set.\n left_boundary: The left boundary of the fuzzy set.\n peak: The peak (central) value of the fuzzy set.\n right_boundary: The right boundary of the fuzzy set.\n Methods:\n membership(x): Calculate the membership value of an input 'x' in the fuzzy set.\n union(other): Calculate the union of this fuzzy set with another fuzzy set.\n intersection(other): Calculate the intersection of this fuzzy set with another.\n complement(): Calculate the complement (negation) of this fuzzy set.\n plot(): Plot the membership function of the fuzzy set.\n\n >>> sheru = FuzzySet(\"Sheru\", 0.4, 1, 0.6)\n >>> sheru\n FuzzySet(name='Sheru', left_boundary=0.4, peak=1, right_boundary=0.6)\n >>> str(sheru)\n 'Sheru: [0.4, 1, 0.6]'\n\n >>> siya = FuzzySet(\"Siya\", 0.5, 1, 0.7)\n >>> siya\n FuzzySet(name='Siya', left_boundary=0.5, peak=1, right_boundary=0.7)\n\n # Complement Operation\n >>> sheru.complement()\n FuzzySet(name='\u00acSheru', left_boundary=0.4, peak=0.6, right_boundary=0)\n >>> siya.complement() # doctest: +NORMALIZE_WHITESPACE\n FuzzySet(name='\u00acSiya', left_boundary=0.30000000000000004, peak=0.5,\n right_boundary=0)\n\n # Intersection Operation\n >>> siya.intersection(sheru)\n FuzzySet(name='Siya \u2229 Sheru', left_boundary=0.5, peak=0.6, right_boundary=1.0)\n\n # Membership Operation\n >>> sheru.membership(0.5)\n 0.16666666666666663\n >>> sheru.membership(0.6)\n 0.0\n\n # Union Operations\n >>> siya.union(sheru)\n FuzzySet(name='Siya \u222a Sheru', left_boundary=0.4, peak=0.7, right_boundary=1.0)\n \"\"\"\n\n name: str\n left_boundary: float\n peak: float\n right_boundary: float\n\n def __str__(self) -> str:\n \"\"\"\n >>> FuzzySet(\"fuzzy_set\", 0.1, 0.2, 0.3)\n FuzzySet(name='fuzzy_set', left_boundary=0.1, peak=0.2, right_boundary=0.3)\n \"\"\"\n return (\n f\"{self.name}: [{self.left_boundary}, {self.peak}, {self.right_boundary}]\"\n )\n\n def complement(self) -> FuzzySet:\n \"\"\"\n Calculate the complement (negation) of this fuzzy set.\n Returns:\n FuzzySet: A new fuzzy set representing the complement.\n\n >>> FuzzySet(\"fuzzy_set\", 0.1, 0.2, 0.3).complement()\n FuzzySet(name='\u00acfuzzy_set', left_boundary=0.7, peak=0.9, right_boundary=0.8)\n \"\"\"\n return FuzzySet(\n f\"\u00ac{self.name}\",\n 1 - self.right_boundary,\n 1 - self.left_boundary,\n 1 - self.peak,\n )\n\n def intersection(self, other) -> FuzzySet:\n \"\"\"\n Calculate the intersection of this fuzzy set\n with another fuzzy set.\n Args:\n other: Another fuzzy set to intersect with.\n Returns:\n A new fuzzy set representing the intersection.\n\n >>> FuzzySet(\"a\", 0.1, 0.2, 0.3).intersection(FuzzySet(\"b\", 0.4, 0.5, 0.6))\n FuzzySet(name='a \u2229 b', left_boundary=0.4, peak=0.3, right_boundary=0.35)\n \"\"\"\n return FuzzySet(\n f\"{self.name} \u2229 {other.name}\",\n max(self.left_boundary, other.left_boundary),\n min(self.right_boundary, other.right_boundary),\n (self.peak + other.peak) \/ 2,\n )\n\n def membership(self, x: float) -> float:\n \"\"\"\n Calculate the membership value of an input 'x' in the fuzzy set.\n Returns:\n The membership value of 'x' in the fuzzy set.\n\n >>> a = FuzzySet(\"a\", 0.1, 0.2, 0.3)\n >>> a.membership(0.09)\n 0.0\n >>> a.membership(0.1)\n 0.0\n >>> a.membership(0.11)\n 0.09999999999999995\n >>> a.membership(0.4)\n 0.0\n >>> FuzzySet(\"A\", 0, 0.5, 1).membership(0.1)\n 0.2\n >>> FuzzySet(\"B\", 0.2, 0.7, 1).membership(0.6)\n 0.8\n \"\"\"\n if x <= self.left_boundary or x >= self.right_boundary:\n return 0.0\n elif self.left_boundary < x <= self.peak:\n return (x - self.left_boundary) \/ (self.peak - self.left_boundary)\n elif self.peak < x < self.right_boundary:\n return (self.right_boundary - x) \/ (self.right_boundary - self.peak)\n msg = f\"Invalid value {x} for fuzzy set {self}\"\n raise ValueError(msg)\n\n def union(self, other) -> FuzzySet:\n \"\"\"\n Calculate the union of this fuzzy set with another fuzzy set.\n Args:\n other (FuzzySet): Another fuzzy set to union with.\n Returns:\n FuzzySet: A new fuzzy set representing the union.\n\n >>> FuzzySet(\"a\", 0.1, 0.2, 0.3).union(FuzzySet(\"b\", 0.4, 0.5, 0.6))\n FuzzySet(name='a \u222a b', left_boundary=0.1, peak=0.6, right_boundary=0.35)\n \"\"\"\n return FuzzySet(\n f\"{self.name} \u222a {other.name}\",\n min(self.left_boundary, other.left_boundary),\n max(self.right_boundary, other.right_boundary),\n (self.peak + other.peak) \/ 2,\n )\n\n def plot(self):\n \"\"\"\n Plot the membership function of the fuzzy set.\n \"\"\"\n x = np.linspace(0, 1, 1000)\n y = [self.membership(xi) for xi in x]\n\n plt.plot(x, y, label=self.name)\n\n\nif __name__ == \"__main__\":\n from doctest import testmod\n\n testmod()\n a = FuzzySet(\"A\", 0, 0.5, 1)\n b = FuzzySet(\"B\", 0.2, 0.7, 1)\n\n a.plot()\n b.plot()\n\n plt.xlabel(\"x\")\n plt.ylabel(\"Membership\")\n plt.legend()\n plt.show()\n\n union_ab = a.union(b)\n intersection_ab = a.intersection(b)\n complement_a = a.complement()\n\n union_ab.plot()\n intersection_ab.plot()\n complement_a.plot()\n\n plt.xlabel(\"x\")\n plt.ylabel(\"Membership\")\n plt.legend()\n plt.show()\n"} +{"Prompt":"Simple multithreaded algorithm to show how the 4 phases of a genetic algorithm works Evaluation, Selection, Crossover and Mutation https:en.wikipedia.orgwikiGeneticalgorithm Author: D4rkia Maximum size of the population. Bigger could be faster but is more memory expensive. Number of elements selected in every generation of evolution. The selection takes place from best to worst of that generation and must be smaller than NPOPULATION. Probability that an element of a generation can mutate, changing one of its genes. This will guarantee that all genes will be used during evolution. Just a seed to improve randomness required by the algorithm. Evaluate how similar the item is with the target by just counting each char in the right position evaluateHelxo Worlx, Hello World 'Helxo Worlx', 9.0 Slice and combine two string at a random point. randomslice random.randint0, lenparent1 1 child1 parent1:randomslice parent2randomslice: child2 parent2:randomslice parent1randomslice: return child1, child2 def mutatechild: str, genes: liststr str: Select, crossover and mutate a new population. Select the second parent and generate new population pop Generate more children proportionally to the fitness score. childn intparent11 100 1 childn 10 if childn 10 else childn for in rangechildn: parent2 populationscorerandom.randint0, NSELECTED0 child1, child2 crossoverparent10, parent2 Append new string to the population list. pop.appendmutatechild1, genes pop.appendmutatechild2, genes return pop def basictarget: str, genes: liststr, debug: bool True tupleint, int, str: Verify if NPOPULATION is bigger than NSELECTED if NPOPULATION NSELECTED: msg fNPOPULATION must be bigger than NSELECTED raise ValueErrormsg Verify that the target contains no genes besides the ones inside genes variable. notingeneslist sortedc for c in target if c not in genes if notingeneslist: msg fnotingeneslist is not in genes list, evolution cannot converge raise ValueErrormsg Generate random starting population. population for in rangeNPOPULATION: population.append.joinrandom.choicegenes for i in rangelentarget Just some logs to know what the algorithms is doing. generation, totalpopulation 0, 0 This loop will end when we find a perfect match for our target. while True: generation 1 totalpopulation lenpopulation Random population created. Now it's time to evaluate. Adding a bit of concurrency can make everything faster, import concurrent.futures populationscore: listtuplestr, float with concurrent.futures.ThreadPoolExecutor maxworkersNUMWORKERS as executor: futures executor.submitevaluate, item for item in population concurrent.futures.waitfutures populationscore item.result for item in futures but with a simple algorithm like this, it will probably be slower. We just need to call evaluate for every item inside the population. populationscore evaluateitem, target for item in population Check if there is a matching evolution. populationscore sortedpopulationscore, keylambda x: x1, reverseTrue if populationscore00 target: return generation, totalpopulation, populationscore00 Print the best result every 10 generation. Just to know that the algorithm is working. if debug and generation 10 0: print fnGeneration: generation fnTotal Population:totalpopulation fnBest score: populationscore01 fnBest string: populationscore00 Flush the old population, keeping some of the best evolutions. Keeping this avoid regression of evolution. populationbest population: intNPOPULATION 3 population.clear population.extendpopulationbest Normalize population score to be between 0 and 1. populationscore item, score lentarget for item, score in populationscore This is selection for i in rangeNSELECTED: population.extendselectpopulationscoreinti, populationscore, genes Check if the population has already reached the maximum value and if so, break the cycle. If this check is disabled, the algorithm will take forever to compute large strings, but will also calculate small strings in a far fewer generations. if lenpopulation NPOPULATION: break if name main: targetstr This is a genetic algorithm to evaluate, combine, evolve, and mutate a string! geneslist list ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklm nopqrstuvwxyz.,;!?' generation, population, target basictargetstr, geneslist print fnGeneration: generationnTotal Population: populationnTarget: target","Completions":"from __future__ import annotations\n\nimport random\n\n# Maximum size of the population. Bigger could be faster but is more memory expensive.\nN_POPULATION = 200\n# Number of elements selected in every generation of evolution. The selection takes\n# place from best to worst of that generation and must be smaller than N_POPULATION.\nN_SELECTED = 50\n# Probability that an element of a generation can mutate, changing one of its genes.\n# This will guarantee that all genes will be used during evolution.\nMUTATION_PROBABILITY = 0.4\n# Just a seed to improve randomness required by the algorithm.\nrandom.seed(random.randint(0, 1000))\n\n\ndef evaluate(item: str, main_target: str) -> tuple[str, float]:\n \"\"\"\n Evaluate how similar the item is with the target by just\n counting each char in the right position\n >>> evaluate(\"Helxo Worlx\", \"Hello World\")\n ('Helxo Worlx', 9.0)\n \"\"\"\n score = len([g for position, g in enumerate(item) if g == main_target[position]])\n return (item, float(score))\n\n\ndef crossover(parent_1: str, parent_2: str) -> tuple[str, str]:\n \"\"\"Slice and combine two string at a random point.\"\"\"\n random_slice = random.randint(0, len(parent_1) - 1)\n child_1 = parent_1[:random_slice] + parent_2[random_slice:]\n child_2 = parent_2[:random_slice] + parent_1[random_slice:]\n return (child_1, child_2)\n\n\ndef mutate(child: str, genes: list[str]) -> str:\n \"\"\"Mutate a random gene of a child with another one from the list.\"\"\"\n child_list = list(child)\n if random.uniform(0, 1) < MUTATION_PROBABILITY:\n child_list[random.randint(0, len(child)) - 1] = random.choice(genes)\n return \"\".join(child_list)\n\n\n# Select, crossover and mutate a new population.\ndef select(\n parent_1: tuple[str, float],\n population_score: list[tuple[str, float]],\n genes: list[str],\n) -> list[str]:\n \"\"\"Select the second parent and generate new population\"\"\"\n pop = []\n # Generate more children proportionally to the fitness score.\n child_n = int(parent_1[1] * 100) + 1\n child_n = 10 if child_n >= 10 else child_n\n for _ in range(child_n):\n parent_2 = population_score[random.randint(0, N_SELECTED)][0]\n\n child_1, child_2 = crossover(parent_1[0], parent_2)\n # Append new string to the population list.\n pop.append(mutate(child_1, genes))\n pop.append(mutate(child_2, genes))\n return pop\n\n\ndef basic(target: str, genes: list[str], debug: bool = True) -> tuple[int, int, str]:\n \"\"\"\n Verify that the target contains no genes besides the ones inside genes variable.\n\n >>> from string import ascii_lowercase\n >>> basic(\"doctest\", ascii_lowercase, debug=False)[2]\n 'doctest'\n >>> genes = list(ascii_lowercase)\n >>> genes.remove(\"e\")\n >>> basic(\"test\", genes)\n Traceback (most recent call last):\n ...\n ValueError: ['e'] is not in genes list, evolution cannot converge\n >>> genes.remove(\"s\")\n >>> basic(\"test\", genes)\n Traceback (most recent call last):\n ...\n ValueError: ['e', 's'] is not in genes list, evolution cannot converge\n >>> genes.remove(\"t\")\n >>> basic(\"test\", genes)\n Traceback (most recent call last):\n ...\n ValueError: ['e', 's', 't'] is not in genes list, evolution cannot converge\n \"\"\"\n\n # Verify if N_POPULATION is bigger than N_SELECTED\n if N_POPULATION < N_SELECTED:\n msg = f\"{N_POPULATION} must be bigger than {N_SELECTED}\"\n raise ValueError(msg)\n # Verify that the target contains no genes besides the ones inside genes variable.\n not_in_genes_list = sorted({c for c in target if c not in genes})\n if not_in_genes_list:\n msg = f\"{not_in_genes_list} is not in genes list, evolution cannot converge\"\n raise ValueError(msg)\n\n # Generate random starting population.\n population = []\n for _ in range(N_POPULATION):\n population.append(\"\".join([random.choice(genes) for i in range(len(target))]))\n\n # Just some logs to know what the algorithms is doing.\n generation, total_population = 0, 0\n\n # This loop will end when we find a perfect match for our target.\n while True:\n generation += 1\n total_population += len(population)\n\n # Random population created. Now it's time to evaluate.\n\n # Adding a bit of concurrency can make everything faster,\n #\n # import concurrent.futures\n # population_score: list[tuple[str, float]] = []\n # with concurrent.futures.ThreadPoolExecutor(\n # max_workers=NUM_WORKERS) as executor:\n # futures = {executor.submit(evaluate, item) for item in population}\n # concurrent.futures.wait(futures)\n # population_score = [item.result() for item in futures]\n #\n # but with a simple algorithm like this, it will probably be slower.\n # We just need to call evaluate for every item inside the population.\n population_score = [evaluate(item, target) for item in population]\n\n # Check if there is a matching evolution.\n population_score = sorted(population_score, key=lambda x: x[1], reverse=True)\n if population_score[0][0] == target:\n return (generation, total_population, population_score[0][0])\n\n # Print the best result every 10 generation.\n # Just to know that the algorithm is working.\n if debug and generation % 10 == 0:\n print(\n f\"\\nGeneration: {generation}\"\n f\"\\nTotal Population:{total_population}\"\n f\"\\nBest score: {population_score[0][1]}\"\n f\"\\nBest string: {population_score[0][0]}\"\n )\n\n # Flush the old population, keeping some of the best evolutions.\n # Keeping this avoid regression of evolution.\n population_best = population[: int(N_POPULATION \/ 3)]\n population.clear()\n population.extend(population_best)\n # Normalize population score to be between 0 and 1.\n population_score = [\n (item, score \/ len(target)) for item, score in population_score\n ]\n\n # This is selection\n for i in range(N_SELECTED):\n population.extend(select(population_score[int(i)], population_score, genes))\n # Check if the population has already reached the maximum value and if so,\n # break the cycle. If this check is disabled, the algorithm will take\n # forever to compute large strings, but will also calculate small strings in\n # a far fewer generations.\n if len(population) > N_POPULATION:\n break\n\n\nif __name__ == \"__main__\":\n target_str = (\n \"This is a genetic algorithm to evaluate, combine, evolve, and mutate a string!\"\n )\n genes_list = list(\n \" ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklm\"\n \"nopqrstuvwxyz.,;!?+-*#@^'\u00e8\u00e9\u00f2\u00e0\u20ac\u00f9=)(&%$\u00a3\/\\\\\"\n )\n generation, population, target = basic(target_str, genes_list)\n print(\n f\"\\nGeneration: {generation}\\nTotal Population: {population}\\nTarget: {target}\"\n )\n"} +{"Prompt":"Calculate great circle distance between two points in a sphere, given longitudes and latitudes https:en.wikipedia.orgwikiHaversineformula We know that the globe is sort of spherical, so a path between two points isn't exactly a straight line. We need to account for the Earth's curvature when calculating distance from point A to B. This effect is negligible for small distances but adds up as distance increases. The Haversine method treats the earth as a sphere which allows us to project the two points A and B onto the surface of that sphere and approximate the spherical distance between them. Since the Earth is not a perfect sphere, other methods which model the Earth's ellipsoidal nature are more accurate but a quick and modifiable computation like Haversine can be handy for shorter range distances. Args: lat1, lon1: latitude and longitude of coordinate 1 lat2, lon2: latitude and longitude of coordinate 2 Returns: geographical distance between two points in metres from collections import namedtuple point2d namedtuplepoint2d, lat lon SANFRANCISCO point2d37.774856, 122.424227 YOSEMITE point2d37.864742, 119.537521 fhaversinedistanceSANFRANCISCO, YOSEMITE:0,.0f meters '254,352 meters' CONSTANTS per WGS84 https:en.wikipedia.orgwikiWorldGeodeticSystem Distance in metresm Equation parameters Equation https:en.wikipedia.orgwikiHaversineformulaFormulation Equation Square both values","Completions":"from math import asin, atan, cos, radians, sin, sqrt, tan\n\nAXIS_A = 6378137.0\nAXIS_B = 6356752.314245\nRADIUS = 6378137\n\n\ndef haversine_distance(lat1: float, lon1: float, lat2: float, lon2: float) -> float:\n \"\"\"\n Calculate great circle distance between two points in a sphere,\n given longitudes and latitudes https:\/\/en.wikipedia.org\/wiki\/Haversine_formula\n\n We know that the globe is \"sort of\" spherical, so a path between two points\n isn't exactly a straight line. We need to account for the Earth's curvature\n when calculating distance from point A to B. This effect is negligible for\n small distances but adds up as distance increases. The Haversine method treats\n the earth as a sphere which allows us to \"project\" the two points A and B\n onto the surface of that sphere and approximate the spherical distance between\n them. Since the Earth is not a perfect sphere, other methods which model the\n Earth's ellipsoidal nature are more accurate but a quick and modifiable\n computation like Haversine can be handy for shorter range distances.\n\n Args:\n lat1, lon1: latitude and longitude of coordinate 1\n lat2, lon2: latitude and longitude of coordinate 2\n Returns:\n geographical distance between two points in metres\n >>> from collections import namedtuple\n >>> point_2d = namedtuple(\"point_2d\", \"lat lon\")\n >>> SAN_FRANCISCO = point_2d(37.774856, -122.424227)\n >>> YOSEMITE = point_2d(37.864742, -119.537521)\n >>> f\"{haversine_distance(*SAN_FRANCISCO, *YOSEMITE):0,.0f} meters\"\n '254,352 meters'\n \"\"\"\n # CONSTANTS per WGS84 https:\/\/en.wikipedia.org\/wiki\/World_Geodetic_System\n # Distance in metres(m)\n # Equation parameters\n # Equation https:\/\/en.wikipedia.org\/wiki\/Haversine_formula#Formulation\n flattening = (AXIS_A - AXIS_B) \/ AXIS_A\n phi_1 = atan((1 - flattening) * tan(radians(lat1)))\n phi_2 = atan((1 - flattening) * tan(radians(lat2)))\n lambda_1 = radians(lon1)\n lambda_2 = radians(lon2)\n # Equation\n sin_sq_phi = sin((phi_2 - phi_1) \/ 2)\n sin_sq_lambda = sin((lambda_2 - lambda_1) \/ 2)\n # Square both values\n sin_sq_phi *= sin_sq_phi\n sin_sq_lambda *= sin_sq_lambda\n h_value = sqrt(sin_sq_phi + (cos(phi_1) * cos(phi_2) * sin_sq_lambda))\n return 2 * RADIUS * asin(h_value)\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Calculate the shortest distance along the surface of an ellipsoid between two points on the surface of earth given longitudes and latitudes https:en.wikipedia.orgwikiGeographicaldistanceLambert'sformulaforlonglines NOTE: This algorithm uses geodesyhaversinedistance.py to compute central angle, sigma Representing the earth as an ellipsoid allows us to approximate distances between points on the surface much better than a sphere. Ellipsoidal formulas treat the Earth as an oblate ellipsoid which means accounting for the flattening that happens at the North and South poles. Lambert's formulae provide accuracy on the order of 10 meteres over thousands of kilometeres. Other methods can provide millimeterlevel accuracy but this is a simpler method to calculate long range distances without increasing computational intensity. Args: lat1, lon1: latitude and longitude of coordinate 1 lat2, lon2: latitude and longitude of coordinate 2 Returns: geographical distance between two points in metres from collections import namedtuple point2d namedtuplepoint2d, lat lon SANFRANCISCO point2d37.774856, 122.424227 YOSEMITE point2d37.864742, 119.537521 NEWYORK point2d40.713019, 74.012647 VENICE point2d45.443012, 12.313071 flambertsellipsoidaldistanceSANFRANCISCO, YOSEMITE:0,.0f meters '254,351 meters' flambertsellipsoidaldistanceSANFRANCISCO, NEWYORK:0,.0f meters '4,138,992 meters' flambertsellipsoidaldistanceSANFRANCISCO, VENICE:0,.0f meters '9,737,326 meters' CONSTANTS per WGS84 https:en.wikipedia.orgwikiWorldGeodeticSystem Distance in metresm Equation Parameters https:en.wikipedia.orgwikiGeographicaldistanceLambert'sformulaforlonglines Parametric latitudes https:en.wikipedia.orgwikiLatitudeParametricorreducedlatitude Compute central angle between two points using haversine theta. sigma haversinedistance equatorial radius Intermediate P and Q values Intermediate X value X sigma sinsigma sin2Pcos2Q cos2sigma2 Intermediate Y value Y sigma sinsigma cos2Psin2Q sin2sigma2","Completions":"from math import atan, cos, radians, sin, tan\n\nfrom .haversine_distance import haversine_distance\n\nAXIS_A = 6378137.0\nAXIS_B = 6356752.314245\nEQUATORIAL_RADIUS = 6378137\n\n\ndef lamberts_ellipsoidal_distance(\n lat1: float, lon1: float, lat2: float, lon2: float\n) -> float:\n \"\"\"\n Calculate the shortest distance along the surface of an ellipsoid between\n two points on the surface of earth given longitudes and latitudes\n https:\/\/en.wikipedia.org\/wiki\/Geographical_distance#Lambert's_formula_for_long_lines\n\n NOTE: This algorithm uses geodesy\/haversine_distance.py to compute central angle,\n sigma\n\n Representing the earth as an ellipsoid allows us to approximate distances between\n points on the surface much better than a sphere. Ellipsoidal formulas treat the\n Earth as an oblate ellipsoid which means accounting for the flattening that happens\n at the North and South poles. Lambert's formulae provide accuracy on the order of\n 10 meteres over thousands of kilometeres. Other methods can provide\n millimeter-level accuracy but this is a simpler method to calculate long range\n distances without increasing computational intensity.\n\n Args:\n lat1, lon1: latitude and longitude of coordinate 1\n lat2, lon2: latitude and longitude of coordinate 2\n Returns:\n geographical distance between two points in metres\n\n >>> from collections import namedtuple\n >>> point_2d = namedtuple(\"point_2d\", \"lat lon\")\n >>> SAN_FRANCISCO = point_2d(37.774856, -122.424227)\n >>> YOSEMITE = point_2d(37.864742, -119.537521)\n >>> NEW_YORK = point_2d(40.713019, -74.012647)\n >>> VENICE = point_2d(45.443012, 12.313071)\n >>> f\"{lamberts_ellipsoidal_distance(*SAN_FRANCISCO, *YOSEMITE):0,.0f} meters\"\n '254,351 meters'\n >>> f\"{lamberts_ellipsoidal_distance(*SAN_FRANCISCO, *NEW_YORK):0,.0f} meters\"\n '4,138,992 meters'\n >>> f\"{lamberts_ellipsoidal_distance(*SAN_FRANCISCO, *VENICE):0,.0f} meters\"\n '9,737,326 meters'\n \"\"\"\n\n # CONSTANTS per WGS84 https:\/\/en.wikipedia.org\/wiki\/World_Geodetic_System\n # Distance in metres(m)\n # Equation Parameters\n # https:\/\/en.wikipedia.org\/wiki\/Geographical_distance#Lambert's_formula_for_long_lines\n flattening = (AXIS_A - AXIS_B) \/ AXIS_A\n # Parametric latitudes\n # https:\/\/en.wikipedia.org\/wiki\/Latitude#Parametric_(or_reduced)_latitude\n b_lat1 = atan((1 - flattening) * tan(radians(lat1)))\n b_lat2 = atan((1 - flattening) * tan(radians(lat2)))\n\n # Compute central angle between two points\n # using haversine theta. sigma = haversine_distance \/ equatorial radius\n sigma = haversine_distance(lat1, lon1, lat2, lon2) \/ EQUATORIAL_RADIUS\n\n # Intermediate P and Q values\n p_value = (b_lat1 + b_lat2) \/ 2\n q_value = (b_lat2 - b_lat1) \/ 2\n\n # Intermediate X value\n # X = (sigma - sin(sigma)) * sin^2Pcos^2Q \/ cos^2(sigma\/2)\n x_numerator = (sin(p_value) ** 2) * (cos(q_value) ** 2)\n x_demonimator = cos(sigma \/ 2) ** 2\n x_value = (sigma - sin(sigma)) * (x_numerator \/ x_demonimator)\n\n # Intermediate Y value\n # Y = (sigma + sin(sigma)) * cos^2Psin^2Q \/ sin^2(sigma\/2)\n y_numerator = (cos(p_value) ** 2) * (sin(q_value) ** 2)\n y_denominator = sin(sigma \/ 2) ** 2\n y_value = (sigma + sin(sigma)) * (y_numerator \/ y_denominator)\n\n return EQUATORIAL_RADIUS * (sigma - ((flattening \/ 2) * (x_value + y_value)))\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Building block classes An Angle in degrees unit of measurement Angle Angledegrees90 Angle45.5 Angledegrees45.5 Angle1 Traceback most recent call last: ... TypeError: degrees must be a numeric value between 0 and 360. Angle361 Traceback most recent call last: ... TypeError: degrees must be a numeric value between 0 and 360. A side of a two dimensional Shape such as Polygon, etc. adjacentsides: a list of sides which are adjacent to the current side angle: the angle in degrees between each adjacent side length: the length of the current side in meters Side5 Sidelength5, angleAngledegrees90, nextsideNone Side5, Angle45.6 Sidelength5, angleAngledegrees45.6, nextsideNone Side5, Angle45.6, Side1, Angle2 doctest: ELLIPSIS Sidelength5, angleAngledegrees45.6, nextsideSidelength1, angleAngled... A geometric Ellipse on a 2D surface Ellipse5, 10 Ellipsemajorradius5, minorradius10 Ellipse5, 10 is Ellipse5, 10 False Ellipse5, 10 Ellipse5, 10 True Ellipse5, 10.area 157.07963267948966 Ellipse5, 10.perimeter 47.12388980384689 A geometric Circle on a 2D surface Circle5 Circleradius5 Circle5 is Circle5 False Circle5 Circle5 True Circle5.area 78.53981633974483 Circle5.perimeter 31.41592653589793 Circle5.diameter 10 Return the maximum number of parts that circle can be divided into if cut 'numcuts' times. circle Circle5 circle.maxparts0 1.0 circle.maxparts7 29.0 circle.maxparts54 1486.0 circle.maxparts22.5 265.375 circle.maxparts222 Traceback most recent call last: ... TypeError: numcuts must be a positive numeric value. circle.maxparts222 Traceback most recent call last: ... TypeError: numcuts must be a positive numeric value. An abstract class which represents Polygon on a 2D surface. Polygon Polygonsides Polygon.addsideSide5 PolygonsidesSidelength5, angleAngledegrees90, nextsideNone Polygon.getside0 Traceback most recent call last: ... IndexError: list index out of range Polygon.addsideSide5.getside1 Sidelength5, angleAngledegrees90, nextsideNone Polygon.setside0, Side5 Traceback most recent call last: ... IndexError: list assignment index out of range Polygon.addsideSide5.setside0, Side10 PolygonsidesSidelength10, angleAngledegrees90, nextsideNone A geometric rectangle on a 2D surface. rectangleone Rectangle5, 10 rectangleone.perimeter 30 rectangleone.area 50 Rectangle5, 10 doctest: NORMALIZEWHITESPACE RectanglesidesSidelength5, angleAngledegrees90, nextsideNone, Sidelength10, angleAngledegrees90, nextsideNone a structure which represents a geometrical square on a 2D surface squareone Square5 squareone.perimeter 20 squareone.area 25","Completions":"from __future__ import annotations\n\nimport math\nfrom dataclasses import dataclass, field\nfrom types import NoneType\nfrom typing import Self\n\n# Building block classes\n\n\n@dataclass\nclass Angle:\n \"\"\"\n An Angle in degrees (unit of measurement)\n\n >>> Angle()\n Angle(degrees=90)\n >>> Angle(45.5)\n Angle(degrees=45.5)\n >>> Angle(-1)\n Traceback (most recent call last):\n ...\n TypeError: degrees must be a numeric value between 0 and 360.\n >>> Angle(361)\n Traceback (most recent call last):\n ...\n TypeError: degrees must be a numeric value between 0 and 360.\n \"\"\"\n\n degrees: float = 90\n\n def __post_init__(self) -> None:\n if not isinstance(self.degrees, (int, float)) or not 0 <= self.degrees <= 360:\n raise TypeError(\"degrees must be a numeric value between 0 and 360.\")\n\n\n@dataclass\nclass Side:\n \"\"\"\n A side of a two dimensional Shape such as Polygon, etc.\n adjacent_sides: a list of sides which are adjacent to the current side\n angle: the angle in degrees between each adjacent side\n length: the length of the current side in meters\n\n >>> Side(5)\n Side(length=5, angle=Angle(degrees=90), next_side=None)\n >>> Side(5, Angle(45.6))\n Side(length=5, angle=Angle(degrees=45.6), next_side=None)\n >>> Side(5, Angle(45.6), Side(1, Angle(2))) # doctest: +ELLIPSIS\n Side(length=5, angle=Angle(degrees=45.6), next_side=Side(length=1, angle=Angle(d...\n \"\"\"\n\n length: float\n angle: Angle = field(default_factory=Angle)\n next_side: Side | None = None\n\n def __post_init__(self) -> None:\n if not isinstance(self.length, (int, float)) or self.length <= 0:\n raise TypeError(\"length must be a positive numeric value.\")\n if not isinstance(self.angle, Angle):\n raise TypeError(\"angle must be an Angle object.\")\n if not isinstance(self.next_side, (Side, NoneType)):\n raise TypeError(\"next_side must be a Side or None.\")\n\n\n@dataclass\nclass Ellipse:\n \"\"\"\n A geometric Ellipse on a 2D surface\n\n >>> Ellipse(5, 10)\n Ellipse(major_radius=5, minor_radius=10)\n >>> Ellipse(5, 10) is Ellipse(5, 10)\n False\n >>> Ellipse(5, 10) == Ellipse(5, 10)\n True\n \"\"\"\n\n major_radius: float\n minor_radius: float\n\n @property\n def area(self) -> float:\n \"\"\"\n >>> Ellipse(5, 10).area\n 157.07963267948966\n \"\"\"\n return math.pi * self.major_radius * self.minor_radius\n\n @property\n def perimeter(self) -> float:\n \"\"\"\n >>> Ellipse(5, 10).perimeter\n 47.12388980384689\n \"\"\"\n return math.pi * (self.major_radius + self.minor_radius)\n\n\nclass Circle(Ellipse):\n \"\"\"\n A geometric Circle on a 2D surface\n\n >>> Circle(5)\n Circle(radius=5)\n >>> Circle(5) is Circle(5)\n False\n >>> Circle(5) == Circle(5)\n True\n >>> Circle(5).area\n 78.53981633974483\n >>> Circle(5).perimeter\n 31.41592653589793\n \"\"\"\n\n def __init__(self, radius: float) -> None:\n super().__init__(radius, radius)\n self.radius = radius\n\n def __repr__(self) -> str:\n return f\"Circle(radius={self.radius})\"\n\n @property\n def diameter(self) -> float:\n \"\"\"\n >>> Circle(5).diameter\n 10\n \"\"\"\n return self.radius * 2\n\n def max_parts(self, num_cuts: float) -> float:\n \"\"\"\n Return the maximum number of parts that circle can be divided into if cut\n 'num_cuts' times.\n\n >>> circle = Circle(5)\n >>> circle.max_parts(0)\n 1.0\n >>> circle.max_parts(7)\n 29.0\n >>> circle.max_parts(54)\n 1486.0\n >>> circle.max_parts(22.5)\n 265.375\n >>> circle.max_parts(-222)\n Traceback (most recent call last):\n ...\n TypeError: num_cuts must be a positive numeric value.\n >>> circle.max_parts(\"-222\")\n Traceback (most recent call last):\n ...\n TypeError: num_cuts must be a positive numeric value.\n \"\"\"\n if not isinstance(num_cuts, (int, float)) or num_cuts < 0:\n raise TypeError(\"num_cuts must be a positive numeric value.\")\n return (num_cuts + 2 + num_cuts**2) * 0.5\n\n\n@dataclass\nclass Polygon:\n \"\"\"\n An abstract class which represents Polygon on a 2D surface.\n\n >>> Polygon()\n Polygon(sides=[])\n \"\"\"\n\n sides: list[Side] = field(default_factory=list)\n\n def add_side(self, side: Side) -> Self:\n \"\"\"\n >>> Polygon().add_side(Side(5))\n Polygon(sides=[Side(length=5, angle=Angle(degrees=90), next_side=None)])\n \"\"\"\n self.sides.append(side)\n return self\n\n def get_side(self, index: int) -> Side:\n \"\"\"\n >>> Polygon().get_side(0)\n Traceback (most recent call last):\n ...\n IndexError: list index out of range\n >>> Polygon().add_side(Side(5)).get_side(-1)\n Side(length=5, angle=Angle(degrees=90), next_side=None)\n \"\"\"\n return self.sides[index]\n\n def set_side(self, index: int, side: Side) -> Self:\n \"\"\"\n >>> Polygon().set_side(0, Side(5))\n Traceback (most recent call last):\n ...\n IndexError: list assignment index out of range\n >>> Polygon().add_side(Side(5)).set_side(0, Side(10))\n Polygon(sides=[Side(length=10, angle=Angle(degrees=90), next_side=None)])\n \"\"\"\n self.sides[index] = side\n return self\n\n\nclass Rectangle(Polygon):\n \"\"\"\n A geometric rectangle on a 2D surface.\n\n >>> rectangle_one = Rectangle(5, 10)\n >>> rectangle_one.perimeter()\n 30\n >>> rectangle_one.area()\n 50\n \"\"\"\n\n def __init__(self, short_side_length: float, long_side_length: float) -> None:\n super().__init__()\n self.short_side_length = short_side_length\n self.long_side_length = long_side_length\n self.post_init()\n\n def post_init(self) -> None:\n \"\"\"\n >>> Rectangle(5, 10) # doctest: +NORMALIZE_WHITESPACE\n Rectangle(sides=[Side(length=5, angle=Angle(degrees=90), next_side=None),\n Side(length=10, angle=Angle(degrees=90), next_side=None)])\n \"\"\"\n self.short_side = Side(self.short_side_length)\n self.long_side = Side(self.long_side_length)\n super().add_side(self.short_side)\n super().add_side(self.long_side)\n\n def perimeter(self) -> float:\n return (self.short_side.length + self.long_side.length) * 2\n\n def area(self) -> float:\n return self.short_side.length * self.long_side.length\n\n\n@dataclass\nclass Square(Rectangle):\n \"\"\"\n a structure which represents a\n geometrical square on a 2D surface\n >>> square_one = Square(5)\n >>> square_one.perimeter()\n 20\n >>> square_one.area()\n 25\n \"\"\"\n\n def __init__(self, side_length: float) -> None:\n super().__init__(side_length, side_length)\n\n def perimeter(self) -> float:\n return super().perimeter()\n\n def area(self) -> float:\n return super().area()\n\n\nif __name__ == \"__main__\":\n __import__(\"doctest\").testmod()\n"} +{"Prompt":"https:en.wikipedia.orgwikiBC3A9ziercurve https:www.tutorialspoint.comcomputergraphicscomputergraphicscurves.htm Bezier curve is a weighted sum of a set of control points. Generate Bezier curves from a given set of control points. This implementation works only for 2d coordinates in the xy plane. listofpoints: Control points in the xy plane on which to interpolate. These points control the behavior shape of the Bezier curve. Degree determines the flexibility of the curve. Degree 1 will produce a straight line. The basis function determines the weight of each control point at time t. t: time value between 0 and 1 inclusive at which to evaluate the basis of the curve. returns the x, y values of basis function at time t curve BezierCurve1,1, 1,2 curve.basisfunction0 1.0, 0.0 curve.basisfunction1 0.0, 1.0 basis function for each i the basis must sum up to 1 for it to produce a valid Bezier curve. The function to produce the values of the Bezier curve at time t. t: the value of time t at which to evaluate the Bezier function Returns the x, y coordinates of the Bezier curve at time t. The first point in the curve is when t 0. The last point in the curve is when t 1. curve BezierCurve1,1, 1,2 curve.beziercurvefunction0 1.0, 1.0 curve.beziercurvefunction1 1.0, 2.0 For all points, sum up the product of ith basis function and ith point. Plots the Bezier curve using matplotlib plotting capabilities. stepsize: defines the steps at which to evaluate the Bezier curve. The smaller the step size, the finer the curve produced.","Completions":"# https:\/\/en.wikipedia.org\/wiki\/B%C3%A9zier_curve\n# https:\/\/www.tutorialspoint.com\/computer_graphics\/computer_graphics_curves.htm\nfrom __future__ import annotations\n\nfrom scipy.special import comb # type: ignore\n\n\nclass BezierCurve:\n \"\"\"\n Bezier curve is a weighted sum of a set of control points.\n Generate Bezier curves from a given set of control points.\n This implementation works only for 2d coordinates in the xy plane.\n \"\"\"\n\n def __init__(self, list_of_points: list[tuple[float, float]]):\n \"\"\"\n list_of_points: Control points in the xy plane on which to interpolate. These\n points control the behavior (shape) of the Bezier curve.\n \"\"\"\n self.list_of_points = list_of_points\n # Degree determines the flexibility of the curve.\n # Degree = 1 will produce a straight line.\n self.degree = len(list_of_points) - 1\n\n def basis_function(self, t: float) -> list[float]:\n \"\"\"\n The basis function determines the weight of each control point at time t.\n t: time value between 0 and 1 inclusive at which to evaluate the basis of\n the curve.\n returns the x, y values of basis function at time t\n\n >>> curve = BezierCurve([(1,1), (1,2)])\n >>> curve.basis_function(0)\n [1.0, 0.0]\n >>> curve.basis_function(1)\n [0.0, 1.0]\n \"\"\"\n assert 0 <= t <= 1, \"Time t must be between 0 and 1.\"\n output_values: list[float] = []\n for i in range(len(self.list_of_points)):\n # basis function for each i\n output_values.append(\n comb(self.degree, i) * ((1 - t) ** (self.degree - i)) * (t**i)\n )\n # the basis must sum up to 1 for it to produce a valid Bezier curve.\n assert round(sum(output_values), 5) == 1\n return output_values\n\n def bezier_curve_function(self, t: float) -> tuple[float, float]:\n \"\"\"\n The function to produce the values of the Bezier curve at time t.\n t: the value of time t at which to evaluate the Bezier function\n Returns the x, y coordinates of the Bezier curve at time t.\n The first point in the curve is when t = 0.\n The last point in the curve is when t = 1.\n\n >>> curve = BezierCurve([(1,1), (1,2)])\n >>> curve.bezier_curve_function(0)\n (1.0, 1.0)\n >>> curve.bezier_curve_function(1)\n (1.0, 2.0)\n \"\"\"\n\n assert 0 <= t <= 1, \"Time t must be between 0 and 1.\"\n\n basis_function = self.basis_function(t)\n x = 0.0\n y = 0.0\n for i in range(len(self.list_of_points)):\n # For all points, sum up the product of i-th basis function and i-th point.\n x += basis_function[i] * self.list_of_points[i][0]\n y += basis_function[i] * self.list_of_points[i][1]\n return (x, y)\n\n def plot_curve(self, step_size: float = 0.01):\n \"\"\"\n Plots the Bezier curve using matplotlib plotting capabilities.\n step_size: defines the step(s) at which to evaluate the Bezier curve.\n The smaller the step size, the finer the curve produced.\n \"\"\"\n from matplotlib import pyplot as plt # type: ignore\n\n to_plot_x: list[float] = [] # x coordinates of points to plot\n to_plot_y: list[float] = [] # y coordinates of points to plot\n\n t = 0.0\n while t <= 1:\n value = self.bezier_curve_function(t)\n to_plot_x.append(value[0])\n to_plot_y.append(value[1])\n t += step_size\n\n x = [i[0] for i in self.list_of_points]\n y = [i[1] for i in self.list_of_points]\n\n plt.plot(\n to_plot_x,\n to_plot_y,\n color=\"blue\",\n label=\"Curve of Degree \" + str(self.degree),\n )\n plt.scatter(x, y, color=\"red\", label=\"Control Points\")\n plt.legend()\n plt.show()\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n\n BezierCurve([(1, 2), (3, 5)]).plot_curve() # degree 1\n BezierCurve([(0, 0), (5, 5), (5, 0)]).plot_curve() # degree 2\n BezierCurve([(0, 0), (5, 5), (5, 0), (2.5, -2.5)]).plot_curve() # degree 3\n"} +{"Prompt":"render 3d points for 2d surfaces. Converts 3d point to a 2d drawable point convertto2d1.0, 2.0, 3.0, 10.0, 10.0 7.6923076923076925, 15.384615384615385 convertto2d1, 2, 3, 10, 10 7.6923076923076925, 15.384615384615385 convertto2d1, 2, 3, 10, 10 '1' is str Traceback most recent call last: ... TypeError: Input values must either be float or int: '1', 2, 3, 10, 10 rotate a point around a certain axis with a certain angle angle can be any integer between 1, 360 and axis can be any one of 'x', 'y', 'z' rotate1.0, 2.0, 3.0, 'y', 90.0 3.130524675073759, 2.0, 0.4470070007889556 rotate1, 2, 3, z, 180 0.999736015495891, 2.0001319704760485, 3 rotate'1', 2, 3, z, 90.0 '1' is str Traceback most recent call last: ... TypeError: Input values except axis must either be float or int: '1', 2, 3, 90.0 rotate1, 2, 3, n, 90 'n' is not a valid axis Traceback most recent call last: ... ValueError: not a valid axis, choose one of 'x', 'y', 'z' rotate1, 2, 3, x, 90 1, 2.5049096187183877, 2.5933429780983657 rotate1, 2, 3, x, 450 450 wrap around to 90 1, 3.5776792428178217, 0.44744970165427644","Completions":"from __future__ import annotations\n\nimport math\n\n__version__ = \"2020.9.26\"\n__author__ = \"xcodz-dot, cclaus, dhruvmanila\"\n\n\ndef convert_to_2d(\n x: float, y: float, z: float, scale: float, distance: float\n) -> tuple[float, float]:\n \"\"\"\n Converts 3d point to a 2d drawable point\n\n >>> convert_to_2d(1.0, 2.0, 3.0, 10.0, 10.0)\n (7.6923076923076925, 15.384615384615385)\n\n >>> convert_to_2d(1, 2, 3, 10, 10)\n (7.6923076923076925, 15.384615384615385)\n\n >>> convert_to_2d(\"1\", 2, 3, 10, 10) # '1' is str\n Traceback (most recent call last):\n ...\n TypeError: Input values must either be float or int: ['1', 2, 3, 10, 10]\n \"\"\"\n if not all(isinstance(val, (float, int)) for val in locals().values()):\n msg = f\"Input values must either be float or int: {list(locals().values())}\"\n raise TypeError(msg)\n projected_x = ((x * distance) \/ (z + distance)) * scale\n projected_y = ((y * distance) \/ (z + distance)) * scale\n return projected_x, projected_y\n\n\ndef rotate(\n x: float, y: float, z: float, axis: str, angle: float\n) -> tuple[float, float, float]:\n \"\"\"\n rotate a point around a certain axis with a certain angle\n angle can be any integer between 1, 360 and axis can be any one of\n 'x', 'y', 'z'\n\n >>> rotate(1.0, 2.0, 3.0, 'y', 90.0)\n (3.130524675073759, 2.0, 0.4470070007889556)\n\n >>> rotate(1, 2, 3, \"z\", 180)\n (0.999736015495891, -2.0001319704760485, 3)\n\n >>> rotate('1', 2, 3, \"z\", 90.0) # '1' is str\n Traceback (most recent call last):\n ...\n TypeError: Input values except axis must either be float or int: ['1', 2, 3, 90.0]\n\n >>> rotate(1, 2, 3, \"n\", 90) # 'n' is not a valid axis\n Traceback (most recent call last):\n ...\n ValueError: not a valid axis, choose one of 'x', 'y', 'z'\n\n >>> rotate(1, 2, 3, \"x\", -90)\n (1, -2.5049096187183877, -2.5933429780983657)\n\n >>> rotate(1, 2, 3, \"x\", 450) # 450 wrap around to 90\n (1, 3.5776792428178217, -0.44744970165427644)\n \"\"\"\n if not isinstance(axis, str):\n raise TypeError(\"Axis must be a str\")\n input_variables = locals()\n del input_variables[\"axis\"]\n if not all(isinstance(val, (float, int)) for val in input_variables.values()):\n msg = (\n \"Input values except axis must either be float or int: \"\n f\"{list(input_variables.values())}\"\n )\n raise TypeError(msg)\n angle = (angle % 360) \/ 450 * 180 \/ math.pi\n if axis == \"z\":\n new_x = x * math.cos(angle) - y * math.sin(angle)\n new_y = y * math.cos(angle) + x * math.sin(angle)\n new_z = z\n elif axis == \"x\":\n new_y = y * math.cos(angle) - z * math.sin(angle)\n new_z = z * math.cos(angle) + y * math.sin(angle)\n new_x = x\n elif axis == \"y\":\n new_x = x * math.cos(angle) - z * math.sin(angle)\n new_z = z * math.cos(angle) + x * math.sin(angle)\n new_y = y\n else:\n raise ValueError(\"not a valid axis, choose one of 'x', 'y', 'z'\")\n\n return new_x, new_y, new_z\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n print(f\"{convert_to_2d(1.0, 2.0, 3.0, 10.0, 10.0) = }\")\n print(f\"{rotate(1.0, 2.0, 3.0, 'y', 90.0) = }\")\n"} +{"Prompt":"function to search the path Search for a path on a grid avoiding obstacles. grid 0, 1, 0, 0, 0, 0, ... 0, 1, 0, 0, 0, 0, ... 0, 1, 0, 0, 0, 0, ... 0, 1, 0, 0, 1, 0, ... 0, 0, 0, 0, 1, 0 init 0, 0 goal lengrid 1, lengrid0 1 cost 1 heuristic 0 lengrid0 for in rangelengrid heuristic 0 for row in rangelengrid0 for col in rangelengrid for i in rangelengrid: ... for j in rangelengrid0: ... heuristicij absi goal0 absj goal1 ... if gridij 1: ... heuristicij 99 path, action searchgrid, init, goal, cost, heuristic path doctest: NORMALIZEWHITESPACE 0, 0, 1, 0, 2, 0, 3, 0, 4, 0, 4, 1, 4, 2, 4, 3, 3, 3, 2, 3, 2, 4, 2, 5, 3, 5, 4, 5 action doctest: NORMALIZEWHITESPACE 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 2, 0, 0, 0, 3, 3, 2, 0, 0, 0, 0, 2, 2, 3, 3, 3, 0, 2 all coordinates are given in format y,x the cost map which pushes the path closer to the goal added extra penalty in the heuristic map","Completions":"from __future__ import annotations\n\nDIRECTIONS = [\n [-1, 0], # left\n [0, -1], # down\n [1, 0], # right\n [0, 1], # up\n]\n\n\n# function to search the path\ndef search(\n grid: list[list[int]],\n init: list[int],\n goal: list[int],\n cost: int,\n heuristic: list[list[int]],\n) -> tuple[list[list[int]], list[list[int]]]:\n \"\"\"\n Search for a path on a grid avoiding obstacles.\n >>> grid = [[0, 1, 0, 0, 0, 0],\n ... [0, 1, 0, 0, 0, 0],\n ... [0, 1, 0, 0, 0, 0],\n ... [0, 1, 0, 0, 1, 0],\n ... [0, 0, 0, 0, 1, 0]]\n >>> init = [0, 0]\n >>> goal = [len(grid) - 1, len(grid[0]) - 1]\n >>> cost = 1\n >>> heuristic = [[0] * len(grid[0]) for _ in range(len(grid))]\n >>> heuristic = [[0 for row in range(len(grid[0]))] for col in range(len(grid))]\n >>> for i in range(len(grid)):\n ... for j in range(len(grid[0])):\n ... heuristic[i][j] = abs(i - goal[0]) + abs(j - goal[1])\n ... if grid[i][j] == 1:\n ... heuristic[i][j] = 99\n >>> path, action = search(grid, init, goal, cost, heuristic)\n >>> path # doctest: +NORMALIZE_WHITESPACE\n [[0, 0], [1, 0], [2, 0], [3, 0], [4, 0], [4, 1], [4, 2], [4, 3], [3, 3],\n [2, 3], [2, 4], [2, 5], [3, 5], [4, 5]]\n >>> action # doctest: +NORMALIZE_WHITESPACE\n [[0, 0, 0, 0, 0, 0], [2, 0, 0, 0, 0, 0], [2, 0, 0, 0, 3, 3],\n [2, 0, 0, 0, 0, 2], [2, 3, 3, 3, 0, 2]]\n \"\"\"\n closed = [\n [0 for col in range(len(grid[0]))] for row in range(len(grid))\n ] # the reference grid\n closed[init[0]][init[1]] = 1\n action = [\n [0 for col in range(len(grid[0]))] for row in range(len(grid))\n ] # the action grid\n\n x = init[0]\n y = init[1]\n g = 0\n f = g + heuristic[x][y] # cost from starting cell to destination cell\n cell = [[f, g, x, y]]\n\n found = False # flag that is set when search is complete\n resign = False # flag set if we can't find expand\n\n while not found and not resign:\n if len(cell) == 0:\n raise ValueError(\"Algorithm is unable to find solution\")\n else: # to choose the least costliest action so as to move closer to the goal\n cell.sort()\n cell.reverse()\n next_cell = cell.pop()\n x = next_cell[2]\n y = next_cell[3]\n g = next_cell[1]\n\n if x == goal[0] and y == goal[1]:\n found = True\n else:\n for i in range(len(DIRECTIONS)): # to try out different valid actions\n x2 = x + DIRECTIONS[i][0]\n y2 = y + DIRECTIONS[i][1]\n if x2 >= 0 and x2 < len(grid) and y2 >= 0 and y2 < len(grid[0]):\n if closed[x2][y2] == 0 and grid[x2][y2] == 0:\n g2 = g + cost\n f2 = g2 + heuristic[x2][y2]\n cell.append([f2, g2, x2, y2])\n closed[x2][y2] = 1\n action[x2][y2] = i\n invpath = []\n x = goal[0]\n y = goal[1]\n invpath.append([x, y]) # we get the reverse path from here\n while x != init[0] or y != init[1]:\n x2 = x - DIRECTIONS[action[x][y]][0]\n y2 = y - DIRECTIONS[action[x][y]][1]\n x = x2\n y = y2\n invpath.append([x, y])\n\n path = []\n for i in range(len(invpath)):\n path.append(invpath[len(invpath) - 1 - i])\n return path, action\n\n\nif __name__ == \"__main__\":\n grid = [\n [0, 1, 0, 0, 0, 0],\n [0, 1, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles\n [0, 1, 0, 0, 0, 0],\n [0, 1, 0, 0, 1, 0],\n [0, 0, 0, 0, 1, 0],\n ]\n\n init = [0, 0]\n # all coordinates are given in format [y,x]\n goal = [len(grid) - 1, len(grid[0]) - 1]\n cost = 1\n\n # the cost map which pushes the path closer to the goal\n heuristic = [[0 for row in range(len(grid[0]))] for col in range(len(grid))]\n for i in range(len(grid)):\n for j in range(len(grid[0])):\n heuristic[i][j] = abs(i - goal[0]) + abs(j - goal[1])\n if grid[i][j] == 1:\n # added extra penalty in the heuristic map\n heuristic[i][j] = 99\n\n path, action = search(grid, init, goal, cost, heuristic)\n\n print(\"ACTION MAP\")\n for i in range(len(action)):\n print(action[i])\n\n for i in range(len(path)):\n print(path[i])\n"} +{"Prompt":"Use an ant colony optimization algorithm to solve the travelling salesman problem TSP which asks the following question: Given a list of cities and the distances between each pair of cities, what is the shortest possible route that visits each city exactly once and returns to the origin city? https:en.wikipedia.orgwikiAntcolonyoptimizationalgorithms https:en.wikipedia.orgwikiTravellingsalesmanproblem Author: Clark Ant colony algorithm main function maincitiescities, antsnum10, iterationsnum20, ... pheromoneevaporation0.7, alpha1.0, beta5.0, q10 0, 1, 2, 3, 4, 5, 6, 7, 0, 37.909778143828696 maincities0: 0, 0, 1: 2, 2, antsnum5, iterationsnum5, ... pheromoneevaporation0.7, alpha1.0, beta5.0, q10 0, 1, 0, 5.656854249492381 maincities0: 0, 0, 1: 2, 2, 4: 4, 4, antsnum5, iterationsnum5, ... pheromoneevaporation0.7, alpha1.0, beta5.0, q10 Traceback most recent call last: ... IndexError: list index out of range maincities, antsnum5, iterationsnum5, ... pheromoneevaporation0.7, alpha1.0, beta5.0, q10 Traceback most recent call last: ... StopIteration maincities0: 0, 0, 1: 2, 2, antsnum0, iterationsnum5, ... pheromoneevaporation0.7, alpha1.0, beta5.0, q10 , inf maincities0: 0, 0, 1: 2, 2, antsnum5, iterationsnum0, ... pheromoneevaporation0.7, alpha1.0, beta5.0, q10 , inf maincities0: 0, 0, 1: 2, 2, antsnum5, iterationsnum5, ... pheromoneevaporation1, alpha1.0, beta5.0, q10 0, 1, 0, 5.656854249492381 maincities0: 0, 0, 1: 2, 2, antsnum5, iterationsnum5, ... pheromoneevaporation0, alpha1.0, beta5.0, q10 0, 1, 0, 5.656854249492381 Initialize the pheromone matrix Calculate the distance between two coordinate points distance0, 0, 3, 4 5.0 distance0, 0, 3, 4 5.0 distance0, 0, 3, 4 5.0 Update pheromones on the route and update the best route pheromoneupdatepheromone1.0, 1.0, 1.0, 1.0, ... cities0: 0,0, 1: 2,2, pheromoneevaporation0.7, ... antsroute0, 1, 0, q10, bestpath, ... bestdistancefloatinf 0.7, 4.235533905932737, 4.235533905932737, 0.7, 0, 1, 0, 5.656854249492381 pheromoneupdatepheromone, ... cities0: 0,0, 1: 2,2, pheromoneevaporation0.7, ... antsroute0, 1, 0, q10, bestpath, ... bestdistancefloatinf Traceback most recent call last: ... IndexError: list index out of range pheromoneupdatepheromone1.0, 1.0, 1.0, 1.0, ... cities, pheromoneevaporation0.7, ... antsroute0, 1, 0, q10, bestpath, ... bestdistancefloatinf Traceback most recent call last: ... KeyError: 0 Choose the next city for ants cityselectpheromone1.0, 1.0, 1.0, 1.0, currentcity0: 0, 0, ... unvisitedcities1: 2, 2, alpha1.0, beta5.0 1: 2, 2, cityselectpheromone, currentcity0: 0,0, ... unvisitedcities1: 2, 2, alpha1.0, beta5.0 Traceback most recent call last: ... IndexError: list index out of range cityselectpheromone1.0, 1.0, 1.0, 1.0, currentcity, ... unvisitedcities1: 2, 2, alpha1.0, beta5.0 Traceback most recent call last: ... StopIteration cityselectpheromone1.0, 1.0, 1.0, 1.0, currentcity0: 0, 0, ... unvisitedcities, alpha1.0, beta5.0 Traceback most recent call last: ... IndexError: list index out of range","Completions":"import copy\nimport random\n\ncities = {\n 0: [0, 0],\n 1: [0, 5],\n 2: [3, 8],\n 3: [8, 10],\n 4: [12, 8],\n 5: [12, 4],\n 6: [8, 0],\n 7: [6, 2],\n}\n\n\ndef main(\n cities: dict[int, list[int]],\n ants_num: int,\n iterations_num: int,\n pheromone_evaporation: float,\n alpha: float,\n beta: float,\n q: float, # Pheromone system parameters Q\uff0cwhich is a constant\n) -> tuple[list[int], float]:\n \"\"\"\n Ant colony algorithm main function\n >>> main(cities=cities, ants_num=10, iterations_num=20,\n ... pheromone_evaporation=0.7, alpha=1.0, beta=5.0, q=10)\n ([0, 1, 2, 3, 4, 5, 6, 7, 0], 37.909778143828696)\n >>> main(cities={0: [0, 0], 1: [2, 2]}, ants_num=5, iterations_num=5,\n ... pheromone_evaporation=0.7, alpha=1.0, beta=5.0, q=10)\n ([0, 1, 0], 5.656854249492381)\n >>> main(cities={0: [0, 0], 1: [2, 2], 4: [4, 4]}, ants_num=5, iterations_num=5,\n ... pheromone_evaporation=0.7, alpha=1.0, beta=5.0, q=10)\n Traceback (most recent call last):\n ...\n IndexError: list index out of range\n >>> main(cities={}, ants_num=5, iterations_num=5,\n ... pheromone_evaporation=0.7, alpha=1.0, beta=5.0, q=10)\n Traceback (most recent call last):\n ...\n StopIteration\n >>> main(cities={0: [0, 0], 1: [2, 2]}, ants_num=0, iterations_num=5,\n ... pheromone_evaporation=0.7, alpha=1.0, beta=5.0, q=10)\n ([], inf)\n >>> main(cities={0: [0, 0], 1: [2, 2]}, ants_num=5, iterations_num=0,\n ... pheromone_evaporation=0.7, alpha=1.0, beta=5.0, q=10)\n ([], inf)\n >>> main(cities={0: [0, 0], 1: [2, 2]}, ants_num=5, iterations_num=5,\n ... pheromone_evaporation=1, alpha=1.0, beta=5.0, q=10)\n ([0, 1, 0], 5.656854249492381)\n >>> main(cities={0: [0, 0], 1: [2, 2]}, ants_num=5, iterations_num=5,\n ... pheromone_evaporation=0, alpha=1.0, beta=5.0, q=10)\n ([0, 1, 0], 5.656854249492381)\n \"\"\"\n # Initialize the pheromone matrix\n cities_num = len(cities)\n pheromone = [[1.0] * cities_num] * cities_num\n\n best_path: list[int] = []\n best_distance = float(\"inf\")\n for _ in range(iterations_num):\n ants_route = []\n for _ in range(ants_num):\n unvisited_cities = copy.deepcopy(cities)\n current_city = {next(iter(cities.keys())): next(iter(cities.values()))}\n del unvisited_cities[next(iter(current_city.keys()))]\n ant_route = [next(iter(current_city.keys()))]\n while unvisited_cities:\n current_city, unvisited_cities = city_select(\n pheromone, current_city, unvisited_cities, alpha, beta\n )\n ant_route.append(next(iter(current_city.keys())))\n ant_route.append(0)\n ants_route.append(ant_route)\n\n pheromone, best_path, best_distance = pheromone_update(\n pheromone,\n cities,\n pheromone_evaporation,\n ants_route,\n q,\n best_path,\n best_distance,\n )\n return best_path, best_distance\n\n\ndef distance(city1: list[int], city2: list[int]) -> float:\n \"\"\"\n Calculate the distance between two coordinate points\n >>> distance([0, 0], [3, 4] )\n 5.0\n >>> distance([0, 0], [-3, 4] )\n 5.0\n >>> distance([0, 0], [-3, -4] )\n 5.0\n \"\"\"\n return (((city1[0] - city2[0]) ** 2) + ((city1[1] - city2[1]) ** 2)) ** 0.5\n\n\ndef pheromone_update(\n pheromone: list[list[float]],\n cities: dict[int, list[int]],\n pheromone_evaporation: float,\n ants_route: list[list[int]],\n q: float, # Pheromone system parameters Q\uff0cwhich is a constant\n best_path: list[int],\n best_distance: float,\n) -> tuple[list[list[float]], list[int], float]:\n \"\"\"\n Update pheromones on the route and update the best route\n >>>\n >>> pheromone_update(pheromone=[[1.0, 1.0], [1.0, 1.0]],\n ... cities={0: [0,0], 1: [2,2]}, pheromone_evaporation=0.7,\n ... ants_route=[[0, 1, 0]], q=10, best_path=[],\n ... best_distance=float(\"inf\"))\n ([[0.7, 4.235533905932737], [4.235533905932737, 0.7]], [0, 1, 0], 5.656854249492381)\n >>> pheromone_update(pheromone=[],\n ... cities={0: [0,0], 1: [2,2]}, pheromone_evaporation=0.7,\n ... ants_route=[[0, 1, 0]], q=10, best_path=[],\n ... best_distance=float(\"inf\"))\n Traceback (most recent call last):\n ...\n IndexError: list index out of range\n >>> pheromone_update(pheromone=[[1.0, 1.0], [1.0, 1.0]],\n ... cities={}, pheromone_evaporation=0.7,\n ... ants_route=[[0, 1, 0]], q=10, best_path=[],\n ... best_distance=float(\"inf\"))\n Traceback (most recent call last):\n ...\n KeyError: 0\n \"\"\"\n for a in range(len(cities)): # Update the volatilization of pheromone on all routes\n for b in range(len(cities)):\n pheromone[a][b] *= pheromone_evaporation\n for ant_route in ants_route:\n total_distance = 0.0\n for i in range(len(ant_route) - 1): # Calculate total distance\n total_distance += distance(cities[ant_route[i]], cities[ant_route[i + 1]])\n delta_pheromone = q \/ total_distance\n for i in range(len(ant_route) - 1): # Update pheromones\n pheromone[ant_route[i]][ant_route[i + 1]] += delta_pheromone\n pheromone[ant_route[i + 1]][ant_route[i]] = pheromone[ant_route[i]][\n ant_route[i + 1]\n ]\n\n if total_distance < best_distance:\n best_path = ant_route\n best_distance = total_distance\n\n return pheromone, best_path, best_distance\n\n\ndef city_select(\n pheromone: list[list[float]],\n current_city: dict[int, list[int]],\n unvisited_cities: dict[int, list[int]],\n alpha: float,\n beta: float,\n) -> tuple[dict[int, list[int]], dict[int, list[int]]]:\n \"\"\"\n Choose the next city for ants\n >>> city_select(pheromone=[[1.0, 1.0], [1.0, 1.0]], current_city={0: [0, 0]},\n ... unvisited_cities={1: [2, 2]}, alpha=1.0, beta=5.0)\n ({1: [2, 2]}, {})\n >>> city_select(pheromone=[], current_city={0: [0,0]},\n ... unvisited_cities={1: [2, 2]}, alpha=1.0, beta=5.0)\n Traceback (most recent call last):\n ...\n IndexError: list index out of range\n >>> city_select(pheromone=[[1.0, 1.0], [1.0, 1.0]], current_city={},\n ... unvisited_cities={1: [2, 2]}, alpha=1.0, beta=5.0)\n Traceback (most recent call last):\n ...\n StopIteration\n >>> city_select(pheromone=[[1.0, 1.0], [1.0, 1.0]], current_city={0: [0, 0]},\n ... unvisited_cities={}, alpha=1.0, beta=5.0)\n Traceback (most recent call last):\n ...\n IndexError: list index out of range\n \"\"\"\n probabilities = []\n for city in unvisited_cities:\n city_distance = distance(\n unvisited_cities[city], next(iter(current_city.values()))\n )\n probability = (pheromone[city][next(iter(current_city.keys()))] ** alpha) * (\n (1 \/ city_distance) ** beta\n )\n probabilities.append(probability)\n\n chosen_city_i = random.choices(\n list(unvisited_cities.keys()), weights=probabilities\n )[0]\n chosen_city = {chosen_city_i: unvisited_cities[chosen_city_i]}\n del unvisited_cities[next(iter(chosen_city.keys()))]\n return chosen_city, unvisited_cities\n\n\nif __name__ == \"__main__\":\n best_path, best_distance = main(\n cities=cities,\n ants_num=10,\n iterations_num=20,\n pheromone_evaporation=0.7,\n alpha=1.0,\n beta=5.0,\n q=10,\n )\n\n print(f\"{best_path = }\")\n print(f\"{best_distance = }\")\n"} +{"Prompt":"Finding Articulation Points in Undirected Graph AP found via bridge AP found via cycle Adjacency list of graph","Completions":"# Finding Articulation Points in Undirected Graph\ndef compute_ap(l): # noqa: E741\n n = len(l)\n out_edge_count = 0\n low = [0] * n\n visited = [False] * n\n is_art = [False] * n\n\n def dfs(root, at, parent, out_edge_count):\n if parent == root:\n out_edge_count += 1\n visited[at] = True\n low[at] = at\n\n for to in l[at]:\n if to == parent:\n pass\n elif not visited[to]:\n out_edge_count = dfs(root, to, at, out_edge_count)\n low[at] = min(low[at], low[to])\n\n # AP found via bridge\n if at < low[to]:\n is_art[at] = True\n # AP found via cycle\n if at == low[to]:\n is_art[at] = True\n else:\n low[at] = min(low[at], to)\n return out_edge_count\n\n for i in range(n):\n if not visited[i]:\n out_edge_count = 0\n out_edge_count = dfs(i, i, -1, out_edge_count)\n is_art[i] = out_edge_count > 1\n\n for x in range(len(is_art)):\n if is_art[x] is True:\n print(x)\n\n\n# Adjacency list of graph\ndata = {\n 0: [1, 2],\n 1: [0, 2],\n 2: [0, 1, 3, 5],\n 3: [2, 4],\n 4: [3],\n 5: [2, 6, 8],\n 6: [5, 7],\n 7: [6, 8],\n 8: [5, 7],\n}\ncompute_ap(data)\n"} +{"Prompt":"Depth First Search. Args : G Dictionary of edges s Starting Node Vars : vis Set of visited nodes S Traversal Stack Breadth First Search. Args : G Dictionary of edges s Starting Node Vars : vis Set of visited nodes Q Traversal Stack Dijkstra's shortest path Algorithm Args : G Dictionary of edges s Starting Node Vars : dist Dictionary storing shortest distance from s to every other node known Set of knows nodes path Preceding node in path Topological Sort Reading an Adjacency matrix n intinput.strip a for in rangen: a.appendtuplemapint, input.strip.split return a, n def floyaandn: a, n aandn dist lista path 0 n for i in rangen for k in rangen: for i in rangen: for j in rangen: if distij distik distkj: distij distik distkj pathik k printdist def primg, s: dist, known, path s: 0, set, s: 0 while True: if lenknown leng 1: break mini 100000 for i in dist: if i not in known and disti mini: mini disti u i known.addu for v in gu: if v0 not in known and v1 dist.getv0, 100000: distv0 v1 pathv0 u return dist def edglist: r Get the edges and number of edges from the user Parameters: None Returns: tuple: A tuple containing a list of edges and number of edges Example: Simulate user input for 3 edges and 4 vertices: 1, 2, 2, 3, 3, 4 inputdata 4 3n1 2n2 3n3 4n import sys,io originalinput sys.stdin sys.stdin io.StringIOinputdata Redirect stdin for testing edglist 1, 2, 2, 3, 3, 4, 4 sys.stdin originalinput Restore original stdin Kruskal's MST Algorithm Args : E Edge list n Number of Nodes Vars : s Set of all nodes as unique disjoint sets initially Sort edges on the basis of distance Find the isolated node in the graph Parameters: graph dict: A dictionary representing a graph. Returns: list: A list of isolated nodes. Examples: graph1 1: 2, 3, 2: 1, 3, 3: 1, 2, 4: findisolatednodesgraph1 4 graph2 'A': 'B', 'C', 'B': 'A', 'C': 'A', 'D': findisolatednodesgraph2 'D' graph3 'X': , 'Y': , 'Z': findisolatednodesgraph3 'X', 'Y', 'Z' graph4 1: 2, 3, 2: 1, 3, 3: 1, 2 findisolatednodesgraph4 graph5 findisolatednodesgraph5","Completions":"from collections import deque\n\n\ndef _input(message):\n return input(message).strip().split(\" \")\n\n\ndef initialize_unweighted_directed_graph(\n node_count: int, edge_count: int\n) -> dict[int, list[int]]:\n graph: dict[int, list[int]] = {}\n for i in range(node_count):\n graph[i + 1] = []\n\n for e in range(edge_count):\n x, y = (int(i) for i in _input(f\"Edge {e + 1}: \"))\n graph[x].append(y)\n return graph\n\n\ndef initialize_unweighted_undirected_graph(\n node_count: int, edge_count: int\n) -> dict[int, list[int]]:\n graph: dict[int, list[int]] = {}\n for i in range(node_count):\n graph[i + 1] = []\n\n for e in range(edge_count):\n x, y = (int(i) for i in _input(f\"Edge {e + 1}: \"))\n graph[x].append(y)\n graph[y].append(x)\n return graph\n\n\ndef initialize_weighted_undirected_graph(\n node_count: int, edge_count: int\n) -> dict[int, list[tuple[int, int]]]:\n graph: dict[int, list[tuple[int, int]]] = {}\n for i in range(node_count):\n graph[i + 1] = []\n\n for e in range(edge_count):\n x, y, w = (int(i) for i in _input(f\"Edge {e + 1}: \"))\n graph[x].append((y, w))\n graph[y].append((x, w))\n return graph\n\n\nif __name__ == \"__main__\":\n n, m = (int(i) for i in _input(\"Number of nodes and edges: \"))\n\n graph_choice = int(\n _input(\n \"Press 1 or 2 or 3 \\n\"\n \"1. Unweighted directed \\n\"\n \"2. Unweighted undirected \\n\"\n \"3. Weighted undirected \\n\"\n )[0]\n )\n\n g = {\n 1: initialize_unweighted_directed_graph,\n 2: initialize_unweighted_undirected_graph,\n 3: initialize_weighted_undirected_graph,\n }[graph_choice](n, m)\n\n\n\"\"\"\n--------------------------------------------------------------------------------\n Depth First Search.\n Args : G - Dictionary of edges\n s - Starting Node\n Vars : vis - Set of visited nodes\n S - Traversal Stack\n--------------------------------------------------------------------------------\n\"\"\"\n\n\ndef dfs(g, s):\n vis, _s = {s}, [s]\n print(s)\n while _s:\n flag = 0\n for i in g[_s[-1]]:\n if i not in vis:\n _s.append(i)\n vis.add(i)\n flag = 1\n print(i)\n break\n if not flag:\n _s.pop()\n\n\n\"\"\"\n--------------------------------------------------------------------------------\n Breadth First Search.\n Args : G - Dictionary of edges\n s - Starting Node\n Vars : vis - Set of visited nodes\n Q - Traversal Stack\n--------------------------------------------------------------------------------\n\"\"\"\n\n\ndef bfs(g, s):\n vis, q = {s}, deque([s])\n print(s)\n while q:\n u = q.popleft()\n for v in g[u]:\n if v not in vis:\n vis.add(v)\n q.append(v)\n print(v)\n\n\n\"\"\"\n--------------------------------------------------------------------------------\n Dijkstra's shortest path Algorithm\n Args : G - Dictionary of edges\n s - Starting Node\n Vars : dist - Dictionary storing shortest distance from s to every other node\n known - Set of knows nodes\n path - Preceding node in path\n--------------------------------------------------------------------------------\n\"\"\"\n\n\ndef dijk(g, s):\n dist, known, path = {s: 0}, set(), {s: 0}\n while True:\n if len(known) == len(g) - 1:\n break\n mini = 100000\n for i in dist:\n if i not in known and dist[i] < mini:\n mini = dist[i]\n u = i\n known.add(u)\n for v in g[u]:\n if v[0] not in known and dist[u] + v[1] < dist.get(v[0], 100000):\n dist[v[0]] = dist[u] + v[1]\n path[v[0]] = u\n for i in dist:\n if i != s:\n print(dist[i])\n\n\n\"\"\"\n--------------------------------------------------------------------------------\n Topological Sort\n--------------------------------------------------------------------------------\n\"\"\"\n\n\ndef topo(g, ind=None, q=None):\n if q is None:\n q = [1]\n if ind is None:\n ind = [0] * (len(g) + 1) # SInce oth Index is ignored\n for u in g:\n for v in g[u]:\n ind[v] += 1\n q = deque()\n for i in g:\n if ind[i] == 0:\n q.append(i)\n if len(q) == 0:\n return\n v = q.popleft()\n print(v)\n for w in g[v]:\n ind[w] -= 1\n if ind[w] == 0:\n q.append(w)\n topo(g, ind, q)\n\n\n\"\"\"\n--------------------------------------------------------------------------------\n Reading an Adjacency matrix\n--------------------------------------------------------------------------------\n\"\"\"\n\n\ndef adjm():\n r\"\"\"\n Reading an Adjacency matrix\n\n Parameters:\n None\n\n Returns:\n tuple: A tuple containing a list of edges and number of edges\n\n Example:\n >>> # Simulate user input for 3 nodes\n >>> input_data = \"4\\n0 1 0 1\\n1 0 1 0\\n0 1 0 1\\n1 0 1 0\\n\"\n >>> import sys,io\n >>> original_input = sys.stdin\n >>> sys.stdin = io.StringIO(input_data) # Redirect stdin for testing\n >>> adjm()\n ([(0, 1, 0, 1), (1, 0, 1, 0), (0, 1, 0, 1), (1, 0, 1, 0)], 4)\n >>> sys.stdin = original_input # Restore original stdin\n \"\"\"\n n = int(input().strip())\n a = []\n for _ in range(n):\n a.append(tuple(map(int, input().strip().split())))\n return a, n\n\n\n\"\"\"\n--------------------------------------------------------------------------------\n Floyd Warshall's algorithm\n Args : G - Dictionary of edges\n s - Starting Node\n Vars : dist - Dictionary storing shortest distance from s to every other node\n known - Set of knows nodes\n path - Preceding node in path\n\n--------------------------------------------------------------------------------\n\"\"\"\n\n\ndef floy(a_and_n):\n (a, n) = a_and_n\n dist = list(a)\n path = [[0] * n for i in range(n)]\n for k in range(n):\n for i in range(n):\n for j in range(n):\n if dist[i][j] > dist[i][k] + dist[k][j]:\n dist[i][j] = dist[i][k] + dist[k][j]\n path[i][k] = k\n print(dist)\n\n\n\"\"\"\n--------------------------------------------------------------------------------\n Prim's MST Algorithm\n Args : G - Dictionary of edges\n s - Starting Node\n Vars : dist - Dictionary storing shortest distance from s to nearest node\n known - Set of knows nodes\n path - Preceding node in path\n--------------------------------------------------------------------------------\n\"\"\"\n\n\ndef prim(g, s):\n dist, known, path = {s: 0}, set(), {s: 0}\n while True:\n if len(known) == len(g) - 1:\n break\n mini = 100000\n for i in dist:\n if i not in known and dist[i] < mini:\n mini = dist[i]\n u = i\n known.add(u)\n for v in g[u]:\n if v[0] not in known and v[1] < dist.get(v[0], 100000):\n dist[v[0]] = v[1]\n path[v[0]] = u\n return dist\n\n\n\"\"\"\n--------------------------------------------------------------------------------\n Accepting Edge list\n Vars : n - Number of nodes\n m - Number of edges\n Returns : l - Edge list\n n - Number of Nodes\n--------------------------------------------------------------------------------\n\"\"\"\n\n\ndef edglist():\n r\"\"\"\n Get the edges and number of edges from the user\n\n Parameters:\n None\n\n Returns:\n tuple: A tuple containing a list of edges and number of edges\n\n Example:\n >>> # Simulate user input for 3 edges and 4 vertices: (1, 2), (2, 3), (3, 4)\n >>> input_data = \"4 3\\n1 2\\n2 3\\n3 4\\n\"\n >>> import sys,io\n >>> original_input = sys.stdin\n >>> sys.stdin = io.StringIO(input_data) # Redirect stdin for testing\n >>> edglist()\n ([(1, 2), (2, 3), (3, 4)], 4)\n >>> sys.stdin = original_input # Restore original stdin\n \"\"\"\n n, m = tuple(map(int, input().split(\" \")))\n edges = []\n for _ in range(m):\n edges.append(tuple(map(int, input().split(\" \"))))\n return edges, n\n\n\n\"\"\"\n--------------------------------------------------------------------------------\n Kruskal's MST Algorithm\n Args : E - Edge list\n n - Number of Nodes\n Vars : s - Set of all nodes as unique disjoint sets (initially)\n--------------------------------------------------------------------------------\n\"\"\"\n\n\ndef krusk(e_and_n):\n \"\"\"\n Sort edges on the basis of distance\n \"\"\"\n (e, n) = e_and_n\n e.sort(reverse=True, key=lambda x: x[2])\n s = [{i} for i in range(1, n + 1)]\n while True:\n if len(s) == 1:\n break\n print(s)\n x = e.pop()\n for i in range(len(s)):\n if x[0] in s[i]:\n break\n for j in range(len(s)):\n if x[1] in s[j]:\n if i == j:\n break\n s[j].update(s[i])\n s.pop(i)\n break\n\n\ndef find_isolated_nodes(graph):\n \"\"\"\n Find the isolated node in the graph\n\n Parameters:\n graph (dict): A dictionary representing a graph.\n\n Returns:\n list: A list of isolated nodes.\n\n Examples:\n >>> graph1 = {1: [2, 3], 2: [1, 3], 3: [1, 2], 4: []}\n >>> find_isolated_nodes(graph1)\n [4]\n\n >>> graph2 = {'A': ['B', 'C'], 'B': ['A'], 'C': ['A'], 'D': []}\n >>> find_isolated_nodes(graph2)\n ['D']\n\n >>> graph3 = {'X': [], 'Y': [], 'Z': []}\n >>> find_isolated_nodes(graph3)\n ['X', 'Y', 'Z']\n\n >>> graph4 = {1: [2, 3], 2: [1, 3], 3: [1, 2]}\n >>> find_isolated_nodes(graph4)\n []\n\n >>> graph5 = {}\n >>> find_isolated_nodes(graph5)\n []\n \"\"\"\n isolated = []\n for node in graph:\n if not graph[node]:\n isolated.append(node)\n return isolated\n"} +{"Prompt":"Returns shortest paths from a vertex src to all other vertices. edges 2, 1, 10, 3, 2, 3, 0, 3, 5, 0, 1, 4 g src: s, dst: d, weight: w for s, d, w in edges bellmanfordg, 4, 4, 0 0.0, 2.0, 8.0, 5.0 g src: s, dst: d, weight: w for s, d, w in edges 1, 3, 5 bellmanfordg, 4, 5, 0 Traceback most recent call last: ... Exception: Negative cycle found","Completions":"from __future__ import annotations\n\n\ndef print_distance(distance: list[float], src):\n print(f\"Vertex\\tShortest Distance from vertex {src}\")\n for i, d in enumerate(distance):\n print(f\"{i}\\t\\t{d}\")\n\n\ndef check_negative_cycle(\n graph: list[dict[str, int]], distance: list[float], edge_count: int\n):\n for j in range(edge_count):\n u, v, w = (graph[j][k] for k in [\"src\", \"dst\", \"weight\"])\n if distance[u] != float(\"inf\") and distance[u] + w < distance[v]:\n return True\n return False\n\n\ndef bellman_ford(\n graph: list[dict[str, int]], vertex_count: int, edge_count: int, src: int\n) -> list[float]:\n \"\"\"\n Returns shortest paths from a vertex src to all\n other vertices.\n >>> edges = [(2, 1, -10), (3, 2, 3), (0, 3, 5), (0, 1, 4)]\n >>> g = [{\"src\": s, \"dst\": d, \"weight\": w} for s, d, w in edges]\n >>> bellman_ford(g, 4, 4, 0)\n [0.0, -2.0, 8.0, 5.0]\n >>> g = [{\"src\": s, \"dst\": d, \"weight\": w} for s, d, w in edges + [(1, 3, 5)]]\n >>> bellman_ford(g, 4, 5, 0)\n Traceback (most recent call last):\n ...\n Exception: Negative cycle found\n \"\"\"\n distance = [float(\"inf\")] * vertex_count\n distance[src] = 0.0\n\n for _ in range(vertex_count - 1):\n for j in range(edge_count):\n u, v, w = (graph[j][k] for k in [\"src\", \"dst\", \"weight\"])\n\n if distance[u] != float(\"inf\") and distance[u] + w < distance[v]:\n distance[v] = distance[u] + w\n\n negative_cycle_exists = check_negative_cycle(graph, distance, edge_count)\n if negative_cycle_exists:\n raise Exception(\"Negative cycle found\")\n\n return distance\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n\n V = int(input(\"Enter number of vertices: \").strip())\n E = int(input(\"Enter number of edges: \").strip())\n\n graph: list[dict[str, int]] = [{} for _ in range(E)]\n\n for i in range(E):\n print(\"Edge \", i + 1)\n src, dest, weight = (\n int(x)\n for x in input(\"Enter source, destination, weight: \").strip().split(\" \")\n )\n graph[i] = {\"src\": src, \"dst\": dest, \"weight\": weight}\n\n source = int(input(\"\\nEnter shortest path source:\").strip())\n shortest_distance = bellman_ford(graph, V, E, source)\n print_distance(shortest_distance, 0)\n"} +{"Prompt":"Bidirectional Dijkstra's algorithm. A bidirectional approach is an efficient and less time consuming optimization for Dijkstra's searching algorithm Reference: shorturl.atexHM7 Author: Swayam Singh https:github.compractice404 Bidirectional Dijkstra's algorithm. Returns: shortestpathdistance int: length of the shortest path. Warnings: If the destination is not reachable, function returns 1 bidirectionaldijE, F, graphfwd, graphbwd 3","Completions":"# Author: Swayam Singh (https:\/\/github.com\/practice404)\n\n\nfrom queue import PriorityQueue\nfrom typing import Any\n\nimport numpy as np\n\n\ndef pass_and_relaxation(\n graph: dict,\n v: str,\n visited_forward: set,\n visited_backward: set,\n cst_fwd: dict,\n cst_bwd: dict,\n queue: PriorityQueue,\n parent: dict,\n shortest_distance: float,\n) -> float:\n for nxt, d in graph[v]:\n if nxt in visited_forward:\n continue\n old_cost_f = cst_fwd.get(nxt, np.inf)\n new_cost_f = cst_fwd[v] + d\n if new_cost_f < old_cost_f:\n queue.put((new_cost_f, nxt))\n cst_fwd[nxt] = new_cost_f\n parent[nxt] = v\n if nxt in visited_backward:\n if cst_fwd[v] + d + cst_bwd[nxt] < shortest_distance:\n shortest_distance = cst_fwd[v] + d + cst_bwd[nxt]\n return shortest_distance\n\n\ndef bidirectional_dij(\n source: str, destination: str, graph_forward: dict, graph_backward: dict\n) -> int:\n \"\"\"\n Bi-directional Dijkstra's algorithm.\n\n Returns:\n shortest_path_distance (int): length of the shortest path.\n\n Warnings:\n If the destination is not reachable, function returns -1\n\n >>> bidirectional_dij(\"E\", \"F\", graph_fwd, graph_bwd)\n 3\n \"\"\"\n shortest_path_distance = -1\n\n visited_forward = set()\n visited_backward = set()\n cst_fwd = {source: 0}\n cst_bwd = {destination: 0}\n parent_forward = {source: None}\n parent_backward = {destination: None}\n queue_forward: PriorityQueue[Any] = PriorityQueue()\n queue_backward: PriorityQueue[Any] = PriorityQueue()\n\n shortest_distance = np.inf\n\n queue_forward.put((0, source))\n queue_backward.put((0, destination))\n\n if source == destination:\n return 0\n\n while not queue_forward.empty() and not queue_backward.empty():\n _, v_fwd = queue_forward.get()\n visited_forward.add(v_fwd)\n\n _, v_bwd = queue_backward.get()\n visited_backward.add(v_bwd)\n\n shortest_distance = pass_and_relaxation(\n graph_forward,\n v_fwd,\n visited_forward,\n visited_backward,\n cst_fwd,\n cst_bwd,\n queue_forward,\n parent_forward,\n shortest_distance,\n )\n\n shortest_distance = pass_and_relaxation(\n graph_backward,\n v_bwd,\n visited_backward,\n visited_forward,\n cst_bwd,\n cst_fwd,\n queue_backward,\n parent_backward,\n shortest_distance,\n )\n\n if cst_fwd[v_fwd] + cst_bwd[v_bwd] >= shortest_distance:\n break\n\n if shortest_distance != np.inf:\n shortest_path_distance = shortest_distance\n return shortest_path_distance\n\n\ngraph_fwd = {\n \"B\": [[\"C\", 1]],\n \"C\": [[\"D\", 1]],\n \"D\": [[\"F\", 1]],\n \"E\": [[\"B\", 1], [\"G\", 2]],\n \"F\": [],\n \"G\": [[\"F\", 1]],\n}\ngraph_bwd = {\n \"B\": [[\"E\", 1]],\n \"C\": [[\"B\", 1]],\n \"D\": [[\"C\", 1]],\n \"F\": [[\"D\", 1], [\"G\", 1]],\n \"E\": [[None, np.inf]],\n \"G\": [[\"E\", 2]],\n}\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"https:en.wikipedia.orgwikiBidirectionalsearch 1 for manhattan, 0 for euclidean k Node0, 0, 4, 3, 0, None k.calculateheuristic 5.0 n Node1, 4, 3, 4, 2, None n.calculateheuristic 2.0 l k, n n l0 False l.sort n l0 True Heuristic for the A astar AStar0, 0, lengrid 1, lengrid0 1 astar.start.posy delta30, astar.start.posx delta31 0, 1 x.pos for x in astar.getsuccessorsastar.start 1, 0, 0, 1 astar.start.posy delta20, astar.start.posx delta21 1, 0 astar.retracepathastar.start 0, 0 astar.search doctest: NORMALIZEWHITESPACE 0, 0, 1, 0, 2, 0, 2, 1, 2, 2, 2, 3, 3, 3, 4, 3, 4, 4, 5, 4, 5, 5, 6, 5, 6, 6 Open Nodes are sorted using lt retrieve the best current path Returns a list of successors both in the grid and free spaces Retrace the path from parents to parents until start node bdastar BidirectionalAStar0, 0, lengrid 1, lengrid0 1 bdastar.fwdastar.start.pos bdastar.bwdastar.target.pos True bdastar.retracebidirectionalpathbdastar.fwdastar.start, ... bdastar.bwdastar.start 0, 0 bdastar.search doctest: NORMALIZEWHITESPACE 0, 0, 0, 1, 0, 2, 1, 2, 1, 3, 2, 3, 2, 4, 2, 5, 3, 5, 4, 5, 5, 5, 5, 6, 6, 6 retrieve the best current path all coordinates are given in format y,x","Completions":"from __future__ import annotations\n\nimport time\nfrom math import sqrt\n\n# 1 for manhattan, 0 for euclidean\nHEURISTIC = 0\n\ngrid = [\n [0, 0, 0, 0, 0, 0, 0],\n [0, 1, 0, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles\n [0, 0, 0, 0, 0, 0, 0],\n [0, 0, 1, 0, 0, 0, 0],\n [1, 0, 1, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 1, 0, 0],\n]\n\ndelta = [[-1, 0], [0, -1], [1, 0], [0, 1]] # up, left, down, right\n\nTPosition = tuple[int, int]\n\n\nclass Node:\n \"\"\"\n >>> k = Node(0, 0, 4, 3, 0, None)\n >>> k.calculate_heuristic()\n 5.0\n >>> n = Node(1, 4, 3, 4, 2, None)\n >>> n.calculate_heuristic()\n 2.0\n >>> l = [k, n]\n >>> n == l[0]\n False\n >>> l.sort()\n >>> n == l[0]\n True\n \"\"\"\n\n def __init__(\n self,\n pos_x: int,\n pos_y: int,\n goal_x: int,\n goal_y: int,\n g_cost: int,\n parent: Node | None,\n ) -> None:\n self.pos_x = pos_x\n self.pos_y = pos_y\n self.pos = (pos_y, pos_x)\n self.goal_x = goal_x\n self.goal_y = goal_y\n self.g_cost = g_cost\n self.parent = parent\n self.h_cost = self.calculate_heuristic()\n self.f_cost = self.g_cost + self.h_cost\n\n def calculate_heuristic(self) -> float:\n \"\"\"\n Heuristic for the A*\n \"\"\"\n dy = self.pos_x - self.goal_x\n dx = self.pos_y - self.goal_y\n if HEURISTIC == 1:\n return abs(dx) + abs(dy)\n else:\n return sqrt(dy**2 + dx**2)\n\n def __lt__(self, other: Node) -> bool:\n return self.f_cost < other.f_cost\n\n\nclass AStar:\n \"\"\"\n >>> astar = AStar((0, 0), (len(grid) - 1, len(grid[0]) - 1))\n >>> (astar.start.pos_y + delta[3][0], astar.start.pos_x + delta[3][1])\n (0, 1)\n >>> [x.pos for x in astar.get_successors(astar.start)]\n [(1, 0), (0, 1)]\n >>> (astar.start.pos_y + delta[2][0], astar.start.pos_x + delta[2][1])\n (1, 0)\n >>> astar.retrace_path(astar.start)\n [(0, 0)]\n >>> astar.search() # doctest: +NORMALIZE_WHITESPACE\n [(0, 0), (1, 0), (2, 0), (2, 1), (2, 2), (2, 3), (3, 3),\n (4, 3), (4, 4), (5, 4), (5, 5), (6, 5), (6, 6)]\n \"\"\"\n\n def __init__(self, start: TPosition, goal: TPosition):\n self.start = Node(start[1], start[0], goal[1], goal[0], 0, None)\n self.target = Node(goal[1], goal[0], goal[1], goal[0], 99999, None)\n\n self.open_nodes = [self.start]\n self.closed_nodes: list[Node] = []\n\n self.reached = False\n\n def search(self) -> list[TPosition]:\n while self.open_nodes:\n # Open Nodes are sorted using __lt__\n self.open_nodes.sort()\n current_node = self.open_nodes.pop(0)\n\n if current_node.pos == self.target.pos:\n return self.retrace_path(current_node)\n\n self.closed_nodes.append(current_node)\n successors = self.get_successors(current_node)\n\n for child_node in successors:\n if child_node in self.closed_nodes:\n continue\n\n if child_node not in self.open_nodes:\n self.open_nodes.append(child_node)\n else:\n # retrieve the best current path\n better_node = self.open_nodes.pop(self.open_nodes.index(child_node))\n\n if child_node.g_cost < better_node.g_cost:\n self.open_nodes.append(child_node)\n else:\n self.open_nodes.append(better_node)\n\n return [self.start.pos]\n\n def get_successors(self, parent: Node) -> list[Node]:\n \"\"\"\n Returns a list of successors (both in the grid and free spaces)\n \"\"\"\n successors = []\n for action in delta:\n pos_x = parent.pos_x + action[1]\n pos_y = parent.pos_y + action[0]\n if not (0 <= pos_x <= len(grid[0]) - 1 and 0 <= pos_y <= len(grid) - 1):\n continue\n\n if grid[pos_y][pos_x] != 0:\n continue\n\n successors.append(\n Node(\n pos_x,\n pos_y,\n self.target.pos_y,\n self.target.pos_x,\n parent.g_cost + 1,\n parent,\n )\n )\n return successors\n\n def retrace_path(self, node: Node | None) -> list[TPosition]:\n \"\"\"\n Retrace the path from parents to parents until start node\n \"\"\"\n current_node = node\n path = []\n while current_node is not None:\n path.append((current_node.pos_y, current_node.pos_x))\n current_node = current_node.parent\n path.reverse()\n return path\n\n\nclass BidirectionalAStar:\n \"\"\"\n >>> bd_astar = BidirectionalAStar((0, 0), (len(grid) - 1, len(grid[0]) - 1))\n >>> bd_astar.fwd_astar.start.pos == bd_astar.bwd_astar.target.pos\n True\n >>> bd_astar.retrace_bidirectional_path(bd_astar.fwd_astar.start,\n ... bd_astar.bwd_astar.start)\n [(0, 0)]\n >>> bd_astar.search() # doctest: +NORMALIZE_WHITESPACE\n [(0, 0), (0, 1), (0, 2), (1, 2), (1, 3), (2, 3), (2, 4),\n (2, 5), (3, 5), (4, 5), (5, 5), (5, 6), (6, 6)]\n \"\"\"\n\n def __init__(self, start: TPosition, goal: TPosition) -> None:\n self.fwd_astar = AStar(start, goal)\n self.bwd_astar = AStar(goal, start)\n self.reached = False\n\n def search(self) -> list[TPosition]:\n while self.fwd_astar.open_nodes or self.bwd_astar.open_nodes:\n self.fwd_astar.open_nodes.sort()\n self.bwd_astar.open_nodes.sort()\n current_fwd_node = self.fwd_astar.open_nodes.pop(0)\n current_bwd_node = self.bwd_astar.open_nodes.pop(0)\n\n if current_bwd_node.pos == current_fwd_node.pos:\n return self.retrace_bidirectional_path(\n current_fwd_node, current_bwd_node\n )\n\n self.fwd_astar.closed_nodes.append(current_fwd_node)\n self.bwd_astar.closed_nodes.append(current_bwd_node)\n\n self.fwd_astar.target = current_bwd_node\n self.bwd_astar.target = current_fwd_node\n\n successors = {\n self.fwd_astar: self.fwd_astar.get_successors(current_fwd_node),\n self.bwd_astar: self.bwd_astar.get_successors(current_bwd_node),\n }\n\n for astar in [self.fwd_astar, self.bwd_astar]:\n for child_node in successors[astar]:\n if child_node in astar.closed_nodes:\n continue\n\n if child_node not in astar.open_nodes:\n astar.open_nodes.append(child_node)\n else:\n # retrieve the best current path\n better_node = astar.open_nodes.pop(\n astar.open_nodes.index(child_node)\n )\n\n if child_node.g_cost < better_node.g_cost:\n astar.open_nodes.append(child_node)\n else:\n astar.open_nodes.append(better_node)\n\n return [self.fwd_astar.start.pos]\n\n def retrace_bidirectional_path(\n self, fwd_node: Node, bwd_node: Node\n ) -> list[TPosition]:\n fwd_path = self.fwd_astar.retrace_path(fwd_node)\n bwd_path = self.bwd_astar.retrace_path(bwd_node)\n bwd_path.pop()\n bwd_path.reverse()\n path = fwd_path + bwd_path\n return path\n\n\nif __name__ == \"__main__\":\n # all coordinates are given in format [y,x]\n init = (0, 0)\n goal = (len(grid) - 1, len(grid[0]) - 1)\n for elem in grid:\n print(elem)\n\n start_time = time.time()\n a_star = AStar(init, goal)\n path = a_star.search()\n end_time = time.time() - start_time\n print(f\"AStar execution time = {end_time:f} seconds\")\n\n bd_start_time = time.time()\n bidir_astar = BidirectionalAStar(init, goal)\n bd_end_time = time.time() - bd_start_time\n print(f\"BidirectionalAStar execution time = {bd_end_time:f} seconds\")\n"} +{"Prompt":"https:en.wikipedia.orgwikiBidirectionalsearch Comment out slow pytests... 9.15s call graphsbidirectionalbreadthfirstsearch.py:: graphs.bidirectionalbreadthfirstsearch.BreadthFirstSearch bfs BreadthFirstSearch0, 0, lengrid 1, lengrid0 1 bfs.start.posy delta30, bfs.start.posx delta31 0, 1 x.pos for x in bfs.getsuccessorsbfs.start 1, 0, 0, 1 bfs.start.posy delta20, bfs.start.posx delta21 1, 0 bfs.retracepathbfs.start 0, 0 bfs.search doctest: NORMALIZEWHITESPACE 0, 0, 1, 0, 2, 0, 3, 0, 3, 1, 4, 1, 5, 1, 5, 2, 5, 3, 5, 4, 5, 5, 6, 5, 6, 6 Returns a list of successors both in the grid and free spaces Retrace the path from parents to parents until start node bdbfs BidirectionalBreadthFirstSearch0, 0, lengrid 1, ... lengrid0 1 bdbfs.fwdbfs.start.pos bdbfs.bwdbfs.target.pos True bdbfs.retracebidirectionalpathbdbfs.fwdbfs.start, ... bdbfs.bwdbfs.start 0, 0 bdbfs.search doctest: NORMALIZEWHITESPACE 0, 0, 0, 1, 0, 2, 1, 2, 2, 2, 2, 3, 2, 4, 3, 4, 3, 5, 3, 6, 4, 6, 5, 6, 6, 6 all coordinates are given in format y,x","Completions":"from __future__ import annotations\n\nimport time\n\nPath = list[tuple[int, int]]\n\ngrid = [\n [0, 0, 0, 0, 0, 0, 0],\n [0, 1, 0, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles\n [0, 0, 0, 0, 0, 0, 0],\n [0, 0, 1, 0, 0, 0, 0],\n [1, 0, 1, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 1, 0, 0],\n]\n\ndelta = [[-1, 0], [0, -1], [1, 0], [0, 1]] # up, left, down, right\n\n\nclass Node:\n def __init__(\n self, pos_x: int, pos_y: int, goal_x: int, goal_y: int, parent: Node | None\n ):\n self.pos_x = pos_x\n self.pos_y = pos_y\n self.pos = (pos_y, pos_x)\n self.goal_x = goal_x\n self.goal_y = goal_y\n self.parent = parent\n\n\nclass BreadthFirstSearch:\n \"\"\"\n # Comment out slow pytests...\n # 9.15s call graphs\/bidirectional_breadth_first_search.py:: \\\n # graphs.bidirectional_breadth_first_search.BreadthFirstSearch\n # >>> bfs = BreadthFirstSearch((0, 0), (len(grid) - 1, len(grid[0]) - 1))\n # >>> (bfs.start.pos_y + delta[3][0], bfs.start.pos_x + delta[3][1])\n (0, 1)\n # >>> [x.pos for x in bfs.get_successors(bfs.start)]\n [(1, 0), (0, 1)]\n # >>> (bfs.start.pos_y + delta[2][0], bfs.start.pos_x + delta[2][1])\n (1, 0)\n # >>> bfs.retrace_path(bfs.start)\n [(0, 0)]\n # >>> bfs.search() # doctest: +NORMALIZE_WHITESPACE\n [(0, 0), (1, 0), (2, 0), (3, 0), (3, 1), (4, 1),\n (5, 1), (5, 2), (5, 3), (5, 4), (5, 5), (6, 5), (6, 6)]\n \"\"\"\n\n def __init__(self, start: tuple[int, int], goal: tuple[int, int]):\n self.start = Node(start[1], start[0], goal[1], goal[0], None)\n self.target = Node(goal[1], goal[0], goal[1], goal[0], None)\n\n self.node_queue = [self.start]\n self.reached = False\n\n def search(self) -> Path | None:\n while self.node_queue:\n current_node = self.node_queue.pop(0)\n\n if current_node.pos == self.target.pos:\n self.reached = True\n return self.retrace_path(current_node)\n\n successors = self.get_successors(current_node)\n\n for node in successors:\n self.node_queue.append(node)\n\n if not self.reached:\n return [self.start.pos]\n return None\n\n def get_successors(self, parent: Node) -> list[Node]:\n \"\"\"\n Returns a list of successors (both in the grid and free spaces)\n \"\"\"\n successors = []\n for action in delta:\n pos_x = parent.pos_x + action[1]\n pos_y = parent.pos_y + action[0]\n if not (0 <= pos_x <= len(grid[0]) - 1 and 0 <= pos_y <= len(grid) - 1):\n continue\n\n if grid[pos_y][pos_x] != 0:\n continue\n\n successors.append(\n Node(pos_x, pos_y, self.target.pos_y, self.target.pos_x, parent)\n )\n return successors\n\n def retrace_path(self, node: Node | None) -> Path:\n \"\"\"\n Retrace the path from parents to parents until start node\n \"\"\"\n current_node = node\n path = []\n while current_node is not None:\n path.append((current_node.pos_y, current_node.pos_x))\n current_node = current_node.parent\n path.reverse()\n return path\n\n\nclass BidirectionalBreadthFirstSearch:\n \"\"\"\n >>> bd_bfs = BidirectionalBreadthFirstSearch((0, 0), (len(grid) - 1,\n ... len(grid[0]) - 1))\n >>> bd_bfs.fwd_bfs.start.pos == bd_bfs.bwd_bfs.target.pos\n True\n >>> bd_bfs.retrace_bidirectional_path(bd_bfs.fwd_bfs.start,\n ... bd_bfs.bwd_bfs.start)\n [(0, 0)]\n >>> bd_bfs.search() # doctest: +NORMALIZE_WHITESPACE\n [(0, 0), (0, 1), (0, 2), (1, 2), (2, 2), (2, 3),\n (2, 4), (3, 4), (3, 5), (3, 6), (4, 6), (5, 6), (6, 6)]\n \"\"\"\n\n def __init__(self, start, goal):\n self.fwd_bfs = BreadthFirstSearch(start, goal)\n self.bwd_bfs = BreadthFirstSearch(goal, start)\n self.reached = False\n\n def search(self) -> Path | None:\n while self.fwd_bfs.node_queue or self.bwd_bfs.node_queue:\n current_fwd_node = self.fwd_bfs.node_queue.pop(0)\n current_bwd_node = self.bwd_bfs.node_queue.pop(0)\n\n if current_bwd_node.pos == current_fwd_node.pos:\n self.reached = True\n return self.retrace_bidirectional_path(\n current_fwd_node, current_bwd_node\n )\n\n self.fwd_bfs.target = current_bwd_node\n self.bwd_bfs.target = current_fwd_node\n\n successors = {\n self.fwd_bfs: self.fwd_bfs.get_successors(current_fwd_node),\n self.bwd_bfs: self.bwd_bfs.get_successors(current_bwd_node),\n }\n\n for bfs in [self.fwd_bfs, self.bwd_bfs]:\n for node in successors[bfs]:\n bfs.node_queue.append(node)\n\n if not self.reached:\n return [self.fwd_bfs.start.pos]\n return None\n\n def retrace_bidirectional_path(self, fwd_node: Node, bwd_node: Node) -> Path:\n fwd_path = self.fwd_bfs.retrace_path(fwd_node)\n bwd_path = self.bwd_bfs.retrace_path(bwd_node)\n bwd_path.pop()\n bwd_path.reverse()\n path = fwd_path + bwd_path\n return path\n\n\nif __name__ == \"__main__\":\n # all coordinates are given in format [y,x]\n import doctest\n\n doctest.testmod()\n init = (0, 0)\n goal = (len(grid) - 1, len(grid[0]) - 1)\n for elem in grid:\n print(elem)\n\n start_bfs_time = time.time()\n bfs = BreadthFirstSearch(init, goal)\n path = bfs.search()\n bfs_time = time.time() - start_bfs_time\n\n print(\"Unidirectional BFS computation time : \", bfs_time)\n\n start_bd_bfs_time = time.time()\n bd_bfs = BidirectionalBreadthFirstSearch(init, goal)\n bd_path = bd_bfs.search()\n bd_bfs_time = time.time() - start_bd_bfs_time\n\n print(\"Bidirectional BFS computation time : \", bd_bfs_time)\n"} +{"Prompt":"Borvka's algorithm. Determines the minimum spanning tree MST of a graph using the Borvka's algorithm. Borvka's algorithm is a greedy algorithm for finding a minimum spanning tree in a connected graph, or a minimum spanning forest if a graph that is not connected. The time complexity of this algorithm is OELogV, where E represents the number of edges, while V represents the number of nodes. Onumberofedges Log numberofnodes The space complexity of this algorithm is OV E, since we have to keep a couple of lists whose sizes are equal to the number of nodes, as well as keep all the edges of a graph inside of the data structure itself. Borvka's algorithm gives us pretty much the same result as other MST Algorithms they all find the minimum spanning tree, and the time complexity is approximately the same. One advantage that Borvka's algorithm has compared to the alternatives is that it doesn't need to presort the edges or maintain a priority queue in order to find the minimum spanning tree. Even though that doesn't help its complexity, since it still passes the edges logE times, it is a bit simpler to code. Details: https:en.wikipedia.orgwikiBorC5AFvka27salgorithm Arguments: numofnodes the number of nodes in the graph Attributes: mnumofnodes the number of nodes in the graph. medges the list of edges. mcomponent the dictionary which stores the index of the component which a node belongs to. Adds an edge in the format first, second, edge weight to graph. self.medges.appendunode, vnode, weight def findcomponentself, unode: int int: Finds the component index of a given node if self.mcomponentunode ! unode: for k in self.mcomponent: self.mcomponentk self.findcomponentk def unionself, componentsize: listint, unode: int, vnode: int None: Performs Borvka's algorithm to find MST. Initialize additional lists required to algorithm. componentsize mstweight 0 minimumweightedge: listAny 1 self.mnumofnodes A list of components initialized to all of the nodes for node in rangeself.mnumofnodes: self.mcomponent.updatenode: node componentsize.append1 numofcomponents self.mnumofnodes while numofcomponents 1: for edge in self.medges: u, v, w edge ucomponent self.mcomponentu vcomponent self.mcomponentv if ucomponent ! vcomponent: g Graph8 for uvw in 0, 1, 10, 0, 2, 6, 0, 3, 5, 1, 3, 15, 2, 3, 4, ... 3, 4, 8, 4, 5, 10, 4, 6, 6, 4, 7, 5, 5, 7, 15, 6, 7, 4: ... g.addedgeuvw g.boruvka Added edge 0 3 Added weight: 5 BLANKLINE Added edge 0 1 Added weight: 10 BLANKLINE Added edge 2 3 Added weight: 4 BLANKLINE Added edge 4 7 Added weight: 5 BLANKLINE Added edge 4 5 Added weight: 10 BLANKLINE Added edge 6 7 Added weight: 4 BLANKLINE Added edge 3 4 Added weight: 8 BLANKLINE The total weight of the minimal spanning tree is: 46","Completions":"from __future__ import annotations\n\nfrom typing import Any\n\n\nclass Graph:\n def __init__(self, num_of_nodes: int) -> None:\n \"\"\"\n Arguments:\n num_of_nodes - the number of nodes in the graph\n Attributes:\n m_num_of_nodes - the number of nodes in the graph.\n m_edges - the list of edges.\n m_component - the dictionary which stores the index of the component which\n a node belongs to.\n \"\"\"\n\n self.m_num_of_nodes = num_of_nodes\n self.m_edges: list[list[int]] = []\n self.m_component: dict[int, int] = {}\n\n def add_edge(self, u_node: int, v_node: int, weight: int) -> None:\n \"\"\"Adds an edge in the format [first, second, edge weight] to graph.\"\"\"\n\n self.m_edges.append([u_node, v_node, weight])\n\n def find_component(self, u_node: int) -> int:\n \"\"\"Propagates a new component throughout a given component.\"\"\"\n\n if self.m_component[u_node] == u_node:\n return u_node\n return self.find_component(self.m_component[u_node])\n\n def set_component(self, u_node: int) -> None:\n \"\"\"Finds the component index of a given node\"\"\"\n\n if self.m_component[u_node] != u_node:\n for k in self.m_component:\n self.m_component[k] = self.find_component(k)\n\n def union(self, component_size: list[int], u_node: int, v_node: int) -> None:\n \"\"\"Union finds the roots of components for two nodes, compares the components\n in terms of size, and attaches the smaller one to the larger one to form\n single component\"\"\"\n\n if component_size[u_node] <= component_size[v_node]:\n self.m_component[u_node] = v_node\n component_size[v_node] += component_size[u_node]\n self.set_component(u_node)\n\n elif component_size[u_node] >= component_size[v_node]:\n self.m_component[v_node] = self.find_component(u_node)\n component_size[u_node] += component_size[v_node]\n self.set_component(v_node)\n\n def boruvka(self) -> None:\n \"\"\"Performs Bor\u016fvka's algorithm to find MST.\"\"\"\n\n # Initialize additional lists required to algorithm.\n component_size = []\n mst_weight = 0\n\n minimum_weight_edge: list[Any] = [-1] * self.m_num_of_nodes\n\n # A list of components (initialized to all of the nodes)\n for node in range(self.m_num_of_nodes):\n self.m_component.update({node: node})\n component_size.append(1)\n\n num_of_components = self.m_num_of_nodes\n\n while num_of_components > 1:\n for edge in self.m_edges:\n u, v, w = edge\n\n u_component = self.m_component[u]\n v_component = self.m_component[v]\n\n if u_component != v_component:\n \"\"\"If the current minimum weight edge of component u doesn't\n exist (is -1), or if it's greater than the edge we're\n observing right now, we will assign the value of the edge\n we're observing to it.\n\n If the current minimum weight edge of component v doesn't\n exist (is -1), or if it's greater than the edge we're\n observing right now, we will assign the value of the edge\n we're observing to it\"\"\"\n\n for component in (u_component, v_component):\n if (\n minimum_weight_edge[component] == -1\n or minimum_weight_edge[component][2] > w\n ):\n minimum_weight_edge[component] = [u, v, w]\n\n for edge in minimum_weight_edge:\n if isinstance(edge, list):\n u, v, w = edge\n\n u_component = self.m_component[u]\n v_component = self.m_component[v]\n\n if u_component != v_component:\n mst_weight += w\n self.union(component_size, u_component, v_component)\n print(f\"Added edge [{u} - {v}]\\nAdded weight: {w}\\n\")\n num_of_components -= 1\n\n minimum_weight_edge = [-1] * self.m_num_of_nodes\n print(f\"The total weight of the minimal spanning tree is: {mst_weight}\")\n\n\ndef test_vector() -> None:\n \"\"\"\n >>> g = Graph(8)\n >>> for u_v_w in ((0, 1, 10), (0, 2, 6), (0, 3, 5), (1, 3, 15), (2, 3, 4),\n ... (3, 4, 8), (4, 5, 10), (4, 6, 6), (4, 7, 5), (5, 7, 15), (6, 7, 4)):\n ... g.add_edge(*u_v_w)\n >>> g.boruvka()\n Added edge [0 - 3]\n Added weight: 5\n \n Added edge [0 - 1]\n Added weight: 10\n \n Added edge [2 - 3]\n Added weight: 4\n \n Added edge [4 - 7]\n Added weight: 5\n \n Added edge [4 - 5]\n Added weight: 10\n \n Added edge [6 - 7]\n Added weight: 4\n \n Added edge [3 - 4]\n Added weight: 8\n \n The total weight of the minimal spanning tree is: 46\n \"\"\"\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"!usrbinpython Author: OMKAR PATHAK from future import annotations from queue import Queue class Graph: def initself None: self.vertices: dictint, listint def printgraphself None: for i in self.vertices: printi, : , .joinstrj for j in self.verticesi def addedgeself, fromvertex: int, tovertex: int None: if fromvertex in self.vertices: self.verticesfromvertex.appendtovertex else: self.verticesfromvertex tovertex def bfsself, startvertex: int setint: initialize set for storing already visited vertices visited set create a first in first out queue to store all the vertices for BFS queue: Queue Queue mark the source node as visited and enqueue it visited.addstartvertex queue.putstartvertex while not queue.empty: vertex queue.get loop through all adjacent vertex and enqueue it if not yet visited for adjacentvertex in self.verticesvertex: if adjacentvertex not in visited: queue.putadjacentvertex visited.addadjacentvertex return visited if name main: from doctest import testmod testmodverboseTrue g Graph g.addedge0, 1 g.addedge0, 2 g.addedge1, 2 g.addedge2, 0 g.addedge2, 3 g.addedge3, 3 g.printgraph 0 : 1 2 1 : 2 2 : 0 3 3 : 3 assert sortedg.bfs2 0, 1, 2, 3","Completions":"#!\/usr\/bin\/python\n\n\"\"\" Author: OMKAR PATHAK \"\"\"\nfrom __future__ import annotations\n\nfrom queue import Queue\n\n\nclass Graph:\n def __init__(self) -> None:\n self.vertices: dict[int, list[int]] = {}\n\n def print_graph(self) -> None:\n \"\"\"\n prints adjacency list representation of graaph\n >>> g = Graph()\n >>> g.print_graph()\n >>> g.add_edge(0, 1)\n >>> g.print_graph()\n 0 : 1\n \"\"\"\n for i in self.vertices:\n print(i, \" : \", \" -> \".join([str(j) for j in self.vertices[i]]))\n\n def add_edge(self, from_vertex: int, to_vertex: int) -> None:\n \"\"\"\n adding the edge between two vertices\n >>> g = Graph()\n >>> g.print_graph()\n >>> g.add_edge(0, 1)\n >>> g.print_graph()\n 0 : 1\n \"\"\"\n if from_vertex in self.vertices:\n self.vertices[from_vertex].append(to_vertex)\n else:\n self.vertices[from_vertex] = [to_vertex]\n\n def bfs(self, start_vertex: int) -> set[int]:\n \"\"\"\n >>> g = Graph()\n >>> g.add_edge(0, 1)\n >>> g.add_edge(0, 1)\n >>> g.add_edge(0, 2)\n >>> g.add_edge(1, 2)\n >>> g.add_edge(2, 0)\n >>> g.add_edge(2, 3)\n >>> g.add_edge(3, 3)\n >>> sorted(g.bfs(2))\n [0, 1, 2, 3]\n \"\"\"\n # initialize set for storing already visited vertices\n visited = set()\n\n # create a first in first out queue to store all the vertices for BFS\n queue: Queue = Queue()\n\n # mark the source node as visited and enqueue it\n visited.add(start_vertex)\n queue.put(start_vertex)\n\n while not queue.empty():\n vertex = queue.get()\n\n # loop through all adjacent vertex and enqueue it if not yet visited\n for adjacent_vertex in self.vertices[vertex]:\n if adjacent_vertex not in visited:\n queue.put(adjacent_vertex)\n visited.add(adjacent_vertex)\n return visited\n\n\nif __name__ == \"__main__\":\n from doctest import testmod\n\n testmod(verbose=True)\n\n g = Graph()\n g.add_edge(0, 1)\n g.add_edge(0, 2)\n g.add_edge(1, 2)\n g.add_edge(2, 0)\n g.add_edge(2, 3)\n g.add_edge(3, 3)\n\n g.print_graph()\n # 0 : 1 -> 2\n # 1 : 2\n # 2 : 0 -> 3\n # 3 : 3\n\n assert sorted(g.bfs(2)) == [0, 1, 2, 3]\n"} +{"Prompt":"https:en.wikipedia.orgwikiBreadthfirstsearch pseudocode: breadthfirstsearchgraph G, start vertex s: all nodes initially unexplored mark s as explored let Q queue data structure, initialized with s while Q is nonempty: remove the first node of Q, call it v for each edgev, w: for w in graphv if w unexplored: mark w as explored add w to Q at the end Implementation of breadth first search using queue.Queue. ''.joinbreadthfirstsearchG, 'A' 'ABCDEF' Implementation of breadth first search using collection.queue. ''.joinbreadthfirstsearchwithdequeG, 'A' 'ABCDEF' breadthfirstsearch finished 10000 runs in 0.20999 seconds breadthfirstsearchwithdeque finished 10000 runs in 0.01421 seconds","Completions":"from __future__ import annotations\n\nfrom collections import deque\nfrom queue import Queue\nfrom timeit import timeit\n\nG = {\n \"A\": [\"B\", \"C\"],\n \"B\": [\"A\", \"D\", \"E\"],\n \"C\": [\"A\", \"F\"],\n \"D\": [\"B\"],\n \"E\": [\"B\", \"F\"],\n \"F\": [\"C\", \"E\"],\n}\n\n\ndef breadth_first_search(graph: dict, start: str) -> list[str]:\n \"\"\"\n Implementation of breadth first search using queue.Queue.\n\n >>> ''.join(breadth_first_search(G, 'A'))\n 'ABCDEF'\n \"\"\"\n explored = {start}\n result = [start]\n queue: Queue = Queue()\n queue.put(start)\n while not queue.empty():\n v = queue.get()\n for w in graph[v]:\n if w not in explored:\n explored.add(w)\n result.append(w)\n queue.put(w)\n return result\n\n\ndef breadth_first_search_with_deque(graph: dict, start: str) -> list[str]:\n \"\"\"\n Implementation of breadth first search using collection.queue.\n\n >>> ''.join(breadth_first_search_with_deque(G, 'A'))\n 'ABCDEF'\n \"\"\"\n visited = {start}\n result = [start]\n queue = deque([start])\n while queue:\n v = queue.popleft()\n for child in graph[v]:\n if child not in visited:\n visited.add(child)\n result.append(child)\n queue.append(child)\n return result\n\n\ndef benchmark_function(name: str) -> None:\n setup = f\"from __main__ import G, {name}\"\n number = 10000\n res = timeit(f\"{name}(G, 'A')\", setup=setup, number=number)\n print(f\"{name:<35} finished {number} runs in {res:.5f} seconds\")\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n\n benchmark_function(\"breadth_first_search\")\n benchmark_function(\"breadth_first_search_with_deque\")\n # breadth_first_search finished 10000 runs in 0.20999 seconds\n # breadth_first_search_with_deque finished 10000 runs in 0.01421 seconds\n"} +{"Prompt":"Breath First Search BFS can be used when finding the shortest path from a given source node to a target node in an unweighted graph. Graph is implemented as dictionary of adjacency lists. Also, Source vertex have to be defined upon initialization. mapping node to its parent in resulting breadth first tree This function is a helper for running breath first search on this graph. g Graphgraph, G g.breathfirstsearch g.parent 'G': None, 'C': 'G', 'A': 'C', 'F': 'C', 'B': 'A', 'E': 'A', 'D': 'B' This shortest path function returns a string, describing the result: 1. No path is found. The string is a human readable message to indicate this. 2. The shortest path is found. The string is in the form v1v2v3...vn, where v1 is the source vertex and vn is the target vertex, if it exists separately. g Graphgraph, G g.breathfirstsearch Case 1 No path is found. g.shortestpathFoo Traceback most recent call last: ... ValueError: No path from vertex: G to vertex: Foo Case 2 The path is found. g.shortestpathD 'GCABD' g.shortestpathG 'G'","Completions":"from __future__ import annotations\n\ngraph = {\n \"A\": [\"B\", \"C\", \"E\"],\n \"B\": [\"A\", \"D\", \"E\"],\n \"C\": [\"A\", \"F\", \"G\"],\n \"D\": [\"B\"],\n \"E\": [\"A\", \"B\", \"D\"],\n \"F\": [\"C\"],\n \"G\": [\"C\"],\n}\n\n\nclass Graph:\n def __init__(self, graph: dict[str, list[str]], source_vertex: str) -> None:\n \"\"\"\n Graph is implemented as dictionary of adjacency lists. Also,\n Source vertex have to be defined upon initialization.\n \"\"\"\n self.graph = graph\n # mapping node to its parent in resulting breadth first tree\n self.parent: dict[str, str | None] = {}\n self.source_vertex = source_vertex\n\n def breath_first_search(self) -> None:\n \"\"\"\n This function is a helper for running breath first search on this graph.\n >>> g = Graph(graph, \"G\")\n >>> g.breath_first_search()\n >>> g.parent\n {'G': None, 'C': 'G', 'A': 'C', 'F': 'C', 'B': 'A', 'E': 'A', 'D': 'B'}\n \"\"\"\n visited = {self.source_vertex}\n self.parent[self.source_vertex] = None\n queue = [self.source_vertex] # first in first out queue\n\n while queue:\n vertex = queue.pop(0)\n for adjacent_vertex in self.graph[vertex]:\n if adjacent_vertex not in visited:\n visited.add(adjacent_vertex)\n self.parent[adjacent_vertex] = vertex\n queue.append(adjacent_vertex)\n\n def shortest_path(self, target_vertex: str) -> str:\n \"\"\"\n This shortest path function returns a string, describing the result:\n 1.) No path is found. The string is a human readable message to indicate this.\n 2.) The shortest path is found. The string is in the form\n `v1(->v2->v3->...->vn)`, where v1 is the source vertex and vn is the target\n vertex, if it exists separately.\n\n >>> g = Graph(graph, \"G\")\n >>> g.breath_first_search()\n\n Case 1 - No path is found.\n >>> g.shortest_path(\"Foo\")\n Traceback (most recent call last):\n ...\n ValueError: No path from vertex: G to vertex: Foo\n\n Case 2 - The path is found.\n >>> g.shortest_path(\"D\")\n 'G->C->A->B->D'\n >>> g.shortest_path(\"G\")\n 'G'\n \"\"\"\n if target_vertex == self.source_vertex:\n return self.source_vertex\n\n target_vertex_parent = self.parent.get(target_vertex)\n if target_vertex_parent is None:\n msg = (\n f\"No path from vertex: {self.source_vertex} to vertex: {target_vertex}\"\n )\n raise ValueError(msg)\n\n return self.shortest_path(target_vertex_parent) + f\"->{target_vertex}\"\n\n\nif __name__ == \"__main__\":\n g = Graph(graph, \"G\")\n g.breath_first_search()\n print(g.shortest_path(\"D\"))\n print(g.shortest_path(\"G\"))\n print(g.shortest_path(\"Foo\"))\n"} +{"Prompt":"Breadthfirst search shortest path implementations. doctest: python m doctest v bfsshortestpath.py Manual test: python bfsshortestpath.py Find shortest path between start and goal nodes. Args: graph dict: nodelist of neighboring nodes keyvalue pairs. start: start node. goal: target node. Returns: Shortest path between start and goal nodes as a string of nodes. 'Not found' string if no path found. Example: bfsshortestpathdemograph, G, D 'G', 'C', 'A', 'B', 'D' bfsshortestpathdemograph, G, G 'G' bfsshortestpathdemograph, G, Unknown keep track of explored nodes keep track of all the paths to be checked return path if start is goal keeps looping until all possible paths have been checked pop the first path from the queue get the last node from the path go through all neighbour nodes, construct a new path and push it into the queue return path if neighbour is goal mark node as explored in case there's no path between the 2 nodes Find shortest path distance between start and target nodes. Args: graph: nodelist of neighboring nodes keyvalue pairs. start: node to start search from. target: node to search for. Returns: Number of edges in shortest path between start and target nodes. 1 if no path exists. Example: bfsshortestpathdistancedemograph, G, D 4 bfsshortestpathdistancedemograph, A, A 0 bfsshortestpathdistancedemograph, A, Unknown 1 Keep tab on distances from start node.","Completions":"demo_graph = {\n \"A\": [\"B\", \"C\", \"E\"],\n \"B\": [\"A\", \"D\", \"E\"],\n \"C\": [\"A\", \"F\", \"G\"],\n \"D\": [\"B\"],\n \"E\": [\"A\", \"B\", \"D\"],\n \"F\": [\"C\"],\n \"G\": [\"C\"],\n}\n\n\ndef bfs_shortest_path(graph: dict, start, goal) -> list[str]:\n \"\"\"Find shortest path between `start` and `goal` nodes.\n Args:\n graph (dict): node\/list of neighboring nodes key\/value pairs.\n start: start node.\n goal: target node.\n Returns:\n Shortest path between `start` and `goal` nodes as a string of nodes.\n 'Not found' string if no path found.\n Example:\n >>> bfs_shortest_path(demo_graph, \"G\", \"D\")\n ['G', 'C', 'A', 'B', 'D']\n >>> bfs_shortest_path(demo_graph, \"G\", \"G\")\n ['G']\n >>> bfs_shortest_path(demo_graph, \"G\", \"Unknown\")\n []\n \"\"\"\n # keep track of explored nodes\n explored = set()\n # keep track of all the paths to be checked\n queue = [[start]]\n\n # return path if start is goal\n if start == goal:\n return [start]\n\n # keeps looping until all possible paths have been checked\n while queue:\n # pop the first path from the queue\n path = queue.pop(0)\n # get the last node from the path\n node = path[-1]\n if node not in explored:\n neighbours = graph[node]\n # go through all neighbour nodes, construct a new path and\n # push it into the queue\n for neighbour in neighbours:\n new_path = list(path)\n new_path.append(neighbour)\n queue.append(new_path)\n # return path if neighbour is goal\n if neighbour == goal:\n return new_path\n\n # mark node as explored\n explored.add(node)\n\n # in case there's no path between the 2 nodes\n return []\n\n\ndef bfs_shortest_path_distance(graph: dict, start, target) -> int:\n \"\"\"Find shortest path distance between `start` and `target` nodes.\n Args:\n graph: node\/list of neighboring nodes key\/value pairs.\n start: node to start search from.\n target: node to search for.\n Returns:\n Number of edges in shortest path between `start` and `target` nodes.\n -1 if no path exists.\n Example:\n >>> bfs_shortest_path_distance(demo_graph, \"G\", \"D\")\n 4\n >>> bfs_shortest_path_distance(demo_graph, \"A\", \"A\")\n 0\n >>> bfs_shortest_path_distance(demo_graph, \"A\", \"Unknown\")\n -1\n \"\"\"\n if not graph or start not in graph or target not in graph:\n return -1\n if start == target:\n return 0\n queue = [start]\n visited = set(start)\n # Keep tab on distances from `start` node.\n dist = {start: 0, target: -1}\n while queue:\n node = queue.pop(0)\n if node == target:\n dist[target] = (\n dist[node] if dist[target] == -1 else min(dist[target], dist[node])\n )\n for adjacent in graph[node]:\n if adjacent not in visited:\n visited.add(adjacent)\n queue.append(adjacent)\n dist[adjacent] = dist[node] + 1\n return dist[target]\n\n\nif __name__ == \"__main__\":\n print(bfs_shortest_path(demo_graph, \"G\", \"D\")) # returns ['G', 'C', 'A', 'B', 'D']\n print(bfs_shortest_path_distance(demo_graph, \"G\", \"D\")) # returns 4\n"} +{"Prompt":"Finding the shortest path in 01graph in OE V which is faster than dijkstra. 01graph is the weighted graph with the weights equal to 0 or 1. Link: https:codeforces.comblogentry22276 Weighted directed graph edge. destinationvertex: int weight: int class AdjacencyList: Get all the vertices adjacent to the given one. return iterself.graphvertex property def sizeself: return self.size def addedgeself, fromvertex: int, tovertex: int, weight: int: if weight not in 0, 1: raise ValueErrorEdge weight must be either 0 or 1. if tovertex 0 or tovertex self.size: raise ValueErrorVertex indexes must be in 0; size. self.graphfromvertex.appendEdgetovertex, weight def getshortestpathself, startvertex: int, finishvertex: int int None: queue dequestartvertex distances: listint None None self.size distancesstartvertex 0 while queue: currentvertex queue.popleft currentdistance distancescurrentvertex if currentdistance is None: continue for edge in selfcurrentvertex: newdistance currentdistance edge.weight destvertexdistance distancesedge.destinationvertex if isinstancedestvertexdistance, int and newdistance destvertexdistance : continue distancesedge.destinationvertex newdistance if edge.weight 0: queue.appendleftedge.destinationvertex else: queue.appendedge.destinationvertex if distancesfinishvertex is None: raise ValueErrorNo path from startvertex to finishvertex. return distancesfinishvertex if name main: import doctest doctest.testmod","Completions":"from __future__ import annotations\n\nfrom collections import deque\nfrom collections.abc import Iterator\nfrom dataclasses import dataclass\n\n\n@dataclass\nclass Edge:\n \"\"\"Weighted directed graph edge.\"\"\"\n\n destination_vertex: int\n weight: int\n\n\nclass AdjacencyList:\n \"\"\"Graph adjacency list.\"\"\"\n\n def __init__(self, size: int):\n self._graph: list[list[Edge]] = [[] for _ in range(size)]\n self._size = size\n\n def __getitem__(self, vertex: int) -> Iterator[Edge]:\n \"\"\"Get all the vertices adjacent to the given one.\"\"\"\n return iter(self._graph[vertex])\n\n @property\n def size(self):\n return self._size\n\n def add_edge(self, from_vertex: int, to_vertex: int, weight: int):\n \"\"\"\n >>> g = AdjacencyList(2)\n >>> g.add_edge(0, 1, 0)\n >>> g.add_edge(1, 0, 1)\n >>> list(g[0])\n [Edge(destination_vertex=1, weight=0)]\n >>> list(g[1])\n [Edge(destination_vertex=0, weight=1)]\n >>> g.add_edge(0, 1, 2)\n Traceback (most recent call last):\n ...\n ValueError: Edge weight must be either 0 or 1.\n >>> g.add_edge(0, 2, 1)\n Traceback (most recent call last):\n ...\n ValueError: Vertex indexes must be in [0; size).\n \"\"\"\n if weight not in (0, 1):\n raise ValueError(\"Edge weight must be either 0 or 1.\")\n\n if to_vertex < 0 or to_vertex >= self.size:\n raise ValueError(\"Vertex indexes must be in [0; size).\")\n\n self._graph[from_vertex].append(Edge(to_vertex, weight))\n\n def get_shortest_path(self, start_vertex: int, finish_vertex: int) -> int | None:\n \"\"\"\n Return the shortest distance from start_vertex to finish_vertex in 0-1-graph.\n 1 1 1\n 0--------->3 6--------7>------->8\n | ^ ^ ^ |1\n | | | |0 v\n 0| |0 1| 9-------->10\n | | | ^ 1\n v | | |0\n 1--------->2<-------4------->5\n 0 1 1\n >>> g = AdjacencyList(11)\n >>> g.add_edge(0, 1, 0)\n >>> g.add_edge(0, 3, 1)\n >>> g.add_edge(1, 2, 0)\n >>> g.add_edge(2, 3, 0)\n >>> g.add_edge(4, 2, 1)\n >>> g.add_edge(4, 5, 1)\n >>> g.add_edge(4, 6, 1)\n >>> g.add_edge(5, 9, 0)\n >>> g.add_edge(6, 7, 1)\n >>> g.add_edge(7, 8, 1)\n >>> g.add_edge(8, 10, 1)\n >>> g.add_edge(9, 7, 0)\n >>> g.add_edge(9, 10, 1)\n >>> g.add_edge(1, 2, 2)\n Traceback (most recent call last):\n ...\n ValueError: Edge weight must be either 0 or 1.\n >>> g.get_shortest_path(0, 3)\n 0\n >>> g.get_shortest_path(0, 4)\n Traceback (most recent call last):\n ...\n ValueError: No path from start_vertex to finish_vertex.\n >>> g.get_shortest_path(4, 10)\n 2\n >>> g.get_shortest_path(4, 8)\n 2\n >>> g.get_shortest_path(0, 1)\n 0\n >>> g.get_shortest_path(1, 0)\n Traceback (most recent call last):\n ...\n ValueError: No path from start_vertex to finish_vertex.\n \"\"\"\n queue = deque([start_vertex])\n distances: list[int | None] = [None] * self.size\n distances[start_vertex] = 0\n\n while queue:\n current_vertex = queue.popleft()\n current_distance = distances[current_vertex]\n if current_distance is None:\n continue\n\n for edge in self[current_vertex]:\n new_distance = current_distance + edge.weight\n dest_vertex_distance = distances[edge.destination_vertex]\n if (\n isinstance(dest_vertex_distance, int)\n and new_distance >= dest_vertex_distance\n ):\n continue\n distances[edge.destination_vertex] = new_distance\n if edge.weight == 0:\n queue.appendleft(edge.destination_vertex)\n else:\n queue.append(edge.destination_vertex)\n\n if distances[finish_vertex] is None:\n raise ValueError(\"No path from start_vertex to finish_vertex.\")\n\n return distances[finish_vertex]\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Check if a graph is bipartite using depthfirst search DFS. Args: graph: Adjacency list representing the graph. Returns: True if bipartite, False otherwise. Checks if the graph can be divided into two sets of vertices, such that no two vertices within the same set are connected by an edge. Examples: FIXME: This test should pass. isbipartitedfsdefaultdictlist, 0: 1, 2, 1: 0, 3, 2: 0, 4 Traceback most recent call last: ... RuntimeError: dictionary changed size during iteration isbipartitedfsdefaultdictlist, 0: 1, 2, 1: 0, 3, 2: 0, 1 False isbipartitedfs True isbipartitedfs0: 1, 3, 1: 0, 2, 2: 1, 3, 3: 0, 2 True isbipartitedfs0: 1, 2, 3, 1: 0, 2, 2: 0, 1, 3, 3: 0, 2 False isbipartitedfs0: 4, 1: , 2: 4, 3: 4, 4: 0, 2, 3 True isbipartitedfs0: 1, 3, 1: 0, 2, 2: 1, 3, 3: 0, 2, 4: 0 False isbipartitedfs7: 1, 3, 1: 0, 2, 2: 1, 3, 3: 0, 2, 4: 0 Traceback most recent call last: ... KeyError: 0 FIXME: This test should fails with KeyError: 4. isbipartitedfs0: 1, 3, 1: 0, 2, 2: 1, 3, 3: 0, 2, 9: 0 False isbipartitedfs0: 1, 3, 1: 0, 2 Traceback most recent call last: ... KeyError: 1 isbipartitedfs1: 0, 2, 0: 1, 1, 1: 0, 2, 2: 1, 1 True isbipartitedfs0.9: 1, 3, 1: 0, 2, 2: 1, 3, 3: 0, 2 Traceback most recent call last: ... KeyError: 0 FIXME: This test should fails with TypeError: list indices must be integers or... isbipartitedfs0: 1.0, 3.0, 1.0: 0, 2.0, 2.0: 1.0, 3.0, 3.0: 0, 2.0 True isbipartitedfsa: 1, 3, b: 0, 2, c: 1, 3, d: 0, 2 Traceback most recent call last: ... KeyError: 1 isbipartitedfs0: b, d, 1: a, c, 2: b, d, 3: a, c Traceback most recent call last: ... KeyError: 'b' Perform DepthFirst Search DFS on the graph starting from a node. Args: node: The current node being visited. color: The color assigned to the current node. Returns: True if the graph is bipartite starting from the current node, False otherwise. Check if a graph is bipartite using a breadthfirst search BFS. Args: graph: Adjacency list representing the graph. Returns: True if bipartite, False otherwise. Check if the graph can be divided into two sets of vertices, such that no two vertices within the same set are connected by an edge. Examples: FIXME: This test should pass. isbipartitebfsdefaultdictlist, 0: 1, 2, 1: 0, 3, 2: 0, 4 Traceback most recent call last: ... RuntimeError: dictionary changed size during iteration isbipartitebfsdefaultdictlist, 0: 1, 2, 1: 0, 2, 2: 0, 1 False isbipartitebfs True isbipartitebfs0: 1, 3, 1: 0, 2, 2: 1, 3, 3: 0, 2 True isbipartitebfs0: 1, 2, 3, 1: 0, 2, 2: 0, 1, 3, 3: 0, 2 False isbipartitebfs0: 4, 1: , 2: 4, 3: 4, 4: 0, 2, 3 True isbipartitebfs0: 1, 3, 1: 0, 2, 2: 1, 3, 3: 0, 2, 4: 0 False isbipartitebfs7: 1, 3, 1: 0, 2, 2: 1, 3, 3: 0, 2, 4: 0 Traceback most recent call last: ... KeyError: 0 FIXME: This test should fails with KeyError: 4. isbipartitebfs0: 1, 3, 1: 0, 2, 2: 1, 3, 3: 0, 2, 9: 0 False isbipartitebfs0: 1, 3, 1: 0, 2 Traceback most recent call last: ... KeyError: 1 isbipartitebfs1: 0, 2, 0: 1, 1, 1: 0, 2, 2: 1, 1 True isbipartitebfs0.9: 1, 3, 1: 0, 2, 2: 1, 3, 3: 0, 2 Traceback most recent call last: ... KeyError: 0 FIXME: This test should fails with TypeError: list indices must be integers or... isbipartitebfs0: 1.0, 3.0, 1.0: 0, 2.0, 2.0: 1.0, 3.0, 3.0: 0, 2.0 True isbipartitebfsa: 1, 3, b: 0, 2, c: 1, 3, d: 0, 2 Traceback most recent call last: ... KeyError: 1 isbipartitebfs0: b, d, 1: a, c, 2: b, d, 3: a, c Traceback most recent call last: ... KeyError: 'b'","Completions":"from collections import defaultdict, deque\n\n\ndef is_bipartite_dfs(graph: defaultdict[int, list[int]]) -> bool:\n \"\"\"\n Check if a graph is bipartite using depth-first search (DFS).\n\n Args:\n graph: Adjacency list representing the graph.\n\n Returns:\n True if bipartite, False otherwise.\n\n Checks if the graph can be divided into two sets of vertices, such that no two\n vertices within the same set are connected by an edge.\n\n Examples:\n # FIXME: This test should pass.\n >>> is_bipartite_dfs(defaultdict(list, {0: [1, 2], 1: [0, 3], 2: [0, 4]}))\n Traceback (most recent call last):\n ...\n RuntimeError: dictionary changed size during iteration\n >>> is_bipartite_dfs(defaultdict(list, {0: [1, 2], 1: [0, 3], 2: [0, 1]}))\n False\n >>> is_bipartite_dfs({})\n True\n >>> is_bipartite_dfs({0: [1, 3], 1: [0, 2], 2: [1, 3], 3: [0, 2]})\n True\n >>> is_bipartite_dfs({0: [1, 2, 3], 1: [0, 2], 2: [0, 1, 3], 3: [0, 2]})\n False\n >>> is_bipartite_dfs({0: [4], 1: [], 2: [4], 3: [4], 4: [0, 2, 3]})\n True\n >>> is_bipartite_dfs({0: [1, 3], 1: [0, 2], 2: [1, 3], 3: [0, 2], 4: [0]})\n False\n >>> is_bipartite_dfs({7: [1, 3], 1: [0, 2], 2: [1, 3], 3: [0, 2], 4: [0]})\n Traceback (most recent call last):\n ...\n KeyError: 0\n\n # FIXME: This test should fails with KeyError: 4.\n >>> is_bipartite_dfs({0: [1, 3], 1: [0, 2], 2: [1, 3], 3: [0, 2], 9: [0]})\n False\n >>> is_bipartite_dfs({0: [-1, 3], 1: [0, -2]})\n Traceback (most recent call last):\n ...\n KeyError: -1\n >>> is_bipartite_dfs({-1: [0, 2], 0: [-1, 1], 1: [0, 2], 2: [-1, 1]})\n True\n >>> is_bipartite_dfs({0.9: [1, 3], 1: [0, 2], 2: [1, 3], 3: [0, 2]})\n Traceback (most recent call last):\n ...\n KeyError: 0\n\n # FIXME: This test should fails with TypeError: list indices must be integers or...\n >>> is_bipartite_dfs({0: [1.0, 3.0], 1.0: [0, 2.0], 2.0: [1.0, 3.0], 3.0: [0, 2.0]})\n True\n >>> is_bipartite_dfs({\"a\": [1, 3], \"b\": [0, 2], \"c\": [1, 3], \"d\": [0, 2]})\n Traceback (most recent call last):\n ...\n KeyError: 1\n >>> is_bipartite_dfs({0: [\"b\", \"d\"], 1: [\"a\", \"c\"], 2: [\"b\", \"d\"], 3: [\"a\", \"c\"]})\n Traceback (most recent call last):\n ...\n KeyError: 'b'\n \"\"\"\n\n def depth_first_search(node: int, color: int) -> bool:\n \"\"\"\n Perform Depth-First Search (DFS) on the graph starting from a node.\n\n Args:\n node: The current node being visited.\n color: The color assigned to the current node.\n\n Returns:\n True if the graph is bipartite starting from the current node,\n False otherwise.\n \"\"\"\n if visited[node] == -1:\n visited[node] = color\n for neighbor in graph[node]:\n if not depth_first_search(neighbor, 1 - color):\n return False\n return visited[node] == color\n\n visited: defaultdict[int, int] = defaultdict(lambda: -1)\n for node in graph:\n if visited[node] == -1 and not depth_first_search(node, 0):\n return False\n return True\n\n\ndef is_bipartite_bfs(graph: defaultdict[int, list[int]]) -> bool:\n \"\"\"\n Check if a graph is bipartite using a breadth-first search (BFS).\n\n Args:\n graph: Adjacency list representing the graph.\n\n Returns:\n True if bipartite, False otherwise.\n\n Check if the graph can be divided into two sets of vertices, such that no two\n vertices within the same set are connected by an edge.\n\n Examples:\n # FIXME: This test should pass.\n >>> is_bipartite_bfs(defaultdict(list, {0: [1, 2], 1: [0, 3], 2: [0, 4]}))\n Traceback (most recent call last):\n ...\n RuntimeError: dictionary changed size during iteration\n >>> is_bipartite_bfs(defaultdict(list, {0: [1, 2], 1: [0, 2], 2: [0, 1]}))\n False\n >>> is_bipartite_bfs({})\n True\n >>> is_bipartite_bfs({0: [1, 3], 1: [0, 2], 2: [1, 3], 3: [0, 2]})\n True\n >>> is_bipartite_bfs({0: [1, 2, 3], 1: [0, 2], 2: [0, 1, 3], 3: [0, 2]})\n False\n >>> is_bipartite_bfs({0: [4], 1: [], 2: [4], 3: [4], 4: [0, 2, 3]})\n True\n >>> is_bipartite_bfs({0: [1, 3], 1: [0, 2], 2: [1, 3], 3: [0, 2], 4: [0]})\n False\n >>> is_bipartite_bfs({7: [1, 3], 1: [0, 2], 2: [1, 3], 3: [0, 2], 4: [0]})\n Traceback (most recent call last):\n ...\n KeyError: 0\n\n # FIXME: This test should fails with KeyError: 4.\n >>> is_bipartite_bfs({0: [1, 3], 1: [0, 2], 2: [1, 3], 3: [0, 2], 9: [0]})\n False\n >>> is_bipartite_bfs({0: [-1, 3], 1: [0, -2]})\n Traceback (most recent call last):\n ...\n KeyError: -1\n >>> is_bipartite_bfs({-1: [0, 2], 0: [-1, 1], 1: [0, 2], 2: [-1, 1]})\n True\n >>> is_bipartite_bfs({0.9: [1, 3], 1: [0, 2], 2: [1, 3], 3: [0, 2]})\n Traceback (most recent call last):\n ...\n KeyError: 0\n\n # FIXME: This test should fails with TypeError: list indices must be integers or...\n >>> is_bipartite_bfs({0: [1.0, 3.0], 1.0: [0, 2.0], 2.0: [1.0, 3.0], 3.0: [0, 2.0]})\n True\n >>> is_bipartite_bfs({\"a\": [1, 3], \"b\": [0, 2], \"c\": [1, 3], \"d\": [0, 2]})\n Traceback (most recent call last):\n ...\n KeyError: 1\n >>> is_bipartite_bfs({0: [\"b\", \"d\"], 1: [\"a\", \"c\"], 2: [\"b\", \"d\"], 3: [\"a\", \"c\"]})\n Traceback (most recent call last):\n ...\n KeyError: 'b'\n \"\"\"\n visited: defaultdict[int, int] = defaultdict(lambda: -1)\n for node in graph:\n if visited[node] == -1:\n queue: deque[int] = deque()\n queue.append(node)\n visited[node] = 0\n while queue:\n curr_node = queue.popleft()\n for neighbor in graph[curr_node]:\n if visited[neighbor] == -1:\n visited[neighbor] = 1 - visited[curr_node]\n queue.append(neighbor)\n elif visited[neighbor] == visited[curr_node]:\n return False\n return True\n\n\nif __name__ == \"__main\":\n import doctest\n\n result = doctest.testmod()\n if result.failed:\n print(f\"{result.failed} test(s) failed.\")\n else:\n print(\"All tests passed!\")\n"} +{"Prompt":"Program to check if a cycle is present in a given graph Returns True if graph is cyclic else False checkcyclegraph0:, 1:0, 3, 2:0, 4, 3:5, 4:5, 5: False checkcyclegraph0:1, 2, 1:2, 2:0, 3, 3:3 True Keep track of visited nodes To detect a back edge, keep track of vertices currently in the recursion stack Recur for all neighbours. If any neighbour is visited and in recstk then graph is cyclic. graph 0:, 1:0, 3, 2:0, 4, 3:5, 4:5, 5: vertex, visited, recstk 0, set, set depthfirstsearchgraph, vertex, visited, recstk False Mark current node as visited and add to recursion stack The node needs to be removed from recursion stack before function ends","Completions":"def check_cycle(graph: dict) -> bool:\n \"\"\"\n Returns True if graph is cyclic else False\n >>> check_cycle(graph={0:[], 1:[0, 3], 2:[0, 4], 3:[5], 4:[5], 5:[]})\n False\n >>> check_cycle(graph={0:[1, 2], 1:[2], 2:[0, 3], 3:[3]})\n True\n \"\"\"\n # Keep track of visited nodes\n visited: set[int] = set()\n # To detect a back edge, keep track of vertices currently in the recursion stack\n rec_stk: set[int] = set()\n return any(\n node not in visited and depth_first_search(graph, node, visited, rec_stk)\n for node in graph\n )\n\n\ndef depth_first_search(graph: dict, vertex: int, visited: set, rec_stk: set) -> bool:\n \"\"\"\n Recur for all neighbours.\n If any neighbour is visited and in rec_stk then graph is cyclic.\n >>> graph = {0:[], 1:[0, 3], 2:[0, 4], 3:[5], 4:[5], 5:[]}\n >>> vertex, visited, rec_stk = 0, set(), set()\n >>> depth_first_search(graph, vertex, visited, rec_stk)\n False\n \"\"\"\n # Mark current node as visited and add to recursion stack\n visited.add(vertex)\n rec_stk.add(vertex)\n\n for node in graph[vertex]:\n if node not in visited:\n if depth_first_search(graph, node, visited, rec_stk):\n return True\n elif node in rec_stk:\n return True\n\n # The node needs to be removed from recursion stack before function ends\n rec_stk.remove(vertex)\n return False\n\n\nif __name__ == \"__main__\":\n from doctest import testmod\n\n testmod()\n"} +{"Prompt":"https:en.wikipedia.orgwikiComponentgraphtheory Finding connected components in graph Use depth first search to find all vertices being in the same component as initial vertex dfstestgraph1, 0, 5 False 0, 1, 3, 2 dfstestgraph2, 0, 6 False 0, 1, 3, 2 This function takes graph as a parameter and then returns the list of connected components connectedcomponentstestgraph1 0, 1, 3, 2, 4, 5, 6 connectedcomponentstestgraph2 0, 1, 3, 2, 4, 5","Completions":"test_graph_1 = {0: [1, 2], 1: [0, 3], 2: [0], 3: [1], 4: [5, 6], 5: [4, 6], 6: [4, 5]}\n\ntest_graph_2 = {0: [1, 2, 3], 1: [0, 3], 2: [0], 3: [0, 1], 4: [], 5: []}\n\n\ndef dfs(graph: dict, vert: int, visited: list) -> list:\n \"\"\"\n Use depth first search to find all vertices\n being in the same component as initial vertex\n >>> dfs(test_graph_1, 0, 5 * [False])\n [0, 1, 3, 2]\n >>> dfs(test_graph_2, 0, 6 * [False])\n [0, 1, 3, 2]\n \"\"\"\n\n visited[vert] = True\n connected_verts = []\n\n for neighbour in graph[vert]:\n if not visited[neighbour]:\n connected_verts += dfs(graph, neighbour, visited)\n\n return [vert, *connected_verts]\n\n\ndef connected_components(graph: dict) -> list:\n \"\"\"\n This function takes graph as a parameter\n and then returns the list of connected components\n >>> connected_components(test_graph_1)\n [[0, 1, 3, 2], [4, 5, 6]]\n >>> connected_components(test_graph_2)\n [[0, 1, 3, 2], [4], [5]]\n \"\"\"\n\n graph_size = len(graph)\n visited = graph_size * [False]\n components_list = []\n\n for i in range(graph_size):\n if not visited[i]:\n i_connected = dfs(graph, i, visited)\n components_list.append(i_connected)\n\n return components_list\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"LeetCode 133. Clone Graph https:leetcode.comproblemsclonegraph Given a reference of a node in a connected undirected graph. Return a deep copy clone of the graph. Each node in the graph contains a value int and a list ListNode of its neighbors. Node3.neighbors hashNode3 ! 0 True This function returns a clone of a connected undirected graph. clonegraphNode1 Nodevalue1, neighbors clonegraphNode1, Node2 Nodevalue1, neighborsNodevalue2, neighbors clonegraphNone is None True","Completions":"from dataclasses import dataclass\n\n\n@dataclass\nclass Node:\n value: int = 0\n neighbors: list[\"Node\"] | None = None\n\n def __post_init__(self) -> None:\n \"\"\"\n >>> Node(3).neighbors\n []\n \"\"\"\n self.neighbors = self.neighbors or []\n\n def __hash__(self) -> int:\n \"\"\"\n >>> hash(Node(3)) != 0\n True\n \"\"\"\n return id(self)\n\n\ndef clone_graph(node: Node | None) -> Node | None:\n \"\"\"\n This function returns a clone of a connected undirected graph.\n >>> clone_graph(Node(1))\n Node(value=1, neighbors=[])\n >>> clone_graph(Node(1, [Node(2)]))\n Node(value=1, neighbors=[Node(value=2, neighbors=[])])\n >>> clone_graph(None) is None\n True\n \"\"\"\n if not node:\n return None\n\n originals_to_clones = {} # map nodes to clones\n\n stack = [node]\n\n while stack:\n original = stack.pop()\n\n if original in originals_to_clones:\n continue\n\n originals_to_clones[original] = Node(original.value)\n\n stack.extend(original.neighbors or [])\n\n for original, clone in originals_to_clones.items():\n for neighbor in original.neighbors or []:\n cloned_neighbor = originals_to_clones[neighbor]\n\n if not clone.neighbors:\n clone.neighbors = []\n\n clone.neighbors.append(cloned_neighbor)\n\n return originals_to_clones[node]\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Non recursive implementation of a DFS algorithm. from future import annotations def depthfirstsearchgraph: dict, start: str setstr: explored, stack setstart, start while stack: v stack.pop explored.addv Differences from BFS: 1 pop last element instead of first one 2 add adjacent elements to stack without exploring them for adj in reversedgraphv: if adj not in explored: stack.appendadj return explored G A: B, C, D, B: A, D, E, C: A, F, D: B, D, E: B, F, F: C, E, G, G: F, if name main: import doctest doctest.testmod printdepthfirstsearchG, A","Completions":"from __future__ import annotations\n\n\ndef depth_first_search(graph: dict, start: str) -> set[str]:\n \"\"\"Depth First Search on Graph\n :param graph: directed graph in dictionary format\n :param start: starting vertex as a string\n :returns: the trace of the search\n >>> input_G = { \"A\": [\"B\", \"C\", \"D\"], \"B\": [\"A\", \"D\", \"E\"],\n ... \"C\": [\"A\", \"F\"], \"D\": [\"B\", \"D\"], \"E\": [\"B\", \"F\"],\n ... \"F\": [\"C\", \"E\", \"G\"], \"G\": [\"F\"] }\n >>> output_G = list({'A', 'B', 'C', 'D', 'E', 'F', 'G'})\n >>> all(x in output_G for x in list(depth_first_search(input_G, \"A\")))\n True\n >>> all(x in output_G for x in list(depth_first_search(input_G, \"G\")))\n True\n \"\"\"\n explored, stack = set(start), [start]\n\n while stack:\n v = stack.pop()\n explored.add(v)\n # Differences from BFS:\n # 1) pop last element instead of first one\n # 2) add adjacent elements to stack without exploring them\n for adj in reversed(graph[v]):\n if adj not in explored:\n stack.append(adj)\n return explored\n\n\nG = {\n \"A\": [\"B\", \"C\", \"D\"],\n \"B\": [\"A\", \"D\", \"E\"],\n \"C\": [\"A\", \"F\"],\n \"D\": [\"B\", \"D\"],\n \"E\": [\"B\", \"F\"],\n \"F\": [\"C\", \"E\", \"G\"],\n \"G\": [\"F\"],\n}\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n print(depth_first_search(G, \"A\"))\n"} +{"Prompt":"!usrbinpython Author: OMKAR PATHAK class Graph: def initself: self.vertex for printing the Graph vertices def printgraphself None: printself.vertex for i in self.vertex: printi, , .joinstrj for j in self.vertexi for adding the edge between two vertices def addedgeself, fromvertex: int, tovertex: int None: check if vertex is already present, if fromvertex in self.vertex: self.vertexfromvertex.appendtovertex else: else make a new vertex self.vertexfromvertex tovertex def dfsself None: visited array for storing already visited nodes visited False lenself.vertex call the recursive helper function for i in rangelenself.vertex: if not visitedi: self.dfsrecursivei, visited def dfsrecursiveself, startvertex: int, visited: list None: mark start vertex as visited visitedstartvertex True printstartvertex, end Recur for all the vertices that are adjacent to this node for i in self.vertex: if not visitedi: print , end self.dfsrecursivei, visited if name main: import doctest doctest.testmod g Graph g.addedge0, 1 g.addedge0, 2 g.addedge1, 2 g.addedge2, 0 g.addedge2, 3 g.addedge3, 3 g.printgraph printDFS: g.dfs","Completions":"#!\/usr\/bin\/python\n\n\"\"\" Author: OMKAR PATHAK \"\"\"\n\n\nclass Graph:\n def __init__(self):\n self.vertex = {}\n\n # for printing the Graph vertices\n def print_graph(self) -> None:\n \"\"\"\n Print the graph vertices.\n\n Example:\n >>> g = Graph()\n >>> g.add_edge(0, 1)\n >>> g.add_edge(0, 2)\n >>> g.add_edge(1, 2)\n >>> g.add_edge(2, 0)\n >>> g.add_edge(2, 3)\n >>> g.add_edge(3, 3)\n >>> g.print_graph()\n {0: [1, 2], 1: [2], 2: [0, 3], 3: [3]}\n 0 -> 1 -> 2\n 1 -> 2\n 2 -> 0 -> 3\n 3 -> 3\n \"\"\"\n print(self.vertex)\n for i in self.vertex:\n print(i, \" -> \", \" -> \".join([str(j) for j in self.vertex[i]]))\n\n # for adding the edge between two vertices\n def add_edge(self, from_vertex: int, to_vertex: int) -> None:\n \"\"\"\n Add an edge between two vertices.\n\n :param from_vertex: The source vertex.\n :param to_vertex: The destination vertex.\n\n Example:\n >>> g = Graph()\n >>> g.add_edge(0, 1)\n >>> g.add_edge(0, 2)\n >>> g.print_graph()\n {0: [1, 2]}\n 0 -> 1 -> 2\n \"\"\"\n # check if vertex is already present,\n if from_vertex in self.vertex:\n self.vertex[from_vertex].append(to_vertex)\n else:\n # else make a new vertex\n self.vertex[from_vertex] = [to_vertex]\n\n def dfs(self) -> None:\n \"\"\"\n Perform depth-first search (DFS) traversal on the graph\n and print the visited vertices.\n\n Example:\n >>> g = Graph()\n >>> g.add_edge(0, 1)\n >>> g.add_edge(0, 2)\n >>> g.add_edge(1, 2)\n >>> g.add_edge(2, 0)\n >>> g.add_edge(2, 3)\n >>> g.add_edge(3, 3)\n >>> g.dfs()\n 0 1 2 3\n \"\"\"\n # visited array for storing already visited nodes\n visited = [False] * len(self.vertex)\n\n # call the recursive helper function\n for i in range(len(self.vertex)):\n if not visited[i]:\n self.dfs_recursive(i, visited)\n\n def dfs_recursive(self, start_vertex: int, visited: list) -> None:\n \"\"\"\n Perform a recursive depth-first search (DFS) traversal on the graph.\n\n :param start_vertex: The starting vertex for the traversal.\n :param visited: A list to track visited vertices.\n\n Example:\n >>> g = Graph()\n >>> g.add_edge(0, 1)\n >>> g.add_edge(0, 2)\n >>> g.add_edge(1, 2)\n >>> g.add_edge(2, 0)\n >>> g.add_edge(2, 3)\n >>> g.add_edge(3, 3)\n >>> visited = [False] * len(g.vertex)\n >>> g.dfs_recursive(0, visited)\n 0 1 2 3\n \"\"\"\n # mark start vertex as visited\n visited[start_vertex] = True\n\n print(start_vertex, end=\"\")\n\n # Recur for all the vertices that are adjacent to this node\n for i in self.vertex:\n if not visited[i]:\n print(\" \", end=\"\")\n self.dfs_recursive(i, visited)\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n\n g = Graph()\n g.add_edge(0, 1)\n g.add_edge(0, 2)\n g.add_edge(1, 2)\n g.add_edge(2, 0)\n g.add_edge(2, 3)\n g.add_edge(3, 3)\n\n g.print_graph()\n print(\"DFS:\")\n g.dfs()\n"} +{"Prompt":"pseudocode DIJKSTRAgraph G, start vertex s, destination vertex d: all nodes initially unexplored 1 let H min heap data structure, initialized with 0 and s here 0 indicates the distance from start vertex s 2 while H is nonempty: 3 remove the first node and cost of H, call it U and cost 4 if U has been previously explored: 5 go to the while loop, line 2 Once a node is explored there is no need to make it again 6 mark U as explored 7 if U is d: 8 return cost total cost from start to destination vertex 9 for each edgeU, V: ccost of edgeU,V for V in graphU 10 if V explored: 11 go to next V in line 9 12 totalcost cost c 13 add totalcost,V to H You can think at cost as a distance where Dijkstra finds the shortest distance between vertices s and v in a graph G. The use of a min heap as H guarantees that if a vertex has already been explored there will be no other path with shortest distance, that happens because heapq.heappop will always return the next vertex with the shortest distance, considering that the heap stores not only the distance between previous vertex and current vertex but the entire distance between each vertex that makes up the path from start vertex to target vertex. Return the cost of the shortest path between vertices start and end. dijkstraG, E, C 6 dijkstraG2, E, F 3 dijkstraG3, E, F 3 G2 B: C, 1, C: D, 1, D: F, 1, E: B, 1, F, 3, F: , r Layout of G3: E 1 B 1 C 1 D 1 F 2 G 1","Completions":"import heapq\n\n\ndef dijkstra(graph, start, end):\n \"\"\"Return the cost of the shortest path between vertices start and end.\n\n >>> dijkstra(G, \"E\", \"C\")\n 6\n >>> dijkstra(G2, \"E\", \"F\")\n 3\n >>> dijkstra(G3, \"E\", \"F\")\n 3\n \"\"\"\n\n heap = [(0, start)] # cost from start node,end node\n visited = set()\n while heap:\n (cost, u) = heapq.heappop(heap)\n if u in visited:\n continue\n visited.add(u)\n if u == end:\n return cost\n for v, c in graph[u]:\n if v in visited:\n continue\n next_item = cost + c\n heapq.heappush(heap, (next_item, v))\n return -1\n\n\nG = {\n \"A\": [[\"B\", 2], [\"C\", 5]],\n \"B\": [[\"A\", 2], [\"D\", 3], [\"E\", 1], [\"F\", 1]],\n \"C\": [[\"A\", 5], [\"F\", 3]],\n \"D\": [[\"B\", 3]],\n \"E\": [[\"B\", 4], [\"F\", 3]],\n \"F\": [[\"C\", 3], [\"E\", 3]],\n}\n\nr\"\"\"\nLayout of G2:\n\nE -- 1 --> B -- 1 --> C -- 1 --> D -- 1 --> F\n \\ \/\\\n \\ ||\n ----------------- 3 --------------------\n\"\"\"\nG2 = {\n \"B\": [[\"C\", 1]],\n \"C\": [[\"D\", 1]],\n \"D\": [[\"F\", 1]],\n \"E\": [[\"B\", 1], [\"F\", 3]],\n \"F\": [],\n}\n\nr\"\"\"\nLayout of G3:\n\nE -- 1 --> B -- 1 --> C -- 1 --> D -- 1 --> F\n \\ \/\\\n \\ ||\n -------- 2 ---------> G ------- 1 ------\n\"\"\"\nG3 = {\n \"B\": [[\"C\", 1]],\n \"C\": [[\"D\", 1]],\n \"D\": [[\"F\", 1]],\n \"E\": [[\"B\", 1], [\"G\", 2]],\n \"F\": [],\n \"G\": [[\"F\", 1]],\n}\n\nshort_distance = dijkstra(G, \"E\", \"C\")\nprint(short_distance) # E -- 3 --> F -- 3 --> C == 6\n\nshort_distance = dijkstra(G2, \"E\", \"F\")\nprint(short_distance) # E -- 3 --> F == 3\n\nshort_distance = dijkstra(G3, \"E\", \"F\")\nprint(short_distance) # E -- 2 --> G -- 1 --> F == 3\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Title: Dijkstra's Algorithm for finding single source shortest path from scratch Author: Shubham Malik References: https:en.wikipedia.orgwikiDijkstra27salgorithm For storing the vertex set to retrieve node with the lowest distance Based on Min Heap Priority queue class constructor method. Examples: priorityqueuetest PriorityQueue priorityqueuetest.cursize 0 priorityqueuetest.array priorityqueuetest.pos Conditional boolean method to determine if the priority queue is empty or not. Examples: priorityqueuetest PriorityQueue priorityqueuetest.isempty True priorityqueuetest.insert2, 'A' priorityqueuetest.isempty False Sorts the queue array so that the minimum element is root. Examples: priorityqueuetest PriorityQueue priorityqueuetest.cursize 3 priorityqueuetest.pos 'A': 0, 'B': 1, 'C': 2 priorityqueuetest.array 5, 'A', 10, 'B', 15, 'C' priorityqueuetest.minheapify0 Traceback most recent call last: ... TypeError: 'list' object is not callable priorityqueuetest.array 5, 'A', 10, 'B', 15, 'C' priorityqueuetest.array 10, 'A', 5, 'B', 15, 'C' priorityqueuetest.minheapify0 Traceback most recent call last: ... TypeError: 'list' object is not callable priorityqueuetest.array 10, 'A', 5, 'B', 15, 'C' priorityqueuetest.array 10, 'A', 15, 'B', 5, 'C' priorityqueuetest.minheapify0 Traceback most recent call last: ... TypeError: 'list' object is not callable priorityqueuetest.array 10, 'A', 15, 'B', 5, 'C' priorityqueuetest.array 10, 'A', 5, 'B' priorityqueuetest.cursize lenpriorityqueuetest.array priorityqueuetest.pos 'A': 0, 'B': 1 priorityqueuetest.minheapify0 Traceback most recent call last: ... TypeError: 'list' object is not callable priorityqueuetest.array 10, 'A', 5, 'B' Inserts a node into the Priority Queue. Examples: priorityqueuetest PriorityQueue priorityqueuetest.insert10, 'A' priorityqueuetest.array 10, 'A' priorityqueuetest.insert15, 'B' priorityqueuetest.array 10, 'A', 15, 'B' priorityqueuetest.insert5, 'C' priorityqueuetest.array 5, 'C', 10, 'A', 15, 'B' Removes and returns the min element at top of priority queue. Examples: priorityqueuetest PriorityQueue priorityqueuetest.array 10, 'A', 15, 'B' priorityqueuetest.cursize lenpriorityqueuetest.array priorityqueuetest.pos 'A': 0, 'B': 1 priorityqueuetest.insert5, 'C' priorityqueuetest.extractmin 'C' priorityqueuetest.array0 15, 'B' Returns the index of left child Examples: priorityqueuetest PriorityQueue priorityqueuetest.left0 1 priorityqueuetest.left1 3 Returns the index of right child Examples: priorityqueuetest PriorityQueue priorityqueuetest.right0 2 priorityqueuetest.right1 4 Returns the index of parent Examples: priorityqueuetest PriorityQueue priorityqueuetest.par1 0 priorityqueuetest.par2 1 priorityqueuetest.par4 2 Swaps array elements at indices i and j, update the pos Examples: priorityqueuetest PriorityQueue priorityqueuetest.array 10, 'A', 15, 'B' priorityqueuetest.cursize lenpriorityqueuetest.array priorityqueuetest.pos 'A': 0, 'B': 1 priorityqueuetest.swap0, 1 priorityqueuetest.array 15, 'B', 10, 'A' priorityqueuetest.pos 'A': 1, 'B': 0 Decrease the key value for a given tuple, assuming the newd is at most oldd. Examples: priorityqueuetest PriorityQueue priorityqueuetest.array 10, 'A', 15, 'B' priorityqueuetest.cursize lenpriorityqueuetest.array priorityqueuetest.pos 'A': 0, 'B': 1 priorityqueuetest.decreasekey10, 'A', 5 priorityqueuetest.array 5, 'A', 15, 'B' assuming the newd is atmost oldd Graph class constructor Examples: graphtest Graph1 graphtest.numnodes 1 graphtest.dist 0 graphtest.par 1 graphtest.adjList To store the distance from source vertex Add edge going from node u to v and v to u with weight w: u w v, v w u Examples: graphtest Graph1 graphtest.addedge1, 2, 1 graphtest.addedge2, 3, 2 graphtest.adjList 1: 2, 1, 2: 1, 1, 3, 2, 3: 2, 2 Check if u already in graph Assuming undirected graph Show the graph: u vw Examples: graphtest Graph1 graphtest.addedge1, 2, 1 graphtest.showgraph 1 21 2 11 graphtest.addedge2, 3, 2 graphtest.showgraph 1 21 2 11 32 3 22 Dijkstra algorithm Examples: graphtest Graph3 graphtest.addedge0, 1, 2 graphtest.addedge1, 2, 2 graphtest.dijkstra0 Distance from node: 0 Node 0 has distance: 0 Node 1 has distance: 2 Node 2 has distance: 4 graphtest.dist 0, 2, 4 graphtest Graph2 graphtest.addedge0, 1, 2 graphtest.dijkstra0 Distance from node: 0 Node 0 has distance: 0 Node 1 has distance: 2 graphtest.dist 0, 2 graphtest Graph3 graphtest.addedge0, 1, 2 graphtest.dijkstra0 Distance from node: 0 Node 0 has distance: 0 Node 1 has distance: 2 Node 2 has distance: 0 graphtest.dist 0, 2, 0 graphtest Graph3 graphtest.addedge0, 1, 2 graphtest.addedge1, 2, 2 graphtest.addedge0, 2, 1 graphtest.dijkstra0 Distance from node: 0 Node 0 has distance: 0 Node 1 has distance: 2 Node 2 has distance: 1 graphtest.dist 0, 2, 1 graphtest Graph4 graphtest.addedge0, 1, 4 graphtest.addedge1, 2, 2 graphtest.addedge2, 3, 1 graphtest.addedge0, 2, 3 graphtest.dijkstra0 Distance from node: 0 Node 0 has distance: 0 Node 1 has distance: 4 Node 2 has distance: 3 Node 3 has distance: 4 graphtest.dist 0, 4, 3, 4 graphtest Graph4 graphtest.addedge0, 1, 4 graphtest.addedge1, 2, 2 graphtest.addedge2, 3, 1 graphtest.addedge0, 2, 7 graphtest.dijkstra0 Distance from node: 0 Node 0 has distance: 0 Node 1 has distance: 4 Node 2 has distance: 6 Node 3 has distance: 7 graphtest.dist 0, 4, 6, 7 Flush old junk values in par src is the source node Update the distance of all the neighbours of u and if their prev dist was INFINITY then push them in Q Show the shortest distances from src Show the distances from src to all other nodes in a graph Examples: graphtest Graph1 graphtest.showdistances0 Distance from node: 0 Node 0 has distance: 0 Shows the shortest path from src to dest. WARNING: Use it after calling dijkstra. Examples: graphtest Graph4 graphtest.addedge0, 1, 1 graphtest.addedge1, 2, 2 graphtest.addedge2, 3, 3 graphtest.dijkstra0 Distance from node: 0 Node 0 has distance: 0 Node 1 has distance: 1 Node 2 has distance: 3 Node 3 has distance: 6 graphtest.showpath0, 3 doctest: NORMALIZEWHITESPACE Path to reach 3 from 0 0 1 2 3 Total cost of path: 6 Backtracking from dest to src OUTPUT 0 14 78 1 04 28 711 7 08 111 61 87 2 18 37 82 54 3 27 49 514 8 22 66 77 5 24 314 410 62 4 39 510 6 52 71 86 Distance from node: 0 Node 0 has distance: 0 Node 1 has distance: 4 Node 2 has distance: 12 Node 3 has distance: 19 Node 4 has distance: 21 Node 5 has distance: 11 Node 6 has distance: 9 Node 7 has distance: 8 Node 8 has distance: 14 Path to reach 4 from 0 0 7 6 5 4 Total cost of path: 21","Completions":"# Title: Dijkstra's Algorithm for finding single source shortest path from scratch\n# Author: Shubham Malik\n# References: https:\/\/en.wikipedia.org\/wiki\/Dijkstra%27s_algorithm\n\nimport math\nimport sys\n\n# For storing the vertex set to retrieve node with the lowest distance\n\n\nclass PriorityQueue:\n # Based on Min Heap\n def __init__(self):\n \"\"\"\n Priority queue class constructor method.\n\n Examples:\n >>> priority_queue_test = PriorityQueue()\n >>> priority_queue_test.cur_size\n 0\n >>> priority_queue_test.array\n []\n >>> priority_queue_test.pos\n {}\n \"\"\"\n self.cur_size = 0\n self.array = []\n self.pos = {} # To store the pos of node in array\n\n def is_empty(self):\n \"\"\"\n Conditional boolean method to determine if the priority queue is empty or not.\n\n Examples:\n >>> priority_queue_test = PriorityQueue()\n >>> priority_queue_test.is_empty()\n True\n >>> priority_queue_test.insert((2, 'A'))\n >>> priority_queue_test.is_empty()\n False\n \"\"\"\n return self.cur_size == 0\n\n def min_heapify(self, idx):\n \"\"\"\n Sorts the queue array so that the minimum element is root.\n\n Examples:\n >>> priority_queue_test = PriorityQueue()\n >>> priority_queue_test.cur_size = 3\n >>> priority_queue_test.pos = {'A': 0, 'B': 1, 'C': 2}\n\n >>> priority_queue_test.array = [(5, 'A'), (10, 'B'), (15, 'C')]\n >>> priority_queue_test.min_heapify(0)\n Traceback (most recent call last):\n ...\n TypeError: 'list' object is not callable\n >>> priority_queue_test.array\n [(5, 'A'), (10, 'B'), (15, 'C')]\n\n >>> priority_queue_test.array = [(10, 'A'), (5, 'B'), (15, 'C')]\n >>> priority_queue_test.min_heapify(0)\n Traceback (most recent call last):\n ...\n TypeError: 'list' object is not callable\n >>> priority_queue_test.array\n [(10, 'A'), (5, 'B'), (15, 'C')]\n\n >>> priority_queue_test.array = [(10, 'A'), (15, 'B'), (5, 'C')]\n >>> priority_queue_test.min_heapify(0)\n Traceback (most recent call last):\n ...\n TypeError: 'list' object is not callable\n >>> priority_queue_test.array\n [(10, 'A'), (15, 'B'), (5, 'C')]\n\n >>> priority_queue_test.array = [(10, 'A'), (5, 'B')]\n >>> priority_queue_test.cur_size = len(priority_queue_test.array)\n >>> priority_queue_test.pos = {'A': 0, 'B': 1}\n >>> priority_queue_test.min_heapify(0)\n Traceback (most recent call last):\n ...\n TypeError: 'list' object is not callable\n >>> priority_queue_test.array\n [(10, 'A'), (5, 'B')]\n \"\"\"\n lc = self.left(idx)\n rc = self.right(idx)\n if lc < self.cur_size and self.array(lc)[0] < self.array[idx][0]:\n smallest = lc\n else:\n smallest = idx\n if rc < self.cur_size and self.array(rc)[0] < self.array[smallest][0]:\n smallest = rc\n if smallest != idx:\n self.swap(idx, smallest)\n self.min_heapify(smallest)\n\n def insert(self, tup):\n \"\"\"\n Inserts a node into the Priority Queue.\n\n Examples:\n >>> priority_queue_test = PriorityQueue()\n >>> priority_queue_test.insert((10, 'A'))\n >>> priority_queue_test.array\n [(10, 'A')]\n >>> priority_queue_test.insert((15, 'B'))\n >>> priority_queue_test.array\n [(10, 'A'), (15, 'B')]\n >>> priority_queue_test.insert((5, 'C'))\n >>> priority_queue_test.array\n [(5, 'C'), (10, 'A'), (15, 'B')]\n \"\"\"\n self.pos[tup[1]] = self.cur_size\n self.cur_size += 1\n self.array.append((sys.maxsize, tup[1]))\n self.decrease_key((sys.maxsize, tup[1]), tup[0])\n\n def extract_min(self):\n \"\"\"\n Removes and returns the min element at top of priority queue.\n\n Examples:\n >>> priority_queue_test = PriorityQueue()\n >>> priority_queue_test.array = [(10, 'A'), (15, 'B')]\n >>> priority_queue_test.cur_size = len(priority_queue_test.array)\n >>> priority_queue_test.pos = {'A': 0, 'B': 1}\n >>> priority_queue_test.insert((5, 'C'))\n >>> priority_queue_test.extract_min()\n 'C'\n >>> priority_queue_test.array[0]\n (15, 'B')\n \"\"\"\n min_node = self.array[0][1]\n self.array[0] = self.array[self.cur_size - 1]\n self.cur_size -= 1\n self.min_heapify(1)\n del self.pos[min_node]\n return min_node\n\n def left(self, i):\n \"\"\"\n Returns the index of left child\n\n Examples:\n >>> priority_queue_test = PriorityQueue()\n >>> priority_queue_test.left(0)\n 1\n >>> priority_queue_test.left(1)\n 3\n \"\"\"\n return 2 * i + 1\n\n def right(self, i):\n \"\"\"\n Returns the index of right child\n\n Examples:\n >>> priority_queue_test = PriorityQueue()\n >>> priority_queue_test.right(0)\n 2\n >>> priority_queue_test.right(1)\n 4\n \"\"\"\n return 2 * i + 2\n\n def par(self, i):\n \"\"\"\n Returns the index of parent\n\n Examples:\n >>> priority_queue_test = PriorityQueue()\n >>> priority_queue_test.par(1)\n 0\n >>> priority_queue_test.par(2)\n 1\n >>> priority_queue_test.par(4)\n 2\n \"\"\"\n return math.floor(i \/ 2)\n\n def swap(self, i, j):\n \"\"\"\n Swaps array elements at indices i and j, update the pos{}\n\n Examples:\n >>> priority_queue_test = PriorityQueue()\n >>> priority_queue_test.array = [(10, 'A'), (15, 'B')]\n >>> priority_queue_test.cur_size = len(priority_queue_test.array)\n >>> priority_queue_test.pos = {'A': 0, 'B': 1}\n >>> priority_queue_test.swap(0, 1)\n >>> priority_queue_test.array\n [(15, 'B'), (10, 'A')]\n >>> priority_queue_test.pos\n {'A': 1, 'B': 0}\n \"\"\"\n self.pos[self.array[i][1]] = j\n self.pos[self.array[j][1]] = i\n temp = self.array[i]\n self.array[i] = self.array[j]\n self.array[j] = temp\n\n def decrease_key(self, tup, new_d):\n \"\"\"\n Decrease the key value for a given tuple, assuming the new_d is at most old_d.\n\n Examples:\n >>> priority_queue_test = PriorityQueue()\n >>> priority_queue_test.array = [(10, 'A'), (15, 'B')]\n >>> priority_queue_test.cur_size = len(priority_queue_test.array)\n >>> priority_queue_test.pos = {'A': 0, 'B': 1}\n >>> priority_queue_test.decrease_key((10, 'A'), 5)\n >>> priority_queue_test.array\n [(5, 'A'), (15, 'B')]\n \"\"\"\n idx = self.pos[tup[1]]\n # assuming the new_d is atmost old_d\n self.array[idx] = (new_d, tup[1])\n while idx > 0 and self.array[self.par(idx)][0] > self.array[idx][0]:\n self.swap(idx, self.par(idx))\n idx = self.par(idx)\n\n\nclass Graph:\n def __init__(self, num):\n \"\"\"\n Graph class constructor\n\n Examples:\n >>> graph_test = Graph(1)\n >>> graph_test.num_nodes\n 1\n >>> graph_test.dist\n [0]\n >>> graph_test.par\n [-1]\n >>> graph_test.adjList\n {}\n \"\"\"\n self.adjList = {} # To store graph: u -> (v,w)\n self.num_nodes = num # Number of nodes in graph\n # To store the distance from source vertex\n self.dist = [0] * self.num_nodes\n self.par = [-1] * self.num_nodes # To store the path\n\n def add_edge(self, u, v, w):\n \"\"\"\n Add edge going from node u to v and v to u with weight w: u (w)-> v, v (w) -> u\n\n Examples:\n >>> graph_test = Graph(1)\n >>> graph_test.add_edge(1, 2, 1)\n >>> graph_test.add_edge(2, 3, 2)\n >>> graph_test.adjList\n {1: [(2, 1)], 2: [(1, 1), (3, 2)], 3: [(2, 2)]}\n \"\"\"\n # Check if u already in graph\n if u in self.adjList:\n self.adjList[u].append((v, w))\n else:\n self.adjList[u] = [(v, w)]\n\n # Assuming undirected graph\n if v in self.adjList:\n self.adjList[v].append((u, w))\n else:\n self.adjList[v] = [(u, w)]\n\n def show_graph(self):\n \"\"\"\n Show the graph: u -> v(w)\n\n Examples:\n >>> graph_test = Graph(1)\n >>> graph_test.add_edge(1, 2, 1)\n >>> graph_test.show_graph()\n 1 -> 2(1)\n 2 -> 1(1)\n >>> graph_test.add_edge(2, 3, 2)\n >>> graph_test.show_graph()\n 1 -> 2(1)\n 2 -> 1(1) -> 3(2)\n 3 -> 2(2)\n \"\"\"\n for u in self.adjList:\n print(u, \"->\", \" -> \".join(str(f\"{v}({w})\") for v, w in self.adjList[u]))\n\n def dijkstra(self, src):\n \"\"\"\n Dijkstra algorithm\n\n Examples:\n >>> graph_test = Graph(3)\n >>> graph_test.add_edge(0, 1, 2)\n >>> graph_test.add_edge(1, 2, 2)\n >>> graph_test.dijkstra(0)\n Distance from node: 0\n Node 0 has distance: 0\n Node 1 has distance: 2\n Node 2 has distance: 4\n >>> graph_test.dist\n [0, 2, 4]\n\n >>> graph_test = Graph(2)\n >>> graph_test.add_edge(0, 1, 2)\n >>> graph_test.dijkstra(0)\n Distance from node: 0\n Node 0 has distance: 0\n Node 1 has distance: 2\n >>> graph_test.dist\n [0, 2]\n\n >>> graph_test = Graph(3)\n >>> graph_test.add_edge(0, 1, 2)\n >>> graph_test.dijkstra(0)\n Distance from node: 0\n Node 0 has distance: 0\n Node 1 has distance: 2\n Node 2 has distance: 0\n >>> graph_test.dist\n [0, 2, 0]\n\n >>> graph_test = Graph(3)\n >>> graph_test.add_edge(0, 1, 2)\n >>> graph_test.add_edge(1, 2, 2)\n >>> graph_test.add_edge(0, 2, 1)\n >>> graph_test.dijkstra(0)\n Distance from node: 0\n Node 0 has distance: 0\n Node 1 has distance: 2\n Node 2 has distance: 1\n >>> graph_test.dist\n [0, 2, 1]\n\n >>> graph_test = Graph(4)\n >>> graph_test.add_edge(0, 1, 4)\n >>> graph_test.add_edge(1, 2, 2)\n >>> graph_test.add_edge(2, 3, 1)\n >>> graph_test.add_edge(0, 2, 3)\n >>> graph_test.dijkstra(0)\n Distance from node: 0\n Node 0 has distance: 0\n Node 1 has distance: 4\n Node 2 has distance: 3\n Node 3 has distance: 4\n >>> graph_test.dist\n [0, 4, 3, 4]\n\n >>> graph_test = Graph(4)\n >>> graph_test.add_edge(0, 1, 4)\n >>> graph_test.add_edge(1, 2, 2)\n >>> graph_test.add_edge(2, 3, 1)\n >>> graph_test.add_edge(0, 2, 7)\n >>> graph_test.dijkstra(0)\n Distance from node: 0\n Node 0 has distance: 0\n Node 1 has distance: 4\n Node 2 has distance: 6\n Node 3 has distance: 7\n >>> graph_test.dist\n [0, 4, 6, 7]\n \"\"\"\n # Flush old junk values in par[]\n self.par = [-1] * self.num_nodes\n # src is the source node\n self.dist[src] = 0\n q = PriorityQueue()\n q.insert((0, src)) # (dist from src, node)\n for u in self.adjList:\n if u != src:\n self.dist[u] = sys.maxsize # Infinity\n self.par[u] = -1\n\n while not q.is_empty():\n u = q.extract_min() # Returns node with the min dist from source\n # Update the distance of all the neighbours of u and\n # if their prev dist was INFINITY then push them in Q\n for v, w in self.adjList[u]:\n new_dist = self.dist[u] + w\n if self.dist[v] > new_dist:\n if self.dist[v] == sys.maxsize:\n q.insert((new_dist, v))\n else:\n q.decrease_key((self.dist[v], v), new_dist)\n self.dist[v] = new_dist\n self.par[v] = u\n\n # Show the shortest distances from src\n self.show_distances(src)\n\n def show_distances(self, src):\n \"\"\"\n Show the distances from src to all other nodes in a graph\n\n Examples:\n >>> graph_test = Graph(1)\n >>> graph_test.show_distances(0)\n Distance from node: 0\n Node 0 has distance: 0\n \"\"\"\n print(f\"Distance from node: {src}\")\n for u in range(self.num_nodes):\n print(f\"Node {u} has distance: {self.dist[u]}\")\n\n def show_path(self, src, dest):\n \"\"\"\n Shows the shortest path from src to dest.\n WARNING: Use it *after* calling dijkstra.\n\n Examples:\n >>> graph_test = Graph(4)\n >>> graph_test.add_edge(0, 1, 1)\n >>> graph_test.add_edge(1, 2, 2)\n >>> graph_test.add_edge(2, 3, 3)\n >>> graph_test.dijkstra(0)\n Distance from node: 0\n Node 0 has distance: 0\n Node 1 has distance: 1\n Node 2 has distance: 3\n Node 3 has distance: 6\n >>> graph_test.show_path(0, 3) # doctest: +NORMALIZE_WHITESPACE\n ----Path to reach 3 from 0----\n 0 -> 1 -> 2 -> 3\n Total cost of path: 6\n \"\"\"\n path = []\n cost = 0\n temp = dest\n # Backtracking from dest to src\n while self.par[temp] != -1:\n path.append(temp)\n if temp != src:\n for v, w in self.adjList[temp]:\n if v == self.par[temp]:\n cost += w\n break\n temp = self.par[temp]\n path.append(src)\n path.reverse()\n\n print(f\"----Path to reach {dest} from {src}----\")\n for u in path:\n print(f\"{u}\", end=\" \")\n if u != dest:\n print(\"-> \", end=\"\")\n\n print(\"\\nTotal cost of path: \", cost)\n\n\nif __name__ == \"__main__\":\n from doctest import testmod\n\n testmod()\n graph = Graph(9)\n graph.add_edge(0, 1, 4)\n graph.add_edge(0, 7, 8)\n graph.add_edge(1, 2, 8)\n graph.add_edge(1, 7, 11)\n graph.add_edge(2, 3, 7)\n graph.add_edge(2, 8, 2)\n graph.add_edge(2, 5, 4)\n graph.add_edge(3, 4, 9)\n graph.add_edge(3, 5, 14)\n graph.add_edge(4, 5, 10)\n graph.add_edge(5, 6, 2)\n graph.add_edge(6, 7, 1)\n graph.add_edge(6, 8, 6)\n graph.add_edge(7, 8, 7)\n graph.show_graph()\n graph.dijkstra(0)\n graph.show_path(0, 4)\n\n# OUTPUT\n# 0 -> 1(4) -> 7(8)\n# 1 -> 0(4) -> 2(8) -> 7(11)\n# 7 -> 0(8) -> 1(11) -> 6(1) -> 8(7)\n# 2 -> 1(8) -> 3(7) -> 8(2) -> 5(4)\n# 3 -> 2(7) -> 4(9) -> 5(14)\n# 8 -> 2(2) -> 6(6) -> 7(7)\n# 5 -> 2(4) -> 3(14) -> 4(10) -> 6(2)\n# 4 -> 3(9) -> 5(10)\n# 6 -> 5(2) -> 7(1) -> 8(6)\n# Distance from node: 0\n# Node 0 has distance: 0\n# Node 1 has distance: 4\n# Node 2 has distance: 12\n# Node 3 has distance: 19\n# Node 4 has distance: 21\n# Node 5 has distance: 11\n# Node 6 has distance: 9\n# Node 7 has distance: 8\n# Node 8 has distance: 14\n# ----Path to reach 4 from 0----\n# 0 -> 7 -> 6 -> 5 -> 4\n# Total cost of path: 21\n"} +{"Prompt":"graph Graph2 graph.vertices 2 lengraph.graph 2 lengraph.graph0 2 Graph0.printsolution doctest: NORMALIZEWHITESPACE Vertex \t Distance from Source A utility function to find the vertex with minimum distance value, from the set of vertices not yet included in shortest path tree. Graph3.minimumdistance1, 2, 3, False, False, True 0 Initialize minimum distance for next node Search not nearest vertex not in the shortest path tree Function that implements Dijkstra's single source shortest path algorithm for a graph represented using adjacency matrix representation. Graph4.dijkstra1 doctest: NORMALIZEWHITESPACE Vertex Distance from Source 0 \t\t 10000000 1 \t\t 0 2 \t\t 10000000 3 \t\t 10000000 Update dist value of the adjacent vertices of the picked vertex only if the current distance is greater than new distance and the vertex in not in the shortest path tree","Completions":"from __future__ import annotations\n\n\nclass Graph:\n def __init__(self, vertices: int) -> None:\n \"\"\"\n >>> graph = Graph(2)\n >>> graph.vertices\n 2\n >>> len(graph.graph)\n 2\n >>> len(graph.graph[0])\n 2\n \"\"\"\n self.vertices = vertices\n self.graph = [[0] * vertices for _ in range(vertices)]\n\n def print_solution(self, distances_from_source: list[int]) -> None:\n \"\"\"\n >>> Graph(0).print_solution([]) # doctest: +NORMALIZE_WHITESPACE\n Vertex \t Distance from Source\n \"\"\"\n print(\"Vertex \\t Distance from Source\")\n for vertex in range(self.vertices):\n print(vertex, \"\\t\\t\", distances_from_source[vertex])\n\n def minimum_distance(\n self, distances_from_source: list[int], visited: list[bool]\n ) -> int:\n \"\"\"\n A utility function to find the vertex with minimum distance value, from the set\n of vertices not yet included in shortest path tree.\n\n >>> Graph(3).minimum_distance([1, 2, 3], [False, False, True])\n 0\n \"\"\"\n\n # Initialize minimum distance for next node\n minimum = 1e7\n min_index = 0\n\n # Search not nearest vertex not in the shortest path tree\n for vertex in range(self.vertices):\n if distances_from_source[vertex] < minimum and visited[vertex] is False:\n minimum = distances_from_source[vertex]\n min_index = vertex\n return min_index\n\n def dijkstra(self, source: int) -> None:\n \"\"\"\n Function that implements Dijkstra's single source shortest path algorithm for a\n graph represented using adjacency matrix representation.\n\n >>> Graph(4).dijkstra(1) # doctest: +NORMALIZE_WHITESPACE\n Vertex Distance from Source\n 0 \t\t 10000000\n 1 \t\t 0\n 2 \t\t 10000000\n 3 \t\t 10000000\n \"\"\"\n\n distances = [int(1e7)] * self.vertices # distances from the source\n distances[source] = 0\n visited = [False] * self.vertices\n\n for _ in range(self.vertices):\n u = self.minimum_distance(distances, visited)\n visited[u] = True\n\n # Update dist value of the adjacent vertices\n # of the picked vertex only if the current\n # distance is greater than new distance and\n # the vertex in not in the shortest path tree\n for v in range(self.vertices):\n if (\n self.graph[u][v] > 0\n and visited[v] is False\n and distances[v] > distances[u] + self.graph[u][v]\n ):\n distances[v] = distances[u] + self.graph[u][v]\n\n self.print_solution(distances)\n\n\nif __name__ == \"__main__\":\n graph = Graph(9)\n graph.graph = [\n [0, 4, 0, 0, 0, 0, 0, 8, 0],\n [4, 0, 8, 0, 0, 0, 0, 11, 0],\n [0, 8, 0, 7, 0, 4, 0, 0, 2],\n [0, 0, 7, 0, 9, 14, 0, 0, 0],\n [0, 0, 0, 9, 0, 10, 0, 0, 0],\n [0, 0, 4, 14, 10, 0, 2, 0, 0],\n [0, 0, 0, 0, 0, 2, 0, 1, 6],\n [8, 11, 0, 0, 0, 0, 1, 0, 7],\n [0, 0, 2, 0, 0, 0, 6, 7, 0],\n ]\n graph.dijkstra(0)\n"} +{"Prompt":"This script implements the Dijkstra algorithm on a binary grid. The grid consists of 0s and 1s, where 1 represents a walkable node and 0 represents an obstacle. The algorithm finds the shortest path from a start node to a destination node. Diagonal movement can be allowed or disallowed. Implements Dijkstra's algorithm on a binary grid. Args: grid np.ndarray: A 2D numpy array representing the grid. 1 represents a walkable node and 0 represents an obstacle. source Tupleint, int: A tuple representing the start node. destination Tupleint, int: A tuple representing the destination node. allowdiagonal bool: A boolean determining whether diagonal movements are allowed. Returns: TupleUnionfloat, int, ListTupleint, int: The shortest distance from the start node to the destination node and the shortest path as a list of nodes. dijkstranp.array1, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 2, 2, False 4.0, 0, 0, 0, 1, 1, 1, 2, 1, 2, 2 dijkstranp.array1, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 2, 2, True 2.0, 0, 0, 1, 1, 2, 2 dijkstranp.array1, 1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 2, 2, False 4.0, 0, 0, 0, 1, 0, 2, 1, 2, 2, 2","Completions":"from heapq import heappop, heappush\n\nimport numpy as np\n\n\ndef dijkstra(\n grid: np.ndarray,\n source: tuple[int, int],\n destination: tuple[int, int],\n allow_diagonal: bool,\n) -> tuple[float | int, list[tuple[int, int]]]:\n \"\"\"\n Implements Dijkstra's algorithm on a binary grid.\n\n Args:\n grid (np.ndarray): A 2D numpy array representing the grid.\n 1 represents a walkable node and 0 represents an obstacle.\n source (Tuple[int, int]): A tuple representing the start node.\n destination (Tuple[int, int]): A tuple representing the\n destination node.\n allow_diagonal (bool): A boolean determining whether\n diagonal movements are allowed.\n\n Returns:\n Tuple[Union[float, int], List[Tuple[int, int]]]:\n The shortest distance from the start node to the destination node\n and the shortest path as a list of nodes.\n\n >>> dijkstra(np.array([[1, 1, 1], [0, 1, 0], [0, 1, 1]]), (0, 0), (2, 2), False)\n (4.0, [(0, 0), (0, 1), (1, 1), (2, 1), (2, 2)])\n\n >>> dijkstra(np.array([[1, 1, 1], [0, 1, 0], [0, 1, 1]]), (0, 0), (2, 2), True)\n (2.0, [(0, 0), (1, 1), (2, 2)])\n\n >>> dijkstra(np.array([[1, 1, 1], [0, 0, 1], [0, 1, 1]]), (0, 0), (2, 2), False)\n (4.0, [(0, 0), (0, 1), (0, 2), (1, 2), (2, 2)])\n \"\"\"\n rows, cols = grid.shape\n dx = [-1, 1, 0, 0]\n dy = [0, 0, -1, 1]\n if allow_diagonal:\n dx += [-1, -1, 1, 1]\n dy += [-1, 1, -1, 1]\n\n queue, visited = [(0, source)], set()\n matrix = np.full((rows, cols), np.inf)\n matrix[source] = 0\n predecessors = np.empty((rows, cols), dtype=object)\n predecessors[source] = None\n\n while queue:\n (dist, (x, y)) = heappop(queue)\n if (x, y) in visited:\n continue\n visited.add((x, y))\n\n if (x, y) == destination:\n path = []\n while (x, y) != source:\n path.append((x, y))\n x, y = predecessors[x, y]\n path.append(source) # add the source manually\n path.reverse()\n return matrix[destination], path\n\n for i in range(len(dx)):\n nx, ny = x + dx[i], y + dy[i]\n if 0 <= nx < rows and 0 <= ny < cols:\n next_node = grid[nx][ny]\n if next_node == 1 and matrix[nx, ny] > dist + 1:\n heappush(queue, (dist + 1, (nx, ny)))\n matrix[nx, ny] = dist + 1\n predecessors[nx, ny] = (x, y)\n\n return np.inf, []\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Here we will add our edges containing with the following parameters: vertex closest to source, vertex closest to sink and flow capacity through that edge ... This is a sample depth first search to be used at maxflow Here we calculate the flow that reaches the sink Example to use Will be a bipartite graph, than it has the vertices near the source4 and the vertices near the sink4 Here we make a graphs with 10 vertexsource and sink includes Now we add the vertices next to the font in the font with 1 capacity in this edge source source vertices We will do the same thing for the vertices near the sink, but from vertex to sink sink vertices sink Finally we add the verices near the sink to the vertices near the source. source vertices sink vertices Now we can know that is the maximum flowsource sink","Completions":"INF = float(\"inf\")\n\n\nclass Dinic:\n def __init__(self, n):\n self.lvl = [0] * n\n self.ptr = [0] * n\n self.q = [0] * n\n self.adj = [[] for _ in range(n)]\n\n \"\"\"\n Here we will add our edges containing with the following parameters:\n vertex closest to source, vertex closest to sink and flow capacity\n through that edge ...\n \"\"\"\n\n def add_edge(self, a, b, c, rcap=0):\n self.adj[a].append([b, len(self.adj[b]), c, 0])\n self.adj[b].append([a, len(self.adj[a]) - 1, rcap, 0])\n\n # This is a sample depth first search to be used at max_flow\n def depth_first_search(self, vertex, sink, flow):\n if vertex == sink or not flow:\n return flow\n\n for i in range(self.ptr[vertex], len(self.adj[vertex])):\n e = self.adj[vertex][i]\n if self.lvl[e[0]] == self.lvl[vertex] + 1:\n p = self.depth_first_search(e[0], sink, min(flow, e[2] - e[3]))\n if p:\n self.adj[vertex][i][3] += p\n self.adj[e[0]][e[1]][3] -= p\n return p\n self.ptr[vertex] = self.ptr[vertex] + 1\n return 0\n\n # Here we calculate the flow that reaches the sink\n def max_flow(self, source, sink):\n flow, self.q[0] = 0, source\n for l in range(31): # noqa: E741 l = 30 maybe faster for random data\n while True:\n self.lvl, self.ptr = [0] * len(self.q), [0] * len(self.q)\n qi, qe, self.lvl[source] = 0, 1, 1\n while qi < qe and not self.lvl[sink]:\n v = self.q[qi]\n qi += 1\n for e in self.adj[v]:\n if not self.lvl[e[0]] and (e[2] - e[3]) >> (30 - l):\n self.q[qe] = e[0]\n qe += 1\n self.lvl[e[0]] = self.lvl[v] + 1\n\n p = self.depth_first_search(source, sink, INF)\n while p:\n flow += p\n p = self.depth_first_search(source, sink, INF)\n\n if not self.lvl[sink]:\n break\n\n return flow\n\n\n# Example to use\n\n\"\"\"\nWill be a bipartite graph, than it has the vertices near the source(4)\nand the vertices near the sink(4)\n\"\"\"\n# Here we make a graphs with 10 vertex(source and sink includes)\ngraph = Dinic(10)\nsource = 0\nsink = 9\n\"\"\"\nNow we add the vertices next to the font in the font with 1 capacity in this edge\n(source -> source vertices)\n\"\"\"\nfor vertex in range(1, 5):\n graph.add_edge(source, vertex, 1)\n\"\"\"\nWe will do the same thing for the vertices near the sink, but from vertex to sink\n(sink vertices -> sink)\n\"\"\"\nfor vertex in range(5, 9):\n graph.add_edge(vertex, sink, 1)\n\"\"\"\nFinally we add the verices near the sink to the vertices near the source.\n(source vertices -> sink vertices)\n\"\"\"\nfor vertex in range(1, 5):\n graph.add_edge(vertex, vertex + 4, 1)\n\n# Now we can know that is the maximum flow(source -> sink)\nprint(graph.max_flow(source, sink))\n"} +{"Prompt":"the default weight is 1 if not assigned but all the implementation is weighted adding vertices and edges adding the weight is optional handles repetition handles if the input does not exist if no destination is meant the default value is 1 check if there is any non isolated nodes check if all the children are visited check if se have reached the starting point c is the count of nodes you want and if you leave it or pass 1 to the function the count will be random from 10 to 10000 every vertex has max 100 edges check if there is any non isolated nodes check if all the children are visited check if se have reached the starting point check if there is any non isolated nodes check if all the children are visited check if se have reached the starting point check if there is any non isolated nodes check if all the children are visited check if se have reached the starting point adding vertices and edges adding the weight is optional handles repetition check if the u exists if there already is a edge if u does not exist add the other way if there already is a edge if u does not exist handles if the input does not exist the other way round if no destination is meant the default value is 1 check if there is any non isolated nodes check if all the children are visited check if se have reached the starting point c is the count of nodes you want and if you leave it or pass 1 to the function the count will be random from 10 to 10000 every vertex has max 100 edges check if there is any non isolated nodes check if all the children are visited check if se have reached the starting point check if there is any non isolated nodes check if all the children are visited check if se have reached the starting point","Completions":"from collections import deque\nfrom math import floor\nfrom random import random\nfrom time import time\n\n# the default weight is 1 if not assigned but all the implementation is weighted\n\n\nclass DirectedGraph:\n def __init__(self):\n self.graph = {}\n\n # adding vertices and edges\n # adding the weight is optional\n # handles repetition\n def add_pair(self, u, v, w=1):\n if self.graph.get(u):\n if self.graph[u].count([w, v]) == 0:\n self.graph[u].append([w, v])\n else:\n self.graph[u] = [[w, v]]\n if not self.graph.get(v):\n self.graph[v] = []\n\n def all_nodes(self):\n return list(self.graph)\n\n # handles if the input does not exist\n def remove_pair(self, u, v):\n if self.graph.get(u):\n for _ in self.graph[u]:\n if _[1] == v:\n self.graph[u].remove(_)\n\n # if no destination is meant the default value is -1\n def dfs(self, s=-2, d=-1):\n if s == d:\n return []\n stack = []\n visited = []\n if s == -2:\n s = next(iter(self.graph))\n stack.append(s)\n visited.append(s)\n ss = s\n\n while True:\n # check if there is any non isolated nodes\n if len(self.graph[s]) != 0:\n ss = s\n for node in self.graph[s]:\n if visited.count(node[1]) < 1:\n if node[1] == d:\n visited.append(d)\n return visited\n else:\n stack.append(node[1])\n visited.append(node[1])\n ss = node[1]\n break\n\n # check if all the children are visited\n if s == ss:\n stack.pop()\n if len(stack) != 0:\n s = stack[len(stack) - 1]\n else:\n s = ss\n\n # check if se have reached the starting point\n if len(stack) == 0:\n return visited\n\n # c is the count of nodes you want and if you leave it or pass -1 to the function\n # the count will be random from 10 to 10000\n def fill_graph_randomly(self, c=-1):\n if c == -1:\n c = floor(random() * 10000) + 10\n for i in range(c):\n # every vertex has max 100 edges\n for _ in range(floor(random() * 102) + 1):\n n = floor(random() * c) + 1\n if n != i:\n self.add_pair(i, n, 1)\n\n def bfs(self, s=-2):\n d = deque()\n visited = []\n if s == -2:\n s = next(iter(self.graph))\n d.append(s)\n visited.append(s)\n while d:\n s = d.popleft()\n if len(self.graph[s]) != 0:\n for node in self.graph[s]:\n if visited.count(node[1]) < 1:\n d.append(node[1])\n visited.append(node[1])\n return visited\n\n def in_degree(self, u):\n count = 0\n for x in self.graph:\n for y in self.graph[x]:\n if y[1] == u:\n count += 1\n return count\n\n def out_degree(self, u):\n return len(self.graph[u])\n\n def topological_sort(self, s=-2):\n stack = []\n visited = []\n if s == -2:\n s = next(iter(self.graph))\n stack.append(s)\n visited.append(s)\n ss = s\n sorted_nodes = []\n\n while True:\n # check if there is any non isolated nodes\n if len(self.graph[s]) != 0:\n ss = s\n for node in self.graph[s]:\n if visited.count(node[1]) < 1:\n stack.append(node[1])\n visited.append(node[1])\n ss = node[1]\n break\n\n # check if all the children are visited\n if s == ss:\n sorted_nodes.append(stack.pop())\n if len(stack) != 0:\n s = stack[len(stack) - 1]\n else:\n s = ss\n\n # check if se have reached the starting point\n if len(stack) == 0:\n return sorted_nodes\n\n def cycle_nodes(self):\n stack = []\n visited = []\n s = next(iter(self.graph))\n stack.append(s)\n visited.append(s)\n parent = -2\n indirect_parents = []\n ss = s\n on_the_way_back = False\n anticipating_nodes = set()\n\n while True:\n # check if there is any non isolated nodes\n if len(self.graph[s]) != 0:\n ss = s\n for node in self.graph[s]:\n if (\n visited.count(node[1]) > 0\n and node[1] != parent\n and indirect_parents.count(node[1]) > 0\n and not on_the_way_back\n ):\n len_stack = len(stack) - 1\n while len_stack >= 0:\n if stack[len_stack] == node[1]:\n anticipating_nodes.add(node[1])\n break\n else:\n anticipating_nodes.add(stack[len_stack])\n len_stack -= 1\n if visited.count(node[1]) < 1:\n stack.append(node[1])\n visited.append(node[1])\n ss = node[1]\n break\n\n # check if all the children are visited\n if s == ss:\n stack.pop()\n on_the_way_back = True\n if len(stack) != 0:\n s = stack[len(stack) - 1]\n else:\n on_the_way_back = False\n indirect_parents.append(parent)\n parent = s\n s = ss\n\n # check if se have reached the starting point\n if len(stack) == 0:\n return list(anticipating_nodes)\n\n def has_cycle(self):\n stack = []\n visited = []\n s = next(iter(self.graph))\n stack.append(s)\n visited.append(s)\n parent = -2\n indirect_parents = []\n ss = s\n on_the_way_back = False\n anticipating_nodes = set()\n\n while True:\n # check if there is any non isolated nodes\n if len(self.graph[s]) != 0:\n ss = s\n for node in self.graph[s]:\n if (\n visited.count(node[1]) > 0\n and node[1] != parent\n and indirect_parents.count(node[1]) > 0\n and not on_the_way_back\n ):\n len_stack_minus_one = len(stack) - 1\n while len_stack_minus_one >= 0:\n if stack[len_stack_minus_one] == node[1]:\n anticipating_nodes.add(node[1])\n break\n else:\n return True\n if visited.count(node[1]) < 1:\n stack.append(node[1])\n visited.append(node[1])\n ss = node[1]\n break\n\n # check if all the children are visited\n if s == ss:\n stack.pop()\n on_the_way_back = True\n if len(stack) != 0:\n s = stack[len(stack) - 1]\n else:\n on_the_way_back = False\n indirect_parents.append(parent)\n parent = s\n s = ss\n\n # check if se have reached the starting point\n if len(stack) == 0:\n return False\n\n def dfs_time(self, s=-2, e=-1):\n begin = time()\n self.dfs(s, e)\n end = time()\n return end - begin\n\n def bfs_time(self, s=-2):\n begin = time()\n self.bfs(s)\n end = time()\n return end - begin\n\n\nclass Graph:\n def __init__(self):\n self.graph = {}\n\n # adding vertices and edges\n # adding the weight is optional\n # handles repetition\n def add_pair(self, u, v, w=1):\n # check if the u exists\n if self.graph.get(u):\n # if there already is a edge\n if self.graph[u].count([w, v]) == 0:\n self.graph[u].append([w, v])\n else:\n # if u does not exist\n self.graph[u] = [[w, v]]\n # add the other way\n if self.graph.get(v):\n # if there already is a edge\n if self.graph[v].count([w, u]) == 0:\n self.graph[v].append([w, u])\n else:\n # if u does not exist\n self.graph[v] = [[w, u]]\n\n # handles if the input does not exist\n def remove_pair(self, u, v):\n if self.graph.get(u):\n for _ in self.graph[u]:\n if _[1] == v:\n self.graph[u].remove(_)\n # the other way round\n if self.graph.get(v):\n for _ in self.graph[v]:\n if _[1] == u:\n self.graph[v].remove(_)\n\n # if no destination is meant the default value is -1\n def dfs(self, s=-2, d=-1):\n if s == d:\n return []\n stack = []\n visited = []\n if s == -2:\n s = next(iter(self.graph))\n stack.append(s)\n visited.append(s)\n ss = s\n\n while True:\n # check if there is any non isolated nodes\n if len(self.graph[s]) != 0:\n ss = s\n for node in self.graph[s]:\n if visited.count(node[1]) < 1:\n if node[1] == d:\n visited.append(d)\n return visited\n else:\n stack.append(node[1])\n visited.append(node[1])\n ss = node[1]\n break\n\n # check if all the children are visited\n if s == ss:\n stack.pop()\n if len(stack) != 0:\n s = stack[len(stack) - 1]\n else:\n s = ss\n\n # check if se have reached the starting point\n if len(stack) == 0:\n return visited\n\n # c is the count of nodes you want and if you leave it or pass -1 to the function\n # the count will be random from 10 to 10000\n def fill_graph_randomly(self, c=-1):\n if c == -1:\n c = floor(random() * 10000) + 10\n for i in range(c):\n # every vertex has max 100 edges\n for _ in range(floor(random() * 102) + 1):\n n = floor(random() * c) + 1\n if n != i:\n self.add_pair(i, n, 1)\n\n def bfs(self, s=-2):\n d = deque()\n visited = []\n if s == -2:\n s = next(iter(self.graph))\n d.append(s)\n visited.append(s)\n while d:\n s = d.popleft()\n if len(self.graph[s]) != 0:\n for node in self.graph[s]:\n if visited.count(node[1]) < 1:\n d.append(node[1])\n visited.append(node[1])\n return visited\n\n def degree(self, u):\n return len(self.graph[u])\n\n def cycle_nodes(self):\n stack = []\n visited = []\n s = next(iter(self.graph))\n stack.append(s)\n visited.append(s)\n parent = -2\n indirect_parents = []\n ss = s\n on_the_way_back = False\n anticipating_nodes = set()\n\n while True:\n # check if there is any non isolated nodes\n if len(self.graph[s]) != 0:\n ss = s\n for node in self.graph[s]:\n if (\n visited.count(node[1]) > 0\n and node[1] != parent\n and indirect_parents.count(node[1]) > 0\n and not on_the_way_back\n ):\n len_stack = len(stack) - 1\n while len_stack >= 0:\n if stack[len_stack] == node[1]:\n anticipating_nodes.add(node[1])\n break\n else:\n anticipating_nodes.add(stack[len_stack])\n len_stack -= 1\n if visited.count(node[1]) < 1:\n stack.append(node[1])\n visited.append(node[1])\n ss = node[1]\n break\n\n # check if all the children are visited\n if s == ss:\n stack.pop()\n on_the_way_back = True\n if len(stack) != 0:\n s = stack[len(stack) - 1]\n else:\n on_the_way_back = False\n indirect_parents.append(parent)\n parent = s\n s = ss\n\n # check if se have reached the starting point\n if len(stack) == 0:\n return list(anticipating_nodes)\n\n def has_cycle(self):\n stack = []\n visited = []\n s = next(iter(self.graph))\n stack.append(s)\n visited.append(s)\n parent = -2\n indirect_parents = []\n ss = s\n on_the_way_back = False\n anticipating_nodes = set()\n\n while True:\n # check if there is any non isolated nodes\n if len(self.graph[s]) != 0:\n ss = s\n for node in self.graph[s]:\n if (\n visited.count(node[1]) > 0\n and node[1] != parent\n and indirect_parents.count(node[1]) > 0\n and not on_the_way_back\n ):\n len_stack_minus_one = len(stack) - 1\n while len_stack_minus_one >= 0:\n if stack[len_stack_minus_one] == node[1]:\n anticipating_nodes.add(node[1])\n break\n else:\n return True\n if visited.count(node[1]) < 1:\n stack.append(node[1])\n visited.append(node[1])\n ss = node[1]\n break\n\n # check if all the children are visited\n if s == ss:\n stack.pop()\n on_the_way_back = True\n if len(stack) != 0:\n s = stack[len(stack) - 1]\n else:\n on_the_way_back = False\n indirect_parents.append(parent)\n parent = s\n s = ss\n\n # check if se have reached the starting point\n if len(stack) == 0:\n return False\n\n def all_nodes(self):\n return list(self.graph)\n\n def dfs_time(self, s=-2, e=-1):\n begin = time()\n self.dfs(s, e)\n end = time()\n return end - begin\n\n def bfs_time(self, s=-2):\n begin = time()\n self.bfs(s)\n end = time()\n return end - begin\n"} +{"Prompt":"make only one source and one sink make fake vertex if there are more than one source or sink it's just a reference, so you shouldn't change it in your algorithms, use deep copy before doing that You should override it use this to save your result push some substance to graph Relabeltofront selection rule move through list if it was relabeled, swap elements and start from 0 index if it's neighbour and current vertex is higher graph 0, 0, 4, 6, 0, 0, 0, 0, 5, 2, 0, 0, 0, 0, 0, 0, 4, 4, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, prepare our network set algorithm and calculate","Completions":"class FlowNetwork:\n def __init__(self, graph, sources, sinks):\n self.source_index = None\n self.sink_index = None\n self.graph = graph\n\n self._normalize_graph(sources, sinks)\n self.vertices_count = len(graph)\n self.maximum_flow_algorithm = None\n\n # make only one source and one sink\n def _normalize_graph(self, sources, sinks):\n if sources is int:\n sources = [sources]\n if sinks is int:\n sinks = [sinks]\n\n if len(sources) == 0 or len(sinks) == 0:\n return\n\n self.source_index = sources[0]\n self.sink_index = sinks[0]\n\n # make fake vertex if there are more\n # than one source or sink\n if len(sources) > 1 or len(sinks) > 1:\n max_input_flow = 0\n for i in sources:\n max_input_flow += sum(self.graph[i])\n\n size = len(self.graph) + 1\n for room in self.graph:\n room.insert(0, 0)\n self.graph.insert(0, [0] * size)\n for i in sources:\n self.graph[0][i + 1] = max_input_flow\n self.source_index = 0\n\n size = len(self.graph) + 1\n for room in self.graph:\n room.append(0)\n self.graph.append([0] * size)\n for i in sinks:\n self.graph[i + 1][size - 1] = max_input_flow\n self.sink_index = size - 1\n\n def find_maximum_flow(self):\n if self.maximum_flow_algorithm is None:\n raise Exception(\"You need to set maximum flow algorithm before.\")\n if self.source_index is None or self.sink_index is None:\n return 0\n\n self.maximum_flow_algorithm.execute()\n return self.maximum_flow_algorithm.getMaximumFlow()\n\n def set_maximum_flow_algorithm(self, algorithm):\n self.maximum_flow_algorithm = algorithm(self)\n\n\nclass FlowNetworkAlgorithmExecutor:\n def __init__(self, flow_network):\n self.flow_network = flow_network\n self.verticies_count = flow_network.verticesCount\n self.source_index = flow_network.sourceIndex\n self.sink_index = flow_network.sinkIndex\n # it's just a reference, so you shouldn't change\n # it in your algorithms, use deep copy before doing that\n self.graph = flow_network.graph\n self.executed = False\n\n def execute(self):\n if not self.executed:\n self._algorithm()\n self.executed = True\n\n # You should override it\n def _algorithm(self):\n pass\n\n\nclass MaximumFlowAlgorithmExecutor(FlowNetworkAlgorithmExecutor):\n def __init__(self, flow_network):\n super().__init__(flow_network)\n # use this to save your result\n self.maximum_flow = -1\n\n def get_maximum_flow(self):\n if not self.executed:\n raise Exception(\"You should execute algorithm before using its result!\")\n\n return self.maximum_flow\n\n\nclass PushRelabelExecutor(MaximumFlowAlgorithmExecutor):\n def __init__(self, flow_network):\n super().__init__(flow_network)\n\n self.preflow = [[0] * self.verticies_count for i in range(self.verticies_count)]\n\n self.heights = [0] * self.verticies_count\n self.excesses = [0] * self.verticies_count\n\n def _algorithm(self):\n self.heights[self.source_index] = self.verticies_count\n\n # push some substance to graph\n for nextvertex_index, bandwidth in enumerate(self.graph[self.source_index]):\n self.preflow[self.source_index][nextvertex_index] += bandwidth\n self.preflow[nextvertex_index][self.source_index] -= bandwidth\n self.excesses[nextvertex_index] += bandwidth\n\n # Relabel-to-front selection rule\n vertices_list = [\n i\n for i in range(self.verticies_count)\n if i not in {self.source_index, self.sink_index}\n ]\n\n # move through list\n i = 0\n while i < len(vertices_list):\n vertex_index = vertices_list[i]\n previous_height = self.heights[vertex_index]\n self.process_vertex(vertex_index)\n if self.heights[vertex_index] > previous_height:\n # if it was relabeled, swap elements\n # and start from 0 index\n vertices_list.insert(0, vertices_list.pop(i))\n i = 0\n else:\n i += 1\n\n self.maximum_flow = sum(self.preflow[self.source_index])\n\n def process_vertex(self, vertex_index):\n while self.excesses[vertex_index] > 0:\n for neighbour_index in range(self.verticies_count):\n # if it's neighbour and current vertex is higher\n if (\n self.graph[vertex_index][neighbour_index]\n - self.preflow[vertex_index][neighbour_index]\n > 0\n and self.heights[vertex_index] > self.heights[neighbour_index]\n ):\n self.push(vertex_index, neighbour_index)\n\n self.relabel(vertex_index)\n\n def push(self, from_index, to_index):\n preflow_delta = min(\n self.excesses[from_index],\n self.graph[from_index][to_index] - self.preflow[from_index][to_index],\n )\n self.preflow[from_index][to_index] += preflow_delta\n self.preflow[to_index][from_index] -= preflow_delta\n self.excesses[from_index] -= preflow_delta\n self.excesses[to_index] += preflow_delta\n\n def relabel(self, vertex_index):\n min_height = None\n for to_index in range(self.verticies_count):\n if (\n self.graph[vertex_index][to_index]\n - self.preflow[vertex_index][to_index]\n > 0\n ) and (min_height is None or self.heights[to_index] < min_height):\n min_height = self.heights[to_index]\n\n if min_height is not None:\n self.heights[vertex_index] = min_height + 1\n\n\nif __name__ == \"__main__\":\n entrances = [0]\n exits = [3]\n # graph = [\n # [0, 0, 4, 6, 0, 0],\n # [0, 0, 5, 2, 0, 0],\n # [0, 0, 0, 0, 4, 4],\n # [0, 0, 0, 0, 6, 6],\n # [0, 0, 0, 0, 0, 0],\n # [0, 0, 0, 0, 0, 0],\n # ]\n graph = [[0, 7, 0, 0], [0, 0, 6, 0], [0, 0, 0, 8], [9, 0, 0, 0]]\n\n # prepare our network\n flow_network = FlowNetwork(graph, entrances, exits)\n # set algorithm\n flow_network.set_maximum_flow_algorithm(PushRelabelExecutor)\n # and calculate\n maximum_flow = flow_network.find_maximum_flow()\n\n print(f\"maximum flow is {maximum_flow}\")\n"} +{"Prompt":"Eulerian Path is a path in graph that visits every edge exactly once. Eulerian Circuit is an Eulerian Path which starts and ends on the same vertex. time complexity is OVE space complexity is OVE using dfs for finding eulerian path traversal for checking in graph has euler path or circuit all degree is zero","Completions":"# Eulerian Path is a path in graph that visits every edge exactly once.\n# Eulerian Circuit is an Eulerian Path which starts and ends on the same\n# vertex.\n# time complexity is O(V+E)\n# space complexity is O(VE)\n\n\n# using dfs for finding eulerian path traversal\ndef dfs(u, graph, visited_edge, path=None):\n path = (path or []) + [u]\n for v in graph[u]:\n if visited_edge[u][v] is False:\n visited_edge[u][v], visited_edge[v][u] = True, True\n path = dfs(v, graph, visited_edge, path)\n return path\n\n\n# for checking in graph has euler path or circuit\ndef check_circuit_or_path(graph, max_node):\n odd_degree_nodes = 0\n odd_node = -1\n for i in range(max_node):\n if i not in graph:\n continue\n if len(graph[i]) % 2 == 1:\n odd_degree_nodes += 1\n odd_node = i\n if odd_degree_nodes == 0:\n return 1, odd_node\n if odd_degree_nodes == 2:\n return 2, odd_node\n return 3, odd_node\n\n\ndef check_euler(graph, max_node):\n visited_edge = [[False for _ in range(max_node + 1)] for _ in range(max_node + 1)]\n check, odd_node = check_circuit_or_path(graph, max_node)\n if check == 3:\n print(\"graph is not Eulerian\")\n print(\"no path\")\n return\n start_node = 1\n if check == 2:\n start_node = odd_node\n print(\"graph has a Euler path\")\n if check == 1:\n print(\"graph has a Euler cycle\")\n path = dfs(start_node, graph, visited_edge)\n print(path)\n\n\ndef main():\n g1 = {1: [2, 3, 4], 2: [1, 3], 3: [1, 2], 4: [1, 5], 5: [4]}\n g2 = {1: [2, 3, 4, 5], 2: [1, 3], 3: [1, 2], 4: [1, 5], 5: [1, 4]}\n g3 = {1: [2, 3, 4], 2: [1, 3, 4], 3: [1, 2], 4: [1, 2, 5], 5: [4]}\n g4 = {1: [2, 3], 2: [1, 3], 3: [1, 2]}\n g5 = {\n 1: [],\n 2: []\n # all degree is zero\n }\n max_node = 10\n check_euler(g1, max_node)\n check_euler(g2, max_node)\n check_euler(g3, max_node)\n check_euler(g4, max_node)\n check_euler(g5, max_node)\n\n\nif __name__ == \"__main__\":\n main()\n"} +{"Prompt":"You are given a treea simple connected graph with no cycles. The tree has N nodes numbered from 1 to N and is rooted at node 1. Find the maximum number of edges you can remove from the tree to get a forest such that each connected component of the forest contains an even number of nodes. Constraints 2 2 100 Note: The tree input will be such that it can always be decomposed into components containing an even number of nodes. pylint: disableinvalidname DFS traversal pylint: disableredefinedoutername ret 1 visitedstart True for v in treestart: if v not in visited: ret dfsv if ret 2 0: cuts.appendstart return ret def eventree: dfs1 if name main: n, m 10, 9 tree defaultdictlist visited: dictint, bool cuts: listint count 0 edges 2, 1, 3, 1, 4, 3, 5, 2, 6, 1, 7, 2, 8, 6, 9, 8, 10, 8 for u, v in edges: treeu.appendv treev.appendu eventree printlencuts 1","Completions":"# pylint: disable=invalid-name\nfrom collections import defaultdict\n\n\ndef dfs(start: int) -> int:\n \"\"\"DFS traversal\"\"\"\n # pylint: disable=redefined-outer-name\n ret = 1\n visited[start] = True\n for v in tree[start]:\n if v not in visited:\n ret += dfs(v)\n if ret % 2 == 0:\n cuts.append(start)\n return ret\n\n\ndef even_tree():\n \"\"\"\n 2 1\n 3 1\n 4 3\n 5 2\n 6 1\n 7 2\n 8 6\n 9 8\n 10 8\n On removing edges (1,3) and (1,6), we can get the desired result 2.\n \"\"\"\n dfs(1)\n\n\nif __name__ == \"__main__\":\n n, m = 10, 9\n tree = defaultdict(list)\n visited: dict[int, bool] = {}\n cuts: list[int] = []\n count = 0\n edges = [(2, 1), (3, 1), (4, 3), (5, 2), (6, 1), (7, 2), (8, 6), (9, 8), (10, 8)]\n for u, v in edges:\n tree[u].append(v)\n tree[v].append(u)\n even_tree()\n print(len(cuts) - 1)\n"} +{"Prompt":"An edge is a bridge if, after removing it count of connected components in graph will be increased by one. Bridges represent vulnerabilities in a connected network and are useful for designing reliable networks. For example, in a wired computer network, an articulation point indicates the critical computers and a bridge indicates the critical wires or connections. For more details, refer this article: https:www.geeksforgeeks.orgbridgeinagraph Return the list of undirected graph bridges a1, b1, ..., ak, bk; ai bi computebridgesgetdemograph0 3, 4, 2, 3, 2, 5 computebridgesgetdemograph1 6, 7, 0, 6, 1, 9, 3, 4, 2, 4, 2, 5 computebridgesgetdemograph2 1, 6, 4, 6, 0, 4 computebridgesgetdemograph3 computebridges This edge is a back edge and cannot be a bridge","Completions":"def __get_demo_graph(index):\n return [\n {\n 0: [1, 2],\n 1: [0, 2],\n 2: [0, 1, 3, 5],\n 3: [2, 4],\n 4: [3],\n 5: [2, 6, 8],\n 6: [5, 7],\n 7: [6, 8],\n 8: [5, 7],\n },\n {\n 0: [6],\n 1: [9],\n 2: [4, 5],\n 3: [4],\n 4: [2, 3],\n 5: [2],\n 6: [0, 7],\n 7: [6],\n 8: [],\n 9: [1],\n },\n {\n 0: [4],\n 1: [6],\n 2: [],\n 3: [5, 6, 7],\n 4: [0, 6],\n 5: [3, 8, 9],\n 6: [1, 3, 4, 7],\n 7: [3, 6, 8, 9],\n 8: [5, 7],\n 9: [5, 7],\n },\n {\n 0: [1, 3],\n 1: [0, 2, 4],\n 2: [1, 3, 4],\n 3: [0, 2, 4],\n 4: [1, 2, 3],\n },\n ][index]\n\n\ndef compute_bridges(graph: dict[int, list[int]]) -> list[tuple[int, int]]:\n \"\"\"\n Return the list of undirected graph bridges [(a1, b1), ..., (ak, bk)]; ai <= bi\n >>> compute_bridges(__get_demo_graph(0))\n [(3, 4), (2, 3), (2, 5)]\n >>> compute_bridges(__get_demo_graph(1))\n [(6, 7), (0, 6), (1, 9), (3, 4), (2, 4), (2, 5)]\n >>> compute_bridges(__get_demo_graph(2))\n [(1, 6), (4, 6), (0, 4)]\n >>> compute_bridges(__get_demo_graph(3))\n []\n >>> compute_bridges({})\n []\n \"\"\"\n\n id_ = 0\n n = len(graph) # No of vertices in graph\n low = [0] * n\n visited = [False] * n\n\n def dfs(at, parent, bridges, id_):\n visited[at] = True\n low[at] = id_\n id_ += 1\n for to in graph[at]:\n if to == parent:\n pass\n elif not visited[to]:\n dfs(to, at, bridges, id_)\n low[at] = min(low[at], low[to])\n if id_ <= low[to]:\n bridges.append((at, to) if at < to else (to, at))\n else:\n # This edge is a back edge and cannot be a bridge\n low[at] = min(low[at], low[to])\n\n bridges: list[tuple[int, int]] = []\n for i in range(n):\n if not visited[i]:\n dfs(i, -1, bridges, id_)\n return bridges\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"FPGraphMiner A Fast Frequent Pattern Mining Algorithm for Network Graphs A novel Frequent Pattern Graph Mining algorithm, FPGraphMiner, that compactly represents a set of network graphs as a Frequent Pattern Graph or FPGraph. This graph can be used to efficiently mine frequent subgraphs including maximal frequent subgraphs and maximum common subgraphs. URL: https:www.researchgate.netpublication235255851 fmt: off fmt: on Return Distinct edges from edge array of multiple graphs sortedgetdistinctedgeedgearray 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h' Return bitcode of distinctedge Returns Frequency Table print'bit',bit bt''.joinbit Store Distinct edge, WTBitcode, Bitcode in descending order Returns nodes format nodesbitcode:edges that represent the bitcode getnodes'ab', 5, '11111', 'ac', 5, '11111', 'df', 5, '11111', ... 'bd', 5, '11111', 'bc', 5, '11111' '11111': 'ab', 'ac', 'df', 'bd', 'bc' Returns cluster format cluster:WTbitcode:nodes with same WT Returns support getsupport5: '11111': 'ab', 'ac', 'df', 'bd', 'bc', ... 4: '11101': 'ef', 'eg', 'de', 'fg', '11011': 'cd', ... 3: '11001': 'ad', '10101': 'dg', ... 2: '10010': 'dh', 'bh', '11000': 'be', '10100': 'gh', ... '10001': 'ce', ... 1: '00100': 'fh', 'eh', '10000': 'hi' 100.0, 80.0, 60.0, 40.0, 20.0 create edge between the nodes creates edge only if the condition satisfies find different DFS walk from given node to Header node find edges of multiple frequent subgraphs returns Edge list for frequent subgraphs Preprocess the edge array preprocess'abe1', 'ace3', 'ade5', 'bce4', 'bde2', 'bee6', 'bhe12', ... 'cde2', 'cee4', 'dee1', 'dfe8', 'dge5', 'dhe10', 'efe3', ... 'ege2', 'fge6', 'ghe6', 'hie3'","Completions":"# fmt: off\nedge_array = [\n ['ab-e1', 'ac-e3', 'ad-e5', 'bc-e4', 'bd-e2', 'be-e6', 'bh-e12', 'cd-e2', 'ce-e4',\n 'de-e1', 'df-e8', 'dg-e5', 'dh-e10', 'ef-e3', 'eg-e2', 'fg-e6', 'gh-e6', 'hi-e3'],\n ['ab-e1', 'ac-e3', 'ad-e5', 'bc-e4', 'bd-e2', 'be-e6', 'cd-e2', 'de-e1', 'df-e8',\n 'ef-e3', 'eg-e2', 'fg-e6'],\n ['ab-e1', 'ac-e3', 'bc-e4', 'bd-e2', 'de-e1', 'df-e8', 'dg-e5', 'ef-e3', 'eg-e2',\n 'eh-e12', 'fg-e6', 'fh-e10', 'gh-e6'],\n ['ab-e1', 'ac-e3', 'bc-e4', 'bd-e2', 'bh-e12', 'cd-e2', 'df-e8', 'dh-e10'],\n ['ab-e1', 'ac-e3', 'ad-e5', 'bc-e4', 'bd-e2', 'cd-e2', 'ce-e4', 'de-e1', 'df-e8',\n 'dg-e5', 'ef-e3', 'eg-e2', 'fg-e6']\n]\n# fmt: on\n\n\ndef get_distinct_edge(edge_array):\n \"\"\"\n Return Distinct edges from edge array of multiple graphs\n >>> sorted(get_distinct_edge(edge_array))\n ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']\n \"\"\"\n distinct_edge = set()\n for row in edge_array:\n for item in row:\n distinct_edge.add(item[0])\n return list(distinct_edge)\n\n\ndef get_bitcode(edge_array, distinct_edge):\n \"\"\"\n Return bitcode of distinct_edge\n \"\"\"\n bitcode = [\"0\"] * len(edge_array)\n for i, row in enumerate(edge_array):\n for item in row:\n if distinct_edge in item[0]:\n bitcode[i] = \"1\"\n break\n return \"\".join(bitcode)\n\n\ndef get_frequency_table(edge_array):\n \"\"\"\n Returns Frequency Table\n \"\"\"\n distinct_edge = get_distinct_edge(edge_array)\n frequency_table = {}\n\n for item in distinct_edge:\n bit = get_bitcode(edge_array, item)\n # print('bit',bit)\n # bt=''.join(bit)\n s = bit.count(\"1\")\n frequency_table[item] = [s, bit]\n # Store [Distinct edge, WT(Bitcode), Bitcode] in descending order\n sorted_frequency_table = [\n [k, v[0], v[1]]\n for k, v in sorted(frequency_table.items(), key=lambda v: v[1][0], reverse=True)\n ]\n return sorted_frequency_table\n\n\ndef get_nodes(frequency_table):\n \"\"\"\n Returns nodes\n format nodes={bitcode:edges that represent the bitcode}\n >>> get_nodes([['ab', 5, '11111'], ['ac', 5, '11111'], ['df', 5, '11111'],\n ... ['bd', 5, '11111'], ['bc', 5, '11111']])\n {'11111': ['ab', 'ac', 'df', 'bd', 'bc']}\n \"\"\"\n nodes = {}\n for _, item in enumerate(frequency_table):\n nodes.setdefault(item[2], []).append(item[0])\n return nodes\n\n\ndef get_cluster(nodes):\n \"\"\"\n Returns cluster\n format cluster:{WT(bitcode):nodes with same WT}\n \"\"\"\n cluster = {}\n for key, value in nodes.items():\n cluster.setdefault(key.count(\"1\"), {})[key] = value\n return cluster\n\n\ndef get_support(cluster):\n \"\"\"\n Returns support\n >>> get_support({5: {'11111': ['ab', 'ac', 'df', 'bd', 'bc']},\n ... 4: {'11101': ['ef', 'eg', 'de', 'fg'], '11011': ['cd']},\n ... 3: {'11001': ['ad'], '10101': ['dg']},\n ... 2: {'10010': ['dh', 'bh'], '11000': ['be'], '10100': ['gh'],\n ... '10001': ['ce']},\n ... 1: {'00100': ['fh', 'eh'], '10000': ['hi']}})\n [100.0, 80.0, 60.0, 40.0, 20.0]\n \"\"\"\n return [i * 100 \/ len(cluster) for i in cluster]\n\n\ndef print_all() -> None:\n print(\"\\nNodes\\n\")\n for key, value in nodes.items():\n print(key, value)\n print(\"\\nSupport\\n\")\n print(support)\n print(\"\\n Cluster \\n\")\n for key, value in sorted(cluster.items(), reverse=True):\n print(key, value)\n print(\"\\n Graph\\n\")\n for key, value in graph.items():\n print(key, value)\n print(\"\\n Edge List of Frequent subgraphs \\n\")\n for edge_list in freq_subgraph_edge_list:\n print(edge_list)\n\n\ndef create_edge(nodes, graph, cluster, c1):\n \"\"\"\n create edge between the nodes\n \"\"\"\n for i in cluster[c1]:\n count = 0\n c2 = c1 + 1\n while c2 < max(cluster.keys()):\n for j in cluster[c2]:\n \"\"\"\n creates edge only if the condition satisfies\n \"\"\"\n if int(i, 2) & int(j, 2) == int(i, 2):\n if tuple(nodes[i]) in graph:\n graph[tuple(nodes[i])].append(nodes[j])\n else:\n graph[tuple(nodes[i])] = [nodes[j]]\n count += 1\n if count == 0:\n c2 = c2 + 1\n else:\n break\n\n\ndef construct_graph(cluster, nodes):\n x = cluster[max(cluster.keys())]\n cluster[max(cluster.keys()) + 1] = \"Header\"\n graph = {}\n for i in x:\n if ([\"Header\"],) in graph:\n graph[([\"Header\"],)].append(x[i])\n else:\n graph[([\"Header\"],)] = [x[i]]\n for i in x:\n graph[(x[i],)] = [[\"Header\"]]\n i = 1\n while i < max(cluster) - 1:\n create_edge(nodes, graph, cluster, i)\n i = i + 1\n return graph\n\n\ndef my_dfs(graph, start, end, path=None):\n \"\"\"\n find different DFS walk from given node to Header node\n \"\"\"\n path = (path or []) + [start]\n if start == end:\n paths.append(path)\n for node in graph[start]:\n if tuple(node) not in path:\n my_dfs(graph, tuple(node), end, path)\n\n\ndef find_freq_subgraph_given_support(s, cluster, graph):\n \"\"\"\n find edges of multiple frequent subgraphs\n \"\"\"\n k = int(s \/ 100 * (len(cluster) - 1))\n for i in cluster[k]:\n my_dfs(graph, tuple(cluster[k][i]), ([\"Header\"],))\n\n\ndef freq_subgraphs_edge_list(paths):\n \"\"\"\n returns Edge list for frequent subgraphs\n \"\"\"\n freq_sub_el = []\n for edges in paths:\n el = []\n for j in range(len(edges) - 1):\n temp = list(edges[j])\n for e in temp:\n edge = (e[0], e[1])\n el.append(edge)\n freq_sub_el.append(el)\n return freq_sub_el\n\n\ndef preprocess(edge_array):\n \"\"\"\n Preprocess the edge array\n >>> preprocess([['ab-e1', 'ac-e3', 'ad-e5', 'bc-e4', 'bd-e2', 'be-e6', 'bh-e12',\n ... 'cd-e2', 'ce-e4', 'de-e1', 'df-e8', 'dg-e5', 'dh-e10', 'ef-e3',\n ... 'eg-e2', 'fg-e6', 'gh-e6', 'hi-e3']])\n\n \"\"\"\n for i in range(len(edge_array)):\n for j in range(len(edge_array[i])):\n t = edge_array[i][j].split(\"-\")\n edge_array[i][j] = t\n\n\nif __name__ == \"__main__\":\n preprocess(edge_array)\n frequency_table = get_frequency_table(edge_array)\n nodes = get_nodes(frequency_table)\n cluster = get_cluster(nodes)\n support = get_support(cluster)\n graph = construct_graph(cluster, nodes)\n find_freq_subgraph_given_support(60, cluster, graph)\n paths: list = []\n freq_subgraph_edge_list = freq_subgraphs_edge_list(paths)\n print_all()\n"} +{"Prompt":"Author: Phyllipe Bezerra https:github.compmba","Completions":"# Author: Phyllipe Bezerra (https:\/\/github.com\/pmba)\n\nclothes = {\n 0: \"underwear\",\n 1: \"pants\",\n 2: \"belt\",\n 3: \"suit\",\n 4: \"shoe\",\n 5: \"socks\",\n 6: \"shirt\",\n 7: \"tie\",\n 8: \"watch\",\n}\n\ngraph = [[1, 4], [2, 4], [3], [], [], [4], [2, 7], [3], []]\n\nvisited = [0 for x in range(len(graph))]\nstack = []\n\n\ndef print_stack(stack, clothes):\n order = 1\n while stack:\n current_clothing = stack.pop()\n print(order, clothes[current_clothing])\n order += 1\n\n\ndef depth_first_search(u, visited, graph):\n visited[u] = 1\n for v in graph[u]:\n if not visited[v]:\n depth_first_search(v, visited, graph)\n\n stack.append(u)\n\n\ndef topological_sort(graph, visited):\n for v in range(len(graph)):\n if not visited[v]:\n depth_first_search(v, visited, graph)\n\n\nif __name__ == \"__main__\":\n topological_sort(graph, visited)\n print(stack)\n print_stack(stack, clothes)\n"} +{"Prompt":"Finds the stable match in any bipartite graph, i.e a pairing where no 2 objects prefer each other over their partner. The function accepts the preferences of oegan donors and recipients where both are assigned numbers from 0 to n1 and returns a list where the index position corresponds to the donor and value at the index is the organ recipient. To better understand the algorithm, see also: https:github.comakashvshroffGaleShapleyStableMatching README. https:www.youtube.comwatch?vQcv1IqHWAzgt13s Numberphile YouTube. donorpref 0, 1, 3, 2, 0, 2, 3, 1, 1, 0, 2, 3, 0, 3, 1, 2 recipientpref 3, 1, 2, 0, 3, 1, 0, 2, 0, 3, 1, 2, 1, 0, 3, 2 stablematchingdonorpref, recipientpref 1, 2, 3, 0","Completions":"from __future__ import annotations\n\n\ndef stable_matching(\n donor_pref: list[list[int]], recipient_pref: list[list[int]]\n) -> list[int]:\n \"\"\"\n Finds the stable match in any bipartite graph, i.e a pairing where no 2 objects\n prefer each other over their partner. The function accepts the preferences of\n oegan donors and recipients (where both are assigned numbers from 0 to n-1) and\n returns a list where the index position corresponds to the donor and value at the\n index is the organ recipient.\n\n To better understand the algorithm, see also:\n https:\/\/github.com\/akashvshroff\/Gale_Shapley_Stable_Matching (README).\n https:\/\/www.youtube.com\/watch?v=Qcv1IqHWAzg&t=13s (Numberphile YouTube).\n\n >>> donor_pref = [[0, 1, 3, 2], [0, 2, 3, 1], [1, 0, 2, 3], [0, 3, 1, 2]]\n >>> recipient_pref = [[3, 1, 2, 0], [3, 1, 0, 2], [0, 3, 1, 2], [1, 0, 3, 2]]\n >>> stable_matching(donor_pref, recipient_pref)\n [1, 2, 3, 0]\n \"\"\"\n assert len(donor_pref) == len(recipient_pref)\n\n n = len(donor_pref)\n unmatched_donors = list(range(n))\n donor_record = [-1] * n # who the donor has donated to\n rec_record = [-1] * n # who the recipient has received from\n num_donations = [0] * n\n\n while unmatched_donors:\n donor = unmatched_donors[0]\n donor_preference = donor_pref[donor]\n recipient = donor_preference[num_donations[donor]]\n num_donations[donor] += 1\n rec_preference = recipient_pref[recipient]\n prev_donor = rec_record[recipient]\n\n if prev_donor != -1:\n if rec_preference.index(prev_donor) > rec_preference.index(donor):\n rec_record[recipient] = donor\n donor_record[donor] = recipient\n unmatched_donors.append(prev_donor)\n unmatched_donors.remove(donor)\n else:\n rec_record[recipient] = donor\n donor_record[donor] = recipient\n unmatched_donors.remove(donor)\n return donor_record\n"} +{"Prompt":"!usrbinenv python3 Author: Vikram Nithyanandam Description: The following implementation is a robust unweighted Graph data structure implemented using an adjacency list. This vertices and edges of this graph can be effectively initialized and modified while storing your chosen generic value in each vertex. Adjacency List: https:en.wikipedia.orgwikiAdjacencylist Potential Future Ideas: Add a flag to set edge weights on and set edge weights Make edge weights and vertex values customizable to store whatever the client wants Support multigraph functionality if the client wants it Parameters: vertices: listT The list of vertex names the client wants to pass in. Default is empty. edges: listlistT The list of edges the client wants to pass in. Each edge is a 2element list. Default is empty. directed: bool Indicates if graph is directed or undirected. Default is True. Falsey checks Adds a vertex to the graph. If the given vertex already exists, a ValueError will be thrown. Creates an edge from source vertex to destination vertex. If any given vertex doesn't exist or the edge already exists, a ValueError will be thrown. add the destination vertex to the list associated with the source vertex and vice versa if not directed Removes the given vertex from the graph and deletes all incoming and outgoing edges from the given vertex as well. If the given vertex does not exist, a ValueError will be thrown. If not directed, find all neighboring vertices and delete all references of edges connecting to the given vertex If directed, search all neighbors of all vertices and delete all references of edges connecting to the given vertex Finally, delete the given vertex and all of its outgoing edge references Removes the edge between the two vertices. If any given vertex doesn't exist or the edge does not exist, a ValueError will be thrown. remove the destination vertex from the list associated with the source vertex and vice versa if not directed Returns True if the graph contains the vertex, False otherwise. Returns True if the graph contains the edge from the sourcevertex to the destinationvertex, False otherwise. If any given vertex doesn't exist, a ValueError will be thrown. Clears all vertices and edges. generate graph input build graphs test graph initialization with vertices and edges Build graphs WITHOUT edges Test containsvertex build empty graphs run addvertex test addvertex worked build graphs WITHOUT edges test removevertex worked build graphs WITHOUT edges test adding and removing vertices remove all vertices generate graphs and graph input generate all possible edges for testing test containsedge function since this edge exists for undirected but the reverse may not exist for directed generate graph input build graphs WITHOUT edges run and test addedge generate graph input and graphs run and test removeedge make some more edge options!","Completions":"#!\/usr\/bin\/env python3\n\"\"\"\nAuthor: Vikram Nithyanandam\n\nDescription:\nThe following implementation is a robust unweighted Graph data structure\nimplemented using an adjacency list. This vertices and edges of this graph can be\neffectively initialized and modified while storing your chosen generic\nvalue in each vertex.\n\nAdjacency List: https:\/\/en.wikipedia.org\/wiki\/Adjacency_list\n\nPotential Future Ideas:\n- Add a flag to set edge weights on and set edge weights\n- Make edge weights and vertex values customizable to store whatever the client wants\n- Support multigraph functionality if the client wants it\n\"\"\"\nfrom __future__ import annotations\n\nimport random\nimport unittest\nfrom pprint import pformat\nfrom typing import Generic, TypeVar\n\nimport pytest\n\nT = TypeVar(\"T\")\n\n\nclass GraphAdjacencyList(Generic[T]):\n def __init__(\n self, vertices: list[T], edges: list[list[T]], directed: bool = True\n ) -> None:\n \"\"\"\n Parameters:\n - vertices: (list[T]) The list of vertex names the client wants to\n pass in. Default is empty.\n - edges: (list[list[T]]) The list of edges the client wants to\n pass in. Each edge is a 2-element list. Default is empty.\n - directed: (bool) Indicates if graph is directed or undirected.\n Default is True.\n \"\"\"\n self.adj_list: dict[T, list[T]] = {} # dictionary of lists of T\n self.directed = directed\n\n # Falsey checks\n edges = edges or []\n vertices = vertices or []\n\n for vertex in vertices:\n self.add_vertex(vertex)\n\n for edge in edges:\n if len(edge) != 2:\n msg = f\"Invalid input: {edge} is the wrong length.\"\n raise ValueError(msg)\n self.add_edge(edge[0], edge[1])\n\n def add_vertex(self, vertex: T) -> None:\n \"\"\"\n Adds a vertex to the graph. If the given vertex already exists,\n a ValueError will be thrown.\n \"\"\"\n if self.contains_vertex(vertex):\n msg = f\"Incorrect input: {vertex} is already in the graph.\"\n raise ValueError(msg)\n self.adj_list[vertex] = []\n\n def add_edge(self, source_vertex: T, destination_vertex: T) -> None:\n \"\"\"\n Creates an edge from source vertex to destination vertex. If any\n given vertex doesn't exist or the edge already exists, a ValueError\n will be thrown.\n \"\"\"\n if not (\n self.contains_vertex(source_vertex)\n and self.contains_vertex(destination_vertex)\n ):\n msg = (\n f\"Incorrect input: Either {source_vertex} or \"\n f\"{destination_vertex} does not exist\"\n )\n raise ValueError(msg)\n if self.contains_edge(source_vertex, destination_vertex):\n msg = (\n \"Incorrect input: The edge already exists between \"\n f\"{source_vertex} and {destination_vertex}\"\n )\n raise ValueError(msg)\n\n # add the destination vertex to the list associated with the source vertex\n # and vice versa if not directed\n self.adj_list[source_vertex].append(destination_vertex)\n if not self.directed:\n self.adj_list[destination_vertex].append(source_vertex)\n\n def remove_vertex(self, vertex: T) -> None:\n \"\"\"\n Removes the given vertex from the graph and deletes all incoming and\n outgoing edges from the given vertex as well. If the given vertex\n does not exist, a ValueError will be thrown.\n \"\"\"\n if not self.contains_vertex(vertex):\n msg = f\"Incorrect input: {vertex} does not exist in this graph.\"\n raise ValueError(msg)\n\n if not self.directed:\n # If not directed, find all neighboring vertices and delete all references\n # of edges connecting to the given vertex\n for neighbor in self.adj_list[vertex]:\n self.adj_list[neighbor].remove(vertex)\n else:\n # If directed, search all neighbors of all vertices and delete all\n # references of edges connecting to the given vertex\n for edge_list in self.adj_list.values():\n if vertex in edge_list:\n edge_list.remove(vertex)\n\n # Finally, delete the given vertex and all of its outgoing edge references\n self.adj_list.pop(vertex)\n\n def remove_edge(self, source_vertex: T, destination_vertex: T) -> None:\n \"\"\"\n Removes the edge between the two vertices. If any given vertex\n doesn't exist or the edge does not exist, a ValueError will be thrown.\n \"\"\"\n if not (\n self.contains_vertex(source_vertex)\n and self.contains_vertex(destination_vertex)\n ):\n msg = (\n f\"Incorrect input: Either {source_vertex} or \"\n f\"{destination_vertex} does not exist\"\n )\n raise ValueError(msg)\n if not self.contains_edge(source_vertex, destination_vertex):\n msg = (\n \"Incorrect input: The edge does NOT exist between \"\n f\"{source_vertex} and {destination_vertex}\"\n )\n raise ValueError(msg)\n\n # remove the destination vertex from the list associated with the source\n # vertex and vice versa if not directed\n self.adj_list[source_vertex].remove(destination_vertex)\n if not self.directed:\n self.adj_list[destination_vertex].remove(source_vertex)\n\n def contains_vertex(self, vertex: T) -> bool:\n \"\"\"\n Returns True if the graph contains the vertex, False otherwise.\n \"\"\"\n return vertex in self.adj_list\n\n def contains_edge(self, source_vertex: T, destination_vertex: T) -> bool:\n \"\"\"\n Returns True if the graph contains the edge from the source_vertex to the\n destination_vertex, False otherwise. If any given vertex doesn't exist, a\n ValueError will be thrown.\n \"\"\"\n if not (\n self.contains_vertex(source_vertex)\n and self.contains_vertex(destination_vertex)\n ):\n msg = (\n f\"Incorrect input: Either {source_vertex} \"\n f\"or {destination_vertex} does not exist.\"\n )\n raise ValueError(msg)\n\n return destination_vertex in self.adj_list[source_vertex]\n\n def clear_graph(self) -> None:\n \"\"\"\n Clears all vertices and edges.\n \"\"\"\n self.adj_list = {}\n\n def __repr__(self) -> str:\n return pformat(self.adj_list)\n\n\nclass TestGraphAdjacencyList(unittest.TestCase):\n def __assert_graph_edge_exists_check(\n self,\n undirected_graph: GraphAdjacencyList,\n directed_graph: GraphAdjacencyList,\n edge: list[int],\n ) -> None:\n assert undirected_graph.contains_edge(edge[0], edge[1])\n assert undirected_graph.contains_edge(edge[1], edge[0])\n assert directed_graph.contains_edge(edge[0], edge[1])\n\n def __assert_graph_edge_does_not_exist_check(\n self,\n undirected_graph: GraphAdjacencyList,\n directed_graph: GraphAdjacencyList,\n edge: list[int],\n ) -> None:\n assert not undirected_graph.contains_edge(edge[0], edge[1])\n assert not undirected_graph.contains_edge(edge[1], edge[0])\n assert not directed_graph.contains_edge(edge[0], edge[1])\n\n def __assert_graph_vertex_exists_check(\n self,\n undirected_graph: GraphAdjacencyList,\n directed_graph: GraphAdjacencyList,\n vertex: int,\n ) -> None:\n assert undirected_graph.contains_vertex(vertex)\n assert directed_graph.contains_vertex(vertex)\n\n def __assert_graph_vertex_does_not_exist_check(\n self,\n undirected_graph: GraphAdjacencyList,\n directed_graph: GraphAdjacencyList,\n vertex: int,\n ) -> None:\n assert not undirected_graph.contains_vertex(vertex)\n assert not directed_graph.contains_vertex(vertex)\n\n def __generate_random_edges(\n self, vertices: list[int], edge_pick_count: int\n ) -> list[list[int]]:\n assert edge_pick_count <= len(vertices)\n\n random_source_vertices: list[int] = random.sample(\n vertices[0 : int(len(vertices) \/ 2)], edge_pick_count\n )\n random_destination_vertices: list[int] = random.sample(\n vertices[int(len(vertices) \/ 2) :], edge_pick_count\n )\n random_edges: list[list[int]] = []\n\n for source in random_source_vertices:\n for dest in random_destination_vertices:\n random_edges.append([source, dest])\n\n return random_edges\n\n def __generate_graphs(\n self, vertex_count: int, min_val: int, max_val: int, edge_pick_count: int\n ) -> tuple[GraphAdjacencyList, GraphAdjacencyList, list[int], list[list[int]]]:\n if max_val - min_val + 1 < vertex_count:\n raise ValueError(\n \"Will result in duplicate vertices. Either increase range \"\n \"between min_val and max_val or decrease vertex count.\"\n )\n\n # generate graph input\n random_vertices: list[int] = random.sample(\n range(min_val, max_val + 1), vertex_count\n )\n random_edges: list[list[int]] = self.__generate_random_edges(\n random_vertices, edge_pick_count\n )\n\n # build graphs\n undirected_graph = GraphAdjacencyList(\n vertices=random_vertices, edges=random_edges, directed=False\n )\n directed_graph = GraphAdjacencyList(\n vertices=random_vertices, edges=random_edges, directed=True\n )\n\n return undirected_graph, directed_graph, random_vertices, random_edges\n\n def test_init_check(self) -> None:\n (\n undirected_graph,\n directed_graph,\n random_vertices,\n random_edges,\n ) = self.__generate_graphs(20, 0, 100, 4)\n\n # test graph initialization with vertices and edges\n for num in random_vertices:\n self.__assert_graph_vertex_exists_check(\n undirected_graph, directed_graph, num\n )\n\n for edge in random_edges:\n self.__assert_graph_edge_exists_check(\n undirected_graph, directed_graph, edge\n )\n assert not undirected_graph.directed\n assert directed_graph.directed\n\n def test_contains_vertex(self) -> None:\n random_vertices: list[int] = random.sample(range(101), 20)\n\n # Build graphs WITHOUT edges\n undirected_graph = GraphAdjacencyList(\n vertices=random_vertices, edges=[], directed=False\n )\n directed_graph = GraphAdjacencyList(\n vertices=random_vertices, edges=[], directed=True\n )\n\n # Test contains_vertex\n for num in range(101):\n assert (num in random_vertices) == undirected_graph.contains_vertex(num)\n assert (num in random_vertices) == directed_graph.contains_vertex(num)\n\n def test_add_vertices(self) -> None:\n random_vertices: list[int] = random.sample(range(101), 20)\n\n # build empty graphs\n undirected_graph: GraphAdjacencyList = GraphAdjacencyList(\n vertices=[], edges=[], directed=False\n )\n directed_graph: GraphAdjacencyList = GraphAdjacencyList(\n vertices=[], edges=[], directed=True\n )\n\n # run add_vertex\n for num in random_vertices:\n undirected_graph.add_vertex(num)\n\n for num in random_vertices:\n directed_graph.add_vertex(num)\n\n # test add_vertex worked\n for num in random_vertices:\n self.__assert_graph_vertex_exists_check(\n undirected_graph, directed_graph, num\n )\n\n def test_remove_vertices(self) -> None:\n random_vertices: list[int] = random.sample(range(101), 20)\n\n # build graphs WITHOUT edges\n undirected_graph = GraphAdjacencyList(\n vertices=random_vertices, edges=[], directed=False\n )\n directed_graph = GraphAdjacencyList(\n vertices=random_vertices, edges=[], directed=True\n )\n\n # test remove_vertex worked\n for num in random_vertices:\n self.__assert_graph_vertex_exists_check(\n undirected_graph, directed_graph, num\n )\n\n undirected_graph.remove_vertex(num)\n directed_graph.remove_vertex(num)\n\n self.__assert_graph_vertex_does_not_exist_check(\n undirected_graph, directed_graph, num\n )\n\n def test_add_and_remove_vertices_repeatedly(self) -> None:\n random_vertices1: list[int] = random.sample(range(51), 20)\n random_vertices2: list[int] = random.sample(range(51, 101), 20)\n\n # build graphs WITHOUT edges\n undirected_graph = GraphAdjacencyList(\n vertices=random_vertices1, edges=[], directed=False\n )\n directed_graph = GraphAdjacencyList(\n vertices=random_vertices1, edges=[], directed=True\n )\n\n # test adding and removing vertices\n for i, _ in enumerate(random_vertices1):\n undirected_graph.add_vertex(random_vertices2[i])\n directed_graph.add_vertex(random_vertices2[i])\n\n self.__assert_graph_vertex_exists_check(\n undirected_graph, directed_graph, random_vertices2[i]\n )\n\n undirected_graph.remove_vertex(random_vertices1[i])\n directed_graph.remove_vertex(random_vertices1[i])\n\n self.__assert_graph_vertex_does_not_exist_check(\n undirected_graph, directed_graph, random_vertices1[i]\n )\n\n # remove all vertices\n for i, _ in enumerate(random_vertices1):\n undirected_graph.remove_vertex(random_vertices2[i])\n directed_graph.remove_vertex(random_vertices2[i])\n\n self.__assert_graph_vertex_does_not_exist_check(\n undirected_graph, directed_graph, random_vertices2[i]\n )\n\n def test_contains_edge(self) -> None:\n # generate graphs and graph input\n vertex_count = 20\n (\n undirected_graph,\n directed_graph,\n random_vertices,\n random_edges,\n ) = self.__generate_graphs(vertex_count, 0, 100, 4)\n\n # generate all possible edges for testing\n all_possible_edges: list[list[int]] = []\n for i in range(vertex_count - 1):\n for j in range(i + 1, vertex_count):\n all_possible_edges.append([random_vertices[i], random_vertices[j]])\n all_possible_edges.append([random_vertices[j], random_vertices[i]])\n\n # test contains_edge function\n for edge in all_possible_edges:\n if edge in random_edges:\n self.__assert_graph_edge_exists_check(\n undirected_graph, directed_graph, edge\n )\n elif [edge[1], edge[0]] in random_edges:\n # since this edge exists for undirected but the reverse\n # may not exist for directed\n self.__assert_graph_edge_exists_check(\n undirected_graph, directed_graph, [edge[1], edge[0]]\n )\n else:\n self.__assert_graph_edge_does_not_exist_check(\n undirected_graph, directed_graph, edge\n )\n\n def test_add_edge(self) -> None:\n # generate graph input\n random_vertices: list[int] = random.sample(range(101), 15)\n random_edges: list[list[int]] = self.__generate_random_edges(random_vertices, 4)\n\n # build graphs WITHOUT edges\n undirected_graph = GraphAdjacencyList(\n vertices=random_vertices, edges=[], directed=False\n )\n directed_graph = GraphAdjacencyList(\n vertices=random_vertices, edges=[], directed=True\n )\n\n # run and test add_edge\n for edge in random_edges:\n undirected_graph.add_edge(edge[0], edge[1])\n directed_graph.add_edge(edge[0], edge[1])\n self.__assert_graph_edge_exists_check(\n undirected_graph, directed_graph, edge\n )\n\n def test_remove_edge(self) -> None:\n # generate graph input and graphs\n (\n undirected_graph,\n directed_graph,\n random_vertices,\n random_edges,\n ) = self.__generate_graphs(20, 0, 100, 4)\n\n # run and test remove_edge\n for edge in random_edges:\n self.__assert_graph_edge_exists_check(\n undirected_graph, directed_graph, edge\n )\n undirected_graph.remove_edge(edge[0], edge[1])\n directed_graph.remove_edge(edge[0], edge[1])\n self.__assert_graph_edge_does_not_exist_check(\n undirected_graph, directed_graph, edge\n )\n\n def test_add_and_remove_edges_repeatedly(self) -> None:\n (\n undirected_graph,\n directed_graph,\n random_vertices,\n random_edges,\n ) = self.__generate_graphs(20, 0, 100, 4)\n\n # make some more edge options!\n more_random_edges: list[list[int]] = []\n\n while len(more_random_edges) != len(random_edges):\n edges: list[list[int]] = self.__generate_random_edges(random_vertices, 4)\n for edge in edges:\n if len(more_random_edges) == len(random_edges):\n break\n elif edge not in more_random_edges and edge not in random_edges:\n more_random_edges.append(edge)\n\n for i, _ in enumerate(random_edges):\n undirected_graph.add_edge(more_random_edges[i][0], more_random_edges[i][1])\n directed_graph.add_edge(more_random_edges[i][0], more_random_edges[i][1])\n\n self.__assert_graph_edge_exists_check(\n undirected_graph, directed_graph, more_random_edges[i]\n )\n\n undirected_graph.remove_edge(random_edges[i][0], random_edges[i][1])\n directed_graph.remove_edge(random_edges[i][0], random_edges[i][1])\n\n self.__assert_graph_edge_does_not_exist_check(\n undirected_graph, directed_graph, random_edges[i]\n )\n\n def test_add_vertex_exception_check(self) -> None:\n (\n undirected_graph,\n directed_graph,\n random_vertices,\n random_edges,\n ) = self.__generate_graphs(20, 0, 100, 4)\n\n for vertex in random_vertices:\n with pytest.raises(ValueError):\n undirected_graph.add_vertex(vertex)\n with pytest.raises(ValueError):\n directed_graph.add_vertex(vertex)\n\n def test_remove_vertex_exception_check(self) -> None:\n (\n undirected_graph,\n directed_graph,\n random_vertices,\n random_edges,\n ) = self.__generate_graphs(20, 0, 100, 4)\n\n for i in range(101):\n if i not in random_vertices:\n with pytest.raises(ValueError):\n undirected_graph.remove_vertex(i)\n with pytest.raises(ValueError):\n directed_graph.remove_vertex(i)\n\n def test_add_edge_exception_check(self) -> None:\n (\n undirected_graph,\n directed_graph,\n random_vertices,\n random_edges,\n ) = self.__generate_graphs(20, 0, 100, 4)\n\n for edge in random_edges:\n with pytest.raises(ValueError):\n undirected_graph.add_edge(edge[0], edge[1])\n with pytest.raises(ValueError):\n directed_graph.add_edge(edge[0], edge[1])\n\n def test_remove_edge_exception_check(self) -> None:\n (\n undirected_graph,\n directed_graph,\n random_vertices,\n random_edges,\n ) = self.__generate_graphs(20, 0, 100, 4)\n\n more_random_edges: list[list[int]] = []\n\n while len(more_random_edges) != len(random_edges):\n edges: list[list[int]] = self.__generate_random_edges(random_vertices, 4)\n for edge in edges:\n if len(more_random_edges) == len(random_edges):\n break\n elif edge not in more_random_edges and edge not in random_edges:\n more_random_edges.append(edge)\n\n for edge in more_random_edges:\n with pytest.raises(ValueError):\n undirected_graph.remove_edge(edge[0], edge[1])\n with pytest.raises(ValueError):\n directed_graph.remove_edge(edge[0], edge[1])\n\n def test_contains_edge_exception_check(self) -> None:\n (\n undirected_graph,\n directed_graph,\n random_vertices,\n random_edges,\n ) = self.__generate_graphs(20, 0, 100, 4)\n\n for vertex in random_vertices:\n with pytest.raises(ValueError):\n undirected_graph.contains_edge(vertex, 102)\n with pytest.raises(ValueError):\n directed_graph.contains_edge(vertex, 102)\n\n with pytest.raises(ValueError):\n undirected_graph.contains_edge(103, 102)\n with pytest.raises(ValueError):\n directed_graph.contains_edge(103, 102)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n"} +{"Prompt":"!usrbinenv python3 Author: Vikram Nithyanandam Description: The following implementation is a robust unweighted Graph data structure implemented using an adjacency matrix. This vertices and edges of this graph can be effectively initialized and modified while storing your chosen generic value in each vertex. Adjacency Matrix: https:mathworld.wolfram.comAdjacencyMatrix.html Potential Future Ideas: Add a flag to set edge weights on and set edge weights Make edge weights and vertex values customizable to store whatever the client wants Support multigraph functionality if the client wants it Parameters: vertices: listT The list of vertex names the client wants to pass in. Default is empty. edges: listlistT The list of edges the client wants to pass in. Each edge is a 2element list. Default is empty. directed: bool Indicates if graph is directed or undirected. Default is True. Falsey checks Creates an edge from source vertex to destination vertex. If any given vertex doesn't exist or the edge already exists, a ValueError will be thrown. Get the indices of the corresponding vertices and set their edge value to 1. Removes the edge between the two vertices. If any given vertex doesn't exist or the edge does not exist, a ValueError will be thrown. Get the indices of the corresponding vertices and set their edge value to 0. Adds a vertex to the graph. If the given vertex already exists, a ValueError will be thrown. build column for vertex build row for vertex and update other data structures Removes the given vertex from the graph and deletes all incoming and outgoing edges from the given vertex as well. If the given vertex does not exist, a ValueError will be thrown. first slide up the rows by deleting the row corresponding to the vertex being deleted. next, slide the columns to the left by deleting the values in the column corresponding to the vertex being deleted final clean up decrement indices for vertices shifted by the deleted vertex in the adj matrix Returns True if the graph contains the vertex, False otherwise. Returns True if the graph contains the edge from the sourcevertex to the destinationvertex, False otherwise. If any given vertex doesn't exist, a ValueError will be thrown. Clears all vertices and edges. generate graph input build graphs test graph initialization with vertices and edges Build graphs WITHOUT edges Test containsvertex build empty graphs run addvertex test addvertex worked build graphs WITHOUT edges test removevertex worked build graphs WITHOUT edges test adding and removing vertices remove all vertices generate graphs and graph input generate all possible edges for testing test containsedge function since this edge exists for undirected but the reverse may not exist for directed generate graph input build graphs WITHOUT edges run and test addedge generate graph input and graphs run and test removeedge make some more edge options!","Completions":"#!\/usr\/bin\/env python3\n\"\"\"\nAuthor: Vikram Nithyanandam\n\nDescription:\nThe following implementation is a robust unweighted Graph data structure\nimplemented using an adjacency matrix. This vertices and edges of this graph can be\neffectively initialized and modified while storing your chosen generic\nvalue in each vertex.\n\nAdjacency Matrix: https:\/\/mathworld.wolfram.com\/AdjacencyMatrix.html\n\nPotential Future Ideas:\n- Add a flag to set edge weights on and set edge weights\n- Make edge weights and vertex values customizable to store whatever the client wants\n- Support multigraph functionality if the client wants it\n\"\"\"\nfrom __future__ import annotations\n\nimport random\nimport unittest\nfrom pprint import pformat\nfrom typing import Generic, TypeVar\n\nimport pytest\n\nT = TypeVar(\"T\")\n\n\nclass GraphAdjacencyMatrix(Generic[T]):\n def __init__(\n self, vertices: list[T], edges: list[list[T]], directed: bool = True\n ) -> None:\n \"\"\"\n Parameters:\n - vertices: (list[T]) The list of vertex names the client wants to\n pass in. Default is empty.\n - edges: (list[list[T]]) The list of edges the client wants to\n pass in. Each edge is a 2-element list. Default is empty.\n - directed: (bool) Indicates if graph is directed or undirected.\n Default is True.\n \"\"\"\n self.directed = directed\n self.vertex_to_index: dict[T, int] = {}\n self.adj_matrix: list[list[int]] = []\n\n # Falsey checks\n edges = edges or []\n vertices = vertices or []\n\n for vertex in vertices:\n self.add_vertex(vertex)\n\n for edge in edges:\n if len(edge) != 2:\n msg = f\"Invalid input: {edge} must have length 2.\"\n raise ValueError(msg)\n self.add_edge(edge[0], edge[1])\n\n def add_edge(self, source_vertex: T, destination_vertex: T) -> None:\n \"\"\"\n Creates an edge from source vertex to destination vertex. If any\n given vertex doesn't exist or the edge already exists, a ValueError\n will be thrown.\n \"\"\"\n if not (\n self.contains_vertex(source_vertex)\n and self.contains_vertex(destination_vertex)\n ):\n msg = (\n f\"Incorrect input: Either {source_vertex} or \"\n f\"{destination_vertex} does not exist\"\n )\n raise ValueError(msg)\n if self.contains_edge(source_vertex, destination_vertex):\n msg = (\n \"Incorrect input: The edge already exists between \"\n f\"{source_vertex} and {destination_vertex}\"\n )\n raise ValueError(msg)\n\n # Get the indices of the corresponding vertices and set their edge value to 1.\n u: int = self.vertex_to_index[source_vertex]\n v: int = self.vertex_to_index[destination_vertex]\n self.adj_matrix[u][v] = 1\n if not self.directed:\n self.adj_matrix[v][u] = 1\n\n def remove_edge(self, source_vertex: T, destination_vertex: T) -> None:\n \"\"\"\n Removes the edge between the two vertices. If any given vertex\n doesn't exist or the edge does not exist, a ValueError will be thrown.\n \"\"\"\n if not (\n self.contains_vertex(source_vertex)\n and self.contains_vertex(destination_vertex)\n ):\n msg = (\n f\"Incorrect input: Either {source_vertex} or \"\n f\"{destination_vertex} does not exist\"\n )\n raise ValueError(msg)\n if not self.contains_edge(source_vertex, destination_vertex):\n msg = (\n \"Incorrect input: The edge does NOT exist between \"\n f\"{source_vertex} and {destination_vertex}\"\n )\n raise ValueError(msg)\n\n # Get the indices of the corresponding vertices and set their edge value to 0.\n u: int = self.vertex_to_index[source_vertex]\n v: int = self.vertex_to_index[destination_vertex]\n self.adj_matrix[u][v] = 0\n if not self.directed:\n self.adj_matrix[v][u] = 0\n\n def add_vertex(self, vertex: T) -> None:\n \"\"\"\n Adds a vertex to the graph. If the given vertex already exists,\n a ValueError will be thrown.\n \"\"\"\n if self.contains_vertex(vertex):\n msg = f\"Incorrect input: {vertex} already exists in this graph.\"\n raise ValueError(msg)\n\n # build column for vertex\n for row in self.adj_matrix:\n row.append(0)\n\n # build row for vertex and update other data structures\n self.adj_matrix.append([0] * (len(self.adj_matrix) + 1))\n self.vertex_to_index[vertex] = len(self.adj_matrix) - 1\n\n def remove_vertex(self, vertex: T) -> None:\n \"\"\"\n Removes the given vertex from the graph and deletes all incoming and\n outgoing edges from the given vertex as well. If the given vertex\n does not exist, a ValueError will be thrown.\n \"\"\"\n if not self.contains_vertex(vertex):\n msg = f\"Incorrect input: {vertex} does not exist in this graph.\"\n raise ValueError(msg)\n\n # first slide up the rows by deleting the row corresponding to\n # the vertex being deleted.\n start_index = self.vertex_to_index[vertex]\n self.adj_matrix.pop(start_index)\n\n # next, slide the columns to the left by deleting the values in\n # the column corresponding to the vertex being deleted\n for lst in self.adj_matrix:\n lst.pop(start_index)\n\n # final clean up\n self.vertex_to_index.pop(vertex)\n\n # decrement indices for vertices shifted by the deleted vertex in the adj matrix\n for vertex in self.vertex_to_index:\n if self.vertex_to_index[vertex] >= start_index:\n self.vertex_to_index[vertex] = self.vertex_to_index[vertex] - 1\n\n def contains_vertex(self, vertex: T) -> bool:\n \"\"\"\n Returns True if the graph contains the vertex, False otherwise.\n \"\"\"\n return vertex in self.vertex_to_index\n\n def contains_edge(self, source_vertex: T, destination_vertex: T) -> bool:\n \"\"\"\n Returns True if the graph contains the edge from the source_vertex to the\n destination_vertex, False otherwise. If any given vertex doesn't exist, a\n ValueError will be thrown.\n \"\"\"\n if not (\n self.contains_vertex(source_vertex)\n and self.contains_vertex(destination_vertex)\n ):\n msg = (\n f\"Incorrect input: Either {source_vertex} \"\n f\"or {destination_vertex} does not exist.\"\n )\n raise ValueError(msg)\n\n u = self.vertex_to_index[source_vertex]\n v = self.vertex_to_index[destination_vertex]\n return self.adj_matrix[u][v] == 1\n\n def clear_graph(self) -> None:\n \"\"\"\n Clears all vertices and edges.\n \"\"\"\n self.vertex_to_index = {}\n self.adj_matrix = []\n\n def __repr__(self) -> str:\n first = \"Adj Matrix:\\n\" + pformat(self.adj_matrix)\n second = \"\\nVertex to index mapping:\\n\" + pformat(self.vertex_to_index)\n return first + second\n\n\nclass TestGraphMatrix(unittest.TestCase):\n def __assert_graph_edge_exists_check(\n self,\n undirected_graph: GraphAdjacencyMatrix,\n directed_graph: GraphAdjacencyMatrix,\n edge: list[int],\n ) -> None:\n assert undirected_graph.contains_edge(edge[0], edge[1])\n assert undirected_graph.contains_edge(edge[1], edge[0])\n assert directed_graph.contains_edge(edge[0], edge[1])\n\n def __assert_graph_edge_does_not_exist_check(\n self,\n undirected_graph: GraphAdjacencyMatrix,\n directed_graph: GraphAdjacencyMatrix,\n edge: list[int],\n ) -> None:\n assert not undirected_graph.contains_edge(edge[0], edge[1])\n assert not undirected_graph.contains_edge(edge[1], edge[0])\n assert not directed_graph.contains_edge(edge[0], edge[1])\n\n def __assert_graph_vertex_exists_check(\n self,\n undirected_graph: GraphAdjacencyMatrix,\n directed_graph: GraphAdjacencyMatrix,\n vertex: int,\n ) -> None:\n assert undirected_graph.contains_vertex(vertex)\n assert directed_graph.contains_vertex(vertex)\n\n def __assert_graph_vertex_does_not_exist_check(\n self,\n undirected_graph: GraphAdjacencyMatrix,\n directed_graph: GraphAdjacencyMatrix,\n vertex: int,\n ) -> None:\n assert not undirected_graph.contains_vertex(vertex)\n assert not directed_graph.contains_vertex(vertex)\n\n def __generate_random_edges(\n self, vertices: list[int], edge_pick_count: int\n ) -> list[list[int]]:\n assert edge_pick_count <= len(vertices)\n\n random_source_vertices: list[int] = random.sample(\n vertices[0 : int(len(vertices) \/ 2)], edge_pick_count\n )\n random_destination_vertices: list[int] = random.sample(\n vertices[int(len(vertices) \/ 2) :], edge_pick_count\n )\n random_edges: list[list[int]] = []\n\n for source in random_source_vertices:\n for dest in random_destination_vertices:\n random_edges.append([source, dest])\n\n return random_edges\n\n def __generate_graphs(\n self, vertex_count: int, min_val: int, max_val: int, edge_pick_count: int\n ) -> tuple[GraphAdjacencyMatrix, GraphAdjacencyMatrix, list[int], list[list[int]]]:\n if max_val - min_val + 1 < vertex_count:\n raise ValueError(\n \"Will result in duplicate vertices. Either increase \"\n \"range between min_val and max_val or decrease vertex count\"\n )\n\n # generate graph input\n random_vertices: list[int] = random.sample(\n range(min_val, max_val + 1), vertex_count\n )\n random_edges: list[list[int]] = self.__generate_random_edges(\n random_vertices, edge_pick_count\n )\n\n # build graphs\n undirected_graph = GraphAdjacencyMatrix(\n vertices=random_vertices, edges=random_edges, directed=False\n )\n directed_graph = GraphAdjacencyMatrix(\n vertices=random_vertices, edges=random_edges, directed=True\n )\n\n return undirected_graph, directed_graph, random_vertices, random_edges\n\n def test_init_check(self) -> None:\n (\n undirected_graph,\n directed_graph,\n random_vertices,\n random_edges,\n ) = self.__generate_graphs(20, 0, 100, 4)\n\n # test graph initialization with vertices and edges\n for num in random_vertices:\n self.__assert_graph_vertex_exists_check(\n undirected_graph, directed_graph, num\n )\n\n for edge in random_edges:\n self.__assert_graph_edge_exists_check(\n undirected_graph, directed_graph, edge\n )\n\n assert not undirected_graph.directed\n assert directed_graph.directed\n\n def test_contains_vertex(self) -> None:\n random_vertices: list[int] = random.sample(range(101), 20)\n\n # Build graphs WITHOUT edges\n undirected_graph = GraphAdjacencyMatrix(\n vertices=random_vertices, edges=[], directed=False\n )\n directed_graph = GraphAdjacencyMatrix(\n vertices=random_vertices, edges=[], directed=True\n )\n\n # Test contains_vertex\n for num in range(101):\n assert (num in random_vertices) == undirected_graph.contains_vertex(num)\n assert (num in random_vertices) == directed_graph.contains_vertex(num)\n\n def test_add_vertices(self) -> None:\n random_vertices: list[int] = random.sample(range(101), 20)\n\n # build empty graphs\n undirected_graph: GraphAdjacencyMatrix = GraphAdjacencyMatrix(\n vertices=[], edges=[], directed=False\n )\n directed_graph: GraphAdjacencyMatrix = GraphAdjacencyMatrix(\n vertices=[], edges=[], directed=True\n )\n\n # run add_vertex\n for num in random_vertices:\n undirected_graph.add_vertex(num)\n\n for num in random_vertices:\n directed_graph.add_vertex(num)\n\n # test add_vertex worked\n for num in random_vertices:\n self.__assert_graph_vertex_exists_check(\n undirected_graph, directed_graph, num\n )\n\n def test_remove_vertices(self) -> None:\n random_vertices: list[int] = random.sample(range(101), 20)\n\n # build graphs WITHOUT edges\n undirected_graph = GraphAdjacencyMatrix(\n vertices=random_vertices, edges=[], directed=False\n )\n directed_graph = GraphAdjacencyMatrix(\n vertices=random_vertices, edges=[], directed=True\n )\n\n # test remove_vertex worked\n for num in random_vertices:\n self.__assert_graph_vertex_exists_check(\n undirected_graph, directed_graph, num\n )\n\n undirected_graph.remove_vertex(num)\n directed_graph.remove_vertex(num)\n\n self.__assert_graph_vertex_does_not_exist_check(\n undirected_graph, directed_graph, num\n )\n\n def test_add_and_remove_vertices_repeatedly(self) -> None:\n random_vertices1: list[int] = random.sample(range(51), 20)\n random_vertices2: list[int] = random.sample(range(51, 101), 20)\n\n # build graphs WITHOUT edges\n undirected_graph = GraphAdjacencyMatrix(\n vertices=random_vertices1, edges=[], directed=False\n )\n directed_graph = GraphAdjacencyMatrix(\n vertices=random_vertices1, edges=[], directed=True\n )\n\n # test adding and removing vertices\n for i, _ in enumerate(random_vertices1):\n undirected_graph.add_vertex(random_vertices2[i])\n directed_graph.add_vertex(random_vertices2[i])\n\n self.__assert_graph_vertex_exists_check(\n undirected_graph, directed_graph, random_vertices2[i]\n )\n\n undirected_graph.remove_vertex(random_vertices1[i])\n directed_graph.remove_vertex(random_vertices1[i])\n\n self.__assert_graph_vertex_does_not_exist_check(\n undirected_graph, directed_graph, random_vertices1[i]\n )\n\n # remove all vertices\n for i, _ in enumerate(random_vertices1):\n undirected_graph.remove_vertex(random_vertices2[i])\n directed_graph.remove_vertex(random_vertices2[i])\n\n self.__assert_graph_vertex_does_not_exist_check(\n undirected_graph, directed_graph, random_vertices2[i]\n )\n\n def test_contains_edge(self) -> None:\n # generate graphs and graph input\n vertex_count = 20\n (\n undirected_graph,\n directed_graph,\n random_vertices,\n random_edges,\n ) = self.__generate_graphs(vertex_count, 0, 100, 4)\n\n # generate all possible edges for testing\n all_possible_edges: list[list[int]] = []\n for i in range(vertex_count - 1):\n for j in range(i + 1, vertex_count):\n all_possible_edges.append([random_vertices[i], random_vertices[j]])\n all_possible_edges.append([random_vertices[j], random_vertices[i]])\n\n # test contains_edge function\n for edge in all_possible_edges:\n if edge in random_edges:\n self.__assert_graph_edge_exists_check(\n undirected_graph, directed_graph, edge\n )\n elif [edge[1], edge[0]] in random_edges:\n # since this edge exists for undirected but the reverse may\n # not exist for directed\n self.__assert_graph_edge_exists_check(\n undirected_graph, directed_graph, [edge[1], edge[0]]\n )\n else:\n self.__assert_graph_edge_does_not_exist_check(\n undirected_graph, directed_graph, edge\n )\n\n def test_add_edge(self) -> None:\n # generate graph input\n random_vertices: list[int] = random.sample(range(101), 15)\n random_edges: list[list[int]] = self.__generate_random_edges(random_vertices, 4)\n\n # build graphs WITHOUT edges\n undirected_graph = GraphAdjacencyMatrix(\n vertices=random_vertices, edges=[], directed=False\n )\n directed_graph = GraphAdjacencyMatrix(\n vertices=random_vertices, edges=[], directed=True\n )\n\n # run and test add_edge\n for edge in random_edges:\n undirected_graph.add_edge(edge[0], edge[1])\n directed_graph.add_edge(edge[0], edge[1])\n self.__assert_graph_edge_exists_check(\n undirected_graph, directed_graph, edge\n )\n\n def test_remove_edge(self) -> None:\n # generate graph input and graphs\n (\n undirected_graph,\n directed_graph,\n random_vertices,\n random_edges,\n ) = self.__generate_graphs(20, 0, 100, 4)\n\n # run and test remove_edge\n for edge in random_edges:\n self.__assert_graph_edge_exists_check(\n undirected_graph, directed_graph, edge\n )\n undirected_graph.remove_edge(edge[0], edge[1])\n directed_graph.remove_edge(edge[0], edge[1])\n self.__assert_graph_edge_does_not_exist_check(\n undirected_graph, directed_graph, edge\n )\n\n def test_add_and_remove_edges_repeatedly(self) -> None:\n (\n undirected_graph,\n directed_graph,\n random_vertices,\n random_edges,\n ) = self.__generate_graphs(20, 0, 100, 4)\n\n # make some more edge options!\n more_random_edges: list[list[int]] = []\n\n while len(more_random_edges) != len(random_edges):\n edges: list[list[int]] = self.__generate_random_edges(random_vertices, 4)\n for edge in edges:\n if len(more_random_edges) == len(random_edges):\n break\n elif edge not in more_random_edges and edge not in random_edges:\n more_random_edges.append(edge)\n\n for i, _ in enumerate(random_edges):\n undirected_graph.add_edge(more_random_edges[i][0], more_random_edges[i][1])\n directed_graph.add_edge(more_random_edges[i][0], more_random_edges[i][1])\n\n self.__assert_graph_edge_exists_check(\n undirected_graph, directed_graph, more_random_edges[i]\n )\n\n undirected_graph.remove_edge(random_edges[i][0], random_edges[i][1])\n directed_graph.remove_edge(random_edges[i][0], random_edges[i][1])\n\n self.__assert_graph_edge_does_not_exist_check(\n undirected_graph, directed_graph, random_edges[i]\n )\n\n def test_add_vertex_exception_check(self) -> None:\n (\n undirected_graph,\n directed_graph,\n random_vertices,\n random_edges,\n ) = self.__generate_graphs(20, 0, 100, 4)\n\n for vertex in random_vertices:\n with pytest.raises(ValueError):\n undirected_graph.add_vertex(vertex)\n with pytest.raises(ValueError):\n directed_graph.add_vertex(vertex)\n\n def test_remove_vertex_exception_check(self) -> None:\n (\n undirected_graph,\n directed_graph,\n random_vertices,\n random_edges,\n ) = self.__generate_graphs(20, 0, 100, 4)\n\n for i in range(101):\n if i not in random_vertices:\n with pytest.raises(ValueError):\n undirected_graph.remove_vertex(i)\n with pytest.raises(ValueError):\n directed_graph.remove_vertex(i)\n\n def test_add_edge_exception_check(self) -> None:\n (\n undirected_graph,\n directed_graph,\n random_vertices,\n random_edges,\n ) = self.__generate_graphs(20, 0, 100, 4)\n\n for edge in random_edges:\n with pytest.raises(ValueError):\n undirected_graph.add_edge(edge[0], edge[1])\n with pytest.raises(ValueError):\n directed_graph.add_edge(edge[0], edge[1])\n\n def test_remove_edge_exception_check(self) -> None:\n (\n undirected_graph,\n directed_graph,\n random_vertices,\n random_edges,\n ) = self.__generate_graphs(20, 0, 100, 4)\n\n more_random_edges: list[list[int]] = []\n\n while len(more_random_edges) != len(random_edges):\n edges: list[list[int]] = self.__generate_random_edges(random_vertices, 4)\n for edge in edges:\n if len(more_random_edges) == len(random_edges):\n break\n elif edge not in more_random_edges and edge not in random_edges:\n more_random_edges.append(edge)\n\n for edge in more_random_edges:\n with pytest.raises(ValueError):\n undirected_graph.remove_edge(edge[0], edge[1])\n with pytest.raises(ValueError):\n directed_graph.remove_edge(edge[0], edge[1])\n\n def test_contains_edge_exception_check(self) -> None:\n (\n undirected_graph,\n directed_graph,\n random_vertices,\n random_edges,\n ) = self.__generate_graphs(20, 0, 100, 4)\n\n for vertex in random_vertices:\n with pytest.raises(ValueError):\n undirected_graph.contains_edge(vertex, 102)\n with pytest.raises(ValueError):\n directed_graph.contains_edge(vertex, 102)\n\n with pytest.raises(ValueError):\n undirected_graph.contains_edge(103, 102)\n with pytest.raises(ValueError):\n directed_graph.contains_edge(103, 102)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n"} +{"Prompt":"!usrbinenv python3 Author: OMKAR PATHAK, Nwachukwu Chidiebere Use a Python dictionary to construct the graph. Adjacency List type Graph Data Structure that accounts for directed and undirected Graphs. Initialize graph object indicating whether it's directed or undirected. Directed graph example: dgraph GraphAdjacencyList printdgraph dgraph.addedge0, 1 0: 1, 1: dgraph.addedge1, 2.addedge1, 4.addedge1, 5 0: 1, 1: 2, 4, 5, 2: , 4: , 5: dgraph.addedge2, 0.addedge2, 6.addedge2, 7 0: 1, 1: 2, 4, 5, 2: 0, 6, 7, 4: , 5: , 6: , 7: dgraph 0: 1, 1: 2, 4, 5, 2: 0, 6, 7, 4: , 5: , 6: , 7: printreprdgraph 0: 1, 1: 2, 4, 5, 2: 0, 6, 7, 4: , 5: , 6: , 7: Undirected graph example: ugraph GraphAdjacencyListdirectedFalse ugraph.addedge0, 1 0: 1, 1: 0 ugraph.addedge1, 2.addedge1, 4.addedge1, 5 0: 1, 1: 0, 2, 4, 5, 2: 1, 4: 1, 5: 1 ugraph.addedge2, 0.addedge2, 6.addedge2, 7 0: 1, 2, 1: 0, 2, 4, 5, 2: 1, 0, 6, 7, 4: 1, 5: 1, 6: 2, 7: 2 ugraph.addedge4, 5 0: 1, 2, 1: 0, 2, 4, 5, 2: 1, 0, 6, 7, 4: 1, 5, 5: 1, 4, 6: 2, 7: 2 printugraph 0: 1, 2, 1: 0, 2, 4, 5, 2: 1, 0, 6, 7, 4: 1, 5, 5: 1, 4, 6: 2, 7: 2 printreprugraph 0: 1, 2, 1: 0, 2, 4, 5, 2: 1, 0, 6, 7, 4: 1, 5, 5: 1, 4, 6: 2, 7: 2 chargraph GraphAdjacencyListdirectedFalse chargraph.addedge'a', 'b' 'a': 'b', 'b': 'a' chargraph.addedge'b', 'c'.addedge'b', 'e'.addedge'b', 'f' 'a': 'b', 'b': 'a', 'c', 'e', 'f', 'c': 'b', 'e': 'b', 'f': 'b' chargraph 'a': 'b', 'b': 'a', 'c', 'e', 'f', 'c': 'b', 'e': 'b', 'f': 'b' Parameters: directed: bool Indicates if graph is directed or undirected. Default is True. Connects vertices together. Creates and Edge from source vertex to destination vertex. Vertices will be created if not found in graph if both source vertex and destination vertex are both present in the adjacency list, add destination vertex to source vertex list of adjacent vertices and add source vertex to destination vertex list of adjacent vertices. if only source vertex is present in adjacency list, add destination vertex to source vertex list of adjacent vertices, then create a new vertex with destination vertex as key and assign a list containing the source vertex as it's first adjacent vertex. if only destination vertex is present in adjacency list, add source vertex to destination vertex list of adjacent vertices, then create a new vertex with source vertex as key and assign a list containing the source vertex as it's first adjacent vertex. if both source vertex and destination vertex are not present in adjacency list, create a new vertex with source vertex as key and assign a list containing the destination vertex as it's first adjacent vertex also create a new vertex with destination vertex as key and assign a list containing the source vertex as it's first adjacent vertex. if both source vertex and destination vertex are present in adjacency list, add destination vertex to source vertex list of adjacent vertices. if only source vertex is present in adjacency list, add destination vertex to source vertex list of adjacent vertices and create a new vertex with destination vertex as key, which has no adjacent vertex if only destination vertex is present in adjacency list, create a new vertex with source vertex as key and assign a list containing destination vertex as first adjacent vertex if both source vertex and destination vertex are not present in adjacency list, create a new vertex with source vertex as key and a list containing destination vertex as it's first adjacent vertex. Then create a new vertex with destination vertex as key, which has no adjacent vertex","Completions":"#!\/usr\/bin\/env python3\n\n# Author: OMKAR PATHAK, Nwachukwu Chidiebere\n\n# Use a Python dictionary to construct the graph.\nfrom __future__ import annotations\n\nfrom pprint import pformat\nfrom typing import Generic, TypeVar\n\nT = TypeVar(\"T\")\n\n\nclass GraphAdjacencyList(Generic[T]):\n \"\"\"\n Adjacency List type Graph Data Structure that accounts for directed and undirected\n Graphs. Initialize graph object indicating whether it's directed or undirected.\n\n Directed graph example:\n >>> d_graph = GraphAdjacencyList()\n >>> print(d_graph)\n {}\n >>> d_graph.add_edge(0, 1)\n {0: [1], 1: []}\n >>> d_graph.add_edge(1, 2).add_edge(1, 4).add_edge(1, 5)\n {0: [1], 1: [2, 4, 5], 2: [], 4: [], 5: []}\n >>> d_graph.add_edge(2, 0).add_edge(2, 6).add_edge(2, 7)\n {0: [1], 1: [2, 4, 5], 2: [0, 6, 7], 4: [], 5: [], 6: [], 7: []}\n >>> d_graph\n {0: [1], 1: [2, 4, 5], 2: [0, 6, 7], 4: [], 5: [], 6: [], 7: []}\n >>> print(repr(d_graph))\n {0: [1], 1: [2, 4, 5], 2: [0, 6, 7], 4: [], 5: [], 6: [], 7: []}\n\n Undirected graph example:\n >>> u_graph = GraphAdjacencyList(directed=False)\n >>> u_graph.add_edge(0, 1)\n {0: [1], 1: [0]}\n >>> u_graph.add_edge(1, 2).add_edge(1, 4).add_edge(1, 5)\n {0: [1], 1: [0, 2, 4, 5], 2: [1], 4: [1], 5: [1]}\n >>> u_graph.add_edge(2, 0).add_edge(2, 6).add_edge(2, 7)\n {0: [1, 2], 1: [0, 2, 4, 5], 2: [1, 0, 6, 7], 4: [1], 5: [1], 6: [2], 7: [2]}\n >>> u_graph.add_edge(4, 5)\n {0: [1, 2],\n 1: [0, 2, 4, 5],\n 2: [1, 0, 6, 7],\n 4: [1, 5],\n 5: [1, 4],\n 6: [2],\n 7: [2]}\n >>> print(u_graph)\n {0: [1, 2],\n 1: [0, 2, 4, 5],\n 2: [1, 0, 6, 7],\n 4: [1, 5],\n 5: [1, 4],\n 6: [2],\n 7: [2]}\n >>> print(repr(u_graph))\n {0: [1, 2],\n 1: [0, 2, 4, 5],\n 2: [1, 0, 6, 7],\n 4: [1, 5],\n 5: [1, 4],\n 6: [2],\n 7: [2]}\n >>> char_graph = GraphAdjacencyList(directed=False)\n >>> char_graph.add_edge('a', 'b')\n {'a': ['b'], 'b': ['a']}\n >>> char_graph.add_edge('b', 'c').add_edge('b', 'e').add_edge('b', 'f')\n {'a': ['b'], 'b': ['a', 'c', 'e', 'f'], 'c': ['b'], 'e': ['b'], 'f': ['b']}\n >>> char_graph\n {'a': ['b'], 'b': ['a', 'c', 'e', 'f'], 'c': ['b'], 'e': ['b'], 'f': ['b']}\n \"\"\"\n\n def __init__(self, directed: bool = True) -> None:\n \"\"\"\n Parameters:\n directed: (bool) Indicates if graph is directed or undirected. Default is True.\n \"\"\"\n\n self.adj_list: dict[T, list[T]] = {} # dictionary of lists\n self.directed = directed\n\n def add_edge(\n self, source_vertex: T, destination_vertex: T\n ) -> GraphAdjacencyList[T]:\n \"\"\"\n Connects vertices together. Creates and Edge from source vertex to destination\n vertex.\n Vertices will be created if not found in graph\n \"\"\"\n\n if not self.directed: # For undirected graphs\n # if both source vertex and destination vertex are both present in the\n # adjacency list, add destination vertex to source vertex list of adjacent\n # vertices and add source vertex to destination vertex list of adjacent\n # vertices.\n if source_vertex in self.adj_list and destination_vertex in self.adj_list:\n self.adj_list[source_vertex].append(destination_vertex)\n self.adj_list[destination_vertex].append(source_vertex)\n # if only source vertex is present in adjacency list, add destination vertex\n # to source vertex list of adjacent vertices, then create a new vertex with\n # destination vertex as key and assign a list containing the source vertex\n # as it's first adjacent vertex.\n elif source_vertex in self.adj_list:\n self.adj_list[source_vertex].append(destination_vertex)\n self.adj_list[destination_vertex] = [source_vertex]\n # if only destination vertex is present in adjacency list, add source vertex\n # to destination vertex list of adjacent vertices, then create a new vertex\n # with source vertex as key and assign a list containing the source vertex\n # as it's first adjacent vertex.\n elif destination_vertex in self.adj_list:\n self.adj_list[destination_vertex].append(source_vertex)\n self.adj_list[source_vertex] = [destination_vertex]\n # if both source vertex and destination vertex are not present in adjacency\n # list, create a new vertex with source vertex as key and assign a list\n # containing the destination vertex as it's first adjacent vertex also\n # create a new vertex with destination vertex as key and assign a list\n # containing the source vertex as it's first adjacent vertex.\n else:\n self.adj_list[source_vertex] = [destination_vertex]\n self.adj_list[destination_vertex] = [source_vertex]\n else: # For directed graphs\n # if both source vertex and destination vertex are present in adjacency\n # list, add destination vertex to source vertex list of adjacent vertices.\n if source_vertex in self.adj_list and destination_vertex in self.adj_list:\n self.adj_list[source_vertex].append(destination_vertex)\n # if only source vertex is present in adjacency list, add destination\n # vertex to source vertex list of adjacent vertices and create a new vertex\n # with destination vertex as key, which has no adjacent vertex\n elif source_vertex in self.adj_list:\n self.adj_list[source_vertex].append(destination_vertex)\n self.adj_list[destination_vertex] = []\n # if only destination vertex is present in adjacency list, create a new\n # vertex with source vertex as key and assign a list containing destination\n # vertex as first adjacent vertex\n elif destination_vertex in self.adj_list:\n self.adj_list[source_vertex] = [destination_vertex]\n # if both source vertex and destination vertex are not present in adjacency\n # list, create a new vertex with source vertex as key and a list containing\n # destination vertex as it's first adjacent vertex. Then create a new vertex\n # with destination vertex as key, which has no adjacent vertex\n else:\n self.adj_list[source_vertex] = [destination_vertex]\n self.adj_list[destination_vertex] = []\n\n return self\n\n def __repr__(self) -> str:\n return pformat(self.adj_list)\n"} +{"Prompt":"floydwarshall.py The problem is to find the shortest distance between all pairs of vertices in a weighted directed graph that can have negative edge weights. :param graph: 2D array calculated from weightedgei, j :type graph: ListListfloat :param v: number of vertices :type v: int :return: shortest distance between all vertex pairs distanceuv will contain the shortest distance from vertex u to v. 1. For all edges from v to n, distanceij weightedgei, j. 3. The algorithm then performs distanceij mindistanceij, distanceik distancekj for each possible pair i, j of vertices. 4. The above is repeated for each vertex k in the graph. 5. Whenever distanceij is given a new minimum value, next vertexij is updated to the next vertexik. check vertex k against all other vertices i, j looping through rows of graph array looping through columns of graph array src and dst are indices that must be within the array size graphev failure to follow this will result in an error Example Input Enter number of vertices: 3 Enter number of edges: 2 generated graph from vertex and edge inputs inf, inf, inf, inf, inf, inf, inf, inf, inf 0.0, inf, inf, inf, 0.0, inf, inf, inf, 0.0 specify source, destination and weight for edge 1 Edge 1 Enter source:1 Enter destination:2 Enter weight:2 specify source, destination and weight for edge 2 Edge 2 Enter source:2 Enter destination:1 Enter weight:1 Expected Output from the vertice, edge and src, dst, weight inputs!! 0\t\tINF\tINF INF\t0\t2 INF\t1\t0","Completions":"# floyd_warshall.py\n\"\"\"\n The problem is to find the shortest distance between all pairs of vertices in a\n weighted directed graph that can have negative edge weights.\n\"\"\"\n\n\ndef _print_dist(dist, v):\n print(\"\\nThe shortest path matrix using Floyd Warshall algorithm\\n\")\n for i in range(v):\n for j in range(v):\n if dist[i][j] != float(\"inf\"):\n print(int(dist[i][j]), end=\"\\t\")\n else:\n print(\"INF\", end=\"\\t\")\n print()\n\n\ndef floyd_warshall(graph, v):\n \"\"\"\n :param graph: 2D array calculated from weight[edge[i, j]]\n :type graph: List[List[float]]\n :param v: number of vertices\n :type v: int\n :return: shortest distance between all vertex pairs\n distance[u][v] will contain the shortest distance from vertex u to v.\n\n 1. For all edges from v to n, distance[i][j] = weight(edge(i, j)).\n 3. The algorithm then performs distance[i][j] = min(distance[i][j], distance[i][k] +\n distance[k][j]) for each possible pair i, j of vertices.\n 4. The above is repeated for each vertex k in the graph.\n 5. Whenever distance[i][j] is given a new minimum value, next vertex[i][j] is\n updated to the next vertex[i][k].\n \"\"\"\n\n dist = [[float(\"inf\") for _ in range(v)] for _ in range(v)]\n\n for i in range(v):\n for j in range(v):\n dist[i][j] = graph[i][j]\n\n # check vertex k against all other vertices (i, j)\n for k in range(v):\n # looping through rows of graph array\n for i in range(v):\n # looping through columns of graph array\n for j in range(v):\n if (\n dist[i][k] != float(\"inf\")\n and dist[k][j] != float(\"inf\")\n and dist[i][k] + dist[k][j] < dist[i][j]\n ):\n dist[i][j] = dist[i][k] + dist[k][j]\n\n _print_dist(dist, v)\n return dist, v\n\n\nif __name__ == \"__main__\":\n v = int(input(\"Enter number of vertices: \"))\n e = int(input(\"Enter number of edges: \"))\n\n graph = [[float(\"inf\") for i in range(v)] for j in range(v)]\n\n for i in range(v):\n graph[i][i] = 0.0\n\n # src and dst are indices that must be within the array size graph[e][v]\n # failure to follow this will result in an error\n for i in range(e):\n print(\"\\nEdge \", i + 1)\n src = int(input(\"Enter source:\"))\n dst = int(input(\"Enter destination:\"))\n weight = float(input(\"Enter weight:\"))\n graph[src][dst] = weight\n\n floyd_warshall(graph, v)\n\n # Example Input\n # Enter number of vertices: 3\n # Enter number of edges: 2\n\n # # generated graph from vertex and edge inputs\n # [[inf, inf, inf], [inf, inf, inf], [inf, inf, inf]]\n # [[0.0, inf, inf], [inf, 0.0, inf], [inf, inf, 0.0]]\n\n # specify source, destination and weight for edge #1\n # Edge 1\n # Enter source:1\n # Enter destination:2\n # Enter weight:2\n\n # specify source, destination and weight for edge #2\n # Edge 2\n # Enter source:2\n # Enter destination:1\n # Enter weight:1\n\n # # Expected Output from the vertice, edge and src, dst, weight inputs!!\n # 0\t\tINF\tINF\n # INF\t0\t2\n # INF\t1\t0\n"} +{"Prompt":"https:en.wikipedia.orgwikiBestfirstsearchGreedyBFS 0's are free path whereas 1's are obstacles k Node0, 0, 4, 5, 0, None k.calculateheuristic 9 n Node1, 4, 3, 4, 2, None n.calculateheuristic 2 l k, n n l0 False l.sort n l0 True The heuristic here is the Manhattan Distance Could elaborate to offer more than one choice grid TESTGRIDS2 gbf GreedyBestFirstgrid, 0, 0, lengrid 1, lengrid0 1 x.pos for x in gbf.getsuccessorsgbf.start 1, 0, 0, 1 gbf.start.posy delta30, gbf.start.posx delta31 0, 1 gbf.start.posy delta20, gbf.start.posx delta21 1, 0 gbf.retracepathgbf.start 0, 0 gbf.search doctest: NORMALIZEWHITESPACE 0, 0, 1, 0, 2, 0, 2, 1, 3, 1, 4, 1, 4, 2, 4, 3, 4, 4 Search for the path, if a path is not found, only the starting position is returned Open Nodes are sorted using lt Returns a list of successors both in the grid and free spaces Retrace the path from parents to parents until start node","Completions":"from __future__ import annotations\n\nPath = list[tuple[int, int]]\n\n# 0's are free path whereas 1's are obstacles\nTEST_GRIDS = [\n [\n [0, 0, 0, 0, 0, 0, 0],\n [0, 1, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0],\n [0, 0, 1, 0, 0, 0, 0],\n [1, 0, 1, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 1, 0, 0],\n ],\n [\n [0, 0, 0, 1, 1, 0, 0],\n [0, 0, 0, 0, 1, 0, 1],\n [0, 0, 0, 1, 1, 0, 0],\n [0, 1, 0, 0, 1, 0, 0],\n [1, 0, 0, 1, 1, 0, 1],\n [0, 0, 0, 0, 0, 0, 0],\n ],\n [\n [0, 0, 1, 0, 0],\n [0, 1, 0, 0, 0],\n [0, 0, 1, 0, 1],\n [1, 0, 0, 1, 1],\n [0, 0, 0, 0, 0],\n ],\n]\n\ndelta = ([-1, 0], [0, -1], [1, 0], [0, 1]) # up, left, down, right\n\n\nclass Node:\n \"\"\"\n >>> k = Node(0, 0, 4, 5, 0, None)\n >>> k.calculate_heuristic()\n 9\n >>> n = Node(1, 4, 3, 4, 2, None)\n >>> n.calculate_heuristic()\n 2\n >>> l = [k, n]\n >>> n == l[0]\n False\n >>> l.sort()\n >>> n == l[0]\n True\n \"\"\"\n\n def __init__(\n self,\n pos_x: int,\n pos_y: int,\n goal_x: int,\n goal_y: int,\n g_cost: float,\n parent: Node | None,\n ):\n self.pos_x = pos_x\n self.pos_y = pos_y\n self.pos = (pos_y, pos_x)\n self.goal_x = goal_x\n self.goal_y = goal_y\n self.g_cost = g_cost\n self.parent = parent\n self.f_cost = self.calculate_heuristic()\n\n def calculate_heuristic(self) -> float:\n \"\"\"\n The heuristic here is the Manhattan Distance\n Could elaborate to offer more than one choice\n \"\"\"\n dx = abs(self.pos_x - self.goal_x)\n dy = abs(self.pos_y - self.goal_y)\n return dx + dy\n\n def __lt__(self, other) -> bool:\n return self.f_cost < other.f_cost\n\n def __eq__(self, other) -> bool:\n return self.pos == other.pos\n\n\nclass GreedyBestFirst:\n \"\"\"\n >>> grid = TEST_GRIDS[2]\n >>> gbf = GreedyBestFirst(grid, (0, 0), (len(grid) - 1, len(grid[0]) - 1))\n >>> [x.pos for x in gbf.get_successors(gbf.start)]\n [(1, 0), (0, 1)]\n >>> (gbf.start.pos_y + delta[3][0], gbf.start.pos_x + delta[3][1])\n (0, 1)\n >>> (gbf.start.pos_y + delta[2][0], gbf.start.pos_x + delta[2][1])\n (1, 0)\n >>> gbf.retrace_path(gbf.start)\n [(0, 0)]\n >>> gbf.search() # doctest: +NORMALIZE_WHITESPACE\n [(0, 0), (1, 0), (2, 0), (2, 1), (3, 1), (4, 1), (4, 2), (4, 3),\n (4, 4)]\n \"\"\"\n\n def __init__(\n self, grid: list[list[int]], start: tuple[int, int], goal: tuple[int, int]\n ):\n self.grid = grid\n self.start = Node(start[1], start[0], goal[1], goal[0], 0, None)\n self.target = Node(goal[1], goal[0], goal[1], goal[0], 99999, None)\n\n self.open_nodes = [self.start]\n self.closed_nodes: list[Node] = []\n\n self.reached = False\n\n def search(self) -> Path | None:\n \"\"\"\n Search for the path,\n if a path is not found, only the starting position is returned\n \"\"\"\n while self.open_nodes:\n # Open Nodes are sorted using __lt__\n self.open_nodes.sort()\n current_node = self.open_nodes.pop(0)\n\n if current_node.pos == self.target.pos:\n self.reached = True\n return self.retrace_path(current_node)\n\n self.closed_nodes.append(current_node)\n successors = self.get_successors(current_node)\n\n for child_node in successors:\n if child_node in self.closed_nodes:\n continue\n\n if child_node not in self.open_nodes:\n self.open_nodes.append(child_node)\n\n if not self.reached:\n return [self.start.pos]\n return None\n\n def get_successors(self, parent: Node) -> list[Node]:\n \"\"\"\n Returns a list of successors (both in the grid and free spaces)\n \"\"\"\n return [\n Node(\n pos_x,\n pos_y,\n self.target.pos_x,\n self.target.pos_y,\n parent.g_cost + 1,\n parent,\n )\n for action in delta\n if (\n 0 <= (pos_x := parent.pos_x + action[1]) < len(self.grid[0])\n and 0 <= (pos_y := parent.pos_y + action[0]) < len(self.grid)\n and self.grid[pos_y][pos_x] == 0\n )\n ]\n\n def retrace_path(self, node: Node | None) -> Path:\n \"\"\"\n Retrace the path from parents to parents until start node\n \"\"\"\n current_node = node\n path = []\n while current_node is not None:\n path.append((current_node.pos_y, current_node.pos_x))\n current_node = current_node.parent\n path.reverse()\n return path\n\n\nif __name__ == \"__main__\":\n for idx, grid in enumerate(TEST_GRIDS):\n print(f\"==grid-{idx + 1}==\")\n\n init = (0, 0)\n goal = (len(grid) - 1, len(grid[0]) - 1)\n for elem in grid:\n print(elem)\n\n print(\"------\")\n\n greedy_bf = GreedyBestFirst(grid, init, goal)\n path = greedy_bf.search()\n if path:\n for pos_x, pos_y in path:\n grid[pos_x][pos_y] = 2\n\n for elem in grid:\n print(elem)\n"} +{"Prompt":"Author: Manuel Di Lullo https:github.commanueldilullo Description: Approximization algorithm for minimum vertex cover problem. Greedy Approach. Uses graphs represented with an adjacency list URL: https:mathworld.wolfram.comMinimumVertexCover.html URL: https:cs.stackexchange.comquestions129017greedyalgorithmforvertexcover Greedy APX Algorithm for min Vertex Cover input: graph graph stored in an adjacency list where each vertex is represented with an integer example: graph 0: 1, 3, 1: 0, 3, 2: 0, 3, 4, 3: 0, 1, 2, 4: 2, 3 greedyminvertexcovergraph 0, 1, 2, 4 queue used to store nodes and their rank for each node and his adjacency list add them and the rank of the node to queue using heapq module the queue will be filled like a Priority Queue heapq works with a min priority queue, so I used 1lenv to build it Ologn chosenvertices set of chosen vertices while queue isn't empty and there are still edges queue00 is the rank of the node with max rank extract vertex with max rank from queue and add it to chosenvertices Remove all arcs adjacent to argmax if v haven't adjacent node, skip if argmax is reachable from elem remove argmax from elem's adjacent list and update his rank reorder the queue","Completions":"import heapq\n\n\ndef greedy_min_vertex_cover(graph: dict) -> set[int]:\n \"\"\"\n Greedy APX Algorithm for min Vertex Cover\n @input: graph (graph stored in an adjacency list where each vertex\n is represented with an integer)\n @example:\n >>> graph = {0: [1, 3], 1: [0, 3], 2: [0, 3, 4], 3: [0, 1, 2], 4: [2, 3]}\n >>> greedy_min_vertex_cover(graph)\n {0, 1, 2, 4}\n \"\"\"\n # queue used to store nodes and their rank\n queue: list[list] = []\n\n # for each node and his adjacency list add them and the rank of the node to queue\n # using heapq module the queue will be filled like a Priority Queue\n # heapq works with a min priority queue, so I used -1*len(v) to build it\n for key, value in graph.items():\n # O(log(n))\n heapq.heappush(queue, [-1 * len(value), (key, value)])\n\n # chosen_vertices = set of chosen vertices\n chosen_vertices = set()\n\n # while queue isn't empty and there are still edges\n # (queue[0][0] is the rank of the node with max rank)\n while queue and queue[0][0] != 0:\n # extract vertex with max rank from queue and add it to chosen_vertices\n argmax = heapq.heappop(queue)[1][0]\n chosen_vertices.add(argmax)\n\n # Remove all arcs adjacent to argmax\n for elem in queue:\n # if v haven't adjacent node, skip\n if elem[0] == 0:\n continue\n # if argmax is reachable from elem\n # remove argmax from elem's adjacent list and update his rank\n if argmax in elem[1][1]:\n index = elem[1][1].index(argmax)\n del elem[1][1][index]\n elem[0] += 1\n # re-order the queue\n heapq.heapify(queue)\n return chosen_vertices\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n\n graph = {0: [1, 3], 1: [0, 3], 2: [0, 3, 4], 3: [0, 1, 2], 4: [2, 3]}\n print(f\"Minimum vertex cover:\\n{greedy_min_vertex_cover(graph)}\")\n"} +{"Prompt":"Finding longest distance in Directed Acyclic Graph using KahnsAlgorithm Adjacency list of Graph","Completions":"# Finding longest distance in Directed Acyclic Graph using KahnsAlgorithm\ndef longest_distance(graph):\n indegree = [0] * len(graph)\n queue = []\n long_dist = [1] * len(graph)\n\n for values in graph.values():\n for i in values:\n indegree[i] += 1\n\n for i in range(len(indegree)):\n if indegree[i] == 0:\n queue.append(i)\n\n while queue:\n vertex = queue.pop(0)\n for x in graph[vertex]:\n indegree[x] -= 1\n\n if long_dist[vertex] + 1 > long_dist[x]:\n long_dist[x] = long_dist[vertex] + 1\n\n if indegree[x] == 0:\n queue.append(x)\n\n print(max(long_dist))\n\n\n# Adjacency list of Graph\ngraph = {0: [2, 3, 4], 1: [2, 7], 2: [5], 3: [5, 7], 4: [7], 5: [6], 6: [7], 7: []}\nlongest_distance(graph)\n"} +{"Prompt":"Kahn's Algorithm is used to find Topological ordering of Directed Acyclic Graph using BFS Adjacency List of Graph","Completions":"def topological_sort(graph):\n \"\"\"\n Kahn's Algorithm is used to find Topological ordering of Directed Acyclic Graph\n using BFS\n \"\"\"\n indegree = [0] * len(graph)\n queue = []\n topo = []\n cnt = 0\n\n for values in graph.values():\n for i in values:\n indegree[i] += 1\n\n for i in range(len(indegree)):\n if indegree[i] == 0:\n queue.append(i)\n\n while queue:\n vertex = queue.pop(0)\n cnt += 1\n topo.append(vertex)\n for x in graph[vertex]:\n indegree[x] -= 1\n if indegree[x] == 0:\n queue.append(x)\n\n if cnt != len(graph):\n print(\"Cycle exists\")\n else:\n print(topo)\n\n\n# Adjacency List of Graph\ngraph = {0: [1, 2], 1: [3], 2: [3], 3: [4, 5], 4: [], 5: []}\ntopological_sort(graph)\n"} +{"Prompt":"An implementation of Karger's Algorithm for partitioning a graph. Adjacency list representation of this graph: https:en.wikipedia.orgwikiFile:SinglerunofKargerE28099sMincutalgorithm.svg Partitions a graph using Karger's Algorithm. Implemented from pseudocode found here: https:en.wikipedia.orgwikiKarger27salgorithm. This function involves random choices, meaning it will not give consistent outputs. Args: graph: A dictionary containing adacency lists for the graph. Nodes must be strings. Returns: The cutset of the cut found by Karger's Algorithm. graph '0':'1', '1':'0' partitiongraphgraph '0', '1' Dict that maps contracted nodes to a list of all the nodes it contains. Choose a random edge. Contract edge u, v to new node uv Remove nodes u and v. Find cutset.","Completions":"from __future__ import annotations\n\nimport random\n\n# Adjacency list representation of this graph:\n# https:\/\/en.wikipedia.org\/wiki\/File:Single_run_of_Karger%E2%80%99s_Mincut_algorithm.svg\nTEST_GRAPH = {\n \"1\": [\"2\", \"3\", \"4\", \"5\"],\n \"2\": [\"1\", \"3\", \"4\", \"5\"],\n \"3\": [\"1\", \"2\", \"4\", \"5\", \"10\"],\n \"4\": [\"1\", \"2\", \"3\", \"5\", \"6\"],\n \"5\": [\"1\", \"2\", \"3\", \"4\", \"7\"],\n \"6\": [\"7\", \"8\", \"9\", \"10\", \"4\"],\n \"7\": [\"6\", \"8\", \"9\", \"10\", \"5\"],\n \"8\": [\"6\", \"7\", \"9\", \"10\"],\n \"9\": [\"6\", \"7\", \"8\", \"10\"],\n \"10\": [\"6\", \"7\", \"8\", \"9\", \"3\"],\n}\n\n\ndef partition_graph(graph: dict[str, list[str]]) -> set[tuple[str, str]]:\n \"\"\"\n Partitions a graph using Karger's Algorithm. Implemented from\n pseudocode found here:\n https:\/\/en.wikipedia.org\/wiki\/Karger%27s_algorithm.\n This function involves random choices, meaning it will not give\n consistent outputs.\n\n Args:\n graph: A dictionary containing adacency lists for the graph.\n Nodes must be strings.\n\n Returns:\n The cutset of the cut found by Karger's Algorithm.\n\n >>> graph = {'0':['1'], '1':['0']}\n >>> partition_graph(graph)\n {('0', '1')}\n \"\"\"\n # Dict that maps contracted nodes to a list of all the nodes it \"contains.\"\n contracted_nodes = {node: {node} for node in graph}\n\n graph_copy = {node: graph[node][:] for node in graph}\n\n while len(graph_copy) > 2:\n # Choose a random edge.\n u = random.choice(list(graph_copy.keys()))\n v = random.choice(graph_copy[u])\n\n # Contract edge (u, v) to new node uv\n uv = u + v\n uv_neighbors = list(set(graph_copy[u] + graph_copy[v]))\n uv_neighbors.remove(u)\n uv_neighbors.remove(v)\n graph_copy[uv] = uv_neighbors\n for neighbor in uv_neighbors:\n graph_copy[neighbor].append(uv)\n\n contracted_nodes[uv] = set(contracted_nodes[u].union(contracted_nodes[v]))\n\n # Remove nodes u and v.\n del graph_copy[u]\n del graph_copy[v]\n for neighbor in uv_neighbors:\n if u in graph_copy[neighbor]:\n graph_copy[neighbor].remove(u)\n if v in graph_copy[neighbor]:\n graph_copy[neighbor].remove(v)\n\n # Find cutset.\n groups = [contracted_nodes[node] for node in graph_copy]\n return {\n (node, neighbor)\n for node in groups[0]\n for neighbor in graph[node]\n if neighbor in groups[1]\n }\n\n\nif __name__ == \"__main__\":\n print(partition_graph(TEST_GRAPH))\n"} +{"Prompt":"Undirected Unweighted Graph for running Markov Chain Algorithm Running Markov Chain algorithm and calculating the number of times each node is visited transitions ... 'a', 'a', 0.9, ... 'a', 'b', 0.075, ... 'a', 'c', 0.025, ... 'b', 'a', 0.15, ... 'b', 'b', 0.8, ... 'b', 'c', 0.05, ... 'c', 'a', 0.25, ... 'c', 'b', 0.25, ... 'c', 'c', 0.5 ... result gettransitions'a', transitions, 5000 result'a' result'b' result'c' True","Completions":"from __future__ import annotations\n\nfrom collections import Counter\nfrom random import random\n\n\nclass MarkovChainGraphUndirectedUnweighted:\n \"\"\"\n Undirected Unweighted Graph for running Markov Chain Algorithm\n \"\"\"\n\n def __init__(self):\n self.connections = {}\n\n def add_node(self, node: str) -> None:\n self.connections[node] = {}\n\n def add_transition_probability(\n self, node1: str, node2: str, probability: float\n ) -> None:\n if node1 not in self.connections:\n self.add_node(node1)\n if node2 not in self.connections:\n self.add_node(node2)\n self.connections[node1][node2] = probability\n\n def get_nodes(self) -> list[str]:\n return list(self.connections)\n\n def transition(self, node: str) -> str:\n current_probability = 0\n random_value = random()\n\n for dest in self.connections[node]:\n current_probability += self.connections[node][dest]\n if current_probability > random_value:\n return dest\n return \"\"\n\n\ndef get_transitions(\n start: str, transitions: list[tuple[str, str, float]], steps: int\n) -> dict[str, int]:\n \"\"\"\n Running Markov Chain algorithm and calculating the number of times each node is\n visited\n\n >>> transitions = [\n ... ('a', 'a', 0.9),\n ... ('a', 'b', 0.075),\n ... ('a', 'c', 0.025),\n ... ('b', 'a', 0.15),\n ... ('b', 'b', 0.8),\n ... ('b', 'c', 0.05),\n ... ('c', 'a', 0.25),\n ... ('c', 'b', 0.25),\n ... ('c', 'c', 0.5)\n ... ]\n\n >>> result = get_transitions('a', transitions, 5000)\n\n >>> result['a'] > result['b'] > result['c']\n True\n \"\"\"\n\n graph = MarkovChainGraphUndirectedUnweighted()\n\n for node1, node2, probability in transitions:\n graph.add_transition_probability(node1, node2, probability)\n\n visited = Counter(graph.get_nodes())\n node = start\n\n for _ in range(steps):\n node = graph.transition(node)\n visited[node] += 1\n\n return visited\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Author: Manuel Di Lullo https:github.commanueldilullo Description: Approximization algorithm for minimum vertex cover problem. Matching Approach. Uses graphs represented with an adjacency list URL: https:mathworld.wolfram.comMinimumVertexCover.html URL: https:www.princeton.eduaaaPublicTeachingORF523ORF523Lec6.pdf APX Algorithm for min Vertex Cover using Matching Approach input: graph graph stored in an adjacency list where each vertex is represented as an integer example: graph 0: 1, 3, 1: 0, 3, 2: 0, 3, 4, 3: 0, 1, 2, 4: 2, 3 matchingminvertexcovergraph 0, 1, 2, 4 chosenvertices set of chosen vertices edges list of graph's edges While there are still elements in edges list, take an arbitrary edge fromnode, tonode and add his extremity to chosenvertices and then remove all arcs adjacent to the fromnode and tonode Return a set of couples that represents all of the edges. input: graph graph stored in an adjacency list where each vertex is represented as an integer example: graph 0: 1, 3, 1: 0, 3, 2: 0, 3, 3: 0, 1, 2 getedgesgraph 0, 1, 3, 1, 0, 3, 2, 0, 3, 0, 2, 3, 1, 0, 3, 2, 1, 3 graph 0: 1, 3, 1: 0, 3, 2: 0, 3, 4, 3: 0, 1, 2, 4: 2, 3 printfMatching vertex cover:nmatchingminvertexcovergraph","Completions":"def matching_min_vertex_cover(graph: dict) -> set:\n \"\"\"\n APX Algorithm for min Vertex Cover using Matching Approach\n @input: graph (graph stored in an adjacency list where each vertex\n is represented as an integer)\n @example:\n >>> graph = {0: [1, 3], 1: [0, 3], 2: [0, 3, 4], 3: [0, 1, 2], 4: [2, 3]}\n >>> matching_min_vertex_cover(graph)\n {0, 1, 2, 4}\n \"\"\"\n # chosen_vertices = set of chosen vertices\n chosen_vertices = set()\n # edges = list of graph's edges\n edges = get_edges(graph)\n\n # While there are still elements in edges list, take an arbitrary edge\n # (from_node, to_node) and add his extremity to chosen_vertices and then\n # remove all arcs adjacent to the from_node and to_node\n while edges:\n from_node, to_node = edges.pop()\n chosen_vertices.add(from_node)\n chosen_vertices.add(to_node)\n for edge in edges.copy():\n if from_node in edge or to_node in edge:\n edges.discard(edge)\n return chosen_vertices\n\n\ndef get_edges(graph: dict) -> set:\n \"\"\"\n Return a set of couples that represents all of the edges.\n @input: graph (graph stored in an adjacency list where each vertex is\n represented as an integer)\n @example:\n >>> graph = {0: [1, 3], 1: [0, 3], 2: [0, 3], 3: [0, 1, 2]}\n >>> get_edges(graph)\n {(0, 1), (3, 1), (0, 3), (2, 0), (3, 0), (2, 3), (1, 0), (3, 2), (1, 3)}\n \"\"\"\n edges = set()\n for from_node, to_nodes in graph.items():\n for to_node in to_nodes:\n edges.add((from_node, to_node))\n return edges\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n\n # graph = {0: [1, 3], 1: [0, 3], 2: [0, 3, 4], 3: [0, 1, 2], 4: [2, 3]}\n # print(f\"Matching vertex cover:\\n{matching_min_vertex_cover(graph)}\")\n"} +{"Prompt":"Find the path from top left to bottom right of array of numbers with the lowest possible sum and return the sum along this path. minpathsum ... 1, 3, 1, ... 1, 5, 1, ... 4, 2, 1, ... 7 minpathsum ... 1, 0, 5, 6, 7, ... 8, 9, 0, 4, 2, ... 4, 4, 4, 5, 1, ... 9, 6, 3, 1, 0, ... 8, 4, 3, 2, 7, ... 20 minpathsumNone Traceback most recent call last: ... TypeError: The grid does not contain the appropriate information minpathsum Traceback most recent call last: ... TypeError: The grid does not contain the appropriate information fillrow2, 2, 2, 1, 2, 3 3, 4, 5","Completions":"def min_path_sum(grid: list) -> int:\n \"\"\"\n Find the path from top left to bottom right of array of numbers\n with the lowest possible sum and return the sum along this path.\n >>> min_path_sum([\n ... [1, 3, 1],\n ... [1, 5, 1],\n ... [4, 2, 1],\n ... ])\n 7\n\n >>> min_path_sum([\n ... [1, 0, 5, 6, 7],\n ... [8, 9, 0, 4, 2],\n ... [4, 4, 4, 5, 1],\n ... [9, 6, 3, 1, 0],\n ... [8, 4, 3, 2, 7],\n ... ])\n 20\n\n >>> min_path_sum(None)\n Traceback (most recent call last):\n ...\n TypeError: The grid does not contain the appropriate information\n\n >>> min_path_sum([[]])\n Traceback (most recent call last):\n ...\n TypeError: The grid does not contain the appropriate information\n \"\"\"\n\n if not grid or not grid[0]:\n raise TypeError(\"The grid does not contain the appropriate information\")\n\n for cell_n in range(1, len(grid[0])):\n grid[0][cell_n] += grid[0][cell_n - 1]\n row_above = grid[0]\n\n for row_n in range(1, len(grid)):\n current_row = grid[row_n]\n grid[row_n] = fill_row(current_row, row_above)\n row_above = grid[row_n]\n\n return grid[-1][-1]\n\n\ndef fill_row(current_row: list, row_above: list) -> list:\n \"\"\"\n >>> fill_row([2, 2, 2], [1, 2, 3])\n [3, 4, 5]\n \"\"\"\n\n current_row[0] += row_above[0]\n for cell_n in range(1, len(current_row)):\n current_row[cell_n] += min(current_row[cell_n - 1], row_above[cell_n])\n\n return current_row\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Data structure to store graphs based on adjacency lists Adds a vertex to the graph Adds an edge to the graph For Boruvks's algorithm the weights should be distinct Converts the weights to be distinct Returns string representation of the graph Returna all edges in the graph Returns all vertices in the graph Builds a graph from the given set of vertices and edges Disjoint set Union and Find for Boruvka's algorithm Implementation of Boruvka's algorithm g Graph g Graph.build0, 1, 2, 3, 0, 1, 1, 0, 2, 1,2, 3, 1 g.distinctweight bg Graph.boruvkamstg printbg 1 0 1 2 0 2 0 1 1 0 2 2 3 2 3 2 3 3","Completions":"class Graph:\n \"\"\"\n Data structure to store graphs (based on adjacency lists)\n \"\"\"\n\n def __init__(self):\n self.num_vertices = 0\n self.num_edges = 0\n self.adjacency = {}\n\n def add_vertex(self, vertex):\n \"\"\"\n Adds a vertex to the graph\n\n \"\"\"\n if vertex not in self.adjacency:\n self.adjacency[vertex] = {}\n self.num_vertices += 1\n\n def add_edge(self, head, tail, weight):\n \"\"\"\n Adds an edge to the graph\n\n \"\"\"\n\n self.add_vertex(head)\n self.add_vertex(tail)\n\n if head == tail:\n return\n\n self.adjacency[head][tail] = weight\n self.adjacency[tail][head] = weight\n\n def distinct_weight(self):\n \"\"\"\n For Boruvks's algorithm the weights should be distinct\n Converts the weights to be distinct\n\n \"\"\"\n edges = self.get_edges()\n for edge in edges:\n head, tail, weight = edge\n edges.remove((tail, head, weight))\n for i in range(len(edges)):\n edges[i] = list(edges[i])\n\n edges.sort(key=lambda e: e[2])\n for i in range(len(edges) - 1):\n if edges[i][2] >= edges[i + 1][2]:\n edges[i + 1][2] = edges[i][2] + 1\n for edge in edges:\n head, tail, weight = edge\n self.adjacency[head][tail] = weight\n self.adjacency[tail][head] = weight\n\n def __str__(self):\n \"\"\"\n Returns string representation of the graph\n \"\"\"\n string = \"\"\n for tail in self.adjacency:\n for head in self.adjacency[tail]:\n weight = self.adjacency[head][tail]\n string += f\"{head} -> {tail} == {weight}\\n\"\n return string.rstrip(\"\\n\")\n\n def get_edges(self):\n \"\"\"\n Returna all edges in the graph\n \"\"\"\n output = []\n for tail in self.adjacency:\n for head in self.adjacency[tail]:\n output.append((tail, head, self.adjacency[head][tail]))\n return output\n\n def get_vertices(self):\n \"\"\"\n Returns all vertices in the graph\n \"\"\"\n return self.adjacency.keys()\n\n @staticmethod\n def build(vertices=None, edges=None):\n \"\"\"\n Builds a graph from the given set of vertices and edges\n\n \"\"\"\n g = Graph()\n if vertices is None:\n vertices = []\n if edges is None:\n edge = []\n for vertex in vertices:\n g.add_vertex(vertex)\n for edge in edges:\n g.add_edge(*edge)\n return g\n\n class UnionFind:\n \"\"\"\n Disjoint set Union and Find for Boruvka's algorithm\n \"\"\"\n\n def __init__(self):\n self.parent = {}\n self.rank = {}\n\n def __len__(self):\n return len(self.parent)\n\n def make_set(self, item):\n if item in self.parent:\n return self.find(item)\n\n self.parent[item] = item\n self.rank[item] = 0\n return item\n\n def find(self, item):\n if item not in self.parent:\n return self.make_set(item)\n if item != self.parent[item]:\n self.parent[item] = self.find(self.parent[item])\n return self.parent[item]\n\n def union(self, item1, item2):\n root1 = self.find(item1)\n root2 = self.find(item2)\n\n if root1 == root2:\n return root1\n\n if self.rank[root1] > self.rank[root2]:\n self.parent[root2] = root1\n return root1\n\n if self.rank[root1] < self.rank[root2]:\n self.parent[root1] = root2\n return root2\n\n if self.rank[root1] == self.rank[root2]:\n self.rank[root1] += 1\n self.parent[root2] = root1\n return root1\n return None\n\n @staticmethod\n def boruvka_mst(graph):\n \"\"\"\n Implementation of Boruvka's algorithm\n >>> g = Graph()\n >>> g = Graph.build([0, 1, 2, 3], [[0, 1, 1], [0, 2, 1],[2, 3, 1]])\n >>> g.distinct_weight()\n >>> bg = Graph.boruvka_mst(g)\n >>> print(bg)\n 1 -> 0 == 1\n 2 -> 0 == 2\n 0 -> 1 == 1\n 0 -> 2 == 2\n 3 -> 2 == 3\n 2 -> 3 == 3\n \"\"\"\n num_components = graph.num_vertices\n\n union_find = Graph.UnionFind()\n mst_edges = []\n while num_components > 1:\n cheap_edge = {}\n for vertex in graph.get_vertices():\n cheap_edge[vertex] = -1\n\n edges = graph.get_edges()\n for edge in edges:\n head, tail, weight = edge\n edges.remove((tail, head, weight))\n for edge in edges:\n head, tail, weight = edge\n set1 = union_find.find(head)\n set2 = union_find.find(tail)\n if set1 != set2:\n if cheap_edge[set1] == -1 or cheap_edge[set1][2] > weight:\n cheap_edge[set1] = [head, tail, weight]\n\n if cheap_edge[set2] == -1 or cheap_edge[set2][2] > weight:\n cheap_edge[set2] = [head, tail, weight]\n for vertex in cheap_edge:\n if cheap_edge[vertex] != -1:\n head, tail, weight = cheap_edge[vertex]\n if union_find.find(head) != union_find.find(tail):\n union_find.union(head, tail)\n mst_edges.append(cheap_edge[vertex])\n num_components = num_components - 1\n mst = Graph.build(edges=mst_edges)\n return mst\n"} +{"Prompt":"kruskal4, 0, 1, 3, 1, 2, 5, 2, 3, 1 2, 3, 1, 0, 1, 3, 1, 2, 5 kruskal4, 0, 1, 3, 1, 2, 5, 2, 3, 1, 0, 2, 1, 0, 3, 2 2, 3, 1, 0, 2, 1, 0, 1, 3 kruskal4, 0, 1, 3, 1, 2, 5, 2, 3, 1, 0, 2, 1, 0, 3, 2, ... 2, 1, 1 2, 3, 1, 0, 2, 1, 2, 1, 1","Completions":"def kruskal(\n num_nodes: int, edges: list[tuple[int, int, int]]\n) -> list[tuple[int, int, int]]:\n \"\"\"\n >>> kruskal(4, [(0, 1, 3), (1, 2, 5), (2, 3, 1)])\n [(2, 3, 1), (0, 1, 3), (1, 2, 5)]\n\n >>> kruskal(4, [(0, 1, 3), (1, 2, 5), (2, 3, 1), (0, 2, 1), (0, 3, 2)])\n [(2, 3, 1), (0, 2, 1), (0, 1, 3)]\n\n >>> kruskal(4, [(0, 1, 3), (1, 2, 5), (2, 3, 1), (0, 2, 1), (0, 3, 2),\n ... (2, 1, 1)])\n [(2, 3, 1), (0, 2, 1), (2, 1, 1)]\n \"\"\"\n edges = sorted(edges, key=lambda edge: edge[2])\n\n parent = list(range(num_nodes))\n\n def find_parent(i):\n if i != parent[i]:\n parent[i] = find_parent(parent[i])\n return parent[i]\n\n minimum_spanning_tree_cost = 0\n minimum_spanning_tree = []\n\n for edge in edges:\n parent_a = find_parent(edge[0])\n parent_b = find_parent(edge[1])\n if parent_a != parent_b:\n minimum_spanning_tree_cost += edge[2]\n minimum_spanning_tree.append(edge)\n parent[parent_a] = parent_b\n\n return minimum_spanning_tree\n\n\nif __name__ == \"__main__\": # pragma: no cover\n num_nodes, num_edges = list(map(int, input().strip().split()))\n edges = []\n\n for _ in range(num_edges):\n node1, node2, cost = (int(x) for x in input().strip().split())\n edges.append((node1, node2, cost))\n\n kruskal(num_nodes, edges)\n"} +{"Prompt":"Disjoint Set Node to store the parent and rank Disjoint Set DataStructure map from node name to the node object create a new set with x as its member find the set x belongs to with pathcompression helper function for union operation merge 2 disjoint sets connections: map from the node to the neighbouring nodes with weights add a node ONLY if its not present in the graph add an edge with the given weight Kruskal's Algorithm to generate a Minimum Spanning Tree MST of a graph Details: https:en.wikipedia.orgwikiKruskal27salgorithm Example: g1 GraphUndirectedWeightedint g1.addedge1, 2, 1 g1.addedge2, 3, 2 g1.addedge3, 4, 1 g1.addedge3, 5, 100 Removed in MST g1.addedge4, 5, 5 assert 5 in g1.connections3 mst g1.kruskal assert 5 not in mst.connections3 g2 GraphUndirectedWeightedstr g2.addedge'A', 'B', 1 g2.addedge'B', 'C', 2 g2.addedge'C', 'D', 1 g2.addedge'C', 'E', 100 Removed in MST g2.addedge'D', 'E', 5 assert 'E' in g2.connectionsC mst g2.kruskal assert 'E' not in mst.connections'C' getting the edges in ascending order of weights creating the disjoint set MST generation","Completions":"from __future__ import annotations\n\nfrom typing import Generic, TypeVar\n\nT = TypeVar(\"T\")\n\n\nclass DisjointSetTreeNode(Generic[T]):\n # Disjoint Set Node to store the parent and rank\n def __init__(self, data: T) -> None:\n self.data = data\n self.parent = self\n self.rank = 0\n\n\nclass DisjointSetTree(Generic[T]):\n # Disjoint Set DataStructure\n def __init__(self) -> None:\n # map from node name to the node object\n self.map: dict[T, DisjointSetTreeNode[T]] = {}\n\n def make_set(self, data: T) -> None:\n # create a new set with x as its member\n self.map[data] = DisjointSetTreeNode(data)\n\n def find_set(self, data: T) -> DisjointSetTreeNode[T]:\n # find the set x belongs to (with path-compression)\n elem_ref = self.map[data]\n if elem_ref != elem_ref.parent:\n elem_ref.parent = self.find_set(elem_ref.parent.data)\n return elem_ref.parent\n\n def link(\n self, node1: DisjointSetTreeNode[T], node2: DisjointSetTreeNode[T]\n ) -> None:\n # helper function for union operation\n if node1.rank > node2.rank:\n node2.parent = node1\n else:\n node1.parent = node2\n if node1.rank == node2.rank:\n node2.rank += 1\n\n def union(self, data1: T, data2: T) -> None:\n # merge 2 disjoint sets\n self.link(self.find_set(data1), self.find_set(data2))\n\n\nclass GraphUndirectedWeighted(Generic[T]):\n def __init__(self) -> None:\n # connections: map from the node to the neighbouring nodes (with weights)\n self.connections: dict[T, dict[T, int]] = {}\n\n def add_node(self, node: T) -> None:\n # add a node ONLY if its not present in the graph\n if node not in self.connections:\n self.connections[node] = {}\n\n def add_edge(self, node1: T, node2: T, weight: int) -> None:\n # add an edge with the given weight\n self.add_node(node1)\n self.add_node(node2)\n self.connections[node1][node2] = weight\n self.connections[node2][node1] = weight\n\n def kruskal(self) -> GraphUndirectedWeighted[T]:\n # Kruskal's Algorithm to generate a Minimum Spanning Tree (MST) of a graph\n \"\"\"\n Details: https:\/\/en.wikipedia.org\/wiki\/Kruskal%27s_algorithm\n\n Example:\n >>> g1 = GraphUndirectedWeighted[int]()\n >>> g1.add_edge(1, 2, 1)\n >>> g1.add_edge(2, 3, 2)\n >>> g1.add_edge(3, 4, 1)\n >>> g1.add_edge(3, 5, 100) # Removed in MST\n >>> g1.add_edge(4, 5, 5)\n >>> assert 5 in g1.connections[3]\n >>> mst = g1.kruskal()\n >>> assert 5 not in mst.connections[3]\n\n >>> g2 = GraphUndirectedWeighted[str]()\n >>> g2.add_edge('A', 'B', 1)\n >>> g2.add_edge('B', 'C', 2)\n >>> g2.add_edge('C', 'D', 1)\n >>> g2.add_edge('C', 'E', 100) # Removed in MST\n >>> g2.add_edge('D', 'E', 5)\n >>> assert 'E' in g2.connections[\"C\"]\n >>> mst = g2.kruskal()\n >>> assert 'E' not in mst.connections['C']\n \"\"\"\n\n # getting the edges in ascending order of weights\n edges = []\n seen = set()\n for start in self.connections:\n for end in self.connections[start]:\n if (start, end) not in seen:\n seen.add((end, start))\n edges.append((start, end, self.connections[start][end]))\n edges.sort(key=lambda x: x[2])\n\n # creating the disjoint set\n disjoint_set = DisjointSetTree[T]()\n for node in self.connections:\n disjoint_set.make_set(node)\n\n # MST generation\n num_edges = 0\n index = 0\n graph = GraphUndirectedWeighted[T]()\n while num_edges < len(self.connections) - 1:\n u, v, w = edges[index]\n index += 1\n parent_u = disjoint_set.find_set(u)\n parent_v = disjoint_set.find_set(v)\n if parent_u != parent_v:\n num_edges += 1\n graph.add_edge(u, v, w)\n disjoint_set.union(u, v)\n return graph\n"} +{"Prompt":"Update function if value of any node in minheap decreases adjacencylist 0: 1, 1, 3, 3, ... 1: 0, 1, 2, 6, 3, 5, 4, 1, ... 2: 1, 6, 4, 5, 5, 2, ... 3: 0, 3, 1, 5, 4, 1, ... 4: 1, 1, 2, 5, 3, 1, 5, 4, ... 5: 2, 2, 4, 4 prismsalgorithmadjacencylist 0, 1, 1, 4, 4, 3, 4, 5, 5, 2 Minimum Distance of explored vertex with neighboring vertex of partial tree formed in graph Prims Algorithm","Completions":"import sys\nfrom collections import defaultdict\n\n\nclass Heap:\n def __init__(self):\n self.node_position = []\n\n def get_position(self, vertex):\n return self.node_position[vertex]\n\n def set_position(self, vertex, pos):\n self.node_position[vertex] = pos\n\n def top_to_bottom(self, heap, start, size, positions):\n if start > size \/\/ 2 - 1:\n return\n else:\n if 2 * start + 2 >= size:\n smallest_child = 2 * start + 1\n else:\n if heap[2 * start + 1] < heap[2 * start + 2]:\n smallest_child = 2 * start + 1\n else:\n smallest_child = 2 * start + 2\n if heap[smallest_child] < heap[start]:\n temp, temp1 = heap[smallest_child], positions[smallest_child]\n heap[smallest_child], positions[smallest_child] = (\n heap[start],\n positions[start],\n )\n heap[start], positions[start] = temp, temp1\n\n temp = self.get_position(positions[smallest_child])\n self.set_position(\n positions[smallest_child], self.get_position(positions[start])\n )\n self.set_position(positions[start], temp)\n\n self.top_to_bottom(heap, smallest_child, size, positions)\n\n # Update function if value of any node in min-heap decreases\n def bottom_to_top(self, val, index, heap, position):\n temp = position[index]\n\n while index != 0:\n parent = int((index - 2) \/ 2) if index % 2 == 0 else int((index - 1) \/ 2)\n\n if val < heap[parent]:\n heap[index] = heap[parent]\n position[index] = position[parent]\n self.set_position(position[parent], index)\n else:\n heap[index] = val\n position[index] = temp\n self.set_position(temp, index)\n break\n index = parent\n else:\n heap[0] = val\n position[0] = temp\n self.set_position(temp, 0)\n\n def heapify(self, heap, positions):\n start = len(heap) \/\/ 2 - 1\n for i in range(start, -1, -1):\n self.top_to_bottom(heap, i, len(heap), positions)\n\n def delete_minimum(self, heap, positions):\n temp = positions[0]\n heap[0] = sys.maxsize\n self.top_to_bottom(heap, 0, len(heap), positions)\n return temp\n\n\ndef prisms_algorithm(adjacency_list):\n \"\"\"\n >>> adjacency_list = {0: [[1, 1], [3, 3]],\n ... 1: [[0, 1], [2, 6], [3, 5], [4, 1]],\n ... 2: [[1, 6], [4, 5], [5, 2]],\n ... 3: [[0, 3], [1, 5], [4, 1]],\n ... 4: [[1, 1], [2, 5], [3, 1], [5, 4]],\n ... 5: [[2, 2], [4, 4]]}\n >>> prisms_algorithm(adjacency_list)\n [(0, 1), (1, 4), (4, 3), (4, 5), (5, 2)]\n \"\"\"\n\n heap = Heap()\n\n visited = [0] * len(adjacency_list)\n nbr_tv = [-1] * len(adjacency_list) # Neighboring Tree Vertex of selected vertex\n # Minimum Distance of explored vertex with neighboring vertex of partial tree\n # formed in graph\n distance_tv = [] # Heap of Distance of vertices from their neighboring vertex\n positions = []\n\n for vertex in range(len(adjacency_list)):\n distance_tv.append(sys.maxsize)\n positions.append(vertex)\n heap.node_position.append(vertex)\n\n tree_edges = []\n visited[0] = 1\n distance_tv[0] = sys.maxsize\n for neighbor, distance in adjacency_list[0]:\n nbr_tv[neighbor] = 0\n distance_tv[neighbor] = distance\n heap.heapify(distance_tv, positions)\n\n for _ in range(1, len(adjacency_list)):\n vertex = heap.delete_minimum(distance_tv, positions)\n if visited[vertex] == 0:\n tree_edges.append((nbr_tv[vertex], vertex))\n visited[vertex] = 1\n for neighbor, distance in adjacency_list[vertex]:\n if (\n visited[neighbor] == 0\n and distance < distance_tv[heap.get_position(neighbor)]\n ):\n distance_tv[heap.get_position(neighbor)] = distance\n heap.bottom_to_top(\n distance, heap.get_position(neighbor), distance_tv, positions\n )\n nbr_tv[neighbor] = vertex\n return tree_edges\n\n\nif __name__ == \"__main__\": # pragma: no cover\n # < --------- Prims Algorithm --------- >\n edges_number = int(input(\"Enter number of edges: \").strip())\n adjacency_list = defaultdict(list)\n for _ in range(edges_number):\n edge = [int(x) for x in input().strip().split()]\n adjacency_list[edge[0]].append([edge[1], edge[2]])\n adjacency_list[edge[1]].append([edge[0], edge[2]])\n print(prisms_algorithm(adjacency_list))\n"} +{"Prompt":"Prim's also known as Jarnk's algorithm is a greedy algorithm that finds a minimum spanning tree for a weighted undirected graph. This means it finds a subset of the edges that forms a tree that includes every vertex, where the total weight of all the edges in the tree is minimized. The algorithm operates by building this tree one vertex at a time, from an arbitrary starting vertex, at each step adding the cheapest possible connection from the tree to another vertex. heap helper function get the position of the parent of the current node getparentposition1 0 getparentposition2 0 heap helper function get the position of the left child of the current node getchildleftposition0 1 heap helper function get the position of the right child of the current node getchildrightposition0 2 Minimum Priority Queue Class Functions: isempty: function to check if the priority queue is empty push: function to add an element with given priority to the queue extractmin: function to remove and return the element with lowest weight highest priority updatekey: function to update the weight of the given key bubbleup: helper function to place a node at the proper position upward movement bubbledown: helper function to place a node at the proper position downward movement swapnodes: helper function to swap the nodes at the given positions queue MinPriorityQueue queue.push1, 1000 queue.push2, 100 queue.push3, 4000 queue.push4, 3000 queue.extractmin 2 queue.updatekey4, 50 queue.extractmin 4 queue.extractmin 1 queue.extractmin 3 Check if the priority queue is empty Add an element with given priority to the queue Remove and return the element with lowest weight highest priority Update the weight of the given key Place a node at the proper position upward movement to be used internally only Place a node at the proper position downward movement to be used internally only Swap the nodes at the given positions Graph Undirected Weighted Class Functions: addnode: function to add a node in the graph addedge: function to add an edge between 2 nodes in the graph Add a node in the graph if it is not in the graph Add an edge between 2 nodes in the graph graph GraphUndirectedWeighted graph.addedgea, b, 3 graph.addedgeb, c, 10 graph.addedgec, d, 5 graph.addedgea, c, 15 graph.addedgeb, d, 100 dist, parent primsalgograph absdista distb 3 absdistd distb 15 absdista distc 13 prim's algorithm for minimum spanning tree initialization running prim's algorithm","Completions":"from __future__ import annotations\n\nfrom sys import maxsize\nfrom typing import Generic, TypeVar\n\nT = TypeVar(\"T\")\n\n\ndef get_parent_position(position: int) -> int:\n \"\"\"\n heap helper function get the position of the parent of the current node\n\n >>> get_parent_position(1)\n 0\n >>> get_parent_position(2)\n 0\n \"\"\"\n return (position - 1) \/\/ 2\n\n\ndef get_child_left_position(position: int) -> int:\n \"\"\"\n heap helper function get the position of the left child of the current node\n\n >>> get_child_left_position(0)\n 1\n \"\"\"\n return (2 * position) + 1\n\n\ndef get_child_right_position(position: int) -> int:\n \"\"\"\n heap helper function get the position of the right child of the current node\n\n >>> get_child_right_position(0)\n 2\n \"\"\"\n return (2 * position) + 2\n\n\nclass MinPriorityQueue(Generic[T]):\n \"\"\"\n Minimum Priority Queue Class\n\n Functions:\n is_empty: function to check if the priority queue is empty\n push: function to add an element with given priority to the queue\n extract_min: function to remove and return the element with lowest weight (highest\n priority)\n update_key: function to update the weight of the given key\n _bubble_up: helper function to place a node at the proper position (upward\n movement)\n _bubble_down: helper function to place a node at the proper position (downward\n movement)\n _swap_nodes: helper function to swap the nodes at the given positions\n\n >>> queue = MinPriorityQueue()\n\n >>> queue.push(1, 1000)\n >>> queue.push(2, 100)\n >>> queue.push(3, 4000)\n >>> queue.push(4, 3000)\n\n >>> queue.extract_min()\n 2\n\n >>> queue.update_key(4, 50)\n\n >>> queue.extract_min()\n 4\n >>> queue.extract_min()\n 1\n >>> queue.extract_min()\n 3\n \"\"\"\n\n def __init__(self) -> None:\n self.heap: list[tuple[T, int]] = []\n self.position_map: dict[T, int] = {}\n self.elements: int = 0\n\n def __len__(self) -> int:\n return self.elements\n\n def __repr__(self) -> str:\n return str(self.heap)\n\n def is_empty(self) -> bool:\n # Check if the priority queue is empty\n return self.elements == 0\n\n def push(self, elem: T, weight: int) -> None:\n # Add an element with given priority to the queue\n self.heap.append((elem, weight))\n self.position_map[elem] = self.elements\n self.elements += 1\n self._bubble_up(elem)\n\n def extract_min(self) -> T:\n # Remove and return the element with lowest weight (highest priority)\n if self.elements > 1:\n self._swap_nodes(0, self.elements - 1)\n elem, _ = self.heap.pop()\n del self.position_map[elem]\n self.elements -= 1\n if self.elements > 0:\n bubble_down_elem, _ = self.heap[0]\n self._bubble_down(bubble_down_elem)\n return elem\n\n def update_key(self, elem: T, weight: int) -> None:\n # Update the weight of the given key\n position = self.position_map[elem]\n self.heap[position] = (elem, weight)\n if position > 0:\n parent_position = get_parent_position(position)\n _, parent_weight = self.heap[parent_position]\n if parent_weight > weight:\n self._bubble_up(elem)\n else:\n self._bubble_down(elem)\n else:\n self._bubble_down(elem)\n\n def _bubble_up(self, elem: T) -> None:\n # Place a node at the proper position (upward movement) [to be used internally\n # only]\n curr_pos = self.position_map[elem]\n if curr_pos == 0:\n return None\n parent_position = get_parent_position(curr_pos)\n _, weight = self.heap[curr_pos]\n _, parent_weight = self.heap[parent_position]\n if parent_weight > weight:\n self._swap_nodes(parent_position, curr_pos)\n return self._bubble_up(elem)\n return None\n\n def _bubble_down(self, elem: T) -> None:\n # Place a node at the proper position (downward movement) [to be used\n # internally only]\n curr_pos = self.position_map[elem]\n _, weight = self.heap[curr_pos]\n child_left_position = get_child_left_position(curr_pos)\n child_right_position = get_child_right_position(curr_pos)\n if child_left_position < self.elements and child_right_position < self.elements:\n _, child_left_weight = self.heap[child_left_position]\n _, child_right_weight = self.heap[child_right_position]\n if child_right_weight < child_left_weight and child_right_weight < weight:\n self._swap_nodes(child_right_position, curr_pos)\n return self._bubble_down(elem)\n if child_left_position < self.elements:\n _, child_left_weight = self.heap[child_left_position]\n if child_left_weight < weight:\n self._swap_nodes(child_left_position, curr_pos)\n return self._bubble_down(elem)\n else:\n return None\n if child_right_position < self.elements:\n _, child_right_weight = self.heap[child_right_position]\n if child_right_weight < weight:\n self._swap_nodes(child_right_position, curr_pos)\n return self._bubble_down(elem)\n return None\n\n def _swap_nodes(self, node1_pos: int, node2_pos: int) -> None:\n # Swap the nodes at the given positions\n node1_elem = self.heap[node1_pos][0]\n node2_elem = self.heap[node2_pos][0]\n self.heap[node1_pos], self.heap[node2_pos] = (\n self.heap[node2_pos],\n self.heap[node1_pos],\n )\n self.position_map[node1_elem] = node2_pos\n self.position_map[node2_elem] = node1_pos\n\n\nclass GraphUndirectedWeighted(Generic[T]):\n \"\"\"\n Graph Undirected Weighted Class\n\n Functions:\n add_node: function to add a node in the graph\n add_edge: function to add an edge between 2 nodes in the graph\n \"\"\"\n\n def __init__(self) -> None:\n self.connections: dict[T, dict[T, int]] = {}\n self.nodes: int = 0\n\n def __repr__(self) -> str:\n return str(self.connections)\n\n def __len__(self) -> int:\n return self.nodes\n\n def add_node(self, node: T) -> None:\n # Add a node in the graph if it is not in the graph\n if node not in self.connections:\n self.connections[node] = {}\n self.nodes += 1\n\n def add_edge(self, node1: T, node2: T, weight: int) -> None:\n # Add an edge between 2 nodes in the graph\n self.add_node(node1)\n self.add_node(node2)\n self.connections[node1][node2] = weight\n self.connections[node2][node1] = weight\n\n\ndef prims_algo(\n graph: GraphUndirectedWeighted[T],\n) -> tuple[dict[T, int], dict[T, T | None]]:\n \"\"\"\n >>> graph = GraphUndirectedWeighted()\n\n >>> graph.add_edge(\"a\", \"b\", 3)\n >>> graph.add_edge(\"b\", \"c\", 10)\n >>> graph.add_edge(\"c\", \"d\", 5)\n >>> graph.add_edge(\"a\", \"c\", 15)\n >>> graph.add_edge(\"b\", \"d\", 100)\n\n >>> dist, parent = prims_algo(graph)\n\n >>> abs(dist[\"a\"] - dist[\"b\"])\n 3\n >>> abs(dist[\"d\"] - dist[\"b\"])\n 15\n >>> abs(dist[\"a\"] - dist[\"c\"])\n 13\n \"\"\"\n # prim's algorithm for minimum spanning tree\n dist: dict[T, int] = {node: maxsize for node in graph.connections}\n parent: dict[T, T | None] = {node: None for node in graph.connections}\n\n priority_queue: MinPriorityQueue[T] = MinPriorityQueue()\n for node, weight in dist.items():\n priority_queue.push(node, weight)\n\n if priority_queue.is_empty():\n return dist, parent\n\n # initialization\n node = priority_queue.extract_min()\n dist[node] = 0\n for neighbour in graph.connections[node]:\n if dist[neighbour] > dist[node] + graph.connections[node][neighbour]:\n dist[neighbour] = dist[node] + graph.connections[node][neighbour]\n priority_queue.update_key(neighbour, dist[neighbour])\n parent[neighbour] = node\n\n # running prim's algorithm\n while not priority_queue.is_empty():\n node = priority_queue.extract_min()\n for neighbour in graph.connections[node]:\n if dist[neighbour] > dist[node] + graph.connections[node][neighbour]:\n dist[neighbour] = dist[node] + graph.connections[node][neighbour]\n priority_queue.update_key(neighbour, dist[neighbour])\n parent[neighbour] = node\n return dist, parent\n"} +{"Prompt":"update printupdate, item euclidean distance integer division by time variable manhattan distance printx prints, s printj, j printneighbour, neighbours L block hyper parameters start and end destination printopenlist0.minkey, openlisti.minkey","Completions":"import heapq\nimport sys\n\nimport numpy as np\n\nTPos = tuple[int, int]\n\n\nclass PriorityQueue:\n def __init__(self):\n self.elements = []\n self.set = set()\n\n def minkey(self):\n if not self.empty():\n return self.elements[0][0]\n else:\n return float(\"inf\")\n\n def empty(self):\n return len(self.elements) == 0\n\n def put(self, item, priority):\n if item not in self.set:\n heapq.heappush(self.elements, (priority, item))\n self.set.add(item)\n else:\n # update\n # print(\"update\", item)\n temp = []\n (pri, x) = heapq.heappop(self.elements)\n while x != item:\n temp.append((pri, x))\n (pri, x) = heapq.heappop(self.elements)\n temp.append((priority, item))\n for pro, xxx in temp:\n heapq.heappush(self.elements, (pro, xxx))\n\n def remove_element(self, item):\n if item in self.set:\n self.set.remove(item)\n temp = []\n (pro, x) = heapq.heappop(self.elements)\n while x != item:\n temp.append((pro, x))\n (pro, x) = heapq.heappop(self.elements)\n for prito, yyy in temp:\n heapq.heappush(self.elements, (prito, yyy))\n\n def top_show(self):\n return self.elements[0][1]\n\n def get(self):\n (priority, item) = heapq.heappop(self.elements)\n self.set.remove(item)\n return (priority, item)\n\n\ndef consistent_heuristic(p: TPos, goal: TPos):\n # euclidean distance\n a = np.array(p)\n b = np.array(goal)\n return np.linalg.norm(a - b)\n\n\ndef heuristic_2(p: TPos, goal: TPos):\n # integer division by time variable\n return consistent_heuristic(p, goal) \/\/ t\n\n\ndef heuristic_1(p: TPos, goal: TPos):\n # manhattan distance\n return abs(p[0] - goal[0]) + abs(p[1] - goal[1])\n\n\ndef key(start: TPos, i: int, goal: TPos, g_function: dict[TPos, float]):\n ans = g_function[start] + W1 * heuristics[i](start, goal)\n return ans\n\n\ndef do_something(back_pointer, goal, start):\n grid = np.chararray((n, n))\n for i in range(n):\n for j in range(n):\n grid[i][j] = \"*\"\n\n for i in range(n):\n for j in range(n):\n if (j, (n - 1) - i) in blocks:\n grid[i][j] = \"#\"\n\n grid[0][(n - 1)] = \"-\"\n x = back_pointer[goal]\n while x != start:\n (x_c, y_c) = x\n # print(x)\n grid[(n - 1) - y_c][x_c] = \"-\"\n x = back_pointer[x]\n grid[(n - 1)][0] = \"-\"\n\n for i in range(n):\n for j in range(n):\n if (i, j) == (0, n - 1):\n print(grid[i][j], end=\" \")\n print(\"<-- End position\", end=\" \")\n else:\n print(grid[i][j], end=\" \")\n print()\n print(\"^\")\n print(\"Start position\")\n print()\n print(\"# is an obstacle\")\n print(\"- is the path taken by algorithm\")\n print(\"PATH TAKEN BY THE ALGORITHM IS:-\")\n x = back_pointer[goal]\n while x != start:\n print(x, end=\" \")\n x = back_pointer[x]\n print(x)\n sys.exit()\n\n\ndef valid(p: TPos):\n if p[0] < 0 or p[0] > n - 1:\n return False\n if p[1] < 0 or p[1] > n - 1:\n return False\n return True\n\n\ndef expand_state(\n s,\n j,\n visited,\n g_function,\n close_list_anchor,\n close_list_inad,\n open_list,\n back_pointer,\n):\n for itera in range(n_heuristic):\n open_list[itera].remove_element(s)\n # print(\"s\", s)\n # print(\"j\", j)\n (x, y) = s\n left = (x - 1, y)\n right = (x + 1, y)\n up = (x, y + 1)\n down = (x, y - 1)\n\n for neighbours in [left, right, up, down]:\n if neighbours not in blocks:\n if valid(neighbours) and neighbours not in visited:\n # print(\"neighbour\", neighbours)\n visited.add(neighbours)\n back_pointer[neighbours] = -1\n g_function[neighbours] = float(\"inf\")\n\n if valid(neighbours) and g_function[neighbours] > g_function[s] + 1:\n g_function[neighbours] = g_function[s] + 1\n back_pointer[neighbours] = s\n if neighbours not in close_list_anchor:\n open_list[0].put(neighbours, key(neighbours, 0, goal, g_function))\n if neighbours not in close_list_inad:\n for var in range(1, n_heuristic):\n if key(neighbours, var, goal, g_function) <= W2 * key(\n neighbours, 0, goal, g_function\n ):\n open_list[j].put(\n neighbours, key(neighbours, var, goal, g_function)\n )\n\n\ndef make_common_ground():\n some_list = []\n for x in range(1, 5):\n for y in range(1, 6):\n some_list.append((x, y))\n\n for x in range(15, 20):\n some_list.append((x, 17))\n\n for x in range(10, 19):\n for y in range(1, 15):\n some_list.append((x, y))\n\n # L block\n for x in range(1, 4):\n for y in range(12, 19):\n some_list.append((x, y))\n for x in range(3, 13):\n for y in range(16, 19):\n some_list.append((x, y))\n return some_list\n\n\nheuristics = {0: consistent_heuristic, 1: heuristic_1, 2: heuristic_2}\n\nblocks_blk = [\n (0, 1),\n (1, 1),\n (2, 1),\n (3, 1),\n (4, 1),\n (5, 1),\n (6, 1),\n (7, 1),\n (8, 1),\n (9, 1),\n (10, 1),\n (11, 1),\n (12, 1),\n (13, 1),\n (14, 1),\n (15, 1),\n (16, 1),\n (17, 1),\n (18, 1),\n (19, 1),\n]\nblocks_all = make_common_ground()\n\n\nblocks = blocks_blk\n# hyper parameters\nW1 = 1\nW2 = 1\nn = 20\nn_heuristic = 3 # one consistent and two other inconsistent\n\n# start and end destination\nstart = (0, 0)\ngoal = (n - 1, n - 1)\n\nt = 1\n\n\ndef multi_a_star(start: TPos, goal: TPos, n_heuristic: int):\n g_function = {start: 0, goal: float(\"inf\")}\n back_pointer = {start: -1, goal: -1}\n open_list = []\n visited = set()\n\n for i in range(n_heuristic):\n open_list.append(PriorityQueue())\n open_list[i].put(start, key(start, i, goal, g_function))\n\n close_list_anchor: list[int] = []\n close_list_inad: list[int] = []\n while open_list[0].minkey() < float(\"inf\"):\n for i in range(1, n_heuristic):\n # print(open_list[0].minkey(), open_list[i].minkey())\n if open_list[i].minkey() <= W2 * open_list[0].minkey():\n global t\n t += 1\n if g_function[goal] <= open_list[i].minkey():\n if g_function[goal] < float(\"inf\"):\n do_something(back_pointer, goal, start)\n else:\n _, get_s = open_list[i].top_show()\n visited.add(get_s)\n expand_state(\n get_s,\n i,\n visited,\n g_function,\n close_list_anchor,\n close_list_inad,\n open_list,\n back_pointer,\n )\n close_list_inad.append(get_s)\n else:\n if g_function[goal] <= open_list[0].minkey():\n if g_function[goal] < float(\"inf\"):\n do_something(back_pointer, goal, start)\n else:\n get_s = open_list[0].top_show()\n visited.add(get_s)\n expand_state(\n get_s,\n 0,\n visited,\n g_function,\n close_list_anchor,\n close_list_inad,\n open_list,\n back_pointer,\n )\n close_list_anchor.append(get_s)\n print(\"No path found to goal\")\n print()\n for i in range(n - 1, -1, -1):\n for j in range(n):\n if (j, i) in blocks:\n print(\"#\", end=\" \")\n elif (j, i) in back_pointer:\n if (j, i) == (n - 1, n - 1):\n print(\"*\", end=\" \")\n else:\n print(\"-\", end=\" \")\n else:\n print(\"*\", end=\" \")\n if (j, i) == (n - 1, n - 1):\n print(\"<-- End position\", end=\" \")\n print()\n print(\"^\")\n print(\"Start position\")\n print()\n print(\"# is an obstacle\")\n print(\"- is the path taken by algorithm\")\n\n\nif __name__ == \"__main__\":\n multi_a_star(start, goal, n_heuristic)\n"} +{"Prompt":"Author: https:github.combhushanborole The input graph for the algorithm is: A B C A 0 1 1 B 0 0 1 C 1 0 0","Completions":"\"\"\"\nThe input graph for the algorithm is:\n\n A B C\nA 0 1 1\nB 0 0 1\nC 1 0 0\n\n\"\"\"\n\ngraph = [[0, 1, 1], [0, 0, 1], [1, 0, 0]]\n\n\nclass Node:\n def __init__(self, name):\n self.name = name\n self.inbound = []\n self.outbound = []\n\n def add_inbound(self, node):\n self.inbound.append(node)\n\n def add_outbound(self, node):\n self.outbound.append(node)\n\n def __repr__(self):\n return f\"\"\n\n\ndef page_rank(nodes, limit=3, d=0.85):\n ranks = {}\n for node in nodes:\n ranks[node.name] = 1\n\n outbounds = {}\n for node in nodes:\n outbounds[node.name] = len(node.outbound)\n\n for i in range(limit):\n print(f\"======= Iteration {i + 1} =======\")\n for _, node in enumerate(nodes):\n ranks[node.name] = (1 - d) + d * sum(\n ranks[ib] \/ outbounds[ib] for ib in node.inbound\n )\n print(ranks)\n\n\ndef main():\n names = list(input(\"Enter Names of the Nodes: \").split())\n\n nodes = [Node(name) for name in names]\n\n for ri, row in enumerate(graph):\n for ci, col in enumerate(row):\n if col == 1:\n nodes[ci].add_inbound(names[ri])\n nodes[ri].add_outbound(names[ci])\n\n print(\"======= Nodes =======\")\n for node in nodes:\n print(node)\n\n page_rank(nodes)\n\n\nif __name__ == \"__main__\":\n main()\n"} +{"Prompt":"Prim's Algorithm. Determines the minimum spanning treeMST of a graph using the Prim's Algorithm. Details: https:en.wikipedia.orgwikiPrim27salgorithm Class Vertex. def initself, id: self.id strid self.key None self.pi None self.neighbors self.edges vertex:distance def ltself, other: Return the vertex id. return self.id def addneighborself, vertex: Destination vertex and weight. self.edgesvertex.id weight def connectgraph, a, b, edge: add the neighbors: grapha 1.addneighborgraphb 1 graphb 1.addneighborgrapha 1 add the edges: grapha 1.addedgegraphb 1, edge graphb 1.addedgegrapha 1, edge def primgraph: list, root: Vertex list: a for u in graph: u.key math.inf u.pi None root.key 0 q graph: while q: u minq q.removeu for v in u.neighbors: if v in q and u.edgesv.id v.key: v.pi u v.key u.edgesv.id for i in range1, lengraph: a.appendintgraphi.id 1, intgraphi.pi.id 1 return a def primheapgraph: list, root: Vertex Iteratortuple: for u in graph: u.key math.inf u.pi None root.key 0 h listgraph hq.heapifyh while h: u hq.heappoph for v in u.neighbors: if v in h and u.edgesv.id v.key: v.pi u v.key u.edgesv.id hq.heapifyh for i in range1, lengraph: yield intgraphi.id 1, intgraphi.pi.id 1 def testvector None: Creates a list to store x vertices. if name main: import doctest doctest.testmod","Completions":"import heapq as hq\nimport math\nfrom collections.abc import Iterator\n\n\nclass Vertex:\n \"\"\"Class Vertex.\"\"\"\n\n def __init__(self, id_):\n \"\"\"\n Arguments:\n id - input an id to identify the vertex\n Attributes:\n neighbors - a list of the vertices it is linked to\n edges - a dict to store the edges's weight\n \"\"\"\n self.id = str(id_)\n self.key = None\n self.pi = None\n self.neighbors = []\n self.edges = {} # {vertex:distance}\n\n def __lt__(self, other):\n \"\"\"Comparison rule to < operator.\"\"\"\n return self.key < other.key\n\n def __repr__(self):\n \"\"\"Return the vertex id.\"\"\"\n return self.id\n\n def add_neighbor(self, vertex):\n \"\"\"Add a pointer to a vertex at neighbor's list.\"\"\"\n self.neighbors.append(vertex)\n\n def add_edge(self, vertex, weight):\n \"\"\"Destination vertex and weight.\"\"\"\n self.edges[vertex.id] = weight\n\n\ndef connect(graph, a, b, edge):\n # add the neighbors:\n graph[a - 1].add_neighbor(graph[b - 1])\n graph[b - 1].add_neighbor(graph[a - 1])\n # add the edges:\n graph[a - 1].add_edge(graph[b - 1], edge)\n graph[b - 1].add_edge(graph[a - 1], edge)\n\n\ndef prim(graph: list, root: Vertex) -> list:\n \"\"\"Prim's Algorithm.\n\n Runtime:\n O(mn) with `m` edges and `n` vertices\n\n Return:\n List with the edges of a Minimum Spanning Tree\n\n Usage:\n prim(graph, graph[0])\n \"\"\"\n a = []\n for u in graph:\n u.key = math.inf\n u.pi = None\n root.key = 0\n q = graph[:]\n while q:\n u = min(q)\n q.remove(u)\n for v in u.neighbors:\n if (v in q) and (u.edges[v.id] < v.key):\n v.pi = u\n v.key = u.edges[v.id]\n for i in range(1, len(graph)):\n a.append((int(graph[i].id) + 1, int(graph[i].pi.id) + 1))\n return a\n\n\ndef prim_heap(graph: list, root: Vertex) -> Iterator[tuple]:\n \"\"\"Prim's Algorithm with min heap.\n\n Runtime:\n O((m + n)log n) with `m` edges and `n` vertices\n\n Yield:\n Edges of a Minimum Spanning Tree\n\n Usage:\n prim(graph, graph[0])\n \"\"\"\n for u in graph:\n u.key = math.inf\n u.pi = None\n root.key = 0\n\n h = list(graph)\n hq.heapify(h)\n\n while h:\n u = hq.heappop(h)\n for v in u.neighbors:\n if (v in h) and (u.edges[v.id] < v.key):\n v.pi = u\n v.key = u.edges[v.id]\n hq.heapify(h)\n\n for i in range(1, len(graph)):\n yield (int(graph[i].id) + 1, int(graph[i].pi.id) + 1)\n\n\ndef test_vector() -> None:\n \"\"\"\n # Creates a list to store x vertices.\n >>> x = 5\n >>> G = [Vertex(n) for n in range(x)]\n\n >>> connect(G, 1, 2, 15)\n >>> connect(G, 1, 3, 12)\n >>> connect(G, 2, 4, 13)\n >>> connect(G, 2, 5, 5)\n >>> connect(G, 3, 2, 6)\n >>> connect(G, 3, 4, 6)\n >>> connect(G, 0, 0, 0) # Generate the minimum spanning tree:\n >>> G_heap = G[:]\n >>> MST = prim(G, G[0])\n >>> MST_heap = prim_heap(G, G[0])\n >>> for i in MST:\n ... print(i)\n (2, 3)\n (3, 1)\n (4, 3)\n (5, 2)\n >>> for i in MST_heap:\n ... print(i)\n (2, 3)\n (3, 1)\n (4, 3)\n (5, 2)\n \"\"\"\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Author: Manuel Di Lullo https:github.commanueldilullo Description: Random graphs generator. Uses graphs represented with an adjacency list. URL: https:en.wikipedia.orgwikiRandomgraph Generate a random graph input: verticesnumber number of vertices, probability probability that a generic edge u,v exists, directed if True: graph will be a directed graph, otherwise it will be an undirected graph examples: random.seed1 randomgraph4, 0.5 0: 1, 1: 0, 2, 3, 2: 1, 3, 3: 1, 2 random.seed1 randomgraph4, 0.5, True 0: 1, 1: 2, 3, 2: 3, 3: if probability is greater or equal than 1, then generate a complete graph if probability is lower or equal than 0, then return a graph without edges for each couple of nodes, add an edge from u to v if the number randomly generated is greater than probability probability if the graph is undirected, add an edge in from j to i, either Generate a complete graph with verticesnumber vertices. input: verticesnumber number of vertices, directed False if the graph is undirected, True otherwise example: completegraph3 0: 1, 2, 1: 0, 2, 2: 0, 1","Completions":"import random\n\n\ndef random_graph(\n vertices_number: int, probability: float, directed: bool = False\n) -> dict:\n \"\"\"\n Generate a random graph\n @input: vertices_number (number of vertices),\n probability (probability that a generic edge (u,v) exists),\n directed (if True: graph will be a directed graph,\n otherwise it will be an undirected graph)\n @examples:\n >>> random.seed(1)\n >>> random_graph(4, 0.5)\n {0: [1], 1: [0, 2, 3], 2: [1, 3], 3: [1, 2]}\n >>> random.seed(1)\n >>> random_graph(4, 0.5, True)\n {0: [1], 1: [2, 3], 2: [3], 3: []}\n \"\"\"\n graph: dict = {i: [] for i in range(vertices_number)}\n\n # if probability is greater or equal than 1, then generate a complete graph\n if probability >= 1:\n return complete_graph(vertices_number)\n # if probability is lower or equal than 0, then return a graph without edges\n if probability <= 0:\n return graph\n\n # for each couple of nodes, add an edge from u to v\n # if the number randomly generated is greater than probability probability\n for i in range(vertices_number):\n for j in range(i + 1, vertices_number):\n if random.random() < probability:\n graph[i].append(j)\n if not directed:\n # if the graph is undirected, add an edge in from j to i, either\n graph[j].append(i)\n return graph\n\n\ndef complete_graph(vertices_number: int) -> dict:\n \"\"\"\n Generate a complete graph with vertices_number vertices.\n @input: vertices_number (number of vertices),\n directed (False if the graph is undirected, True otherwise)\n @example:\n >>> complete_graph(3)\n {0: [1, 2], 1: [0, 2], 2: [0, 1]}\n \"\"\"\n return {\n i: [j for j in range(vertices_number) if i != j] for i in range(vertices_number)\n }\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"n no of nodes, m no of edges input graph data edges","Completions":"from __future__ import annotations\n\n\ndef dfs(u):\n global graph, reversed_graph, scc, component, visit, stack\n if visit[u]:\n return\n visit[u] = True\n for v in graph[u]:\n dfs(v)\n stack.append(u)\n\n\ndef dfs2(u):\n global graph, reversed_graph, scc, component, visit, stack\n if visit[u]:\n return\n visit[u] = True\n component.append(u)\n for v in reversed_graph[u]:\n dfs2(v)\n\n\ndef kosaraju():\n global graph, reversed_graph, scc, component, visit, stack\n for i in range(n):\n dfs(i)\n visit = [False] * n\n for i in stack[::-1]:\n if visit[i]:\n continue\n component = []\n dfs2(i)\n scc.append(component)\n return scc\n\n\nif __name__ == \"__main__\":\n # n - no of nodes, m - no of edges\n n, m = list(map(int, input().strip().split()))\n\n graph: list[list[int]] = [[] for _ in range(n)] # graph\n reversed_graph: list[list[int]] = [[] for i in range(n)] # reversed graph\n # input graph data (edges)\n for _ in range(m):\n u, v = list(map(int, input().strip().split()))\n graph[u].append(v)\n reversed_graph[v].append(u)\n\n stack: list[int] = []\n visit: list[bool] = [False] * n\n scc: list[int] = []\n component: list[int] = []\n print(kosaraju())\n"} +{"Prompt":"https:en.wikipedia.orgwikiStronglyconnectedcomponent Finding strongly connected components in directed graph Use depth first search to sort graph At this time graph is the same as input topologysorttestgraph1, 0, 5 False 1, 2, 4, 3, 0 topologysorttestgraph2, 0, 6 False 2, 1, 5, 4, 3, 0 Use depth first search to find strongliy connected vertices. Now graph is reversed findcomponents0: 1, 1: 2, 2: 0, 0, 5 False 0, 1, 2 findcomponents0: 2, 1: 0, 2: 0, 1, 0, 6 False 0, 2, 1 This function takes graph as a parameter and then returns the list of strongly connected components stronglyconnectedcomponentstestgraph1 0, 1, 2, 3, 4 stronglyconnectedcomponentstestgraph2 0, 2, 1, 3, 5, 4","Completions":"test_graph_1 = {0: [2, 3], 1: [0], 2: [1], 3: [4], 4: []}\n\ntest_graph_2 = {0: [1, 2, 3], 1: [2], 2: [0], 3: [4], 4: [5], 5: [3]}\n\n\ndef topology_sort(\n graph: dict[int, list[int]], vert: int, visited: list[bool]\n) -> list[int]:\n \"\"\"\n Use depth first search to sort graph\n At this time graph is the same as input\n >>> topology_sort(test_graph_1, 0, 5 * [False])\n [1, 2, 4, 3, 0]\n >>> topology_sort(test_graph_2, 0, 6 * [False])\n [2, 1, 5, 4, 3, 0]\n \"\"\"\n\n visited[vert] = True\n order = []\n\n for neighbour in graph[vert]:\n if not visited[neighbour]:\n order += topology_sort(graph, neighbour, visited)\n\n order.append(vert)\n\n return order\n\n\ndef find_components(\n reversed_graph: dict[int, list[int]], vert: int, visited: list[bool]\n) -> list[int]:\n \"\"\"\n Use depth first search to find strongliy connected\n vertices. Now graph is reversed\n >>> find_components({0: [1], 1: [2], 2: [0]}, 0, 5 * [False])\n [0, 1, 2]\n >>> find_components({0: [2], 1: [0], 2: [0, 1]}, 0, 6 * [False])\n [0, 2, 1]\n \"\"\"\n\n visited[vert] = True\n component = [vert]\n\n for neighbour in reversed_graph[vert]:\n if not visited[neighbour]:\n component += find_components(reversed_graph, neighbour, visited)\n\n return component\n\n\ndef strongly_connected_components(graph: dict[int, list[int]]) -> list[list[int]]:\n \"\"\"\n This function takes graph as a parameter\n and then returns the list of strongly connected components\n >>> strongly_connected_components(test_graph_1)\n [[0, 1, 2], [3], [4]]\n >>> strongly_connected_components(test_graph_2)\n [[0, 2, 1], [3, 5, 4]]\n \"\"\"\n\n visited = len(graph) * [False]\n reversed_graph: dict[int, list[int]] = {vert: [] for vert in range(len(graph))}\n\n for vert, neighbours in graph.items():\n for neighbour in neighbours:\n reversed_graph[neighbour].append(vert)\n\n order = []\n for i, was_visited in enumerate(visited):\n if not was_visited:\n order += topology_sort(graph, i, visited)\n\n components_list = []\n visited = len(graph) * [False]\n\n for i in range(len(graph)):\n vert = order[len(graph) - i - 1]\n if not visited[vert]:\n component = find_components(reversed_graph, vert, visited)\n components_list.append(component)\n\n return components_list\n"} +{"Prompt":"Tarjan's algo for finding strongly connected components in a directed graph Uses two main attributes of each node to track reachability, the index of that node within a componentindex, and the lowest index reachable from that nodelowlink. We then perform a dfs of the each component making sure to update these parameters for each node and saving the nodes we visit on the way. If ever we find that the lowest reachable node from a current node is equal to the index of the current node then it must be the root of a strongly connected component and so we save it and it's equireachable vertices as a strongly connected component. Complexity: strongconnect is called at most once for each node and has a complexity of OE as it is DFS. Therefore this has complexity OV E for a graph G V, E tarjan2, 3, 4, 2, 3, 4, 0, 1, 3, 0, 1, 2, 1 4, 3, 1, 2, 0 tarjan, , , 0, 1, 2, 3 a 0, 1, 2, 3, 4, 5, 4 b 1, 0, 3, 2, 5, 4, 0 n 7 sortedtarjancreategraphn, listzipa, b sorted ... tarjancreategraphn, listzipa::1, b::1 True a 0, 1, 2, 3, 4, 5, 6 b 0, 1, 2, 3, 4, 5, 6 sortedtarjancreategraphn, listzipa, b 0, 1, 2, 3, 4, 5, 6 n 7 source 0, 0, 1, 2, 3, 3, 4, 4, 6 target 1, 3, 2, 0, 1, 4, 5, 6, 5 edges listzipsource, target creategraphn, edges 1, 3, 2, 0, 1, 4, 5, 6, , 5 Test","Completions":"from collections import deque\n\n\ndef tarjan(g: list[list[int]]) -> list[list[int]]:\n \"\"\"\n Tarjan's algo for finding strongly connected components in a directed graph\n\n Uses two main attributes of each node to track reachability, the index of that node\n within a component(index), and the lowest index reachable from that node(lowlink).\n\n We then perform a dfs of the each component making sure to update these parameters\n for each node and saving the nodes we visit on the way.\n\n If ever we find that the lowest reachable node from a current node is equal to the\n index of the current node then it must be the root of a strongly connected\n component and so we save it and it's equireachable vertices as a strongly\n connected component.\n\n Complexity: strong_connect() is called at most once for each node and has a\n complexity of O(|E|) as it is DFS.\n Therefore this has complexity O(|V| + |E|) for a graph G = (V, E)\n\n >>> tarjan([[2, 3, 4], [2, 3, 4], [0, 1, 3], [0, 1, 2], [1]])\n [[4, 3, 1, 2, 0]]\n >>> tarjan([[], [], [], []])\n [[0], [1], [2], [3]]\n >>> a = [0, 1, 2, 3, 4, 5, 4]\n >>> b = [1, 0, 3, 2, 5, 4, 0]\n >>> n = 7\n >>> sorted(tarjan(create_graph(n, list(zip(a, b))))) == sorted(\n ... tarjan(create_graph(n, list(zip(a[::-1], b[::-1])))))\n True\n >>> a = [0, 1, 2, 3, 4, 5, 6]\n >>> b = [0, 1, 2, 3, 4, 5, 6]\n >>> sorted(tarjan(create_graph(n, list(zip(a, b)))))\n [[0], [1], [2], [3], [4], [5], [6]]\n \"\"\"\n\n n = len(g)\n stack: deque[int] = deque()\n on_stack = [False for _ in range(n)]\n index_of = [-1 for _ in range(n)]\n lowlink_of = index_of[:]\n\n def strong_connect(v: int, index: int, components: list[list[int]]) -> int:\n index_of[v] = index # the number when this node is seen\n lowlink_of[v] = index # lowest rank node reachable from here\n index += 1\n stack.append(v)\n on_stack[v] = True\n\n for w in g[v]:\n if index_of[w] == -1:\n index = strong_connect(w, index, components)\n lowlink_of[v] = (\n lowlink_of[w] if lowlink_of[w] < lowlink_of[v] else lowlink_of[v]\n )\n elif on_stack[w]:\n lowlink_of[v] = (\n lowlink_of[w] if lowlink_of[w] < lowlink_of[v] else lowlink_of[v]\n )\n\n if lowlink_of[v] == index_of[v]:\n component = []\n w = stack.pop()\n on_stack[w] = False\n component.append(w)\n while w != v:\n w = stack.pop()\n on_stack[w] = False\n component.append(w)\n components.append(component)\n return index\n\n components: list[list[int]] = []\n for v in range(n):\n if index_of[v] == -1:\n strong_connect(v, 0, components)\n\n return components\n\n\ndef create_graph(n: int, edges: list[tuple[int, int]]) -> list[list[int]]:\n \"\"\"\n >>> n = 7\n >>> source = [0, 0, 1, 2, 3, 3, 4, 4, 6]\n >>> target = [1, 3, 2, 0, 1, 4, 5, 6, 5]\n >>> edges = list(zip(source, target))\n >>> create_graph(n, edges)\n [[1, 3], [2], [0], [1, 4], [5, 6], [], [5]]\n \"\"\"\n g: list[list[int]] = [[] for _ in range(n)]\n for u, v in edges:\n g[u].append(v)\n return g\n\n\nif __name__ == \"__main__\":\n # Test\n n_vertices = 7\n source = [0, 0, 1, 2, 3, 3, 4, 4, 6]\n target = [1, 3, 2, 0, 1, 4, 5, 6, 5]\n edges = list(zip(source, target))\n g = create_graph(n_vertices, edges)\n\n assert [[5], [6], [4], [3, 2, 1, 0]] == tarjan(g)\n"} +{"Prompt":"Given a list of stock prices calculate the maximum profit that can be made from a single buy and sell of one share of stock. We only allowed to complete one buy transaction and one sell transaction but must buy before we sell. Example : prices 7, 1, 5, 3, 6, 4 maxprofit will return 5 which is by buying at price 1 and selling at price 6. This problem can be solved using the concept of GREEDY ALGORITHM. We iterate over the price array once, keeping track of the lowest price point buy and the maximum profit we can get at each point. The greedy choice at each point is to either buy at the current price if it's less than our current buying price, or sell at the current price if the profit is more than our current maximum profit. maxprofit7, 1, 5, 3, 6, 4 5 maxprofit7, 6, 4, 3, 1 0","Completions":"def max_profit(prices: list[int]) -> int:\n \"\"\"\n >>> max_profit([7, 1, 5, 3, 6, 4])\n 5\n >>> max_profit([7, 6, 4, 3, 1])\n 0\n \"\"\"\n if not prices:\n return 0\n\n min_price = prices[0]\n max_profit: int = 0\n\n for price in prices:\n min_price = min(price, min_price)\n max_profit = max(price - min_price, max_profit)\n\n return max_profit\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n print(max_profit([7, 1, 5, 3, 6, 4]))\n"} +{"Prompt":"https:en.wikipedia.orgwikiSetcoverproblem Return the valuetoweight ratio for the item. Returns: float: The valuetoweight ratio for the item. Examples: Item10, 65.ratio 6.5 Item20, 100.ratio 5.0 Item30, 120.ratio 4.0 Solve the Fractional Cover Problem. Args: items: A list of items, where each item has weight and value attributes. capacity: The maximum weight capacity of the knapsack. Returns: The maximum value that can be obtained by selecting fractions of items to cover the knapsack's capacity. Raises: ValueError: If capacity is negative. Examples: fractionalcoverItem10, 60, Item20, 100, Item30, 120, capacity50 240.0 fractionalcoverItem20, 100, Item30, 120, Item10, 60, capacity25 135.0 fractionalcoverItem10, 60, Item20, 100, Item30, 120, capacity60 280.0 fractionalcoveritemsItem5, 30, Item10, 60, Item15, 90, capacity30 180.0 fractionalcoveritems, capacity50 0.0 fractionalcoveritemsItem10, 60, capacity5 30.0 fractionalcoveritemsItem10, 60, capacity1 6.0 fractionalcoveritemsItem10, 60, capacity0 0.0 fractionalcoveritemsItem10, 60, capacity1 Traceback most recent call last: ... ValueError: Capacity cannot be negative Sort the items by their valuetoweight ratio in descending order","Completions":"# https:\/\/en.wikipedia.org\/wiki\/Set_cover_problem\n\nfrom dataclasses import dataclass\nfrom operator import attrgetter\n\n\n@dataclass\nclass Item:\n weight: int\n value: int\n\n @property\n def ratio(self) -> float:\n \"\"\"\n Return the value-to-weight ratio for the item.\n\n Returns:\n float: The value-to-weight ratio for the item.\n\n Examples:\n >>> Item(10, 65).ratio\n 6.5\n\n >>> Item(20, 100).ratio\n 5.0\n\n >>> Item(30, 120).ratio\n 4.0\n \"\"\"\n return self.value \/ self.weight\n\n\ndef fractional_cover(items: list[Item], capacity: int) -> float:\n \"\"\"\n Solve the Fractional Cover Problem.\n\n Args:\n items: A list of items, where each item has weight and value attributes.\n capacity: The maximum weight capacity of the knapsack.\n\n Returns:\n The maximum value that can be obtained by selecting fractions of items to cover\n the knapsack's capacity.\n\n Raises:\n ValueError: If capacity is negative.\n\n Examples:\n >>> fractional_cover((Item(10, 60), Item(20, 100), Item(30, 120)), capacity=50)\n 240.0\n\n >>> fractional_cover([Item(20, 100), Item(30, 120), Item(10, 60)], capacity=25)\n 135.0\n\n >>> fractional_cover([Item(10, 60), Item(20, 100), Item(30, 120)], capacity=60)\n 280.0\n\n >>> fractional_cover(items=[Item(5, 30), Item(10, 60), Item(15, 90)], capacity=30)\n 180.0\n\n >>> fractional_cover(items=[], capacity=50)\n 0.0\n\n >>> fractional_cover(items=[Item(10, 60)], capacity=5)\n 30.0\n\n >>> fractional_cover(items=[Item(10, 60)], capacity=1)\n 6.0\n\n >>> fractional_cover(items=[Item(10, 60)], capacity=0)\n 0.0\n\n >>> fractional_cover(items=[Item(10, 60)], capacity=-1)\n Traceback (most recent call last):\n ...\n ValueError: Capacity cannot be negative\n \"\"\"\n if capacity < 0:\n raise ValueError(\"Capacity cannot be negative\")\n\n total_value = 0.0\n remaining_capacity = capacity\n\n # Sort the items by their value-to-weight ratio in descending order\n for item in sorted(items, key=attrgetter(\"ratio\"), reverse=True):\n if remaining_capacity == 0:\n break\n\n weight_taken = min(item.weight, remaining_capacity)\n total_value += weight_taken * item.ratio\n remaining_capacity -= weight_taken\n\n return total_value\n\n\nif __name__ == \"__main__\":\n import doctest\n\n if result := doctest.testmod().failed:\n print(f\"{result} test(s) failed\")\n else:\n print(\"All tests passed\")\n"} +{"Prompt":"fracknapsack60, 100, 120, 10, 20, 30, 50, 3 240.0 fracknapsack10, 40, 30, 50, 5, 4, 6, 3, 10, 4 105.0 fracknapsack10, 40, 30, 50, 5, 4, 6, 3, 8, 4 95.0 fracknapsack10, 40, 30, 50, 5, 4, 6, 8, 4 60.0 fracknapsack10, 40, 30, 5, 4, 6, 3, 8, 4 60.0 fracknapsack10, 40, 30, 50, 5, 4, 6, 3, 0, 4 0 fracknapsack10, 40, 30, 50, 5, 4, 6, 3, 8, 0 95.0 fracknapsack10, 40, 30, 50, 5, 4, 6, 3, 8, 4 0 fracknapsack10, 40, 30, 50, 5, 4, 6, 3, 8, 4 95.0 fracknapsack10, 40, 30, 50, 5, 4, 6, 3, 800, 4 130 fracknapsack10, 40, 30, 50, 5, 4, 6, 3, 8, 400 95.0 fracknapsackABCD, 5, 4, 6, 3, 8, 400 Traceback most recent call last: ... TypeError: unsupported operand types for : 'str' and 'int'","Completions":"from bisect import bisect\nfrom itertools import accumulate\n\n\ndef frac_knapsack(vl, wt, w, n):\n \"\"\"\n >>> frac_knapsack([60, 100, 120], [10, 20, 30], 50, 3)\n 240.0\n >>> frac_knapsack([10, 40, 30, 50], [5, 4, 6, 3], 10, 4)\n 105.0\n >>> frac_knapsack([10, 40, 30, 50], [5, 4, 6, 3], 8, 4)\n 95.0\n >>> frac_knapsack([10, 40, 30, 50], [5, 4, 6], 8, 4)\n 60.0\n >>> frac_knapsack([10, 40, 30], [5, 4, 6, 3], 8, 4)\n 60.0\n >>> frac_knapsack([10, 40, 30, 50], [5, 4, 6, 3], 0, 4)\n 0\n >>> frac_knapsack([10, 40, 30, 50], [5, 4, 6, 3], 8, 0)\n 95.0\n >>> frac_knapsack([10, 40, 30, 50], [5, 4, 6, 3], -8, 4)\n 0\n >>> frac_knapsack([10, 40, 30, 50], [5, 4, 6, 3], 8, -4)\n 95.0\n >>> frac_knapsack([10, 40, 30, 50], [5, 4, 6, 3], 800, 4)\n 130\n >>> frac_knapsack([10, 40, 30, 50], [5, 4, 6, 3], 8, 400)\n 95.0\n >>> frac_knapsack(\"ABCD\", [5, 4, 6, 3], 8, 400)\n Traceback (most recent call last):\n ...\n TypeError: unsupported operand type(s) for \/: 'str' and 'int'\n \"\"\"\n\n r = sorted(zip(vl, wt), key=lambda x: x[0] \/ x[1], reverse=True)\n vl, wt = [i[0] for i in r], [i[1] for i in r]\n acc = list(accumulate(wt))\n k = bisect(acc, w)\n return (\n 0\n if k == 0\n else sum(vl[:k]) + (w - acc[k - 1]) * (vl[k]) \/ (wt[k])\n if k != n\n else sum(vl[:k])\n )\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"https:en.wikipedia.orgwikiContinuousknapsackproblem https:www.guru99.comfractionalknapsackproblemgreedy.html https:medium.comwalkinthecodegreedyalgorithmfractionalknapsackproblem9aba1daecc93 value 1, 3, 5, 7, 9 weight 0.9, 0.7, 0.5, 0.3, 0.1 fractionalknapsackvalue, weight, 5 25, 1, 1, 1, 1, 1 fractionalknapsackvalue, weight, 15 25, 1, 1, 1, 1, 1 fractionalknapsackvalue, weight, 25 25, 1, 1, 1, 1, 1 fractionalknapsackvalue, weight, 26 25, 1, 1, 1, 1, 1 fractionalknapsackvalue, weight, 1 90.0, 0, 0, 0, 0, 10.0 fractionalknapsack1, 3, 5, 7, weight, 30 16, 1, 1, 1, 1 fractionalknapsackvalue, 0.9, 0.7, 0.5, 0.3, 0.1, 30 25, 1, 1, 1, 1, 1 fractionalknapsack, , 30 0,","Completions":"# https:\/\/en.wikipedia.org\/wiki\/Continuous_knapsack_problem\n# https:\/\/www.guru99.com\/fractional-knapsack-problem-greedy.html\n# https:\/\/medium.com\/walkinthecode\/greedy-algorithm-fractional-knapsack-problem-9aba1daecc93\n\nfrom __future__ import annotations\n\n\ndef fractional_knapsack(\n value: list[int], weight: list[int], capacity: int\n) -> tuple[float, list[float]]:\n \"\"\"\n >>> value = [1, 3, 5, 7, 9]\n >>> weight = [0.9, 0.7, 0.5, 0.3, 0.1]\n >>> fractional_knapsack(value, weight, 5)\n (25, [1, 1, 1, 1, 1])\n >>> fractional_knapsack(value, weight, 15)\n (25, [1, 1, 1, 1, 1])\n >>> fractional_knapsack(value, weight, 25)\n (25, [1, 1, 1, 1, 1])\n >>> fractional_knapsack(value, weight, 26)\n (25, [1, 1, 1, 1, 1])\n >>> fractional_knapsack(value, weight, -1)\n (-90.0, [0, 0, 0, 0, -10.0])\n >>> fractional_knapsack([1, 3, 5, 7], weight, 30)\n (16, [1, 1, 1, 1])\n >>> fractional_knapsack(value, [0.9, 0.7, 0.5, 0.3, 0.1], 30)\n (25, [1, 1, 1, 1, 1])\n >>> fractional_knapsack([], [], 30)\n (0, [])\n \"\"\"\n index = list(range(len(value)))\n ratio = [v \/ w for v, w in zip(value, weight)]\n index.sort(key=lambda i: ratio[i], reverse=True)\n\n max_value: float = 0\n fractions: list[float] = [0] * len(value)\n for i in index:\n if weight[i] <= capacity:\n fractions[i] = 1\n max_value += value[i]\n capacity -= weight[i]\n else:\n fractions[i] = capacity \/ weight[i]\n max_value += value[i] * capacity \/ weight[i]\n break\n\n return max_value, fractions\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Task: There are n gas stations along a circular route, where the amount of gas at the ith station is gasquantitiesi. You have a car with an unlimited gas tank and it costs costsi of gas to travel from the ith station to its next i 1th station. You begin the journey with an empty tank at one of the gas stations. Given two integer arrays gasquantities and costs, return the starting gas station's index if you can travel around the circuit once in the clockwise direction otherwise, return 1. If there exists a solution, it is guaranteed to be unique Reference: https:leetcode.comproblemsgasstationdescription Implementation notes: First, check whether the total gas is enough to complete the journey. If not, return 1. However, if there is enough gas, it is guaranteed that there is a valid starting index to reach the end of the journey. Greedily calculate the net gain gasquantity cost at each station. If the net gain ever goes below 0 while iterating through the stations, start checking from the next station. This function returns a tuple of gas stations. Args: gasquantities: Amount of gas available at each station costs: The cost of gas required to move from one station to the next Returns: A tuple of gas stations gasstations getgasstations1, 2, 3, 4, 5, 3, 4, 5, 1, 2 lengasstations 5 gasstations0 GasStationgasquantity1, cost3 gasstations1 GasStationgasquantity5, cost2 This function returns the index from which to start the journey in order to reach the end. Args: gasquantities list: Amount of gas available at each station cost list: The cost of gas required to move from one station to the next Returns: start int: start index needed to complete the journey Examples: cancompletejourneygetgasstations1, 2, 3, 4, 5, 3, 4, 5, 1, 2 3 cancompletejourneygetgasstations2, 3, 4, 3, 4, 3 1","Completions":"from dataclasses import dataclass\n\n\n@dataclass\nclass GasStation:\n gas_quantity: int\n cost: int\n\n\ndef get_gas_stations(\n gas_quantities: list[int], costs: list[int]\n) -> tuple[GasStation, ...]:\n \"\"\"\n This function returns a tuple of gas stations.\n\n Args:\n gas_quantities: Amount of gas available at each station\n costs: The cost of gas required to move from one station to the next\n\n Returns:\n A tuple of gas stations\n\n >>> gas_stations = get_gas_stations([1, 2, 3, 4, 5], [3, 4, 5, 1, 2])\n >>> len(gas_stations)\n 5\n >>> gas_stations[0]\n GasStation(gas_quantity=1, cost=3)\n >>> gas_stations[-1]\n GasStation(gas_quantity=5, cost=2)\n \"\"\"\n return tuple(\n GasStation(quantity, cost) for quantity, cost in zip(gas_quantities, costs)\n )\n\n\ndef can_complete_journey(gas_stations: tuple[GasStation, ...]) -> int:\n \"\"\"\n This function returns the index from which to start the journey\n in order to reach the end.\n\n Args:\n gas_quantities [list]: Amount of gas available at each station\n cost [list]: The cost of gas required to move from one station to the next\n\n Returns:\n start [int]: start index needed to complete the journey\n\n Examples:\n >>> can_complete_journey(get_gas_stations([1, 2, 3, 4, 5], [3, 4, 5, 1, 2]))\n 3\n >>> can_complete_journey(get_gas_stations([2, 3, 4], [3, 4, 3]))\n -1\n \"\"\"\n total_gas = sum(gas_station.gas_quantity for gas_station in gas_stations)\n total_cost = sum(gas_station.cost for gas_station in gas_stations)\n if total_gas < total_cost:\n return -1\n\n start = 0\n net = 0\n for i, gas_station in enumerate(gas_stations):\n net += gas_station.gas_quantity - gas_station.cost\n if net < 0:\n start = i + 1\n net = 0\n return start\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Test cases: Do you want to enter your denominations ? YN :N Enter the change you want to make in Indian Currency: 987 Following is minimal change for 987 : 500 100 100 100 100 50 20 10 5 2 Do you want to enter your denominations ? YN :Y Enter number of denomination:10 1 5 10 20 50 100 200 500 1000 2000 Enter the change you want to make: 18745 Following is minimal change for 18745 : 2000 2000 2000 2000 2000 2000 2000 2000 2000 500 200 20 20 5 Do you want to enter your denominations ? YN :N Enter the change you want to make: 0 The total value cannot be zero or negative. Do you want to enter your denominations ? YN :N Enter the change you want to make: 98 The total value cannot be zero or negative. Do you want to enter your denominations ? YN :Y Enter number of denomination:5 1 5 100 500 1000 Enter the change you want to make: 456 Following is minimal change for 456 : 100 100 100 100 5 5 5 5 5 5 5 5 5 5 5 1 Find the minimum change from the given denominations and value findminimumchange1, 5, 10, 20, 50, 100, 200, 500, 1000,2000, 18745 2000, 2000, 2000, 2000, 2000, 2000, 2000, 2000, 2000, 500, 200, 20, 20, 5 findminimumchange1, 2, 5, 10, 20, 50, 100, 500, 2000, 987 500, 100, 100, 100, 100, 50, 20, 10, 5, 2 findminimumchange1, 2, 5, 10, 20, 50, 100, 500, 2000, 0 findminimumchange1, 2, 5, 10, 20, 50, 100, 500, 2000, 98 findminimumchange1, 5, 100, 500, 1000, 456 100, 100, 100, 100, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 1 Initialize Result Traverse through all denomination Find denominations Driver Code All denominations of Indian Currency if user does not enter Print result","Completions":"def find_minimum_change(denominations: list[int], value: str) -> list[int]:\n \"\"\"\n Find the minimum change from the given denominations and value\n >>> find_minimum_change([1, 5, 10, 20, 50, 100, 200, 500, 1000,2000], 18745)\n [2000, 2000, 2000, 2000, 2000, 2000, 2000, 2000, 2000, 500, 200, 20, 20, 5]\n >>> find_minimum_change([1, 2, 5, 10, 20, 50, 100, 500, 2000], 987)\n [500, 100, 100, 100, 100, 50, 20, 10, 5, 2]\n >>> find_minimum_change([1, 2, 5, 10, 20, 50, 100, 500, 2000], 0)\n []\n >>> find_minimum_change([1, 2, 5, 10, 20, 50, 100, 500, 2000], -98)\n []\n >>> find_minimum_change([1, 5, 100, 500, 1000], 456)\n [100, 100, 100, 100, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 1]\n \"\"\"\n total_value = int(value)\n\n # Initialize Result\n answer = []\n\n # Traverse through all denomination\n for denomination in reversed(denominations):\n # Find denominations\n while int(total_value) >= int(denomination):\n total_value -= int(denomination)\n answer.append(denomination) # Append the \"answers\" array\n\n return answer\n\n\n# Driver Code\nif __name__ == \"__main__\":\n denominations = []\n value = \"0\"\n\n if (\n input(\"Do you want to enter your denominations ? (yY\/n): \").strip().lower()\n == \"y\"\n ):\n n = int(input(\"Enter the number of denominations you want to add: \").strip())\n\n for i in range(n):\n denominations.append(int(input(f\"Denomination {i}: \").strip()))\n value = input(\"Enter the change you want to make in Indian Currency: \").strip()\n else:\n # All denominations of Indian Currency if user does not enter\n denominations = [1, 2, 5, 10, 20, 50, 100, 500, 2000]\n value = input(\"Enter the change you want to make: \").strip()\n\n if int(value) == 0 or int(value) < 0:\n print(\"The total value cannot be zero or negative.\")\n\n else:\n print(f\"Following is minimal change for {value}: \")\n answer = find_minimum_change(denominations, value)\n # Print result\n for i in range(len(answer)):\n print(answer[i], end=\" \")\n"} +{"Prompt":"Calculate the minimum waiting time using a greedy algorithm. reference: https:www.youtube.comwatch?vSf3eiO12eJs For doctests run following command: python m doctest v minimumwaitingtime.py The minimumwaitingtime function uses a greedy algorithm to calculate the minimum time for queries to complete. It sorts the list in nondecreasing order, calculates the waiting time for each query by multiplying its position in the list with the sum of all remaining query times, and returns the total waiting time. A doctest ensures that the function produces the correct output. This function takes a list of query times and returns the minimum waiting time for all queries to be completed. Args: queries: A list of queries measured in picoseconds Returns: totalwaitingtime: Minimum waiting time measured in picoseconds Examples: minimumwaitingtime3, 2, 1, 2, 6 17 minimumwaitingtime3, 2, 1 4 minimumwaitingtime1, 2, 3, 4 10 minimumwaitingtime5, 5, 5, 5 30 minimumwaitingtime 0","Completions":"def minimum_waiting_time(queries: list[int]) -> int:\n \"\"\"\n This function takes a list of query times and returns the minimum waiting time\n for all queries to be completed.\n\n Args:\n queries: A list of queries measured in picoseconds\n\n Returns:\n total_waiting_time: Minimum waiting time measured in picoseconds\n\n Examples:\n >>> minimum_waiting_time([3, 2, 1, 2, 6])\n 17\n >>> minimum_waiting_time([3, 2, 1])\n 4\n >>> minimum_waiting_time([1, 2, 3, 4])\n 10\n >>> minimum_waiting_time([5, 5, 5, 5])\n 30\n >>> minimum_waiting_time([])\n 0\n \"\"\"\n n = len(queries)\n if n in (0, 1):\n return 0\n return sum(query * (n - i - 1) for i, query in enumerate(sorted(queries)))\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"This is a pure Python implementation of the greedymergesort algorithm reference: https:www.geeksforgeeks.orgoptimalfilemergepatterns For doctests run following command: python3 m doctest v greedymergesort.py Objective Merge a set of sorted files of different length into a single sorted file. We need to find an optimal solution, where the resultant file will be generated in minimum time. Approach If the number of sorted files are given, there are many ways to merge them into a single sorted file. This merge can be performed pair wise. To merge a mrecord file and a nrecord file requires possibly mn record moves the optimal choice being, merge the two smallest files together at each step greedy approach. Function to merge all the files with optimum cost Args: files list: A list of sizes of different files to be merged Returns: optimalmergecost int: Optimal cost to merge all those files Examples: optimalmergepattern2, 3, 4 14 optimalmergepattern5, 10, 20, 30, 30 205 optimalmergepattern8, 8, 8, 8, 8 96 Consider two files with minimum cost to be merged","Completions":"def optimal_merge_pattern(files: list) -> float:\n \"\"\"Function to merge all the files with optimum cost\n\n Args:\n files [list]: A list of sizes of different files to be merged\n\n Returns:\n optimal_merge_cost [int]: Optimal cost to merge all those files\n\n Examples:\n >>> optimal_merge_pattern([2, 3, 4])\n 14\n >>> optimal_merge_pattern([5, 10, 20, 30, 30])\n 205\n >>> optimal_merge_pattern([8, 8, 8, 8, 8])\n 96\n \"\"\"\n optimal_merge_cost = 0\n while len(files) > 1:\n temp = 0\n # Consider two files with minimum cost to be merged\n for _ in range(2):\n min_index = files.index(min(files))\n temp += files[min_index]\n files.pop(min_index)\n files.append(temp)\n optimal_merge_cost += temp\n return optimal_merge_cost\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"smallestrange function takes a list of sorted integer lists and finds the smallest range that includes at least one number from each list, using a min heap for efficiency. Find the smallest range from each list in nums. Uses min heap for efficiency. The range includes at least one number from each list. Args: nums: List of k sorted integer lists. Returns: list: Smallest range as a twoelement list. Examples: smallestrange4, 10, 15, 24, 26, 0, 9, 12, 20, 5, 18, 22, 30 20, 24 smallestrange1, 2, 3, 1, 2, 3, 1, 2, 3 1, 1 smallestrange1, 2, 3, 1, 2, 3, 1, 2, 3 1, 1 smallestrange3, 2, 1, 0, 0, 0, 1, 2, 3 1, 1 smallestrange1, 2, 3, 4, 5, 6, 7, 8, 9 3, 7 smallestrange0, 0, 0, 0, 0, 0, 0, 0, 0 0, 0 smallestrange, , Traceback most recent call last: ... IndexError: list index out of range Initialize smallestrange with large integer values","Completions":"from heapq import heappop, heappush\nfrom sys import maxsize\n\n\ndef smallest_range(nums: list[list[int]]) -> list[int]:\n \"\"\"\n Find the smallest range from each list in nums.\n\n Uses min heap for efficiency. The range includes at least one number from each list.\n\n Args:\n nums: List of k sorted integer lists.\n\n Returns:\n list: Smallest range as a two-element list.\n\n Examples:\n >>> smallest_range([[4, 10, 15, 24, 26], [0, 9, 12, 20], [5, 18, 22, 30]])\n [20, 24]\n >>> smallest_range([[1, 2, 3], [1, 2, 3], [1, 2, 3]])\n [1, 1]\n >>> smallest_range(((1, 2, 3), (1, 2, 3), (1, 2, 3)))\n [1, 1]\n >>> smallest_range(((-3, -2, -1), (0, 0, 0), (1, 2, 3)))\n [-1, 1]\n >>> smallest_range([[1, 2, 3], [4, 5, 6], [7, 8, 9]])\n [3, 7]\n >>> smallest_range([[0, 0, 0], [0, 0, 0], [0, 0, 0]])\n [0, 0]\n >>> smallest_range([[], [], []])\n Traceback (most recent call last):\n ...\n IndexError: list index out of range\n \"\"\"\n\n min_heap: list[tuple[int, int, int]] = []\n current_max = -maxsize - 1\n\n for i, items in enumerate(nums):\n heappush(min_heap, (items[0], i, 0))\n current_max = max(current_max, items[0])\n\n # Initialize smallest_range with large integer values\n smallest_range = [-maxsize - 1, maxsize]\n\n while min_heap:\n current_min, list_index, element_index = heappop(min_heap)\n\n if current_max - current_min < smallest_range[1] - smallest_range[0]:\n smallest_range = [current_min, current_max]\n\n if element_index == len(nums[list_index]) - 1:\n break\n\n next_element = nums[list_index][element_index + 1]\n heappush(min_heap, (next_element, list_index, element_index + 1))\n current_max = max(current_max, next_element)\n\n return smallest_range\n\n\nif __name__ == \"__main__\":\n from doctest import testmod\n\n testmod()\n print(f\"{smallest_range([[1, 2, 3], [1, 2, 3], [1, 2, 3]])}\") # Output: [1, 1]\n"} +{"Prompt":"Adler32 is a checksum algorithm which was invented by Mark Adler in 1995. Compared to a cyclic redundancy check of the same length, it trades reliability for speed preferring the latter. Adler32 is more reliable than Fletcher16, and slightly less reliable than Fletcher32.2 source: https:en.wikipedia.orgwikiAdler32 Function implements adler32 hash. Iterates and evaluates a new value for each character adler32'Algorithms' 363791387 adler32'go adler em all' 708642122","Completions":"MOD_ADLER = 65521\n\n\ndef adler32(plain_text: str) -> int:\n \"\"\"\n Function implements adler-32 hash.\n Iterates and evaluates a new value for each character\n\n >>> adler32('Algorithms')\n 363791387\n\n >>> adler32('go adler em all')\n 708642122\n \"\"\"\n a = 1\n b = 0\n for plain_chr in plain_text:\n a = (a + ord(plain_chr)) % MOD_ADLER\n b = (b + a) % MOD_ADLER\n return (b << 16) | a\n"} +{"Prompt":"example of simple chaos machine Chaos Machine K, t, m K 0.33, 0.44, 0.55, 0.44, 0.33 t 3 m 5 Buffer Space with Parameters Space bufferspace: listfloat paramsspace: listfloat Machine Time machinetime 0 def pushseed: global bufferspace, paramsspace, machinetime, K, m, t Choosing Dynamical Systems All for key, value in enumeratebufferspace: Evolution Parameter e floatseed value Control Theory: Orbit Change value bufferspacekey 1 m e 1 Control Theory: Trajectory Change r paramsspacekey e 1 3 Modification Transition Function Jumps bufferspacekey roundfloatr value 1 value, 10 paramsspacekey r Saving to Parameters Space Logistic Map assert maxbufferspace 1 assert maxparamsspace 4 Machine Time machinetime 1 def pull: global bufferspace, paramsspace, machinetime, K, m, t PRNG Xorshift by George Marsaglia def xorshiftx, y: x y 13 y x 17 x y 5 return x Choosing Dynamical Systems Increment key machinetime m Evolution Time Length for in ranget: Variables Position Parameters r paramsspacekey value bufferspacekey Modification Transition Function Flow bufferspacekey roundfloatr value 1 value, 10 paramsspacekey machinetime 0.01 r 1.01 1 3 Choosing Chaotic Data x intbufferspacekey 2 m 1010 y intbufferspacekey 2 m 1010 Machine Time machinetime 1 return xorshiftx, y 0xFFFFFFFF def reset: global bufferspace, paramsspace, machinetime, K, m, t bufferspace K paramsspace 0 m machinetime 0 if name main: Initialization reset Pushing Data Input import random message random.samplerange0xFFFFFFFF, 100 for chunk in message: pushchunk for controlling inp Pulling Data Output while inp in e, E: printfformatpull, '04x' printbufferspace printparamsspace inp inputeexit? .strip","Completions":"# Chaos Machine (K, t, m)\nK = [0.33, 0.44, 0.55, 0.44, 0.33]\nt = 3\nm = 5\n\n# Buffer Space (with Parameters Space)\nbuffer_space: list[float] = []\nparams_space: list[float] = []\n\n# Machine Time\nmachine_time = 0\n\n\ndef push(seed):\n global buffer_space, params_space, machine_time, K, m, t\n\n # Choosing Dynamical Systems (All)\n for key, value in enumerate(buffer_space):\n # Evolution Parameter\n e = float(seed \/ value)\n\n # Control Theory: Orbit Change\n value = (buffer_space[(key + 1) % m] + e) % 1\n\n # Control Theory: Trajectory Change\n r = (params_space[key] + e) % 1 + 3\n\n # Modification (Transition Function) - Jumps\n buffer_space[key] = round(float(r * value * (1 - value)), 10)\n params_space[key] = r # Saving to Parameters Space\n\n # Logistic Map\n assert max(buffer_space) < 1\n assert max(params_space) < 4\n\n # Machine Time\n machine_time += 1\n\n\ndef pull():\n global buffer_space, params_space, machine_time, K, m, t\n\n # PRNG (Xorshift by George Marsaglia)\n def xorshift(x, y):\n x ^= y >> 13\n y ^= x << 17\n x ^= y >> 5\n return x\n\n # Choosing Dynamical Systems (Increment)\n key = machine_time % m\n\n # Evolution (Time Length)\n for _ in range(t):\n # Variables (Position + Parameters)\n r = params_space[key]\n value = buffer_space[key]\n\n # Modification (Transition Function) - Flow\n buffer_space[key] = round(float(r * value * (1 - value)), 10)\n params_space[key] = (machine_time * 0.01 + r * 1.01) % 1 + 3\n\n # Choosing Chaotic Data\n x = int(buffer_space[(key + 2) % m] * (10**10))\n y = int(buffer_space[(key - 2) % m] * (10**10))\n\n # Machine Time\n machine_time += 1\n\n return xorshift(x, y) % 0xFFFFFFFF\n\n\ndef reset():\n global buffer_space, params_space, machine_time, K, m, t\n\n buffer_space = K\n params_space = [0] * m\n machine_time = 0\n\n\nif __name__ == \"__main__\":\n # Initialization\n reset()\n\n # Pushing Data (Input)\n import random\n\n message = random.sample(range(0xFFFFFFFF), 100)\n for chunk in message:\n push(chunk)\n\n # for controlling\n inp = \"\"\n\n # Pulling Data (Output)\n while inp in (\"e\", \"E\"):\n print(f\"{format(pull(), '#04x')}\")\n print(buffer_space)\n print(params_space)\n inp = input(\"(e)exit? \").strip()\n"} +{"Prompt":"This algorithm k33 was first reported by Dan Bernstein many years ago in comp.lang.c Another version of this algorithm now favored by Bernstein uses xor: hashi hashi 1 33 stri; First Magic constant 33: It has never been adequately explained. It's magic because it works better than many other constants, prime or not. Second Magic Constant 5381: 1. odd number 2. prime number 3. deficient number 4. 001010100000101 b source: http:www.cse.yorku.caozhash.html Implementation of djb2 hash algorithm that is popular because of it's magic constants. djb2'Algorithms' 3782405311 djb2'scramble bits' 1609059040","Completions":"def djb2(s: str) -> int:\n \"\"\"\n Implementation of djb2 hash algorithm that\n is popular because of it's magic constants.\n\n >>> djb2('Algorithms')\n 3782405311\n\n >>> djb2('scramble bits')\n 1609059040\n \"\"\"\n hash_value = 5381\n for x in s:\n hash_value = ((hash_value << 5) + hash_value) + ord(x)\n return hash_value & 0xFFFFFFFF\n"} +{"Prompt":"Implementation of ElfHash Algorithm, a variant of PJW hash function. elfhash'lorem ipsum' 253956621","Completions":"def elf_hash(data: str) -> int:\n \"\"\"\n Implementation of ElfHash Algorithm, a variant of PJW hash function.\n\n >>> elf_hash('lorem ipsum')\n 253956621\n \"\"\"\n hash_ = x = 0\n for letter in data:\n hash_ = (hash_ << 4) + ord(letter)\n x = hash_ & 0xF0000000\n if x != 0:\n hash_ ^= x >> 24\n hash_ &= ~x\n return hash_\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"The Fletcher checksum is an algorithm for computing a positiondependent checksum devised by John G. Fletcher 19342012 at Lawrence Livermore Labs in the late 1970s.1 The objective of the Fletcher checksum was to provide errordetection properties approaching those of a cyclic redundancy check but with the lower computational effort associated with summation techniques. Source: https:en.wikipedia.orgwikiFletcher27schecksum Loop through every character in the data and add to two sums. fletcher16'hello world' 6752 fletcher16'onethousandfourhundredthirtyfour' 28347 fletcher16'The quick brown fox jumps over the lazy dog.' 5655","Completions":"def fletcher16(text: str) -> int:\n \"\"\"\n Loop through every character in the data and add to two sums.\n\n >>> fletcher16('hello world')\n 6752\n >>> fletcher16('onethousandfourhundredthirtyfour')\n 28347\n >>> fletcher16('The quick brown fox jumps over the lazy dog.')\n 5655\n \"\"\"\n data = bytes(text, \"ascii\")\n sum1 = 0\n sum2 = 0\n for character in data:\n sum1 = (sum1 + character) % 255\n sum2 = (sum1 + sum2) % 255\n return (sum2 << 8) | sum1\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Author: Joo Gustavo A. Amorim Gabriel Kunz Author email: joaogustavoamorimgmail.com and gabrielkunzuergs.edu.br Coding date: apr 2019 Black: True This code implement the Hamming code: https:en.wikipedia.orgwikiHammingcode In telecommunication, Hamming codes are a family of linear errorcorrecting codes. Hamming codes can detect up to twobit errors or correct onebit errors without detection of uncorrected errors. By contrast, the simple parity code cannot correct errors, and can detect only an odd number of bits in error. Hamming codes are perfect codes, that is, they achieve the highest possible rate for codes with their block length and minimum distance of three. the implemented code consists of: a function responsible for encoding the message emitterConverter return the encoded message a function responsible for decoding the message receptorConverter return the decoded message and a ack of data integrity how to use: to be used you must declare how many parity bits sizePari you want to include in the message. it is desired for test purposes to select a bit to be set as an error. This serves to check whether the code is working correctly. Lastly, the variable of the messageword that must be desired to be encoded text. how this work: declaration of variables sizePari, be, text converts the messageword text to binary using the texttobits function encodes the message using the rules of hamming encoding decodes the message using the rules of hamming encoding print the original message, the encoded message and the decoded message forces an error in the coded text variable decodes the message that was forced the error print the original message, the encoded message, the bit changed message and the decoded message Imports Functions of binary conversion texttobitsmsg '011011010111001101100111' textfrombits'011011010111001101100111' 'msg' Functions of hamming code :param sizepar: how many parity bits the message must have :param data: information bits :return: message to be transmitted by unreliable medium bits of information merged with parity bits emitterconverter4, 101010111111 '1', '1', '1', '1', '0', '1', '0', '0', '1', '0', '1', '1', '1', '1', '1', '1' emitterconverter5, 101010111111 Traceback most recent call last: ... ValueError: size of parity don't match with size of data sorted information data for the size of the output data data position template parity parity bit counter counter position of data bits Performs a template of bit positions who should be given, and who should be parity Sorts the data to the new output size Calculates parity Bit counter one for a given parity counter to control the loop reading Mount the message receptorconverter4, 1111010010111111 '1', '0', '1', '0', '1', '0', '1', '1', '1', '1', '1', '1', True data position template parity Parity bit counter Counter p data bit reading list of parity received Performs a template of bit positions who should be given, and who should be parity Sorts the data to the new output size calculates the parity with the data sorted information data for the size of the output data Data position feedback parity Parity bit counter Counter p data bit reading Performs a template position of bits who should be given, and who should be parity Sorts the data to the new output size Calculates parity Bit counter one for a certain parity Counter to control loop reading Mount the message Example how to use number of parity bits sizePari 4 location of the bit that will be forced an error be 2 Messageword to be encoded and decoded with hamming text inputEnter the word to be read: text Message01 Convert the message to binary binaryText texttobitstext Prints the binary of the string printText input in binary is ' binaryText ' total transmitted bits totalBits lenbinaryText sizePari printSize of data is strtotalBits printn Message exchange printData to send binaryText dataOut emitterConvertersizePari, binaryText printData converted .joindataOut dataReceiv, ack receptorConvertersizePari, dataOut print Data receive .joindataReceiv tt Data integrity: strack printn Force error printData to send binaryText dataOut emitterConvertersizePari, binaryText printData converted .joindataOut forces error dataOutbe 1 dataOutbe 0 0 dataOutbe 1 printData after transmission .joindataOut dataReceiv, ack receptorConvertersizePari, dataOut print Data receive .joindataReceiv tt Data integrity: strack","Completions":"# Author: Jo\u00e3o Gustavo A. Amorim & Gabriel Kunz\n# Author email: joaogustavoamorim@gmail.com and gabriel-kunz@uergs.edu.br\n# Coding date: apr 2019\n# Black: True\n\n\"\"\"\n * This code implement the Hamming code:\n https:\/\/en.wikipedia.org\/wiki\/Hamming_code - In telecommunication,\n Hamming codes are a family of linear error-correcting codes. Hamming\n codes can detect up to two-bit errors or correct one-bit errors\n without detection of uncorrected errors. By contrast, the simple\n parity code cannot correct errors, and can detect only an odd number\n of bits in error. Hamming codes are perfect codes, that is, they\n achieve the highest possible rate for codes with their block length\n and minimum distance of three.\n\n * the implemented code consists of:\n * a function responsible for encoding the message (emitterConverter)\n * return the encoded message\n * a function responsible for decoding the message (receptorConverter)\n * return the decoded message and a ack of data integrity\n\n * how to use:\n to be used you must declare how many parity bits (sizePari)\n you want to include in the message.\n it is desired (for test purposes) to select a bit to be set\n as an error. This serves to check whether the code is working correctly.\n Lastly, the variable of the message\/word that must be desired to be\n encoded (text).\n\n * how this work:\n declaration of variables (sizePari, be, text)\n\n converts the message\/word (text) to binary using the\n text_to_bits function\n encodes the message using the rules of hamming encoding\n decodes the message using the rules of hamming encoding\n print the original message, the encoded message and the\n decoded message\n\n forces an error in the coded text variable\n decodes the message that was forced the error\n print the original message, the encoded message, the bit changed\n message and the decoded message\n\"\"\"\n\n# Imports\nimport numpy as np\n\n\n# Functions of binary conversion--------------------------------------\ndef text_to_bits(text, encoding=\"utf-8\", errors=\"surrogatepass\"):\n \"\"\"\n >>> text_to_bits(\"msg\")\n '011011010111001101100111'\n \"\"\"\n bits = bin(int.from_bytes(text.encode(encoding, errors), \"big\"))[2:]\n return bits.zfill(8 * ((len(bits) + 7) \/\/ 8))\n\n\ndef text_from_bits(bits, encoding=\"utf-8\", errors=\"surrogatepass\"):\n \"\"\"\n >>> text_from_bits('011011010111001101100111')\n 'msg'\n \"\"\"\n n = int(bits, 2)\n return n.to_bytes((n.bit_length() + 7) \/\/ 8, \"big\").decode(encoding, errors) or \"\\0\"\n\n\n# Functions of hamming code-------------------------------------------\ndef emitter_converter(size_par, data):\n \"\"\"\n :param size_par: how many parity bits the message must have\n :param data: information bits\n :return: message to be transmitted by unreliable medium\n - bits of information merged with parity bits\n\n >>> emitter_converter(4, \"101010111111\")\n ['1', '1', '1', '1', '0', '1', '0', '0', '1', '0', '1', '1', '1', '1', '1', '1']\n >>> emitter_converter(5, \"101010111111\")\n Traceback (most recent call last):\n ...\n ValueError: size of parity don't match with size of data\n \"\"\"\n if size_par + len(data) <= 2**size_par - (len(data) - 1):\n raise ValueError(\"size of parity don't match with size of data\")\n\n data_out = []\n parity = []\n bin_pos = [bin(x)[2:] for x in range(1, size_par + len(data) + 1)]\n\n # sorted information data for the size of the output data\n data_ord = []\n # data position template + parity\n data_out_gab = []\n # parity bit counter\n qtd_bp = 0\n # counter position of data bits\n cont_data = 0\n\n for x in range(1, size_par + len(data) + 1):\n # Performs a template of bit positions - who should be given,\n # and who should be parity\n if qtd_bp < size_par:\n if (np.log(x) \/ np.log(2)).is_integer():\n data_out_gab.append(\"P\")\n qtd_bp = qtd_bp + 1\n else:\n data_out_gab.append(\"D\")\n else:\n data_out_gab.append(\"D\")\n\n # Sorts the data to the new output size\n if data_out_gab[-1] == \"D\":\n data_ord.append(data[cont_data])\n cont_data += 1\n else:\n data_ord.append(None)\n\n # Calculates parity\n qtd_bp = 0 # parity bit counter\n for bp in range(1, size_par + 1):\n # Bit counter one for a given parity\n cont_bo = 0\n # counter to control the loop reading\n cont_loop = 0\n for x in data_ord:\n if x is not None:\n try:\n aux = (bin_pos[cont_loop])[-1 * (bp)]\n except IndexError:\n aux = \"0\"\n if aux == \"1\" and x == \"1\":\n cont_bo += 1\n cont_loop += 1\n parity.append(cont_bo % 2)\n\n qtd_bp += 1\n\n # Mount the message\n cont_bp = 0 # parity bit counter\n for x in range(size_par + len(data)):\n if data_ord[x] is None:\n data_out.append(str(parity[cont_bp]))\n cont_bp += 1\n else:\n data_out.append(data_ord[x])\n\n return data_out\n\n\ndef receptor_converter(size_par, data):\n \"\"\"\n >>> receptor_converter(4, \"1111010010111111\")\n (['1', '0', '1', '0', '1', '0', '1', '1', '1', '1', '1', '1'], True)\n \"\"\"\n # data position template + parity\n data_out_gab = []\n # Parity bit counter\n qtd_bp = 0\n # Counter p data bit reading\n cont_data = 0\n # list of parity received\n parity_received = []\n data_output = []\n\n for x in range(1, len(data) + 1):\n # Performs a template of bit positions - who should be given,\n # and who should be parity\n if qtd_bp < size_par and (np.log(x) \/ np.log(2)).is_integer():\n data_out_gab.append(\"P\")\n qtd_bp = qtd_bp + 1\n else:\n data_out_gab.append(\"D\")\n\n # Sorts the data to the new output size\n if data_out_gab[-1] == \"D\":\n data_output.append(data[cont_data])\n else:\n parity_received.append(data[cont_data])\n cont_data += 1\n\n # -----------calculates the parity with the data\n data_out = []\n parity = []\n bin_pos = [bin(x)[2:] for x in range(1, size_par + len(data_output) + 1)]\n\n # sorted information data for the size of the output data\n data_ord = []\n # Data position feedback + parity\n data_out_gab = []\n # Parity bit counter\n qtd_bp = 0\n # Counter p data bit reading\n cont_data = 0\n\n for x in range(1, size_par + len(data_output) + 1):\n # Performs a template position of bits - who should be given,\n # and who should be parity\n if qtd_bp < size_par and (np.log(x) \/ np.log(2)).is_integer():\n data_out_gab.append(\"P\")\n qtd_bp = qtd_bp + 1\n else:\n data_out_gab.append(\"D\")\n\n # Sorts the data to the new output size\n if data_out_gab[-1] == \"D\":\n data_ord.append(data_output[cont_data])\n cont_data += 1\n else:\n data_ord.append(None)\n\n # Calculates parity\n qtd_bp = 0 # parity bit counter\n for bp in range(1, size_par + 1):\n # Bit counter one for a certain parity\n cont_bo = 0\n # Counter to control loop reading\n cont_loop = 0\n for x in data_ord:\n if x is not None:\n try:\n aux = (bin_pos[cont_loop])[-1 * (bp)]\n except IndexError:\n aux = \"0\"\n if aux == \"1\" and x == \"1\":\n cont_bo += 1\n cont_loop += 1\n parity.append(str(cont_bo % 2))\n\n qtd_bp += 1\n\n # Mount the message\n cont_bp = 0 # Parity bit counter\n for x in range(size_par + len(data_output)):\n if data_ord[x] is None:\n data_out.append(str(parity[cont_bp]))\n cont_bp += 1\n else:\n data_out.append(data_ord[x])\n\n ack = parity_received == parity\n return data_output, ack\n\n\n# ---------------------------------------------------------------------\n\"\"\"\n# Example how to use\n\n# number of parity bits\nsizePari = 4\n\n# location of the bit that will be forced an error\nbe = 2\n\n# Message\/word to be encoded and decoded with hamming\n# text = input(\"Enter the word to be read: \")\ntext = \"Message01\"\n\n# Convert the message to binary\nbinaryText = text_to_bits(text)\n\n# Prints the binary of the string\nprint(\"Text input in binary is '\" + binaryText + \"'\")\n\n# total transmitted bits\ntotalBits = len(binaryText) + sizePari\nprint(\"Size of data is \" + str(totalBits))\n\nprint(\"\\n --Message exchange--\")\nprint(\"Data to send ------------> \" + binaryText)\ndataOut = emitterConverter(sizePari, binaryText)\nprint(\"Data converted ----------> \" + \"\".join(dataOut))\ndataReceiv, ack = receptorConverter(sizePari, dataOut)\nprint(\n \"Data receive ------------> \"\n + \"\".join(dataReceiv)\n + \"\\t\\t -- Data integrity: \"\n + str(ack)\n)\n\n\nprint(\"\\n --Force error--\")\nprint(\"Data to send ------------> \" + binaryText)\ndataOut = emitterConverter(sizePari, binaryText)\nprint(\"Data converted ----------> \" + \"\".join(dataOut))\n\n# forces error\ndataOut[-be] = \"1\" * (dataOut[-be] == \"0\") + \"0\" * (dataOut[-be] == \"1\")\nprint(\"Data after transmission -> \" + \"\".join(dataOut))\ndataReceiv, ack = receptorConverter(sizePari, dataOut)\nprint(\n \"Data receive ------------> \"\n + \"\".join(dataReceiv)\n + \"\\t\\t -- Data integrity: \"\n + str(ack)\n)\n\"\"\"\n"} +{"Prompt":"Luhn Algorithm from future import annotations def isluhnstring: str bool: checkdigit: int vector: liststr liststring vector, checkdigit vector:1, intvector1 vector: listint intdigit for digit in vector vector.reverse for i, digit in enumeratevector: if i 1 0: doubled: int digit 2 if doubled 9: doubled 9 checkdigit doubled else: checkdigit digit return checkdigit 10 0 if name main: import doctest doctest.testmod assert isluhn79927398713 assert not isluhn79927398714","Completions":"from __future__ import annotations\n\n\ndef is_luhn(string: str) -> bool:\n \"\"\"\n Perform Luhn validation on an input string\n Algorithm:\n * Double every other digit starting from 2nd last digit.\n * Subtract 9 if number is greater than 9.\n * Sum the numbers\n *\n >>> test_cases = (79927398710, 79927398711, 79927398712, 79927398713,\n ... 79927398714, 79927398715, 79927398716, 79927398717, 79927398718,\n ... 79927398719)\n >>> [is_luhn(str(test_case)) for test_case in test_cases]\n [False, False, False, True, False, False, False, False, False, False]\n \"\"\"\n check_digit: int\n _vector: list[str] = list(string)\n __vector, check_digit = _vector[:-1], int(_vector[-1])\n vector: list[int] = [int(digit) for digit in __vector]\n\n vector.reverse()\n for i, digit in enumerate(vector):\n if i & 1 == 0:\n doubled: int = digit * 2\n if doubled > 9:\n doubled -= 9\n check_digit += doubled\n else:\n check_digit += digit\n\n return check_digit % 10 == 0\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n assert is_luhn(\"79927398713\")\n assert not is_luhn(\"79927398714\")\n"} +{"Prompt":"The MD5 algorithm is a hash function that's commonly used as a checksum to detect data corruption. The algorithm works by processing a given message in blocks of 512 bits, padding the message as needed. It uses the blocks to operate a 128bit state and performs a total of 64 such operations. Note that all values are littleendian, so inputs are converted as needed. Although MD5 was used as a cryptographic hash function in the past, it's since been cracked, so it shouldn't be used for security purposes. For more info, see https:en.wikipedia.orgwikiMD5 Converts the given string to littleendian in groups of 8 chars. Arguments: string32 string 32char string Raises: ValueError input is not 32 char Returns: 32char littleendian string tolittleendianb'1234567890abcdfghijklmnopqrstuvw' b'pqrstuvwhijklmno90abcdfg12345678' tolittleendianb'1234567890' Traceback most recent call last: ... ValueError: Input must be of length 32 Converts the given nonnegative integer to hex string. Example: Suppose the input is the following: i 1234 The input is 0x000004d2 in hex, so the littleendian hex string is d2040000. Arguments: i int integer Raises: ValueError input is negative Returns: 8char littleendian hex string reformathex1234 b'd2040000' reformathex666 b'9a020000' reformathex0 b'00000000' reformathex1234567890 b'd2029649' reformathex1234567890987654321 b'b11c6cb1' reformathex1 Traceback most recent call last: ... ValueError: Input must be nonnegative Preprocesses the message string: Convert message to bit string Pad bit string to a multiple of 512 chars: Append a 1 Append 0's until length 448 mod 512 Append length of original message 64 chars Example: Suppose the input is the following: message a The message bit string is 01100001, which is 8 bits long. Thus, the bit string needs 439 bits of padding so that bitstring 1 padding 448 mod 512. The message length is 000010000...0 in 64bit littleendian binary. The combined bit string is then 512 bits long. Arguments: message string message string Returns: processed bit string padded to a multiple of 512 chars preprocessba b01100001 b1 ... b0 439 b00001000 b0 56 True preprocessb b1 b0 447 b0 64 True Pad bitstring to a multiple of 512 chars Splits bit string into blocks of 512 chars and yields each block as a list of 32bit words Example: Suppose the input is the following: bitstring 000000000...0 0x00 32 bits, padded to the right 000000010...0 0x01 32 bits, padded to the right 000000100...0 0x02 32 bits, padded to the right 000000110...0 0x03 32 bits, padded to the right ... 000011110...0 0x0a 32 bits, padded to the right Then lenbitstring 512, so there'll be 1 block. The block is split into 32bit words, and each word is converted to little endian. The first word is interpreted as 0 in decimal, the second word is interpreted as 1 in decimal, etc. Thus, blockwords 0, 1, 2, 3, ..., 15. Arguments: bitstring string bit string with multiple of 512 as length Raises: ValueError length of bit string isn't multiple of 512 Yields: a list of 16 32bit words teststring .joinformatn 24, 032b for n in range16 ... .encodeutf8 listgetblockwordsteststring 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 listgetblockwordsteststring 4 listrange16 4 True listgetblockwordsb1 512 4294967295 16 True listgetblockwordsb listgetblockwordsb1111 Traceback most recent call last: ... ValueError: Input must have length that's a multiple of 512 Perform bitwise NOT on given int. Arguments: i int given int Raises: ValueError input is negative Returns: Result of bitwise NOT on i not3234 4294967261 not321234 4294966061 not324294966061 1234 not320 4294967295 not321 4294967294 not321 Traceback most recent call last: ... ValueError: Input must be nonnegative Add two numbers as 32bit ints. Arguments: a int first given int b int second given int Returns: a b as an unsigned 32bit int sum321, 1 2 sum322, 3 5 sum320, 0 0 sum321, 1 4294967294 sum324294967295, 1 0 Rotate the bits of a given int left by a given amount. Arguments: i int given int shift int shift amount Raises: ValueError either given int or shift is negative Returns: i rotated to the left by shift bits leftrotate321234, 1 2468 leftrotate321111, 4 17776 leftrotate322147483648, 1 1 leftrotate322147483648, 3 4 leftrotate324294967295, 4 4294967295 leftrotate321234, 0 1234 leftrotate320, 0 0 leftrotate321, 0 Traceback most recent call last: ... ValueError: Input must be nonnegative leftrotate320, 1 Traceback most recent call last: ... ValueError: Shift must be nonnegative Returns the 32char MD5 hash of a given message. Reference: https:en.wikipedia.orgwikiMD5Algorithm Arguments: message string message Returns: 32char MD5 hash string md5meb b'd41d8cd98f00b204e9800998ecf8427e' md5mebThe quick brown fox jumps over the lazy dog b'9e107d9d372bb6826bd81d3542a419d6' md5mebThe quick brown fox jumps over the lazy dog. b'e4d909c290d0fb1ca068ffaddf22cbd0' import hashlib from string import asciiletters msgs b, asciiletters.encodeutf8, .encodeutf8, ... bThe quick brown fox jumps over the lazy dog. allmd5memsg hashlib.md5msg.hexdigest.encodeutf8 for msg in msgs True Convert to bit string, add padding and append message length Starting states Process bit string in chunks, each with 16 32char words Hash current chunk f b c not32b d Alternate definition for f f d b not32d c Alternate definition for f Add hashed chunk to running total","Completions":"from collections.abc import Generator\nfrom math import sin\n\n\ndef to_little_endian(string_32: bytes) -> bytes:\n \"\"\"\n Converts the given string to little-endian in groups of 8 chars.\n\n Arguments:\n string_32 {[string]} -- [32-char string]\n\n Raises:\n ValueError -- [input is not 32 char]\n\n Returns:\n 32-char little-endian string\n >>> to_little_endian(b'1234567890abcdfghijklmnopqrstuvw')\n b'pqrstuvwhijklmno90abcdfg12345678'\n >>> to_little_endian(b'1234567890')\n Traceback (most recent call last):\n ...\n ValueError: Input must be of length 32\n \"\"\"\n if len(string_32) != 32:\n raise ValueError(\"Input must be of length 32\")\n\n little_endian = b\"\"\n for i in [3, 2, 1, 0]:\n little_endian += string_32[8 * i : 8 * i + 8]\n return little_endian\n\n\ndef reformat_hex(i: int) -> bytes:\n \"\"\"\n Converts the given non-negative integer to hex string.\n\n Example: Suppose the input is the following:\n i = 1234\n\n The input is 0x000004d2 in hex, so the little-endian hex string is\n \"d2040000\".\n\n Arguments:\n i {[int]} -- [integer]\n\n Raises:\n ValueError -- [input is negative]\n\n Returns:\n 8-char little-endian hex string\n\n >>> reformat_hex(1234)\n b'd2040000'\n >>> reformat_hex(666)\n b'9a020000'\n >>> reformat_hex(0)\n b'00000000'\n >>> reformat_hex(1234567890)\n b'd2029649'\n >>> reformat_hex(1234567890987654321)\n b'b11c6cb1'\n >>> reformat_hex(-1)\n Traceback (most recent call last):\n ...\n ValueError: Input must be non-negative\n \"\"\"\n if i < 0:\n raise ValueError(\"Input must be non-negative\")\n\n hex_rep = format(i, \"08x\")[-8:]\n little_endian_hex = b\"\"\n for i in [3, 2, 1, 0]:\n little_endian_hex += hex_rep[2 * i : 2 * i + 2].encode(\"utf-8\")\n return little_endian_hex\n\n\ndef preprocess(message: bytes) -> bytes:\n \"\"\"\n Preprocesses the message string:\n - Convert message to bit string\n - Pad bit string to a multiple of 512 chars:\n - Append a 1\n - Append 0's until length = 448 (mod 512)\n - Append length of original message (64 chars)\n\n Example: Suppose the input is the following:\n message = \"a\"\n\n The message bit string is \"01100001\", which is 8 bits long. Thus, the\n bit string needs 439 bits of padding so that\n (bit_string + \"1\" + padding) = 448 (mod 512).\n The message length is \"000010000...0\" in 64-bit little-endian binary.\n The combined bit string is then 512 bits long.\n\n Arguments:\n message {[string]} -- [message string]\n\n Returns:\n processed bit string padded to a multiple of 512 chars\n\n >>> preprocess(b\"a\") == (b\"01100001\" + b\"1\" +\n ... (b\"0\" * 439) + b\"00001000\" + (b\"0\" * 56))\n True\n >>> preprocess(b\"\") == b\"1\" + (b\"0\" * 447) + (b\"0\" * 64)\n True\n \"\"\"\n bit_string = b\"\"\n for char in message:\n bit_string += format(char, \"08b\").encode(\"utf-8\")\n start_len = format(len(bit_string), \"064b\").encode(\"utf-8\")\n\n # Pad bit_string to a multiple of 512 chars\n bit_string += b\"1\"\n while len(bit_string) % 512 != 448:\n bit_string += b\"0\"\n bit_string += to_little_endian(start_len[32:]) + to_little_endian(start_len[:32])\n\n return bit_string\n\n\ndef get_block_words(bit_string: bytes) -> Generator[list[int], None, None]:\n \"\"\"\n Splits bit string into blocks of 512 chars and yields each block as a list\n of 32-bit words\n\n Example: Suppose the input is the following:\n bit_string =\n \"000000000...0\" + # 0x00 (32 bits, padded to the right)\n \"000000010...0\" + # 0x01 (32 bits, padded to the right)\n \"000000100...0\" + # 0x02 (32 bits, padded to the right)\n \"000000110...0\" + # 0x03 (32 bits, padded to the right)\n ...\n \"000011110...0\" # 0x0a (32 bits, padded to the right)\n\n Then len(bit_string) == 512, so there'll be 1 block. The block is split\n into 32-bit words, and each word is converted to little endian. The\n first word is interpreted as 0 in decimal, the second word is\n interpreted as 1 in decimal, etc.\n\n Thus, block_words == [[0, 1, 2, 3, ..., 15]].\n\n Arguments:\n bit_string {[string]} -- [bit string with multiple of 512 as length]\n\n Raises:\n ValueError -- [length of bit string isn't multiple of 512]\n\n Yields:\n a list of 16 32-bit words\n\n >>> test_string = (\"\".join(format(n << 24, \"032b\") for n in range(16))\n ... .encode(\"utf-8\"))\n >>> list(get_block_words(test_string))\n [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]]\n >>> list(get_block_words(test_string * 4)) == [list(range(16))] * 4\n True\n >>> list(get_block_words(b\"1\" * 512)) == [[4294967295] * 16]\n True\n >>> list(get_block_words(b\"\"))\n []\n >>> list(get_block_words(b\"1111\"))\n Traceback (most recent call last):\n ...\n ValueError: Input must have length that's a multiple of 512\n \"\"\"\n if len(bit_string) % 512 != 0:\n raise ValueError(\"Input must have length that's a multiple of 512\")\n\n for pos in range(0, len(bit_string), 512):\n block = bit_string[pos : pos + 512]\n block_words = []\n for i in range(0, 512, 32):\n block_words.append(int(to_little_endian(block[i : i + 32]), 2))\n yield block_words\n\n\ndef not_32(i: int) -> int:\n \"\"\"\n Perform bitwise NOT on given int.\n\n Arguments:\n i {[int]} -- [given int]\n\n Raises:\n ValueError -- [input is negative]\n\n Returns:\n Result of bitwise NOT on i\n\n >>> not_32(34)\n 4294967261\n >>> not_32(1234)\n 4294966061\n >>> not_32(4294966061)\n 1234\n >>> not_32(0)\n 4294967295\n >>> not_32(1)\n 4294967294\n >>> not_32(-1)\n Traceback (most recent call last):\n ...\n ValueError: Input must be non-negative\n \"\"\"\n if i < 0:\n raise ValueError(\"Input must be non-negative\")\n\n i_str = format(i, \"032b\")\n new_str = \"\"\n for c in i_str:\n new_str += \"1\" if c == \"0\" else \"0\"\n return int(new_str, 2)\n\n\ndef sum_32(a: int, b: int) -> int:\n \"\"\"\n Add two numbers as 32-bit ints.\n\n Arguments:\n a {[int]} -- [first given int]\n b {[int]} -- [second given int]\n\n Returns:\n (a + b) as an unsigned 32-bit int\n\n >>> sum_32(1, 1)\n 2\n >>> sum_32(2, 3)\n 5\n >>> sum_32(0, 0)\n 0\n >>> sum_32(-1, -1)\n 4294967294\n >>> sum_32(4294967295, 1)\n 0\n \"\"\"\n return (a + b) % 2**32\n\n\ndef left_rotate_32(i: int, shift: int) -> int:\n \"\"\"\n Rotate the bits of a given int left by a given amount.\n\n Arguments:\n i {[int]} -- [given int]\n shift {[int]} -- [shift amount]\n\n Raises:\n ValueError -- [either given int or shift is negative]\n\n Returns:\n `i` rotated to the left by `shift` bits\n\n >>> left_rotate_32(1234, 1)\n 2468\n >>> left_rotate_32(1111, 4)\n 17776\n >>> left_rotate_32(2147483648, 1)\n 1\n >>> left_rotate_32(2147483648, 3)\n 4\n >>> left_rotate_32(4294967295, 4)\n 4294967295\n >>> left_rotate_32(1234, 0)\n 1234\n >>> left_rotate_32(0, 0)\n 0\n >>> left_rotate_32(-1, 0)\n Traceback (most recent call last):\n ...\n ValueError: Input must be non-negative\n >>> left_rotate_32(0, -1)\n Traceback (most recent call last):\n ...\n ValueError: Shift must be non-negative\n \"\"\"\n if i < 0:\n raise ValueError(\"Input must be non-negative\")\n if shift < 0:\n raise ValueError(\"Shift must be non-negative\")\n return ((i << shift) ^ (i >> (32 - shift))) % 2**32\n\n\ndef md5_me(message: bytes) -> bytes:\n \"\"\"\n Returns the 32-char MD5 hash of a given message.\n\n Reference: https:\/\/en.wikipedia.org\/wiki\/MD5#Algorithm\n\n Arguments:\n message {[string]} -- [message]\n\n Returns:\n 32-char MD5 hash string\n\n >>> md5_me(b\"\")\n b'd41d8cd98f00b204e9800998ecf8427e'\n >>> md5_me(b\"The quick brown fox jumps over the lazy dog\")\n b'9e107d9d372bb6826bd81d3542a419d6'\n >>> md5_me(b\"The quick brown fox jumps over the lazy dog.\")\n b'e4d909c290d0fb1ca068ffaddf22cbd0'\n\n >>> import hashlib\n >>> from string import ascii_letters\n >>> msgs = [b\"\", ascii_letters.encode(\"utf-8\"), \"\u00dc\u00f1\u00ee\u00e7\u00f8\u2202\u00e9\".encode(\"utf-8\"),\n ... b\"The quick brown fox jumps over the lazy dog.\"]\n >>> all(md5_me(msg) == hashlib.md5(msg).hexdigest().encode(\"utf-8\") for msg in msgs)\n True\n \"\"\"\n\n # Convert to bit string, add padding and append message length\n bit_string = preprocess(message)\n\n added_consts = [int(2**32 * abs(sin(i + 1))) for i in range(64)]\n\n # Starting states\n a0 = 0x67452301\n b0 = 0xEFCDAB89\n c0 = 0x98BADCFE\n d0 = 0x10325476\n\n shift_amounts = [\n 7,\n 12,\n 17,\n 22,\n 7,\n 12,\n 17,\n 22,\n 7,\n 12,\n 17,\n 22,\n 7,\n 12,\n 17,\n 22,\n 5,\n 9,\n 14,\n 20,\n 5,\n 9,\n 14,\n 20,\n 5,\n 9,\n 14,\n 20,\n 5,\n 9,\n 14,\n 20,\n 4,\n 11,\n 16,\n 23,\n 4,\n 11,\n 16,\n 23,\n 4,\n 11,\n 16,\n 23,\n 4,\n 11,\n 16,\n 23,\n 6,\n 10,\n 15,\n 21,\n 6,\n 10,\n 15,\n 21,\n 6,\n 10,\n 15,\n 21,\n 6,\n 10,\n 15,\n 21,\n ]\n\n # Process bit string in chunks, each with 16 32-char words\n for block_words in get_block_words(bit_string):\n a = a0\n b = b0\n c = c0\n d = d0\n\n # Hash current chunk\n for i in range(64):\n if i <= 15:\n # f = (b & c) | (not_32(b) & d) # Alternate definition for f\n f = d ^ (b & (c ^ d))\n g = i\n elif i <= 31:\n # f = (d & b) | (not_32(d) & c) # Alternate definition for f\n f = c ^ (d & (b ^ c))\n g = (5 * i + 1) % 16\n elif i <= 47:\n f = b ^ c ^ d\n g = (3 * i + 5) % 16\n else:\n f = c ^ (b | not_32(d))\n g = (7 * i) % 16\n f = (f + a + added_consts[i] + block_words[g]) % 2**32\n a = d\n d = c\n c = b\n b = sum_32(b, left_rotate_32(f, shift_amounts[i]))\n\n # Add hashed chunk to running total\n a0 = sum_32(a0, a)\n b0 = sum_32(b0, b)\n c0 = sum_32(c0, c)\n d0 = sum_32(d0, d)\n\n digest = reformat_hex(a0) + reformat_hex(b0) + reformat_hex(c0) + reformat_hex(d0)\n return digest\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"This algorithm was created for sdbm a publicdomain reimplementation of ndbm database library. It was found to do well in scrambling bits, causing better distribution of the keys and fewer splits. It also happens to be a good general hashing function with good distribution. The actual function pseudo code is: for i in i..lenstr: hashi hashi 1 65599 stri; What is included below is the faster version used in gawk. there is even a faster, duffdevice version The magic constant 65599 was picked out of thin air while experimenting with different constants. It turns out to be a prime. This is one of the algorithms used in berkeley db see sleepycat and elsewhere. source: http:www.cse.yorku.caozhash.html Function implements sdbm hash, easy to use, great for bits scrambling. iterates over each character in the given string and applies function to each of them. sdbm'Algorithms' 1462174910723540325254304520539387479031000036 sdbm'scramble bits' 730247649148944819640658295400555317318720608290373040936089","Completions":"def sdbm(plain_text: str) -> int:\n \"\"\"\n Function implements sdbm hash, easy to use, great for bits scrambling.\n iterates over each character in the given string and applies function to each of\n them.\n\n >>> sdbm('Algorithms')\n 1462174910723540325254304520539387479031000036\n\n >>> sdbm('scramble bits')\n 730247649148944819640658295400555317318720608290373040936089\n \"\"\"\n hash_value = 0\n for plain_chr in plain_text:\n hash_value = (\n ord(plain_chr) + (hash_value << 6) + (hash_value << 16) - hash_value\n )\n return hash_value\n"} +{"Prompt":"Implementation of the SHA1 hash function and gives utilities to find hash of string or hash of text from a file. Also contains a Test class to verify that the generated hash matches what is returned by the hashlib library Usage: python sha1.py string Hello World!! python sha1.py file helloworld.txt When run without any arguments, it prints the hash of the string Hello World!! Welcome to Cryptography SHA1 hash or SHA1 sum of a string is a cryptographic function, which means it is easy to calculate forwards but extremely difficult to calculate backwards. What this means is you can easily calculate the hash of a string, but it is extremely difficult to know the original string if you have its hash. This property is useful for communicating securely, send encrypted messages and is very useful in payment systems, blockchain and cryptocurrency etc. The algorithm as described in the reference: First we start with a message. The message is padded and the length of the message is added to the end. It is then split into blocks of 512 bits or 64 bytes. The blocks are then processed one at a time. Each block must be expanded and compressed. The value after each compression is added to a 160bit buffer called the current hash state. After the last block is processed, the current hash state is returned as the final hash. Reference: https:deadhacker.com20060221sha1illustrated Class to contain the entire pipeline for SHA1 hashing algorithm SHA1Hashbytes'Allan', 'utf8'.finalhash '872af2d8ac3d8695387e7c804bf0e02c18df9e6e' Initiates the variables data and h. h is a list of 5 8digit hexadecimal numbers corresponding to 1732584193, 4023233417, 2562383102, 271733878, 3285377520 respectively. We will start with this as a message digest. 0x is how you write hexadecimal numbers in Python Static method to be used inside other methods. Left rotates n by b. SHA1Hash''.rotate12,2 48 Pads the input message with zeros so that paddeddata has 64 bytes or 512 bits Returns a list of bytestrings each of length 64 staticmethod Takes a bytestringblock of length 64, unpacks it to a list of integers and returns a list of 80 integers after some bit operations Calls all the other methods to process the input. Pads the data, then splits into blocks and then does a series of operations for each block including expansion. For each block, the variable h that was initialized is copied to a,b,c,d,e and these 5 variables a,b,c,d,e undergo several changes. After all the blocks are processed, these 5 variables are pairwise added to h ie a to h0, b to h1 and so on. This h becomes our final hash which is returned. Provides option 'string' or 'file' to take input and prints the calculated SHA1 hash. unittest.main has been commented out because we probably don't want to run the test each time. unittest.main In any case hash input should be a bytestring","Completions":"import argparse\nimport hashlib # hashlib is only used inside the Test class\nimport struct\n\n\nclass SHA1Hash:\n \"\"\"\n Class to contain the entire pipeline for SHA1 hashing algorithm\n >>> SHA1Hash(bytes('Allan', 'utf-8')).final_hash()\n '872af2d8ac3d8695387e7c804bf0e02c18df9e6e'\n \"\"\"\n\n def __init__(self, data):\n \"\"\"\n Initiates the variables data and h. h is a list of 5 8-digit hexadecimal\n numbers corresponding to\n (1732584193, 4023233417, 2562383102, 271733878, 3285377520)\n respectively. We will start with this as a message digest. 0x is how you write\n hexadecimal numbers in Python\n \"\"\"\n self.data = data\n self.h = [0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0]\n\n @staticmethod\n def rotate(n, b):\n \"\"\"\n Static method to be used inside other methods. Left rotates n by b.\n >>> SHA1Hash('').rotate(12,2)\n 48\n \"\"\"\n return ((n << b) | (n >> (32 - b))) & 0xFFFFFFFF\n\n def padding(self):\n \"\"\"\n Pads the input message with zeros so that padded_data has 64 bytes or 512 bits\n \"\"\"\n padding = b\"\\x80\" + b\"\\x00\" * (63 - (len(self.data) + 8) % 64)\n padded_data = self.data + padding + struct.pack(\">Q\", 8 * len(self.data))\n return padded_data\n\n def split_blocks(self):\n \"\"\"\n Returns a list of bytestrings each of length 64\n \"\"\"\n return [\n self.padded_data[i : i + 64] for i in range(0, len(self.padded_data), 64)\n ]\n\n # @staticmethod\n def expand_block(self, block):\n \"\"\"\n Takes a bytestring-block of length 64, unpacks it to a list of integers and\n returns a list of 80 integers after some bit operations\n \"\"\"\n w = list(struct.unpack(\">16L\", block)) + [0] * 64\n for i in range(16, 80):\n w[i] = self.rotate((w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]), 1)\n return w\n\n def final_hash(self):\n \"\"\"\n Calls all the other methods to process the input. Pads the data, then splits\n into blocks and then does a series of operations for each block (including\n expansion).\n For each block, the variable h that was initialized is copied to a,b,c,d,e\n and these 5 variables a,b,c,d,e undergo several changes. After all the blocks\n are processed, these 5 variables are pairwise added to h ie a to h[0], b to h[1]\n and so on. This h becomes our final hash which is returned.\n \"\"\"\n self.padded_data = self.padding()\n self.blocks = self.split_blocks()\n for block in self.blocks:\n expanded_block = self.expand_block(block)\n a, b, c, d, e = self.h\n for i in range(80):\n if 0 <= i < 20:\n f = (b & c) | ((~b) & d)\n k = 0x5A827999\n elif 20 <= i < 40:\n f = b ^ c ^ d\n k = 0x6ED9EBA1\n elif 40 <= i < 60:\n f = (b & c) | (b & d) | (c & d)\n k = 0x8F1BBCDC\n elif 60 <= i < 80:\n f = b ^ c ^ d\n k = 0xCA62C1D6\n a, b, c, d, e = (\n self.rotate(a, 5) + f + e + k + expanded_block[i] & 0xFFFFFFFF,\n a,\n self.rotate(b, 30),\n c,\n d,\n )\n self.h = (\n self.h[0] + a & 0xFFFFFFFF,\n self.h[1] + b & 0xFFFFFFFF,\n self.h[2] + c & 0xFFFFFFFF,\n self.h[3] + d & 0xFFFFFFFF,\n self.h[4] + e & 0xFFFFFFFF,\n )\n return (\"{:08x}\" * 5).format(*self.h)\n\n\ndef test_sha1_hash():\n msg = b\"Test String\"\n assert SHA1Hash(msg).final_hash() == hashlib.sha1(msg).hexdigest() # noqa: S324\n\n\ndef main():\n \"\"\"\n Provides option 'string' or 'file' to take input and prints the calculated SHA1\n hash. unittest.main() has been commented out because we probably don't want to run\n the test each time.\n \"\"\"\n # unittest.main()\n parser = argparse.ArgumentParser(description=\"Process some strings or files\")\n parser.add_argument(\n \"--string\",\n dest=\"input_string\",\n default=\"Hello World!! Welcome to Cryptography\",\n help=\"Hash the string\",\n )\n parser.add_argument(\"--file\", dest=\"input_file\", help=\"Hash contents of a file\")\n args = parser.parse_args()\n input_string = args.input_string\n # In any case hash input should be a bytestring\n if args.input_file:\n with open(args.input_file, \"rb\") as f:\n hash_input = f.read()\n else:\n hash_input = bytes(input_string, \"utf-8\")\n print(SHA1Hash(hash_input).final_hash())\n\n\nif __name__ == \"__main__\":\n main()\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Author: M. Yathurshan Black Formatter: True Implementation of SHA256 Hash function in a Python class and provides utilities to find hash of string or hash of text from a file. Usage: python sha256.py string Hello World!! python sha256.py file helloworld.txt When run without any arguments, it prints the hash of the string Hello World!! Welcome to Cryptography References: https:qvault.iocryptographyhowsha2worksstepbystepsha256 https:en.wikipedia.orgwikiSHA2 Class to contain the entire pipeline for SHA1 Hashing Algorithm SHA256b'Python'.hash '18885f27b5af9012df19e496460f9294d5ab76128824c6f993787004f6d9a7db' SHA256b'hello world'.hash 'b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9' Initialize hash values Initialize round constants Convert into blocks of 64 bytes Convert the given block into a list of 4 byte integers add 48 0ed integers modify the zeroed indexes at the end of the array Compression Modify final values Right rotate a given unsigned number by a certain amount of rotations Test class for the SHA256 class. Inherits the TestCase class from unittest Provides option 'string' or 'file' to take input and prints the calculated SHA256 hash unittest.main hash input should be a bytestring","Completions":"# Author: M. Yathurshan\n# Black Formatter: True\n\n\"\"\"\nImplementation of SHA256 Hash function in a Python class and provides utilities\nto find hash of string or hash of text from a file.\n\nUsage: python sha256.py --string \"Hello World!!\"\n python sha256.py --file \"hello_world.txt\"\n When run without any arguments,\n it prints the hash of the string \"Hello World!! Welcome to Cryptography\"\n\nReferences:\nhttps:\/\/qvault.io\/cryptography\/how-sha-2-works-step-by-step-sha-256\/\nhttps:\/\/en.wikipedia.org\/wiki\/SHA-2\n\"\"\"\n\nimport argparse\nimport struct\nimport unittest\n\n\nclass SHA256:\n \"\"\"\n Class to contain the entire pipeline for SHA1 Hashing Algorithm\n\n >>> SHA256(b'Python').hash\n '18885f27b5af9012df19e496460f9294d5ab76128824c6f993787004f6d9a7db'\n\n >>> SHA256(b'hello world').hash\n 'b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9'\n \"\"\"\n\n def __init__(self, data: bytes) -> None:\n self.data = data\n\n # Initialize hash values\n self.hashes = [\n 0x6A09E667,\n 0xBB67AE85,\n 0x3C6EF372,\n 0xA54FF53A,\n 0x510E527F,\n 0x9B05688C,\n 0x1F83D9AB,\n 0x5BE0CD19,\n ]\n\n # Initialize round constants\n self.round_constants = [\n 0x428A2F98,\n 0x71374491,\n 0xB5C0FBCF,\n 0xE9B5DBA5,\n 0x3956C25B,\n 0x59F111F1,\n 0x923F82A4,\n 0xAB1C5ED5,\n 0xD807AA98,\n 0x12835B01,\n 0x243185BE,\n 0x550C7DC3,\n 0x72BE5D74,\n 0x80DEB1FE,\n 0x9BDC06A7,\n 0xC19BF174,\n 0xE49B69C1,\n 0xEFBE4786,\n 0x0FC19DC6,\n 0x240CA1CC,\n 0x2DE92C6F,\n 0x4A7484AA,\n 0x5CB0A9DC,\n 0x76F988DA,\n 0x983E5152,\n 0xA831C66D,\n 0xB00327C8,\n 0xBF597FC7,\n 0xC6E00BF3,\n 0xD5A79147,\n 0x06CA6351,\n 0x14292967,\n 0x27B70A85,\n 0x2E1B2138,\n 0x4D2C6DFC,\n 0x53380D13,\n 0x650A7354,\n 0x766A0ABB,\n 0x81C2C92E,\n 0x92722C85,\n 0xA2BFE8A1,\n 0xA81A664B,\n 0xC24B8B70,\n 0xC76C51A3,\n 0xD192E819,\n 0xD6990624,\n 0xF40E3585,\n 0x106AA070,\n 0x19A4C116,\n 0x1E376C08,\n 0x2748774C,\n 0x34B0BCB5,\n 0x391C0CB3,\n 0x4ED8AA4A,\n 0x5B9CCA4F,\n 0x682E6FF3,\n 0x748F82EE,\n 0x78A5636F,\n 0x84C87814,\n 0x8CC70208,\n 0x90BEFFFA,\n 0xA4506CEB,\n 0xBEF9A3F7,\n 0xC67178F2,\n ]\n\n self.preprocessed_data = self.preprocessing(self.data)\n self.final_hash()\n\n @staticmethod\n def preprocessing(data: bytes) -> bytes:\n padding = b\"\\x80\" + (b\"\\x00\" * (63 - (len(data) + 8) % 64))\n big_endian_integer = struct.pack(\">Q\", (len(data) * 8))\n return data + padding + big_endian_integer\n\n def final_hash(self) -> None:\n # Convert into blocks of 64 bytes\n self.blocks = [\n self.preprocessed_data[x : x + 64]\n for x in range(0, len(self.preprocessed_data), 64)\n ]\n\n for block in self.blocks:\n # Convert the given block into a list of 4 byte integers\n words = list(struct.unpack(\">16L\", block))\n # add 48 0-ed integers\n words += [0] * 48\n\n a, b, c, d, e, f, g, h = self.hashes\n\n for index in range(64):\n if index > 15:\n # modify the zero-ed indexes at the end of the array\n s0 = (\n self.ror(words[index - 15], 7)\n ^ self.ror(words[index - 15], 18)\n ^ (words[index - 15] >> 3)\n )\n s1 = (\n self.ror(words[index - 2], 17)\n ^ self.ror(words[index - 2], 19)\n ^ (words[index - 2] >> 10)\n )\n\n words[index] = (\n words[index - 16] + s0 + words[index - 7] + s1\n ) % 0x100000000\n\n # Compression\n s1 = self.ror(e, 6) ^ self.ror(e, 11) ^ self.ror(e, 25)\n ch = (e & f) ^ ((~e & (0xFFFFFFFF)) & g)\n temp1 = (\n h + s1 + ch + self.round_constants[index] + words[index]\n ) % 0x100000000\n s0 = self.ror(a, 2) ^ self.ror(a, 13) ^ self.ror(a, 22)\n maj = (a & b) ^ (a & c) ^ (b & c)\n temp2 = (s0 + maj) % 0x100000000\n\n h, g, f, e, d, c, b, a = (\n g,\n f,\n e,\n ((d + temp1) % 0x100000000),\n c,\n b,\n a,\n ((temp1 + temp2) % 0x100000000),\n )\n\n mutated_hash_values = [a, b, c, d, e, f, g, h]\n\n # Modify final values\n self.hashes = [\n ((element + mutated_hash_values[index]) % 0x100000000)\n for index, element in enumerate(self.hashes)\n ]\n\n self.hash = \"\".join([hex(value)[2:].zfill(8) for value in self.hashes])\n\n def ror(self, value: int, rotations: int) -> int:\n \"\"\"\n Right rotate a given unsigned number by a certain amount of rotations\n \"\"\"\n return 0xFFFFFFFF & (value << (32 - rotations)) | (value >> rotations)\n\n\nclass SHA256HashTest(unittest.TestCase):\n \"\"\"\n Test class for the SHA256 class. Inherits the TestCase class from unittest\n \"\"\"\n\n def test_match_hashes(self) -> None:\n import hashlib\n\n msg = bytes(\"Test String\", \"utf-8\")\n assert SHA256(msg).hash == hashlib.sha256(msg).hexdigest()\n\n\ndef main() -> None:\n \"\"\"\n Provides option 'string' or 'file' to take input\n and prints the calculated SHA-256 hash\n \"\"\"\n\n # unittest.main()\n\n import doctest\n\n doctest.testmod()\n\n parser = argparse.ArgumentParser()\n parser.add_argument(\n \"-s\",\n \"--string\",\n dest=\"input_string\",\n default=\"Hello World!! Welcome to Cryptography\",\n help=\"Hash the string\",\n )\n parser.add_argument(\n \"-f\", \"--file\", dest=\"input_file\", help=\"Hash contents of a file\"\n )\n\n args = parser.parse_args()\n\n input_string = args.input_string\n\n # hash input should be a bytestring\n if args.input_file:\n with open(args.input_file, \"rb\") as f:\n hash_input = f.read()\n else:\n hash_input = bytes(input_string, \"utf-8\")\n\n print(SHA256(hash_input).hash)\n\n\nif __name__ == \"__main__\":\n main()\n"} +{"Prompt":"To get an insight into Greedy Algorithm through the Knapsack problem A shopkeeper has bags of wheat that each have different weights and different profits. eg. profit 5 8 7 1 12 3 4 weight 2 7 1 6 4 2 5 maxweight 100 Constraints: maxweight 0 profiti 0 weighti 0 Calculate the maximum profit that the shopkeeper can make given maxmum weight that can be carried. Function description is as follows :param profit: Take a list of profits :param weight: Take a list of weight if bags corresponding to the profits :param maxweight: Maximum weight that could be carried :return: Maximum expected gain calcprofit1, 2, 3, 3, 4, 5, 15 6 calcprofit10, 9 , 8, 3 ,4 , 5, 25 27 List created to store profit gained for the 1kg in case of each weight respectively. Calculate and append profitweight for each element. Creating a copy of the list and sorting profitweight in ascending order declaring useful variables loop till the total weight do not reach max limit e.g. 15 kg and till ilength flag value for encountered greatest element in sortedprofitbyweight Calculate the index of the biggestprofitbyweight in profitbyweight list. This will give the index of the first encountered element which is same as of biggestprofitbyweight. There may be one or more values same as that of biggestprofitbyweight but index always encounter the very first element only. To curb this alter the values in profitbyweight once they are used here it is done to 1 because neither profit nor weight can be in negative. check if the weight encountered is less than the total weight encountered before. Adding profit gained for the given weight 1 weightindexweightindex Since the weight encountered is greater than limit, therefore take the required number of remaining kgs and calculate profit for it. weight remaining weightindex Function Call","Completions":"# To get an insight into Greedy Algorithm through the Knapsack problem\n\n\n\"\"\"\nA shopkeeper has bags of wheat that each have different weights and different profits.\neg.\nprofit 5 8 7 1 12 3 4\nweight 2 7 1 6 4 2 5\nmax_weight 100\n\nConstraints:\nmax_weight > 0\nprofit[i] >= 0\nweight[i] >= 0\nCalculate the maximum profit that the shopkeeper can make given maxmum weight that can\nbe carried.\n\"\"\"\n\n\ndef calc_profit(profit: list, weight: list, max_weight: int) -> int:\n \"\"\"\n Function description is as follows-\n :param profit: Take a list of profits\n :param weight: Take a list of weight if bags corresponding to the profits\n :param max_weight: Maximum weight that could be carried\n :return: Maximum expected gain\n\n >>> calc_profit([1, 2, 3], [3, 4, 5], 15)\n 6\n >>> calc_profit([10, 9 , 8], [3 ,4 , 5], 25)\n 27\n \"\"\"\n if len(profit) != len(weight):\n raise ValueError(\"The length of profit and weight must be same.\")\n if max_weight <= 0:\n raise ValueError(\"max_weight must greater than zero.\")\n if any(p < 0 for p in profit):\n raise ValueError(\"Profit can not be negative.\")\n if any(w < 0 for w in weight):\n raise ValueError(\"Weight can not be negative.\")\n\n # List created to store profit gained for the 1kg in case of each weight\n # respectively. Calculate and append profit\/weight for each element.\n profit_by_weight = [p \/ w for p, w in zip(profit, weight)]\n\n # Creating a copy of the list and sorting profit\/weight in ascending order\n sorted_profit_by_weight = sorted(profit_by_weight)\n\n # declaring useful variables\n length = len(sorted_profit_by_weight)\n limit = 0\n gain = 0\n i = 0\n\n # loop till the total weight do not reach max limit e.g. 15 kg and till i= weight[index]:\n limit += weight[index]\n # Adding profit gained for the given weight 1 ===\n # weight[index]\/weight[index]\n gain += 1 * profit[index]\n else:\n # Since the weight encountered is greater than limit, therefore take the\n # required number of remaining kgs and calculate profit for it.\n # weight remaining \/ weight[index]\n gain += (max_weight - limit) \/ weight[index] * profit[index]\n break\n i += 1\n return gain\n\n\nif __name__ == \"__main__\":\n print(\n \"Input profits, weights, and then max_weight (all positive ints) separated by \"\n \"spaces.\"\n )\n\n profit = [int(x) for x in input(\"Input profits separated by spaces: \").split()]\n weight = [int(x) for x in input(\"Input weights separated by spaces: \").split()]\n max_weight = int(input(\"Max weight allowed: \"))\n\n # Function Call\n calc_profit(profit, weight, max_weight)\n"} +{"Prompt":"A naive recursive implementation of 01 Knapsack Problem https:en.wikipedia.orgwikiKnapsackproblem Returns the maximum value that can be put in a knapsack of a capacity cap, whereby each weight w has a specific value val. cap 50 val 60, 100, 120 w 10, 20, 30 c lenval knapsackcap, w, val, c 220 The result is 220 cause the values of 100 and 120 got the weight of 50 which is the limit of the capacity. Base Case If weight of the nth item is more than Knapsack of capacity, then this item cannot be included in the optimal solution, else return the maximum of two cases: 1 nth item included 2 not included","Completions":"from __future__ import annotations\n\n\ndef knapsack(capacity: int, weights: list[int], values: list[int], counter: int) -> int:\n \"\"\"\n Returns the maximum value that can be put in a knapsack of a capacity cap,\n whereby each weight w has a specific value val.\n\n >>> cap = 50\n >>> val = [60, 100, 120]\n >>> w = [10, 20, 30]\n >>> c = len(val)\n >>> knapsack(cap, w, val, c)\n 220\n\n The result is 220 cause the values of 100 and 120 got the weight of 50\n which is the limit of the capacity.\n \"\"\"\n\n # Base Case\n if counter == 0 or capacity == 0:\n return 0\n\n # If weight of the nth item is more than Knapsack of capacity,\n # then this item cannot be included in the optimal solution,\n # else return the maximum of two cases:\n # (1) nth item included\n # (2) not included\n if weights[counter - 1] > capacity:\n return knapsack(capacity, weights, values, counter - 1)\n else:\n left_capacity = capacity - weights[counter - 1]\n new_value_included = values[counter - 1] + knapsack(\n left_capacity, weights, values, counter - 1\n )\n without_new_value = knapsack(capacity, weights, values, counter - 1)\n return max(new_value_included, without_new_value)\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"To get an insight into naive recursive way to solve the Knapsack problem A shopkeeper has bags of wheat that each have different weights and different profits. eg. noofitems 4 profit 5 4 8 6 weight 1 2 4 5 maxweight 5 Constraints: maxweight 0 profiti 0 weighti 0 Calculate the maximum profit that the shopkeeper can make given maxmum weight that can be carried. Function description is as follows :param weights: Take a list of weights :param values: Take a list of profits corresponding to the weights :param numberofitems: number of items available to pick from :param maxweight: Maximum weight that could be carried :param index: the element we are looking at :return: Maximum expected gain knapsack1, 2, 4, 5, 5, 4, 8, 6, 4, 5, 0 13 knapsack3 ,4 , 5, 10, 9 , 8, 3, 25, 0 27","Completions":"# To get an insight into naive recursive way to solve the Knapsack problem\n\n\n\"\"\"\nA shopkeeper has bags of wheat that each have different weights and different profits.\neg.\nno_of_items 4\nprofit 5 4 8 6\nweight 1 2 4 5\nmax_weight 5\nConstraints:\nmax_weight > 0\nprofit[i] >= 0\nweight[i] >= 0\nCalculate the maximum profit that the shopkeeper can make given maxmum weight that can\nbe carried.\n\"\"\"\n\n\ndef knapsack(\n weights: list, values: list, number_of_items: int, max_weight: int, index: int\n) -> int:\n \"\"\"\n Function description is as follows-\n :param weights: Take a list of weights\n :param values: Take a list of profits corresponding to the weights\n :param number_of_items: number of items available to pick from\n :param max_weight: Maximum weight that could be carried\n :param index: the element we are looking at\n :return: Maximum expected gain\n >>> knapsack([1, 2, 4, 5], [5, 4, 8, 6], 4, 5, 0)\n 13\n >>> knapsack([3 ,4 , 5], [10, 9 , 8], 3, 25, 0)\n 27\n \"\"\"\n if index == number_of_items:\n return 0\n ans1 = 0\n ans2 = 0\n ans1 = knapsack(weights, values, number_of_items, max_weight, index + 1)\n if weights[index] <= max_weight:\n ans2 = values[index] + knapsack(\n weights, values, number_of_items, max_weight - weights[index], index + 1\n )\n return max(ans1, ans2)\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Test cases for knapsack kp.calcprofit takes the required argument profit, weight, maxweight and returns whether the answer matches to the expected ones Returns ValueError for any negative maxweight value :return: ValueError profit 10, 20, 30, 40, 50, 60 weight 2, 4, 6, 8, 10, 12 maxweight 15 Returns ValueError for any negative profit value in the list :return: ValueError profit 10, 20, 30, 40, 50, 60 weight 2, 4, 6, 8, 10, 12 maxweight 15 Returns ValueError for any negative weight value in the list :return: ValueError profit 10, 20, 30, 40, 50, 60 weight 2, 4, 6, 8, 10, 12 maxweight 15 Returns ValueError for any zero maxweight value :return: ValueError profit 10, 20, 30, 40, 50, 60 weight 2, 4, 6, 8, 10, 12 maxweight null Returns IndexError if length of lists profit and weight are unequal. :return: IndexError profit 10, 20, 30, 40, 50 weight 2, 4, 6, 8, 10, 12 maxweight 100","Completions":"import unittest\n\nimport pytest\n\nfrom knapsack import greedy_knapsack as kp\n\n\nclass TestClass(unittest.TestCase):\n \"\"\"\n Test cases for knapsack\n \"\"\"\n\n def test_sorted(self):\n \"\"\"\n kp.calc_profit takes the required argument (profit, weight, max_weight)\n and returns whether the answer matches to the expected ones\n \"\"\"\n profit = [10, 20, 30, 40, 50, 60]\n weight = [2, 4, 6, 8, 10, 12]\n max_weight = 100\n assert kp.calc_profit(profit, weight, max_weight) == 210\n\n def test_negative_max_weight(self):\n \"\"\"\n Returns ValueError for any negative max_weight value\n :return: ValueError\n \"\"\"\n # profit = [10, 20, 30, 40, 50, 60]\n # weight = [2, 4, 6, 8, 10, 12]\n # max_weight = -15\n pytest.raises(ValueError, match=\"max_weight must greater than zero.\")\n\n def test_negative_profit_value(self):\n \"\"\"\n Returns ValueError for any negative profit value in the list\n :return: ValueError\n \"\"\"\n # profit = [10, -20, 30, 40, 50, 60]\n # weight = [2, 4, 6, 8, 10, 12]\n # max_weight = 15\n pytest.raises(ValueError, match=\"Weight can not be negative.\")\n\n def test_negative_weight_value(self):\n \"\"\"\n Returns ValueError for any negative weight value in the list\n :return: ValueError\n \"\"\"\n # profit = [10, 20, 30, 40, 50, 60]\n # weight = [2, -4, 6, -8, 10, 12]\n # max_weight = 15\n pytest.raises(ValueError, match=\"Profit can not be negative.\")\n\n def test_null_max_weight(self):\n \"\"\"\n Returns ValueError for any zero max_weight value\n :return: ValueError\n \"\"\"\n # profit = [10, 20, 30, 40, 50, 60]\n # weight = [2, 4, 6, 8, 10, 12]\n # max_weight = null\n pytest.raises(ValueError, match=\"max_weight must greater than zero.\")\n\n def test_unequal_list_length(self):\n \"\"\"\n Returns IndexError if length of lists (profit and weight) are unequal.\n :return: IndexError\n \"\"\"\n # profit = [10, 20, 30, 40, 50]\n # weight = [2, 4, 6, 8, 10, 12]\n # max_weight = 100\n pytest.raises(IndexError, match=\"The length of profit and weight must be same.\")\n\n\nif __name__ == \"__main__\":\n unittest.main()\n"} +{"Prompt":"Created on Fri Oct 16 09:31:07 2020 author: Dr. Tobias Schrder license: MITlicense This file contains the testsuite for the knapsack problem. test for the base case test for the base case test for the knapsack","Completions":"import unittest\n\nfrom knapsack import knapsack as k\n\n\nclass Test(unittest.TestCase):\n def test_base_case(self):\n \"\"\"\n test for the base case\n \"\"\"\n cap = 0\n val = [0]\n w = [0]\n c = len(val)\n assert k.knapsack(cap, w, val, c) == 0\n\n val = [60]\n w = [10]\n c = len(val)\n assert k.knapsack(cap, w, val, c) == 0\n\n def test_easy_case(self):\n \"\"\"\n test for the base case\n \"\"\"\n cap = 3\n val = [1, 2, 3]\n w = [3, 2, 1]\n c = len(val)\n assert k.knapsack(cap, w, val, c) == 5\n\n def test_knapsack(self):\n \"\"\"\n test for the knapsack\n \"\"\"\n cap = 50\n val = [60, 100, 120]\n w = [10, 20, 30]\n c = len(val)\n assert k.knapsack(cap, w, val, c) == 220\n\n\nif __name__ == \"__main__\":\n unittest.main()\n"} +{"Prompt":"Gaussian elimination method for solving a system of linear equations. Gaussian elimination https:en.wikipedia.orgwikiGaussianelimination This function performs a retroactive linear system resolution for triangular matrix Examples: 2x1 2x2 1x3 5 2x1 2x2 1 0x1 2x2 1x3 7 0x1 2x2 1 0x1 0x2 5x3 15 gaussianelimination2, 2, 1, 0, 2, 1, 0, 0, 5, 5, 7, 15 array2., 2., 3. gaussianelimination2, 2, 0, 2, 1, 1 array1. , 0.5 This function performs Gaussian elimination method Examples: 1x1 4x2 2x3 2 1x1 2x2 5 5x1 2x2 2x3 3 5x1 2x2 5 1x1 1x2 0x3 4 gaussianelimination1, 4, 2, 5, 2, 2, 1, 1, 0, 2, 3, 4 array 2.3 , 1.7 , 5.55 gaussianelimination1, 2, 5, 2, 5, 5 array0. , 2.5 coefficients must to be a square matrix so we need to check first augmented matrix scale the matrix leaving it triangular","Completions":"import numpy as np\nfrom numpy import float64\nfrom numpy.typing import NDArray\n\n\ndef retroactive_resolution(\n coefficients: NDArray[float64], vector: NDArray[float64]\n) -> NDArray[float64]:\n \"\"\"\n This function performs a retroactive linear system resolution\n for triangular matrix\n\n Examples:\n 2x1 + 2x2 - 1x3 = 5 2x1 + 2x2 = -1\n 0x1 - 2x2 - 1x3 = -7 0x1 - 2x2 = -1\n 0x1 + 0x2 + 5x3 = 15\n >>> gaussian_elimination([[2, 2, -1], [0, -2, -1], [0, 0, 5]], [[5], [-7], [15]])\n array([[2.],\n [2.],\n [3.]])\n >>> gaussian_elimination([[2, 2], [0, -2]], [[-1], [-1]])\n array([[-1. ],\n [ 0.5]])\n \"\"\"\n\n rows, columns = np.shape(coefficients)\n\n x: NDArray[float64] = np.zeros((rows, 1), dtype=float)\n for row in reversed(range(rows)):\n total = np.dot(coefficients[row, row + 1 :], x[row + 1 :])\n x[row, 0] = (vector[row][0] - total[0]) \/ coefficients[row, row]\n\n return x\n\n\ndef gaussian_elimination(\n coefficients: NDArray[float64], vector: NDArray[float64]\n) -> NDArray[float64]:\n \"\"\"\n This function performs Gaussian elimination method\n\n Examples:\n 1x1 - 4x2 - 2x3 = -2 1x1 + 2x2 = 5\n 5x1 + 2x2 - 2x3 = -3 5x1 + 2x2 = 5\n 1x1 - 1x2 + 0x3 = 4\n >>> gaussian_elimination([[1, -4, -2], [5, 2, -2], [1, -1, 0]], [[-2], [-3], [4]])\n array([[ 2.3 ],\n [-1.7 ],\n [ 5.55]])\n >>> gaussian_elimination([[1, 2], [5, 2]], [[5], [5]])\n array([[0. ],\n [2.5]])\n \"\"\"\n # coefficients must to be a square matrix so we need to check first\n rows, columns = np.shape(coefficients)\n if rows != columns:\n return np.array((), dtype=float)\n\n # augmented matrix\n augmented_mat: NDArray[float64] = np.concatenate((coefficients, vector), axis=1)\n augmented_mat = augmented_mat.astype(\"float64\")\n\n # scale the matrix leaving it triangular\n for row in range(rows - 1):\n pivot = augmented_mat[row, row]\n for col in range(row + 1, columns):\n factor = augmented_mat[col, row] \/ pivot\n augmented_mat[col, :] -= factor * augmented_mat[row, :]\n\n x = retroactive_resolution(\n augmented_mat[:, 0:columns], augmented_mat[:, columns : columns + 1]\n )\n\n return x\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Jacobi Iteration Method https:en.wikipedia.orgwikiJacobimethod Method to find solution of system of linear equations Jacobi Iteration Method: An iterative algorithm to determine the solutions of strictly diagonally dominant system of linear equations 4x1 x2 x3 2 x1 5x2 2x3 6 x1 2x2 4x3 4 xinit 0.5, 0.5 , 0.5 Examples: coefficient np.array4, 1, 1, 1, 5, 2, 1, 2, 4 constant np.array2, 6, 4 initval 0.5, 0.5, 0.5 iterations 3 jacobiiterationmethodcoefficient, constant, initval, iterations 0.909375, 1.14375, 0.7484375 coefficient np.array4, 1, 1, 1, 5, 2 constant np.array2, 6, 4 initval 0.5, 0.5, 0.5 iterations 3 jacobiiterationmethodcoefficient, constant, initval, iterations Traceback most recent call last: ... ValueError: Coefficient matrix dimensions must be nxn but received 2x3 coefficient np.array4, 1, 1, 1, 5, 2, 1, 2, 4 constant np.array2, 6 initval 0.5, 0.5, 0.5 iterations 3 jacobiiterationmethod ... coefficient, constant, initval, iterations ... doctest: NORMALIZEWHITESPACE Traceback most recent call last: ... ValueError: Coefficient and constant matrices dimensions must be nxn and nx1 but received 3x3 and 2x1 coefficient np.array4, 1, 1, 1, 5, 2, 1, 2, 4 constant np.array2, 6, 4 initval 0.5, 0.5 iterations 3 jacobiiterationmethod ... coefficient, constant, initval, iterations ... doctest: NORMALIZEWHITESPACE Traceback most recent call last: ... ValueError: Number of initial values must be equal to number of rows in coefficient matrix but received 2 and 3 coefficient np.array4, 1, 1, 1, 5, 2, 1, 2, 4 constant np.array2, 6, 4 initval 0.5, 0.5, 0.5 iterations 0 jacobiiterationmethodcoefficient, constant, initval, iterations Traceback most recent call last: ... ValueError: Iterations must be at least 1 Iterates the whole matrix for given number of times for in rangeiterations: newval for row in rangerows: temp 0 for col in rangecols: if col row: denom tablerowcol elif col cols 1: val tablerowcol else: temp 1 tablerowcol initvalcol temp temp val denom newval.appendtemp initval newval denominator a list of values along the diagonal vallast values of the last column of the table array masks boolean mask of all strings without diagonal elements array coefficientmatrix nodiagonals coefficientmatrix array values without diagonal elements Here we get 'icol' these are the column numbers, for each row without diagonal elements, except for the last column. 'icol' is converted to a twodimensional list 'ind', which will be used to make selections from 'initval' 'arr' array see below. Iterates the whole matrix for given number of times Checks if the given matrix is strictly diagonally dominant table np.array4, 1, 1, 2, 1, 5, 2, 6, 1, 2, 4, 4 strictlydiagonallydominanttable True table np.array4, 1, 1, 2, 1, 5, 2, 6, 1, 2, 3, 4 strictlydiagonallydominanttable Traceback most recent call last: ... ValueError: Coefficient matrix is not strictly diagonally dominant Test Cases","Completions":"from __future__ import annotations\n\nimport numpy as np\nfrom numpy import float64\nfrom numpy.typing import NDArray\n\n\n# Method to find solution of system of linear equations\ndef jacobi_iteration_method(\n coefficient_matrix: NDArray[float64],\n constant_matrix: NDArray[float64],\n init_val: list[float],\n iterations: int,\n) -> list[float]:\n \"\"\"\n Jacobi Iteration Method:\n An iterative algorithm to determine the solutions of strictly diagonally dominant\n system of linear equations\n\n 4x1 + x2 + x3 = 2\n x1 + 5x2 + 2x3 = -6\n x1 + 2x2 + 4x3 = -4\n\n x_init = [0.5, -0.5 , -0.5]\n\n Examples:\n\n >>> coefficient = np.array([[4, 1, 1], [1, 5, 2], [1, 2, 4]])\n >>> constant = np.array([[2], [-6], [-4]])\n >>> init_val = [0.5, -0.5, -0.5]\n >>> iterations = 3\n >>> jacobi_iteration_method(coefficient, constant, init_val, iterations)\n [0.909375, -1.14375, -0.7484375]\n\n\n >>> coefficient = np.array([[4, 1, 1], [1, 5, 2]])\n >>> constant = np.array([[2], [-6], [-4]])\n >>> init_val = [0.5, -0.5, -0.5]\n >>> iterations = 3\n >>> jacobi_iteration_method(coefficient, constant, init_val, iterations)\n Traceback (most recent call last):\n ...\n ValueError: Coefficient matrix dimensions must be nxn but received 2x3\n\n >>> coefficient = np.array([[4, 1, 1], [1, 5, 2], [1, 2, 4]])\n >>> constant = np.array([[2], [-6]])\n >>> init_val = [0.5, -0.5, -0.5]\n >>> iterations = 3\n >>> jacobi_iteration_method(\n ... coefficient, constant, init_val, iterations\n ... ) # doctest: +NORMALIZE_WHITESPACE\n Traceback (most recent call last):\n ...\n ValueError: Coefficient and constant matrices dimensions must be nxn and nx1 but\n received 3x3 and 2x1\n\n >>> coefficient = np.array([[4, 1, 1], [1, 5, 2], [1, 2, 4]])\n >>> constant = np.array([[2], [-6], [-4]])\n >>> init_val = [0.5, -0.5]\n >>> iterations = 3\n >>> jacobi_iteration_method(\n ... coefficient, constant, init_val, iterations\n ... ) # doctest: +NORMALIZE_WHITESPACE\n Traceback (most recent call last):\n ...\n ValueError: Number of initial values must be equal to number of rows in coefficient\n matrix but received 2 and 3\n\n >>> coefficient = np.array([[4, 1, 1], [1, 5, 2], [1, 2, 4]])\n >>> constant = np.array([[2], [-6], [-4]])\n >>> init_val = [0.5, -0.5, -0.5]\n >>> iterations = 0\n >>> jacobi_iteration_method(coefficient, constant, init_val, iterations)\n Traceback (most recent call last):\n ...\n ValueError: Iterations must be at least 1\n \"\"\"\n\n rows1, cols1 = coefficient_matrix.shape\n rows2, cols2 = constant_matrix.shape\n\n if rows1 != cols1:\n msg = f\"Coefficient matrix dimensions must be nxn but received {rows1}x{cols1}\"\n raise ValueError(msg)\n\n if cols2 != 1:\n msg = f\"Constant matrix must be nx1 but received {rows2}x{cols2}\"\n raise ValueError(msg)\n\n if rows1 != rows2:\n msg = (\n \"Coefficient and constant matrices dimensions must be nxn and nx1 but \"\n f\"received {rows1}x{cols1} and {rows2}x{cols2}\"\n )\n raise ValueError(msg)\n\n if len(init_val) != rows1:\n msg = (\n \"Number of initial values must be equal to number of rows in coefficient \"\n f\"matrix but received {len(init_val)} and {rows1}\"\n )\n raise ValueError(msg)\n\n if iterations <= 0:\n raise ValueError(\"Iterations must be at least 1\")\n\n table: NDArray[float64] = np.concatenate(\n (coefficient_matrix, constant_matrix), axis=1\n )\n\n rows, cols = table.shape\n\n strictly_diagonally_dominant(table)\n\n \"\"\"\n # Iterates the whole matrix for given number of times\n for _ in range(iterations):\n new_val = []\n for row in range(rows):\n temp = 0\n for col in range(cols):\n if col == row:\n denom = table[row][col]\n elif col == cols - 1:\n val = table[row][col]\n else:\n temp += (-1) * table[row][col] * init_val[col]\n temp = (temp + val) \/ denom\n new_val.append(temp)\n init_val = new_val\n \"\"\"\n\n # denominator - a list of values along the diagonal\n denominator = np.diag(coefficient_matrix)\n\n # val_last - values of the last column of the table array\n val_last = table[:, -1]\n\n # masks - boolean mask of all strings without diagonal\n # elements array coefficient_matrix\n masks = ~np.eye(coefficient_matrix.shape[0], dtype=bool)\n\n # no_diagonals - coefficient_matrix array values without diagonal elements\n no_diagonals = coefficient_matrix[masks].reshape(-1, rows - 1)\n\n # Here we get 'i_col' - these are the column numbers, for each row\n # without diagonal elements, except for the last column.\n i_row, i_col = np.where(masks)\n ind = i_col.reshape(-1, rows - 1)\n\n #'i_col' is converted to a two-dimensional list 'ind', which will be\n # used to make selections from 'init_val' ('arr' array see below).\n\n # Iterates the whole matrix for given number of times\n for _ in range(iterations):\n arr = np.take(init_val, ind)\n sum_product_rows = np.sum((-1) * no_diagonals * arr, axis=1)\n new_val = (sum_product_rows + val_last) \/ denominator\n init_val = new_val\n\n return new_val.tolist()\n\n\n# Checks if the given matrix is strictly diagonally dominant\ndef strictly_diagonally_dominant(table: NDArray[float64]) -> bool:\n \"\"\"\n >>> table = np.array([[4, 1, 1, 2], [1, 5, 2, -6], [1, 2, 4, -4]])\n >>> strictly_diagonally_dominant(table)\n True\n\n >>> table = np.array([[4, 1, 1, 2], [1, 5, 2, -6], [1, 2, 3, -4]])\n >>> strictly_diagonally_dominant(table)\n Traceback (most recent call last):\n ...\n ValueError: Coefficient matrix is not strictly diagonally dominant\n \"\"\"\n\n rows, cols = table.shape\n\n is_diagonally_dominant = True\n\n for i in range(rows):\n total = 0\n for j in range(cols - 1):\n if i == j:\n continue\n else:\n total += table[i][j]\n\n if table[i][i] <= total:\n raise ValueError(\"Coefficient matrix is not strictly diagonally dominant\")\n\n return is_diagonally_dominant\n\n\n# Test Cases\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Lowerupper LU decomposition factors a matrix as a product of a lower triangular matrix and an upper triangular matrix. A square matrix has an LU decomposition under the following conditions: If the matrix is invertible, then it has an LU decomposition if and only if all of its leading principal minors are nonzero see https:en.wikipedia.orgwikiMinorlinearalgebra for an explanation of leading principal minors of a matrix. If the matrix is singular i.e., not invertible and it has a rank of k i.e., it has k linearly independent columns, then it has an LU decomposition if its first k leading principal minors are nonzero. This algorithm will simply attempt to perform LU decomposition on any square matrix and raise an error if no such decomposition exists. Reference: https:en.wikipedia.orgwikiLUdecomposition Perform LU decomposition on a given matrix and raises an error if the matrix isn't square or if no such decomposition exists matrix np.array2, 2, 1, 0, 1, 2, 5, 3, 1 lowermat, uppermat lowerupperdecompositionmatrix lowermat array1. , 0. , 0. , 0. , 1. , 0. , 2.5, 8. , 1. uppermat array 2. , 2. , 1. , 0. , 1. , 2. , 0. , 0. , 17.5 matrix np.array4, 3, 6, 3 lowermat, uppermat lowerupperdecompositionmatrix lowermat array1. , 0. , 1.5, 1. uppermat array 4. , 3. , 0. , 1.5 Matrix is not square matrix np.array2, 2, 1, 0, 1, 2 lowermat, uppermat lowerupperdecompositionmatrix Traceback most recent call last: ... ValueError: 'table' has to be of square shaped array but got a 2x3 array: 2 2 1 0 1 2 Matrix is invertible, but its first leading principal minor is 0 matrix np.array0, 1, 1, 0 lowermat, uppermat lowerupperdecompositionmatrix Traceback most recent call last: ... ArithmeticError: No LU decomposition exists Matrix is singular, but its first leading principal minor is 1 matrix np.array1, 0, 1, 0 lowermat, uppermat lowerupperdecompositionmatrix lowermat array1., 0., 1., 1. uppermat array1., 0., 0., 0. Matrix is singular, but its first leading principal minor is 0 matrix np.array0, 1, 0, 1 lowermat, uppermat lowerupperdecompositionmatrix Traceback most recent call last: ... ArithmeticError: No LU decomposition exists Ensure that table is a square array in 'total', the necessary data is extracted through slices and the sum of the products is obtained.","Completions":"from __future__ import annotations\n\nimport numpy as np\n\n\ndef lower_upper_decomposition(table: np.ndarray) -> tuple[np.ndarray, np.ndarray]:\n \"\"\"\n Perform LU decomposition on a given matrix and raises an error if the matrix\n isn't square or if no such decomposition exists\n >>> matrix = np.array([[2, -2, 1], [0, 1, 2], [5, 3, 1]])\n >>> lower_mat, upper_mat = lower_upper_decomposition(matrix)\n >>> lower_mat\n array([[1. , 0. , 0. ],\n [0. , 1. , 0. ],\n [2.5, 8. , 1. ]])\n >>> upper_mat\n array([[ 2. , -2. , 1. ],\n [ 0. , 1. , 2. ],\n [ 0. , 0. , -17.5]])\n\n >>> matrix = np.array([[4, 3], [6, 3]])\n >>> lower_mat, upper_mat = lower_upper_decomposition(matrix)\n >>> lower_mat\n array([[1. , 0. ],\n [1.5, 1. ]])\n >>> upper_mat\n array([[ 4. , 3. ],\n [ 0. , -1.5]])\n\n # Matrix is not square\n >>> matrix = np.array([[2, -2, 1], [0, 1, 2]])\n >>> lower_mat, upper_mat = lower_upper_decomposition(matrix)\n Traceback (most recent call last):\n ...\n ValueError: 'table' has to be of square shaped array but got a 2x3 array:\n [[ 2 -2 1]\n [ 0 1 2]]\n\n # Matrix is invertible, but its first leading principal minor is 0\n >>> matrix = np.array([[0, 1], [1, 0]])\n >>> lower_mat, upper_mat = lower_upper_decomposition(matrix)\n Traceback (most recent call last):\n ...\n ArithmeticError: No LU decomposition exists\n\n # Matrix is singular, but its first leading principal minor is 1\n >>> matrix = np.array([[1, 0], [1, 0]])\n >>> lower_mat, upper_mat = lower_upper_decomposition(matrix)\n >>> lower_mat\n array([[1., 0.],\n [1., 1.]])\n >>> upper_mat\n array([[1., 0.],\n [0., 0.]])\n\n # Matrix is singular, but its first leading principal minor is 0\n >>> matrix = np.array([[0, 1], [0, 1]])\n >>> lower_mat, upper_mat = lower_upper_decomposition(matrix)\n Traceback (most recent call last):\n ...\n ArithmeticError: No LU decomposition exists\n \"\"\"\n # Ensure that table is a square array\n rows, columns = np.shape(table)\n if rows != columns:\n msg = (\n \"'table' has to be of square shaped array but got a \"\n f\"{rows}x{columns} array:\\n{table}\"\n )\n raise ValueError(msg)\n\n lower = np.zeros((rows, columns))\n upper = np.zeros((rows, columns))\n\n # in 'total', the necessary data is extracted through slices\n # and the sum of the products is obtained.\n\n for i in range(columns):\n for j in range(i):\n total = np.sum(lower[i, :i] * upper[:i, j])\n if upper[j][j] == 0:\n raise ArithmeticError(\"No LU decomposition exists\")\n lower[i][j] = (table[i][j] - total) \/ upper[j][j]\n lower[i][i] = 1\n for j in range(i, columns):\n total = np.sum(lower[i, :i] * upper[:i, j])\n upper[i][j] = table[i][j] - total\n return lower, upper\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Resources: https:en.wikipedia.orgwikiConjugategradientmethod https:en.wikipedia.orgwikiDefinitesymmetricmatrix Returns True if input matrix is symmetric positive definite. Returns False otherwise. For a matrix to be SPD, all eigenvalues must be positive. import numpy as np matrix np.array ... 4.12401784, 5.01453636, 0.63865857, ... 5.01453636, 12.33347422, 3.40493586, ... 0.63865857, 3.40493586, 5.78591885 ismatrixspdmatrix True matrix np.array ... 0.34634879, 1.96165514, 2.18277744, ... 0.74074469, 1.19648894, 1.34223498, ... 0.7687067 , 0.06018373, 1.16315631 ismatrixspdmatrix False Ensure matrix is square. If matrix not symmetric, exit right away. Get eigenvalues and eignevectors for a symmetric matrix. Check sign of all eigenvalues. np.all returns a value of type np.bool Returns a symmetric positive definite matrix given a dimension. Input: dimension gives the square matrix dimension. Output: spdmatrix is an diminesion x dimensions symmetric positive definite SPD matrix. import numpy as np dimension 3 spdmatrix createspdmatrixdimension ismatrixspdspdmatrix True Returns solution to the linear system np.dotspdmatrix, x b. Input: spdmatrix is an NxN Symmetric Positive Definite SPD matrix. loadvector is an Nx1 vector. Output: x is an Nx1 vector that is the solution vector. import numpy as np spdmatrix np.array ... 8.73256573, 5.02034289, 2.68709226, ... 5.02034289, 3.78188322, 0.91980451, ... 2.68709226, 0.91980451, 1.94746467 b np.array ... 5.80872761, ... 3.23807431, ... 1.95381422 conjugategradientspdmatrix, b array0.63114139, 0.01561498, 0.13979294 Ensure proper dimensionality. Initialize solution guess, residual, search direction. Set initial errors in solution guess and residual. Set iteration counter to threshold number of iterations. Save this value so we only calculate the matrixvector product once. The main algorithm. Update search direction magnitude. Update solution guess. Calculate new residual. Calculate new Krylov subspace scale. Calculate new A conjuage search direction. Calculate errors. Update variables. Update number of iterations. testconjugategradient self running tests Create linear system with SPD matrix and known solution xtrue. Numpy solution. Our implementation. Ensure both solutions are close to xtrue and therefore one another.","Completions":"from typing import Any\n\nimport numpy as np\n\n\ndef _is_matrix_spd(matrix: np.ndarray) -> bool:\n \"\"\"\n Returns True if input matrix is symmetric positive definite.\n Returns False otherwise.\n\n For a matrix to be SPD, all eigenvalues must be positive.\n\n >>> import numpy as np\n >>> matrix = np.array([\n ... [4.12401784, -5.01453636, -0.63865857],\n ... [-5.01453636, 12.33347422, -3.40493586],\n ... [-0.63865857, -3.40493586, 5.78591885]])\n >>> _is_matrix_spd(matrix)\n True\n >>> matrix = np.array([\n ... [0.34634879, 1.96165514, 2.18277744],\n ... [0.74074469, -1.19648894, -1.34223498],\n ... [-0.7687067 , 0.06018373, -1.16315631]])\n >>> _is_matrix_spd(matrix)\n False\n \"\"\"\n # Ensure matrix is square.\n assert np.shape(matrix)[0] == np.shape(matrix)[1]\n\n # If matrix not symmetric, exit right away.\n if np.allclose(matrix, matrix.T) is False:\n return False\n\n # Get eigenvalues and eignevectors for a symmetric matrix.\n eigen_values, _ = np.linalg.eigh(matrix)\n\n # Check sign of all eigenvalues.\n # np.all returns a value of type np.bool_\n return bool(np.all(eigen_values > 0))\n\n\ndef _create_spd_matrix(dimension: int) -> Any:\n \"\"\"\n Returns a symmetric positive definite matrix given a dimension.\n\n Input:\n dimension gives the square matrix dimension.\n\n Output:\n spd_matrix is an diminesion x dimensions symmetric positive definite (SPD) matrix.\n\n >>> import numpy as np\n >>> dimension = 3\n >>> spd_matrix = _create_spd_matrix(dimension)\n >>> _is_matrix_spd(spd_matrix)\n True\n \"\"\"\n random_matrix = np.random.randn(dimension, dimension)\n spd_matrix = np.dot(random_matrix, random_matrix.T)\n assert _is_matrix_spd(spd_matrix)\n return spd_matrix\n\n\ndef conjugate_gradient(\n spd_matrix: np.ndarray,\n load_vector: np.ndarray,\n max_iterations: int = 1000,\n tol: float = 1e-8,\n) -> Any:\n \"\"\"\n Returns solution to the linear system np.dot(spd_matrix, x) = b.\n\n Input:\n spd_matrix is an NxN Symmetric Positive Definite (SPD) matrix.\n load_vector is an Nx1 vector.\n\n Output:\n x is an Nx1 vector that is the solution vector.\n\n >>> import numpy as np\n >>> spd_matrix = np.array([\n ... [8.73256573, -5.02034289, -2.68709226],\n ... [-5.02034289, 3.78188322, 0.91980451],\n ... [-2.68709226, 0.91980451, 1.94746467]])\n >>> b = np.array([\n ... [-5.80872761],\n ... [ 3.23807431],\n ... [ 1.95381422]])\n >>> conjugate_gradient(spd_matrix, b)\n array([[-0.63114139],\n [-0.01561498],\n [ 0.13979294]])\n \"\"\"\n # Ensure proper dimensionality.\n assert np.shape(spd_matrix)[0] == np.shape(spd_matrix)[1]\n assert np.shape(load_vector)[0] == np.shape(spd_matrix)[0]\n assert _is_matrix_spd(spd_matrix)\n\n # Initialize solution guess, residual, search direction.\n x0 = np.zeros((np.shape(load_vector)[0], 1))\n r0 = np.copy(load_vector)\n p0 = np.copy(r0)\n\n # Set initial errors in solution guess and residual.\n error_residual = 1e9\n error_x_solution = 1e9\n error = 1e9\n\n # Set iteration counter to threshold number of iterations.\n iterations = 0\n\n while error > tol:\n # Save this value so we only calculate the matrix-vector product once.\n w = np.dot(spd_matrix, p0)\n\n # The main algorithm.\n\n # Update search direction magnitude.\n alpha = np.dot(r0.T, r0) \/ np.dot(p0.T, w)\n # Update solution guess.\n x = x0 + alpha * p0\n # Calculate new residual.\n r = r0 - alpha * w\n # Calculate new Krylov subspace scale.\n beta = np.dot(r.T, r) \/ np.dot(r0.T, r0)\n # Calculate new A conjuage search direction.\n p = r + beta * p0\n\n # Calculate errors.\n error_residual = np.linalg.norm(r - r0)\n error_x_solution = np.linalg.norm(x - x0)\n error = np.maximum(error_residual, error_x_solution)\n\n # Update variables.\n x0 = np.copy(x)\n r0 = np.copy(r)\n p0 = np.copy(p)\n\n # Update number of iterations.\n iterations += 1\n if iterations > max_iterations:\n break\n\n return x\n\n\ndef test_conjugate_gradient() -> None:\n \"\"\"\n >>> test_conjugate_gradient() # self running tests\n \"\"\"\n # Create linear system with SPD matrix and known solution x_true.\n dimension = 3\n spd_matrix = _create_spd_matrix(dimension)\n x_true = np.random.randn(dimension, 1)\n b = np.dot(spd_matrix, x_true)\n\n # Numpy solution.\n x_numpy = np.linalg.solve(spd_matrix, b)\n\n # Our implementation.\n x_conjugate_gradient = conjugate_gradient(spd_matrix, b)\n\n # Ensure both solutions are close to x_true (and therefore one another).\n assert np.linalg.norm(x_numpy - x_true) <= 1e-6\n assert np.linalg.norm(x_conjugate_gradient - x_true) <= 1e-6\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n test_conjugate_gradient()\n"} +{"Prompt":"Solve a linear system of equations using Gaussian elimination with partial pivoting Args: matrix: Coefficient matrix with the last column representing the constants. Returns: Solution vector. Raises: ValueError: If the matrix is not correct i.e., singular. https:courses.engr.illinois.educs357su2013lect.htm Lecture 7 Example: A np.array2, 1, 1, 3, 1, 2, 2, 1, 2, dtypefloat B np.array8, 11, 3, dtypefloat solution solvelinearsystemnp.columnstackA, B np.allclosesolution, np.array2., 3., 1. True solvelinearsystemnp.array0, 0, 0, 0, dtypefloat arraynan, nan Lead element search Upper triangular matrix Find x vector Back Substitution Return the solution vector Example usage:","Completions":"import numpy as np\n\nmatrix = np.array(\n [\n [5.0, -5.0, -3.0, 4.0, -11.0],\n [1.0, -4.0, 6.0, -4.0, -10.0],\n [-2.0, -5.0, 4.0, -5.0, -12.0],\n [-3.0, -3.0, 5.0, -5.0, 8.0],\n ],\n dtype=float,\n)\n\n\ndef solve_linear_system(matrix: np.ndarray) -> np.ndarray:\n \"\"\"\n Solve a linear system of equations using Gaussian elimination with partial pivoting\n\n Args:\n - matrix: Coefficient matrix with the last column representing the constants.\n\n Returns:\n - Solution vector.\n\n Raises:\n - ValueError: If the matrix is not correct (i.e., singular).\n\n https:\/\/courses.engr.illinois.edu\/cs357\/su2013\/lect.htm Lecture 7\n\n Example:\n >>> A = np.array([[2, 1, -1], [-3, -1, 2], [-2, 1, 2]], dtype=float)\n >>> B = np.array([8, -11, -3], dtype=float)\n >>> solution = solve_linear_system(np.column_stack((A, B)))\n >>> np.allclose(solution, np.array([2., 3., -1.]))\n True\n >>> solve_linear_system(np.array([[0, 0], [0, 0]], dtype=float))\n array([nan, nan])\n \"\"\"\n ab = np.copy(matrix)\n num_of_rows = ab.shape[0]\n num_of_columns = ab.shape[1] - 1\n x_lst: list[float] = []\n\n # Lead element search\n for column_num in range(num_of_rows):\n for i in range(column_num, num_of_columns):\n if abs(ab[i][column_num]) > abs(ab[column_num][column_num]):\n ab[[column_num, i]] = ab[[i, column_num]]\n if ab[column_num, column_num] == 0.0:\n raise ValueError(\"Matrix is not correct\")\n else:\n pass\n if column_num != 0:\n for i in range(column_num, num_of_rows):\n ab[i, :] -= (\n ab[i, column_num - 1]\n \/ ab[column_num - 1, column_num - 1]\n * ab[column_num - 1, :]\n )\n\n # Upper triangular matrix\n for column_num in range(num_of_rows):\n for i in range(column_num, num_of_columns):\n if abs(ab[i][column_num]) > abs(ab[column_num][column_num]):\n ab[[column_num, i]] = ab[[i, column_num]]\n if ab[column_num, column_num] == 0.0:\n raise ValueError(\"Matrix is not correct\")\n else:\n pass\n if column_num != 0:\n for i in range(column_num, num_of_rows):\n ab[i, :] -= (\n ab[i, column_num - 1]\n \/ ab[column_num - 1, column_num - 1]\n * ab[column_num - 1, :]\n )\n\n # Find x vector (Back Substitution)\n for column_num in range(num_of_rows - 1, -1, -1):\n x = ab[column_num, -1] \/ ab[column_num, column_num]\n x_lst.insert(0, x)\n for i in range(column_num - 1, -1, -1):\n ab[i, -1] -= ab[i, column_num] * x\n\n # Return the solution vector\n return np.asarray(x_lst)\n\n\nif __name__ == \"__main__\":\n from doctest import testmod\n from pathlib import Path\n\n testmod()\n file_path = Path(__file__).parent \/ \"matrix.txt\"\n try:\n matrix = np.loadtxt(file_path)\n except FileNotFoundError:\n print(f\"Error: {file_path} not found. Using default matrix instead.\")\n\n # Example usage:\n print(f\"Matrix:\\n{matrix}\")\n print(f\"{solve_linear_system(matrix) = }\")\n"} +{"Prompt":"Created on Mon Feb 26 14:29:11 2018 author: Christian Bender license: MITlicense This module contains some useful classes and functions for dealing with linear algebra in python. Overview: class Vector function zerovectordimension function unitbasisvectordimension, pos function axpyscalar, vector1, vector2 function randomvectorN, a, b class Matrix function squarezeromatrixN function randommatrixW, H, a, b This class represents a vector of arbitrary size. You need to give the vector components. Overview of the methods: initcomponents: Collectionfloat None: init the vector len: gets the size of the vector number of components str: returns a string representation addother: Vector: vector addition subother: Vector: vector subtraction mulother: float: scalar multiplication mulother: Vector: dot product copy: copies this vector and returns it componenti: gets the ith component 0indexed changecomponentpos: int, value: float: changes specified component euclideanlength: returns the euclidean length of the vector angleother: Vector, deg: bool: returns the angle between two vectors TODO: compareoperator input: components or nothing simple constructor for init the vector returns the size of the vector returns a string representation of the vector input: other vector assumes: other vector has the same size returns a new vector that represents the sum. input: other vector assumes: other vector has the same size returns a new vector that represents the difference. mul implements the scalar multiplication and the dotproduct copies this vector and returns it. input: index 0indexed output: the ith component of the vector. input: an index pos and a value changes the specified component pos with the 'value' precondition returns the euclidean length of the vector Vector2, 3, 4.euclideanlength 5.385164807134504 Vector1.euclideanlength 1.0 Vector0, 1, 2, 3, 4, 5, 6.euclideanlength 9.539392014169456 Vector.euclideanlength Traceback most recent call last: ... Exception: Vector is empty find angle between two Vector self, Vector Vector3, 4, 1.angleVector2, 1, 1 1.4906464636572374 Vector3, 4, 1.angleVector2, 1, 1, deg True 85.40775111366095 Vector3, 4, 1.angleVector2, 1 Traceback most recent call last: ... Exception: invalid operand! returns a zerovector of size 'dimension' precondition returns a unit basis vector with a One at index 'pos' indexing at 0 precondition input: a 'scalar' and two vectors 'x' and 'y' output: a vector computes the axpy operation precondition input: size N of the vector. random range a,b output: returns a random vector of size N, with random integer components between 'a' and 'b'. class: Matrix This class represents an arbitrary matrix. Overview of the methods: init: str: returns a string representation addother: Matrix: matrix addition subother: Matrix: matrix subtraction mulother: float: scalar multiplication mulother: Vector: vector multiplication height : returns height width : returns width componentx: int, y: int: returns specified component changecomponentx: int, y: int, value: float: changes specified component minorx: int, y: int: returns minor along x, y cofactorx: int, y: int: returns cofactor along x, y determinant : returns determinant simple constructor for initializing the matrix with components. returns a string representation of this matrix. implements matrix addition. implements matrix subtraction. implements the matrixvector multiplication. implements the matrixscalar multiplication getter for the height getter for the width returns the specified x,y component changes the xy component of this matrix returns the minor along x, y returns the cofactor signed minor along x, y returns the determinant of an nxn matrix using Laplace expansion returns a square zeromatrix of dimension NxN returns a random matrix WxH with integer components between 'a' and 'b'","Completions":"from __future__ import annotations\n\nimport math\nimport random\nfrom collections.abc import Collection\nfrom typing import overload\n\n\nclass Vector:\n \"\"\"\n This class represents a vector of arbitrary size.\n You need to give the vector components.\n\n Overview of the methods:\n\n __init__(components: Collection[float] | None): init the vector\n __len__(): gets the size of the vector (number of components)\n __str__(): returns a string representation\n __add__(other: Vector): vector addition\n __sub__(other: Vector): vector subtraction\n __mul__(other: float): scalar multiplication\n __mul__(other: Vector): dot product\n copy(): copies this vector and returns it\n component(i): gets the i-th component (0-indexed)\n change_component(pos: int, value: float): changes specified component\n euclidean_length(): returns the euclidean length of the vector\n angle(other: Vector, deg: bool): returns the angle between two vectors\n TODO: compare-operator\n \"\"\"\n\n def __init__(self, components: Collection[float] | None = None) -> None:\n \"\"\"\n input: components or nothing\n simple constructor for init the vector\n \"\"\"\n if components is None:\n components = []\n self.__components = list(components)\n\n def __len__(self) -> int:\n \"\"\"\n returns the size of the vector\n \"\"\"\n return len(self.__components)\n\n def __str__(self) -> str:\n \"\"\"\n returns a string representation of the vector\n \"\"\"\n return \"(\" + \",\".join(map(str, self.__components)) + \")\"\n\n def __add__(self, other: Vector) -> Vector:\n \"\"\"\n input: other vector\n assumes: other vector has the same size\n returns a new vector that represents the sum.\n \"\"\"\n size = len(self)\n if size == len(other):\n result = [self.__components[i] + other.component(i) for i in range(size)]\n return Vector(result)\n else:\n raise Exception(\"must have the same size\")\n\n def __sub__(self, other: Vector) -> Vector:\n \"\"\"\n input: other vector\n assumes: other vector has the same size\n returns a new vector that represents the difference.\n \"\"\"\n size = len(self)\n if size == len(other):\n result = [self.__components[i] - other.component(i) for i in range(size)]\n return Vector(result)\n else: # error case\n raise Exception(\"must have the same size\")\n\n @overload\n def __mul__(self, other: float) -> Vector:\n ...\n\n @overload\n def __mul__(self, other: Vector) -> float:\n ...\n\n def __mul__(self, other: float | Vector) -> float | Vector:\n \"\"\"\n mul implements the scalar multiplication\n and the dot-product\n \"\"\"\n if isinstance(other, (float, int)):\n ans = [c * other for c in self.__components]\n return Vector(ans)\n elif isinstance(other, Vector) and len(self) == len(other):\n size = len(self)\n prods = [self.__components[i] * other.component(i) for i in range(size)]\n return sum(prods)\n else: # error case\n raise Exception(\"invalid operand!\")\n\n def copy(self) -> Vector:\n \"\"\"\n copies this vector and returns it.\n \"\"\"\n return Vector(self.__components)\n\n def component(self, i: int) -> float:\n \"\"\"\n input: index (0-indexed)\n output: the i-th component of the vector.\n \"\"\"\n if isinstance(i, int) and -len(self.__components) <= i < len(self.__components):\n return self.__components[i]\n else:\n raise Exception(\"index out of range\")\n\n def change_component(self, pos: int, value: float) -> None:\n \"\"\"\n input: an index (pos) and a value\n changes the specified component (pos) with the\n 'value'\n \"\"\"\n # precondition\n assert -len(self.__components) <= pos < len(self.__components)\n self.__components[pos] = value\n\n def euclidean_length(self) -> float:\n \"\"\"\n returns the euclidean length of the vector\n\n >>> Vector([2, 3, 4]).euclidean_length()\n 5.385164807134504\n >>> Vector([1]).euclidean_length()\n 1.0\n >>> Vector([0, -1, -2, -3, 4, 5, 6]).euclidean_length()\n 9.539392014169456\n >>> Vector([]).euclidean_length()\n Traceback (most recent call last):\n ...\n Exception: Vector is empty\n \"\"\"\n if len(self.__components) == 0:\n raise Exception(\"Vector is empty\")\n squares = [c**2 for c in self.__components]\n return math.sqrt(sum(squares))\n\n def angle(self, other: Vector, deg: bool = False) -> float:\n \"\"\"\n find angle between two Vector (self, Vector)\n\n >>> Vector([3, 4, -1]).angle(Vector([2, -1, 1]))\n 1.4906464636572374\n >>> Vector([3, 4, -1]).angle(Vector([2, -1, 1]), deg = True)\n 85.40775111366095\n >>> Vector([3, 4, -1]).angle(Vector([2, -1]))\n Traceback (most recent call last):\n ...\n Exception: invalid operand!\n \"\"\"\n num = self * other\n den = self.euclidean_length() * other.euclidean_length()\n if deg:\n return math.degrees(math.acos(num \/ den))\n else:\n return math.acos(num \/ den)\n\n\ndef zero_vector(dimension: int) -> Vector:\n \"\"\"\n returns a zero-vector of size 'dimension'\n \"\"\"\n # precondition\n assert isinstance(dimension, int)\n return Vector([0] * dimension)\n\n\ndef unit_basis_vector(dimension: int, pos: int) -> Vector:\n \"\"\"\n returns a unit basis vector with a One\n at index 'pos' (indexing at 0)\n \"\"\"\n # precondition\n assert isinstance(dimension, int)\n assert isinstance(pos, int)\n ans = [0] * dimension\n ans[pos] = 1\n return Vector(ans)\n\n\ndef axpy(scalar: float, x: Vector, y: Vector) -> Vector:\n \"\"\"\n input: a 'scalar' and two vectors 'x' and 'y'\n output: a vector\n computes the axpy operation\n \"\"\"\n # precondition\n assert isinstance(x, Vector)\n assert isinstance(y, Vector)\n assert isinstance(scalar, (int, float))\n return x * scalar + y\n\n\ndef random_vector(n: int, a: int, b: int) -> Vector:\n \"\"\"\n input: size (N) of the vector.\n random range (a,b)\n output: returns a random vector of size N, with\n random integer components between 'a' and 'b'.\n \"\"\"\n random.seed(None)\n ans = [random.randint(a, b) for _ in range(n)]\n return Vector(ans)\n\n\nclass Matrix:\n \"\"\"\n class: Matrix\n This class represents an arbitrary matrix.\n\n Overview of the methods:\n\n __init__():\n __str__(): returns a string representation\n __add__(other: Matrix): matrix addition\n __sub__(other: Matrix): matrix subtraction\n __mul__(other: float): scalar multiplication\n __mul__(other: Vector): vector multiplication\n height() : returns height\n width() : returns width\n component(x: int, y: int): returns specified component\n change_component(x: int, y: int, value: float): changes specified component\n minor(x: int, y: int): returns minor along (x, y)\n cofactor(x: int, y: int): returns cofactor along (x, y)\n determinant() : returns determinant\n \"\"\"\n\n def __init__(self, matrix: list[list[float]], w: int, h: int) -> None:\n \"\"\"\n simple constructor for initializing the matrix with components.\n \"\"\"\n self.__matrix = matrix\n self.__width = w\n self.__height = h\n\n def __str__(self) -> str:\n \"\"\"\n returns a string representation of this matrix.\n \"\"\"\n ans = \"\"\n for i in range(self.__height):\n ans += \"|\"\n for j in range(self.__width):\n if j < self.__width - 1:\n ans += str(self.__matrix[i][j]) + \",\"\n else:\n ans += str(self.__matrix[i][j]) + \"|\\n\"\n return ans\n\n def __add__(self, other: Matrix) -> Matrix:\n \"\"\"\n implements matrix addition.\n \"\"\"\n if self.__width == other.width() and self.__height == other.height():\n matrix = []\n for i in range(self.__height):\n row = [\n self.__matrix[i][j] + other.component(i, j)\n for j in range(self.__width)\n ]\n matrix.append(row)\n return Matrix(matrix, self.__width, self.__height)\n else:\n raise Exception(\"matrix must have the same dimension!\")\n\n def __sub__(self, other: Matrix) -> Matrix:\n \"\"\"\n implements matrix subtraction.\n \"\"\"\n if self.__width == other.width() and self.__height == other.height():\n matrix = []\n for i in range(self.__height):\n row = [\n self.__matrix[i][j] - other.component(i, j)\n for j in range(self.__width)\n ]\n matrix.append(row)\n return Matrix(matrix, self.__width, self.__height)\n else:\n raise Exception(\"matrices must have the same dimension!\")\n\n @overload\n def __mul__(self, other: float) -> Matrix:\n ...\n\n @overload\n def __mul__(self, other: Vector) -> Vector:\n ...\n\n def __mul__(self, other: float | Vector) -> Vector | Matrix:\n \"\"\"\n implements the matrix-vector multiplication.\n implements the matrix-scalar multiplication\n \"\"\"\n if isinstance(other, Vector): # matrix-vector\n if len(other) == self.__width:\n ans = zero_vector(self.__height)\n for i in range(self.__height):\n prods = [\n self.__matrix[i][j] * other.component(j)\n for j in range(self.__width)\n ]\n ans.change_component(i, sum(prods))\n return ans\n else:\n raise Exception(\n \"vector must have the same size as the \"\n \"number of columns of the matrix!\"\n )\n elif isinstance(other, (int, float)): # matrix-scalar\n matrix = [\n [self.__matrix[i][j] * other for j in range(self.__width)]\n for i in range(self.__height)\n ]\n return Matrix(matrix, self.__width, self.__height)\n return None\n\n def height(self) -> int:\n \"\"\"\n getter for the height\n \"\"\"\n return self.__height\n\n def width(self) -> int:\n \"\"\"\n getter for the width\n \"\"\"\n return self.__width\n\n def component(self, x: int, y: int) -> float:\n \"\"\"\n returns the specified (x,y) component\n \"\"\"\n if 0 <= x < self.__height and 0 <= y < self.__width:\n return self.__matrix[x][y]\n else:\n raise Exception(\"change_component: indices out of bounds\")\n\n def change_component(self, x: int, y: int, value: float) -> None:\n \"\"\"\n changes the x-y component of this matrix\n \"\"\"\n if 0 <= x < self.__height and 0 <= y < self.__width:\n self.__matrix[x][y] = value\n else:\n raise Exception(\"change_component: indices out of bounds\")\n\n def minor(self, x: int, y: int) -> float:\n \"\"\"\n returns the minor along (x, y)\n \"\"\"\n if self.__height != self.__width:\n raise Exception(\"Matrix is not square\")\n minor = self.__matrix[:x] + self.__matrix[x + 1 :]\n for i in range(len(minor)):\n minor[i] = minor[i][:y] + minor[i][y + 1 :]\n return Matrix(minor, self.__width - 1, self.__height - 1).determinant()\n\n def cofactor(self, x: int, y: int) -> float:\n \"\"\"\n returns the cofactor (signed minor) along (x, y)\n \"\"\"\n if self.__height != self.__width:\n raise Exception(\"Matrix is not square\")\n if 0 <= x < self.__height and 0 <= y < self.__width:\n return (-1) ** (x + y) * self.minor(x, y)\n else:\n raise Exception(\"Indices out of bounds\")\n\n def determinant(self) -> float:\n \"\"\"\n returns the determinant of an nxn matrix using Laplace expansion\n \"\"\"\n if self.__height != self.__width:\n raise Exception(\"Matrix is not square\")\n if self.__height < 1:\n raise Exception(\"Matrix has no element\")\n elif self.__height == 1:\n return self.__matrix[0][0]\n elif self.__height == 2:\n return (\n self.__matrix[0][0] * self.__matrix[1][1]\n - self.__matrix[0][1] * self.__matrix[1][0]\n )\n else:\n cofactor_prods = [\n self.__matrix[0][y] * self.cofactor(0, y) for y in range(self.__width)\n ]\n return sum(cofactor_prods)\n\n\ndef square_zero_matrix(n: int) -> Matrix:\n \"\"\"\n returns a square zero-matrix of dimension NxN\n \"\"\"\n ans: list[list[float]] = [[0] * n for _ in range(n)]\n return Matrix(ans, n, n)\n\n\ndef random_matrix(width: int, height: int, a: int, b: int) -> Matrix:\n \"\"\"\n returns a random matrix WxH with integer components\n between 'a' and 'b'\n \"\"\"\n random.seed(None)\n matrix: list[list[float]] = [\n [random.randint(a, b) for _ in range(width)] for _ in range(height)\n ]\n return Matrix(matrix, width, height)\n"} +{"Prompt":"coordinates is a two dimensional matrix: x, y, x, y, ... number of points you want to use printpointstopolynomial Traceback most recent call last: ... ValueError: The program cannot work out a fitting polynomial. printpointstopolynomial Traceback most recent call last: ... ValueError: The program cannot work out a fitting polynomial. printpointstopolynomial1, 0, 2, 0, 3, 0 fxx20.0x10.0x00.0 printpointstopolynomial1, 1, 2, 1, 3, 1 fxx20.0x10.0x01.0 printpointstopolynomial1, 3, 2, 3, 3, 3 fxx20.0x10.0x03.0 printpointstopolynomial1, 1, 2, 2, 3, 3 fxx20.0x11.0x00.0 printpointstopolynomial1, 1, 2, 4, 3, 9 fxx21.0x10.0x00.0 printpointstopolynomial1, 3, 2, 6, 3, 11 fxx21.0x10.0x02.0 printpointstopolynomial1, 3, 2, 6, 3, 11 fxx21.0x10.0x02.0 printpointstopolynomial1, 5, 2, 2, 3, 9 fxx25.0x118.0x018.0 put the x and x to the power values in a matrix put the y values into a vector manipulating all the values in the matrix manipulating the values in the vector make solutions","Completions":"def points_to_polynomial(coordinates: list[list[int]]) -> str:\n \"\"\"\n coordinates is a two dimensional matrix: [[x, y], [x, y], ...]\n number of points you want to use\n\n >>> print(points_to_polynomial([]))\n Traceback (most recent call last):\n ...\n ValueError: The program cannot work out a fitting polynomial.\n >>> print(points_to_polynomial([[]]))\n Traceback (most recent call last):\n ...\n ValueError: The program cannot work out a fitting polynomial.\n >>> print(points_to_polynomial([[1, 0], [2, 0], [3, 0]]))\n f(x)=x^2*0.0+x^1*-0.0+x^0*0.0\n >>> print(points_to_polynomial([[1, 1], [2, 1], [3, 1]]))\n f(x)=x^2*0.0+x^1*-0.0+x^0*1.0\n >>> print(points_to_polynomial([[1, 3], [2, 3], [3, 3]]))\n f(x)=x^2*0.0+x^1*-0.0+x^0*3.0\n >>> print(points_to_polynomial([[1, 1], [2, 2], [3, 3]]))\n f(x)=x^2*0.0+x^1*1.0+x^0*0.0\n >>> print(points_to_polynomial([[1, 1], [2, 4], [3, 9]]))\n f(x)=x^2*1.0+x^1*-0.0+x^0*0.0\n >>> print(points_to_polynomial([[1, 3], [2, 6], [3, 11]]))\n f(x)=x^2*1.0+x^1*-0.0+x^0*2.0\n >>> print(points_to_polynomial([[1, -3], [2, -6], [3, -11]]))\n f(x)=x^2*-1.0+x^1*-0.0+x^0*-2.0\n >>> print(points_to_polynomial([[1, 5], [2, 2], [3, 9]]))\n f(x)=x^2*5.0+x^1*-18.0+x^0*18.0\n \"\"\"\n if len(coordinates) == 0 or not all(len(pair) == 2 for pair in coordinates):\n raise ValueError(\"The program cannot work out a fitting polynomial.\")\n\n if len({tuple(pair) for pair in coordinates}) != len(coordinates):\n raise ValueError(\"The program cannot work out a fitting polynomial.\")\n\n set_x = {x for x, _ in coordinates}\n if len(set_x) == 1:\n return f\"x={coordinates[0][0]}\"\n\n if len(set_x) != len(coordinates):\n raise ValueError(\"The program cannot work out a fitting polynomial.\")\n\n x = len(coordinates)\n\n # put the x and x to the power values in a matrix\n matrix: list[list[float]] = [\n [\n coordinates[count_of_line][0] ** (x - (count_in_line + 1))\n for count_in_line in range(x)\n ]\n for count_of_line in range(x)\n ]\n\n # put the y values into a vector\n vector: list[float] = [coordinates[count_of_line][1] for count_of_line in range(x)]\n\n for count in range(x):\n for number in range(x):\n if count == number:\n continue\n fraction = matrix[number][count] \/ matrix[count][count]\n for counting_columns, item in enumerate(matrix[count]):\n # manipulating all the values in the matrix\n matrix[number][counting_columns] -= item * fraction\n # manipulating the values in the vector\n vector[number] -= vector[count] * fraction\n\n # make solutions\n solution: list[str] = [\n str(vector[count] \/ matrix[count][count]) for count in range(x)\n ]\n\n solved = \"f(x)=\"\n\n for count in range(x):\n remove_e: list[str] = solution[count].split(\"E\")\n if len(remove_e) > 1:\n solution[count] = f\"{remove_e[0]}*10^{remove_e[1]}\"\n solved += f\"x^{x - (count + 1)}*{solution[count]}\"\n if count + 1 != x:\n solved += \"+\"\n\n return solved\n\n\nif __name__ == \"__main__\":\n print(points_to_polynomial([]))\n print(points_to_polynomial([[]]))\n print(points_to_polynomial([[1, 0], [2, 0], [3, 0]]))\n print(points_to_polynomial([[1, 1], [2, 1], [3, 1]]))\n print(points_to_polynomial([[1, 3], [2, 3], [3, 3]]))\n print(points_to_polynomial([[1, 1], [2, 2], [3, 3]]))\n print(points_to_polynomial([[1, 1], [2, 4], [3, 9]]))\n print(points_to_polynomial([[1, 3], [2, 6], [3, 11]]))\n print(points_to_polynomial([[1, -3], [2, -6], [3, -11]]))\n print(points_to_polynomial([[1, 5], [2, 2], [3, 9]]))\n"} +{"Prompt":"Power Iteration. Find the largest eigenvalue and corresponding eigenvector of matrix inputmatrix given a random vector in the same space. Will work so long as vector has component of largest eigenvector. inputmatrix must be either real or Hermitian. Input inputmatrix: input matrix whose largest eigenvalue we will find. Numpy array. np.shapeinputmatrix N,N. vector: random initial vector in same space as matrix. Numpy array. np.shapevector N, or N,1 Output largesteigenvalue: largest eigenvalue of the matrix inputmatrix. Float. Scalar. largesteigenvector: eigenvector corresponding to largesteigenvalue. Numpy array. np.shapelargesteigenvector N, or N,1. import numpy as np inputmatrix np.array ... 41, 4, 20, ... 4, 26, 30, ... 20, 30, 50 ... vector np.array41,4,20 poweriterationinputmatrix,vector 79.66086378788381, array0.44472726, 0.46209842, 0.76725662 Ensure matrix is square. Ensure proper dimensionality. Ensure inputs are either both complex or both real Ensure complex inputmatrix is Hermitian Set convergence to False. Will define convergence when we exceed maxiterations or when we have small changes from one iteration to next. Multiple matrix by the vector. Normalize the resulting output vector. Find rayleigh quotient faster than usual bc we know vector is normalized already Check convergence. testpoweriteration self running tests Our implementation. Numpy implementation. Get eigenvalues and eigenvectors using builtin numpy eigh eigh used for symmetric or hermetian matrices. Last eigenvalue is the maximum one. Last column in this matrix is eigenvector corresponding to largest eigenvalue. Check our implementation and numpy gives close answers. Take absolute values element wise of each eigenvector. as they are only unique to a minus sign.","Completions":"import numpy as np\n\n\ndef power_iteration(\n input_matrix: np.ndarray,\n vector: np.ndarray,\n error_tol: float = 1e-12,\n max_iterations: int = 100,\n) -> tuple[float, np.ndarray]:\n \"\"\"\n Power Iteration.\n Find the largest eigenvalue and corresponding eigenvector\n of matrix input_matrix given a random vector in the same space.\n Will work so long as vector has component of largest eigenvector.\n input_matrix must be either real or Hermitian.\n\n Input\n input_matrix: input matrix whose largest eigenvalue we will find.\n Numpy array. np.shape(input_matrix) == (N,N).\n vector: random initial vector in same space as matrix.\n Numpy array. np.shape(vector) == (N,) or (N,1)\n\n Output\n largest_eigenvalue: largest eigenvalue of the matrix input_matrix.\n Float. Scalar.\n largest_eigenvector: eigenvector corresponding to largest_eigenvalue.\n Numpy array. np.shape(largest_eigenvector) == (N,) or (N,1).\n\n >>> import numpy as np\n >>> input_matrix = np.array([\n ... [41, 4, 20],\n ... [ 4, 26, 30],\n ... [20, 30, 50]\n ... ])\n >>> vector = np.array([41,4,20])\n >>> power_iteration(input_matrix,vector)\n (79.66086378788381, array([0.44472726, 0.46209842, 0.76725662]))\n \"\"\"\n\n # Ensure matrix is square.\n assert np.shape(input_matrix)[0] == np.shape(input_matrix)[1]\n # Ensure proper dimensionality.\n assert np.shape(input_matrix)[0] == np.shape(vector)[0]\n # Ensure inputs are either both complex or both real\n assert np.iscomplexobj(input_matrix) == np.iscomplexobj(vector)\n is_complex = np.iscomplexobj(input_matrix)\n if is_complex:\n # Ensure complex input_matrix is Hermitian\n assert np.array_equal(input_matrix, input_matrix.conj().T)\n\n # Set convergence to False. Will define convergence when we exceed max_iterations\n # or when we have small changes from one iteration to next.\n\n convergence = False\n lambda_previous = 0\n iterations = 0\n error = 1e12\n\n while not convergence:\n # Multiple matrix by the vector.\n w = np.dot(input_matrix, vector)\n # Normalize the resulting output vector.\n vector = w \/ np.linalg.norm(w)\n # Find rayleigh quotient\n # (faster than usual b\/c we know vector is normalized already)\n vector_h = vector.conj().T if is_complex else vector.T\n lambda_ = np.dot(vector_h, np.dot(input_matrix, vector))\n\n # Check convergence.\n error = np.abs(lambda_ - lambda_previous) \/ lambda_\n iterations += 1\n\n if error <= error_tol or iterations >= max_iterations:\n convergence = True\n\n lambda_previous = lambda_\n\n if is_complex:\n lambda_ = np.real(lambda_)\n\n return lambda_, vector\n\n\ndef test_power_iteration() -> None:\n \"\"\"\n >>> test_power_iteration() # self running tests\n \"\"\"\n real_input_matrix = np.array([[41, 4, 20], [4, 26, 30], [20, 30, 50]])\n real_vector = np.array([41, 4, 20])\n complex_input_matrix = real_input_matrix.astype(np.complex128)\n imag_matrix = np.triu(1j * complex_input_matrix, 1)\n complex_input_matrix += imag_matrix\n complex_input_matrix += -1 * imag_matrix.T\n complex_vector = np.array([41, 4, 20]).astype(np.complex128)\n\n for problem_type in [\"real\", \"complex\"]:\n if problem_type == \"real\":\n input_matrix = real_input_matrix\n vector = real_vector\n elif problem_type == \"complex\":\n input_matrix = complex_input_matrix\n vector = complex_vector\n\n # Our implementation.\n eigen_value, eigen_vector = power_iteration(input_matrix, vector)\n\n # Numpy implementation.\n\n # Get eigenvalues and eigenvectors using built-in numpy\n # eigh (eigh used for symmetric or hermetian matrices).\n eigen_values, eigen_vectors = np.linalg.eigh(input_matrix)\n # Last eigenvalue is the maximum one.\n eigen_value_max = eigen_values[-1]\n # Last column in this matrix is eigenvector corresponding to largest eigenvalue.\n eigen_vector_max = eigen_vectors[:, -1]\n\n # Check our implementation and numpy gives close answers.\n assert np.abs(eigen_value - eigen_value_max) <= 1e-6\n # Take absolute values element wise of each eigenvector.\n # as they are only unique to a minus sign.\n assert np.linalg.norm(np.abs(eigen_vector) - np.abs(eigen_vector_max)) <= 1e-6\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n test_power_iteration()\n"} +{"Prompt":"Calculate the rank of a matrix. See: https:en.wikipedia.orgwikiRanklinearalgebra Finds the rank of a matrix. Args: matrix: The matrix as a list of lists. Returns: The rank of the matrix. Example: matrix1 1, 2, 3, ... 4, 5, 6, ... 7, 8, 9 rankofmatrixmatrix1 2 matrix2 1, 0, 0, ... 0, 1, 0, ... 0, 0, 0 rankofmatrixmatrix2 2 matrix3 1, 2, 3, 4, ... 5, 6, 7, 8, ... 9, 10, 11, 12 rankofmatrixmatrix3 2 rankofmatrix2,3,1,1, ... 1,1,2,4, ... 3,1,3,2, ... 6,3,0,7 4 rankofmatrix2,1,3,6, ... 3,3,1,2, ... 1,1,1,2 3 rankofmatrix2,1,0, ... 1,3,4, ... 4,1,3 3 rankofmatrix3,2,1, ... 6,4,2 1 rankofmatrix, 0 rankofmatrix1 1 rankofmatrix 0 Check if diagonal element is not zero Eliminate all the elements below the diagonal Find a nonzero diagonal element to swap rows Reduce the row pointer by one to stay on the same row","Completions":"def rank_of_matrix(matrix: list[list[int | float]]) -> int:\n \"\"\"\n Finds the rank of a matrix.\n Args:\n matrix: The matrix as a list of lists.\n Returns:\n The rank of the matrix.\n Example:\n >>> matrix1 = [[1, 2, 3],\n ... [4, 5, 6],\n ... [7, 8, 9]]\n >>> rank_of_matrix(matrix1)\n 2\n >>> matrix2 = [[1, 0, 0],\n ... [0, 1, 0],\n ... [0, 0, 0]]\n >>> rank_of_matrix(matrix2)\n 2\n >>> matrix3 = [[1, 2, 3, 4],\n ... [5, 6, 7, 8],\n ... [9, 10, 11, 12]]\n >>> rank_of_matrix(matrix3)\n 2\n >>> rank_of_matrix([[2,3,-1,-1],\n ... [1,-1,-2,4],\n ... [3,1,3,-2],\n ... [6,3,0,-7]])\n 4\n >>> rank_of_matrix([[2,1,-3,-6],\n ... [3,-3,1,2],\n ... [1,1,1,2]])\n 3\n >>> rank_of_matrix([[2,-1,0],\n ... [1,3,4],\n ... [4,1,-3]])\n 3\n >>> rank_of_matrix([[3,2,1],\n ... [-6,-4,-2]])\n 1\n >>> rank_of_matrix([[],[]])\n 0\n >>> rank_of_matrix([[1]])\n 1\n >>> rank_of_matrix([[]])\n 0\n \"\"\"\n\n rows = len(matrix)\n columns = len(matrix[0])\n rank = min(rows, columns)\n\n for row in range(rank):\n # Check if diagonal element is not zero\n if matrix[row][row] != 0:\n # Eliminate all the elements below the diagonal\n for col in range(row + 1, rows):\n multiplier = matrix[col][row] \/ matrix[row][row]\n for i in range(row, columns):\n matrix[col][i] -= multiplier * matrix[row][i]\n else:\n # Find a non-zero diagonal element to swap rows\n reduce = True\n for i in range(row + 1, rows):\n if matrix[i][row] != 0:\n matrix[row], matrix[i] = matrix[i], matrix[row]\n reduce = False\n break\n if reduce:\n rank -= 1\n for i in range(rows):\n matrix[i][row] = matrix[i][rank]\n\n # Reduce the row pointer by one to stay on the same row\n row -= 1\n\n return rank\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"https:en.wikipedia.orgwikiRayleighquotient Checks if a matrix is Hermitian. import numpy as np A np.array ... 2, 21j, 4, ... 21j, 3, 1j, ... 4, 1j, 1 ishermitianA True A np.array ... 2, 21j, 41j, ... 21j, 3, 1j, ... 4, 1j, 1 ishermitianA False Returns the Rayleigh quotient of a Hermitian matrix A and vector v. import numpy as np A np.array ... 1, 2, 4, ... 2, 3, 1, ... 4, 1, 1 ... v np.array ... 1, ... 2, ... 3 ... rayleighquotientA, v array3.","Completions":"from typing import Any\n\nimport numpy as np\n\n\ndef is_hermitian(matrix: np.ndarray) -> bool:\n \"\"\"\n Checks if a matrix is Hermitian.\n >>> import numpy as np\n >>> A = np.array([\n ... [2, 2+1j, 4],\n ... [2-1j, 3, 1j],\n ... [4, -1j, 1]])\n >>> is_hermitian(A)\n True\n >>> A = np.array([\n ... [2, 2+1j, 4+1j],\n ... [2-1j, 3, 1j],\n ... [4, -1j, 1]])\n >>> is_hermitian(A)\n False\n \"\"\"\n return np.array_equal(matrix, matrix.conjugate().T)\n\n\ndef rayleigh_quotient(a: np.ndarray, v: np.ndarray) -> Any:\n \"\"\"\n Returns the Rayleigh quotient of a Hermitian matrix A and\n vector v.\n >>> import numpy as np\n >>> A = np.array([\n ... [1, 2, 4],\n ... [2, 3, -1],\n ... [4, -1, 1]\n ... ])\n >>> v = np.array([\n ... [1],\n ... [2],\n ... [3]\n ... ])\n >>> rayleigh_quotient(A, v)\n array([[3.]])\n \"\"\"\n v_star = v.conjugate().T\n v_star_dot = v_star.dot(a)\n assert isinstance(v_star_dot, np.ndarray)\n return (v_star_dot.dot(v)) \/ (v_star.dot(v))\n\n\ndef tests() -> None:\n a = np.array([[2, 2 + 1j, 4], [2 - 1j, 3, 1j], [4, -1j, 1]])\n v = np.array([[1], [2], [3]])\n assert is_hermitian(a), f\"{a} is not hermitian.\"\n print(rayleigh_quotient(a, v))\n\n a = np.array([[1, 2, 4], [2, 3, -1], [4, -1, 1]])\n assert is_hermitian(a), f\"{a} is not hermitian.\"\n assert rayleigh_quotient(a, v) == float(3)\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n tests()\n"} +{"Prompt":"Schur complement of a symmetric matrix X given as a 2x2 block matrix consisting of matrices A, B and C. Matrix A must be quadratic and nonsingular. In case A is singular, a pseudoinverse may be provided using the pseudoinv argument. Link to Wiki: https:en.wikipedia.orgwikiSchurcomplement See also Convex Optimization Boyd and Vandenberghe, A.5.5 import numpy as np a np.array1, 2, 2, 1 b np.array0, 3, 3, 0 c np.array2, 1, 6, 3 schurcomplementa, b, c array 5., 5., 0., 6.","Completions":"import unittest\n\nimport numpy as np\nimport pytest\n\n\ndef schur_complement(\n mat_a: np.ndarray,\n mat_b: np.ndarray,\n mat_c: np.ndarray,\n pseudo_inv: np.ndarray | None = None,\n) -> np.ndarray:\n \"\"\"\n Schur complement of a symmetric matrix X given as a 2x2 block matrix\n consisting of matrices A, B and C.\n Matrix A must be quadratic and non-singular.\n In case A is singular, a pseudo-inverse may be provided using\n the pseudo_inv argument.\n\n Link to Wiki: https:\/\/en.wikipedia.org\/wiki\/Schur_complement\n See also Convex Optimization \u2013 Boyd and Vandenberghe, A.5.5\n >>> import numpy as np\n >>> a = np.array([[1, 2], [2, 1]])\n >>> b = np.array([[0, 3], [3, 0]])\n >>> c = np.array([[2, 1], [6, 3]])\n >>> schur_complement(a, b, c)\n array([[ 5., -5.],\n [ 0., 6.]])\n \"\"\"\n shape_a = np.shape(mat_a)\n shape_b = np.shape(mat_b)\n shape_c = np.shape(mat_c)\n\n if shape_a[0] != shape_b[0]:\n msg = (\n \"Expected the same number of rows for A and B. \"\n f\"Instead found A of size {shape_a} and B of size {shape_b}\"\n )\n raise ValueError(msg)\n\n if shape_b[1] != shape_c[1]:\n msg = (\n \"Expected the same number of columns for B and C. \"\n f\"Instead found B of size {shape_b} and C of size {shape_c}\"\n )\n raise ValueError(msg)\n\n a_inv = pseudo_inv\n if a_inv is None:\n try:\n a_inv = np.linalg.inv(mat_a)\n except np.linalg.LinAlgError:\n raise ValueError(\n \"Input matrix A is not invertible. Cannot compute Schur complement.\"\n )\n\n return mat_c - mat_b.T @ a_inv @ mat_b\n\n\nclass TestSchurComplement(unittest.TestCase):\n def test_schur_complement(self) -> None:\n a = np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]])\n b = np.array([[0, 3], [3, 0], [2, 3]])\n c = np.array([[2, 1], [6, 3]])\n\n s = schur_complement(a, b, c)\n\n input_matrix = np.block([[a, b], [b.T, c]])\n\n det_x = np.linalg.det(input_matrix)\n det_a = np.linalg.det(a)\n det_s = np.linalg.det(s)\n\n assert np.is_close(det_x, det_a * det_s)\n\n def test_improper_a_b_dimensions(self) -> None:\n a = np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]])\n b = np.array([[0, 3], [3, 0], [2, 3]])\n c = np.array([[2, 1], [6, 3]])\n\n with pytest.raises(ValueError):\n schur_complement(a, b, c)\n\n def test_improper_b_c_dimensions(self) -> None:\n a = np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]])\n b = np.array([[0, 3], [3, 0], [2, 3]])\n c = np.array([[2, 1, 3], [6, 3, 5]])\n\n with pytest.raises(ValueError):\n schur_complement(a, b, c)\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n unittest.main()\n"} +{"Prompt":"Created on Mon Feb 26 15:40:07 2018 author: Christian Bender license: MITlicense This file contains the testsuite for the linear algebra library. test for method component test for method toString test for method size test for method euclideanlength test for operator test for operator test for operator test for global function zerovector test for global function unitbasisvector test for global function axpy operation test for method copy test for method changecomponent test for Matrix method str test for Matrix method minor test for Matrix method cofactor test for Matrix method determinant test for Matrix operator test for Matrix method changecomponent test for Matrix method component test for Matrix operator test for Matrix operator test for global function squarezeromatrix","Completions":"import unittest\n\nimport pytest\n\nfrom .lib import (\n Matrix,\n Vector,\n axpy,\n square_zero_matrix,\n unit_basis_vector,\n zero_vector,\n)\n\n\nclass Test(unittest.TestCase):\n def test_component(self) -> None:\n \"\"\"\n test for method component()\n \"\"\"\n x = Vector([1, 2, 3])\n assert x.component(0) == 1\n assert x.component(2) == 3\n _ = Vector()\n\n def test_str(self) -> None:\n \"\"\"\n test for method toString()\n \"\"\"\n x = Vector([0, 0, 0, 0, 0, 1])\n assert str(x) == \"(0,0,0,0,0,1)\"\n\n def test_size(self) -> None:\n \"\"\"\n test for method size()\n \"\"\"\n x = Vector([1, 2, 3, 4])\n assert len(x) == 4\n\n def test_euclidean_length(self) -> None:\n \"\"\"\n test for method euclidean_length()\n \"\"\"\n x = Vector([1, 2])\n y = Vector([1, 2, 3, 4, 5])\n z = Vector([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])\n w = Vector([1, -1, 1, -1, 2, -3, 4, -5])\n assert x.euclidean_length() == pytest.approx(2.236, abs=1e-3)\n assert y.euclidean_length() == pytest.approx(7.416, abs=1e-3)\n assert z.euclidean_length() == 0\n assert w.euclidean_length() == pytest.approx(7.616, abs=1e-3)\n\n def test_add(self) -> None:\n \"\"\"\n test for + operator\n \"\"\"\n x = Vector([1, 2, 3])\n y = Vector([1, 1, 1])\n assert (x + y).component(0) == 2\n assert (x + y).component(1) == 3\n assert (x + y).component(2) == 4\n\n def test_sub(self) -> None:\n \"\"\"\n test for - operator\n \"\"\"\n x = Vector([1, 2, 3])\n y = Vector([1, 1, 1])\n assert (x - y).component(0) == 0\n assert (x - y).component(1) == 1\n assert (x - y).component(2) == 2\n\n def test_mul(self) -> None:\n \"\"\"\n test for * operator\n \"\"\"\n x = Vector([1, 2, 3])\n a = Vector([2, -1, 4]) # for test of dot product\n b = Vector([1, -2, -1])\n assert str(x * 3.0) == \"(3.0,6.0,9.0)\"\n assert a * b == 0\n\n def test_zero_vector(self) -> None:\n \"\"\"\n test for global function zero_vector()\n \"\"\"\n assert str(zero_vector(10)).count(\"0\") == 10\n\n def test_unit_basis_vector(self) -> None:\n \"\"\"\n test for global function unit_basis_vector()\n \"\"\"\n assert str(unit_basis_vector(3, 1)) == \"(0,1,0)\"\n\n def test_axpy(self) -> None:\n \"\"\"\n test for global function axpy() (operation)\n \"\"\"\n x = Vector([1, 2, 3])\n y = Vector([1, 0, 1])\n assert str(axpy(2, x, y)) == \"(3,4,7)\"\n\n def test_copy(self) -> None:\n \"\"\"\n test for method copy()\n \"\"\"\n x = Vector([1, 0, 0, 0, 0, 0])\n y = x.copy()\n assert str(x) == str(y)\n\n def test_change_component(self) -> None:\n \"\"\"\n test for method change_component()\n \"\"\"\n x = Vector([1, 0, 0])\n x.change_component(0, 0)\n x.change_component(1, 1)\n assert str(x) == \"(0,1,0)\"\n\n def test_str_matrix(self) -> None:\n \"\"\"\n test for Matrix method str()\n \"\"\"\n a = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]], 3, 3)\n assert str(a) == \"|1,2,3|\\n|2,4,5|\\n|6,7,8|\\n\"\n\n def test_minor(self) -> None:\n \"\"\"\n test for Matrix method minor()\n \"\"\"\n a = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]], 3, 3)\n minors = [[-3, -14, -10], [-5, -10, -5], [-2, -1, 0]]\n for x in range(a.height()):\n for y in range(a.width()):\n assert minors[x][y] == a.minor(x, y)\n\n def test_cofactor(self) -> None:\n \"\"\"\n test for Matrix method cofactor()\n \"\"\"\n a = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]], 3, 3)\n cofactors = [[-3, 14, -10], [5, -10, 5], [-2, 1, 0]]\n for x in range(a.height()):\n for y in range(a.width()):\n assert cofactors[x][y] == a.cofactor(x, y)\n\n def test_determinant(self) -> None:\n \"\"\"\n test for Matrix method determinant()\n \"\"\"\n a = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]], 3, 3)\n assert a.determinant() == -5\n\n def test__mul__matrix(self) -> None:\n \"\"\"\n test for Matrix * operator\n \"\"\"\n a = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]], 3, 3)\n x = Vector([1, 2, 3])\n assert str(a * x) == \"(14,32,50)\"\n assert str(a * 2) == \"|2,4,6|\\n|8,10,12|\\n|14,16,18|\\n\"\n\n def test_change_component_matrix(self) -> None:\n \"\"\"\n test for Matrix method change_component()\n \"\"\"\n a = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]], 3, 3)\n a.change_component(0, 2, 5)\n assert str(a) == \"|1,2,5|\\n|2,4,5|\\n|6,7,8|\\n\"\n\n def test_component_matrix(self) -> None:\n \"\"\"\n test for Matrix method component()\n \"\"\"\n a = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]], 3, 3)\n assert a.component(2, 1) == 7, 0.01\n\n def test__add__matrix(self) -> None:\n \"\"\"\n test for Matrix + operator\n \"\"\"\n a = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]], 3, 3)\n b = Matrix([[1, 2, 7], [2, 4, 5], [6, 7, 10]], 3, 3)\n assert str(a + b) == \"|2,4,10|\\n|4,8,10|\\n|12,14,18|\\n\"\n\n def test__sub__matrix(self) -> None:\n \"\"\"\n test for Matrix - operator\n \"\"\"\n a = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]], 3, 3)\n b = Matrix([[1, 2, 7], [2, 4, 5], [6, 7, 10]], 3, 3)\n assert str(a - b) == \"|0,0,-4|\\n|0,0,0|\\n|0,0,-2|\\n\"\n\n def test_square_zero_matrix(self) -> None:\n \"\"\"\n test for global function square_zero_matrix()\n \"\"\"\n assert str(square_zero_matrix(5)) == (\n \"|0,0,0,0,0|\\n|0,0,0,0,0|\\n|0,0,0,0,0|\\n|0,0,0,0,0|\\n|0,0,0,0,0|\\n\"\n )\n\n\nif __name__ == \"__main__\":\n unittest.main()\n"} +{"Prompt":"2D Transformations are regularly used in Linear Algebra. I have added the codes for reflection, projection, scaling and rotation 2D matrices. scaling5 5.0, 0.0, 0.0, 5.0 rotation45 0.5253219888177297, 0.8509035245341184, 0.8509035245341184, 0.5253219888177297 projection45 0.27596319193541496, 0.446998331800279, 0.446998331800279, 0.7240368080645851 reflection45 0.05064397763545947, 0.893996663600558, 0.893996663600558, 0.7018070490682369 scaling5 5.0, 0.0, 0.0, 5.0 rotation45 doctest: NORMALIZEWHITESPACE 0.5253219888177297, 0.8509035245341184, 0.8509035245341184, 0.5253219888177297 projection45 doctest: NORMALIZEWHITESPACE 0.27596319193541496, 0.446998331800279, 0.446998331800279, 0.7240368080645851 reflection45 doctest: NORMALIZEWHITESPACE 0.05064397763545947, 0.893996663600558, 0.893996663600558, 0.7018070490682369","Completions":"from math import cos, sin\n\n\ndef scaling(scaling_factor: float) -> list[list[float]]:\n \"\"\"\n >>> scaling(5)\n [[5.0, 0.0], [0.0, 5.0]]\n \"\"\"\n scaling_factor = float(scaling_factor)\n return [[scaling_factor * int(x == y) for x in range(2)] for y in range(2)]\n\n\ndef rotation(angle: float) -> list[list[float]]:\n \"\"\"\n >>> rotation(45) # doctest: +NORMALIZE_WHITESPACE\n [[0.5253219888177297, -0.8509035245341184],\n [0.8509035245341184, 0.5253219888177297]]\n \"\"\"\n c, s = cos(angle), sin(angle)\n return [[c, -s], [s, c]]\n\n\ndef projection(angle: float) -> list[list[float]]:\n \"\"\"\n >>> projection(45) # doctest: +NORMALIZE_WHITESPACE\n [[0.27596319193541496, 0.446998331800279],\n [0.446998331800279, 0.7240368080645851]]\n \"\"\"\n c, s = cos(angle), sin(angle)\n cs = c * s\n return [[c * c, cs], [cs, s * s]]\n\n\ndef reflection(angle: float) -> list[list[float]]:\n \"\"\"\n >>> reflection(45) # doctest: +NORMALIZE_WHITESPACE\n [[0.05064397763545947, 0.893996663600558],\n [0.893996663600558, 0.7018070490682369]]\n \"\"\"\n c, s = cos(angle), sin(angle)\n cs = c * s\n return [[2 * c - 1, 2 * cs], [2 * cs, 2 * s - 1]]\n\n\nprint(f\" {scaling(5) = }\")\nprint(f\" {rotation(45) = }\")\nprint(f\"{projection(45) = }\")\nprint(f\"{reflection(45) = }\")\n"} +{"Prompt":"Python implementation of the simplex algorithm for solving linear programs in tabular form with , , and constraints and each variable x1, x2, ... 0. See https:gist.github.comimengusf9619a568f7da5bc74eaf20169a24d98 for how to convert linear programs to simplex tableaus, and the steps taken in the simplex algorithm. Resources: https:en.wikipedia.orgwikiSimplexalgorithm https:tinyurl.comsimplex4beginners Operate on simplex tableaus Tableaunp.array1,1,0,0,1,1,3,1,0,4,3,1,0,1,4, 2, 2 Traceback most recent call last: ... TypeError: Tableau must have type float64 Tableaunp.array1,1,0,0,1,1,3,1,0,4,3,1,0,1,4., 2, 2 Traceback most recent call last: ... ValueError: RHS must be 0 Tableaunp.array1,1,0,0,1,1,3,1,0,4,3,1,0,1,4., 2, 2 Traceback most recent call last: ... ValueError: number of artificial variables must be a natural number Max iteration number to prevent cycling Check if RHS is negative Number of decision variables x1, x2, x3... 2 if there are or constraints nonstandard, 1 otherwise std Number of slack variables added to make inequalities into equalities Objectives for each stage In two stage simplex, first minimise then maximise Index of current pivot row and column Does objective row only contain nonnegative values? Generate column titles for tableau of specific dimensions Tableaunp.array1,1,0,0,1,1,3,1,0,4,3,1,0,1,4., ... 2, 0.generatecoltitles 'x1', 'x2', 's1', 's2', 'RHS' Tableaunp.array1,1,0,0,1,1,3,1,0,4,3,1,0,1,4., ... 2, 2.generatecoltitles 'x1', 'x2', 'RHS' decision slack Finds the pivot row and column. Tableaunp.array2,1,0,0,0, 3,1,1,0,6, 1,2,0,1,7., ... 2, 0.findpivot 1, 0 Find entries of highest magnitude in objective rows Choice is only valid if below 0 for maximise, and above for minimise Pivot row is chosen as having the lowest quotient when elements of the pivot column divide the righthand side Slice excluding the objective rows RHS Elements of pivot column within slice Array filled with nans If element in pivot column is greater than zero, return quotient or nan otherwise Arg of minimum quotient excluding the nan values. nstages is added to compensate for earlier exclusion of objective columns Pivots on value on the intersection of pivot row and column. Tableaunp.array2,3,0,0,0,1,3,1,0,4,3,1,0,1,4., ... 2, 2.pivot1, 0.tolist ... doctest: NORMALIZEWHITESPACE 0.0, 3.0, 2.0, 0.0, 8.0, 1.0, 3.0, 1.0, 0.0, 4.0, 0.0, 8.0, 3.0, 1.0, 8.0 Avoid changes to original tableau Entry becomes 1 Variable in pivot column becomes basic, ie the only nonzero entry Exits first phase of the twostage method by deleting artificial rows and columns, or completes the algorithm if exiting the standard case. Tableaunp.array ... 3, 3, 1, 1, 0, 0, 4, ... 2, 1, 0, 0, 0, 0, 0., ... 1, 2, 1, 0, 1, 0, 2, ... 2, 1, 0, 1, 0, 1, 2 ... , 2, 2.changestage.tolist ... doctest: NORMALIZEWHITESPACE 2.0, 1.0, 0.0, 0.0, 0.0, 1.0, 2.0, 1.0, 0.0, 2.0, 2.0, 1.0, 0.0, 1.0, 2.0 Objective of original objective row remains Slice containing ids for artificial columns Delete the artificial variable columns Delete the objective row of the first stage Operate on tableau until objective function cannot be improved further. Standard linear program: Max: x1 x2 ST: x1 3x2 4 3x1 x2 4 Tableaunp.array1,1,0,0,0,1,3,1,0,4,3,1,0,1,4., ... 2, 0.runsimplex 'P': 2.0, 'x1': 1.0, 'x2': 1.0 Standard linear program with 3 variables: Max: 3x1 x2 3x3 ST: 2x1 x2 x3 2 x1 2x2 3x3 5 2x1 2x2 x3 6 Tableaunp.array ... 3,1,3,0,0,0,0, ... 2,1,1,1,0,0,2, ... 1,2,3,0,1,0,5, ... 2,2,1,0,0,1,6. ... ,3,0.runsimplex doctest: ELLIPSIS 'P': 5.4, 'x1': 0.199..., 'x3': 1.6 Optimal tableau input: Tableaunp.array ... 0, 0, 0.25, 0.25, 2, ... 0, 1, 0.375, 0.125, 1, ... 1, 0, 0.125, 0.375, 1 ... , 2, 0.runsimplex 'P': 2.0, 'x1': 1.0, 'x2': 1.0 Nonstandard: constraints Max: 2x1 3x2 x3 ST: x1 x2 x3 40 2x1 x2 x3 10 x2 x3 10 Tableaunp.array ... 2, 0, 0, 0, 1, 1, 0, 0, 20, ... 2, 3, 1, 0, 0, 0, 0, 0, 0, ... 1, 1, 1, 1, 0, 0, 0, 0, 40, ... 2, 1, 1, 0, 1, 0, 1, 0, 10, ... 0, 1, 1, 0, 0, 1, 0, 1, 10. ... , 3, 2.runsimplex 'P': 70.0, 'x1': 10.0, 'x2': 10.0, 'x3': 20.0 Non standard: minimisation and equalities Min: x1 x2 ST: 2x1 x2 12 6x1 5x2 40 Tableaunp.array ... 8, 6, 0, 0, 52, ... 1, 1, 0, 0, 0, ... 2, 1, 1, 0, 12, ... 6, 5, 0, 1, 40., ... , 2, 2.runsimplex 'P': 7.0, 'x1': 5.0, 'x2': 2.0 Pivot on slack variables Max: 8x1 6x2 ST: x1 3x2 33 4x1 2x2 48 2x1 4x2 48 x1 x2 10 x1 2 Tableaunp.array ... 2, 1, 0, 0, 0, 1, 1, 0, 0, 12.0, ... 8, 6, 0, 0, 0, 0, 0, 0, 0, 0.0, ... 1, 3, 1, 0, 0, 0, 0, 0, 0, 33.0, ... 4, 2, 0, 1, 0, 0, 0, 0, 0, 60.0, ... 2, 4, 0, 0, 1, 0, 0, 0, 0, 48.0, ... 1, 1, 0, 0, 0, 1, 0, 1, 0, 10.0, ... 1, 0, 0, 0, 0, 0, 1, 0, 1, 2.0 ... , 2, 2.runsimplex doctest: ELLIPSIS 'P': 132.0, 'x1': 12.000... 'x2': 5.999... Stop simplex algorithm from cycling. Completion of each stage removes an objective. If both stages are complete, then no objectives are left Find the values of each variable at optimal solution If there are no more negative values in objective row Delete artificial variable columns and rows. Update attributes Given the final tableau, add the corresponding values of the basic decision variables to the outputdict Tableaunp.array ... 0,0,0.875,0.375,5, ... 0,1,0.375,0.125,1, ... 1,0,0.125,0.375,1 ... ,2, 0.interprettableau 'P': 5.0, 'x1': 1.0, 'x2': 1.0 P RHS of final tableau Gives indices of nonzero entries in the ith column First entry in the nonzero indices If there is only one nonzero value in column, which is one","Completions":"from typing import Any\n\nimport numpy as np\n\n\nclass Tableau:\n \"\"\"Operate on simplex tableaus\n\n >>> Tableau(np.array([[-1,-1,0,0,1],[1,3,1,0,4],[3,1,0,1,4]]), 2, 2)\n Traceback (most recent call last):\n ...\n TypeError: Tableau must have type float64\n\n >>> Tableau(np.array([[-1,-1,0,0,-1],[1,3,1,0,4],[3,1,0,1,4.]]), 2, 2)\n Traceback (most recent call last):\n ...\n ValueError: RHS must be > 0\n\n >>> Tableau(np.array([[-1,-1,0,0,1],[1,3,1,0,4],[3,1,0,1,4.]]), -2, 2)\n Traceback (most recent call last):\n ...\n ValueError: number of (artificial) variables must be a natural number\n \"\"\"\n\n # Max iteration number to prevent cycling\n maxiter = 100\n\n def __init__(\n self, tableau: np.ndarray, n_vars: int, n_artificial_vars: int\n ) -> None:\n if tableau.dtype != \"float64\":\n raise TypeError(\"Tableau must have type float64\")\n\n # Check if RHS is negative\n if not (tableau[:, -1] >= 0).all():\n raise ValueError(\"RHS must be > 0\")\n\n if n_vars < 2 or n_artificial_vars < 0:\n raise ValueError(\n \"number of (artificial) variables must be a natural number\"\n )\n\n self.tableau = tableau\n self.n_rows, n_cols = tableau.shape\n\n # Number of decision variables x1, x2, x3...\n self.n_vars, self.n_artificial_vars = n_vars, n_artificial_vars\n\n # 2 if there are >= or == constraints (nonstandard), 1 otherwise (std)\n self.n_stages = (self.n_artificial_vars > 0) + 1\n\n # Number of slack variables added to make inequalities into equalities\n self.n_slack = n_cols - self.n_vars - self.n_artificial_vars - 1\n\n # Objectives for each stage\n self.objectives = [\"max\"]\n\n # In two stage simplex, first minimise then maximise\n if self.n_artificial_vars:\n self.objectives.append(\"min\")\n\n self.col_titles = self.generate_col_titles()\n\n # Index of current pivot row and column\n self.row_idx = None\n self.col_idx = None\n\n # Does objective row only contain (non)-negative values?\n self.stop_iter = False\n\n def generate_col_titles(self) -> list[str]:\n \"\"\"Generate column titles for tableau of specific dimensions\n\n >>> Tableau(np.array([[-1,-1,0,0,1],[1,3,1,0,4],[3,1,0,1,4.]]),\n ... 2, 0).generate_col_titles()\n ['x1', 'x2', 's1', 's2', 'RHS']\n\n >>> Tableau(np.array([[-1,-1,0,0,1],[1,3,1,0,4],[3,1,0,1,4.]]),\n ... 2, 2).generate_col_titles()\n ['x1', 'x2', 'RHS']\n \"\"\"\n args = (self.n_vars, self.n_slack)\n\n # decision | slack\n string_starts = [\"x\", \"s\"]\n titles = []\n for i in range(2):\n for j in range(args[i]):\n titles.append(string_starts[i] + str(j + 1))\n titles.append(\"RHS\")\n return titles\n\n def find_pivot(self) -> tuple[Any, Any]:\n \"\"\"Finds the pivot row and column.\n >>> Tableau(np.array([[-2,1,0,0,0], [3,1,1,0,6], [1,2,0,1,7.]]),\n ... 2, 0).find_pivot()\n (1, 0)\n \"\"\"\n objective = self.objectives[-1]\n\n # Find entries of highest magnitude in objective rows\n sign = (objective == \"min\") - (objective == \"max\")\n col_idx = np.argmax(sign * self.tableau[0, :-1])\n\n # Choice is only valid if below 0 for maximise, and above for minimise\n if sign * self.tableau[0, col_idx] <= 0:\n self.stop_iter = True\n return 0, 0\n\n # Pivot row is chosen as having the lowest quotient when elements of\n # the pivot column divide the right-hand side\n\n # Slice excluding the objective rows\n s = slice(self.n_stages, self.n_rows)\n\n # RHS\n dividend = self.tableau[s, -1]\n\n # Elements of pivot column within slice\n divisor = self.tableau[s, col_idx]\n\n # Array filled with nans\n nans = np.full(self.n_rows - self.n_stages, np.nan)\n\n # If element in pivot column is greater than zero, return\n # quotient or nan otherwise\n quotients = np.divide(dividend, divisor, out=nans, where=divisor > 0)\n\n # Arg of minimum quotient excluding the nan values. n_stages is added\n # to compensate for earlier exclusion of objective columns\n row_idx = np.nanargmin(quotients) + self.n_stages\n return row_idx, col_idx\n\n def pivot(self, row_idx: int, col_idx: int) -> np.ndarray:\n \"\"\"Pivots on value on the intersection of pivot row and column.\n\n >>> Tableau(np.array([[-2,-3,0,0,0],[1,3,1,0,4],[3,1,0,1,4.]]),\n ... 2, 2).pivot(1, 0).tolist()\n ... # doctest: +NORMALIZE_WHITESPACE\n [[0.0, 3.0, 2.0, 0.0, 8.0],\n [1.0, 3.0, 1.0, 0.0, 4.0],\n [0.0, -8.0, -3.0, 1.0, -8.0]]\n \"\"\"\n # Avoid changes to original tableau\n piv_row = self.tableau[row_idx].copy()\n\n piv_val = piv_row[col_idx]\n\n # Entry becomes 1\n piv_row *= 1 \/ piv_val\n\n # Variable in pivot column becomes basic, ie the only non-zero entry\n for idx, coeff in enumerate(self.tableau[:, col_idx]):\n self.tableau[idx] += -coeff * piv_row\n self.tableau[row_idx] = piv_row\n return self.tableau\n\n def change_stage(self) -> np.ndarray:\n \"\"\"Exits first phase of the two-stage method by deleting artificial\n rows and columns, or completes the algorithm if exiting the standard\n case.\n\n >>> Tableau(np.array([\n ... [3, 3, -1, -1, 0, 0, 4],\n ... [2, 1, 0, 0, 0, 0, 0.],\n ... [1, 2, -1, 0, 1, 0, 2],\n ... [2, 1, 0, -1, 0, 1, 2]\n ... ]), 2, 2).change_stage().tolist()\n ... # doctest: +NORMALIZE_WHITESPACE\n [[2.0, 1.0, 0.0, 0.0, 0.0],\n [1.0, 2.0, -1.0, 0.0, 2.0],\n [2.0, 1.0, 0.0, -1.0, 2.0]]\n \"\"\"\n # Objective of original objective row remains\n self.objectives.pop()\n\n if not self.objectives:\n return self.tableau\n\n # Slice containing ids for artificial columns\n s = slice(-self.n_artificial_vars - 1, -1)\n\n # Delete the artificial variable columns\n self.tableau = np.delete(self.tableau, s, axis=1)\n\n # Delete the objective row of the first stage\n self.tableau = np.delete(self.tableau, 0, axis=0)\n\n self.n_stages = 1\n self.n_rows -= 1\n self.n_artificial_vars = 0\n self.stop_iter = False\n return self.tableau\n\n def run_simplex(self) -> dict[Any, Any]:\n \"\"\"Operate on tableau until objective function cannot be\n improved further.\n\n # Standard linear program:\n Max: x1 + x2\n ST: x1 + 3x2 <= 4\n 3x1 + x2 <= 4\n >>> Tableau(np.array([[-1,-1,0,0,0],[1,3,1,0,4],[3,1,0,1,4.]]),\n ... 2, 0).run_simplex()\n {'P': 2.0, 'x1': 1.0, 'x2': 1.0}\n\n # Standard linear program with 3 variables:\n Max: 3x1 + x2 + 3x3\n ST: 2x1 + x2 + x3 \u2264 2\n x1 + 2x2 + 3x3 \u2264 5\n 2x1 + 2x2 + x3 \u2264 6\n >>> Tableau(np.array([\n ... [-3,-1,-3,0,0,0,0],\n ... [2,1,1,1,0,0,2],\n ... [1,2,3,0,1,0,5],\n ... [2,2,1,0,0,1,6.]\n ... ]),3,0).run_simplex() # doctest: +ELLIPSIS\n {'P': 5.4, 'x1': 0.199..., 'x3': 1.6}\n\n\n # Optimal tableau input:\n >>> Tableau(np.array([\n ... [0, 0, 0.25, 0.25, 2],\n ... [0, 1, 0.375, -0.125, 1],\n ... [1, 0, -0.125, 0.375, 1]\n ... ]), 2, 0).run_simplex()\n {'P': 2.0, 'x1': 1.0, 'x2': 1.0}\n\n # Non-standard: >= constraints\n Max: 2x1 + 3x2 + x3\n ST: x1 + x2 + x3 <= 40\n 2x1 + x2 - x3 >= 10\n - x2 + x3 >= 10\n >>> Tableau(np.array([\n ... [2, 0, 0, 0, -1, -1, 0, 0, 20],\n ... [-2, -3, -1, 0, 0, 0, 0, 0, 0],\n ... [1, 1, 1, 1, 0, 0, 0, 0, 40],\n ... [2, 1, -1, 0, -1, 0, 1, 0, 10],\n ... [0, -1, 1, 0, 0, -1, 0, 1, 10.]\n ... ]), 3, 2).run_simplex()\n {'P': 70.0, 'x1': 10.0, 'x2': 10.0, 'x3': 20.0}\n\n # Non standard: minimisation and equalities\n Min: x1 + x2\n ST: 2x1 + x2 = 12\n 6x1 + 5x2 = 40\n >>> Tableau(np.array([\n ... [8, 6, 0, 0, 52],\n ... [1, 1, 0, 0, 0],\n ... [2, 1, 1, 0, 12],\n ... [6, 5, 0, 1, 40.],\n ... ]), 2, 2).run_simplex()\n {'P': 7.0, 'x1': 5.0, 'x2': 2.0}\n\n\n # Pivot on slack variables\n Max: 8x1 + 6x2\n ST: x1 + 3x2 <= 33\n 4x1 + 2x2 <= 48\n 2x1 + 4x2 <= 48\n x1 + x2 >= 10\n x1 >= 2\n >>> Tableau(np.array([\n ... [2, 1, 0, 0, 0, -1, -1, 0, 0, 12.0],\n ... [-8, -6, 0, 0, 0, 0, 0, 0, 0, 0.0],\n ... [1, 3, 1, 0, 0, 0, 0, 0, 0, 33.0],\n ... [4, 2, 0, 1, 0, 0, 0, 0, 0, 60.0],\n ... [2, 4, 0, 0, 1, 0, 0, 0, 0, 48.0],\n ... [1, 1, 0, 0, 0, -1, 0, 1, 0, 10.0],\n ... [1, 0, 0, 0, 0, 0, -1, 0, 1, 2.0]\n ... ]), 2, 2).run_simplex() # doctest: +ELLIPSIS\n {'P': 132.0, 'x1': 12.000... 'x2': 5.999...}\n \"\"\"\n # Stop simplex algorithm from cycling.\n for _ in range(Tableau.maxiter):\n # Completion of each stage removes an objective. If both stages\n # are complete, then no objectives are left\n if not self.objectives:\n # Find the values of each variable at optimal solution\n return self.interpret_tableau()\n\n row_idx, col_idx = self.find_pivot()\n\n # If there are no more negative values in objective row\n if self.stop_iter:\n # Delete artificial variable columns and rows. Update attributes\n self.tableau = self.change_stage()\n else:\n self.tableau = self.pivot(row_idx, col_idx)\n return {}\n\n def interpret_tableau(self) -> dict[str, float]:\n \"\"\"Given the final tableau, add the corresponding values of the basic\n decision variables to the `output_dict`\n >>> Tableau(np.array([\n ... [0,0,0.875,0.375,5],\n ... [0,1,0.375,-0.125,1],\n ... [1,0,-0.125,0.375,1]\n ... ]),2, 0).interpret_tableau()\n {'P': 5.0, 'x1': 1.0, 'x2': 1.0}\n \"\"\"\n # P = RHS of final tableau\n output_dict = {\"P\": abs(self.tableau[0, -1])}\n\n for i in range(self.n_vars):\n # Gives indices of nonzero entries in the ith column\n nonzero = np.nonzero(self.tableau[:, i])\n n_nonzero = len(nonzero[0])\n\n # First entry in the nonzero indices\n nonzero_rowidx = nonzero[0][0]\n nonzero_val = self.tableau[nonzero_rowidx, i]\n\n # If there is only one nonzero value in column, which is one\n if n_nonzero == 1 and nonzero_val == 1:\n rhs_val = self.tableau[nonzero_rowidx, -1]\n output_dict[self.col_titles[i]] = rhs_val\n return output_dict\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Apriori Algorithm is a Association rule mining technique, also known as market basket analysis, aims to discover interesting relationships or associations among a set of items in a transactional or relational database. For example, Apriori Algorithm states: If a customer buys item A and item B, then they are likely to buy item C. This rule suggests a relationship between items A, B, and C, indicating that customers who purchased A and B are more likely to also purchase item C. WIKI: https:en.wikipedia.orgwikiApriorialgorithm Examples: https:www.kaggle.comcodeearthianaprioriassociationrulesmining Returns a sample transaction dataset. loaddata 'milk', 'milk', 'butter', 'milk', 'bread', 'milk', 'bread', 'chips' Prune candidate itemsets that are not frequent. The goal of pruning is to filter out candidate itemsets that are not frequent. This is done by checking if all the k1 subsets of a candidate itemset are present in the frequent itemsets of the previous iteration valid subsequences of the frequent itemsets from the previous iteration. Prunes candidate itemsets that are not frequent. itemset 'X', 'Y', 'Z' candidates 'X', 'Y', 'X', 'Z', 'Y', 'Z' pruneitemset, candidates, 2 'X', 'Y', 'X', 'Z', 'Y', 'Z' itemset '1', '2', '3', '4' candidates '1', '2', '4' pruneitemset, candidates, 3 Returns a list of frequent itemsets and their support counts. data 'A', 'B', 'C', 'A', 'B', 'A', 'C', 'A', 'D', 'B', 'C' aprioridata, 2 'A', 'B', 1, 'A', 'C', 2, 'B', 'C', 2 data '1', '2', '3', '1', '2', '1', '3', '1', '4', '2', '3' aprioridata, 3 Count itemset support Prune infrequent itemsets Append frequent itemsets as a list to maintain order Apriori algorithm for finding frequent itemsets. Args: data: A list of transactions, where each transaction is a list of items. minsupport: The minimum support threshold for frequent itemsets. Returns: A list of frequent itemsets along with their support counts. userdefined threshold or minimum support level","Completions":"from itertools import combinations\n\n\ndef load_data() -> list[list[str]]:\n \"\"\"\n Returns a sample transaction dataset.\n\n >>> load_data()\n [['milk'], ['milk', 'butter'], ['milk', 'bread'], ['milk', 'bread', 'chips']]\n \"\"\"\n return [[\"milk\"], [\"milk\", \"butter\"], [\"milk\", \"bread\"], [\"milk\", \"bread\", \"chips\"]]\n\n\ndef prune(itemset: list, candidates: list, length: int) -> list:\n \"\"\"\n Prune candidate itemsets that are not frequent.\n The goal of pruning is to filter out candidate itemsets that are not frequent. This\n is done by checking if all the (k-1) subsets of a candidate itemset are present in\n the frequent itemsets of the previous iteration (valid subsequences of the frequent\n itemsets from the previous iteration).\n\n Prunes candidate itemsets that are not frequent.\n\n >>> itemset = ['X', 'Y', 'Z']\n >>> candidates = [['X', 'Y'], ['X', 'Z'], ['Y', 'Z']]\n >>> prune(itemset, candidates, 2)\n [['X', 'Y'], ['X', 'Z'], ['Y', 'Z']]\n\n >>> itemset = ['1', '2', '3', '4']\n >>> candidates = ['1', '2', '4']\n >>> prune(itemset, candidates, 3)\n []\n \"\"\"\n pruned = []\n for candidate in candidates:\n is_subsequence = True\n for item in candidate:\n if item not in itemset or itemset.count(item) < length - 1:\n is_subsequence = False\n break\n if is_subsequence:\n pruned.append(candidate)\n return pruned\n\n\ndef apriori(data: list[list[str]], min_support: int) -> list[tuple[list[str], int]]:\n \"\"\"\n Returns a list of frequent itemsets and their support counts.\n\n >>> data = [['A', 'B', 'C'], ['A', 'B'], ['A', 'C'], ['A', 'D'], ['B', 'C']]\n >>> apriori(data, 2)\n [(['A', 'B'], 1), (['A', 'C'], 2), (['B', 'C'], 2)]\n\n >>> data = [['1', '2', '3'], ['1', '2'], ['1', '3'], ['1', '4'], ['2', '3']]\n >>> apriori(data, 3)\n []\n \"\"\"\n itemset = [list(transaction) for transaction in data]\n frequent_itemsets = []\n length = 1\n\n while itemset:\n # Count itemset support\n counts = [0] * len(itemset)\n for transaction in data:\n for j, candidate in enumerate(itemset):\n if all(item in transaction for item in candidate):\n counts[j] += 1\n\n # Prune infrequent itemsets\n itemset = [item for i, item in enumerate(itemset) if counts[i] >= min_support]\n\n # Append frequent itemsets (as a list to maintain order)\n for i, item in enumerate(itemset):\n frequent_itemsets.append((sorted(item), counts[i]))\n\n length += 1\n itemset = prune(itemset, list(combinations(itemset, length)), length)\n\n return frequent_itemsets\n\n\nif __name__ == \"__main__\":\n \"\"\"\n Apriori algorithm for finding frequent itemsets.\n\n Args:\n data: A list of transactions, where each transaction is a list of items.\n min_support: The minimum support threshold for frequent itemsets.\n\n Returns:\n A list of frequent itemsets along with their support counts.\n \"\"\"\n import doctest\n\n doctest.testmod()\n\n # user-defined threshold or minimum support level\n frequent_itemsets = apriori(data=load_data(), min_support=2)\n print(\"\\n\".join(f\"{itemset}: {support}\" for itemset, support in frequent_itemsets))\n"} +{"Prompt":"The A algorithm combines features of uniformcost search and pure heuristic search to efficiently compute optimal solutions. The A algorithm is a bestfirst search algorithm in which the cost associated with a node is fn gn hn, where gn is the cost of the path from the initial state to node n and hn is the heuristic estimate or the cost or a path from node n to a goal. The A algorithm introduces a heuristic into a regular graphsearching algorithm, essentially planning ahead at each step so a more optimal decision is made. For this reason, A is known as an algorithm with brains. https:en.wikipedia.orgwikiAsearchalgorithm Class cell represents a cell in the world which have the properties: position: represented by tuple of x and y coordinates initially set to 0,0. parent: Contains the parent cell object visited before we arrived at this cell. g, h, f: Parameters used when calling our heuristic function. Overrides equals method because otherwise cell assign will give wrong results. Gridworld class represents the external world here a grid MM matrix. worldsize: create a numpy array with the given worldsize default is 5. Return the neighbours of cell Implementation of a start algorithm. world : Object of the world object. start : Object of the cell as start position. stop : Object of the cell as goal position. p Gridworld start Cell start.position 0,0 goal Cell goal.position 4,4 astarp, start, goal 0, 0, 1, 1, 2, 2, 3, 3, 4, 4 Start position and goal Just for visual reasons.","Completions":"import numpy as np\n\n\nclass Cell:\n \"\"\"\n Class cell represents a cell in the world which have the properties:\n position: represented by tuple of x and y coordinates initially set to (0,0).\n parent: Contains the parent cell object visited before we arrived at this cell.\n g, h, f: Parameters used when calling our heuristic function.\n \"\"\"\n\n def __init__(self):\n self.position = (0, 0)\n self.parent = None\n self.g = 0\n self.h = 0\n self.f = 0\n\n \"\"\"\n Overrides equals method because otherwise cell assign will give\n wrong results.\n \"\"\"\n\n def __eq__(self, cell):\n return self.position == cell.position\n\n def showcell(self):\n print(self.position)\n\n\nclass Gridworld:\n \"\"\"\n Gridworld class represents the external world here a grid M*M\n matrix.\n world_size: create a numpy array with the given world_size default is 5.\n \"\"\"\n\n def __init__(self, world_size=(5, 5)):\n self.w = np.zeros(world_size)\n self.world_x_limit = world_size[0]\n self.world_y_limit = world_size[1]\n\n def show(self):\n print(self.w)\n\n def get_neigbours(self, cell):\n \"\"\"\n Return the neighbours of cell\n \"\"\"\n neughbour_cord = [\n (-1, -1),\n (-1, 0),\n (-1, 1),\n (0, -1),\n (0, 1),\n (1, -1),\n (1, 0),\n (1, 1),\n ]\n current_x = cell.position[0]\n current_y = cell.position[1]\n neighbours = []\n for n in neughbour_cord:\n x = current_x + n[0]\n y = current_y + n[1]\n if 0 <= x < self.world_x_limit and 0 <= y < self.world_y_limit:\n c = Cell()\n c.position = (x, y)\n c.parent = cell\n neighbours.append(c)\n return neighbours\n\n\ndef astar(world, start, goal):\n \"\"\"\n Implementation of a start algorithm.\n world : Object of the world object.\n start : Object of the cell as start position.\n stop : Object of the cell as goal position.\n\n >>> p = Gridworld()\n >>> start = Cell()\n >>> start.position = (0,0)\n >>> goal = Cell()\n >>> goal.position = (4,4)\n >>> astar(p, start, goal)\n [(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]\n \"\"\"\n _open = []\n _closed = []\n _open.append(start)\n\n while _open:\n min_f = np.argmin([n.f for n in _open])\n current = _open[min_f]\n _closed.append(_open.pop(min_f))\n if current == goal:\n break\n for n in world.get_neigbours(current):\n for c in _closed:\n if c == n:\n continue\n n.g = current.g + 1\n x1, y1 = n.position\n x2, y2 = goal.position\n n.h = (y2 - y1) ** 2 + (x2 - x1) ** 2\n n.f = n.h + n.g\n\n for c in _open:\n if c == n and c.f < n.f:\n continue\n _open.append(n)\n path = []\n while current.parent is not None:\n path.append(current.position)\n current = current.parent\n path.append(current.position)\n return path[::-1]\n\n\nif __name__ == \"__main__\":\n world = Gridworld()\n # Start position and goal\n start = Cell()\n start.position = (0, 0)\n goal = Cell()\n goal.position = (4, 4)\n print(f\"path from {start.position} to {goal.position}\")\n s = astar(world, start, goal)\n # Just for visual reasons.\n for i in s:\n world.w[i] = 1\n print(world.w)\n"} +{"Prompt":"Demonstration of the Automatic Differentiation Reverse mode. Reference: https:en.wikipedia.orgwikiAutomaticdifferentiation Author: Poojan Smart Email: smrtpoojangmail.com Class represents list of supported operations on Variable for gradient calculation. Class represents ndimensional object which is used to wrap numpy array on which operations will be performed and the gradient will be calculated. Examples: Variable5.0 Variable5.0 Variable5.0, 2.9 Variable5. 2.9 Variable5.0, 2.9 Variable1.0, 5.5 Variable6. 8.4 Variable8.0, 10.0 Variable 8. 10. pointers to the operations to which the Variable is input pointer to the operation of which the Variable is output of if tracker is enabled, computation graph will be updated if tracker is enabled, computation graph will be updated if tracker is enabled, computation graph will be updated if tracker is enabled, computation graph will be updated if tracker is enabled, computation graph will be updated if tracker is enabled, computation graph will be updated Class represents operation between single or two Variable objects. Operation objects contains type of operation, pointers to input Variable objects and pointer to resulting Variable from the operation. Class contains methods to compute partial derivatives of Variable based on the computation graph. Examples: with GradientTracker as tracker: ... a Variable2.0, 5.0 ... b Variable1.0, 2.0 ... m Variable1.0, 2.0 ... c a b ... d a b ... e c d tracker.gradiente, a array0.25, 0.04 tracker.gradiente, b array1. , 0.25 tracker.gradiente, m is None True with GradientTracker as tracker: ... a Variable2.0, 5.0 ... b Variable1.0, 2.0 ... c a b tracker.gradientc, a array1., 2. tracker.gradientc, b array2., 5. with GradientTracker as tracker: ... a Variable2.0, 5.0 ... b a 3 tracker.gradientb, a array12., 75. Executes at the creation of class object and returns if object is already created. This class follows singleton design pattern. Adds Operation object to the related Variable objects for creating computational graph for calculating gradients. Args: optype: Operation type params: Input parameters to the operation output: Output variable of the operation Reverse accumulation of partial derivatives to calculate gradients of target variable with respect to source variable. Args: target: target variable for which gradients are calculated. source: source variable with respect to which the gradients are calculated. Returns: Gradient of the source variable with respect to the target variable partial derivatives with respect to target iterating through each operations in the computation graph as per the chain rule, multiplying partial derivatives of variables with respect to the target Compute the derivative of given operationfunction Args: param: variable to be differentiated operation: function performed on the input variable Returns: Derivative of input variable with respect to the output of the operation","Completions":"from __future__ import annotations\n\nfrom collections import defaultdict\nfrom enum import Enum\nfrom types import TracebackType\nfrom typing import Any\n\nimport numpy as np\nfrom typing_extensions import Self # noqa: UP035\n\n\nclass OpType(Enum):\n \"\"\"\n Class represents list of supported operations on Variable for gradient calculation.\n \"\"\"\n\n ADD = 0\n SUB = 1\n MUL = 2\n DIV = 3\n MATMUL = 4\n POWER = 5\n NOOP = 6\n\n\nclass Variable:\n \"\"\"\n Class represents n-dimensional object which is used to wrap numpy array on which\n operations will be performed and the gradient will be calculated.\n\n Examples:\n >>> Variable(5.0)\n Variable(5.0)\n >>> Variable([5.0, 2.9])\n Variable([5. 2.9])\n >>> Variable([5.0, 2.9]) + Variable([1.0, 5.5])\n Variable([6. 8.4])\n >>> Variable([[8.0, 10.0]])\n Variable([[ 8. 10.]])\n \"\"\"\n\n def __init__(self, value: Any) -> None:\n self.value = np.array(value)\n\n # pointers to the operations to which the Variable is input\n self.param_to: list[Operation] = []\n # pointer to the operation of which the Variable is output of\n self.result_of: Operation = Operation(OpType.NOOP)\n\n def __repr__(self) -> str:\n return f\"Variable({self.value})\"\n\n def to_ndarray(self) -> np.ndarray:\n return self.value\n\n def __add__(self, other: Variable) -> Variable:\n result = Variable(self.value + other.value)\n\n with GradientTracker() as tracker:\n # if tracker is enabled, computation graph will be updated\n if tracker.enabled:\n tracker.append(OpType.ADD, params=[self, other], output=result)\n return result\n\n def __sub__(self, other: Variable) -> Variable:\n result = Variable(self.value - other.value)\n\n with GradientTracker() as tracker:\n # if tracker is enabled, computation graph will be updated\n if tracker.enabled:\n tracker.append(OpType.SUB, params=[self, other], output=result)\n return result\n\n def __mul__(self, other: Variable) -> Variable:\n result = Variable(self.value * other.value)\n\n with GradientTracker() as tracker:\n # if tracker is enabled, computation graph will be updated\n if tracker.enabled:\n tracker.append(OpType.MUL, params=[self, other], output=result)\n return result\n\n def __truediv__(self, other: Variable) -> Variable:\n result = Variable(self.value \/ other.value)\n\n with GradientTracker() as tracker:\n # if tracker is enabled, computation graph will be updated\n if tracker.enabled:\n tracker.append(OpType.DIV, params=[self, other], output=result)\n return result\n\n def __matmul__(self, other: Variable) -> Variable:\n result = Variable(self.value @ other.value)\n\n with GradientTracker() as tracker:\n # if tracker is enabled, computation graph will be updated\n if tracker.enabled:\n tracker.append(OpType.MATMUL, params=[self, other], output=result)\n return result\n\n def __pow__(self, power: int) -> Variable:\n result = Variable(self.value**power)\n\n with GradientTracker() as tracker:\n # if tracker is enabled, computation graph will be updated\n if tracker.enabled:\n tracker.append(\n OpType.POWER,\n params=[self],\n output=result,\n other_params={\"power\": power},\n )\n return result\n\n def add_param_to(self, param_to: Operation) -> None:\n self.param_to.append(param_to)\n\n def add_result_of(self, result_of: Operation) -> None:\n self.result_of = result_of\n\n\nclass Operation:\n \"\"\"\n Class represents operation between single or two Variable objects.\n Operation objects contains type of operation, pointers to input Variable\n objects and pointer to resulting Variable from the operation.\n \"\"\"\n\n def __init__(\n self,\n op_type: OpType,\n other_params: dict | None = None,\n ) -> None:\n self.op_type = op_type\n self.other_params = {} if other_params is None else other_params\n\n def add_params(self, params: list[Variable]) -> None:\n self.params = params\n\n def add_output(self, output: Variable) -> None:\n self.output = output\n\n def __eq__(self, value) -> bool:\n return self.op_type == value if isinstance(value, OpType) else False\n\n\nclass GradientTracker:\n \"\"\"\n Class contains methods to compute partial derivatives of Variable\n based on the computation graph.\n\n Examples:\n\n >>> with GradientTracker() as tracker:\n ... a = Variable([2.0, 5.0])\n ... b = Variable([1.0, 2.0])\n ... m = Variable([1.0, 2.0])\n ... c = a + b\n ... d = a * b\n ... e = c \/ d\n >>> tracker.gradient(e, a)\n array([-0.25, -0.04])\n >>> tracker.gradient(e, b)\n array([-1. , -0.25])\n >>> tracker.gradient(e, m) is None\n True\n\n >>> with GradientTracker() as tracker:\n ... a = Variable([[2.0, 5.0]])\n ... b = Variable([[1.0], [2.0]])\n ... c = a @ b\n >>> tracker.gradient(c, a)\n array([[1., 2.]])\n >>> tracker.gradient(c, b)\n array([[2.],\n [5.]])\n\n >>> with GradientTracker() as tracker:\n ... a = Variable([[2.0, 5.0]])\n ... b = a ** 3\n >>> tracker.gradient(b, a)\n array([[12., 75.]])\n \"\"\"\n\n instance = None\n\n def __new__(cls) -> Self:\n \"\"\"\n Executes at the creation of class object and returns if\n object is already created. This class follows singleton\n design pattern.\n \"\"\"\n if cls.instance is None:\n cls.instance = super().__new__(cls)\n return cls.instance\n\n def __init__(self) -> None:\n self.enabled = False\n\n def __enter__(self) -> Self:\n self.enabled = True\n return self\n\n def __exit__(\n self,\n exc_type: type[BaseException] | None,\n exc: BaseException | None,\n traceback: TracebackType | None,\n ) -> None:\n self.enabled = False\n\n def append(\n self,\n op_type: OpType,\n params: list[Variable],\n output: Variable,\n other_params: dict | None = None,\n ) -> None:\n \"\"\"\n Adds Operation object to the related Variable objects for\n creating computational graph for calculating gradients.\n\n Args:\n op_type: Operation type\n params: Input parameters to the operation\n output: Output variable of the operation\n \"\"\"\n operation = Operation(op_type, other_params=other_params)\n param_nodes = []\n for param in params:\n param.add_param_to(operation)\n param_nodes.append(param)\n output.add_result_of(operation)\n\n operation.add_params(param_nodes)\n operation.add_output(output)\n\n def gradient(self, target: Variable, source: Variable) -> np.ndarray | None:\n \"\"\"\n Reverse accumulation of partial derivatives to calculate gradients\n of target variable with respect to source variable.\n\n Args:\n target: target variable for which gradients are calculated.\n source: source variable with respect to which the gradients are\n calculated.\n\n Returns:\n Gradient of the source variable with respect to the target variable\n \"\"\"\n\n # partial derivatives with respect to target\n partial_deriv = defaultdict(lambda: 0)\n partial_deriv[target] = np.ones_like(target.to_ndarray())\n\n # iterating through each operations in the computation graph\n operation_queue = [target.result_of]\n while len(operation_queue) > 0:\n operation = operation_queue.pop()\n for param in operation.params:\n # as per the chain rule, multiplying partial derivatives\n # of variables with respect to the target\n dparam_doutput = self.derivative(param, operation)\n dparam_dtarget = dparam_doutput * partial_deriv[operation.output]\n partial_deriv[param] += dparam_dtarget\n\n if param.result_of and param.result_of != OpType.NOOP:\n operation_queue.append(param.result_of)\n\n return partial_deriv.get(source)\n\n def derivative(self, param: Variable, operation: Operation) -> np.ndarray:\n \"\"\"\n Compute the derivative of given operation\/function\n\n Args:\n param: variable to be differentiated\n operation: function performed on the input variable\n\n Returns:\n Derivative of input variable with respect to the output of\n the operation\n \"\"\"\n params = operation.params\n\n if operation == OpType.ADD:\n return np.ones_like(params[0].to_ndarray(), dtype=np.float64)\n if operation == OpType.SUB:\n if params[0] == param:\n return np.ones_like(params[0].to_ndarray(), dtype=np.float64)\n return -np.ones_like(params[1].to_ndarray(), dtype=np.float64)\n if operation == OpType.MUL:\n return (\n params[1].to_ndarray().T\n if params[0] == param\n else params[0].to_ndarray().T\n )\n if operation == OpType.DIV:\n if params[0] == param:\n return 1 \/ params[1].to_ndarray()\n return -params[0].to_ndarray() \/ (params[1].to_ndarray() ** 2)\n if operation == OpType.MATMUL:\n return (\n params[1].to_ndarray().T\n if params[0] == param\n else params[0].to_ndarray().T\n )\n if operation == OpType.POWER:\n power = operation.other_params[\"power\"]\n return power * (params[0].to_ndarray() ** (power - 1))\n\n err_msg = f\"invalid operation type: {operation.op_type}\"\n raise ValueError(err_msg)\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Normalization. Wikipedia: https:en.wikipedia.orgwikiNormalization Normalization is the process of converting numerical data to a standard range of values. This range is typically between 0, 1 or 1, 1. The equation for normalization is xnorm x xminxmax xmin where xnorm is the normalized value, x is the value, xmin is the minimum value within the column or list of data, and xmax is the maximum value within the column or list of data. Normalization is used to speed up the training of data and put all of the data on a similar scale. This is useful because variance in the range of values of a dataset can heavily impact optimization particularly Gradient Descent. Standardization Wikipedia: https:en.wikipedia.orgwikiStandardization Standardization is the process of converting numerical data to a normally distributed range of values. This range will have a mean of 0 and standard deviation of 1. This is also known as zscore normalization. The equation for standardization is xstd x musigma where mu is the mean of the column or list of values and sigma is the standard deviation of the column or list of values. Choosing between Normalization Standardization is more of an art of a science, but it is often recommended to run experiments with both to see which performs better. Additionally, a few rules of thumb are: 1. gaussian normal distributions work better with standardization 2. nongaussian nonnormal distributions work better with normalization 3. If a column or list of values has extreme values outliers, use standardization Return a normalized list of values. params: data, a list of values to normalize returns: a list of normalized values rounded to ndigits decimal places examples: normalization2, 7, 10, 20, 30, 50 0.0, 0.104, 0.167, 0.375, 0.583, 1.0 normalization5, 10, 15, 20, 25 0.0, 0.25, 0.5, 0.75, 1.0 variables for calculation normalize data Return a standardized list of values. params: data, a list of values to standardize returns: a list of standardized values rounded to ndigits decimal places examples: standardization2, 7, 10, 20, 30, 50 0.999, 0.719, 0.551, 0.009, 0.57, 1.69 standardization5, 10, 15, 20, 25 1.265, 0.632, 0.0, 0.632, 1.265 variables for calculation standardize data","Completions":"from statistics import mean, stdev\n\n\ndef normalization(data: list, ndigits: int = 3) -> list:\n \"\"\"\n Return a normalized list of values.\n\n @params: data, a list of values to normalize\n @returns: a list of normalized values (rounded to ndigits decimal places)\n @examples:\n >>> normalization([2, 7, 10, 20, 30, 50])\n [0.0, 0.104, 0.167, 0.375, 0.583, 1.0]\n >>> normalization([5, 10, 15, 20, 25])\n [0.0, 0.25, 0.5, 0.75, 1.0]\n \"\"\"\n # variables for calculation\n x_min = min(data)\n x_max = max(data)\n # normalize data\n return [round((x - x_min) \/ (x_max - x_min), ndigits) for x in data]\n\n\ndef standardization(data: list, ndigits: int = 3) -> list:\n \"\"\"\n Return a standardized list of values.\n\n @params: data, a list of values to standardize\n @returns: a list of standardized values (rounded to ndigits decimal places)\n @examples:\n >>> standardization([2, 7, 10, 20, 30, 50])\n [-0.999, -0.719, -0.551, 0.009, 0.57, 1.69]\n >>> standardization([5, 10, 15, 20, 25])\n [-1.265, -0.632, 0.0, 0.632, 1.265]\n \"\"\"\n # variables for calculation\n mu = mean(data)\n sigma = stdev(data)\n # standardize data\n return [round((x - mu) \/ (sigma), ndigits) for x in data]\n"} +{"Prompt":"Implementation of a basic regression decision tree. Input data set: The input data set must be 1dimensional with continuous labels. Output: The decision tree maps a real number input to a real number output. meansquarederror: param labels: a onedimensional numpy array param prediction: a floating point value return value: meansquarederror calculates the error if prediction is used to estimate the labels tester DecisionTree testlabels np.array1,2,3,4,5,6,7,8,9,10 testprediction float6 tester.meansquarederrortestlabels, testprediction ... TestDecisionTree.helpermeansquarederrortesttestlabels, ... testprediction True testlabels np.array1,2,3 testprediction float2 tester.meansquarederrortestlabels, testprediction ... TestDecisionTree.helpermeansquarederrortesttestlabels, ... testprediction True train: param x: a onedimensional numpy array param y: a onedimensional numpy array. The contents of y are the labels for the corresponding X values train does not have a return value Examples: 1. Try to train when x y are of same length 1 dimensions No errors dt DecisionTree dt.trainnp.array10,20,30,40,50,np.array0,0,0,1,1 2. Try to train when x is 2 dimensions dt DecisionTree dt.trainnp.array1,2,3,4,5,1,2,3,4,5,np.array0,0,0,1,1 Traceback most recent call last: ... ValueError: Input data set must be onedimensional 3. Try to train when x and y are not of the same length dt DecisionTree dt.trainnp.array1,2,3,4,5,np.array0,0,0,1,1,0,0,0,1,1 Traceback most recent call last: ... ValueError: x and y have different lengths 4. Try to train when x y are of the same length but different dimensions dt DecisionTree dt.trainnp.array1,2,3,4,5,np.array1,2,3,4,5 Traceback most recent call last: ... ValueError: Data set labels must be onedimensional This section is to check that the inputs conform to our dimensionality constraints loop over all possible splits for the decision tree. find the best split. if no split exists that is less than 2 error for the entire array then the data set is not split and the average for the entire array is used as the predictor predict: param x: a floating point value to predict the label of the prediction function works by recursively calling the predict function of the appropriate subtrees based on the tree's decision boundary Decision Tres test class staticmethod def helpermeansquarederrortestlabels, prediction: squarederrorsum float0 for label in labels: squarederrorsum label prediction 2 return floatsquarederrorsum labels.size def main: x np.arange1.0, 1.0, 0.005 y np.sinx tree DecisionTreedepth10, minleafsize10 tree.trainx, y testcases np.random.rand10 2 1 predictions np.arraytree.predictx for x in testcases avgerror np.meanpredictions testcases 2 printTest values: strtestcases printPredictions: strpredictions printAverage error: stravgerror if name main: main import doctest doctest.testmodnamemeansquarrederror, verboseTrue","Completions":"import numpy as np\n\n\nclass DecisionTree:\n def __init__(self, depth=5, min_leaf_size=5):\n self.depth = depth\n self.decision_boundary = 0\n self.left = None\n self.right = None\n self.min_leaf_size = min_leaf_size\n self.prediction = None\n\n def mean_squared_error(self, labels, prediction):\n \"\"\"\n mean_squared_error:\n @param labels: a one-dimensional numpy array\n @param prediction: a floating point value\n return value: mean_squared_error calculates the error if prediction is used to\n estimate the labels\n >>> tester = DecisionTree()\n >>> test_labels = np.array([1,2,3,4,5,6,7,8,9,10])\n >>> test_prediction = float(6)\n >>> tester.mean_squared_error(test_labels, test_prediction) == (\n ... TestDecisionTree.helper_mean_squared_error_test(test_labels,\n ... test_prediction))\n True\n >>> test_labels = np.array([1,2,3])\n >>> test_prediction = float(2)\n >>> tester.mean_squared_error(test_labels, test_prediction) == (\n ... TestDecisionTree.helper_mean_squared_error_test(test_labels,\n ... test_prediction))\n True\n \"\"\"\n if labels.ndim != 1:\n print(\"Error: Input labels must be one dimensional\")\n\n return np.mean((labels - prediction) ** 2)\n\n def train(self, x, y):\n \"\"\"\n train:\n @param x: a one-dimensional numpy array\n @param y: a one-dimensional numpy array.\n The contents of y are the labels for the corresponding X values\n\n train() does not have a return value\n\n Examples:\n 1. Try to train when x & y are of same length & 1 dimensions (No errors)\n >>> dt = DecisionTree()\n >>> dt.train(np.array([10,20,30,40,50]),np.array([0,0,0,1,1]))\n\n 2. Try to train when x is 2 dimensions\n >>> dt = DecisionTree()\n >>> dt.train(np.array([[1,2,3,4,5],[1,2,3,4,5]]),np.array([0,0,0,1,1]))\n Traceback (most recent call last):\n ...\n ValueError: Input data set must be one-dimensional\n\n 3. Try to train when x and y are not of the same length\n >>> dt = DecisionTree()\n >>> dt.train(np.array([1,2,3,4,5]),np.array([[0,0,0,1,1],[0,0,0,1,1]]))\n Traceback (most recent call last):\n ...\n ValueError: x and y have different lengths\n\n 4. Try to train when x & y are of the same length but different dimensions\n >>> dt = DecisionTree()\n >>> dt.train(np.array([1,2,3,4,5]),np.array([[1],[2],[3],[4],[5]]))\n Traceback (most recent call last):\n ...\n ValueError: Data set labels must be one-dimensional\n\n This section is to check that the inputs conform to our dimensionality\n constraints\n \"\"\"\n if x.ndim != 1:\n raise ValueError(\"Input data set must be one-dimensional\")\n if len(x) != len(y):\n raise ValueError(\"x and y have different lengths\")\n if y.ndim != 1:\n raise ValueError(\"Data set labels must be one-dimensional\")\n\n if len(x) < 2 * self.min_leaf_size:\n self.prediction = np.mean(y)\n return\n\n if self.depth == 1:\n self.prediction = np.mean(y)\n return\n\n best_split = 0\n min_error = self.mean_squared_error(x, np.mean(y)) * 2\n\n \"\"\"\n loop over all possible splits for the decision tree. find the best split.\n if no split exists that is less than 2 * error for the entire array\n then the data set is not split and the average for the entire array is used as\n the predictor\n \"\"\"\n for i in range(len(x)):\n if len(x[:i]) < self.min_leaf_size:\n continue\n elif len(x[i:]) < self.min_leaf_size:\n continue\n else:\n error_left = self.mean_squared_error(x[:i], np.mean(y[:i]))\n error_right = self.mean_squared_error(x[i:], np.mean(y[i:]))\n error = error_left + error_right\n if error < min_error:\n best_split = i\n min_error = error\n\n if best_split != 0:\n left_x = x[:best_split]\n left_y = y[:best_split]\n right_x = x[best_split:]\n right_y = y[best_split:]\n\n self.decision_boundary = x[best_split]\n self.left = DecisionTree(\n depth=self.depth - 1, min_leaf_size=self.min_leaf_size\n )\n self.right = DecisionTree(\n depth=self.depth - 1, min_leaf_size=self.min_leaf_size\n )\n self.left.train(left_x, left_y)\n self.right.train(right_x, right_y)\n else:\n self.prediction = np.mean(y)\n\n return\n\n def predict(self, x):\n \"\"\"\n predict:\n @param x: a floating point value to predict the label of\n the prediction function works by recursively calling the predict function\n of the appropriate subtrees based on the tree's decision boundary\n \"\"\"\n if self.prediction is not None:\n return self.prediction\n elif self.left or self.right is not None:\n if x >= self.decision_boundary:\n return self.right.predict(x)\n else:\n return self.left.predict(x)\n else:\n print(\"Error: Decision tree not yet trained\")\n return None\n\n\nclass TestDecisionTree:\n \"\"\"Decision Tres test class\"\"\"\n\n @staticmethod\n def helper_mean_squared_error_test(labels, prediction):\n \"\"\"\n helper_mean_squared_error_test:\n @param labels: a one dimensional numpy array\n @param prediction: a floating point value\n return value: helper_mean_squared_error_test calculates the mean squared error\n \"\"\"\n squared_error_sum = float(0)\n for label in labels:\n squared_error_sum += (label - prediction) ** 2\n\n return float(squared_error_sum \/ labels.size)\n\n\ndef main():\n \"\"\"\n In this demonstration we're generating a sample data set from the sin function in\n numpy. We then train a decision tree on the data set and use the decision tree to\n predict the label of 10 different test values. Then the mean squared error over\n this test is displayed.\n \"\"\"\n x = np.arange(-1.0, 1.0, 0.005)\n y = np.sin(x)\n\n tree = DecisionTree(depth=10, min_leaf_size=10)\n tree.train(x, y)\n\n test_cases = (np.random.rand(10) * 2) - 1\n predictions = np.array([tree.predict(x) for x in test_cases])\n avg_error = np.mean((predictions - test_cases) ** 2)\n\n print(\"Test values: \" + str(test_cases))\n print(\"Predictions: \" + str(predictions))\n print(\"Average error: \" + str(avg_error))\n\n\nif __name__ == \"__main__\":\n main()\n import doctest\n\n doctest.testmod(name=\"mean_squarred_error\", verbose=True)\n"} +{"Prompt":"Copyright c 2023 Diego Gasco diego.gasco99gmail.com, Diegomangasco on GitHub Requirements: numpy version 1.21 scipy version 1.3.3 Notes: Each column of the features matrix corresponds to a class item Function to reshape a row Numpy array into a column Numpy array inputarray np.array1, 2, 3 columnreshapeinputarray array1, 2, 3 Function to compute the covariance matrix inside each class. features np.array1, 2, 3, 4, 5, 6, 7, 8, 9 labels np.array0, 1, 0 covariancewithinclassesfeatures, labels, 2 array0.66666667, 0.66666667, 0.66666667, 0.66666667, 0.66666667, 0.66666667, 0.66666667, 0.66666667, 0.66666667 Centralize the data of class i If covariancesum is not None If covariancesum is np.nan i.e. first loop Function to compute the covariance matrix between multiple classes features np.array9, 2, 3, 4, 3, 6, 1, 8, 9 labels np.array0, 1, 0 covariancebetweenclassesfeatures, labels, 2 array 3.55555556, 1.77777778, 2.66666667, 1.77777778, 0.88888889, 1.33333333, 2.66666667, 1.33333333, 2. If covariancesum is not None If covariancesum is np.nan i.e. first loop Principal Component Analysis. For more details, see: https:en.wikipedia.orgwikiPrincipalcomponentanalysis. Parameters: features: the features extracted from the dataset dimensions: to filter the projected data for the desired dimension testprincipalcomponentanalysis Check if the features have been loaded Center the dataset Take all the columns in the reverse order 1, and then takes only the first Project the database on the new space Linear Discriminant Analysis. For more details, see: https:en.wikipedia.orgwikiLineardiscriminantanalysis. Parameters: features: the features extracted from the dataset labels: the class labels of the features classes: the number of classes present in the dataset dimensions: to filter the projected data for the desired dimension testlineardiscriminantanalysis Check if the dimension desired is less than the number of classes Check if features have been already loaded Create dummy dataset with 2 classes and 3 features Assert that the function raises an AssertionError if dimensions classes","Completions":"# Copyright (c) 2023 Diego Gasco (diego.gasco99@gmail.com), Diegomangasco on GitHub\n\n\"\"\"\nRequirements:\n - numpy version 1.21\n - scipy version 1.3.3\nNotes:\n - Each column of the features matrix corresponds to a class item\n\"\"\"\n\nimport logging\n\nimport numpy as np\nimport pytest\nfrom scipy.linalg import eigh\n\nlogging.basicConfig(level=logging.INFO, format=\"%(message)s\")\n\n\ndef column_reshape(input_array: np.ndarray) -> np.ndarray:\n \"\"\"Function to reshape a row Numpy array into a column Numpy array\n >>> input_array = np.array([1, 2, 3])\n >>> column_reshape(input_array)\n array([[1],\n [2],\n [3]])\n \"\"\"\n\n return input_array.reshape((input_array.size, 1))\n\n\ndef covariance_within_classes(\n features: np.ndarray, labels: np.ndarray, classes: int\n) -> np.ndarray:\n \"\"\"Function to compute the covariance matrix inside each class.\n >>> features = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])\n >>> labels = np.array([0, 1, 0])\n >>> covariance_within_classes(features, labels, 2)\n array([[0.66666667, 0.66666667, 0.66666667],\n [0.66666667, 0.66666667, 0.66666667],\n [0.66666667, 0.66666667, 0.66666667]])\n \"\"\"\n\n covariance_sum = np.nan\n for i in range(classes):\n data = features[:, labels == i]\n data_mean = data.mean(1)\n # Centralize the data of class i\n centered_data = data - column_reshape(data_mean)\n if i > 0:\n # If covariance_sum is not None\n covariance_sum += np.dot(centered_data, centered_data.T)\n else:\n # If covariance_sum is np.nan (i.e. first loop)\n covariance_sum = np.dot(centered_data, centered_data.T)\n\n return covariance_sum \/ features.shape[1]\n\n\ndef covariance_between_classes(\n features: np.ndarray, labels: np.ndarray, classes: int\n) -> np.ndarray:\n \"\"\"Function to compute the covariance matrix between multiple classes\n >>> features = np.array([[9, 2, 3], [4, 3, 6], [1, 8, 9]])\n >>> labels = np.array([0, 1, 0])\n >>> covariance_between_classes(features, labels, 2)\n array([[ 3.55555556, 1.77777778, -2.66666667],\n [ 1.77777778, 0.88888889, -1.33333333],\n [-2.66666667, -1.33333333, 2. ]])\n \"\"\"\n\n general_data_mean = features.mean(1)\n covariance_sum = np.nan\n for i in range(classes):\n data = features[:, labels == i]\n device_data = data.shape[1]\n data_mean = data.mean(1)\n if i > 0:\n # If covariance_sum is not None\n covariance_sum += device_data * np.dot(\n column_reshape(data_mean) - column_reshape(general_data_mean),\n (column_reshape(data_mean) - column_reshape(general_data_mean)).T,\n )\n else:\n # If covariance_sum is np.nan (i.e. first loop)\n covariance_sum = device_data * np.dot(\n column_reshape(data_mean) - column_reshape(general_data_mean),\n (column_reshape(data_mean) - column_reshape(general_data_mean)).T,\n )\n\n return covariance_sum \/ features.shape[1]\n\n\ndef principal_component_analysis(features: np.ndarray, dimensions: int) -> np.ndarray:\n \"\"\"\n Principal Component Analysis.\n\n For more details, see: https:\/\/en.wikipedia.org\/wiki\/Principal_component_analysis.\n Parameters:\n * features: the features extracted from the dataset\n * dimensions: to filter the projected data for the desired dimension\n\n >>> test_principal_component_analysis()\n \"\"\"\n\n # Check if the features have been loaded\n if features.any():\n data_mean = features.mean(1)\n # Center the dataset\n centered_data = features - np.reshape(data_mean, (data_mean.size, 1))\n covariance_matrix = np.dot(centered_data, centered_data.T) \/ features.shape[1]\n _, eigenvectors = np.linalg.eigh(covariance_matrix)\n # Take all the columns in the reverse order (-1), and then takes only the first\n filtered_eigenvectors = eigenvectors[:, ::-1][:, 0:dimensions]\n # Project the database on the new space\n projected_data = np.dot(filtered_eigenvectors.T, features)\n logging.info(\"Principal Component Analysis computed\")\n\n return projected_data\n else:\n logging.basicConfig(level=logging.ERROR, format=\"%(message)s\", force=True)\n logging.error(\"Dataset empty\")\n raise AssertionError\n\n\ndef linear_discriminant_analysis(\n features: np.ndarray, labels: np.ndarray, classes: int, dimensions: int\n) -> np.ndarray:\n \"\"\"\n Linear Discriminant Analysis.\n\n For more details, see: https:\/\/en.wikipedia.org\/wiki\/Linear_discriminant_analysis.\n Parameters:\n * features: the features extracted from the dataset\n * labels: the class labels of the features\n * classes: the number of classes present in the dataset\n * dimensions: to filter the projected data for the desired dimension\n\n >>> test_linear_discriminant_analysis()\n \"\"\"\n\n # Check if the dimension desired is less than the number of classes\n assert classes > dimensions\n\n # Check if features have been already loaded\n if features.any:\n _, eigenvectors = eigh(\n covariance_between_classes(features, labels, classes),\n covariance_within_classes(features, labels, classes),\n )\n filtered_eigenvectors = eigenvectors[:, ::-1][:, :dimensions]\n svd_matrix, _, _ = np.linalg.svd(filtered_eigenvectors)\n filtered_svd_matrix = svd_matrix[:, 0:dimensions]\n projected_data = np.dot(filtered_svd_matrix.T, features)\n logging.info(\"Linear Discriminant Analysis computed\")\n\n return projected_data\n else:\n logging.basicConfig(level=logging.ERROR, format=\"%(message)s\", force=True)\n logging.error(\"Dataset empty\")\n raise AssertionError\n\n\ndef test_linear_discriminant_analysis() -> None:\n # Create dummy dataset with 2 classes and 3 features\n features = np.array([[1, 2, 3, 4, 5], [2, 3, 4, 5, 6], [3, 4, 5, 6, 7]])\n labels = np.array([0, 0, 0, 1, 1])\n classes = 2\n dimensions = 2\n\n # Assert that the function raises an AssertionError if dimensions > classes\n with pytest.raises(AssertionError) as error_info: # noqa: PT012\n projected_data = linear_discriminant_analysis(\n features, labels, classes, dimensions\n )\n if isinstance(projected_data, np.ndarray):\n raise AssertionError(\n \"Did not raise AssertionError for dimensions > classes\"\n )\n assert error_info.type is AssertionError\n\n\ndef test_principal_component_analysis() -> None:\n features = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])\n dimensions = 2\n expected_output = np.array([[6.92820323, 8.66025404, 10.39230485], [3.0, 3.0, 3.0]])\n\n with pytest.raises(AssertionError) as error_info: # noqa: PT012\n output = principal_component_analysis(features, dimensions)\n if not np.allclose(expected_output, output):\n raise AssertionError\n assert error_info.type is AssertionError\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"this is code for forecasting but I modified it and used it for safety checker of data for ex: you have an online shop and for some reason some data are missing the amount of data that u expected are not supposed to be then we can use it ps : 1. ofc we can use normal statistic method but in this case the data is quite absurd and only a little 2. ofc u can use this and modified it for forecasting purpose for the next 3 months sales or something, u can just adjust it for ur own purpose First method: linear regression input : training data date, totaluser, totalevent in list of float output : list of total user prediction in float n linearregressionprediction2,3,4,5, 5,3,4,6, 3,1,2,4, 2,1, 2,2 absn 5.0 1e6 Checking precision because of floating point errors True second method: Sarimax sarimax is a statistic method which using previous input and learn its pattern to predict future data input : training data totaluser, with exog data totalevent in list of float output : list of total user prediction in float sarimaxpredictor4,2,6,8, 3,1,2,4, 2 6.6666671111109626 Suppress the User Warning raised by SARIMAX due to insufficient observations Third method: Support vector regressor svr is quite the same with svmsupport vector machine it uses the same principles as the SVM for classification, with only a few minor differences and the only different is that it suits better for regression purpose input : training data date, totaluser, totalevent in list of float where x list of set date and total event output : list of total user prediction in float supportvectorregressor5,2,1,5,6,2, 3,2, 2,1,4 1.634932078116079 Optional method: interquatile range input : list of total user in float output : low limit of input in float this method can be used to check whether some data is outlier or not interquartilerangechecker1,2,3,4,5,6,7,8,9,10 2.8 Used to review all the votes list result prediction and compare it to the actual result. input : list of predictions output : print whether it's safe or not datasafetychecker2, 3, 4, 5.0 False data column total user in a day, how much online event held in one day, what day is thatsundaysaturday start normalization split data for svr input variable total date and total match for linear regression sarimax voting system with forecasting check the safety of today's data","Completions":"from warnings import simplefilter\n\nimport numpy as np\nimport pandas as pd\nfrom sklearn.preprocessing import Normalizer\nfrom sklearn.svm import SVR\nfrom statsmodels.tsa.statespace.sarimax import SARIMAX\n\n\ndef linear_regression_prediction(\n train_dt: list, train_usr: list, train_mtch: list, test_dt: list, test_mtch: list\n) -> float:\n \"\"\"\n First method: linear regression\n input : training data (date, total_user, total_event) in list of float\n output : list of total user prediction in float\n >>> n = linear_regression_prediction([2,3,4,5], [5,3,4,6], [3,1,2,4], [2,1], [2,2])\n >>> abs(n - 5.0) < 1e-6 # Checking precision because of floating point errors\n True\n \"\"\"\n x = np.array([[1, item, train_mtch[i]] for i, item in enumerate(train_dt)])\n y = np.array(train_usr)\n beta = np.dot(np.dot(np.linalg.inv(np.dot(x.transpose(), x)), x.transpose()), y)\n return abs(beta[0] + test_dt[0] * beta[1] + test_mtch[0] + beta[2])\n\n\ndef sarimax_predictor(train_user: list, train_match: list, test_match: list) -> float:\n \"\"\"\n second method: Sarimax\n sarimax is a statistic method which using previous input\n and learn its pattern to predict future data\n input : training data (total_user, with exog data = total_event) in list of float\n output : list of total user prediction in float\n >>> sarimax_predictor([4,2,6,8], [3,1,2,4], [2])\n 6.6666671111109626\n \"\"\"\n # Suppress the User Warning raised by SARIMAX due to insufficient observations\n simplefilter(\"ignore\", UserWarning)\n order = (1, 2, 1)\n seasonal_order = (1, 1, 1, 7)\n model = SARIMAX(\n train_user, exog=train_match, order=order, seasonal_order=seasonal_order\n )\n model_fit = model.fit(disp=False, maxiter=600, method=\"nm\")\n result = model_fit.predict(1, len(test_match), exog=[test_match])\n return result[0]\n\n\ndef support_vector_regressor(x_train: list, x_test: list, train_user: list) -> float:\n \"\"\"\n Third method: Support vector regressor\n svr is quite the same with svm(support vector machine)\n it uses the same principles as the SVM for classification,\n with only a few minor differences and the only different is that\n it suits better for regression purpose\n input : training data (date, total_user, total_event) in list of float\n where x = list of set (date and total event)\n output : list of total user prediction in float\n >>> support_vector_regressor([[5,2],[1,5],[6,2]], [[3,2]], [2,1,4])\n 1.634932078116079\n \"\"\"\n regressor = SVR(kernel=\"rbf\", C=1, gamma=0.1, epsilon=0.1)\n regressor.fit(x_train, train_user)\n y_pred = regressor.predict(x_test)\n return y_pred[0]\n\n\ndef interquartile_range_checker(train_user: list) -> float:\n \"\"\"\n Optional method: interquatile range\n input : list of total user in float\n output : low limit of input in float\n this method can be used to check whether some data is outlier or not\n >>> interquartile_range_checker([1,2,3,4,5,6,7,8,9,10])\n 2.8\n \"\"\"\n train_user.sort()\n q1 = np.percentile(train_user, 25)\n q3 = np.percentile(train_user, 75)\n iqr = q3 - q1\n low_lim = q1 - (iqr * 0.1)\n return low_lim\n\n\ndef data_safety_checker(list_vote: list, actual_result: float) -> bool:\n \"\"\"\n Used to review all the votes (list result prediction)\n and compare it to the actual result.\n input : list of predictions\n output : print whether it's safe or not\n >>> data_safety_checker([2, 3, 4], 5.0)\n False\n \"\"\"\n safe = 0\n not_safe = 0\n\n if not isinstance(actual_result, float):\n raise TypeError(\"Actual result should be float. Value passed is a list\")\n\n for i in list_vote:\n if i > actual_result:\n safe = not_safe + 1\n else:\n if abs(abs(i) - abs(actual_result)) <= 0.1:\n safe += 1\n else:\n not_safe += 1\n return safe > not_safe\n\n\nif __name__ == \"__main__\":\n \"\"\"\n data column = total user in a day, how much online event held in one day,\n what day is that(sunday-saturday)\n \"\"\"\n data_input_df = pd.read_csv(\"ex_data.csv\")\n\n # start normalization\n normalize_df = Normalizer().fit_transform(data_input_df.values)\n # split data\n total_date = normalize_df[:, 2].tolist()\n total_user = normalize_df[:, 0].tolist()\n total_match = normalize_df[:, 1].tolist()\n\n # for svr (input variable = total date and total match)\n x = normalize_df[:, [1, 2]].tolist()\n x_train = x[: len(x) - 1]\n x_test = x[len(x) - 1 :]\n\n # for linear regression & sarimax\n train_date = total_date[: len(total_date) - 1]\n train_user = total_user[: len(total_user) - 1]\n train_match = total_match[: len(total_match) - 1]\n\n test_date = total_date[len(total_date) - 1 :]\n test_user = total_user[len(total_user) - 1 :]\n test_match = total_match[len(total_match) - 1 :]\n\n # voting system with forecasting\n res_vote = [\n linear_regression_prediction(\n train_date, train_user, train_match, test_date, test_match\n ),\n sarimax_predictor(train_user, train_match, test_match),\n support_vector_regressor(x_train, x_test, train_user),\n ]\n\n # check the safety of today's data\n not_str = \"\" if data_safety_checker(res_vote, test_user[0]) else \"not \"\n print(f\"Today's data is {not_str}safe.\")\n"} +{"Prompt":"The Frequent Pattern Growth algorithm FPGrowth is a widely used data mining technique for discovering frequent itemsets in large transaction databases. It overcomes some of the limitations of traditional methods such as Apriori by efficiently constructing the FPTree WIKI: https:athena.ecs.csus.edumeiassociationcwFpGrowth.html Examples: https:www.javatpoint.comfpgrowthalgorithmindatamining A node in a Frequent Pattern tree. Args: name: The name of this node. numoccur: The number of occurrences of the node. parentnode: The parent node. Example: parent TreeNodeParent, 1, None child TreeNodeChild, 2, parent child.name 'Child' child.count 2 Create Frequent Pattern tree Args: dataset: A list of transactions, where each transaction is a list of items. minsup: The minimum support threshold. Items with support less than this will be pruned. Default is 1. Returns: The root of the FPTree. headertable: The header table dictionary with item information. Example: dataset ... 'A', 'B', 'C', ... 'A', 'C', ... 'A', 'B', 'E', ... 'A', 'B', 'C', 'E', ... 'B', 'E' ... minsup 2 fptree, headertable createtreedataset, minsup fptree TreeNode'Null Set', 1, None lenheadertable 4 headertableA 4, None, TreeNode'A', 4, TreeNode'Null Set', 1, None headertableE1 doctest: NORMALIZEWHITESPACE TreeNode'E', 1, TreeNode'B', 3, TreeNode'A', 4, TreeNode'Null Set', 1, None sortedheadertable 'A', 'B', 'C', 'E' fptree.name 'Null Set' sortedfptree.children 'A', 'B' fptree.children'A'.name 'A' sortedfptree.children'A'.children 'B', 'C' Update the FPTree with a transaction. Args: items: List of items in the transaction. intree: The current node in the FPTree. headertable: The header table dictionary with item information. count: The count of the transaction. Example: dataset ... 'A', 'B', 'C', ... 'A', 'C', ... 'A', 'B', 'E', ... 'A', 'B', 'C', 'E', ... 'B', 'E' ... minsup 2 fptree, headertable createtreedataset, minsup fptree TreeNode'Null Set', 1, None transaction 'A', 'B', 'E' updatetreetransaction, fptree, headertable, 1 fptree TreeNode'Null Set', 1, None fptree.children'A'.children'B'.children'E'.children fptree.children'A'.children'B'.children'E'.count 2 headertable'E'1.name 'E' Update the header table with a node link. Args: nodetotest: The node to be updated in the header table. targetnode: The node to link to. Example: dataset ... 'A', 'B', 'C', ... 'A', 'C', ... 'A', 'B', 'E', ... 'A', 'B', 'C', 'E', ... 'B', 'E' ... minsup 2 fptree, headertable createtreedataset, minsup fptree TreeNode'Null Set', 1, None node1 TreeNodeA, 3, None node2 TreeNodeB, 4, None node1 TreeNode'A', 3, None node1 updateheadernode1, node2 node1 TreeNode'A', 3, None node1.nodelink TreeNode'B', 4, None node2.nodelink is None True Return the updated node Ascend the FPTree from a leaf node to its root, adding item names to the prefix path. Args: leafnode: The leaf node to start ascending from. prefixpath: A list to store the item as they are ascended. Example: dataset ... 'A', 'B', 'C', ... 'A', 'C', ... 'A', 'B', 'E', ... 'A', 'B', 'C', 'E', ... 'B', 'E' ... minsup 2 fptree, headertable createtreedataset, minsup path ascendtreefptree.children'A', path path ascending from a leaf node 'A' 'A' Find the conditional pattern base for a given base pattern. Args: basepat: The base pattern for which to find the conditional pattern base. treenode: The node in the FPTree. Example: dataset ... 'A', 'B', 'C', ... 'A', 'C', ... 'A', 'B', 'E', ... 'A', 'B', 'C', 'E', ... 'B', 'E' ... minsup 2 fptree, headertable createtreedataset, minsup fptree TreeNode'Null Set', 1, None lenheadertable 4 basepattern frozenset'A' sortedfindprefixpathbasepattern, fptree.children'A' Mine the FPTree recursively to discover frequent itemsets. Args: intree: The FPTree to mine. headertable: The header table dictionary with item information. minsup: The minimum support threshold. prefix: A set of items as a prefix for the itemsets being mined. freqitemlist: A list to store the frequent itemsets. Example: dataset ... 'A', 'B', 'C', ... 'A', 'C', ... 'A', 'B', 'E', ... 'A', 'B', 'C', 'E', ... 'B', 'E' ... minsup 2 fptree, headertable createtreedataset, minsup fptree TreeNode'Null Set', 1, None frequentitemsets minetreefptree, headertable, minsup, set, frequentitemsets expeitm 'C', 'C', 'A', 'E', 'A', 'E', 'E', 'B', 'A', 'B' allexpected in frequentitemsets for expected in expeitm True Pass headertablebasepat1 as nodetotest to updateheader","Completions":"from __future__ import annotations\n\nfrom dataclasses import dataclass, field\n\n\n@dataclass\nclass TreeNode:\n \"\"\"\n A node in a Frequent Pattern tree.\n\n Args:\n name: The name of this node.\n num_occur: The number of occurrences of the node.\n parent_node: The parent node.\n\n Example:\n >>> parent = TreeNode(\"Parent\", 1, None)\n >>> child = TreeNode(\"Child\", 2, parent)\n >>> child.name\n 'Child'\n >>> child.count\n 2\n \"\"\"\n\n name: str\n count: int\n parent: TreeNode | None = None\n children: dict[str, TreeNode] = field(default_factory=dict)\n node_link: TreeNode | None = None\n\n def __repr__(self) -> str:\n return f\"TreeNode({self.name!r}, {self.count!r}, {self.parent!r})\"\n\n def inc(self, num_occur: int) -> None:\n self.count += num_occur\n\n def disp(self, ind: int = 1) -> None:\n print(f\"{' ' * ind} {self.name} {self.count}\")\n for child in self.children.values():\n child.disp(ind + 1)\n\n\ndef create_tree(data_set: list, min_sup: int = 1) -> tuple[TreeNode, dict]:\n \"\"\"\n Create Frequent Pattern tree\n\n Args:\n data_set: A list of transactions, where each transaction is a list of items.\n min_sup: The minimum support threshold.\n Items with support less than this will be pruned. Default is 1.\n\n Returns:\n The root of the FP-Tree.\n header_table: The header table dictionary with item information.\n\n Example:\n >>> data_set = [\n ... ['A', 'B', 'C'],\n ... ['A', 'C'],\n ... ['A', 'B', 'E'],\n ... ['A', 'B', 'C', 'E'],\n ... ['B', 'E']\n ... ]\n >>> min_sup = 2\n >>> fp_tree, header_table = create_tree(data_set, min_sup)\n >>> fp_tree\n TreeNode('Null Set', 1, None)\n >>> len(header_table)\n 4\n >>> header_table[\"A\"]\n [[4, None], TreeNode('A', 4, TreeNode('Null Set', 1, None))]\n >>> header_table[\"E\"][1] # doctest: +NORMALIZE_WHITESPACE\n TreeNode('E', 1, TreeNode('B', 3, TreeNode('A', 4, TreeNode('Null Set', 1, None))))\n >>> sorted(header_table)\n ['A', 'B', 'C', 'E']\n >>> fp_tree.name\n 'Null Set'\n >>> sorted(fp_tree.children)\n ['A', 'B']\n >>> fp_tree.children['A'].name\n 'A'\n >>> sorted(fp_tree.children['A'].children)\n ['B', 'C']\n \"\"\"\n header_table: dict = {}\n for trans in data_set:\n for item in trans:\n header_table[item] = header_table.get(item, [0, None])\n header_table[item][0] += 1\n\n for k in list(header_table):\n if header_table[k][0] < min_sup:\n del header_table[k]\n\n if not (freq_item_set := set(header_table)):\n return TreeNode(\"Null Set\", 1, None), {}\n\n for k in header_table:\n header_table[k] = [header_table[k], None]\n\n fp_tree = TreeNode(\"Null Set\", 1, None) # Parent is None for the root node\n for tran_set in data_set:\n local_d = {\n item: header_table[item][0] for item in tran_set if item in freq_item_set\n }\n if local_d:\n sorted_items = sorted(\n local_d.items(), key=lambda item_info: item_info[1], reverse=True\n )\n ordered_items = [item[0] for item in sorted_items]\n update_tree(ordered_items, fp_tree, header_table, 1)\n\n return fp_tree, header_table\n\n\ndef update_tree(items: list, in_tree: TreeNode, header_table: dict, count: int) -> None:\n \"\"\"\n Update the FP-Tree with a transaction.\n\n Args:\n items: List of items in the transaction.\n in_tree: The current node in the FP-Tree.\n header_table: The header table dictionary with item information.\n count: The count of the transaction.\n\n Example:\n >>> data_set = [\n ... ['A', 'B', 'C'],\n ... ['A', 'C'],\n ... ['A', 'B', 'E'],\n ... ['A', 'B', 'C', 'E'],\n ... ['B', 'E']\n ... ]\n >>> min_sup = 2\n >>> fp_tree, header_table = create_tree(data_set, min_sup)\n >>> fp_tree\n TreeNode('Null Set', 1, None)\n >>> transaction = ['A', 'B', 'E']\n >>> update_tree(transaction, fp_tree, header_table, 1)\n >>> fp_tree\n TreeNode('Null Set', 1, None)\n >>> fp_tree.children['A'].children['B'].children['E'].children\n {}\n >>> fp_tree.children['A'].children['B'].children['E'].count\n 2\n >>> header_table['E'][1].name\n 'E'\n \"\"\"\n if items[0] in in_tree.children:\n in_tree.children[items[0]].inc(count)\n else:\n in_tree.children[items[0]] = TreeNode(items[0], count, in_tree)\n if header_table[items[0]][1] is None:\n header_table[items[0]][1] = in_tree.children[items[0]]\n else:\n update_header(header_table[items[0]][1], in_tree.children[items[0]])\n if len(items) > 1:\n update_tree(items[1:], in_tree.children[items[0]], header_table, count)\n\n\ndef update_header(node_to_test: TreeNode, target_node: TreeNode) -> TreeNode:\n \"\"\"\n Update the header table with a node link.\n\n Args:\n node_to_test: The node to be updated in the header table.\n target_node: The node to link to.\n\n Example:\n >>> data_set = [\n ... ['A', 'B', 'C'],\n ... ['A', 'C'],\n ... ['A', 'B', 'E'],\n ... ['A', 'B', 'C', 'E'],\n ... ['B', 'E']\n ... ]\n >>> min_sup = 2\n >>> fp_tree, header_table = create_tree(data_set, min_sup)\n >>> fp_tree\n TreeNode('Null Set', 1, None)\n >>> node1 = TreeNode(\"A\", 3, None)\n >>> node2 = TreeNode(\"B\", 4, None)\n >>> node1\n TreeNode('A', 3, None)\n >>> node1 = update_header(node1, node2)\n >>> node1\n TreeNode('A', 3, None)\n >>> node1.node_link\n TreeNode('B', 4, None)\n >>> node2.node_link is None\n True\n \"\"\"\n while node_to_test.node_link is not None:\n node_to_test = node_to_test.node_link\n if node_to_test.node_link is None:\n node_to_test.node_link = target_node\n # Return the updated node\n return node_to_test\n\n\ndef ascend_tree(leaf_node: TreeNode, prefix_path: list[str]) -> None:\n \"\"\"\n Ascend the FP-Tree from a leaf node to its root, adding item names to the prefix\n path.\n\n Args:\n leaf_node: The leaf node to start ascending from.\n prefix_path: A list to store the item as they are ascended.\n\n Example:\n >>> data_set = [\n ... ['A', 'B', 'C'],\n ... ['A', 'C'],\n ... ['A', 'B', 'E'],\n ... ['A', 'B', 'C', 'E'],\n ... ['B', 'E']\n ... ]\n >>> min_sup = 2\n >>> fp_tree, header_table = create_tree(data_set, min_sup)\n\n >>> path = []\n >>> ascend_tree(fp_tree.children['A'], path)\n >>> path # ascending from a leaf node 'A'\n ['A']\n \"\"\"\n if leaf_node.parent is not None:\n prefix_path.append(leaf_node.name)\n ascend_tree(leaf_node.parent, prefix_path)\n\n\ndef find_prefix_path(base_pat: frozenset, tree_node: TreeNode | None) -> dict:\n \"\"\"\n Find the conditional pattern base for a given base pattern.\n\n Args:\n base_pat: The base pattern for which to find the conditional pattern base.\n tree_node: The node in the FP-Tree.\n\n Example:\n >>> data_set = [\n ... ['A', 'B', 'C'],\n ... ['A', 'C'],\n ... ['A', 'B', 'E'],\n ... ['A', 'B', 'C', 'E'],\n ... ['B', 'E']\n ... ]\n >>> min_sup = 2\n >>> fp_tree, header_table = create_tree(data_set, min_sup)\n >>> fp_tree\n TreeNode('Null Set', 1, None)\n >>> len(header_table)\n 4\n >>> base_pattern = frozenset(['A'])\n >>> sorted(find_prefix_path(base_pattern, fp_tree.children['A']))\n []\n \"\"\"\n cond_pats: dict = {}\n while tree_node is not None:\n prefix_path: list = []\n ascend_tree(tree_node, prefix_path)\n if len(prefix_path) > 1:\n cond_pats[frozenset(prefix_path[1:])] = tree_node.count\n tree_node = tree_node.node_link\n return cond_pats\n\n\ndef mine_tree(\n in_tree: TreeNode,\n header_table: dict,\n min_sup: int,\n pre_fix: set,\n freq_item_list: list,\n) -> None:\n \"\"\"\n Mine the FP-Tree recursively to discover frequent itemsets.\n\n Args:\n in_tree: The FP-Tree to mine.\n header_table: The header table dictionary with item information.\n min_sup: The minimum support threshold.\n pre_fix: A set of items as a prefix for the itemsets being mined.\n freq_item_list: A list to store the frequent itemsets.\n\n Example:\n >>> data_set = [\n ... ['A', 'B', 'C'],\n ... ['A', 'C'],\n ... ['A', 'B', 'E'],\n ... ['A', 'B', 'C', 'E'],\n ... ['B', 'E']\n ... ]\n >>> min_sup = 2\n >>> fp_tree, header_table = create_tree(data_set, min_sup)\n >>> fp_tree\n TreeNode('Null Set', 1, None)\n >>> frequent_itemsets = []\n >>> mine_tree(fp_tree, header_table, min_sup, set([]), frequent_itemsets)\n >>> expe_itm = [{'C'}, {'C', 'A'}, {'E'}, {'A', 'E'}, {'E', 'B'}, {'A'}, {'B'}]\n >>> all(expected in frequent_itemsets for expected in expe_itm)\n True\n \"\"\"\n sorted_items = sorted(header_table.items(), key=lambda item_info: item_info[1][0])\n big_l = [item[0] for item in sorted_items]\n for base_pat in big_l:\n new_freq_set = pre_fix.copy()\n new_freq_set.add(base_pat)\n freq_item_list.append(new_freq_set)\n cond_patt_bases = find_prefix_path(base_pat, header_table[base_pat][1])\n my_cond_tree, my_head = create_tree(list(cond_patt_bases), min_sup)\n if my_head is not None:\n # Pass header_table[base_pat][1] as node_to_test to update_header\n header_table[base_pat][1] = update_header(\n header_table[base_pat][1], my_cond_tree\n )\n mine_tree(my_cond_tree, my_head, min_sup, new_freq_set, freq_item_list)\n\n\nif __name__ == \"__main__\":\n from doctest import testmod\n\n testmod()\n data_set: list[frozenset] = [\n frozenset([\"bread\", \"milk\", \"cheese\"]),\n frozenset([\"bread\", \"milk\"]),\n frozenset([\"bread\", \"diapers\"]),\n frozenset([\"bread\", \"milk\", \"diapers\"]),\n frozenset([\"milk\", \"diapers\"]),\n frozenset([\"milk\", \"cheese\"]),\n frozenset([\"diapers\", \"cheese\"]),\n frozenset([\"bread\", \"milk\", \"cheese\", \"diapers\"]),\n ]\n print(f\"{len(data_set) = }\")\n fp_tree, header_table = create_tree(data_set, min_sup=3)\n print(f\"{fp_tree = }\")\n print(f\"{len(header_table) = }\")\n freq_items: list = []\n mine_tree(fp_tree, header_table, 3, set(), freq_items)\n print(f\"{freq_items = }\")\n"} +{"Prompt":"Initialize a GradientBoostingClassifier. Parameters: nestimators int: The number of weak learners to train. learningrate float: The learning rate for updating the model. Attributes: nestimators int: The number of weak learners. learningrate float: The learning rate. models list: A list to store the trained weak learners. Fit the GradientBoostingClassifier to the training data. Parameters: features np.ndarray: The training features. target np.ndarray: The target values. Returns: None import numpy as np from sklearn.datasets import loadiris clf GradientBoostingClassifiernestimators100, learningrate0.1 iris loadiris X, y iris.data, iris.target clf.fitX, y Check if the model is trained lenclf.models 100 True Calculate the pseudoresiduals Fit a weak learner e.g., decision tree to the residuals Update the model by adding the weak learner with a learning rate Make predictions on input data. Parameters: features np.ndarray: The input data for making predictions. Returns: np.ndarray: An array of binary predictions 1 or 1. import numpy as np from sklearn.datasets import loadiris clf GradientBoostingClassifiernestimators100, learningrate0.1 iris loadiris X, y iris.data, iris.target clf.fitX, y ypred clf.predictX Check if the predictions have the correct shape ypred.shape y.shape True Initialize predictions with zeros Calculate the negative gradient pseudoresiduals for logistic loss. Parameters: target np.ndarray: The target values. ypred np.ndarray: The predicted values. Returns: np.ndarray: An array of pseudoresiduals. import numpy as np clf GradientBoostingClassifiernestimators100, learningrate0.1 target np.array0, 1, 0, 1 ypred np.array0.2, 0.8, 0.3, 0.7 residuals clf.gradienttarget, ypred Check if residuals have the correct shape residuals.shape target.shape True","Completions":"import numpy as np\nfrom sklearn.datasets import load_iris\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.tree import DecisionTreeRegressor\n\n\nclass GradientBoostingClassifier:\n def __init__(self, n_estimators: int = 100, learning_rate: float = 0.1) -> None:\n \"\"\"\n Initialize a GradientBoostingClassifier.\n\n Parameters:\n - n_estimators (int): The number of weak learners to train.\n - learning_rate (float): The learning rate for updating the model.\n\n Attributes:\n - n_estimators (int): The number of weak learners.\n - learning_rate (float): The learning rate.\n - models (list): A list to store the trained weak learners.\n \"\"\"\n self.n_estimators = n_estimators\n self.learning_rate = learning_rate\n self.models: list[tuple[DecisionTreeRegressor, float]] = []\n\n def fit(self, features: np.ndarray, target: np.ndarray) -> None:\n \"\"\"\n Fit the GradientBoostingClassifier to the training data.\n\n Parameters:\n - features (np.ndarray): The training features.\n - target (np.ndarray): The target values.\n\n Returns:\n None\n\n >>> import numpy as np\n >>> from sklearn.datasets import load_iris\n >>> clf = GradientBoostingClassifier(n_estimators=100, learning_rate=0.1)\n >>> iris = load_iris()\n >>> X, y = iris.data, iris.target\n >>> clf.fit(X, y)\n >>> # Check if the model is trained\n >>> len(clf.models) == 100\n True\n \"\"\"\n for _ in range(self.n_estimators):\n # Calculate the pseudo-residuals\n residuals = -self.gradient(target, self.predict(features))\n # Fit a weak learner (e.g., decision tree) to the residuals\n model = DecisionTreeRegressor(max_depth=1)\n model.fit(features, residuals)\n # Update the model by adding the weak learner with a learning rate\n self.models.append((model, self.learning_rate))\n\n def predict(self, features: np.ndarray) -> np.ndarray:\n \"\"\"\n Make predictions on input data.\n\n Parameters:\n - features (np.ndarray): The input data for making predictions.\n\n Returns:\n - np.ndarray: An array of binary predictions (-1 or 1).\n\n >>> import numpy as np\n >>> from sklearn.datasets import load_iris\n >>> clf = GradientBoostingClassifier(n_estimators=100, learning_rate=0.1)\n >>> iris = load_iris()\n >>> X, y = iris.data, iris.target\n >>> clf.fit(X, y)\n >>> y_pred = clf.predict(X)\n >>> # Check if the predictions have the correct shape\n >>> y_pred.shape == y.shape\n True\n \"\"\"\n # Initialize predictions with zeros\n predictions = np.zeros(features.shape[0])\n for model, learning_rate in self.models:\n predictions += learning_rate * model.predict(features)\n return np.sign(predictions) # Convert to binary predictions (-1 or 1)\n\n def gradient(self, target: np.ndarray, y_pred: np.ndarray) -> np.ndarray:\n \"\"\"\n Calculate the negative gradient (pseudo-residuals) for logistic loss.\n\n Parameters:\n - target (np.ndarray): The target values.\n - y_pred (np.ndarray): The predicted values.\n\n Returns:\n - np.ndarray: An array of pseudo-residuals.\n\n >>> import numpy as np\n >>> clf = GradientBoostingClassifier(n_estimators=100, learning_rate=0.1)\n >>> target = np.array([0, 1, 0, 1])\n >>> y_pred = np.array([0.2, 0.8, 0.3, 0.7])\n >>> residuals = clf.gradient(target, y_pred)\n >>> # Check if residuals have the correct shape\n >>> residuals.shape == target.shape\n True\n \"\"\"\n return -target \/ (1 + np.exp(target * y_pred))\n\n\nif __name__ == \"__main__\":\n iris = load_iris()\n X, y = iris.data, iris.target\n X_train, X_test, y_train, y_test = train_test_split(\n X, y, test_size=0.2, random_state=42\n )\n\n clf = GradientBoostingClassifier(n_estimators=100, learning_rate=0.1)\n clf.fit(X_train, y_train)\n\n y_pred = clf.predict(X_test)\n accuracy = accuracy_score(y_test, y_pred)\n print(f\"Accuracy: {accuracy:.2f}\")\n"} +{"Prompt":"Implementation of gradient descent algorithm for minimizing cost of a linear hypothesis function. List of input, output pairs :param dataset: train data or test data :param exampleno: example number whose error has to be checked :return: error in example pointed by example number. Calculates hypothesis function value for a given input :param datainputtuple: Input tuple of a particular example :return: Value of hypothesis function at that point. Note that there is an 'biased input' whose value is fixed as 1. It is not explicitly mentioned in input data.. But, ML hypothesis functions use it. So, we have to take care of it separately. Line 36 takes care of it. :param dataset: test data or train data :param exampleno: example whose output is to be fetched :return: output for that example Calculates hypothesis value for a given example :param dataset: test data or traindata :param exampleno: example whose hypothesis value is to be calculated :return: hypothesis value for that example Calculates the sum of cost function derivative :param index: index wrt derivative is being calculated :param end: value where summation ends, default is m, number of examples :return: Returns the summation of cost derivative Note: If index is 1, this means we are calculating summation wrt to biased parameter. :param index: index of the parameter vector wrt to derivative is to be calculated :return: derivative wrt to that index Note: If index is 1, this means we are calculating summation wrt to biased parameter. Tune these values to set a tolerance value for predicted output","Completions":"import numpy\n\n# List of input, output pairs\ntrain_data = (\n ((5, 2, 3), 15),\n ((6, 5, 9), 25),\n ((11, 12, 13), 41),\n ((1, 1, 1), 8),\n ((11, 12, 13), 41),\n)\ntest_data = (((515, 22, 13), 555), ((61, 35, 49), 150))\nparameter_vector = [2, 4, 1, 5]\nm = len(train_data)\nLEARNING_RATE = 0.009\n\n\ndef _error(example_no, data_set=\"train\"):\n \"\"\"\n :param data_set: train data or test data\n :param example_no: example number whose error has to be checked\n :return: error in example pointed by example number.\n \"\"\"\n return calculate_hypothesis_value(example_no, data_set) - output(\n example_no, data_set\n )\n\n\ndef _hypothesis_value(data_input_tuple):\n \"\"\"\n Calculates hypothesis function value for a given input\n :param data_input_tuple: Input tuple of a particular example\n :return: Value of hypothesis function at that point.\n Note that there is an 'biased input' whose value is fixed as 1.\n It is not explicitly mentioned in input data.. But, ML hypothesis functions use it.\n So, we have to take care of it separately. Line 36 takes care of it.\n \"\"\"\n hyp_val = 0\n for i in range(len(parameter_vector) - 1):\n hyp_val += data_input_tuple[i] * parameter_vector[i + 1]\n hyp_val += parameter_vector[0]\n return hyp_val\n\n\ndef output(example_no, data_set):\n \"\"\"\n :param data_set: test data or train data\n :param example_no: example whose output is to be fetched\n :return: output for that example\n \"\"\"\n if data_set == \"train\":\n return train_data[example_no][1]\n elif data_set == \"test\":\n return test_data[example_no][1]\n return None\n\n\ndef calculate_hypothesis_value(example_no, data_set):\n \"\"\"\n Calculates hypothesis value for a given example\n :param data_set: test data or train_data\n :param example_no: example whose hypothesis value is to be calculated\n :return: hypothesis value for that example\n \"\"\"\n if data_set == \"train\":\n return _hypothesis_value(train_data[example_no][0])\n elif data_set == \"test\":\n return _hypothesis_value(test_data[example_no][0])\n return None\n\n\ndef summation_of_cost_derivative(index, end=m):\n \"\"\"\n Calculates the sum of cost function derivative\n :param index: index wrt derivative is being calculated\n :param end: value where summation ends, default is m, number of examples\n :return: Returns the summation of cost derivative\n Note: If index is -1, this means we are calculating summation wrt to biased\n parameter.\n \"\"\"\n summation_value = 0\n for i in range(end):\n if index == -1:\n summation_value += _error(i)\n else:\n summation_value += _error(i) * train_data[i][0][index]\n return summation_value\n\n\ndef get_cost_derivative(index):\n \"\"\"\n :param index: index of the parameter vector wrt to derivative is to be calculated\n :return: derivative wrt to that index\n Note: If index is -1, this means we are calculating summation wrt to biased\n parameter.\n \"\"\"\n cost_derivative_value = summation_of_cost_derivative(index, m) \/ m\n return cost_derivative_value\n\n\ndef run_gradient_descent():\n global parameter_vector\n # Tune these values to set a tolerance value for predicted output\n absolute_error_limit = 0.000002\n relative_error_limit = 0\n j = 0\n while True:\n j += 1\n temp_parameter_vector = [0, 0, 0, 0]\n for i in range(len(parameter_vector)):\n cost_derivative = get_cost_derivative(i - 1)\n temp_parameter_vector[i] = (\n parameter_vector[i] - LEARNING_RATE * cost_derivative\n )\n if numpy.allclose(\n parameter_vector,\n temp_parameter_vector,\n atol=absolute_error_limit,\n rtol=relative_error_limit,\n ):\n break\n parameter_vector = temp_parameter_vector\n print((\"Number of iterations:\", j))\n\n\ndef test_gradient_descent():\n for i in range(len(test_data)):\n print((\"Actual output value:\", output(i, \"test\")))\n print((\"Hypothesis output:\", calculate_hypothesis_value(i, \"test\")))\n\n\nif __name__ == \"__main__\":\n run_gradient_descent()\n print(\"\\nTesting gradient descent for a linear hypothesis function.\\n\")\n test_gradient_descent()\n"} +{"Prompt":"README, Author Anurag Kumarmailto:anuragkumarak95gmail.com Requirements: sklearn numpy matplotlib Python: 3.5 Inputs: X , a 2D numpy array of features. k , number of clusters to create. initialcentroids , initial centroid values generated by utility functionmentioned in usage. maxiter , maximum number of iterations to process. heterogeneity , empty list that will be filled with heterogeneity values if passed to kmeans func. Usage: 1. define 'k' value, 'X' features array and 'heterogeneity' empty list 2. create initialcentroids, initialcentroids getinitialcentroids X, k, seed0 seed value for initial centroid generation, None for randomnessdefaultNone 3. find centroids and clusters using kmeans function. centroids, clusterassignment kmeans X, k, initialcentroids, maxiter400, recordheterogeneityheterogeneity, verboseTrue whether to print logs in console or not.defaultFalse 4. Plot the loss function and heterogeneity values for every iteration saved in heterogeneity list. plotheterogeneity heterogeneity, k 5. Transfers Dataframe into excel format it must have feature called 'Clust' with k means clustering numbers in it. Randomly choose k data points as initial centroids if seed is not None: useful for obtaining consistent results np.random.seedseed n data.shape0 number of data points Pick K indices from range 0, N. randindices np.random.randint0, n, k Keep centroids as dense format, as many entries will be nonzero due to averaging. As long as at least one document in a cluster contains a word, it will carry a nonzero weight in the TFIDF vector of the centroid. centroids datarandindices, : return centroids def centroidpairwisedistx, centroids: return pairwisedistancesx, centroids, metriceuclidean def assignclustersdata, centroids: Compute distances between each data point and the set of centroids: Fill in the blank RHS only distancesfromcentroids centroidpairwisedistdata, centroids Compute cluster assignments for each data point: Fill in the blank RHS only clusterassignment np.argmindistancesfromcentroids, axis1 return clusterassignment def revisecentroidsdata, k, clusterassignment: newcentroids for i in rangek: Select all data points that belong to cluster i. Fill in the blank RHS only memberdatapoints dataclusterassignment i Compute the mean of the data points. Fill in the blank RHS only centroid memberdatapoints.meanaxis0 newcentroids.appendcentroid newcentroids np.arraynewcentroids return newcentroids def computeheterogeneitydata, k, centroids, clusterassignment: heterogeneity 0.0 for i in rangek: Select all data points that belong to cluster i. Fill in the blank RHS only memberdatapoints dataclusterassignment i, : if memberdatapoints.shape0 0: check if ith cluster is nonempty Compute distances from centroid to data points RHS only distances pairwisedistances memberdatapoints, centroidsi, metriceuclidean squareddistances distances2 heterogeneity np.sumsquareddistances return heterogeneity def plotheterogeneityheterogeneity, k: plt.figurefigsize7, 4 plt.plotheterogeneity, linewidth4 plt.xlabel Iterations plt.ylabelHeterogeneity plt.titlefHeterogeneity of clustering over time, Kk:d plt.rcParams.updatefont.size: 16 plt.show def kmeans data, k, initialcentroids, maxiter500, recordheterogeneityNone, verboseFalse : 1. Make cluster assignments using nearest centroids 2. Compute a new centroid for each of the k clusters, averaging all data points assigned to that cluster. Check for convergence: if none of the assignments changed, stop Print number of new assignments Record heterogeneity convergence metric YOUR CODE HERE Mock test below Generate a clustering report given these two arguments: predicted dataframe with predicted cluster column fillmissingreport dictionary of rules on how we are going to fill in missing values for final generated report not included in modelling; predicted pd.DataFrame predicted'numbers' 1, 2, 3 predicted'col1' 0.5, 2.5, 4.5 predicted'col2' 100, 200, 300 predicted'col3' 10, 20, 30 predicted'Cluster' 1, 1, 2 reportgeneratorpredicted, 'col1', 'col2', 0 Features Type Mark 1 2 0 of Customers ClusterSize False 2.000000 1.000000 1 of Customers ClusterProportion False 0.666667 0.333333 2 col1 meanwithzeros True 1.500000 4.500000 3 col2 meanwithzeros True 150.000000 300.000000 4 numbers meanwithzeros False 1.500000 3.000000 .. ... ... ... ... ... 99 dummy 5 False 1.000000 1.000000 100 dummy 95 False 1.000000 1.000000 101 dummy stdev False 0.000000 NaN 102 dummy mode False 1.000000 1.000000 103 dummy median False 1.000000 1.000000 BLANKLINE 104 rows x 5 columns Fill missing values with given rules calculate the size of clustercount of clientID's avoid SettingWithCopyWarning rename created predicted cluster to match report column names calculating the proportion of cluster rename created predicted cluster to match report column names generating dataframe with count of nan values filling values in order to match report drop count values except for cluster size concat report with cluster size and nan values","Completions":"import warnings\n\nimport numpy as np\nimport pandas as pd\nfrom matplotlib import pyplot as plt\nfrom sklearn.metrics import pairwise_distances\n\nwarnings.filterwarnings(\"ignore\")\n\nTAG = \"K-MEANS-CLUST\/ \"\n\n\ndef get_initial_centroids(data, k, seed=None):\n \"\"\"Randomly choose k data points as initial centroids\"\"\"\n if seed is not None: # useful for obtaining consistent results\n np.random.seed(seed)\n n = data.shape[0] # number of data points\n\n # Pick K indices from range [0, N).\n rand_indices = np.random.randint(0, n, k)\n\n # Keep centroids as dense format, as many entries will be nonzero due to averaging.\n # As long as at least one document in a cluster contains a word,\n # it will carry a nonzero weight in the TF-IDF vector of the centroid.\n centroids = data[rand_indices, :]\n\n return centroids\n\n\ndef centroid_pairwise_dist(x, centroids):\n return pairwise_distances(x, centroids, metric=\"euclidean\")\n\n\ndef assign_clusters(data, centroids):\n # Compute distances between each data point and the set of centroids:\n # Fill in the blank (RHS only)\n distances_from_centroids = centroid_pairwise_dist(data, centroids)\n\n # Compute cluster assignments for each data point:\n # Fill in the blank (RHS only)\n cluster_assignment = np.argmin(distances_from_centroids, axis=1)\n\n return cluster_assignment\n\n\ndef revise_centroids(data, k, cluster_assignment):\n new_centroids = []\n for i in range(k):\n # Select all data points that belong to cluster i. Fill in the blank (RHS only)\n member_data_points = data[cluster_assignment == i]\n # Compute the mean of the data points. Fill in the blank (RHS only)\n centroid = member_data_points.mean(axis=0)\n new_centroids.append(centroid)\n new_centroids = np.array(new_centroids)\n\n return new_centroids\n\n\ndef compute_heterogeneity(data, k, centroids, cluster_assignment):\n heterogeneity = 0.0\n for i in range(k):\n # Select all data points that belong to cluster i. Fill in the blank (RHS only)\n member_data_points = data[cluster_assignment == i, :]\n\n if member_data_points.shape[0] > 0: # check if i-th cluster is non-empty\n # Compute distances from centroid to data points (RHS only)\n distances = pairwise_distances(\n member_data_points, [centroids[i]], metric=\"euclidean\"\n )\n squared_distances = distances**2\n heterogeneity += np.sum(squared_distances)\n\n return heterogeneity\n\n\ndef plot_heterogeneity(heterogeneity, k):\n plt.figure(figsize=(7, 4))\n plt.plot(heterogeneity, linewidth=4)\n plt.xlabel(\"# Iterations\")\n plt.ylabel(\"Heterogeneity\")\n plt.title(f\"Heterogeneity of clustering over time, K={k:d}\")\n plt.rcParams.update({\"font.size\": 16})\n plt.show()\n\n\ndef kmeans(\n data, k, initial_centroids, maxiter=500, record_heterogeneity=None, verbose=False\n):\n \"\"\"Runs k-means on given data and initial set of centroids.\n maxiter: maximum number of iterations to run.(default=500)\n record_heterogeneity: (optional) a list, to store the history of heterogeneity\n as function of iterations\n if None, do not store the history.\n verbose: if True, print how many data points changed their cluster labels in\n each iteration\"\"\"\n centroids = initial_centroids[:]\n prev_cluster_assignment = None\n\n for itr in range(maxiter):\n if verbose:\n print(itr, end=\"\")\n\n # 1. Make cluster assignments using nearest centroids\n cluster_assignment = assign_clusters(data, centroids)\n\n # 2. Compute a new centroid for each of the k clusters, averaging all data\n # points assigned to that cluster.\n centroids = revise_centroids(data, k, cluster_assignment)\n\n # Check for convergence: if none of the assignments changed, stop\n if (\n prev_cluster_assignment is not None\n and (prev_cluster_assignment == cluster_assignment).all()\n ):\n break\n\n # Print number of new assignments\n if prev_cluster_assignment is not None:\n num_changed = np.sum(prev_cluster_assignment != cluster_assignment)\n if verbose:\n print(\n f\" {num_changed:5d} elements changed their cluster assignment.\"\n )\n\n # Record heterogeneity convergence metric\n if record_heterogeneity is not None:\n # YOUR CODE HERE\n score = compute_heterogeneity(data, k, centroids, cluster_assignment)\n record_heterogeneity.append(score)\n\n prev_cluster_assignment = cluster_assignment[:]\n\n return centroids, cluster_assignment\n\n\n# Mock test below\nif False: # change to true to run this test case.\n from sklearn import datasets as ds\n\n dataset = ds.load_iris()\n k = 3\n heterogeneity = []\n initial_centroids = get_initial_centroids(dataset[\"data\"], k, seed=0)\n centroids, cluster_assignment = kmeans(\n dataset[\"data\"],\n k,\n initial_centroids,\n maxiter=400,\n record_heterogeneity=heterogeneity,\n verbose=True,\n )\n plot_heterogeneity(heterogeneity, k)\n\n\ndef report_generator(\n predicted: pd.DataFrame, clustering_variables: np.ndarray, fill_missing_report=None\n) -> pd.DataFrame:\n \"\"\"\n Generate a clustering report given these two arguments:\n predicted - dataframe with predicted cluster column\n fill_missing_report - dictionary of rules on how we are going to fill in missing\n values for final generated report (not included in modelling);\n >>> predicted = pd.DataFrame()\n >>> predicted['numbers'] = [1, 2, 3]\n >>> predicted['col1'] = [0.5, 2.5, 4.5]\n >>> predicted['col2'] = [100, 200, 300]\n >>> predicted['col3'] = [10, 20, 30]\n >>> predicted['Cluster'] = [1, 1, 2]\n >>> report_generator(predicted, ['col1', 'col2'], 0)\n Features Type Mark 1 2\n 0 # of Customers ClusterSize False 2.000000 1.000000\n 1 % of Customers ClusterProportion False 0.666667 0.333333\n 2 col1 mean_with_zeros True 1.500000 4.500000\n 3 col2 mean_with_zeros True 150.000000 300.000000\n 4 numbers mean_with_zeros False 1.500000 3.000000\n .. ... ... ... ... ...\n 99 dummy 5% False 1.000000 1.000000\n 100 dummy 95% False 1.000000 1.000000\n 101 dummy stdev False 0.000000 NaN\n 102 dummy mode False 1.000000 1.000000\n 103 dummy median False 1.000000 1.000000\n \n [104 rows x 5 columns]\n \"\"\"\n # Fill missing values with given rules\n if fill_missing_report:\n predicted = predicted.fillna(value=fill_missing_report)\n predicted[\"dummy\"] = 1\n numeric_cols = predicted.select_dtypes(np.number).columns\n report = (\n predicted.groupby([\"Cluster\"])[ # construct report dataframe\n numeric_cols\n ] # group by cluster number\n .agg(\n [\n (\"sum\", \"sum\"),\n (\"mean_with_zeros\", lambda x: np.mean(np.nan_to_num(x))),\n (\"mean_without_zeros\", lambda x: x.replace(0, np.NaN).mean()),\n (\n \"mean_25-75\",\n lambda x: np.mean(\n np.nan_to_num(\n sorted(x)[\n round(len(x) * 25 \/ 100) : round(len(x) * 75 \/ 100)\n ]\n )\n ),\n ),\n (\"mean_with_na\", \"mean\"),\n (\"min\", lambda x: x.min()),\n (\"5%\", lambda x: x.quantile(0.05)),\n (\"25%\", lambda x: x.quantile(0.25)),\n (\"50%\", lambda x: x.quantile(0.50)),\n (\"75%\", lambda x: x.quantile(0.75)),\n (\"95%\", lambda x: x.quantile(0.95)),\n (\"max\", lambda x: x.max()),\n (\"count\", lambda x: x.count()),\n (\"stdev\", lambda x: x.std()),\n (\"mode\", lambda x: x.mode()[0]),\n (\"median\", lambda x: x.median()),\n (\"# > 0\", lambda x: (x > 0).sum()),\n ]\n )\n .T.reset_index()\n .rename(index=str, columns={\"level_0\": \"Features\", \"level_1\": \"Type\"})\n ) # rename columns\n # calculate the size of cluster(count of clientID's)\n # avoid SettingWithCopyWarning\n clustersize = report[\n (report[\"Features\"] == \"dummy\") & (report[\"Type\"] == \"count\")\n ].copy()\n # rename created predicted cluster to match report column names\n clustersize.Type = \"ClusterSize\"\n clustersize.Features = \"# of Customers\"\n # calculating the proportion of cluster\n clusterproportion = pd.DataFrame(\n clustersize.iloc[:, 2:].to_numpy() \/ clustersize.iloc[:, 2:].to_numpy().sum()\n )\n # rename created predicted cluster to match report column names\n clusterproportion[\"Type\"] = \"% of Customers\"\n clusterproportion[\"Features\"] = \"ClusterProportion\"\n cols = clusterproportion.columns.tolist()\n cols = cols[-2:] + cols[:-2]\n clusterproportion = clusterproportion[cols] # rearrange columns to match report\n clusterproportion.columns = report.columns\n # generating dataframe with count of nan values\n a = pd.DataFrame(\n abs(\n report[report[\"Type\"] == \"count\"].iloc[:, 2:].to_numpy()\n - clustersize.iloc[:, 2:].to_numpy()\n )\n )\n a[\"Features\"] = 0\n a[\"Type\"] = \"# of nan\"\n # filling values in order to match report\n a.Features = report[report[\"Type\"] == \"count\"].Features.tolist()\n cols = a.columns.tolist()\n cols = cols[-2:] + cols[:-2]\n a = a[cols] # rearrange columns to match report\n a.columns = report.columns # rename columns to match report\n # drop count values except for cluster size\n report = report.drop(report[report.Type == \"count\"].index)\n # concat report with cluster size and nan values\n report = pd.concat([report, a, clustersize, clusterproportion], axis=0)\n report[\"Mark\"] = report[\"Features\"].isin(clustering_variables)\n cols = report.columns.tolist()\n cols = cols[0:2] + cols[-1:] + cols[2:-1]\n report = report[cols]\n sorter1 = {\n \"ClusterSize\": 9,\n \"ClusterProportion\": 8,\n \"mean_with_zeros\": 7,\n \"mean_with_na\": 6,\n \"max\": 5,\n \"50%\": 4,\n \"min\": 3,\n \"25%\": 2,\n \"75%\": 1,\n \"# of nan\": 0,\n \"# > 0\": -1,\n \"sum_with_na\": -2,\n }\n report = (\n report.assign(\n Sorter1=lambda x: x.Type.map(sorter1),\n Sorter2=lambda x: list(reversed(range(len(x)))),\n )\n .sort_values([\"Sorter1\", \"Mark\", \"Sorter2\"], ascending=False)\n .drop([\"Sorter1\", \"Sorter2\"], axis=1)\n )\n report.columns.name = \"\"\n report = report.reset_index()\n report = report.drop(columns=[\"index\"])\n return report\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"kNearest Neighbours kNN is a simple nonparametric supervised learning algorithm used for classification. Given some labelled training data, a given point is classified using its k nearest neighbours according to some distance metric. The most commonly occurring label among the neighbours becomes the label of the given point. In effect, the label of the given point is decided by a majority vote. This implementation uses the commonly used Euclidean distance metric, but other distance metrics can also be used. Reference: https:en.wikipedia.orgwikiKnearestneighborsalgorithm Create a kNN classifier using the given training data and class labels Calculate the Euclidean distance between two points KNN.euclideandistancenp.array0, 0, np.array3, 4 5.0 KNN.euclideandistancenp.array1, 2, 3, np.array1, 8, 11 10.0 Classify a given point using the kNN algorithm trainX np.array ... 0, 0, 1, 0, 0, 1, 0.5, 0.5, 3, 3, 2, 3, 3, 2 ... trainy np.array0, 0, 0, 0, 1, 1, 1 classes 'A', 'B' knn KNNtrainX, trainy, classes point np.array1.2, 1.2 knn.classifypoint 'A' Distances of all points from the point to be classified Choosing k points with the shortest distances Most commonly occurring class is the one into which the point is classified","Completions":"from collections import Counter\nfrom heapq import nsmallest\n\nimport numpy as np\nfrom sklearn import datasets\nfrom sklearn.model_selection import train_test_split\n\n\nclass KNN:\n def __init__(\n self,\n train_data: np.ndarray[float],\n train_target: np.ndarray[int],\n class_labels: list[str],\n ) -> None:\n \"\"\"\n Create a kNN classifier using the given training data and class labels\n \"\"\"\n self.data = zip(train_data, train_target)\n self.labels = class_labels\n\n @staticmethod\n def _euclidean_distance(a: np.ndarray[float], b: np.ndarray[float]) -> float:\n \"\"\"\n Calculate the Euclidean distance between two points\n >>> KNN._euclidean_distance(np.array([0, 0]), np.array([3, 4]))\n 5.0\n >>> KNN._euclidean_distance(np.array([1, 2, 3]), np.array([1, 8, 11]))\n 10.0\n \"\"\"\n return np.linalg.norm(a - b)\n\n def classify(self, pred_point: np.ndarray[float], k: int = 5) -> str:\n \"\"\"\n Classify a given point using the kNN algorithm\n >>> train_X = np.array(\n ... [[0, 0], [1, 0], [0, 1], [0.5, 0.5], [3, 3], [2, 3], [3, 2]]\n ... )\n >>> train_y = np.array([0, 0, 0, 0, 1, 1, 1])\n >>> classes = ['A', 'B']\n >>> knn = KNN(train_X, train_y, classes)\n >>> point = np.array([1.2, 1.2])\n >>> knn.classify(point)\n 'A'\n \"\"\"\n # Distances of all points from the point to be classified\n distances = (\n (self._euclidean_distance(data_point[0], pred_point), data_point[1])\n for data_point in self.data\n )\n\n # Choosing k points with the shortest distances\n votes = (i[1] for i in nsmallest(k, distances))\n\n # Most commonly occurring class is the one into which the point is classified\n result = Counter(votes).most_common(1)[0][0]\n return self.labels[result]\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n\n iris = datasets.load_iris()\n\n X = np.array(iris[\"data\"])\n y = np.array(iris[\"target\"])\n iris_classes = iris[\"target_names\"]\n\n X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)\n iris_point = np.array([4.4, 3.1, 1.3, 1.4])\n classifier = KNN(X_train, y_train, iris_classes)\n print(classifier.classify(iris_point, k=3))\n"} +{"Prompt":"Linear Discriminant Analysis Assumptions About Data : 1. The input variables has a gaussian distribution. 2. The variance calculated for each input variables by class grouping is the same. 3. The mix of classes in your training set is representative of the problem. Learning The Model : The LDA model requires the estimation of statistics from the training data : 1. Mean of each input value for each class. 2. Probability of an instance belong to each class. 3. Covariance for the input data for each class Calculate the class means : meanx 1n for i 1 to i n sumxi Calculate the class probabilities : Py 0 county 0 county 0 county 1 Py 1 county 1 county 0 county 1 Calculate the variance : We can calculate the variance for dataset in two steps : 1. Calculate the squared difference for each input variable from the group mean. 2. Calculate the mean of the squared difference. SquaredDifference x meank 2 Variance 1 countx countclasses for i 1 to i n sumSquaredDifferencexi Making Predictions : discriminantx x mean variance mean 2 2 variance Lnprobability After calculating the discriminant value for each class, the class with the largest discriminant value is taken as the prediction. Author: EverLookNeverSee Make a training dataset drawn from a gaussian distribution Generate gaussian distribution instances basedon given mean and standard deviation :param mean: mean value of class :param stddev: value of standard deviation entered by usr or default value of it :param instancecount: instance number of class :return: a list containing generated values basedon given mean, stddev and instancecount gaussiandistribution5.0, 1.0, 20 doctest: NORMALIZEWHITESPACE 6.288184753155463, 6.4494456086997705, 5.066335808938262, 4.235456349028368, 3.9078267848958586, 5.031334516831717, 3.977896829989127, 3.56317055489747, 5.199311976483754, 5.133374604658605, 5.546468300338232, 4.086029056264687, 5.005005283626573, 4.935258239627312, 3.494170998739258, 5.537997178661033, 5.320711100998849, 7.3891120432406865, 5.202969177309964, 4.855297691835079 Make corresponding Y flags to detecting classes Generate y values for corresponding classes :param classcount: Number of classesdata groupings in dataset :param instancecount: number of instances in class :return: corresponding values for data groupings in dataset ygenerator1, 10 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ygenerator2, 5, 10 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ygenerator4, 10, 5, 15, 20 doctest: NORMALIZEWHITESPACE 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3 Calculate the class means Calculate given class mean :param instancecount: Number of instances in class :param items: items that related to specific classdata grouping :return: calculated actual mean of considered class items gaussiandistribution5.0, 1.0, 20 calculatemeanlenitems, items 5.011267842911003 the sum of all items divided by number of instances Calculate the class probabilities Calculate the probability that a given instance will belong to which class :param instancecount: number of instances in class :param totalcount: the number of all instances :return: value of probability for considered class calculateprobabilities20, 60 0.3333333333333333 calculateprobabilities30, 100 0.3 number of instances in specific class divided by number of all instances Calculate the variance Calculate the variance :param items: a list containing all itemsgaussian distribution of all classes :param means: a list containing real mean values of each class :param totalcount: the number of all instances :return: calculated variance for considered dataset items gaussiandistribution5.0, 1.0, 20 means 5.011267842911003 totalcount 20 calculatevarianceitems, means, totalcount 0.9618530973487491 iterate over number of elements in items for loop iterates over number of elements in inner layer of items appending squared differences to 'squareddiff' list one divided by the number of all instances number of classes multiplied by sum of all squared differences Making predictions This function predicts new indexesgroups for our data :param xitems: a list containing all itemsgaussian distribution of all classes :param means: a list containing real mean values of each class :param variance: calculated value of variance by calculatevariance function :param probabilities: a list containing all probabilities of classes :return: a list containing predicted Y values xitems 6.288184753155463, 6.4494456086997705, 5.066335808938262, ... 4.235456349028368, 3.9078267848958586, 5.031334516831717, ... 3.977896829989127, 3.56317055489747, 5.199311976483754, ... 5.133374604658605, 5.546468300338232, 4.086029056264687, ... 5.005005283626573, 4.935258239627312, 3.494170998739258, ... 5.537997178661033, 5.320711100998849, 7.3891120432406865, ... 5.202969177309964, 4.855297691835079, 11.288184753155463, ... 11.44944560869977, 10.066335808938263, 9.235456349028368, ... 8.907826784895859, 10.031334516831716, 8.977896829989128, ... 8.56317055489747, 10.199311976483754, 10.133374604658606, ... 10.546468300338232, 9.086029056264687, 10.005005283626572, ... 9.935258239627313, 8.494170998739259, 10.537997178661033, ... 10.320711100998848, 12.389112043240686, 10.202969177309964, ... 9.85529769183508, 16.288184753155463, 16.449445608699772, ... 15.066335808938263, 14.235456349028368, 13.907826784895859, ... 15.031334516831716, 13.977896829989128, 13.56317055489747, ... 15.199311976483754, 15.133374604658606, 15.546468300338232, ... 14.086029056264687, 15.005005283626572, 14.935258239627313, ... 13.494170998739259, 15.537997178661033, 15.320711100998848, ... 17.389112043240686, 15.202969177309964, 14.85529769183508 means 5.011267842911003, 10.011267842911003, 15.011267842911002 variance 0.9618530973487494 probabilities 0.3333333333333333, 0.3333333333333333, 0.3333333333333333 predictyvaluesxitems, means, variance, ... probabilities doctest: NORMALIZEWHITESPACE 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2 An empty list to store generated discriminant values of all items in dataset for each class for loop iterates over number of elements in list for loop iterates over number of inner items of each element for loop iterates over number of classes we have in our dataset appending values of discriminants for each class to 'temp' list appending discriminant values of each item to 'results' list Calculating Accuracy Calculate the value of accuracy basedon predictions :param actualy:a list containing initial Y values generated by 'ygenerator' function :param predictedy: a list containing predicted Y values generated by 'predictyvalues' function :return: percentage of accuracy actualy 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, ... 1, 1 ,1 ,1 ,1 ,1 ,1 predictedy 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, ... 0, 0, 1, 1, 1, 0, 1, 1, 1 accuracyactualy, predictedy 50.0 actualy 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, ... 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2 predictedy 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, ... 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2 accuracyactualy, predictedy 100.0 iterate over one element of each list at a time zip mode prediction is correct if actual Y value equals to predicted Y value percentage of accuracy equals to number of correct predictions divided by number of all data and multiplied by 100 Ask for user value and validate that it fulfill a condition. :inputtype: user input expected type of value :inputmsg: message to show user in the screen :errmsg: message to show in the screen in case of error :condition: function that represents the condition that user input is valid. :default: Default value in case the user does not type anything :return: user's input Main Function This function starts execution phase while True: print Linear Discriminant Analysis .center50, print 50, n printFirst of all we should specify the number of classes that printwe want to generate as training dataset Trying to get number of classes nclasses validinput inputtypeint, conditionlambda x: x 0, inputmsgEnter the number of classes Data Groupings: , errmsgNumber of classes should be positive!, print 100 Trying to get the value of standard deviation stddev validinput inputtypefloat, conditionlambda x: x 0, inputmsg Enter the value of standard deviation Default value is 1.0 for all classes: , errmsgStandard deviation should not be negative!, default1.0, print 100 Trying to get number of instances in classes and theirs means to generate dataset counts An empty list to store instance counts of classes in dataset for i in rangenclasses: usercount validinput inputtypeint, conditionlambda x: x 0, inputmsgfEnter The number of instances for classi1: , errmsgNumber of instances should be positive!, counts.appendusercount print 100 An empty list to store values of userentered means of classes usermeans for a in rangenclasses: usermean validinput inputtypefloat, inputmsgfEnter the value of mean for classa1: , errmsgThis is an invalid value., usermeans.appendusermean print 100 printStandard deviation: , stddev print out the number of instances in classes in separated line for i, count in enumeratecounts, 1: printfNumber of instances in classi is: count print 100 print out mean values of classes separated line for i, usermean in enumerateusermeans, 1: printfMean of classi is: usermean print 100 Generating training dataset drawn from gaussian distribution x gaussiandistributionusermeansj, stddev, countsj for j in rangenclasses printGenerated Normal Distribution: n, x print 100 Generating Ys to detecting corresponding classes y ygeneratornclasses, counts printGenerated Corresponding Ys: n, y print 100 Calculating the value of actual mean for each class actualmeans calculatemeancountsk, xk for k in rangenclasses for loop iterates over number of elements in 'actualmeans' list and print out them in separated line for i, actualmean in enumerateactualmeans, 1: printfActualReal mean of classi is: actualmean print 100 Calculating the value of probabilities for each class probabilities calculateprobabilitiescountsi, sumcounts for i in rangenclasses for loop iterates over number of elements in 'probabilities' list and print out them in separated line for i, probability in enumerateprobabilities, 1: printfProbability of classi is: probability print 100 Calculating the values of variance for each class variance calculatevariancex, actualmeans, sumcounts printVariance: , variance print 100 Predicting Y values storing predicted Y values in 'preindexes' variable preindexes predictyvaluesx, actualmeans, variance, probabilities print 100 Calculating Accuracy of the model printfAccuracy: accuracyy, preindexes print 100 print DONE .center100, if inputPress any key to restart or 'q' for quit: .strip.lower q: printn GoodBye!.center100, n break systemcls if name nt else clear noqa: S605 if name main: main","Completions":"from collections.abc import Callable\nfrom math import log\nfrom os import name, system\nfrom random import gauss, seed\nfrom typing import TypeVar\n\n\n# Make a training dataset drawn from a gaussian distribution\ndef gaussian_distribution(mean: float, std_dev: float, instance_count: int) -> list:\n \"\"\"\n Generate gaussian distribution instances based-on given mean and standard deviation\n :param mean: mean value of class\n :param std_dev: value of standard deviation entered by usr or default value of it\n :param instance_count: instance number of class\n :return: a list containing generated values based-on given mean, std_dev and\n instance_count\n\n >>> gaussian_distribution(5.0, 1.0, 20) # doctest: +NORMALIZE_WHITESPACE\n [6.288184753155463, 6.4494456086997705, 5.066335808938262, 4.235456349028368,\n 3.9078267848958586, 5.031334516831717, 3.977896829989127, 3.56317055489747,\n 5.199311976483754, 5.133374604658605, 5.546468300338232, 4.086029056264687,\n 5.005005283626573, 4.935258239627312, 3.494170998739258, 5.537997178661033,\n 5.320711100998849, 7.3891120432406865, 5.202969177309964, 4.855297691835079]\n \"\"\"\n seed(1)\n return [gauss(mean, std_dev) for _ in range(instance_count)]\n\n\n# Make corresponding Y flags to detecting classes\ndef y_generator(class_count: int, instance_count: list) -> list:\n \"\"\"\n Generate y values for corresponding classes\n :param class_count: Number of classes(data groupings) in dataset\n :param instance_count: number of instances in class\n :return: corresponding values for data groupings in dataset\n\n >>> y_generator(1, [10])\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n >>> y_generator(2, [5, 10])\n [0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]\n >>> y_generator(4, [10, 5, 15, 20]) # doctest: +NORMALIZE_WHITESPACE\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,\n 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3]\n \"\"\"\n\n return [k for k in range(class_count) for _ in range(instance_count[k])]\n\n\n# Calculate the class means\ndef calculate_mean(instance_count: int, items: list) -> float:\n \"\"\"\n Calculate given class mean\n :param instance_count: Number of instances in class\n :param items: items that related to specific class(data grouping)\n :return: calculated actual mean of considered class\n\n >>> items = gaussian_distribution(5.0, 1.0, 20)\n >>> calculate_mean(len(items), items)\n 5.011267842911003\n \"\"\"\n # the sum of all items divided by number of instances\n return sum(items) \/ instance_count\n\n\n# Calculate the class probabilities\ndef calculate_probabilities(instance_count: int, total_count: int) -> float:\n \"\"\"\n Calculate the probability that a given instance will belong to which class\n :param instance_count: number of instances in class\n :param total_count: the number of all instances\n :return: value of probability for considered class\n\n >>> calculate_probabilities(20, 60)\n 0.3333333333333333\n >>> calculate_probabilities(30, 100)\n 0.3\n \"\"\"\n # number of instances in specific class divided by number of all instances\n return instance_count \/ total_count\n\n\n# Calculate the variance\ndef calculate_variance(items: list, means: list, total_count: int) -> float:\n \"\"\"\n Calculate the variance\n :param items: a list containing all items(gaussian distribution of all classes)\n :param means: a list containing real mean values of each class\n :param total_count: the number of all instances\n :return: calculated variance for considered dataset\n\n >>> items = gaussian_distribution(5.0, 1.0, 20)\n >>> means = [5.011267842911003]\n >>> total_count = 20\n >>> calculate_variance([items], means, total_count)\n 0.9618530973487491\n \"\"\"\n squared_diff = [] # An empty list to store all squared differences\n # iterate over number of elements in items\n for i in range(len(items)):\n # for loop iterates over number of elements in inner layer of items\n for j in range(len(items[i])):\n # appending squared differences to 'squared_diff' list\n squared_diff.append((items[i][j] - means[i]) ** 2)\n\n # one divided by (the number of all instances - number of classes) multiplied by\n # sum of all squared differences\n n_classes = len(means) # Number of classes in dataset\n return 1 \/ (total_count - n_classes) * sum(squared_diff)\n\n\n# Making predictions\ndef predict_y_values(\n x_items: list, means: list, variance: float, probabilities: list\n) -> list:\n \"\"\"This function predicts new indexes(groups for our data)\n :param x_items: a list containing all items(gaussian distribution of all classes)\n :param means: a list containing real mean values of each class\n :param variance: calculated value of variance by calculate_variance function\n :param probabilities: a list containing all probabilities of classes\n :return: a list containing predicted Y values\n\n >>> x_items = [[6.288184753155463, 6.4494456086997705, 5.066335808938262,\n ... 4.235456349028368, 3.9078267848958586, 5.031334516831717,\n ... 3.977896829989127, 3.56317055489747, 5.199311976483754,\n ... 5.133374604658605, 5.546468300338232, 4.086029056264687,\n ... 5.005005283626573, 4.935258239627312, 3.494170998739258,\n ... 5.537997178661033, 5.320711100998849, 7.3891120432406865,\n ... 5.202969177309964, 4.855297691835079], [11.288184753155463,\n ... 11.44944560869977, 10.066335808938263, 9.235456349028368,\n ... 8.907826784895859, 10.031334516831716, 8.977896829989128,\n ... 8.56317055489747, 10.199311976483754, 10.133374604658606,\n ... 10.546468300338232, 9.086029056264687, 10.005005283626572,\n ... 9.935258239627313, 8.494170998739259, 10.537997178661033,\n ... 10.320711100998848, 12.389112043240686, 10.202969177309964,\n ... 9.85529769183508], [16.288184753155463, 16.449445608699772,\n ... 15.066335808938263, 14.235456349028368, 13.907826784895859,\n ... 15.031334516831716, 13.977896829989128, 13.56317055489747,\n ... 15.199311976483754, 15.133374604658606, 15.546468300338232,\n ... 14.086029056264687, 15.005005283626572, 14.935258239627313,\n ... 13.494170998739259, 15.537997178661033, 15.320711100998848,\n ... 17.389112043240686, 15.202969177309964, 14.85529769183508]]\n\n >>> means = [5.011267842911003, 10.011267842911003, 15.011267842911002]\n >>> variance = 0.9618530973487494\n >>> probabilities = [0.3333333333333333, 0.3333333333333333, 0.3333333333333333]\n >>> predict_y_values(x_items, means, variance,\n ... probabilities) # doctest: +NORMALIZE_WHITESPACE\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1,\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,\n 2, 2, 2, 2, 2, 2, 2, 2, 2]\n\n \"\"\"\n # An empty list to store generated discriminant values of all items in dataset for\n # each class\n results = []\n # for loop iterates over number of elements in list\n for i in range(len(x_items)):\n # for loop iterates over number of inner items of each element\n for j in range(len(x_items[i])):\n temp = [] # to store all discriminant values of each item as a list\n # for loop iterates over number of classes we have in our dataset\n for k in range(len(x_items)):\n # appending values of discriminants for each class to 'temp' list\n temp.append(\n x_items[i][j] * (means[k] \/ variance)\n - (means[k] ** 2 \/ (2 * variance))\n + log(probabilities[k])\n )\n # appending discriminant values of each item to 'results' list\n results.append(temp)\n\n return [result.index(max(result)) for result in results]\n\n\n# Calculating Accuracy\ndef accuracy(actual_y: list, predicted_y: list) -> float:\n \"\"\"\n Calculate the value of accuracy based-on predictions\n :param actual_y:a list containing initial Y values generated by 'y_generator'\n function\n :param predicted_y: a list containing predicted Y values generated by\n 'predict_y_values' function\n :return: percentage of accuracy\n\n >>> actual_y = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1,\n ... 1, 1 ,1 ,1 ,1 ,1 ,1]\n >>> predicted_y = [0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0,\n ... 0, 0, 1, 1, 1, 0, 1, 1, 1]\n >>> accuracy(actual_y, predicted_y)\n 50.0\n\n >>> actual_y = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1,\n ... 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2]\n >>> predicted_y = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1,\n ... 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2]\n >>> accuracy(actual_y, predicted_y)\n 100.0\n \"\"\"\n # iterate over one element of each list at a time (zip mode)\n # prediction is correct if actual Y value equals to predicted Y value\n correct = sum(1 for i, j in zip(actual_y, predicted_y) if i == j)\n # percentage of accuracy equals to number of correct predictions divided by number\n # of all data and multiplied by 100\n return (correct \/ len(actual_y)) * 100\n\n\nnum = TypeVar(\"num\")\n\n\ndef valid_input(\n input_type: Callable[[object], num], # Usually float or int\n input_msg: str,\n err_msg: str,\n condition: Callable[[num], bool] = lambda x: True,\n default: str | None = None,\n) -> num:\n \"\"\"\n Ask for user value and validate that it fulfill a condition.\n\n :input_type: user input expected type of value\n :input_msg: message to show user in the screen\n :err_msg: message to show in the screen in case of error\n :condition: function that represents the condition that user input is valid.\n :default: Default value in case the user does not type anything\n :return: user's input\n \"\"\"\n while True:\n try:\n user_input = input_type(input(input_msg).strip() or default)\n if condition(user_input):\n return user_input\n else:\n print(f\"{user_input}: {err_msg}\")\n continue\n except ValueError:\n print(\n f\"{user_input}: Incorrect input type, expected {input_type.__name__!r}\"\n )\n\n\n# Main Function\ndef main():\n \"\"\"This function starts execution phase\"\"\"\n while True:\n print(\" Linear Discriminant Analysis \".center(50, \"*\"))\n print(\"*\" * 50, \"\\n\")\n print(\"First of all we should specify the number of classes that\")\n print(\"we want to generate as training dataset\")\n # Trying to get number of classes\n n_classes = valid_input(\n input_type=int,\n condition=lambda x: x > 0,\n input_msg=\"Enter the number of classes (Data Groupings): \",\n err_msg=\"Number of classes should be positive!\",\n )\n\n print(\"-\" * 100)\n\n # Trying to get the value of standard deviation\n std_dev = valid_input(\n input_type=float,\n condition=lambda x: x >= 0,\n input_msg=(\n \"Enter the value of standard deviation\"\n \"(Default value is 1.0 for all classes): \"\n ),\n err_msg=\"Standard deviation should not be negative!\",\n default=\"1.0\",\n )\n\n print(\"-\" * 100)\n\n # Trying to get number of instances in classes and theirs means to generate\n # dataset\n counts = [] # An empty list to store instance counts of classes in dataset\n for i in range(n_classes):\n user_count = valid_input(\n input_type=int,\n condition=lambda x: x > 0,\n input_msg=(f\"Enter The number of instances for class_{i+1}: \"),\n err_msg=\"Number of instances should be positive!\",\n )\n counts.append(user_count)\n print(\"-\" * 100)\n\n # An empty list to store values of user-entered means of classes\n user_means = []\n for a in range(n_classes):\n user_mean = valid_input(\n input_type=float,\n input_msg=(f\"Enter the value of mean for class_{a+1}: \"),\n err_msg=\"This is an invalid value.\",\n )\n user_means.append(user_mean)\n print(\"-\" * 100)\n\n print(\"Standard deviation: \", std_dev)\n # print out the number of instances in classes in separated line\n for i, count in enumerate(counts, 1):\n print(f\"Number of instances in class_{i} is: {count}\")\n print(\"-\" * 100)\n\n # print out mean values of classes separated line\n for i, user_mean in enumerate(user_means, 1):\n print(f\"Mean of class_{i} is: {user_mean}\")\n print(\"-\" * 100)\n\n # Generating training dataset drawn from gaussian distribution\n x = [\n gaussian_distribution(user_means[j], std_dev, counts[j])\n for j in range(n_classes)\n ]\n print(\"Generated Normal Distribution: \\n\", x)\n print(\"-\" * 100)\n\n # Generating Ys to detecting corresponding classes\n y = y_generator(n_classes, counts)\n print(\"Generated Corresponding Ys: \\n\", y)\n print(\"-\" * 100)\n\n # Calculating the value of actual mean for each class\n actual_means = [calculate_mean(counts[k], x[k]) for k in range(n_classes)]\n # for loop iterates over number of elements in 'actual_means' list and print\n # out them in separated line\n for i, actual_mean in enumerate(actual_means, 1):\n print(f\"Actual(Real) mean of class_{i} is: {actual_mean}\")\n print(\"-\" * 100)\n\n # Calculating the value of probabilities for each class\n probabilities = [\n calculate_probabilities(counts[i], sum(counts)) for i in range(n_classes)\n ]\n\n # for loop iterates over number of elements in 'probabilities' list and print\n # out them in separated line\n for i, probability in enumerate(probabilities, 1):\n print(f\"Probability of class_{i} is: {probability}\")\n print(\"-\" * 100)\n\n # Calculating the values of variance for each class\n variance = calculate_variance(x, actual_means, sum(counts))\n print(\"Variance: \", variance)\n print(\"-\" * 100)\n\n # Predicting Y values\n # storing predicted Y values in 'pre_indexes' variable\n pre_indexes = predict_y_values(x, actual_means, variance, probabilities)\n print(\"-\" * 100)\n\n # Calculating Accuracy of the model\n print(f\"Accuracy: {accuracy(y, pre_indexes)}\")\n print(\"-\" * 100)\n print(\" DONE \".center(100, \"+\"))\n\n if input(\"Press any key to restart or 'q' for quit: \").strip().lower() == \"q\":\n print(\"\\n\" + \"GoodBye!\".center(100, \"-\") + \"\\n\")\n break\n system(\"cls\" if name == \"nt\" else \"clear\") # noqa: S605\n\n\nif __name__ == \"__main__\":\n main()\n"} +{"Prompt":"Linear regression is the most basic type of regression commonly used for predictive analysis. The idea is pretty simple: we have a dataset and we have features associated with it. Features should be chosen very cautiously as they determine how much our model will be able to make future predictions. We try to set the weight of these features, over many iterations, so that they best fit our dataset. In this particular code, I had used a CSGO dataset ADR vs Rating. We try to best fit a line through dataset and estimate the parameters. Collect dataset of CSGO The dataset contains ADR vs Rating of a Player :return : dataset obtained from the link, as matrix Run steep gradient descent and updates the Feature vector accordingly :param datax : contains the dataset :param datay : contains the output associated with each dataentry :param lendata : length of the data :param alpha : Learning rate of the model :param theta : Feature vector weight's for our model ;param return : Updated Feature's, using currfeatures alpha gradientw.r.t. feature Return sum of square error for error calculation :param datax : contains our dataset :param datay : contains the output result vector :param lendata : len of the dataset :param theta : contains the feature vector :return : sum of square error computed from given feature's Implement Linear regression over the dataset :param datax : contains our dataset :param datay : contains the output result vector :return : feature for line of best fit Feature vector Return sum of square error for error calculation :param predictedy : contains the output of prediction result vector :param originaly : contains values of expected outcome :return : mean absolute error computed from given feature's Driver function data collectdataset lendata data.shape0 datax np.cnp.oneslendata, data:, :1.astypefloat datay data:, 1.astypefloat theta runlinearregressiondatax, datay lenresult theta.shape1 printResultant Feature vector : for i in rangelenresult: printftheta0, i:.5f if name main: main","Completions":"import numpy as np\nimport requests\n\n\ndef collect_dataset():\n \"\"\"Collect dataset of CSGO\n The dataset contains ADR vs Rating of a Player\n :return : dataset obtained from the link, as matrix\n \"\"\"\n response = requests.get(\n \"https:\/\/raw.githubusercontent.com\/yashLadha\/The_Math_of_Intelligence\/\"\n \"master\/Week1\/ADRvsRating.csv\"\n )\n lines = response.text.splitlines()\n data = []\n for item in lines:\n item = item.split(\",\")\n data.append(item)\n data.pop(0) # This is for removing the labels from the list\n dataset = np.matrix(data)\n return dataset\n\n\ndef run_steep_gradient_descent(data_x, data_y, len_data, alpha, theta):\n \"\"\"Run steep gradient descent and updates the Feature vector accordingly_\n :param data_x : contains the dataset\n :param data_y : contains the output associated with each data-entry\n :param len_data : length of the data_\n :param alpha : Learning rate of the model\n :param theta : Feature vector (weight's for our model)\n ;param return : Updated Feature's, using\n curr_features - alpha_ * gradient(w.r.t. feature)\n \"\"\"\n n = len_data\n\n prod = np.dot(theta, data_x.transpose())\n prod -= data_y.transpose()\n sum_grad = np.dot(prod, data_x)\n theta = theta - (alpha \/ n) * sum_grad\n return theta\n\n\ndef sum_of_square_error(data_x, data_y, len_data, theta):\n \"\"\"Return sum of square error for error calculation\n :param data_x : contains our dataset\n :param data_y : contains the output (result vector)\n :param len_data : len of the dataset\n :param theta : contains the feature vector\n :return : sum of square error computed from given feature's\n \"\"\"\n prod = np.dot(theta, data_x.transpose())\n prod -= data_y.transpose()\n sum_elem = np.sum(np.square(prod))\n error = sum_elem \/ (2 * len_data)\n return error\n\n\ndef run_linear_regression(data_x, data_y):\n \"\"\"Implement Linear regression over the dataset\n :param data_x : contains our dataset\n :param data_y : contains the output (result vector)\n :return : feature for line of best fit (Feature vector)\n \"\"\"\n iterations = 100000\n alpha = 0.0001550\n\n no_features = data_x.shape[1]\n len_data = data_x.shape[0] - 1\n\n theta = np.zeros((1, no_features))\n\n for i in range(iterations):\n theta = run_steep_gradient_descent(data_x, data_y, len_data, alpha, theta)\n error = sum_of_square_error(data_x, data_y, len_data, theta)\n print(f\"At Iteration {i + 1} - Error is {error:.5f}\")\n\n return theta\n\n\ndef mean_absolute_error(predicted_y, original_y):\n \"\"\"Return sum of square error for error calculation\n :param predicted_y : contains the output of prediction (result vector)\n :param original_y : contains values of expected outcome\n :return : mean absolute error computed from given feature's\n \"\"\"\n total = sum(abs(y - predicted_y[i]) for i, y in enumerate(original_y))\n return total \/ len(original_y)\n\n\ndef main():\n \"\"\"Driver function\"\"\"\n data = collect_dataset()\n\n len_data = data.shape[0]\n data_x = np.c_[np.ones(len_data), data[:, :-1]].astype(float)\n data_y = data[:, -1].astype(float)\n\n theta = run_linear_regression(data_x, data_y)\n len_result = theta.shape[1]\n print(\"Resultant Feature vector : \")\n for i in range(len_result):\n print(f\"{theta[0, i]:.5f}\")\n\n\nif __name__ == \"__main__\":\n main()\n"} +{"Prompt":"Locally weighted linear regression, also called local regression, is a type of nonparametric linear regression that prioritizes data closest to a given prediction point. The algorithm estimates the vector of model coefficients using weighted least squares regression: XWXXWy, where X is the design matrix, y is the response vector, and W is the diagonal weight matrix. This implementation calculates w, the weight of the ith training sample, using the Gaussian weight: w expx x2, where x is the ith training sample, x is the prediction point, is the bandwidth, and x is the Euclidean norm also called the 2norm or the L norm. The bandwidth controls how quickly the weight of a training sample decreases as its distance from the prediction point increases. One can think of the Gaussian weight as a bell curve centered around the prediction point: a training sample is weighted lower if it's farther from the center, and controls the spread of the bell curve. Other types of locally weighted regression such as locally estimated scatterplot smoothing LOESS typically use different weight functions. References: https:en.wikipedia.orgwikiLocalregression https:en.wikipedia.orgwikiWeightedleastsquares https:cs229.stanford.edunotes2022fallmainnotes.pdf Calculate the weight of every point in the training data around a given prediction point Args: point: xvalue at which the prediction is being made xtrain: ndarray of xvalues for training tau: bandwidth value, controls how quickly the weight of training values decreases as the distance from the prediction point increases Returns: m x m weight matrix around the prediction point, where m is the size of the training set weightmatrix ... np.array1., 1., ... np.array16.99, 10.34, 21.01,23.68, 24.59,25.69, ... 0.6 ... array1.43807972e207, 0.00000000e000, 0.00000000e000, 0.00000000e000, 0.00000000e000, 0.00000000e000, 0.00000000e000, 0.00000000e000, 0.00000000e000 Calculate the local weights at a given prediction point using the weight matrix for that point Args: point: xvalue at which the prediction is being made xtrain: ndarray of xvalues for training ytrain: ndarray of yvalues for training tau: bandwidth value, controls how quickly the weight of training values decreases as the distance from the prediction point increases Returns: ndarray of local weights localweight ... np.array1., 1., ... np.array16.99, 10.34, 21.01,23.68, 24.59,25.69, ... np.array1.01, 1.66, 3.5, ... 0.6 ... array0.00873174, 0.08272556 Calculate predictions for each point in the training data Args: xtrain: ndarray of xvalues for training ytrain: ndarray of yvalues for training tau: bandwidth value, controls how quickly the weight of training values decreases as the distance from the prediction point increases Returns: ndarray of predictions localweightregression ... np.array16.99, 10.34, 21.01, 23.68, 24.59, 25.69, ... np.array1.01, 1.66, 3.5, ... 0.6 ... array1.07173261, 1.65970737, 3.50160179 Load data from seaborn and split it into x and y points pass No doctests, function is for demo purposes only pairing elements of one and xdata Plot predictions and display the graph pass No doctests, function is for demo purposes only Demo with a dataset from the seaborn module","Completions":"import matplotlib.pyplot as plt\nimport numpy as np\n\n\ndef weight_matrix(point: np.ndarray, x_train: np.ndarray, tau: float) -> np.ndarray:\n \"\"\"\n Calculate the weight of every point in the training data around a given\n prediction point\n\n Args:\n point: x-value at which the prediction is being made\n x_train: ndarray of x-values for training\n tau: bandwidth value, controls how quickly the weight of training values\n decreases as the distance from the prediction point increases\n\n Returns:\n m x m weight matrix around the prediction point, where m is the size of\n the training set\n >>> weight_matrix(\n ... np.array([1., 1.]),\n ... np.array([[16.99, 10.34], [21.01,23.68], [24.59,25.69]]),\n ... 0.6\n ... )\n array([[1.43807972e-207, 0.00000000e+000, 0.00000000e+000],\n [0.00000000e+000, 0.00000000e+000, 0.00000000e+000],\n [0.00000000e+000, 0.00000000e+000, 0.00000000e+000]])\n \"\"\"\n m = len(x_train) # Number of training samples\n weights = np.eye(m) # Initialize weights as identity matrix\n for j in range(m):\n diff = point - x_train[j]\n weights[j, j] = np.exp(diff @ diff.T \/ (-2.0 * tau**2))\n\n return weights\n\n\ndef local_weight(\n point: np.ndarray, x_train: np.ndarray, y_train: np.ndarray, tau: float\n) -> np.ndarray:\n \"\"\"\n Calculate the local weights at a given prediction point using the weight\n matrix for that point\n\n Args:\n point: x-value at which the prediction is being made\n x_train: ndarray of x-values for training\n y_train: ndarray of y-values for training\n tau: bandwidth value, controls how quickly the weight of training values\n decreases as the distance from the prediction point increases\n Returns:\n ndarray of local weights\n >>> local_weight(\n ... np.array([1., 1.]),\n ... np.array([[16.99, 10.34], [21.01,23.68], [24.59,25.69]]),\n ... np.array([[1.01, 1.66, 3.5]]),\n ... 0.6\n ... )\n array([[0.00873174],\n [0.08272556]])\n \"\"\"\n weight_mat = weight_matrix(point, x_train, tau)\n weight = np.linalg.inv(x_train.T @ weight_mat @ x_train) @ (\n x_train.T @ weight_mat @ y_train.T\n )\n\n return weight\n\n\ndef local_weight_regression(\n x_train: np.ndarray, y_train: np.ndarray, tau: float\n) -> np.ndarray:\n \"\"\"\n Calculate predictions for each point in the training data\n\n Args:\n x_train: ndarray of x-values for training\n y_train: ndarray of y-values for training\n tau: bandwidth value, controls how quickly the weight of training values\n decreases as the distance from the prediction point increases\n\n Returns:\n ndarray of predictions\n >>> local_weight_regression(\n ... np.array([[16.99, 10.34], [21.01, 23.68], [24.59, 25.69]]),\n ... np.array([[1.01, 1.66, 3.5]]),\n ... 0.6\n ... )\n array([1.07173261, 1.65970737, 3.50160179])\n \"\"\"\n y_pred = np.zeros(len(x_train)) # Initialize array of predictions\n for i, item in enumerate(x_train):\n y_pred[i] = np.dot(item, local_weight(item, x_train, y_train, tau)).item()\n\n return y_pred\n\n\ndef load_data(\n dataset_name: str, x_name: str, y_name: str\n) -> tuple[np.ndarray, np.ndarray, np.ndarray]:\n \"\"\"\n Load data from seaborn and split it into x and y points\n >>> pass # No doctests, function is for demo purposes only\n \"\"\"\n import seaborn as sns\n\n data = sns.load_dataset(dataset_name)\n x_data = np.array(data[x_name])\n y_data = np.array(data[y_name])\n\n one = np.ones(len(y_data))\n\n # pairing elements of one and x_data\n x_train = np.column_stack((one, x_data))\n\n return x_train, x_data, y_data\n\n\ndef plot_preds(\n x_train: np.ndarray,\n preds: np.ndarray,\n x_data: np.ndarray,\n y_data: np.ndarray,\n x_name: str,\n y_name: str,\n) -> None:\n \"\"\"\n Plot predictions and display the graph\n >>> pass # No doctests, function is for demo purposes only\n \"\"\"\n x_train_sorted = np.sort(x_train, axis=0)\n plt.scatter(x_data, y_data, color=\"blue\")\n plt.plot(\n x_train_sorted[:, 1],\n preds[x_train[:, 1].argsort(0)],\n color=\"yellow\",\n linewidth=5,\n )\n plt.title(\"Local Weighted Regression\")\n plt.xlabel(x_name)\n plt.ylabel(y_name)\n plt.show()\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n\n # Demo with a dataset from the seaborn module\n training_data_x, total_bill, tip = load_data(\"tips\", \"total_bill\", \"tip\")\n predictions = local_weight_regression(training_data_x, tip, 5)\n plot_preds(training_data_x, predictions, total_bill, tip, \"total_bill\", \"tip\")\n"} +{"Prompt":"!usrbinpython Logistic Regression from scratch In62: In63: importing all the required libraries Implementing logistic regression for classification problem Helpful resources: Coursera ML course https:medium.commartinpellalogisticregressionfromscratchinpython124c5636b8ac getipython.runlinemagic'matplotlib', 'inline' In67: sigmoid function or logistic function is used as a hypothesis function in classification problems Also known as Logistic Function. 1 fx 1 e The sigmoid function approaches a value of 1 as its input 'x' becomes increasing positive. Opposite for negative values. Reference: https:en.wikipedia.orgwikiSigmoidfunction param z: input to the function returns: returns value in the range 0 to 1 Examples: sigmoidfunction4 0.9820137900379085 sigmoidfunctionnp.array3, 3 array0.04742587, 0.95257413 sigmoidfunctionnp.array3, 3, 1 array0.04742587, 0.95257413, 0.73105858 sigmoidfunctionnp.array0.01, 2, 1.9 array0.49750002, 0.11920292, 0.13010847 sigmoidfunctionnp.array1.3, 5.3, 12 array0.21416502, 0.9950332 , 0.99999386 sigmoidfunctionnp.array0.01, 0.02, 4.1 array0.50249998, 0.50499983, 0.9836975 sigmoidfunctionnp.array0.8 array0.68997448 Cost function quantifies the error between predicted and expected values. The cost function used in Logistic Regression is called Log Loss or Cross Entropy Function. J 1m y loghx 1 y log1 hx Where: J is the cost that we want to minimize during training m is the number of training examples represents the summation over all training examples y is the actual binary label 0 or 1 for a given example hx is the predicted probability that x belongs to the positive class param h: the output of sigmoid function. It is the estimated probability that the input example 'x' belongs to the positive class param y: the actual binary label associated with input example 'x' Examples: estimations sigmoidfunctionnp.array0.3, 4.3, 8.1 costfunctionhestimations,ynp.array1, 0, 1 0.18937868932131605 estimations sigmoidfunctionnp.array4, 3, 1 costfunctionhestimations,ynp.array1, 0, 0 1.459999655669926 estimations sigmoidfunctionnp.array4, 3, 1 costfunctionhestimations,ynp.array1,0,0 0.1266663223365915 estimations sigmoidfunction0 costfunctionhestimations,ynp.array1 0.6931471805599453 References: https:en.wikipedia.orgwikiLogisticregression here alpha is the learning rate, X is the feature matrix,y is the target matrix In68:","Completions":"#!\/usr\/bin\/python\n\n# Logistic Regression from scratch\n\n# In[62]:\n\n# In[63]:\n\n# importing all the required libraries\n\n\"\"\"\nImplementing logistic regression for classification problem\nHelpful resources:\nCoursera ML course\nhttps:\/\/medium.com\/@martinpella\/logistic-regression-from-scratch-in-python-124c5636b8ac\n\"\"\"\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom sklearn import datasets\n\n# get_ipython().run_line_magic('matplotlib', 'inline')\n\n\n# In[67]:\n\n# sigmoid function or logistic function is used as a hypothesis function in\n# classification problems\n\n\ndef sigmoid_function(z: float | np.ndarray) -> float | np.ndarray:\n \"\"\"\n Also known as Logistic Function.\n\n 1\n f(x) = -------\n 1 + e\u207b\u02e3\n\n The sigmoid function approaches a value of 1 as its input 'x' becomes\n increasing positive. Opposite for negative values.\n\n Reference: https:\/\/en.wikipedia.org\/wiki\/Sigmoid_function\n\n @param z: input to the function\n @returns: returns value in the range 0 to 1\n\n Examples:\n >>> sigmoid_function(4)\n 0.9820137900379085\n >>> sigmoid_function(np.array([-3, 3]))\n array([0.04742587, 0.95257413])\n >>> sigmoid_function(np.array([-3, 3, 1]))\n array([0.04742587, 0.95257413, 0.73105858])\n >>> sigmoid_function(np.array([-0.01, -2, -1.9]))\n array([0.49750002, 0.11920292, 0.13010847])\n >>> sigmoid_function(np.array([-1.3, 5.3, 12]))\n array([0.21416502, 0.9950332 , 0.99999386])\n >>> sigmoid_function(np.array([0.01, 0.02, 4.1]))\n array([0.50249998, 0.50499983, 0.9836975 ])\n >>> sigmoid_function(np.array([0.8]))\n array([0.68997448])\n \"\"\"\n return 1 \/ (1 + np.exp(-z))\n\n\ndef cost_function(h: np.ndarray, y: np.ndarray) -> float:\n \"\"\"\n Cost function quantifies the error between predicted and expected values.\n The cost function used in Logistic Regression is called Log Loss\n or Cross Entropy Function.\n\n J(\u03b8) = (1\/m) * \u03a3 [ -y * log(h\u03b8(x)) - (1 - y) * log(1 - h\u03b8(x)) ]\n\n Where:\n - J(\u03b8) is the cost that we want to minimize during training\n - m is the number of training examples\n - \u03a3 represents the summation over all training examples\n - y is the actual binary label (0 or 1) for a given example\n - h\u03b8(x) is the predicted probability that x belongs to the positive class\n\n @param h: the output of sigmoid function. It is the estimated probability\n that the input example 'x' belongs to the positive class\n\n @param y: the actual binary label associated with input example 'x'\n\n Examples:\n >>> estimations = sigmoid_function(np.array([0.3, -4.3, 8.1]))\n >>> cost_function(h=estimations,y=np.array([1, 0, 1]))\n 0.18937868932131605\n >>> estimations = sigmoid_function(np.array([4, 3, 1]))\n >>> cost_function(h=estimations,y=np.array([1, 0, 0]))\n 1.459999655669926\n >>> estimations = sigmoid_function(np.array([4, -3, -1]))\n >>> cost_function(h=estimations,y=np.array([1,0,0]))\n 0.1266663223365915\n >>> estimations = sigmoid_function(0)\n >>> cost_function(h=estimations,y=np.array([1]))\n 0.6931471805599453\n\n References:\n - https:\/\/en.wikipedia.org\/wiki\/Logistic_regression\n \"\"\"\n return (-y * np.log(h) - (1 - y) * np.log(1 - h)).mean()\n\n\ndef log_likelihood(x, y, weights):\n scores = np.dot(x, weights)\n return np.sum(y * scores - np.log(1 + np.exp(scores)))\n\n\n# here alpha is the learning rate, X is the feature matrix,y is the target matrix\ndef logistic_reg(alpha, x, y, max_iterations=70000):\n theta = np.zeros(x.shape[1])\n\n for iterations in range(max_iterations):\n z = np.dot(x, theta)\n h = sigmoid_function(z)\n gradient = np.dot(x.T, h - y) \/ y.size\n theta = theta - alpha * gradient # updating the weights\n z = np.dot(x, theta)\n h = sigmoid_function(z)\n j = cost_function(h, y)\n if iterations % 100 == 0:\n print(f\"loss: {j} \\t\") # printing the loss after every 100 iterations\n return theta\n\n\n# In[68]:\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n\n iris = datasets.load_iris()\n x = iris.data[:, :2]\n y = (iris.target != 0) * 1\n\n alpha = 0.1\n theta = logistic_reg(alpha, x, y, max_iterations=70000)\n print(\"theta: \", theta) # printing the theta i.e our weights vector\n\n def predict_prob(x):\n return sigmoid_function(\n np.dot(x, theta)\n ) # predicting the value of probability from the logistic regression algorithm\n\n plt.figure(figsize=(10, 6))\n plt.scatter(x[y == 0][:, 0], x[y == 0][:, 1], color=\"b\", label=\"0\")\n plt.scatter(x[y == 1][:, 0], x[y == 1][:, 1], color=\"r\", label=\"1\")\n (x1_min, x1_max) = (x[:, 0].min(), x[:, 0].max())\n (x2_min, x2_max) = (x[:, 1].min(), x[:, 1].max())\n (xx1, xx2) = np.meshgrid(np.linspace(x1_min, x1_max), np.linspace(x2_min, x2_max))\n grid = np.c_[xx1.ravel(), xx2.ravel()]\n probs = predict_prob(grid).reshape(xx1.shape)\n plt.contour(xx1, xx2, probs, [0.5], linewidths=1, colors=\"black\")\n\n plt.legend()\n plt.show()\n"} +{"Prompt":"Calculate the mean binary crossentropy BCE loss between true labels and predicted probabilities. BCE loss quantifies dissimilarity between true labels 0 or 1 and predicted probabilities. It's widely used in binary classification tasks. BCE ytrue lnypred 1 ytrue ln1 ypred Reference: https:en.wikipedia.orgwikiCrossentropy Parameters: ytrue: True binary labels 0 or 1 ypred: Predicted probabilities for class 1 epsilon: Small constant to avoid numerical instability truelabels np.array0, 1, 1, 0, 1 predictedprobs np.array0.2, 0.7, 0.9, 0.3, 0.8 binarycrossentropytruelabels, predictedprobs 0.2529995012327421 truelabels np.array0, 1, 1, 0, 1 predictedprobs np.array0.3, 0.8, 0.9, 0.2 binarycrossentropytruelabels, predictedprobs Traceback most recent call last: ... ValueError: Input arrays must have the same length. Calculate the mean binary focal crossentropy BFCE loss between true labels and predicted probabilities. BFCE loss quantifies dissimilarity between true labels 0 or 1 and predicted probabilities. It's a variation of binary crossentropy that addresses class imbalance by focusing on hard examples. BCFE alpha 1 ypredgamma ytrue logypred 1 alpha ypredgamma 1 ytrue log1 ypred Reference: Lin et al., 2018https:arxiv.orgpdf1708.02002.pdf Parameters: ytrue: True binary labels 0 or 1. ypred: Predicted probabilities for class 1. gamma: Focusing parameter for modulating the loss default: 2.0. alpha: Weighting factor for class 1 default: 0.25. epsilon: Small constant to avoid numerical instability. truelabels np.array0, 1, 1, 0, 1 predictedprobs np.array0.2, 0.7, 0.9, 0.3, 0.8 binaryfocalcrossentropytruelabels, predictedprobs 0.008257977659239775 truelabels np.array0, 1, 1, 0, 1 predictedprobs np.array0.3, 0.8, 0.9, 0.2 binaryfocalcrossentropytruelabels, predictedprobs Traceback most recent call last: ... ValueError: Input arrays must have the same length. Clip predicted probabilities to avoid log0 Calculate categorical crossentropy CCE loss between true class labels and predicted class probabilities. CCE ytrue lnypred Reference: https:en.wikipedia.orgwikiCrossentropy Parameters: ytrue: True class labels onehot encoded ypred: Predicted class probabilities epsilon: Small constant to avoid numerical instability truelabels np.array1, 0, 0, 0, 1, 0, 0, 0, 1 predprobs np.array0.9, 0.1, 0.0, 0.2, 0.7, 0.1, 0.0, 0.1, 0.9 categoricalcrossentropytruelabels, predprobs 0.567395975254385 truelabels np.array1, 0, 0, 1 predprobs np.array0.9, 0.1, 0.0, 0.2, 0.7, 0.1 categoricalcrossentropytruelabels, predprobs Traceback most recent call last: ... ValueError: Input arrays must have the same shape. truelabels np.array2, 0, 1, 1, 0, 0 predprobs np.array0.9, 0.1, 0.0, 0.2, 0.7, 0.1 categoricalcrossentropytruelabels, predprobs Traceback most recent call last: ... ValueError: ytrue must be onehot encoded. truelabels np.array1, 0, 1, 1, 0, 0 predprobs np.array0.9, 0.1, 0.0, 0.2, 0.7, 0.1 categoricalcrossentropytruelabels, predprobs Traceback most recent call last: ... ValueError: ytrue must be onehot encoded. truelabels np.array1, 0, 0, 0, 1, 0 predprobs np.array0.9, 0.1, 0.1, 0.2, 0.7, 0.1 categoricalcrossentropytruelabels, predprobs Traceback most recent call last: ... ValueError: Predicted probabilities must sum to approximately 1. Calculate the mean hinge loss for between true labels and predicted probabilities for training support vector machines SVMs. Hinge loss max0, 1 true pred Reference: https:en.wikipedia.orgwikiHingeloss Args: ytrue: actual values ground truth encoded as 1 or 1 ypred: predicted values truelabels np.array1, 1, 1, 1, 1 pred np.array4, 0.3, 0.7, 5, 10 hingelosstruelabels, pred 1.52 truelabels np.array1, 1, 1, 1, 1, 1 pred np.array4, 0.3, 0.7, 5, 10 hingelosstruelabels, pred Traceback most recent call last: ... ValueError: Length of predicted and actual array must be same. truelabels np.array1, 1, 10, 1, 1 pred np.array4, 0.3, 0.7, 5, 10 hingelosstruelabels, pred Traceback most recent call last: ... ValueError: ytrue can have values 1 or 1 only. Calculate the mean Huber loss between the given ground truth and predicted values. The Huber loss describes the penalty incurred by an estimation procedure, and it serves as a measure of accuracy for regression models. Huber loss 0.5 ytrue ypred2 if ytrue ypred delta delta ytrue ypred 0.5 delta2 otherwise Reference: https:en.wikipedia.orgwikiHuberloss Parameters: ytrue: The true values ground truth ypred: The predicted values truevalues np.array0.9, 10.0, 2.0, 1.0, 5.2 predictedvalues np.array0.8, 2.1, 2.9, 4.2, 5.2 np.isclosehuberlosstruevalues, predictedvalues, 1.0, 2.102 True truelabels np.array11.0, 21.0, 3.32, 4.0, 5.0 predictedprobs np.array8.3, 20.8, 2.9, 11.2, 5.0 np.isclosehuberlosstruelabels, predictedprobs, 1.0, 1.80164 True truelabels np.array11.0, 21.0, 3.32, 4.0 predictedprobs np.array8.3, 20.8, 2.9, 11.2, 5.0 huberlosstruelabels, predictedprobs, 1.0 Traceback most recent call last: ... ValueError: Input arrays must have the same length. Calculate the mean squared error MSE between ground truth and predicted values. MSE measures the squared difference between true values and predicted values, and it serves as a measure of accuracy for regression models. MSE 1n ytrue ypred2 Reference: https:en.wikipedia.orgwikiMeansquarederror Parameters: ytrue: The true values ground truth ypred: The predicted values truevalues np.array1.0, 2.0, 3.0, 4.0, 5.0 predictedvalues np.array0.8, 2.1, 2.9, 4.2, 5.2 np.isclosemeansquarederrortruevalues, predictedvalues, 0.028 True truelabels np.array1.0, 2.0, 3.0, 4.0, 5.0 predictedprobs np.array0.3, 0.8, 0.9, 0.2 meansquarederrortruelabels, predictedprobs Traceback most recent call last: ... ValueError: Input arrays must have the same length. Calculates the Mean Absolute Error MAE between ground truth observed and predicted values. MAE measures the absolute difference between true values and predicted values. Equation: MAE 1n absytrue ypred Reference: https:en.wikipedia.orgwikiMeanabsoluteerror Parameters: ytrue: The true values ground truth ypred: The predicted values truevalues np.array1.0, 2.0, 3.0, 4.0, 5.0 predictedvalues np.array0.8, 2.1, 2.9, 4.2, 5.2 np.isclosemeanabsoluteerrortruevalues, predictedvalues, 0.16 True truevalues np.array1.0, 2.0, 3.0, 4.0, 5.0 predictedvalues np.array0.8, 2.1, 2.9, 4.2, 5.2 np.isclosemeanabsoluteerrortruevalues, predictedvalues, 2.16 False truelabels np.array1.0, 2.0, 3.0, 4.0, 5.0 predictedprobs np.array0.3, 0.8, 0.9, 5.2 meanabsoluteerrortruelabels, predictedprobs Traceback most recent call last: ... ValueError: Input arrays must have the same length. Calculate the mean squared logarithmic error MSLE between ground truth and predicted values. MSLE measures the squared logarithmic difference between true values and predicted values for regression models. It's particularly useful for dealing with skewed or largevalue data, and it's often used when the relative differences between predicted and true values are more important than absolute differences. MSLE 1n log1 ytrue log1 ypred2 Reference: https:insideaiml.comblogMeanSquaredLogarithmicErrorLoss1035 Parameters: ytrue: The true values ground truth ypred: The predicted values truevalues np.array1.0, 2.0, 3.0, 4.0, 5.0 predictedvalues np.array0.8, 2.1, 2.9, 4.2, 5.2 meansquaredlogarithmicerrortruevalues, predictedvalues 0.0030860877925181344 truelabels np.array1.0, 2.0, 3.0, 4.0, 5.0 predictedprobs np.array0.3, 0.8, 0.9, 0.2 meansquaredlogarithmicerrortruelabels, predictedprobs Traceback most recent call last: ... ValueError: Input arrays must have the same length. Calculate the Mean Absolute Percentage Error between ytrue and ypred. Mean Absolute Percentage Error calculates the average of the absolute percentage differences between the predicted and true values. Formula ytrueiYprediytruein Source: https:stephenallwright.comgoodmapescore Parameters: ytrue np.ndarray: Numpy array containing truetarget values. ypred np.ndarray: Numpy array containing predicted values. Returns: float: The Mean Absolute Percentage error between ytrue and ypred. Examples: ytrue np.array10, 20, 30, 40 ypred np.array12, 18, 33, 45 meanabsolutepercentageerrorytrue, ypred 0.13125 ytrue np.array1, 2, 3, 4 ypred np.array2, 3, 4, 5 meanabsolutepercentageerrorytrue, ypred 0.5208333333333333 ytrue np.array34, 37, 44, 47, 48, 48, 46, 43, 32, 27, 26, 24 ypred np.array37, 40, 46, 44, 46, 50, 45, 44, 34, 30, 22, 23 meanabsolutepercentageerrorytrue, ypred 0.064671076436071 Calculate the perplexity for the ytrue and ypred. Compute the Perplexity which useful in predicting language model accuracy in Natural Language Processing NLP. Perplexity is measure of how certain the model in its predictions. Perplexity Loss exp1N lnpx Reference: https:en.wikipedia.orgwikiPerplexity Args: ytrue: Actual label encoded sentences of shape batchsize, sentencelength ypred: Predicted sentences of shape batchsize, sentencelength, vocabsize epsilon: Small floating point number to avoid getting inf for log0 Returns: Perplexity loss between ytrue and ypred. ytrue np.array1, 4, 2, 3 ypred np.array ... 0.28, 0.19, 0.21 , 0.15, 0.15, ... 0.24, 0.19, 0.09, 0.18, 0.27, ... 0.03, 0.26, 0.21, 0.18, 0.30, ... 0.28, 0.10, 0.33, 0.15, 0.12 ... perplexitylossytrue, ypred 5.0247347775367945 ytrue np.array1, 4, 2, 3 ypred np.array ... 0.28, 0.19, 0.21 , 0.15, 0.15, ... 0.24, 0.19, 0.09, 0.18, 0.27, ... 0.30, 0.10, 0.20, 0.15, 0.25, ... 0.03, 0.26, 0.21, 0.18, 0.30, ... 0.28, 0.10, 0.33, 0.15, 0.12, ... 0.30, 0.10, 0.20, 0.15, 0.25, ... perplexitylossytrue, ypred Traceback most recent call last: ... ValueError: Sentence length of ytrue and ypred must be equal. ytrue np.array1, 4, 2, 11 ypred np.array ... 0.28, 0.19, 0.21 , 0.15, 0.15, ... 0.24, 0.19, 0.09, 0.18, 0.27, ... 0.03, 0.26, 0.21, 0.18, 0.30, ... 0.28, 0.10, 0.33, 0.15, 0.12 ... perplexitylossytrue, ypred Traceback most recent call last: ... ValueError: Label value must not be greater than vocabulary size. ytrue np.array1, 4 ypred np.array ... 0.28, 0.19, 0.21 , 0.15, 0.15, ... 0.24, 0.19, 0.09, 0.18, 0.27, ... 0.03, 0.26, 0.21, 0.18, 0.30, ... 0.28, 0.10, 0.33, 0.15, 0.12 ... perplexitylossytrue, ypred Traceback most recent call last: ... ValueError: Batch size of ytrue and ypred must be equal. Matrix to select prediction value only for true class Getting the matrix containing prediction for only true class Calculating perplexity for each sentence","Completions":"import numpy as np\n\n\ndef binary_cross_entropy(\n y_true: np.ndarray, y_pred: np.ndarray, epsilon: float = 1e-15\n) -> float:\n \"\"\"\n Calculate the mean binary cross-entropy (BCE) loss between true labels and predicted\n probabilities.\n\n BCE loss quantifies dissimilarity between true labels (0 or 1) and predicted\n probabilities. It's widely used in binary classification tasks.\n\n BCE = -\u03a3(y_true * ln(y_pred) + (1 - y_true) * ln(1 - y_pred))\n\n Reference: https:\/\/en.wikipedia.org\/wiki\/Cross_entropy\n\n Parameters:\n - y_true: True binary labels (0 or 1)\n - y_pred: Predicted probabilities for class 1\n - epsilon: Small constant to avoid numerical instability\n\n >>> true_labels = np.array([0, 1, 1, 0, 1])\n >>> predicted_probs = np.array([0.2, 0.7, 0.9, 0.3, 0.8])\n >>> binary_cross_entropy(true_labels, predicted_probs)\n 0.2529995012327421\n >>> true_labels = np.array([0, 1, 1, 0, 1])\n >>> predicted_probs = np.array([0.3, 0.8, 0.9, 0.2])\n >>> binary_cross_entropy(true_labels, predicted_probs)\n Traceback (most recent call last):\n ...\n ValueError: Input arrays must have the same length.\n \"\"\"\n if len(y_true) != len(y_pred):\n raise ValueError(\"Input arrays must have the same length.\")\n\n y_pred = np.clip(y_pred, epsilon, 1 - epsilon) # Clip predictions to avoid log(0)\n bce_loss = -(y_true * np.log(y_pred) + (1 - y_true) * np.log(1 - y_pred))\n return np.mean(bce_loss)\n\n\ndef binary_focal_cross_entropy(\n y_true: np.ndarray,\n y_pred: np.ndarray,\n gamma: float = 2.0,\n alpha: float = 0.25,\n epsilon: float = 1e-15,\n) -> float:\n \"\"\"\n Calculate the mean binary focal cross-entropy (BFCE) loss between true labels\n and predicted probabilities.\n\n BFCE loss quantifies dissimilarity between true labels (0 or 1) and predicted\n probabilities. It's a variation of binary cross-entropy that addresses class\n imbalance by focusing on hard examples.\n\n BCFE = -\u03a3(alpha * (1 - y_pred)**gamma * y_true * log(y_pred)\n + (1 - alpha) * y_pred**gamma * (1 - y_true) * log(1 - y_pred))\n\n Reference: [Lin et al., 2018](https:\/\/arxiv.org\/pdf\/1708.02002.pdf)\n\n Parameters:\n - y_true: True binary labels (0 or 1).\n - y_pred: Predicted probabilities for class 1.\n - gamma: Focusing parameter for modulating the loss (default: 2.0).\n - alpha: Weighting factor for class 1 (default: 0.25).\n - epsilon: Small constant to avoid numerical instability.\n\n >>> true_labels = np.array([0, 1, 1, 0, 1])\n >>> predicted_probs = np.array([0.2, 0.7, 0.9, 0.3, 0.8])\n >>> binary_focal_cross_entropy(true_labels, predicted_probs)\n 0.008257977659239775\n >>> true_labels = np.array([0, 1, 1, 0, 1])\n >>> predicted_probs = np.array([0.3, 0.8, 0.9, 0.2])\n >>> binary_focal_cross_entropy(true_labels, predicted_probs)\n Traceback (most recent call last):\n ...\n ValueError: Input arrays must have the same length.\n \"\"\"\n if len(y_true) != len(y_pred):\n raise ValueError(\"Input arrays must have the same length.\")\n # Clip predicted probabilities to avoid log(0)\n y_pred = np.clip(y_pred, epsilon, 1 - epsilon)\n\n bcfe_loss = -(\n alpha * (1 - y_pred) ** gamma * y_true * np.log(y_pred)\n + (1 - alpha) * y_pred**gamma * (1 - y_true) * np.log(1 - y_pred)\n )\n\n return np.mean(bcfe_loss)\n\n\ndef categorical_cross_entropy(\n y_true: np.ndarray, y_pred: np.ndarray, epsilon: float = 1e-15\n) -> float:\n \"\"\"\n Calculate categorical cross-entropy (CCE) loss between true class labels and\n predicted class probabilities.\n\n CCE = -\u03a3(y_true * ln(y_pred))\n\n Reference: https:\/\/en.wikipedia.org\/wiki\/Cross_entropy\n\n Parameters:\n - y_true: True class labels (one-hot encoded)\n - y_pred: Predicted class probabilities\n - epsilon: Small constant to avoid numerical instability\n\n >>> true_labels = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]])\n >>> pred_probs = np.array([[0.9, 0.1, 0.0], [0.2, 0.7, 0.1], [0.0, 0.1, 0.9]])\n >>> categorical_cross_entropy(true_labels, pred_probs)\n 0.567395975254385\n >>> true_labels = np.array([[1, 0], [0, 1]])\n >>> pred_probs = np.array([[0.9, 0.1, 0.0], [0.2, 0.7, 0.1]])\n >>> categorical_cross_entropy(true_labels, pred_probs)\n Traceback (most recent call last):\n ...\n ValueError: Input arrays must have the same shape.\n >>> true_labels = np.array([[2, 0, 1], [1, 0, 0]])\n >>> pred_probs = np.array([[0.9, 0.1, 0.0], [0.2, 0.7, 0.1]])\n >>> categorical_cross_entropy(true_labels, pred_probs)\n Traceback (most recent call last):\n ...\n ValueError: y_true must be one-hot encoded.\n >>> true_labels = np.array([[1, 0, 1], [1, 0, 0]])\n >>> pred_probs = np.array([[0.9, 0.1, 0.0], [0.2, 0.7, 0.1]])\n >>> categorical_cross_entropy(true_labels, pred_probs)\n Traceback (most recent call last):\n ...\n ValueError: y_true must be one-hot encoded.\n >>> true_labels = np.array([[1, 0, 0], [0, 1, 0]])\n >>> pred_probs = np.array([[0.9, 0.1, 0.1], [0.2, 0.7, 0.1]])\n >>> categorical_cross_entropy(true_labels, pred_probs)\n Traceback (most recent call last):\n ...\n ValueError: Predicted probabilities must sum to approximately 1.\n \"\"\"\n if y_true.shape != y_pred.shape:\n raise ValueError(\"Input arrays must have the same shape.\")\n\n if np.any((y_true != 0) & (y_true != 1)) or np.any(y_true.sum(axis=1) != 1):\n raise ValueError(\"y_true must be one-hot encoded.\")\n\n if not np.all(np.isclose(np.sum(y_pred, axis=1), 1, rtol=epsilon, atol=epsilon)):\n raise ValueError(\"Predicted probabilities must sum to approximately 1.\")\n\n y_pred = np.clip(y_pred, epsilon, 1) # Clip predictions to avoid log(0)\n return -np.sum(y_true * np.log(y_pred))\n\n\ndef hinge_loss(y_true: np.ndarray, y_pred: np.ndarray) -> float:\n \"\"\"\n Calculate the mean hinge loss for between true labels and predicted probabilities\n for training support vector machines (SVMs).\n\n Hinge loss = max(0, 1 - true * pred)\n\n Reference: https:\/\/en.wikipedia.org\/wiki\/Hinge_loss\n\n Args:\n - y_true: actual values (ground truth) encoded as -1 or 1\n - y_pred: predicted values\n\n >>> true_labels = np.array([-1, 1, 1, -1, 1])\n >>> pred = np.array([-4, -0.3, 0.7, 5, 10])\n >>> hinge_loss(true_labels, pred)\n 1.52\n >>> true_labels = np.array([-1, 1, 1, -1, 1, 1])\n >>> pred = np.array([-4, -0.3, 0.7, 5, 10])\n >>> hinge_loss(true_labels, pred)\n Traceback (most recent call last):\n ...\n ValueError: Length of predicted and actual array must be same.\n >>> true_labels = np.array([-1, 1, 10, -1, 1])\n >>> pred = np.array([-4, -0.3, 0.7, 5, 10])\n >>> hinge_loss(true_labels, pred)\n Traceback (most recent call last):\n ...\n ValueError: y_true can have values -1 or 1 only.\n \"\"\"\n if len(y_true) != len(y_pred):\n raise ValueError(\"Length of predicted and actual array must be same.\")\n\n if np.any((y_true != -1) & (y_true != 1)):\n raise ValueError(\"y_true can have values -1 or 1 only.\")\n\n hinge_losses = np.maximum(0, 1.0 - (y_true * y_pred))\n return np.mean(hinge_losses)\n\n\ndef huber_loss(y_true: np.ndarray, y_pred: np.ndarray, delta: float) -> float:\n \"\"\"\n Calculate the mean Huber loss between the given ground truth and predicted values.\n\n The Huber loss describes the penalty incurred by an estimation procedure, and it\n serves as a measure of accuracy for regression models.\n\n Huber loss =\n 0.5 * (y_true - y_pred)^2 if |y_true - y_pred| <= delta\n delta * |y_true - y_pred| - 0.5 * delta^2 otherwise\n\n Reference: https:\/\/en.wikipedia.org\/wiki\/Huber_loss\n\n Parameters:\n - y_true: The true values (ground truth)\n - y_pred: The predicted values\n\n >>> true_values = np.array([0.9, 10.0, 2.0, 1.0, 5.2])\n >>> predicted_values = np.array([0.8, 2.1, 2.9, 4.2, 5.2])\n >>> np.isclose(huber_loss(true_values, predicted_values, 1.0), 2.102)\n True\n >>> true_labels = np.array([11.0, 21.0, 3.32, 4.0, 5.0])\n >>> predicted_probs = np.array([8.3, 20.8, 2.9, 11.2, 5.0])\n >>> np.isclose(huber_loss(true_labels, predicted_probs, 1.0), 1.80164)\n True\n >>> true_labels = np.array([11.0, 21.0, 3.32, 4.0])\n >>> predicted_probs = np.array([8.3, 20.8, 2.9, 11.2, 5.0])\n >>> huber_loss(true_labels, predicted_probs, 1.0)\n Traceback (most recent call last):\n ...\n ValueError: Input arrays must have the same length.\n \"\"\"\n if len(y_true) != len(y_pred):\n raise ValueError(\"Input arrays must have the same length.\")\n\n huber_mse = 0.5 * (y_true - y_pred) ** 2\n huber_mae = delta * (np.abs(y_true - y_pred) - 0.5 * delta)\n return np.where(np.abs(y_true - y_pred) <= delta, huber_mse, huber_mae).mean()\n\n\ndef mean_squared_error(y_true: np.ndarray, y_pred: np.ndarray) -> float:\n \"\"\"\n Calculate the mean squared error (MSE) between ground truth and predicted values.\n\n MSE measures the squared difference between true values and predicted values, and it\n serves as a measure of accuracy for regression models.\n\n MSE = (1\/n) * \u03a3(y_true - y_pred)^2\n\n Reference: https:\/\/en.wikipedia.org\/wiki\/Mean_squared_error\n\n Parameters:\n - y_true: The true values (ground truth)\n - y_pred: The predicted values\n\n >>> true_values = np.array([1.0, 2.0, 3.0, 4.0, 5.0])\n >>> predicted_values = np.array([0.8, 2.1, 2.9, 4.2, 5.2])\n >>> np.isclose(mean_squared_error(true_values, predicted_values), 0.028)\n True\n >>> true_labels = np.array([1.0, 2.0, 3.0, 4.0, 5.0])\n >>> predicted_probs = np.array([0.3, 0.8, 0.9, 0.2])\n >>> mean_squared_error(true_labels, predicted_probs)\n Traceback (most recent call last):\n ...\n ValueError: Input arrays must have the same length.\n \"\"\"\n if len(y_true) != len(y_pred):\n raise ValueError(\"Input arrays must have the same length.\")\n\n squared_errors = (y_true - y_pred) ** 2\n return np.mean(squared_errors)\n\n\ndef mean_absolute_error(y_true: np.ndarray, y_pred: np.ndarray) -> float:\n \"\"\"\n Calculates the Mean Absolute Error (MAE) between ground truth (observed)\n and predicted values.\n\n MAE measures the absolute difference between true values and predicted values.\n\n Equation:\n MAE = (1\/n) * \u03a3(abs(y_true - y_pred))\n\n Reference: https:\/\/en.wikipedia.org\/wiki\/Mean_absolute_error\n\n Parameters:\n - y_true: The true values (ground truth)\n - y_pred: The predicted values\n\n >>> true_values = np.array([1.0, 2.0, 3.0, 4.0, 5.0])\n >>> predicted_values = np.array([0.8, 2.1, 2.9, 4.2, 5.2])\n >>> np.isclose(mean_absolute_error(true_values, predicted_values), 0.16)\n True\n >>> true_values = np.array([1.0, 2.0, 3.0, 4.0, 5.0])\n >>> predicted_values = np.array([0.8, 2.1, 2.9, 4.2, 5.2])\n >>> np.isclose(mean_absolute_error(true_values, predicted_values), 2.16)\n False\n >>> true_labels = np.array([1.0, 2.0, 3.0, 4.0, 5.0])\n >>> predicted_probs = np.array([0.3, 0.8, 0.9, 5.2])\n >>> mean_absolute_error(true_labels, predicted_probs)\n Traceback (most recent call last):\n ...\n ValueError: Input arrays must have the same length.\n \"\"\"\n if len(y_true) != len(y_pred):\n raise ValueError(\"Input arrays must have the same length.\")\n\n return np.mean(abs(y_true - y_pred))\n\n\ndef mean_squared_logarithmic_error(y_true: np.ndarray, y_pred: np.ndarray) -> float:\n \"\"\"\n Calculate the mean squared logarithmic error (MSLE) between ground truth and\n predicted values.\n\n MSLE measures the squared logarithmic difference between true values and predicted\n values for regression models. It's particularly useful for dealing with skewed or\n large-value data, and it's often used when the relative differences between\n predicted and true values are more important than absolute differences.\n\n MSLE = (1\/n) * \u03a3(log(1 + y_true) - log(1 + y_pred))^2\n\n Reference: https:\/\/insideaiml.com\/blog\/MeanSquared-Logarithmic-Error-Loss-1035\n\n Parameters:\n - y_true: The true values (ground truth)\n - y_pred: The predicted values\n\n >>> true_values = np.array([1.0, 2.0, 3.0, 4.0, 5.0])\n >>> predicted_values = np.array([0.8, 2.1, 2.9, 4.2, 5.2])\n >>> mean_squared_logarithmic_error(true_values, predicted_values)\n 0.0030860877925181344\n >>> true_labels = np.array([1.0, 2.0, 3.0, 4.0, 5.0])\n >>> predicted_probs = np.array([0.3, 0.8, 0.9, 0.2])\n >>> mean_squared_logarithmic_error(true_labels, predicted_probs)\n Traceback (most recent call last):\n ...\n ValueError: Input arrays must have the same length.\n \"\"\"\n if len(y_true) != len(y_pred):\n raise ValueError(\"Input arrays must have the same length.\")\n\n squared_logarithmic_errors = (np.log1p(y_true) - np.log1p(y_pred)) ** 2\n return np.mean(squared_logarithmic_errors)\n\n\ndef mean_absolute_percentage_error(\n y_true: np.ndarray, y_pred: np.ndarray, epsilon: float = 1e-15\n) -> float:\n \"\"\"\n Calculate the Mean Absolute Percentage Error between y_true and y_pred.\n\n Mean Absolute Percentage Error calculates the average of the absolute\n percentage differences between the predicted and true values.\n\n Formula = (\u03a3|y_true[i]-Y_pred[i]\/y_true[i]|)\/n\n\n Source: https:\/\/stephenallwright.com\/good-mape-score\/\n\n Parameters:\n y_true (np.ndarray): Numpy array containing true\/target values.\n y_pred (np.ndarray): Numpy array containing predicted values.\n\n Returns:\n float: The Mean Absolute Percentage error between y_true and y_pred.\n\n Examples:\n >>> y_true = np.array([10, 20, 30, 40])\n >>> y_pred = np.array([12, 18, 33, 45])\n >>> mean_absolute_percentage_error(y_true, y_pred)\n 0.13125\n\n >>> y_true = np.array([1, 2, 3, 4])\n >>> y_pred = np.array([2, 3, 4, 5])\n >>> mean_absolute_percentage_error(y_true, y_pred)\n 0.5208333333333333\n\n >>> y_true = np.array([34, 37, 44, 47, 48, 48, 46, 43, 32, 27, 26, 24])\n >>> y_pred = np.array([37, 40, 46, 44, 46, 50, 45, 44, 34, 30, 22, 23])\n >>> mean_absolute_percentage_error(y_true, y_pred)\n 0.064671076436071\n \"\"\"\n if len(y_true) != len(y_pred):\n raise ValueError(\"The length of the two arrays should be the same.\")\n\n y_true = np.where(y_true == 0, epsilon, y_true)\n absolute_percentage_diff = np.abs((y_true - y_pred) \/ y_true)\n\n return np.mean(absolute_percentage_diff)\n\n\ndef perplexity_loss(\n y_true: np.ndarray, y_pred: np.ndarray, epsilon: float = 1e-7\n) -> float:\n \"\"\"\n Calculate the perplexity for the y_true and y_pred.\n\n Compute the Perplexity which useful in predicting language model\n accuracy in Natural Language Processing (NLP.)\n Perplexity is measure of how certain the model in its predictions.\n\n Perplexity Loss = exp(-1\/N (\u03a3 ln(p(x)))\n\n Reference:\n https:\/\/en.wikipedia.org\/wiki\/Perplexity\n\n Args:\n y_true: Actual label encoded sentences of shape (batch_size, sentence_length)\n y_pred: Predicted sentences of shape (batch_size, sentence_length, vocab_size)\n epsilon: Small floating point number to avoid getting inf for log(0)\n\n Returns:\n Perplexity loss between y_true and y_pred.\n\n >>> y_true = np.array([[1, 4], [2, 3]])\n >>> y_pred = np.array(\n ... [[[0.28, 0.19, 0.21 , 0.15, 0.15],\n ... [0.24, 0.19, 0.09, 0.18, 0.27]],\n ... [[0.03, 0.26, 0.21, 0.18, 0.30],\n ... [0.28, 0.10, 0.33, 0.15, 0.12]]]\n ... )\n >>> perplexity_loss(y_true, y_pred)\n 5.0247347775367945\n >>> y_true = np.array([[1, 4], [2, 3]])\n >>> y_pred = np.array(\n ... [[[0.28, 0.19, 0.21 , 0.15, 0.15],\n ... [0.24, 0.19, 0.09, 0.18, 0.27],\n ... [0.30, 0.10, 0.20, 0.15, 0.25]],\n ... [[0.03, 0.26, 0.21, 0.18, 0.30],\n ... [0.28, 0.10, 0.33, 0.15, 0.12],\n ... [0.30, 0.10, 0.20, 0.15, 0.25]],]\n ... )\n >>> perplexity_loss(y_true, y_pred)\n Traceback (most recent call last):\n ...\n ValueError: Sentence length of y_true and y_pred must be equal.\n >>> y_true = np.array([[1, 4], [2, 11]])\n >>> y_pred = np.array(\n ... [[[0.28, 0.19, 0.21 , 0.15, 0.15],\n ... [0.24, 0.19, 0.09, 0.18, 0.27]],\n ... [[0.03, 0.26, 0.21, 0.18, 0.30],\n ... [0.28, 0.10, 0.33, 0.15, 0.12]]]\n ... )\n >>> perplexity_loss(y_true, y_pred)\n Traceback (most recent call last):\n ...\n ValueError: Label value must not be greater than vocabulary size.\n >>> y_true = np.array([[1, 4]])\n >>> y_pred = np.array(\n ... [[[0.28, 0.19, 0.21 , 0.15, 0.15],\n ... [0.24, 0.19, 0.09, 0.18, 0.27]],\n ... [[0.03, 0.26, 0.21, 0.18, 0.30],\n ... [0.28, 0.10, 0.33, 0.15, 0.12]]]\n ... )\n >>> perplexity_loss(y_true, y_pred)\n Traceback (most recent call last):\n ...\n ValueError: Batch size of y_true and y_pred must be equal.\n \"\"\"\n\n vocab_size = y_pred.shape[2]\n\n if y_true.shape[0] != y_pred.shape[0]:\n raise ValueError(\"Batch size of y_true and y_pred must be equal.\")\n if y_true.shape[1] != y_pred.shape[1]:\n raise ValueError(\"Sentence length of y_true and y_pred must be equal.\")\n if np.max(y_true) > vocab_size:\n raise ValueError(\"Label value must not be greater than vocabulary size.\")\n\n # Matrix to select prediction value only for true class\n filter_matrix = np.array(\n [[list(np.eye(vocab_size)[word]) for word in sentence] for sentence in y_true]\n )\n\n # Getting the matrix containing prediction for only true class\n true_class_pred = np.sum(y_pred * filter_matrix, axis=2).clip(epsilon, 1)\n\n # Calculating perplexity for each sentence\n perp_losses = np.exp(np.negative(np.mean(np.log(true_class_pred), axis=1)))\n\n return np.mean(perp_losses)\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Mel Frequency Cepstral Coefficients MFCC Calculation MFCC is an algorithm widely used in audio and speech processing to represent the shortterm power spectrum of a sound signal in a more compact and discriminative way. It is particularly popular in speech and audio processing tasks such as speech recognition and speaker identification. How Mel Frequency Cepstral Coefficients are Calculated: 1. Preprocessing: Load an audio signal and normalize it to ensure that the values fall within a specific range e.g., between 1 and 1. Frame the audio signal into overlapping, fixedlength segments, typically using a technique like windowing to reduce spectral leakage. 2. Fourier Transform: Apply a Fast Fourier Transform FFT to each audio frame to convert it from the time domain to the frequency domain. This results in a representation of the audio frame as a sequence of frequency components. 3. Power Spectrum: Calculate the power spectrum by taking the squared magnitude of each frequency component obtained from the FFT. This step measures the energy distribution across different frequency bands. 4. Mel Filterbank: Apply a set of triangular filterbanks spaced in the Mel frequency scale to the power spectrum. These filters mimic the human auditory system's frequency response. Each filterbank sums the power spectrum values within its band. 5. Logarithmic Compression: Take the logarithm typically base 10 of the filterbank values to compress the dynamic range. This step mimics the logarithmic response of the human ear to sound intensity. 6. Discrete Cosine Transform DCT: Apply the Discrete Cosine Transform to the log filterbank energies to obtain the MFCC coefficients. This transformation helps decorrelate the filterbank energies and captures the most important features of the audio signal. 7. Feature Extraction: Select a subset of the DCT coefficients to form the feature vector. Often, the first few coefficients e.g., 1213 are used for most applications. References: MelFrequency Cepstral Coefficients MFCCs: https:en.wikipedia.orgwikiMelfrequencycepstrum Speech and Language Processing by Daniel Jurafsky James H. Martin: https:web.stanford.edujurafskyslp3 Mel Frequency Cepstral Coefficient MFCC tutorial http:practicalcryptography.commiscellaneousmachinelearning guidemelfrequencycepstralcoefficientsmfccs Author: Amir Lavasani Calculate Mel Frequency Cepstral Coefficients MFCCs from an audio signal. Args: audio: The input audio signal. samplerate: The sample rate of the audio signal in Hz. fttsize: The size of the FFT window default is 1024. hoplength: The hop length for frame creation default is 20ms. melfilternum: The number of Mel filters default is 10. dctfilternum: The number of DCT filters default is 40. Returns: A matrix of MFCCs for the input audio. Raises: ValueError: If the input audio is empty. Example: samplerate 44100 Sample rate of 44.1 kHz duration 2.0 Duration of 1 second t np.linspace0, duration, intsamplerate duration, endpointFalse audio 0.5 np.sin2 np.pi 440.0 t Generate a 440 Hz sine wave mfccs mfccaudio, samplerate mfccs.shape 40, 101 normalize audio frame audio into convert to frequency domain For simplicity we will choose the Hanning window. Normalize an audio signal by scaling it to have values between 1 and 1. Args: audio: The input audio signal. Returns: The normalized audio signal. Examples: audio np.array1, 2, 3, 4, 5 normalizedaudio normalizeaudio np.maxnormalizedaudio 1.0 np.minnormalizedaudio 0.2 Divide the entire audio signal by the maximum absolute value Split an audio signal into overlapping frames. Args: audio: The input audio signal. samplerate: The sample rate of the audio signal. hoplength: The length of the hopping default is 20ms. fttsize: The size of the FFT window default is 1024. Returns: An array of overlapping frames. Examples: audio np.array1, 2, 3, 4, 5, 6, 7, 8, 9, 101000 samplerate 8000 frames audioframesaudio, samplerate, hoplength10, fttsize512 frames.shape 126, 512 Pad the audio signal to handle edge cases Calculate the number of frames Initialize an array to store the frames Split the audio signal into frames Calculate the Fast Fourier Transform FFT of windowed audio data. Args: audiowindowed: The windowed audio signal. fttsize: The size of the FFT default is 1024. Returns: The FFT of the audio data. Examples: audiowindowed np.array1.0, 2.0, 3.0, 4.0, 5.0, 6.0 audiofft calculatefftaudiowindowed, fttsize4 np.allcloseaudiofft0, np.array6.00.j, 1.50.8660254j, 1.50.8660254j True Transpose the audio data to have time in rows and channels in columns Initialize an array to store the FFT results Compute FFT for each channel Transpose the FFT results back to the original shape Calculate the power of the audio signal from its FFT. Args: audiofft: The FFT of the audio signal. Returns: The power of the audio signal. Examples: audiofft np.array12j, 23j, 34j, 45j power calculatesignalpoweraudiofft np.allclosepower, np.array5, 13, 25, 41 True Calculate the power by squaring the absolute values of the FFT coefficients Convert a frequency in Hertz to the mel scale. Args: freq: The frequency in Hertz. Returns: The frequency in mel scale. Examples: roundfreqtomel1000, 2 999.99 Use the formula to convert frequency to the mel scale Convert a frequency in the mel scale to Hertz. Args: mels: The frequency in mel scale. Returns: The frequency in Hertz. Examples: roundmeltofreq999.99, 2 1000.01 Use the formula to convert mel scale to frequency Create a Melspaced filter bank for audio processing. Args: samplerate: The sample rate of the audio. melfilternum: The number of mel filters default is 10. fttsize: The size of the FFT default is 1024. Returns: Melspaced filter bank. Examples: roundmelspacedfilterbank8000, 10, 102401, 10 0.0004603981 Calculate filter points and mel frequencies normalize filters taken from the librosa library Generate filters for audio processing. Args: filterpoints: A list of filter points. fttsize: The size of the FFT. Returns: A matrix of filters. Examples: getfiltersnp.array0, 20, 51, 95, 161, 256, dtypeint, 512.shape 4, 257 Linearly increase values from 0 to 1 Linearly decrease values from 1 to 0 Calculate the filter points and frequencies for mel frequency filters. Args: samplerate: The sample rate of the audio. freqmin: The minimum frequency in Hertz. freqhigh: The maximum frequency in Hertz. melfilternum: The number of mel filters default is 10. fttsize: The size of the FFT default is 1024. Returns: Filter points and corresponding frequencies. Examples: filterpoints getfilterpoints8000, 0, 4000, melfilternum4, fttsize512 filterpoints0 array 0, 20, 51, 95, 161, 256 filterpoints1 array 0. , 324.46707094, 799.33254207, 1494.30973963, 2511.42581671, 4000. Convert minimum and maximum frequencies to mel scale Generate equally spaced mel frequencies Convert mel frequencies back to Hertz Calculate filter points as integer values Compute the Discrete Cosine Transform DCT basis matrix. Args: dctfilternum: The number of DCT filters to generate. filternum: The number of the fbank filters. Returns: The DCT basis matrix. Examples: rounddiscretecosinetransform3, 500, 5 0.44721 Example function to calculate Mel Frequency Cepstral Coefficients MFCCs from an audio file. Args: wavfilepath: The path to the WAV audio file. Returns: np.ndarray: The computed MFCCs for the audio. Load the audio from the WAV file Calculate MFCCs","Completions":"import logging\n\nimport numpy as np\nimport scipy.fftpack as fft\nfrom scipy.signal import get_window\n\nlogging.basicConfig(filename=f\"{__file__}.log\", level=logging.INFO)\n\n\ndef mfcc(\n audio: np.ndarray,\n sample_rate: int,\n ftt_size: int = 1024,\n hop_length: int = 20,\n mel_filter_num: int = 10,\n dct_filter_num: int = 40,\n) -> np.ndarray:\n \"\"\"\n Calculate Mel Frequency Cepstral Coefficients (MFCCs) from an audio signal.\n\n Args:\n audio: The input audio signal.\n sample_rate: The sample rate of the audio signal (in Hz).\n ftt_size: The size of the FFT window (default is 1024).\n hop_length: The hop length for frame creation (default is 20ms).\n mel_filter_num: The number of Mel filters (default is 10).\n dct_filter_num: The number of DCT filters (default is 40).\n\n Returns:\n A matrix of MFCCs for the input audio.\n\n Raises:\n ValueError: If the input audio is empty.\n\n Example:\n >>> sample_rate = 44100 # Sample rate of 44.1 kHz\n >>> duration = 2.0 # Duration of 1 second\n >>> t = np.linspace(0, duration, int(sample_rate * duration), endpoint=False)\n >>> audio = 0.5 * np.sin(2 * np.pi * 440.0 * t) # Generate a 440 Hz sine wave\n >>> mfccs = mfcc(audio, sample_rate)\n >>> mfccs.shape\n (40, 101)\n \"\"\"\n logging.info(f\"Sample rate: {sample_rate}Hz\")\n logging.info(f\"Audio duration: {len(audio) \/ sample_rate}s\")\n logging.info(f\"Audio min: {np.min(audio)}\")\n logging.info(f\"Audio max: {np.max(audio)}\")\n\n # normalize audio\n audio_normalized = normalize(audio)\n\n logging.info(f\"Normalized audio min: {np.min(audio_normalized)}\")\n logging.info(f\"Normalized audio max: {np.max(audio_normalized)}\")\n\n # frame audio into\n audio_framed = audio_frames(\n audio_normalized, sample_rate, ftt_size=ftt_size, hop_length=hop_length\n )\n\n logging.info(f\"Framed audio shape: {audio_framed.shape}\")\n logging.info(f\"First frame: {audio_framed[0]}\")\n\n # convert to frequency domain\n # For simplicity we will choose the Hanning window.\n window = get_window(\"hann\", ftt_size, fftbins=True)\n audio_windowed = audio_framed * window\n\n logging.info(f\"Windowed audio shape: {audio_windowed.shape}\")\n logging.info(f\"First frame: {audio_windowed[0]}\")\n\n audio_fft = calculate_fft(audio_windowed, ftt_size)\n logging.info(f\"fft audio shape: {audio_fft.shape}\")\n logging.info(f\"First frame: {audio_fft[0]}\")\n\n audio_power = calculate_signal_power(audio_fft)\n logging.info(f\"power audio shape: {audio_power.shape}\")\n logging.info(f\"First frame: {audio_power[0]}\")\n\n filters = mel_spaced_filterbank(sample_rate, mel_filter_num, ftt_size)\n logging.info(f\"filters shape: {filters.shape}\")\n\n audio_filtered = np.dot(filters, np.transpose(audio_power))\n audio_log = 10.0 * np.log10(audio_filtered)\n logging.info(f\"audio_log shape: {audio_log.shape}\")\n\n dct_filters = discrete_cosine_transform(dct_filter_num, mel_filter_num)\n cepstral_coefficents = np.dot(dct_filters, audio_log)\n\n logging.info(f\"cepstral_coefficents shape: {cepstral_coefficents.shape}\")\n return cepstral_coefficents\n\n\ndef normalize(audio: np.ndarray) -> np.ndarray:\n \"\"\"\n Normalize an audio signal by scaling it to have values between -1 and 1.\n\n Args:\n audio: The input audio signal.\n\n Returns:\n The normalized audio signal.\n\n Examples:\n >>> audio = np.array([1, 2, 3, 4, 5])\n >>> normalized_audio = normalize(audio)\n >>> np.max(normalized_audio)\n 1.0\n >>> np.min(normalized_audio)\n 0.2\n \"\"\"\n # Divide the entire audio signal by the maximum absolute value\n return audio \/ np.max(np.abs(audio))\n\n\ndef audio_frames(\n audio: np.ndarray,\n sample_rate: int,\n hop_length: int = 20,\n ftt_size: int = 1024,\n) -> np.ndarray:\n \"\"\"\n Split an audio signal into overlapping frames.\n\n Args:\n audio: The input audio signal.\n sample_rate: The sample rate of the audio signal.\n hop_length: The length of the hopping (default is 20ms).\n ftt_size: The size of the FFT window (default is 1024).\n\n Returns:\n An array of overlapping frames.\n\n Examples:\n >>> audio = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]*1000)\n >>> sample_rate = 8000\n >>> frames = audio_frames(audio, sample_rate, hop_length=10, ftt_size=512)\n >>> frames.shape\n (126, 512)\n \"\"\"\n\n hop_size = np.round(sample_rate * hop_length \/ 1000).astype(int)\n\n # Pad the audio signal to handle edge cases\n audio = np.pad(audio, int(ftt_size \/ 2), mode=\"reflect\")\n\n # Calculate the number of frames\n frame_count = int((len(audio) - ftt_size) \/ hop_size) + 1\n\n # Initialize an array to store the frames\n frames = np.zeros((frame_count, ftt_size))\n\n # Split the audio signal into frames\n for n in range(frame_count):\n frames[n] = audio[n * hop_size : n * hop_size + ftt_size]\n\n return frames\n\n\ndef calculate_fft(audio_windowed: np.ndarray, ftt_size: int = 1024) -> np.ndarray:\n \"\"\"\n Calculate the Fast Fourier Transform (FFT) of windowed audio data.\n\n Args:\n audio_windowed: The windowed audio signal.\n ftt_size: The size of the FFT (default is 1024).\n\n Returns:\n The FFT of the audio data.\n\n Examples:\n >>> audio_windowed = np.array([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])\n >>> audio_fft = calculate_fft(audio_windowed, ftt_size=4)\n >>> np.allclose(audio_fft[0], np.array([6.0+0.j, -1.5+0.8660254j, -1.5-0.8660254j]))\n True\n \"\"\"\n # Transpose the audio data to have time in rows and channels in columns\n audio_transposed = np.transpose(audio_windowed)\n\n # Initialize an array to store the FFT results\n audio_fft = np.empty(\n (int(1 + ftt_size \/\/ 2), audio_transposed.shape[1]),\n dtype=np.complex64,\n order=\"F\",\n )\n\n # Compute FFT for each channel\n for n in range(audio_fft.shape[1]):\n audio_fft[:, n] = fft.fft(audio_transposed[:, n], axis=0)[: audio_fft.shape[0]]\n\n # Transpose the FFT results back to the original shape\n return np.transpose(audio_fft)\n\n\ndef calculate_signal_power(audio_fft: np.ndarray) -> np.ndarray:\n \"\"\"\n Calculate the power of the audio signal from its FFT.\n\n Args:\n audio_fft: The FFT of the audio signal.\n\n Returns:\n The power of the audio signal.\n\n Examples:\n >>> audio_fft = np.array([1+2j, 2+3j, 3+4j, 4+5j])\n >>> power = calculate_signal_power(audio_fft)\n >>> np.allclose(power, np.array([5, 13, 25, 41]))\n True\n \"\"\"\n # Calculate the power by squaring the absolute values of the FFT coefficients\n return np.square(np.abs(audio_fft))\n\n\ndef freq_to_mel(freq: float) -> float:\n \"\"\"\n Convert a frequency in Hertz to the mel scale.\n\n Args:\n freq: The frequency in Hertz.\n\n Returns:\n The frequency in mel scale.\n\n Examples:\n >>> round(freq_to_mel(1000), 2)\n 999.99\n \"\"\"\n # Use the formula to convert frequency to the mel scale\n return 2595.0 * np.log10(1.0 + freq \/ 700.0)\n\n\ndef mel_to_freq(mels: float) -> float:\n \"\"\"\n Convert a frequency in the mel scale to Hertz.\n\n Args:\n mels: The frequency in mel scale.\n\n Returns:\n The frequency in Hertz.\n\n Examples:\n >>> round(mel_to_freq(999.99), 2)\n 1000.01\n \"\"\"\n # Use the formula to convert mel scale to frequency\n return 700.0 * (10.0 ** (mels \/ 2595.0) - 1.0)\n\n\ndef mel_spaced_filterbank(\n sample_rate: int, mel_filter_num: int = 10, ftt_size: int = 1024\n) -> np.ndarray:\n \"\"\"\n Create a Mel-spaced filter bank for audio processing.\n\n Args:\n sample_rate: The sample rate of the audio.\n mel_filter_num: The number of mel filters (default is 10).\n ftt_size: The size of the FFT (default is 1024).\n\n Returns:\n Mel-spaced filter bank.\n\n Examples:\n >>> round(mel_spaced_filterbank(8000, 10, 1024)[0][1], 10)\n 0.0004603981\n \"\"\"\n freq_min = 0\n freq_high = sample_rate \/\/ 2\n\n logging.info(f\"Minimum frequency: {freq_min}\")\n logging.info(f\"Maximum frequency: {freq_high}\")\n\n # Calculate filter points and mel frequencies\n filter_points, mel_freqs = get_filter_points(\n sample_rate,\n freq_min,\n freq_high,\n mel_filter_num,\n ftt_size,\n )\n\n filters = get_filters(filter_points, ftt_size)\n\n # normalize filters\n # taken from the librosa library\n enorm = 2.0 \/ (mel_freqs[2 : mel_filter_num + 2] - mel_freqs[:mel_filter_num])\n return filters * enorm[:, np.newaxis]\n\n\ndef get_filters(filter_points: np.ndarray, ftt_size: int) -> np.ndarray:\n \"\"\"\n Generate filters for audio processing.\n\n Args:\n filter_points: A list of filter points.\n ftt_size: The size of the FFT.\n\n Returns:\n A matrix of filters.\n\n Examples:\n >>> get_filters(np.array([0, 20, 51, 95, 161, 256], dtype=int), 512).shape\n (4, 257)\n \"\"\"\n num_filters = len(filter_points) - 2\n filters = np.zeros((num_filters, int(ftt_size \/ 2) + 1))\n\n for n in range(num_filters):\n start = filter_points[n]\n mid = filter_points[n + 1]\n end = filter_points[n + 2]\n\n # Linearly increase values from 0 to 1\n filters[n, start:mid] = np.linspace(0, 1, mid - start)\n\n # Linearly decrease values from 1 to 0\n filters[n, mid:end] = np.linspace(1, 0, end - mid)\n\n return filters\n\n\ndef get_filter_points(\n sample_rate: int,\n freq_min: int,\n freq_high: int,\n mel_filter_num: int = 10,\n ftt_size: int = 1024,\n) -> tuple[np.ndarray, np.ndarray]:\n \"\"\"\n Calculate the filter points and frequencies for mel frequency filters.\n\n Args:\n sample_rate: The sample rate of the audio.\n freq_min: The minimum frequency in Hertz.\n freq_high: The maximum frequency in Hertz.\n mel_filter_num: The number of mel filters (default is 10).\n ftt_size: The size of the FFT (default is 1024).\n\n Returns:\n Filter points and corresponding frequencies.\n\n Examples:\n >>> filter_points = get_filter_points(8000, 0, 4000, mel_filter_num=4, ftt_size=512)\n >>> filter_points[0]\n array([ 0, 20, 51, 95, 161, 256])\n >>> filter_points[1]\n array([ 0. , 324.46707094, 799.33254207, 1494.30973963,\n 2511.42581671, 4000. ])\n \"\"\"\n # Convert minimum and maximum frequencies to mel scale\n fmin_mel = freq_to_mel(freq_min)\n fmax_mel = freq_to_mel(freq_high)\n\n logging.info(f\"MEL min: {fmin_mel}\")\n logging.info(f\"MEL max: {fmax_mel}\")\n\n # Generate equally spaced mel frequencies\n mels = np.linspace(fmin_mel, fmax_mel, num=mel_filter_num + 2)\n\n # Convert mel frequencies back to Hertz\n freqs = mel_to_freq(mels)\n\n # Calculate filter points as integer values\n filter_points = np.floor((ftt_size + 1) \/ sample_rate * freqs).astype(int)\n\n return filter_points, freqs\n\n\ndef discrete_cosine_transform(dct_filter_num: int, filter_num: int) -> np.ndarray:\n \"\"\"\n Compute the Discrete Cosine Transform (DCT) basis matrix.\n\n Args:\n dct_filter_num: The number of DCT filters to generate.\n filter_num: The number of the fbank filters.\n\n Returns:\n The DCT basis matrix.\n\n Examples:\n >>> round(discrete_cosine_transform(3, 5)[0][0], 5)\n 0.44721\n \"\"\"\n basis = np.empty((dct_filter_num, filter_num))\n basis[0, :] = 1.0 \/ np.sqrt(filter_num)\n\n samples = np.arange(1, 2 * filter_num, 2) * np.pi \/ (2.0 * filter_num)\n\n for i in range(1, dct_filter_num):\n basis[i, :] = np.cos(i * samples) * np.sqrt(2.0 \/ filter_num)\n\n return basis\n\n\ndef example(wav_file_path: str = \".\/path-to-file\/sample.wav\") -> np.ndarray:\n \"\"\"\n Example function to calculate Mel Frequency Cepstral Coefficients\n (MFCCs) from an audio file.\n\n Args:\n wav_file_path: The path to the WAV audio file.\n\n Returns:\n np.ndarray: The computed MFCCs for the audio.\n \"\"\"\n from scipy.io import wavfile\n\n # Load the audio from the WAV file\n sample_rate, audio = wavfile.read(wav_file_path)\n\n # Calculate MFCCs\n return mfcc(audio, sample_rate)\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"wrapperY 0, 0, 1","Completions":"from sklearn.neural_network import MLPClassifier\n\nX = [[0.0, 0.0], [1.0, 1.0], [1.0, 0.0], [0.0, 1.0]]\ny = [0, 1, 0, 0]\n\n\nclf = MLPClassifier(\n solver=\"lbfgs\", alpha=1e-5, hidden_layer_sizes=(5, 2), random_state=1\n)\n\nclf.fit(X, y)\n\n\ntest = [[0.0, 0.0], [0.0, 1.0], [1.0, 1.0]]\nY = clf.predict(test)\n\n\ndef wrapper(y):\n \"\"\"\n >>> wrapper(Y)\n [0, 0, 1]\n \"\"\"\n return list(y)\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Polynomial regression is a type of regression analysis that models the relationship between a predictor x and the response y as an mthdegree polynomial: y x x ... x By treating x, x, ..., x as distinct variables, we see that polynomial regression is a special case of multiple linear regression. Therefore, we can use ordinary least squares OLS estimation to estimate the vector of model parameters , , , ..., for polynomial regression: XXXy Xy where X is the design matrix, y is the response vector, and X denotes the MoorePenrose pseudoinverse of X. In the case of polynomial regression, the design matrix is 1 x x x X 1 x x x 1 x x x In OLS estimation, inverting XX to compute X can be very numerically unstable. This implementation sidesteps this need to invert XX by computing X using singular value decomposition SVD: VUy where UV is an SVD of X. References: https:en.wikipedia.orgwikiPolynomialregression https:en.wikipedia.orgwikiMooreE28093Penroseinverse https:en.wikipedia.orgwikiNumericalmethodsforlinearleastsquares https:en.wikipedia.orgwikiSingularvaluedecomposition raises ValueError: if the polynomial degree is negative Constructs a polynomial regression design matrix for the given input data. For input data x x, x, ..., x and polynomial degree m, the design matrix is the Vandermonde matrix 1 x x x X 1 x x x 1 x x x Reference: https:en.wikipedia.orgwikiVandermondematrix param data: the input predictor values x, either for model fitting or for prediction param degree: the polynomial degree m returns: the Vandermonde matrix X see above raises ValueError: if input data is not N x 1 x np.array0, 1, 2 PolynomialRegression.designmatrixx, degree0 array1, 1, 1 PolynomialRegression.designmatrixx, degree1 array1, 0, 1, 1, 1, 2 PolynomialRegression.designmatrixx, degree2 array1, 0, 0, 1, 1, 1, 1, 2, 4 PolynomialRegression.designmatrixx, degree3 array1, 0, 0, 0, 1, 1, 1, 1, 1, 2, 4, 8 PolynomialRegression.designmatrixnp.array0, 0, 0 , 0, degree3 Traceback most recent call last: ... ValueError: Data must have dimensions N x 1 Computes the polynomial regression model parameters using ordinary least squares OLS estimation: XXXy Xy where X denotes the MoorePenrose pseudoinverse of the design matrix X. This function computes X using singular value decomposition SVD. References: https:en.wikipedia.orgwikiMooreE28093Penroseinverse https:en.wikipedia.orgwikiSingularvaluedecomposition https:en.wikipedia.orgwikiMulticollinearity param xtrain: the predictor values x for model fitting param ytrain: the response values y for model fitting raises ArithmeticError: if X isn't full rank, then XX is singular and doesn't exist x np.array0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 y x3 2 x2 3 x 5 polyreg PolynomialRegressiondegree3 polyreg.fitx, y polyreg.params array5., 3., 2., 1. polyreg PolynomialRegressiondegree20 polyreg.fitx, y Traceback most recent call last: ... ArithmeticError: Design matrix is not full rank, can't compute coefficients Make sure errors don't grow too large: coefs np.array250, 50, 2, 36, 20, 12, 10, 2, 1, 15, 1 y PolynomialRegression.designmatrixx, lencoefs 1 coefs polyreg PolynomialRegressiondegreelencoefs 1 polyreg.fitx, y np.allclosepolyreg.params, coefs, atol10e3 True np.linalg.pinv computes the MoorePenrose pseudoinverse using SVD Computes the predicted response values y for the given input data by constructing the design matrix X and evaluating y X. param data: the predictor values x for prediction returns: the predicted response values y X raises ArithmeticError: if this function is called before the model parameters are fit x np.array0, 1, 2, 3, 4 y x3 2 x2 3 x 5 polyreg PolynomialRegressiondegree3 polyreg.fitx, y polyreg.predictnp.array1 array11. polyreg.predictnp.array2 array27. polyreg.predictnp.array6 array157. PolynomialRegressiondegree3.predictx Traceback most recent call last: ... ArithmeticError: Predictor hasn't been fit yet Fit a polynomial regression model to predict fuel efficiency using seaborn's mpg dataset pass Placeholder, function is only for demo purposes","Completions":"import matplotlib.pyplot as plt\nimport numpy as np\n\n\nclass PolynomialRegression:\n __slots__ = \"degree\", \"params\"\n\n def __init__(self, degree: int) -> None:\n \"\"\"\n @raises ValueError: if the polynomial degree is negative\n \"\"\"\n if degree < 0:\n raise ValueError(\"Polynomial degree must be non-negative\")\n\n self.degree = degree\n self.params = None\n\n @staticmethod\n def _design_matrix(data: np.ndarray, degree: int) -> np.ndarray:\n \"\"\"\n Constructs a polynomial regression design matrix for the given input data. For\n input data x = (x\u2081, x\u2082, ..., x\u2099) and polynomial degree m, the design matrix is\n the Vandermonde matrix\n\n |1 x\u2081 x\u2081\u00b2 \u22ef x\u2081\u1d50|\n X = |1 x\u2082 x\u2082\u00b2 \u22ef x\u2082\u1d50|\n |\u22ee \u22ee \u22ee \u22f1 \u22ee |\n |1 x\u2099 x\u2099\u00b2 \u22ef x\u2099\u1d50|\n\n Reference: https:\/\/en.wikipedia.org\/wiki\/Vandermonde_matrix\n\n @param data: the input predictor values x, either for model fitting or for\n prediction\n @param degree: the polynomial degree m\n @returns: the Vandermonde matrix X (see above)\n @raises ValueError: if input data is not N x 1\n\n >>> x = np.array([0, 1, 2])\n >>> PolynomialRegression._design_matrix(x, degree=0)\n array([[1],\n [1],\n [1]])\n >>> PolynomialRegression._design_matrix(x, degree=1)\n array([[1, 0],\n [1, 1],\n [1, 2]])\n >>> PolynomialRegression._design_matrix(x, degree=2)\n array([[1, 0, 0],\n [1, 1, 1],\n [1, 2, 4]])\n >>> PolynomialRegression._design_matrix(x, degree=3)\n array([[1, 0, 0, 0],\n [1, 1, 1, 1],\n [1, 2, 4, 8]])\n >>> PolynomialRegression._design_matrix(np.array([[0, 0], [0 , 0]]), degree=3)\n Traceback (most recent call last):\n ...\n ValueError: Data must have dimensions N x 1\n \"\"\"\n rows, *remaining = data.shape\n if remaining:\n raise ValueError(\"Data must have dimensions N x 1\")\n\n return np.vander(data, N=degree + 1, increasing=True)\n\n def fit(self, x_train: np.ndarray, y_train: np.ndarray) -> None:\n \"\"\"\n Computes the polynomial regression model parameters using ordinary least squares\n (OLS) estimation:\n\n \u03b2 = (X\u1d40X)\u207b\u00b9X\u1d40y = X\u207ay\n\n where X\u207a denotes the Moore\u2013Penrose pseudoinverse of the design matrix X. This\n function computes X\u207a using singular value decomposition (SVD).\n\n References:\n - https:\/\/en.wikipedia.org\/wiki\/Moore%E2%80%93Penrose_inverse\n - https:\/\/en.wikipedia.org\/wiki\/Singular_value_decomposition\n - https:\/\/en.wikipedia.org\/wiki\/Multicollinearity\n\n @param x_train: the predictor values x for model fitting\n @param y_train: the response values y for model fitting\n @raises ArithmeticError: if X isn't full rank, then X\u1d40X is singular and \u03b2\n doesn't exist\n\n >>> x = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])\n >>> y = x**3 - 2 * x**2 + 3 * x - 5\n >>> poly_reg = PolynomialRegression(degree=3)\n >>> poly_reg.fit(x, y)\n >>> poly_reg.params\n array([-5., 3., -2., 1.])\n >>> poly_reg = PolynomialRegression(degree=20)\n >>> poly_reg.fit(x, y)\n Traceback (most recent call last):\n ...\n ArithmeticError: Design matrix is not full rank, can't compute coefficients\n\n Make sure errors don't grow too large:\n >>> coefs = np.array([-250, 50, -2, 36, 20, -12, 10, 2, -1, -15, 1])\n >>> y = PolynomialRegression._design_matrix(x, len(coefs) - 1) @ coefs\n >>> poly_reg = PolynomialRegression(degree=len(coefs) - 1)\n >>> poly_reg.fit(x, y)\n >>> np.allclose(poly_reg.params, coefs, atol=10e-3)\n True\n \"\"\"\n X = PolynomialRegression._design_matrix(x_train, self.degree) # noqa: N806\n _, cols = X.shape\n if np.linalg.matrix_rank(X) < cols:\n raise ArithmeticError(\n \"Design matrix is not full rank, can't compute coefficients\"\n )\n\n # np.linalg.pinv() computes the Moore\u2013Penrose pseudoinverse using SVD\n self.params = np.linalg.pinv(X) @ y_train\n\n def predict(self, data: np.ndarray) -> np.ndarray:\n \"\"\"\n Computes the predicted response values y for the given input data by\n constructing the design matrix X and evaluating y = X\u03b2.\n\n @param data: the predictor values x for prediction\n @returns: the predicted response values y = X\u03b2\n @raises ArithmeticError: if this function is called before the model\n parameters are fit\n\n >>> x = np.array([0, 1, 2, 3, 4])\n >>> y = x**3 - 2 * x**2 + 3 * x - 5\n >>> poly_reg = PolynomialRegression(degree=3)\n >>> poly_reg.fit(x, y)\n >>> poly_reg.predict(np.array([-1]))\n array([-11.])\n >>> poly_reg.predict(np.array([-2]))\n array([-27.])\n >>> poly_reg.predict(np.array([6]))\n array([157.])\n >>> PolynomialRegression(degree=3).predict(x)\n Traceback (most recent call last):\n ...\n ArithmeticError: Predictor hasn't been fit yet\n \"\"\"\n if self.params is None:\n raise ArithmeticError(\"Predictor hasn't been fit yet\")\n\n return PolynomialRegression._design_matrix(data, self.degree) @ self.params\n\n\ndef main() -> None:\n \"\"\"\n Fit a polynomial regression model to predict fuel efficiency using seaborn's mpg\n dataset\n\n >>> pass # Placeholder, function is only for demo purposes\n \"\"\"\n import seaborn as sns\n\n mpg_data = sns.load_dataset(\"mpg\")\n\n poly_reg = PolynomialRegression(degree=2)\n poly_reg.fit(mpg_data.weight, mpg_data.mpg)\n\n weight_sorted = np.sort(mpg_data.weight)\n predictions = poly_reg.predict(weight_sorted)\n\n plt.scatter(mpg_data.weight, mpg_data.mpg, color=\"gray\", alpha=0.5)\n plt.plot(weight_sorted, predictions, color=\"red\", linewidth=3)\n plt.title(\"Predicting Fuel Efficiency Using Polynomial Regression\")\n plt.xlabel(\"Weight (lbs)\")\n plt.ylabel(\"Fuel Efficiency (mpg)\")\n plt.show()\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n\n main()\n"} +{"Prompt":"Here I implemented the scoring functions. MAE, MSE, RMSE, RMSLE are included. Those are used for calculating differences between predicted values and actual values. Metrics are slightly differentiated. Sometimes squared, rooted, even log is used. Using log and roots can be perceived as tools for penalizing big errors. However, using appropriate metrics depends on the situations, and types of data Mean Absolute Error Examplesrounded for precision: actual 1,2,3;predict 1,4,3 np.aroundmaepredict,actual,decimals 2 0.67 actual 1,1,1;predict 1,1,1 maepredict,actual 0.0 Mean Squared Error Examplesrounded for precision: actual 1,2,3;predict 1,4,3 np.aroundmsepredict,actual,decimals 2 1.33 actual 1,1,1;predict 1,1,1 msepredict,actual 0.0 Root Mean Squared Error Examplesrounded for precision: actual 1,2,3;predict 1,4,3 np.aroundrmsepredict,actual,decimals 2 1.15 actual 1,1,1;predict 1,1,1 rmsepredict,actual 0.0 Root Mean Square Logarithmic Error Examplesrounded for precision: actual 10,10,30;predict 10,2,30 np.aroundrmslepredict,actual,decimals 2 0.75 actual 1,1,1;predict 1,1,1 rmslepredict,actual 0.0 Mean Bias Deviation This value is Negative, if the model underpredicts, positive, if it overpredicts. Examplerounded for precision: Here the model overpredicts actual 1,2,3;predict 2,3,4 np.aroundmbdpredict,actual,decimals 2 50.0 Here the model underpredicts actual 1,2,3;predict 0,1,1 np.aroundmbdpredict,actual,decimals 2 66.67 printnumerator, denumerator","Completions":"import numpy as np\n\n\"\"\" Here I implemented the scoring functions.\n MAE, MSE, RMSE, RMSLE are included.\n\n Those are used for calculating differences between\n predicted values and actual values.\n\n Metrics are slightly differentiated. Sometimes squared, rooted,\n even log is used.\n\n Using log and roots can be perceived as tools for penalizing big\n errors. However, using appropriate metrics depends on the situations,\n and types of data\n\"\"\"\n\n\n# Mean Absolute Error\ndef mae(predict, actual):\n \"\"\"\n Examples(rounded for precision):\n >>> actual = [1,2,3];predict = [1,4,3]\n >>> np.around(mae(predict,actual),decimals = 2)\n 0.67\n\n >>> actual = [1,1,1];predict = [1,1,1]\n >>> mae(predict,actual)\n 0.0\n \"\"\"\n predict = np.array(predict)\n actual = np.array(actual)\n\n difference = abs(predict - actual)\n score = difference.mean()\n\n return score\n\n\n# Mean Squared Error\ndef mse(predict, actual):\n \"\"\"\n Examples(rounded for precision):\n >>> actual = [1,2,3];predict = [1,4,3]\n >>> np.around(mse(predict,actual),decimals = 2)\n 1.33\n\n >>> actual = [1,1,1];predict = [1,1,1]\n >>> mse(predict,actual)\n 0.0\n \"\"\"\n predict = np.array(predict)\n actual = np.array(actual)\n\n difference = predict - actual\n square_diff = np.square(difference)\n\n score = square_diff.mean()\n return score\n\n\n# Root Mean Squared Error\ndef rmse(predict, actual):\n \"\"\"\n Examples(rounded for precision):\n >>> actual = [1,2,3];predict = [1,4,3]\n >>> np.around(rmse(predict,actual),decimals = 2)\n 1.15\n\n >>> actual = [1,1,1];predict = [1,1,1]\n >>> rmse(predict,actual)\n 0.0\n \"\"\"\n predict = np.array(predict)\n actual = np.array(actual)\n\n difference = predict - actual\n square_diff = np.square(difference)\n mean_square_diff = square_diff.mean()\n score = np.sqrt(mean_square_diff)\n return score\n\n\n# Root Mean Square Logarithmic Error\ndef rmsle(predict, actual):\n \"\"\"\n Examples(rounded for precision):\n >>> actual = [10,10,30];predict = [10,2,30]\n >>> np.around(rmsle(predict,actual),decimals = 2)\n 0.75\n\n >>> actual = [1,1,1];predict = [1,1,1]\n >>> rmsle(predict,actual)\n 0.0\n \"\"\"\n predict = np.array(predict)\n actual = np.array(actual)\n\n log_predict = np.log(predict + 1)\n log_actual = np.log(actual + 1)\n\n difference = log_predict - log_actual\n square_diff = np.square(difference)\n mean_square_diff = square_diff.mean()\n\n score = np.sqrt(mean_square_diff)\n\n return score\n\n\n# Mean Bias Deviation\ndef mbd(predict, actual):\n \"\"\"\n This value is Negative, if the model underpredicts,\n positive, if it overpredicts.\n\n Example(rounded for precision):\n\n Here the model overpredicts\n >>> actual = [1,2,3];predict = [2,3,4]\n >>> np.around(mbd(predict,actual),decimals = 2)\n 50.0\n\n Here the model underpredicts\n >>> actual = [1,2,3];predict = [0,1,1]\n >>> np.around(mbd(predict,actual),decimals = 2)\n -66.67\n \"\"\"\n predict = np.array(predict)\n actual = np.array(actual)\n\n difference = predict - actual\n numerator = np.sum(difference) \/ len(predict)\n denumerator = np.sum(actual) \/ len(predict)\n # print(numerator, denumerator)\n score = float(numerator) \/ denumerator * 100\n\n return score\n\n\ndef manual_accuracy(predict, actual):\n return np.mean(np.array(actual) == np.array(predict))\n"} +{"Prompt":"https:en.wikipedia.orgwikiSelforganizingmap Compute the winning vector by Euclidean distance SelfOrganizingMap.getwinner1, 2, 3, 4, 5, 6, 1, 2, 3 1 Update the winning vector. SelfOrganizingMap.update1, 2, 3, 4, 5, 6, 1, 2, 3, 1, 0.1 1, 2, 3, 3.7, 4.7, 6 Driver code Training Examples m, n weight initialization n, C training training sample Compute the winning vector Update the winning vector classify test sample results running the main function","Completions":"import math\n\n\nclass SelfOrganizingMap:\n def get_winner(self, weights: list[list[float]], sample: list[int]) -> int:\n \"\"\"\n Compute the winning vector by Euclidean distance\n\n >>> SelfOrganizingMap().get_winner([[1, 2, 3], [4, 5, 6]], [1, 2, 3])\n 1\n \"\"\"\n d0 = 0.0\n d1 = 0.0\n for i in range(len(sample)):\n d0 += math.pow((sample[i] - weights[0][i]), 2)\n d1 += math.pow((sample[i] - weights[1][i]), 2)\n return 0 if d0 > d1 else 1\n return 0\n\n def update(\n self, weights: list[list[int | float]], sample: list[int], j: int, alpha: float\n ) -> list[list[int | float]]:\n \"\"\"\n Update the winning vector.\n\n >>> SelfOrganizingMap().update([[1, 2, 3], [4, 5, 6]], [1, 2, 3], 1, 0.1)\n [[1, 2, 3], [3.7, 4.7, 6]]\n \"\"\"\n for i in range(len(weights)):\n weights[j][i] += alpha * (sample[i] - weights[j][i])\n return weights\n\n\n# Driver code\ndef main() -> None:\n # Training Examples ( m, n )\n training_samples = [[1, 1, 0, 0], [0, 0, 0, 1], [1, 0, 0, 0], [0, 0, 1, 1]]\n\n # weight initialization ( n, C )\n weights = [[0.2, 0.6, 0.5, 0.9], [0.8, 0.4, 0.7, 0.3]]\n\n # training\n self_organizing_map = SelfOrganizingMap()\n epochs = 3\n alpha = 0.5\n\n for _ in range(epochs):\n for j in range(len(training_samples)):\n # training sample\n sample = training_samples[j]\n\n # Compute the winning vector\n winner = self_organizing_map.get_winner(weights, sample)\n\n # Update the winning vector\n weights = self_organizing_map.update(weights, sample, winner, alpha)\n\n # classify test sample\n sample = [0, 0, 0, 1]\n winner = self_organizing_map.get_winner(weights, sample)\n\n # results\n print(f\"Clusters that the test sample belongs to : {winner}\")\n print(f\"Weights that have been trained : {weights}\")\n\n\n# running the main() function\nif __name__ == \"__main__\":\n main()\n"} +{"Prompt":"Implementation of sequential minimal optimization SMO for support vector machines SVM. Sequential minimal optimization SMO is an algorithm for solving the quadratic programming QP problem that arises during the training of support vector machines. It was invented by John Platt in 1998. Input: 0: type: numpy.ndarray. 1: first column of ndarray must be tags of samples, must be 1 or 1. 2: rows of ndarray represent samples. Usage: Command: python3 sequentialminimumoptimization.py Code: from sequentialminimumoptimization import SmoSVM, Kernel kernel Kernelkernel'poly', degree3., coef01., gamma0.5 initalphas np.zerostrain.shape0 SVM SmoSVMtraintrain, alphalistinitalphas, kernelfunckernel, cost0.4, b0.0, tolerance0.001 SVM.fit predict SVM.predicttestsamples Reference: https:www.microsoft.comenusresearchwpcontentuploads201602smobook.pdf https:www.microsoft.comenusresearchwpcontentuploads201602tr9814.pdf Calculate alphas using SMO algorithm 1: Find alpha1, alpha2 2: calculate new alpha2 and new alpha1 3: update thresholdb 4: update error value,here we only calculate those nonbound samples' error if i1 or i2 is nonbound,update there error value to zero Predict test samples Check if alpha violate KKT condition Get value calculated from kernel function for test samples,use Kernel function for train samples,Kernel values have been saved in matrix Get sample's error Two cases: 1:Sampleindex is nonbound,Fetch error from list: error 2:sampleindex is bound,Use predicted value deduct true value: gxi yi get from error data get by gxi yi Calculate Kernel matrix of all possible i1,i2 ,saving time Predict test sample's tag Choose alpha1 and alpha2 Choose first alpha ;steps: 1:First loop over all sample 2:Second loop over all nonbound samples till all nonbound samples does not voilate kkt condition. 3:Repeat this two process endlessly,till all samples does not voilate kkt condition samples after first loop. all sample nonbound sample Choose the second alpha by using heuristic algorithm ;steps: 1: Choose alpha2 which gets the maximum step size E1 E2. 2: Start in a random point,loop over all nonbound samples till alpha1 and alpha2 are optimized. 3: Start in a random point,loop over all samples till alpha1 and alpha2 are optimized. Get the new alpha2 and new alpha1 calculate L and H which bound the new alpha2 calculate eta select the new alpha2 which could get the minimal objectives a2new has a boundary way 1 way 2 Use objective function check which alpha2 new could get the minimal objectives a1new has a boundary too Normalise data using minmax way 0: download dataset and load into pandas' dataframe 1: preprocessing data 2: dividing data into traindata data and testdata data 3: choose kernel function,and set initial alphas to zerooptional 4: calculating best alphas using SMO algorithm and predict testdata samples 5: check accuracy change stdout We can not get the optimum w of our kernel svm model which is different from linear svm. For this reason, we generate randomly distributed points with high desity and prediced values of these points are calculated by using our trained model. Then we could use this prediced values to draw contour map. And this contour map can represent svm's partition boundary. Plot contour map which represents the partition boundary Plot all train samples Plot support vectors","Completions":"import os\nimport sys\nimport urllib.request\n\nimport numpy as np\nimport pandas as pd\nfrom matplotlib import pyplot as plt\nfrom sklearn.datasets import make_blobs, make_circles\nfrom sklearn.preprocessing import StandardScaler\n\nCANCER_DATASET_URL = (\n \"https:\/\/archive.ics.uci.edu\/ml\/machine-learning-databases\/\"\n \"breast-cancer-wisconsin\/wdbc.data\"\n)\n\n\nclass SmoSVM:\n def __init__(\n self,\n train,\n kernel_func,\n alpha_list=None,\n cost=0.4,\n b=0.0,\n tolerance=0.001,\n auto_norm=True,\n ):\n self._init = True\n self._auto_norm = auto_norm\n self._c = np.float64(cost)\n self._b = np.float64(b)\n self._tol = np.float64(tolerance) if tolerance > 0.0001 else np.float64(0.001)\n\n self.tags = train[:, 0]\n self.samples = self._norm(train[:, 1:]) if self._auto_norm else train[:, 1:]\n self.alphas = alpha_list if alpha_list is not None else np.zeros(train.shape[0])\n self.Kernel = kernel_func\n\n self._eps = 0.001\n self._all_samples = list(range(self.length))\n self._K_matrix = self._calculate_k_matrix()\n self._error = np.zeros(self.length)\n self._unbound = []\n\n self.choose_alpha = self._choose_alphas()\n\n # Calculate alphas using SMO algorithm\n def fit(self):\n k = self._k\n state = None\n while True:\n # 1: Find alpha1, alpha2\n try:\n i1, i2 = self.choose_alpha.send(state)\n state = None\n except StopIteration:\n print(\"Optimization done!\\nEvery sample satisfy the KKT condition!\")\n break\n\n # 2: calculate new alpha2 and new alpha1\n y1, y2 = self.tags[i1], self.tags[i2]\n a1, a2 = self.alphas[i1].copy(), self.alphas[i2].copy()\n e1, e2 = self._e(i1), self._e(i2)\n args = (i1, i2, a1, a2, e1, e2, y1, y2)\n a1_new, a2_new = self._get_new_alpha(*args)\n if not a1_new and not a2_new:\n state = False\n continue\n self.alphas[i1], self.alphas[i2] = a1_new, a2_new\n\n # 3: update threshold(b)\n b1_new = np.float64(\n -e1\n - y1 * k(i1, i1) * (a1_new - a1)\n - y2 * k(i2, i1) * (a2_new - a2)\n + self._b\n )\n b2_new = np.float64(\n -e2\n - y2 * k(i2, i2) * (a2_new - a2)\n - y1 * k(i1, i2) * (a1_new - a1)\n + self._b\n )\n if 0.0 < a1_new < self._c:\n b = b1_new\n if 0.0 < a2_new < self._c:\n b = b2_new\n if not (np.float64(0) < a2_new < self._c) and not (\n np.float64(0) < a1_new < self._c\n ):\n b = (b1_new + b2_new) \/ 2.0\n b_old = self._b\n self._b = b\n\n # 4: update error value,here we only calculate those non-bound samples'\n # error\n self._unbound = [i for i in self._all_samples if self._is_unbound(i)]\n for s in self.unbound:\n if s in (i1, i2):\n continue\n self._error[s] += (\n y1 * (a1_new - a1) * k(i1, s)\n + y2 * (a2_new - a2) * k(i2, s)\n + (self._b - b_old)\n )\n\n # if i1 or i2 is non-bound,update there error value to zero\n if self._is_unbound(i1):\n self._error[i1] = 0\n if self._is_unbound(i2):\n self._error[i2] = 0\n\n # Predict test samples\n def predict(self, test_samples, classify=True):\n if test_samples.shape[1] > self.samples.shape[1]:\n raise ValueError(\n \"Test samples' feature length does not equal to that of train samples\"\n )\n\n if self._auto_norm:\n test_samples = self._norm(test_samples)\n\n results = []\n for test_sample in test_samples:\n result = self._predict(test_sample)\n if classify:\n results.append(1 if result > 0 else -1)\n else:\n results.append(result)\n return np.array(results)\n\n # Check if alpha violate KKT condition\n def _check_obey_kkt(self, index):\n alphas = self.alphas\n tol = self._tol\n r = self._e(index) * self.tags[index]\n c = self._c\n\n return (r < -tol and alphas[index] < c) or (r > tol and alphas[index] > 0.0)\n\n # Get value calculated from kernel function\n def _k(self, i1, i2):\n # for test samples,use Kernel function\n if isinstance(i2, np.ndarray):\n return self.Kernel(self.samples[i1], i2)\n # for train samples,Kernel values have been saved in matrix\n else:\n return self._K_matrix[i1, i2]\n\n # Get sample's error\n def _e(self, index):\n \"\"\"\n Two cases:\n 1:Sample[index] is non-bound,Fetch error from list: _error\n 2:sample[index] is bound,Use predicted value deduct true value: g(xi) - yi\n\n \"\"\"\n # get from error data\n if self._is_unbound(index):\n return self._error[index]\n # get by g(xi) - yi\n else:\n gx = np.dot(self.alphas * self.tags, self._K_matrix[:, index]) + self._b\n yi = self.tags[index]\n return gx - yi\n\n # Calculate Kernel matrix of all possible i1,i2 ,saving time\n def _calculate_k_matrix(self):\n k_matrix = np.zeros([self.length, self.length])\n for i in self._all_samples:\n for j in self._all_samples:\n k_matrix[i, j] = np.float64(\n self.Kernel(self.samples[i, :], self.samples[j, :])\n )\n return k_matrix\n\n # Predict test sample's tag\n def _predict(self, sample):\n k = self._k\n predicted_value = (\n np.sum(\n [\n self.alphas[i1] * self.tags[i1] * k(i1, sample)\n for i1 in self._all_samples\n ]\n )\n + self._b\n )\n return predicted_value\n\n # Choose alpha1 and alpha2\n def _choose_alphas(self):\n locis = yield from self._choose_a1()\n if not locis:\n return None\n return locis\n\n def _choose_a1(self):\n \"\"\"\n Choose first alpha ;steps:\n 1:First loop over all sample\n 2:Second loop over all non-bound samples till all non-bound samples does not\n voilate kkt condition.\n 3:Repeat this two process endlessly,till all samples does not voilate kkt\n condition samples after first loop.\n \"\"\"\n while True:\n all_not_obey = True\n # all sample\n print(\"scanning all sample!\")\n for i1 in [i for i in self._all_samples if self._check_obey_kkt(i)]:\n all_not_obey = False\n yield from self._choose_a2(i1)\n\n # non-bound sample\n print(\"scanning non-bound sample!\")\n while True:\n not_obey = True\n for i1 in [\n i\n for i in self._all_samples\n if self._check_obey_kkt(i) and self._is_unbound(i)\n ]:\n not_obey = False\n yield from self._choose_a2(i1)\n if not_obey:\n print(\"all non-bound samples fit the KKT condition!\")\n break\n if all_not_obey:\n print(\"all samples fit the KKT condition! Optimization done!\")\n break\n return False\n\n def _choose_a2(self, i1):\n \"\"\"\n Choose the second alpha by using heuristic algorithm ;steps:\n 1: Choose alpha2 which gets the maximum step size (|E1 - E2|).\n 2: Start in a random point,loop over all non-bound samples till alpha1 and\n alpha2 are optimized.\n 3: Start in a random point,loop over all samples till alpha1 and alpha2 are\n optimized.\n \"\"\"\n self._unbound = [i for i in self._all_samples if self._is_unbound(i)]\n\n if len(self.unbound) > 0:\n tmp_error = self._error.copy().tolist()\n tmp_error_dict = {\n index: value\n for index, value in enumerate(tmp_error)\n if self._is_unbound(index)\n }\n if self._e(i1) >= 0:\n i2 = min(tmp_error_dict, key=lambda index: tmp_error_dict[index])\n else:\n i2 = max(tmp_error_dict, key=lambda index: tmp_error_dict[index])\n cmd = yield i1, i2\n if cmd is None:\n return\n\n for i2 in np.roll(self.unbound, np.random.choice(self.length)):\n cmd = yield i1, i2\n if cmd is None:\n return\n\n for i2 in np.roll(self._all_samples, np.random.choice(self.length)):\n cmd = yield i1, i2\n if cmd is None:\n return\n\n # Get the new alpha2 and new alpha1\n def _get_new_alpha(self, i1, i2, a1, a2, e1, e2, y1, y2):\n k = self._k\n if i1 == i2:\n return None, None\n\n # calculate L and H which bound the new alpha2\n s = y1 * y2\n if s == -1:\n l, h = max(0.0, a2 - a1), min(self._c, self._c + a2 - a1)\n else:\n l, h = max(0.0, a2 + a1 - self._c), min(self._c, a2 + a1)\n if l == h:\n return None, None\n\n # calculate eta\n k11 = k(i1, i1)\n k22 = k(i2, i2)\n k12 = k(i1, i2)\n\n # select the new alpha2 which could get the minimal objectives\n if (eta := k11 + k22 - 2.0 * k12) > 0.0:\n a2_new_unc = a2 + (y2 * (e1 - e2)) \/ eta\n # a2_new has a boundary\n if a2_new_unc >= h:\n a2_new = h\n elif a2_new_unc <= l:\n a2_new = l\n else:\n a2_new = a2_new_unc\n else:\n b = self._b\n l1 = a1 + s * (a2 - l)\n h1 = a1 + s * (a2 - h)\n\n # way 1\n f1 = y1 * (e1 + b) - a1 * k(i1, i1) - s * a2 * k(i1, i2)\n f2 = y2 * (e2 + b) - a2 * k(i2, i2) - s * a1 * k(i1, i2)\n ol = (\n l1 * f1\n + l * f2\n + 1 \/ 2 * l1**2 * k(i1, i1)\n + 1 \/ 2 * l**2 * k(i2, i2)\n + s * l * l1 * k(i1, i2)\n )\n oh = (\n h1 * f1\n + h * f2\n + 1 \/ 2 * h1**2 * k(i1, i1)\n + 1 \/ 2 * h**2 * k(i2, i2)\n + s * h * h1 * k(i1, i2)\n )\n \"\"\"\n # way 2\n Use objective function check which alpha2 new could get the minimal\n objectives\n \"\"\"\n if ol < (oh - self._eps):\n a2_new = l\n elif ol > oh + self._eps:\n a2_new = h\n else:\n a2_new = a2\n\n # a1_new has a boundary too\n a1_new = a1 + s * (a2 - a2_new)\n if a1_new < 0:\n a2_new += s * a1_new\n a1_new = 0\n if a1_new > self._c:\n a2_new += s * (a1_new - self._c)\n a1_new = self._c\n\n return a1_new, a2_new\n\n # Normalise data using min_max way\n def _norm(self, data):\n if self._init:\n self._min = np.min(data, axis=0)\n self._max = np.max(data, axis=0)\n self._init = False\n return (data - self._min) \/ (self._max - self._min)\n else:\n return (data - self._min) \/ (self._max - self._min)\n\n def _is_unbound(self, index):\n return bool(0.0 < self.alphas[index] < self._c)\n\n def _is_support(self, index):\n return bool(self.alphas[index] > 0)\n\n @property\n def unbound(self):\n return self._unbound\n\n @property\n def support(self):\n return [i for i in range(self.length) if self._is_support(i)]\n\n @property\n def length(self):\n return self.samples.shape[0]\n\n\nclass Kernel:\n def __init__(self, kernel, degree=1.0, coef0=0.0, gamma=1.0):\n self.degree = np.float64(degree)\n self.coef0 = np.float64(coef0)\n self.gamma = np.float64(gamma)\n self._kernel_name = kernel\n self._kernel = self._get_kernel(kernel_name=kernel)\n self._check()\n\n def _polynomial(self, v1, v2):\n return (self.gamma * np.inner(v1, v2) + self.coef0) ** self.degree\n\n def _linear(self, v1, v2):\n return np.inner(v1, v2) + self.coef0\n\n def _rbf(self, v1, v2):\n return np.exp(-1 * (self.gamma * np.linalg.norm(v1 - v2) ** 2))\n\n def _check(self):\n if self._kernel == self._rbf and self.gamma < 0:\n raise ValueError(\"gamma value must greater than 0\")\n\n def _get_kernel(self, kernel_name):\n maps = {\"linear\": self._linear, \"poly\": self._polynomial, \"rbf\": self._rbf}\n return maps[kernel_name]\n\n def __call__(self, v1, v2):\n return self._kernel(v1, v2)\n\n def __repr__(self):\n return self._kernel_name\n\n\ndef count_time(func):\n def call_func(*args, **kwargs):\n import time\n\n start_time = time.time()\n func(*args, **kwargs)\n end_time = time.time()\n print(f\"smo algorithm cost {end_time - start_time} seconds\")\n\n return call_func\n\n\n@count_time\ndef test_cancel_data():\n print(\"Hello!\\nStart test svm by smo algorithm!\")\n # 0: download dataset and load into pandas' dataframe\n if not os.path.exists(r\"cancel_data.csv\"):\n request = urllib.request.Request( # noqa: S310\n CANCER_DATASET_URL,\n headers={\"User-Agent\": \"Mozilla\/4.0 (compatible; MSIE 5.5; Windows NT)\"},\n )\n response = urllib.request.urlopen(request) # noqa: S310\n content = response.read().decode(\"utf-8\")\n with open(r\"cancel_data.csv\", \"w\") as f:\n f.write(content)\n\n data = pd.read_csv(r\"cancel_data.csv\", header=None)\n\n # 1: pre-processing data\n del data[data.columns.tolist()[0]]\n data = data.dropna(axis=0)\n data = data.replace({\"M\": np.float64(1), \"B\": np.float64(-1)})\n samples = np.array(data)[:, :]\n\n # 2: dividing data into train_data data and test_data data\n train_data, test_data = samples[:328, :], samples[328:, :]\n test_tags, test_samples = test_data[:, 0], test_data[:, 1:]\n\n # 3: choose kernel function,and set initial alphas to zero(optional)\n mykernel = Kernel(kernel=\"rbf\", degree=5, coef0=1, gamma=0.5)\n al = np.zeros(train_data.shape[0])\n\n # 4: calculating best alphas using SMO algorithm and predict test_data samples\n mysvm = SmoSVM(\n train=train_data,\n kernel_func=mykernel,\n alpha_list=al,\n cost=0.4,\n b=0.0,\n tolerance=0.001,\n )\n mysvm.fit()\n predict = mysvm.predict(test_samples)\n\n # 5: check accuracy\n score = 0\n test_num = test_tags.shape[0]\n for i in range(test_tags.shape[0]):\n if test_tags[i] == predict[i]:\n score += 1\n print(f\"\\nall: {test_num}\\nright: {score}\\nfalse: {test_num - score}\")\n print(f\"Rough Accuracy: {score \/ test_tags.shape[0]}\")\n\n\ndef test_demonstration():\n # change stdout\n print(\"\\nStart plot,please wait!!!\")\n sys.stdout = open(os.devnull, \"w\")\n\n ax1 = plt.subplot2grid((2, 2), (0, 0))\n ax2 = plt.subplot2grid((2, 2), (0, 1))\n ax3 = plt.subplot2grid((2, 2), (1, 0))\n ax4 = plt.subplot2grid((2, 2), (1, 1))\n ax1.set_title(\"linear svm,cost:0.1\")\n test_linear_kernel(ax1, cost=0.1)\n ax2.set_title(\"linear svm,cost:500\")\n test_linear_kernel(ax2, cost=500)\n ax3.set_title(\"rbf kernel svm,cost:0.1\")\n test_rbf_kernel(ax3, cost=0.1)\n ax4.set_title(\"rbf kernel svm,cost:500\")\n test_rbf_kernel(ax4, cost=500)\n\n sys.stdout = sys.__stdout__\n print(\"Plot done!!!\")\n\n\ndef test_linear_kernel(ax, cost):\n train_x, train_y = make_blobs(\n n_samples=500, centers=2, n_features=2, random_state=1\n )\n train_y[train_y == 0] = -1\n scaler = StandardScaler()\n train_x_scaled = scaler.fit_transform(train_x, train_y)\n train_data = np.hstack((train_y.reshape(500, 1), train_x_scaled))\n mykernel = Kernel(kernel=\"linear\", degree=5, coef0=1, gamma=0.5)\n mysvm = SmoSVM(\n train=train_data,\n kernel_func=mykernel,\n cost=cost,\n tolerance=0.001,\n auto_norm=False,\n )\n mysvm.fit()\n plot_partition_boundary(mysvm, train_data, ax=ax)\n\n\ndef test_rbf_kernel(ax, cost):\n train_x, train_y = make_circles(\n n_samples=500, noise=0.1, factor=0.1, random_state=1\n )\n train_y[train_y == 0] = -1\n scaler = StandardScaler()\n train_x_scaled = scaler.fit_transform(train_x, train_y)\n train_data = np.hstack((train_y.reshape(500, 1), train_x_scaled))\n mykernel = Kernel(kernel=\"rbf\", degree=5, coef0=1, gamma=0.5)\n mysvm = SmoSVM(\n train=train_data,\n kernel_func=mykernel,\n cost=cost,\n tolerance=0.001,\n auto_norm=False,\n )\n mysvm.fit()\n plot_partition_boundary(mysvm, train_data, ax=ax)\n\n\ndef plot_partition_boundary(\n model, train_data, ax, resolution=100, colors=(\"b\", \"k\", \"r\")\n):\n \"\"\"\n We can not get the optimum w of our kernel svm model which is different from linear\n svm. For this reason, we generate randomly distributed points with high desity and\n prediced values of these points are calculated by using our trained model. Then we\n could use this prediced values to draw contour map.\n And this contour map can represent svm's partition boundary.\n \"\"\"\n train_data_x = train_data[:, 1]\n train_data_y = train_data[:, 2]\n train_data_tags = train_data[:, 0]\n xrange = np.linspace(train_data_x.min(), train_data_x.max(), resolution)\n yrange = np.linspace(train_data_y.min(), train_data_y.max(), resolution)\n test_samples = np.array([(x, y) for x in xrange for y in yrange]).reshape(\n resolution * resolution, 2\n )\n\n test_tags = model.predict(test_samples, classify=False)\n grid = test_tags.reshape((len(xrange), len(yrange)))\n\n # Plot contour map which represents the partition boundary\n ax.contour(\n xrange,\n yrange,\n np.mat(grid).T,\n levels=(-1, 0, 1),\n linestyles=(\"--\", \"-\", \"--\"),\n linewidths=(1, 1, 1),\n colors=colors,\n )\n # Plot all train samples\n ax.scatter(\n train_data_x,\n train_data_y,\n c=train_data_tags,\n cmap=plt.cm.Dark2,\n lw=0,\n alpha=0.5,\n )\n\n # Plot support vectors\n support = model.support\n ax.scatter(\n train_data_x[support],\n train_data_y[support],\n c=train_data_tags[support],\n cmap=plt.cm.Dark2,\n )\n\n\nif __name__ == \"__main__\":\n test_cancel_data()\n test_demonstration()\n plt.show()\n"} +{"Prompt":"Similarity Search : https:en.wikipedia.orgwikiSimilaritysearch Similarity search is a search algorithm for finding the nearest vector from vectors, used in natural language processing. In this algorithm, it calculates distance with euclidean distance and returns a list containing two data for each vector: 1. the nearest vector 2. distance between the vector and the nearest vector float Calculates euclidean distance between two data. :param inputa: ndarray of first vector. :param inputb: ndarray of second vector. :return: Euclidean distance of inputa and inputb. By using math.sqrt, result will be float. euclideannp.array0, np.array1 1.0 euclideannp.array0, 1, np.array1, 1 1.0 euclideannp.array0, 0, 0, np.array0, 0, 1 1.0 :param dataset: Set containing the vectors. Should be ndarray. :param valuearray: vectorvectors we want to know the nearest vector from dataset. :return: Result will be a list containing 1. the nearest vector 2. distance from the vector dataset np.array0, 1, 2 valuearray np.array0 similaritysearchdataset, valuearray 0, 0.0 dataset np.array0, 0, 1, 1, 2, 2 valuearray np.array0, 1 similaritysearchdataset, valuearray 0, 0, 1.0 dataset np.array0, 0, 0, 1, 1, 1, 2, 2, 2 valuearray np.array0, 0, 1 similaritysearchdataset, valuearray 0, 0, 0, 1.0 dataset np.array0, 0, 0, 1, 1, 1, 2, 2, 2 valuearray np.array0, 0, 0, 0, 0, 1 similaritysearchdataset, valuearray 0, 0, 0, 0.0, 0, 0, 0, 1.0 These are the errors that might occur: 1. If dimensions are different. For example, dataset has 2d array and valuearray has 1d array: dataset np.array1 valuearray np.array1 similaritysearchdataset, valuearray Traceback most recent call last: ... ValueError: Wrong input data's dimensions... dataset : 2, valuearray : 1 2. If data's shapes are different. For example, dataset has shape of 3, 2 and valuearray has 2, 3. We are expecting same shapes of two arrays, so it is wrong. dataset np.array0, 0, 1, 1, 2, 2 valuearray np.array0, 0, 0, 0, 0, 1 similaritysearchdataset, valuearray Traceback most recent call last: ... ValueError: Wrong input data's shape... dataset : 2, valuearray : 3 3. If data types are different. When trying to compare, we are expecting same types so they should be same. If not, it'll come up with errors. dataset np.array0, 0, 1, 1, 2, 2, dtypenp.float32 valuearray np.array0, 0, 0, 1, dtypenp.int32 similaritysearchdataset, valuearray doctest: NORMALIZEWHITESPACE Traceback most recent call last: ... TypeError: Input data have different datatype... dataset : float32, valuearray : int32 Calculates cosine similarity between two data. :param inputa: ndarray of first vector. :param inputb: ndarray of second vector. :return: Cosine similarity of inputa and inputb. By using math.sqrt, result will be float. cosinesimilaritynp.array1, np.array1 1.0 cosinesimilaritynp.array1, 2, np.array6, 32 0.9615239476408232","Completions":"from __future__ import annotations\n\nimport math\n\nimport numpy as np\nfrom numpy.linalg import norm\n\n\ndef euclidean(input_a: np.ndarray, input_b: np.ndarray) -> float:\n \"\"\"\n Calculates euclidean distance between two data.\n :param input_a: ndarray of first vector.\n :param input_b: ndarray of second vector.\n :return: Euclidean distance of input_a and input_b. By using math.sqrt(),\n result will be float.\n\n >>> euclidean(np.array([0]), np.array([1]))\n 1.0\n >>> euclidean(np.array([0, 1]), np.array([1, 1]))\n 1.0\n >>> euclidean(np.array([0, 0, 0]), np.array([0, 0, 1]))\n 1.0\n \"\"\"\n return math.sqrt(sum(pow(a - b, 2) for a, b in zip(input_a, input_b)))\n\n\ndef similarity_search(\n dataset: np.ndarray, value_array: np.ndarray\n) -> list[list[list[float] | float]]:\n \"\"\"\n :param dataset: Set containing the vectors. Should be ndarray.\n :param value_array: vector\/vectors we want to know the nearest vector from dataset.\n :return: Result will be a list containing\n 1. the nearest vector\n 2. distance from the vector\n\n >>> dataset = np.array([[0], [1], [2]])\n >>> value_array = np.array([[0]])\n >>> similarity_search(dataset, value_array)\n [[[0], 0.0]]\n\n >>> dataset = np.array([[0, 0], [1, 1], [2, 2]])\n >>> value_array = np.array([[0, 1]])\n >>> similarity_search(dataset, value_array)\n [[[0, 0], 1.0]]\n\n >>> dataset = np.array([[0, 0, 0], [1, 1, 1], [2, 2, 2]])\n >>> value_array = np.array([[0, 0, 1]])\n >>> similarity_search(dataset, value_array)\n [[[0, 0, 0], 1.0]]\n\n >>> dataset = np.array([[0, 0, 0], [1, 1, 1], [2, 2, 2]])\n >>> value_array = np.array([[0, 0, 0], [0, 0, 1]])\n >>> similarity_search(dataset, value_array)\n [[[0, 0, 0], 0.0], [[0, 0, 0], 1.0]]\n\n These are the errors that might occur:\n\n 1. If dimensions are different.\n For example, dataset has 2d array and value_array has 1d array:\n >>> dataset = np.array([[1]])\n >>> value_array = np.array([1])\n >>> similarity_search(dataset, value_array)\n Traceback (most recent call last):\n ...\n ValueError: Wrong input data's dimensions... dataset : 2, value_array : 1\n\n 2. If data's shapes are different.\n For example, dataset has shape of (3, 2) and value_array has (2, 3).\n We are expecting same shapes of two arrays, so it is wrong.\n >>> dataset = np.array([[0, 0], [1, 1], [2, 2]])\n >>> value_array = np.array([[0, 0, 0], [0, 0, 1]])\n >>> similarity_search(dataset, value_array)\n Traceback (most recent call last):\n ...\n ValueError: Wrong input data's shape... dataset : 2, value_array : 3\n\n 3. If data types are different.\n When trying to compare, we are expecting same types so they should be same.\n If not, it'll come up with errors.\n >>> dataset = np.array([[0, 0], [1, 1], [2, 2]], dtype=np.float32)\n >>> value_array = np.array([[0, 0], [0, 1]], dtype=np.int32)\n >>> similarity_search(dataset, value_array) # doctest: +NORMALIZE_WHITESPACE\n Traceback (most recent call last):\n ...\n TypeError: Input data have different datatype...\n dataset : float32, value_array : int32\n \"\"\"\n\n if dataset.ndim != value_array.ndim:\n msg = (\n \"Wrong input data's dimensions... \"\n f\"dataset : {dataset.ndim}, value_array : {value_array.ndim}\"\n )\n raise ValueError(msg)\n\n try:\n if dataset.shape[1] != value_array.shape[1]:\n msg = (\n \"Wrong input data's shape... \"\n f\"dataset : {dataset.shape[1]}, value_array : {value_array.shape[1]}\"\n )\n raise ValueError(msg)\n except IndexError:\n if dataset.ndim != value_array.ndim:\n raise TypeError(\"Wrong shape\")\n\n if dataset.dtype != value_array.dtype:\n msg = (\n \"Input data have different datatype... \"\n f\"dataset : {dataset.dtype}, value_array : {value_array.dtype}\"\n )\n raise TypeError(msg)\n\n answer = []\n\n for value in value_array:\n dist = euclidean(value, dataset[0])\n vector = dataset[0].tolist()\n\n for dataset_value in dataset[1:]:\n temp_dist = euclidean(value, dataset_value)\n\n if dist > temp_dist:\n dist = temp_dist\n vector = dataset_value.tolist()\n\n answer.append([vector, dist])\n\n return answer\n\n\ndef cosine_similarity(input_a: np.ndarray, input_b: np.ndarray) -> float:\n \"\"\"\n Calculates cosine similarity between two data.\n :param input_a: ndarray of first vector.\n :param input_b: ndarray of second vector.\n :return: Cosine similarity of input_a and input_b. By using math.sqrt(),\n result will be float.\n\n >>> cosine_similarity(np.array([1]), np.array([1]))\n 1.0\n >>> cosine_similarity(np.array([1, 2]), np.array([6, 32]))\n 0.9615239476408232\n \"\"\"\n return np.dot(input_a, input_b) \/ (norm(input_a) * norm(input_b))\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Return the squared second norm of vector normsquaredv sumx x for x in v Args: vector ndarray: input vector Returns: float: squared second norm of vector normsquared1, 2 5 normsquarednp.asarray1, 2 5 normsquared0, 0 0 Support Vector Classifier Args: kernel str: kernel to use. Default: linear Possible choices: linear regularization: constraint for soft margin data not linearly separable Default: unbound SVCkernelasdf Traceback most recent call last: ... ValueError: Unknown kernel: asdf SVCkernelrbf Traceback most recent call last: ... ValueError: rbf kernel requires gamma SVCkernelrbf, gamma1 Traceback most recent call last: ... ValueError: gamma must be 0 in the future, there could be a default value like in sklearn sklear: defgamma 1nfeatures X.var wiki previously it was 1nfeatures kernels Linear kernel as if no kernel used at all return np.dotvector1, vector2 def rbfself, vector1: ndarray, vector2: ndarray float: return np.expself.gamma normsquaredvector1 vector2 def fitself, observations: listndarray, classes: ndarray None: self.observations observations self.classes classes using Wolfe's Dual to calculate w. Primal problem: minimize 12normsquaredw constraint: ynw . xn b 1 With l a vector Dual problem: maximize sumnln 12 sumnsummlnlmynymxn . xm constraint: self.C ln 0 and sumnlnyn 0 Then we get w using w sumnlnynxn At the end we can get b meanyn w . xn Since we use kernels, we only need lstar to calculate b and to classify observations n, np.shapeclasses def tominimizecandidate: ndarray float: s 0 n, np.shapecandidate for i in rangen: for j in rangen: s candidatei candidatej classesi classesj self.kernelobservationsi, observationsj return 1 2 s sumcandidate lycontraint LinearConstraintclasses, 0, 0 lbounds Bounds0, self.regularization lstar minimize tominimize, np.onesn, boundslbounds, constraintslycontraint .x self.optimum lstar calculating mean offset of separation plane to points s 0 for i in rangen: for j in rangen: s classesi classesi self.optimumi self.kernel observationsi, observationsj self.offset s n def predictself, observation: ndarray int: s sum self.optimumn self.classesn self.kernelself.observationsn, observation for n in rangelenself.classes return 1 if s self.offset 0 else 1 if name main: import doctest doctest.testmod","Completions":"import numpy as np\nfrom numpy import ndarray\nfrom scipy.optimize import Bounds, LinearConstraint, minimize\n\n\ndef norm_squared(vector: ndarray) -> float:\n \"\"\"\n Return the squared second norm of vector\n norm_squared(v) = sum(x * x for x in v)\n\n Args:\n vector (ndarray): input vector\n\n Returns:\n float: squared second norm of vector\n\n >>> norm_squared([1, 2])\n 5\n >>> norm_squared(np.asarray([1, 2]))\n 5\n >>> norm_squared([0, 0])\n 0\n \"\"\"\n return np.dot(vector, vector)\n\n\nclass SVC:\n \"\"\"\n Support Vector Classifier\n\n Args:\n kernel (str): kernel to use. Default: linear\n Possible choices:\n - linear\n regularization: constraint for soft margin (data not linearly separable)\n Default: unbound\n\n >>> SVC(kernel=\"asdf\")\n Traceback (most recent call last):\n ...\n ValueError: Unknown kernel: asdf\n\n >>> SVC(kernel=\"rbf\")\n Traceback (most recent call last):\n ...\n ValueError: rbf kernel requires gamma\n\n >>> SVC(kernel=\"rbf\", gamma=-1)\n Traceback (most recent call last):\n ...\n ValueError: gamma must be > 0\n \"\"\"\n\n def __init__(\n self,\n *,\n regularization: float = np.inf,\n kernel: str = \"linear\",\n gamma: float = 0.0,\n ) -> None:\n self.regularization = regularization\n self.gamma = gamma\n if kernel == \"linear\":\n self.kernel = self.__linear\n elif kernel == \"rbf\":\n if self.gamma == 0:\n raise ValueError(\"rbf kernel requires gamma\")\n if not isinstance(self.gamma, (float, int)):\n raise ValueError(\"gamma must be float or int\")\n if not self.gamma > 0:\n raise ValueError(\"gamma must be > 0\")\n self.kernel = self.__rbf\n # in the future, there could be a default value like in sklearn\n # sklear: def_gamma = 1\/(n_features * X.var()) (wiki)\n # previously it was 1\/(n_features)\n else:\n msg = f\"Unknown kernel: {kernel}\"\n raise ValueError(msg)\n\n # kernels\n def __linear(self, vector1: ndarray, vector2: ndarray) -> float:\n \"\"\"Linear kernel (as if no kernel used at all)\"\"\"\n return np.dot(vector1, vector2)\n\n def __rbf(self, vector1: ndarray, vector2: ndarray) -> float:\n \"\"\"\n RBF: Radial Basis Function Kernel\n\n Note: for more information see:\n https:\/\/en.wikipedia.org\/wiki\/Radial_basis_function_kernel\n\n Args:\n vector1 (ndarray): first vector\n vector2 (ndarray): second vector)\n\n Returns:\n float: exp(-(gamma * norm_squared(vector1 - vector2)))\n \"\"\"\n return np.exp(-(self.gamma * norm_squared(vector1 - vector2)))\n\n def fit(self, observations: list[ndarray], classes: ndarray) -> None:\n \"\"\"\n Fits the SVC with a set of observations.\n\n Args:\n observations (list[ndarray]): list of observations\n classes (ndarray): classification of each observation (in {1, -1})\n \"\"\"\n\n self.observations = observations\n self.classes = classes\n\n # using Wolfe's Dual to calculate w.\n # Primal problem: minimize 1\/2*norm_squared(w)\n # constraint: yn(w . xn + b) >= 1\n #\n # With l a vector\n # Dual problem: maximize sum_n(ln) -\n # 1\/2 * sum_n(sum_m(ln*lm*yn*ym*xn . xm))\n # constraint: self.C >= ln >= 0\n # and sum_n(ln*yn) = 0\n # Then we get w using w = sum_n(ln*yn*xn)\n # At the end we can get b ~= mean(yn - w . xn)\n #\n # Since we use kernels, we only need l_star to calculate b\n # and to classify observations\n\n (n,) = np.shape(classes)\n\n def to_minimize(candidate: ndarray) -> float:\n \"\"\"\n Opposite of the function to maximize\n\n Args:\n candidate (ndarray): candidate array to test\n\n Return:\n float: Wolfe's Dual result to minimize\n \"\"\"\n s = 0\n (n,) = np.shape(candidate)\n for i in range(n):\n for j in range(n):\n s += (\n candidate[i]\n * candidate[j]\n * classes[i]\n * classes[j]\n * self.kernel(observations[i], observations[j])\n )\n return 1 \/ 2 * s - sum(candidate)\n\n ly_contraint = LinearConstraint(classes, 0, 0)\n l_bounds = Bounds(0, self.regularization)\n\n l_star = minimize(\n to_minimize, np.ones(n), bounds=l_bounds, constraints=[ly_contraint]\n ).x\n self.optimum = l_star\n\n # calculating mean offset of separation plane to points\n s = 0\n for i in range(n):\n for j in range(n):\n s += classes[i] - classes[i] * self.optimum[i] * self.kernel(\n observations[i], observations[j]\n )\n self.offset = s \/ n\n\n def predict(self, observation: ndarray) -> int:\n \"\"\"\n Get the expected class of an observation\n\n Args:\n observation (Vector): observation\n\n Returns:\n int {1, -1}: expected class\n\n >>> xs = [\n ... np.asarray([0, 1]), np.asarray([0, 2]),\n ... np.asarray([1, 1]), np.asarray([1, 2])\n ... ]\n >>> y = np.asarray([1, 1, -1, -1])\n >>> s = SVC()\n >>> s.fit(xs, y)\n >>> s.predict(np.asarray([0, 1]))\n 1\n >>> s.predict(np.asarray([1, 1]))\n -1\n >>> s.predict(np.asarray([2, 2]))\n -1\n \"\"\"\n s = sum(\n self.optimum[n]\n * self.classes[n]\n * self.kernel(self.observations[n], observation)\n for n in range(len(self.classes))\n )\n return 1 if s + self.offset >= 0 else -1\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"tfidf Wikipedia: https:en.wikipedia.orgwikiTfE28093idf tfidf and other word frequency algorithms are often used as a weighting factor in information retrieval and text mining. 83 of textbased recommender systems use tfidf for term weighting. In Layman's terms, tfidf is a statistic intended to reflect how important a word is to a document in a corpus a collection of documents Here I've implemented several word frequency algorithms that are commonly used in information retrieval: Term Frequency, Document Frequency, and TFIDF TermFrequencyInverseDocumentFrequency are included. Term Frequency is a statistical function that returns a number representing how frequently an expression occurs in a document. This indicates how significant a particular term is in a given document. Document Frequency is a statistical function that returns an integer representing the number of documents in a corpus that a term occurs in where the max number returned would be the number of documents in the corpus. Inverse Document Frequency is mathematically written as log10Ndf, where N is the number of documents in your corpus and df is the Document Frequency. If df is 0, a ZeroDivisionError will be thrown. TermFrequencyInverseDocumentFrequency is a measure of the originality of a term. It is mathematically written as tflog10Ndf. It compares the number of times a term appears in a document with the number of documents the term appears in. If df is 0, a ZeroDivisionError will be thrown. Return the number of times a term occurs within a given document. params: term, the term to search a document for, and document, the document to search within returns: an integer representing the number of times a term is found within the document examples: termfrequencyto, To be, or not to be 2 strip all punctuation and newlines and replace it with '' Calculate the number of documents in a corpus that contain a given term params : term, the term to search each document for, and corpus, a collection of documents. Each document should be separated by a newline. returns : the number of documents in the corpus that contain the term you are searching for and the number of documents in the corpus examples : documentfrequencyfirst, This is the first document in the corpus.nThIs is the second document in the corpus.nTHIS is the third document in the corpus. 1, 3 Return an integer denoting the importance of a word. This measure of importance is calculated by log10Ndf, where N is the number of documents and df is the Document Frequency. params : df, the Document Frequency, N, the number of documents in the corpus and smoothing, if True return the idfsmooth returns : log10Ndf or 1log10N1df examples : inversedocumentfrequency3, 0 Traceback most recent call last: ... ValueError: log100 is undefined. inversedocumentfrequency1, 3 0.477 inversedocumentfrequency0, 3 Traceback most recent call last: ... ZeroDivisionError: df must be 0 inversedocumentfrequency0, 3,True 1.477 Combine the term frequency and inverse document frequency functions to calculate the originality of a term. This 'originality' is calculated by multiplying the term frequency and the inverse document frequency : tfidf TF IDF params : tf, the term frequency, and idf, the inverse document frequency examples : tfidf2, 0.477 0.954","Completions":"import string\nfrom math import log10\n\n\"\"\"\n tf-idf Wikipedia: https:\/\/en.wikipedia.org\/wiki\/Tf%E2%80%93idf\n tf-idf and other word frequency algorithms are often used\n as a weighting factor in information retrieval and text\n mining. 83% of text-based recommender systems use\n tf-idf for term weighting. In Layman's terms, tf-idf\n is a statistic intended to reflect how important a word\n is to a document in a corpus (a collection of documents)\n\n\n Here I've implemented several word frequency algorithms\n that are commonly used in information retrieval: Term Frequency,\n Document Frequency, and TF-IDF (Term-Frequency*Inverse-Document-Frequency)\n are included.\n\n Term Frequency is a statistical function that\n returns a number representing how frequently\n an expression occurs in a document. This\n indicates how significant a particular term is in\n a given document.\n\n Document Frequency is a statistical function that returns\n an integer representing the number of documents in a\n corpus that a term occurs in (where the max number returned\n would be the number of documents in the corpus).\n\n Inverse Document Frequency is mathematically written as\n log10(N\/df), where N is the number of documents in your\n corpus and df is the Document Frequency. If df is 0, a\n ZeroDivisionError will be thrown.\n\n Term-Frequency*Inverse-Document-Frequency is a measure\n of the originality of a term. It is mathematically written\n as tf*log10(N\/df). It compares the number of times\n a term appears in a document with the number of documents\n the term appears in. If df is 0, a ZeroDivisionError will be thrown.\n\"\"\"\n\n\ndef term_frequency(term: str, document: str) -> int:\n \"\"\"\n Return the number of times a term occurs within\n a given document.\n @params: term, the term to search a document for, and document,\n the document to search within\n @returns: an integer representing the number of times a term is\n found within the document\n\n @examples:\n >>> term_frequency(\"to\", \"To be, or not to be\")\n 2\n \"\"\"\n # strip all punctuation and newlines and replace it with ''\n document_without_punctuation = document.translate(\n str.maketrans(\"\", \"\", string.punctuation)\n ).replace(\"\\n\", \"\")\n tokenize_document = document_without_punctuation.split(\" \") # word tokenization\n return len([word for word in tokenize_document if word.lower() == term.lower()])\n\n\ndef document_frequency(term: str, corpus: str) -> tuple[int, int]:\n \"\"\"\n Calculate the number of documents in a corpus that contain a\n given term\n @params : term, the term to search each document for, and corpus, a collection of\n documents. Each document should be separated by a newline.\n @returns : the number of documents in the corpus that contain the term you are\n searching for and the number of documents in the corpus\n @examples :\n >>> document_frequency(\"first\", \"This is the first document in the corpus.\\\\nThIs\\\nis the second document in the corpus.\\\\nTHIS is \\\nthe third document in the corpus.\")\n (1, 3)\n \"\"\"\n corpus_without_punctuation = corpus.lower().translate(\n str.maketrans(\"\", \"\", string.punctuation)\n ) # strip all punctuation and replace it with ''\n docs = corpus_without_punctuation.split(\"\\n\")\n term = term.lower()\n return (len([doc for doc in docs if term in doc]), len(docs))\n\n\ndef inverse_document_frequency(df: int, n: int, smoothing=False) -> float:\n \"\"\"\n Return an integer denoting the importance\n of a word. This measure of importance is\n calculated by log10(N\/df), where N is the\n number of documents and df is\n the Document Frequency.\n @params : df, the Document Frequency, N,\n the number of documents in the corpus and\n smoothing, if True return the idf-smooth\n @returns : log10(N\/df) or 1+log10(N\/1+df)\n @examples :\n >>> inverse_document_frequency(3, 0)\n Traceback (most recent call last):\n ...\n ValueError: log10(0) is undefined.\n >>> inverse_document_frequency(1, 3)\n 0.477\n >>> inverse_document_frequency(0, 3)\n Traceback (most recent call last):\n ...\n ZeroDivisionError: df must be > 0\n >>> inverse_document_frequency(0, 3,True)\n 1.477\n \"\"\"\n if smoothing:\n if n == 0:\n raise ValueError(\"log10(0) is undefined.\")\n return round(1 + log10(n \/ (1 + df)), 3)\n\n if df == 0:\n raise ZeroDivisionError(\"df must be > 0\")\n elif n == 0:\n raise ValueError(\"log10(0) is undefined.\")\n return round(log10(n \/ df), 3)\n\n\ndef tf_idf(tf: int, idf: int) -> float:\n \"\"\"\n Combine the term frequency\n and inverse document frequency functions to\n calculate the originality of a term. This\n 'originality' is calculated by multiplying\n the term frequency and the inverse document\n frequency : tf-idf = TF * IDF\n @params : tf, the term frequency, and idf, the inverse document\n frequency\n @examples :\n >>> tf_idf(2, 0.477)\n 0.954\n \"\"\"\n return round(tf * idf, 3)\n"} +{"Prompt":"XGBoost Classifier Example Split dataset into features and target data is features datahandling'data':'5.1, 3.5, 1.4, 0.2','target':0 '5.1, 3.5, 1.4, 0.2', 0 datahandling ... 'data': '4.9, 3.0, 1.4, 0.2, 4.7, 3.2, 1.3, 0.2', 'target': 0, 0 ... '4.9, 3.0, 1.4, 0.2, 4.7, 3.2, 1.3, 0.2', 0, 0 THIS TEST IS BROKEN!! xgboostnp.array5.1, 3.6, 1.4, 0.2, np.array0 XGBClassifierbasescore0.5, booster'gbtree', callbacksNone, colsamplebylevel1, colsamplebynode1, colsamplebytree1, earlystoppingroundsNone, enablecategoricalFalse, evalmetricNone, gamma0, gpuid1, growpolicy'depthwise', importancetypeNone, interactionconstraints'', learningrate0.300000012, maxbin256, maxcattoonehot4, maxdeltastep0, maxdepth6, maxleaves0, minchildweight1, missingnan, monotoneconstraints'', nestimators100, njobs0, numparalleltree1, predictor'auto', randomstate0, regalpha0, reglambda1, ... main Url for the algorithm: https:xgboost.readthedocs.ioenstable Iris type dataset is used to demonstrate algorithm. Load Iris dataset Create an XGBoost Classifier from the training data Display the confusion matrix of the classifier with both training and test sets","Completions":"# XGBoost Classifier Example\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom sklearn.datasets import load_iris\nfrom sklearn.metrics import ConfusionMatrixDisplay\nfrom sklearn.model_selection import train_test_split\nfrom xgboost import XGBClassifier\n\n\ndef data_handling(data: dict) -> tuple:\n # Split dataset into features and target\n # data is features\n \"\"\"\n >>> data_handling(({'data':'[5.1, 3.5, 1.4, 0.2]','target':([0])}))\n ('[5.1, 3.5, 1.4, 0.2]', [0])\n >>> data_handling(\n ... {'data': '[4.9, 3.0, 1.4, 0.2], [4.7, 3.2, 1.3, 0.2]', 'target': ([0, 0])}\n ... )\n ('[4.9, 3.0, 1.4, 0.2], [4.7, 3.2, 1.3, 0.2]', [0, 0])\n \"\"\"\n return (data[\"data\"], data[\"target\"])\n\n\ndef xgboost(features: np.ndarray, target: np.ndarray) -> XGBClassifier:\n \"\"\"\n # THIS TEST IS BROKEN!! >>> xgboost(np.array([[5.1, 3.6, 1.4, 0.2]]), np.array([0]))\n XGBClassifier(base_score=0.5, booster='gbtree', callbacks=None,\n colsample_bylevel=1, colsample_bynode=1, colsample_bytree=1,\n early_stopping_rounds=None, enable_categorical=False,\n eval_metric=None, gamma=0, gpu_id=-1, grow_policy='depthwise',\n importance_type=None, interaction_constraints='',\n learning_rate=0.300000012, max_bin=256, max_cat_to_onehot=4,\n max_delta_step=0, max_depth=6, max_leaves=0, min_child_weight=1,\n missing=nan, monotone_constraints='()', n_estimators=100,\n n_jobs=0, num_parallel_tree=1, predictor='auto', random_state=0,\n reg_alpha=0, reg_lambda=1, ...)\n \"\"\"\n classifier = XGBClassifier()\n classifier.fit(features, target)\n return classifier\n\n\ndef main() -> None:\n \"\"\"\n >>> main()\n\n Url for the algorithm:\n https:\/\/xgboost.readthedocs.io\/en\/stable\/\n Iris type dataset is used to demonstrate algorithm.\n \"\"\"\n\n # Load Iris dataset\n iris = load_iris()\n features, targets = data_handling(iris)\n x_train, x_test, y_train, y_test = train_test_split(\n features, targets, test_size=0.25\n )\n\n names = iris[\"target_names\"]\n\n # Create an XGBoost Classifier from the training data\n xgboost_classifier = xgboost(x_train, y_train)\n\n # Display the confusion matrix of the classifier with both training and test sets\n ConfusionMatrixDisplay.from_estimator(\n xgboost_classifier,\n x_test,\n y_test,\n display_labels=names,\n cmap=\"Blues\",\n normalize=\"true\",\n )\n plt.title(\"Normalized Confusion Matrix - IRIS Dataset\")\n plt.show()\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod(verbose=True)\n main()\n"} +{"Prompt":"XGBoost Regressor Example Split dataset into features and target. Data is features. datahandling ... 'data':' 8.3252 41. 6.9841269 1.02380952 322. 2.55555556 37.88 122.23 ' ... ,'target':4.526 ' 8.3252 41. 6.9841269 1.02380952 322. 2.55555556 37.88 122.23 ', 4.526 xgboostnp.array 2.3571 , 52. , 6.00813008, 1.06775068, ... 907. , 2.45799458, 40.58 , 124.26,np.array1.114, ... np.array1.97840000e00, 3.70000000e01, 4.98858447e00, 1.03881279e00, ... 1.14300000e03, 2.60958904e00, 3.67800000e01, 1.19780000e02 array1.1139996, dtypefloat32 Predict target for test data The URL for this algorithm https:xgboost.readthedocs.ioenstable California house price dataset is used to demonstrate the algorithm. Expected error values: Mean Absolute Error: 0.30957163379906033 Mean Square Error: 0.22611560196662744 Load California house price dataset Error printing","Completions":"# XGBoost Regressor Example\nimport numpy as np\nfrom sklearn.datasets import fetch_california_housing\nfrom sklearn.metrics import mean_absolute_error, mean_squared_error\nfrom sklearn.model_selection import train_test_split\nfrom xgboost import XGBRegressor\n\n\ndef data_handling(data: dict) -> tuple:\n # Split dataset into features and target. Data is features.\n \"\"\"\n >>> data_handling((\n ... {'data':'[ 8.3252 41. 6.9841269 1.02380952 322. 2.55555556 37.88 -122.23 ]'\n ... ,'target':([4.526])}))\n ('[ 8.3252 41. 6.9841269 1.02380952 322. 2.55555556 37.88 -122.23 ]', [4.526])\n \"\"\"\n return (data[\"data\"], data[\"target\"])\n\n\ndef xgboost(\n features: np.ndarray, target: np.ndarray, test_features: np.ndarray\n) -> np.ndarray:\n \"\"\"\n >>> xgboost(np.array([[ 2.3571 , 52. , 6.00813008, 1.06775068,\n ... 907. , 2.45799458, 40.58 , -124.26]]),np.array([1.114]),\n ... np.array([[1.97840000e+00, 3.70000000e+01, 4.98858447e+00, 1.03881279e+00,\n ... 1.14300000e+03, 2.60958904e+00, 3.67800000e+01, -1.19780000e+02]]))\n array([[1.1139996]], dtype=float32)\n \"\"\"\n xgb = XGBRegressor(\n verbosity=0, random_state=42, tree_method=\"exact\", base_score=0.5\n )\n xgb.fit(features, target)\n # Predict target for test data\n predictions = xgb.predict(test_features)\n predictions = predictions.reshape(len(predictions), 1)\n return predictions\n\n\ndef main() -> None:\n \"\"\"\n The URL for this algorithm\n https:\/\/xgboost.readthedocs.io\/en\/stable\/\n California house price dataset is used to demonstrate the algorithm.\n\n Expected error values:\n Mean Absolute Error: 0.30957163379906033\n Mean Square Error: 0.22611560196662744\n \"\"\"\n # Load California house price dataset\n california = fetch_california_housing()\n data, target = data_handling(california)\n x_train, x_test, y_train, y_test = train_test_split(\n data, target, test_size=0.25, random_state=1\n )\n predictions = xgboost(x_train, y_train, x_test)\n # Error printing\n print(f\"Mean Absolute Error: {mean_absolute_error(y_test, predictions)}\")\n print(f\"Mean Square Error: {mean_squared_error(y_test, predictions)}\")\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod(verbose=True)\n main()\n"} +{"Prompt":"Absolute Value. def absvalnum: float float: return num if num 0 else num def absminx: listint int: if lenx 0: raise ValueErrorabsmin arg is an empty sequence j x0 for i in x: if absvali absvalj: j i return j def absmaxx: listint int: if lenx 0: raise ValueErrorabsmax arg is an empty sequence j x0 for i in x: if absi absj: j i return j def absmaxsortx: listint int: if lenx 0: raise ValueErrorabsmaxsort arg is an empty sequence return sortedx, keyabs1 def testabsval: assert absval0 0 assert absval34 34 assert absval100000000000 100000000000 a 3, 1, 2, 11 assert absmaxa 11 assert absmaxsorta 11 assert absmina 1 if name main: import doctest doctest.testmod testabsval printabsval34 34","Completions":"def abs_val(num: float) -> float:\n \"\"\"\n Find the absolute value of a number.\n\n >>> abs_val(-5.1)\n 5.1\n >>> abs_val(-5) == abs_val(5)\n True\n >>> abs_val(0)\n 0\n \"\"\"\n return -num if num < 0 else num\n\n\ndef abs_min(x: list[int]) -> int:\n \"\"\"\n >>> abs_min([0,5,1,11])\n 0\n >>> abs_min([3,-10,-2])\n -2\n >>> abs_min([])\n Traceback (most recent call last):\n ...\n ValueError: abs_min() arg is an empty sequence\n \"\"\"\n if len(x) == 0:\n raise ValueError(\"abs_min() arg is an empty sequence\")\n j = x[0]\n for i in x:\n if abs_val(i) < abs_val(j):\n j = i\n return j\n\n\ndef abs_max(x: list[int]) -> int:\n \"\"\"\n >>> abs_max([0,5,1,11])\n 11\n >>> abs_max([3,-10,-2])\n -10\n >>> abs_max([])\n Traceback (most recent call last):\n ...\n ValueError: abs_max() arg is an empty sequence\n \"\"\"\n if len(x) == 0:\n raise ValueError(\"abs_max() arg is an empty sequence\")\n j = x[0]\n for i in x:\n if abs(i) > abs(j):\n j = i\n return j\n\n\ndef abs_max_sort(x: list[int]) -> int:\n \"\"\"\n >>> abs_max_sort([0,5,1,11])\n 11\n >>> abs_max_sort([3,-10,-2])\n -10\n >>> abs_max_sort([])\n Traceback (most recent call last):\n ...\n ValueError: abs_max_sort() arg is an empty sequence\n \"\"\"\n if len(x) == 0:\n raise ValueError(\"abs_max_sort() arg is an empty sequence\")\n return sorted(x, key=abs)[-1]\n\n\ndef test_abs_val():\n \"\"\"\n >>> test_abs_val()\n \"\"\"\n assert abs_val(0) == 0\n assert abs_val(34) == 34\n assert abs_val(-100000000000) == 100000000000\n\n a = [-3, -1, 2, -11]\n assert abs_max(a) == -11\n assert abs_max_sort(a) == -11\n assert abs_min(a) == -1\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n\n test_abs_val()\n print(abs_val(-34)) # --> 34\n"} +{"Prompt":"Illustrate how to add the integer without arithmetic operation Author: suraj Kumar Time Complexity: 1 https:en.wikipedia.orgwikiBitwiseoperation Implementation of addition of integer Examples: add3, 5 8 add13, 5 18 add7, 2 5 add0, 7 7 add321, 0 321","Completions":"def add(first: int, second: int) -> int:\n \"\"\"\n Implementation of addition of integer\n\n Examples:\n >>> add(3, 5)\n 8\n >>> add(13, 5)\n 18\n >>> add(-7, 2)\n -5\n >>> add(0, -7)\n -7\n >>> add(-321, 0)\n -321\n \"\"\"\n while second != 0:\n c = first & second\n first ^= second\n second = c << 1\n return first\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n\n first = int(input(\"Enter the first number: \").strip())\n second = int(input(\"Enter the second number: \").strip())\n print(f\"{add(first, second) = }\")\n"} +{"Prompt":"Finds the aliquot sum of an input integer, where the aliquot sum of a number n is defined as the sum of all natural numbers less than n that divide n evenly. For example, the aliquot sum of 15 is 1 3 5 9. This is a simple On implementation. param inputnum: a positive integer whose aliquot sum is to be found return: the aliquot sum of inputnum, if inputnum is positive. Otherwise, raise a ValueError Wikipedia Explanation: https:en.wikipedia.orgwikiAliquotsum aliquotsum15 9 aliquotsum6 6 aliquotsum1 Traceback most recent call last: ... ValueError: Input must be positive aliquotsum0 Traceback most recent call last: ... ValueError: Input must be positive aliquotsum1.6 Traceback most recent call last: ... ValueError: Input must be an integer aliquotsum12 16 aliquotsum1 0 aliquotsum19 1","Completions":"def aliquot_sum(input_num: int) -> int:\n \"\"\"\n Finds the aliquot sum of an input integer, where the\n aliquot sum of a number n is defined as the sum of all\n natural numbers less than n that divide n evenly. For\n example, the aliquot sum of 15 is 1 + 3 + 5 = 9. This is\n a simple O(n) implementation.\n @param input_num: a positive integer whose aliquot sum is to be found\n @return: the aliquot sum of input_num, if input_num is positive.\n Otherwise, raise a ValueError\n Wikipedia Explanation: https:\/\/en.wikipedia.org\/wiki\/Aliquot_sum\n\n >>> aliquot_sum(15)\n 9\n >>> aliquot_sum(6)\n 6\n >>> aliquot_sum(-1)\n Traceback (most recent call last):\n ...\n ValueError: Input must be positive\n >>> aliquot_sum(0)\n Traceback (most recent call last):\n ...\n ValueError: Input must be positive\n >>> aliquot_sum(1.6)\n Traceback (most recent call last):\n ...\n ValueError: Input must be an integer\n >>> aliquot_sum(12)\n 16\n >>> aliquot_sum(1)\n 0\n >>> aliquot_sum(19)\n 1\n \"\"\"\n if not isinstance(input_num, int):\n raise ValueError(\"Input must be an integer\")\n if input_num <= 0:\n raise ValueError(\"Input must be positive\")\n return sum(\n divisor for divisor in range(1, input_num \/\/ 2 + 1) if input_num % divisor == 0\n )\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"In a multithreaded download, this algorithm could be used to provide each worker thread with a block of nonoverlapping bytes to download. For example: for i in allocationlist: requests.geturl,headers'Range':f'bytesi' Divide a number of bytes into x partitions. :param numberofbytes: the total of bytes. :param partitions: the number of partition need to be allocated. :return: list of bytes to be assigned to each worker thread allocationnum16647, 4 '14161', '41628322', '832312483', '1248416647' allocationnum50000, 5 '110000', '1000120000', '2000130000', '3000140000', '4000150000' allocationnum888, 999 Traceback most recent call last: ... ValueError: partitions can not numberofbytes! allocationnum888, 4 Traceback most recent call last: ... ValueError: partitions must be a positive number!","Completions":"from __future__ import annotations\n\n\ndef allocation_num(number_of_bytes: int, partitions: int) -> list[str]:\n \"\"\"\n Divide a number of bytes into x partitions.\n :param number_of_bytes: the total of bytes.\n :param partitions: the number of partition need to be allocated.\n :return: list of bytes to be assigned to each worker thread\n\n >>> allocation_num(16647, 4)\n ['1-4161', '4162-8322', '8323-12483', '12484-16647']\n >>> allocation_num(50000, 5)\n ['1-10000', '10001-20000', '20001-30000', '30001-40000', '40001-50000']\n >>> allocation_num(888, 999)\n Traceback (most recent call last):\n ...\n ValueError: partitions can not > number_of_bytes!\n >>> allocation_num(888, -4)\n Traceback (most recent call last):\n ...\n ValueError: partitions must be a positive number!\n \"\"\"\n if partitions <= 0:\n raise ValueError(\"partitions must be a positive number!\")\n if partitions > number_of_bytes:\n raise ValueError(\"partitions can not > number_of_bytes!\")\n bytes_per_partition = number_of_bytes \/\/ partitions\n allocation_list = []\n for i in range(partitions):\n start_bytes = i * bytes_per_partition + 1\n end_bytes = (\n number_of_bytes if i == partitions - 1 else (i + 1) * bytes_per_partition\n )\n allocation_list.append(f\"{start_bytes}-{end_bytes}\")\n return allocation_list\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"arclength45, 5 3.9269908169872414 arclength120, 15 31.415926535897928 arclength90, 10 15.707963267948966","Completions":"from math import pi\n\n\ndef arc_length(angle: int, radius: int) -> float:\n \"\"\"\n >>> arc_length(45, 5)\n 3.9269908169872414\n >>> arc_length(120, 15)\n 31.415926535897928\n >>> arc_length(90, 10)\n 15.707963267948966\n \"\"\"\n return 2 * pi * radius * (angle \/ 360)\n\n\nif __name__ == \"__main__\":\n print(arc_length(90, 10))\n"} +{"Prompt":"Find the area of various geometric shapes Wikipedia reference: https:en.wikipedia.orgwikiArea Calculate the Surface Area of a Cube. surfaceareacube1 6 surfaceareacube1.6 15.360000000000003 surfaceareacube0 0 surfaceareacube3 54 surfaceareacube1 Traceback most recent call last: ... ValueError: surfaceareacube only accepts nonnegative values Calculate the Surface Area of a Cuboid. surfaceareacuboid1, 2, 3 22 surfaceareacuboid0, 0, 0 0 surfaceareacuboid1.6, 2.6, 3.6 38.56 surfaceareacuboid1, 2, 3 Traceback most recent call last: ... ValueError: surfaceareacuboid only accepts nonnegative values surfaceareacuboid1, 2, 3 Traceback most recent call last: ... ValueError: surfaceareacuboid only accepts nonnegative values surfaceareacuboid1, 2, 3 Traceback most recent call last: ... ValueError: surfaceareacuboid only accepts nonnegative values Calculate the Surface Area of a Sphere. Wikipedia reference: https:en.wikipedia.orgwikiSphere Formula: 4 pi r2 surfaceareasphere5 314.1592653589793 surfaceareasphere1 12.566370614359172 surfaceareasphere1.6 32.169908772759484 surfaceareasphere0 0.0 surfaceareasphere1 Traceback most recent call last: ... ValueError: surfaceareasphere only accepts nonnegative values Calculate the Surface Area of a Hemisphere. Formula: 3 pi r2 surfaceareahemisphere5 235.61944901923448 surfaceareahemisphere1 9.42477796076938 surfaceareahemisphere0 0.0 surfaceareahemisphere1.1 11.40398133253095 surfaceareahemisphere1 Traceback most recent call last: ... ValueError: surfaceareahemisphere only accepts nonnegative values Calculate the Surface Area of a Cone. Wikipedia reference: https:en.wikipedia.orgwikiCone Formula: pi r r h 2 r 2 0.5 surfaceareacone10, 24 1130.9733552923256 surfaceareacone6, 8 301.59289474462014 surfaceareacone1.6, 2.6 23.387862992395807 surfaceareacone0, 0 0.0 surfaceareacone1, 2 Traceback most recent call last: ... ValueError: surfaceareacone only accepts nonnegative values surfaceareacone1, 2 Traceback most recent call last: ... ValueError: surfaceareacone only accepts nonnegative values surfaceareacone1, 2 Traceback most recent call last: ... ValueError: surfaceareacone only accepts nonnegative values Calculate the Surface Area of a Conical Frustum. surfaceareaconicalfrustum1, 2, 3 45.511728065337266 surfaceareaconicalfrustum4, 5, 6 300.7913575056268 surfaceareaconicalfrustum0, 0, 0 0.0 surfaceareaconicalfrustum1.6, 2.6, 3.6 78.57907060751548 surfaceareaconicalfrustum1, 2, 3 Traceback most recent call last: ... ValueError: surfaceareaconicalfrustum only accepts nonnegative values surfaceareaconicalfrustum1, 2, 3 Traceback most recent call last: ... ValueError: surfaceareaconicalfrustum only accepts nonnegative values surfaceareaconicalfrustum1, 2, 3 Traceback most recent call last: ... ValueError: surfaceareaconicalfrustum only accepts nonnegative values Calculate the Surface Area of a Cylinder. Wikipedia reference: https:en.wikipedia.orgwikiCylinder Formula: 2 pi r h r surfaceareacylinder7, 10 747.6990515543707 surfaceareacylinder1.6, 2.6 42.22300526424682 surfaceareacylinder0, 0 0.0 surfaceareacylinder6, 8 527.7875658030853 surfaceareacylinder1, 2 Traceback most recent call last: ... ValueError: surfaceareacylinder only accepts nonnegative values surfaceareacylinder1, 2 Traceback most recent call last: ... ValueError: surfaceareacylinder only accepts nonnegative values surfaceareacylinder1, 2 Traceback most recent call last: ... ValueError: surfaceareacylinder only accepts nonnegative values Calculate the Area of a Torus. Wikipedia reference: https:en.wikipedia.orgwikiTorus :return 4pi2 torusradius tuberadius surfaceareatorus1, 1 39.47841760435743 surfaceareatorus4, 3 473.7410112522892 surfaceareatorus3, 4 Traceback most recent call last: ... ValueError: surfaceareatorus does not support spindle or self intersecting tori surfaceareatorus1.6, 1.6 101.06474906715503 surfaceareatorus0, 0 0.0 surfaceareatorus1, 1 Traceback most recent call last: ... ValueError: surfaceareatorus only accepts nonnegative values surfaceareatorus1, 1 Traceback most recent call last: ... ValueError: surfaceareatorus only accepts nonnegative values Calculate the area of a rectangle. arearectangle10, 20 200 arearectangle1.6, 2.6 4.16 arearectangle0, 0 0 arearectangle1, 2 Traceback most recent call last: ... ValueError: arearectangle only accepts nonnegative values arearectangle1, 2 Traceback most recent call last: ... ValueError: arearectangle only accepts nonnegative values arearectangle1, 2 Traceback most recent call last: ... ValueError: arearectangle only accepts nonnegative values Calculate the area of a square. areasquare10 100 areasquare0 0 areasquare1.6 2.5600000000000005 areasquare1 Traceback most recent call last: ... ValueError: areasquare only accepts nonnegative values Calculate the area of a triangle given the base and height. areatriangle10, 10 50.0 areatriangle1.6, 2.6 2.08 areatriangle0, 0 0.0 areatriangle1, 2 Traceback most recent call last: ... ValueError: areatriangle only accepts nonnegative values areatriangle1, 2 Traceback most recent call last: ... ValueError: areatriangle only accepts nonnegative values areatriangle1, 2 Traceback most recent call last: ... ValueError: areatriangle only accepts nonnegative values Calculate area of triangle when the length of 3 sides are known. This function uses Heron's formula: https:en.wikipedia.orgwikiHeron27sformula areatrianglethreesides5, 12, 13 30.0 areatrianglethreesides10, 11, 12 51.521233486786784 areatrianglethreesides0, 0, 0 0.0 areatrianglethreesides1.6, 2.6, 3.6 1.8703742940919619 areatrianglethreesides1, 2, 1 Traceback most recent call last: ... ValueError: areatrianglethreesides only accepts nonnegative values areatrianglethreesides1, 2, 1 Traceback most recent call last: ... ValueError: areatrianglethreesides only accepts nonnegative values areatrianglethreesides2, 4, 7 Traceback most recent call last: ... ValueError: Given three sides do not form a triangle areatrianglethreesides2, 7, 4 Traceback most recent call last: ... ValueError: Given three sides do not form a triangle areatrianglethreesides7, 2, 4 Traceback most recent call last: ... ValueError: Given three sides do not form a triangle Calculate the area of a parallelogram. areaparallelogram10, 20 200 areaparallelogram1.6, 2.6 4.16 areaparallelogram0, 0 0 areaparallelogram1, 2 Traceback most recent call last: ... ValueError: areaparallelogram only accepts nonnegative values areaparallelogram1, 2 Traceback most recent call last: ... ValueError: areaparallelogram only accepts nonnegative values areaparallelogram1, 2 Traceback most recent call last: ... ValueError: areaparallelogram only accepts nonnegative values Calculate the area of a trapezium. areatrapezium10, 20, 30 450.0 areatrapezium1.6, 2.6, 3.6 7.5600000000000005 areatrapezium0, 0, 0 0.0 areatrapezium1, 2, 3 Traceback most recent call last: ... ValueError: areatrapezium only accepts nonnegative values areatrapezium1, 2, 3 Traceback most recent call last: ... ValueError: areatrapezium only accepts nonnegative values areatrapezium1, 2, 3 Traceback most recent call last: ... ValueError: areatrapezium only accepts nonnegative values areatrapezium1, 2, 3 Traceback most recent call last: ... ValueError: areatrapezium only accepts nonnegative values areatrapezium1, 2, 3 Traceback most recent call last: ... ValueError: areatrapezium only accepts nonnegative values areatrapezium1, 2, 3 Traceback most recent call last: ... ValueError: areatrapezium only accepts nonnegative values areatrapezium1, 2, 3 Traceback most recent call last: ... ValueError: areatrapezium only accepts nonnegative values Calculate the area of a circle. areacircle20 1256.6370614359173 areacircle1.6 8.042477193189871 areacircle0 0.0 areacircle1 Traceback most recent call last: ... ValueError: areacircle only accepts nonnegative values Calculate the area of a ellipse. areaellipse10, 10 314.1592653589793 areaellipse10, 20 628.3185307179587 areaellipse0, 0 0.0 areaellipse1.6, 2.6 13.06902543893354 areaellipse10, 20 Traceback most recent call last: ... ValueError: areaellipse only accepts nonnegative values areaellipse10, 20 Traceback most recent call last: ... ValueError: areaellipse only accepts nonnegative values areaellipse10, 20 Traceback most recent call last: ... ValueError: areaellipse only accepts nonnegative values Calculate the area of a rhombus. arearhombus10, 20 100.0 arearhombus1.6, 2.6 2.08 arearhombus0, 0 0.0 arearhombus1, 2 Traceback most recent call last: ... ValueError: arearhombus only accepts nonnegative values arearhombus1, 2 Traceback most recent call last: ... ValueError: arearhombus only accepts nonnegative values arearhombus1, 2 Traceback most recent call last: ... ValueError: arearhombus only accepts nonnegative values Calculate the area of a regular polygon. Wikipedia reference: https:en.wikipedia.orgwikiPolygonRegularpolygons Formula: ns2cotpin4 arearegpolygon3, 10 43.301270189221945 arearegpolygon4, 10 100.00000000000001 arearegpolygon0, 0 Traceback most recent call last: ... ValueError: arearegpolygon only accepts integers greater than or equal to three as number of sides arearegpolygon1, 2 Traceback most recent call last: ... ValueError: arearegpolygon only accepts integers greater than or equal to three as number of sides arearegpolygon5, 2 Traceback most recent call last: ... ValueError: arearegpolygon only accepts nonnegative values as length of a side arearegpolygon1, 2 Traceback most recent call last: ... ValueError: arearegpolygon only accepts integers greater than or equal to three as number of sides","Completions":"from math import pi, sqrt, tan\n\n\ndef surface_area_cube(side_length: float) -> float:\n \"\"\"\n Calculate the Surface Area of a Cube.\n\n >>> surface_area_cube(1)\n 6\n >>> surface_area_cube(1.6)\n 15.360000000000003\n >>> surface_area_cube(0)\n 0\n >>> surface_area_cube(3)\n 54\n >>> surface_area_cube(-1)\n Traceback (most recent call last):\n ...\n ValueError: surface_area_cube() only accepts non-negative values\n \"\"\"\n if side_length < 0:\n raise ValueError(\"surface_area_cube() only accepts non-negative values\")\n return 6 * side_length**2\n\n\ndef surface_area_cuboid(length: float, breadth: float, height: float) -> float:\n \"\"\"\n Calculate the Surface Area of a Cuboid.\n\n >>> surface_area_cuboid(1, 2, 3)\n 22\n >>> surface_area_cuboid(0, 0, 0)\n 0\n >>> surface_area_cuboid(1.6, 2.6, 3.6)\n 38.56\n >>> surface_area_cuboid(-1, 2, 3)\n Traceback (most recent call last):\n ...\n ValueError: surface_area_cuboid() only accepts non-negative values\n >>> surface_area_cuboid(1, -2, 3)\n Traceback (most recent call last):\n ...\n ValueError: surface_area_cuboid() only accepts non-negative values\n >>> surface_area_cuboid(1, 2, -3)\n Traceback (most recent call last):\n ...\n ValueError: surface_area_cuboid() only accepts non-negative values\n \"\"\"\n if length < 0 or breadth < 0 or height < 0:\n raise ValueError(\"surface_area_cuboid() only accepts non-negative values\")\n return 2 * ((length * breadth) + (breadth * height) + (length * height))\n\n\ndef surface_area_sphere(radius: float) -> float:\n \"\"\"\n Calculate the Surface Area of a Sphere.\n Wikipedia reference: https:\/\/en.wikipedia.org\/wiki\/Sphere\n Formula: 4 * pi * r^2\n\n >>> surface_area_sphere(5)\n 314.1592653589793\n >>> surface_area_sphere(1)\n 12.566370614359172\n >>> surface_area_sphere(1.6)\n 32.169908772759484\n >>> surface_area_sphere(0)\n 0.0\n >>> surface_area_sphere(-1)\n Traceback (most recent call last):\n ...\n ValueError: surface_area_sphere() only accepts non-negative values\n \"\"\"\n if radius < 0:\n raise ValueError(\"surface_area_sphere() only accepts non-negative values\")\n return 4 * pi * radius**2\n\n\ndef surface_area_hemisphere(radius: float) -> float:\n \"\"\"\n Calculate the Surface Area of a Hemisphere.\n Formula: 3 * pi * r^2\n\n >>> surface_area_hemisphere(5)\n 235.61944901923448\n >>> surface_area_hemisphere(1)\n 9.42477796076938\n >>> surface_area_hemisphere(0)\n 0.0\n >>> surface_area_hemisphere(1.1)\n 11.40398133253095\n >>> surface_area_hemisphere(-1)\n Traceback (most recent call last):\n ...\n ValueError: surface_area_hemisphere() only accepts non-negative values\n \"\"\"\n if radius < 0:\n raise ValueError(\"surface_area_hemisphere() only accepts non-negative values\")\n return 3 * pi * radius**2\n\n\ndef surface_area_cone(radius: float, height: float) -> float:\n \"\"\"\n Calculate the Surface Area of a Cone.\n Wikipedia reference: https:\/\/en.wikipedia.org\/wiki\/Cone\n Formula: pi * r * (r + (h ** 2 + r ** 2) ** 0.5)\n\n >>> surface_area_cone(10, 24)\n 1130.9733552923256\n >>> surface_area_cone(6, 8)\n 301.59289474462014\n >>> surface_area_cone(1.6, 2.6)\n 23.387862992395807\n >>> surface_area_cone(0, 0)\n 0.0\n >>> surface_area_cone(-1, -2)\n Traceback (most recent call last):\n ...\n ValueError: surface_area_cone() only accepts non-negative values\n >>> surface_area_cone(1, -2)\n Traceback (most recent call last):\n ...\n ValueError: surface_area_cone() only accepts non-negative values\n >>> surface_area_cone(-1, 2)\n Traceback (most recent call last):\n ...\n ValueError: surface_area_cone() only accepts non-negative values\n \"\"\"\n if radius < 0 or height < 0:\n raise ValueError(\"surface_area_cone() only accepts non-negative values\")\n return pi * radius * (radius + (height**2 + radius**2) ** 0.5)\n\n\ndef surface_area_conical_frustum(\n radius_1: float, radius_2: float, height: float\n) -> float:\n \"\"\"\n Calculate the Surface Area of a Conical Frustum.\n\n >>> surface_area_conical_frustum(1, 2, 3)\n 45.511728065337266\n >>> surface_area_conical_frustum(4, 5, 6)\n 300.7913575056268\n >>> surface_area_conical_frustum(0, 0, 0)\n 0.0\n >>> surface_area_conical_frustum(1.6, 2.6, 3.6)\n 78.57907060751548\n >>> surface_area_conical_frustum(-1, 2, 3)\n Traceback (most recent call last):\n ...\n ValueError: surface_area_conical_frustum() only accepts non-negative values\n >>> surface_area_conical_frustum(1, -2, 3)\n Traceback (most recent call last):\n ...\n ValueError: surface_area_conical_frustum() only accepts non-negative values\n >>> surface_area_conical_frustum(1, 2, -3)\n Traceback (most recent call last):\n ...\n ValueError: surface_area_conical_frustum() only accepts non-negative values\n \"\"\"\n if radius_1 < 0 or radius_2 < 0 or height < 0:\n raise ValueError(\n \"surface_area_conical_frustum() only accepts non-negative values\"\n )\n slant_height = (height**2 + (radius_1 - radius_2) ** 2) ** 0.5\n return pi * ((slant_height * (radius_1 + radius_2)) + radius_1**2 + radius_2**2)\n\n\ndef surface_area_cylinder(radius: float, height: float) -> float:\n \"\"\"\n Calculate the Surface Area of a Cylinder.\n Wikipedia reference: https:\/\/en.wikipedia.org\/wiki\/Cylinder\n Formula: 2 * pi * r * (h + r)\n\n >>> surface_area_cylinder(7, 10)\n 747.6990515543707\n >>> surface_area_cylinder(1.6, 2.6)\n 42.22300526424682\n >>> surface_area_cylinder(0, 0)\n 0.0\n >>> surface_area_cylinder(6, 8)\n 527.7875658030853\n >>> surface_area_cylinder(-1, -2)\n Traceback (most recent call last):\n ...\n ValueError: surface_area_cylinder() only accepts non-negative values\n >>> surface_area_cylinder(1, -2)\n Traceback (most recent call last):\n ...\n ValueError: surface_area_cylinder() only accepts non-negative values\n >>> surface_area_cylinder(-1, 2)\n Traceback (most recent call last):\n ...\n ValueError: surface_area_cylinder() only accepts non-negative values\n \"\"\"\n if radius < 0 or height < 0:\n raise ValueError(\"surface_area_cylinder() only accepts non-negative values\")\n return 2 * pi * radius * (height + radius)\n\n\ndef surface_area_torus(torus_radius: float, tube_radius: float) -> float:\n \"\"\"Calculate the Area of a Torus.\n Wikipedia reference: https:\/\/en.wikipedia.org\/wiki\/Torus\n :return 4pi^2 * torus_radius * tube_radius\n >>> surface_area_torus(1, 1)\n 39.47841760435743\n >>> surface_area_torus(4, 3)\n 473.7410112522892\n >>> surface_area_torus(3, 4)\n Traceback (most recent call last):\n ...\n ValueError: surface_area_torus() does not support spindle or self intersecting tori\n >>> surface_area_torus(1.6, 1.6)\n 101.06474906715503\n >>> surface_area_torus(0, 0)\n 0.0\n >>> surface_area_torus(-1, 1)\n Traceback (most recent call last):\n ...\n ValueError: surface_area_torus() only accepts non-negative values\n >>> surface_area_torus(1, -1)\n Traceback (most recent call last):\n ...\n ValueError: surface_area_torus() only accepts non-negative values\n \"\"\"\n if torus_radius < 0 or tube_radius < 0:\n raise ValueError(\"surface_area_torus() only accepts non-negative values\")\n if torus_radius < tube_radius:\n raise ValueError(\n \"surface_area_torus() does not support spindle or self intersecting tori\"\n )\n return 4 * pow(pi, 2) * torus_radius * tube_radius\n\n\ndef area_rectangle(length: float, width: float) -> float:\n \"\"\"\n Calculate the area of a rectangle.\n\n >>> area_rectangle(10, 20)\n 200\n >>> area_rectangle(1.6, 2.6)\n 4.16\n >>> area_rectangle(0, 0)\n 0\n >>> area_rectangle(-1, -2)\n Traceback (most recent call last):\n ...\n ValueError: area_rectangle() only accepts non-negative values\n >>> area_rectangle(1, -2)\n Traceback (most recent call last):\n ...\n ValueError: area_rectangle() only accepts non-negative values\n >>> area_rectangle(-1, 2)\n Traceback (most recent call last):\n ...\n ValueError: area_rectangle() only accepts non-negative values\n \"\"\"\n if length < 0 or width < 0:\n raise ValueError(\"area_rectangle() only accepts non-negative values\")\n return length * width\n\n\ndef area_square(side_length: float) -> float:\n \"\"\"\n Calculate the area of a square.\n\n >>> area_square(10)\n 100\n >>> area_square(0)\n 0\n >>> area_square(1.6)\n 2.5600000000000005\n >>> area_square(-1)\n Traceback (most recent call last):\n ...\n ValueError: area_square() only accepts non-negative values\n \"\"\"\n if side_length < 0:\n raise ValueError(\"area_square() only accepts non-negative values\")\n return side_length**2\n\n\ndef area_triangle(base: float, height: float) -> float:\n \"\"\"\n Calculate the area of a triangle given the base and height.\n\n >>> area_triangle(10, 10)\n 50.0\n >>> area_triangle(1.6, 2.6)\n 2.08\n >>> area_triangle(0, 0)\n 0.0\n >>> area_triangle(-1, -2)\n Traceback (most recent call last):\n ...\n ValueError: area_triangle() only accepts non-negative values\n >>> area_triangle(1, -2)\n Traceback (most recent call last):\n ...\n ValueError: area_triangle() only accepts non-negative values\n >>> area_triangle(-1, 2)\n Traceback (most recent call last):\n ...\n ValueError: area_triangle() only accepts non-negative values\n \"\"\"\n if base < 0 or height < 0:\n raise ValueError(\"area_triangle() only accepts non-negative values\")\n return (base * height) \/ 2\n\n\ndef area_triangle_three_sides(side1: float, side2: float, side3: float) -> float:\n \"\"\"\n Calculate area of triangle when the length of 3 sides are known.\n This function uses Heron's formula: https:\/\/en.wikipedia.org\/wiki\/Heron%27s_formula\n\n >>> area_triangle_three_sides(5, 12, 13)\n 30.0\n >>> area_triangle_three_sides(10, 11, 12)\n 51.521233486786784\n >>> area_triangle_three_sides(0, 0, 0)\n 0.0\n >>> area_triangle_three_sides(1.6, 2.6, 3.6)\n 1.8703742940919619\n >>> area_triangle_three_sides(-1, -2, -1)\n Traceback (most recent call last):\n ...\n ValueError: area_triangle_three_sides() only accepts non-negative values\n >>> area_triangle_three_sides(1, -2, 1)\n Traceback (most recent call last):\n ...\n ValueError: area_triangle_three_sides() only accepts non-negative values\n >>> area_triangle_three_sides(2, 4, 7)\n Traceback (most recent call last):\n ...\n ValueError: Given three sides do not form a triangle\n >>> area_triangle_three_sides(2, 7, 4)\n Traceback (most recent call last):\n ...\n ValueError: Given three sides do not form a triangle\n >>> area_triangle_three_sides(7, 2, 4)\n Traceback (most recent call last):\n ...\n ValueError: Given three sides do not form a triangle\n \"\"\"\n if side1 < 0 or side2 < 0 or side3 < 0:\n raise ValueError(\"area_triangle_three_sides() only accepts non-negative values\")\n elif side1 + side2 < side3 or side1 + side3 < side2 or side2 + side3 < side1:\n raise ValueError(\"Given three sides do not form a triangle\")\n semi_perimeter = (side1 + side2 + side3) \/ 2\n area = sqrt(\n semi_perimeter\n * (semi_perimeter - side1)\n * (semi_perimeter - side2)\n * (semi_perimeter - side3)\n )\n return area\n\n\ndef area_parallelogram(base: float, height: float) -> float:\n \"\"\"\n Calculate the area of a parallelogram.\n\n >>> area_parallelogram(10, 20)\n 200\n >>> area_parallelogram(1.6, 2.6)\n 4.16\n >>> area_parallelogram(0, 0)\n 0\n >>> area_parallelogram(-1, -2)\n Traceback (most recent call last):\n ...\n ValueError: area_parallelogram() only accepts non-negative values\n >>> area_parallelogram(1, -2)\n Traceback (most recent call last):\n ...\n ValueError: area_parallelogram() only accepts non-negative values\n >>> area_parallelogram(-1, 2)\n Traceback (most recent call last):\n ...\n ValueError: area_parallelogram() only accepts non-negative values\n \"\"\"\n if base < 0 or height < 0:\n raise ValueError(\"area_parallelogram() only accepts non-negative values\")\n return base * height\n\n\ndef area_trapezium(base1: float, base2: float, height: float) -> float:\n \"\"\"\n Calculate the area of a trapezium.\n\n >>> area_trapezium(10, 20, 30)\n 450.0\n >>> area_trapezium(1.6, 2.6, 3.6)\n 7.5600000000000005\n >>> area_trapezium(0, 0, 0)\n 0.0\n >>> area_trapezium(-1, -2, -3)\n Traceback (most recent call last):\n ...\n ValueError: area_trapezium() only accepts non-negative values\n >>> area_trapezium(-1, 2, 3)\n Traceback (most recent call last):\n ...\n ValueError: area_trapezium() only accepts non-negative values\n >>> area_trapezium(1, -2, 3)\n Traceback (most recent call last):\n ...\n ValueError: area_trapezium() only accepts non-negative values\n >>> area_trapezium(1, 2, -3)\n Traceback (most recent call last):\n ...\n ValueError: area_trapezium() only accepts non-negative values\n >>> area_trapezium(-1, -2, 3)\n Traceback (most recent call last):\n ...\n ValueError: area_trapezium() only accepts non-negative values\n >>> area_trapezium(1, -2, -3)\n Traceback (most recent call last):\n ...\n ValueError: area_trapezium() only accepts non-negative values\n >>> area_trapezium(-1, 2, -3)\n Traceback (most recent call last):\n ...\n ValueError: area_trapezium() only accepts non-negative values\n \"\"\"\n if base1 < 0 or base2 < 0 or height < 0:\n raise ValueError(\"area_trapezium() only accepts non-negative values\")\n return 1 \/ 2 * (base1 + base2) * height\n\n\ndef area_circle(radius: float) -> float:\n \"\"\"\n Calculate the area of a circle.\n\n >>> area_circle(20)\n 1256.6370614359173\n >>> area_circle(1.6)\n 8.042477193189871\n >>> area_circle(0)\n 0.0\n >>> area_circle(-1)\n Traceback (most recent call last):\n ...\n ValueError: area_circle() only accepts non-negative values\n \"\"\"\n if radius < 0:\n raise ValueError(\"area_circle() only accepts non-negative values\")\n return pi * radius**2\n\n\ndef area_ellipse(radius_x: float, radius_y: float) -> float:\n \"\"\"\n Calculate the area of a ellipse.\n\n >>> area_ellipse(10, 10)\n 314.1592653589793\n >>> area_ellipse(10, 20)\n 628.3185307179587\n >>> area_ellipse(0, 0)\n 0.0\n >>> area_ellipse(1.6, 2.6)\n 13.06902543893354\n >>> area_ellipse(-10, 20)\n Traceback (most recent call last):\n ...\n ValueError: area_ellipse() only accepts non-negative values\n >>> area_ellipse(10, -20)\n Traceback (most recent call last):\n ...\n ValueError: area_ellipse() only accepts non-negative values\n >>> area_ellipse(-10, -20)\n Traceback (most recent call last):\n ...\n ValueError: area_ellipse() only accepts non-negative values\n \"\"\"\n if radius_x < 0 or radius_y < 0:\n raise ValueError(\"area_ellipse() only accepts non-negative values\")\n return pi * radius_x * radius_y\n\n\ndef area_rhombus(diagonal_1: float, diagonal_2: float) -> float:\n \"\"\"\n Calculate the area of a rhombus.\n\n >>> area_rhombus(10, 20)\n 100.0\n >>> area_rhombus(1.6, 2.6)\n 2.08\n >>> area_rhombus(0, 0)\n 0.0\n >>> area_rhombus(-1, -2)\n Traceback (most recent call last):\n ...\n ValueError: area_rhombus() only accepts non-negative values\n >>> area_rhombus(1, -2)\n Traceback (most recent call last):\n ...\n ValueError: area_rhombus() only accepts non-negative values\n >>> area_rhombus(-1, 2)\n Traceback (most recent call last):\n ...\n ValueError: area_rhombus() only accepts non-negative values\n \"\"\"\n if diagonal_1 < 0 or diagonal_2 < 0:\n raise ValueError(\"area_rhombus() only accepts non-negative values\")\n return 1 \/ 2 * diagonal_1 * diagonal_2\n\n\ndef area_reg_polygon(sides: int, length: float) -> float:\n \"\"\"\n Calculate the area of a regular polygon.\n Wikipedia reference: https:\/\/en.wikipedia.org\/wiki\/Polygon#Regular_polygons\n Formula: (n*s^2*cot(pi\/n))\/4\n\n >>> area_reg_polygon(3, 10)\n 43.301270189221945\n >>> area_reg_polygon(4, 10)\n 100.00000000000001\n >>> area_reg_polygon(0, 0)\n Traceback (most recent call last):\n ...\n ValueError: area_reg_polygon() only accepts integers greater than or equal to \\\nthree as number of sides\n >>> area_reg_polygon(-1, -2)\n Traceback (most recent call last):\n ...\n ValueError: area_reg_polygon() only accepts integers greater than or equal to \\\nthree as number of sides\n >>> area_reg_polygon(5, -2)\n Traceback (most recent call last):\n ...\n ValueError: area_reg_polygon() only accepts non-negative values as \\\nlength of a side\n >>> area_reg_polygon(-1, 2)\n Traceback (most recent call last):\n ...\n ValueError: area_reg_polygon() only accepts integers greater than or equal to \\\nthree as number of sides\n \"\"\"\n if not isinstance(sides, int) or sides < 3:\n raise ValueError(\n \"area_reg_polygon() only accepts integers greater than or \\\nequal to three as number of sides\"\n )\n elif length < 0:\n raise ValueError(\n \"area_reg_polygon() only accepts non-negative values as \\\nlength of a side\"\n )\n return (sides * length**2) \/ (4 * tan(pi \/ sides))\n return (sides * length**2) \/ (4 * tan(pi \/ sides))\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod(verbose=True) # verbose so we can see methods missing tests\n\n print(\"[DEMO] Areas of various geometric shapes: \\n\")\n print(f\"Rectangle: {area_rectangle(10, 20) = }\")\n print(f\"Square: {area_square(10) = }\")\n print(f\"Triangle: {area_triangle(10, 10) = }\")\n print(f\"Triangle: {area_triangle_three_sides(5, 12, 13) = }\")\n print(f\"Parallelogram: {area_parallelogram(10, 20) = }\")\n print(f\"Rhombus: {area_rhombus(10, 20) = }\")\n print(f\"Trapezium: {area_trapezium(10, 20, 30) = }\")\n print(f\"Circle: {area_circle(20) = }\")\n print(f\"Ellipse: {area_ellipse(10, 20) = }\")\n print(\"\\nSurface Areas of various geometric shapes: \\n\")\n print(f\"Cube: {surface_area_cube(20) = }\")\n print(f\"Cuboid: {surface_area_cuboid(10, 20, 30) = }\")\n print(f\"Sphere: {surface_area_sphere(20) = }\")\n print(f\"Hemisphere: {surface_area_hemisphere(20) = }\")\n print(f\"Cone: {surface_area_cone(10, 20) = }\")\n print(f\"Conical Frustum: {surface_area_conical_frustum(10, 20, 30) = }\")\n print(f\"Cylinder: {surface_area_cylinder(10, 20) = }\")\n print(f\"Torus: {surface_area_torus(20, 10) = }\")\n print(f\"Equilateral Triangle: {area_reg_polygon(3, 10) = }\")\n print(f\"Square: {area_reg_polygon(4, 10) = }\")\n print(f\"Reqular Pentagon: {area_reg_polygon(5, 10) = }\")\n"} +{"Prompt":"Approximates the area under the curve using the trapezoidal rule Treats curve as a collection of linear lines and sums the area of the trapezium shape they form :param fnc: a function which defines a curve :param xstart: left end point to indicate the start of line segment :param xend: right end point to indicate end of line segment :param steps: an accuracy gauge; more steps increases the accuracy :return: a float representing the length of the curve def fx: ... return 5 ftrapezoidalareaf, 12.0, 14.0, 1000:.3f '10.000' def fx: ... return 9x2 ftrapezoidalareaf, 4.0, 0, 10000:.4f '192.0000' ftrapezoidalareaf, 4.0, 4.0, 10000:.4f '384.0000' Approximates small segments of curve as linear and solve for trapezoidal area Increment step","Completions":"from __future__ import annotations\n\nfrom collections.abc import Callable\n\n\ndef trapezoidal_area(\n fnc: Callable[[float], float],\n x_start: float,\n x_end: float,\n steps: int = 100,\n) -> float:\n \"\"\"\n Treats curve as a collection of linear lines and sums the area of the\n trapezium shape they form\n :param fnc: a function which defines a curve\n :param x_start: left end point to indicate the start of line segment\n :param x_end: right end point to indicate end of line segment\n :param steps: an accuracy gauge; more steps increases the accuracy\n :return: a float representing the length of the curve\n\n >>> def f(x):\n ... return 5\n >>> f\"{trapezoidal_area(f, 12.0, 14.0, 1000):.3f}\"\n '10.000'\n >>> def f(x):\n ... return 9*x**2\n >>> f\"{trapezoidal_area(f, -4.0, 0, 10000):.4f}\"\n '192.0000'\n >>> f\"{trapezoidal_area(f, -4.0, 4.0, 10000):.4f}\"\n '384.0000'\n \"\"\"\n x1 = x_start\n fx1 = fnc(x_start)\n area = 0.0\n for _ in range(steps):\n # Approximates small segments of curve as linear and solve\n # for trapezoidal area\n x2 = (x_end - x_start) \/ steps + x1\n fx2 = fnc(x2)\n area += abs(fx2 + fx1) * (x2 - x1) \/ 2\n # Increment step\n x1 = x2\n fx1 = fx2\n return area\n\n\nif __name__ == \"__main__\":\n\n def f(x):\n return x**3 + x**2\n\n print(\"f(x) = x^3 + x^2\")\n print(\"The area between the curve, x = -5, x = 5 and the x axis is:\")\n i = 10\n while i <= 100000:\n print(f\"with {i} steps: {trapezoidal_area(f, -5, 5, i)}\")\n i *= 10\n"} +{"Prompt":"Return the average absolute deviation of a list of numbers. Wiki: https:en.wikipedia.orgwikiAverageabsolutedeviation averageabsolutedeviation0 0.0 averageabsolutedeviation4, 1, 3, 2 1.0 averageabsolutedeviation2, 70, 6, 50, 20, 8, 4, 0 20.0 averageabsolutedeviation20, 0, 30, 15 16.25 averageabsolutedeviation Traceback most recent call last: ... ValueError: List is empty","Completions":"def average_absolute_deviation(nums: list[int]) -> float:\n \"\"\"\n Return the average absolute deviation of a list of numbers.\n Wiki: https:\/\/en.wikipedia.org\/wiki\/Average_absolute_deviation\n\n >>> average_absolute_deviation([0])\n 0.0\n >>> average_absolute_deviation([4, 1, 3, 2])\n 1.0\n >>> average_absolute_deviation([2, 70, 6, 50, 20, 8, 4, 0])\n 20.0\n >>> average_absolute_deviation([-20, 0, 30, 15])\n 16.25\n >>> average_absolute_deviation([])\n Traceback (most recent call last):\n ...\n ValueError: List is empty\n \"\"\"\n if not nums: # Makes sure that the list is not empty\n raise ValueError(\"List is empty\")\n\n average = sum(nums) \/ len(nums) # Calculate the average\n return sum(abs(x - average) for x in nums) \/ len(nums)\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Find mean of a list of numbers. Wiki: https:en.wikipedia.orgwikiMean mean3, 6, 9, 12, 15, 18, 21 12.0 mean5, 10, 15, 20, 25, 30, 35 20.0 mean1, 2, 3, 4, 5, 6, 7, 8 4.5 mean Traceback most recent call last: ... ValueError: List is empty","Completions":"from __future__ import annotations\n\n\ndef mean(nums: list) -> float:\n \"\"\"\n Find mean of a list of numbers.\n Wiki: https:\/\/en.wikipedia.org\/wiki\/Mean\n\n >>> mean([3, 6, 9, 12, 15, 18, 21])\n 12.0\n >>> mean([5, 10, 15, 20, 25, 30, 35])\n 20.0\n >>> mean([1, 2, 3, 4, 5, 6, 7, 8])\n 4.5\n >>> mean([])\n Traceback (most recent call last):\n ...\n ValueError: List is empty\n \"\"\"\n if not nums:\n raise ValueError(\"List is empty\")\n return sum(nums) \/ len(nums)\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Find median of a list of numbers. Wiki: https:en.wikipedia.orgwikiMedian median0 0 median4, 1, 3, 2 2.5 median2, 70, 6, 50, 20, 8, 4 8 Args: nums: List of nums Returns: Median. The sorted function returns listSupportsRichComparisonTsorted which does not support","Completions":"from __future__ import annotations\n\n\ndef median(nums: list) -> int | float:\n \"\"\"\n Find median of a list of numbers.\n Wiki: https:\/\/en.wikipedia.org\/wiki\/Median\n\n >>> median([0])\n 0\n >>> median([4, 1, 3, 2])\n 2.5\n >>> median([2, 70, 6, 50, 20, 8, 4])\n 8\n\n Args:\n nums: List of nums\n\n Returns:\n Median.\n \"\"\"\n # The sorted function returns list[SupportsRichComparisonT@sorted]\n # which does not support `+`\n sorted_list: list[int] = sorted(nums)\n length = len(sorted_list)\n mid_index = length >> 1\n return (\n (sorted_list[mid_index] + sorted_list[mid_index - 1]) \/ 2\n if length % 2 == 0\n else sorted_list[mid_index]\n )\n\n\ndef main():\n import doctest\n\n doctest.testmod()\n\n\nif __name__ == \"__main__\":\n main()\n"} +{"Prompt":"This function returns the modeMode as in the measures of central tendency of the input data. The input list may contain any Datastructure or any Datatype. mode2, 3, 4, 5, 3, 4, 2, 5, 2, 2, 4, 2, 2, 2 2 mode3, 4, 5, 3, 4, 2, 5, 2, 2, 4, 4, 2, 2, 2 2 mode3, 4, 5, 3, 4, 2, 5, 2, 2, 4, 4, 4, 2, 2, 4, 2 2, 4 modex, y, y, z 'y' modex, x , y, y, z 'x', 'y' Gets values of modes","Completions":"from typing import Any\n\n\ndef mode(input_list: list) -> list[Any]:\n \"\"\"This function returns the mode(Mode as in the measures of\n central tendency) of the input data.\n\n The input list may contain any Datastructure or any Datatype.\n\n >>> mode([2, 3, 4, 5, 3, 4, 2, 5, 2, 2, 4, 2, 2, 2])\n [2]\n >>> mode([3, 4, 5, 3, 4, 2, 5, 2, 2, 4, 4, 2, 2, 2])\n [2]\n >>> mode([3, 4, 5, 3, 4, 2, 5, 2, 2, 4, 4, 4, 2, 2, 4, 2])\n [2, 4]\n >>> mode([\"x\", \"y\", \"y\", \"z\"])\n ['y']\n >>> mode([\"x\", \"x\" , \"y\", \"y\", \"z\"])\n ['x', 'y']\n \"\"\"\n if not input_list:\n return []\n result = [input_list.count(value) for value in input_list]\n y = max(result) # Gets the maximum count in the input list.\n # Gets values of modes\n return sorted({input_list[i] for i, value in enumerate(result) if value == y})\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Implement a popular pidigitextraction algorithm known as the BaileyBorweinPlouffe BBP formula to calculate the nth hex digit of pi. Wikipedia page: https:en.wikipedia.orgwikiBaileyE28093BorweinE28093Plouffeformula param digitposition: a positive integer representing the position of the digit to extract. The digit immediately after the decimal point is located at position 1. param precision: number of terms in the second summation to calculate. A higher number reduces the chance of an error but increases the runtime. return: a hexadecimal digit representing the digit at the nth position in pi's decimal expansion. .joinbaileyborweinplouffei for i in range1, 11 '243f6a8885' baileyborweinplouffe5, 10000 '6' baileyborweinplouffe10 Traceback most recent call last: ... ValueError: Digit position must be a positive integer baileyborweinplouffe0 Traceback most recent call last: ... ValueError: Digit position must be a positive integer baileyborweinplouffe1.7 Traceback most recent call last: ... ValueError: Digit position must be a positive integer baileyborweinplouffe2, 10 Traceback most recent call last: ... ValueError: Precision must be a nonnegative integer baileyborweinplouffe2, 1.6 Traceback most recent call last: ... ValueError: Precision must be a nonnegative integer compute an approximation of 16 n 1 pi whose fractional part is mostly accurate return the first hex digit of the fractional part of the result only care about first digit of fractional part; don't need decimal Private helper function to implement the summation functionality. param digitpostoextract: digit position to extract param denominatoraddend: added to denominator of fractions in the formula param precision: same as precision in main function return: floatingpoint number whose integer part is not important if the exponential term is an integer and we mod it by the denominator before dividing, only the integer part of the sum will change; the fractional part will not","Completions":"def bailey_borwein_plouffe(digit_position: int, precision: int = 1000) -> str:\n \"\"\"\n Implement a popular pi-digit-extraction algorithm known as the\n Bailey-Borwein-Plouffe (BBP) formula to calculate the nth hex digit of pi.\n Wikipedia page:\n https:\/\/en.wikipedia.org\/wiki\/Bailey%E2%80%93Borwein%E2%80%93Plouffe_formula\n @param digit_position: a positive integer representing the position of the digit to\n extract.\n The digit immediately after the decimal point is located at position 1.\n @param precision: number of terms in the second summation to calculate.\n A higher number reduces the chance of an error but increases the runtime.\n @return: a hexadecimal digit representing the digit at the nth position\n in pi's decimal expansion.\n\n >>> \"\".join(bailey_borwein_plouffe(i) for i in range(1, 11))\n '243f6a8885'\n >>> bailey_borwein_plouffe(5, 10000)\n '6'\n >>> bailey_borwein_plouffe(-10)\n Traceback (most recent call last):\n ...\n ValueError: Digit position must be a positive integer\n >>> bailey_borwein_plouffe(0)\n Traceback (most recent call last):\n ...\n ValueError: Digit position must be a positive integer\n >>> bailey_borwein_plouffe(1.7)\n Traceback (most recent call last):\n ...\n ValueError: Digit position must be a positive integer\n >>> bailey_borwein_plouffe(2, -10)\n Traceback (most recent call last):\n ...\n ValueError: Precision must be a nonnegative integer\n >>> bailey_borwein_plouffe(2, 1.6)\n Traceback (most recent call last):\n ...\n ValueError: Precision must be a nonnegative integer\n \"\"\"\n if (not isinstance(digit_position, int)) or (digit_position <= 0):\n raise ValueError(\"Digit position must be a positive integer\")\n elif (not isinstance(precision, int)) or (precision < 0):\n raise ValueError(\"Precision must be a nonnegative integer\")\n\n # compute an approximation of (16 ** (n - 1)) * pi whose fractional part is mostly\n # accurate\n sum_result = (\n 4 * _subsum(digit_position, 1, precision)\n - 2 * _subsum(digit_position, 4, precision)\n - _subsum(digit_position, 5, precision)\n - _subsum(digit_position, 6, precision)\n )\n\n # return the first hex digit of the fractional part of the result\n return hex(int((sum_result % 1) * 16))[2:]\n\n\ndef _subsum(\n digit_pos_to_extract: int, denominator_addend: int, precision: int\n) -> float:\n # only care about first digit of fractional part; don't need decimal\n \"\"\"\n Private helper function to implement the summation\n functionality.\n @param digit_pos_to_extract: digit position to extract\n @param denominator_addend: added to denominator of fractions in the formula\n @param precision: same as precision in main function\n @return: floating-point number whose integer part is not important\n \"\"\"\n total = 0.0\n for sum_index in range(digit_pos_to_extract + precision):\n denominator = 8 * sum_index + denominator_addend\n if sum_index < digit_pos_to_extract:\n # if the exponential term is an integer and we mod it by the denominator\n # before dividing, only the integer part of the sum will change;\n # the fractional part will not\n exponential_term = pow(\n 16, digit_pos_to_extract - 1 - sum_index, denominator\n )\n else:\n exponential_term = pow(16, digit_pos_to_extract - 1 - sum_index)\n total += exponential_term \/ denominator\n return total\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"This function returns the number negative base 2 of the decimal number of the input data. Args: int: The decimal number to convert. Returns: int: The negative base 2 number. Examples: decimaltonegativebase20 0 decimaltonegativebase219 111101 decimaltonegativebase24 100 decimaltonegativebase27 11011","Completions":"def decimal_to_negative_base_2(num: int) -> int:\n \"\"\"\n This function returns the number negative base 2\n of the decimal number of the input data.\n\n Args:\n int: The decimal number to convert.\n\n Returns:\n int: The negative base 2 number.\n\n Examples:\n >>> decimal_to_negative_base_2(0)\n 0\n >>> decimal_to_negative_base_2(-19)\n 111101\n >>> decimal_to_negative_base_2(4)\n 100\n >>> decimal_to_negative_base_2(7)\n 11011\n \"\"\"\n if num == 0:\n return 0\n ans = \"\"\n while num != 0:\n num, rem = divmod(num, -2)\n if rem < 0:\n rem += 2\n num += 1\n ans = str(rem) + ans\n return int(ans)\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Implementation of Basic Math in Python. import math def primefactorsn: int list: if n 0: raise ValueErrorOnly positive integers have prime factors pf while n 2 0: pf.append2 n intn 2 for i in range3, intmath.sqrtn 1, 2: while n i 0: pf.appendi n intn i if n 2: pf.appendn return pf def numberofdivisorsn: int int: if n 0: raise ValueErrorOnly positive numbers are accepted div 1 temp 1 while n 2 0: temp 1 n intn 2 div temp for i in range3, intmath.sqrtn 1, 2: temp 1 while n i 0: temp 1 n intn i div temp if n 1: div 2 return div def sumofdivisorsn: int int: if n 0: raise ValueErrorOnly positive numbers are accepted s 1 temp 1 while n 2 0: temp 1 n intn 2 if temp 1: s 2temp 1 2 1 for i in range3, intmath.sqrtn 1, 2: temp 1 while n i 0: temp 1 n intn i if temp 1: s itemp 1 i 1 return ints def eulerphin: int int: if n 0: raise ValueErrorOnly positive numbers are accepted s n for x in setprimefactorsn: s x 1 x return ints if name main: import doctest doctest.testmod","Completions":"import math\n\n\ndef prime_factors(n: int) -> list:\n \"\"\"Find Prime Factors.\n >>> prime_factors(100)\n [2, 2, 5, 5]\n >>> prime_factors(0)\n Traceback (most recent call last):\n ...\n ValueError: Only positive integers have prime factors\n >>> prime_factors(-10)\n Traceback (most recent call last):\n ...\n ValueError: Only positive integers have prime factors\n \"\"\"\n if n <= 0:\n raise ValueError(\"Only positive integers have prime factors\")\n pf = []\n while n % 2 == 0:\n pf.append(2)\n n = int(n \/ 2)\n for i in range(3, int(math.sqrt(n)) + 1, 2):\n while n % i == 0:\n pf.append(i)\n n = int(n \/ i)\n if n > 2:\n pf.append(n)\n return pf\n\n\ndef number_of_divisors(n: int) -> int:\n \"\"\"Calculate Number of Divisors of an Integer.\n >>> number_of_divisors(100)\n 9\n >>> number_of_divisors(0)\n Traceback (most recent call last):\n ...\n ValueError: Only positive numbers are accepted\n >>> number_of_divisors(-10)\n Traceback (most recent call last):\n ...\n ValueError: Only positive numbers are accepted\n \"\"\"\n if n <= 0:\n raise ValueError(\"Only positive numbers are accepted\")\n div = 1\n temp = 1\n while n % 2 == 0:\n temp += 1\n n = int(n \/ 2)\n div *= temp\n for i in range(3, int(math.sqrt(n)) + 1, 2):\n temp = 1\n while n % i == 0:\n temp += 1\n n = int(n \/ i)\n div *= temp\n if n > 1:\n div *= 2\n return div\n\n\ndef sum_of_divisors(n: int) -> int:\n \"\"\"Calculate Sum of Divisors.\n >>> sum_of_divisors(100)\n 217\n >>> sum_of_divisors(0)\n Traceback (most recent call last):\n ...\n ValueError: Only positive numbers are accepted\n >>> sum_of_divisors(-10)\n Traceback (most recent call last):\n ...\n ValueError: Only positive numbers are accepted\n \"\"\"\n if n <= 0:\n raise ValueError(\"Only positive numbers are accepted\")\n s = 1\n temp = 1\n while n % 2 == 0:\n temp += 1\n n = int(n \/ 2)\n if temp > 1:\n s *= (2**temp - 1) \/ (2 - 1)\n for i in range(3, int(math.sqrt(n)) + 1, 2):\n temp = 1\n while n % i == 0:\n temp += 1\n n = int(n \/ i)\n if temp > 1:\n s *= (i**temp - 1) \/ (i - 1)\n return int(s)\n\n\ndef euler_phi(n: int) -> int:\n \"\"\"Calculate Euler's Phi Function.\n >>> euler_phi(100)\n 40\n >>> euler_phi(0)\n Traceback (most recent call last):\n ...\n ValueError: Only positive numbers are accepted\n >>> euler_phi(-10)\n Traceback (most recent call last):\n ...\n ValueError: Only positive numbers are accepted\n \"\"\"\n if n <= 0:\n raise ValueError(\"Only positive numbers are accepted\")\n s = n\n for x in set(prime_factors(n)):\n s *= (x - 1) \/ x\n return int(s)\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Binary Exponentiation This is a method to find ab in Olog b time complexity and is one of the most commonly used methods of exponentiation. The method is also useful for modular exponentiation, when the solution to ab c is required. To calculate ab: If b is even, then ab a ab 2 If b is odd, then ab a ab 1 Repeat until b 1 or b 0 For modular exponentiation, we use the fact that a b c a c b c c Computes ab recursively, where a is the base and b is the exponent binaryexprecursive3, 5 243 binaryexprecursive11, 13 34522712143931 binaryexprecursive1, 3 1 binaryexprecursive0, 5 0 binaryexprecursive3, 1 3 binaryexprecursive3, 0 1 binaryexprecursive1.5, 4 5.0625 binaryexprecursive3, 1 Traceback most recent call last: ... ValueError: Exponent must be a nonnegative integer Computes ab iteratively, where a is the base and b is the exponent binaryexpiterative3, 5 243 binaryexpiterative11, 13 34522712143931 binaryexpiterative1, 3 1 binaryexpiterative0, 5 0 binaryexpiterative3, 1 3 binaryexpiterative3, 0 1 binaryexpiterative1.5, 4 5.0625 binaryexpiterative3, 1 Traceback most recent call last: ... ValueError: Exponent must be a nonnegative integer Computes ab c recursively, where a is the base, b is the exponent, and c is the modulus binaryexpmodrecursive3, 4, 5 1 binaryexpmodrecursive11, 13, 7 4 binaryexpmodrecursive1.5, 4, 3 2.0625 binaryexpmodrecursive7, 1, 10 Traceback most recent call last: ... ValueError: Exponent must be a nonnegative integer binaryexpmodrecursive7, 13, 0 Traceback most recent call last: ... ValueError: Modulus must be a positive integer Computes ab c iteratively, where a is the base, b is the exponent, and c is the modulus binaryexpmoditerative3, 4, 5 1 binaryexpmoditerative11, 13, 7 4 binaryexpmoditerative1.5, 4, 3 2.0625 binaryexpmoditerative7, 1, 10 Traceback most recent call last: ... ValueError: Exponent must be a nonnegative integer binaryexpmoditerative7, 13, 0 Traceback most recent call last: ... ValueError: Modulus must be a positive integer","Completions":"def binary_exp_recursive(base: float, exponent: int) -> float:\n \"\"\"\n Computes a^b recursively, where a is the base and b is the exponent\n\n >>> binary_exp_recursive(3, 5)\n 243\n >>> binary_exp_recursive(11, 13)\n 34522712143931\n >>> binary_exp_recursive(-1, 3)\n -1\n >>> binary_exp_recursive(0, 5)\n 0\n >>> binary_exp_recursive(3, 1)\n 3\n >>> binary_exp_recursive(3, 0)\n 1\n >>> binary_exp_recursive(1.5, 4)\n 5.0625\n >>> binary_exp_recursive(3, -1)\n Traceback (most recent call last):\n ...\n ValueError: Exponent must be a non-negative integer\n \"\"\"\n if exponent < 0:\n raise ValueError(\"Exponent must be a non-negative integer\")\n\n if exponent == 0:\n return 1\n\n if exponent % 2 == 1:\n return binary_exp_recursive(base, exponent - 1) * base\n\n b = binary_exp_recursive(base, exponent \/\/ 2)\n return b * b\n\n\ndef binary_exp_iterative(base: float, exponent: int) -> float:\n \"\"\"\n Computes a^b iteratively, where a is the base and b is the exponent\n\n >>> binary_exp_iterative(3, 5)\n 243\n >>> binary_exp_iterative(11, 13)\n 34522712143931\n >>> binary_exp_iterative(-1, 3)\n -1\n >>> binary_exp_iterative(0, 5)\n 0\n >>> binary_exp_iterative(3, 1)\n 3\n >>> binary_exp_iterative(3, 0)\n 1\n >>> binary_exp_iterative(1.5, 4)\n 5.0625\n >>> binary_exp_iterative(3, -1)\n Traceback (most recent call last):\n ...\n ValueError: Exponent must be a non-negative integer\n \"\"\"\n if exponent < 0:\n raise ValueError(\"Exponent must be a non-negative integer\")\n\n res: int | float = 1\n while exponent > 0:\n if exponent & 1:\n res *= base\n\n base *= base\n exponent >>= 1\n\n return res\n\n\ndef binary_exp_mod_recursive(base: float, exponent: int, modulus: int) -> float:\n \"\"\"\n Computes a^b % c recursively, where a is the base, b is the exponent, and c is the\n modulus\n\n >>> binary_exp_mod_recursive(3, 4, 5)\n 1\n >>> binary_exp_mod_recursive(11, 13, 7)\n 4\n >>> binary_exp_mod_recursive(1.5, 4, 3)\n 2.0625\n >>> binary_exp_mod_recursive(7, -1, 10)\n Traceback (most recent call last):\n ...\n ValueError: Exponent must be a non-negative integer\n >>> binary_exp_mod_recursive(7, 13, 0)\n Traceback (most recent call last):\n ...\n ValueError: Modulus must be a positive integer\n \"\"\"\n if exponent < 0:\n raise ValueError(\"Exponent must be a non-negative integer\")\n if modulus <= 0:\n raise ValueError(\"Modulus must be a positive integer\")\n\n if exponent == 0:\n return 1\n\n if exponent % 2 == 1:\n return (binary_exp_mod_recursive(base, exponent - 1, modulus) * base) % modulus\n\n r = binary_exp_mod_recursive(base, exponent \/\/ 2, modulus)\n return (r * r) % modulus\n\n\ndef binary_exp_mod_iterative(base: float, exponent: int, modulus: int) -> float:\n \"\"\"\n Computes a^b % c iteratively, where a is the base, b is the exponent, and c is the\n modulus\n\n >>> binary_exp_mod_iterative(3, 4, 5)\n 1\n >>> binary_exp_mod_iterative(11, 13, 7)\n 4\n >>> binary_exp_mod_iterative(1.5, 4, 3)\n 2.0625\n >>> binary_exp_mod_iterative(7, -1, 10)\n Traceback (most recent call last):\n ...\n ValueError: Exponent must be a non-negative integer\n >>> binary_exp_mod_iterative(7, 13, 0)\n Traceback (most recent call last):\n ...\n ValueError: Modulus must be a positive integer\n \"\"\"\n if exponent < 0:\n raise ValueError(\"Exponent must be a non-negative integer\")\n if modulus <= 0:\n raise ValueError(\"Modulus must be a positive integer\")\n\n res: int | float = 1\n while exponent > 0:\n if exponent & 1:\n res = ((res % modulus) * (base % modulus)) % modulus\n\n base *= base\n exponent >>= 1\n\n return res\n\n\nif __name__ == \"__main__\":\n from timeit import timeit\n\n a = 1269380576\n b = 374\n c = 34\n\n runs = 100_000\n print(\n timeit(\n f\"binary_exp_recursive({a}, {b})\",\n setup=\"from __main__ import binary_exp_recursive\",\n number=runs,\n )\n )\n print(\n timeit(\n f\"binary_exp_iterative({a}, {b})\",\n setup=\"from __main__ import binary_exp_iterative\",\n number=runs,\n )\n )\n print(\n timeit(\n f\"binary_exp_mod_recursive({a}, {b}, {c})\",\n setup=\"from __main__ import binary_exp_mod_recursive\",\n number=runs,\n )\n )\n print(\n timeit(\n f\"binary_exp_mod_iterative({a}, {b}, {c})\",\n setup=\"from __main__ import binary_exp_mod_iterative\",\n number=runs,\n )\n )\n"} +{"Prompt":"Binary Multiplication This is a method to find ab in a time complexity of Olog b This is one of the most commonly used methods of finding result of multiplication. Also useful in cases where solution to abc is required, where a,b,c can be numbers over the computers calculation limits. Done using iteration, can also be done using recursion Let's say you need to calculate a b RULE 1 : a b aa b2 example : 4 4 44 42 8 2 RULE 2 : IF b is odd, then a b a a b 1, where b 1 is even. Once b is even, repeat the process to get a b Repeat the process until b 1 or b 0, because a1 a and a0 0 As far as the modulo is concerned, the fact : ab c ac bc c Now apply RULE 1 or 2, whichever is required. author chinmoy159 Multiply 'a' and 'b' using bitwise multiplication. Parameters: a int: The first number. b int: The second number. Returns: int: a b Examples: binarymultiply2, 3 6 binarymultiply5, 0 0 binarymultiply3, 4 12 binarymultiply10, 5 50 binarymultiply0, 5 0 binarymultiply2, 1 2 binarymultiply1, 10 10 Calculate a b c using binary multiplication and modular arithmetic. Parameters: a int: The first number. b int: The second number. modulus int: The modulus. Returns: int: a b modulus. Examples: binarymodmultiply2, 3, 5 1 binarymodmultiply5, 0, 7 0 binarymodmultiply3, 4, 6 0 binarymodmultiply10, 5, 13 11 binarymodmultiply2, 1, 5 2 binarymodmultiply1, 10, 3 1","Completions":"def binary_multiply(a: int, b: int) -> int:\n \"\"\"\n Multiply 'a' and 'b' using bitwise multiplication.\n\n Parameters:\n a (int): The first number.\n b (int): The second number.\n\n Returns:\n int: a * b\n\n Examples:\n >>> binary_multiply(2, 3)\n 6\n >>> binary_multiply(5, 0)\n 0\n >>> binary_multiply(3, 4)\n 12\n >>> binary_multiply(10, 5)\n 50\n >>> binary_multiply(0, 5)\n 0\n >>> binary_multiply(2, 1)\n 2\n >>> binary_multiply(1, 10)\n 10\n \"\"\"\n res = 0\n while b > 0:\n if b & 1:\n res += a\n\n a += a\n b >>= 1\n\n return res\n\n\ndef binary_mod_multiply(a: int, b: int, modulus: int) -> int:\n \"\"\"\n Calculate (a * b) % c using binary multiplication and modular arithmetic.\n\n Parameters:\n a (int): The first number.\n b (int): The second number.\n modulus (int): The modulus.\n\n Returns:\n int: (a * b) % modulus.\n\n Examples:\n >>> binary_mod_multiply(2, 3, 5)\n 1\n >>> binary_mod_multiply(5, 0, 7)\n 0\n >>> binary_mod_multiply(3, 4, 6)\n 0\n >>> binary_mod_multiply(10, 5, 13)\n 11\n >>> binary_mod_multiply(2, 1, 5)\n 2\n >>> binary_mod_multiply(1, 10, 3)\n 1\n \"\"\"\n res = 0\n while b > 0:\n if b & 1:\n res = ((res % modulus) + (a % modulus)) % modulus\n\n a += a\n b >>= 1\n\n return res\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Find binomial coefficient using Pascal's triangle. Calculate Cn, r using Pascal's triangle. :param n: The total number of items. :param r: The number of items to choose. :return: The binomial coefficient Cn, r. binomialcoefficient10, 5 252 binomialcoefficient10, 0 1 binomialcoefficient0, 10 1 binomialcoefficient10, 10 1 binomialcoefficient5, 2 10 binomialcoefficient5, 6 0 binomialcoefficient3, 5 0 binomialcoefficient2, 3 Traceback most recent call last: ... ValueError: n and r must be nonnegative integers binomialcoefficient5, 1 Traceback most recent call last: ... ValueError: n and r must be nonnegative integers binomialcoefficient10.1, 5 Traceback most recent call last: ... TypeError: 'float' object cannot be interpreted as an integer binomialcoefficient10, 5.1 Traceback most recent call last: ... TypeError: 'float' object cannot be interpreted as an integer nc0 1 to compute current row from previous row.","Completions":"def binomial_coefficient(n: int, r: int) -> int:\n \"\"\"\n Find binomial coefficient using Pascal's triangle.\n\n Calculate C(n, r) using Pascal's triangle.\n\n :param n: The total number of items.\n :param r: The number of items to choose.\n :return: The binomial coefficient C(n, r).\n\n >>> binomial_coefficient(10, 5)\n 252\n >>> binomial_coefficient(10, 0)\n 1\n >>> binomial_coefficient(0, 10)\n 1\n >>> binomial_coefficient(10, 10)\n 1\n >>> binomial_coefficient(5, 2)\n 10\n >>> binomial_coefficient(5, 6)\n 0\n >>> binomial_coefficient(3, 5)\n 0\n >>> binomial_coefficient(-2, 3)\n Traceback (most recent call last):\n ...\n ValueError: n and r must be non-negative integers\n >>> binomial_coefficient(5, -1)\n Traceback (most recent call last):\n ...\n ValueError: n and r must be non-negative integers\n >>> binomial_coefficient(10.1, 5)\n Traceback (most recent call last):\n ...\n TypeError: 'float' object cannot be interpreted as an integer\n >>> binomial_coefficient(10, 5.1)\n Traceback (most recent call last):\n ...\n TypeError: 'float' object cannot be interpreted as an integer\n \"\"\"\n if n < 0 or r < 0:\n raise ValueError(\"n and r must be non-negative integers\")\n if 0 in (n, r):\n return 1\n c = [0 for i in range(r + 1)]\n # nc0 = 1\n c[0] = 1\n for i in range(1, n + 1):\n # to compute current row from previous row.\n j = min(i, r)\n while j > 0:\n c[j] += c[j - 1]\n j -= 1\n return c[r]\n\n\nif __name__ == \"__main__\":\n from doctest import testmod\n\n testmod()\n print(binomial_coefficient(n=10, r=5))\n"} +{"Prompt":"For more information about the Binomial Distribution https:en.wikipedia.orgwikiBinomialdistribution from math import factorial def binomialdistributionsuccesses: int, trials: int, prob: float float: if successes trials: raise ValueErrorsuccesses must be lower or equal to trials if trials 0 or successes 0: raise ValueErrorthe function is defined for nonnegative integers if not isinstancesuccesses, int or not isinstancetrials, int: raise ValueErrorthe function is defined for nonnegative integers if not 0 prob 1: raise ValueErrorprob has to be in range of 1 0 probability probsuccesses 1 prob trials successes Calculate the binomial coefficient: n! k!nk! coefficient floatfactorialtrials coefficient factorialsuccesses factorialtrials successes return probability coefficient if name main: from doctest import testmod testmod printProbability of 2 successes out of 4 trails printwith probability of 0.75 is:, end printbinomialdistribution2, 4, 0.75","Completions":"from math import factorial\n\n\ndef binomial_distribution(successes: int, trials: int, prob: float) -> float:\n \"\"\"\n Return probability of k successes out of n tries, with p probability for one\n success\n\n The function uses the factorial function in order to calculate the binomial\n coefficient\n\n >>> binomial_distribution(3, 5, 0.7)\n 0.30870000000000003\n >>> binomial_distribution (2, 4, 0.5)\n 0.375\n \"\"\"\n if successes > trials:\n raise ValueError(\"\"\"successes must be lower or equal to trials\"\"\")\n if trials < 0 or successes < 0:\n raise ValueError(\"the function is defined for non-negative integers\")\n if not isinstance(successes, int) or not isinstance(trials, int):\n raise ValueError(\"the function is defined for non-negative integers\")\n if not 0 < prob < 1:\n raise ValueError(\"prob has to be in range of 1 - 0\")\n probability = (prob**successes) * ((1 - prob) ** (trials - successes))\n # Calculate the binomial coefficient: n! \/ k!(n-k)!\n coefficient = float(factorial(trials))\n coefficient \/= factorial(successes) * factorial(trials - successes)\n return probability * coefficient\n\n\nif __name__ == \"__main__\":\n from doctest import testmod\n\n testmod()\n print(\"Probability of 2 successes out of 4 trails\")\n print(\"with probability of 0.75 is:\", end=\" \")\n print(binomial_distribution(2, 4, 0.75))\n"} +{"Prompt":"https:en.wikipedia.orgwikiFloorandceilingfunctions Return the ceiling of x as an Integral. :param x: the number :return: the smallest integer x. import math allceiln math.ceiln for n ... in 1, 1, 0, 0, 1.1, 1.1, 1.0, 1.0, 1000000000 True","Completions":"def ceil(x: float) -> int:\n \"\"\"\n Return the ceiling of x as an Integral.\n\n :param x: the number\n :return: the smallest integer >= x.\n\n >>> import math\n >>> all(ceil(n) == math.ceil(n) for n\n ... in (1, -1, 0, -0, 1.1, -1.1, 1.0, -1.0, 1_000_000_000))\n True\n \"\"\"\n return int(x) if x - int(x) <= 0 else int(x) + 1\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"This function calculates the Chebyshev distance also known as the Chessboard distance between two ndimensional points represented as lists. https:en.wikipedia.orgwikiChebyshevdistance chebyshevdistance1.0, 1.0, 2.0, 2.0 1.0 chebyshevdistance1.0, 1.0, 9.0, 2.0, 2.0, 5.2 14.2 chebyshevdistance1.0, 2.0, 2.0 Traceback most recent call last: ... ValueError: Both points must have the same dimension.","Completions":"def chebyshev_distance(point_a: list[float], point_b: list[float]) -> float:\n \"\"\"\n This function calculates the Chebyshev distance (also known as the\n Chessboard distance) between two n-dimensional points represented as lists.\n\n https:\/\/en.wikipedia.org\/wiki\/Chebyshev_distance\n\n >>> chebyshev_distance([1.0, 1.0], [2.0, 2.0])\n 1.0\n >>> chebyshev_distance([1.0, 1.0, 9.0], [2.0, 2.0, -5.2])\n 14.2\n >>> chebyshev_distance([1.0], [2.0, 2.0])\n Traceback (most recent call last):\n ...\n ValueError: Both points must have the same dimension.\n \"\"\"\n if len(point_a) != len(point_b):\n raise ValueError(\"Both points must have the same dimension.\")\n\n return max(abs(a - b) for a, b in zip(point_a, point_b))\n"} +{"Prompt":"Takes list of possible side lengths and determines whether a twodimensional polygon with such side lengths can exist. Returns a boolean value for the comparison of the largest side length with sum of the rest. Wiki: https:en.wikipedia.orgwikiTriangleinequality checkpolygon6, 10, 5 True checkpolygon3, 7, 13, 2 False checkpolygon1, 4.3, 5.2, 12.2 False nums 3, 7, 13, 2 checkpolygonnums Run function, do not show answer in output nums Check numbers are not reordered 3, 7, 13, 2 checkpolygon Traceback most recent call last: ... ValueError: Monogons and Digons are not polygons in the Euclidean space checkpolygon2, 5, 6 Traceback most recent call last: ... ValueError: All values must be greater than 0","Completions":"from __future__ import annotations\n\n\ndef check_polygon(nums: list[float]) -> bool:\n \"\"\"\n Takes list of possible side lengths and determines whether a\n two-dimensional polygon with such side lengths can exist.\n\n Returns a boolean value for the < comparison\n of the largest side length with sum of the rest.\n Wiki: https:\/\/en.wikipedia.org\/wiki\/Triangle_inequality\n\n >>> check_polygon([6, 10, 5])\n True\n >>> check_polygon([3, 7, 13, 2])\n False\n >>> check_polygon([1, 4.3, 5.2, 12.2])\n False\n >>> nums = [3, 7, 13, 2]\n >>> _ = check_polygon(nums) # Run function, do not show answer in output\n >>> nums # Check numbers are not reordered\n [3, 7, 13, 2]\n >>> check_polygon([])\n Traceback (most recent call last):\n ...\n ValueError: Monogons and Digons are not polygons in the Euclidean space\n >>> check_polygon([-2, 5, 6])\n Traceback (most recent call last):\n ...\n ValueError: All values must be greater than 0\n \"\"\"\n if len(nums) < 2:\n raise ValueError(\"Monogons and Digons are not polygons in the Euclidean space\")\n if any(i <= 0 for i in nums):\n raise ValueError(\"All values must be greater than 0\")\n copy_nums = nums.copy()\n copy_nums.sort()\n return copy_nums[-1] < sum(copy_nums[:-1])\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Chinese Remainder Theorem: GCD Greatest Common Divisor or HCF Highest Common Factor If GCDa,b 1, then for any remainder ra modulo a and any remainder rb modulo b there exists integer n, such that n ra mod a and n ramod b. If n1 and n2 are two such integers, then n1n2mod ab Algorithm : 1. Use extended euclid algorithm to find x,y such that ax by 1 2. Take n raby rbax Extended Euclid extendedeuclid10, 6 1, 2 extendedeuclid7, 5 2, 3 Uses ExtendedEuclid to find inverses chineseremaindertheorem5,1,7,3 31 Explanation : 31 is the smallest number such that i When we divide it by 5, we get remainder 1 ii When we divide it by 7, we get remainder 3 chineseremaindertheorem6,1,4,3 14 SAME SOLUTION USING InvertModulo instead ExtendedEuclid This function find the inverses of a i.e., a1 invertmodulo2, 5 3 invertmodulo8,7 1 Same a above using InvertingModulo chineseremaindertheorem25,1,7,3 31 chineseremaindertheorem26,1,4,3 14","Completions":"from __future__ import annotations\n\n\n# Extended Euclid\ndef extended_euclid(a: int, b: int) -> tuple[int, int]:\n \"\"\"\n >>> extended_euclid(10, 6)\n (-1, 2)\n\n >>> extended_euclid(7, 5)\n (-2, 3)\n\n \"\"\"\n if b == 0:\n return (1, 0)\n (x, y) = extended_euclid(b, a % b)\n k = a \/\/ b\n return (y, x - k * y)\n\n\n# Uses ExtendedEuclid to find inverses\ndef chinese_remainder_theorem(n1: int, r1: int, n2: int, r2: int) -> int:\n \"\"\"\n >>> chinese_remainder_theorem(5,1,7,3)\n 31\n\n Explanation : 31 is the smallest number such that\n (i) When we divide it by 5, we get remainder 1\n (ii) When we divide it by 7, we get remainder 3\n\n >>> chinese_remainder_theorem(6,1,4,3)\n 14\n\n \"\"\"\n (x, y) = extended_euclid(n1, n2)\n m = n1 * n2\n n = r2 * x * n1 + r1 * y * n2\n return (n % m + m) % m\n\n\n# ----------SAME SOLUTION USING InvertModulo instead ExtendedEuclid----------------\n\n\n# This function find the inverses of a i.e., a^(-1)\ndef invert_modulo(a: int, n: int) -> int:\n \"\"\"\n >>> invert_modulo(2, 5)\n 3\n\n >>> invert_modulo(8,7)\n 1\n\n \"\"\"\n (b, x) = extended_euclid(a, n)\n if b < 0:\n b = (b % n + n) % n\n return b\n\n\n# Same a above using InvertingModulo\ndef chinese_remainder_theorem2(n1: int, r1: int, n2: int, r2: int) -> int:\n \"\"\"\n >>> chinese_remainder_theorem2(5,1,7,3)\n 31\n\n >>> chinese_remainder_theorem2(6,1,4,3)\n 14\n\n \"\"\"\n x, y = invert_modulo(n1, n2), invert_modulo(n2, n1)\n m = n1 * n2\n n = r2 * x * n1 + r1 * y * n2\n return (n % m + m) % m\n\n\nif __name__ == \"__main__\":\n from doctest import testmod\n\n testmod(name=\"chinese_remainder_theorem\", verbose=True)\n testmod(name=\"chinese_remainder_theorem2\", verbose=True)\n testmod(name=\"invert_modulo\", verbose=True)\n testmod(name=\"extended_euclid\", verbose=True)\n"} +{"Prompt":"The Chudnovsky algorithm is a fast method for calculating the digits of PI, based on Ramanujans PI formulae. https:en.wikipedia.orgwikiChudnovskyalgorithm PI constantterm multinomialterm linearterm exponentialterm where constantterm 426880 sqrt10005 The linearterm and the exponentialterm can be defined iteratively as follows: Lk1 Lk 545140134 where L0 13591409 Xk1 Xk 262537412640768000 where X0 1 The multinomialterm is defined as follows: 6k! 3k! k! 3 where k is the kth iteration. This algorithm correctly calculates around 14 digits of PI per iteration pi10 '3.14159265' pi100 '3.14159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534211706' pi'hello' Traceback most recent call last: ... TypeError: Undefined for nonintegers pi1 Traceback most recent call last: ... ValueError: Undefined for nonnatural numbers","Completions":"from decimal import Decimal, getcontext\nfrom math import ceil, factorial\n\n\ndef pi(precision: int) -> str:\n \"\"\"\n The Chudnovsky algorithm is a fast method for calculating the digits of PI,\n based on Ramanujan\u2019s PI formulae.\n\n https:\/\/en.wikipedia.org\/wiki\/Chudnovsky_algorithm\n\n PI = constant_term \/ ((multinomial_term * linear_term) \/ exponential_term)\n where constant_term = 426880 * sqrt(10005)\n\n The linear_term and the exponential_term can be defined iteratively as follows:\n L_k+1 = L_k + 545140134 where L_0 = 13591409\n X_k+1 = X_k * -262537412640768000 where X_0 = 1\n\n The multinomial_term is defined as follows:\n 6k! \/ ((3k)! * (k!) ^ 3)\n where k is the k_th iteration.\n\n This algorithm correctly calculates around 14 digits of PI per iteration\n\n >>> pi(10)\n '3.14159265'\n >>> pi(100)\n '3.14159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534211706'\n >>> pi('hello')\n Traceback (most recent call last):\n ...\n TypeError: Undefined for non-integers\n >>> pi(-1)\n Traceback (most recent call last):\n ...\n ValueError: Undefined for non-natural numbers\n \"\"\"\n\n if not isinstance(precision, int):\n raise TypeError(\"Undefined for non-integers\")\n elif precision < 1:\n raise ValueError(\"Undefined for non-natural numbers\")\n\n getcontext().prec = precision\n num_iterations = ceil(precision \/ 14)\n constant_term = 426880 * Decimal(10005).sqrt()\n exponential_term = 1\n linear_term = 13591409\n partial_sum = Decimal(linear_term)\n for k in range(1, num_iterations):\n multinomial_term = factorial(6 * k) \/\/ (factorial(3 * k) * factorial(k) ** 3)\n linear_term += 545140134\n exponential_term *= -262537412640768000\n partial_sum += Decimal(multinomial_term * linear_term) \/ exponential_term\n return str(constant_term \/ partial_sum)[:-1]\n\n\nif __name__ == \"__main__\":\n n = 50\n print(f\"The first {n} digits of pi is: {pi(n)}\")\n"} +{"Prompt":"The Collatz conjecture is a famous unsolved problem in mathematics. Given a starting positive integer, define the following sequence: If the current term n is even, then the next term is n2. If the current term n is odd, then the next term is 3n 1. The conjecture claims that this sequence will always reach 1 for any starting number. Other names for this problem include the 3n 1 problem, the Ulam conjecture, Kakutani's problem, the Thwaites conjecture, Hasse's algorithm, the Syracuse problem, and the hailstone sequence. Reference: https:en.wikipedia.orgwikiCollatzconjecture Generate the Collatz sequence starting at n. tuplecollatzsequence2.1 Traceback most recent call last: ... Exception: Sequence only defined for positive integers tuplecollatzsequence0 Traceback most recent call last: ... Exception: Sequence only defined for positive integers tuplecollatzsequence4 4, 2, 1 tuplecollatzsequence11 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1 tuplecollatzsequence31 doctest: NORMALIZEWHITESPACE 31, 94, 47, 142, 71, 214, 107, 322, 161, 484, 242, 121, 364, 182, 91, 274, 137, 412, 206, 103, 310, 155, 466, 233, 700, 350, 175, 526, 263, 790, 395, 1186, 593, 1780, 890, 445, 1336, 668, 334, 167, 502, 251, 754, 377, 1132, 566, 283, 850, 425, 1276, 638, 319, 958, 479, 1438, 719, 2158, 1079, 3238, 1619, 4858, 2429, 7288, 3644, 1822, 911, 2734, 1367, 4102, 2051, 6154, 3077, 9232, 4616, 2308, 1154, 577, 1732, 866, 433, 1300, 650, 325, 976, 488, 244, 122, 61, 184, 92, 46, 23, 70, 35, 106, 53, 160, 80, 40, 20, 10, 5, 16, 8, 4, 2, 1 tuplecollatzsequence43 doctest: NORMALIZEWHITESPACE 43, 130, 65, 196, 98, 49, 148, 74, 37, 112, 56, 28, 14, 7, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1","Completions":"from __future__ import annotations\n\nfrom collections.abc import Generator\n\n\ndef collatz_sequence(n: int) -> Generator[int, None, None]:\n \"\"\"\n Generate the Collatz sequence starting at n.\n >>> tuple(collatz_sequence(2.1))\n Traceback (most recent call last):\n ...\n Exception: Sequence only defined for positive integers\n >>> tuple(collatz_sequence(0))\n Traceback (most recent call last):\n ...\n Exception: Sequence only defined for positive integers\n >>> tuple(collatz_sequence(4))\n (4, 2, 1)\n >>> tuple(collatz_sequence(11))\n (11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1)\n >>> tuple(collatz_sequence(31)) # doctest: +NORMALIZE_WHITESPACE\n (31, 94, 47, 142, 71, 214, 107, 322, 161, 484, 242, 121, 364, 182, 91, 274, 137,\n 412, 206, 103, 310, 155, 466, 233, 700, 350, 175, 526, 263, 790, 395, 1186, 593,\n 1780, 890, 445, 1336, 668, 334, 167, 502, 251, 754, 377, 1132, 566, 283, 850, 425,\n 1276, 638, 319, 958, 479, 1438, 719, 2158, 1079, 3238, 1619, 4858, 2429, 7288, 3644,\n 1822, 911, 2734, 1367, 4102, 2051, 6154, 3077, 9232, 4616, 2308, 1154, 577, 1732,\n 866, 433, 1300, 650, 325, 976, 488, 244, 122, 61, 184, 92, 46, 23, 70, 35, 106, 53,\n 160, 80, 40, 20, 10, 5, 16, 8, 4, 2, 1)\n >>> tuple(collatz_sequence(43)) # doctest: +NORMALIZE_WHITESPACE\n (43, 130, 65, 196, 98, 49, 148, 74, 37, 112, 56, 28, 14, 7, 22, 11, 34, 17, 52, 26,\n 13, 40, 20, 10, 5, 16, 8, 4, 2, 1)\n \"\"\"\n if not isinstance(n, int) or n < 1:\n raise Exception(\"Sequence only defined for positive integers\")\n\n yield n\n while n != 1:\n if n % 2 == 0:\n n \/\/= 2\n else:\n n = 3 * n + 1\n yield n\n\n\ndef main():\n n = int(input(\"Your number: \"))\n sequence = tuple(collatz_sequence(n))\n print(sequence)\n print(f\"Collatz sequence from {n} took {len(sequence)} steps.\")\n\n\nif __name__ == \"__main__\":\n main()\n"} +{"Prompt":"https:en.wikipedia.orgwikiCombination Returns the number of different combinations of k length which can be made from n values, where n k. Examples: combinations10,5 252 combinations6,3 20 combinations20,5 15504 combinations52, 5 2598960 combinations0, 0 1 combinations4, 5 ... Traceback most recent call last: ValueError: Please enter positive integers for n and k where n k If either of the conditions are true, the function is being asked to calculate a factorial of a negative number, which is not possible","Completions":"def combinations(n: int, k: int) -> int:\n \"\"\"\n Returns the number of different combinations of k length which can\n be made from n values, where n >= k.\n\n Examples:\n >>> combinations(10,5)\n 252\n\n >>> combinations(6,3)\n 20\n\n >>> combinations(20,5)\n 15504\n\n >>> combinations(52, 5)\n 2598960\n\n >>> combinations(0, 0)\n 1\n\n >>> combinations(-4, -5)\n ...\n Traceback (most recent call last):\n ValueError: Please enter positive integers for n and k where n >= k\n \"\"\"\n\n # If either of the conditions are true, the function is being asked\n # to calculate a factorial of a negative number, which is not possible\n if n < k or k < 0:\n raise ValueError(\"Please enter positive integers for n and k where n >= k\")\n res = 1\n for i in range(k):\n res *= n - i\n res \/\/= i + 1\n return res\n\n\nif __name__ == \"__main__\":\n print(\n \"The number of five-card hands possible from a standard\",\n f\"fifty-two card deck is: {combinations(52, 5)}\\n\",\n )\n\n print(\n \"If a class of 40 students must be arranged into groups of\",\n f\"4 for group projects, there are {combinations(40, 4)} ways\",\n \"to arrange them.\\n\",\n )\n\n print(\n \"If 10 teams are competing in a Formula One race, there\",\n f\"are {combinations(10, 3)} ways that first, second and\",\n \"third place can be awarded.\",\n )\n"} +{"Prompt":"Finding the continuous fraction for a rational number using python https:en.wikipedia.orgwikiContinuedfraction :param num: Fraction of the number whose continued fractions to be found. Use Fractionstrnumber for more accurate results due to float inaccuracies. :return: The continued fraction of rational number. It is the all commas in the n 1tuple notation. continuedfractionFraction2 2 continuedfractionFraction3.245 3, 4, 12, 4 continuedfractionFraction2.25 2, 4 continuedfraction1Fraction2.25 0, 2, 4 continuedfractionFraction41593 4, 2, 6, 7 continuedfractionFraction0 0 continuedfractionFraction0.75 0, 1, 3 continuedfractionFraction2.25 2.25 3 0.75 3, 1, 3","Completions":"from fractions import Fraction\nfrom math import floor\n\n\ndef continued_fraction(num: Fraction) -> list[int]:\n \"\"\"\n :param num:\n Fraction of the number whose continued fractions to be found.\n Use Fraction(str(number)) for more accurate results due to\n float inaccuracies.\n\n :return:\n The continued fraction of rational number.\n It is the all commas in the (n + 1)-tuple notation.\n\n >>> continued_fraction(Fraction(2))\n [2]\n >>> continued_fraction(Fraction(\"3.245\"))\n [3, 4, 12, 4]\n >>> continued_fraction(Fraction(\"2.25\"))\n [2, 4]\n >>> continued_fraction(1\/Fraction(\"2.25\"))\n [0, 2, 4]\n >>> continued_fraction(Fraction(\"415\/93\"))\n [4, 2, 6, 7]\n >>> continued_fraction(Fraction(0))\n [0]\n >>> continued_fraction(Fraction(0.75))\n [0, 1, 3]\n >>> continued_fraction(Fraction(\"-2.25\")) # -2.25 = -3 + 0.75\n [-3, 1, 3]\n \"\"\"\n numerator, denominator = num.as_integer_ratio()\n continued_fraction_list: list[int] = []\n while True:\n integer_part = floor(numerator \/ denominator)\n continued_fraction_list.append(integer_part)\n numerator -= integer_part * denominator\n if numerator == 0:\n break\n numerator, denominator = denominator, numerator\n\n return continued_fraction_list\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n\n print(\"Continued Fraction of 0.84375 is: \", continued_fraction(Fraction(\"0.84375\")))\n"} +{"Prompt":"Isolate the Decimal part of a Number https:stackoverflow.comquestions3886402howtogetnumbersafterdecimalpoint Isolates the decimal part of a number. If digitAmount 0 round to that decimal place, else print the entire decimal. decimalisolate1.53, 0 0.53 decimalisolate35.345, 1 0.3 decimalisolate35.345, 2 0.34 decimalisolate35.345, 3 0.345 decimalisolate14.789, 3 0.789 decimalisolate0, 2 0 decimalisolate14.123, 1 0.1 decimalisolate14.123, 2 0.12 decimalisolate14.123, 3 0.123","Completions":"def decimal_isolate(number: float, digit_amount: int) -> float:\n \"\"\"\n Isolates the decimal part of a number.\n If digitAmount > 0 round to that decimal place, else print the entire decimal.\n >>> decimal_isolate(1.53, 0)\n 0.53\n >>> decimal_isolate(35.345, 1)\n 0.3\n >>> decimal_isolate(35.345, 2)\n 0.34\n >>> decimal_isolate(35.345, 3)\n 0.345\n >>> decimal_isolate(-14.789, 3)\n -0.789\n >>> decimal_isolate(0, 2)\n 0\n >>> decimal_isolate(-14.123, 1)\n -0.1\n >>> decimal_isolate(-14.123, 2)\n -0.12\n >>> decimal_isolate(-14.123, 3)\n -0.123\n \"\"\"\n if digit_amount > 0:\n return round(number - int(number), digit_amount)\n return number - int(number)\n\n\nif __name__ == \"__main__\":\n print(decimal_isolate(1.53, 0))\n print(decimal_isolate(35.345, 1))\n print(decimal_isolate(35.345, 2))\n print(decimal_isolate(35.345, 3))\n print(decimal_isolate(-14.789, 3))\n print(decimal_isolate(0, 2))\n print(decimal_isolate(-14.123, 1))\n print(decimal_isolate(-14.123, 2))\n print(decimal_isolate(-14.123, 3))\n"} +{"Prompt":"Return a decimal number in its simplest fraction form decimaltofraction2 2, 1 decimaltofraction89. 89, 1 decimaltofraction67 67, 1 decimaltofraction45.0 45, 1 decimaltofraction1.5 3, 2 decimaltofraction6.25 25, 4 decimaltofraction78td Traceback most recent call last: ValueError: Please enter a valid number","Completions":"def decimal_to_fraction(decimal: float | str) -> tuple[int, int]:\n \"\"\"\n Return a decimal number in its simplest fraction form\n >>> decimal_to_fraction(2)\n (2, 1)\n >>> decimal_to_fraction(89.)\n (89, 1)\n >>> decimal_to_fraction(\"67\")\n (67, 1)\n >>> decimal_to_fraction(\"45.0\")\n (45, 1)\n >>> decimal_to_fraction(1.5)\n (3, 2)\n >>> decimal_to_fraction(\"6.25\")\n (25, 4)\n >>> decimal_to_fraction(\"78td\")\n Traceback (most recent call last):\n ValueError: Please enter a valid number\n \"\"\"\n try:\n decimal = float(decimal)\n except ValueError:\n raise ValueError(\"Please enter a valid number\")\n fractional_part = decimal - int(decimal)\n if fractional_part == 0:\n return int(decimal), 1\n else:\n number_of_frac_digits = len(str(decimal).split(\".\")[1])\n numerator = int(decimal * (10**number_of_frac_digits))\n denominator = 10**number_of_frac_digits\n divisor, dividend = denominator, numerator\n while True:\n remainder = dividend % divisor\n if remainder == 0:\n break\n dividend, divisor = divisor, remainder\n numerator, denominator = numerator \/ divisor, denominator \/ divisor\n return int(numerator), int(denominator)\n\n\nif __name__ == \"__main__\":\n print(f\"{decimal_to_fraction(2) = }\")\n print(f\"{decimal_to_fraction(89.0) = }\")\n print(f\"{decimal_to_fraction('67') = }\")\n print(f\"{decimal_to_fraction('45.0') = }\")\n print(f\"{decimal_to_fraction(1.5) = }\")\n print(f\"{decimal_to_fraction('6.25') = }\")\n print(f\"{decimal_to_fraction('78td') = }\")\n"} +{"Prompt":"dodecahedron.py A regular dodecahedron is a threedimensional figure made up of 12 pentagon faces having the same equal size. Calculates the surface area of a regular dodecahedron a 3 25 10 5 1 2 1 2 e2 where: a is the area of the dodecahedron e is the length of the edge referenceDodecahedron Study.com https:study.comacademylessondodecahedronvolumesurfaceareaformulas.html :param edge: length of the edge of the dodecahedron :type edge: float :return: the surface area of the dodecahedron as a float Tests: dodecahedronsurfacearea5 516.1432201766901 dodecahedronsurfacearea10 2064.5728807067603 dodecahedronsurfacearea1 Traceback most recent call last: ... ValueError: Length must be a positive. Calculates the volume of a regular dodecahedron v 15 7 5 1 2 4 e3 where: v is the volume of the dodecahedron e is the length of the edge referenceDodecahedron Study.com https:study.comacademylessondodecahedronvolumesurfaceareaformulas.html :param edge: length of the edge of the dodecahedron :type edge: float :return: the volume of the dodecahedron as a float Tests: dodecahedronvolume5 957.8898700780791 dodecahedronvolume10 7663.118960624633 dodecahedronvolume1 Traceback most recent call last: ... ValueError: Length must be a positive.","Completions":"# dodecahedron.py\n\n\"\"\"\nA regular dodecahedron is a three-dimensional figure made up of\n12 pentagon faces having the same equal size.\n\"\"\"\n\n\ndef dodecahedron_surface_area(edge: float) -> float:\n \"\"\"\n Calculates the surface area of a regular dodecahedron\n a = 3 * ((25 + 10 * (5** (1 \/ 2))) ** (1 \/ 2 )) * (e**2)\n where:\n a --> is the area of the dodecahedron\n e --> is the length of the edge\n reference-->\"Dodecahedron\" Study.com\n \n\n :param edge: length of the edge of the dodecahedron\n :type edge: float\n :return: the surface area of the dodecahedron as a float\n\n\n Tests:\n >>> dodecahedron_surface_area(5)\n 516.1432201766901\n >>> dodecahedron_surface_area(10)\n 2064.5728807067603\n >>> dodecahedron_surface_area(-1)\n Traceback (most recent call last):\n ...\n ValueError: Length must be a positive.\n \"\"\"\n\n if edge <= 0 or not isinstance(edge, int):\n raise ValueError(\"Length must be a positive.\")\n return 3 * ((25 + 10 * (5 ** (1 \/ 2))) ** (1 \/ 2)) * (edge**2)\n\n\ndef dodecahedron_volume(edge: float) -> float:\n \"\"\"\n Calculates the volume of a regular dodecahedron\n v = ((15 + (7 * (5** (1 \/ 2)))) \/ 4) * (e**3)\n where:\n v --> is the volume of the dodecahedron\n e --> is the length of the edge\n reference-->\"Dodecahedron\" Study.com\n \n\n :param edge: length of the edge of the dodecahedron\n :type edge: float\n :return: the volume of the dodecahedron as a float\n\n Tests:\n >>> dodecahedron_volume(5)\n 957.8898700780791\n >>> dodecahedron_volume(10)\n 7663.118960624633\n >>> dodecahedron_volume(-1)\n Traceback (most recent call last):\n ...\n ValueError: Length must be a positive.\n \"\"\"\n\n if edge <= 0 or not isinstance(edge, int):\n raise ValueError(\"Length must be a positive.\")\n return ((15 + (7 * (5 ** (1 \/ 2)))) \/ 4) * (edge**3)\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Compute double factorial using recursive method. Recursion can be costly for large numbers. To learn about the theory behind this algorithm: https:en.wikipedia.orgwikiDoublefactorial from math import prod alldoublefactorialrecursivei prodrangei, 0, 2 for i in range20 True doublefactorialrecursive0.1 Traceback most recent call last: ... ValueError: doublefactorialrecursive only accepts integral values doublefactorialrecursive1 Traceback most recent call last: ... ValueError: doublefactorialrecursive not defined for negative values Compute double factorial using iterative method. To learn about the theory behind this algorithm: https:en.wikipedia.orgwikiDoublefactorial from math import prod alldoublefactorialiterativei prodrangei, 0, 2 for i in range20 True doublefactorialiterative0.1 Traceback most recent call last: ... ValueError: doublefactorialiterative only accepts integral values doublefactorialiterative1 Traceback most recent call last: ... ValueError: doublefactorialiterative not defined for negative values","Completions":"def double_factorial_recursive(n: int) -> int:\n \"\"\"\n Compute double factorial using recursive method.\n Recursion can be costly for large numbers.\n\n To learn about the theory behind this algorithm:\n https:\/\/en.wikipedia.org\/wiki\/Double_factorial\n\n >>> from math import prod\n >>> all(double_factorial_recursive(i) == prod(range(i, 0, -2)) for i in range(20))\n True\n >>> double_factorial_recursive(0.1)\n Traceback (most recent call last):\n ...\n ValueError: double_factorial_recursive() only accepts integral values\n >>> double_factorial_recursive(-1)\n Traceback (most recent call last):\n ...\n ValueError: double_factorial_recursive() not defined for negative values\n \"\"\"\n if not isinstance(n, int):\n raise ValueError(\"double_factorial_recursive() only accepts integral values\")\n if n < 0:\n raise ValueError(\"double_factorial_recursive() not defined for negative values\")\n return 1 if n <= 1 else n * double_factorial_recursive(n - 2)\n\n\ndef double_factorial_iterative(num: int) -> int:\n \"\"\"\n Compute double factorial using iterative method.\n\n To learn about the theory behind this algorithm:\n https:\/\/en.wikipedia.org\/wiki\/Double_factorial\n\n >>> from math import prod\n >>> all(double_factorial_iterative(i) == prod(range(i, 0, -2)) for i in range(20))\n True\n >>> double_factorial_iterative(0.1)\n Traceback (most recent call last):\n ...\n ValueError: double_factorial_iterative() only accepts integral values\n >>> double_factorial_iterative(-1)\n Traceback (most recent call last):\n ...\n ValueError: double_factorial_iterative() not defined for negative values\n \"\"\"\n if not isinstance(num, int):\n raise ValueError(\"double_factorial_iterative() only accepts integral values\")\n if num < 0:\n raise ValueError(\"double_factorial_iterative() not defined for negative values\")\n value = 1\n for i in range(num, 0, -2):\n value *= i\n return value\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"https:en.wikipedia.orgwikiAutomaticdifferentiationAutomaticdifferentiationusingdualnumbers https:blog.jliszka.org20131024exactnumericnthderivatives.html Note this only works for basic functions, fx where the power of x is positive. differentiatelambda x: x2, 2, 2 2 differentiatelambda x: x2 x4, 9, 2 196830 differentiatelambda y: 0.5 y 3 6, 3.5, 4 7605.0 differentiatelambda y: y 2, 4, 3 0 differentiate8, 8, 8 Traceback most recent call last: ... ValueError: differentiate requires a function as input for func differentiatelambda x: x 2, , 1 Traceback most recent call last: ... ValueError: differentiate requires a float as input for position differentiatelambda x: x2, 3, Traceback most recent call last: ... ValueError: differentiate requires an int as input for order","Completions":"from math import factorial\n\n\"\"\"\nhttps:\/\/en.wikipedia.org\/wiki\/Automatic_differentiation#Automatic_differentiation_using_dual_numbers\nhttps:\/\/blog.jliszka.org\/2013\/10\/24\/exact-numeric-nth-derivatives.html\n\nNote this only works for basic functions, f(x) where the power of x is positive.\n\"\"\"\n\n\nclass Dual:\n def __init__(self, real, rank):\n self.real = real\n if isinstance(rank, int):\n self.duals = [1] * rank\n else:\n self.duals = rank\n\n def __repr__(self):\n return (\n f\"{self.real}+\"\n f\"{'+'.join(str(dual)+'E'+str(n+1)for n,dual in enumerate(self.duals))}\"\n )\n\n def reduce(self):\n cur = self.duals.copy()\n while cur[-1] == 0:\n cur.pop(-1)\n return Dual(self.real, cur)\n\n def __add__(self, other):\n if not isinstance(other, Dual):\n return Dual(self.real + other, self.duals)\n s_dual = self.duals.copy()\n o_dual = other.duals.copy()\n if len(s_dual) > len(o_dual):\n o_dual.extend([1] * (len(s_dual) - len(o_dual)))\n elif len(s_dual) < len(o_dual):\n s_dual.extend([1] * (len(o_dual) - len(s_dual)))\n new_duals = []\n for i in range(len(s_dual)):\n new_duals.append(s_dual[i] + o_dual[i])\n return Dual(self.real + other.real, new_duals)\n\n __radd__ = __add__\n\n def __sub__(self, other):\n return self + other * -1\n\n def __mul__(self, other):\n if not isinstance(other, Dual):\n new_duals = []\n for i in self.duals:\n new_duals.append(i * other)\n return Dual(self.real * other, new_duals)\n new_duals = [0] * (len(self.duals) + len(other.duals) + 1)\n for i, item in enumerate(self.duals):\n for j, jtem in enumerate(other.duals):\n new_duals[i + j + 1] += item * jtem\n for k in range(len(self.duals)):\n new_duals[k] += self.duals[k] * other.real\n for index in range(len(other.duals)):\n new_duals[index] += other.duals[index] * self.real\n return Dual(self.real * other.real, new_duals)\n\n __rmul__ = __mul__\n\n def __truediv__(self, other):\n if not isinstance(other, Dual):\n new_duals = []\n for i in self.duals:\n new_duals.append(i \/ other)\n return Dual(self.real \/ other, new_duals)\n raise ValueError\n\n def __floordiv__(self, other):\n if not isinstance(other, Dual):\n new_duals = []\n for i in self.duals:\n new_duals.append(i \/\/ other)\n return Dual(self.real \/\/ other, new_duals)\n raise ValueError\n\n def __pow__(self, n):\n if n < 0 or isinstance(n, float):\n raise ValueError(\"power must be a positive integer\")\n if n == 0:\n return 1\n if n == 1:\n return self\n x = self\n for _ in range(n - 1):\n x *= self\n return x\n\n\ndef differentiate(func, position, order):\n \"\"\"\n >>> differentiate(lambda x: x**2, 2, 2)\n 2\n >>> differentiate(lambda x: x**2 * x**4, 9, 2)\n 196830\n >>> differentiate(lambda y: 0.5 * (y + 3) ** 6, 3.5, 4)\n 7605.0\n >>> differentiate(lambda y: y ** 2, 4, 3)\n 0\n >>> differentiate(8, 8, 8)\n Traceback (most recent call last):\n ...\n ValueError: differentiate() requires a function as input for func\n >>> differentiate(lambda x: x **2, \"\", 1)\n Traceback (most recent call last):\n ...\n ValueError: differentiate() requires a float as input for position\n >>> differentiate(lambda x: x**2, 3, \"\")\n Traceback (most recent call last):\n ...\n ValueError: differentiate() requires an int as input for order\n \"\"\"\n if not callable(func):\n raise ValueError(\"differentiate() requires a function as input for func\")\n if not isinstance(position, (float, int)):\n raise ValueError(\"differentiate() requires a float as input for position\")\n if not isinstance(order, int):\n raise ValueError(\"differentiate() requires an int as input for order\")\n d = Dual(position, 1)\n result = func(d)\n if order == 0:\n return result.real\n return result.duals[order - 1] * factorial(order)\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n\n def f(y):\n return y**2 * y**4\n\n print(differentiate(f, 9, 2))\n"} +{"Prompt":"!usrbinenv python3 Implementation of entropy of information https:en.wikipedia.orgwikiEntropyinformationtheory This method takes path and two dict as argument and than calculates entropy of them. :param dict: :param dict: :return: Prints 1 Entropy of information based on 1 alphabet 2 Entropy of information based on couples of 2 alphabet 3 print Entropy of HX nXn1 Text from random books. Also, random quotes. text Behind Winstons back the voice ... from the telescreen was still ... babbling and the overfulfilment calculateprobtext 4.0 6.0 2.0 text The Ministry of TruthMinitrue, in Newspeak Newspeak was the official ... face in elegant lettering, the three calculateprobtext 4.0 5.0 1.0 text Had repulsive dashwoods suspicion sincerity but advantage now him. ... Remark easily garret nor nay. Civil those mrs enjoy shy fat merry. ... You greatest jointure saw horrible. He private he on be imagine ... suppose. Fertile beloved evident through no service elderly is. Blind ... there if every no so at. Own neglected you preferred way sincerity ... delivered his attempted. To of message cottage windows do besides ... against uncivil. Delightful unreserved impossible few estimating ... men favourable see entreaties. She propriety immediate was improving. ... He or entrance humoured likewise moderate. Much nor game son say ... feel. Fat make met can must form into gate. Me we offending prevailed ... discovery. calculateprobtext 4.0 7.0 3.0 what is our total sum of probabilities. one length string for each alpha we go in our dict and if it is in it we calculate entropy print entropy two len string for each alpha two in size calculate entropy. print second entropy print the difference between them Convert text input into two dicts of counts. The first dictionary stores the frequency of single character strings. The second dictionary stores the frequency of two character strings. first case when we have space at start. text Had repulsive dashwoods suspicion sincerity but advantage now him. Remark easily garret nor nay. Civil those mrs enjoy shy fat merry. You greatest jointure saw horrible. He private he on be imagine suppose. Fertile beloved evident through no service elderly is. Blind there if every no so at. Own neglected you preferred way sincerity delivered his attempted. To of message cottage windows do besides against uncivil. Delightful unreserved impossible few estimating men favourable see entreaties. She propriety immediate was improving. He or entrance humoured likewise moderate. Much nor game son say feel. Fat make met can must form into gate. Me we offending prevailed discovery. calculateprobtext","Completions":"#!\/usr\/bin\/env python3\n\n\"\"\"\nImplementation of entropy of information\nhttps:\/\/en.wikipedia.org\/wiki\/Entropy_(information_theory)\n\"\"\"\nfrom __future__ import annotations\n\nimport math\nfrom collections import Counter\nfrom string import ascii_lowercase\n\n\ndef calculate_prob(text: str) -> None:\n \"\"\"\n This method takes path and two dict as argument\n and than calculates entropy of them.\n :param dict:\n :param dict:\n :return: Prints\n 1) Entropy of information based on 1 alphabet\n 2) Entropy of information based on couples of 2 alphabet\n 3) print Entropy of H(X n\u2223Xn\u22121)\n\n Text from random books. Also, random quotes.\n >>> text = (\"Behind Winston\u2019s back the voice \"\n ... \"from the telescreen was still \"\n ... \"babbling and the overfulfilment\")\n >>> calculate_prob(text)\n 4.0\n 6.0\n 2.0\n\n >>> text = (\"The Ministry of Truth\u2014Minitrue, in Newspeak [Newspeak was the official\"\n ... \"face in elegant lettering, the three\")\n >>> calculate_prob(text)\n 4.0\n 5.0\n 1.0\n >>> text = (\"Had repulsive dashwoods suspicion sincerity but advantage now him. \"\n ... \"Remark easily garret nor nay. Civil those mrs enjoy shy fat merry. \"\n ... \"You greatest jointure saw horrible. He private he on be imagine \"\n ... \"suppose. Fertile beloved evident through no service elderly is. Blind \"\n ... \"there if every no so at. Own neglected you preferred way sincerity \"\n ... \"delivered his attempted. To of message cottage windows do besides \"\n ... \"against uncivil. Delightful unreserved impossible few estimating \"\n ... \"men favourable see entreaties. She propriety immediate was improving. \"\n ... \"He or entrance humoured likewise moderate. Much nor game son say \"\n ... \"feel. Fat make met can must form into gate. Me we offending prevailed \"\n ... \"discovery.\")\n >>> calculate_prob(text)\n 4.0\n 7.0\n 3.0\n \"\"\"\n single_char_strings, two_char_strings = analyze_text(text)\n my_alphas = list(\" \" + ascii_lowercase)\n # what is our total sum of probabilities.\n all_sum = sum(single_char_strings.values())\n\n # one length string\n my_fir_sum = 0\n # for each alpha we go in our dict and if it is in it we calculate entropy\n for ch in my_alphas:\n if ch in single_char_strings:\n my_str = single_char_strings[ch]\n prob = my_str \/ all_sum\n my_fir_sum += prob * math.log2(prob) # entropy formula.\n\n # print entropy\n print(f\"{round(-1 * my_fir_sum):.1f}\")\n\n # two len string\n all_sum = sum(two_char_strings.values())\n my_sec_sum = 0\n # for each alpha (two in size) calculate entropy.\n for ch0 in my_alphas:\n for ch1 in my_alphas:\n sequence = ch0 + ch1\n if sequence in two_char_strings:\n my_str = two_char_strings[sequence]\n prob = int(my_str) \/ all_sum\n my_sec_sum += prob * math.log2(prob)\n\n # print second entropy\n print(f\"{round(-1 * my_sec_sum):.1f}\")\n\n # print the difference between them\n print(f\"{round((-1 * my_sec_sum) - (-1 * my_fir_sum)):.1f}\")\n\n\ndef analyze_text(text: str) -> tuple[dict, dict]:\n \"\"\"\n Convert text input into two dicts of counts.\n The first dictionary stores the frequency of single character strings.\n The second dictionary stores the frequency of two character strings.\n \"\"\"\n single_char_strings = Counter() # type: ignore\n two_char_strings = Counter() # type: ignore\n single_char_strings[text[-1]] += 1\n\n # first case when we have space at start.\n two_char_strings[\" \" + text[0]] += 1\n for i in range(len(text) - 1):\n single_char_strings[text[i]] += 1\n two_char_strings[text[i : i + 2]] += 1\n return single_char_strings, two_char_strings\n\n\ndef main():\n import doctest\n\n doctest.testmod()\n # text = (\n # \"Had repulsive dashwoods suspicion sincerity but advantage now him. Remark \"\n # \"easily garret nor nay. Civil those mrs enjoy shy fat merry. You greatest \"\n # \"jointure saw horrible. He private he on be imagine suppose. Fertile \"\n # \"beloved evident through no service elderly is. Blind there if every no so \"\n # \"at. Own neglected you preferred way sincerity delivered his attempted. To \"\n # \"of message cottage windows do besides against uncivil. Delightful \"\n # \"unreserved impossible few estimating men favourable see entreaties. She \"\n # \"propriety immediate was improving. He or entrance humoured likewise \"\n # \"moderate. Much nor game son say feel. Fat make met can must form into \"\n # \"gate. Me we offending prevailed discovery. \"\n # )\n\n # calculate_prob(text)\n\n\nif __name__ == \"__main__\":\n main()\n"} +{"Prompt":"Calculate the distance between the two endpoints of two vectors. A vector is defined as a list, tuple, or numpy 1D array. euclideandistance0, 0, 2, 2 2.8284271247461903 euclideandistancenp.array0, 0, 0, np.array2, 2, 2 3.4641016151377544 euclideandistancenp.array1, 2, 3, 4, np.array5, 6, 7, 8 8.0 euclideandistance1, 2, 3, 4, 5, 6, 7, 8 8.0 Calculate the distance between the two endpoints of two vectors without numpy. A vector is defined as a list, tuple, or numpy 1D array. euclideandistancenonp0, 0, 2, 2 2.8284271247461903 euclideandistancenonp1, 2, 3, 4, 5, 6, 7, 8 8.0 Benchmarks","Completions":"from __future__ import annotations\n\nimport typing\nfrom collections.abc import Iterable\n\nimport numpy as np\n\nVector = typing.Union[Iterable[float], Iterable[int], np.ndarray] # noqa: UP007\nVectorOut = typing.Union[np.float64, int, float] # noqa: UP007\n\n\ndef euclidean_distance(vector_1: Vector, vector_2: Vector) -> VectorOut:\n \"\"\"\n Calculate the distance between the two endpoints of two vectors.\n A vector is defined as a list, tuple, or numpy 1D array.\n >>> euclidean_distance((0, 0), (2, 2))\n 2.8284271247461903\n >>> euclidean_distance(np.array([0, 0, 0]), np.array([2, 2, 2]))\n 3.4641016151377544\n >>> euclidean_distance(np.array([1, 2, 3, 4]), np.array([5, 6, 7, 8]))\n 8.0\n >>> euclidean_distance([1, 2, 3, 4], [5, 6, 7, 8])\n 8.0\n \"\"\"\n return np.sqrt(np.sum((np.asarray(vector_1) - np.asarray(vector_2)) ** 2))\n\n\ndef euclidean_distance_no_np(vector_1: Vector, vector_2: Vector) -> VectorOut:\n \"\"\"\n Calculate the distance between the two endpoints of two vectors without numpy.\n A vector is defined as a list, tuple, or numpy 1D array.\n >>> euclidean_distance_no_np((0, 0), (2, 2))\n 2.8284271247461903\n >>> euclidean_distance_no_np([1, 2, 3, 4], [5, 6, 7, 8])\n 8.0\n \"\"\"\n return sum((v1 - v2) ** 2 for v1, v2 in zip(vector_1, vector_2)) ** (1 \/ 2)\n\n\nif __name__ == \"__main__\":\n\n def benchmark() -> None:\n \"\"\"\n Benchmarks\n \"\"\"\n from timeit import timeit\n\n print(\"Without Numpy\")\n print(\n timeit(\n \"euclidean_distance_no_np([1, 2, 3], [4, 5, 6])\",\n number=10000,\n globals=globals(),\n )\n )\n print(\"With Numpy\")\n print(\n timeit(\n \"euclidean_distance([1, 2, 3], [4, 5, 6])\",\n number=10000,\n globals=globals(),\n )\n )\n\n benchmark()\n"} +{"Prompt":"Calculate numeric solution at each step to an ODE using Euler's Method For reference to Euler's method refer to https:en.wikipedia.orgwikiEulermethod. Args: odefunc Callable: The ordinary differential equation as a function of x and y. y0 float: The initial value for y. x0 float: The initial value for x. stepsize float: The increment value for x. xend float: The final value of x to be calculated. Returns: np.ndarray: Solution of y for every step in x. the exact solution is math.expx def fx, y: ... return y y0 1 y expliciteulerf, y0, 0.0, 0.01, 5 y1 144.77277243257308","Completions":"from collections.abc import Callable\n\nimport numpy as np\n\n\ndef explicit_euler(\n ode_func: Callable, y0: float, x0: float, step_size: float, x_end: float\n) -> np.ndarray:\n \"\"\"Calculate numeric solution at each step to an ODE using Euler's Method\n\n For reference to Euler's method refer to https:\/\/en.wikipedia.org\/wiki\/Euler_method.\n\n Args:\n ode_func (Callable): The ordinary differential equation\n as a function of x and y.\n y0 (float): The initial value for y.\n x0 (float): The initial value for x.\n step_size (float): The increment value for x.\n x_end (float): The final value of x to be calculated.\n\n Returns:\n np.ndarray: Solution of y for every step in x.\n\n >>> # the exact solution is math.exp(x)\n >>> def f(x, y):\n ... return y\n >>> y0 = 1\n >>> y = explicit_euler(f, y0, 0.0, 0.01, 5)\n >>> y[-1]\n 144.77277243257308\n \"\"\"\n n = int(np.ceil((x_end - x0) \/ step_size))\n y = np.zeros((n + 1,))\n y[0] = y0\n x = x0\n\n for k in range(n):\n y[k + 1] = y[k] + step_size * ode_func(x, y[k])\n x += step_size\n\n return y\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Calculate solution at each step to an ODE using Euler's Modified Method The Euler Method is straightforward to implement, but can't give accurate solutions. So, some changes were proposed to improve accuracy. https:en.wikipedia.orgwikiEulermethod Arguments: odefunc The ode as a function of x and y y0 the initial value for y x0 the initial value for x stepsize the increment value for x xend the end value for x the exact solution is math.expx def f1x, y: ... return 2xy2 y eulermodifiedf1, 1.0, 0.0, 0.2, 1.0 y1 0.503338255442106 import math def f2x, y: ... return 2y x3math.exp2x y eulermodifiedf2, 1.0, 0.0, 0.1, 0.3 y1 0.5525976431951775","Completions":"from collections.abc import Callable\n\nimport numpy as np\n\n\ndef euler_modified(\n ode_func: Callable, y0: float, x0: float, step_size: float, x_end: float\n) -> np.ndarray:\n \"\"\"\n Calculate solution at each step to an ODE using Euler's Modified Method\n The Euler Method is straightforward to implement, but can't give accurate solutions.\n So, some changes were proposed to improve accuracy.\n\n https:\/\/en.wikipedia.org\/wiki\/Euler_method\n\n Arguments:\n ode_func -- The ode as a function of x and y\n y0 -- the initial value for y\n x0 -- the initial value for x\n stepsize -- the increment value for x\n x_end -- the end value for x\n\n >>> # the exact solution is math.exp(x)\n >>> def f1(x, y):\n ... return -2*x*(y**2)\n >>> y = euler_modified(f1, 1.0, 0.0, 0.2, 1.0)\n >>> y[-1]\n 0.503338255442106\n >>> import math\n >>> def f2(x, y):\n ... return -2*y + (x**3)*math.exp(-2*x)\n >>> y = euler_modified(f2, 1.0, 0.0, 0.1, 0.3)\n >>> y[-1]\n 0.5525976431951775\n \"\"\"\n n = int(np.ceil((x_end - x0) \/ step_size))\n y = np.zeros((n + 1,))\n y[0] = y0\n x = x0\n\n for k in range(n):\n y_get = y[k] + step_size * ode_func(x, y[k])\n y[k + 1] = y[k] + (\n (step_size \/ 2) * (ode_func(x, y[k]) + ode_func(x + step_size, y_get))\n )\n x += step_size\n\n return y\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Eulers Totient function finds the number of relative primes of a number n from 1 to n n 10 totientcalculation totientn for i in range1, n: ... printfi has totientcalculationi relative primes. 1 has 0 relative primes. 2 has 1 relative primes. 3 has 2 relative primes. 4 has 2 relative primes. 5 has 4 relative primes. 6 has 2 relative primes. 7 has 6 relative primes. 8 has 4 relative primes. 9 has 6 relative primes.","Completions":"# Eulers Totient function finds the number of relative primes of a number n from 1 to n\ndef totient(n: int) -> list:\n \"\"\"\n >>> n = 10\n >>> totient_calculation = totient(n)\n >>> for i in range(1, n):\n ... print(f\"{i} has {totient_calculation[i]} relative primes.\")\n 1 has 0 relative primes.\n 2 has 1 relative primes.\n 3 has 2 relative primes.\n 4 has 2 relative primes.\n 5 has 4 relative primes.\n 6 has 2 relative primes.\n 7 has 6 relative primes.\n 8 has 4 relative primes.\n 9 has 6 relative primes.\n \"\"\"\n is_prime = [True for i in range(n + 1)]\n totients = [i - 1 for i in range(n + 1)]\n primes = []\n for i in range(2, n + 1):\n if is_prime[i]:\n primes.append(i)\n for j in range(len(primes)):\n if i * primes[j] >= n:\n break\n is_prime[i * primes[j]] = False\n\n if i % primes[j] == 0:\n totients[i * primes[j]] = totients[i] * primes[j]\n break\n\n totients[i * primes[j]] = totients[i] * (primes[j] - 1)\n\n return totients\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Extended Euclidean Algorithm. Finds 2 numbers a and b such that it satisfies the equation am bn gcdm, n a.k.a Bezout's Identity https:en.wikipedia.orgwikiExtendedEuclideanalgorithm Author: S. Sharma silentcat Date: 20190225T12:08:5306:00 Email: silentcatprotonmail.com Last modified by: pikulet Last modified time: 20201002 Extended Euclidean Algorithm. Finds 2 numbers a and b such that it satisfies the equation am bn gcdm, n a.k.a Bezout's Identity extendedeuclideanalgorithm1, 24 1, 0 extendedeuclideanalgorithm8, 14 2, 1 extendedeuclideanalgorithm240, 46 9, 47 extendedeuclideanalgorithm1, 4 1, 0 extendedeuclideanalgorithm2, 4 1, 0 extendedeuclideanalgorithm0, 4 0, 1 extendedeuclideanalgorithm2, 0 1, 0 base cases sign correction for negative numbers Call Extended Euclidean Algorithm. if lensys.argv 3: print2 integer arguments required return 1 a intsys.argv1 b intsys.argv2 printextendedeuclideanalgorithma, b return 0 if name main: raise SystemExitmain","Completions":"# @Author: S. Sharma \n# @Date: 2019-02-25T12:08:53-06:00\n# @Email: silentcat@protonmail.com\n# @Last modified by: pikulet\n# @Last modified time: 2020-10-02\nfrom __future__ import annotations\n\nimport sys\n\n\ndef extended_euclidean_algorithm(a: int, b: int) -> tuple[int, int]:\n \"\"\"\n Extended Euclidean Algorithm.\n\n Finds 2 numbers a and b such that it satisfies\n the equation am + bn = gcd(m, n) (a.k.a Bezout's Identity)\n\n >>> extended_euclidean_algorithm(1, 24)\n (1, 0)\n\n >>> extended_euclidean_algorithm(8, 14)\n (2, -1)\n\n >>> extended_euclidean_algorithm(240, 46)\n (-9, 47)\n\n >>> extended_euclidean_algorithm(1, -4)\n (1, 0)\n\n >>> extended_euclidean_algorithm(-2, -4)\n (-1, 0)\n\n >>> extended_euclidean_algorithm(0, -4)\n (0, -1)\n\n >>> extended_euclidean_algorithm(2, 0)\n (1, 0)\n\n \"\"\"\n # base cases\n if abs(a) == 1:\n return a, 0\n elif abs(b) == 1:\n return 0, b\n\n old_remainder, remainder = a, b\n old_coeff_a, coeff_a = 1, 0\n old_coeff_b, coeff_b = 0, 1\n\n while remainder != 0:\n quotient = old_remainder \/\/ remainder\n old_remainder, remainder = remainder, old_remainder - quotient * remainder\n old_coeff_a, coeff_a = coeff_a, old_coeff_a - quotient * coeff_a\n old_coeff_b, coeff_b = coeff_b, old_coeff_b - quotient * coeff_b\n\n # sign correction for negative numbers\n if a < 0:\n old_coeff_a = -old_coeff_a\n if b < 0:\n old_coeff_b = -old_coeff_b\n\n return old_coeff_a, old_coeff_b\n\n\ndef main():\n \"\"\"Call Extended Euclidean Algorithm.\"\"\"\n if len(sys.argv) < 3:\n print(\"2 integer arguments required\")\n return 1\n a = int(sys.argv[1])\n b = int(sys.argv[2])\n print(extended_euclidean_algorithm(a, b))\n return 0\n\n\nif __name__ == \"__main__\":\n raise SystemExit(main())\n"} +{"Prompt":"Factorial of a positive integer https:en.wikipedia.orgwikiFactorial Calculate the factorial of specified number n!. import math allfactoriali math.factoriali for i in range20 True factorial0.1 Traceback most recent call last: ... ValueError: factorial only accepts integral values factorial1 Traceback most recent call last: ... ValueError: factorial not defined for negative values factorial1 1 factorial6 720 factorial0 1 Calculate the factorial of a positive integer https:en.wikipedia.orgwikiFactorial import math allfactoriali math.factoriali for i in range20 True factorial0.1 Traceback most recent call last: ... ValueError: factorial only accepts integral values factorial1 Traceback most recent call last: ... ValueError: factorial not defined for negative values","Completions":"def factorial(number: int) -> int:\n \"\"\"\n Calculate the factorial of specified number (n!).\n\n >>> import math\n >>> all(factorial(i) == math.factorial(i) for i in range(20))\n True\n >>> factorial(0.1)\n Traceback (most recent call last):\n ...\n ValueError: factorial() only accepts integral values\n >>> factorial(-1)\n Traceback (most recent call last):\n ...\n ValueError: factorial() not defined for negative values\n >>> factorial(1)\n 1\n >>> factorial(6)\n 720\n >>> factorial(0)\n 1\n \"\"\"\n if number != int(number):\n raise ValueError(\"factorial() only accepts integral values\")\n if number < 0:\n raise ValueError(\"factorial() not defined for negative values\")\n value = 1\n for i in range(1, number + 1):\n value *= i\n return value\n\n\ndef factorial_recursive(n: int) -> int:\n \"\"\"\n Calculate the factorial of a positive integer\n https:\/\/en.wikipedia.org\/wiki\/Factorial\n\n >>> import math\n >>> all(factorial(i) == math.factorial(i) for i in range(20))\n True\n >>> factorial(0.1)\n Traceback (most recent call last):\n ...\n ValueError: factorial() only accepts integral values\n >>> factorial(-1)\n Traceback (most recent call last):\n ...\n ValueError: factorial() not defined for negative values\n \"\"\"\n if not isinstance(n, int):\n raise ValueError(\"factorial() only accepts integral values\")\n if n < 0:\n raise ValueError(\"factorial() not defined for negative values\")\n return 1 if n in {0, 1} else n * factorial(n - 1)\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n\n n = int(input(\"Enter a positive integer: \").strip() or 0)\n print(f\"factorial{n} is {factorial(n)}\")\n"} +{"Prompt":"factorsofanumber1 1 factorsofanumber5 1, 5 factorsofanumber24 1, 2, 3, 4, 6, 8, 12, 24 factorsofanumber24","Completions":"from doctest import testmod\nfrom math import sqrt\n\n\ndef factors_of_a_number(num: int) -> list:\n \"\"\"\n >>> factors_of_a_number(1)\n [1]\n >>> factors_of_a_number(5)\n [1, 5]\n >>> factors_of_a_number(24)\n [1, 2, 3, 4, 6, 8, 12, 24]\n >>> factors_of_a_number(-24)\n []\n \"\"\"\n facs: list[int] = []\n if num < 1:\n return facs\n facs.append(1)\n if num == 1:\n return facs\n facs.append(num)\n for i in range(2, int(sqrt(num)) + 1):\n if num % i == 0: # If i is a factor of num\n facs.append(i)\n d = num \/\/ i # num\/\/i is the other factor of num\n if d != i: # If d and i are distinct\n facs.append(d) # we have found another factor\n facs.sort()\n return facs\n\n\nif __name__ == \"__main__\":\n testmod(name=\"factors_of_a_number\", verbose=True)\n"} +{"Prompt":"Fast inverse square root 1sqrtx using the Quake III algorithm. Reference: https:en.wikipedia.orgwikiFastinversesquareroot Accuracy: https:en.wikipedia.orgwikiFastinversesquarerootAccuracy Compute the fast inverse square root of a floatingpoint number using the famous Quake III algorithm. :param float number: Input number for which to calculate the inverse square root. :return float: The fast inverse square root of the input number. Example: fastinversesqrt10 0.3156857923527257 fastinversesqrt4 0.49915357479239103 fastinversesqrt4.1 0.4932849504615651 fastinversesqrt0 Traceback most recent call last: ... ValueError: Input must be a positive number. fastinversesqrt1 Traceback most recent call last: ... ValueError: Input must be a positive number. from math import isclose, sqrt allisclosefastinversesqrti, 1 sqrti, reltol0.00132 ... for i in range50, 60 True https:en.wikipedia.orgwikiFastinversesquarerootAccuracy","Completions":"import struct\n\n\ndef fast_inverse_sqrt(number: float) -> float:\n \"\"\"\n Compute the fast inverse square root of a floating-point number using the famous\n Quake III algorithm.\n\n :param float number: Input number for which to calculate the inverse square root.\n :return float: The fast inverse square root of the input number.\n\n Example:\n >>> fast_inverse_sqrt(10)\n 0.3156857923527257\n >>> fast_inverse_sqrt(4)\n 0.49915357479239103\n >>> fast_inverse_sqrt(4.1)\n 0.4932849504615651\n >>> fast_inverse_sqrt(0)\n Traceback (most recent call last):\n ...\n ValueError: Input must be a positive number.\n >>> fast_inverse_sqrt(-1)\n Traceback (most recent call last):\n ...\n ValueError: Input must be a positive number.\n >>> from math import isclose, sqrt\n >>> all(isclose(fast_inverse_sqrt(i), 1 \/ sqrt(i), rel_tol=0.00132)\n ... for i in range(50, 60))\n True\n \"\"\"\n if number <= 0:\n raise ValueError(\"Input must be a positive number.\")\n i = struct.unpack(\">i\", struct.pack(\">f\", number))[0]\n i = 0x5F3759DF - (i >> 1)\n y = struct.unpack(\">f\", struct.pack(\">i\", i))[0]\n return y * (1.5 - 0.5 * number * y * y)\n\n\nif __name__ == \"__main__\":\n from doctest import testmod\n\n testmod()\n # https:\/\/en.wikipedia.org\/wiki\/Fast_inverse_square_root#Accuracy\n from math import sqrt\n\n for i in range(5, 101, 5):\n print(f\"{i:>3}: {(1 \/ sqrt(i)) - fast_inverse_sqrt(i):.5f}\")\n"} +{"Prompt":"Python program to show the usage of Fermat's little theorem in a division According to Fermat's little theorem, a b mod p always equals a b p 2 mod p Here we assume that p is a prime number, b divides a, and p doesn't divide b Wikipedia reference: https:en.wikipedia.orgwikiFermat27slittletheorem a prime number using binary exponentiation function, Ologp: using Python operators:","Completions":"# Python program to show the usage of Fermat's little theorem in a division\n# According to Fermat's little theorem, (a \/ b) mod p always equals\n# a * (b ^ (p - 2)) mod p\n# Here we assume that p is a prime number, b divides a, and p doesn't divide b\n# Wikipedia reference: https:\/\/en.wikipedia.org\/wiki\/Fermat%27s_little_theorem\n\n\ndef binary_exponentiation(a: int, n: float, mod: int) -> int:\n if n == 0:\n return 1\n\n elif n % 2 == 1:\n return (binary_exponentiation(a, n - 1, mod) * a) % mod\n\n else:\n b = binary_exponentiation(a, n \/ 2, mod)\n return (b * b) % mod\n\n\n# a prime number\np = 701\n\na = 1000000000\nb = 10\n\n# using binary exponentiation function, O(log(p)):\nprint((a \/ b) % p == (a * binary_exponentiation(b, p - 2, p)) % p)\n\n# using Python operators:\nprint((a \/ b) % p == (a * b ** (p - 2)) % p)\n"} +{"Prompt":"Calculates the Fibonacci sequence using iteration, recursion, memoization, and a simplified form of Binet's formula NOTE 1: the iterative, recursive, memoization functions are more accurate than the Binet's formula function because the Binet formula function uses floats NOTE 2: the Binet's formula function is much more limited in the size of inputs that it can handle due to the size limitations of Python floats See benchmark numbers in main for performance comparisons https:en.wikipedia.orgwikiFibonaccinumber for more information Times the execution of a function with parameters Calculates the first n 1indexed Fibonacci numbers using iteration with yield listfibiterativeyield0 0 tuplefibiterativeyield1 0, 1 tuplefibiterativeyield5 0, 1, 1, 2, 3, 5 tuplefibiterativeyield10 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55 tuplefibiterativeyield1 Traceback most recent call last: ... ValueError: n is negative Calculates the first n 0indexed Fibonacci numbers using iteration fibiterative0 0 fibiterative1 0, 1 fibiterative5 0, 1, 1, 2, 3, 5 fibiterative10 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55 fibiterative1 Traceback most recent call last: ... ValueError: n is negative Calculates the first n 0indexed Fibonacci numbers using recursion fibiterative0 0 fibiterative1 0, 1 fibiterative5 0, 1, 1, 2, 3, 5 fibiterative10 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55 fibiterative1 Traceback most recent call last: ... ValueError: n is negative Calculates the ith 0indexed Fibonacci number using recursion fibrecursiveterm0 0 fibrecursiveterm1 1 fibrecursiveterm5 5 fibrecursiveterm10 55 fibrecursiveterm1 Traceback most recent call last: ... Exception: n is negative Calculates the first n 0indexed Fibonacci numbers using recursion fibiterative0 0 fibiterative1 0, 1 fibiterative5 0, 1, 1, 2, 3, 5 fibiterative10 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55 fibiterative1 Traceback most recent call last: ... ValueError: n is negative Calculates the ith 0indexed Fibonacci number using recursion Calculates the first n 0indexed Fibonacci numbers using memoization fibmemoization0 0 fibmemoization1 0, 1 fibmemoization5 0, 1, 1, 2, 3, 5 fibmemoization10 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55 fibiterative1 Traceback most recent call last: ... ValueError: n is negative Cache must be outside recursuive function other it will reset every time it calls itself. Calculates the first n 0indexed Fibonacci numbers using a simplified form of Binet's formula: https:en.m.wikipedia.orgwikiFibonaccinumberComputationbyrounding NOTE 1: this function diverges from fibiterative at around n 71, likely due to compounding floatingpoint arithmetic errors NOTE 2: this function doesn't accept n 1475 because it overflows thereafter due to the size limitations of Python floats fibbinet0 0 fibbinet1 0, 1 fibbinet5 0, 1, 1, 2, 3, 5 fibbinet10 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55 fibbinet1 Traceback most recent call last: ... ValueError: n is negative fibbinet1475 Traceback most recent call last: ... ValueError: n is too large Time on an M1 MacBook Pro Fastest to slowest","Completions":"import functools\nfrom collections.abc import Iterator\nfrom math import sqrt\nfrom time import time\n\n\ndef time_func(func, *args, **kwargs):\n \"\"\"\n Times the execution of a function with parameters\n \"\"\"\n start = time()\n output = func(*args, **kwargs)\n end = time()\n if int(end - start) > 0:\n print(f\"{func.__name__} runtime: {(end - start):0.4f} s\")\n else:\n print(f\"{func.__name__} runtime: {(end - start) * 1000:0.4f} ms\")\n return output\n\n\ndef fib_iterative_yield(n: int) -> Iterator[int]:\n \"\"\"\n Calculates the first n (1-indexed) Fibonacci numbers using iteration with yield\n >>> list(fib_iterative_yield(0))\n [0]\n >>> tuple(fib_iterative_yield(1))\n (0, 1)\n >>> tuple(fib_iterative_yield(5))\n (0, 1, 1, 2, 3, 5)\n >>> tuple(fib_iterative_yield(10))\n (0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55)\n >>> tuple(fib_iterative_yield(-1))\n Traceback (most recent call last):\n ...\n ValueError: n is negative\n \"\"\"\n if n < 0:\n raise ValueError(\"n is negative\")\n a, b = 0, 1\n yield a\n for _ in range(n):\n yield b\n a, b = b, a + b\n\n\ndef fib_iterative(n: int) -> list[int]:\n \"\"\"\n Calculates the first n (0-indexed) Fibonacci numbers using iteration\n >>> fib_iterative(0)\n [0]\n >>> fib_iterative(1)\n [0, 1]\n >>> fib_iterative(5)\n [0, 1, 1, 2, 3, 5]\n >>> fib_iterative(10)\n [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]\n >>> fib_iterative(-1)\n Traceback (most recent call last):\n ...\n ValueError: n is negative\n \"\"\"\n if n < 0:\n raise ValueError(\"n is negative\")\n if n == 0:\n return [0]\n fib = [0, 1]\n for _ in range(n - 1):\n fib.append(fib[-1] + fib[-2])\n return fib\n\n\ndef fib_recursive(n: int) -> list[int]:\n \"\"\"\n Calculates the first n (0-indexed) Fibonacci numbers using recursion\n >>> fib_iterative(0)\n [0]\n >>> fib_iterative(1)\n [0, 1]\n >>> fib_iterative(5)\n [0, 1, 1, 2, 3, 5]\n >>> fib_iterative(10)\n [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]\n >>> fib_iterative(-1)\n Traceback (most recent call last):\n ...\n ValueError: n is negative\n \"\"\"\n\n def fib_recursive_term(i: int) -> int:\n \"\"\"\n Calculates the i-th (0-indexed) Fibonacci number using recursion\n >>> fib_recursive_term(0)\n 0\n >>> fib_recursive_term(1)\n 1\n >>> fib_recursive_term(5)\n 5\n >>> fib_recursive_term(10)\n 55\n >>> fib_recursive_term(-1)\n Traceback (most recent call last):\n ...\n Exception: n is negative\n \"\"\"\n if i < 0:\n raise ValueError(\"n is negative\")\n if i < 2:\n return i\n return fib_recursive_term(i - 1) + fib_recursive_term(i - 2)\n\n if n < 0:\n raise ValueError(\"n is negative\")\n return [fib_recursive_term(i) for i in range(n + 1)]\n\n\ndef fib_recursive_cached(n: int) -> list[int]:\n \"\"\"\n Calculates the first n (0-indexed) Fibonacci numbers using recursion\n >>> fib_iterative(0)\n [0]\n >>> fib_iterative(1)\n [0, 1]\n >>> fib_iterative(5)\n [0, 1, 1, 2, 3, 5]\n >>> fib_iterative(10)\n [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]\n >>> fib_iterative(-1)\n Traceback (most recent call last):\n ...\n ValueError: n is negative\n \"\"\"\n\n @functools.cache\n def fib_recursive_term(i: int) -> int:\n \"\"\"\n Calculates the i-th (0-indexed) Fibonacci number using recursion\n \"\"\"\n if i < 0:\n raise ValueError(\"n is negative\")\n if i < 2:\n return i\n return fib_recursive_term(i - 1) + fib_recursive_term(i - 2)\n\n if n < 0:\n raise ValueError(\"n is negative\")\n return [fib_recursive_term(i) for i in range(n + 1)]\n\n\ndef fib_memoization(n: int) -> list[int]:\n \"\"\"\n Calculates the first n (0-indexed) Fibonacci numbers using memoization\n >>> fib_memoization(0)\n [0]\n >>> fib_memoization(1)\n [0, 1]\n >>> fib_memoization(5)\n [0, 1, 1, 2, 3, 5]\n >>> fib_memoization(10)\n [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]\n >>> fib_iterative(-1)\n Traceback (most recent call last):\n ...\n ValueError: n is negative\n \"\"\"\n if n < 0:\n raise ValueError(\"n is negative\")\n # Cache must be outside recursuive function\n # other it will reset every time it calls itself.\n cache: dict[int, int] = {0: 0, 1: 1, 2: 1} # Prefilled cache\n\n def rec_fn_memoized(num: int) -> int:\n if num in cache:\n return cache[num]\n\n value = rec_fn_memoized(num - 1) + rec_fn_memoized(num - 2)\n cache[num] = value\n return value\n\n return [rec_fn_memoized(i) for i in range(n + 1)]\n\n\ndef fib_binet(n: int) -> list[int]:\n \"\"\"\n Calculates the first n (0-indexed) Fibonacci numbers using a simplified form\n of Binet's formula:\n https:\/\/en.m.wikipedia.org\/wiki\/Fibonacci_number#Computation_by_rounding\n\n NOTE 1: this function diverges from fib_iterative at around n = 71, likely\n due to compounding floating-point arithmetic errors\n\n NOTE 2: this function doesn't accept n >= 1475 because it overflows\n thereafter due to the size limitations of Python floats\n >>> fib_binet(0)\n [0]\n >>> fib_binet(1)\n [0, 1]\n >>> fib_binet(5)\n [0, 1, 1, 2, 3, 5]\n >>> fib_binet(10)\n [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]\n >>> fib_binet(-1)\n Traceback (most recent call last):\n ...\n ValueError: n is negative\n >>> fib_binet(1475)\n Traceback (most recent call last):\n ...\n ValueError: n is too large\n \"\"\"\n if n < 0:\n raise ValueError(\"n is negative\")\n if n >= 1475:\n raise ValueError(\"n is too large\")\n sqrt_5 = sqrt(5)\n phi = (1 + sqrt_5) \/ 2\n return [round(phi**i \/ sqrt_5) for i in range(n + 1)]\n\n\nif __name__ == \"__main__\":\n from doctest import testmod\n\n testmod()\n # Time on an M1 MacBook Pro -- Fastest to slowest\n num = 30\n time_func(fib_iterative_yield, num) # 0.0012 ms\n time_func(fib_iterative, num) # 0.0031 ms\n time_func(fib_binet, num) # 0.0062 ms\n time_func(fib_memoization, num) # 0.0100 ms\n time_func(fib_recursive_cached, num) # 0.0153 ms\n time_func(fib_recursive, num) # 257.0910 ms\n"} +{"Prompt":"for nums in 3, 2, 1, 3, 2, 1, 3, 3, 0, 3.0, 3.1, 2.9: ... findmaxiterativenums maxnums True True True True findmaxiterative2, 4, 9, 7, 19, 94, 5 94 findmaxiterative Traceback most recent call last: ... ValueError: findmaxiterative arg is an empty sequence Divide and Conquer algorithm find max value in list :param nums: contains elements :param left: index of first element :param right: index of last element :return: max in nums for nums in 3, 2, 1, 3, 2, 1, 3, 3, 0, 3.0, 3.1, 2.9: ... findmaxrecursivenums, 0, lennums 1 maxnums True True True True nums 1, 3, 5, 7, 9, 2, 4, 6, 8, 10 findmaxrecursivenums, 0, lennums 1 maxnums True findmaxrecursive, 0, 0 Traceback most recent call last: ... ValueError: findmaxrecursive arg is an empty sequence findmaxrecursivenums, 0, lennums maxnums Traceback most recent call last: ... IndexError: list index out of range findmaxrecursivenums, lennums, 1 maxnums True findmaxrecursivenums, lennums 1, 1 maxnums Traceback most recent call last: ... IndexError: list index out of range","Completions":"from __future__ import annotations\n\n\ndef find_max_iterative(nums: list[int | float]) -> int | float:\n \"\"\"\n >>> for nums in ([3, 2, 1], [-3, -2, -1], [3, -3, 0], [3.0, 3.1, 2.9]):\n ... find_max_iterative(nums) == max(nums)\n True\n True\n True\n True\n >>> find_max_iterative([2, 4, 9, 7, 19, 94, 5])\n 94\n >>> find_max_iterative([])\n Traceback (most recent call last):\n ...\n ValueError: find_max_iterative() arg is an empty sequence\n \"\"\"\n if len(nums) == 0:\n raise ValueError(\"find_max_iterative() arg is an empty sequence\")\n max_num = nums[0]\n for x in nums:\n if x > max_num:\n max_num = x\n return max_num\n\n\n# Divide and Conquer algorithm\ndef find_max_recursive(nums: list[int | float], left: int, right: int) -> int | float:\n \"\"\"\n find max value in list\n :param nums: contains elements\n :param left: index of first element\n :param right: index of last element\n :return: max in nums\n\n >>> for nums in ([3, 2, 1], [-3, -2, -1], [3, -3, 0], [3.0, 3.1, 2.9]):\n ... find_max_recursive(nums, 0, len(nums) - 1) == max(nums)\n True\n True\n True\n True\n >>> nums = [1, 3, 5, 7, 9, 2, 4, 6, 8, 10]\n >>> find_max_recursive(nums, 0, len(nums) - 1) == max(nums)\n True\n >>> find_max_recursive([], 0, 0)\n Traceback (most recent call last):\n ...\n ValueError: find_max_recursive() arg is an empty sequence\n >>> find_max_recursive(nums, 0, len(nums)) == max(nums)\n Traceback (most recent call last):\n ...\n IndexError: list index out of range\n >>> find_max_recursive(nums, -len(nums), -1) == max(nums)\n True\n >>> find_max_recursive(nums, -len(nums) - 1, -1) == max(nums)\n Traceback (most recent call last):\n ...\n IndexError: list index out of range\n \"\"\"\n if len(nums) == 0:\n raise ValueError(\"find_max_recursive() arg is an empty sequence\")\n if (\n left >= len(nums)\n or left < -len(nums)\n or right >= len(nums)\n or right < -len(nums)\n ):\n raise IndexError(\"list index out of range\")\n if left == right:\n return nums[left]\n mid = (left + right) >> 1 # the middle\n left_max = find_max_recursive(nums, left, mid) # find max in range[left, mid]\n right_max = find_max_recursive(\n nums, mid + 1, right\n ) # find max in range[mid + 1, right]\n\n return left_max if left_max >= right_max else right_max\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod(verbose=True)\n"} +{"Prompt":"Find Minimum Number in a List :param nums: contains elements :return: min number in list for nums in 3, 2, 1, 3, 2, 1, 3, 3, 0, 3.0, 3.1, 2.9: ... findminiterativenums minnums True True True True findminiterative0, 1, 2, 3, 4, 5, 3, 24, 56 56 findminiterative Traceback most recent call last: ... ValueError: findminiterative arg is an empty sequence Divide and Conquer algorithm find min value in list :param nums: contains elements :param left: index of first element :param right: index of last element :return: min in nums for nums in 3, 2, 1, 3, 2, 1, 3, 3, 0, 3.0, 3.1, 2.9: ... findminrecursivenums, 0, lennums 1 minnums True True True True nums 1, 3, 5, 7, 9, 2, 4, 6, 8, 10 findminrecursivenums, 0, lennums 1 minnums True findminrecursive, 0, 0 Traceback most recent call last: ... ValueError: findminrecursive arg is an empty sequence findminrecursivenums, 0, lennums minnums Traceback most recent call last: ... IndexError: list index out of range findminrecursivenums, lennums, 1 minnums True findminrecursivenums, lennums 1, 1 minnums Traceback most recent call last: ... IndexError: list index out of range","Completions":"from __future__ import annotations\n\n\ndef find_min_iterative(nums: list[int | float]) -> int | float:\n \"\"\"\n Find Minimum Number in a List\n :param nums: contains elements\n :return: min number in list\n\n >>> for nums in ([3, 2, 1], [-3, -2, -1], [3, -3, 0], [3.0, 3.1, 2.9]):\n ... find_min_iterative(nums) == min(nums)\n True\n True\n True\n True\n >>> find_min_iterative([0, 1, 2, 3, 4, 5, -3, 24, -56])\n -56\n >>> find_min_iterative([])\n Traceback (most recent call last):\n ...\n ValueError: find_min_iterative() arg is an empty sequence\n \"\"\"\n if len(nums) == 0:\n raise ValueError(\"find_min_iterative() arg is an empty sequence\")\n min_num = nums[0]\n for num in nums:\n min_num = min(min_num, num)\n return min_num\n\n\n# Divide and Conquer algorithm\ndef find_min_recursive(nums: list[int | float], left: int, right: int) -> int | float:\n \"\"\"\n find min value in list\n :param nums: contains elements\n :param left: index of first element\n :param right: index of last element\n :return: min in nums\n\n >>> for nums in ([3, 2, 1], [-3, -2, -1], [3, -3, 0], [3.0, 3.1, 2.9]):\n ... find_min_recursive(nums, 0, len(nums) - 1) == min(nums)\n True\n True\n True\n True\n >>> nums = [1, 3, 5, 7, 9, 2, 4, 6, 8, 10]\n >>> find_min_recursive(nums, 0, len(nums) - 1) == min(nums)\n True\n >>> find_min_recursive([], 0, 0)\n Traceback (most recent call last):\n ...\n ValueError: find_min_recursive() arg is an empty sequence\n >>> find_min_recursive(nums, 0, len(nums)) == min(nums)\n Traceback (most recent call last):\n ...\n IndexError: list index out of range\n >>> find_min_recursive(nums, -len(nums), -1) == min(nums)\n True\n >>> find_min_recursive(nums, -len(nums) - 1, -1) == min(nums)\n Traceback (most recent call last):\n ...\n IndexError: list index out of range\n \"\"\"\n if len(nums) == 0:\n raise ValueError(\"find_min_recursive() arg is an empty sequence\")\n if (\n left >= len(nums)\n or left < -len(nums)\n or right >= len(nums)\n or right < -len(nums)\n ):\n raise IndexError(\"list index out of range\")\n if left == right:\n return nums[left]\n mid = (left + right) >> 1 # the middle\n left_min = find_min_recursive(nums, left, mid) # find min in range[left, mid]\n right_min = find_min_recursive(\n nums, mid + 1, right\n ) # find min in range[mid + 1, right]\n\n return left_min if left_min <= right_min else right_min\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod(verbose=True)\n"} +{"Prompt":"https:en.wikipedia.orgwikiFloorandceilingfunctions Return the floor of x as an Integral. :param x: the number :return: the largest integer x. import math allfloorn math.floorn for n ... in 1, 1, 0, 0, 1.1, 1.1, 1.0, 1.0, 1000000000 True","Completions":"def floor(x: float) -> int:\n \"\"\"\n Return the floor of x as an Integral.\n :param x: the number\n :return: the largest integer <= x.\n >>> import math\n >>> all(floor(n) == math.floor(n) for n\n ... in (1, -1, 0, -0, 1.1, -1.1, 1.0, -1.0, 1_000_000_000))\n True\n \"\"\"\n return int(x) if x - int(x) >= 0 else int(x) - 1\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Gamma function is a very useful tool in math and physics. It helps calculating complex integral in a convenient way. for more info: https:en.wikipedia.orgwikiGammafunction In mathematics, the gamma function is one commonly used extension of the factorial function to complex numbers. The gamma function is defined for all complex numbers except the nonpositive integers Python's Standard Library math.gamma function overflows around gamma171.624. Calculates the value of Gamma function of num where num is either an integer 1, 2, 3.. or a halfinteger 0.5, 1.5, 2.5 .... gammaiterative1 Traceback most recent call last: ... ValueError: math domain error gammaiterative0 Traceback most recent call last: ... ValueError: math domain error gammaiterative9 40320.0 from math import gamma as mathgamma all.99999999 gammaiterativei mathgammai 1.000000001 ... for i in range1, 50 True gammaiterative1mathgamma1 1.000000001 Traceback most recent call last: ... ValueError: math domain error gammaiterative3.3 mathgamma3.3 0.00000001 True Calculates the value of Gamma function of num where num is either an integer 1, 2, 3.. or a halfinteger 0.5, 1.5, 2.5 .... Implemented using recursion Examples: from math import isclose, gamma as mathgamma gammarecursive0.5 1.7724538509055159 gammarecursive1 1.0 gammarecursive2 1.0 gammarecursive3.5 3.3233509704478426 gammarecursive171.5 9.483367566824795e307 allisclosegammarecursivenum, mathgammanum ... for num in 0.5, 2, 3.5, 171.5 True gammarecursive0 Traceback most recent call last: ... ValueError: math domain error gammarecursive1.1 Traceback most recent call last: ... ValueError: math domain error gammarecursive4 Traceback most recent call last: ... ValueError: math domain error gammarecursive172 Traceback most recent call last: ... OverflowError: math range error gammarecursive1.1 Traceback most recent call last: ... NotImplementedError: num must be an integer or a halfinteger","Completions":"import math\n\nfrom numpy import inf\nfrom scipy.integrate import quad\n\n\ndef gamma_iterative(num: float) -> float:\n \"\"\"\n Calculates the value of Gamma function of num\n where num is either an integer (1, 2, 3..) or a half-integer (0.5, 1.5, 2.5 ...).\n\n >>> gamma_iterative(-1)\n Traceback (most recent call last):\n ...\n ValueError: math domain error\n >>> gamma_iterative(0)\n Traceback (most recent call last):\n ...\n ValueError: math domain error\n >>> gamma_iterative(9)\n 40320.0\n >>> from math import gamma as math_gamma\n >>> all(.99999999 < gamma_iterative(i) \/ math_gamma(i) <= 1.000000001\n ... for i in range(1, 50))\n True\n >>> gamma_iterative(-1)\/math_gamma(-1) <= 1.000000001\n Traceback (most recent call last):\n ...\n ValueError: math domain error\n >>> gamma_iterative(3.3) - math_gamma(3.3) <= 0.00000001\n True\n \"\"\"\n if num <= 0:\n raise ValueError(\"math domain error\")\n\n return quad(integrand, 0, inf, args=(num))[0]\n\n\ndef integrand(x: float, z: float) -> float:\n return math.pow(x, z - 1) * math.exp(-x)\n\n\ndef gamma_recursive(num: float) -> float:\n \"\"\"\n Calculates the value of Gamma function of num\n where num is either an integer (1, 2, 3..) or a half-integer (0.5, 1.5, 2.5 ...).\n Implemented using recursion\n Examples:\n >>> from math import isclose, gamma as math_gamma\n >>> gamma_recursive(0.5)\n 1.7724538509055159\n >>> gamma_recursive(1)\n 1.0\n >>> gamma_recursive(2)\n 1.0\n >>> gamma_recursive(3.5)\n 3.3233509704478426\n >>> gamma_recursive(171.5)\n 9.483367566824795e+307\n >>> all(isclose(gamma_recursive(num), math_gamma(num))\n ... for num in (0.5, 2, 3.5, 171.5))\n True\n >>> gamma_recursive(0)\n Traceback (most recent call last):\n ...\n ValueError: math domain error\n >>> gamma_recursive(-1.1)\n Traceback (most recent call last):\n ...\n ValueError: math domain error\n >>> gamma_recursive(-4)\n Traceback (most recent call last):\n ...\n ValueError: math domain error\n >>> gamma_recursive(172)\n Traceback (most recent call last):\n ...\n OverflowError: math range error\n >>> gamma_recursive(1.1)\n Traceback (most recent call last):\n ...\n NotImplementedError: num must be an integer or a half-integer\n \"\"\"\n if num <= 0:\n raise ValueError(\"math domain error\")\n if num > 171.5:\n raise OverflowError(\"math range error\")\n elif num - int(num) not in (0, 0.5):\n raise NotImplementedError(\"num must be an integer or a half-integer\")\n elif num == 0.5:\n return math.sqrt(math.pi)\n else:\n return 1.0 if num == 1 else (num - 1) * gamma_recursive(num - 1)\n\n\nif __name__ == \"__main__\":\n from doctest import testmod\n\n testmod()\n num = 1.0\n while num:\n num = float(input(\"Gamma of: \"))\n print(f\"gamma_iterative({num}) = {gamma_iterative(num)}\")\n print(f\"gamma_recursive({num}) = {gamma_recursive(num)}\")\n print(\"\\nEnter 0 to exit...\")\n"} +{"Prompt":"Reference: https:en.wikipedia.orgwikiGaussianfunction gaussian1 0.24197072451914337 gaussian24 3.342714441794458e126 gaussian1, 4, 2 0.06475879783294587 gaussian1, 5, 3 0.05467002489199788 Supports NumPy Arrays Use numpy.meshgrid with this to generate gaussian blur on images. import numpy as np x np.arange15 gaussianx array3.98942280e01, 2.41970725e01, 5.39909665e02, 4.43184841e03, 1.33830226e04, 1.48671951e06, 6.07588285e09, 9.13472041e12, 5.05227108e15, 1.02797736e18, 7.69459863e23, 2.11881925e27, 2.14638374e32, 7.99882776e38, 1.09660656e43 gaussian15 5.530709549844416e50 gaussian1,2, 'string' Traceback most recent call last: ... TypeError: unsupported operand types for : 'list' and 'float' gaussian'hello world' Traceback most recent call last: ... TypeError: unsupported operand types for : 'str' and 'float' gaussian10234 doctest: IGNOREEXCEPTIONDETAIL Traceback most recent call last: ... OverflowError: 34, 'Result too large' gaussian10326 0.3989422804014327 gaussian2523, mu234234, sigma3425 0.0","Completions":"from numpy import exp, pi, sqrt\n\n\ndef gaussian(x, mu: float = 0.0, sigma: float = 1.0) -> int:\n \"\"\"\n >>> gaussian(1)\n 0.24197072451914337\n\n >>> gaussian(24)\n 3.342714441794458e-126\n\n >>> gaussian(1, 4, 2)\n 0.06475879783294587\n\n >>> gaussian(1, 5, 3)\n 0.05467002489199788\n\n Supports NumPy Arrays\n Use numpy.meshgrid with this to generate gaussian blur on images.\n >>> import numpy as np\n >>> x = np.arange(15)\n >>> gaussian(x)\n array([3.98942280e-01, 2.41970725e-01, 5.39909665e-02, 4.43184841e-03,\n 1.33830226e-04, 1.48671951e-06, 6.07588285e-09, 9.13472041e-12,\n 5.05227108e-15, 1.02797736e-18, 7.69459863e-23, 2.11881925e-27,\n 2.14638374e-32, 7.99882776e-38, 1.09660656e-43])\n\n >>> gaussian(15)\n 5.530709549844416e-50\n\n >>> gaussian([1,2, 'string'])\n Traceback (most recent call last):\n ...\n TypeError: unsupported operand type(s) for -: 'list' and 'float'\n\n >>> gaussian('hello world')\n Traceback (most recent call last):\n ...\n TypeError: unsupported operand type(s) for -: 'str' and 'float'\n\n >>> gaussian(10**234) # doctest: +IGNORE_EXCEPTION_DETAIL\n Traceback (most recent call last):\n ...\n OverflowError: (34, 'Result too large')\n\n >>> gaussian(10**-326)\n 0.3989422804014327\n\n >>> gaussian(2523, mu=234234, sigma=3425)\n 0.0\n \"\"\"\n return 1 \/ sqrt(2 * pi * sigma**2) * exp(-((x - mu) ** 2) \/ (2 * sigma**2))\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"This script demonstrates an implementation of the Gaussian Error Linear Unit function. https:en.wikipedia.orgwikiActivationfunctionComparisonofactivationfunctions The function takes a vector of K real numbers as input and returns x sigmoid1.702x. Gaussian Error Linear Unit GELU is a highperforming neural network activation function. This script is inspired by a corresponding research paper. https:arxiv.orgabs1606.08415 Mathematical function sigmoid takes a vector x of K real numbers as input and returns 1 1 ex. https:en.wikipedia.orgwikiSigmoidfunction sigmoidnp.array1.0, 1.0, 2.0 array0.26894142, 0.73105858, 0.88079708 Implements the Gaussian Error Linear Unit GELU function Parameters: vector np.ndarray: A numpy array of shape 1, n consisting of real values Returns: geluvec np.ndarray: The input numpy array, after applying gelu Examples: gaussianerrorlinearunitnp.array1.0, 1.0, 2.0 array0.15420423, 0.84579577, 1.93565862 gaussianerrorlinearunitnp.array3 array0.01807131","Completions":"import numpy as np\n\n\ndef sigmoid(vector: np.ndarray) -> np.ndarray:\n \"\"\"\n Mathematical function sigmoid takes a vector x of K real numbers as input and\n returns 1\/ (1 + e^-x).\n https:\/\/en.wikipedia.org\/wiki\/Sigmoid_function\n\n >>> sigmoid(np.array([-1.0, 1.0, 2.0]))\n array([0.26894142, 0.73105858, 0.88079708])\n \"\"\"\n return 1 \/ (1 + np.exp(-vector))\n\n\ndef gaussian_error_linear_unit(vector: np.ndarray) -> np.ndarray:\n \"\"\"\n Implements the Gaussian Error Linear Unit (GELU) function\n\n Parameters:\n vector (np.ndarray): A numpy array of shape (1, n) consisting of real values\n\n Returns:\n gelu_vec (np.ndarray): The input numpy array, after applying gelu\n\n Examples:\n >>> gaussian_error_linear_unit(np.array([-1.0, 1.0, 2.0]))\n array([-0.15420423, 0.84579577, 1.93565862])\n\n >>> gaussian_error_linear_unit(np.array([-3]))\n array([-0.01807131])\n \"\"\"\n return vector * sigmoid(1.702 * vector)\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"A Sophie Germain prime is any prime p, where 2p 1 is also prime. The second number, 2p 1 is called a safe prime. Examples of Germain primes include: 2, 3, 5, 11, 23 Their corresponding safe primes: 5, 7, 11, 23, 47 https:en.wikipedia.orgwikiSafeandSophieGermainprimes Checks if input number and 2number 1 are prime. isgermainprime3 True isgermainprime11 True isgermainprime4 False isgermainprime23 True isgermainprime13 False isgermainprime20 False isgermainprime'abc' Traceback most recent call last: ... TypeError: Input value must be a positive integer. Input value: abc Checks if input number and number 12 are prime. The smallest safe prime is 5, with the Germain prime is 2. issafeprime5 True issafeprime11 True issafeprime1 False issafeprime2 False issafeprime3 False issafeprime47 True issafeprime'abc' Traceback most recent call last: ... TypeError: Input value must be a positive integer. Input value: abc","Completions":"from maths.prime_check import is_prime\n\n\ndef is_germain_prime(number: int) -> bool:\n \"\"\"Checks if input number and 2*number + 1 are prime.\n\n >>> is_germain_prime(3)\n True\n >>> is_germain_prime(11)\n True\n >>> is_germain_prime(4)\n False\n >>> is_germain_prime(23)\n True\n >>> is_germain_prime(13)\n False\n >>> is_germain_prime(20)\n False\n >>> is_germain_prime('abc')\n Traceback (most recent call last):\n ...\n TypeError: Input value must be a positive integer. Input value: abc\n \"\"\"\n if not isinstance(number, int) or number < 1:\n msg = f\"Input value must be a positive integer. Input value: {number}\"\n raise TypeError(msg)\n\n return is_prime(number) and is_prime(2 * number + 1)\n\n\ndef is_safe_prime(number: int) -> bool:\n \"\"\"Checks if input number and (number - 1)\/2 are prime.\n The smallest safe prime is 5, with the Germain prime is 2.\n\n >>> is_safe_prime(5)\n True\n >>> is_safe_prime(11)\n True\n >>> is_safe_prime(1)\n False\n >>> is_safe_prime(2)\n False\n >>> is_safe_prime(3)\n False\n >>> is_safe_prime(47)\n True\n >>> is_safe_prime('abc')\n Traceback (most recent call last):\n ...\n TypeError: Input value must be a positive integer. Input value: abc\n \"\"\"\n if not isinstance(number, int) or number < 1:\n msg = f\"Input value must be a positive integer. Input value: {number}\"\n raise TypeError(msg)\n\n return (number - 1) % 2 == 0 and is_prime(number) and is_prime((number - 1) \/\/ 2)\n\n\nif __name__ == \"__main__\":\n from doctest import testmod\n\n testmod()\n"} +{"Prompt":"Greatest Common Divisor. Wikipedia reference: https:en.wikipedia.orgwikiGreatestcommondivisor gcda, b gcda, b gcda, b gcda, b by definition of divisibility Calculate Greatest Common Divisor GCD. greatestcommondivisor24, 40 8 greatestcommondivisor1, 1 1 greatestcommondivisor1, 800 1 greatestcommondivisor11, 37 1 greatestcommondivisor3, 5 1 greatestcommondivisor16, 4 4 greatestcommondivisor3, 9 3 greatestcommondivisor9, 3 3 greatestcommondivisor3, 9 3 greatestcommondivisor3, 9 3 Below method is more memory efficient because it does not create additional stack frames for recursive functions calls as done in the above method. gcdbyiterative24, 40 8 greatestcommondivisor24, 40 gcdbyiterative24, 40 True gcdbyiterative3, 9 3 gcdbyiterative3, 9 3 gcdbyiterative1, 800 1 gcdbyiterative11, 37 1 Call Greatest Common Divisor function.","Completions":"def greatest_common_divisor(a: int, b: int) -> int:\n \"\"\"\n Calculate Greatest Common Divisor (GCD).\n >>> greatest_common_divisor(24, 40)\n 8\n >>> greatest_common_divisor(1, 1)\n 1\n >>> greatest_common_divisor(1, 800)\n 1\n >>> greatest_common_divisor(11, 37)\n 1\n >>> greatest_common_divisor(3, 5)\n 1\n >>> greatest_common_divisor(16, 4)\n 4\n >>> greatest_common_divisor(-3, 9)\n 3\n >>> greatest_common_divisor(9, -3)\n 3\n >>> greatest_common_divisor(3, -9)\n 3\n >>> greatest_common_divisor(-3, -9)\n 3\n \"\"\"\n return abs(b) if a == 0 else greatest_common_divisor(b % a, a)\n\n\ndef gcd_by_iterative(x: int, y: int) -> int:\n \"\"\"\n Below method is more memory efficient because it does not create additional\n stack frames for recursive functions calls (as done in the above method).\n >>> gcd_by_iterative(24, 40)\n 8\n >>> greatest_common_divisor(24, 40) == gcd_by_iterative(24, 40)\n True\n >>> gcd_by_iterative(-3, -9)\n 3\n >>> gcd_by_iterative(3, -9)\n 3\n >>> gcd_by_iterative(1, -800)\n 1\n >>> gcd_by_iterative(11, 37)\n 1\n \"\"\"\n while y: # --> when y=0 then loop will terminate and return x as final GCD.\n x, y = y, x % y\n return abs(x)\n\n\ndef main():\n \"\"\"\n Call Greatest Common Divisor function.\n \"\"\"\n try:\n nums = input(\"Enter two integers separated by comma (,): \").split(\",\")\n num_1 = int(nums[0])\n num_2 = int(nums[1])\n print(\n f\"greatest_common_divisor({num_1}, {num_2}) = \"\n f\"{greatest_common_divisor(num_1, num_2)}\"\n )\n print(f\"By iterative gcd({num_1}, {num_2}) = {gcd_by_iterative(num_1, num_2)}\")\n except (IndexError, UnboundLocalError, ValueError):\n print(\"Wrong input\")\n\n\nif __name__ == \"__main__\":\n main()\n"} +{"Prompt":"This theorem states that the number of prime factors of n will be approximately loglogn for most natural numbers n exactprimefactorcount51242183 3 the n input value must be odd so that we can skip one element ie i 2 this condition checks the prime number n is greater than 2 The number of distinct prime factors isare 3 The value of loglogn is 2.8765","Completions":"# This theorem states that the number of prime factors of n\n# will be approximately log(log(n)) for most natural numbers n\n\nimport math\n\n\ndef exact_prime_factor_count(n: int) -> int:\n \"\"\"\n >>> exact_prime_factor_count(51242183)\n 3\n \"\"\"\n count = 0\n if n % 2 == 0:\n count += 1\n while n % 2 == 0:\n n = int(n \/ 2)\n # the n input value must be odd so that\n # we can skip one element (ie i += 2)\n\n i = 3\n\n while i <= int(math.sqrt(n)):\n if n % i == 0:\n count += 1\n while n % i == 0:\n n = int(n \/ i)\n i = i + 2\n\n # this condition checks the prime\n # number n is greater than 2\n\n if n > 2:\n count += 1\n return count\n\n\nif __name__ == \"__main__\":\n n = 51242183\n print(f\"The number of distinct prime factors is\/are {exact_prime_factor_count(n)}\")\n print(f\"The value of log(log(n)) is {math.log(math.log(n)):.4f}\")\n\n \"\"\"\n The number of distinct prime factors is\/are 3\n The value of log(log(n)) is 2.8765\n \"\"\"\n"} +{"Prompt":"Integer Square Root Algorithm An efficient method to calculate the square root of a nonnegative integer 'num' rounded down to the nearest integer. It uses a binary search approach to find the integer square root without using any builtin exponent functions or operators. https:en.wikipedia.orgwikiIntegersquareroot https:docs.python.org3librarymath.htmlmath.isqrt Note: This algorithm is designed for nonnegative integers only. The result is rounded down to the nearest integer. The algorithm has a time complexity of Ologx. Original algorithm idea based on binary search. Returns the integer square root of a nonnegative integer num. Args: num: A nonnegative integer. Returns: The integer square root of num. Raises: ValueError: If num is not an integer or is negative. integersquarerooti for i in range18 0, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 4, 4 integersquareroot625 25 integersquareroot2147483647 46340 from math import isqrt allintegersquarerooti isqrti for i in range20 True integersquareroot1 Traceback most recent call last: ... ValueError: num must be nonnegative integer integersquareroot1.5 Traceback most recent call last: ... ValueError: num must be nonnegative integer integersquareroot0 Traceback most recent call last: ... ValueError: num must be nonnegative integer","Completions":"def integer_square_root(num: int) -> int:\n \"\"\"\n Returns the integer square root of a non-negative integer num.\n Args:\n num: A non-negative integer.\n Returns:\n The integer square root of num.\n Raises:\n ValueError: If num is not an integer or is negative.\n >>> [integer_square_root(i) for i in range(18)]\n [0, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 4, 4]\n >>> integer_square_root(625)\n 25\n >>> integer_square_root(2_147_483_647)\n 46340\n >>> from math import isqrt\n >>> all(integer_square_root(i) == isqrt(i) for i in range(20))\n True\n >>> integer_square_root(-1)\n Traceback (most recent call last):\n ...\n ValueError: num must be non-negative integer\n >>> integer_square_root(1.5)\n Traceback (most recent call last):\n ...\n ValueError: num must be non-negative integer\n >>> integer_square_root(\"0\")\n Traceback (most recent call last):\n ...\n ValueError: num must be non-negative integer\n \"\"\"\n if not isinstance(num, int) or num < 0:\n raise ValueError(\"num must be non-negative integer\")\n\n if num < 2:\n return num\n\n left_bound = 0\n right_bound = num \/\/ 2\n\n while left_bound <= right_bound:\n mid = left_bound + (right_bound - left_bound) \/\/ 2\n mid_squared = mid * mid\n if mid_squared == num:\n return mid\n\n if mid_squared < num:\n left_bound = mid + 1\n else:\n right_bound = mid - 1\n\n return right_bound\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"An implementation of interquartile range IQR which is a measure of statistical dispersion, which is the spread of the data. The function takes the list of numeric values as input and returns the IQR. Script inspired by this Wikipedia article: https:en.wikipedia.orgwikiInterquartilerange This is the implementation of the median. :param nums: The list of numeric nums :return: Median of the list findmediannums1, 2, 2, 3, 4 2 findmediannums1, 2, 2, 3, 4, 4 2.5 findmediannums1, 2, 0, 3, 4, 4 1.5 findmediannums1.1, 2.2, 2, 3.3, 4.4, 4 2.65 Return the interquartile range for a list of numeric values. :param nums: The list of numeric values. :return: interquartile range interquartilerangenums4, 1, 2, 3, 2 2.0 interquartilerangenums 2, 7, 10, 9, 8, 4, 67, 45 17.0 interquartilerangenums 2.1, 7.1, 10.1, 9.1, 8.1, 4.1, 67.1, 45.1 17.2 interquartilerangenums 0, 0, 0, 0, 0 0.0 interquartilerangenums Traceback most recent call last: ... ValueError: The list is empty. Provide a nonempty list.","Completions":"from __future__ import annotations\n\n\ndef find_median(nums: list[int | float]) -> float:\n \"\"\"\n This is the implementation of the median.\n :param nums: The list of numeric nums\n :return: Median of the list\n >>> find_median(nums=([1, 2, 2, 3, 4]))\n 2\n >>> find_median(nums=([1, 2, 2, 3, 4, 4]))\n 2.5\n >>> find_median(nums=([-1, 2, 0, 3, 4, -4]))\n 1.5\n >>> find_median(nums=([1.1, 2.2, 2, 3.3, 4.4, 4]))\n 2.65\n \"\"\"\n div, mod = divmod(len(nums), 2)\n if mod:\n return nums[div]\n return (nums[div] + nums[(div) - 1]) \/ 2\n\n\ndef interquartile_range(nums: list[int | float]) -> float:\n \"\"\"\n Return the interquartile range for a list of numeric values.\n :param nums: The list of numeric values.\n :return: interquartile range\n\n >>> interquartile_range(nums=[4, 1, 2, 3, 2])\n 2.0\n >>> interquartile_range(nums = [-2, -7, -10, 9, 8, 4, -67, 45])\n 17.0\n >>> interquartile_range(nums = [-2.1, -7.1, -10.1, 9.1, 8.1, 4.1, -67.1, 45.1])\n 17.2\n >>> interquartile_range(nums = [0, 0, 0, 0, 0])\n 0.0\n >>> interquartile_range(nums=[])\n Traceback (most recent call last):\n ...\n ValueError: The list is empty. Provide a non-empty list.\n \"\"\"\n if not nums:\n raise ValueError(\"The list is empty. Provide a non-empty list.\")\n nums.sort()\n length = len(nums)\n div, mod = divmod(length, 2)\n q1 = find_median(nums[:div])\n half_length = sum((div, mod))\n q3 = find_median(nums[half_length:length])\n return q3 - q1\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Returns whether num is a palindrome or not see for reference https:en.wikipedia.orgwikiPalindromicnumber. isintpalindrome121 False isintpalindrome0 True isintpalindrome10 False isintpalindrome11 True isintpalindrome101 True isintpalindrome120 False","Completions":"def is_int_palindrome(num: int) -> bool:\n \"\"\"\n Returns whether `num` is a palindrome or not\n (see for reference https:\/\/en.wikipedia.org\/wiki\/Palindromic_number).\n\n >>> is_int_palindrome(-121)\n False\n >>> is_int_palindrome(0)\n True\n >>> is_int_palindrome(10)\n False\n >>> is_int_palindrome(11)\n True\n >>> is_int_palindrome(101)\n True\n >>> is_int_palindrome(120)\n False\n \"\"\"\n if num < 0:\n return False\n\n num_copy: int = num\n rev_num: int = 0\n while num > 0:\n rev_num = rev_num * 10 + (num % 10)\n num \/\/= 10\n\n return num_copy == rev_num\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Is IP v4 address valid? A valid IP address must be four octets in the form of A.B.C.D, where A,B,C and D are numbers from 0254 for example: 192.168.23.1, 172.254.254.254 are valid IP address 192.168.255.0, 255.192.3.121 are invalid IP address print Valid IP address If IP is valid. or print Invalid IP address If IP is invalid. isipv4addressvalid192.168.0.23 True isipv4addressvalid192.255.15.8 False isipv4addressvalid172.100.0.8 True isipv4addressvalid254.255.0.255 False isipv4addressvalid1.2.33333333.4 False isipv4addressvalid1.2.3.4 False isipv4addressvalid1.2.3 False isipv4addressvalid1.2.3.4.5 False isipv4addressvalid1.2.A.4 False isipv4addressvalid0.0.0.0 True isipv4addressvalid1.2.3. False","Completions":"def is_ip_v4_address_valid(ip_v4_address: str) -> bool:\n \"\"\"\n print \"Valid IP address\" If IP is valid.\n or\n print \"Invalid IP address\" If IP is invalid.\n\n >>> is_ip_v4_address_valid(\"192.168.0.23\")\n True\n\n >>> is_ip_v4_address_valid(\"192.255.15.8\")\n False\n\n >>> is_ip_v4_address_valid(\"172.100.0.8\")\n True\n\n >>> is_ip_v4_address_valid(\"254.255.0.255\")\n False\n\n >>> is_ip_v4_address_valid(\"1.2.33333333.4\")\n False\n\n >>> is_ip_v4_address_valid(\"1.2.-3.4\")\n False\n\n >>> is_ip_v4_address_valid(\"1.2.3\")\n False\n\n >>> is_ip_v4_address_valid(\"1.2.3.4.5\")\n False\n\n >>> is_ip_v4_address_valid(\"1.2.A.4\")\n False\n\n >>> is_ip_v4_address_valid(\"0.0.0.0\")\n True\n\n >>> is_ip_v4_address_valid(\"1.2.3.\")\n False\n \"\"\"\n octets = [int(i) for i in ip_v4_address.split(\".\") if i.isdigit()]\n return len(octets) == 4 and all(0 <= int(octet) <= 254 for octet in octets)\n\n\nif __name__ == \"__main__\":\n ip = input().strip()\n valid_or_invalid = \"valid\" if is_ip_v4_address_valid(ip) else \"invalid\"\n print(f\"{ip} is a {valid_or_invalid} IP v4 address.\")\n"} +{"Prompt":"References: wikipedia:square free number psfblack : True ruff : True doctest: NORMALIZEWHITESPACE This functions takes a list of prime factors as input. returns True if the factors are square free. issquarefree1, 1, 2, 3, 4 False These are wrong but should return some value it simply checks for repetition in the numbers. issquarefree1, 3, 4, 'sd', 0.0 True issquarefree1, 0.5, 2, 0.0 True issquarefree1, 2, 2, 5 False issquarefree'asd' True issquarefree24 Traceback most recent call last: ... TypeError: 'int' object is not iterable","Completions":"from __future__ import annotations\n\n\ndef is_square_free(factors: list[int]) -> bool:\n \"\"\"\n # doctest: +NORMALIZE_WHITESPACE\n This functions takes a list of prime factors as input.\n returns True if the factors are square free.\n >>> is_square_free([1, 1, 2, 3, 4])\n False\n\n These are wrong but should return some value\n it simply checks for repetition in the numbers.\n >>> is_square_free([1, 3, 4, 'sd', 0.0])\n True\n\n >>> is_square_free([1, 0.5, 2, 0.0])\n True\n >>> is_square_free([1, 2, 2, 5])\n False\n >>> is_square_free('asd')\n True\n >>> is_square_free(24)\n Traceback (most recent call last):\n ...\n TypeError: 'int' object is not iterable\n \"\"\"\n return len(set(factors)) == len(factors)\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"The Jaccard similarity coefficient is a commonly used indicator of the similarity between two sets. Let U be a set and A and B be subsets of U, then the Jaccard indexsimilarity is defined to be the ratio of the number of elements of their intersection and the number of elements of their union. Inspired from Wikipedia and the book Mining of Massive Datasets MMDS 2nd Edition, Chapter 3 https:en.wikipedia.orgwikiJaccardindex https:mmds.org Jaccard similarity is widely used with MinHashing. Finds the jaccard similarity between two sets. Essentially, its intersection over union. The alternative way to calculate this is to take union as sum of the number of items in the two sets. This will lead to jaccard similarity of a set with itself be 12 instead of 1. MMDS 2nd Edition, Page 77 Parameters: :seta set,list,tuple: A nonempty setlist :setb set,list,tuple: A nonempty setlist :alternativeUnion boolean: If True, use sum of number of items as union Output: float The jaccard similarity between the two sets. Examples: seta 'a', 'b', 'c', 'd', 'e' setb 'c', 'd', 'e', 'f', 'h', 'i' jaccardsimilarityseta, setb 0.375 jaccardsimilarityseta, seta 1.0 jaccardsimilarityseta, seta, True 0.5 seta 'a', 'b', 'c', 'd', 'e' setb 'c', 'd', 'e', 'f', 'h', 'i' jaccardsimilarityseta, setb 0.375 seta 'c', 'd', 'e', 'f', 'h', 'i' setb 'a', 'b', 'c', 'd', 'e' jaccardsimilarityseta, setb 0.375 seta 'c', 'd', 'e', 'f', 'h', 'i' setb 'a', 'b', 'c', 'd' jaccardsimilarityseta, setb, True 0.2 seta 'a', 'b' setb 'c', 'd' jaccardsimilarityseta, setb Traceback most recent call last: ... ValueError: Set a and b must either both be sets or be either a list or a tuple. Cast seta to list because tuples cannot be mutated","Completions":"def jaccard_similarity(\n set_a: set[str] | list[str] | tuple[str],\n set_b: set[str] | list[str] | tuple[str],\n alternative_union=False,\n):\n \"\"\"\n Finds the jaccard similarity between two sets.\n Essentially, its intersection over union.\n\n The alternative way to calculate this is to take union as sum of the\n number of items in the two sets. This will lead to jaccard similarity\n of a set with itself be 1\/2 instead of 1. [MMDS 2nd Edition, Page 77]\n\n Parameters:\n :set_a (set,list,tuple): A non-empty set\/list\n :set_b (set,list,tuple): A non-empty set\/list\n :alternativeUnion (boolean): If True, use sum of number of\n items as union\n\n Output:\n (float) The jaccard similarity between the two sets.\n\n Examples:\n >>> set_a = {'a', 'b', 'c', 'd', 'e'}\n >>> set_b = {'c', 'd', 'e', 'f', 'h', 'i'}\n >>> jaccard_similarity(set_a, set_b)\n 0.375\n >>> jaccard_similarity(set_a, set_a)\n 1.0\n >>> jaccard_similarity(set_a, set_a, True)\n 0.5\n >>> set_a = ['a', 'b', 'c', 'd', 'e']\n >>> set_b = ('c', 'd', 'e', 'f', 'h', 'i')\n >>> jaccard_similarity(set_a, set_b)\n 0.375\n >>> set_a = ('c', 'd', 'e', 'f', 'h', 'i')\n >>> set_b = ['a', 'b', 'c', 'd', 'e']\n >>> jaccard_similarity(set_a, set_b)\n 0.375\n >>> set_a = ('c', 'd', 'e', 'f', 'h', 'i')\n >>> set_b = ['a', 'b', 'c', 'd']\n >>> jaccard_similarity(set_a, set_b, True)\n 0.2\n >>> set_a = {'a', 'b'}\n >>> set_b = ['c', 'd']\n >>> jaccard_similarity(set_a, set_b)\n Traceback (most recent call last):\n ...\n ValueError: Set a and b must either both be sets or be either a list or a tuple.\n \"\"\"\n\n if isinstance(set_a, set) and isinstance(set_b, set):\n intersection_length = len(set_a.intersection(set_b))\n\n if alternative_union:\n union_length = len(set_a) + len(set_b)\n else:\n union_length = len(set_a.union(set_b))\n\n return intersection_length \/ union_length\n\n elif isinstance(set_a, (list, tuple)) and isinstance(set_b, (list, tuple)):\n intersection = [element for element in set_a if element in set_b]\n\n if alternative_union:\n return len(intersection) \/ (len(set_a) + len(set_b))\n else:\n # Cast set_a to list because tuples cannot be mutated\n union = list(set_a) + [element for element in set_b if element not in set_a]\n return len(intersection) \/ len(union)\n raise ValueError(\n \"Set a and b must either both be sets or be either a list or a tuple.\"\n )\n\n\nif __name__ == \"__main__\":\n set_a = {\"a\", \"b\", \"c\", \"d\", \"e\"}\n set_b = {\"c\", \"d\", \"e\", \"f\", \"h\", \"i\"}\n print(jaccard_similarity(set_a, set_b))\n"} +{"Prompt":"Calculate joint probability distribution https:en.wikipedia.orgwikiJointprobabilitydistribution jointdistribution jointprobabilitydistribution ... 1, 2, 2, 5, 8, 0.7, 0.3, 0.3, 0.5, 0.2 ... from math import isclose isclosejointdistribution.pop1, 8, 0.14 True jointdistribution 1, 2: 0.21, 1, 5: 0.35, 2, 2: 0.09, 2, 5: 0.15, 2, 8: 0.06 Function to calculate the expectation mean from math import isclose iscloseexpectation1, 2, 0.7, 0.3, 1.3 True Function to calculate the variance from math import isclose isclosevariance1,2,0.7,0.3, 0.21 True Function to calculate the covariance covariance1, 2, 2, 5, 8, 0.7, 0.3, 0.3, 0.5, 0.2 2.7755575615628914e17 Function to calculate the standard deviation standarddeviation0.21 0.458257569495584 Input values for X and Y Convert input values to integers Input probabilities for X and Y Convert input probabilities to floats Calculate the joint probability distribution Print the joint probability distribution","Completions":"def joint_probability_distribution(\n x_values: list[int],\n y_values: list[int],\n x_probabilities: list[float],\n y_probabilities: list[float],\n) -> dict:\n \"\"\"\n >>> joint_distribution = joint_probability_distribution(\n ... [1, 2], [-2, 5, 8], [0.7, 0.3], [0.3, 0.5, 0.2]\n ... )\n >>> from math import isclose\n >>> isclose(joint_distribution.pop((1, 8)), 0.14)\n True\n >>> joint_distribution\n {(1, -2): 0.21, (1, 5): 0.35, (2, -2): 0.09, (2, 5): 0.15, (2, 8): 0.06}\n \"\"\"\n return {\n (x, y): x_prob * y_prob\n for x, x_prob in zip(x_values, x_probabilities)\n for y, y_prob in zip(y_values, y_probabilities)\n }\n\n\n# Function to calculate the expectation (mean)\ndef expectation(values: list, probabilities: list) -> float:\n \"\"\"\n >>> from math import isclose\n >>> isclose(expectation([1, 2], [0.7, 0.3]), 1.3)\n True\n \"\"\"\n return sum(x * p for x, p in zip(values, probabilities))\n\n\n# Function to calculate the variance\ndef variance(values: list[int], probabilities: list[float]) -> float:\n \"\"\"\n >>> from math import isclose\n >>> isclose(variance([1,2],[0.7,0.3]), 0.21)\n True\n \"\"\"\n mean = expectation(values, probabilities)\n return sum((x - mean) ** 2 * p for x, p in zip(values, probabilities))\n\n\n# Function to calculate the covariance\ndef covariance(\n x_values: list[int],\n y_values: list[int],\n x_probabilities: list[float],\n y_probabilities: list[float],\n) -> float:\n \"\"\"\n >>> covariance([1, 2], [-2, 5, 8], [0.7, 0.3], [0.3, 0.5, 0.2])\n -2.7755575615628914e-17\n \"\"\"\n mean_x = expectation(x_values, x_probabilities)\n mean_y = expectation(y_values, y_probabilities)\n return sum(\n (x - mean_x) * (y - mean_y) * px * py\n for x, px in zip(x_values, x_probabilities)\n for y, py in zip(y_values, y_probabilities)\n )\n\n\n# Function to calculate the standard deviation\ndef standard_deviation(variance: float) -> float:\n \"\"\"\n >>> standard_deviation(0.21)\n 0.458257569495584\n \"\"\"\n return variance**0.5\n\n\nif __name__ == \"__main__\":\n from doctest import testmod\n\n testmod()\n # Input values for X and Y\n x_vals = input(\"Enter values of X separated by spaces: \").split()\n y_vals = input(\"Enter values of Y separated by spaces: \").split()\n\n # Convert input values to integers\n x_values = [int(x) for x in x_vals]\n y_values = [int(y) for y in y_vals]\n\n # Input probabilities for X and Y\n x_probs = input(\"Enter probabilities for X separated by spaces: \").split()\n y_probs = input(\"Enter probabilities for Y separated by spaces: \").split()\n assert len(x_values) == len(x_probs)\n assert len(y_values) == len(y_probs)\n\n # Convert input probabilities to floats\n x_probabilities = [float(p) for p in x_probs]\n y_probabilities = [float(p) for p in y_probs]\n\n # Calculate the joint probability distribution\n jpd = joint_probability_distribution(\n x_values, y_values, x_probabilities, y_probabilities\n )\n\n # Print the joint probability distribution\n print(\n \"\\n\".join(\n f\"P(X={x}, Y={y}) = {probability}\" for (x, y), probability in jpd.items()\n )\n )\n mean_xy = expectation(\n [x * y for x in x_values for y in y_values],\n [px * py for px in x_probabilities for py in y_probabilities],\n )\n print(f\"x mean: {expectation(x_values, x_probabilities) = }\")\n print(f\"y mean: {expectation(y_values, y_probabilities) = }\")\n print(f\"xy mean: {mean_xy}\")\n print(f\"x: {variance(x_values, x_probabilities) = }\")\n print(f\"y: {variance(y_values, y_probabilities) = }\")\n print(f\"{covariance(x_values, y_values, x_probabilities, y_probabilities) = }\")\n print(f\"x: {standard_deviation(variance(x_values, x_probabilities)) = }\")\n print(f\"y: {standard_deviation(variance(y_values, y_probabilities)) = }\")\n"} +{"Prompt":"The Josephus problem is a famous theoretical problem related to a certain countingout game. This module provides functions to solve the Josephus problem for numpeople and a stepsize. The Josephus problem is defined as follows: numpeople are standing in a circle. Starting with a specified person, you count around the circle, skipping a fixed number of people stepsize. The person at which you stop counting is eliminated from the circle. The counting continues until only one person remains. For more information about the Josephus problem, refer to: https:en.wikipedia.orgwikiJosephusproblem Solve the Josephus problem for numpeople and a stepsize recursively. Args: numpeople: A positive integer representing the number of people. stepsize: A positive integer representing the step size for elimination. Returns: The position of the last person remaining. Raises: ValueError: If numpeople or stepsize is not a positive integer. Examples: josephusrecursive7, 3 3 josephusrecursive10, 2 4 josephusrecursive0, 2 Traceback most recent call last: ... ValueError: numpeople or stepsize is not a positive integer. josephusrecursive1.9, 2 Traceback most recent call last: ... ValueError: numpeople or stepsize is not a positive integer. josephusrecursive2, 2 Traceback most recent call last: ... ValueError: numpeople or stepsize is not a positive integer. josephusrecursive7, 0 Traceback most recent call last: ... ValueError: numpeople or stepsize is not a positive integer. josephusrecursive7, 2 Traceback most recent call last: ... ValueError: numpeople or stepsize is not a positive integer. josephusrecursive1000, 0.01 Traceback most recent call last: ... ValueError: numpeople or stepsize is not a positive integer. josephusrecursivecat, dog Traceback most recent call last: ... ValueError: numpeople or stepsize is not a positive integer. Find the winner of the Josephus problem for numpeople and a stepsize. Args: numpeople int: Number of people. stepsize int: Step size for elimination. Returns: int: The position of the last person remaining 1based index. Examples: findwinner7, 3 4 findwinner10, 2 5 Solve the Josephus problem for numpeople and a stepsize iteratively. Args: numpeople int: The number of people in the circle. stepsize int: The number of steps to take before eliminating someone. Returns: int: The position of the last person standing. Examples: josephusiterative5, 2 3 josephusiterative7, 3 4","Completions":"def josephus_recursive(num_people: int, step_size: int) -> int:\n \"\"\"\n Solve the Josephus problem for num_people and a step_size recursively.\n\n Args:\n num_people: A positive integer representing the number of people.\n step_size: A positive integer representing the step size for elimination.\n\n Returns:\n The position of the last person remaining.\n\n Raises:\n ValueError: If num_people or step_size is not a positive integer.\n\n Examples:\n >>> josephus_recursive(7, 3)\n 3\n >>> josephus_recursive(10, 2)\n 4\n >>> josephus_recursive(0, 2)\n Traceback (most recent call last):\n ...\n ValueError: num_people or step_size is not a positive integer.\n >>> josephus_recursive(1.9, 2)\n Traceback (most recent call last):\n ...\n ValueError: num_people or step_size is not a positive integer.\n >>> josephus_recursive(-2, 2)\n Traceback (most recent call last):\n ...\n ValueError: num_people or step_size is not a positive integer.\n >>> josephus_recursive(7, 0)\n Traceback (most recent call last):\n ...\n ValueError: num_people or step_size is not a positive integer.\n >>> josephus_recursive(7, -2)\n Traceback (most recent call last):\n ...\n ValueError: num_people or step_size is not a positive integer.\n >>> josephus_recursive(1_000, 0.01)\n Traceback (most recent call last):\n ...\n ValueError: num_people or step_size is not a positive integer.\n >>> josephus_recursive(\"cat\", \"dog\")\n Traceback (most recent call last):\n ...\n ValueError: num_people or step_size is not a positive integer.\n \"\"\"\n if (\n not isinstance(num_people, int)\n or not isinstance(step_size, int)\n or num_people <= 0\n or step_size <= 0\n ):\n raise ValueError(\"num_people or step_size is not a positive integer.\")\n\n if num_people == 1:\n return 0\n\n return (josephus_recursive(num_people - 1, step_size) + step_size) % num_people\n\n\ndef find_winner(num_people: int, step_size: int) -> int:\n \"\"\"\n Find the winner of the Josephus problem for num_people and a step_size.\n\n Args:\n num_people (int): Number of people.\n step_size (int): Step size for elimination.\n\n Returns:\n int: The position of the last person remaining (1-based index).\n\n Examples:\n >>> find_winner(7, 3)\n 4\n >>> find_winner(10, 2)\n 5\n \"\"\"\n return josephus_recursive(num_people, step_size) + 1\n\n\ndef josephus_iterative(num_people: int, step_size: int) -> int:\n \"\"\"\n Solve the Josephus problem for num_people and a step_size iteratively.\n\n Args:\n num_people (int): The number of people in the circle.\n step_size (int): The number of steps to take before eliminating someone.\n\n Returns:\n int: The position of the last person standing.\n\n Examples:\n >>> josephus_iterative(5, 2)\n 3\n >>> josephus_iterative(7, 3)\n 4\n \"\"\"\n circle = list(range(1, num_people + 1))\n current = 0\n\n while len(circle) > 1:\n current = (current + step_size - 1) % len(circle)\n circle.pop(current)\n\n return circle[0]\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Juggler Sequence Juggler sequence start with any positive integer n. The next term is obtained as follows: If n term is even, the next term is floor value of square root of n . If n is odd, the next term is floor value of 3 time the square root of n. https:en.wikipedia.orgwikiJugglersequence Author : Akshay Dubey https:github.comitsAkshayDubey jugglersequence0 Traceback most recent call last: ... ValueError: Input value of number0 must be a positive integer jugglersequence1 1 jugglersequence2 2, 1 jugglersequence3 3, 5, 11, 36, 6, 2, 1 jugglersequence5 5, 11, 36, 6, 2, 1 jugglersequence10 10, 3, 5, 11, 36, 6, 2, 1 jugglersequence25 25, 125, 1397, 52214, 228, 15, 58, 7, 18, 4, 2, 1 jugglersequence6.0 Traceback most recent call last: ... TypeError: Input value of number6.0 must be an integer jugglersequence1 Traceback most recent call last: ... ValueError: Input value of number1 must be a positive integer","Completions":"# Author : Akshay Dubey (https:\/\/github.com\/itsAkshayDubey)\nimport math\n\n\ndef juggler_sequence(number: int) -> list[int]:\n \"\"\"\n >>> juggler_sequence(0)\n Traceback (most recent call last):\n ...\n ValueError: Input value of [number=0] must be a positive integer\n >>> juggler_sequence(1)\n [1]\n >>> juggler_sequence(2)\n [2, 1]\n >>> juggler_sequence(3)\n [3, 5, 11, 36, 6, 2, 1]\n >>> juggler_sequence(5)\n [5, 11, 36, 6, 2, 1]\n >>> juggler_sequence(10)\n [10, 3, 5, 11, 36, 6, 2, 1]\n >>> juggler_sequence(25)\n [25, 125, 1397, 52214, 228, 15, 58, 7, 18, 4, 2, 1]\n >>> juggler_sequence(6.0)\n Traceback (most recent call last):\n ...\n TypeError: Input value of [number=6.0] must be an integer\n >>> juggler_sequence(-1)\n Traceback (most recent call last):\n ...\n ValueError: Input value of [number=-1] must be a positive integer\n \"\"\"\n if not isinstance(number, int):\n msg = f\"Input value of [number={number}] must be an integer\"\n raise TypeError(msg)\n if number < 1:\n msg = f\"Input value of [number={number}] must be a positive integer\"\n raise ValueError(msg)\n sequence = [number]\n while number != 1:\n if number % 2 == 0:\n number = math.floor(math.sqrt(number))\n else:\n number = math.floor(\n math.sqrt(number) * math.sqrt(number) * math.sqrt(number)\n )\n sequence.append(number)\n return sequence\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Multiply two numbers using Karatsuba algorithm def karatsubaa: int, b: int int: if lenstra 1 or lenstrb 1: return a b m1 maxlenstra, lenstrb m2 m1 2 a1, a2 divmoda, 10m2 b1, b2 divmodb, 10m2 x karatsubaa2, b2 y karatsubaa1 a2, b1 b2 z karatsubaa1, b1 return z 10 2 m2 y z x 10 m2 x def main: printkaratsuba15463, 23489 if name main: main","Completions":"def karatsuba(a: int, b: int) -> int:\n \"\"\"\n >>> karatsuba(15463, 23489) == 15463 * 23489\n True\n >>> karatsuba(3, 9) == 3 * 9\n True\n \"\"\"\n if len(str(a)) == 1 or len(str(b)) == 1:\n return a * b\n\n m1 = max(len(str(a)), len(str(b)))\n m2 = m1 \/\/ 2\n\n a1, a2 = divmod(a, 10**m2)\n b1, b2 = divmod(b, 10**m2)\n\n x = karatsuba(a2, b2)\n y = karatsuba((a1 + a2), (b1 + b2))\n z = karatsuba(a1, b1)\n\n return (z * 10 ** (2 * m2)) + ((y - z - x) * 10 ** (m2)) + (x)\n\n\ndef main():\n print(karatsuba(15463, 23489))\n\n\nif __name__ == \"__main__\":\n main()\n"} +{"Prompt":"Finds k'th lexicographic permutation in increasing order of 0,1,2,...n1 in On2 time. Examples: First permutation is always 0,1,2,...n kthpermutation0,5 0, 1, 2, 3, 4 The order of permutation of 0,1,2,3 is 0,1,2,3, 0,1,3,2, 0,2,1,3, 0,2,3,1, 0,3,1,2, 0,3,2,1, 1,0,2,3, 1,0,3,2, 1,2,0,3, 1,2,3,0, 1,3,0,2 kthpermutation10,4 1, 3, 0, 2 Factorails from 1! to n1! Find permutation","Completions":"def kth_permutation(k, n):\n \"\"\"\n Finds k'th lexicographic permutation (in increasing order) of\n 0,1,2,...n-1 in O(n^2) time.\n\n Examples:\n First permutation is always 0,1,2,...n\n >>> kth_permutation(0,5)\n [0, 1, 2, 3, 4]\n\n The order of permutation of 0,1,2,3 is [0,1,2,3], [0,1,3,2], [0,2,1,3],\n [0,2,3,1], [0,3,1,2], [0,3,2,1], [1,0,2,3], [1,0,3,2], [1,2,0,3],\n [1,2,3,0], [1,3,0,2]\n >>> kth_permutation(10,4)\n [1, 3, 0, 2]\n \"\"\"\n # Factorails from 1! to (n-1)!\n factorials = [1]\n for i in range(2, n):\n factorials.append(factorials[-1] * i)\n assert 0 <= k < factorials[-1] * n, \"k out of bounds\"\n\n permutation = []\n elements = list(range(n))\n\n # Find permutation\n while factorials:\n factorial = factorials.pop()\n number, k = divmod(k, factorial)\n permutation.append(elements[number])\n elements.remove(elements[number])\n permutation.append(elements[0])\n\n return permutation\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Author: Abhijeeth S Reduces large number to a more manageable number res5, 7 4.892790030352132 res0, 5 0 res3, 0 1 res1, 5 Traceback most recent call last: ... ValueError: math domain error We use the relation xy ylog10x, where 10 is the base. Read two numbers from input and typecast them to int using map function. Here x is the base and y is the power. We find the log of each number, using the function res, which takes two arguments. We check for the largest number","Completions":"# Author: Abhijeeth S\n\nimport math\n\n\ndef res(x, y):\n \"\"\"\n Reduces large number to a more manageable number\n >>> res(5, 7)\n 4.892790030352132\n >>> res(0, 5)\n 0\n >>> res(3, 0)\n 1\n >>> res(-1, 5)\n Traceback (most recent call last):\n ...\n ValueError: math domain error\n \"\"\"\n if 0 not in (x, y):\n # We use the relation x^y = y*log10(x), where 10 is the base.\n return y * math.log10(x)\n else:\n if x == 0: # 0 raised to any number is 0\n return 0\n elif y == 0:\n return 1 # any number raised to 0 is 1\n raise AssertionError(\"This should never happen\")\n\n\nif __name__ == \"__main__\": # Main function\n # Read two numbers from input and typecast them to int using map function.\n # Here x is the base and y is the power.\n prompt = \"Enter the base and the power separated by a comma: \"\n x1, y1 = map(int, input(prompt).split(\",\"))\n x2, y2 = map(int, input(prompt).split(\",\"))\n\n # We find the log of each number, using the function res(), which takes two\n # arguments.\n res1 = res(x1, y1)\n res2 = res(x2, y2)\n\n # We check for the largest number\n if res1 > res2:\n print(\"Largest number is\", x1, \"^\", y1)\n elif res2 > res1:\n print(\"Largest number is\", x2, \"^\", y2)\n else:\n print(\"Both are equal\")\n"} +{"Prompt":"Find the least common multiple of two numbers. Learn more: https:en.wikipedia.orgwikiLeastcommonmultiple leastcommonmultipleslow5, 2 10 leastcommonmultipleslow12, 76 228 Find the least common multiple of two numbers. https:en.wikipedia.orgwikiLeastcommonmultipleUsingthegreatestcommondivisor leastcommonmultiplefast5,2 10 leastcommonmultiplefast12,76 228","Completions":"import unittest\nfrom timeit import timeit\n\nfrom maths.greatest_common_divisor import greatest_common_divisor\n\n\ndef least_common_multiple_slow(first_num: int, second_num: int) -> int:\n \"\"\"\n Find the least common multiple of two numbers.\n\n Learn more: https:\/\/en.wikipedia.org\/wiki\/Least_common_multiple\n\n >>> least_common_multiple_slow(5, 2)\n 10\n >>> least_common_multiple_slow(12, 76)\n 228\n \"\"\"\n max_num = first_num if first_num >= second_num else second_num\n common_mult = max_num\n while (common_mult % first_num > 0) or (common_mult % second_num > 0):\n common_mult += max_num\n return common_mult\n\n\ndef least_common_multiple_fast(first_num: int, second_num: int) -> int:\n \"\"\"\n Find the least common multiple of two numbers.\n https:\/\/en.wikipedia.org\/wiki\/Least_common_multiple#Using_the_greatest_common_divisor\n >>> least_common_multiple_fast(5,2)\n 10\n >>> least_common_multiple_fast(12,76)\n 228\n \"\"\"\n return first_num \/\/ greatest_common_divisor(first_num, second_num) * second_num\n\n\ndef benchmark():\n setup = (\n \"from __main__ import least_common_multiple_slow, least_common_multiple_fast\"\n )\n print(\n \"least_common_multiple_slow():\",\n timeit(\"least_common_multiple_slow(1000, 999)\", setup=setup),\n )\n print(\n \"least_common_multiple_fast():\",\n timeit(\"least_common_multiple_fast(1000, 999)\", setup=setup),\n )\n\n\nclass TestLeastCommonMultiple(unittest.TestCase):\n test_inputs = (\n (10, 20),\n (13, 15),\n (4, 31),\n (10, 42),\n (43, 34),\n (5, 12),\n (12, 25),\n (10, 25),\n (6, 9),\n )\n expected_results = (20, 195, 124, 210, 1462, 60, 300, 50, 18)\n\n def test_lcm_function(self):\n for i, (first_num, second_num) in enumerate(self.test_inputs):\n slow_result = least_common_multiple_slow(first_num, second_num)\n fast_result = least_common_multiple_fast(first_num, second_num)\n with self.subTest(i=i):\n assert slow_result == self.expected_results[i]\n assert fast_result == self.expected_results[i]\n\n\nif __name__ == \"__main__\":\n benchmark()\n unittest.main()\n"} +{"Prompt":"Approximates the arc length of a line segment by treating the curve as a sequence of linear lines and summing their lengths :param fnc: a function which defines a curve :param xstart: left end point to indicate the start of line segment :param xend: right end point to indicate end of line segment :param steps: an accuracy gauge; more steps increases accuracy :return: a float representing the length of the curve def fx: ... return x flinelengthf, 0, 1, 10:.6f '1.414214' def fx: ... return 1 flinelengthf, 5.5, 4.5:.6f '10.000000' def fx: ... return math.sin5 x math.cos10 x x x10 flinelengthf, 0.0, 10.0, 10000:.6f '69.534930' Approximates curve as a sequence of linear lines and sums their length Increment step","Completions":"from __future__ import annotations\n\nimport math\nfrom collections.abc import Callable\n\n\ndef line_length(\n fnc: Callable[[float], float],\n x_start: float,\n x_end: float,\n steps: int = 100,\n) -> float:\n \"\"\"\n Approximates the arc length of a line segment by treating the curve as a\n sequence of linear lines and summing their lengths\n :param fnc: a function which defines a curve\n :param x_start: left end point to indicate the start of line segment\n :param x_end: right end point to indicate end of line segment\n :param steps: an accuracy gauge; more steps increases accuracy\n :return: a float representing the length of the curve\n\n >>> def f(x):\n ... return x\n >>> f\"{line_length(f, 0, 1, 10):.6f}\"\n '1.414214'\n\n >>> def f(x):\n ... return 1\n >>> f\"{line_length(f, -5.5, 4.5):.6f}\"\n '10.000000'\n\n >>> def f(x):\n ... return math.sin(5 * x) + math.cos(10 * x) + x * x\/10\n >>> f\"{line_length(f, 0.0, 10.0, 10000):.6f}\"\n '69.534930'\n \"\"\"\n\n x1 = x_start\n fx1 = fnc(x_start)\n length = 0.0\n\n for _ in range(steps):\n # Approximates curve as a sequence of linear lines and sums their length\n x2 = (x_end - x_start) \/ steps + x1\n fx2 = fnc(x2)\n length += math.hypot(x2 - x1, fx2 - fx1)\n\n # Increment step\n x1 = x2\n fx1 = fx2\n\n return length\n\n\nif __name__ == \"__main__\":\n\n def f(x):\n return math.sin(10 * x)\n\n print(\"f(x) = sin(10 * x)\")\n print(\"The length of the curve from x = -10 to x = 10 is:\")\n i = 10\n while i <= 100000:\n print(f\"With {i} steps: {line_length(f, -10, 10, i)}\")\n i *= 10\n"} +{"Prompt":"Liouville Lambda Function The Liouville Lambda function, denoted by n and n is 1 if n is the product of an even number of prime numbers, and 1 if it is the product of an odd number of primes. https:en.wikipedia.orgwikiLiouvillefunction Author : Akshay Dubey https:github.comitsAkshayDubey This functions takes an integer number as input. returns 1 if n has even number of prime factors and 1 otherwise. liouvillelambda10 1 liouvillelambda11 1 liouvillelambda0 Traceback most recent call last: ... ValueError: Input must be a positive integer liouvillelambda1 Traceback most recent call last: ... ValueError: Input must be a positive integer liouvillelambda11.0 Traceback most recent call last: ... TypeError: Input value of number11.0 must be an integer","Completions":"# Author : Akshay Dubey (https:\/\/github.com\/itsAkshayDubey)\nfrom maths.prime_factors import prime_factors\n\n\ndef liouville_lambda(number: int) -> int:\n \"\"\"\n This functions takes an integer number as input.\n returns 1 if n has even number of prime factors and -1 otherwise.\n >>> liouville_lambda(10)\n 1\n >>> liouville_lambda(11)\n -1\n >>> liouville_lambda(0)\n Traceback (most recent call last):\n ...\n ValueError: Input must be a positive integer\n >>> liouville_lambda(-1)\n Traceback (most recent call last):\n ...\n ValueError: Input must be a positive integer\n >>> liouville_lambda(11.0)\n Traceback (most recent call last):\n ...\n TypeError: Input value of [number=11.0] must be an integer\n \"\"\"\n if not isinstance(number, int):\n msg = f\"Input value of [number={number}] must be an integer\"\n raise TypeError(msg)\n if number < 1:\n raise ValueError(\"Input must be a positive integer\")\n return -1 if len(prime_factors(number)) % 2 else 1\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"In mathematics, the LucasLehmer test LLT is a primality test for Mersenne numbers. https:en.wikipedia.orgwikiLucasE28093Lehmerprimalitytest A Mersenne number is a number that is one less than a power of two. That is Mp 2p 1 https:en.wikipedia.orgwikiMersenneprime The LucasLehmer test is the primality test used by the Great Internet Mersenne Prime Search GIMPS to locate large primes. Primality test 2p 1 Return true if 2p 1 is prime lucaslehmertestp7 True lucaslehmertestp11 False M11 211 1 2047 23 89","Completions":"# Primality test 2^p - 1\n# Return true if 2^p - 1 is prime\ndef lucas_lehmer_test(p: int) -> bool:\n \"\"\"\n >>> lucas_lehmer_test(p=7)\n True\n\n >>> lucas_lehmer_test(p=11)\n False\n\n # M_11 = 2^11 - 1 = 2047 = 23 * 89\n \"\"\"\n\n if p < 2:\n raise ValueError(\"p should not be less than 2!\")\n elif p == 2:\n return True\n\n s = 4\n m = (1 << p) - 1\n for _ in range(p - 2):\n s = ((s * s) - 2) % m\n return s == 0\n\n\nif __name__ == \"__main__\":\n print(lucas_lehmer_test(7))\n print(lucas_lehmer_test(11))\n"} +{"Prompt":"https:en.wikipedia.orgwikiLucasnumber Returns the nth lucas number recursivelucasnumber1 1 recursivelucasnumber20 15127 recursivelucasnumber0 2 recursivelucasnumber25 167761 recursivelucasnumber1.5 Traceback most recent call last: ... TypeError: recursivelucasnumber accepts only integer arguments. Returns the nth lucas number dynamiclucasnumber1 1 dynamiclucasnumber20 15127 dynamiclucasnumber0 2 dynamiclucasnumber25 167761 dynamiclucasnumber1.5 Traceback most recent call last: ... TypeError: dynamiclucasnumber accepts only integer arguments.","Completions":"def recursive_lucas_number(n_th_number: int) -> int:\n \"\"\"\n Returns the nth lucas number\n >>> recursive_lucas_number(1)\n 1\n >>> recursive_lucas_number(20)\n 15127\n >>> recursive_lucas_number(0)\n 2\n >>> recursive_lucas_number(25)\n 167761\n >>> recursive_lucas_number(-1.5)\n Traceback (most recent call last):\n ...\n TypeError: recursive_lucas_number accepts only integer arguments.\n \"\"\"\n if not isinstance(n_th_number, int):\n raise TypeError(\"recursive_lucas_number accepts only integer arguments.\")\n if n_th_number == 0:\n return 2\n if n_th_number == 1:\n return 1\n\n return recursive_lucas_number(n_th_number - 1) + recursive_lucas_number(\n n_th_number - 2\n )\n\n\ndef dynamic_lucas_number(n_th_number: int) -> int:\n \"\"\"\n Returns the nth lucas number\n >>> dynamic_lucas_number(1)\n 1\n >>> dynamic_lucas_number(20)\n 15127\n >>> dynamic_lucas_number(0)\n 2\n >>> dynamic_lucas_number(25)\n 167761\n >>> dynamic_lucas_number(-1.5)\n Traceback (most recent call last):\n ...\n TypeError: dynamic_lucas_number accepts only integer arguments.\n \"\"\"\n if not isinstance(n_th_number, int):\n raise TypeError(\"dynamic_lucas_number accepts only integer arguments.\")\n a, b = 2, 1\n for _ in range(n_th_number):\n a, b = b, a + b\n return a\n\n\nif __name__ == \"__main__\":\n from doctest import testmod\n\n testmod()\n n = int(input(\"Enter the number of terms in lucas series:\\n\").strip())\n print(\"Using recursive function to calculate lucas series:\")\n print(\" \".join(str(recursive_lucas_number(i)) for i in range(n)))\n print(\"\\nUsing dynamic function to calculate lucas series:\")\n print(\" \".join(str(dynamic_lucas_number(i)) for i in range(n)))\n"} +{"Prompt":"https:en.wikipedia.orgwikiTaylorseriesTrigonometricfunctions Finds the maclaurin approximation of sin :param theta: the angle to which sin is found :param accuracy: the degree of accuracy wanted minimum :return: the value of sine in radians from math import isclose, sin allisclosemaclaurinsinx, 50, sinx for x in range25, 25 True maclaurinsin10 0.5440211108893691 maclaurinsin10 0.5440211108893704 maclaurinsin10, 15 0.544021110889369 maclaurinsin10, 15 0.5440211108893704 maclaurinsin10 Traceback most recent call last: ... ValueError: maclaurinsin requires either an int or float for theta maclaurinsin10, 30 Traceback most recent call last: ... ValueError: maclaurinsin requires a positive int for accuracy maclaurinsin10, 30.5 Traceback most recent call last: ... ValueError: maclaurinsin requires a positive int for accuracy maclaurinsin10, 30 Traceback most recent call last: ... ValueError: maclaurinsin requires a positive int for accuracy Finds the maclaurin approximation of cos :param theta: the angle to which cos is found :param accuracy: the degree of accuracy wanted :return: the value of cosine in radians from math import isclose, cos allisclosemaclaurincosx, 50, cosx for x in range25, 25 True maclaurincos5 0.2836621854632268 maclaurincos5 0.2836621854632265 maclaurincos10, 15 0.8390715290764524 maclaurincos10, 15 0.8390715290764521 maclaurincos10 Traceback most recent call last: ... ValueError: maclaurincos requires either an int or float for theta maclaurincos10, 30 Traceback most recent call last: ... ValueError: maclaurincos requires a positive int for accuracy maclaurincos10, 30.5 Traceback most recent call last: ... ValueError: maclaurincos requires a positive int for accuracy maclaurincos10, 30 Traceback most recent call last: ... ValueError: maclaurincos requires a positive int for accuracy","Completions":"from math import factorial, pi\n\n\ndef maclaurin_sin(theta: float, accuracy: int = 30) -> float:\n \"\"\"\n Finds the maclaurin approximation of sin\n\n :param theta: the angle to which sin is found\n :param accuracy: the degree of accuracy wanted minimum\n :return: the value of sine in radians\n\n\n >>> from math import isclose, sin\n >>> all(isclose(maclaurin_sin(x, 50), sin(x)) for x in range(-25, 25))\n True\n >>> maclaurin_sin(10)\n -0.5440211108893691\n >>> maclaurin_sin(-10)\n 0.5440211108893704\n >>> maclaurin_sin(10, 15)\n -0.544021110889369\n >>> maclaurin_sin(-10, 15)\n 0.5440211108893704\n >>> maclaurin_sin(\"10\")\n Traceback (most recent call last):\n ...\n ValueError: maclaurin_sin() requires either an int or float for theta\n >>> maclaurin_sin(10, -30)\n Traceback (most recent call last):\n ...\n ValueError: maclaurin_sin() requires a positive int for accuracy\n >>> maclaurin_sin(10, 30.5)\n Traceback (most recent call last):\n ...\n ValueError: maclaurin_sin() requires a positive int for accuracy\n >>> maclaurin_sin(10, \"30\")\n Traceback (most recent call last):\n ...\n ValueError: maclaurin_sin() requires a positive int for accuracy\n \"\"\"\n\n if not isinstance(theta, (int, float)):\n raise ValueError(\"maclaurin_sin() requires either an int or float for theta\")\n\n if not isinstance(accuracy, int) or accuracy <= 0:\n raise ValueError(\"maclaurin_sin() requires a positive int for accuracy\")\n\n theta = float(theta)\n div = theta \/\/ (2 * pi)\n theta -= 2 * div * pi\n return sum(\n (-1) ** r * theta ** (2 * r + 1) \/ factorial(2 * r + 1) for r in range(accuracy)\n )\n\n\ndef maclaurin_cos(theta: float, accuracy: int = 30) -> float:\n \"\"\"\n Finds the maclaurin approximation of cos\n\n :param theta: the angle to which cos is found\n :param accuracy: the degree of accuracy wanted\n :return: the value of cosine in radians\n\n\n >>> from math import isclose, cos\n >>> all(isclose(maclaurin_cos(x, 50), cos(x)) for x in range(-25, 25))\n True\n >>> maclaurin_cos(5)\n 0.2836621854632268\n >>> maclaurin_cos(-5)\n 0.2836621854632265\n >>> maclaurin_cos(10, 15)\n -0.8390715290764524\n >>> maclaurin_cos(-10, 15)\n -0.8390715290764521\n >>> maclaurin_cos(\"10\")\n Traceback (most recent call last):\n ...\n ValueError: maclaurin_cos() requires either an int or float for theta\n >>> maclaurin_cos(10, -30)\n Traceback (most recent call last):\n ...\n ValueError: maclaurin_cos() requires a positive int for accuracy\n >>> maclaurin_cos(10, 30.5)\n Traceback (most recent call last):\n ...\n ValueError: maclaurin_cos() requires a positive int for accuracy\n >>> maclaurin_cos(10, \"30\")\n Traceback (most recent call last):\n ...\n ValueError: maclaurin_cos() requires a positive int for accuracy\n \"\"\"\n\n if not isinstance(theta, (int, float)):\n raise ValueError(\"maclaurin_cos() requires either an int or float for theta\")\n\n if not isinstance(accuracy, int) or accuracy <= 0:\n raise ValueError(\"maclaurin_cos() requires a positive int for accuracy\")\n\n theta = float(theta)\n div = theta \/\/ (2 * pi)\n theta -= 2 * div * pi\n return sum((-1) ** r * theta ** (2 * r) \/ factorial(2 * r) for r in range(accuracy))\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n\n print(maclaurin_sin(10))\n print(maclaurin_sin(-10))\n print(maclaurin_sin(10, 15))\n print(maclaurin_sin(-10, 15))\n\n print(maclaurin_cos(5))\n print(maclaurin_cos(-5))\n print(maclaurin_cos(10, 15))\n print(maclaurin_cos(-10, 15))\n"} +{"Prompt":"Expectts two list of numbers representing two points in the same ndimensional space https:en.wikipedia.orgwikiTaxicabgeometry manhattandistance1,1, 2,2 2.0 manhattandistance1.5,1.5, 2,2 1.0 manhattandistance1.5,1.5, 2.5,2 1.5 manhattandistance3, 3, 3, 0, 0, 0 9.0 manhattandistance1,1, None Traceback most recent call last: ... ValueError: Missing an input manhattandistance1,1, 2, 2, 2 Traceback most recent call last: ... ValueError: Both points must be in the same ndimensional space manhattandistance1,one, 2, 2, 2 Traceback most recent call last: ... TypeError: Expected a list of numbers as input, found str manhattandistance1, 2, 2, 2 Traceback most recent call last: ... TypeError: Expected a list of numbers as input, found int manhattandistance1,1, notalist Traceback most recent call last: ... TypeError: Expected a list of numbers as input, found str validatepointNone Traceback most recent call last: ... ValueError: Missing an input validatepoint1,one Traceback most recent call last: ... TypeError: Expected a list of numbers as input, found str validatepoint1 Traceback most recent call last: ... TypeError: Expected a list of numbers as input, found int validatepointnotalist Traceback most recent call last: ... TypeError: Expected a list of numbers as input, found str Version with one liner manhattandistanceoneliner1,1, 2,2 2.0 manhattandistanceoneliner1.5,1.5, 2,2 1.0 manhattandistanceoneliner1.5,1.5, 2.5,2 1.5 manhattandistanceoneliner3, 3, 3, 0, 0, 0 9.0 manhattandistanceoneliner1,1, None Traceback most recent call last: ... ValueError: Missing an input manhattandistanceoneliner1,1, 2, 2, 2 Traceback most recent call last: ... ValueError: Both points must be in the same ndimensional space manhattandistanceoneliner1,one, 2, 2, 2 Traceback most recent call last: ... TypeError: Expected a list of numbers as input, found str manhattandistanceoneliner1, 2, 2, 2 Traceback most recent call last: ... TypeError: Expected a list of numbers as input, found int manhattandistanceoneliner1,1, notalist Traceback most recent call last: ... TypeError: Expected a list of numbers as input, found str","Completions":"def manhattan_distance(point_a: list, point_b: list) -> float:\n \"\"\"\n Expectts two list of numbers representing two points in the same\n n-dimensional space\n\n https:\/\/en.wikipedia.org\/wiki\/Taxicab_geometry\n\n >>> manhattan_distance([1,1], [2,2])\n 2.0\n >>> manhattan_distance([1.5,1.5], [2,2])\n 1.0\n >>> manhattan_distance([1.5,1.5], [2.5,2])\n 1.5\n >>> manhattan_distance([-3, -3, -3], [0, 0, 0])\n 9.0\n >>> manhattan_distance([1,1], None)\n Traceback (most recent call last):\n ...\n ValueError: Missing an input\n >>> manhattan_distance([1,1], [2, 2, 2])\n Traceback (most recent call last):\n ...\n ValueError: Both points must be in the same n-dimensional space\n >>> manhattan_distance([1,\"one\"], [2, 2, 2])\n Traceback (most recent call last):\n ...\n TypeError: Expected a list of numbers as input, found str\n >>> manhattan_distance(1, [2, 2, 2])\n Traceback (most recent call last):\n ...\n TypeError: Expected a list of numbers as input, found int\n >>> manhattan_distance([1,1], \"not_a_list\")\n Traceback (most recent call last):\n ...\n TypeError: Expected a list of numbers as input, found str\n \"\"\"\n\n _validate_point(point_a)\n _validate_point(point_b)\n if len(point_a) != len(point_b):\n raise ValueError(\"Both points must be in the same n-dimensional space\")\n\n return float(sum(abs(a - b) for a, b in zip(point_a, point_b)))\n\n\ndef _validate_point(point: list[float]) -> None:\n \"\"\"\n >>> _validate_point(None)\n Traceback (most recent call last):\n ...\n ValueError: Missing an input\n >>> _validate_point([1,\"one\"])\n Traceback (most recent call last):\n ...\n TypeError: Expected a list of numbers as input, found str\n >>> _validate_point(1)\n Traceback (most recent call last):\n ...\n TypeError: Expected a list of numbers as input, found int\n >>> _validate_point(\"not_a_list\")\n Traceback (most recent call last):\n ...\n TypeError: Expected a list of numbers as input, found str\n \"\"\"\n if point:\n if isinstance(point, list):\n for item in point:\n if not isinstance(item, (int, float)):\n msg = (\n \"Expected a list of numbers as input, found \"\n f\"{type(item).__name__}\"\n )\n raise TypeError(msg)\n else:\n msg = f\"Expected a list of numbers as input, found {type(point).__name__}\"\n raise TypeError(msg)\n else:\n raise ValueError(\"Missing an input\")\n\n\ndef manhattan_distance_one_liner(point_a: list, point_b: list) -> float:\n \"\"\"\n Version with one liner\n\n >>> manhattan_distance_one_liner([1,1], [2,2])\n 2.0\n >>> manhattan_distance_one_liner([1.5,1.5], [2,2])\n 1.0\n >>> manhattan_distance_one_liner([1.5,1.5], [2.5,2])\n 1.5\n >>> manhattan_distance_one_liner([-3, -3, -3], [0, 0, 0])\n 9.0\n >>> manhattan_distance_one_liner([1,1], None)\n Traceback (most recent call last):\n ...\n ValueError: Missing an input\n >>> manhattan_distance_one_liner([1,1], [2, 2, 2])\n Traceback (most recent call last):\n ...\n ValueError: Both points must be in the same n-dimensional space\n >>> manhattan_distance_one_liner([1,\"one\"], [2, 2, 2])\n Traceback (most recent call last):\n ...\n TypeError: Expected a list of numbers as input, found str\n >>> manhattan_distance_one_liner(1, [2, 2, 2])\n Traceback (most recent call last):\n ...\n TypeError: Expected a list of numbers as input, found int\n >>> manhattan_distance_one_liner([1,1], \"not_a_list\")\n Traceback (most recent call last):\n ...\n TypeError: Expected a list of numbers as input, found str\n \"\"\"\n\n _validate_point(point_a)\n _validate_point(point_b)\n if len(point_a) != len(point_b):\n raise ValueError(\"Both points must be in the same n-dimensional space\")\n\n return float(sum(abs(x - y) for x, y in zip(point_a, point_b)))\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Matrix Exponentiation import timeit class Matrix: def initself, arg: if isinstancearg, list: Initializes a matrix identical to the one provided. self.t arg self.n lenarg else: Initializes a square matrix of the given size and set values to zero. self.n arg self.t 0 for in rangeself.n for in rangeself.n def mulself, b: matrix Matrixself.n for i in rangeself.n: for j in rangeself.n: for k in rangeself.n: matrix.tij self.tik b.tkj return matrix def modularexponentiationa, b: matrix Matrix1, 0, 0, 1 while b 0: if b 1: matrix a a a b 1 return matrix def fibonacciwithmatrixexponentiationn, f1, f2: Trivial Cases if n 1: return f1 elif n 2: return f2 matrix Matrix1, 1, 1, 0 matrix modularexponentiationmatrix, n 2 return f2 matrix.t00 f1 matrix.t01 def simplefibonaccin, f1, f2: Trivial Cases if n 1: return f1 elif n 2: return f2 fn1 f1 fn2 f2 n 2 while n 0: fn1, fn2 fn1 fn2, fn1 n 1 return fn1 def matrixexponentiationtime: setup from random import randint from main import fibonacciwithmatrixexponentiation code simplefibonaccirandint1,70000, 1, 1 exectime timeit.timeitsetupsetup, stmtcode, number100 print Without matrix exponentiation the average execution time is , exectime 100 return exectime def main: matrixexponentiationtime simplefibonaccitime if name main: main","Completions":"import timeit\n\n\"\"\"\nMatrix Exponentiation is a technique to solve linear recurrences in logarithmic time.\nYou read more about it here:\nhttps:\/\/zobayer.blogspot.com\/2010\/11\/matrix-exponentiation.html\nhttps:\/\/www.hackerearth.com\/practice\/notes\/matrix-exponentiation-1\/\n\"\"\"\n\n\nclass Matrix:\n def __init__(self, arg):\n if isinstance(arg, list): # Initializes a matrix identical to the one provided.\n self.t = arg\n self.n = len(arg)\n else: # Initializes a square matrix of the given size and set values to zero.\n self.n = arg\n self.t = [[0 for _ in range(self.n)] for _ in range(self.n)]\n\n def __mul__(self, b):\n matrix = Matrix(self.n)\n for i in range(self.n):\n for j in range(self.n):\n for k in range(self.n):\n matrix.t[i][j] += self.t[i][k] * b.t[k][j]\n return matrix\n\n\ndef modular_exponentiation(a, b):\n matrix = Matrix([[1, 0], [0, 1]])\n while b > 0:\n if b & 1:\n matrix *= a\n a *= a\n b >>= 1\n return matrix\n\n\ndef fibonacci_with_matrix_exponentiation(n, f1, f2):\n # Trivial Cases\n if n == 1:\n return f1\n elif n == 2:\n return f2\n matrix = Matrix([[1, 1], [1, 0]])\n matrix = modular_exponentiation(matrix, n - 2)\n return f2 * matrix.t[0][0] + f1 * matrix.t[0][1]\n\n\ndef simple_fibonacci(n, f1, f2):\n # Trivial Cases\n if n == 1:\n return f1\n elif n == 2:\n return f2\n\n fn_1 = f1\n fn_2 = f2\n n -= 2\n\n while n > 0:\n fn_1, fn_2 = fn_1 + fn_2, fn_1\n n -= 1\n\n return fn_1\n\n\ndef matrix_exponentiation_time():\n setup = \"\"\"\nfrom random import randint\nfrom __main__ import fibonacci_with_matrix_exponentiation\n\"\"\"\n code = \"fibonacci_with_matrix_exponentiation(randint(1,70000), 1, 1)\"\n exec_time = timeit.timeit(setup=setup, stmt=code, number=100)\n print(\"With matrix exponentiation the average execution time is \", exec_time \/ 100)\n return exec_time\n\n\ndef simple_fibonacci_time():\n setup = \"\"\"\nfrom random import randint\nfrom __main__ import simple_fibonacci\n\"\"\"\n code = \"simple_fibonacci(randint(1,70000), 1, 1)\"\n exec_time = timeit.timeit(setup=setup, stmt=code, number=100)\n print(\n \"Without matrix exponentiation the average execution time is \", exec_time \/ 100\n )\n return exec_time\n\n\ndef main():\n matrix_exponentiation_time()\n simple_fibonacci_time()\n\n\nif __name__ == \"__main__\":\n main()\n"} +{"Prompt":"Given an array of integer elements and an integer 'k', we are required to find the maximum sum of 'k' consecutive elements in the array. Instead of using a nested for loop, in a Brute force approach we will use a technique called 'Window sliding technique' where the nested loops can be converted to a single loop to reduce time complexity. Returns the maximum sum of k consecutive elements arr 1, 4, 2, 10, 2, 3, 1, 0, 20 k 4 maxsuminarrayarr, k 24 k 10 maxsuminarrayarr,k Traceback most recent call last: ... ValueError: Invalid Input arr 1, 4, 2, 10, 2, 13, 1, 0, 2 k 4 maxsuminarrayarr, k 27","Completions":"from __future__ import annotations\n\n\ndef max_sum_in_array(array: list[int], k: int) -> int:\n \"\"\"\n Returns the maximum sum of k consecutive elements\n >>> arr = [1, 4, 2, 10, 2, 3, 1, 0, 20]\n >>> k = 4\n >>> max_sum_in_array(arr, k)\n 24\n >>> k = 10\n >>> max_sum_in_array(arr,k)\n Traceback (most recent call last):\n ...\n ValueError: Invalid Input\n >>> arr = [1, 4, 2, 10, 2, 13, 1, 0, 2]\n >>> k = 4\n >>> max_sum_in_array(arr, k)\n 27\n \"\"\"\n if len(array) < k or k < 0:\n raise ValueError(\"Invalid Input\")\n max_sum = current_sum = sum(array[:k])\n for i in range(len(array) - k):\n current_sum = current_sum - array[i] + array[i + k]\n max_sum = max(max_sum, current_sum)\n return max_sum\n\n\nif __name__ == \"__main__\":\n from doctest import testmod\n from random import randint\n\n testmod()\n array = [randint(-1000, 1000) for i in range(100)]\n k = randint(0, 110)\n print(f\"The maximum sum of {k} consecutive elements is {max_sum_in_array(array,k)}\")\n"} +{"Prompt":"medianoftwoarrays1, 2, 3 2 medianoftwoarrays0, 1.1, 2.5, 1 0.5 medianoftwoarrays, 2.5, 1 1.75 medianoftwoarrays, 0 0 medianoftwoarrays, Traceback most recent call last: ... IndexError: list index out of range","Completions":"from __future__ import annotations\n\n\ndef median_of_two_arrays(nums1: list[float], nums2: list[float]) -> float:\n \"\"\"\n >>> median_of_two_arrays([1, 2], [3])\n 2\n >>> median_of_two_arrays([0, -1.1], [2.5, 1])\n 0.5\n >>> median_of_two_arrays([], [2.5, 1])\n 1.75\n >>> median_of_two_arrays([], [0])\n 0\n >>> median_of_two_arrays([], [])\n Traceback (most recent call last):\n ...\n IndexError: list index out of range\n \"\"\"\n all_numbers = sorted(nums1 + nums2)\n div, mod = divmod(len(all_numbers), 2)\n if mod == 1:\n return all_numbers[div]\n else:\n return (all_numbers[div] + all_numbers[div - 1]) \/ 2\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n array_1 = [float(x) for x in input(\"Enter the elements of first array: \").split()]\n array_2 = [float(x) for x in input(\"Enter the elements of second array: \").split()]\n print(f\"The median of two arrays is: {median_of_two_arrays(array_1, array_2)}\")\n"} +{"Prompt":"This function calculates the Minkowski distance for a given order between two ndimensional points represented as lists. For the case of order 1, the Minkowski distance degenerates to the Manhattan distance. For order 2, the usual Euclidean distance is obtained. https:en.wikipedia.orgwikiMinkowskidistance Note: due to floating point calculation errors the output of this function may be inaccurate. minkowskidistance1.0, 1.0, 2.0, 2.0, 1 2.0 minkowskidistance1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 2 8.0 import numpy as np np.isclose5.0, minkowskidistance5.0, 0.0, 3 True minkowskidistance1.0, 2.0, 1 Traceback most recent call last: ... ValueError: The order must be greater than or equal to 1. minkowskidistance1.0, 1.0, 2.0, 1 Traceback most recent call last: ... ValueError: Both points must have the same dimension.","Completions":"def minkowski_distance(\n point_a: list[float],\n point_b: list[float],\n order: int,\n) -> float:\n \"\"\"\n This function calculates the Minkowski distance for a given order between\n two n-dimensional points represented as lists. For the case of order = 1,\n the Minkowski distance degenerates to the Manhattan distance. For\n order = 2, the usual Euclidean distance is obtained.\n\n https:\/\/en.wikipedia.org\/wiki\/Minkowski_distance\n\n Note: due to floating point calculation errors the output of this\n function may be inaccurate.\n\n >>> minkowski_distance([1.0, 1.0], [2.0, 2.0], 1)\n 2.0\n >>> minkowski_distance([1.0, 2.0, 3.0, 4.0], [5.0, 6.0, 7.0, 8.0], 2)\n 8.0\n >>> import numpy as np\n >>> np.isclose(5.0, minkowski_distance([5.0], [0.0], 3))\n True\n >>> minkowski_distance([1.0], [2.0], -1)\n Traceback (most recent call last):\n ...\n ValueError: The order must be greater than or equal to 1.\n >>> minkowski_distance([1.0], [1.0, 2.0], 1)\n Traceback (most recent call last):\n ...\n ValueError: Both points must have the same dimension.\n \"\"\"\n if order < 1:\n raise ValueError(\"The order must be greater than or equal to 1.\")\n\n if len(point_a) != len(point_b):\n raise ValueError(\"Both points must have the same dimension.\")\n\n return sum(abs(a - b) ** order for a, b in zip(point_a, point_b)) ** (1 \/ order)\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"References: https:en.wikipedia.orgwikiMC3B6biusfunction References: wikipedia:square free number psfblack : True ruff : True Mobius function mobius24 0 mobius1 1 mobius'asd' Traceback most recent call last: ... TypeError: '' not supported between instances of 'int' and 'str' mobius10400 0 mobius10400 1 mobius1424 1 mobius1, '2', 2.0 Traceback most recent call last: ... TypeError: '' not supported between instances of 'int' and 'list'","Completions":"from maths.is_square_free import is_square_free\nfrom maths.prime_factors import prime_factors\n\n\ndef mobius(n: int) -> int:\n \"\"\"\n Mobius function\n >>> mobius(24)\n 0\n >>> mobius(-1)\n 1\n >>> mobius('asd')\n Traceback (most recent call last):\n ...\n TypeError: '<=' not supported between instances of 'int' and 'str'\n >>> mobius(10**400)\n 0\n >>> mobius(10**-400)\n 1\n >>> mobius(-1424)\n 1\n >>> mobius([1, '2', 2.0])\n Traceback (most recent call last):\n ...\n TypeError: '<=' not supported between instances of 'int' and 'list'\n \"\"\"\n factors = prime_factors(n)\n if is_square_free(factors):\n return -1 if len(factors) % 2 else 1\n return 0\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Modular Division : An efficient algorithm for dividing b by a modulo n. GCD Greatest Common Divisor or HCF Highest Common Factor Given three integers a, b, and n, such that gcda,n1 and n1, the algorithm should return an integer x such that 0xn1, and baxmodn that is, baxmodn. Theorem: a has a multiplicative inverse modulo n iff gcda,n 1 This find x ba1 mod n Uses ExtendedEuclid to find the inverse of a modulardivision4,8,5 2 modulardivision3,8,5 1 modulardivision4, 11, 5 4 This function find the inverses of a i.e., a1 invertmodulo2, 5 3 invertmodulo8,7 1 Finding Modular division using invertmodulo This function used the above inversion of a to find x ba1mod n modulardivision24,8,5 2 modulardivision23,8,5 1 modulardivision24, 11, 5 4 Extended Euclid's Algorithm : If d divides a and b and d ax by for integers x and y, then d gcda,b extendedgcd10, 6 2, 1, 2 extendedgcd7, 5 1, 2, 3 extendedgcd function is used when d gcda,b is required in output Extended Euclid extendedeuclid10, 6 1, 2 extendedeuclid7, 5 2, 3 Euclid's Lemma : d divides a and b, if and only if d divides ab and b Euclid's Algorithm greatestcommondivisor7,5 1 Note : In number theory, two integers a and b are said to be relatively prime, mutually prime, or coprime if the only positive integer factor that divides both of them is 1 i.e., gcda,b 1. greatestcommondivisor121, 11 11","Completions":"from __future__ import annotations\n\n\ndef modular_division(a: int, b: int, n: int) -> int:\n \"\"\"\n Modular Division :\n An efficient algorithm for dividing b by a modulo n.\n\n GCD ( Greatest Common Divisor ) or HCF ( Highest Common Factor )\n\n Given three integers a, b, and n, such that gcd(a,n)=1 and n>1, the algorithm should\n return an integer x such that 0\u2264x\u2264n\u22121, and b\/a=x(modn) (that is, b=ax(modn)).\n\n Theorem:\n a has a multiplicative inverse modulo n iff gcd(a,n) = 1\n\n\n This find x = b*a^(-1) mod n\n Uses ExtendedEuclid to find the inverse of a\n\n >>> modular_division(4,8,5)\n 2\n\n >>> modular_division(3,8,5)\n 1\n\n >>> modular_division(4, 11, 5)\n 4\n\n \"\"\"\n assert n > 1\n assert a > 0\n assert greatest_common_divisor(a, n) == 1\n (d, t, s) = extended_gcd(n, a) # Implemented below\n x = (b * s) % n\n return x\n\n\ndef invert_modulo(a: int, n: int) -> int:\n \"\"\"\n This function find the inverses of a i.e., a^(-1)\n\n >>> invert_modulo(2, 5)\n 3\n\n >>> invert_modulo(8,7)\n 1\n\n \"\"\"\n (b, x) = extended_euclid(a, n) # Implemented below\n if b < 0:\n b = (b % n + n) % n\n return b\n\n\n# ------------------ Finding Modular division using invert_modulo -------------------\n\n\ndef modular_division2(a: int, b: int, n: int) -> int:\n \"\"\"\n This function used the above inversion of a to find x = (b*a^(-1))mod n\n\n >>> modular_division2(4,8,5)\n 2\n\n >>> modular_division2(3,8,5)\n 1\n\n >>> modular_division2(4, 11, 5)\n 4\n\n \"\"\"\n s = invert_modulo(a, n)\n x = (b * s) % n\n return x\n\n\ndef extended_gcd(a: int, b: int) -> tuple[int, int, int]:\n \"\"\"\n Extended Euclid's Algorithm : If d divides a and b and d = a*x + b*y for integers x\n and y, then d = gcd(a,b)\n >>> extended_gcd(10, 6)\n (2, -1, 2)\n\n >>> extended_gcd(7, 5)\n (1, -2, 3)\n\n ** extended_gcd function is used when d = gcd(a,b) is required in output\n\n \"\"\"\n assert a >= 0\n assert b >= 0\n\n if b == 0:\n d, x, y = a, 1, 0\n else:\n (d, p, q) = extended_gcd(b, a % b)\n x = q\n y = p - q * (a \/\/ b)\n\n assert a % d == 0\n assert b % d == 0\n assert d == a * x + b * y\n\n return (d, x, y)\n\n\ndef extended_euclid(a: int, b: int) -> tuple[int, int]:\n \"\"\"\n Extended Euclid\n >>> extended_euclid(10, 6)\n (-1, 2)\n\n >>> extended_euclid(7, 5)\n (-2, 3)\n\n \"\"\"\n if b == 0:\n return (1, 0)\n (x, y) = extended_euclid(b, a % b)\n k = a \/\/ b\n return (y, x - k * y)\n\n\ndef greatest_common_divisor(a: int, b: int) -> int:\n \"\"\"\n Euclid's Lemma : d divides a and b, if and only if d divides a-b and b\n Euclid's Algorithm\n\n >>> greatest_common_divisor(7,5)\n 1\n\n Note : In number theory, two integers a and b are said to be relatively prime,\n mutually prime, or co-prime if the only positive integer (factor) that divides\n both of them is 1 i.e., gcd(a,b) = 1.\n\n >>> greatest_common_divisor(121, 11)\n 11\n\n \"\"\"\n if a < b:\n a, b = b, a\n\n while a % b != 0:\n a, b = b, a % b\n\n return b\n\n\nif __name__ == \"__main__\":\n from doctest import testmod\n\n testmod(name=\"modular_division\", verbose=True)\n testmod(name=\"modular_division2\", verbose=True)\n testmod(name=\"invert_modulo\", verbose=True)\n testmod(name=\"extended_gcd\", verbose=True)\n testmod(name=\"extended_euclid\", verbose=True)\n testmod(name=\"greatest_common_divisor\", verbose=True)\n"} +{"Prompt":"Modular Exponential. Modular exponentiation is a type of exponentiation performed over a modulus. For more explanation, please check https:en.wikipedia.orgwikiModularexponentiation Calculate Modular Exponential. def modularexponentialbase: int, power: int, mod: int: if power 0: return 1 base mod result 1 while power 0: if power 1: result result base mod power power 1 base base base mod return result def main:","Completions":"\"\"\"Calculate Modular Exponential.\"\"\"\n\n\ndef modular_exponential(base: int, power: int, mod: int):\n \"\"\"\n >>> modular_exponential(5, 0, 10)\n 1\n >>> modular_exponential(2, 8, 7)\n 4\n >>> modular_exponential(3, -2, 9)\n -1\n \"\"\"\n\n if power < 0:\n return -1\n base %= mod\n result = 1\n\n while power > 0:\n if power & 1:\n result = (result * base) % mod\n power = power >> 1\n base = (base * base) % mod\n\n return result\n\n\ndef main():\n \"\"\"Call Modular Exponential Function.\"\"\"\n print(modular_exponential(3, 200, 13))\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n\n main()\n"} +{"Prompt":"author: MatteoRaso An implementation of the Monte Carlo method used to find pi. 1. Draw a 2x2 square centred at 0,0. 2. Inscribe a circle within the square. 3. For each iteration, place a dot anywhere in the square. a. Record the number of dots within the circle. 4. After all the dots are placed, divide the dots in the circle by the total. 5. Multiply this value by 4 to get your estimate of pi. 6. Print the estimated and numpy value of pi A local function to see if a dot lands in the circle. Our circle has a radius of 1, so a distance greater than 1 would land outside the circle. The proportion of guesses that landed in the circle The ratio of the area for circle to square is pi4. An implementation of the Monte Carlo method to find area under a single variable nonnegative realvalued continuous function, say fx, where x lies within a continuous bounded interval, say minvalue, maxvalue, where minvalue and maxvalue are finite numbers 1. Let x be a uniformly distributed random variable between minvalue to maxvalue 2. Expected value of fx integrate fx from minvalue to maxvaluemaxvalue minvalue 3. Finding expected value of fx: a. Repeatedly draw x from uniform distribution b. Evaluate fx at each of the drawn x values c. Expected value average of the function evaluations 4. Estimated value of integral Expected value maxvalue minvalue 5. Returns estimated value Checks estimation error for areaundercurveestimator function for fx x where x lies within minvalue to maxvalue 1. Calls areaundercurveestimator function 2. Compares with the expected value 3. Prints estimated, expected and error value Represents identity function functiontointegratex for x in 2.0, 1.0, 0.0, 1.0, 2.0 2.0, 1.0, 0.0, 1.0, 2.0 Area under curve y sqrt4 x2 where x lies in 0 to 2 is equal to pi Represents semicircle with radius 2 functiontointegratex for x in 2.0, 0.0, 2.0 0.0, 2.0, 0.0","Completions":"from collections.abc import Callable\nfrom math import pi, sqrt\nfrom random import uniform\nfrom statistics import mean\n\n\ndef pi_estimator(iterations: int):\n \"\"\"\n An implementation of the Monte Carlo method used to find pi.\n 1. Draw a 2x2 square centred at (0,0).\n 2. Inscribe a circle within the square.\n 3. For each iteration, place a dot anywhere in the square.\n a. Record the number of dots within the circle.\n 4. After all the dots are placed, divide the dots in the circle by the total.\n 5. Multiply this value by 4 to get your estimate of pi.\n 6. Print the estimated and numpy value of pi\n \"\"\"\n\n # A local function to see if a dot lands in the circle.\n def is_in_circle(x: float, y: float) -> bool:\n distance_from_centre = sqrt((x**2) + (y**2))\n # Our circle has a radius of 1, so a distance\n # greater than 1 would land outside the circle.\n return distance_from_centre <= 1\n\n # The proportion of guesses that landed in the circle\n proportion = mean(\n int(is_in_circle(uniform(-1.0, 1.0), uniform(-1.0, 1.0)))\n for _ in range(iterations)\n )\n # The ratio of the area for circle to square is pi\/4.\n pi_estimate = proportion * 4\n print(f\"The estimated value of pi is {pi_estimate}\")\n print(f\"The numpy value of pi is {pi}\")\n print(f\"The total error is {abs(pi - pi_estimate)}\")\n\n\ndef area_under_curve_estimator(\n iterations: int,\n function_to_integrate: Callable[[float], float],\n min_value: float = 0.0,\n max_value: float = 1.0,\n) -> float:\n \"\"\"\n An implementation of the Monte Carlo method to find area under\n a single variable non-negative real-valued continuous function,\n say f(x), where x lies within a continuous bounded interval,\n say [min_value, max_value], where min_value and max_value are\n finite numbers\n 1. Let x be a uniformly distributed random variable between min_value to\n max_value\n 2. Expected value of f(x) =\n (integrate f(x) from min_value to max_value)\/(max_value - min_value)\n 3. Finding expected value of f(x):\n a. Repeatedly draw x from uniform distribution\n b. Evaluate f(x) at each of the drawn x values\n c. Expected value = average of the function evaluations\n 4. Estimated value of integral = Expected value * (max_value - min_value)\n 5. Returns estimated value\n \"\"\"\n\n return mean(\n function_to_integrate(uniform(min_value, max_value)) for _ in range(iterations)\n ) * (max_value - min_value)\n\n\ndef area_under_line_estimator_check(\n iterations: int, min_value: float = 0.0, max_value: float = 1.0\n) -> None:\n \"\"\"\n Checks estimation error for area_under_curve_estimator function\n for f(x) = x where x lies within min_value to max_value\n 1. Calls \"area_under_curve_estimator\" function\n 2. Compares with the expected value\n 3. Prints estimated, expected and error value\n \"\"\"\n\n def identity_function(x: float) -> float:\n \"\"\"\n Represents identity function\n >>> [function_to_integrate(x) for x in [-2.0, -1.0, 0.0, 1.0, 2.0]]\n [-2.0, -1.0, 0.0, 1.0, 2.0]\n \"\"\"\n return x\n\n estimated_value = area_under_curve_estimator(\n iterations, identity_function, min_value, max_value\n )\n expected_value = (max_value * max_value - min_value * min_value) \/ 2\n\n print(\"******************\")\n print(f\"Estimating area under y=x where x varies from {min_value} to {max_value}\")\n print(f\"Estimated value is {estimated_value}\")\n print(f\"Expected value is {expected_value}\")\n print(f\"Total error is {abs(estimated_value - expected_value)}\")\n print(\"******************\")\n\n\ndef pi_estimator_using_area_under_curve(iterations: int) -> None:\n \"\"\"\n Area under curve y = sqrt(4 - x^2) where x lies in 0 to 2 is equal to pi\n \"\"\"\n\n def function_to_integrate(x: float) -> float:\n \"\"\"\n Represents semi-circle with radius 2\n >>> [function_to_integrate(x) for x in [-2.0, 0.0, 2.0]]\n [0.0, 2.0, 0.0]\n \"\"\"\n return sqrt(4.0 - x * x)\n\n estimated_value = area_under_curve_estimator(\n iterations, function_to_integrate, 0.0, 2.0\n )\n\n print(\"******************\")\n print(\"Estimating pi using area_under_curve_estimator\")\n print(f\"Estimated value is {estimated_value}\")\n print(f\"Expected value is {pi}\")\n print(f\"Total error is {abs(estimated_value - pi)}\")\n print(\"******************\")\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Initialize a six sided dice self.sides listrange1, Dice.NUMSIDES 1 def rollself: return random.choiceself.sides def throwdicenumthrows: int, numdice: int 2 listfloat: dices Dice for i in rangenumdice countofsum 0 lendices Dice.NUMSIDES 1 for in rangenumthrows: countofsumsumdice.roll for dice in dices 1 probability roundcount 100 numthrows, 2 for count in countofsum return probabilitynumdice: remove probability of sums that never appear if name main: import doctest doctest.testmod","Completions":"from __future__ import annotations\n\nimport random\n\n\nclass Dice:\n NUM_SIDES = 6\n\n def __init__(self):\n \"\"\"Initialize a six sided dice\"\"\"\n self.sides = list(range(1, Dice.NUM_SIDES + 1))\n\n def roll(self):\n return random.choice(self.sides)\n\n\ndef throw_dice(num_throws: int, num_dice: int = 2) -> list[float]:\n \"\"\"\n Return probability list of all possible sums when throwing dice.\n\n >>> random.seed(0)\n >>> throw_dice(10, 1)\n [10.0, 0.0, 30.0, 50.0, 10.0, 0.0]\n >>> throw_dice(100, 1)\n [19.0, 17.0, 17.0, 11.0, 23.0, 13.0]\n >>> throw_dice(1000, 1)\n [18.8, 15.5, 16.3, 17.6, 14.2, 17.6]\n >>> throw_dice(10000, 1)\n [16.35, 16.89, 16.93, 16.6, 16.52, 16.71]\n >>> throw_dice(10000, 2)\n [2.74, 5.6, 7.99, 11.26, 13.92, 16.7, 14.44, 10.63, 8.05, 5.92, 2.75]\n \"\"\"\n dices = [Dice() for i in range(num_dice)]\n count_of_sum = [0] * (len(dices) * Dice.NUM_SIDES + 1)\n for _ in range(num_throws):\n count_of_sum[sum(dice.roll() for dice in dices)] += 1\n probability = [round((count * 100) \/ num_throws, 2) for count in count_of_sum]\n return probability[num_dice:] # remove probability of sums that never appear\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Find the number of digits in a number. numdigits12345 5 numdigits123 3 numdigits0 1 numdigits1 1 numdigits123456 6 numdigits'123' Raises a TypeError for noninteger input Traceback most recent call last: ... TypeError: Input must be an integer Find the number of digits in a number. abs is used as logarithm for negative numbers is not defined. numdigitsfast12345 5 numdigitsfast123 3 numdigitsfast0 1 numdigitsfast1 1 numdigitsfast123456 6 numdigits'123' Raises a TypeError for noninteger input Traceback most recent call last: ... TypeError: Input must be an integer Find the number of digits in a number. abs is used for negative numbers numdigitsfaster12345 5 numdigitsfaster123 3 numdigitsfaster0 1 numdigitsfaster1 1 numdigitsfaster123456 6 numdigits'123' Raises a TypeError for noninteger input Traceback most recent call last: ... TypeError: Input must be an integer Benchmark multiple functions, with three different length int values.","Completions":"import math\nfrom timeit import timeit\n\n\ndef num_digits(n: int) -> int:\n \"\"\"\n Find the number of digits in a number.\n\n >>> num_digits(12345)\n 5\n >>> num_digits(123)\n 3\n >>> num_digits(0)\n 1\n >>> num_digits(-1)\n 1\n >>> num_digits(-123456)\n 6\n >>> num_digits('123') # Raises a TypeError for non-integer input\n Traceback (most recent call last):\n ...\n TypeError: Input must be an integer\n \"\"\"\n\n if not isinstance(n, int):\n raise TypeError(\"Input must be an integer\")\n\n digits = 0\n n = abs(n)\n while True:\n n = n \/\/ 10\n digits += 1\n if n == 0:\n break\n return digits\n\n\ndef num_digits_fast(n: int) -> int:\n \"\"\"\n Find the number of digits in a number.\n abs() is used as logarithm for negative numbers is not defined.\n\n >>> num_digits_fast(12345)\n 5\n >>> num_digits_fast(123)\n 3\n >>> num_digits_fast(0)\n 1\n >>> num_digits_fast(-1)\n 1\n >>> num_digits_fast(-123456)\n 6\n >>> num_digits('123') # Raises a TypeError for non-integer input\n Traceback (most recent call last):\n ...\n TypeError: Input must be an integer\n \"\"\"\n\n if not isinstance(n, int):\n raise TypeError(\"Input must be an integer\")\n\n return 1 if n == 0 else math.floor(math.log(abs(n), 10) + 1)\n\n\ndef num_digits_faster(n: int) -> int:\n \"\"\"\n Find the number of digits in a number.\n abs() is used for negative numbers\n\n >>> num_digits_faster(12345)\n 5\n >>> num_digits_faster(123)\n 3\n >>> num_digits_faster(0)\n 1\n >>> num_digits_faster(-1)\n 1\n >>> num_digits_faster(-123456)\n 6\n >>> num_digits('123') # Raises a TypeError for non-integer input\n Traceback (most recent call last):\n ...\n TypeError: Input must be an integer\n \"\"\"\n\n if not isinstance(n, int):\n raise TypeError(\"Input must be an integer\")\n\n return len(str(abs(n)))\n\n\ndef benchmark() -> None:\n \"\"\"\n Benchmark multiple functions, with three different length int values.\n \"\"\"\n from collections.abc import Callable\n\n def benchmark_a_function(func: Callable, value: int) -> None:\n call = f\"{func.__name__}({value})\"\n timing = timeit(f\"__main__.{call}\", setup=\"import __main__\")\n print(f\"{call}: {func(value)} -- {timing} seconds\")\n\n for value in (262144, 1125899906842624, 1267650600228229401496703205376):\n for func in (num_digits, num_digits_fast, num_digits_faster):\n benchmark_a_function(func, value)\n print()\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n benchmark()\n"} +{"Prompt":"Use the AdamsBashforth methods to solve Ordinary Differential Equations. https:en.wikipedia.orgwikiLinearmultistepmethod Author : Ravi Kumar args: func: An ordinary differential equation ODE as function of x and y. xinitials: List containing initial required values of x. yinitials: List containing initial required values of y. stepsize: The increment value of x. xfinal: The final value of x. Returns: Solution of y at each nodal point def fx, y: ... return x y AdamsBashforthf, 0, 0.2, 0.4, 0, 0.2, 1, 0.2, 1 doctest: ELLIPSIS AdamsBashforthfunc..., xinitials0, 0.2, 0.4, yinitials0, 0.2, 1, step... AdamsBashforthf, 0, 0.2, 1, 0, 0, 0.04, 0.2, 1.step2 Traceback most recent call last: ... ValueError: The final value of x must be greater than the initial values of x. AdamsBashforthf, 0, 0.2, 0.3, 0, 0, 0.04, 0.2, 1.step3 Traceback most recent call last: ... ValueError: xvalues must be equally spaced according to step size. AdamsBashforthf,0,0.2,0.4,0.6,0.8,0,0,0.04,0.128,0.307,0.2,1.step5 Traceback most recent call last: ... ValueError: Step size must be positive. def fx, y: ... return x AdamsBashforthf, 0, 0.2, 0, 0, 0.2, 1.step2 array0. , 0. , 0.06, 0.16, 0.3 , 0.48 AdamsBashforthf, 0, 0.2, 0.4, 0, 0, 0.04, 0.2, 1.step2 Traceback most recent call last: ... ValueError: Insufficient initial points information. def fx, y: ... return x y y AdamsBashforthf, 0, 0.2, 0.4, 0, 0, 0.04, 0.2, 1.step3 y3 0.15533333333333332 AdamsBashforthf, 0, 0.2, 0, 0, 0.2, 1.step3 Traceback most recent call last: ... ValueError: Insufficient initial points information. def fx,y: ... return x y y AdamsBashforth ... f, 0, 0.2, 0.4, 0.6, 0, 0, 0.04, 0.128, 0.2, 1.step4 y4 0.30699999999999994 y5 0.5771083333333333 AdamsBashforthf, 0, 0.2, 0.4, 0, 0, 0.04, 0.2, 1.step4 Traceback most recent call last: ... ValueError: Insufficient initial points information. def fx,y: ... return x y y AdamsBashforth ... f, 0, 0.2, 0.4, 0.6, 0.8, 0, 0.02140, 0.02140, 0.22211, 0.42536, ... 0.2, 1.step5 y1 0.05436839444444452 AdamsBashforthf, 0, 0.2, 0.4, 0, 0, 0.04, 0.2, 1.step5 Traceback most recent call last: ... ValueError: Insufficient initial points information.","Completions":"from collections.abc import Callable\nfrom dataclasses import dataclass\n\nimport numpy as np\n\n\n@dataclass\nclass AdamsBashforth:\n \"\"\"\n args:\n func: An ordinary differential equation (ODE) as function of x and y.\n x_initials: List containing initial required values of x.\n y_initials: List containing initial required values of y.\n step_size: The increment value of x.\n x_final: The final value of x.\n\n Returns: Solution of y at each nodal point\n\n >>> def f(x, y):\n ... return x + y\n >>> AdamsBashforth(f, [0, 0.2, 0.4], [0, 0.2, 1], 0.2, 1) # doctest: +ELLIPSIS\n AdamsBashforth(func=..., x_initials=[0, 0.2, 0.4], y_initials=[0, 0.2, 1], step...)\n >>> AdamsBashforth(f, [0, 0.2, 1], [0, 0, 0.04], 0.2, 1).step_2()\n Traceback (most recent call last):\n ...\n ValueError: The final value of x must be greater than the initial values of x.\n\n >>> AdamsBashforth(f, [0, 0.2, 0.3], [0, 0, 0.04], 0.2, 1).step_3()\n Traceback (most recent call last):\n ...\n ValueError: x-values must be equally spaced according to step size.\n\n >>> AdamsBashforth(f,[0,0.2,0.4,0.6,0.8],[0,0,0.04,0.128,0.307],-0.2,1).step_5()\n Traceback (most recent call last):\n ...\n ValueError: Step size must be positive.\n \"\"\"\n\n func: Callable[[float, float], float]\n x_initials: list[float]\n y_initials: list[float]\n step_size: float\n x_final: float\n\n def __post_init__(self) -> None:\n if self.x_initials[-1] >= self.x_final:\n raise ValueError(\n \"The final value of x must be greater than the initial values of x.\"\n )\n\n if self.step_size <= 0:\n raise ValueError(\"Step size must be positive.\")\n\n if not all(\n round(x1 - x0, 10) == self.step_size\n for x0, x1 in zip(self.x_initials, self.x_initials[1:])\n ):\n raise ValueError(\"x-values must be equally spaced according to step size.\")\n\n def step_2(self) -> np.ndarray:\n \"\"\"\n >>> def f(x, y):\n ... return x\n >>> AdamsBashforth(f, [0, 0.2], [0, 0], 0.2, 1).step_2()\n array([0. , 0. , 0.06, 0.16, 0.3 , 0.48])\n\n >>> AdamsBashforth(f, [0, 0.2, 0.4], [0, 0, 0.04], 0.2, 1).step_2()\n Traceback (most recent call last):\n ...\n ValueError: Insufficient initial points information.\n \"\"\"\n\n if len(self.x_initials) != 2 or len(self.y_initials) != 2:\n raise ValueError(\"Insufficient initial points information.\")\n\n x_0, x_1 = self.x_initials[:2]\n y_0, y_1 = self.y_initials[:2]\n\n n = int((self.x_final - x_1) \/ self.step_size)\n y = np.zeros(n + 2)\n y[0] = y_0\n y[1] = y_1\n\n for i in range(n):\n y[i + 2] = y[i + 1] + (self.step_size \/ 2) * (\n 3 * self.func(x_1, y[i + 1]) - self.func(x_0, y[i])\n )\n x_0 = x_1\n x_1 += self.step_size\n\n return y\n\n def step_3(self) -> np.ndarray:\n \"\"\"\n >>> def f(x, y):\n ... return x + y\n >>> y = AdamsBashforth(f, [0, 0.2, 0.4], [0, 0, 0.04], 0.2, 1).step_3()\n >>> y[3]\n 0.15533333333333332\n\n >>> AdamsBashforth(f, [0, 0.2], [0, 0], 0.2, 1).step_3()\n Traceback (most recent call last):\n ...\n ValueError: Insufficient initial points information.\n \"\"\"\n if len(self.x_initials) != 3 or len(self.y_initials) != 3:\n raise ValueError(\"Insufficient initial points information.\")\n\n x_0, x_1, x_2 = self.x_initials[:3]\n y_0, y_1, y_2 = self.y_initials[:3]\n\n n = int((self.x_final - x_2) \/ self.step_size)\n y = np.zeros(n + 4)\n y[0] = y_0\n y[1] = y_1\n y[2] = y_2\n\n for i in range(n + 1):\n y[i + 3] = y[i + 2] + (self.step_size \/ 12) * (\n 23 * self.func(x_2, y[i + 2])\n - 16 * self.func(x_1, y[i + 1])\n + 5 * self.func(x_0, y[i])\n )\n x_0 = x_1\n x_1 = x_2\n x_2 += self.step_size\n\n return y\n\n def step_4(self) -> np.ndarray:\n \"\"\"\n >>> def f(x,y):\n ... return x + y\n >>> y = AdamsBashforth(\n ... f, [0, 0.2, 0.4, 0.6], [0, 0, 0.04, 0.128], 0.2, 1).step_4()\n >>> y[4]\n 0.30699999999999994\n >>> y[5]\n 0.5771083333333333\n\n >>> AdamsBashforth(f, [0, 0.2, 0.4], [0, 0, 0.04], 0.2, 1).step_4()\n Traceback (most recent call last):\n ...\n ValueError: Insufficient initial points information.\n \"\"\"\n\n if len(self.x_initials) != 4 or len(self.y_initials) != 4:\n raise ValueError(\"Insufficient initial points information.\")\n\n x_0, x_1, x_2, x_3 = self.x_initials[:4]\n y_0, y_1, y_2, y_3 = self.y_initials[:4]\n\n n = int((self.x_final - x_3) \/ self.step_size)\n y = np.zeros(n + 4)\n y[0] = y_0\n y[1] = y_1\n y[2] = y_2\n y[3] = y_3\n\n for i in range(n):\n y[i + 4] = y[i + 3] + (self.step_size \/ 24) * (\n 55 * self.func(x_3, y[i + 3])\n - 59 * self.func(x_2, y[i + 2])\n + 37 * self.func(x_1, y[i + 1])\n - 9 * self.func(x_0, y[i])\n )\n x_0 = x_1\n x_1 = x_2\n x_2 = x_3\n x_3 += self.step_size\n\n return y\n\n def step_5(self) -> np.ndarray:\n \"\"\"\n >>> def f(x,y):\n ... return x + y\n >>> y = AdamsBashforth(\n ... f, [0, 0.2, 0.4, 0.6, 0.8], [0, 0.02140, 0.02140, 0.22211, 0.42536],\n ... 0.2, 1).step_5()\n >>> y[-1]\n 0.05436839444444452\n\n >>> AdamsBashforth(f, [0, 0.2, 0.4], [0, 0, 0.04], 0.2, 1).step_5()\n Traceback (most recent call last):\n ...\n ValueError: Insufficient initial points information.\n \"\"\"\n\n if len(self.x_initials) != 5 or len(self.y_initials) != 5:\n raise ValueError(\"Insufficient initial points information.\")\n\n x_0, x_1, x_2, x_3, x_4 = self.x_initials[:5]\n y_0, y_1, y_2, y_3, y_4 = self.y_initials[:5]\n\n n = int((self.x_final - x_4) \/ self.step_size)\n y = np.zeros(n + 6)\n y[0] = y_0\n y[1] = y_1\n y[2] = y_2\n y[3] = y_3\n y[4] = y_4\n\n for i in range(n + 1):\n y[i + 5] = y[i + 4] + (self.step_size \/ 720) * (\n 1901 * self.func(x_4, y[i + 4])\n - 2774 * self.func(x_3, y[i + 3])\n - 2616 * self.func(x_2, y[i + 2])\n - 1274 * self.func(x_1, y[i + 1])\n + 251 * self.func(x_0, y[i])\n )\n x_0 = x_1\n x_1 = x_2\n x_2 = x_3\n x_3 = x_4\n x_4 += self.step_size\n\n return y\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"finds where function becomes 0 in a,b using bolzano bisectionlambda x: x 3 1, 5, 5 1.0000000149011612 bisectionlambda x: x 3 1, 2, 1000 Traceback most recent call last: ... ValueError: could not find root in given interval. bisectionlambda x: x 2 4 x 3, 0, 2 1.0 bisectionlambda x: x 2 4 x 3, 2, 4 3.0 bisectionlambda x: x 2 4 x 3, 4, 1000 Traceback most recent call last: ... ValueError: could not find root in given interval. then this algorithm can't find the root","Completions":"from collections.abc import Callable\n\n\ndef bisection(function: Callable[[float], float], a: float, b: float) -> float:\n \"\"\"\n finds where function becomes 0 in [a,b] using bolzano\n >>> bisection(lambda x: x ** 3 - 1, -5, 5)\n 1.0000000149011612\n >>> bisection(lambda x: x ** 3 - 1, 2, 1000)\n Traceback (most recent call last):\n ...\n ValueError: could not find root in given interval.\n >>> bisection(lambda x: x ** 2 - 4 * x + 3, 0, 2)\n 1.0\n >>> bisection(lambda x: x ** 2 - 4 * x + 3, 2, 4)\n 3.0\n >>> bisection(lambda x: x ** 2 - 4 * x + 3, 4, 1000)\n Traceback (most recent call last):\n ...\n ValueError: could not find root in given interval.\n \"\"\"\n start: float = a\n end: float = b\n if function(a) == 0: # one of the a or b is a root for the function\n return a\n elif function(b) == 0:\n return b\n elif (\n function(a) * function(b) > 0\n ): # if none of these are root and they are both positive or negative,\n # then this algorithm can't find the root\n raise ValueError(\"could not find root in given interval.\")\n else:\n mid: float = start + (end - start) \/ 2.0\n while abs(start - mid) > 10**-7: # until precisely equals to 10^-7\n if function(mid) == 0:\n return mid\n elif function(mid) * function(start) < 0:\n end = mid\n else:\n start = mid\n mid = start + (end - start) \/ 2.0\n return mid\n\n\ndef f(x: float) -> float:\n return x**3 - 2 * x - 5\n\n\nif __name__ == \"__main__\":\n print(bisection(f, 1, 1000))\n\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Given a function on floating number fx and two floating numbers a and b such that fa fb 0 and fx is continuous in a, b. Here fx represents algebraic or transcendental equation. Find root of function in interval a, b Or find a value of x such that fx is 0 https:en.wikipedia.orgwikiBisectionmethod equation5 15 equation0 10 equation5 15 equation0.1 9.99 equation0.1 9.99 bisection2, 5 3.1611328125 bisection0, 6 3.158203125 bisection2, 3 Traceback most recent call last: ... ValueError: Wrong space! Bolzano theory in order to find if there is a root between a and b Find middle point Check if middle point is root Decide the side to repeat the steps","Completions":"def equation(x: float) -> float:\n \"\"\"\n >>> equation(5)\n -15\n >>> equation(0)\n 10\n >>> equation(-5)\n -15\n >>> equation(0.1)\n 9.99\n >>> equation(-0.1)\n 9.99\n \"\"\"\n return 10 - x * x\n\n\ndef bisection(a: float, b: float) -> float:\n \"\"\"\n >>> bisection(-2, 5)\n 3.1611328125\n >>> bisection(0, 6)\n 3.158203125\n >>> bisection(2, 3)\n Traceback (most recent call last):\n ...\n ValueError: Wrong space!\n \"\"\"\n # Bolzano theory in order to find if there is a root between a and b\n if equation(a) * equation(b) >= 0:\n raise ValueError(\"Wrong space!\")\n\n c = a\n while (b - a) >= 0.01:\n # Find middle point\n c = (a + b) \/ 2\n # Check if middle point is root\n if equation(c) == 0.0:\n break\n # Decide the side to repeat the steps\n if equation(c) * equation(a) < 0:\n b = c\n else:\n a = c\n return c\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n\n print(bisection(-2, 5))\n print(bisection(0, 6))\n"} +{"Prompt":"Author : Syed Faizan 3rd Year IIIT Pune Github : faizan2700 Purpose : You have one function fx which takes float integer and returns float you have to integrate the function in limits a to b. The approximation proposed by Thomas Simpsons in 1743 is one way to calculate integration. read article : https:cpalgorithms.comnummethodssimpsonintegration.html simpsonintegration takes function,lowerlimita,upperlimitb,precision and returns the integration of function in given limit. constants the more the number of steps the more accurate Summary of Simpson Approximation : By simpsons integration : 1. integration of fxdx with limit a to b is fx0 4 fx1 2 fx2 4 fx3 2 fx4..... fxn where x0 a xi a i h xn b Args: function : the function which's integration is desired a : the lower limit of integration b : upper limit of integration precision : precision of the result,error required default is 4 Returns: result : the value of the approximated integration of function in range a to b Raises: AssertionError: function is not callable AssertionError: a is not float or integer AssertionError: function should return float or integer AssertionError: b is not float or integer AssertionError: precision is not positive integer simpsonintegrationlambda x : xx,1,2,3 2.333 simpsonintegrationlambda x : xx,'wronginput',2,3 Traceback most recent call last: ... AssertionError: a should be float or integer your input : wronginput simpsonintegrationlambda x : xx,1,'wronginput',3 Traceback most recent call last: ... AssertionError: b should be float or integer your input : wronginput simpsonintegrationlambda x : xx,1,2,'wronginput' Traceback most recent call last: ... AssertionError: precision should be positive integer your input : wronginput simpsonintegration'wronginput',2,3,4 Traceback most recent call last: ... AssertionError: the functionobject passed should be callable your input : ... simpsonintegrationlambda x : xx,3.45,3.2,1 2.8 simpsonintegrationlambda x : xx,3.45,3.2,0 Traceback most recent call last: ... AssertionError: precision should be positive integer your input : 0 simpsonintegrationlambda x : xx,3.45,3.2,1 Traceback most recent call last: ... AssertionError: precision should be positive integer your input : 1 just applying the formula of simpson for approximate integration written in mentioned article in first comment of this file and above this function","Completions":"# constants\n# the more the number of steps the more accurate\nN_STEPS = 1000\n\n\ndef f(x: float) -> float:\n return x * x\n\n\n\"\"\"\nSummary of Simpson Approximation :\n\nBy simpsons integration :\n1. integration of fxdx with limit a to b is =\n f(x0) + 4 * f(x1) + 2 * f(x2) + 4 * f(x3) + 2 * f(x4)..... + f(xn)\nwhere x0 = a\nxi = a + i * h\nxn = b\n\"\"\"\n\n\ndef simpson_integration(function, a: float, b: float, precision: int = 4) -> float:\n \"\"\"\n Args:\n function : the function which's integration is desired\n a : the lower limit of integration\n b : upper limit of integration\n precision : precision of the result,error required default is 4\n\n Returns:\n result : the value of the approximated integration of function in range a to b\n\n Raises:\n AssertionError: function is not callable\n AssertionError: a is not float or integer\n AssertionError: function should return float or integer\n AssertionError: b is not float or integer\n AssertionError: precision is not positive integer\n\n >>> simpson_integration(lambda x : x*x,1,2,3)\n 2.333\n\n >>> simpson_integration(lambda x : x*x,'wrong_input',2,3)\n Traceback (most recent call last):\n ...\n AssertionError: a should be float or integer your input : wrong_input\n\n >>> simpson_integration(lambda x : x*x,1,'wrong_input',3)\n Traceback (most recent call last):\n ...\n AssertionError: b should be float or integer your input : wrong_input\n\n >>> simpson_integration(lambda x : x*x,1,2,'wrong_input')\n Traceback (most recent call last):\n ...\n AssertionError: precision should be positive integer your input : wrong_input\n >>> simpson_integration('wrong_input',2,3,4)\n Traceback (most recent call last):\n ...\n AssertionError: the function(object) passed should be callable your input : ...\n\n >>> simpson_integration(lambda x : x*x,3.45,3.2,1)\n -2.8\n\n >>> simpson_integration(lambda x : x*x,3.45,3.2,0)\n Traceback (most recent call last):\n ...\n AssertionError: precision should be positive integer your input : 0\n\n >>> simpson_integration(lambda x : x*x,3.45,3.2,-1)\n Traceback (most recent call last):\n ...\n AssertionError: precision should be positive integer your input : -1\n\n \"\"\"\n assert callable(\n function\n ), f\"the function(object) passed should be callable your input : {function}\"\n assert isinstance(a, (float, int)), f\"a should be float or integer your input : {a}\"\n assert isinstance(function(a), (float, int)), (\n \"the function should return integer or float return type of your function, \"\n f\"{type(a)}\"\n )\n assert isinstance(b, (float, int)), f\"b should be float or integer your input : {b}\"\n assert (\n isinstance(precision, int) and precision > 0\n ), f\"precision should be positive integer your input : {precision}\"\n\n # just applying the formula of simpson for approximate integration written in\n # mentioned article in first comment of this file and above this function\n\n h = (b - a) \/ N_STEPS\n result = function(a) + function(b)\n\n for i in range(1, N_STEPS):\n a1 = a + h * i\n result += function(a1) * (4 if i % 2 else 2)\n\n result *= h \/ 3\n return round(result, precision)\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"function is the f we want to find its root x0 and x1 are two random starting points intersectionlambda x: x 3 1, 5, 5 0.9999999999954654 intersectionlambda x: x 3 1, 5, 5 Traceback most recent call last: ... ZeroDivisionError: float division by zero, could not find root intersectionlambda x: x 3 1, 100, 200 1.0000000000003888 intersectionlambda x: x 2 4 x 3, 0, 2 0.9999999998088019 intersectionlambda x: x 2 4 x 3, 2, 4 2.9999999998088023 intersectionlambda x: x 2 4 x 3, 4, 1000 3.0000000001786042 intersectionmath.sin, math.pi, math.pi 0.0 intersectionmath.cos, math.pi, math.pi Traceback most recent call last: ... ZeroDivisionError: float division by zero, could not find root","Completions":"import math\nfrom collections.abc import Callable\n\n\ndef intersection(function: Callable[[float], float], x0: float, x1: float) -> float:\n \"\"\"\n function is the f we want to find its root\n x0 and x1 are two random starting points\n >>> intersection(lambda x: x ** 3 - 1, -5, 5)\n 0.9999999999954654\n >>> intersection(lambda x: x ** 3 - 1, 5, 5)\n Traceback (most recent call last):\n ...\n ZeroDivisionError: float division by zero, could not find root\n >>> intersection(lambda x: x ** 3 - 1, 100, 200)\n 1.0000000000003888\n >>> intersection(lambda x: x ** 2 - 4 * x + 3, 0, 2)\n 0.9999999998088019\n >>> intersection(lambda x: x ** 2 - 4 * x + 3, 2, 4)\n 2.9999999998088023\n >>> intersection(lambda x: x ** 2 - 4 * x + 3, 4, 1000)\n 3.0000000001786042\n >>> intersection(math.sin, -math.pi, math.pi)\n 0.0\n >>> intersection(math.cos, -math.pi, math.pi)\n Traceback (most recent call last):\n ...\n ZeroDivisionError: float division by zero, could not find root\n \"\"\"\n x_n: float = x0\n x_n1: float = x1\n while True:\n if x_n == x_n1 or function(x_n1) == function(x_n):\n raise ZeroDivisionError(\"float division by zero, could not find root\")\n x_n2: float = x_n1 - (\n function(x_n1) \/ ((function(x_n1) - function(x_n)) \/ (x_n1 - x_n))\n )\n if abs(x_n2 - x_n1) < 10**-5:\n return x_n2\n x_n = x_n1\n x_n1 = x_n2\n\n\ndef f(x: float) -> float:\n return math.pow(x, 3) - (2 * x) - 5\n\n\nif __name__ == \"__main__\":\n print(intersection(f, 3, 3.5))\n"} +{"Prompt":"Python program to show how to interpolate and evaluate a polynomial using Neville's method. Nevilles method evaluates a polynomial that passes through a given set of x and y points for a particular x value x0 using the Newton polynomial form. Reference: https:rpubs.comaaronsc32nevillesmethodpolynomialinterpolation Interpolate and evaluate a polynomial using Neville's method. Arguments: xpoints, ypoints: Iterables of x and corresponding y points through which the polynomial passes. x0: The value of x to evaluate the polynomial for. Return Value: A list of the approximated value and the Neville iterations table respectively. import pprint nevilleinterpolate1,2,3,4,6, 6,7,8,9,11, 50 10.0 pprint.pprintnevilleinterpolate1,2,3,4,6, 6,7,8,9,11, 991 0, 6, 0, 0, 0, 0, 7, 0, 0, 0, 0, 8, 104.0, 0, 0, 0, 9, 104.0, 104.0, 0, 0, 11, 104.0, 104.0, 104.0 nevilleinterpolate1,2,3,4,6, 6,7,8,9,11, 990 104.0 nevilleinterpolate1,2,3,4,6, 6,7,8,9,11, '' Traceback most recent call last: ... TypeError: unsupported operand types for : 'str' and 'int'","Completions":"def neville_interpolate(x_points: list, y_points: list, x0: int) -> list:\n \"\"\"\n Interpolate and evaluate a polynomial using Neville's method.\n Arguments:\n x_points, y_points: Iterables of x and corresponding y points through\n which the polynomial passes.\n x0: The value of x to evaluate the polynomial for.\n Return Value: A list of the approximated value and the Neville iterations\n table respectively.\n >>> import pprint\n >>> neville_interpolate((1,2,3,4,6), (6,7,8,9,11), 5)[0]\n 10.0\n >>> pprint.pprint(neville_interpolate((1,2,3,4,6), (6,7,8,9,11), 99)[1])\n [[0, 6, 0, 0, 0],\n [0, 7, 0, 0, 0],\n [0, 8, 104.0, 0, 0],\n [0, 9, 104.0, 104.0, 0],\n [0, 11, 104.0, 104.0, 104.0]]\n >>> neville_interpolate((1,2,3,4,6), (6,7,8,9,11), 99)[0]\n 104.0\n >>> neville_interpolate((1,2,3,4,6), (6,7,8,9,11), '')\n Traceback (most recent call last):\n ...\n TypeError: unsupported operand type(s) for -: 'str' and 'int'\n \"\"\"\n n = len(x_points)\n q = [[0] * n for i in range(n)]\n for i in range(n):\n q[i][1] = y_points[i]\n\n for i in range(2, n):\n for j in range(i, n):\n q[j][i] = (\n (x0 - x_points[j - i + 1]) * q[j][i - 1]\n - (x0 - x_points[j]) * q[j - 1][i - 1]\n ) \/ (x_points[j] - x_points[j - i + 1])\n\n return [q[n - 1][n - 1], q]\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"https:www.geeksforgeeks.orgnewtonforwardbackwardinterpolation for calculating u value ucal1, 2 0 ucal1.1, 2 0.11000000000000011 ucal1.2, 2 0.23999999999999994 for calculating forward difference table","Completions":"# https:\/\/www.geeksforgeeks.org\/newton-forward-backward-interpolation\/\nfrom __future__ import annotations\n\nimport math\n\n\n# for calculating u value\ndef ucal(u: float, p: int) -> float:\n \"\"\"\n >>> ucal(1, 2)\n 0\n >>> ucal(1.1, 2)\n 0.11000000000000011\n >>> ucal(1.2, 2)\n 0.23999999999999994\n \"\"\"\n temp = u\n for i in range(1, p):\n temp = temp * (u - i)\n return temp\n\n\ndef main() -> None:\n n = int(input(\"enter the numbers of values: \"))\n y: list[list[float]] = []\n for _ in range(n):\n y.append([])\n for i in range(n):\n for j in range(n):\n y[i].append(j)\n y[i][j] = 0\n\n print(\"enter the values of parameters in a list: \")\n x = list(map(int, input().split()))\n\n print(\"enter the values of corresponding parameters: \")\n for i in range(n):\n y[i][0] = float(input())\n\n value = int(input(\"enter the value to interpolate: \"))\n u = (value - x[0]) \/ (x[1] - x[0])\n\n # for calculating forward difference table\n\n for i in range(1, n):\n for j in range(n - i):\n y[j][i] = y[j + 1][i - 1] - y[j][i - 1]\n\n summ = y[0][0]\n for i in range(1, n):\n summ += (ucal(u, i) * y[0][i]) \/ math.factorial(i)\n\n print(f\"the value at {value} is {summ}\")\n\n\nif __name__ == \"__main__\":\n main()\n"} +{"Prompt":"The NewtonRaphson method aka the Newton method is a rootfinding algorithm that approximates a root of a given realvalued function fx. It is an iterative method given by the formula xn 1 xn fxn f'xn with the precision of the approximation increasing as the number of iterations increase. Reference: https:en.wikipedia.orgwikiNewton27smethod Approximate the derivative of a function fx at a point x using the finite difference method import math tolerance 1e5 derivative calcderivativelambda x: x2, 2 math.isclosederivative, 4, abstoltolerance True derivative calcderivativemath.sin, 0 math.isclosederivative, 1, abstoltolerance True Find a root of the given function f using the NewtonRaphson method. :param f: A realvalued singlevariable function :param x0: Initial guess :param maxiter: Maximum number of iterations :param step: Step size of x, used to approximate f'x :param maxerror: Maximum approximation error :param logsteps: bool denoting whether to log intermediate steps :return: A tuple containing the approximation, the error, and the intermediate steps. If logsteps is False, then an empty list is returned for the third element of the tuple. :raises ZeroDivisionError: The derivative approaches 0. :raises ArithmeticError: No solution exists, or the solution isn't found before the iteration limit is reached. import math tolerance 1e15 root, newtonraphsonlambda x: x2 5x 2, 0.4, maxerrortolerance math.iscloseroot, 5 math.sqrt17 2, abstoltolerance True root, newtonraphsonlambda x: math.logx 1, 2, maxerrortolerance math.iscloseroot, math.e, abstoltolerance True root, newtonraphsonmath.sin, 1, maxerrortolerance math.iscloseroot, 0, abstoltolerance True newtonraphsonmath.cos, 0 Traceback most recent call last: ... ZeroDivisionError: No converging solution found, zero derivative newtonraphsonlambda x: x2 1, 2 Traceback most recent call last: ... ArithmeticError: No converging solution found, iteration limit reached","Completions":"from collections.abc import Callable\n\nRealFunc = Callable[[float], float]\n\n\ndef calc_derivative(f: RealFunc, x: float, delta_x: float = 1e-3) -> float:\n \"\"\"\n Approximate the derivative of a function f(x) at a point x using the finite\n difference method\n\n >>> import math\n >>> tolerance = 1e-5\n >>> derivative = calc_derivative(lambda x: x**2, 2)\n >>> math.isclose(derivative, 4, abs_tol=tolerance)\n True\n >>> derivative = calc_derivative(math.sin, 0)\n >>> math.isclose(derivative, 1, abs_tol=tolerance)\n True\n \"\"\"\n return (f(x + delta_x \/ 2) - f(x - delta_x \/ 2)) \/ delta_x\n\n\ndef newton_raphson(\n f: RealFunc,\n x0: float = 0,\n max_iter: int = 100,\n step: float = 1e-6,\n max_error: float = 1e-6,\n log_steps: bool = False,\n) -> tuple[float, float, list[float]]:\n \"\"\"\n Find a root of the given function f using the Newton-Raphson method.\n\n :param f: A real-valued single-variable function\n :param x0: Initial guess\n :param max_iter: Maximum number of iterations\n :param step: Step size of x, used to approximate f'(x)\n :param max_error: Maximum approximation error\n :param log_steps: bool denoting whether to log intermediate steps\n\n :return: A tuple containing the approximation, the error, and the intermediate\n steps. If log_steps is False, then an empty list is returned for the third\n element of the tuple.\n\n :raises ZeroDivisionError: The derivative approaches 0.\n :raises ArithmeticError: No solution exists, or the solution isn't found before the\n iteration limit is reached.\n\n >>> import math\n >>> tolerance = 1e-15\n >>> root, *_ = newton_raphson(lambda x: x**2 - 5*x + 2, 0.4, max_error=tolerance)\n >>> math.isclose(root, (5 - math.sqrt(17)) \/ 2, abs_tol=tolerance)\n True\n >>> root, *_ = newton_raphson(lambda x: math.log(x) - 1, 2, max_error=tolerance)\n >>> math.isclose(root, math.e, abs_tol=tolerance)\n True\n >>> root, *_ = newton_raphson(math.sin, 1, max_error=tolerance)\n >>> math.isclose(root, 0, abs_tol=tolerance)\n True\n >>> newton_raphson(math.cos, 0)\n Traceback (most recent call last):\n ...\n ZeroDivisionError: No converging solution found, zero derivative\n >>> newton_raphson(lambda x: x**2 + 1, 2)\n Traceback (most recent call last):\n ...\n ArithmeticError: No converging solution found, iteration limit reached\n \"\"\"\n\n def f_derivative(x: float) -> float:\n return calc_derivative(f, x, step)\n\n a = x0 # Set initial guess\n steps = []\n for _ in range(max_iter):\n if log_steps: # Log intermediate steps\n steps.append(a)\n\n error = abs(f(a))\n if error < max_error:\n return a, error, steps\n\n if f_derivative(a) == 0:\n raise ZeroDivisionError(\"No converging solution found, zero derivative\")\n a -= f(a) \/ f_derivative(a) # Calculate next estimate\n raise ArithmeticError(\"No converging solution found, iteration limit reached\")\n\n\nif __name__ == \"__main__\":\n import doctest\n from math import exp, tanh\n\n doctest.testmod()\n\n def func(x: float) -> float:\n return tanh(x) ** 2 - exp(3 * x)\n\n solution, err, steps = newton_raphson(\n func, x0=10, max_iter=100, step=1e-6, log_steps=True\n )\n print(f\"{solution=}, {err=}\")\n print(\"\\n\".join(str(x) for x in steps))\n"} +{"Prompt":"Approximates the area under the curve using the trapezoidal rule Treats curve as a collection of linear lines and sums the area of the trapezium shape they form :param fnc: a function which defines a curve :param xstart: left end point to indicate the start of line segment :param xend: right end point to indicate end of line segment :param steps: an accuracy gauge; more steps increases the accuracy :return: a float representing the length of the curve def fx: ... return 5 '.3f' trapezoidalareaf, 12.0, 14.0, 1000 '10.000' def fx: ... return 9x2 '.4f' trapezoidalareaf, 4.0, 0, 10000 '192.0000' '.4f' trapezoidalareaf, 4.0, 4.0, 10000 '384.0000' Approximates small segments of curve as linear and solve for trapezoidal area Increment step","Completions":"from __future__ import annotations\n\nfrom collections.abc import Callable\n\n\ndef trapezoidal_area(\n fnc: Callable[[float], float],\n x_start: float,\n x_end: float,\n steps: int = 100,\n) -> float:\n \"\"\"\n Treats curve as a collection of linear lines and sums the area of the\n trapezium shape they form\n :param fnc: a function which defines a curve\n :param x_start: left end point to indicate the start of line segment\n :param x_end: right end point to indicate end of line segment\n :param steps: an accuracy gauge; more steps increases the accuracy\n :return: a float representing the length of the curve\n\n >>> def f(x):\n ... return 5\n >>> '%.3f' % trapezoidal_area(f, 12.0, 14.0, 1000)\n '10.000'\n\n >>> def f(x):\n ... return 9*x**2\n >>> '%.4f' % trapezoidal_area(f, -4.0, 0, 10000)\n '192.0000'\n\n >>> '%.4f' % trapezoidal_area(f, -4.0, 4.0, 10000)\n '384.0000'\n \"\"\"\n x1 = x_start\n fx1 = fnc(x_start)\n area = 0.0\n\n for _ in range(steps):\n # Approximates small segments of curve as linear and solve\n # for trapezoidal area\n x2 = (x_end - x_start) \/ steps + x1\n fx2 = fnc(x2)\n area += abs(fx2 + fx1) * (x2 - x1) \/ 2\n\n # Increment step\n x1 = x2\n fx1 = fx2\n return area\n\n\nif __name__ == \"__main__\":\n\n def f(x):\n return x**3\n\n print(\"f(x) = x^3\")\n print(\"The area between the curve, x = -10, x = 10 and the x axis is:\")\n i = 10\n while i <= 100000:\n area = trapezoidal_area(f, -5, 5, i)\n print(f\"with {i} steps: {area}\")\n i *= 10\n"} +{"Prompt":"Calculate the numeric solution at each step to the ODE fx, y using RK4 https:en.wikipedia.orgwikiRungeKuttamethods Arguments: f The ode as a function of x and y y0 the initial value for y x0 the initial value for x h the stepsize xend the end value for x the exact solution is math.expx def fx, y: ... return y y0 1 y rungekuttaf, y0, 0.0, 0.01, 5 y1 148.41315904125113","Completions":"import numpy as np\n\n\ndef runge_kutta(f, y0, x0, h, x_end):\n \"\"\"\n Calculate the numeric solution at each step to the ODE f(x, y) using RK4\n\n https:\/\/en.wikipedia.org\/wiki\/Runge-Kutta_methods\n\n Arguments:\n f -- The ode as a function of x and y\n y0 -- the initial value for y\n x0 -- the initial value for x\n h -- the stepsize\n x_end -- the end value for x\n\n >>> # the exact solution is math.exp(x)\n >>> def f(x, y):\n ... return y\n >>> y0 = 1\n >>> y = runge_kutta(f, y0, 0.0, 0.01, 5)\n >>> y[-1]\n 148.41315904125113\n \"\"\"\n n = int(np.ceil((x_end - x0) \/ h))\n y = np.zeros((n + 1,))\n y[0] = y0\n x = x0\n\n for k in range(n):\n k1 = f(x, y[k])\n k2 = f(x + 0.5 * h, y[k] + 0.5 * h * k1)\n k3 = f(x + 0.5 * h, y[k] + 0.5 * h * k2)\n k4 = f(x + h, y[k] + h * k3)\n y[k + 1] = y[k] + (1 \/ 6) * h * (k1 + 2 * k2 + 2 * k3 + k4)\n x += h\n\n return y\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Use the RungeKuttaFehlberg method to solve Ordinary Differential Equations. Solve an Ordinary Differential Equations using RungeKuttaFehlberg Method rkf45 of order 5. https:en.wikipedia.orgwikiRungeE28093KuttaE28093Fehlbergmethod args: func: An ordinary differential equation ODE as function of x and y. xinitial: The initial value of x. yinitial: The initial value of y. stepsize: The increment value of x. xfinal: The final value of x. Returns: Solution of y at each nodal point exact value of y1 is tan0.2 0.2027100937470787 def fx, y: ... return 1 y2 y rungekuttafehlberg45f, 0, 0, 0.2, 1 y1 0.2027100937470787 def fx,y: ... return x y rungekuttafehlberg45f, 1, 0, 0.2, 0 y1 0.18000000000000002 y rungekuttafehlberg455, 0, 0, 0.1, 1 Traceback most recent call last: ... TypeError: 'int' object is not callable def fx, y: ... return x y y rungekuttafehlberg45f, 0, 0, 0.2, 1 Traceback most recent call last: ... ValueError: The final value of x must be greater than initial value of x. def fx, y: ... return x y rungekuttafehlberg45f, 1, 0, 0.2, 0 Traceback most recent call last: ... ValueError: Step size must be positive.","Completions":"from collections.abc import Callable\n\nimport numpy as np\n\n\ndef runge_kutta_fehlberg_45(\n func: Callable,\n x_initial: float,\n y_initial: float,\n step_size: float,\n x_final: float,\n) -> np.ndarray:\n \"\"\"\n Solve an Ordinary Differential Equations using Runge-Kutta-Fehlberg Method (rkf45)\n of order 5.\n\n https:\/\/en.wikipedia.org\/wiki\/Runge%E2%80%93Kutta%E2%80%93Fehlberg_method\n\n args:\n func: An ordinary differential equation (ODE) as function of x and y.\n x_initial: The initial value of x.\n y_initial: The initial value of y.\n step_size: The increment value of x.\n x_final: The final value of x.\n\n Returns:\n Solution of y at each nodal point\n\n # exact value of y[1] is tan(0.2) = 0.2027100937470787\n >>> def f(x, y):\n ... return 1 + y**2\n >>> y = runge_kutta_fehlberg_45(f, 0, 0, 0.2, 1)\n >>> y[1]\n 0.2027100937470787\n >>> def f(x,y):\n ... return x\n >>> y = runge_kutta_fehlberg_45(f, -1, 0, 0.2, 0)\n >>> y[1]\n -0.18000000000000002\n >>> y = runge_kutta_fehlberg_45(5, 0, 0, 0.1, 1)\n Traceback (most recent call last):\n ...\n TypeError: 'int' object is not callable\n >>> def f(x, y):\n ... return x + y\n >>> y = runge_kutta_fehlberg_45(f, 0, 0, 0.2, -1)\n Traceback (most recent call last):\n ...\n ValueError: The final value of x must be greater than initial value of x.\n >>> def f(x, y):\n ... return x\n >>> y = runge_kutta_fehlberg_45(f, -1, 0, -0.2, 0)\n Traceback (most recent call last):\n ...\n ValueError: Step size must be positive.\n \"\"\"\n if x_initial >= x_final:\n raise ValueError(\n \"The final value of x must be greater than initial value of x.\"\n )\n\n if step_size <= 0:\n raise ValueError(\"Step size must be positive.\")\n\n n = int((x_final - x_initial) \/ step_size)\n y = np.zeros(\n (n + 1),\n )\n x = np.zeros(n + 1)\n y[0] = y_initial\n x[0] = x_initial\n for i in range(n):\n k1 = step_size * func(x[i], y[i])\n k2 = step_size * func(x[i] + step_size \/ 4, y[i] + k1 \/ 4)\n k3 = step_size * func(\n x[i] + (3 \/ 8) * step_size, y[i] + (3 \/ 32) * k1 + (9 \/ 32) * k2\n )\n k4 = step_size * func(\n x[i] + (12 \/ 13) * step_size,\n y[i] + (1932 \/ 2197) * k1 - (7200 \/ 2197) * k2 + (7296 \/ 2197) * k3,\n )\n k5 = step_size * func(\n x[i] + step_size,\n y[i] + (439 \/ 216) * k1 - 8 * k2 + (3680 \/ 513) * k3 - (845 \/ 4104) * k4,\n )\n k6 = step_size * func(\n x[i] + step_size \/ 2,\n y[i]\n - (8 \/ 27) * k1\n + 2 * k2\n - (3544 \/ 2565) * k3\n + (1859 \/ 4104) * k4\n - (11 \/ 40) * k5,\n )\n y[i + 1] = (\n y[i]\n + (16 \/ 135) * k1\n + (6656 \/ 12825) * k3\n + (28561 \/ 56430) * k4\n - (9 \/ 50) * k5\n + (2 \/ 55) * k6\n )\n x[i + 1] = step_size + x[i]\n return y\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Use the RungeKuttaGill's method of order 4 to solve Ordinary Differential Equations. https:www.geeksforgeeks.orggills4thordermethodtosolvedifferentialequations Author : Ravi Kumar Solve an Ordinary Differential Equations using RungeKuttaGills Method of order 4. args: func: An ordinary differential equation ODE as function of x and y. xinitial: The initial value of x. yinitial: The initial value of y. stepsize: The increment value of x. xfinal: The final value of x. Returns: Solution of y at each nodal point def fx, y: ... return xy2 y rungekuttagillsf, 0, 3, 0.2, 5 y1 3.4104259225717537 def fx,y: ... return x y rungekuttagillsf, 1, 0, 0.2, 0 y array 0. , 0.18, 0.32, 0.42, 0.48, 0.5 def fx, y: ... return x y y rungekuttagillsf, 0, 0, 0.2, 1 Traceback most recent call last: ... ValueError: The final value of x must be greater than initial value of x. def fx, y: ... return x y rungekuttagillsf, 1, 0, 0.2, 0 Traceback most recent call last: ... ValueError: Step size must be positive.","Completions":"from collections.abc import Callable\nfrom math import sqrt\n\nimport numpy as np\n\n\ndef runge_kutta_gills(\n func: Callable[[float, float], float],\n x_initial: float,\n y_initial: float,\n step_size: float,\n x_final: float,\n) -> np.ndarray:\n \"\"\"\n Solve an Ordinary Differential Equations using Runge-Kutta-Gills Method of order 4.\n\n args:\n func: An ordinary differential equation (ODE) as function of x and y.\n x_initial: The initial value of x.\n y_initial: The initial value of y.\n step_size: The increment value of x.\n x_final: The final value of x.\n\n Returns:\n Solution of y at each nodal point\n\n >>> def f(x, y):\n ... return (x-y)\/2\n >>> y = runge_kutta_gills(f, 0, 3, 0.2, 5)\n >>> y[-1]\n 3.4104259225717537\n\n >>> def f(x,y):\n ... return x\n >>> y = runge_kutta_gills(f, -1, 0, 0.2, 0)\n >>> y\n array([ 0. , -0.18, -0.32, -0.42, -0.48, -0.5 ])\n\n >>> def f(x, y):\n ... return x + y\n >>> y = runge_kutta_gills(f, 0, 0, 0.2, -1)\n Traceback (most recent call last):\n ...\n ValueError: The final value of x must be greater than initial value of x.\n\n >>> def f(x, y):\n ... return x\n >>> y = runge_kutta_gills(f, -1, 0, -0.2, 0)\n Traceback (most recent call last):\n ...\n ValueError: Step size must be positive.\n \"\"\"\n if x_initial >= x_final:\n raise ValueError(\n \"The final value of x must be greater than initial value of x.\"\n )\n\n if step_size <= 0:\n raise ValueError(\"Step size must be positive.\")\n\n n = int((x_final - x_initial) \/ step_size)\n y = np.zeros(n + 1)\n y[0] = y_initial\n for i in range(n):\n k1 = step_size * func(x_initial, y[i])\n k2 = step_size * func(x_initial + step_size \/ 2, y[i] + k1 \/ 2)\n k3 = step_size * func(\n x_initial + step_size \/ 2,\n y[i] + (-0.5 + 1 \/ sqrt(2)) * k1 + (1 - 1 \/ sqrt(2)) * k2,\n )\n k4 = step_size * func(\n x_initial + step_size, y[i] - (1 \/ sqrt(2)) * k2 + (1 + 1 \/ sqrt(2)) * k3\n )\n\n y[i + 1] = y[i] + (k1 + (2 - sqrt(2)) * k2 + (2 + sqrt(2)) * k3 + k4) \/ 6\n x_initial += step_size\n return y\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Implementing Secant method in Python Author: dimgrichr f5 39.98652410600183 secantmethod1, 3, 2 0.2139409276214589","Completions":"from math import exp\n\n\ndef f(x: float) -> float:\n \"\"\"\n >>> f(5)\n 39.98652410600183\n \"\"\"\n return 8 * x - 2 * exp(-x)\n\n\ndef secant_method(lower_bound: float, upper_bound: float, repeats: int) -> float:\n \"\"\"\n >>> secant_method(1, 3, 2)\n 0.2139409276214589\n \"\"\"\n x0 = lower_bound\n x1 = upper_bound\n for _ in range(repeats):\n x0, x1 = x1, x1 - (f(x1) * (x1 - x0)) \/ (f(x1) - f(x0))\n return x1\n\n\nif __name__ == \"__main__\":\n print(f\"Example: {secant_method(1, 3, 2)}\")\n"} +{"Prompt":"Numerical integration or quadrature for a smooth function f with known values at xi This method is the classical approach of summing 'Equally Spaced Abscissas' method 2: Simpson Rule Simpson Rule intf deltax2 ba3f1 4f2 2f3 ... fn Calculate the definite integral of a function using Simpson's Rule. :param boundary: A list containing the lower and upper bounds of integration. :param steps: The number of steps or resolution for the integration. :return: The approximate integral value. roundmethod20, 2, 4, 10, 10 2.6666666667 roundmethod22, 0, 10, 10 0.2666666667 roundmethod22, 1, 10, 10 2.172 roundmethod20, 1, 10, 10 0.3333333333 roundmethod20, 2, 10, 10 2.6666666667 roundmethod20, 2, 100, 10 2.5621226667 roundmethod20, 1, 1000, 10 0.3320026653 roundmethod20, 2, 0, 10 Traceback most recent call last: ... ZeroDivisionError: Number of steps must be greater than zero roundmethod20, 2, 10, 10 Traceback most recent call last: ... ZeroDivisionError: Number of steps must be greater than zero","Completions":"def method_2(boundary: list[int], steps: int) -> float:\n # \"Simpson Rule\"\n # int(f) = delta_x\/2 * (b-a)\/3*(f1 + 4f2 + 2f_3 + ... + fn)\n \"\"\"\n Calculate the definite integral of a function using Simpson's Rule.\n :param boundary: A list containing the lower and upper bounds of integration.\n :param steps: The number of steps or resolution for the integration.\n :return: The approximate integral value.\n\n >>> round(method_2([0, 2, 4], 10), 10)\n 2.6666666667\n >>> round(method_2([2, 0], 10), 10)\n -0.2666666667\n >>> round(method_2([-2, -1], 10), 10)\n 2.172\n >>> round(method_2([0, 1], 10), 10)\n 0.3333333333\n >>> round(method_2([0, 2], 10), 10)\n 2.6666666667\n >>> round(method_2([0, 2], 100), 10)\n 2.5621226667\n >>> round(method_2([0, 1], 1000), 10)\n 0.3320026653\n >>> round(method_2([0, 2], 0), 10)\n Traceback (most recent call last):\n ...\n ZeroDivisionError: Number of steps must be greater than zero\n >>> round(method_2([0, 2], -10), 10)\n Traceback (most recent call last):\n ...\n ZeroDivisionError: Number of steps must be greater than zero\n \"\"\"\n if steps <= 0:\n raise ZeroDivisionError(\"Number of steps must be greater than zero\")\n\n h = (boundary[1] - boundary[0]) \/ steps\n a = boundary[0]\n b = boundary[1]\n x_i = make_points(a, b, h)\n y = 0.0\n y += (h \/ 3.0) * f(a)\n cnt = 2\n for i in x_i:\n y += (h \/ 3) * (4 - 2 * (cnt % 2)) * f(i)\n cnt += 1\n y += (h \/ 3.0) * f(b)\n return y\n\n\ndef make_points(a, b, h):\n x = a + h\n while x < (b - h):\n yield x\n x = x + h\n\n\ndef f(x): # enter your function here\n y = (x - 0) * (x - 0)\n return y\n\n\ndef main():\n a = 0.0 # Lower bound of integration\n b = 1.0 # Upper bound of integration\n steps = 10.0 # number of steps or resolution\n boundary = [a, b] # boundary of integration\n y = method_2(boundary, steps)\n print(f\"y = {y}\")\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n main()\n"} +{"Prompt":"Square root approximated using Newton's method. https:en.wikipedia.orgwikiNewton27smethod allabssquarerootiterativei math.sqrti 1e14 for i in range500 True squarerootiterative1 Traceback most recent call last: ... ValueError: math domain error squarerootiterative4 2.0 squarerootiterative3.2 1.788854381999832 squarerootiterative140 11.832159566199232","Completions":"import math\n\n\ndef fx(x: float, a: float) -> float:\n return math.pow(x, 2) - a\n\n\ndef fx_derivative(x: float) -> float:\n return 2 * x\n\n\ndef get_initial_point(a: float) -> float:\n start = 2.0\n\n while start <= a:\n start = math.pow(start, 2)\n\n return start\n\n\ndef square_root_iterative(\n a: float, max_iter: int = 9999, tolerance: float = 1e-14\n) -> float:\n \"\"\"\n Square root approximated using Newton's method.\n https:\/\/en.wikipedia.org\/wiki\/Newton%27s_method\n\n >>> all(abs(square_root_iterative(i) - math.sqrt(i)) <= 1e-14 for i in range(500))\n True\n\n >>> square_root_iterative(-1)\n Traceback (most recent call last):\n ...\n ValueError: math domain error\n\n >>> square_root_iterative(4)\n 2.0\n\n >>> square_root_iterative(3.2)\n 1.788854381999832\n\n >>> square_root_iterative(140)\n 11.832159566199232\n \"\"\"\n\n if a < 0:\n raise ValueError(\"math domain error\")\n\n value = get_initial_point(a)\n\n for _ in range(max_iter):\n prev_value = value\n value = value - fx(value, a) \/ fx_derivative(value)\n if abs(prev_value - value) < tolerance:\n return value\n\n return value\n\n\nif __name__ == \"__main__\":\n from doctest import testmod\n\n testmod()\n"} +{"Prompt":"Returns the prime numbers num. The prime numbers are calculated using an odd sieve implementation of the Sieve of Eratosthenes algorithm see for reference https:en.wikipedia.orgwikiSieveofEratosthenes. oddsieve2 oddsieve3 2 oddsieve10 2, 3, 5, 7 oddsieve20 2, 3, 5, 7, 11, 13, 17, 19 Odd sieve for numbers in range 3, num 1","Completions":"from itertools import compress, repeat\nfrom math import ceil, sqrt\n\n\ndef odd_sieve(num: int) -> list[int]:\n \"\"\"\n Returns the prime numbers < `num`. The prime numbers are calculated using an\n odd sieve implementation of the Sieve of Eratosthenes algorithm\n (see for reference https:\/\/en.wikipedia.org\/wiki\/Sieve_of_Eratosthenes).\n\n >>> odd_sieve(2)\n []\n >>> odd_sieve(3)\n [2]\n >>> odd_sieve(10)\n [2, 3, 5, 7]\n >>> odd_sieve(20)\n [2, 3, 5, 7, 11, 13, 17, 19]\n \"\"\"\n\n if num <= 2:\n return []\n if num == 3:\n return [2]\n\n # Odd sieve for numbers in range [3, num - 1]\n sieve = bytearray(b\"\\x01\") * ((num >> 1) - 1)\n\n for i in range(3, int(sqrt(num)) + 1, 2):\n if sieve[(i >> 1) - 1]:\n i_squared = i**2\n sieve[(i_squared >> 1) - 1 :: i] = repeat(\n 0, ceil((num - i_squared) \/ (i << 1))\n )\n\n return [2] + list(compress(range(3, num, 2), sieve))\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Check if a number is a perfect cube or not. perfectcube27 True perfectcube4 False Check if a number is a perfect cube or not using binary search. Time complexity : OLogn Space complexity: O1 perfectcubebinarysearch27 True perfectcubebinarysearch64 True perfectcubebinarysearch4 False perfectcubebinarysearcha Traceback most recent call last: ... TypeError: perfectcubebinarysearch only accepts integers perfectcubebinarysearch0.1 Traceback most recent call last: ... TypeError: perfectcubebinarysearch only accepts integers","Completions":"def perfect_cube(n: int) -> bool:\n \"\"\"\n Check if a number is a perfect cube or not.\n\n >>> perfect_cube(27)\n True\n >>> perfect_cube(4)\n False\n \"\"\"\n val = n ** (1 \/ 3)\n return (val * val * val) == n\n\n\ndef perfect_cube_binary_search(n: int) -> bool:\n \"\"\"\n Check if a number is a perfect cube or not using binary search.\n Time complexity : O(Log(n))\n Space complexity: O(1)\n\n >>> perfect_cube_binary_search(27)\n True\n >>> perfect_cube_binary_search(64)\n True\n >>> perfect_cube_binary_search(4)\n False\n >>> perfect_cube_binary_search(\"a\")\n Traceback (most recent call last):\n ...\n TypeError: perfect_cube_binary_search() only accepts integers\n >>> perfect_cube_binary_search(0.1)\n Traceback (most recent call last):\n ...\n TypeError: perfect_cube_binary_search() only accepts integers\n \"\"\"\n if not isinstance(n, int):\n raise TypeError(\"perfect_cube_binary_search() only accepts integers\")\n if n < 0:\n n = -n\n left = 0\n right = n\n while left <= right:\n mid = left + (right - left) \/\/ 2\n if mid * mid * mid == n:\n return True\n elif mid * mid * mid < n:\n left = mid + 1\n else:\n right = mid - 1\n return False\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Perfect Number In number theory, a perfect number is a positive integer that is equal to the sum of its positive divisors, excluding the number itself. For example: 6 divisors1, 2, 3, 6 Excluding 6, the sumdivisors is 1 2 3 6 So, 6 is a Perfect Number Other examples of Perfect Numbers: 28, 486, ... https:en.wikipedia.orgwikiPerfectnumber Check if a number is a perfect number. A perfect number is a positive integer that is equal to the sum of its proper divisors excluding itself. Args: number: The number to be checked. Returns: True if the number is a perfect number otherwise, False. Start from 1 because dividing by 0 will raise ZeroDivisionError. A number at most can be divisible by the half of the number except the number itself. For example, 6 is at most can be divisible by 3 except by 6 itself. Examples: perfect27 False perfect28 True perfect29 False perfect6 True perfect12 False perfect496 True perfect8128 True perfect0 False perfect1 False perfect12.34 Traceback most recent call last: ... ValueError: number must an integer perfectHello Traceback most recent call last: ... ValueError: number must an integer","Completions":"def perfect(number: int) -> bool:\n \"\"\"\n Check if a number is a perfect number.\n\n A perfect number is a positive integer that is equal to the sum of its proper\n divisors (excluding itself).\n\n Args:\n number: The number to be checked.\n\n Returns:\n True if the number is a perfect number otherwise, False.\n Start from 1 because dividing by 0 will raise ZeroDivisionError.\n A number at most can be divisible by the half of the number except the number\n itself. For example, 6 is at most can be divisible by 3 except by 6 itself.\n Examples:\n >>> perfect(27)\n False\n >>> perfect(28)\n True\n >>> perfect(29)\n False\n >>> perfect(6)\n True\n >>> perfect(12)\n False\n >>> perfect(496)\n True\n >>> perfect(8128)\n True\n >>> perfect(0)\n False\n >>> perfect(-1)\n False\n >>> perfect(12.34)\n Traceback (most recent call last):\n ...\n ValueError: number must an integer\n >>> perfect(\"Hello\")\n Traceback (most recent call last):\n ...\n ValueError: number must an integer\n \"\"\"\n if not isinstance(number, int):\n raise ValueError(\"number must an integer\")\n if number <= 0:\n return False\n return sum(i for i in range(1, number \/\/ 2 + 1) if number % i == 0) == number\n\n\nif __name__ == \"__main__\":\n from doctest import testmod\n\n testmod()\n print(\"Program to check whether a number is a Perfect number or not...\")\n try:\n number = int(input(\"Enter a positive integer: \").strip())\n except ValueError:\n msg = \"number must an integer\"\n print(msg)\n raise ValueError(msg)\n\n print(f\"{number} is {'' if perfect(number) else 'not '}a Perfect Number.\")\n"} +{"Prompt":"Check if a number is perfect square number or not :param num: the number to be checked :return: True if number is square number, otherwise False perfectsquare9 True perfectsquare16 True perfectsquare1 True perfectsquare0 True perfectsquare10 False Check if a number is perfect square using binary search. Time complexity : OLogn Space complexity: O1 perfectsquarebinarysearch9 True perfectsquarebinarysearch16 True perfectsquarebinarysearch1 True perfectsquarebinarysearch0 True perfectsquarebinarysearch10 False perfectsquarebinarysearch1 False perfectsquarebinarysearch1.1 False perfectsquarebinarysearcha Traceback most recent call last: ... TypeError: '' not supported between instances of 'int' and 'str' perfectsquarebinarysearchNone Traceback most recent call last: ... TypeError: '' not supported between instances of 'int' and 'NoneType' perfectsquarebinarysearch Traceback most recent call last: ... TypeError: '' not supported between instances of 'int' and 'list'","Completions":"import math\n\n\ndef perfect_square(num: int) -> bool:\n \"\"\"\n Check if a number is perfect square number or not\n :param num: the number to be checked\n :return: True if number is square number, otherwise False\n\n >>> perfect_square(9)\n True\n >>> perfect_square(16)\n True\n >>> perfect_square(1)\n True\n >>> perfect_square(0)\n True\n >>> perfect_square(10)\n False\n \"\"\"\n return math.sqrt(num) * math.sqrt(num) == num\n\n\ndef perfect_square_binary_search(n: int) -> bool:\n \"\"\"\n Check if a number is perfect square using binary search.\n Time complexity : O(Log(n))\n Space complexity: O(1)\n\n >>> perfect_square_binary_search(9)\n True\n >>> perfect_square_binary_search(16)\n True\n >>> perfect_square_binary_search(1)\n True\n >>> perfect_square_binary_search(0)\n True\n >>> perfect_square_binary_search(10)\n False\n >>> perfect_square_binary_search(-1)\n False\n >>> perfect_square_binary_search(1.1)\n False\n >>> perfect_square_binary_search(\"a\")\n Traceback (most recent call last):\n ...\n TypeError: '<=' not supported between instances of 'int' and 'str'\n >>> perfect_square_binary_search(None)\n Traceback (most recent call last):\n ...\n TypeError: '<=' not supported between instances of 'int' and 'NoneType'\n >>> perfect_square_binary_search([])\n Traceback (most recent call last):\n ...\n TypeError: '<=' not supported between instances of 'int' and 'list'\n \"\"\"\n left = 0\n right = n\n while left <= right:\n mid = (left + right) \/\/ 2\n if mid**2 == n:\n return True\n elif mid**2 > n:\n right = mid - 1\n else:\n left = mid + 1\n return False\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Return the persistence of a given number. https:en.wikipedia.orgwikiPersistenceofanumber multiplicativepersistence217 2 multiplicativepersistence1 Traceback most recent call last: ... ValueError: multiplicativepersistence does not accept negative values multiplicativepersistencelong number Traceback most recent call last: ... ValueError: multiplicativepersistence only accepts integral values Return the persistence of a given number. https:en.wikipedia.orgwikiPersistenceofanumber additivepersistence199 3 additivepersistence1 Traceback most recent call last: ... ValueError: additivepersistence does not accept negative values additivepersistencelong number Traceback most recent call last: ... ValueError: additivepersistence only accepts integral values","Completions":"def multiplicative_persistence(num: int) -> int:\n \"\"\"\n Return the persistence of a given number.\n\n https:\/\/en.wikipedia.org\/wiki\/Persistence_of_a_number\n\n >>> multiplicative_persistence(217)\n 2\n >>> multiplicative_persistence(-1)\n Traceback (most recent call last):\n ...\n ValueError: multiplicative_persistence() does not accept negative values\n >>> multiplicative_persistence(\"long number\")\n Traceback (most recent call last):\n ...\n ValueError: multiplicative_persistence() only accepts integral values\n \"\"\"\n\n if not isinstance(num, int):\n raise ValueError(\"multiplicative_persistence() only accepts integral values\")\n if num < 0:\n raise ValueError(\"multiplicative_persistence() does not accept negative values\")\n\n steps = 0\n num_string = str(num)\n\n while len(num_string) != 1:\n numbers = [int(i) for i in num_string]\n\n total = 1\n for i in range(len(numbers)):\n total *= numbers[i]\n\n num_string = str(total)\n\n steps += 1\n return steps\n\n\ndef additive_persistence(num: int) -> int:\n \"\"\"\n Return the persistence of a given number.\n\n https:\/\/en.wikipedia.org\/wiki\/Persistence_of_a_number\n\n >>> additive_persistence(199)\n 3\n >>> additive_persistence(-1)\n Traceback (most recent call last):\n ...\n ValueError: additive_persistence() does not accept negative values\n >>> additive_persistence(\"long number\")\n Traceback (most recent call last):\n ...\n ValueError: additive_persistence() only accepts integral values\n \"\"\"\n\n if not isinstance(num, int):\n raise ValueError(\"additive_persistence() only accepts integral values\")\n if num < 0:\n raise ValueError(\"additive_persistence() does not accept negative values\")\n\n steps = 0\n num_string = str(num)\n\n while len(num_string) != 1:\n numbers = [int(i) for i in num_string]\n\n total = 0\n for i in range(len(numbers)):\n total += numbers[i]\n\n num_string = str(total)\n\n steps += 1\n return steps\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"https:en.wikipedia.orgwikiLeibnizformulaforCF80 Leibniz Formula for Pi The Leibniz formula is the special case arctan1 pi 4. Leibniz's formula converges extremely slowly: it exhibits sublinear convergence. Convergence https:en.wikipedia.orgwikiLeibnizformulaforCF80Convergence We cannot try to prove against an interrupted, uncompleted generation. https:en.wikipedia.orgwikiLeibnizformulaforCF80Unusualbehaviour The errors can in fact be predicted, but those calculations also approach infinity for accuracy. Our output will be a string so that we can definitely store all digits. import math floatcalculatepi15 math.pi True Since we cannot predict errors or interrupt any infinite alternating series generation since they approach infinity, or interrupt any alternating series, we'll need math.isclose math.isclosefloatcalculatepi50, math.pi True math.isclosefloatcalculatepi100, math.pi True Since math.pi contains only 16 digits, here are some tests with known values: calculatepi50 '3.14159265358979323846264338327950288419716939937510' calculatepi80 '3.14159265358979323846264338327950288419716939937510582097494459230781640628620899' Variables used for the iteration process We can't compare against anything if we make a generator, so we'll stick with plain return logic","Completions":"def calculate_pi(limit: int) -> str:\n \"\"\"\n https:\/\/en.wikipedia.org\/wiki\/Leibniz_formula_for_%CF%80\n Leibniz Formula for Pi\n\n The Leibniz formula is the special case arctan(1) = pi \/ 4.\n Leibniz's formula converges extremely slowly: it exhibits sublinear convergence.\n\n Convergence (https:\/\/en.wikipedia.org\/wiki\/Leibniz_formula_for_%CF%80#Convergence)\n\n We cannot try to prove against an interrupted, uncompleted generation.\n https:\/\/en.wikipedia.org\/wiki\/Leibniz_formula_for_%CF%80#Unusual_behaviour\n The errors can in fact be predicted, but those calculations also approach infinity\n for accuracy.\n\n Our output will be a string so that we can definitely store all digits.\n\n >>> import math\n >>> float(calculate_pi(15)) == math.pi\n True\n\n Since we cannot predict errors or interrupt any infinite alternating series\n generation since they approach infinity, or interrupt any alternating series, we'll\n need math.isclose()\n\n >>> math.isclose(float(calculate_pi(50)), math.pi)\n True\n >>> math.isclose(float(calculate_pi(100)), math.pi)\n True\n\n Since math.pi contains only 16 digits, here are some tests with known values:\n\n >>> calculate_pi(50)\n '3.14159265358979323846264338327950288419716939937510'\n >>> calculate_pi(80)\n '3.14159265358979323846264338327950288419716939937510582097494459230781640628620899'\n \"\"\"\n # Variables used for the iteration process\n q = 1\n r = 0\n t = 1\n k = 1\n n = 3\n l = 3\n\n decimal = limit\n counter = 0\n\n result = \"\"\n\n # We can't compare against anything if we make a generator,\n # so we'll stick with plain return logic\n while counter != decimal + 1:\n if 4 * q + r - t < n * t:\n result += str(n)\n if counter == 0:\n result += \".\"\n\n if decimal == counter:\n break\n\n counter += 1\n nr = 10 * (r - n * t)\n n = ((10 * (3 * q + r)) \/\/ t) - 10 * n\n q *= 10\n r = nr\n else:\n nr = (2 * q + r) * l\n nn = (q * (7 * k) + 2 + (r * l)) \/\/ (t * l)\n q *= k\n t *= l\n l += 2\n k += 1\n n = nn\n r = nr\n return result\n\n\ndef main() -> None:\n print(f\"{calculate_pi(50) = }\")\n import doctest\n\n doctest.testmod()\n\n\nif __name__ == \"__main__\":\n main()\n"} +{"Prompt":"True, if the point lies in the unit circle False, otherwise Generates a point randomly drawn from the unit square 0, 1 x 0, 1. Generates an estimate of the mathematical constant PI. See https:en.wikipedia.orgwikiMonteCarlomethodOverview The estimate is generated by Monte Carlo simulations. Let U be uniformly drawn from the unit square 0, 1 x 0, 1. The probability that U lies in the unit circle is: PU in unit circle 14 PI and therefore PI 4 PU in unit circle We can get an estimate of the probability PU in unit circle. See https:en.wikipedia.orgwikiEmpiricalprobability by: 1. Draw a point uniformly from the unit square. 2. Repeat the first step n times and count the number of points in the unit circle, which is called m. 3. An estimate of PU in unit circle is mn import doctest doctest.testmod","Completions":"import random\n\n\nclass Point:\n def __init__(self, x: float, y: float) -> None:\n self.x = x\n self.y = y\n\n def is_in_unit_circle(self) -> bool:\n \"\"\"\n True, if the point lies in the unit circle\n False, otherwise\n \"\"\"\n return (self.x**2 + self.y**2) <= 1\n\n @classmethod\n def random_unit_square(cls):\n \"\"\"\n Generates a point randomly drawn from the unit square [0, 1) x [0, 1).\n \"\"\"\n return cls(x=random.random(), y=random.random())\n\n\ndef estimate_pi(number_of_simulations: int) -> float:\n \"\"\"\n Generates an estimate of the mathematical constant PI.\n See https:\/\/en.wikipedia.org\/wiki\/Monte_Carlo_method#Overview\n\n The estimate is generated by Monte Carlo simulations. Let U be uniformly drawn from\n the unit square [0, 1) x [0, 1). The probability that U lies in the unit circle is:\n\n P[U in unit circle] = 1\/4 PI\n\n and therefore\n\n PI = 4 * P[U in unit circle]\n\n We can get an estimate of the probability P[U in unit circle].\n See https:\/\/en.wikipedia.org\/wiki\/Empirical_probability by:\n\n 1. Draw a point uniformly from the unit square.\n 2. Repeat the first step n times and count the number of points in the unit\n circle, which is called m.\n 3. An estimate of P[U in unit circle] is m\/n\n \"\"\"\n if number_of_simulations < 1:\n raise ValueError(\"At least one simulation is necessary to estimate PI.\")\n\n number_in_unit_circle = 0\n for _ in range(number_of_simulations):\n random_point = Point.random_unit_square()\n\n if random_point.is_in_unit_circle():\n number_in_unit_circle += 1\n\n return 4 * number_in_unit_circle \/ number_of_simulations\n\n\nif __name__ == \"__main__\":\n # import doctest\n\n # doctest.testmod()\n from math import pi\n\n prompt = \"Please enter the desired number of Monte Carlo simulations: \"\n my_pi = estimate_pi(int(input(prompt).strip()))\n print(f\"An estimate of PI is {my_pi} with an error of {abs(my_pi - pi)}\")\n"} +{"Prompt":"Check if three points are collinear in 3D. In short, the idea is that we are able to create a triangle using three points, and the area of that triangle can determine if the three points are collinear or not. First, we create two vectors with the same initial point from the three points, then we will calculate the crossproduct of them. The length of the cross vector is numerically equal to the area of a parallelogram. Finally, the area of the triangle is equal to half of the area of the parallelogram. Since we are only differentiating between zero and anything else, we can get rid of the square root when calculating the length of the vector, and also the division by two at the end. From a second perspective, if the two vectors are parallel and overlapping, we can't get a nonzero perpendicular vector, since there will be an infinite number of orthogonal vectors. To simplify the solution we will not calculate the length, but we will decide directly from the vector whether it is equal to 0, 0, 0 or not. Read More: https:math.stackexchange.coma1951650 Pass two points to get the vector from them in the form x, y, z. createvector0, 0, 0, 1, 1, 1 1, 1, 1 createvector45, 70, 24, 47, 32, 1 2, 38, 23 createvector14, 1, 8, 7, 6, 4 7, 7, 12 Get the cross of the two vectors AB and AC. I used determinant of 2x2 to get the determinant of the 3x3 matrix in the process. Read More: https:en.wikipedia.orgwikiCrossproduct https:en.wikipedia.orgwikiDeterminant get3dvectorscross3, 4, 7, 4, 9, 2 55, 22, 11 get3dvectorscross1, 1, 1, 1, 1, 1 0, 0, 0 get3dvectorscross4, 3, 0, 3, 9, 12 36, 48, 27 get3dvectorscross17.67, 4.7, 6.78, 9.5, 4.78, 19.33 123.2594, 277.15110000000004, 129.11260000000001 Check if vector is equal to 0, 0, 0 of not. Sine the algorithm is very accurate, we will never get a zero vector, so we need to round the vector axis, because we want a result that is either True or False. In other applications, we can return a float that represents the collinearity ratio. iszerovector0, 0, 0, accuracy10 True iszerovector15, 74, 32, accuracy10 False iszerovector15, 74, 32, accuracy10 False Check if three points are collinear or not. 1 Create tow vectors AB and AC. 2 Get the cross vector of the tow vectors. 3 Calcolate the length of the cross vector. 4 If the length is zero then the points are collinear, else they are not. The use of the accuracy parameter is explained in iszerovector docstring. arecollinear4.802293498137402, 3.536233125455244, 0, ... 2.186788107953106, 9.24561398001649, 7.141509524846482, ... 1.530169574640268, 2.447927606600034, 3.343487096469054 True arecollinear6, 2, 6, ... 6.200213806439997, 4.930157614926678, 4.482371908289856, ... 4.085171149525941, 2.459889509029438, 4.354787180795383 True arecollinear2.399001826862445, 2.452009976680793, 4.464656666157666, ... 3.682816335934376, 5.753788986533145, 9.490993909044244, ... 1.962903518985307, 3.741415730125627, 7 False arecollinear1.875375340689544, 7.268426006071538, 7.358196269835993, ... 3.546599383667157, 4.630005261513976, 3.208784032924246, ... 2.564606140206386, 3.937845170672183, 7 False","Completions":"Vector3d = tuple[float, float, float]\nPoint3d = tuple[float, float, float]\n\n\ndef create_vector(end_point1: Point3d, end_point2: Point3d) -> Vector3d:\n \"\"\"\n Pass two points to get the vector from them in the form (x, y, z).\n\n >>> create_vector((0, 0, 0), (1, 1, 1))\n (1, 1, 1)\n >>> create_vector((45, 70, 24), (47, 32, 1))\n (2, -38, -23)\n >>> create_vector((-14, -1, -8), (-7, 6, 4))\n (7, 7, 12)\n \"\"\"\n x = end_point2[0] - end_point1[0]\n y = end_point2[1] - end_point1[1]\n z = end_point2[2] - end_point1[2]\n return (x, y, z)\n\n\ndef get_3d_vectors_cross(ab: Vector3d, ac: Vector3d) -> Vector3d:\n \"\"\"\n Get the cross of the two vectors AB and AC.\n\n I used determinant of 2x2 to get the determinant of the 3x3 matrix in the process.\n\n Read More:\n https:\/\/en.wikipedia.org\/wiki\/Cross_product\n https:\/\/en.wikipedia.org\/wiki\/Determinant\n\n >>> get_3d_vectors_cross((3, 4, 7), (4, 9, 2))\n (-55, 22, 11)\n >>> get_3d_vectors_cross((1, 1, 1), (1, 1, 1))\n (0, 0, 0)\n >>> get_3d_vectors_cross((-4, 3, 0), (3, -9, -12))\n (-36, -48, 27)\n >>> get_3d_vectors_cross((17.67, 4.7, 6.78), (-9.5, 4.78, -19.33))\n (-123.2594, 277.15110000000004, 129.11260000000001)\n \"\"\"\n x = ab[1] * ac[2] - ab[2] * ac[1] # *i\n y = (ab[0] * ac[2] - ab[2] * ac[0]) * -1 # *j\n z = ab[0] * ac[1] - ab[1] * ac[0] # *k\n return (x, y, z)\n\n\ndef is_zero_vector(vector: Vector3d, accuracy: int) -> bool:\n \"\"\"\n Check if vector is equal to (0, 0, 0) of not.\n\n Sine the algorithm is very accurate, we will never get a zero vector,\n so we need to round the vector axis,\n because we want a result that is either True or False.\n In other applications, we can return a float that represents the collinearity ratio.\n\n >>> is_zero_vector((0, 0, 0), accuracy=10)\n True\n >>> is_zero_vector((15, 74, 32), accuracy=10)\n False\n >>> is_zero_vector((-15, -74, -32), accuracy=10)\n False\n \"\"\"\n return tuple(round(x, accuracy) for x in vector) == (0, 0, 0)\n\n\ndef are_collinear(a: Point3d, b: Point3d, c: Point3d, accuracy: int = 10) -> bool:\n \"\"\"\n Check if three points are collinear or not.\n\n 1- Create tow vectors AB and AC.\n 2- Get the cross vector of the tow vectors.\n 3- Calcolate the length of the cross vector.\n 4- If the length is zero then the points are collinear, else they are not.\n\n The use of the accuracy parameter is explained in is_zero_vector docstring.\n\n >>> are_collinear((4.802293498137402, 3.536233125455244, 0),\n ... (-2.186788107953106, -9.24561398001649, 7.141509524846482),\n ... (1.530169574640268, -2.447927606600034, 3.343487096469054))\n True\n >>> are_collinear((-6, -2, 6),\n ... (6.200213806439997, -4.930157614926678, -4.482371908289856),\n ... (-4.085171149525941, -2.459889509029438, 4.354787180795383))\n True\n >>> are_collinear((2.399001826862445, -2.452009976680793, 4.464656666157666),\n ... (-3.682816335934376, 5.753788986533145, 9.490993909044244),\n ... (1.962903518985307, 3.741415730125627, 7))\n False\n >>> are_collinear((1.875375340689544, -7.268426006071538, 7.358196269835993),\n ... (-3.546599383667157, -4.630005261513976, 3.208784032924246),\n ... (-2.564606140206386, 3.937845170672183, 7))\n False\n \"\"\"\n ab = create_vector(a, b)\n ac = create_vector(a, c)\n return is_zero_vector(get_3d_vectors_cross(ab, ac), accuracy)\n"} +{"Prompt":"Use Pollard's Rho algorithm to return a nontrivial factor of num. The returned factor may be composite and require further factorization. If the algorithm will return None if it fails to find a factor within the specified number of attempts or within the specified number of steps. If num is prime, this algorithm is guaranteed to return None. https:en.wikipedia.orgwikiPollard27srhoalgorithm pollardrho18446744073709551617 274177 pollardrho97546105601219326301 9876543191 pollardrho100 2 pollardrho17 pollardrho173 17 pollardrho173, attempts1 pollardrho357 21 pollardrho1 Traceback most recent call last: ... ValueError: The input value cannot be less than 2 A value less than 2 can cause an infinite loop in the algorithm. Because of the relationship between ffx and fx, this algorithm struggles to find factors that are divisible by two. As a workaround, we specifically check for two and even inputs. See: https:math.stackexchange.coma2856214165820 Pollard's Rho algorithm requires a function that returns pseudorandom values between 0 X num. It doesn't need to be random in the sense that the output value is cryptographically secure or difficult to calculate, it only needs to be random in the sense that all output values should be equally likely to appear. For this reason, Pollard suggested using fx x2 1 num However, the success of Pollard's algorithm isn't guaranteed and is determined in part by the initial seed and the chosen random function. To make retries easier, we will instead use fx x2 C num where C is a value that we can modify between each attempt. Returns a pseudorandom value modulo modulus based on the input value and attemptspecific step size. randfn0, 0, 0 Traceback most recent call last: ... ZeroDivisionError: integer division or modulo by zero randfn1, 2, 3 0 randfn0, 10, 7 3 randfn1234, 1, 17 16 These track the position within the cycle detection logic. At each iteration, the tortoise moves one step and the hare moves two. At some point both the tortoise and the hare will enter a cycle whose length p is a divisor of num. Once in that cycle, at some point the tortoise and hare will end up on the same value modulo p. We can detect when this happens because the position difference between the tortoise and the hare will share a common divisor with num. No common divisor yet, just keep searching. We found a common divisor! Unfortunately, the divisor is num itself and is useless. The divisor is a nontrivial factor of num! If we made it here, then this attempt failed. We need to pick a new starting seed for the tortoise and hare in addition to a new step value for the random function. To keep this example implementation deterministic, the new values will be generated based on currently available values instead of using something like random.randint. We can use the hare's position as the new seed. This is actually what Richard Brent's the optimized variant does. The new step value for the random function can just be incremented. At first the results will be similar to what the old function would have produced, but the value will quickly diverge after a bit. We haven't found a divisor within the requested number of attempts. We were unlucky or num itself is actually prime.","Completions":"from __future__ import annotations\n\nfrom math import gcd\n\n\ndef pollard_rho(\n num: int,\n seed: int = 2,\n step: int = 1,\n attempts: int = 3,\n) -> int | None:\n \"\"\"\n Use Pollard's Rho algorithm to return a nontrivial factor of ``num``.\n The returned factor may be composite and require further factorization.\n If the algorithm will return None if it fails to find a factor within\n the specified number of attempts or within the specified number of steps.\n If ``num`` is prime, this algorithm is guaranteed to return None.\n https:\/\/en.wikipedia.org\/wiki\/Pollard%27s_rho_algorithm\n\n >>> pollard_rho(18446744073709551617)\n 274177\n >>> pollard_rho(97546105601219326301)\n 9876543191\n >>> pollard_rho(100)\n 2\n >>> pollard_rho(17)\n >>> pollard_rho(17**3)\n 17\n >>> pollard_rho(17**3, attempts=1)\n >>> pollard_rho(3*5*7)\n 21\n >>> pollard_rho(1)\n Traceback (most recent call last):\n ...\n ValueError: The input value cannot be less than 2\n \"\"\"\n # A value less than 2 can cause an infinite loop in the algorithm.\n if num < 2:\n raise ValueError(\"The input value cannot be less than 2\")\n\n # Because of the relationship between ``f(f(x))`` and ``f(x)``, this\n # algorithm struggles to find factors that are divisible by two.\n # As a workaround, we specifically check for two and even inputs.\n # See: https:\/\/math.stackexchange.com\/a\/2856214\/165820\n if num > 2 and num % 2 == 0:\n return 2\n\n # Pollard's Rho algorithm requires a function that returns pseudorandom\n # values between 0 <= X < ``num``. It doesn't need to be random in the\n # sense that the output value is cryptographically secure or difficult\n # to calculate, it only needs to be random in the sense that all output\n # values should be equally likely to appear.\n # For this reason, Pollard suggested using ``f(x) = (x**2 - 1) % num``\n # However, the success of Pollard's algorithm isn't guaranteed and is\n # determined in part by the initial seed and the chosen random function.\n # To make retries easier, we will instead use ``f(x) = (x**2 + C) % num``\n # where ``C`` is a value that we can modify between each attempt.\n def rand_fn(value: int, step: int, modulus: int) -> int:\n \"\"\"\n Returns a pseudorandom value modulo ``modulus`` based on the\n input ``value`` and attempt-specific ``step`` size.\n\n >>> rand_fn(0, 0, 0)\n Traceback (most recent call last):\n ...\n ZeroDivisionError: integer division or modulo by zero\n >>> rand_fn(1, 2, 3)\n 0\n >>> rand_fn(0, 10, 7)\n 3\n >>> rand_fn(1234, 1, 17)\n 16\n \"\"\"\n return (pow(value, 2) + step) % modulus\n\n for _ in range(attempts):\n # These track the position within the cycle detection logic.\n tortoise = seed\n hare = seed\n\n while True:\n # At each iteration, the tortoise moves one step and the hare moves two.\n tortoise = rand_fn(tortoise, step, num)\n hare = rand_fn(hare, step, num)\n hare = rand_fn(hare, step, num)\n\n # At some point both the tortoise and the hare will enter a cycle whose\n # length ``p`` is a divisor of ``num``. Once in that cycle, at some point\n # the tortoise and hare will end up on the same value modulo ``p``.\n # We can detect when this happens because the position difference between\n # the tortoise and the hare will share a common divisor with ``num``.\n divisor = gcd(hare - tortoise, num)\n\n if divisor == 1:\n # No common divisor yet, just keep searching.\n continue\n else:\n # We found a common divisor!\n if divisor == num:\n # Unfortunately, the divisor is ``num`` itself and is useless.\n break\n else:\n # The divisor is a nontrivial factor of ``num``!\n return divisor\n\n # If we made it here, then this attempt failed.\n # We need to pick a new starting seed for the tortoise and hare\n # in addition to a new step value for the random function.\n # To keep this example implementation deterministic, the\n # new values will be generated based on currently available\n # values instead of using something like ``random.randint``.\n\n # We can use the hare's position as the new seed.\n # This is actually what Richard Brent's the \"optimized\" variant does.\n seed = hare\n\n # The new step value for the random function can just be incremented.\n # At first the results will be similar to what the old function would\n # have produced, but the value will quickly diverge after a bit.\n step += 1\n\n # We haven't found a divisor within the requested number of attempts.\n # We were unlucky or ``num`` itself is actually prime.\n return None\n\n\nif __name__ == \"__main__\":\n import argparse\n\n parser = argparse.ArgumentParser()\n parser.add_argument(\n \"num\",\n type=int,\n help=\"The value to find a divisor of\",\n )\n parser.add_argument(\n \"--attempts\",\n type=int,\n default=3,\n help=\"The number of attempts before giving up\",\n )\n args = parser.parse_args()\n\n divisor = pollard_rho(args.num, attempts=args.attempts)\n if divisor is None:\n print(f\"{args.num} is probably prime\")\n else:\n quotient = args.num \/\/ divisor\n print(f\"{args.num} = {divisor} * {quotient}\")\n"} +{"Prompt":"Evaluate a polynomial fx at specified point x and return the value. Arguments: poly the coefficients of a polynomial as an iterable in order of ascending degree x the point at which to evaluate the polynomial evaluatepoly0.0, 0.0, 5.0, 9.3, 7.0, 10.0 79800.0 Evaluate a polynomial at specified point using Horner's method. In terms of computational complexity, Horner's method is an efficient method of evaluating a polynomial. It avoids the use of expensive exponentiation, and instead uses only multiplication and addition to evaluate the polynomial in On, where n is the degree of the polynomial. https:en.wikipedia.orgwikiHorner'smethod Arguments: poly the coefficients of a polynomial as an iterable in order of ascending degree x the point at which to evaluate the polynomial horner0.0, 0.0, 5.0, 9.3, 7.0, 10.0 79800.0 Example: poly 0.0, 0.0, 5.0, 9.3, 7.0 fx 7.0x4 9.3x3 5.0x2 x 13.0 f13 7.0134 9.3133 5.0132 180339.9 evaluatepolypoly, x 180339.9","Completions":"from collections.abc import Sequence\n\n\ndef evaluate_poly(poly: Sequence[float], x: float) -> float:\n \"\"\"Evaluate a polynomial f(x) at specified point x and return the value.\n\n Arguments:\n poly -- the coefficients of a polynomial as an iterable in order of\n ascending degree\n x -- the point at which to evaluate the polynomial\n\n >>> evaluate_poly((0.0, 0.0, 5.0, 9.3, 7.0), 10.0)\n 79800.0\n \"\"\"\n return sum(c * (x**i) for i, c in enumerate(poly))\n\n\ndef horner(poly: Sequence[float], x: float) -> float:\n \"\"\"Evaluate a polynomial at specified point using Horner's method.\n\n In terms of computational complexity, Horner's method is an efficient method\n of evaluating a polynomial. It avoids the use of expensive exponentiation,\n and instead uses only multiplication and addition to evaluate the polynomial\n in O(n), where n is the degree of the polynomial.\n\n https:\/\/en.wikipedia.org\/wiki\/Horner's_method\n\n Arguments:\n poly -- the coefficients of a polynomial as an iterable in order of\n ascending degree\n x -- the point at which to evaluate the polynomial\n\n >>> horner((0.0, 0.0, 5.0, 9.3, 7.0), 10.0)\n 79800.0\n \"\"\"\n result = 0.0\n for coeff in reversed(poly):\n result = result * x + coeff\n return result\n\n\nif __name__ == \"__main__\":\n \"\"\"\n Example:\n >>> poly = (0.0, 0.0, 5.0, 9.3, 7.0) # f(x) = 7.0x^4 + 9.3x^3 + 5.0x^2\n >>> x = -13.0\n >>> # f(-13) = 7.0(-13)^4 + 9.3(-13)^3 + 5.0(-13)^2 = 180339.9\n >>> evaluate_poly(poly, x)\n 180339.9\n \"\"\"\n poly = (0.0, 0.0, 5.0, 9.3, 7.0)\n x = 10.0\n print(evaluate_poly(poly, x))\n print(horner(poly, x))\n"} +{"Prompt":"This module implements a single indeterminate polynomials class with some basic operations Reference: https:en.wikipedia.orgwikiPolynomial The coefficients should be in order of degree, from smallest to largest. p Polynomial2, 1, 2, 3 p Polynomial2, 1, 2, 3, 4 Traceback most recent call last: ... ValueError: The number of coefficients should be equal to the degree 1. Polynomial addition p Polynomial2, 1, 2, 3 q Polynomial2, 1, 2, 3 p q 6x2 4x 2 Polynomial subtraction p Polynomial2, 1, 2, 4 q Polynomial2, 1, 2, 3 p q 1x2 Polynomial negation p Polynomial2, 1, 2, 3 p 3x2 2x 1 Polynomial multiplication p Polynomial2, 1, 2, 3 q Polynomial2, 1, 2, 3 p q 9x4 12x3 10x2 4x 1 Evaluates the polynomial at x. p Polynomial2, 1, 2, 3 p.evaluate2 17 p Polynomial2, 1, 2, 3 printp 3x2 2x 1 p Polynomial2, 1, 2, 3 p 3x2 2x 1 Returns the derivative of the polynomial. p Polynomial2, 1, 2, 3 p.derivative 6x 2 Returns the integral of the polynomial. p Polynomial2, 1, 2, 3 p.integral 1.0x3 1.0x2 1.0x Checks if two polynomials are equal. p Polynomial2, 1, 2, 3 q Polynomial2, 1, 2, 3 p q True Checks if two polynomials are not equal. p Polynomial2, 1, 2, 3 q Polynomial2, 1, 2, 3 p ! q False","Completions":"from __future__ import annotations\n\nfrom collections.abc import MutableSequence\n\n\nclass Polynomial:\n def __init__(self, degree: int, coefficients: MutableSequence[float]) -> None:\n \"\"\"\n The coefficients should be in order of degree, from smallest to largest.\n >>> p = Polynomial(2, [1, 2, 3])\n >>> p = Polynomial(2, [1, 2, 3, 4])\n Traceback (most recent call last):\n ...\n ValueError: The number of coefficients should be equal to the degree + 1.\n\n \"\"\"\n if len(coefficients) != degree + 1:\n raise ValueError(\n \"The number of coefficients should be equal to the degree + 1.\"\n )\n\n self.coefficients: list[float] = list(coefficients)\n self.degree = degree\n\n def __add__(self, polynomial_2: Polynomial) -> Polynomial:\n \"\"\"\n Polynomial addition\n >>> p = Polynomial(2, [1, 2, 3])\n >>> q = Polynomial(2, [1, 2, 3])\n >>> p + q\n 6x^2 + 4x + 2\n \"\"\"\n\n if self.degree > polynomial_2.degree:\n coefficients = self.coefficients[:]\n for i in range(polynomial_2.degree + 1):\n coefficients[i] += polynomial_2.coefficients[i]\n return Polynomial(self.degree, coefficients)\n else:\n coefficients = polynomial_2.coefficients[:]\n for i in range(self.degree + 1):\n coefficients[i] += self.coefficients[i]\n return Polynomial(polynomial_2.degree, coefficients)\n\n def __sub__(self, polynomial_2: Polynomial) -> Polynomial:\n \"\"\"\n Polynomial subtraction\n >>> p = Polynomial(2, [1, 2, 4])\n >>> q = Polynomial(2, [1, 2, 3])\n >>> p - q\n 1x^2\n \"\"\"\n return self + polynomial_2 * Polynomial(0, [-1])\n\n def __neg__(self) -> Polynomial:\n \"\"\"\n Polynomial negation\n >>> p = Polynomial(2, [1, 2, 3])\n >>> -p\n - 3x^2 - 2x - 1\n \"\"\"\n return Polynomial(self.degree, [-c for c in self.coefficients])\n\n def __mul__(self, polynomial_2: Polynomial) -> Polynomial:\n \"\"\"\n Polynomial multiplication\n >>> p = Polynomial(2, [1, 2, 3])\n >>> q = Polynomial(2, [1, 2, 3])\n >>> p * q\n 9x^4 + 12x^3 + 10x^2 + 4x + 1\n \"\"\"\n coefficients: list[float] = [0] * (self.degree + polynomial_2.degree + 1)\n for i in range(self.degree + 1):\n for j in range(polynomial_2.degree + 1):\n coefficients[i + j] += (\n self.coefficients[i] * polynomial_2.coefficients[j]\n )\n\n return Polynomial(self.degree + polynomial_2.degree, coefficients)\n\n def evaluate(self, substitution: float) -> float:\n \"\"\"\n Evaluates the polynomial at x.\n >>> p = Polynomial(2, [1, 2, 3])\n >>> p.evaluate(2)\n 17\n \"\"\"\n result: int | float = 0\n for i in range(self.degree + 1):\n result += self.coefficients[i] * (substitution**i)\n return result\n\n def __str__(self) -> str:\n \"\"\"\n >>> p = Polynomial(2, [1, 2, 3])\n >>> print(p)\n 3x^2 + 2x + 1\n \"\"\"\n polynomial = \"\"\n for i in range(self.degree, -1, -1):\n if self.coefficients[i] == 0:\n continue\n elif self.coefficients[i] > 0:\n if polynomial:\n polynomial += \" + \"\n else:\n polynomial += \" - \"\n\n if i == 0:\n polynomial += str(abs(self.coefficients[i]))\n elif i == 1:\n polynomial += str(abs(self.coefficients[i])) + \"x\"\n else:\n polynomial += str(abs(self.coefficients[i])) + \"x^\" + str(i)\n\n return polynomial\n\n def __repr__(self) -> str:\n \"\"\"\n >>> p = Polynomial(2, [1, 2, 3])\n >>> p\n 3x^2 + 2x + 1\n \"\"\"\n return self.__str__()\n\n def derivative(self) -> Polynomial:\n \"\"\"\n Returns the derivative of the polynomial.\n >>> p = Polynomial(2, [1, 2, 3])\n >>> p.derivative()\n 6x + 2\n \"\"\"\n coefficients: list[float] = [0] * self.degree\n for i in range(self.degree):\n coefficients[i] = self.coefficients[i + 1] * (i + 1)\n return Polynomial(self.degree - 1, coefficients)\n\n def integral(self, constant: float = 0) -> Polynomial:\n \"\"\"\n Returns the integral of the polynomial.\n >>> p = Polynomial(2, [1, 2, 3])\n >>> p.integral()\n 1.0x^3 + 1.0x^2 + 1.0x\n \"\"\"\n coefficients: list[float] = [0] * (self.degree + 2)\n coefficients[0] = constant\n for i in range(self.degree + 1):\n coefficients[i + 1] = self.coefficients[i] \/ (i + 1)\n return Polynomial(self.degree + 1, coefficients)\n\n def __eq__(self, polynomial_2: object) -> bool:\n \"\"\"\n Checks if two polynomials are equal.\n >>> p = Polynomial(2, [1, 2, 3])\n >>> q = Polynomial(2, [1, 2, 3])\n >>> p == q\n True\n \"\"\"\n if not isinstance(polynomial_2, Polynomial):\n return False\n\n if self.degree != polynomial_2.degree:\n return False\n\n for i in range(self.degree + 1):\n if self.coefficients[i] != polynomial_2.coefficients[i]:\n return False\n\n return True\n\n def __ne__(self, polynomial_2: object) -> bool:\n \"\"\"\n Checks if two polynomials are not equal.\n >>> p = Polynomial(2, [1, 2, 3])\n >>> q = Polynomial(2, [1, 2, 3])\n >>> p != q\n False\n \"\"\"\n return not self.__eq__(polynomial_2)\n"} +{"Prompt":"Raise base to the power of exponent using recursion Input Enter the base: 3 Enter the exponent: 4 Output 3 to the power of 4 is 81 Input Enter the base: 2 Enter the exponent: 0 Output 2 to the power of 0 is 1 Calculate the power of a base raised to an exponent. power3, 4 81 power2, 0 1 allpowerbase, exponent powbase, exponent ... for base in range10, 10 for exponent in range10 True power'a', 1 'a' power'a', 2 Traceback most recent call last: ... TypeError: can't multiply sequence by nonint of type 'str' power'a', 'b' Traceback most recent call last: ... TypeError: unsupported operand types for : 'str' and 'int' power2, 1 Traceback most recent call last: ... RecursionError: maximum recursion depth exceeded","Completions":"def power(base: int, exponent: int) -> float:\n \"\"\"\n Calculate the power of a base raised to an exponent.\n\n >>> power(3, 4)\n 81\n >>> power(2, 0)\n 1\n >>> all(power(base, exponent) == pow(base, exponent)\n ... for base in range(-10, 10) for exponent in range(10))\n True\n >>> power('a', 1)\n 'a'\n >>> power('a', 2)\n Traceback (most recent call last):\n ...\n TypeError: can't multiply sequence by non-int of type 'str'\n >>> power('a', 'b')\n Traceback (most recent call last):\n ...\n TypeError: unsupported operand type(s) for -: 'str' and 'int'\n >>> power(2, -1)\n Traceback (most recent call last):\n ...\n RecursionError: maximum recursion depth exceeded\n \"\"\"\n return base * power(base, (exponent - 1)) if exponent else 1\n\n\nif __name__ == \"__main__\":\n from doctest import testmod\n\n testmod()\n print(\"Raise base to the power of exponent using recursion...\")\n base = int(input(\"Enter the base: \").strip())\n exponent = int(input(\"Enter the exponent: \").strip())\n result = power(base, abs(exponent))\n if exponent < 0: # power() does not properly deal w\/ negative exponents\n result = 1 \/ result\n print(f\"{base} to the power of {exponent} is {result}\")\n"} +{"Prompt":"Prime Check. import math import unittest import pytest def isprimenumber: int bool: precondition if not isinstancenumber, int or not number 0: raise ValueErrorisprime only accepts positive integers if 1 number 4: 2 and 3 are primes return True elif number 2 or number 2 0 or number 3 0: Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False All primes number are in format of 6k 1 for i in range5, intmath.sqrtnumber 1, 6: if number i 0 or number i 2 0: return False return True class Testunittest.TestCase: def testprimesself: assert isprime2 assert isprime3 assert isprime5 assert isprime7 assert isprime11 assert isprime13 assert isprime17 assert isprime19 assert isprime23 assert isprime29 def testnotprimesself: with pytest.raisesValueError: isprime19 assert not isprime 0 , Zero doesn't have any positive factors, primes must have exactly two. assert not isprime 1 , One only has 1 positive factor, primes must have exactly two. assert not isprime2 2 assert not isprime2 3 assert not isprime3 3 assert not isprime3 5 assert not isprime3 5 7 if name main: unittest.main","Completions":"import math\nimport unittest\n\nimport pytest\n\n\ndef is_prime(number: int) -> bool:\n \"\"\"Checks to see if a number is a prime in O(sqrt(n)).\n\n A number is prime if it has exactly two factors: 1 and itself.\n\n >>> is_prime(0)\n False\n >>> is_prime(1)\n False\n >>> is_prime(2)\n True\n >>> is_prime(3)\n True\n >>> is_prime(27)\n False\n >>> is_prime(87)\n False\n >>> is_prime(563)\n True\n >>> is_prime(2999)\n True\n >>> is_prime(67483)\n False\n >>> is_prime(16.1)\n Traceback (most recent call last):\n ...\n ValueError: is_prime() only accepts positive integers\n >>> is_prime(-4)\n Traceback (most recent call last):\n ...\n ValueError: is_prime() only accepts positive integers\n \"\"\"\n\n # precondition\n if not isinstance(number, int) or not number >= 0:\n raise ValueError(\"is_prime() only accepts positive integers\")\n\n if 1 < number < 4:\n # 2 and 3 are primes\n return True\n elif number < 2 or number % 2 == 0 or number % 3 == 0:\n # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes\n return False\n\n # All primes number are in format of 6k +\/- 1\n for i in range(5, int(math.sqrt(number) + 1), 6):\n if number % i == 0 or number % (i + 2) == 0:\n return False\n return True\n\n\nclass Test(unittest.TestCase):\n def test_primes(self):\n assert is_prime(2)\n assert is_prime(3)\n assert is_prime(5)\n assert is_prime(7)\n assert is_prime(11)\n assert is_prime(13)\n assert is_prime(17)\n assert is_prime(19)\n assert is_prime(23)\n assert is_prime(29)\n\n def test_not_primes(self):\n with pytest.raises(ValueError):\n is_prime(-19)\n assert not is_prime(\n 0\n ), \"Zero doesn't have any positive factors, primes must have exactly two.\"\n assert not is_prime(\n 1\n ), \"One only has 1 positive factor, primes must have exactly two.\"\n assert not is_prime(2 * 2)\n assert not is_prime(2 * 3)\n assert not is_prime(3 * 3)\n assert not is_prime(3 * 5)\n assert not is_prime(3 * 5 * 7)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n"} +{"Prompt":"pythonblack : True Returns prime factors of n as a list. primefactors0 primefactors100 2, 2, 5, 5 primefactors2560 2, 2, 2, 2, 2, 2, 2, 2, 2, 5 primefactors102 primefactors0.02 x primefactors10241 doctest: NORMALIZEWHITESPACE x 2241 5241 True primefactors10354 primefactors'hello' Traceback most recent call last: ... TypeError: '' not supported between instances of 'int' and 'str' primefactors1,2,'hello' Traceback most recent call last: ... TypeError: '' not supported between instances of 'int' and 'list'","Completions":"from __future__ import annotations\n\n\ndef prime_factors(n: int) -> list[int]:\n \"\"\"\n Returns prime factors of n as a list.\n\n >>> prime_factors(0)\n []\n >>> prime_factors(100)\n [2, 2, 5, 5]\n >>> prime_factors(2560)\n [2, 2, 2, 2, 2, 2, 2, 2, 2, 5]\n >>> prime_factors(10**-2)\n []\n >>> prime_factors(0.02)\n []\n >>> x = prime_factors(10**241) # doctest: +NORMALIZE_WHITESPACE\n >>> x == [2]*241 + [5]*241\n True\n >>> prime_factors(10**-354)\n []\n >>> prime_factors('hello')\n Traceback (most recent call last):\n ...\n TypeError: '<=' not supported between instances of 'int' and 'str'\n >>> prime_factors([1,2,'hello'])\n Traceback (most recent call last):\n ...\n TypeError: '<=' not supported between instances of 'int' and 'list'\n\n \"\"\"\n i = 2\n factors = []\n while i * i <= n:\n if n % i:\n i += 1\n else:\n n \/\/= i\n factors.append(i)\n if n > 1:\n factors.append(n)\n return factors\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Return a list of all primes numbers up to max. listslowprimes0 listslowprimes1 listslowprimes10 listslowprimes25 2, 3, 5, 7, 11, 13, 17, 19, 23 listslowprimes11 2, 3, 5, 7, 11 listslowprimes33 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31 listslowprimes10001 997 Return a list of all primes numbers up to max. listprimes0 listprimes1 listprimes10 listprimes25 2, 3, 5, 7, 11, 13, 17, 19, 23 listprimes11 2, 3, 5, 7, 11 listprimes33 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31 listprimes10001 997 only need to check for factors up to sqrti Return a list of all primes numbers up to max. listfastprimes0 listfastprimes1 listfastprimes10 listfastprimes25 2, 3, 5, 7, 11, 13, 17, 19, 23 listfastprimes11 2, 3, 5, 7, 11 listfastprimes33 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31 listfastprimes10001 997 It's useless to test even numbers as they will not be prime As we removed the even numbers, we don't need them now Let's benchmark our functions sidebyside...","Completions":"import math\nfrom collections.abc import Generator\n\n\ndef slow_primes(max_n: int) -> Generator[int, None, None]:\n \"\"\"\n Return a list of all primes numbers up to max.\n >>> list(slow_primes(0))\n []\n >>> list(slow_primes(-1))\n []\n >>> list(slow_primes(-10))\n []\n >>> list(slow_primes(25))\n [2, 3, 5, 7, 11, 13, 17, 19, 23]\n >>> list(slow_primes(11))\n [2, 3, 5, 7, 11]\n >>> list(slow_primes(33))\n [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31]\n >>> list(slow_primes(1000))[-1]\n 997\n \"\"\"\n numbers: Generator = (i for i in range(1, (max_n + 1)))\n for i in (n for n in numbers if n > 1):\n for j in range(2, i):\n if (i % j) == 0:\n break\n else:\n yield i\n\n\ndef primes(max_n: int) -> Generator[int, None, None]:\n \"\"\"\n Return a list of all primes numbers up to max.\n >>> list(primes(0))\n []\n >>> list(primes(-1))\n []\n >>> list(primes(-10))\n []\n >>> list(primes(25))\n [2, 3, 5, 7, 11, 13, 17, 19, 23]\n >>> list(primes(11))\n [2, 3, 5, 7, 11]\n >>> list(primes(33))\n [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31]\n >>> list(primes(1000))[-1]\n 997\n \"\"\"\n numbers: Generator = (i for i in range(1, (max_n + 1)))\n for i in (n for n in numbers if n > 1):\n # only need to check for factors up to sqrt(i)\n bound = int(math.sqrt(i)) + 1\n for j in range(2, bound):\n if (i % j) == 0:\n break\n else:\n yield i\n\n\ndef fast_primes(max_n: int) -> Generator[int, None, None]:\n \"\"\"\n Return a list of all primes numbers up to max.\n >>> list(fast_primes(0))\n []\n >>> list(fast_primes(-1))\n []\n >>> list(fast_primes(-10))\n []\n >>> list(fast_primes(25))\n [2, 3, 5, 7, 11, 13, 17, 19, 23]\n >>> list(fast_primes(11))\n [2, 3, 5, 7, 11]\n >>> list(fast_primes(33))\n [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31]\n >>> list(fast_primes(1000))[-1]\n 997\n \"\"\"\n numbers: Generator = (i for i in range(1, (max_n + 1), 2))\n # It's useless to test even numbers as they will not be prime\n if max_n > 2:\n yield 2 # Because 2 will not be tested, it's necessary to yield it now\n for i in (n for n in numbers if n > 1):\n bound = int(math.sqrt(i)) + 1\n for j in range(3, bound, 2):\n # As we removed the even numbers, we don't need them now\n if (i % j) == 0:\n break\n else:\n yield i\n\n\ndef benchmark():\n \"\"\"\n Let's benchmark our functions side-by-side...\n \"\"\"\n from timeit import timeit\n\n setup = \"from __main__ import slow_primes, primes, fast_primes\"\n print(timeit(\"slow_primes(1_000_000_000_000)\", setup=setup, number=1_000_000))\n print(timeit(\"primes(1_000_000_000_000)\", setup=setup, number=1_000_000))\n print(timeit(\"fast_primes(1_000_000_000_000)\", setup=setup, number=1_000_000))\n\n\nif __name__ == \"__main__\":\n number = int(input(\"Calculate primes up to:\\n>> \").strip())\n for ret in primes(number):\n print(ret)\n benchmark()\n"} +{"Prompt":"Sieve of Eratosthenes Input: n 10 Output: 2 3 5 7 Input: n 20 Output: 2 3 5 7 11 13 17 19 you can read in detail about this at https:en.wikipedia.orgwikiSieveofEratosthenes Print the prime numbers up to n primesieveeratosthenes10 2, 3, 5, 7 primesieveeratosthenes20 2, 3, 5, 7, 11, 13, 17, 19 primesieveeratosthenes2 2 primesieveeratosthenes1 primesieveeratosthenes1 Traceback most recent call last: ... ValueError: Input must be a positive integer","Completions":"def prime_sieve_eratosthenes(num: int) -> list[int]:\n \"\"\"\n Print the prime numbers up to n\n\n >>> prime_sieve_eratosthenes(10)\n [2, 3, 5, 7]\n >>> prime_sieve_eratosthenes(20)\n [2, 3, 5, 7, 11, 13, 17, 19]\n >>> prime_sieve_eratosthenes(2)\n [2]\n >>> prime_sieve_eratosthenes(1)\n []\n >>> prime_sieve_eratosthenes(-1)\n Traceback (most recent call last):\n ...\n ValueError: Input must be a positive integer\n \"\"\"\n\n if num <= 0:\n raise ValueError(\"Input must be a positive integer\")\n\n primes = [True] * (num + 1)\n\n p = 2\n while p * p <= num:\n if primes[p]:\n for i in range(p * p, num + 1, p):\n primes[i] = False\n p += 1\n\n return [prime for prime in range(2, num + 1) if primes[prime]]\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n\n user_num = int(input(\"Enter a positive integer: \").strip())\n print(prime_sieve_eratosthenes(user_num))\n"} +{"Prompt":"Created on Thu Oct 5 16:44:23 2017 author: Christian Bender This Python library contains some useful functions to deal with prime numbers and whole numbers. Overview: isprimenumber sieveerN getprimenumbersN primefactorizationnumber greatestprimefactornumber smallestprimefactornumber getprimen getprimesbetweenpNumber1, pNumber2 isevennumber isoddnumber kgvnumber1, number2 least common multiple getdivisorsnumber all divisors of 'number' inclusive 1, number isperfectnumbernumber NEWFUNCTIONS simplifyfractionnumerator, denominator factorial n n! fib n calculate the nth fibonacci term. goldbachnumber Goldbach's assumption input: positive integer 'number' returns true if 'number' is prime otherwise false. isprime3 True isprime10 False isprime97 True isprime9991 False isprime1 Traceback most recent call last: ... AssertionError: 'number' must been an int and positive isprimetest Traceback most recent call last: ... AssertionError: 'number' must been an int and positive precondition 0 and 1 are none primes. if 'number' divisible by 'divisor' then sets 'status' of false and break up the loop. precondition input: positive integer 'N' 2 returns a list of prime numbers from 2 up to N. This function implements the algorithm called sieve of erathostenes. sieveer8 2, 3, 5, 7 sieveer1 Traceback most recent call last: ... AssertionError: 'N' must been an int and 2 sieveertest Traceback most recent call last: ... AssertionError: 'N' must been an int and 2 precondition beginList: contains all natural numbers from 2 up to N actual sieve of erathostenes filters actual prime numbers. precondition input: positive integer 'N' 2 returns a list of prime numbers from 2 up to N inclusive This function is more efficient as function 'sieveEr...' getprimenumbers8 2, 3, 5, 7 getprimenumbers1 Traceback most recent call last: ... AssertionError: 'N' must been an int and 2 getprimenumberstest Traceback most recent call last: ... AssertionError: 'N' must been an int and 2 precondition iterates over all numbers between 2 up to N1 if a number is prime then appends to list 'ans' precondition input: positive integer 'number' returns a list of the prime number factors of 'number' primefactorization0 0 primefactorization8 2, 2, 2 primefactorization287 7, 41 primefactorization1 Traceback most recent call last: ... AssertionError: 'number' must been an int and 0 primefactorizationtest Traceback most recent call last: ... AssertionError: 'number' must been an int and 0 precondition potential prime number factors. if 'number' not prime then builds the prime factorization of 'number' precondition input: positive integer 'number' 0 returns the greatest prime number factor of 'number' greatestprimefactor0 0 greatestprimefactor8 2 greatestprimefactor287 41 greatestprimefactor1 Traceback most recent call last: ... AssertionError: 'number' must been an int and 0 greatestprimefactortest Traceback most recent call last: ... AssertionError: 'number' must been an int and 0 precondition prime factorization of 'number' precondition input: integer 'number' 0 returns the smallest prime number factor of 'number' smallestprimefactor0 0 smallestprimefactor8 2 smallestprimefactor287 7 smallestprimefactor1 Traceback most recent call last: ... AssertionError: 'number' must been an int and 0 smallestprimefactortest Traceback most recent call last: ... AssertionError: 'number' must been an int and 0 precondition prime factorization of 'number' precondition input: integer 'number' returns true if 'number' is even, otherwise false. iseven0 True iseven8 True iseven287 False iseven1 False iseventest Traceback most recent call last: ... AssertionError: 'number' must been an int precondition input: integer 'number' returns true if 'number' is odd, otherwise false. isodd0 False isodd8 False isodd287 True isodd1 True isoddtest Traceback most recent call last: ... AssertionError: 'number' must been an int precondition Goldbach's assumption input: a even positive integer 'number' 2 returns a list of two prime numbers whose sum is equal to 'number' goldbach8 3, 5 goldbach824 3, 821 goldbach0 Traceback most recent call last: ... AssertionError: 'number' must been an int, even and 2 goldbach1 Traceback most recent call last: ... AssertionError: 'number' must been an int, even and 2 goldbachtest Traceback most recent call last: ... AssertionError: 'number' must been an int, even and 2 precondition creates a list of prime numbers between 2 up to 'number' run variable for whileloops. exit variable. for break up the loops precondition Least common multiple input: two positive integer 'number1' and 'number2' returns the least common multiple of 'number1' and 'number2' kgv8,10 40 kgv824,67 55208 kgv1, 10 10 kgv0 Traceback most recent call last: ... TypeError: kgv missing 1 required positional argument: 'number2' kgv10,1 Traceback most recent call last: ... AssertionError: 'number1' and 'number2' must been positive integer. kgvtest,test2 Traceback most recent call last: ... AssertionError: 'number1' and 'number2' must been positive integer. precondition for kgV x,1 builds the prime factorization of 'number1' and 'number2' iterates through primeFac1 iterates through primeFac2 precondition Gets the nth prime number. input: positive integer 'n' 0 returns the nth prime number, beginning at index 0 getprime0 2 getprime8 23 getprime824 6337 getprime1 Traceback most recent call last: ... AssertionError: 'number' must been a positive int getprimetest Traceback most recent call last: ... AssertionError: 'number' must been a positive int precondition if ans not prime then runs to the next prime number. precondition input: prime numbers 'pNumber1' and 'pNumber2' pNumber1 pNumber2 returns a list of all prime numbers between 'pNumber1' exclusive and 'pNumber2' exclusive getprimesbetween3, 67 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61 getprimesbetween0 Traceback most recent call last: ... TypeError: getprimesbetween missing 1 required positional argument: 'pnumber2' getprimesbetween0, 1 Traceback most recent call last: ... AssertionError: The arguments must been prime numbers and 'pNumber1' 'pNumber2' getprimesbetween1, 3 Traceback most recent call last: ... AssertionError: 'number' must been an int and positive getprimesbetweentest,test Traceback most recent call last: ... AssertionError: 'number' must been an int and positive precondition if number is not prime then fetch the next prime number. fetch the next prime number. precondition 'ans' contains not 'pNumber1' and 'pNumber2' ! input: positive integer 'n' 1 returns all divisors of n inclusive 1 and 'n' getdivisors8 1, 2, 4, 8 getdivisors824 1, 2, 4, 8, 103, 206, 412, 824 getdivisors1 Traceback most recent call last: ... AssertionError: 'n' must been int and 1 getdivisorstest Traceback most recent call last: ... AssertionError: 'n' must been int and 1 precondition precondition input: positive integer 'number' 1 returns true if 'number' is a perfect number otherwise false. isperfectnumber28 True isperfectnumber824 False isperfectnumber1 Traceback most recent call last: ... AssertionError: 'number' must been an int and 1 isperfectnumbertest Traceback most recent call last: ... AssertionError: 'number' must been an int and 1 precondition precondition summed all divisors up to 'number' exclusive, hence :1 input: two integer 'numerator' and 'denominator' assumes: 'denominator' ! 0 returns: a tuple with simplify numerator and denominator. simplifyfraction10, 20 1, 2 simplifyfraction10, 1 10, 1 simplifyfractiontest,test Traceback most recent call last: ... AssertionError: The arguments must been from type int and 'denominator' ! 0 precondition build the greatest common divisor of numerator and denominator. precondition input: positive integer 'n' returns the factorial of 'n' n! factorial0 1 factorial20 2432902008176640000 factorial1 Traceback most recent call last: ... AssertionError: 'n' must been a int and 0 factorialtest Traceback most recent call last: ... AssertionError: 'n' must been a int and 0 precondition input: positive integer 'n' returns the nth fibonacci term , indexing by 0 fib0 1 fib5 8 fib20 10946 fib99 354224848179261915075 fib1 Traceback most recent call last: ... AssertionError: 'n' must been an int and 0 fibtest Traceback most recent call last: ... AssertionError: 'n' must been an int and 0 precondition","Completions":"from math import sqrt\n\nfrom maths.greatest_common_divisor import gcd_by_iterative\n\n\ndef is_prime(number: int) -> bool:\n \"\"\"\n input: positive integer 'number'\n returns true if 'number' is prime otherwise false.\n\n >>> is_prime(3)\n True\n >>> is_prime(10)\n False\n >>> is_prime(97)\n True\n >>> is_prime(9991)\n False\n >>> is_prime(-1)\n Traceback (most recent call last):\n ...\n AssertionError: 'number' must been an int and positive\n >>> is_prime(\"test\")\n Traceback (most recent call last):\n ...\n AssertionError: 'number' must been an int and positive\n \"\"\"\n\n # precondition\n assert isinstance(number, int) and (\n number >= 0\n ), \"'number' must been an int and positive\"\n\n status = True\n\n # 0 and 1 are none primes.\n if number <= 1:\n status = False\n\n for divisor in range(2, int(round(sqrt(number))) + 1):\n # if 'number' divisible by 'divisor' then sets 'status'\n # of false and break up the loop.\n if number % divisor == 0:\n status = False\n break\n\n # precondition\n assert isinstance(status, bool), \"'status' must been from type bool\"\n\n return status\n\n\n# ------------------------------------------\n\n\ndef sieve_er(n):\n \"\"\"\n input: positive integer 'N' > 2\n returns a list of prime numbers from 2 up to N.\n\n This function implements the algorithm called\n sieve of erathostenes.\n\n >>> sieve_er(8)\n [2, 3, 5, 7]\n >>> sieve_er(-1)\n Traceback (most recent call last):\n ...\n AssertionError: 'N' must been an int and > 2\n >>> sieve_er(\"test\")\n Traceback (most recent call last):\n ...\n AssertionError: 'N' must been an int and > 2\n \"\"\"\n\n # precondition\n assert isinstance(n, int) and (n > 2), \"'N' must been an int and > 2\"\n\n # beginList: contains all natural numbers from 2 up to N\n begin_list = list(range(2, n + 1))\n\n ans = [] # this list will be returns.\n\n # actual sieve of erathostenes\n for i in range(len(begin_list)):\n for j in range(i + 1, len(begin_list)):\n if (begin_list[i] != 0) and (begin_list[j] % begin_list[i] == 0):\n begin_list[j] = 0\n\n # filters actual prime numbers.\n ans = [x for x in begin_list if x != 0]\n\n # precondition\n assert isinstance(ans, list), \"'ans' must been from type list\"\n\n return ans\n\n\n# --------------------------------\n\n\ndef get_prime_numbers(n):\n \"\"\"\n input: positive integer 'N' > 2\n returns a list of prime numbers from 2 up to N (inclusive)\n This function is more efficient as function 'sieveEr(...)'\n\n >>> get_prime_numbers(8)\n [2, 3, 5, 7]\n >>> get_prime_numbers(-1)\n Traceback (most recent call last):\n ...\n AssertionError: 'N' must been an int and > 2\n >>> get_prime_numbers(\"test\")\n Traceback (most recent call last):\n ...\n AssertionError: 'N' must been an int and > 2\n \"\"\"\n\n # precondition\n assert isinstance(n, int) and (n > 2), \"'N' must been an int and > 2\"\n\n ans = []\n\n # iterates over all numbers between 2 up to N+1\n # if a number is prime then appends to list 'ans'\n for number in range(2, n + 1):\n if is_prime(number):\n ans.append(number)\n\n # precondition\n assert isinstance(ans, list), \"'ans' must been from type list\"\n\n return ans\n\n\n# -----------------------------------------\n\n\ndef prime_factorization(number):\n \"\"\"\n input: positive integer 'number'\n returns a list of the prime number factors of 'number'\n\n >>> prime_factorization(0)\n [0]\n >>> prime_factorization(8)\n [2, 2, 2]\n >>> prime_factorization(287)\n [7, 41]\n >>> prime_factorization(-1)\n Traceback (most recent call last):\n ...\n AssertionError: 'number' must been an int and >= 0\n >>> prime_factorization(\"test\")\n Traceback (most recent call last):\n ...\n AssertionError: 'number' must been an int and >= 0\n \"\"\"\n\n # precondition\n assert isinstance(number, int) and number >= 0, \"'number' must been an int and >= 0\"\n\n ans = [] # this list will be returns of the function.\n\n # potential prime number factors.\n\n factor = 2\n\n quotient = number\n\n if number in {0, 1}:\n ans.append(number)\n\n # if 'number' not prime then builds the prime factorization of 'number'\n elif not is_prime(number):\n while quotient != 1:\n if is_prime(factor) and (quotient % factor == 0):\n ans.append(factor)\n quotient \/= factor\n else:\n factor += 1\n\n else:\n ans.append(number)\n\n # precondition\n assert isinstance(ans, list), \"'ans' must been from type list\"\n\n return ans\n\n\n# -----------------------------------------\n\n\ndef greatest_prime_factor(number):\n \"\"\"\n input: positive integer 'number' >= 0\n returns the greatest prime number factor of 'number'\n\n >>> greatest_prime_factor(0)\n 0\n >>> greatest_prime_factor(8)\n 2\n >>> greatest_prime_factor(287)\n 41\n >>> greatest_prime_factor(-1)\n Traceback (most recent call last):\n ...\n AssertionError: 'number' must been an int and >= 0\n >>> greatest_prime_factor(\"test\")\n Traceback (most recent call last):\n ...\n AssertionError: 'number' must been an int and >= 0\n \"\"\"\n\n # precondition\n assert isinstance(number, int) and (\n number >= 0\n ), \"'number' must been an int and >= 0\"\n\n ans = 0\n\n # prime factorization of 'number'\n prime_factors = prime_factorization(number)\n\n ans = max(prime_factors)\n\n # precondition\n assert isinstance(ans, int), \"'ans' must been from type int\"\n\n return ans\n\n\n# ----------------------------------------------\n\n\ndef smallest_prime_factor(number):\n \"\"\"\n input: integer 'number' >= 0\n returns the smallest prime number factor of 'number'\n\n >>> smallest_prime_factor(0)\n 0\n >>> smallest_prime_factor(8)\n 2\n >>> smallest_prime_factor(287)\n 7\n >>> smallest_prime_factor(-1)\n Traceback (most recent call last):\n ...\n AssertionError: 'number' must been an int and >= 0\n >>> smallest_prime_factor(\"test\")\n Traceback (most recent call last):\n ...\n AssertionError: 'number' must been an int and >= 0\n \"\"\"\n\n # precondition\n assert isinstance(number, int) and (\n number >= 0\n ), \"'number' must been an int and >= 0\"\n\n ans = 0\n\n # prime factorization of 'number'\n prime_factors = prime_factorization(number)\n\n ans = min(prime_factors)\n\n # precondition\n assert isinstance(ans, int), \"'ans' must been from type int\"\n\n return ans\n\n\n# ----------------------\n\n\ndef is_even(number):\n \"\"\"\n input: integer 'number'\n returns true if 'number' is even, otherwise false.\n\n >>> is_even(0)\n True\n >>> is_even(8)\n True\n >>> is_even(287)\n False\n >>> is_even(-1)\n False\n >>> is_even(\"test\")\n Traceback (most recent call last):\n ...\n AssertionError: 'number' must been an int\n \"\"\"\n\n # precondition\n assert isinstance(number, int), \"'number' must been an int\"\n assert isinstance(number % 2 == 0, bool), \"compare must been from type bool\"\n\n return number % 2 == 0\n\n\n# ------------------------\n\n\ndef is_odd(number):\n \"\"\"\n input: integer 'number'\n returns true if 'number' is odd, otherwise false.\n\n >>> is_odd(0)\n False\n >>> is_odd(8)\n False\n >>> is_odd(287)\n True\n >>> is_odd(-1)\n True\n >>> is_odd(\"test\")\n Traceback (most recent call last):\n ...\n AssertionError: 'number' must been an int\n \"\"\"\n\n # precondition\n assert isinstance(number, int), \"'number' must been an int\"\n assert isinstance(number % 2 != 0, bool), \"compare must been from type bool\"\n\n return number % 2 != 0\n\n\n# ------------------------\n\n\ndef goldbach(number):\n \"\"\"\n Goldbach's assumption\n input: a even positive integer 'number' > 2\n returns a list of two prime numbers whose sum is equal to 'number'\n\n >>> goldbach(8)\n [3, 5]\n >>> goldbach(824)\n [3, 821]\n >>> goldbach(0)\n Traceback (most recent call last):\n ...\n AssertionError: 'number' must been an int, even and > 2\n >>> goldbach(-1)\n Traceback (most recent call last):\n ...\n AssertionError: 'number' must been an int, even and > 2\n >>> goldbach(\"test\")\n Traceback (most recent call last):\n ...\n AssertionError: 'number' must been an int, even and > 2\n \"\"\"\n\n # precondition\n assert (\n isinstance(number, int) and (number > 2) and is_even(number)\n ), \"'number' must been an int, even and > 2\"\n\n ans = [] # this list will returned\n\n # creates a list of prime numbers between 2 up to 'number'\n prime_numbers = get_prime_numbers(number)\n len_pn = len(prime_numbers)\n\n # run variable for while-loops.\n i = 0\n j = None\n\n # exit variable. for break up the loops\n loop = True\n\n while i < len_pn and loop:\n j = i + 1\n\n while j < len_pn and loop:\n if prime_numbers[i] + prime_numbers[j] == number:\n loop = False\n ans.append(prime_numbers[i])\n ans.append(prime_numbers[j])\n\n j += 1\n\n i += 1\n\n # precondition\n assert (\n isinstance(ans, list)\n and (len(ans) == 2)\n and (ans[0] + ans[1] == number)\n and is_prime(ans[0])\n and is_prime(ans[1])\n ), \"'ans' must contains two primes. And sum of elements must been eq 'number'\"\n\n return ans\n\n\n# ----------------------------------------------\n\n\ndef kg_v(number1, number2):\n \"\"\"\n Least common multiple\n input: two positive integer 'number1' and 'number2'\n returns the least common multiple of 'number1' and 'number2'\n\n >>> kg_v(8,10)\n 40\n >>> kg_v(824,67)\n 55208\n >>> kg_v(1, 10)\n 10\n >>> kg_v(0)\n Traceback (most recent call last):\n ...\n TypeError: kg_v() missing 1 required positional argument: 'number2'\n >>> kg_v(10,-1)\n Traceback (most recent call last):\n ...\n AssertionError: 'number1' and 'number2' must been positive integer.\n >>> kg_v(\"test\",\"test2\")\n Traceback (most recent call last):\n ...\n AssertionError: 'number1' and 'number2' must been positive integer.\n \"\"\"\n\n # precondition\n assert (\n isinstance(number1, int)\n and isinstance(number2, int)\n and (number1 >= 1)\n and (number2 >= 1)\n ), \"'number1' and 'number2' must been positive integer.\"\n\n ans = 1 # actual answer that will be return.\n\n # for kgV (x,1)\n if number1 > 1 and number2 > 1:\n # builds the prime factorization of 'number1' and 'number2'\n prime_fac_1 = prime_factorization(number1)\n prime_fac_2 = prime_factorization(number2)\n\n elif number1 == 1 or number2 == 1:\n prime_fac_1 = []\n prime_fac_2 = []\n ans = max(number1, number2)\n\n count1 = 0\n count2 = 0\n\n done = [] # captured numbers int both 'primeFac1' and 'primeFac2'\n\n # iterates through primeFac1\n for n in prime_fac_1:\n if n not in done:\n if n in prime_fac_2:\n count1 = prime_fac_1.count(n)\n count2 = prime_fac_2.count(n)\n\n for _ in range(max(count1, count2)):\n ans *= n\n\n else:\n count1 = prime_fac_1.count(n)\n\n for _ in range(count1):\n ans *= n\n\n done.append(n)\n\n # iterates through primeFac2\n for n in prime_fac_2:\n if n not in done:\n count2 = prime_fac_2.count(n)\n\n for _ in range(count2):\n ans *= n\n\n done.append(n)\n\n # precondition\n assert isinstance(ans, int) and (\n ans >= 0\n ), \"'ans' must been from type int and positive\"\n\n return ans\n\n\n# ----------------------------------\n\n\ndef get_prime(n):\n \"\"\"\n Gets the n-th prime number.\n input: positive integer 'n' >= 0\n returns the n-th prime number, beginning at index 0\n\n >>> get_prime(0)\n 2\n >>> get_prime(8)\n 23\n >>> get_prime(824)\n 6337\n >>> get_prime(-1)\n Traceback (most recent call last):\n ...\n AssertionError: 'number' must been a positive int\n >>> get_prime(\"test\")\n Traceback (most recent call last):\n ...\n AssertionError: 'number' must been a positive int\n \"\"\"\n\n # precondition\n assert isinstance(n, int) and (n >= 0), \"'number' must been a positive int\"\n\n index = 0\n ans = 2 # this variable holds the answer\n\n while index < n:\n index += 1\n\n ans += 1 # counts to the next number\n\n # if ans not prime then\n # runs to the next prime number.\n while not is_prime(ans):\n ans += 1\n\n # precondition\n assert isinstance(ans, int) and is_prime(\n ans\n ), \"'ans' must been a prime number and from type int\"\n\n return ans\n\n\n# ---------------------------------------------------\n\n\ndef get_primes_between(p_number_1, p_number_2):\n \"\"\"\n input: prime numbers 'pNumber1' and 'pNumber2'\n pNumber1 < pNumber2\n returns a list of all prime numbers between 'pNumber1' (exclusive)\n and 'pNumber2' (exclusive)\n\n >>> get_primes_between(3, 67)\n [5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61]\n >>> get_primes_between(0)\n Traceback (most recent call last):\n ...\n TypeError: get_primes_between() missing 1 required positional argument: 'p_number_2'\n >>> get_primes_between(0, 1)\n Traceback (most recent call last):\n ...\n AssertionError: The arguments must been prime numbers and 'pNumber1' < 'pNumber2'\n >>> get_primes_between(-1, 3)\n Traceback (most recent call last):\n ...\n AssertionError: 'number' must been an int and positive\n >>> get_primes_between(\"test\",\"test\")\n Traceback (most recent call last):\n ...\n AssertionError: 'number' must been an int and positive\n \"\"\"\n\n # precondition\n assert (\n is_prime(p_number_1) and is_prime(p_number_2) and (p_number_1 < p_number_2)\n ), \"The arguments must been prime numbers and 'pNumber1' < 'pNumber2'\"\n\n number = p_number_1 + 1 # jump to the next number\n\n ans = [] # this list will be returns.\n\n # if number is not prime then\n # fetch the next prime number.\n while not is_prime(number):\n number += 1\n\n while number < p_number_2:\n ans.append(number)\n\n number += 1\n\n # fetch the next prime number.\n while not is_prime(number):\n number += 1\n\n # precondition\n assert (\n isinstance(ans, list)\n and ans[0] != p_number_1\n and ans[len(ans) - 1] != p_number_2\n ), \"'ans' must been a list without the arguments\"\n\n # 'ans' contains not 'pNumber1' and 'pNumber2' !\n return ans\n\n\n# ----------------------------------------------------\n\n\ndef get_divisors(n):\n \"\"\"\n input: positive integer 'n' >= 1\n returns all divisors of n (inclusive 1 and 'n')\n\n >>> get_divisors(8)\n [1, 2, 4, 8]\n >>> get_divisors(824)\n [1, 2, 4, 8, 103, 206, 412, 824]\n >>> get_divisors(-1)\n Traceback (most recent call last):\n ...\n AssertionError: 'n' must been int and >= 1\n >>> get_divisors(\"test\")\n Traceback (most recent call last):\n ...\n AssertionError: 'n' must been int and >= 1\n \"\"\"\n\n # precondition\n assert isinstance(n, int) and (n >= 1), \"'n' must been int and >= 1\"\n\n ans = [] # will be returned.\n\n for divisor in range(1, n + 1):\n if n % divisor == 0:\n ans.append(divisor)\n\n # precondition\n assert ans[0] == 1 and ans[len(ans) - 1] == n, \"Error in function getDivisiors(...)\"\n\n return ans\n\n\n# ----------------------------------------------------\n\n\ndef is_perfect_number(number):\n \"\"\"\n input: positive integer 'number' > 1\n returns true if 'number' is a perfect number otherwise false.\n\n >>> is_perfect_number(28)\n True\n >>> is_perfect_number(824)\n False\n >>> is_perfect_number(-1)\n Traceback (most recent call last):\n ...\n AssertionError: 'number' must been an int and >= 1\n >>> is_perfect_number(\"test\")\n Traceback (most recent call last):\n ...\n AssertionError: 'number' must been an int and >= 1\n \"\"\"\n\n # precondition\n assert isinstance(number, int) and (\n number > 1\n ), \"'number' must been an int and >= 1\"\n\n divisors = get_divisors(number)\n\n # precondition\n assert (\n isinstance(divisors, list)\n and (divisors[0] == 1)\n and (divisors[len(divisors) - 1] == number)\n ), \"Error in help-function getDivisiors(...)\"\n\n # summed all divisors up to 'number' (exclusive), hence [:-1]\n return sum(divisors[:-1]) == number\n\n\n# ------------------------------------------------------------\n\n\ndef simplify_fraction(numerator, denominator):\n \"\"\"\n input: two integer 'numerator' and 'denominator'\n assumes: 'denominator' != 0\n returns: a tuple with simplify numerator and denominator.\n\n >>> simplify_fraction(10, 20)\n (1, 2)\n >>> simplify_fraction(10, -1)\n (10, -1)\n >>> simplify_fraction(\"test\",\"test\")\n Traceback (most recent call last):\n ...\n AssertionError: The arguments must been from type int and 'denominator' != 0\n \"\"\"\n\n # precondition\n assert (\n isinstance(numerator, int)\n and isinstance(denominator, int)\n and (denominator != 0)\n ), \"The arguments must been from type int and 'denominator' != 0\"\n\n # build the greatest common divisor of numerator and denominator.\n gcd_of_fraction = gcd_by_iterative(abs(numerator), abs(denominator))\n\n # precondition\n assert (\n isinstance(gcd_of_fraction, int)\n and (numerator % gcd_of_fraction == 0)\n and (denominator % gcd_of_fraction == 0)\n ), \"Error in function gcd_by_iterative(...,...)\"\n\n return (numerator \/\/ gcd_of_fraction, denominator \/\/ gcd_of_fraction)\n\n\n# -----------------------------------------------------------------\n\n\ndef factorial(n):\n \"\"\"\n input: positive integer 'n'\n returns the factorial of 'n' (n!)\n\n >>> factorial(0)\n 1\n >>> factorial(20)\n 2432902008176640000\n >>> factorial(-1)\n Traceback (most recent call last):\n ...\n AssertionError: 'n' must been a int and >= 0\n >>> factorial(\"test\")\n Traceback (most recent call last):\n ...\n AssertionError: 'n' must been a int and >= 0\n \"\"\"\n\n # precondition\n assert isinstance(n, int) and (n >= 0), \"'n' must been a int and >= 0\"\n\n ans = 1 # this will be return.\n\n for factor in range(1, n + 1):\n ans *= factor\n\n return ans\n\n\n# -------------------------------------------------------------------\n\n\ndef fib(n: int) -> int:\n \"\"\"\n input: positive integer 'n'\n returns the n-th fibonacci term , indexing by 0\n\n >>> fib(0)\n 1\n >>> fib(5)\n 8\n >>> fib(20)\n 10946\n >>> fib(99)\n 354224848179261915075\n >>> fib(-1)\n Traceback (most recent call last):\n ...\n AssertionError: 'n' must been an int and >= 0\n >>> fib(\"test\")\n Traceback (most recent call last):\n ...\n AssertionError: 'n' must been an int and >= 0\n \"\"\"\n\n # precondition\n assert isinstance(n, int) and (n >= 0), \"'n' must been an int and >= 0\"\n\n tmp = 0\n fib1 = 1\n ans = 1 # this will be return\n\n for _ in range(n - 1):\n tmp = ans\n ans += fib1\n fib1 = tmp\n\n return ans\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Prints the multiplication table of a given number till the given number of terms printmultiplicationtable3, 5 3 1 3 3 2 6 3 3 9 3 4 12 3 5 15 printmultiplicationtable4, 6 4 1 4 4 2 8 4 3 12 4 4 16 4 5 20 4 6 24","Completions":"def multiplication_table(number: int, number_of_terms: int) -> str:\n \"\"\"\n Prints the multiplication table of a given number till the given number of terms\n\n >>> print(multiplication_table(3, 5))\n 3 * 1 = 3\n 3 * 2 = 6\n 3 * 3 = 9\n 3 * 4 = 12\n 3 * 5 = 15\n\n >>> print(multiplication_table(-4, 6))\n -4 * 1 = -4\n -4 * 2 = -8\n -4 * 3 = -12\n -4 * 4 = -16\n -4 * 5 = -20\n -4 * 6 = -24\n \"\"\"\n return \"\\n\".join(\n f\"{number} * {i} = {number * i}\" for i in range(1, number_of_terms + 1)\n )\n\n\nif __name__ == \"__main__\":\n print(multiplication_table(number=5, number_of_terms=10))\n"} +{"Prompt":"Uses Pythagoras theorem to calculate the distance between two points in space. import math class Point: def initself, x, y, z: self.x x self.y y self.z z def reprself str: return fPointself.x, self.y, self.z def distancea: Point, b: Point float: return math.sqrtabsb.x a.x 2 b.y a.y 2 b.z a.z 2 if name main: import doctest doctest.testmod","Completions":"import math\n\n\nclass Point:\n def __init__(self, x, y, z):\n self.x = x\n self.y = y\n self.z = z\n\n def __repr__(self) -> str:\n return f\"Point({self.x}, {self.y}, {self.z})\"\n\n\ndef distance(a: Point, b: Point) -> float:\n \"\"\"\n >>> point1 = Point(2, -1, 7)\n >>> point2 = Point(1, -3, 5)\n >>> print(f\"Distance from {point1} to {point2} is {distance(point1, point2)}\")\n Distance from Point(2, -1, 7) to Point(1, -3, 5) is 3.0\n \"\"\"\n return math.sqrt(abs((b.x - a.x) ** 2 + (b.y - a.y) ** 2 + (b.z - a.z) ** 2))\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Return a QRdecomposition of the matrix A using Householder reflection. The QRdecomposition decomposes the matrix A of shape m, n into an orthogonal matrix Q of shape m, m and an upper triangular matrix R of shape m, n. Note that the matrix A does not have to be square. This method of decomposing A uses the Householder reflection, which is numerically stable and of complexity On3. https:en.wikipedia.orgwikiQRdecompositionUsingHouseholderreflections Arguments: A a numpy.ndarray of shape m, n Note: several optimizations can be made for numeric efficiency, but this is intended to demonstrate how it would be represented in a mathematics textbook. In cases where efficiency is particularly important, an optimized version from BLAS should be used. A np.array12, 51, 4, 6, 167, 68, 4, 24, 41, dtypefloat Q, R qrhouseholderA check that the decomposition is correct np.allcloseQR, A True check that Q is orthogonal np.allcloseQQ.T, np.eyeA.shape0 True np.allcloseQ.TQ, np.eyeA.shape0 True check that R is upper triangular np.allclosenp.triuR, R True select a column of modified matrix A': construct first basis vector determine scaling factor construct vector v for Householder reflection construct the Householder matrix pad with ones and zeros as necessary","Completions":"import numpy as np\n\n\ndef qr_householder(a: np.ndarray):\n \"\"\"Return a QR-decomposition of the matrix A using Householder reflection.\n\n The QR-decomposition decomposes the matrix A of shape (m, n) into an\n orthogonal matrix Q of shape (m, m) and an upper triangular matrix R of\n shape (m, n). Note that the matrix A does not have to be square. This\n method of decomposing A uses the Householder reflection, which is\n numerically stable and of complexity O(n^3).\n\n https:\/\/en.wikipedia.org\/wiki\/QR_decomposition#Using_Householder_reflections\n\n Arguments:\n A -- a numpy.ndarray of shape (m, n)\n\n Note: several optimizations can be made for numeric efficiency, but this is\n intended to demonstrate how it would be represented in a mathematics\n textbook. In cases where efficiency is particularly important, an optimized\n version from BLAS should be used.\n\n >>> A = np.array([[12, -51, 4], [6, 167, -68], [-4, 24, -41]], dtype=float)\n >>> Q, R = qr_householder(A)\n\n >>> # check that the decomposition is correct\n >>> np.allclose(Q@R, A)\n True\n\n >>> # check that Q is orthogonal\n >>> np.allclose(Q@Q.T, np.eye(A.shape[0]))\n True\n >>> np.allclose(Q.T@Q, np.eye(A.shape[0]))\n True\n\n >>> # check that R is upper triangular\n >>> np.allclose(np.triu(R), R)\n True\n \"\"\"\n m, n = a.shape\n t = min(m, n)\n q = np.eye(m)\n r = a.copy()\n\n for k in range(t - 1):\n # select a column of modified matrix A':\n x = r[k:, [k]]\n # construct first basis vector\n e1 = np.zeros_like(x)\n e1[0] = 1.0\n # determine scaling factor\n alpha = np.linalg.norm(x)\n # construct vector v for Householder reflection\n v = x + np.sign(x[0]) * alpha * e1\n v \/= np.linalg.norm(v)\n\n # construct the Householder matrix\n q_k = np.eye(m - k) - 2.0 * v @ v.T\n # pad with ones and zeros as necessary\n q_k = np.block([[np.eye(k), np.zeros((k, m - k))], [np.zeros((m - k, k)), q_k]])\n\n q = q @ q_k.T\n r = q_k @ r\n\n return q, r\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Given the numerical coefficients a, b and c, calculates the roots for any quadratic equation of the form ax2 bx c quadraticrootsa1, b3, c4 1.0, 4.0 quadraticroots5, 6, 1 0.2, 1.0 quadraticroots1, 6, 25 34j, 34j","Completions":"from __future__ import annotations\n\nfrom cmath import sqrt\n\n\ndef quadratic_roots(a: int, b: int, c: int) -> tuple[complex, complex]:\n \"\"\"\n Given the numerical coefficients a, b and c,\n calculates the roots for any quadratic equation of the form ax^2 + bx + c\n\n >>> quadratic_roots(a=1, b=3, c=-4)\n (1.0, -4.0)\n >>> quadratic_roots(5, 6, 1)\n (-0.2, -1.0)\n >>> quadratic_roots(1, -6, 25)\n ((3+4j), (3-4j))\n \"\"\"\n\n if a == 0:\n raise ValueError(\"Coefficient 'a' must not be zero.\")\n delta = b * b - 4 * a * c\n\n root_1 = (-b + sqrt(delta)) \/ (2 * a)\n root_2 = (-b - sqrt(delta)) \/ (2 * a)\n\n return (\n root_1.real if not root_1.imag else root_1,\n root_2.real if not root_2.imag else root_2,\n )\n\n\ndef main():\n solution1, solution2 = quadratic_roots(a=5, b=6, c=1)\n print(f\"The solutions are: {solution1} and {solution2}\")\n\n\nif __name__ == \"__main__\":\n main()\n"} +{"Prompt":"Converts the given angle from degrees to radians https:en.wikipedia.orgwikiRadian radians180 3.141592653589793 radians92 1.6057029118347832 radians274 4.782202150464463 radians109.82 1.9167205845401725 from math import radians as mathradians allabsradiansi mathradiansi 1e8 for i in range2, 361 True","Completions":"from math import pi\n\n\ndef radians(degree: float) -> float:\n \"\"\"\n Converts the given angle from degrees to radians\n https:\/\/en.wikipedia.org\/wiki\/Radian\n\n >>> radians(180)\n 3.141592653589793\n >>> radians(92)\n 1.6057029118347832\n >>> radians(274)\n 4.782202150464463\n >>> radians(109.82)\n 1.9167205845401725\n\n >>> from math import radians as math_radians\n >>> all(abs(radians(i) - math_radians(i)) <= 1e-8 for i in range(-2, 361))\n True\n \"\"\"\n\n return degree \/ (180 \/ pi)\n\n\nif __name__ == \"__main__\":\n from doctest import testmod\n\n testmod()\n"} +{"Prompt":"Fast Polynomial Multiplication using radix2 fast Fourier Transform. Fast Polynomial Multiplication using radix2 fast Fourier Transform. Reference: https:en.wikipedia.orgwikiCooleyE28093TukeyFFTalgorithmTheradix2DITcase For polynomials of degree m and n the algorithms has complexity Onlogn mlogm The main part of the algorithm is split in two parts: 1 DFT: We compute the discrete fourier transform DFT of A and B using a bottomup dynamic approach 2 multiply: Once we obtain the DFT of AB, we can similarly invert it to obtain AB The class FFT takes two polynomials A and B with complex coefficients as arguments; The two polynomials should be represented as a sequence of coefficients starting from the free term. Thus, for instance x 2x3 could be represented as 0,1,0,2 or 0,1,0,2. The constructor adds some zeros at the end so that the polynomials have the same length which is a power of 2 at least the length of their product. Example: Create two polynomials as sequences A 0, 1, 0, 2 x2x3 B 2, 3, 4, 0 23x4x2 Create an FFT object with them x FFTA, B Print product x.product 2x 3x2 8x3 4x4 6x5 00j, 20j, 30j, 80j, 60j, 80j str test printx A 0x0 1x1 2x0 3x2 B 0x2 1x3 2x4 AB 0x00j 1x20j 2x30j 3x80j 4x60j 5x80j Input as list Remove leading zero coefficients Add 0 to make lengths equal a power of 2 A complex root used for the fourier transform The product Discrete fourier transform of A and B Corner case First half of next step Second half of next step Update multiply the DFTs of A and B and find AB Corner Case Inverse DFT First half of next step Even positions Odd positions Update Unpack Remove leading 0's Overwrite str for print; Shows A, B and AB Unit tests","Completions":"import mpmath # for roots of unity\nimport numpy as np\n\n\nclass FFT:\n \"\"\"\n Fast Polynomial Multiplication using radix-2 fast Fourier Transform.\n\n Reference:\n https:\/\/en.wikipedia.org\/wiki\/Cooley%E2%80%93Tukey_FFT_algorithm#The_radix-2_DIT_case\n\n For polynomials of degree m and n the algorithms has complexity\n O(n*logn + m*logm)\n\n The main part of the algorithm is split in two parts:\n 1) __DFT: We compute the discrete fourier transform (DFT) of A and B using a\n bottom-up dynamic approach -\n 2) __multiply: Once we obtain the DFT of A*B, we can similarly\n invert it to obtain A*B\n\n The class FFT takes two polynomials A and B with complex coefficients as arguments;\n The two polynomials should be represented as a sequence of coefficients starting\n from the free term. Thus, for instance x + 2*x^3 could be represented as\n [0,1,0,2] or (0,1,0,2). The constructor adds some zeros at the end so that the\n polynomials have the same length which is a power of 2 at least the length of\n their product.\n\n Example:\n\n Create two polynomials as sequences\n >>> A = [0, 1, 0, 2] # x+2x^3\n >>> B = (2, 3, 4, 0) # 2+3x+4x^2\n\n Create an FFT object with them\n >>> x = FFT(A, B)\n\n Print product\n >>> x.product # 2x + 3x^2 + 8x^3 + 4x^4 + 6x^5\n [(-0+0j), (2+0j), (3+0j), (8+0j), (6+0j), (8+0j)]\n\n __str__ test\n >>> print(x)\n A = 0*x^0 + 1*x^1 + 2*x^0 + 3*x^2\n B = 0*x^2 + 1*x^3 + 2*x^4\n A*B = 0*x^(-0+0j) + 1*x^(2+0j) + 2*x^(3+0j) + 3*x^(8+0j) + 4*x^(6+0j) + 5*x^(8+0j)\n \"\"\"\n\n def __init__(self, poly_a=None, poly_b=None):\n # Input as list\n self.polyA = list(poly_a or [0])[:]\n self.polyB = list(poly_b or [0])[:]\n\n # Remove leading zero coefficients\n while self.polyA[-1] == 0:\n self.polyA.pop()\n self.len_A = len(self.polyA)\n\n while self.polyB[-1] == 0:\n self.polyB.pop()\n self.len_B = len(self.polyB)\n\n # Add 0 to make lengths equal a power of 2\n self.c_max_length = int(\n 2 ** np.ceil(np.log2(len(self.polyA) + len(self.polyB) - 1))\n )\n\n while len(self.polyA) < self.c_max_length:\n self.polyA.append(0)\n while len(self.polyB) < self.c_max_length:\n self.polyB.append(0)\n # A complex root used for the fourier transform\n self.root = complex(mpmath.root(x=1, n=self.c_max_length, k=1))\n\n # The product\n self.product = self.__multiply()\n\n # Discrete fourier transform of A and B\n def __dft(self, which):\n dft = [[x] for x in self.polyA] if which == \"A\" else [[x] for x in self.polyB]\n # Corner case\n if len(dft) <= 1:\n return dft[0]\n #\n next_ncol = self.c_max_length \/\/ 2\n while next_ncol > 0:\n new_dft = [[] for i in range(next_ncol)]\n root = self.root**next_ncol\n\n # First half of next step\n current_root = 1\n for j in range(self.c_max_length \/\/ (next_ncol * 2)):\n for i in range(next_ncol):\n new_dft[i].append(dft[i][j] + current_root * dft[i + next_ncol][j])\n current_root *= root\n # Second half of next step\n current_root = 1\n for j in range(self.c_max_length \/\/ (next_ncol * 2)):\n for i in range(next_ncol):\n new_dft[i].append(dft[i][j] - current_root * dft[i + next_ncol][j])\n current_root *= root\n # Update\n dft = new_dft\n next_ncol = next_ncol \/\/ 2\n return dft[0]\n\n # multiply the DFTs of A and B and find A*B\n def __multiply(self):\n dft_a = self.__dft(\"A\")\n dft_b = self.__dft(\"B\")\n inverce_c = [[dft_a[i] * dft_b[i] for i in range(self.c_max_length)]]\n del dft_a\n del dft_b\n\n # Corner Case\n if len(inverce_c[0]) <= 1:\n return inverce_c[0]\n # Inverse DFT\n next_ncol = 2\n while next_ncol <= self.c_max_length:\n new_inverse_c = [[] for i in range(next_ncol)]\n root = self.root ** (next_ncol \/\/ 2)\n current_root = 1\n # First half of next step\n for j in range(self.c_max_length \/\/ next_ncol):\n for i in range(next_ncol \/\/ 2):\n # Even positions\n new_inverse_c[i].append(\n (\n inverce_c[i][j]\n + inverce_c[i][j + self.c_max_length \/\/ next_ncol]\n )\n \/ 2\n )\n # Odd positions\n new_inverse_c[i + next_ncol \/\/ 2].append(\n (\n inverce_c[i][j]\n - inverce_c[i][j + self.c_max_length \/\/ next_ncol]\n )\n \/ (2 * current_root)\n )\n current_root *= root\n # Update\n inverce_c = new_inverse_c\n next_ncol *= 2\n # Unpack\n inverce_c = [round(x[0].real, 8) + round(x[0].imag, 8) * 1j for x in inverce_c]\n\n # Remove leading 0's\n while inverce_c[-1] == 0:\n inverce_c.pop()\n return inverce_c\n\n # Overwrite __str__ for print(); Shows A, B and A*B\n def __str__(self):\n a = \"A = \" + \" + \".join(\n f\"{coef}*x^{i}\" for coef, i in enumerate(self.polyA[: self.len_A])\n )\n b = \"B = \" + \" + \".join(\n f\"{coef}*x^{i}\" for coef, i in enumerate(self.polyB[: self.len_B])\n )\n c = \"A*B = \" + \" + \".join(\n f\"{coef}*x^{i}\" for coef, i in enumerate(self.product)\n )\n\n return f\"{a}\\n{b}\\n{c}\"\n\n\n# Unit tests\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"returns the biggest possible result that can be achieved by removing one digit from the given number removedigit152 52 removedigit6385 685 removedigit11 1 removedigit2222222 222222 removedigit2222222 Traceback most recent call last: TypeError: only integers accepted as input removedigitstring input Traceback most recent call last: TypeError: only integers accepted as input","Completions":"def remove_digit(num: int) -> int:\n \"\"\"\n\n returns the biggest possible result\n that can be achieved by removing\n one digit from the given number\n\n >>> remove_digit(152)\n 52\n >>> remove_digit(6385)\n 685\n >>> remove_digit(-11)\n 1\n >>> remove_digit(2222222)\n 222222\n >>> remove_digit(\"2222222\")\n Traceback (most recent call last):\n TypeError: only integers accepted as input\n >>> remove_digit(\"string input\")\n Traceback (most recent call last):\n TypeError: only integers accepted as input\n \"\"\"\n\n if not isinstance(num, int):\n raise TypeError(\"only integers accepted as input\")\n else:\n num_str = str(abs(num))\n num_transpositions = [list(num_str) for char in range(len(num_str))]\n for index in range(len(num_str)):\n num_transpositions[index].pop(index)\n return max(\n int(\"\".join(list(transposition))) for transposition in num_transpositions\n )\n\n\nif __name__ == \"__main__\":\n __import__(\"doctest\").testmod()\n"} +{"Prompt":"Segmented Sieve. import math def sieven: int listint: if n 0 or isinstancen, float: msg fNumber n must instead be a positive integer raise ValueErrormsg inprime start 2 end intmath.sqrtn Size of every segment temp True end 1 prime while start end: if tempstart is True: inprime.appendstart for i in rangestart start, end 1, start: tempi False start 1 prime inprime low end 1 high min2 end, n while low n: temp True high low 1 for each in inprime: t math.floorlow each each if t low: t each for j in ranget, high 1, each: tempj low False for j in rangelentemp: if tempj is True: prime.appendj low low high 1 high minhigh end, n return prime if name main: import doctest doctest.testmod printfsieve106","Completions":"import math\n\n\ndef sieve(n: int) -> list[int]:\n \"\"\"\n Segmented Sieve.\n\n Examples:\n >>> sieve(8)\n [2, 3, 5, 7]\n\n >>> sieve(27)\n [2, 3, 5, 7, 11, 13, 17, 19, 23]\n\n >>> sieve(0)\n Traceback (most recent call last):\n ...\n ValueError: Number 0 must instead be a positive integer\n\n >>> sieve(-1)\n Traceback (most recent call last):\n ...\n ValueError: Number -1 must instead be a positive integer\n\n >>> sieve(22.2)\n Traceback (most recent call last):\n ...\n ValueError: Number 22.2 must instead be a positive integer\n \"\"\"\n\n if n <= 0 or isinstance(n, float):\n msg = f\"Number {n} must instead be a positive integer\"\n raise ValueError(msg)\n\n in_prime = []\n start = 2\n end = int(math.sqrt(n)) # Size of every segment\n temp = [True] * (end + 1)\n prime = []\n\n while start <= end:\n if temp[start] is True:\n in_prime.append(start)\n for i in range(start * start, end + 1, start):\n temp[i] = False\n start += 1\n prime += in_prime\n\n low = end + 1\n high = min(2 * end, n)\n\n while low <= n:\n temp = [True] * (high - low + 1)\n for each in in_prime:\n t = math.floor(low \/ each) * each\n if t < low:\n t += each\n\n for j in range(t, high + 1, each):\n temp[j - low] = False\n\n for j in range(len(temp)):\n if temp[j] is True:\n prime.append(j + low)\n\n low = high + 1\n high = min(high + end, n)\n\n return prime\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n\n print(f\"{sieve(10**6) = }\")\n"} +{"Prompt":"Arithmetic mean Reference: https:en.wikipedia.orgwikiArithmeticmean Arithmetic series Reference: https:en.wikipedia.orgwikiArithmeticseries The URL above will redirect you to arithmetic progression checking whether the input series is arithmetic series or not isarithmeticseries2, 4, 6 True isarithmeticseries3, 6, 12, 24 False isarithmeticseries1, 2, 3 True isarithmeticseries4 Traceback most recent call last: ... ValueError: Input series is not valid, valid series 2, 4, 6 isarithmeticseries Traceback most recent call last: ... ValueError: Input list must be a non empty list return the arithmetic mean of series arithmeticmean2, 4, 6 4.0 arithmeticmean3, 6, 9, 12 7.5 arithmeticmean4 Traceback most recent call last: ... ValueError: Input series is not valid, valid series 2, 4, 6 arithmeticmean4, 8, 1 4.333333333333333 arithmeticmean1, 2, 3 2.0 arithmeticmean Traceback most recent call last: ... ValueError: Input list must be a non empty list","Completions":"def is_arithmetic_series(series: list) -> bool:\n \"\"\"\n checking whether the input series is arithmetic series or not\n >>> is_arithmetic_series([2, 4, 6])\n True\n >>> is_arithmetic_series([3, 6, 12, 24])\n False\n >>> is_arithmetic_series([1, 2, 3])\n True\n >>> is_arithmetic_series(4)\n Traceback (most recent call last):\n ...\n ValueError: Input series is not valid, valid series - [2, 4, 6]\n >>> is_arithmetic_series([])\n Traceback (most recent call last):\n ...\n ValueError: Input list must be a non empty list\n \"\"\"\n if not isinstance(series, list):\n raise ValueError(\"Input series is not valid, valid series - [2, 4, 6]\")\n if len(series) == 0:\n raise ValueError(\"Input list must be a non empty list\")\n if len(series) == 1:\n return True\n common_diff = series[1] - series[0]\n for index in range(len(series) - 1):\n if series[index + 1] - series[index] != common_diff:\n return False\n return True\n\n\ndef arithmetic_mean(series: list) -> float:\n \"\"\"\n return the arithmetic mean of series\n\n >>> arithmetic_mean([2, 4, 6])\n 4.0\n >>> arithmetic_mean([3, 6, 9, 12])\n 7.5\n >>> arithmetic_mean(4)\n Traceback (most recent call last):\n ...\n ValueError: Input series is not valid, valid series - [2, 4, 6]\n >>> arithmetic_mean([4, 8, 1])\n 4.333333333333333\n >>> arithmetic_mean([1, 2, 3])\n 2.0\n >>> arithmetic_mean([])\n Traceback (most recent call last):\n ...\n ValueError: Input list must be a non empty list\n\n \"\"\"\n if not isinstance(series, list):\n raise ValueError(\"Input series is not valid, valid series - [2, 4, 6]\")\n if len(series) == 0:\n raise ValueError(\"Input list must be a non empty list\")\n answer = 0\n for val in series:\n answer += val\n return answer \/ len(series)\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Geometric Mean Reference : https:en.wikipedia.orgwikiGeometricmean Geometric series Reference: https:en.wikipedia.orgwikiGeometricseries checking whether the input series is geometric series or not isgeometricseries2, 4, 8 True isgeometricseries3, 6, 12, 24 True isgeometricseries1, 2, 3 False isgeometricseries0, 0, 3 False isgeometricseries Traceback most recent call last: ... ValueError: Input list must be a non empty list isgeometricseries4 Traceback most recent call last: ... ValueError: Input series is not valid, valid series 2, 4, 8 return the geometric mean of series geometricmean2, 4, 8 3.9999999999999996 geometricmean3, 6, 12, 24 8.48528137423857 geometricmean4, 8, 16 7.999999999999999 geometricmean4 Traceback most recent call last: ... ValueError: Input series is not valid, valid series 2, 4, 8 geometricmean1, 2, 3 1.8171205928321397 geometricmean0, 2, 3 0.0 geometricmean Traceback most recent call last: ... ValueError: Input list must be a non empty list","Completions":"def is_geometric_series(series: list) -> bool:\n \"\"\"\n checking whether the input series is geometric series or not\n >>> is_geometric_series([2, 4, 8])\n True\n >>> is_geometric_series([3, 6, 12, 24])\n True\n >>> is_geometric_series([1, 2, 3])\n False\n >>> is_geometric_series([0, 0, 3])\n False\n >>> is_geometric_series([])\n Traceback (most recent call last):\n ...\n ValueError: Input list must be a non empty list\n >>> is_geometric_series(4)\n Traceback (most recent call last):\n ...\n ValueError: Input series is not valid, valid series - [2, 4, 8]\n \"\"\"\n if not isinstance(series, list):\n raise ValueError(\"Input series is not valid, valid series - [2, 4, 8]\")\n if len(series) == 0:\n raise ValueError(\"Input list must be a non empty list\")\n if len(series) == 1:\n return True\n try:\n common_ratio = series[1] \/ series[0]\n for index in range(len(series) - 1):\n if series[index + 1] \/ series[index] != common_ratio:\n return False\n except ZeroDivisionError:\n return False\n return True\n\n\ndef geometric_mean(series: list) -> float:\n \"\"\"\n return the geometric mean of series\n\n >>> geometric_mean([2, 4, 8])\n 3.9999999999999996\n >>> geometric_mean([3, 6, 12, 24])\n 8.48528137423857\n >>> geometric_mean([4, 8, 16])\n 7.999999999999999\n >>> geometric_mean(4)\n Traceback (most recent call last):\n ...\n ValueError: Input series is not valid, valid series - [2, 4, 8]\n >>> geometric_mean([1, 2, 3])\n 1.8171205928321397\n >>> geometric_mean([0, 2, 3])\n 0.0\n >>> geometric_mean([])\n Traceback (most recent call last):\n ...\n ValueError: Input list must be a non empty list\n\n \"\"\"\n if not isinstance(series, list):\n raise ValueError(\"Input series is not valid, valid series - [2, 4, 8]\")\n if len(series) == 0:\n raise ValueError(\"Input list must be a non empty list\")\n answer = 1\n for value in series:\n answer *= value\n return pow(answer, 1 \/ len(series))\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"This is a pure Python implementation of the Geometric Series algorithm https:en.wikipedia.orgwikiGeometricseries Run the doctests with the following command: python3 m doctest v geometricseries.py or python m doctest v geometricseries.py For manual testing run: python3 geometricseries.py Pure Python implementation of Geometric Series algorithm :param nthterm: The last term nth term of Geometric Series :param startterma : The first term of Geometric Series :param commonratior : The common ratio between all the terms :return: The Geometric Series starting from first term a and multiple of common ration with first term with increase in power till last term nth term Examples: geometricseries4, 2, 2 2, 4.0, 8.0, 16.0 geometricseries4.0, 2.0, 2.0 2.0, 4.0, 8.0, 16.0 geometricseries4.1, 2.1, 2.1 2.1, 4.41, 9.261000000000001, 19.448100000000004 geometricseries4, 2, 2 2, 4.0, 8.0, 16.0 geometricseries4, 2, 2 2, 4.0, 8.0, 16.0 geometricseries4, 2, 2 geometricseries0, 100, 500 geometricseries1, 1, 1 1 geometricseries0, 0, 0","Completions":"from __future__ import annotations\n\n\ndef geometric_series(\n nth_term: float,\n start_term_a: float,\n common_ratio_r: float,\n) -> list[float]:\n \"\"\"\n Pure Python implementation of Geometric Series algorithm\n\n :param nth_term: The last term (nth term of Geometric Series)\n :param start_term_a : The first term of Geometric Series\n :param common_ratio_r : The common ratio between all the terms\n :return: The Geometric Series starting from first term a and multiple of common\n ration with first term with increase in power till last term (nth term)\n Examples:\n >>> geometric_series(4, 2, 2)\n [2, 4.0, 8.0, 16.0]\n >>> geometric_series(4.0, 2.0, 2.0)\n [2.0, 4.0, 8.0, 16.0]\n >>> geometric_series(4.1, 2.1, 2.1)\n [2.1, 4.41, 9.261000000000001, 19.448100000000004]\n >>> geometric_series(4, 2, -2)\n [2, -4.0, 8.0, -16.0]\n >>> geometric_series(4, -2, 2)\n [-2, -4.0, -8.0, -16.0]\n >>> geometric_series(-4, 2, 2)\n []\n >>> geometric_series(0, 100, 500)\n []\n >>> geometric_series(1, 1, 1)\n [1]\n >>> geometric_series(0, 0, 0)\n []\n \"\"\"\n if not all((nth_term, start_term_a, common_ratio_r)):\n return []\n series: list[float] = []\n power = 1\n multiple = common_ratio_r\n for _ in range(int(nth_term)):\n if not series:\n series.append(start_term_a)\n else:\n power += 1\n series.append(float(start_term_a * multiple))\n multiple = pow(float(common_ratio_r), power)\n return series\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n\n nth_term = float(input(\"Enter the last number (n term) of the Geometric Series\"))\n start_term_a = float(input(\"Enter the starting term (a) of the Geometric Series\"))\n common_ratio_r = float(\n input(\"Enter the common ratio between two terms (r) of the Geometric Series\")\n )\n print(\"Formula of Geometric Series => a + ar + ar^2 ... +ar^n\")\n print(geometric_series(nth_term, start_term_a, common_ratio_r))\n"} +{"Prompt":"Harmonic mean Reference: https:en.wikipedia.orgwikiHarmonicmean Harmonic series Reference: https:en.wikipedia.orgwikiHarmonicseriesmathematics checking whether the input series is arithmetic series or not isharmonicseries 1, 23, 12, 25, 13 True isharmonicseries 1, 23, 25, 13 False isharmonicseries1, 2, 3 False isharmonicseries12, 13, 14 True isharmonicseries25, 210, 215, 220, 225 True isharmonicseries4 Traceback most recent call last: ... ValueError: Input series is not valid, valid series 1, 23, 2 isharmonicseries Traceback most recent call last: ... ValueError: Input list must be a non empty list isharmonicseries0 Traceback most recent call last: ... ValueError: Input series cannot have 0 as an element isharmonicseries1,2,0,6 Traceback most recent call last: ... ValueError: Input series cannot have 0 as an element return the harmonic mean of series harmonicmean1, 4, 4 2.0 harmonicmean3, 6, 9, 12 5.759999999999999 harmonicmean4 Traceback most recent call last: ... ValueError: Input series is not valid, valid series 2, 4, 6 harmonicmean1, 2, 3 1.6363636363636365 harmonicmean Traceback most recent call last: ... ValueError: Input list must be a non empty list","Completions":"def is_harmonic_series(series: list) -> bool:\n \"\"\"\n checking whether the input series is arithmetic series or not\n >>> is_harmonic_series([ 1, 2\/3, 1\/2, 2\/5, 1\/3])\n True\n >>> is_harmonic_series([ 1, 2\/3, 2\/5, 1\/3])\n False\n >>> is_harmonic_series([1, 2, 3])\n False\n >>> is_harmonic_series([1\/2, 1\/3, 1\/4])\n True\n >>> is_harmonic_series([2\/5, 2\/10, 2\/15, 2\/20, 2\/25])\n True\n >>> is_harmonic_series(4)\n Traceback (most recent call last):\n ...\n ValueError: Input series is not valid, valid series - [1, 2\/3, 2]\n >>> is_harmonic_series([])\n Traceback (most recent call last):\n ...\n ValueError: Input list must be a non empty list\n >>> is_harmonic_series([0])\n Traceback (most recent call last):\n ...\n ValueError: Input series cannot have 0 as an element\n >>> is_harmonic_series([1,2,0,6])\n Traceback (most recent call last):\n ...\n ValueError: Input series cannot have 0 as an element\n \"\"\"\n if not isinstance(series, list):\n raise ValueError(\"Input series is not valid, valid series - [1, 2\/3, 2]\")\n if len(series) == 0:\n raise ValueError(\"Input list must be a non empty list\")\n if len(series) == 1 and series[0] != 0:\n return True\n rec_series = []\n series_len = len(series)\n for i in range(series_len):\n if series[i] == 0:\n raise ValueError(\"Input series cannot have 0 as an element\")\n rec_series.append(1 \/ series[i])\n common_diff = rec_series[1] - rec_series[0]\n for index in range(2, series_len):\n if rec_series[index] - rec_series[index - 1] != common_diff:\n return False\n return True\n\n\ndef harmonic_mean(series: list) -> float:\n \"\"\"\n return the harmonic mean of series\n\n >>> harmonic_mean([1, 4, 4])\n 2.0\n >>> harmonic_mean([3, 6, 9, 12])\n 5.759999999999999\n >>> harmonic_mean(4)\n Traceback (most recent call last):\n ...\n ValueError: Input series is not valid, valid series - [2, 4, 6]\n >>> harmonic_mean([1, 2, 3])\n 1.6363636363636365\n >>> harmonic_mean([])\n Traceback (most recent call last):\n ...\n ValueError: Input list must be a non empty list\n\n \"\"\"\n if not isinstance(series, list):\n raise ValueError(\"Input series is not valid, valid series - [2, 4, 6]\")\n if len(series) == 0:\n raise ValueError(\"Input list must be a non empty list\")\n answer = 0\n for val in series:\n answer += 1 \/ val\n return len(series) \/ answer\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"This is a pure Python implementation of the Harmonic Series algorithm https:en.wikipedia.orgwikiHarmonicseriesmathematics For doctests run following command: python m doctest v harmonicseries.py or python3 m doctest v harmonicseries.py For manual testing run: python3 harmonicseries.py Pure Python implementation of Harmonic Series algorithm :param nterm: The last nth term of Harmonic Series :return: The Harmonic Series starting from 1 to last nth term Examples: harmonicseries5 '1', '12', '13', '14', '15' harmonicseries5.0 '1', '12', '13', '14', '15' harmonicseries5.1 '1', '12', '13', '14', '15' harmonicseries5 harmonicseries0 harmonicseries1 '1'","Completions":"def harmonic_series(n_term: str) -> list:\n \"\"\"Pure Python implementation of Harmonic Series algorithm\n\n :param n_term: The last (nth) term of Harmonic Series\n :return: The Harmonic Series starting from 1 to last (nth) term\n\n Examples:\n >>> harmonic_series(5)\n ['1', '1\/2', '1\/3', '1\/4', '1\/5']\n >>> harmonic_series(5.0)\n ['1', '1\/2', '1\/3', '1\/4', '1\/5']\n >>> harmonic_series(5.1)\n ['1', '1\/2', '1\/3', '1\/4', '1\/5']\n >>> harmonic_series(-5)\n []\n >>> harmonic_series(0)\n []\n >>> harmonic_series(1)\n ['1']\n \"\"\"\n if n_term == \"\":\n return []\n series: list = []\n for temp in range(int(n_term)):\n series.append(f\"1\/{temp + 1}\" if series else \"1\")\n return series\n\n\nif __name__ == \"__main__\":\n nth_term = input(\"Enter the last number (nth term) of the Harmonic Series\")\n print(\"Formula of Harmonic Series => 1+1\/2+1\/3 ..... 1\/n\")\n print(harmonic_series(nth_term))\n"} +{"Prompt":"A hexagonal number sequence is a sequence of figurate numbers where the nth hexagonal number h is the number of distinct dots in a pattern of dots consisting of the outlines of regular hexagons with sides up to n dots, when the hexagons are overlaid so that they share one vertex. Calculates the hexagonal numbers sequence with a formula h n2n1 where: h is nth element of the sequence n is the number of element in the sequence referenceHexagonal number Wikipedia https:en.wikipedia.orgwikiHexagonalnumber :param len: max number of elements :type len: int :return: Hexagonal numbers as a list Tests: hexagonalnumbers10 0, 1, 6, 15, 28, 45, 66, 91, 120, 153 hexagonalnumbers5 0, 1, 6, 15, 28 hexagonalnumbers0 Traceback most recent call last: ... ValueError: Length must be a positive integer.","Completions":"def hexagonal_numbers(length: int) -> list[int]:\n \"\"\"\n :param len: max number of elements\n :type len: int\n :return: Hexagonal numbers as a list\n\n Tests:\n >>> hexagonal_numbers(10)\n [0, 1, 6, 15, 28, 45, 66, 91, 120, 153]\n >>> hexagonal_numbers(5)\n [0, 1, 6, 15, 28]\n >>> hexagonal_numbers(0)\n Traceback (most recent call last):\n ...\n ValueError: Length must be a positive integer.\n \"\"\"\n\n if length <= 0 or not isinstance(length, int):\n raise ValueError(\"Length must be a positive integer.\")\n return [n * (2 * n - 1) for n in range(length)]\n\n\nif __name__ == \"__main__\":\n print(hexagonal_numbers(length=5))\n print(hexagonal_numbers(length=10))\n"} +{"Prompt":"This is a pure Python implementation of the PSeries algorithm https:en.wikipedia.orgwikiHarmonicseriesmathematicsPseries For doctests run following command: python m doctest v pseries.py or python3 m doctest v pseries.py For manual testing run: python3 pseries.py Pure Python implementation of PSeries algorithm :return: The PSeries starting from 1 to last nth term Examples: pseries5, 2 '1', '1 4', '1 9', '1 16', '1 25' pseries5, 2 pseries5, 2 '1', '1 0.25', '1 0.1111111111111111', '1 0.0625', '1 0.04' pseries, 1000 '' pseries0, 0 pseries1, 1 '1'","Completions":"from __future__ import annotations\n\n\ndef p_series(nth_term: float | str, power: float | str) -> list[str]:\n \"\"\"\n Pure Python implementation of P-Series algorithm\n :return: The P-Series starting from 1 to last (nth) term\n Examples:\n >>> p_series(5, 2)\n ['1', '1 \/ 4', '1 \/ 9', '1 \/ 16', '1 \/ 25']\n >>> p_series(-5, 2)\n []\n >>> p_series(5, -2)\n ['1', '1 \/ 0.25', '1 \/ 0.1111111111111111', '1 \/ 0.0625', '1 \/ 0.04']\n >>> p_series(\"\", 1000)\n ['']\n >>> p_series(0, 0)\n []\n >>> p_series(1, 1)\n ['1']\n \"\"\"\n if nth_term == \"\":\n return [\"\"]\n nth_term = int(nth_term)\n power = int(power)\n series: list[str] = []\n for temp in range(int(nth_term)):\n series.append(f\"1 \/ {pow(temp + 1, int(power))}\" if series else \"1\")\n return series\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n\n nth_term = int(input(\"Enter the last number (nth term) of the P-Series\"))\n power = int(input(\"Enter the power for P-Series\"))\n print(\"Formula of P-Series => 1+1\/2^p+1\/3^p ..... 1\/n^p\")\n print(p_series(nth_term, power))\n"} +{"Prompt":"Sieve of Eratosthones The sieve of Eratosthenes is an algorithm used to find prime numbers, less than or equal to a given value. Illustration: https:upload.wikimedia.orgwikipediacommonsbb9SieveofEratosthenesanimation.gif Reference: https:en.wikipedia.orgwikiSieveofEratosthenes doctest provider: Bruno Simas Hadlich https:github.combrunohadlich Also thanks to Dmitry https:github.comLizardWizzard for finding the problem Returns a list with all prime numbers up to n. primesieve50 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47 primesieve25 2, 3, 5, 7, 11, 13, 17, 19, 23 primesieve10 2, 3, 5, 7 primesieve9 2, 3, 5, 7 primesieve2 2 primesieve1 If start is a prime Set multiples of start be False","Completions":"from __future__ import annotations\n\nimport math\n\n\ndef prime_sieve(num: int) -> list[int]:\n \"\"\"\n Returns a list with all prime numbers up to n.\n\n >>> prime_sieve(50)\n [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]\n >>> prime_sieve(25)\n [2, 3, 5, 7, 11, 13, 17, 19, 23]\n >>> prime_sieve(10)\n [2, 3, 5, 7]\n >>> prime_sieve(9)\n [2, 3, 5, 7]\n >>> prime_sieve(2)\n [2]\n >>> prime_sieve(1)\n []\n \"\"\"\n\n if num <= 0:\n msg = f\"{num}: Invalid input, please enter a positive integer.\"\n raise ValueError(msg)\n\n sieve = [True] * (num + 1)\n prime = []\n start = 2\n end = int(math.sqrt(num))\n\n while start <= end:\n # If start is a prime\n if sieve[start] is True:\n prime.append(start)\n\n # Set multiples of start be False\n for i in range(start * start, num + 1, start):\n if sieve[i] is True:\n sieve[i] = False\n\n start += 1\n\n for j in range(end + 1, num + 1):\n if sieve[j] is True:\n prime.append(j)\n\n return prime\n\n\nif __name__ == \"__main__\":\n print(prime_sieve(int(input(\"Enter a positive integer: \").strip())))\n"} +{"Prompt":"This script demonstrates the implementation of the Sigmoid function. The function takes a vector of K real numbers as input and then 1 1 expx. After through Sigmoid, the element of the vector mostly 0 between 1. or 1 between 1. Script inspired from its corresponding Wikipedia article https:en.wikipedia.orgwikiSigmoidfunction Implements the sigmoid function Parameters: vector np.array: A numpy array of shape 1,n consisting of real values Returns: sigmoidvec np.array: The input numpy array, after applying sigmoid. Examples: sigmoidnp.array1.0, 1.0, 2.0 array0.26894142, 0.73105858, 0.88079708 sigmoidnp.array0.0 array0.5","Completions":"import numpy as np\n\n\ndef sigmoid(vector: np.ndarray) -> np.ndarray:\n \"\"\"\n Implements the sigmoid function\n\n Parameters:\n vector (np.array): A numpy array of shape (1,n)\n consisting of real values\n\n Returns:\n sigmoid_vec (np.array): The input numpy array, after applying\n sigmoid.\n\n Examples:\n >>> sigmoid(np.array([-1.0, 1.0, 2.0]))\n array([0.26894142, 0.73105858, 0.88079708])\n\n >>> sigmoid(np.array([0.0]))\n array([0.5])\n \"\"\"\n return 1 \/ (1 + np.exp(-vector))\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Signum function https:en.wikipedia.orgwikiSignfunction Applies signum function on the number Custom test cases: signum10 1 signum10 1 signum0 0 signum20.5 1 signum20.5 1 signum1e6 1 signum1e6 1 signumHello Traceback most recent call last: ... TypeError: '' not supported between instances of 'str' and 'int' signum Traceback most recent call last: ... TypeError: '' not supported between instances of 'list' and 'int' Tests the signum function testsignum","Completions":"def signum(num: float) -> int:\n \"\"\"\n Applies signum function on the number\n\n Custom test cases:\n >>> signum(-10)\n -1\n >>> signum(10)\n 1\n >>> signum(0)\n 0\n >>> signum(-20.5)\n -1\n >>> signum(20.5)\n 1\n >>> signum(-1e-6)\n -1\n >>> signum(1e-6)\n 1\n >>> signum(\"Hello\")\n Traceback (most recent call last):\n ...\n TypeError: '<' not supported between instances of 'str' and 'int'\n >>> signum([])\n Traceback (most recent call last):\n ...\n TypeError: '<' not supported between instances of 'list' and 'int'\n \"\"\"\n if num < 0:\n return -1\n return 1 if num else 0\n\n\ndef test_signum() -> None:\n \"\"\"\n Tests the signum function\n >>> test_signum()\n \"\"\"\n assert signum(5) == 1\n assert signum(-5) == -1\n assert signum(0) == 0\n assert signum(10.5) == 1\n assert signum(-10.5) == -1\n assert signum(1e-6) == 1\n assert signum(-1e-6) == -1\n assert signum(123456789) == 1\n assert signum(-123456789) == -1\n\n\nif __name__ == \"__main__\":\n print(signum(12))\n print(signum(-12))\n print(signum(0))\n"} +{"Prompt":"https:en.wikipedia.orgwikiAugmentedmatrix This algorithm solves simultaneous linear equations of the form a b c d ... as , , , , ..., Where are individual coefficients, the no. of equations no. of coefficients 1 Note in order to work there must exist 1 equation where all instances of and ! 0 simplify1, 2, 3, 4, 5, 6 1.0, 2.0, 3.0, 0.0, 0.75, 1.5 simplify5, 2, 5, 5, 1, 10 1.0, 0.4, 1.0, 0.0, 0.2, 1.0 Divide each row by magnitude of first term creates 'unit' matrix Subtract to cancel term If first term is 0, it is already in form we want, so we preserve it Create next recursion iteration set solvesimultaneous1, 2, 3,4, 5, 6 1.0, 2.0 solvesimultaneous0, 3, 1, 7,3, 2, 1, 11,5, 1, 2, 12 6.4, 1.2, 10.6 solvesimultaneous Traceback most recent call last: ... IndexError: solvesimultaneous requires n lists of length n1 solvesimultaneous1, 2, 3,1, 2 Traceback most recent call last: ... IndexError: solvesimultaneous requires n lists of length n1 solvesimultaneous1, 2, 3,a, 7, 8 Traceback most recent call last: ... ValueError: solvesimultaneous requires lists of integers solvesimultaneous0, 2, 3,4, 0, 6 Traceback most recent call last: ... ValueError: solvesimultaneous requires at least 1 full equation","Completions":"def simplify(current_set: list[list]) -> list[list]:\n \"\"\"\n >>> simplify([[1, 2, 3], [4, 5, 6]])\n [[1.0, 2.0, 3.0], [0.0, 0.75, 1.5]]\n >>> simplify([[5, 2, 5], [5, 1, 10]])\n [[1.0, 0.4, 1.0], [0.0, 0.2, -1.0]]\n \"\"\"\n # Divide each row by magnitude of first term --> creates 'unit' matrix\n duplicate_set = current_set.copy()\n for row_index, row in enumerate(duplicate_set):\n magnitude = row[0]\n for column_index, column in enumerate(row):\n if magnitude == 0:\n current_set[row_index][column_index] = column\n continue\n current_set[row_index][column_index] = column \/ magnitude\n # Subtract to cancel term\n first_row = current_set[0]\n final_set = [first_row]\n current_set = current_set[1::]\n for row in current_set:\n temp_row = []\n # If first term is 0, it is already in form we want, so we preserve it\n if row[0] == 0:\n final_set.append(row)\n continue\n for column_index in range(len(row)):\n temp_row.append(first_row[column_index] - row[column_index])\n final_set.append(temp_row)\n # Create next recursion iteration set\n if len(final_set[0]) != 3:\n current_first_row = final_set[0]\n current_first_column = []\n next_iteration = []\n for row in final_set[1::]:\n current_first_column.append(row[0])\n next_iteration.append(row[1::])\n resultant = simplify(next_iteration)\n for i in range(len(resultant)):\n resultant[i].insert(0, current_first_column[i])\n resultant.insert(0, current_first_row)\n final_set = resultant\n return final_set\n\n\ndef solve_simultaneous(equations: list[list]) -> list:\n \"\"\"\n >>> solve_simultaneous([[1, 2, 3],[4, 5, 6]])\n [-1.0, 2.0]\n >>> solve_simultaneous([[0, -3, 1, 7],[3, 2, -1, 11],[5, 1, -2, 12]])\n [6.4, 1.2, 10.6]\n >>> solve_simultaneous([])\n Traceback (most recent call last):\n ...\n IndexError: solve_simultaneous() requires n lists of length n+1\n >>> solve_simultaneous([[1, 2, 3],[1, 2]])\n Traceback (most recent call last):\n ...\n IndexError: solve_simultaneous() requires n lists of length n+1\n >>> solve_simultaneous([[1, 2, 3],[\"a\", 7, 8]])\n Traceback (most recent call last):\n ...\n ValueError: solve_simultaneous() requires lists of integers\n >>> solve_simultaneous([[0, 2, 3],[4, 0, 6]])\n Traceback (most recent call last):\n ...\n ValueError: solve_simultaneous() requires at least 1 full equation\n \"\"\"\n if len(equations) == 0:\n raise IndexError(\"solve_simultaneous() requires n lists of length n+1\")\n _length = len(equations) + 1\n if any(len(item) != _length for item in equations):\n raise IndexError(\"solve_simultaneous() requires n lists of length n+1\")\n for row in equations:\n if any(not isinstance(column, (int, float)) for column in row):\n raise ValueError(\"solve_simultaneous() requires lists of integers\")\n if len(equations) == 1:\n return [equations[0][-1] \/ equations[0][0]]\n data_set = equations.copy()\n if any(0 in row for row in data_set):\n temp_data = data_set.copy()\n full_row = []\n for row_index, row in enumerate(temp_data):\n if 0 not in row:\n full_row = data_set.pop(row_index)\n break\n if not full_row:\n raise ValueError(\"solve_simultaneous() requires at least 1 full equation\")\n data_set.insert(0, full_row)\n useable_form = data_set.copy()\n simplified = simplify(useable_form)\n simplified = simplified[::-1]\n solutions: list = []\n for row in simplified:\n current_solution = row[-1]\n if not solutions:\n if row[-2] == 0:\n solutions.append(0)\n continue\n solutions.append(current_solution \/ row[-2])\n continue\n temp_row = row.copy()[: len(row) - 1 :]\n while temp_row[0] == 0:\n temp_row.pop(0)\n if len(temp_row) == 0:\n solutions.append(0)\n continue\n temp_row = temp_row[1::]\n temp_row = temp_row[::-1]\n for column_index, column in enumerate(temp_row):\n current_solution -= column * solutions[column_index]\n solutions.append(current_solution)\n final = []\n for item in solutions:\n final.append(float(round(item, 5)))\n return final[::-1]\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n eq = [\n [2, 1, 1, 1, 1, 4],\n [1, 2, 1, 1, 1, 5],\n [1, 1, 2, 1, 1, 6],\n [1, 1, 1, 2, 1, 7],\n [1, 1, 1, 1, 2, 8],\n ]\n print(solve_simultaneous(eq))\n print(solve_simultaneous([[4, 2]]))\n"} +{"Prompt":"Calculate sin function. It's not a perfect function so I am rounding the result to 10 decimal places by default. Formula: sinx x x33! x55! x77! ... Where: x angle in randians. Source: https:www.homeschoolmath.netteachingsinecalculator.php Implement sin function. sin0.0 0.0 sin90.0 1.0 sin180.0 0.0 sin270.0 1.0 sin0.68 0.0118679603 sin1.97 0.0343762121 sin64.0 0.8987940463 sin9999.0 0.9876883406 sin689.0 0.5150380749 sin89.7 0.9999862922 Simplify the angle to be between 360 and 360 degrees. Converting from degrees to radians","Completions":"from math import factorial, radians\n\n\ndef sin(\n angle_in_degrees: float, accuracy: int = 18, rounded_values_count: int = 10\n) -> float:\n \"\"\"\n Implement sin function.\n\n >>> sin(0.0)\n 0.0\n >>> sin(90.0)\n 1.0\n >>> sin(180.0)\n 0.0\n >>> sin(270.0)\n -1.0\n >>> sin(0.68)\n 0.0118679603\n >>> sin(1.97)\n 0.0343762121\n >>> sin(64.0)\n 0.8987940463\n >>> sin(9999.0)\n -0.9876883406\n >>> sin(-689.0)\n 0.5150380749\n >>> sin(89.7)\n 0.9999862922\n \"\"\"\n # Simplify the angle to be between 360 and -360 degrees.\n angle_in_degrees = angle_in_degrees - ((angle_in_degrees \/\/ 360.0) * 360.0)\n\n # Converting from degrees to radians\n angle_in_radians = radians(angle_in_degrees)\n\n result = angle_in_radians\n a = 3\n b = -1\n\n for _ in range(accuracy):\n result += (b * (angle_in_radians**a)) \/ factorial(a)\n\n b = -b # One positive term and the next will be negative and so on...\n a += 2 # Increased by 2 for every term.\n\n return round(result, rounded_values_count)\n\n\nif __name__ == \"__main__\":\n __import__(\"doctest\").testmod()\n"} +{"Prompt":"sockmerchant10, 20, 20, 10, 10, 30, 50, 10, 20 3 sockmerchant1, 1, 3, 3 2","Completions":"from collections import Counter\n\n\ndef sock_merchant(colors: list[int]) -> int:\n \"\"\"\n >>> sock_merchant([10, 20, 20, 10, 10, 30, 50, 10, 20])\n 3\n >>> sock_merchant([1, 1, 3, 3])\n 2\n \"\"\"\n return sum(socks_by_color \/\/ 2 for socks_by_color in Counter(colors).values())\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n\n colors = [int(x) for x in input(\"Enter socks by color :\").rstrip().split()]\n print(f\"sock_merchant({colors}) = {sock_merchant(colors)}\")\n"} +{"Prompt":"This script demonstrates the implementation of the Softmax function. Its a function that takes as input a vector of K real numbers, and normalizes it into a probability distribution consisting of K probabilities proportional to the exponentials of the input numbers. After softmax, the elements of the vector always sum up to 1. Script inspired from its corresponding Wikipedia article https:en.wikipedia.orgwikiSoftmaxfunction Implements the softmax function Parameters: vector np.array,list,tuple: A numpy array of shape 1,n consisting of real values or a similar list,tuple Returns: softmaxvec np.array: The input numpy array after applying softmax. The softmax vector adds up to one. We need to ceil to mitigate for precision np.ceilnp.sumsoftmax1,2,3,4 1.0 vec np.array5,5 softmaxvec array0.5, 0.5 softmax0 array1. Calculate ex for each x in your vector where e is Euler's number approximately 2.718 Add up the all the exponentials Divide every exponent by the sum of all exponents","Completions":"import numpy as np\n\n\ndef softmax(vector):\n \"\"\"\n Implements the softmax function\n\n Parameters:\n vector (np.array,list,tuple): A numpy array of shape (1,n)\n consisting of real values or a similar list,tuple\n\n\n Returns:\n softmax_vec (np.array): The input numpy array after applying\n softmax.\n\n The softmax vector adds up to one. We need to ceil to mitigate for\n precision\n >>> np.ceil(np.sum(softmax([1,2,3,4])))\n 1.0\n\n >>> vec = np.array([5,5])\n >>> softmax(vec)\n array([0.5, 0.5])\n\n >>> softmax([0])\n array([1.])\n \"\"\"\n\n # Calculate e^x for each x in your vector where e is Euler's\n # number (approximately 2.718)\n exponent_vector = np.exp(vector)\n\n # Add up the all the exponentials\n sum_of_exponents = np.sum(exponent_vector)\n\n # Divide every exponent by the sum of all exponents\n softmax_vector = exponent_vector \/ sum_of_exponents\n\n return softmax_vector\n\n\nif __name__ == \"__main__\":\n print(softmax((0,)))\n"} +{"Prompt":"This script implements the SolovayStrassen Primality test. This probabilistic primality test is based on Euler's criterion. It is similar to the Fermat test but uses quadratic residues. It can quickly identify composite numbers but may occasionally classify composite numbers as prime. More details and concepts about this can be found on: https:en.wikipedia.orgwikiSolovayE28093Strassenprimalitytest Calculate the Jacobi symbol. The Jacobi symbol is a generalization of the Legendre symbol, which can be used to simplify computations involving quadratic residues. The Jacobi symbol is used in primality tests, like the SolovayStrassen test, because it helps determine if an integer is a quadratic residue modulo a given modulus, providing valuable information about the number's potential primality or compositeness. Parameters: randoma: A randomly chosen integer from 2 to n2 inclusive number: The number that is tested for primality Returns: jacobisymbol: The Jacobi symbol is a mathematical function used to determine whether an integer is a quadratic residue modulo another integer usually prime or not. jacobisymbol2, 13 1 jacobisymbol5, 19 1 jacobisymbol7, 14 0 Check whether the input number is prime or not using the SolovayStrassen Primality test Parameters: number: The number that is tested for primality iterations: The number of times that the test is run which effects the accuracy Returns: result: True if number is probably prime and false if not random.seed10 solovaystrassen13, 5 True solovaystrassen9, 10 False solovaystrassen17, 15 True","Completions":"import random\n\n\ndef jacobi_symbol(random_a: int, number: int) -> int:\n \"\"\"\n Calculate the Jacobi symbol. The Jacobi symbol is a generalization\n of the Legendre symbol, which can be used to simplify computations involving\n quadratic residues. The Jacobi symbol is used in primality tests, like the\n Solovay-Strassen test, because it helps determine if an integer is a\n quadratic residue modulo a given modulus, providing valuable information\n about the number's potential primality or compositeness.\n\n Parameters:\n random_a: A randomly chosen integer from 2 to n-2 (inclusive)\n number: The number that is tested for primality\n\n Returns:\n jacobi_symbol: The Jacobi symbol is a mathematical function\n used to determine whether an integer is a quadratic residue modulo\n another integer (usually prime) or not.\n\n >>> jacobi_symbol(2, 13)\n -1\n >>> jacobi_symbol(5, 19)\n 1\n >>> jacobi_symbol(7, 14)\n 0\n \"\"\"\n\n if random_a in (0, 1):\n return random_a\n\n random_a %= number\n t = 1\n\n while random_a != 0:\n while random_a % 2 == 0:\n random_a \/\/= 2\n r = number % 8\n if r in (3, 5):\n t = -t\n\n random_a, number = number, random_a\n\n if random_a % 4 == number % 4 == 3:\n t = -t\n\n random_a %= number\n\n return t if number == 1 else 0\n\n\ndef solovay_strassen(number: int, iterations: int) -> bool:\n \"\"\"\n Check whether the input number is prime or not using\n the Solovay-Strassen Primality test\n\n Parameters:\n number: The number that is tested for primality\n iterations: The number of times that the test is run\n which effects the accuracy\n\n Returns:\n result: True if number is probably prime and false\n if not\n\n >>> random.seed(10)\n >>> solovay_strassen(13, 5)\n True\n >>> solovay_strassen(9, 10)\n False\n >>> solovay_strassen(17, 15)\n True\n \"\"\"\n\n if number <= 1:\n return False\n if number <= 3:\n return True\n\n for _ in range(iterations):\n a = random.randint(2, number - 2)\n x = jacobi_symbol(a, number)\n y = pow(a, (number - 1) \/\/ 2, number)\n\n if x == 0 or y != x % number:\n return False\n\n return True\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Assigns ranks to elements in the array. :param data: List of floats. :return: List of ints representing the ranks. Example: assignranks3.2, 1.5, 4.0, 2.7, 5.1 3, 1, 4, 2, 5 assignranks10.5, 8.1, 12.4, 9.3, 11.0 3, 1, 5, 2, 4 Calculates Spearman's rank correlation coefficient. :param variable1: List of floats representing the first variable. :param variable2: List of floats representing the second variable. :return: Spearman's rank correlation coefficient. Example Usage: x 1, 2, 3, 4, 5 y 5, 4, 3, 2, 1 calculatespearmanrankcorrelationx, y 1.0 x 1, 2, 3, 4, 5 y 2, 4, 6, 8, 10 calculatespearmanrankcorrelationx, y 1.0 x 1, 2, 3, 4, 5 y 5, 1, 2, 9, 5 calculatespearmanrankcorrelationx, y 0.6 Calculate differences of ranks Calculate the sum of squared differences Calculate the Spearman's rank correlation coefficient Example usage:","Completions":"from collections.abc import Sequence\n\n\ndef assign_ranks(data: Sequence[float]) -> list[int]:\n \"\"\"\n Assigns ranks to elements in the array.\n\n :param data: List of floats.\n :return: List of ints representing the ranks.\n\n Example:\n >>> assign_ranks([3.2, 1.5, 4.0, 2.7, 5.1])\n [3, 1, 4, 2, 5]\n\n >>> assign_ranks([10.5, 8.1, 12.4, 9.3, 11.0])\n [3, 1, 5, 2, 4]\n \"\"\"\n ranked_data = sorted((value, index) for index, value in enumerate(data))\n ranks = [0] * len(data)\n\n for position, (_, index) in enumerate(ranked_data):\n ranks[index] = position + 1\n\n return ranks\n\n\ndef calculate_spearman_rank_correlation(\n variable_1: Sequence[float], variable_2: Sequence[float]\n) -> float:\n \"\"\"\n Calculates Spearman's rank correlation coefficient.\n\n :param variable_1: List of floats representing the first variable.\n :param variable_2: List of floats representing the second variable.\n :return: Spearman's rank correlation coefficient.\n\n Example Usage:\n\n >>> x = [1, 2, 3, 4, 5]\n >>> y = [5, 4, 3, 2, 1]\n >>> calculate_spearman_rank_correlation(x, y)\n -1.0\n\n >>> x = [1, 2, 3, 4, 5]\n >>> y = [2, 4, 6, 8, 10]\n >>> calculate_spearman_rank_correlation(x, y)\n 1.0\n\n >>> x = [1, 2, 3, 4, 5]\n >>> y = [5, 1, 2, 9, 5]\n >>> calculate_spearman_rank_correlation(x, y)\n 0.6\n \"\"\"\n n = len(variable_1)\n rank_var1 = assign_ranks(variable_1)\n rank_var2 = assign_ranks(variable_2)\n\n # Calculate differences of ranks\n d = [rx - ry for rx, ry in zip(rank_var1, rank_var2)]\n\n # Calculate the sum of squared differences\n d_squared = sum(di**2 for di in d)\n\n # Calculate the Spearman's rank correlation coefficient\n rho = 1 - (6 * d_squared) \/ (n * (n**2 - 1))\n\n return rho\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n\n # Example usage:\n print(\n f\"{calculate_spearman_rank_correlation([1, 2, 3, 4, 5], [2, 4, 6, 8, 10]) = }\"\n )\n\n print(f\"{calculate_spearman_rank_correlation([1, 2, 3, 4, 5], [5, 4, 3, 2, 1]) = }\")\n\n print(f\"{calculate_spearman_rank_correlation([1, 2, 3, 4, 5], [5, 1, 2, 9, 5]) = }\")\n"} +{"Prompt":"An Armstrong number is equal to the sum of its own digits each raised to the power of the number of digits. For example, 370 is an Armstrong number because 333 777 000 370. Armstrong numbers are also called Narcissistic numbers and Pluperfect numbers. OnLine Encyclopedia of Integer Sequences entry: https:oeis.orgA005188 Return True if n is an Armstrong number or False if it is not. allarmstrongnumbern for n in PASSING True anyarmstrongnumbern for n in FAILING False Initialization of sum and number of digits. Calculation of digits of the number Dividing number into separate digits and find Armstrong number Return True if n is a pluperfect number or False if it is not allarmstrongnumbern for n in PASSING True anyarmstrongnumbern for n in FAILING False Init a histogram of the digits Return True if n is a narcissistic number or False if it is not. allarmstrongnumbern for n in PASSING True anyarmstrongnumbern for n in FAILING False check if sum of each digit multiplied expo times is equal to number Request that user input an integer and tell them if it is Armstrong number.","Completions":"PASSING = (1, 153, 370, 371, 1634, 24678051, 115132219018763992565095597973971522401)\nFAILING: tuple = (-153, -1, 0, 1.2, 200, \"A\", [], {}, None)\n\n\ndef armstrong_number(n: int) -> bool:\n \"\"\"\n Return True if n is an Armstrong number or False if it is not.\n\n >>> all(armstrong_number(n) for n in PASSING)\n True\n >>> any(armstrong_number(n) for n in FAILING)\n False\n \"\"\"\n if not isinstance(n, int) or n < 1:\n return False\n\n # Initialization of sum and number of digits.\n total = 0\n number_of_digits = 0\n temp = n\n # Calculation of digits of the number\n number_of_digits = len(str(n))\n # Dividing number into separate digits and find Armstrong number\n temp = n\n while temp > 0:\n rem = temp % 10\n total += rem**number_of_digits\n temp \/\/= 10\n return n == total\n\n\ndef pluperfect_number(n: int) -> bool:\n \"\"\"Return True if n is a pluperfect number or False if it is not\n\n >>> all(armstrong_number(n) for n in PASSING)\n True\n >>> any(armstrong_number(n) for n in FAILING)\n False\n \"\"\"\n if not isinstance(n, int) or n < 1:\n return False\n\n # Init a \"histogram\" of the digits\n digit_histogram = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n digit_total = 0\n total = 0\n temp = n\n while temp > 0:\n temp, rem = divmod(temp, 10)\n digit_histogram[rem] += 1\n digit_total += 1\n\n for cnt, i in zip(digit_histogram, range(len(digit_histogram))):\n total += cnt * i**digit_total\n\n return n == total\n\n\ndef narcissistic_number(n: int) -> bool:\n \"\"\"Return True if n is a narcissistic number or False if it is not.\n\n >>> all(armstrong_number(n) for n in PASSING)\n True\n >>> any(armstrong_number(n) for n in FAILING)\n False\n \"\"\"\n if not isinstance(n, int) or n < 1:\n return False\n expo = len(str(n)) # the power that all digits will be raised to\n # check if sum of each digit multiplied expo times is equal to number\n return n == sum(int(i) ** expo for i in str(n))\n\n\ndef main():\n \"\"\"\n Request that user input an integer and tell them if it is Armstrong number.\n \"\"\"\n num = int(input(\"Enter an integer to see if it is an Armstrong number: \").strip())\n print(f\"{num} is {'' if armstrong_number(num) else 'not '}an Armstrong number.\")\n print(f\"{num} is {'' if narcissistic_number(num) else 'not '}an Armstrong number.\")\n print(f\"{num} is {'' if pluperfect_number(num) else 'not '}an Armstrong number.\")\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n main()\n"} +{"Prompt":"Automorphic Numbers A number n is said to be a Automorphic number if the square of n ends in the same digits as n itself. Examples of Automorphic Numbers: 0, 1, 5, 6, 25, 76, 376, 625, 9376, 90625, ... https:en.wikipedia.orgwikiAutomorphicnumber Author : Akshay Dubey https:github.comitsAkshayDubey Time Complexity : Olog10n doctest: NORMALIZEWHITESPACE This functions takes an integer number as input. returns True if the number is automorphic. isautomorphicnumber1 False isautomorphicnumber0 True isautomorphicnumber5 True isautomorphicnumber6 True isautomorphicnumber7 False isautomorphicnumber25 True isautomorphicnumber259918212890625 True isautomorphicnumber259918212890636 False isautomorphicnumber740081787109376 True isautomorphicnumber5.0 Traceback most recent call last: ... TypeError: Input value of number5.0 must be an integer","Completions":"# Author : Akshay Dubey (https:\/\/github.com\/itsAkshayDubey)\n# Time Complexity : O(log10n)\n\n\ndef is_automorphic_number(number: int) -> bool:\n \"\"\"\n # doctest: +NORMALIZE_WHITESPACE\n This functions takes an integer number as input.\n returns True if the number is automorphic.\n >>> is_automorphic_number(-1)\n False\n >>> is_automorphic_number(0)\n True\n >>> is_automorphic_number(5)\n True\n >>> is_automorphic_number(6)\n True\n >>> is_automorphic_number(7)\n False\n >>> is_automorphic_number(25)\n True\n >>> is_automorphic_number(259918212890625)\n True\n >>> is_automorphic_number(259918212890636)\n False\n >>> is_automorphic_number(740081787109376)\n True\n >>> is_automorphic_number(5.0)\n Traceback (most recent call last):\n ...\n TypeError: Input value of [number=5.0] must be an integer\n \"\"\"\n if not isinstance(number, int):\n msg = f\"Input value of [number={number}] must be an integer\"\n raise TypeError(msg)\n if number < 0:\n return False\n number_square = number * number\n while number > 0:\n if number % 10 != number_square % 10:\n return False\n number \/\/= 10\n number_square \/\/= 10\n return True\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Bell numbers represent the number of ways to partition a set into nonempty subsets. This module provides functions to calculate Bell numbers for sets of integers. In other words, the first n 1 Bell numbers. For more information about Bell numbers, refer to: https:en.wikipedia.orgwikiBellnumber Calculate Bell numbers for the sets of lengths from 0 to maxsetlength. In other words, calculate first maxsetlength 1 Bell numbers. Args: maxsetlength int: The maximum length of the sets for which Bell numbers are calculated. Returns: list: A list of Bell numbers for sets of lengths from 0 to maxsetlength. Examples: bellnumbers0 1 bellnumbers1 1, 1 bellnumbers5 1, 1, 2, 5, 15, 52 Calculate the binomial coefficient Ctotalelements, elementstochoose Args: totalelements int: The total number of elements. elementstochoose int: The number of elements to choose. Returns: int: The binomial coefficient Ctotalelements, elementstochoose. Examples: binomialcoefficient5, 2 10 binomialcoefficient6, 3 20","Completions":"def bell_numbers(max_set_length: int) -> list[int]:\n \"\"\"\n Calculate Bell numbers for the sets of lengths from 0 to max_set_length.\n In other words, calculate first (max_set_length + 1) Bell numbers.\n\n Args:\n max_set_length (int): The maximum length of the sets for which\n Bell numbers are calculated.\n\n Returns:\n list: A list of Bell numbers for sets of lengths from 0 to max_set_length.\n\n Examples:\n >>> bell_numbers(0)\n [1]\n >>> bell_numbers(1)\n [1, 1]\n >>> bell_numbers(5)\n [1, 1, 2, 5, 15, 52]\n \"\"\"\n if max_set_length < 0:\n raise ValueError(\"max_set_length must be non-negative\")\n\n bell = [0] * (max_set_length + 1)\n bell[0] = 1\n\n for i in range(1, max_set_length + 1):\n for j in range(i):\n bell[i] += _binomial_coefficient(i - 1, j) * bell[j]\n\n return bell\n\n\ndef _binomial_coefficient(total_elements: int, elements_to_choose: int) -> int:\n \"\"\"\n Calculate the binomial coefficient C(total_elements, elements_to_choose)\n\n Args:\n total_elements (int): The total number of elements.\n elements_to_choose (int): The number of elements to choose.\n\n Returns:\n int: The binomial coefficient C(total_elements, elements_to_choose).\n\n Examples:\n >>> _binomial_coefficient(5, 2)\n 10\n >>> _binomial_coefficient(6, 3)\n 20\n \"\"\"\n if elements_to_choose in {0, total_elements}:\n return 1\n\n if elements_to_choose > total_elements - elements_to_choose:\n elements_to_choose = total_elements - elements_to_choose\n\n coefficient = 1\n for i in range(elements_to_choose):\n coefficient *= total_elements - i\n coefficient \/\/= i + 1\n\n return coefficient\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Carmichael Numbers A number n is said to be a Carmichael number if it satisfies the following modular arithmetic condition: powerb, n1 MOD n 1, for all b ranging from 1 to n such that b and n are relatively prime, i.e, gcdb, n 1 Examples of Carmichael Numbers: 561, 1105, ... https:en.wikipedia.orgwikiCarmichaelnumber Examples: power2, 15, 3 2 power5, 1, 30 5 Examples: iscarmichaelnumber4 False iscarmichaelnumber561 True iscarmichaelnumber562 False iscarmichaelnumber900 False iscarmichaelnumber1105 True iscarmichaelnumber8911 True iscarmichaelnumber5.1 Traceback most recent call last: ... ValueError: Number 5.1 must instead be a positive integer iscarmichaelnumber7 Traceback most recent call last: ... ValueError: Number 7 must instead be a positive integer iscarmichaelnumber0 Traceback most recent call last: ... ValueError: Number 0 must instead be a positive integer","Completions":"from maths.greatest_common_divisor import greatest_common_divisor\n\n\ndef power(x: int, y: int, mod: int) -> int:\n \"\"\"\n Examples:\n >>> power(2, 15, 3)\n 2\n >>> power(5, 1, 30)\n 5\n \"\"\"\n\n if y == 0:\n return 1\n temp = power(x, y \/\/ 2, mod) % mod\n temp = (temp * temp) % mod\n if y % 2 == 1:\n temp = (temp * x) % mod\n return temp\n\n\ndef is_carmichael_number(n: int) -> bool:\n \"\"\"\n Examples:\n >>> is_carmichael_number(4)\n False\n >>> is_carmichael_number(561)\n True\n >>> is_carmichael_number(562)\n False\n >>> is_carmichael_number(900)\n False\n >>> is_carmichael_number(1105)\n True\n >>> is_carmichael_number(8911)\n True\n >>> is_carmichael_number(5.1)\n Traceback (most recent call last):\n ...\n ValueError: Number 5.1 must instead be a positive integer\n\n >>> is_carmichael_number(-7)\n Traceback (most recent call last):\n ...\n ValueError: Number -7 must instead be a positive integer\n\n >>> is_carmichael_number(0)\n Traceback (most recent call last):\n ...\n ValueError: Number 0 must instead be a positive integer\n \"\"\"\n\n if n <= 0 or not isinstance(n, int):\n msg = f\"Number {n} must instead be a positive integer\"\n raise ValueError(msg)\n\n return all(\n power(b, n - 1, n) == 1\n for b in range(2, n)\n if greatest_common_divisor(b, n) == 1\n )\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n\n number = int(input(\"Enter number: \").strip())\n if is_carmichael_number(number):\n print(f\"{number} is a Carmichael Number.\")\n else:\n print(f\"{number} is not a Carmichael Number.\")\n"} +{"Prompt":"Calculate the nth Catalan number Source: https:en.wikipedia.orgwikiCatalannumber :param number: nth catalan number to calculate :return: the nth catalan number Note: A catalan number is only defined for positive integers catalan5 14 catalan0 Traceback most recent call last: ... ValueError: Input value of number0 must be 0 catalan1 Traceback most recent call last: ... ValueError: Input value of number1 must be 0 catalan5.0 Traceback most recent call last: ... TypeError: Input value of number5.0 must be an integer","Completions":"def catalan(number: int) -> int:\n \"\"\"\n :param number: nth catalan number to calculate\n :return: the nth catalan number\n Note: A catalan number is only defined for positive integers\n\n >>> catalan(5)\n 14\n >>> catalan(0)\n Traceback (most recent call last):\n ...\n ValueError: Input value of [number=0] must be > 0\n >>> catalan(-1)\n Traceback (most recent call last):\n ...\n ValueError: Input value of [number=-1] must be > 0\n >>> catalan(5.0)\n Traceback (most recent call last):\n ...\n TypeError: Input value of [number=5.0] must be an integer\n \"\"\"\n\n if not isinstance(number, int):\n msg = f\"Input value of [number={number}] must be an integer\"\n raise TypeError(msg)\n\n if number < 1:\n msg = f\"Input value of [number={number}] must be > 0\"\n raise ValueError(msg)\n\n current_number = 1\n\n for i in range(1, number):\n current_number *= 4 * i - 2\n current_number \/\/= i + 1\n\n return current_number\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"A Hamming number is a positive integer of the form 2i3j5k, for some nonnegative integers i, j, and k. They are often referred to as regular numbers. More info at: https:en.wikipedia.orgwikiRegularnumber. This function creates an ordered list of n length as requested, and afterwards returns the last value of the list. It must be given a positive integer. :param nelement: The number of elements on the list :return: The nth element of the list hamming5 1, 2, 3, 4, 5 hamming10 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 hamming15 1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 18, 20, 24","Completions":"def hamming(n_element: int) -> list:\n \"\"\"\n This function creates an ordered list of n length as requested, and afterwards\n returns the last value of the list. It must be given a positive integer.\n\n :param n_element: The number of elements on the list\n :return: The nth element of the list\n\n >>> hamming(5)\n [1, 2, 3, 4, 5]\n >>> hamming(10)\n [1, 2, 3, 4, 5, 6, 8, 9, 10, 12]\n >>> hamming(15)\n [1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 18, 20, 24]\n \"\"\"\n n_element = int(n_element)\n if n_element < 1:\n my_error = ValueError(\"a should be a positive number\")\n raise my_error\n\n hamming_list = [1]\n i, j, k = (0, 0, 0)\n index = 1\n while index < n_element:\n while hamming_list[i] * 2 <= hamming_list[-1]:\n i += 1\n while hamming_list[j] * 3 <= hamming_list[-1]:\n j += 1\n while hamming_list[k] * 5 <= hamming_list[-1]:\n k += 1\n hamming_list.append(\n min(hamming_list[i] * 2, hamming_list[j] * 3, hamming_list[k] * 5)\n )\n index += 1\n return hamming_list\n\n\nif __name__ == \"__main__\":\n n = input(\"Enter the last number (nth term) of the Hamming Number Series: \")\n print(\"Formula of Hamming Number Series => 2^i * 3^j * 5^k\")\n hamming_numbers = hamming(int(n))\n print(\"-----------------------------------------------------\")\n print(f\"The list with nth numbers is: {hamming_numbers}\")\n print(\"-----------------------------------------------------\")\n"} +{"Prompt":"A happy number is a number which eventually reaches 1 when replaced by the sum of the square of each digit. :param number: The number to check for happiness. :return: True if the number is a happy number, False otherwise. ishappynumber19 True ishappynumber2 False ishappynumber23 True ishappynumber1 True ishappynumber0 Traceback most recent call last: ... ValueError: number0 must be a positive integer ishappynumber19 Traceback most recent call last: ... ValueError: number19 must be a positive integer ishappynumber19.1 Traceback most recent call last: ... ValueError: number19.1 must be a positive integer ishappynumberhappy Traceback most recent call last: ... ValueError: number'happy' must be a positive integer","Completions":"def is_happy_number(number: int) -> bool:\n \"\"\"\n A happy number is a number which eventually reaches 1 when replaced by the sum of\n the square of each digit.\n\n :param number: The number to check for happiness.\n :return: True if the number is a happy number, False otherwise.\n\n >>> is_happy_number(19)\n True\n >>> is_happy_number(2)\n False\n >>> is_happy_number(23)\n True\n >>> is_happy_number(1)\n True\n >>> is_happy_number(0)\n Traceback (most recent call last):\n ...\n ValueError: number=0 must be a positive integer\n >>> is_happy_number(-19)\n Traceback (most recent call last):\n ...\n ValueError: number=-19 must be a positive integer\n >>> is_happy_number(19.1)\n Traceback (most recent call last):\n ...\n ValueError: number=19.1 must be a positive integer\n >>> is_happy_number(\"happy\")\n Traceback (most recent call last):\n ...\n ValueError: number='happy' must be a positive integer\n \"\"\"\n if not isinstance(number, int) or number <= 0:\n msg = f\"{number=} must be a positive integer\"\n raise ValueError(msg)\n\n seen = set()\n while number != 1 and number not in seen:\n seen.add(number)\n number = sum(int(digit) ** 2 for digit in str(number))\n return number == 1\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"A harshad number or more specifically an nharshad number is a number that's divisible by the sum of its digits in some given base n. Reference: https:en.wikipedia.orgwikiHarshadnumber Convert a given positive decimal integer to base 'base'. Where 'base' ranges from 2 to 36. Examples: inttobase23, 2 '10111' inttobase58, 5 '213' inttobase167, 16 'A7' bases below 2 and beyond 36 will error inttobase98, 1 Traceback most recent call last: ... ValueError: 'base' must be between 2 and 36 inclusive inttobase98, 37 Traceback most recent call last: ... ValueError: 'base' must be between 2 and 36 inclusive Calculate the sum of digit values in a positive integer converted to the given 'base'. Where 'base' ranges from 2 to 36. Examples: sumofdigits103, 12 '13' sumofdigits1275, 4 '30' sumofdigits6645, 2 '1001' bases below 2 and beyond 36 will error sumofdigits543, 1 Traceback most recent call last: ... ValueError: 'base' must be between 2 and 36 inclusive sumofdigits543, 37 Traceback most recent call last: ... ValueError: 'base' must be between 2 and 36 inclusive Finds all Harshad numbers smaller than num in base 'base'. Where 'base' ranges from 2 to 36. Examples: harshadnumbersinbase15, 2 '1', '10', '100', '110', '1000', '1010', '1100' harshadnumbersinbase12, 34 '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B' harshadnumbersinbase12, 4 '1', '2', '3', '10', '12', '20', '21' bases below 2 and beyond 36 will error harshadnumbersinbase234, 37 Traceback most recent call last: ... ValueError: 'base' must be between 2 and 36 inclusive harshadnumbersinbase234, 1 Traceback most recent call last: ... ValueError: 'base' must be between 2 and 36 inclusive Determines whether n in base 'base' is a harshad number. Where 'base' ranges from 2 to 36. Examples: isharshadnumberinbase18, 10 True isharshadnumberinbase21, 10 True isharshadnumberinbase21, 5 False bases below 2 and beyond 36 will error isharshadnumberinbase45, 37 Traceback most recent call last: ... ValueError: 'base' must be between 2 and 36 inclusive isharshadnumberinbase45, 1 Traceback most recent call last: ... ValueError: 'base' must be between 2 and 36 inclusive","Completions":"def int_to_base(number: int, base: int) -> str:\n \"\"\"\n Convert a given positive decimal integer to base 'base'.\n Where 'base' ranges from 2 to 36.\n\n Examples:\n >>> int_to_base(23, 2)\n '10111'\n >>> int_to_base(58, 5)\n '213'\n >>> int_to_base(167, 16)\n 'A7'\n >>> # bases below 2 and beyond 36 will error\n >>> int_to_base(98, 1)\n Traceback (most recent call last):\n ...\n ValueError: 'base' must be between 2 and 36 inclusive\n >>> int_to_base(98, 37)\n Traceback (most recent call last):\n ...\n ValueError: 'base' must be between 2 and 36 inclusive\n \"\"\"\n\n if base < 2 or base > 36:\n raise ValueError(\"'base' must be between 2 and 36 inclusive\")\n\n digits = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n result = \"\"\n\n if number < 0:\n raise ValueError(\"number must be a positive integer\")\n\n while number > 0:\n number, remainder = divmod(number, base)\n result = digits[remainder] + result\n\n if result == \"\":\n result = \"0\"\n\n return result\n\n\ndef sum_of_digits(num: int, base: int) -> str:\n \"\"\"\n Calculate the sum of digit values in a positive integer\n converted to the given 'base'.\n Where 'base' ranges from 2 to 36.\n\n Examples:\n >>> sum_of_digits(103, 12)\n '13'\n >>> sum_of_digits(1275, 4)\n '30'\n >>> sum_of_digits(6645, 2)\n '1001'\n >>> # bases below 2 and beyond 36 will error\n >>> sum_of_digits(543, 1)\n Traceback (most recent call last):\n ...\n ValueError: 'base' must be between 2 and 36 inclusive\n >>> sum_of_digits(543, 37)\n Traceback (most recent call last):\n ...\n ValueError: 'base' must be between 2 and 36 inclusive\n \"\"\"\n\n if base < 2 or base > 36:\n raise ValueError(\"'base' must be between 2 and 36 inclusive\")\n\n num_str = int_to_base(num, base)\n res = sum(int(char, base) for char in num_str)\n res_str = int_to_base(res, base)\n return res_str\n\n\ndef harshad_numbers_in_base(limit: int, base: int) -> list[str]:\n \"\"\"\n Finds all Harshad numbers smaller than num in base 'base'.\n Where 'base' ranges from 2 to 36.\n\n Examples:\n >>> harshad_numbers_in_base(15, 2)\n ['1', '10', '100', '110', '1000', '1010', '1100']\n >>> harshad_numbers_in_base(12, 34)\n ['1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B']\n >>> harshad_numbers_in_base(12, 4)\n ['1', '2', '3', '10', '12', '20', '21']\n >>> # bases below 2 and beyond 36 will error\n >>> harshad_numbers_in_base(234, 37)\n Traceback (most recent call last):\n ...\n ValueError: 'base' must be between 2 and 36 inclusive\n >>> harshad_numbers_in_base(234, 1)\n Traceback (most recent call last):\n ...\n ValueError: 'base' must be between 2 and 36 inclusive\n \"\"\"\n\n if base < 2 or base > 36:\n raise ValueError(\"'base' must be between 2 and 36 inclusive\")\n\n if limit < 0:\n return []\n\n numbers = [\n int_to_base(i, base)\n for i in range(1, limit)\n if i % int(sum_of_digits(i, base), base) == 0\n ]\n\n return numbers\n\n\ndef is_harshad_number_in_base(num: int, base: int) -> bool:\n \"\"\"\n Determines whether n in base 'base' is a harshad number.\n Where 'base' ranges from 2 to 36.\n\n Examples:\n >>> is_harshad_number_in_base(18, 10)\n True\n >>> is_harshad_number_in_base(21, 10)\n True\n >>> is_harshad_number_in_base(-21, 5)\n False\n >>> # bases below 2 and beyond 36 will error\n >>> is_harshad_number_in_base(45, 37)\n Traceback (most recent call last):\n ...\n ValueError: 'base' must be between 2 and 36 inclusive\n >>> is_harshad_number_in_base(45, 1)\n Traceback (most recent call last):\n ...\n ValueError: 'base' must be between 2 and 36 inclusive\n \"\"\"\n\n if base < 2 or base > 36:\n raise ValueError(\"'base' must be between 2 and 36 inclusive\")\n\n if num < 0:\n return False\n\n n = int_to_base(num, base)\n d = sum_of_digits(num, base)\n return int(n, base) % int(d, base) == 0\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Hexagonal Number The nth hexagonal number hn is the number of distinct dots in a pattern of dots consisting of the outlines of regular hexagons with sides up to n dots, when the hexagons are overlaid so that they share one vertex. https:en.wikipedia.orgwikiHexagonalnumber Author : Akshay Dubey https:github.comitsAkshayDubey :param number: nth hexagonal number to calculate :return: the nth hexagonal number Note: A hexagonal number is only defined for positive integers hexagonal4 28 hexagonal11 231 hexagonal22 946 hexagonal0 Traceback most recent call last: ... ValueError: Input must be a positive integer hexagonal1 Traceback most recent call last: ... ValueError: Input must be a positive integer hexagonal11.0 Traceback most recent call last: ... TypeError: Input value of number11.0 must be an integer","Completions":"# Author : Akshay Dubey (https:\/\/github.com\/itsAkshayDubey)\n\n\ndef hexagonal(number: int) -> int:\n \"\"\"\n :param number: nth hexagonal number to calculate\n :return: the nth hexagonal number\n Note: A hexagonal number is only defined for positive integers\n >>> hexagonal(4)\n 28\n >>> hexagonal(11)\n 231\n >>> hexagonal(22)\n 946\n >>> hexagonal(0)\n Traceback (most recent call last):\n ...\n ValueError: Input must be a positive integer\n >>> hexagonal(-1)\n Traceback (most recent call last):\n ...\n ValueError: Input must be a positive integer\n >>> hexagonal(11.0)\n Traceback (most recent call last):\n ...\n TypeError: Input value of [number=11.0] must be an integer\n \"\"\"\n if not isinstance(number, int):\n msg = f\"Input value of [number={number}] must be an integer\"\n raise TypeError(msg)\n if number < 1:\n raise ValueError(\"Input must be a positive integer\")\n return number * (2 * number - 1)\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Krishnamurthy Number It is also known as Peterson Number A Krishnamurthy Number is a number whose sum of the factorial of the digits equals to the original number itself. For example: 145 1! 4! 5! So, 145 is a Krishnamurthy Number factorial3 6 factorial0 1 factorial5 120 krishnamurthy145 True krishnamurthy240 False krishnamurthy1 True","Completions":"def factorial(digit: int) -> int:\n \"\"\"\n >>> factorial(3)\n 6\n >>> factorial(0)\n 1\n >>> factorial(5)\n 120\n \"\"\"\n\n return 1 if digit in (0, 1) else (digit * factorial(digit - 1))\n\n\ndef krishnamurthy(number: int) -> bool:\n \"\"\"\n >>> krishnamurthy(145)\n True\n >>> krishnamurthy(240)\n False\n >>> krishnamurthy(1)\n True\n \"\"\"\n\n fact_sum = 0\n duplicate = number\n while duplicate > 0:\n duplicate, digit = divmod(duplicate, 10)\n fact_sum += factorial(digit)\n return fact_sum == number\n\n\nif __name__ == \"__main__\":\n print(\"Program to check whether a number is a Krisnamurthy Number or not.\")\n number = int(input(\"Enter number: \").strip())\n print(\n f\"{number} is {'' if krishnamurthy(number) else 'not '}a Krishnamurthy Number.\"\n )\n"} +{"Prompt":"Perfect Number In number theory, a perfect number is a positive integer that is equal to the sum of its positive divisors, excluding the number itself. For example: 6 divisors1, 2, 3, 6 Excluding 6, the sumdivisors is 1 2 3 6 So, 6 is a Perfect Number Other examples of Perfect Numbers: 28, 486, ... https:en.wikipedia.orgwikiPerfectnumber Check if a number is a perfect number. A perfect number is a positive integer that is equal to the sum of its proper divisors excluding itself. Args: number: The number to be checked. Returns: True if the number is a perfect number, False otherwise. Start from 1 because dividing by 0 will raise ZeroDivisionError. A number at most can be divisible by the half of the number except the number itself. For example, 6 is at most can be divisible by 3 except by 6 itself. Examples: perfect27 False perfect28 True perfect29 False perfect6 True perfect12 False perfect496 True perfect8128 True perfect0 False perfect1 False perfect12.34 Traceback most recent call last: ... ValueError: number must be an integer perfectHello Traceback most recent call last: ... ValueError: number must be an integer","Completions":"def perfect(number: int) -> bool:\n \"\"\"\n Check if a number is a perfect number.\n\n A perfect number is a positive integer that is equal to the sum of its proper\n divisors (excluding itself).\n\n Args:\n number: The number to be checked.\n\n Returns:\n True if the number is a perfect number, False otherwise.\n\n Start from 1 because dividing by 0 will raise ZeroDivisionError.\n A number at most can be divisible by the half of the number except the number\n itself. For example, 6 is at most can be divisible by 3 except by 6 itself.\n\n Examples:\n >>> perfect(27)\n False\n >>> perfect(28)\n True\n >>> perfect(29)\n False\n >>> perfect(6)\n True\n >>> perfect(12)\n False\n >>> perfect(496)\n True\n >>> perfect(8128)\n True\n >>> perfect(0)\n False\n >>> perfect(-1)\n False\n >>> perfect(12.34)\n Traceback (most recent call last):\n ...\n ValueError: number must be an integer\n >>> perfect(\"Hello\")\n Traceback (most recent call last):\n ...\n ValueError: number must be an integer\n \"\"\"\n if not isinstance(number, int):\n raise ValueError(\"number must be an integer\")\n if number <= 0:\n return False\n return sum(i for i in range(1, number \/\/ 2 + 1) if number % i == 0) == number\n\n\nif __name__ == \"__main__\":\n from doctest import testmod\n\n testmod()\n print(\"Program to check whether a number is a Perfect number or not...\")\n try:\n number = int(input(\"Enter a positive integer: \").strip())\n except ValueError:\n msg = \"number must be an integer\"\n print(msg)\n raise ValueError(msg)\n\n print(f\"{number} is {'' if perfect(number) else 'not '}a Perfect Number.\")\n"} +{"Prompt":"Returns the numth sidesgonal number. It is assumed that num 0 and sides 3 see for reference https:en.wikipedia.orgwikiPolygonalnumber. polygonalnum0, 3 0 polygonalnum3, 3 6 polygonalnum5, 4 25 polygonalnum2, 5 5 polygonalnum1, 0 Traceback most recent call last: ... ValueError: Invalid input: num must be 0 and sides must be 3. polygonalnum0, 2 Traceback most recent call last: ... ValueError: Invalid input: num must be 0 and sides must be 3.","Completions":"def polygonal_num(num: int, sides: int) -> int:\n \"\"\"\n Returns the `num`th `sides`-gonal number. It is assumed that `num` >= 0 and\n `sides` >= 3 (see for reference https:\/\/en.wikipedia.org\/wiki\/Polygonal_number).\n\n >>> polygonal_num(0, 3)\n 0\n >>> polygonal_num(3, 3)\n 6\n >>> polygonal_num(5, 4)\n 25\n >>> polygonal_num(2, 5)\n 5\n >>> polygonal_num(-1, 0)\n Traceback (most recent call last):\n ...\n ValueError: Invalid input: num must be >= 0 and sides must be >= 3.\n >>> polygonal_num(0, 2)\n Traceback (most recent call last):\n ...\n ValueError: Invalid input: num must be >= 0 and sides must be >= 3.\n \"\"\"\n if num < 0 or sides < 3:\n raise ValueError(\"Invalid input: num must be >= 0 and sides must be >= 3.\")\n\n return ((sides - 2) * num**2 - (sides - 4) * num) \/\/ 2\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Pronic Number A number n is said to be a Proic number if there exists an integer m such that n m m 1 Examples of Proic Numbers: 0, 2, 6, 12, 20, 30, 42, 56, 72, 90, 110 ... https:en.wikipedia.orgwikiPronicnumber Author : Akshay Dubey https:github.comitsAkshayDubey doctest: NORMALIZEWHITESPACE This functions takes an integer number as input. returns True if the number is pronic. ispronic1 False ispronic0 True ispronic2 True ispronic5 False ispronic6 True ispronic8 False ispronic30 True ispronic32 False ispronic2147441940 True ispronic9223372033963249500 True ispronic6.0 Traceback most recent call last: ... TypeError: Input value of number6.0 must be an integer","Completions":"# Author : Akshay Dubey (https:\/\/github.com\/itsAkshayDubey)\n\n\ndef is_pronic(number: int) -> bool:\n \"\"\"\n # doctest: +NORMALIZE_WHITESPACE\n This functions takes an integer number as input.\n returns True if the number is pronic.\n >>> is_pronic(-1)\n False\n >>> is_pronic(0)\n True\n >>> is_pronic(2)\n True\n >>> is_pronic(5)\n False\n >>> is_pronic(6)\n True\n >>> is_pronic(8)\n False\n >>> is_pronic(30)\n True\n >>> is_pronic(32)\n False\n >>> is_pronic(2147441940)\n True\n >>> is_pronic(9223372033963249500)\n True\n >>> is_pronic(6.0)\n Traceback (most recent call last):\n ...\n TypeError: Input value of [number=6.0] must be an integer\n \"\"\"\n if not isinstance(number, int):\n msg = f\"Input value of [number={number}] must be an integer\"\n raise TypeError(msg)\n if number < 0 or number % 2 == 1:\n return False\n number_sqrt = int(number**0.5)\n return number == number_sqrt * (number_sqrt + 1)\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} +{"Prompt":"Calculate the nth Proth number Source: https:handwiki.orgwikiProthnumber :param number: nth number to calculate in the sequence :return: the nth number in Proth number Note: indexing starts at 1 i.e. proth1 gives the first Proth number of 3 proth6 25 proth0 Traceback most recent call last: ... ValueError: Input value of number0 must be 0 proth1 Traceback most recent call last: ... ValueError: Input value of number1 must be 0 proth6.0 Traceback most recent call last: ... TypeError: Input value of number6.0 must be an integer 1 for binary starting at 0 i.e. 20, 21, etc. 1 to start the sequence at the 3rd Proth number Hence, we have a 2 in the below statement","Completions":"import math\n\n\ndef proth(number: int) -> int:\n \"\"\"\n :param number: nth number to calculate in the sequence\n :return: the nth number in Proth number\n Note: indexing starts at 1 i.e. proth(1) gives the first Proth number of 3\n >>> proth(6)\n 25\n >>> proth(0)\n Traceback (most recent call last):\n ...\n ValueError: Input value of [number=0] must be > 0\n >>> proth(-1)\n Traceback (most recent call last):\n ...\n ValueError: Input value of [number=-1] must be > 0\n >>> proth(6.0)\n Traceback (most recent call last):\n ...\n TypeError: Input value of [number=6.0] must be an integer\n \"\"\"\n\n if not isinstance(number, int):\n msg = f\"Input value of [number={number}] must be an integer\"\n raise TypeError(msg)\n\n if number < 1:\n msg = f\"Input value of [number={number}] must be > 0\"\n raise ValueError(msg)\n elif number == 1:\n return 3\n elif number == 2:\n return 5\n else:\n \"\"\"\n +1 for binary starting at 0 i.e. 2^0, 2^1, etc.\n +1 to start the sequence at the 3rd Proth number\n Hence, we have a +2 in the below statement\n \"\"\"\n block_index = int(math.log(number \/\/ 3, 2)) + 2\n\n proth_list = [3, 5]\n proth_index = 2\n increment = 3\n for block in range(1, block_index):\n for _ in range(increment):\n proth_list.append(2 ** (block + 1) + proth_list[proth_index - 1])\n proth_index += 1\n increment *= 2\n\n return proth_list[number - 1]\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n\n for number in range(11):\n value = 0\n try:\n value = proth(number)\n except ValueError:\n print(f\"ValueError: there is no {number}th Proth number\")\n continue\n\n print(f\"The {number}th Proth number: {value}\")\n"}