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 o... | 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):
... |
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.hea... |
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 ... | 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
re... |
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 AR... | __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:
... |
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."""
)
... |
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:
... |
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 ... | 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 |
-----... | 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)
... |
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 < ... |
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
) -... |
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__':
... |
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) ->... |
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... | 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
i... |
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(cur... |
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_s... |
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... | 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 __nam... |
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 divi... |
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 i... |
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)
... |
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.a... |
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
... |
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 ... | 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.test... |
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.va... |
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 |... | 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 ... | 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}"
... |
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 num... |
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):
... |
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 | ... | 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... |
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:... |
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 ... |
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 -... |
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 == heigh... |
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]
de... |
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 ... | 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)}... |
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 //... |
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) ->bo... |
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):
... |
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.e... |
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([])
... |
No dataset card yet
- Downloads last month
- 16