RachitD15673 commited on
Commit
1271f77
·
1 Parent(s): 72c0702

Upload final.jsonl

Browse files
Files changed (1) hide show
  1. final.jsonl +50 -0
final.jsonl ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {"Intruction":"This is a question asked by a user","Context":"The stock span problem is a financial problem where we have a series of n daily\nprice quotes for a stock and we need to calculate span of stock's price for all n days.\n\nThe span Si of the stock's price on a given day i is defined as the maximum\nnumber of consecutive days just before the given day, for which the price of the stock\non the current day is less than or equal to its price on the given day.","response":"def calculation_span(price, s):\n n = len(price)\n st = []\n st.append(0)\n s[0] = 1\n for i in range(1, n):\n while len(st) > 0 and price[st[0]] <= price[i]:\n st.pop()\n s[i] = i + 1 if len(st) <= 0 else i - st[0]\n st.append(i)\n\n\ndef print_array(arr, n):\n for i in range(n):\n print(arr[i], end=' ')\n\n\nprice = [10, 4, 5, 90, 120, 80]\nS = [(0) for i in range(len(price) + 1)]\ncalculation_span(price, S)\nprint_array(S, len(price))"}
2
+ {"Intruction":"This is a question asked by a user","Context":"Generate code for middle_element_of_linked_list","response":"from __future__ import annotations\n\n\nclass Node:\n\n def __init__(self, data: int) ->None:\n self.data = data\n self.next = None\n\n\nclass LinkedList:\n\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 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"}
3
+ {"Intruction":"This is a question asked by a user","Context":"Task:\nGiven a positive int number. Return True if this number is power of 4\nor False otherwise.\n\nImplementation notes: Use bit manipulation.\nFor example if the number is the power of 2 it's bits representation:\nn = 0..100..00\nn - 1 = 0..011..11\n\nn & (n - 1) - no intersections = 0\nIf the number is a power of 4 then it should be a power of 2\nand the set bit should be at an odd position.","response":"def power_of_4(number: int) ->bool:\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 doctest.testmod()"}
4
+ {"Intruction":"This is a question asked by a user","Context":"Author: Alexander Joslin\nGitHub: github.com/echoaj\n\nExplanation: https://medium.com/@haleesammar/implemented-in-js-dijkstras-2-stack-\n algorithm-for-evaluating-mathematical-expressions-fc0837dae1ea\n\nWe can use Dijkstra's two stack algorithm to solve an equation\nsuch as: (5 + ((4 * 2) * (2 + 3)))\n\nTHESE ARE THE ALGORITHM'S RULES:\nRULE 1: Scan the expression from left to right. When an operand is encountered,\n push it onto the operand stack.\n\nRULE 2: When an operator is encountered in the expression,\n push it onto the operator stack.\n\nRULE 3: When a left parenthesis is encountered in the expression, ignore it.\n\nRULE 4: When a right parenthesis is encountered in the expression,\n pop an operator off the operator stack. The two operands it must\n operate on must be the last two operands pushed onto the operand stack.\n We therefore pop the operand stack twice, perform the operation,\n and push the result back onto the operand stack so it will be available\n for use as an operand of the next operator popped off the operator stack.\n\nRULE 5: When the entire infix expression has been scanned, the value left on\n the operand stack represents the value of the expression.\n\nNOTE: It only works with whole numbers.","response":"__author__ = 'Alexander Joslin'\nimport operator as op\nfrom .stack import Stack\n\n\ndef dijkstras_two_stack_algorithm(equation: str) ->int:\n operators = {'*': op.mul, '/': op.truediv, '+': op.add, '-': op.sub}\n operand_stack: Stack[int] = Stack()\n operator_stack: Stack[str] = Stack()\n for i in equation:\n if i.isdigit():\n operand_stack.push(int(i))\n elif i in operators:\n operator_stack.push(i)\n elif i == ')':\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 total = operators[opr](num2, num1)\n operand_stack.push(total)\n return operand_stack.peek()\n\n\nif __name__ == '__main__':\n equation = '(5 + ((4 * 2) * (2 + 3)))'\n print(f'{equation} = {dijkstras_two_stack_algorithm(equation)}')"}
5
+ {"Intruction":"This is a question asked by a user","Context":"Generate code for base16","response":"def base16_encode(data: bytes) ->str:\n return ''.join([hex(byte)[2:].zfill(2).upper() for byte in list(data)])\n\n\ndef base16_decode(data: str) ->bytes:\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 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 return bytes(int(data[i] + data[i + 1], 16) for i in range(0, len(data), 2)\n )\n\n\nif __name__ == '__main__':\n import doctest\n doctest.testmod()"}
6
+ {"Intruction":"This is a question asked by a user","Context":"Python3 program to evaluate a prefix expression.","response":"calc = {'+': lambda x, y: x + y, '-': lambda x, y: x - y, '*': lambda x, y:\n x * y, '/': lambda x, y: x / y}\n\n\ndef is_operand(c):\n return c.isdigit()\n\n\ndef evaluate(expression):\n stack = []\n for c in expression.split()[::-1]:\n if is_operand(c):\n stack.append(int(c))\n else:\n o1 = stack.pop()\n o2 = stack.pop()\n stack.append(calc[c](o1, o2))\n return stack.pop()\n\n\nif __name__ == '__main__':\n test_expression = '+ 9 * 2 6'\n print(evaluate(test_expression))\n test_expression = '/ * 10 2 + 4 1 '\n print(evaluate(test_expression))"}
7
+ {"Intruction":"This is a question asked by a user","Context":"A XOR Gate is a logic gate in boolean algebra which results to 1 (True) if only one of\nthe two inputs is 1, and 0 (False) if an even number of inputs are 1.\nFollowing is the truth table of a XOR Gate:\n ------------------------------\n | Input 1 | Input 2 | Output |\n ------------------------------\n | 0 | 0 | 0 |\n | 0 | 1 | 1 |\n | 1 | 0 | 1 |\n | 1 | 1 | 0 |\n ------------------------------\n\nRefer - https://www.geeksforgeeks.org/logic-gates-in-python/","response":"def xor_gate(input_1: int, input_2: int) ->int:\n return (input_1, input_2).count(0) % 2\n\n\nif __name__ == '__main__':\n import doctest\n doctest.testmod()"}
8
+ {"Intruction":"This is a question asked by a user","Context":"Author : Alexander Pantyukhin\nDate : November 30, 2022\n\nTask:\nGiven two int numbers. Return True these numbers have opposite signs\nor False otherwise.\n\nImplementation notes: Use bit manipulation.\nUse XOR for two numbers.","response":"def different_signs(num1: int, num2: int) ->bool:\n return num1 ^ num2 < 0\n\n\nif __name__ == '__main__':\n import doctest\n doctest.testmod()"}
9
+ {"Intruction":"This is a question asked by a user","Context":"A XNOR Gate is a logic gate in boolean algebra which results to 0 (False) if both the\ninputs are different, and 1 (True), if the inputs are same.\nIt's similar to adding a NOT gate to an XOR gate\n\nFollowing is the truth table of a XNOR Gate:\n ------------------------------\n | Input 1 | Input 2 | Output |\n ------------------------------\n | 0 | 0 | 1 |\n | 0 | 1 | 0 |\n | 1 | 0 | 0 |\n | 1 | 1 | 1 |\n ------------------------------\nRefer - https://www.geeksforgeeks.org/logic-gates-in-python/","response":"def xnor_gate(input_1: int, input_2: int) ->int:\n return 1 if input_1 == input_2 else 0\n\n\nif __name__ == '__main__':\n import doctest\n doctest.testmod()"}
10
+ {"Intruction":"This is a question asked by a user","Context":"Generate code for find_triplets_with_0_sum","response":"from itertools import combinations\n\n\ndef find_triplets_with_0_sum(nums: list[int]) ->list[list[int]]:\n return [list(x) for x in sorted({abc for abc in combinations(sorted(\n nums), 3) if not sum(abc)})]"}
11
+ {"Intruction":"This is a question asked by a user","Context":"Generate code for reverse_bits","response":"def get_reverse_bit_string(number: int) ->str:\n if not isinstance(number, int):\n msg = (\n f'operation can not be conducted on a object of type {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 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(\n \"'<' not supported between instances of 'str' and 'int'\")\n result = 0\n for _ in range(1, 33):\n result = result << 1\n end_bit = number % 2\n number = number >> 1\n result = result | end_bit\n return get_reverse_bit_string(result)\n\n\nif __name__ == '__main__':\n import doctest\n doctest.testmod()"}
12
+ {"Intruction":"This is a question asked by a user","Context":"Generate code for brute_force_caesar_cipher","response":"import string\n\n\ndef decrypt(message: str) ->None:\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 doctest.testmod()\n main()"}
13
+ {"Intruction":"This is a question asked by a user","Context":"A Hamiltonian cycle (Hamiltonian circuit) is a graph cycle\nthrough a graph that visits each node exactly once.\nDetermining whether such paths and cycles exist in graphs\nis the 'Hamiltonian path problem', which is NP-complete.\n\nWikipedia: https://en.wikipedia.org/wiki/Hamiltonian_path","response":"def valid_connection(graph: list[list[int]], next_ver: int, curr_ind: int,\n path: list[int]) ->bool:\n if graph[path[curr_ind - 1]][next_ver] == 0:\n return False\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\n ) ->bool:\n if curr_ind == len(graph):\n return graph[path[curr_ind - 1]][path[0]] == 1\n for next_ver in range(len(graph)):\n if valid_connection(graph, next_ver, curr_ind, path):\n path[curr_ind] = next_ver\n if util_hamilton_cycle(graph, path, curr_ind + 1):\n return True\n path[curr_ind] = -1\n return False\n\n\ndef hamilton_cycle(graph: list[list[int]], start_index: int=0) ->list[int]:\n path = [-1] * (len(graph) + 1)\n path[0] = path[-1] = start_index\n return path if util_hamilton_cycle(graph, path, 1) else []"}
14
+ {"Intruction":"This is a question asked by a user","Context":"Generate code for binary_count_trailing_zeros","response":"from math import log2\n\n\ndef binary_count_trailing_zeros(a: int) ->int:\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 doctest.testmod()"}
15
+ {"Intruction":"This is a question asked by a user","Context":"Generate code for gray_code_sequence","response":"def gray_code(bit_count: int) ->list:\n if bit_count < 0:\n raise ValueError('The given input must be positive')\n sequence = gray_code_sequence_string(bit_count)\n for i in range(len(sequence)):\n sequence[i] = int(sequence[i], 2)\n return sequence\n\n\ndef gray_code_sequence_string(bit_count: int) ->list:\n if bit_count == 0:\n return ['0']\n if bit_count == 1:\n return ['0', '1']\n seq_len = 1 << bit_count\n smaller_sequence = gray_code_sequence_string(bit_count - 1)\n sequence = []\n for i in range(seq_len // 2):\n generated_no = '0' + smaller_sequence[i]\n sequence.append(generated_no)\n for i in reversed(range(seq_len // 2)):\n generated_no = '1' + smaller_sequence[i]\n sequence.append(generated_no)\n return sequence\n\n\nif __name__ == '__main__':\n import doctest\n doctest.testmod()"}
16
+ {"Intruction":"This is a question asked by a user","Context":"An AND Gate is a logic gate in boolean algebra which results to 1 (True) if both the\ninputs are 1, and 0 (False) otherwise.\n\nFollowing is the truth table of an AND Gate:\n ------------------------------\n | Input 1 | Input 2 | Output |\n ------------------------------\n | 0 | 0 | 0 |\n | 0 | 1 | 0 |\n | 1 | 0 | 0 |\n | 1 | 1 | 1 |\n ------------------------------\n\nRefer - https://www.geeksforgeeks.org/logic-gates-in-python/","response":"def and_gate(input_1: int, input_2: int) ->int:\n return int(input_1 and input_2)\n\n\nif __name__ == '__main__':\n import doctest\n doctest.testmod()"}
17
+ {"Intruction":"This is a question asked by a user","Context":"Generate code for index_of_rightmost_set_bit","response":"def get_index_of_rightmost_set_bit(number: int) ->int:\n if not isinstance(number, int) or number < 0:\n raise ValueError('Input must be a non-negative integer')\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 doctest.testmod(verbose=True)"}
18
+ {"Intruction":"This is a question asked by a user","Context":"Generate code for binary_count_setbits","response":"def binary_count_setbits(a: int) ->int:\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 doctest.testmod()"}
19
+ {"Intruction":"This is a question asked by a user","Context":"In this problem, we want to determine all possible subsequences\nof the given sequence. We use backtracking to solve this problem.\n\nTime complexity: O(2^n),\nwhere n denotes the length of the given sequence.","response":"from __future__ import annotations\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(sequence: list[Any], current_subsequence: list[\n Any], index: int) ->None:\n if index == len(sequence):\n print(current_subsequence)\n return\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 seq.clear()\n seq.extend(['A', 'B', 'C'])\n generate_all_subsequences(seq)"}
20
+ {"Intruction":"This is a question asked by a user","Context":"Calculates the sum of two non-negative integers using bitwise operators\nWikipedia explanation: https://en.wikipedia.org/wiki/Binary_number","response":"def bitwise_addition_recursive(number: int, other_number: int) ->int:\n if not isinstance(number, int) or not isinstance(other_number, int):\n raise TypeError('Both arguments MUST be integers!')\n if number < 0 or other_number < 0:\n raise ValueError('Both arguments MUST be non-negative!')\n bitwise_sum = number ^ other_number\n carry = number & other_number\n if carry == 0:\n return bitwise_sum\n return bitwise_addition_recursive(bitwise_sum, carry << 1)\n\n\nif __name__ == '__main__':\n import doctest\n doctest.testmod()"}
21
+ {"Intruction":"This is a question asked by a user","Context":"Calculate the Product Sum from a Special Array.\nreference: https://dev.to/sfrasica/algorithms-product-sum-from-an-array-dc6\n\nPython doctests can be run with the following command:\npython -m doctest -v product_sum.py\n\nCalculate the product sum of a \"special\" array which can contain integers or nested\narrays. The product sum is obtained by adding all elements and multiplying by their\nrespective depths.\n\nFor example, in the array [x, y], the product sum is (x + y). In the array [x, [y, z]],\nthe product sum is x + 2 * (y + z). In the array [x, [y, [z]]],\nthe product sum is x + 2 * (y + 3z).\n\nExample Input:\n[5, 2, [-7, 1], 3, [6, [-13, 8], 4]]\nOutput: 12","response":"def product_sum(arr: list[int | list], depth: int) ->int:\n total_sum = 0\n for ele in arr:\n total_sum += product_sum(ele, depth + 1) if isinstance(ele, list\n ) else ele\n return total_sum * depth\n\n\ndef product_sum_array(array: list[int | list]) ->int:\n return product_sum(array, 1)\n\n\nif __name__ == '__main__':\n import doctest\n doctest.testmod()"}
22
+ {"Intruction":"This is a question asked by a user","Context":"Generate code for intersection","response":"import math\nfrom collections.abc import Callable\n\n\ndef intersection(function: Callable[[float], float], x0: float, x1: float\n ) ->float:\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(\n 'float division by zero, could not find root')\n x_n2: float = x_n1 - function(x_n1) / ((function(x_n1) - function(\n x_n)) / (x_n1 - x_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))"}
23
+ {"Intruction":"This is a question asked by a user","Context":"Convert a Decimal Number to an Octal Number.","response":"import math\n\n\ndef decimal_to_octal(num: int) ->str:\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)\n return f'0o{int(octal)}'\n\n\ndef main() ->None:\n print('\\n2 in octal is:')\n print(decimal_to_octal(2))\n print('\\n8 in octal is:')\n print(decimal_to_octal(8))\n print('\\n65 in octal is:')\n print(decimal_to_octal(65))\n print('\\n216 in octal is:')\n print(decimal_to_octal(216))\n print('\\n512 in octal is:')\n print(decimal_to_octal(512))\n print('\\n')\n\n\nif __name__ == '__main__':\n main()"}
24
+ {"Intruction":"This is a question asked by a user","Context":"Convert a string of characters to a sequence of numbers\ncorresponding to the character's position in the alphabet.\n\nhttps://www.dcode.fr/letter-number-cipher\nhttp://bestcodes.weebly.com/a1z26.html","response":"from __future__ import annotations\n\n\ndef encode(plain: str) ->list[int]:\n return [(ord(elem) - 96) for elem in plain]\n\n\ndef decode(encoded: list[int]) ->str:\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()"}
25
+ {"Intruction":"This is a question asked by a user","Context":"Generate code for onepad_cipher","response":"import random\n\n\nclass Onepad:\n\n @staticmethod\n def encrypt(text: str) ->tuple[list[int], list[int]]:\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 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))"}
26
+ {"Intruction":"This is a question asked by a user","Context":"Generate code for binary_and_operator","response":"def binary_and(a: int, b: int) ->str:\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:]\n b_binary = str(bin(b))[2:]\n max_len = max(len(a_binary), len(b_binary))\n return '0b' + ''.join(str(int(char_a == '1' and char_b == '1')) for \n 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 doctest.testmod()"}
27
+ {"Intruction":"This is a question asked by a user","Context":"Author : Naman Sharma\nDate : October 2, 2023\n\nTask:\nTo Find the largest power of 2 less than or equal to a given number.\n\nImplementation notes: Use bit manipulation.\nWe start from 1 & left shift the set bit to check if (res<<1)<=number.\nEach left bit shift represents a pow of 2.\n\nFor example:\nnumber: 15\nres: 1 0b1\n 2 0b10\n 4 0b100\n 8 0b1000\n 16 0b10000 (Exit)","response":"def largest_pow_of_two_le_num(number: int) ->int:\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 doctest.testmod()"}
28
+ {"Intruction":"This is a question asked by a user","Context":"Generate code for hash_table_with_linked_list","response":"from collections import deque\nfrom .hash_table import HashTable\n\n\nclass HashTableWithLinkedList(HashTable):\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n def _set_value(self, key, data):\n self.values[key] = deque([]) if self.values[key\n ] is None else self.values[key]\n self.values[key].appendleft(data)\n self._keys[key] = self.values[key]\n\n def balanced_factor(self):\n return sum(self.charge_factor - len(slot) for slot in self.values\n ) / self.size_table * self.charge_factor\n\n def _collision_resolution(self, key, data=None):\n if not (len(self.values[key]) == self.charge_factor and self.values\n .count(None) == 0):\n return key\n return super()._collision_resolution(key, data)"}
29
+ {"Intruction":"This is a question asked by a user","Context":"A NOT Gate is a logic gate in boolean algebra which results to 0 (False) if the\ninput is high, and 1 (True) if the input is low.\nFollowing is the truth table of a XOR Gate:\n ------------------------------\n | Input | Output |\n ------------------------------\n | 0 | 1 |\n | 1 | 0 |\n ------------------------------\nRefer - https://www.geeksforgeeks.org/logic-gates-in-python/","response":"def not_gate(input_1: int) ->int:\n return 1 if input_1 == 0 else 0\n\n\nif __name__ == '__main__':\n import doctest\n doctest.testmod()"}
30
+ {"Intruction":"This is a question asked by a user","Context":"Generate code for missing_number","response":"def find_missing_number(nums: list[int]) ->int:\n low = min(nums)\n high = max(nums)\n missing_number = high\n for i in range(low, high):\n missing_number ^= i ^ nums[i - low]\n return missing_number\n"}
31
+ {"Intruction":"This is a question asked by a user","Context":"Lower–upper (LU) decomposition factors a matrix as a product of a lower\ntriangular matrix and an upper triangular matrix. A square matrix has an LU\ndecomposition under the following conditions:\n - If the matrix is invertible, then it has an LU decomposition if and only\n if all of its leading principal minors are non-zero (see\n https://en.wikipedia.org/wiki/Minor_(linear_algebra) for an explanation of\n leading principal minors of a matrix).\n - If the matrix is singular (i.e., not invertible) and it has a rank of k\n (i.e., it has k linearly independent columns), then it has an LU\n decomposition if its first k leading principal minors are non-zero.\n\nThis algorithm will simply attempt to perform LU decomposition on any square\nmatrix and raise an error if no such decomposition exists.\n\nReference: https://en.wikipedia.org/wiki/LU_decomposition","response":"from __future__ import annotations\nimport numpy as np\n\n\ndef lower_upper_decomposition(table: np.ndarray) ->tuple[np.ndarray, np.ndarray\n ]:\n rows, columns = np.shape(table)\n if rows != columns:\n msg = (\n f\"'table' has to be of square shaped array but got a {rows}x{columns} array:\\n{table}\"\n )\n raise ValueError(msg)\n lower = np.zeros((rows, columns))\n upper = np.zeros((rows, columns))\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 doctest.testmod()"}
32
+ {"Intruction":"This is a question asked by a user","Context":"Provide the functionality to manipulate a single bit.","response":"def set_bit(number: int, position: int) ->int:\n return number | 1 << position\n\n\ndef clear_bit(number: int, position: int) ->int:\n return number & ~(1 << position)\n\n\ndef flip_bit(number: int, position: int) ->int:\n return number ^ 1 << position\n\n\ndef is_bit_set(number: int, position: int) ->bool:\n return number >> position & 1 == 1\n\n\ndef get_bit(number: int, position: int) ->int:\n return int(number & 1 << position != 0)\n\n\nif __name__ == '__main__':\n import doctest\n doctest.testmod()"}
33
+ {"Intruction":"This is a question asked by a user","Context":"Generate code for count_1s_brian_kernighan_method","response":"def get_1s_count(number: int) ->int:\n if not isinstance(number, int) or number < 0:\n raise ValueError('Input must be a non-negative integer')\n count = 0\n while number:\n number &= number - 1\n count += 1\n return count\n\n\nif __name__ == '__main__':\n import doctest\n doctest.testmod()"}
34
+ {"Intruction":"This is a question asked by a user","Context":"Generate code for is_even","response":"def is_even(number: int) ->bool:\n return number & 1 == 0\n\n\nif __name__ == '__main__':\n import doctest\n doctest.testmod()"}
35
+ {"Intruction":"This is a question asked by a user","Context":"Generate code for mean_threshold","response":"from PIL import Image\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 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 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')"}
36
+ {"Intruction":"This is a question asked by a user","Context":"An NIMPLY Gate is a logic gate in boolean algebra which results to 0 if\neither input 1 is 0, or if input 1 is 1, then it is 0 only if input 2 is 1.\nIt is false if input 1 implies input 2. It is the negated form of imply\n\nFollowing is the truth table of an NIMPLY Gate:\n ------------------------------\n | Input 1 | Input 2 | Output |\n ------------------------------\n | 0 | 0 | 0 |\n | 0 | 1 | 0 |\n | 1 | 0 | 1 |\n | 1 | 1 | 0 |\n ------------------------------\n\nRefer - https://en.wikipedia.org/wiki/NIMPLY_gate","response":"def nimply_gate(input_1: int, input_2: int) ->int:\n return int(input_1 == 1 and input_2 == 0)\n\n\nif __name__ == '__main__':\n import doctest\n doctest.testmod()"}
37
+ {"Intruction":"This is a question asked by a user","Context":"Newton's Method.","response":"from collections.abc import Callable\nRealFunc = Callable[[float], float]\n\n\ndef newton(function: RealFunc, derivative: RealFunc, starting_int: int\n ) ->float:\n prev_guess = float(starting_int)\n while True:\n try:\n next_guess = prev_guess - function(prev_guess) / derivative(\n prev_guess)\n except ZeroDivisionError:\n raise ZeroDivisionError('Could not find root') from None\n if abs(prev_guess - next_guess) < 10 ** -5:\n return next_guess\n prev_guess = next_guess\n\n\ndef f(x: float) ->float:\n return x ** 3 - 2 * x - 5\n\n\ndef f1(x: float) ->float:\n return 3 * x ** 2 - 2\n\n\nif __name__ == '__main__':\n print(newton(f, f1, 3))"}
38
+ {"Intruction":"This is a question asked by a user","Context":"Queue implementation using two stacks","response":"from collections.abc import Iterable\nfrom typing import Generic, TypeVar\n_T = TypeVar('_T')\n\n\nclass QueueByTwoStacks(Generic[_T]):\n\n def __init__(self, iterable: (Iterable[_T] | None)=None) ->None:\n self._stack1: list[_T] = list(iterable or [])\n self._stack2: list[_T] = []\n\n def __len__(self) ->int:\n return len(self._stack1) + len(self._stack2)\n\n def __repr__(self) ->str:\n return f'Queue({tuple(self._stack2[::-1] + self._stack1)})'\n\n def put(self, item: _T) ->None:\n self._stack1.append(item)\n\n def get(self) ->_T:\n stack1_pop = self._stack1.pop\n stack2_append = self._stack2.append\n if not self._stack2:\n while self._stack1:\n stack2_append(stack1_pop())\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 testmod()"}
39
+ {"Intruction":"This is a question asked by a user","Context":"Generate code for quadratic_probing","response":"from .hash_table import HashTable\n\n\nclass QuadraticProbing(HashTable):\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n def _collision_resolution(self, key, data=None):\n i = 1\n new_key = self.hash_function(key + i * i)\n while self.values[new_key] is not None and self.values[new_key] != key:\n i += 1\n new_key = self.hash_function(key + i * i\n ) if not self.balanced_factor() >= self.lim_charge else None\n if new_key is None:\n break\n return new_key"}
40
+ {"Intruction":"This is a question asked by a user","Context":"https://www.enjoyalgorithms.com/blog/median-of-two-sorted-arrays","response":"def find_median_sorted_arrays(nums1: list[int], nums2: list[int]) ->float:\n if not nums1 and not nums2:\n raise ValueError('Both input arrays are empty.')\n merged = sorted(nums1 + nums2)\n total = len(merged)\n if total % 2 == 1:\n return float(merged[total // 2])\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 doctest.testmod()"}
41
+ {"Intruction":"This is a question asked by a user","Context":"Given 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","response":"from itertools import combinations\n\n\ndef pairs_with_sum(arr: list, req_sum: int) ->int:\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 testmod()"}
42
+ {"Intruction":"This is a question asked by a user","Context":"Minimax helps to achieve maximum score in a game by checking all possible moves\ndepth is current depth in game tree.\n\nnodeIndex is index of current node in scores[].\nif move is of maximizer return true else false\nleaves of game tree is stored in scores[]\nheight is maximum height of Game tree","response":"from __future__ import annotations\nimport math\n\n\ndef minimax(depth: int, node_index: int, is_max: bool, scores: list[int],\n height: float) ->int:\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 if depth == height:\n return scores[node_index]\n if is_max:\n return max(minimax(depth + 1, node_index * 2, False, scores, height\n ), minimax(depth + 1, node_index * 2 + 1, False, scores, height))\n return min(minimax(depth + 1, node_index * 2, True, scores, height),\n minimax(depth + 1, node_index * 2 + 1, True, scores, height))\n\n\ndef main() ->None:\n scores = [90, 23, 6, 33, 21, 65, 123, 34423]\n height = math.log(len(scores), 2)\n print('Optimal value : ', end='')\n print(minimax(0, 0, True, scores, height))\n\n\nif __name__ == '__main__':\n import doctest\n doctest.testmod()\n main()"}
43
+ {"Intruction":"This is a question asked by a user","Context":"Author : Alexander Pantyukhin\nDate : November 3, 2022\n\nImplement the class of prefix sum with useful functions based on it.","response":"class PrefixSum:\n\n def __init__(self, array: list[int]) ->None:\n len_array = len(array)\n self.prefix_sum = [0] * len_array\n if len_array > 0:\n self.prefix_sum[0] = array[0]\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 if start == 0:\n return self.prefix_sum[end]\n return self.prefix_sum[end] - self.prefix_sum[start - 1]\n\n def contains_sum(self, target_sum: int) ->bool:\n sums = {0}\n for sum_item in self.prefix_sum:\n if sum_item - target_sum in sums:\n return True\n sums.add(sum_item)\n return False\n\n\nif __name__ == '__main__':\n import doctest\n doctest.testmod()"}
44
+ {"Intruction":"This is a question asked by a user","Context":"Generate code for highest_set_bit","response":"def get_highest_set_bit_position(number: int) ->int:\n if not isinstance(number, int):\n raise TypeError(\"Input value must be an 'int' type\")\n position = 0\n while number:\n position += 1\n number >>= 1\n return position\n\n\nif __name__ == '__main__':\n import doctest\n doctest.testmod()"}
45
+ {"Intruction":"This is a question asked by a user","Context":"A NOR Gate is a logic gate in boolean algebra which results to false(0)\nif any of the input is 1, and True(1) if both the inputs are 0.\nFollowing is the truth table of a 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\nFollowing is the code implementation of the NOR Gate","response":"def nor_gate(input_1: int, input_2: int) ->int:\n return int(input_1 == input_2 == 0)\n\n\ndef main() ->None:\n print('Truth Table of NOR Gate:')\n print('| Input 1 | Input 2 | Output |')\n print(f'| 0 | 0 | {nor_gate(0, 0)} |')\n print(f'| 0 | 1 | {nor_gate(0, 1)} |')\n print(f'| 1 | 0 | {nor_gate(1, 0)} |')\n print(f'| 1 | 1 | {nor_gate(1, 1)} |')\n\n\nif __name__ == '__main__':\n import doctest\n doctest.testmod()\n main()\n\"\"\"Code provided by Akshaj Vishwanathan\"\"\"\n\"\"\"Reference: https://www.geeksforgeeks.org/logic-gates-in-python/\"\"\""}
46
+ {"Intruction":"This is a question asked by a user","Context":"Generate code for cryptomath_module","response":"from maths.greatest_common_divisor import gcd_by_iterative\n\n\ndef find_mod_inverse(a: int, m: int) ->int:\n if gcd_by_iterative(a, m) != 1:\n msg = f'mod inverse of {a!r} and {m!r} does not exist'\n raise ValueError(msg)\n u1, u2, u3 = 1, 0, a\n v1, v2, v3 = 0, 1, m\n while v3 != 0:\n q = u3 // v3\n v1, v2, v3, u1, u2, u3 = (u1 - q * v1, u2 - q * v2, u3 - q * v3, v1,\n v2, v3)\n return u1 % m"}
47
+ {"Intruction":"This is a question asked by a user","Context":"Graph Coloring also called \"m coloring problem\"\nconsists of coloring a given graph with at most m colors\nsuch that no adjacent vertices are assigned the same color\n\nWikipedia: https://en.wikipedia.org/wiki/Graph_coloring","response":"def valid_coloring(neighbours: list[int], colored_vertices: list[int],\n color: int) ->bool:\n return not any(neighbour == 1 and colored_vertices[i] == color for i,\n neighbour in enumerate(neighbours))\n\n\ndef util_color(graph: list[list[int]], max_colors: int, colored_vertices:\n list[int], index: int) ->bool:\n if index == len(graph):\n return True\n for i in range(max_colors):\n if valid_coloring(graph[index], colored_vertices, i):\n colored_vertices[index] = i\n if util_color(graph, max_colors, colored_vertices, index + 1):\n return True\n colored_vertices[index] = -1\n return False\n\n\ndef color(graph: list[list[int]], max_colors: int) ->list[int]:\n colored_vertices = [-1] * len(graph)\n if util_color(graph, max_colors, colored_vertices, 0):\n return colored_vertices\n return []"}
48
+ {"Intruction":"This is a question asked by a user","Context":"Generate code for circular_queue","response":"class CircularQueue:\n\n def __init__(self, n: int):\n self.n = n\n self.array = [None] * self.n\n self.front = 0\n self.rear = 0\n self.size = 0\n\n def __len__(self) ->int:\n return self.size\n\n def is_empty(self) ->bool:\n return self.size == 0\n\n def first(self):\n return False if self.is_empty() else self.array[self.front]\n\n def enqueue(self, data):\n if self.size >= self.n:\n raise Exception('QUEUE IS FULL')\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 if self.size == 0:\n raise Exception('UNDERFLOW')\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"}
49
+ {"Intruction":"This is a question asked by a user","Context":"Generate code for permutations","response":"def permute_recursive(nums: list[int]) ->list[list[int]]:\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 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]\n output: list[list[int]] = []\n backtrack(0)\n return output\n\n\nif __name__ == '__main__':\n import doctest\n result = permute_backtrack([1, 2, 3])\n print(result)\n doctest.testmod()"}
50
+ {"Intruction":"This is a question asked by a user","Context":"Generate code for newton_forward_interpolation","response":"from __future__ import annotations\nimport math\n\n\ndef ucal(u: float, p: int) ->float:\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 print('enter the values of parameters in a list: ')\n x = list(map(int, input().split()))\n print('enter the values of corresponding parameters: ')\n for i in range(n):\n y[i][0] = float(input())\n value = int(input('enter the value to interpolate: '))\n u = (value - x[0]) / (x[1] - x[0])\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 summ = y[0][0]\n for i in range(1, n):\n summ += ucal(u, i) * y[0][i] / math.factorial(i)\n print(f'the value at {value} is {summ}')\n\n\nif __name__ == '__main__':\n main()"}