Dataset Viewer
Auto-converted to Parquet Duplicate
task_id
stringlengths
12
13
domain
stringclasses
2 values
prompt
stringlengths
86
1.17k
content
stringlengths
73
1.09k
verifier
stringclasses
2 values
train-code-1
code
Write Python second_largest(nums) returning second distinct largest integer in nums, or None if fewer than 2 distinct values
def second_largest(nums): unique_nums = set(nums) if len(unique_nums) < 2: return None sorted_nums = sorted(unique_nums, reverse=True) return sorted_nums[1]
code-unittest
train-code-2
code
Write Python chunk_list(lst, size) splitting lst into sublists of length size (last may be shorter); raise ValueError if size <= 0
def chunk_list(lst, size): if size <= 0: raise ValueError("Size must be greater than 0") return [lst[i:i + size] for i in range(0, len(lst), size)]
code-unittest
train-code-4
code
Write Python roman_to_int(s) converting a standard uppercase Roman numeral string (I..MMMCMXCIX) to int
def roman_to_int(s): roman_map = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000} total = 0 prev_value = 0 for char in reversed(s): value = roman_map[char] if value < prev_value: total -= value else: total += value prev_value ...
code-unittest
train-code-5
code
Write Python int_to_roman(num) converting integer 1..3999 to uppercase Roman numeral string
def int_to_roman(num): val = [ 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 ] syms = [ "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I" ] roman_num = '' i = 0 while num > 0: for _ in ...
code-unittest
train-code-6
code
Write Python valid_ipv4(ip) returning True iff ip is valid dotted IPv4 (4 decimal octets 0..255 with no leading zeros)
def valid_ipv4(ip): parts = ip.split('.') if len(parts) != 4: return False for part in parts: if not part.isdigit(): return False num = int(part) if num < 0 or num > 255 or (len(part) > 1 and part[0] == '0'): return False return True
code-unittest
train-code-7
code
Write Python rotate_matrix(m) returning a new NxN 2D list rotated 90 degrees clockwise
def rotate_matrix(m): return [list(reversed(col)) for col in zip(*m)]
code-unittest
train-code-8
code
Write Python merge_intervals(intervals) merging overlapping (start, end) tuples and returning sorted list of (start, end) tuples
def merge_intervals(intervals): if not intervals: return [] intervals.sort(key=lambda x: x[0]) merged = [intervals[0]] for current in intervals[1:]: last_merged = merged[-1] if current[0] <= last_merged[1]: merged[-1] = (last_merged[0], max(last_mer...
code-unittest
train-code-10
code
Write Python rle_decode(pairs) expanding list of (char, count) tuples into concatenated string
def rle_decode(pairs): return ''.join(char * count for char, count in pairs)
code-unittest
train-code-11
code
Write Python parse_qs_simple(qs) parsing query string like 'a=1&b=2&a=3' into dict[str, list[str]] preserving values order (ignore empty segments)
from urllib.parse import parse_qs def parse_qs_simple(qs): parsed = {} for key, value in parse_qs(qs).items(): if len(value) == 0: continue if key not in parsed: parsed[key] = [] parsed[key].extend(value) return parsed
code-unittest
train-code-12
code
Write Python flatten_dict(d) flattening nested dicts into single dict with dotted string keys (empty dict leaves nothing)
def flatten_dict(d, parent_key='', sep='.'): items = [] for k, v in d.items(): new_key = f"{parent_key}{sep}{k}" if parent_key else k if isinstance(v, dict): items.extend(flatten_dict(v, new_key, sep=sep).items()) else: items.append((new_key, v)) return dict(i...
code-unittest
train-code-13
code
Write Python count_islands(grid) counting 4-connected components of '1' in a 2D list of '0'/'1' strings
def count_islands(grid): if not grid or not grid[0]: return 0 rows, cols = len(grid), len(grid[0]) visited = [[False] * cols for _ in range(rows)] def dfs(r, c): if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] == '0' or visited[r][c]: return visite...
code-unittest
train-code-14
code
Write Python sliding_window_max(nums, k) returning list of maximums for each contiguous window of size k
def sliding_window_max(nums, k): if not nums or k <= 0: return [] result = [] deque = [] for i in range(len(nums)): while deque and nums[i] >= nums[deque[-1]]: deque.pop() deque.append(i) if deque[0] == i - k: deque.popl...
code-unittest
train-code-15
code
Write Python lcm_list(nums) returning least common multiple of non-empty list of positive ints
from math import gcd def lcm(a, b): return abs(a*b) // gcd(a, b) def lcm_list(nums): result = nums[0] for num in nums[1:]: result = lcm(result, num) return result
code-unittest
train-code-16
code
Write Python prime_factors(n) returning sorted list of prime factors of integer n >= 2 (with multiplicity)
def prime_factors(n): i = 2 factors = [] while i * i <= n: if n % i: i += 1 else: n //= i factors.append(i) if n > 1: factors.append(n) return sorted(factors)
code-unittest
train-code-18
code
Write Python camel_to_snake(s) converting lowerCamelCase or PascalCase identifier to lower_snake_case
import re def camel_to_snake(s): s = re.sub('(.)([A-Z])', r'\1_\2', s) return s.lower() # Test the function print(camel_to_snake("example")) # Output: example print(camel_to_snake("Example")) # Output: example print(camel_to_snake("EXAMPLE")) # Output: example print(camel_to_snake("camelCase")) # Output: ...
code-unittest
train-code-19
code
Write Python longest_unique_substr(s) returning integer length of longest substring without repeating characters
def longest_unique_substr(s): n = len(s) ans = 0 i = j = 0 char_set = set() while i < n and j < n: if s[j] not in char_set: char_set.add(s[j]) j += 1 ans = max(ans, j - i) else: char_set.remove(s[i]) i += 1 ret...
code-unittest
train-code-20
code
Write Python eval_postfix_simple(tokens) evaluating list of string tokens with integer literals and binary +, -, * operators
def eval_postfix_simple(tokens): stack = [] for token in tokens: if token.isdigit(): stack.append(int(token)) else: b = stack.pop() a = stack.pop() if token == '+': stack.append(a + b) elif token == '-': ...
code-unittest
train-code-21
code
Write Python csv_split_line(line) splitting single CSV row handling double-quoted fields containing commas (strip surrounding quotes)
import csv def csv_split_line(line): reader = csv.reader([line], quotechar='"', escapechar='\\') return next(reader)
code-unittest
train-code-22
code
Write Python spiral_generate(n) returning NxN matrix filled with 1..n*n in clockwise spiral order
def spiral_generate(n): result = [[0] * n for _ in range(n)] num = 1 top, bottom, left, right = 0, n - 1, 0, n - 1 while num <= n * n: for i in range(left, right + 1): result[top][i] = num num += 1 top += 1 for i in range(top, bottom + 1): ...
code-unittest
train-code-23
code
Write Python top_k_words(text, k) returning list of top k lowercased words ordered by count descending then alphabetically
from collections import Counter def top_k_words(text, k): words = text.lower().split() word_counts = Counter(words) top_k = sorted(word_counts.items(), key=lambda x: (-x[1], x[0])) return [word for word, count in top_k[:k]]
code-unittest
train-code-24
code
Write Python decode_base26(s) converting Excel column name ('A'->1, 'Z'->26, 'AA'->27, 'AB'->28) to positive integer
def decode_base26(s): return sum((ord(c) - ord('A') + 1) * (26 ** i) for i, c in enumerate(reversed(s)))
code-unittest
train-code-9
code
Write Python two_sum(nums, target) returning sorted tuple (i, j) with i < j where nums[i]+nums[j]==target, or None
def two_sum(nums, target): num_dict = {} for i, num in enumerate(nums): complement = target - num if complement in num_dict: return tuple(sorted((num_dict[complement], i))) num_dict[num] = i return None
code-unittest
train-hard-1
code
Write Python dijkstra_min_cost(n, edges, src, dst) finding minimum weight from src to dst in a directed graph with vertices 0..n-1 and edges (u, v, w) with w >= 0, returning -1 if unreachable
import heapq def dijkstra_min_cost(n, edges, src, dst): graph = [[] for _ in range(n)] for u, v, w in edges: graph[u].append((v, w)) dist = [float('inf')] * n dist[src] = 0 pq = [(0, src)] while pq: current_dist, u = heapq.heappop(pq) if current_dist > dist[u]:...
code-unittest
train-hard-3
code
Write Python canonical_unix_path(path) simplifying a POSIX path resolving '.', '..', multiple slashes, and no trailing slash unless root '/'
import os def canonical_unix_path(path): return os.path.normpath(path)
code-unittest
train-hard-5
code
Write Python regex_dot_star(pattern, text) returning True iff full text matches regex supporting '.' (any single char) and '*' (zero or more of preceding element)
import re def regex_dot_star(pattern, text): return bool(re.fullmatch(pattern, text))
code-unittest
train-hard-6
code
Write Python max_histogram_rect(heights) returning maximum rectangular area in bar histogram given list of non-negative ints
def max_histogram_rect(heights): stack = [] max_area = 0 index = 0 while index < len(heights): if not stack or heights[index] >= heights[stack[-1]]: stack.append(index) index += 1 else: top_of_stack = stack.pop() area = (heights[top_of...
code-unittest
train-hard-7
code
Write Python is_bipartite_graph(n, edges) returning True iff undirected graph on 0..n-1 with edge list (u, v) is 2-colorable
def is_bipartite_graph(n, edges): from collections import defaultdict, deque graph = defaultdict(list) for u, v in edges: graph[u].append(v) graph[v].append(u) color = [-1] * n def bfs(start): queue = deque([start]) color[start] = 0 whi...
code-unittest
train-hard-8
code
Write Python min_meeting_rooms(intervals) returning minimum concurrent rooms needed for half-open [start, end) tuples
def min_meeting_rooms(intervals): events = [] for start, end in intervals: events.append((start, 1)) events.append((end, -1)) events.sort() current_rooms = 0 max_rooms = 0 for _, event in events: current_rooms += event max_rooms = max(max_rooms, current_...
code-unittest
train-hard-9
code
Write Python levenshtein_dist(a, b) returning minimum insert/delete/replace operations to convert string a to b
def levenshtein_dist(a, b): m, n = len(a), len(b) dp = [[0] * (n + 1) for _ in range(m + 1)] for i in range(m + 1): dp[i][0] = i for j in range(n + 1): dp[0][j] = j for i in range(1, m + 1): for j in range(1, n + 1): if a[i - 1] == b[j - 1]: ...
code-unittest
train-hard-11
code
Write Python n_queens_solutions(n) returning integer count of distinct valid n-queens placements on n x n board
def n_queens_solutions(n): def is_safe(board, row, col): # Check this row on left side for i in range(col): if board[row][i] == 1: return False # Check upper diagonal on left side for i, j in zip(range(row, -1, -1), range(col, -1, -1)): ...
code-unittest
train-hard-13
code
Write Python matrix_spiral_read(mat) returning flat list of elements in an R x C rectangular 2D list in clockwise spiral order (handle empty matrix)
def matrix_spiral_read(mat): if not mat or not mat[0]: return [] result = [] while mat: result += mat.pop(0) if mat and mat[0]: for row in mat: result.append(row.pop()) if mat: result += mat.pop()[::-1] if mat and mat[0]: ...
code-unittest
train-hard-14
code
Write Python word_ladder_steps(begin, end, word_list) returning minimum number of words in shortest transformation sequence from begin to end changing 1 char at a time using word_list (including begin & end in count), or 0 if impossible
from collections import deque def word_ladder_steps(begin, end, word_list): word_set = set(word_list) if end not in word_set: return 0 queue = deque([(begin, 1)]) visited = {begin} while queue: current_word, steps = queue.popleft() if current_word == end: ...
code-unittest
train-hard-16
code
Write Python sudoku_partial_valid(board) returning True iff 9x9 list of single-char strings ('1'..'9' or '.') has no duplicate digits in any row, column, or 3x3 subgrid
def sudoku_partial_valid(board): def has_duplicates(lst): seen = set() for item in lst: if item != '.' and item in seen: return True seen.add(item) return False # Check rows for row in board: if has_duplicates(row): return ...
code-unittest
train-posix-3
posix
Fix pq/item.py and pq/queue.py: higher integer priority dequeues first, and equal-priority items must dequeue strictly in FIFO insertion order. Repository files: ### FILE: pq/item.py ```python def sort_key(priority: int, seq: int, name: str): return (priority, name) ``` ### FILE: pq/queue.py ```python import hea...
### FILE: pq/queue.py ```python import heapq from pq.item import sort_key class TaskQueue: def __init__(self): self.h = [] self.seq = 0 def push(self, name: str, priority: int) -> None: self.seq += 1 heapq.heappush(self.h, (-priority, self.seq, name)) def pop(self) -> str:...
posix-pytest
train-posix-4
posix
Fix tmpl/vars.py and tmpl/render.py: support ${KEY:-default} fallback syntax when KEY is missing or empty string, and render cleanly in single pass without double-expanding substituted values. Repository files: ### FILE: tmpl/render.py ```python import re from tmpl.vars import resolve_token def render(text: str, env...
### FILE: tmpl/vars.py ```python def resolve_token(expr: str, env: dict[str, str]) -> str: key, default = expr.split(':-', 1) if ':' in expr else (expr, '') value = env.get(key.strip(), '') return value if value != '' else default.strip() ``` ### FILE: tmpl/render.py ```python import re from tmpl.vars impo...
posix-pytest
train-posix-5
posix
Fix acl/roles.py and acl/check.py: collect inherited permissions safely even with diamond/cyclic role graphs, and ensure any explicit deny in direct or inherited roles overrides allow. Repository files: ### FILE: acl/check.py ```python from acl.roles import expand_roles def is_allowed(role: str, perm: str, parents: ...
### FILE: acl/check.py ```python from acl.roles import expand_roles def is_allowed(role: str, perm: str, parents: dict, allow: dict, deny: dict) -> bool: if perm in deny.get(role, set()): return False for r in expand_roles(role, parents): if perm in deny.get(r, set()): return False ...
posix-pytest
train-posix-6
posix
Fix cb/window.py and cb/breaker.py: prune events older than (now - window), and open the circuit only when count >= min_calls and failure_rate >= threshold. Repository files: ### FILE: cb/breaker.py ```python from cb.window import EventWindow class Breaker: def __init__(self, span: float, min_calls: int, thresho...
### FILE: cb/breaker.py ```python from cb.window import EventWindow class Breaker: def __init__(self, span: float, min_calls: int, threshold: float): self.win = EventWindow(span) self.min_calls = min_calls self.threshold = threshold def record(self, ts: float, ok: bool) -> bool: ...
posix-pytest
train-hard-15
code
Write Python token_bucket_sim(capacity, rate, events) simulating rate limiter starting full at capacity, where events are (t, cost) strictly non-decreasing timestamps; refill min(capacity, tokens + (t - prev_t) * rate), allow if tokens >= cost (consume and record True) else record False; return list of bools
def token_bucket_sim(capacity, rate, events): tokens = capacity prev_t = 0 results = [] for t, cost in events: # Refill tokens tokens += min(capacity, (t - prev_t) * rate) tokens = min(tokens, capacity) # Ensure tokens do not exceed capacity prev_t = t ...
code-unittest

No dataset card yet

Downloads last month
38

Space using DevodG/janus-star-traces 1