Dataset Viewer
Auto-converted to Parquet Duplicate
instruction
stringlengths
68
159
output
stringlengths
46
20k
Write a Python function that implements the Knapsack problem. Return only the code.
def knapsack(capacity: int, weights: list[int], values: list[int]) -> int: """Return the maximum value obtainable using each item at most once.""" if capacity < 0: raise ValueError("Capacity must be non-negative.") if len(weights) != len(values): raise ValueError("Weights and values must hav...
Write a Python function that finds the first non-repeating character. Return only the code.
def first_non_repeating_character(s): counts = {} for char in s: counts[char] = counts.get(char, 0) + 1 for char in s: if counts[char] == 1: return char return None
Implement a Python function to finds the longest increasing subsequence. Output only the code.
from bisect import bisect_left def longest_increasing_subsequence(nums: list[int]) -> int: """Return the length of the longest strictly increasing subsequence.""" tails = [] for num in nums: index = bisect_left(tails, num) if index == len(tails): tails.append(num) else:...
Create a Python function that parses a binary file safely. Return None on error. Only the code.
import json import struct def parse_binary_file(path, max_payload_bytes=1024 * 1024): """ Parse a binary file containing: - b"BIN1" magic bytes - a little-endian unsigned 32-bit payload length - a UTF-8-encoded JSON object Return the parsed dictionary, or None on invalid/oversized input ...
Write a Python class that implements a bank account with deposits and withdrawals. Return only the code.
class BankAccount: """A bank account that supports deposits and withdrawals.""" def __init__(self, owner: str, initial_balance: float = 0.0) -> None: if not owner.strip(): raise ValueError("Account owner cannot be empty.") if initial_balance < 0: raise ValueError("Initia...
Write a complete Python module that implements a simple interpreter for arithmetic expressions. Use functions and classes. Return only the code.
"""A small, safe interpreter for arithmetic expressions. Supported syntax: Integer and floating-point literals, such as 42, 3.14, .5, and 1e3 Variables supplied through a mapping Addition, subtraction, multiplication, division, and modulo Integer division and right-associative exponentiation Unary ...
Implement a Python function to reverses a linked list. Output only the code.
def reverse_linked_list(head): """Reverse a singly linked list and return its new head.""" previous = None current = head while current is not None: next_node = current.next current.next = previous previous = current current = next_node return previous
Create a Python function that parses a configuration file safely. Return None on error. Only the code.
import json from typing import Any def parse_config_file(file_path: str) -> dict[str, Any] | None: """Parse a UTF-8 JSON configuration object without executing its contents.""" try: with open(file_path, "r", encoding="utf-8") as config_file: config = json.load(config_file) except (OSErr...
Write a Python function that implements binary search. Return only the code.
def binary_search(arr, target): """Return target's index in a sorted array, or -1 if it is not found.""" left, right = 0, len(arr) - 1 while left <= right: mid = (left + right) // 2 if arr[mid] == target: return mid if arr[mid] < target: left = mid + 1 ...
Write a Python function that calculates the LCM of two numbers. Return only the code.
from math import gcd def lcm(a: int, b: int) -> int: a, b = abs(a), abs(b) if a == 0 or b == 0: return 0 return (a // gcd(a, b)) * b
Write a Python function that sorts a list using merge sort. Return only the code.
def merge_sort(items): if len(items) <= 1: return items[:] mid = len(items) // 2 left = merge_sort(items[:mid]) right = merge_sort(items[mid:]) merged = [] i = j = 0 while i < len(left) and j < len(right): if left[i] <= right[j]: merged.append(left[i]) ...
Implement a Python function to computes the Fibonacci sequence up to n. Output only the code.
def fibonacci(n: int) -> list[int]: """Return the first n Fibonacci numbers, starting with 0 and 1.""" if n < 0: raise ValueError("n must be non-negative") sequence = [] a, b = 0, 1 for _ in range(n): sequence.append(a) a, b = b, a + b return sequence
Implement Kadane's algorithm in Python with type hints. Return only the code.
def kadane(nums: list[int]) -> int: """Return the maximum contiguous subarray sum, or 0 for an empty list.""" if not nums: return 0 current_sum = best_sum = nums[0] for i in range(1, len(nums)): current_sum = max(nums[i], current_sum + nums[i]) best_sum = max(best_sum, current_s...
Create a Python function that parses a list of dictionaries safely. Return None on error. Only the code.
def parse_dict_list(data): """Return a validated list of dictionaries, or None on error.""" try: if not isinstance(data, list): return None if not all(isinstance(item, dict) for item in data): return None return [dict(item) for item in data] except Exception: ...
Write a Python function to process a binary file. Include error handling. Return only the code.
import hashlib def process_binary_file(file_path, chunk_size=65536): """Process a binary file, returning its size in bytes and SHA-256 checksum.""" if isinstance(chunk_size, bool) or not isinstance(chunk_size, int) or chunk_size <= 0: raise ValueError("chunk_size must be a positive integer.") tota...
Implement a Python function to implements binary search. Output only the code.
def binary_search(arr, target): """Return target's index in a sorted array, or -1 if not found.""" left, right = 0, len(arr) - 1 while left <= right: mid = left + (right - left) // 2 if arr[mid] == target: return mid elif arr[mid] < target: left = mid + 1 ...
Implement depth-first search in Python with type hints. Return only the code.
from collections.abc import Hashable, Mapping, Sequence from typing import TypeVar T = TypeVar("T", bound=Hashable) def depth_first_search(graph: Mapping[T, Sequence[T]], start: T) -> list[T]: """Return nodes in depth-first preorder, exploring neighbors left to right.""" visited: set[T] = set() order: lis...
Write a Python function that implements Bellman-Ford algorithm. Return only the code.
def bellman_ford(graph, source): """ Compute shortest-path distances from source in a directed weighted graph. Args: graph: Dictionary mapping each vertex to {neighbor: edge_weight}. source: Vertex to start from. Returns: A dictionary mapping each vertex to its shortest distanc...
Implement the segment tree in Python with type hints. Return only the code.
from __future__ import annotations from collections.abc import Callable, Sequence from typing import Generic, TypeVar T = TypeVar("T") class SegmentTree(Generic[T]): """Segment tree supporting point assignments and range queries. The operation must be associative, and identity must be a two-sided identi...
Write a Python function that finds the longest increasing subsequence. Return only the code.
def longest_increasing_subsequence(arr): """Return one longest strictly increasing subsequence in O(n log n) time.""" if not arr: return [] tails = [] # Smallest ending value for each subsequence length. tail_indices = [] # Indices of those ending values. predecessors = [-1] * len(arr) ...
Implement a Python class for a task scheduler with priorities. Return only the class.
import heapq import itertools import threading from typing import Any, Callable class TaskScheduler: """Schedule callables using a priority queue. Lower numeric priorities run first. Tasks with equal priorities run in the order they were added. add_task() queues a callable with optional arguments and...
Create a Python function that parses a list of dictionaries safely. Return None on error. Only the code.
def parse_dict_list(data): try: if not isinstance(data, list): return None if not all(isinstance(item, dict) for item in data): return None return data except Exception: return None
Write a Python function that implements a stack using a list. Return only the code.
def create_stack(): stack = [] def push(item): stack.append(item) def pop(): if not stack: raise IndexError("pop from empty stack") return stack.pop() def peek(): if not stack: raise IndexError("peek from empty stack") return stack[-1] ...
Implement a Python function to finds the first non-repeating character. Output only the code.
from collections import Counter def first_non_repeating_character(s): """Return the first non-repeating character, or None if none exists.""" counts = Counter(s) for char in s: if counts[char] == 1: return char return None
Write a Python function that checks if a number is prime. Return only the code.
from math import isqrt def is_prime(n: int) -> bool: if n < 2: return False if n == 2: return True if n % 2 == 0: return False for divisor in range(3, isqrt(n) + 1, 2): if n % divisor == 0: return False return True
Write a Python class that implements a shopping cart with add/remove/total. Return only the code.
class ShoppingCart: def __init__(self): self._items = {} def add(self, product, price, quantity=1): if price < 0: raise ValueError("Price must be nonnegative.") if quantity <= 0: raise ValueError("Quantity must be positive.") if product not in self._item...
Implement a Python function to finds all prime factors of a number. Output only the code.
def prime_factors(n: int) -> list[int]: """Return all distinct prime factors of n.""" n = abs(n) factors = [] divisor = 2 while divisor * divisor <= n: if n % divisor == 0: factors.append(divisor) while n % divisor == 0: n //= divisor divisor ...
Write a Python function that checks if a number is prime. Return only the code.
def is_prime(n: int) -> bool: if n < 2: return False if n == 2: return True if n % 2 == 0: return False divisor = 3 while divisor * divisor <= n: if n % divisor == 0: return False divisor += 2 return True
Implement the A* pathfinding algorithm in Python with type hints. Return only the code.
from __future__ import annotations from heapq import heappop, heappush from math import sqrt from typing import Iterator, Sequence, TypeAlias Position: TypeAlias = tuple[int, int] Grid: TypeAlias = Sequence[Sequence[int | bool]] _CARDINAL_DIRECTIONS: tuple[tuple[int, int], ...] = ( (-1, 0), (1, 0), (0, -...
Write a Python function that implements the sieve of Eratosthenes. Return only the code.
def sieve(n): """Return a list of all prime numbers less than or equal to n.""" if n < 2: return [] is_prime = [True] * (n + 1) is_prime[0] = is_prime[1] = False p = 2 while p * p <= n: if is_prime[p]: for multiple in range(p * p, n + 1, p): is_prime...
Write a Python function that finds the longest common prefix of strings. Return only the code.
def longest_common_prefix(strings: list[str]) -> str: if not strings: return "" prefix = strings[0] for string in strings[1:]: while not string.startswith(prefix): prefix = prefix[:-1] if not prefix: return "" return prefix
Write a Python function that computes the edit distance between two strings. Return only the code.
def edit_distance(s1: str, s2: str) -> int: """Return the Levenshtein edit distance between two strings.""" if len(s1) < len(s2): s1, s2 = s2, s1 previous = list(range(len(s2) + 1)) for i, char1 in enumerate(s1, start=1): current = [i] for j, char2 in enumerate(s2, start=1): ...
Fill in the body of this function: def parse_input(s): # implements binary search Return only the code.
def parse_input(s): """Return target's index in sorted values, or -1; s is (values, target).""" values, target = s low, high = 0, len(values) - 1 while low <= high: mid = (low + high) // 2 if values[mid] < target: low = mid + 1 elif values[mid] > target: ...
Write a Python function to process a text file line by line. Include error handling. Return only the code.
def process_file(file_path, line_handler): """ Process a UTF-8 text file line by line. Apply line_handler to each line with its newline removed and return the results as a list. Errors raised by line_handler are propagated. Raises: TypeError: If line_handler is not callable. Runtim...
Implement the A* pathfinding algorithm in Python with type hints. Return only the code.
from __future__ import annotations from collections.abc import Callable, Sequence from heapq import heappop, heappush from itertools import count from math import inf, sqrt Position = tuple[int, int] Grid = Sequence[Sequence[int | bool]] Heuristic = Callable[[Position, Position], float] def astar( grid: Grid, ...
Write a Python function that detects a cycle in a linked list. Return only the code.
def has_cycle(head): slow = fast = head while fast is not None and fast.next is not None: slow = slow.next fast = fast.next.next if slow is fast: return True return False
Implement a Python function to calculates the factorial of n. Output only the code.
def factorial(n: int) -> int: if n < 0: raise ValueError("n must be non-negative") result = 1 for i in range(2, n + 1): result *= i return result
Complete this Python function: def filter(x, y): """computes the GCD of two numbers""" Return only the full function.
def filter(x, y): """computes the GCD of two numbers""" x, y = abs(x), abs(y) while y: x, y = y, x % y return x
Write a Python function that implements quicksort. Return only the code.
def quicksort(arr): """Return a sorted copy of the input iterable.""" values = list(arr) def partition(low, high): pivot = values[(low + high) // 2] i, j = low, high while i <= j: while values[i] < pivot: i += 1 while values[j] > pivot: ...
Complete this Python function: def save_state(lst): """computes the GCD of two numbers""" Return only the full function.
def save_state(lst): """computes the GCD of two numbers""" a, b = lst while b: a, b = b, a % b return abs(a)
Implement Kadane's algorithm in Python with type hints. Return only the code.
from collections.abc import Sequence def kadane(values: Sequence[int]) -> int: """Return the maximum contiguous subarray sum, or 0 if empty.""" if not values: return 0 current_sum = best_sum = values[0] for i in range(1, len(values)): current_sum = max(values[i], current_sum + values[...
Implement a Python class for a shopping cart with add/remove/total. Return only the class.
class ShoppingCart: """A shopping cart supporting per-item prices and quantities.""" def __init__(self): self._items = {} # product -> (unit_price, quantity) def add(self, product, price, quantity=1): """Add a product or increase its existing quantity.""" if price < 0: ...
Implement a Python function to computes the binomial coefficient. Output only the code.
def binomial_coefficient(n: int, k: int) -> int: """Return the binomial coefficient C(n, k) for integer n >= 0.""" if n < 0: raise ValueError("n must be non-negative") if k < 0 or k > n: return 0 k = min(k, n - k) result = 1 for i in range(1, k + 1): result = result * (n...
Create a Python function that parses a JSON string safely. Return None on error. Only the code.
import json def parse_json(json_string: str): try: return json.loads(json_string) except (ValueError, TypeError, RecursionError): return None
Implement a Python class for a graph with DFS and BFS. Return only the class.
class Graph: """An undirected graph supporting depth-first and breadth-first searches.""" def __init__(self) -> None: self.adjacency = {} def add_vertex(self, vertex) -> None: """Add a vertex if it is not already present.""" self.adjacency.setdefault(vertex, set()) def add_edg...
Write a Python function that implements the longest common subsequence. Return only the code.
def longest_common_subsequence(s1: str, s2: str) -> str: """Return one longest common subsequence of s1 and s2.""" m, n = len(s1), len(s2) lengths = [[0] * (n + 1) for _ in range(m + 1)] for i in range(1, m + 1): for j in range(1, n + 1): if s1[i - 1] == s2[j - 1]: l...
Implement Bellman-Ford algorithm in Python with type hints. Return only the code.
from dataclasses import dataclass from typing import Generic, Hashable, Mapping, Optional, TypeVar Vertex = TypeVar("Vertex", bound=Hashable) @dataclass(frozen=True) class BellmanFordResult(Generic[Vertex]): distances: dict[Vertex, float] predecessors: dict[Vertex, Optional[Vertex]] has_negative_cycle: bo...
Write a complete Python module that implements a simple blockchain. Use functions and classes. Return only the code.
"""A small, educational blockchain using SHA-256 proof of work. Blocks contain JSON-serializable dictionary data, a timestamp, a nonce, and links to the preceding block. Difficulty specifies the minimum number of leading zero characters required in a block's hexadecimal hash. """ from __future__ import annotations i...
Write a Python function that implements the coin change problem. Return only the code.
def coin_change(coins, amount): """Return the fewest coins needed to make amount, or -1 if impossible.""" if amount < 0: return -1 dp = [amount + 1] * (amount + 1) dp[0] = 0 for coin in set(coins): if coin <= 0: continue for total in range(coin, amount + 1): ...
Implement a Python solution for implements a markdown parser. Return only the code.
import html import re import sys import unicodedata from dataclasses import dataclass from urllib.parse import urlsplit _ESCAPABLE = re.compile(r"[!-/:-@\[-`{-~]") _FENCE_RE = re.compile(r"^( {0,3})(`{3,}|~{3,})(.*)$") _HEADING_RE = re.compile(r"^ {0,3}(#{1,6})(?:[ \t]+(.*))?$") _HR_RE = re.compile( r"^ {0,3}(?:(?...
Implement topological sorting in Python with type hints. Return only the code.
from collections import deque from collections.abc import Hashable, Iterable, Mapping from typing import TypeVar T = TypeVar("T", bound=Hashable) def topological_sort(graph: Mapping[T, Iterable[T]]) -> list[T]: """Return a topological ordering of a directed graph. Vertices with no outgoing edges may be omitt...
Write a Python class that implements a bank account with deposits and withdrawals. Return only the code.
class BankAccount: def __init__(self, initial_balance: float = 0) -> None: if initial_balance < 0: raise ValueError("Initial balance cannot be negative.") self.balance = initial_balance def deposit(self, amount: float) -> float: if amount <= 0: raise ValueError("...
Write a complete Python module that implements a REST API client with retry logic. Use functions and classes. Return only the code.
"""A synchronous REST API client with configurable retries. Requires Python 3.10+ and the ``requests`` package. By default, GET, HEAD, PUT, DELETE, and OPTIONS requests are retried for selected transient HTTP statuses and transport errors. Retries use capped exponential backoff with jitter and honor Retry-After heade...
Write a Python function to process an XML document. Include error handling. Return only the code.
import xml.etree.ElementTree as ET from typing import Any def process_xml_document(xml_document: str | bytes) -> dict[str, Any]: """Parse XML and return its root element as a nested dictionary. Raises: TypeError: If the input is not a string or bytes. ValueError: If the input is empty or conta...
Implement a Python class for a bank account with deposits and withdrawals. Return only the class.
class BankAccount: """A bank account supporting deposits and withdrawals.""" def __init__(self, initial_balance: float = 0.0) -> None: if initial_balance < 0: raise ValueError("Initial balance cannot be negative.") self._balance = float(initial_balance) @property def balanc...
Write a Python class that implements a hash map with collision handling. Return only the code.
class _Node: __slots__ = ("key", "value", "next") def __init__(self, key, value, next_node=None): self.key = key self.value = value self.next = next_node class HashMap: """A hash map using separate chaining and automatic resizing.""" def __init__(self, initial_capacity=8, load...
Write a Python function to process a configuration file. Include error handling. Return only the code.
import configparser from pathlib import Path def process_config_file(file_path: str | Path) -> dict[str, dict[str, str]]: """Load a UTF-8 INI configuration file. Returns: A dictionary mapping section names to their key-value settings. Values from [DEFAULT] are included in each section. Ra...
Implement a Python function to computes the GCD of two numbers. Output only the code.
def gcd(a: int, b: int) -> int: """Return the greatest common divisor of two integers.""" a, b = abs(a), abs(b) while b: a, b = b, a % b return a
Write a Python function that detects a cycle in a linked list. Return only the code.
def has_cycle(head) -> bool: """Return True if the linked list contains a cycle. O(n) time, O(1) space.""" slow = fast = head while fast is not None and fast.next is not None: slow = slow.next fast = fast.next.next if slow is fast: return True return False
Implement the Fenwick tree in Python with type hints. Return only the code.
from typing import List, TypeVar, cast T = TypeVar("T", int, float) class FenwickTree(Generic[T]): """A Fenwick tree for point updates and prefix-sum queries. Indices are one-based. Range queries include both endpoints. """ def __init__(self, size: int) -> None: if size < 0: rais...
Write a Python function that implements a queue using two stacks. Return only the code.
class Queue: def __init__(self): self._incoming = [] self._outgoing = [] def enqueue(self, item): self._incoming.append(item) def _prepare_dequeue(self): if not self._outgoing: while self._incoming: self._outgoing.append(self._incoming.pop()) ...
Complete this Python function: def validate(arr, target): """finds the longest common prefix of strings""" Return only the full function.
def validate(arr, target): """Return the longest common prefix of target and all strings in arr.""" if not arr: return "" prefix = [] for characters in zip(target, *arr): if any(character != characters[0] for character in characters[1:]): break prefix.append(characte...
Write a Python function that implements depth-first search. Return only the code.
def depth_first_search(graph, start): """Return the depth-first traversal order from a node in an adjacency dictionary.""" visited = set() stack = [start] traversal = [] while stack: node = stack.pop() if node in visited: continue visited.add(node) trave...
Write a Python function that implements the sieve of Eratosthenes. Return only the code.
from math import isqrt def sieve(n: int) -> list[int]: """Return all primes up to n, inclusive.""" if n < 2: return [] is_prime = [True] * (n + 1) is_prime[0] = is_prime[1] = False for p in range(2, isqrt(n) + 1): if is_prime[p]: for multiple in range(p * p, n + 1, p):...
Write a Python function that computes the edit distance between two strings. Return only the code.
def edit_distance(s1: str, s2: str) -> int: """Return the Levenshtein distance between two strings.""" if len(s1) < len(s2): s1, s2 = s2, s1 previous_row = list(range(len(s2) + 1)) for i, char1 in enumerate(s1, start=1): current_row = [i] for j, char2 in enumerate(s2, start=1):...
Create a Python function that parses a configuration file safely. Return None on error. Only the code.
import configparser def parse_config_file(path): """Parse an INI configuration file without interpolation; return None on error.""" parser = configparser.ConfigParser(interpolation=None) try: with open(path, "r", encoding="utf-8") as config_file: parser.read_file(config_file) ...
Implement a Python class for a bank account with deposits and withdrawals. Return only the class.
class BankAccount: """A bank account supporting deposits and withdrawals.""" def __init__(self, initial_balance: float = 0.0) -> None: if initial_balance < 0: raise ValueError("Initial balance cannot be negative.") self._balance = initial_balance @property def balance(self)...
Complete this Python function: def transform(x, y): """implements the sieve of Eratosthenes""" Return only the full function.
def transform(x, y): """Return primes in the inclusive range [x, y] using the sieve of Eratosthenes.""" if x > y or y < 2: return [] is_prime = [True] * (y + 1) is_prime[0] = is_prime[1] = False p = 2 while p * p <= y: if is_prime[p]: for multiple in range(p * p, y ...
Complete this Python function: def transform(data): """finds all prime factors of a number""" Return only the full function.
def transform(data): """finds all prime factors of a number""" factors = [] number = abs(data) divisor = 2 while divisor * divisor <= number: while number % divisor == 0: factors.append(divisor) number //= divisor divisor = 3 if divisor == 2 else divisor + 2 ...
Write a Python class that implements a graph with DFS and BFS. Return only the code.
from collections import deque class Graph: """An adjacency-set graph supporting iterative DFS and BFS.""" def __init__(self, directed=False): self.directed = directed self.adjacency = {} def add_vertex(self, vertex): """Add a vertex if it does not already exist.""" self.ad...
Complete this Python function: def process_data(n): """sorts a list using merge sort""" Return only the full function.
def process_data(n): """Sorts a list using merge sort.""" if len(n) <= 1: return n[:] mid = len(n) // 2 left = process_data(n[:mid]) right = process_data(n[mid:]) result = [] i = j = 0 while i < len(left) and j < len(right): if left[i] <= right[j]: result.a...
Write a Python function to process a Parquet file. Include error handling. Return only the code.
from pathlib import Path def process_parquet(file_path, columns=None, filters=None): """Read a Parquet file into a pandas DataFrame. Args: file_path: Path to the Parquet file. columns: Optional list of columns to read. filters: Optional row filters, such as [("column", "==", value)]. ...
Implement a Python function to converts a decimal number to binary. Output only the code.
def decimal_to_binary(number: int) -> str: """Return the binary representation of a decimal integer without a prefix.""" return format(number, "b")
Write a Python function that implements Floyd-Warshall algorithm. Return only the code.
def floyd_warshall(graph): """ Return the all-pairs shortest-path distance matrix. graph must be a square matrix with numeric edge weights, float("inf") for missing edges, and zero on the diagonal. The input is not modified. """ n = len(graph) dist = [row[:] for row in graph] inf = floa...
Implement merge sort in Python with type hints. Return only the code.
from typing import TypeVar T = TypeVar("T") def merge_sort(values: list[T]) -> list[T]: """Return a sorted copy of values without modifying the original list.""" def sort(items: list[T]) -> list[T]: if len(items) <= 1: return items[:] mid = len(items) // 2 left = sort(ite...
Implement a Python class for a priority queue using a heap. Return only the class.
class PriorityQueue: """A min-priority queue implemented using a binary heap. Items must be mutually comparable; smaller items have higher priority. """ def __init__(self): self._heap = [] def __len__(self): return len(self._heap) def is_empty(self): return not self._...
Create a Python function that parses a CSV file safely. Return None on error. Only the code.
import csv def parse_csv(file_path): """Return CSV rows as dictionaries, or None if parsing fails.""" try: with open(file_path, "r", encoding="utf-8-sig", newline="") as file: return list(csv.DictReader(file, strict=True)) except (OSError, ValueError, TypeError, csv.Error): retu...
Create a Python function that parses a binary file safely. Return None on error. Only the code.
def parse_binary_file(file_path): """Return the file's bytes, or None if it cannot be read.""" try: with open(file_path, "rb") as file: return file.read() except (OSError, TypeError, ValueError): return None
Write a Python function that implements Prim's algorithm. Return only the code.
from heapq import heappop, heappush def prim(graph): """Return (mst_edges, total_weight) for an undirected weighted graph. graph maps each vertex to a dictionary of neighbor: edge_weight pairs. mst_edges contains (u, v, weight) tuples. Raises ValueError if the graph is disconnected. Returns ([], 0) fo...
Implement a Python function to implements binary search. Output only the code.
def binary_search(arr, target): """Return target's index in an ascending sorted array, or -1 if not found.""" left, right = 0, len(arr) - 1 while left <= right: mid = (left + right) // 2 if arr[mid] == target: return mid elif arr[mid] < target: left = mid + ...
Write a Python function that finds all prime factors of a number. Return only the code.
def prime_factors(n: int) -> list[int]: """Return the distinct prime factors of n in ascending order.""" if n == 0: raise ValueError("Zero has infinitely many prime factors.") n = abs(n) factors = [] divisor = 2 while divisor * divisor <= n: if n % divisor == 0: fac...
Implement a Python solution for implements a URL shortener with in-memory storage. Return only the code.
import secrets import string from threading import RLock from urllib.parse import urlsplit class URLShortener: """Thread-safe URL shortener whose data lives only in memory.""" _ALPHABET = string.ascii_letters + string.digits def __init__( self, base_url: str = "https://short.example", ...
Write a Python function that implements Kadane's algorithm. Return only the code.
def max_subarray_sum(arr): """Return the maximum sum of a nonempty contiguous subarray.""" if not arr: raise ValueError("arr must not be empty") current_sum = best_sum = arr[0] for i in range(1, len(arr)): current_sum = max(arr[i], current_sum + arr[i]) best_sum = max(best_sum, ...
Implement a Python function to sorts a list using merge sort. Output only the code.
def merge_sort(items): """Return a new list containing the items sorted in ascending order.""" if len(items) <= 1: return items.copy() mid = len(items) // 2 left = merge_sort(items[:mid]) right = merge_sort(items[mid:]) result = [] i = j = 0 while i < len(left) and j < len(rig...
Fill in the body of this function: def parse_input(data): # reverses a linked list Return only the code.
def parse_input(data): previous = None current = data while current is not None: next_node = current.next current.next = previous previous = current current = next_node return previous
Implement a Python function to checks if a string is a palindrome. Output only the code.
def is_palindrome(s: str) -> bool: """Return True if s reads the same forward and backward.""" return s == s[::-1]
Implement a Python class for a hash map with collision handling. Return only the class.
class HashMap: """A hash map using separate chaining to handle collisions.""" _MISSING = object() def __init__(self, initial_capacity: int = 8): if initial_capacity < 1: raise ValueError("initial_capacity must be positive") self._capacity = initial_capacity self._bucke...
Write a Python function that implements quicksort. Return only the code.
def quicksort(arr, low=0, high=None): """Sort arr in place in ascending order and return it.""" if high is None: high = len(arr) - 1 while low < high: pivot = arr[(low + high) // 2] left, right = low, high while left <= right: while arr[left] < pivot: ...
Write a Python class that implements a stack with push/pop/peek. Return only the code.
class Stack: def __init__(self) -> None: self._items = [] def push(self, item) -> None: self._items.append(item) def pop(self): if not self._items: raise IndexError("pop from empty stack") return self._items.pop() def peek(self): if not self._items:...
Fill in the body of this function: def sort(n): # finds the longest common prefix of strings Return only the code.
def sort(n): if not n: return "" prefix = n[0] for s in n[1:]: while not s.startswith(prefix): prefix = prefix[:-1] if not prefix: return "" return prefix
Implement a Python function to implements binary search. Output only the code.
def binary_search(arr, target): """Return target's index in an ascending-sorted array, or -1 if not found.""" left, right = 0, len(arr) - 1 while left <= right: mid = left + (right - left) // 2 if arr[mid] == target: return mid elif arr[mid] < target: left =...
Write a Python function that implements depth-first search. Return only the code.
def depth_first_search(graph, start): """Return nodes in depth-first order from an adjacency-mapping graph.""" visited = set() stack = [start] order = [] while stack: node = stack.pop() if node in visited: continue visited.add(node) order.append(node) ...
Write a Python function to process a binary file. Include error handling. Return only the code.
import hashlib def process_binary_file( file_path: str, chunk_size: int = 1024 * 1024 ) -> dict: """Process a binary file, returning its size and SHA-256 checksum.""" if chunk_size <= 0: raise ValueError("chunk_size must be greater than zero.") total_bytes = 0 checksum = hashlib.sha256() ...
Implement a Python function to implements a stack using a list. Output only the code.
class Stack: def __init__(self): self.items = [] def push(self, item): self.items.append(item) def pop(self): if not self.items: raise IndexError("pop from empty stack") return self.items.pop() def peek(self): if not self.items: raise In...
Write a Python class that implements a bank account with deposits and withdrawals. Return only the code.
class BankAccount: """A bank account supporting deposits and withdrawals.""" def __init__(self, initial_balance: float = 0.0) -> None: if initial_balance < 0: raise ValueError("Initial balance cannot be negative.") self.balance = float(initial_balance) def deposit(self, amount:...
Write a Python function to process a Parquet file. Include error handling. Return only the code.
def process_parquet(file_path, columns=None, filters=None): """ Read a Parquet file into a pandas DataFrame. Args: file_path: Path to the Parquet file. columns: Optional column name or list of column names to read. filters: Optional row filters in pyarrow.dataset format. Return...
Implement breadth-first search in Python with type hints. Return only the code.
from collections import deque from collections.abc import Callable, Hashable, Iterable, Iterator from typing import TypeVar NodeT = TypeVar("NodeT", bound=Hashable) def breadth_first_search( start: NodeT, neighbors: Callable[[NodeT], Iterable[NodeT]], ) -> Iterator[NodeT]: """Yield nodes reachable from st...
Implement a Python function to checks if a number is prime. Output only the code.
def is_prime(n: int) -> bool: """Return True if n is prime, otherwise False.""" if n < 2: return False if n % 2 == 0: return n == 2 divisor = 3 while divisor * divisor <= n: if n % divisor == 0: return False divisor += 2 return True
Fill in the body of this function: def calculate(n): # implements a queue using two stacks Return only the code.
def calculate(n): """Enqueue integers from 0 to n - 1, then dequeue them into a list.""" incoming = [] outgoing = [] result = [] for value in range(n): incoming.append(value) while incoming or outgoing: if not outgoing: while incoming: outgoing.appen...
Fill in the body of this function: def process_data(x, y): # computes the Fibonacci sequence up to n Return only the code.
def process_data(x, y): n = x sequence = [] a, b = 0, 1 for _ in range(n): sequence.append(a) a, b = b, a + b return sequence
End of preview. Expand in Data Studio

Minimax M3.1 Flash Distillation Coding 23K Clean

A clean collection of 23,561 synthetic coding samples generated with Minimax M3.1 Flash, previously exposed through OpenCode under the stealth-model alias Space Bunny Alpha.

The dataset is intended for experimentation with LLM distillation, code-generation models, instruction tuning, supervised fine-tuning, evaluation, and agentic coding systems.

Downloads last month
78