Intruction
stringclasses
1 value
Context
stringlengths
16
1.29k
response
stringlengths
129
1.02k
This is a question asked by a user
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.
def calculation_span(price, s): n = len(price) st = [] st.append(0) s[0] = 1 for i in range(1, n): while len(st) > 0 and price[st[0]] <= price[i]: st.pop() s[i] = i + 1 if len(st) <= 0 else i - st[0] st.append(i) def print_array(arr, n): for i in range(n): print(arr[i], end=' ') price = [10, 4, 5, 90, 120, 80] S = [(0) for i in range(len(price) + 1)] calculation_span(price, S) print_array(S, len(price))
This is a question asked by a user
Generate code for middle_element_of_linked_list
from __future__ import annotations class Node: def __init__(self, data: int) ->None: self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def push(self, new_data: int) ->int: new_node = Node(new_data) new_node.next = self.head self.head = new_node return self.head.data def middle_element(self) ->(int | None): slow_pointer = self.head fast_pointer = self.head if self.head: while fast_pointer and fast_pointer.next: fast_pointer = fast_pointer.next.next slow_pointer = slow_pointer.next return slow_pointer.data else: print('No element found.') return None if __name__ == '__main__': link = LinkedList() for _ in range(int(input().strip())): data = int(input().strip()) link.push(data) print(link.middle_element())
This is a question asked by a user
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.
def power_of_4(number: int) ->bool: if not isinstance(number, int): raise TypeError('number must be an integer') if number <= 0: raise ValueError('number must be positive') if number & number - 1 == 0: c = 0 while number: c += 1 number >>= 1 return c % 2 == 1 else: return False if __name__ == '__main__': import doctest doctest.testmod()
This is a question asked by a user
Author: Alexander Joslin GitHub: github.com/echoaj Explanation: https://medium.com/@haleesammar/implemented-in-js-dijkstras-2-stack- algorithm-for-evaluating-mathematical-expressions-fc0837dae1ea 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.
__author__ = 'Alexander Joslin' import operator as op from .stack import Stack def dijkstras_two_stack_algorithm(equation: str) ->int: operators = {'*': op.mul, '/': op.truediv, '+': op.add, '-': op.sub} operand_stack: Stack[int] = Stack() operator_stack: Stack[str] = Stack() for i in equation: if i.isdigit(): operand_stack.push(int(i)) elif i in operators: operator_stack.push(i) elif i == ')': opr = operator_stack.peek() operator_stack.pop() num1 = operand_stack.peek() operand_stack.pop() num2 = operand_stack.peek() operand_stack.pop() total = operators[opr](num2, num1) operand_stack.push(total) return operand_stack.peek() if __name__ == '__main__': equation = '(5 + ((4 * 2) * (2 + 3)))' print(f'{equation} = {dijkstras_two_stack_algorithm(equation)}')
This is a question asked by a user
Generate code for base16
def base16_encode(data: bytes) ->str: return ''.join([hex(byte)[2:].zfill(2).upper() for byte in list(data)]) def base16_decode(data: str) ->bytes: if len(data) % 2 != 0: raise ValueError( """Base16 encoded data is invalid: Data does not have an even number of hex digits.""" ) if not set(data) <= set('0123456789ABCDEF'): raise ValueError( """Base16 encoded data is invalid: Data is not uppercase hex or it contains invalid characters.""" ) return bytes(int(data[i] + data[i + 1], 16) for i in range(0, len(data), 2) ) if __name__ == '__main__': import doctest doctest.testmod()
This is a question asked by a user
Python3 program to evaluate a prefix expression.
calc = {'+': lambda x, y: x + y, '-': lambda x, y: x - y, '*': lambda x, y: x * y, '/': lambda x, y: x / y} def is_operand(c): return c.isdigit() def evaluate(expression): stack = [] for c in expression.split()[::-1]: if is_operand(c): stack.append(int(c)) else: o1 = stack.pop() o2 = stack.pop() stack.append(calc[c](o1, o2)) return stack.pop() if __name__ == '__main__': test_expression = '+ 9 * 2 6' print(evaluate(test_expression)) test_expression = '/ * 10 2 + 4 1 ' print(evaluate(test_expression))
This is a question asked by a user
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.org/logic-gates-in-python/
def xor_gate(input_1: int, input_2: int) ->int: return (input_1, input_2).count(0) % 2 if __name__ == '__main__': import doctest doctest.testmod()
This is a question asked by a user
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.
def different_signs(num1: int, num2: int) ->bool: return num1 ^ num2 < 0 if __name__ == '__main__': import doctest doctest.testmod()
This is a question asked by a user
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.org/logic-gates-in-python/
def xnor_gate(input_1: int, input_2: int) ->int: return 1 if input_1 == input_2 else 0 if __name__ == '__main__': import doctest doctest.testmod()
This is a question asked by a user
Generate code for find_triplets_with_0_sum
from itertools import combinations def find_triplets_with_0_sum(nums: list[int]) ->list[list[int]]: return [list(x) for x in sorted({abc for abc in combinations(sorted( nums), 3) if not sum(abc)})]
This is a question asked by a user
Generate code for reverse_bits
def get_reverse_bit_string(number: int) ->str: if not isinstance(number, int): msg = ( f'operation can not be conducted on a object of type {type(number).__name__}' ) raise TypeError(msg) bit_string = '' for _ in range(32): bit_string += str(number % 2) number = number >> 1 return bit_string def reverse_bit(number: int) ->str: if number < 0: raise ValueError('the value of input must be positive') elif isinstance(number, float): raise TypeError("Input value must be a 'int' type") elif isinstance(number, str): raise TypeError( "'<' not supported between instances of 'str' and 'int'") result = 0 for _ in range(1, 33): result = result << 1 end_bit = number % 2 number = number >> 1 result = result | end_bit return get_reverse_bit_string(result) if __name__ == '__main__': import doctest doctest.testmod()
This is a question asked by a user
Generate code for brute_force_caesar_cipher
import string def decrypt(message: str) ->None: for key in range(len(string.ascii_uppercase)): translated = '' for symbol in message: if symbol in string.ascii_uppercase: num = string.ascii_uppercase.find(symbol) num = num - key if num < 0: num = num + len(string.ascii_uppercase) translated = translated + string.ascii_uppercase[num] else: translated = translated + symbol print(f'Decryption using Key #{key}: {translated}') def main() ->None: message = input('Encrypted message: ') message = message.upper() decrypt(message) if __name__ == '__main__': import doctest doctest.testmod() main()
This is a question asked by a user
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 NP-complete. Wikipedia: https://en.wikipedia.org/wiki/Hamiltonian_path
def valid_connection(graph: list[list[int]], next_ver: int, curr_ind: int, path: list[int]) ->bool: if graph[path[curr_ind - 1]][next_ver] == 0: return False return not any(vertex == next_ver for vertex in path) def util_hamilton_cycle(graph: list[list[int]], path: list[int], curr_ind: int ) ->bool: if curr_ind == len(graph): return graph[path[curr_ind - 1]][path[0]] == 1 for next_ver in range(len(graph)): if valid_connection(graph, next_ver, curr_ind, path): path[curr_ind] = next_ver if util_hamilton_cycle(graph, path, curr_ind + 1): return True path[curr_ind] = -1 return False def hamilton_cycle(graph: list[list[int]], start_index: int=0) ->list[int]: path = [-1] * (len(graph) + 1) path[0] = path[-1] = start_index return path if util_hamilton_cycle(graph, path, 1) else []
This is a question asked by a user
Generate code for binary_count_trailing_zeros
from math import log2 def binary_count_trailing_zeros(a: int) ->int: if a < 0: raise ValueError('Input value must be a positive integer') elif isinstance(a, float): raise TypeError("Input value must be a 'int' type") return 0 if a == 0 else int(log2(a & -a)) if __name__ == '__main__': import doctest doctest.testmod()
This is a question asked by a user
Generate code for gray_code_sequence
def gray_code(bit_count: int) ->list: if bit_count < 0: raise ValueError('The given input must be positive') sequence = gray_code_sequence_string(bit_count) for i in range(len(sequence)): sequence[i] = int(sequence[i], 2) return sequence def gray_code_sequence_string(bit_count: int) ->list: if bit_count == 0: return ['0'] if bit_count == 1: return ['0', '1'] seq_len = 1 << bit_count smaller_sequence = gray_code_sequence_string(bit_count - 1) sequence = [] for i in range(seq_len // 2): generated_no = '0' + smaller_sequence[i] sequence.append(generated_no) for i in reversed(range(seq_len // 2)): generated_no = '1' + smaller_sequence[i] sequence.append(generated_no) return sequence if __name__ == '__main__': import doctest doctest.testmod()
This is a question asked by a user
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.org/logic-gates-in-python/
def and_gate(input_1: int, input_2: int) ->int: return int(input_1 and input_2) if __name__ == '__main__': import doctest doctest.testmod()
This is a question asked by a user
Generate code for index_of_rightmost_set_bit
def get_index_of_rightmost_set_bit(number: int) ->int: if not isinstance(number, int) or number < 0: raise ValueError('Input must be a non-negative integer') intermediate = number & ~(number - 1) index = 0 while intermediate: intermediate >>= 1 index += 1 return index - 1 if __name__ == '__main__': """ Finding the index of rightmost set bit has some very peculiar use-cases, especially in finding missing or/and repeating numbers in a list of positive integers. """ import doctest doctest.testmod(verbose=True)
This is a question asked by a user
Generate code for binary_count_setbits
def binary_count_setbits(a: int) ->int: if a < 0: raise ValueError('Input value must be a positive integer') elif isinstance(a, float): raise TypeError("Input value must be a 'int' type") return bin(a).count('1') if __name__ == '__main__': import doctest doctest.testmod()
This is a question asked by a user
In this problem, we want to determine all possible subsequences of the given sequence. We use backtracking to solve this problem. Time complexity: O(2^n), where n denotes the length of the given sequence.
from __future__ import annotations from typing import Any def generate_all_subsequences(sequence: list[Any]) ->None: create_state_space_tree(sequence, [], 0) def create_state_space_tree(sequence: list[Any], current_subsequence: list[ Any], index: int) ->None: if index == len(sequence): print(current_subsequence) return create_state_space_tree(sequence, current_subsequence, index + 1) current_subsequence.append(sequence[index]) create_state_space_tree(sequence, current_subsequence, index + 1) current_subsequence.pop() if __name__ == '__main__': seq: list[Any] = [3, 1, 2, 4] generate_all_subsequences(seq) seq.clear() seq.extend(['A', 'B', 'C']) generate_all_subsequences(seq)
This is a question asked by a user
Calculates the sum of two non-negative integers using bitwise operators Wikipedia explanation: https://en.wikipedia.org/wiki/Binary_number
def bitwise_addition_recursive(number: int, other_number: int) ->int: if not isinstance(number, int) or not isinstance(other_number, int): raise TypeError('Both arguments MUST be integers!') if number < 0 or other_number < 0: raise ValueError('Both arguments MUST be non-negative!') bitwise_sum = number ^ other_number carry = number & other_number if carry == 0: return bitwise_sum return bitwise_addition_recursive(bitwise_sum, carry << 1) if __name__ == '__main__': import doctest doctest.testmod()
This is a question asked by a user
Calculate the Product Sum from a Special Array. reference: https://dev.to/sfrasica/algorithms-product-sum-from-an-array-dc6 Python doctests can be run with the following command: python -m doctest -v product_sum.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
def product_sum(arr: list[int | list], depth: int) ->int: total_sum = 0 for ele in arr: total_sum += product_sum(ele, depth + 1) if isinstance(ele, list ) else ele return total_sum * depth def product_sum_array(array: list[int | list]) ->int: return product_sum(array, 1) if __name__ == '__main__': import doctest doctest.testmod()
This is a question asked by a user
Generate code for intersection
import math from collections.abc import Callable def intersection(function: Callable[[float], float], x0: float, x1: float ) ->float: x_n: float = x0 x_n1: float = x1 while True: if x_n == x_n1 or function(x_n1) == function(x_n): raise ZeroDivisionError( 'float division by zero, could not find root') x_n2: float = x_n1 - function(x_n1) / ((function(x_n1) - function( x_n)) / (x_n1 - x_n)) if abs(x_n2 - x_n1) < 10 ** -5: return x_n2 x_n = x_n1 x_n1 = x_n2 def f(x: float) ->float: return math.pow(x, 3) - 2 * x - 5 if __name__ == '__main__': print(intersection(f, 3, 3.5))
This is a question asked by a user
Convert a Decimal Number to an Octal Number.
import math def decimal_to_octal(num: int) ->str: octal = 0 counter = 0 while num > 0: remainder = num % 8 octal = octal + remainder * math.floor(math.pow(10, counter)) counter += 1 num = math.floor(num / 8) return f'0o{int(octal)}' def main() ->None: print('\n2 in octal is:') print(decimal_to_octal(2)) print('\n8 in octal is:') print(decimal_to_octal(8)) print('\n65 in octal is:') print(decimal_to_octal(65)) print('\n216 in octal is:') print(decimal_to_octal(216)) print('\n512 in octal is:') print(decimal_to_octal(512)) print('\n') if __name__ == '__main__': main()
This is a question asked by a user
Convert a string of characters to a sequence of numbers corresponding to the character's position in the alphabet. https://www.dcode.fr/letter-number-cipher http://bestcodes.weebly.com/a1z26.html
from __future__ import annotations def encode(plain: str) ->list[int]: return [(ord(elem) - 96) for elem in plain] def decode(encoded: list[int]) ->str: return ''.join(chr(elem + 96) for elem in encoded) def main() ->None: encoded = encode(input('-> ').strip().lower()) print('Encoded: ', encoded) print('Decoded:', decode(encoded)) if __name__ == '__main__': main()
This is a question asked by a user
Generate code for onepad_cipher
import random class Onepad: @staticmethod def encrypt(text: str) ->tuple[list[int], list[int]]: plain = [ord(i) for i in text] key = [] cipher = [] for i in plain: k = random.randint(1, 300) c = (i + k) * k cipher.append(c) key.append(k) return cipher, key @staticmethod def decrypt(cipher: list[int], key: list[int]) ->str: plain = [] for i in range(len(key)): p = int((cipher[i] - key[i] ** 2) / key[i]) plain.append(chr(p)) return ''.join(plain) if __name__ == '__main__': c, k = Onepad().encrypt('Hello') print(c, k) print(Onepad().decrypt(c, k))
This is a question asked by a user
Generate code for binary_and_operator
def binary_and(a: int, b: int) ->str: if a < 0 or b < 0: raise ValueError('the value of both inputs must be positive') a_binary = str(bin(a))[2:] b_binary = str(bin(b))[2:] max_len = max(len(a_binary), len(b_binary)) return '0b' + ''.join(str(int(char_a == '1' and char_b == '1')) for char_a, char_b in zip(a_binary.zfill(max_len), b_binary.zfill(max_len)) ) if __name__ == '__main__': import doctest doctest.testmod()
This is a question asked by a user
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 (res<<1)<=number. 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)
def largest_pow_of_two_le_num(number: int) ->int: if isinstance(number, float): raise TypeError("Input value must be a 'int' type") if number <= 0: return 0 res = 1 while res << 1 <= number: res <<= 1 return res if __name__ == '__main__': import doctest doctest.testmod()
This is a question asked by a user
Generate code for hash_table_with_linked_list
from collections import deque from .hash_table import HashTable class HashTableWithLinkedList(HashTable): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def _set_value(self, key, data): self.values[key] = deque([]) if self.values[key ] is None else self.values[key] self.values[key].appendleft(data) self._keys[key] = self.values[key] def balanced_factor(self): return sum(self.charge_factor - len(slot) for slot in self.values ) / self.size_table * self.charge_factor def _collision_resolution(self, key, data=None): if not (len(self.values[key]) == self.charge_factor and self.values .count(None) == 0): return key return super()._collision_resolution(key, data)
This is a question asked by a user
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.org/logic-gates-in-python/
def not_gate(input_1: int) ->int: return 1 if input_1 == 0 else 0 if __name__ == '__main__': import doctest doctest.testmod()
This is a question asked by a user
Generate code for missing_number
def find_missing_number(nums: list[int]) ->int: low = min(nums) high = max(nums) missing_number = high for i in range(low, high): missing_number ^= i ^ nums[i - low] return missing_number
This is a question asked by a user
Lower–upper (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 non-zero (see https://en.wikipedia.org/wiki/Minor_(linear_algebra) 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 non-zero. 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.org/wiki/LU_decomposition
from __future__ import annotations import numpy as np def lower_upper_decomposition(table: np.ndarray) ->tuple[np.ndarray, np.ndarray ]: rows, columns = np.shape(table) if rows != columns: msg = ( f"'table' has to be of square shaped array but got a {rows}x{columns} array:\n{table}" ) raise ValueError(msg) lower = np.zeros((rows, columns)) upper = np.zeros((rows, columns)) for i in range(columns): for j in range(i): total = np.sum(lower[i, :i] * upper[:i, j]) if upper[j][j] == 0: raise ArithmeticError('No LU decomposition exists') lower[i][j] = (table[i][j] - total) / upper[j][j] lower[i][i] = 1 for j in range(i, columns): total = np.sum(lower[i, :i] * upper[:i, j]) upper[i][j] = table[i][j] - total return lower, upper if __name__ == '__main__': import doctest doctest.testmod()
This is a question asked by a user
Provide the functionality to manipulate a single bit.
def set_bit(number: int, position: int) ->int: return number | 1 << position def clear_bit(number: int, position: int) ->int: return number & ~(1 << position) def flip_bit(number: int, position: int) ->int: return number ^ 1 << position def is_bit_set(number: int, position: int) ->bool: return number >> position & 1 == 1 def get_bit(number: int, position: int) ->int: return int(number & 1 << position != 0) if __name__ == '__main__': import doctest doctest.testmod()
This is a question asked by a user
Generate code for count_1s_brian_kernighan_method
def get_1s_count(number: int) ->int: if not isinstance(number, int) or number < 0: raise ValueError('Input must be a non-negative integer') count = 0 while number: number &= number - 1 count += 1 return count if __name__ == '__main__': import doctest doctest.testmod()
This is a question asked by a user
Generate code for is_even
def is_even(number: int) ->bool: return number & 1 == 0 if __name__ == '__main__': import doctest doctest.testmod()
This is a question asked by a user
Generate code for mean_threshold
from PIL import Image """ Mean thresholding algorithm for image processing https://en.wikipedia.org/wiki/Thresholding_(image_processing) """ def mean_threshold(image: Image) ->Image: height, width = image.size mean = 0 pixels = image.load() for i in range(width): for j in range(height): pixel = pixels[j, i] mean += pixel mean //= width * height for j in range(width): for i in range(height): pixels[i, j] = 255 if pixels[i, j] > mean else 0 return image if __name__ == '__main__': image = mean_threshold(Image.open('path_to_image').convert('L')) image.save('output_image_path')
This is a question asked by a user
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.org/wiki/NIMPLY_gate
def nimply_gate(input_1: int, input_2: int) ->int: return int(input_1 == 1 and input_2 == 0) if __name__ == '__main__': import doctest doctest.testmod()
This is a question asked by a user
Newton's Method.
from collections.abc import Callable RealFunc = Callable[[float], float] def newton(function: RealFunc, derivative: RealFunc, starting_int: int ) ->float: prev_guess = float(starting_int) while True: try: next_guess = prev_guess - function(prev_guess) / derivative( prev_guess) except ZeroDivisionError: raise ZeroDivisionError('Could not find root') from None if abs(prev_guess - next_guess) < 10 ** -5: return next_guess prev_guess = next_guess def f(x: float) ->float: return x ** 3 - 2 * x - 5 def f1(x: float) ->float: return 3 * x ** 2 - 2 if __name__ == '__main__': print(newton(f, f1, 3))
This is a question asked by a user
Queue implementation using two stacks
from collections.abc import Iterable from typing import Generic, TypeVar _T = TypeVar('_T') class QueueByTwoStacks(Generic[_T]): def __init__(self, iterable: (Iterable[_T] | None)=None) ->None: self._stack1: list[_T] = list(iterable or []) self._stack2: list[_T] = [] def __len__(self) ->int: return len(self._stack1) + len(self._stack2) def __repr__(self) ->str: return f'Queue({tuple(self._stack2[::-1] + self._stack1)})' def put(self, item: _T) ->None: self._stack1.append(item) def get(self) ->_T: stack1_pop = self._stack1.pop stack2_append = self._stack2.append if not self._stack2: while self._stack1: stack2_append(stack1_pop()) if not self._stack2: raise IndexError('Queue is empty') return self._stack2.pop() if __name__ == '__main__': from doctest import testmod testmod()
This is a question asked by a user
Generate code for quadratic_probing
from .hash_table import HashTable class QuadraticProbing(HashTable): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def _collision_resolution(self, key, data=None): i = 1 new_key = self.hash_function(key + i * i) while self.values[new_key] is not None and self.values[new_key] != key: i += 1 new_key = self.hash_function(key + i * i ) if not self.balanced_factor() >= self.lim_charge else None if new_key is None: break return new_key
This is a question asked by a user
https://www.enjoyalgorithms.com/blog/median-of-two-sorted-arrays
def find_median_sorted_arrays(nums1: list[int], nums2: list[int]) ->float: if not nums1 and not nums2: raise ValueError('Both input arrays are empty.') merged = sorted(nums1 + nums2) total = len(merged) if total % 2 == 1: return float(merged[total // 2]) middle1 = merged[total // 2 - 1] middle2 = merged[total // 2] return (float(middle1) + float(middle2)) / 2.0 if __name__ == '__main__': import doctest doctest.testmod()
This is a question asked by a user
Given an array of integers and an integer req_sum, find the number of pairs of array elements whose sum is equal to req_sum. https://practice.geeksforgeeks.org/problems/count-pairs-with-given-sum5022/0
from itertools import combinations def pairs_with_sum(arr: list, req_sum: int) ->int: return len([(1) for a, b in combinations(arr, 2) if a + b == req_sum]) if __name__ == '__main__': from doctest import testmod testmod()
This is a question asked by a user
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
from __future__ import annotations import math def minimax(depth: int, node_index: int, is_max: bool, scores: list[int], height: float) ->int: if depth < 0: raise ValueError('Depth cannot be less than 0') if len(scores) == 0: raise ValueError('Scores cannot be empty') if depth == height: return scores[node_index] if is_max: return max(minimax(depth + 1, node_index * 2, False, scores, height ), minimax(depth + 1, node_index * 2 + 1, False, scores, height)) return min(minimax(depth + 1, node_index * 2, True, scores, height), minimax(depth + 1, node_index * 2 + 1, True, scores, height)) def main() ->None: scores = [90, 23, 6, 33, 21, 65, 123, 34423] height = math.log(len(scores), 2) print('Optimal value : ', end='') print(minimax(0, 0, True, scores, height)) if __name__ == '__main__': import doctest doctest.testmod() main()
This is a question asked by a user
Author : Alexander Pantyukhin Date : November 3, 2022 Implement the class of prefix sum with useful functions based on it.
class PrefixSum: def __init__(self, array: list[int]) ->None: len_array = len(array) self.prefix_sum = [0] * len_array if len_array > 0: self.prefix_sum[0] = array[0] for i in range(1, len_array): self.prefix_sum[i] = self.prefix_sum[i - 1] + array[i] def get_sum(self, start: int, end: int) ->int: if start == 0: return self.prefix_sum[end] return self.prefix_sum[end] - self.prefix_sum[start - 1] def contains_sum(self, target_sum: int) ->bool: sums = {0} for sum_item in self.prefix_sum: if sum_item - target_sum in sums: return True sums.add(sum_item) return False if __name__ == '__main__': import doctest doctest.testmod()
This is a question asked by a user
Generate code for highest_set_bit
def get_highest_set_bit_position(number: int) ->int: if not isinstance(number, int): raise TypeError("Input value must be an 'int' type") position = 0 while number: position += 1 number >>= 1 return position if __name__ == '__main__': import doctest doctest.testmod()
This is a question asked by a user
A NOR Gate is a logic gate in boolean algebra which results to false(0) if any of the input is 1, and True(1) if both the inputs are 0. Following is the truth table of a NOR Gate: | Input 1 | Input 2 | Output | | 0 | 0 | 1 | | 0 | 1 | 0 | | 1 | 0 | 0 | | 1 | 1 | 0 | Following is the code implementation of the NOR Gate
def nor_gate(input_1: int, input_2: int) ->int: return int(input_1 == input_2 == 0) def main() ->None: print('Truth Table of NOR Gate:') print('| Input 1 | Input 2 | Output |') print(f'| 0 | 0 | {nor_gate(0, 0)} |') print(f'| 0 | 1 | {nor_gate(0, 1)} |') print(f'| 1 | 0 | {nor_gate(1, 0)} |') print(f'| 1 | 1 | {nor_gate(1, 1)} |') if __name__ == '__main__': import doctest doctest.testmod() main() """Code provided by Akshaj Vishwanathan""" """Reference: https://www.geeksforgeeks.org/logic-gates-in-python/"""
This is a question asked by a user
Generate code for cryptomath_module
from maths.greatest_common_divisor import gcd_by_iterative def find_mod_inverse(a: int, m: int) ->int: if gcd_by_iterative(a, m) != 1: msg = f'mod inverse of {a!r} and {m!r} does not exist' raise ValueError(msg) u1, u2, u3 = 1, 0, a v1, v2, v3 = 0, 1, m while v3 != 0: q = u3 // v3 v1, v2, v3, u1, u2, u3 = (u1 - q * v1, u2 - q * v2, u3 - q * v3, v1, v2, v3) return u1 % m
This is a question asked by a user
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.org/wiki/Graph_coloring
def valid_coloring(neighbours: list[int], colored_vertices: list[int], color: int) ->bool: return not any(neighbour == 1 and colored_vertices[i] == color for i, neighbour in enumerate(neighbours)) def util_color(graph: list[list[int]], max_colors: int, colored_vertices: list[int], index: int) ->bool: if index == len(graph): return True for i in range(max_colors): if valid_coloring(graph[index], colored_vertices, i): colored_vertices[index] = i if util_color(graph, max_colors, colored_vertices, index + 1): return True colored_vertices[index] = -1 return False def color(graph: list[list[int]], max_colors: int) ->list[int]: colored_vertices = [-1] * len(graph) if util_color(graph, max_colors, colored_vertices, 0): return colored_vertices return []
This is a question asked by a user
Generate code for circular_queue
class CircularQueue: def __init__(self, n: int): self.n = n self.array = [None] * self.n self.front = 0 self.rear = 0 self.size = 0 def __len__(self) ->int: return self.size def is_empty(self) ->bool: return self.size == 0 def first(self): return False if self.is_empty() else self.array[self.front] def enqueue(self, data): if self.size >= self.n: raise Exception('QUEUE IS FULL') self.array[self.rear] = data self.rear = (self.rear + 1) % self.n self.size += 1 return self def dequeue(self): if self.size == 0: raise Exception('UNDERFLOW') temp = self.array[self.front] self.array[self.front] = None self.front = (self.front + 1) % self.n self.size -= 1 return temp
This is a question asked by a user
Generate code for permutations
def permute_recursive(nums: list[int]) ->list[list[int]]: result: list[list[int]] = [] if len(nums) == 0: return [[]] for _ in range(len(nums)): n = nums.pop(0) permutations = permute_recursive(nums.copy()) for perm in permutations: perm.append(n) result.extend(permutations) nums.append(n) return result def permute_backtrack(nums: list[int]) ->list[list[int]]: def backtrack(start: int) ->None: if start == len(nums) - 1: output.append(nums[:]) else: for i in range(start, len(nums)): nums[start], nums[i] = nums[i], nums[start] backtrack(start + 1) nums[start], nums[i] = nums[i], nums[start] output: list[list[int]] = [] backtrack(0) return output if __name__ == '__main__': import doctest result = permute_backtrack([1, 2, 3]) print(result) doctest.testmod()
This is a question asked by a user
Generate code for newton_forward_interpolation
from __future__ import annotations import math def ucal(u: float, p: int) ->float: temp = u for i in range(1, p): temp = temp * (u - i) return temp def main() ->None: n = int(input('enter the numbers of values: ')) y: list[list[float]] = [] for _ in range(n): y.append([]) for i in range(n): for j in range(n): y[i].append(j) y[i][j] = 0 print('enter the values of parameters in a list: ') x = list(map(int, input().split())) print('enter the values of corresponding parameters: ') for i in range(n): y[i][0] = float(input()) value = int(input('enter the value to interpolate: ')) u = (value - x[0]) / (x[1] - x[0]) for i in range(1, n): for j in range(n - i): y[j][i] = y[j + 1][i - 1] - y[j][i - 1] summ = y[0][0] for i in range(1, n): summ += ucal(u, i) * y[0][i] / math.factorial(i) print(f'the value at {value} is {summ}') if __name__ == '__main__': main()