Dataset Viewer
Auto-converted to Parquet Duplicate
id
stringlengths
9
23
stage
stringclasses
1 value
prompt
stringlengths
36
8.07k
answer
stringlengths
79
7.72k
test
stringlengths
153
4.03k
entry_points
listlengths
0
12
entry_declarations
listlengths
0
12
subset
stringclasses
12 values
gpt_difficulty
stringclasses
3 values
gpt_pass_percentage
float64
0.1
1
Algorithm_10008_I
test
### Problem Statement Write a function to calculate the maximum profit that can be made by performing at most `k` transactions on a list of stock prices, where each transaction consists of buying one unit of stock and selling one unit of stock on later days. You are not allowed to engage in multiple transactions simult...
def max_profit_with_k_transactions(prices, k): """ Calculate the maximum profit that can be made with at most k transactions. :param prices: List[int] - list of stock prices :param k: int - maximum number of transactions allowed :return: int - maximum profit achievable """ if not prices or ...
from solution import max_profit_with_k_transactions def test_example_case(): prices = [3, 2, 6, 5, 0, 3] k = 2 assert max_profit_with_k_transactions(prices, k) == 7 def test_no_transactions(): prices = [3, 2, 6, 5, 0, 3] k = 0 assert max_profit_with_k_transactions(prices, k) == 0 def test_emp...
[ "max_profit_with_k_transactions" ]
[ "def max_profit_with_k_transactions(prices, k):" ]
Algorithm
medium
0.556
Algorithm_10071_I
test
### Coding Problem: Maximize Stock Profits with Limited Transactions #### Context: A stock trader wants to maximize their profits from a given list of daily stock prices, but they are limited to making a fixed number of transactions (buy/sell). A transaction consists of buying one unit of stock and then later selling ...
def max_profit_with_k_transactions(prices, k): if not prices or k == 0: return 0 n = len(prices) if k >= n // 2: return sum(max(prices[i + 1] - prices[i], 0) for i in range(n - 1)) # Initialize the DP table profits = [[0] * n for _ in range(k + 1)] # Fill the DP table ...
from solution import max_profit_with_k_transactions def test_single_transaction(): prices = [3, 2, 6, 5, 0, 3] k = 1 assert max_profit_with_k_transactions(prices, k) == 4 def test_multiple_transactions(): prices = [3, 2, 6, 5, 0, 3] k = 2 assert max_profit_with_k_transactions(prices, k) == 7 ...
[ "max_profit_with_k_transactions" ]
[ "def max_profit_with_k_transactions(prices, k):" ]
Algorithm
easy
0.667
Algorithm_10154_I
test
### Problem Statement You are tasked with developing a function for an educational app aimed at teaching children basic arithmetic operations through an engaging quiz. The function should generate a series of unique arithmetic problems for addition, subtraction, and multiplication based on the given parameters. The f...
import random from typing import List def generate_arithmetic_problems(m: int) -> List[str]: if m < 1: return [] problems = [] operations = ['+', '-', '*'] base_count = m // 3 remainder = m % 3 counts = [base_count, base_count, base_count] for i in range(remainder): counts...
from solution import generate_arithmetic_problems def test_generate_arithmetic_problems_5(): problems = generate_arithmetic_problems(5) assert len(problems) == 5 assert all('+' in problem or '-' in problem or '*' in problem for problem in problems) assert sum('+' in problem for problem in problems) in ...
[ "generate_arithmetic_problems" ]
[ "def generate_arithmetic_problems(m):" ]
Algorithm
medium
0.6
Algorithm_10253_I
test
### Scenario You are developing an application where one of the features includes automatically correcting the layout of words in given paragraphs. Specifically, you need to ensure that any consecutive spaces in the text are reduced to a single space while maintaining the order and content of the words. ### Problem St...
def normalize_spacing(paragraph: str) -> str: """ Takes in a string paragraph and reduces any consecutive spaces to a single space. Leading or trailing spaces are removed if present. """ return ' '.join(paragraph.split())
def test_normalize_spacing_multiple_internal_spaces(): assert normalize_spacing("This is a sample paragraph.") == "This is a sample paragraph." def test_normalize_spacing_trailing_leading_spaces(): assert normalize_spacing(" Leading and trailing spaces are tricky. ") == "Leading and trailing space...
[ "normalize_spacing" ]
[ "def normalize_spacing(paragraph):" ]
Algorithm
easy
0.9
Algorithm_10258_I
test
### Linked List: Detect Cycle Length #### Objective You are to implement a function that detects if a linked list contains a cycle. If a cycle is found, the function should return the length of the cycle. #### Task Write a function `detect_cycle_length` that identifies a cycle in a singly linked list and returns the ...
class ListNode: def __init__(self, value=0, next=None): self.value = value self.next = next def detect_cycle_length(head: ListNode) -> int: """ Detects if a cycle exists in the linked list and returns the length of the cycle. Arguments: head: The head node of the singly lin...
def test_empty_list(): assert detect_cycle_length(None) == -1 def test_single_node_no_cycle(): node = ListNode(1) assert detect_cycle_length(node) == -1 def test_single_node_with_cycle(): node = ListNode(1) node.next = node assert detect_cycle_length(node) == 1 def test_two_nodes_no_cycle(): ...
[]
[]
Algorithm
easy
1
Algorithm_10453_I
test
### Real-Time Stock Market Data Analysis #### Scenario: You are developing a stock market analysis tool that fetches real-time stock data and computes various financial metrics required by investment analysts. The system should be able to handle multiple stock symbols and provide functionalities such as calculating mo...
import pandas as pd from typing import List class StockMarketAnalyzer: def __init__(self): self.data = {} def fetch_data(self, stock_symbols: List[str], start_date: str, end_date: str) -> None: """ Mock function to fetch stock data for the given symbols and store in self.data. ...
import pytest from solution import StockMarketAnalyzer def test_fetch_data(): analyzer = StockMarketAnalyzer() analyzer.fetch_data(["AAPL"], "2022-01-01", "2022-01-31") assert "AAPL" in analyzer.data assert len(analyzer.data["AAPL"]) == 31 def test_calculate_moving_average_invalid_symbol(): analyz...
[]
[]
Algorithm
hard
0.1
Algorithm_10506_I
test
### Minimum Window Substring #### Background You are a developer working on a text processing application. One of the features you need to implement is the ability to find the smallest substring in a given text that contains all the characters from a given pattern. This is useful for various applications, such as keyw...
from collections import Counter def min_window_substring(s, t): """ Returns the smallest substring of `s` that contains all the characters in `t`. If no such substring exists, return an empty string. """ if not t or not s: return "" dict_t = Counter(t) required = len(dict_t) ...
def test_min_window_substring(): assert min_window_substring("ADOBECODEBANC", "ABC") == "BANC" assert min_window_substring("a", "a") == "a" assert min_window_substring("a", "aa") == "" assert min_window_substring("bba", "ab") == "ba" assert min_window_substring("cabwefgewcwaefgcf", "cae") == "cwae" ...
[ "min_window_substring" ]
[ "def min_window_substring(s, t):" ]
Algorithm
hard
0.2
Algorithm_10746_I
test
### Coding Question: You are tasked with implementing a function that returns the depth of the deepest leaf node in a binary tree. The function should use a depth-first search (DFS) approach to traverse the tree and find the maximum depth. **Function Signature:** ```python class TreeNode: def __init__(self, value...
class TreeNode: def __init__(self, value=0, left=None, right=None): self.value = value self.left = left self.right = right def max_depth(root: TreeNode) -> int: if not root: return 0 left_depth = max_depth(root.left) right_depth = max_depth(root.right) retu...
from solution import TreeNode, max_depth def test_empty_tree(): assert max_depth(None) == 0 def test_single_node_tree(): assert max_depth(TreeNode(1)) == 1 def test_right_skewed_tree(): root = TreeNode(1, right=TreeNode(2, right=TreeNode(3))) assert max_depth(root) == 3 def test_balanced_tree_depth_...
[]
[]
Algorithm
easy
1
Algorithm_11028_I
test
### Maze Path Finder #### Problem Statement Given a maze represented by a 2D list, write a function to find if there is a path from the start position to the end position. The start position is always at the top-left corner of the maze (i.e., at position (0, 0)), and the end position is always at the bottom-right corn...
def find_path(maze): rows, cols = len(maze), len(maze[0]) directions = [(1, 0), (0, 1), (-1, 0), (0, -1)] def is_valid(x, y): return 0 <= x < rows and 0 <= y < cols and maze[x][y] == 'O' def dfs(x, y, visited): if (x, y) in visited: return False if (x, y) ==...
def test_find_path(): maze1 = [ ['O', 'O', 'W', 'O'], ['W', 'O', 'W', 'O'], ['O', 'O', 'O', 'O'], ['O', 'W', 'O', 'O'] ] assert find_path(maze1) == True maze2 = [ ['O', 'W', 'W', 'O'], ['W', 'W', 'W', 'O'], ['O', 'O', 'O', 'W'], ['O', 'W',...
[ "find_path", "is_valid", "dfs" ]
[ "def find_path(maze):", "def is_valid(x, y):", "def dfs(x, y, visited):" ]
Algorithm
easy
0.7
Algorithm_11135_I
test
## Scenario: Given an array of integers, you are tasked with finding the length of the longest subarray where the difference between the maximum and minimum elements is less than or equal to a given integer, \( k \). This problem is crucial in scenarios where you need to evaluate the stability or variation within speci...
def longest_stable_subarray(arr, k): """ Find the length of the longest stable subarray where the difference between the max and min elements is <= k. >>> longest_stable_subarray([1, 3, 2, 4, 5], 3) 5 >>> longest_stable_subarray([10, 1, 2, 3, 2, 5, 6], 2) 4 >>> longest_stable_subarray([...
from solution import longest_stable_subarray def test_empty_array(): assert longest_stable_subarray([], 1) == 0 def test_single_element_array(): assert longest_stable_subarray([5], 0) == 1 def test_all_elements_equal(): assert longest_stable_subarray([2, 2, 2, 2], 0) == 4 def test_no_valid_subarray(): ...
[ "longest_stable_subarray" ]
[ "def longest_stable_subarray(arr, k):" ]
Algorithm
hard
0.1
Algorithm_11150_I
test
### Question Write a Python program to implement a K-Means clustering algorithm for a given dataset. The goal is to cluster the instances in the dataset into k clusters and evaluate the clustering performance using a silhouette score. ### Requirements: - Implement the K-Means clustering using `KMeans` from the scikit-...
import numpy as np import matplotlib.pyplot as plt from sklearn.cluster import KMeans from sklearn.datasets import make_blobs from sklearn.metrics import silhouette_score from sklearn.preprocessing import StandardScaler def load_dataset(samples: int = 300, centers: int = 3, cluster_std: float = 0.60) -> np.ndarray: ...
import pytest from solution import load_dataset, preprocess_data, kmeans_clustering def test_load_dataset(): data = load_dataset(samples=100, centers=3, cluster_std=0.60) assert data.shape == (100, 2) def test_preprocess_data(): data = np.array([[1, 2], [3, 4], [5, 6]]) processed_data = preprocess_dat...
[ "load_dataset", "preprocess_data", "kmeans_clustering", "main" ]
[ "def load_dataset(samples=300, centers=3, cluster_std=0.6):", "def preprocess_data(data):", "def kmeans_clustering(data):", "def main():" ]
Algorithm
easy
0.9
Algorithm_11347_I
test
### Advanced Problem: Finding the Missing Number in an Arithmetic Progression #### Scenario You are building a function to identify the missing number in an arithmetic progression (AP). An arithmetic progression is a sequence of numbers in which the difference of any two successive members is a constant. Given a list ...
from typing import List def find_missing_number(arr: List[int]) -> int: """ Finds the missing number in an arithmetic progression. The function uses binary search for an optimal O(log n) time complexity. """ n = len(arr) # Calculate the expected common difference total_diff = arr[-1] - arr[...
def test_find_missing_number(): assert find_missing_number([1, 3, 7, 9, 11]) == 5 assert find_missing_number([5, 10, 20, 25]) == 15 assert find_missing_number([10, 20, 30, 50, 60]) == 40 assert find_missing_number([0, 2, 4, 8, 10]) == 6 assert find_missing_number([-10, 0, 10, 30, 40]) == 20 def tes...
[ "find_missing_number" ]
[ "def find_missing_number(arr):" ]
Algorithm
hard
0.1
Algorithm_11385_I
test
### Problem Statement You are tasked with implementing a function to find the smallest substring in a given string `s` that contains all the distinct characters in `s`. The function should be efficient with respect to both time and space complexity. ### Objective Write a function `smallest_substring_with_all_chars(s: ...
def smallest_substring_with_all_chars(s: str) -> str: from collections import defaultdict, Counter # Find all distinct characters in the input string distinct_chars = set(s) num_distinct = len(distinct_chars) # Use a sliding window approach left = 0 min_len = float('inf') min_s...
from solution import smallest_substring_with_all_chars def test_example_1(): s = "abcda" result = smallest_substring_with_all_chars(s) assert result == "abcd" or result == "bcda" def test_example_2(): s = "abac" result = smallest_substring_with_all_chars(s) assert result == "abac" or result ==...
[ "smallest_substring_with_all_chars" ]
[ "def smallest_substring_with_all_chars(s):" ]
Algorithm
hard
0.2
Algorithm_11497_I
test
### Problem Statement You are tasked with implementing a function `find_arithmetic_triplet` that checks if there exists an arithmetic triplet in an array of integers. An arithmetic triplet consists of three elements (a, b, c) such that \(a\), \(b\), and \(c\) are in arithmetic sequence: \(b - a = c - b\). ### Input - ...
def find_arithmetic_triplet(nums): """ Check if there exists an arithmetic triplet in the array `nums`. An arithmetic triplet (a, b, c) satisfies the conditions: - a, b, c are distinct elements in nums - b - a == c - b Params: nums: List[int]: The input list of integers R...
def test_arithmetic_triplet_exists(): assert find_arithmetic_triplet([1, 5, 9, 3, 7]) == True def test_arithmetic_triplet_exists_multiple_triplets(): assert find_arithmetic_triplet([2, 4, 6, 8]) == True def test_arithmetic_triplet_does_not_exist(): assert find_arithmetic_triplet([1, 2, 4]) == False def t...
[ "find_arithmetic_triplet" ]
[ "def find_arithmetic_triplet(nums):" ]
Algorithm
medium
0.4
Algorithm_11520_I
test
### Finding Maximum XOR of a Pair in an Array Given an array of non-negative integers, write a function that returns the maximum XOR value of any two elements in the array. #### Function Signature ```python def find_max_xor(nums: list) -> int: pass ``` #### Input * `nums` (list of int): A list of non-negative in...
class TrieNode: def __init__(self): self.children = {} def find_max_xor(nums): # Create Trie data structure def insert(num): node = trie for bit in range(31, -1, -1): # 32 bits for a non-negative integer cur_bit = (num >> bit) & 1 if cur_bit not in node....
from solution import find_max_xor def test_example_1(): assert find_max_xor([3, 10, 5, 25, 2, 8]) == 28 def test_example_2(): assert find_max_xor([14, 70, 53, 83, 49, 91, 36, 80, 92, 51, 66, 70]) == 127 def test_example_3(): assert find_max_xor([8, 1, 2, 12, 7, 6]) == 15 def test_small_input(): asse...
[]
[]
Algorithm
medium
0.4
Algorithm_11550_I
test
### Context In numerical computing, understanding the behavior of basic operations on different data types is crucial. Floating-point numbers can sometimes lead to precision issues, and one must be cautious while performing equality checks. ### Problem Statement Write a function `approximately_equal(a: float, b: floa...
def approximately_equal(a: float, b: float, tol: float) -> bool: """ Checks if two floating-point numbers `a` and `b` are approximately equal within a given tolerance `tol`. Parameters: a (float): The first floating-point number. b (float): The second floating-point number. tol (float): The...
from solution import approximately_equal def test_approximately_equal_same_numbers(): assert approximately_equal(1.00001, 1.00001, 0.0001) == True def test_approximately_equal_close_numbers_within_tolerance(): assert approximately_equal(1.00001, 1.00002, 0.0001) == True def test_approximately_equal_numbers_o...
[ "approximately_equal" ]
[ "def approximately_equal(a, b, tol):" ]
Algorithm
easy
0.7
Algorithm_11577_I
test
You are required to define a function that formats and extracts specific details from a list of dictionary objects where each dictionary represents data about an employee. The function should also handle missing or incorrect data gracefully. 1. **Data Extraction**: - Extract the employee's full name, employee ID, ...
from typing import List, Dict def process_employee_data(employee_list: List[Dict[str, str]]) -> List[str]: formatted_employee_data = [] for employee in employee_list: try: first_name = employee["first_name"].capitalize() last_name = employee["last_name"].capitalize() ...
from solution import process_employee_data def test_process_employee_data_complete_records(): employees = [ {"first_name": "john", "last_name": "doe", "employee_id": "1234", "department": "engineering"}, {"first_name": "susan", "last_name": "ray", "employee_id": "12131", "department": "marketing"} ...
[ "process_employee_data" ]
[ "def process_employee_data(employee_list):" ]
Algorithm
medium
0.5
Algorithm_11743_I
test
**String Permutations Counter** You are tasked with creating a function that counts all the unique permutations of a given string. The function should return the number of distinct permutations that can be made from the characters of the string. ### Problem Statement Write a function `count_permutations(s: str) -> in...
from math import factorial from collections import Counter def count_permutations(s: str) -> int: """ Returns the count of unique permutations of the input string s. """ n = len(s) if n == 0: return 0 freq_count = Counter(s) denominator = 1 for count in freq_count.values(): ...
from solution import count_permutations def test_unique_characters(): assert count_permutations("abc") == 6 # 3! = 6 def test_duplicates(): assert count_permutations("aab") == 3 # 3! / (2! 1!) = 3 assert count_permutations("aaa") == 1 # 3! / 3! = 1 assert count_permutations("aabb") == 6 # 4! / (2!...
[ "count_permutations" ]
[ "def count_permutations(s):" ]
Algorithm
medium
0.6
Algorithm_11750_I
test
### Question: Employee Time Tracking System You are tasked with enhancing an existing employee time tracking system to improve its functionality and user experience. The current system tracks employee clock-in and clock-out times but lacks several key features. #### Your Task Extend the employee time tracking system ...
def track_time(clock_in: str, clock_out: str) -> dict[str, float]: from datetime import datetime def is_valid_time_format(time_str: str) -> bool: try: datetime.strptime(time_str, "%H:%M") return True except ValueError: return False if not is_valid_time_f...
import pytest from solution import track_time def test_track_time_normal_hours(): assert track_time("09:00", "17:00") == {'total_time': 8.0, 'overtime': 0.0} assert track_time("08:00", "18:30") == {'total_time': 10.5, 'overtime': 2.5} assert track_time("07:45", "19:00") == {'total_time': 11.25, 'overtime':...
[ "track_time", "is_valid_time_format" ]
[ "def track_time(clock_in, clock_out):", "def is_valid_time_format(time_str):" ]
Algorithm
medium
0.6
Algorithm_11780_I
test
### Genetic Algorithm: Optimization ### Scenario You are required to implement a simplified genetic algorithm to solve an optimization problem. The objective is to maximize a given fitness function over a binary search space. ### Task Write a Python function `genetic_algorithm` that performs a genetic algorithm to ma...
import random from typing import List, Callable, Tuple def genetic_algorithm( fitness_function: Callable[[List[int]], float], num_bits: int, population_size: int, generations: int, crossover_rate: float, mutation_rate: float ) -> Tuple[List[int], float]: def create_individual() -> List[int]...
from solution import genetic_algorithm def sample_fitness_function(individual: List[int]) -> float: return sum(individual) def test_genetic_algorithm(): num_bits = 10 population_size = 20 generations = 50 crossover_rate = 0.7 mutation_rate = 0.01 best_individual, best_fitness = genetic_al...
[ "genetic_algorithm", "create_individual", "mutate", "crossover", "tournament_selection" ]
[ "def genetic_algorithm(fitness_function, num_bits, population_size, generations, crossover_rate, mutation_rate):", "def create_individual():", "def mutate(individual, mutation_rate):", "def crossover(parent1, parent2, crossover_rate):", "def tournament_selection(population, k=3):" ]
Algorithm
medium
0.4
Algorithm_11792_I
test
### Problem Statement You are asked to implement a function that evaluates a postfix (Reverse Polish Notation) expression. A postfix expression is a mathematical notation in which every operator follows all of its operands. This format does not need any parentheses as long as operators have a fixed number of operands. ...
def evaluate_postfix(expression: str) -> float: stack = [] operators = {'+', '-', '*', '/'} if not expression: return 0 tokens = expression.split() for token in tokens: if token in operators: b = stack.pop() a = stack.pop() i...
from solution import evaluate_postfix def test_evaluate_postfix_basic(): assert evaluate_postfix("5 1 2 + 4 * + 3 -") == 14 def test_evaluate_postfix_single_operand(): assert evaluate_postfix("5") == 5 def test_evaluate_postfix_addition(): assert evaluate_postfix("3 4 +") == 7 def test_evaluate_postfix_...
[ "evaluate_postfix" ]
[ "def evaluate_postfix(expression):" ]
Algorithm
hard
0.2
Algorithm_11822_I
test
### Problem Description You are given a non-empty list of integers representing the heights of bar graphs. Write a function that computes the maximum rectangular area possible in these bar graphs, where the width of each bar is 1 unit. Each bar’s height is given in the list. ### Function Signature ```python def larges...
def largest_rectangle_area(heights: list) -> int: stack = [] max_area = 0 heights.append(0) # Append 0 to heights to flush remaining heights in stack at the end for i, h in enumerate(heights): while stack and heights[i] < heights[stack[-1]]: height = heights[stack.pop()] ...
def test_largest_rectangle_area(): assert largest_rectangle_area([2, 1, 5, 6, 2, 3]) == 10 assert largest_rectangle_area([2, 4]) == 4 assert largest_rectangle_area([6, 2, 5, 4, 5, 1, 6]) == 12 assert largest_rectangle_area([1, 3, 2, 1, 2]) == 5 assert largest_rectangle_area([2, 1, 2]) == 3 asser...
[ "largest_rectangle_area" ]
[ "def largest_rectangle_area(heights):" ]
Algorithm
medium
0.4
Algorithm_11856_I
test
### Question: Building an Interactive Command-Line To-Do Application #### Context You are asked to develop an interactive command-line to-do application in Python that allows users to manage their tasks efficiently. The application should handle adding, viewing, editing, and deleting tasks, as well as saving and loadi...
import json class ToDoApp: def __init__(self): self.tasks = [] self.next_id = 1 def add_task(self, description: str) -> None: """ Adds a new task to the list with a unique ID and given description. """ task = {"id": self.next_id, "description": descripti...
from solution import ToDoApp def test_add_task(): app = ToDoApp() app.add_task("Test task") assert len(app.tasks) == 1 assert app.tasks[0]["description"] == "Test task" def test_view_tasks_empty(): app = ToDoApp() assert app.view_tasks() == "No tasks available." def test_view_tasks():...
[]
[]
Algorithm
easy
0.889
Algorithm_11886_I
test
### Tree Traversal Verification Challenge #### Background: Tree data structures are a fundamental concept in computer science. They have numerous applications, including representing hierarchical data, managing sorted lists of data, and facilitating search operations. One particular aspect of trees is their traversal ...
def verify_traversals(in_order, pre_order, post_order): if not in_order or not pre_order or not post_order: return in_order == pre_order == post_order == [] if len(in_order) != len(pre_order) or len(in_order) != len(post_order): return False def build_tree_from_in_pre(pre_order, in_order_m...
from solution import verify_traversals def test_verify_traversals_example1(): assert verify_traversals( [4, 2, 5, 1, 6, 3, 7], [1, 2, 4, 5, 3, 6, 7], [4, 5, 2, 6, 7, 3, 1] ) == True def test_verify_traversals_example2(): assert verify_traversals( [4, 2, 5, 1, 6, 3, 7], ...
[ "verify_traversals", "build_tree_from_in_pre", "get_post_order_from_in_pre" ]
[ "def verify_traversals(in_order, pre_order, post_order):", "def build_tree_from_in_pre(pre_order, in_order_map, pre_start, pre_end, in_start, in_end):", "def get_post_order_from_in_pre(pre_order, in_order_map, pre_start, pre_end, in_start, in_end):" ]
Algorithm
hard
0.1
Algorithm_12070_I
test
### Closest Pair of Points **Problem Statement:** Given a list of `n` points on the 2D plane, where each point is represented as a tuple of two integers `(x, y)`, write a function `closest_pair_of_points(points: list[tuple[int, int]]) -> float` that finds and returns the minimum distance between any two points from t...
import math def euclidean_distance(p1, p2): return math.sqrt((p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2) def closest_pair_recursive(points_sorted_by_x, points_sorted_by_y): # Base case if len(points_sorted_by_x) <= 3: min_dist = float('inf') for i in range(len(points_sorted_by_x)): ...
import pytest from solution import closest_pair_of_points def test_closest_pair_basic(): assert math.isclose(closest_pair_of_points([(0, 0), (1, 1), (4, 5), (2, 2)]), 1.4142135623730951, rel_tol=1e-9) def test_closest_pair_less_than_two_points(): with pytest.raises(ValueError, match="At least two points are r...
[ "euclidean_distance", "closest_pair_recursive", "closest_pair_of_points" ]
[ "def euclidean_distance(p1, p2):", "def closest_pair_recursive(points_sorted_by_x, points_sorted_by_y):", "def closest_pair_of_points(points):" ]
Algorithm
medium
0.6
Algorithm_12151_I
test
You are working on an inventory management system that helps businesses track their stock levels and reorder products when necessary. The system should send an email notification when the stock level of an item falls below the reorder threshold. To ensure your code sends the correct email, you should write unit tests t...
def send_email_to_supplier(recipient, subject, body): # This function would typically send an email pass def send_reorder_notification(recipient, item_name): """ Send a reorder notification email to a supplier. Args: recipient (str): The email of the recipient. item_name (str): The nam...
import pytest def fake_send_email(recipient, subject, body): """ A fake email sending function to mock sending email and return a controlled response. """ if not recipient or "@" not in recipient: return {"status": "failed", "message": "Invalid recipient email format"} if not subject: ...
[ "send_email_to_supplier", "send_reorder_notification" ]
[ "def send_email_to_supplier(recipient, subject, body):", "def send_reorder_notification(recipient, item_name):" ]
Algorithm
medium
0.5
Algorithm_12198_I
test
### Coding Assessment Question **Problem Statement**: Given an array of integers, your task is to sort the array according to the frequency of elements. The sorting should be done in such a way that the elements that have higher frequency come first. If two elements have the same frequency, the smaller element should ...
from typing import List from collections import Counter def frequency_sort(arr: List[int]) -> List[int]: """ Sorts the array according to the frequency of elements in descending order. If two elements have the same frequency, the smaller element should precede the larger one. """ # Count the freque...
from solution import frequency_sort def test_frequency_sort_example(): assert frequency_sort([4, 6, 2, 2, 6, 4, 4, 4]) == [4, 4, 4, 4, 2, 2, 6, 6] def test_frequency_sort_empty_array(): assert frequency_sort([]) == [] def test_frequency_sort_single_element(): assert frequency_sort([1]) == [1] def test_f...
[ "frequency_sort" ]
[ "def frequency_sort(arr):" ]
Algorithm
hard
0.1
Algorithm_12334_I
test
### Problem Statement **Context:** You are given a string containing a mix of digits, letters, and other characters. Your task is to identify and sum up all the "hidden" integers within the string. An integer is defined as any consecutive sequence of numerical digits within the string. The final result should be the s...
import re def sum_hidden_integers(s: str) -> int: """ Calculates the sum of hidden integers within the given string. Args: s (str): The input string potentially containing hidden integers. Returns: int: The sum of all hidden integers found within the string. """ # Find all sequences o...
from solution import sum_hidden_integers def test_no_digits(): assert sum_hidden_integers("noDigits") == 0 def test_single_number(): assert sum_hidden_integers("abc123xyz") == 123 def test_multiple_numbers(): assert sum_hidden_integers("a1b2c345") == 348 def test_mixed_with_letters(): assert sum_hid...
[ "sum_hidden_integers" ]
[ "def sum_hidden_integers(s):" ]
Algorithm
easy
1
Algorithm_12433_I
test
### Problem Statement You are developing a system for analyzing and categorizing text documents. One common task in this process is to determine the most frequently occurring words in a document after removing a set of "stop words." Stop words are common words that are often removed because they are considered unimpor...
from typing import List from collections import Counter def most_frequent_words(document: str, stop_words: List[str]) -> List[str]: # Convert document to lowercase and split into words words = document.lower().split() # Filter out the stop words filtered_words = [word for word in words if word not...
from solution import most_frequent_words def test_example_1(): document = "the quick brown fox jumps over the lazy dog" stop_words = ["the", "over"] assert most_frequent_words(document, stop_words) == ["brown", "dog", "fox", "jumps", "lazy", "quick"] def test_example_2(): document = "hello world hello...
[ "most_frequent_words" ]
[ "def most_frequent_words(document, stop_words):" ]
Algorithm
easy
0.8
Algorithm_12608_I
test
### Scenario You are responsible for developing a functionality within a text editor that allows users to perform basic find-and-replace operations on their documents. The implementation needs to handle multiple occurrences of the search string and perform the replacement efficiently. Additionally, the users should be ...
def find_and_replace(text, search, replace, case_sensitive=True): """ Replaces all occurrences of search in text with replace. Handles case-insensitive replacements based on the case_sensitive flag. """ if not text or not search: return text # Nothing to replace if case_sensitive: ...
from solution import find_and_replace def test_find_and_replace_case_sensitive(): text = "Hello World! Welcome to the world of programming." search = "world" replace = "universe" result = find_and_replace(text, search, replace) assert result == "Hello World! Welcome to the universe of programming."...
[ "find_and_replace" ]
[ "def find_and_replace(text, search, replace, case_sensitive=True):" ]
Algorithm
hard
0.1
Algorithm_12635_I
test
### Question: Implementing Depth-First Search for a Graph You need to implement the Depth-First Search (DFS) algorithm to traverse a graph. The function should explore all vertices of a graph starting from a specified source vertex and return the order of visited vertices. ### Scenario In a network analysis tool, you...
def depth_first_search(graph, start_vertex): """ Perform a Depth-First Search (DFS) on the graph starting from the given vertex. Parameters: graph (dict): A dictionary representation of an undirected graph where the keys are vertex identifiers and the values are lists of adjacent vertices. star...
def test_single_node_graph(): graph = {0: []} assert depth_first_search(graph, 0) == [0] def test_simple_connected_graph(): graph = { 0: [1, 2], 1: [0, 3, 4], 2: [0], 3: [1], 4: [1] } assert depth_first_search(graph, 0) == [0, 1, 3, 4, 2] def test_simple_con...
[ "depth_first_search" ]
[ "def depth_first_search(graph, start_vertex):" ]
Algorithm
hard
0.3
Algorithm_12773_I
test
### Problem Statement You are given an array of integers where some integers appear twice and others appear once. Your task is to implement a function that returns all the distinct integers that appear twice in the array. ### Requirements * Implement a function `find_duplicates(nums: List[int]) -> List[int]` that ret...
from typing import List def find_duplicates(nums: List[int]) -> List[int]: """ Returns a sorted list of distinct integers that appear exactly twice in the given array. """ num_count = {} # Count the occurrences of each number for num in nums: if num in num_count: num_co...
from solution import find_duplicates def test_find_duplicates(): assert find_duplicates([4, 3, 2, 7, 8, 2, 3, 1]) == [2, 3] assert find_duplicates([1, 1, 2]) == [1] assert find_duplicates([]) == [] assert find_duplicates([1, 2, 3, 4, 5]) == [] assert find_duplicates([10, 10, 20, 20, 30, 30, 30]) ==...
[ "find_duplicates" ]
[ "def find_duplicates(nums):" ]
Algorithm
hard
0.2
Algorithm_13036_I
test
### Problem Statement You are developing a software for inventory management in a warehouse. The warehouse deals with a variety of items, each of which can be categorized into different types. Write a program that: 1. Takes a list of items where each item is represented by a tuple containing `item_id`, `category`, and...
def aggregate_inventory(items): """ Aggregates the total quantity of items for each category and returns a sorted list of categories with their total quantities in descending order of quantities. Raises a ValueError if any of the quantities are non-positive. """ from collections import defa...
import pytest from solution import aggregate_inventory def test_aggregate_inventory_valid_input(): items = [ ("item_1", "electronics", 10), ("item_2", "furniture", 5), ("item_3", "electronics", 4), ("item_4", "grocery", 15), ("item_5", "furniture", 5) ] expected_outp...
[ "aggregate_inventory" ]
[ "def aggregate_inventory(items):" ]
Algorithm
easy
1
Algorithm_13074_I
test
### Scenario A library is automating the management of its book borrowing system. To better allocate the available books, the librarian wants to optimize the distribution so that the maximum number of books can be borrowed while minimizing the waiting period for the borrowers. Each borrower has a list of books they wis...
def optimize_borrowing(borrower_pref, available_books): """ Optimize the borrowing so that maximum number of borrowers get a book from their preference list. Parameters: borrower_pref (list[list[int]]): List containing the book preferences of each borrower. available_books (list[bool]): List in...
from solution import optimize_borrowing def test_optimize_borrowing_example(): borrower_pref = [[0, 1, 2], [2, 0, 1], [1, 2]] available_books = [True, False, True] assert optimize_borrowing(borrower_pref, available_books) in [[0, 2, -1], [2, 0, -1]] def test_optimize_borrowing_no_pref(): borrower_pref...
[ "optimize_borrowing" ]
[ "def optimize_borrowing(borrower_pref, available_books):" ]
Algorithm
medium
0.5
Algorithm_13075_I
test
### Binary Search Tree (BST) Level Order Traversal A Binary Search Tree (BST) is a node-based binary tree data structure where each node has at most two children referred to as the left child and the right child. For this question, you need to implement the function which performs a level-order traversal on a BST. A l...
from typing import List, Optional from collections import deque class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def insert_into_bst(root: Optional[TreeNode], val: int) -> TreeNode: if root is None: return Tree...
from solution import bst_level_order_traversal def test_bst_level_order_traversal_example1(): assert bst_level_order_traversal([10, 6, 15, 3, 8, 12, 18]) == [[10], [6, 15], [3, 8, 12, 18]] def test_bst_level_order_traversal_example2(): assert bst_level_order_traversal([7, 3, 9, 1, 4, 8, 10]) == [[7], [3, 9], ...
[]
[]
Algorithm
hard
0.3
Algorithm_13084_I
test
**Developing a Custom Sort Algorithm for Optimized Item Retrieval** You are working on a retail application that requires frequent retrieval and display of items based on various priority rules. Currently, items are fetched from a database and displayed in the order they are retrieved. To enhance user experience, the ...
from typing import List, Dict, Any def custom_sort_items(items: List[Dict[str, Any]]) -> List[Dict[str, Any]]: """ Sort items based on custom priority rules. Parameters: - items: List[Dict[str, Any]]: A list of items, where each item is represented as a dictionary. Returns: - List[Dict[str, A...
# Assuming the custom_sort_items function is defined in the file solution.py from solution import custom_sort_items def test_custom_sort_items_varied_popularity(): items = [ {'name': 'Item1', 'popularity': 50, 'price': 30.00, 'availability': True}, {'name': 'Item2', 'popularity': 300, 'price': 20....
[ "custom_sort_items" ]
[ "def custom_sort_items(items):" ]
Algorithm
hard
0.1
Algorithm_13091_I
test
### Coding Question: Implement a Rate Limiter for an API #### Objective: Design and implement a rate limiter function for an API. The function should ensure that a given client does not exceed a specified number of requests in a given time window. If the limit is breached, the function should return an error indicatin...
import time from collections import defaultdict, deque class RateLimiter: def __init__(self): self.requests = defaultdict(deque) def rate_limiter(self, client_id: str, max_requests: int, window: int) -> bool: current_time = time.time() if client_id not in self.requests: sel...
import time from solution import RateLimiter def test_single_client_rate_limit(): limiter = RateLimiter() # Test with a max of 5 requests in 60 seconds assert limiter.rate_limiter("client_1", 5, 60) == True assert limiter.rate_limiter("client_1", 5, 60) == True assert limiter.rate_limiter("cli...
[]
[]
Algorithm
medium
0.6
Algorithm_13167_I
test
### Inventory Management System Optimization You are responsible for maintaining the backend of an inventory management system used by a large retail store. Recently, there have been issues with performance, particularly in the function that updates inventory levels after processing bulk sales transactions. Your task ...
def update_inventory_levels(inventory: dict[str, int], transactions: list[tuple[str, int]]) -> None: """ Updates the inventory levels based on a list of sales transactions. Args: inventory (dict[str, int]): The current inventory levels. transactions (list[tuple[str, int]]): The list of transact...
def test_update_inventory_levels(): inventory = { "product_001": 50, "product_002": 30, "product_003": 100 } transactions = [ ("product_001", 5), ("product_002", 3), ("product_003", 10), ("product_004", 2), ("product_001", 1) ] update_i...
[ "update_inventory_levels" ]
[ "def update_inventory_levels(inventory, transactions):" ]
Algorithm
easy
1
Algorithm_13307_I
test
### Color Palette Optimization **Context**: You are developing a software for a digital artist who frequently changes the color palette in their work. The artist wishes to have their colors sorted in a way that they transition smoothly from one hue to another to facilitate better artistic workflow. **Task**: Write a...
import math def color_distance(color1, color2): """ Helper function to calculate the Euclidean distance between two RGB colors. """ return math.sqrt((color2[0] - color1[0]) ** 2 + (color2[1] - color1[1]) ** 2 + (color2[2] - color1[2]) ** 2) def smooth_color_sort(colors): """ Sorts a list of RG...
from solution import smooth_color_sort, color_distance def test_color_distance(): assert color_distance((0, 0, 0), (0, 0, 0)) == 0 assert color_distance((0, 0, 0), (255, 255, 255)) == math.sqrt(3 * (255 ** 2)) assert color_distance((255, 0, 0), (0, 255, 0)) == math.sqrt(255 ** 2 + 255 ** 2) assert colo...
[ "color_distance", "smooth_color_sort" ]
[ "def color_distance(color1, color2):", "def smooth_color_sort(colors):" ]
Algorithm
hard
0.2
Algorithm_13317_I
test
### Question: Matrix Diagonal Sum and Trace You are provided with two individual tasks. Write two functions to achieve the following: #### Task 1: Sum of Matrix Diagonal Write a function `sum_of_diagonal(matrix: List[List[int]]) -> int` that calculates the sum of all the elements on the main diagonal of a given squar...
def sum_of_diagonal(matrix: list) -> int: if not matrix or any(len(row) != len(matrix) for row in matrix): raise ValueError("Input must be a non-empty square matrix.") return sum(matrix[i][i] for i in range(len(matrix))) def matrix_trace(matrix: list) -> int: return sum_of_diagonal(matrix)
import pytest from solution import sum_of_diagonal, matrix_trace def test_sum_of_diagonal(): assert sum_of_diagonal([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) == 15 assert sum_of_diagonal([[5, 0, 0], [0, 5, 0], [0, 0, 5]]) == 15 assert sum_of_diagonal([[2, 1], [1, 2]]) == 4 def test_matrix_trace(): assert mat...
[ "sum_of_diagonal", "matrix_trace" ]
[ "def sum_of_diagonal(matrix):", "def matrix_trace(matrix):" ]
Algorithm
easy
1
Algorithm_13353_I
test
### Question #### Scenario: You are developing a system to manage a collection of files and their related operations. One essential aspect of this system is organizing the files in such a way that allows for quick retrieval, insertion, and removal. To achieve this, you decide to implement a Min-Heap data structure, wh...
def insert(heap, new_value): """ Inserts a new_value into the Min-Heap and maintains the heap property. """ heap.append(new_value) _bubble_up(heap, len(heap) - 1) def remove_min(heap): """ Removes and returns the minimum element from the Min-Heap while maintaining the heap property. """...
from solution import insert, remove_min, heapify def test_heapify(): assert heapify([15, 10, 25, 6, 14, 20, 60]) == [6, 10, 20, 15, 14, 25, 60] assert heapify([3, 1, 2]) == [1, 3, 2] assert heapify([]) == [] assert heapify([1]) == [1] def test_insert(): heap = heapify([15, 10, 25, 6, 14, 20, 60]) ...
[ "insert", "remove_min", "heapify", "_bubble_up", "_bubble_down" ]
[ "def insert(heap, new_value):", "def remove_min(heap):", "def heapify(values):", "def _bubble_up(heap, index):", "def _bubble_down(heap, index):" ]
Algorithm
medium
0.5
End of preview. Expand in Data Studio

KoDCode preference-distillation inputs

Inputs for the two-stage preference-distillation pipeline: sequence-level knowledge distillation on verified teacher answers, followed by DPO in which only the rejected response varies by source. These files hold the prompt side, the chosen side, and the evaluation set. They contain no rejected responses and no model checkpoints, so any reject source can be regenerated against them.

Files

File Rows Contents
data/sft_train_76k.jsonl 75,752 SeqKD stage. Fields: id, prompt, answer, stage.
data/pref_prompts_24k.jsonl 24,248 Preference stage prompts and chosen answers. Fields: id, prompt, answer, difficulty, prompt_chat_template, stage.
data/heldin_eval_5000.jsonl 5,000 Held-in evaluation. Fields: id, prompt, answer, test, entry_points, entry_declarations, gpt_difficulty, gpt_pass_percentage, subset, stage.

answer is the verified teacher response and serves as the DPO chosen response. It is byte-identical across every reject source in the original experiments. The three id sets are disjoint: no prompt appears in more than one file.

test in the evaluation file is the pytest suite used to score a generated solution. A problem counts as solved only when every test passes.

Known gaps

Training-prompt tests are not included. Verifying that a generated candidate is a genuine failure requires the pytest suite for each of the 24,248 preference prompts. Those suites are not in this release. Without them a reject source cannot be filtered to strict failures, which the original pipeline requires. The missing data is a 24,248-row table keyed by id carrying test, entry_points, and entry_declarations, the same fields the evaluation file already exposes.

prompt_chat_template is model-specific. That field holds the prompt rendered with a Qwen2.5 chat template. Training and generation should use the raw prompt field with the target model's own template. To drop the field:

python -c "
import json
with open('data/pref_prompts_24k.jsonl') as f, open('out.jsonl','w') as g:
    for line in f:
        r = json.loads(line); r.pop('prompt_chat_template', None)
        g.write(json.dumps(r) + '\n')
"

Intended use

Reproducing or extending the reject-source comparison: hold the prompt set and the chosen answers fixed, vary only where the rejected response comes from, and measure held-in pass rate. Reported metrics in the source work are greedy pass@1 and the mean of four samples at temperature 0.6 with top-p 1.0.

Provenance and licensing

Derived from KodCode-V1, which is released under CC BY-NC 4.0. This subset inherits that license, so it is for non-commercial use only. The prompt, test, entry_points, and entry_declarations fields originate there.

The answer field holds responses generated by GPT-4o, used as the teacher and the DPO chosen response. Downstream users should check OpenAI's terms for their own intended use.

Checksums

See checksums.json for SHA-256 digests, byte sizes, and row counts.

Downloads last month
62