Dataset Viewer
Auto-converted to Parquet Duplicate
prompt
listlengths
1
1
completion
listlengths
1
1
meta
dict
[ { "role": "user", "content": "Write a function describe_path(path) that takes a file path as a string and returns a dictionary with three keys describing that path. The 'stem' key holds the file name without its final extension, the 'extension' key holds the final extension in lowercase without the leading ...
[ { "role": "assistant", "content": "from pathlib import PurePath\n\n\ndef describe_path(path):\n p = PurePath(path)\n return {\n \"stem\": p.stem,\n \"extension\": p.suffix[1:].lower(),\n \"parent\": p.parent.name,\n }\n\n\nif __name__ == \"__main__\":\n assert describe_path(...
{ "topic": "working with files and paths", "difficulty": "easy", "provider": "together", "in_tokens": 237, "out_tokens": 1937, "latency_s": 18.7 }
[ { "role": "user", "content": "A compressed text format represents repeated and reversed segments with three rules: a run of lowercase letters stands for itself; `k(X)`, where k is a positive integer (possibly with several digits) and X is any valid compressed expression, decodes to the decoding of X repeate...
[ { "role": "assistant", "content": "import sys\n\n\ndef decode(s):\n n = len(s)\n\n def parse(i):\n parts = []\n while i < n and s[i] != ')':\n ch = s[i]\n if ch.isdigit():\n j = i\n while j < n and s[j].isdigit():\n j...
{ "topic": "string manipulation and text processing", "difficulty": "hard", "provider": "together", "in_tokens": 237, "out_tokens": 3575, "latency_s": 45.5 }
[ { "role": "user", "content": "Write a function extract_hashtags(text) that scans a string and returns a list of all hashtags it contains. A hashtag is defined as a '#' character immediately followed by one or more letters (A-Z, a-z), digits (0-9), or underscores. The returned list must contain the hashtag t...
[ { "role": "assistant", "content": "import re\n\n\ndef extract_hashtags(text):\n \"\"\"Return a list of all hashtags in text, without the leading '#'.\"\"\"\n return re.findall(r\"#([A-Za-z0-9_]+)\", text)\n\n\nif __name__ == \"__main__\":\n sample = \"Loving the #Python and #regex_101 tutorials! #2...
{ "topic": "regular expressions", "difficulty": "easy", "provider": "together", "in_tokens": 234, "out_tokens": 1813, "latency_s": 23.2 }
[ { "role": "user", "content": "Implement a thread-safe bank using only threading primitives from the standard library. Write a class `Bank` with methods `create_account(account_id, balance)`, `transfer(src, dst, amount)`, and `total_balance()`. `transfer` must atomically move `amount` from `src` to `dst`, ra...
[ { "role": "assistant", "content": "import threading\n\n\nclass Bank:\n \"\"\"A thread-safe bank supporting atomic transfers between accounts.\"\"\"\n\n def __init__(self):\n self._balances = {}\n self._locks = {}\n self._guard = threading.Lock() # protects the account registry\n\...
{ "topic": "concurrency basics with threading primitives", "difficulty": "medium", "provider": "together", "in_tokens": 237, "out_tokens": 3503, "latency_s": 34.7 }
[ { "role": "user", "content": "A frog is crossing a river using n lily pads numbered 0 to n-1, starting on pad 0 and trying to reach pad n-1. From pad i it may jump forward exactly 1, 2, or 3 pads, but it is never allowed to make two jumps of length 3 in a row because it must catch its breath. The list costs...
[ { "role": "assistant", "content": "def min_crossing_cost(costs):\n n = len(costs)\n if n == 1:\n return 0\n INF = float(\"inf\")\n # dp[i][p] = minimum energy to be standing on pad i, where the jump\n # that landed on pad i had length p (p in {1, 2, 3}). Index 0 unused.\n dp = [[INF...
{ "topic": "dynamic programming exercises", "difficulty": "medium", "provider": "together", "in_tokens": 235, "out_tokens": 5278, "latency_s": 73.3 }
[ { "role": "user", "content": "You are given a list of order records returned by a fictional REST API, where each record is a dictionary with keys \"id\" (int), \"customer\" (str), \"amount\" (a string such as \"$10.50\"), and \"status\" (one of \"completed\", \"pending\", or \"cancelled\"). Write a function...
[ { "role": "assistant", "content": "def summarize_completed_orders(orders):\n \"\"\"Return a mapping of customer name to total spent on completed orders.\"\"\"\n totals = {}\n for order in orders:\n if order.get(\"status\") != \"completed\":\n continue\n customer = order[\"c...
{ "topic": "API-like data transformation tasks", "difficulty": "easy", "provider": "together", "in_tokens": 237, "out_tokens": 1872, "latency_s": 17.4 }
[ { "role": "user", "content": "Write a function `reassemble(chunks)` that reconstructs a message from out-of-order pieces. `chunks` is a list of `(offset, payload)` tuples, where `offset` is a non-negative integer giving the starting index of the string `payload` in the final message. Pieces may overlap, but...
[ { "role": "assistant", "content": "def reassemble(chunks):\n \"\"\"Reassemble a message from (offset, payload) chunks.\n\n Overlapping regions must agree character-for-character, otherwise a\n ValueError is raised. Returns the assembled string, or None if the\n pieces do not cover a contiguous r...
{ "topic": "unit-testable small algorithms", "difficulty": "medium", "provider": "together", "in_tokens": 237, "out_tokens": 2753, "latency_s": 49.6 }
[ { "role": "user", "content": "A workshop has a single machine and a list of candidate jobs, where each job is a triple (start, end, profit) meaning it must occupy the machine during the half-open interval [start, end) and earns profit if run. After any job finishes at time e, the machine needs g minutes of ...
[ { "role": "assistant", "content": "import bisect\nimport itertools\nimport random\n\n\ndef max_profit(jobs, g):\n \"\"\"Return the maximum total profit of a compatible subset of jobs.\n\n jobs: list of (start, end, profit) tuples; a job occupies [start, end).\n g: maintenance gap; a job ending a...
{ "topic": "interval and scheduling problems", "difficulty": "medium", "provider": "baseten", "in_tokens": 236, "out_tokens": 4818, "latency_s": 35.8 }
[ { "role": "user", "content": "Write a function `next_prime(n)` that takes a non-negative integer `n` and returns the smallest prime number that is strictly greater than `n`. A prime number is an integer greater than 1 whose only positive divisors are 1 and itself. Note that if `n` itself is prime, it must n...
[ { "role": "assistant", "content": "import math\n\n\ndef is_prime(x):\n if x < 2:\n return False\n if x == 2:\n return True\n if x % 2 == 0:\n return False\n for d in range(3, math.isqrt(x) + 1, 2):\n if x % d == 0:\n return False\n return True\n\n\ndef n...
{ "topic": "math utilities (primes, gcd, numeric algorithms)", "difficulty": "easy", "provider": "together", "in_tokens": 243, "out_tokens": 1079, "latency_s": 8.9 }
[ { "role": "user", "content": "You are implementing the cave-generation stage of a roguelike game. The map is a rectangular grid of wall ('#') and floor ('.') cells, refined by a cellular automaton: in each step, every cell simultaneously becomes a wall if its 3x3 neighborhood (the cell itself plus the up to...
[ { "role": "assistant", "content": "def reachable_floor_count(grid, steps, start):\n cells = [list(row) for row in grid]\n rows, cols = len(cells), len(cells[0])\n\n for _ in range(steps):\n nxt = [['.'] * cols for _ in range(rows)]\n for r in range(rows):\n for c in range(c...
{ "topic": "simulations (game logic, cellular automata)", "difficulty": "medium", "provider": "together", "in_tokens": 241, "out_tokens": 3783, "latency_s": 22.9 }
[ { "role": "user", "content": "Write a byte-to-display text pipeline using only the standard library, without calling bytes.decode or str.encode for the UTF-8 step. Implement utf8_decode(data: bytes) -> str that decodes UTF-8 (RFC 3629) manually, byte by byte, and raises ValueError on any malformed input: in...
[ { "role": "assistant", "content": "import unicodedata\n\nELLIPSIS = '\\u2026'\n\n\ndef utf8_decode(data):\n \"\"\"Decode UTF-8 (RFC 3629) manually, raising ValueError on malformed input.\"\"\"\n chars = []\n i = 0\n n = len(data)\n while i < n:\n b0 = data[i]\n if b0 < 0x80:\n ...
{ "topic": "string encodings, unicode, and formatting", "difficulty": "hard", "provider": "together", "in_tokens": 240, "out_tokens": 5578, "latency_s": 78.4 }
[ { "role": "user", "content": "You are given a rectangular grid representing a dungeon, provided as a list of equal-length strings, where each cell is one of: 'S' (your start, exactly one), 'T' (the treasure, exactly one), 'K' (a key, exactly one), 'D' (a locked door, possibly several), '#' (a wall), or '.' ...
[ { "role": "assistant", "content": "from collections import deque\n\n\ndef min_steps_with_key(grid):\n rows, cols = len(grid), len(grid[0])\n start = target = None\n for r in range(rows):\n for c in range(cols):\n if grid[r][c] == 'S':\n start = (r, c)\n e...
{ "topic": "graph traversal (BFS/DFS)", "difficulty": "medium", "provider": "baseten", "in_tokens": 240, "out_tokens": 3729, "latency_s": 33.6 }
[ { "role": "user", "content": "Write a function `closest_value(nums, target)` that takes a non-empty list of integers `nums` and an integer `target`, and returns the value from `nums` that is closest to `target`. If two values are equally close to `target`, return the smaller of the two. Your solution must f...
[ { "role": "assistant", "content": "from bisect import bisect_left\n\n\ndef closest_value(nums, target):\n if not nums:\n raise ValueError('nums must be non-empty')\n ordered = sorted(nums)\n i = bisect_left(ordered, target)\n best = None\n for j in (i - 1, i):\n if 0 <= j < len(...
{ "topic": "sorting and searching problems", "difficulty": "easy", "provider": "together", "in_tokens": 236, "out_tokens": 1637, "latency_s": 7.7 }
[ { "role": "user", "content": "Given a list of n integers nums (2 <= n <= 100000, each |nums[i]| <= 10^6) and an integer k, consider all n*(n-1)/2 unordered index pairs (i, j) with i < j, where the distance of a pair is abs(nums[i] - nums[j]). Collect all of these distances into a list D, sort D in nondecrea...
[ { "role": "assistant", "content": "def kth_smallest_pair_distance(nums, k):\n nums = sorted(nums)\n n = len(nums)\n\n def count_at_most(limit):\n # Count pairs (i, j), i < j, with nums[j] - nums[i] <= limit.\n total = 0\n left = 0\n for right in range(n):\n wh...
{ "topic": "sorting and searching problems", "difficulty": "hard", "provider": "together", "in_tokens": 236, "out_tokens": 2388, "latency_s": 46.5 }
[ { "role": "user", "content": "Write a function make_banner(data: bytes, width: int) -> str that builds a centered banner line from raw bytes. Decode data as UTF-8, replacing any undecodable byte sequences with the Unicode replacement character U+FFFD, then normalize the decoded text using NFC. Define the di...
[ { "role": "assistant", "content": "import unicodedata\n\n\ndef display_width(text):\n \"\"\"Return the number of terminal columns needed to display text.\"\"\"\n total = 0\n for ch in text:\n if unicodedata.combining(ch):\n continue\n if unicodedata.east_asian_width(ch) in ...
{ "topic": "string encodings, unicode, and formatting", "difficulty": "medium", "provider": "together", "in_tokens": 240, "out_tokens": 3749, "latency_s": 41.2 }
[ { "role": "user", "content": "Maya wants to attend as many club meetings as possible this semester, but she can only be in one meeting at a time. Each meeting is given as a tuple (start, end) of integers representing its start and end time. A meeting that ends exactly when another begins does not conflict, ...
[ { "role": "assistant", "content": "def max_meetings(meetings):\n \"\"\"Return the maximum number of non-overlapping meetings that can be attended.\n\n Uses a greedy strategy: repeatedly pick the meeting that ends earliest\n among those that start at or after the end of the last chosen meeting.\n ...
{ "topic": "interval and scheduling problems", "difficulty": "easy", "provider": "together", "in_tokens": 236, "out_tokens": 1637, "latency_s": 16 }
[ { "role": "user", "content": "Write a function `free_slots(window_start, window_end, busy)` that computes the free time intervals inside a working window. The window is the half-open range `[window_start, window_end)` and `busy` is a list of `(start, end)` integer tuples describing busy intervals, which may...
[ { "role": "assistant", "content": "def free_slots(window_start, window_end, busy):\n \"\"\"Return the sorted maximal free intervals within [window_start, window_end).\n\n busy is an iterable of (start, end) integer tuples that may be unsorted,\n overlapping, or partially outside the window. All int...
{ "topic": "unit-testable small algorithms", "difficulty": "medium", "provider": "together", "in_tokens": 237, "out_tokens": 3475, "latency_s": 46.2 }
[ { "role": "user", "content": "For a positive integer n, define G(n) = gcd(1, n) + gcd(2, n) + ... + gcd(n, n), the sum of the greatest common divisors of n with every integer from 1 to n. Write a program that reads a single integer n (1 <= n <= 10^18) from standard input and prints G(n). Because n can be as...
[ { "role": "assistant", "content": "import sys\nimport math\nimport random\n\nSMALL_PRIMES = (2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37)\nMR_BASES = (2, 325, 9375, 28178, 450775, 9780504, 1795265022)\n\n\ndef is_prime(n):\n if n < 2:\n return False\n for p in SMALL_PRIMES:\n if n % p == ...
{ "topic": "math utilities (primes, gcd, numeric algorithms)", "difficulty": "hard", "provider": "together", "in_tokens": 243, "out_tokens": 5219, "latency_s": 62.2 }
[ { "role": "user", "content": "A small grocery store keeps a log of purchases, where each entry is a tuple (customer_name, item_name) meaning that customer bought that item at least once. The same customer-item pair may appear multiple times in the log, but duplicates should not affect the result. Write a fu...
[ { "role": "assistant", "content": "def common_items(records):\n purchases = {}\n for customer, item in records:\n purchases.setdefault(customer, set()).add(item)\n\n if not purchases:\n return set()\n\n item_sets = list(purchases.values())\n common = item_sets[0].copy()\n for...
{ "topic": "dictionary and set algorithms", "difficulty": "easy", "provider": "together", "in_tokens": 236, "out_tokens": 1295, "latency_s": 20.9 }
[ { "role": "user", "content": "A company network consists of n servers labeled 0 through n-1, connected by bidirectional links given as a list of pairs. At minute 0, every server in the list `infected` is compromised by a virus; each subsequent minute, the virus spreads from every infected server to all of i...
[ { "role": "assistant", "content": "from collections import deque\n\n\ndef infection_time(n, links, infected):\n graph = [[] for _ in range(n)]\n for a, b in links:\n graph[a].append(b)\n graph[b].append(a)\n\n dist = [-1] * n\n queue = deque()\n for source in infected:\n ...
{ "topic": "graph traversal (BFS/DFS)", "difficulty": "medium", "provider": "together", "in_tokens": 240, "out_tokens": 1622, "latency_s": 34.5 }
[ { "role": "user", "content": "A small shop keeps a list of integer prices for its items, but the list is unsorted. A customer walks in with a budget and wants to buy the single most expensive item they can afford, meaning the largest price that is less than or equal to the budget. Write a function `best_aff...
[ { "role": "assistant", "content": "def best_affordable(prices, budget):\n \"\"\"Return the largest price <= budget, or -1 if nothing is affordable.\"\"\"\n ordered = sorted(prices) # sorted() leaves the caller's list untouched\n lo, hi = 0, len(ordered) - 1\n best = -1\n # Binary search for ...
{ "topic": "sorting and searching problems", "difficulty": "easy", "provider": "together", "in_tokens": 236, "out_tokens": 1563, "latency_s": 22.5 }
[ { "role": "user", "content": "Build a small user-registration validator based on custom exceptions. Define a base exception `ValidationError(Exception)` whose constructor accepts a `field` name and a `message`, stores both as attributes, and makes `str(err)` return `'<field>: <message>'`; derive from it `Us...
[ { "role": "assistant", "content": "class ValidationError(Exception):\n \"\"\"Base class for field validation errors.\"\"\"\n\n def __init__(self, field, message):\n self.field = field\n self.message = message\n super().__init__(f\"{field}: {message}\")\n\n def __str__(self):\n ...
{ "topic": "error handling and custom exceptions", "difficulty": "medium", "provider": "together", "in_tokens": 237, "out_tokens": 5246, "latency_s": 60.6 }
[ { "role": "user", "content": "In the realm of Graphania there are n cities numbered 1..n, connected by m bidirectional roads, each of which takes 1 hour to traverse. Every city i bears a magical sigil s_i; a traveler standing in any city may activate a portal to any other city carrying the same sigil, and u...
[ { "role": "assistant", "content": "import sys\nfrom collections import deque, defaultdict\n\ndef main():\n data = sys.stdin.buffer.read().split()\n if not data:\n return\n pos = 0\n n = int(data[pos]); pos += 1\n m = int(data[pos]); pos += 1\n sigil = [0] * (n + 1)\n for i in ran...
{ "topic": "graph traversal (BFS/DFS)", "difficulty": "hard", "provider": "together", "in_tokens": 240, "out_tokens": 3020, "latency_s": 57.1 }
[ { "role": "user", "content": "Using the dataclasses module, define a frozen dataclass `Book` with fields `title` (str), `author` (str), and `price` (float). Then apply the Factory design pattern: implement a class `BookFactory` with a static method `from_string(text)` that parses a string in the format 'tit...
[ { "role": "assistant", "content": "from dataclasses import dataclass, replace\n\n\n@dataclass(frozen=True)\nclass Book:\n title: str\n author: str\n price: float\n\n def apply_discount(self, percent: float) -> \"Book\":\n new_price = round(self.price * (1 - percent / 100), 2)\n ret...
{ "topic": "dataclass and OOP design patterns", "difficulty": "easy", "provider": "together", "in_tokens": 239, "out_tokens": 1249, "latency_s": 14 }
[ { "role": "user", "content": "Create a small pricing system using dataclasses and the Strategy design pattern. First, define a dataclass `Item` with fields `name` (str) and `price` (float). Then define a base class `DiscountStrategy` with a method `apply(total)` that returns the total unchanged, a subclass ...
[ { "role": "assistant", "content": "from dataclasses import dataclass\nfrom typing import List, Optional\n\n\n@dataclass\nclass Item:\n name: str\n price: float\n\n\nclass DiscountStrategy:\n def apply(self, total: float) -> float:\n return total\n\n\nclass NoDiscount(DiscountStrategy):\n ...
{ "topic": "dataclass and OOP design patterns", "difficulty": "easy", "provider": "together", "in_tokens": 239, "out_tokens": 2628, "latency_s": 24.8 }
[ { "role": "user", "content": "Write a generator function called `interleave(a, b)` that takes two iterables and yields their items alternately: first the first item of `a`, then the first item of `b`, then the second item of `a`, and so on. If one iterable is shorter than the other, yield all remaining item...
[ { "role": "assistant", "content": "from itertools import zip_longest\n\n\ndef interleave(a, b):\n \"\"\"Yield items from two iterables alternately.\n\n Starts with the first item of `a`. When one iterable is exhausted,\n yields the remaining items of the other in their original order.\n Works la...
{ "topic": "iterators, generators, and itertools", "difficulty": "easy", "provider": "together", "in_tokens": 238, "out_tokens": 2449, "latency_s": 23.9 }
[ { "role": "user", "content": "The Caesar cipher encrypts a message by shifting every letter forward through the alphabet by a fixed number of positions, wrapping around from 'z' back to 'a'. Write a function `encrypt(text, shift)` that returns the encrypted version of `text` using the given integer `shift`....
[ { "role": "assistant", "content": "def encrypt(text, shift):\n shift %= 26\n chars = []\n for ch in text:\n if 'a' <= ch <= 'z':\n chars.append(chr((ord(ch) - ord('a') + shift) % 26 + ord('a')))\n elif 'A' <= ch <= 'Z':\n chars.append(chr((ord(ch) - ord('A') + sh...
{ "topic": "cryptography basics (hashing, ciphers)", "difficulty": "easy", "provider": "together", "in_tokens": 241, "out_tokens": 2037, "latency_s": 34.3 }
[ { "role": "user", "content": "Write a function `longest_run(nums)` that takes a list of integers and returns the length of the longest run of consecutive equal values. A run is a maximal stretch of adjacent elements that are all identical. If the list is empty, the function must return 0. If no two adjacent...
[ { "role": "assistant", "content": "def longest_run(nums):\n # Track the current streak and the best streak seen so far.\n best = 0\n streak = 0\n prev = object() # sentinel that never equals a real list element\n for value in nums:\n if value == prev:\n streak += 1\n ...
{ "topic": "unit-testable small algorithms", "difficulty": "easy", "provider": "together", "in_tokens": 237, "out_tokens": 2109, "latency_s": 27.9 }
[ { "role": "user", "content": "You are implementing a task runner for an operating system. Tasks are added with a name and an integer priority; lower numbers mean higher priority, and tasks with equal priority run in the order they were added (first-in, first-out, like a queue). The runner keeps a history st...
[ { "role": "assistant", "content": "import heapq\n\n\ndef simulate(commands):\n pending = [] # heap of (priority, arrival_order, name); arrival_order gives FIFO tie-breaking\n completed = [] # stack of (name, priority) for undo\n counter = 0\n result = []\n for command in commands:\n ...
{ "topic": "queues, stacks, and heap-based algorithms", "difficulty": "medium", "provider": "together", "in_tokens": 240, "out_tokens": 2530, "latency_s": 44.5 }
[ { "role": "user", "content": "Create two custom exception classes, InvalidAmountError and InsufficientFundsError, both inheriting from Exception. Then implement a BankAccount class with an __init__(self, balance=0) method that stores the starting balance, a deposit(self, amount) method that adds amount to t...
[ { "role": "assistant", "content": "class InvalidAmountError(Exception):\n \"\"\"Raised when a deposit or withdrawal amount is not a positive number.\"\"\"\n pass\n\n\nclass InsufficientFundsError(Exception):\n \"\"\"Raised when a withdrawal exceeds the current balance.\"\"\"\n pass\n\n\nclass Ba...
{ "topic": "error handling and custom exceptions", "difficulty": "easy", "provider": "together", "in_tokens": 237, "out_tokens": 1033, "latency_s": 24.1 }
[ { "role": "user", "content": "An archipelago is represented by an n x m grid of integer elevations. For a given sea level L, every cell whose elevation is strictly greater than L is dry land, and a maximal set of dry cells connected through shared edges (up, down, left, right) forms one island. You are give...
[ { "role": "assistant", "content": "import sys\n\n\ndef count_islands(grid, levels):\n n = len(grid)\n m = len(grid[0])\n total = n * m\n parent = list(range(total))\n rank = [0] * total\n active = [False] * total\n\n def find(x):\n while parent[x] != x:\n parent[x] = p...
{ "topic": "matrix and 2D-grid operations", "difficulty": "hard", "provider": "together", "in_tokens": 239, "out_tokens": 3537, "latency_s": 60.6 }
[ { "role": "user", "content": "You are given the head of a singly linked list of integers. Define a class ListNode with attributes val and next, and write a function alternating_sum(head) that returns the alternating sum of the node values: the first value minus the second value plus the third value minus th...
[ { "role": "assistant", "content": "class ListNode:\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\n\n\ndef alternating_sum(head):\n total = 0\n sign = 1\n current = head\n while current is not None:\n total += sign * current.val\n sign ...
{ "topic": "linked list or binary tree operations", "difficulty": "easy", "provider": "together", "in_tokens": 238, "out_tokens": 1240, "latency_s": 18.3 }
[ { "role": "user", "content": "Write a function normalize_times(text) that scans a string for time expressions written in 12-hour clock format and rewrites each one in 24-hour format, returning the resulting string. A valid expression consists of an hour from 1 to 12 (optionally written with a leading zero),...
[ { "role": "assistant", "content": "import re\n\nTIME_PATTERN = re.compile(r'\\b(0?[1-9]|1[0-2]):([0-5][0-9])\\s*([AaPp])[Mm]\\b')\n\n\ndef normalize_times(text):\n def repl(match):\n hour = int(match.group(1))\n minute = match.group(2)\n if match.group(3).upper() == 'A':\n ...
{ "topic": "regular expressions", "difficulty": "medium", "provider": "together", "in_tokens": 234, "out_tokens": 2849, "latency_s": 23.1 }
[ { "role": "user", "content": "Many recurring events are scheduled by rules like 'the fourth Thursday of November' or 'the last Friday of the month' rather than by a fixed calendar date. Write a function `nth_weekday_of_month(year, month, weekday, n)` that returns a `datetime.date` for the nth occurrence of ...
[ { "role": "assistant", "content": "import calendar\nfrom datetime import date\n\n\ndef nth_weekday_of_month(year, month, weekday, n):\n \"\"\"Return the date of the nth occurrence of weekday in the given month.\n\n weekday: 0 = Monday ... 6 = Sunday.\n n: 1-based; positive counts from the start of ...
{ "topic": "datetime and calendar logic", "difficulty": "medium", "provider": "together", "in_tokens": 236, "out_tokens": 3125, "latency_s": 28.8 }
[ { "role": "user", "content": "Write a function `flatten_json(data: str) -> str` that parses a JSON string and returns a flattened JSON serialization of it. The top-level JSON value must be an object; if it is not, raise a ValueError. Flattening works as follows: nested objects are merged into the parent usi...
[ { "role": "assistant", "content": "import json\n\n\ndef flatten_json(data: str) -> str:\n \"\"\"Parse a JSON string and return a flattened, canonical JSON string.\"\"\"\n parsed = json.loads(data)\n if not isinstance(parsed, dict):\n raise ValueError(\"Top-level JSON value must be an object\...
{ "topic": "JSON parsing and serialization", "difficulty": "medium", "provider": "together", "in_tokens": 236, "out_tokens": 3531, "latency_s": 36.3 }
[ { "role": "user", "content": "Given a positive integer n, count the number of 1-bits in its binary representation (its population count). Write a program that finds the smallest integer m strictly greater than n whose binary representation contains exactly the same number of 1-bits as n. Input: a single lin...
[ { "role": "assistant", "content": "import sys\n\n\ndef next_same_popcount(n):\n # Bit hack for the next larger integer with the same number of set bits.\n # c isolates the lowest set bit of n.\n c = n & -n\n # Adding c flips the lowest run of ones into a single higher one.\n r = n + c\n # ...
{ "topic": "bit manipulation", "difficulty": "medium", "provider": "together", "in_tokens": 234, "out_tokens": 1362, "latency_s": 19.8 }
[ { "role": "user", "content": "Write a function next_prime(n) that takes an integer n (which may be negative, zero, or positive) and returns the smallest prime number p such that p >= n. Recall that a prime is an integer greater than 1 whose only positive divisors are 1 and itself, so the smallest possible a...
[ { "role": "assistant", "content": "import math\n\ndef is_prime(x):\n if x < 2:\n return False\n if x == 2:\n return True\n if x % 2 == 0:\n return False\n for d in range(3, math.isqrt(x) + 1, 2):\n if x % d == 0:\n return False\n return True\n\ndef next_...
{ "topic": "math utilities (primes, gcd, numeric algorithms)", "difficulty": "easy", "provider": "together", "in_tokens": 243, "out_tokens": 1278, "latency_s": 19.7 }
[ { "role": "user", "content": "Write a function `add_business_days(start, days, holidays=None)` that computes the date a given number of business days away from a start date. `start` is a `datetime.date`, `days` is an integer (positive moves forward, negative moves backward, and zero returns `start` unchange...
[ { "role": "assistant", "content": "from datetime import date, timedelta\n\n\ndef add_business_days(start, days, holidays=None):\n holiday_set = set(holidays) if holidays else set()\n current = start\n step = timedelta(days=1) if days >= 0 else timedelta(days=-1)\n remaining = abs(days)\n whil...
{ "topic": "datetime and calendar logic", "difficulty": "medium", "provider": "together", "in_tokens": 236, "out_tokens": 2208, "latency_s": 20 }
[ { "role": "user", "content": "Write a function earliest_free_slot(busy, duration) that finds the earliest time a meeting can start. busy is a list of (start, end) tuples of integers representing half-open busy intervals [start, end); the list may be unsorted and intervals may overlap. duration is a positive...
[ { "role": "assistant", "content": "def earliest_free_slot(busy, duration):\n \"\"\"Return the smallest non-negative integer t such that the half-open\n interval [t, t + duration) does not overlap any busy interval.\n\n Busy intervals are half-open [start, end), may be unsorted, and may\n overlap...
{ "topic": "unit-testable small algorithms", "difficulty": "medium", "provider": "together", "in_tokens": 237, "out_tokens": 2390, "latency_s": 51.8 }
[ { "role": "user", "content": "Euler's totient function phi(k) counts the integers between 1 and k (inclusive) that are coprime with k. Write a program that reads a single integer n (1 <= n <= 200000) from standard input and prints the summatory totient function: the sum of phi(k) for all k from 1 to n. By c...
[ { "role": "assistant", "content": "import sys\n\n\ndef summatory_totient(n):\n phi = list(range(n + 1))\n for p in range(2, n + 1):\n if phi[p] == p: # p is prime\n for multiple in range(p, n + 1, p):\n phi[multiple] -= phi[multiple] // p\n return sum(phi)\n\n\ndef...
{ "topic": "math utilities (primes, gcd, numeric algorithms)", "difficulty": "medium", "provider": "deepinfra", "in_tokens": 246, "out_tokens": 628, "latency_s": 54.8 }
[ { "role": "user", "content": "You are implementing a priority-aware task executor that processes a list of commands strictly in the order they arrive, i.e. the command list is consumed as a FIFO queue. Each command is a tuple: ('add', name, priority) registers a new task with a string name and an integer pr...
[ { "role": "assistant", "content": "import heapq\nfrom collections import deque\n\n\ndef simulate(commands):\n queue = deque(commands)\n heap = [] # entries: (-priority, seq, task_id, name)\n stack = [] # task_ids in registration order, used by undo\n pending = {} # task_id...
{ "topic": "queues, stacks, and heap-based algorithms", "difficulty": "medium", "provider": "together", "in_tokens": 240, "out_tokens": 3177, "latency_s": 44.9 }
[ { "role": "user", "content": "Implement two functions, seal(message, key) and unseal(token, key), that together form a tiny authenticated encryption scheme built from the Vigenère cipher and SHA-256. The Vigenère cipher shifts each lowercase letter of message forward by the alphabet position (a=0, b=1, ...,...
[ { "role": "assistant", "content": "import hashlib\nimport hmac\n\n\ndef _shift_char(ch, shift):\n return chr((ord(ch) - 97 + shift) % 26 + 97)\n\n\ndef _vigenere(text, key, decrypt=False):\n shifts = [ord(ch) - 97 for ch in key]\n result = []\n pos = 0\n for ch in text:\n if 'a' <= ch ...
{ "topic": "cryptography basics (hashing, ciphers)", "difficulty": "medium", "provider": "together", "in_tokens": 241, "out_tokens": 5758, "latency_s": 64.7 }
[ { "role": "user", "content": "Write a function `reverse_even_words(sentence)` that takes a sentence consisting of lowercase words separated by single spaces. The function must reverse every word whose length is even, while words with an odd length must remain unchanged. The order of the words in the sentenc...
[ { "role": "assistant", "content": "def reverse_even_words(sentence):\n if not sentence:\n return sentence\n processed = []\n for word in sentence.split(' '):\n if len(word) % 2 == 0:\n processed.append(word[::-1])\n else:\n processed.append(word)\n retu...
{ "topic": "string manipulation and text processing", "difficulty": "easy", "provider": "together", "in_tokens": 237, "out_tokens": 1772, "latency_s": 24.3 }
[ { "role": "user", "content": "Write a function `file_stats(path)` that takes the path to a UTF-8 text file and returns a dictionary summarizing its contents. The dictionary must contain exactly three keys: 'lines', the number of lines in the file; 'words', the total number of whitespace-separated words; and...
[ { "role": "assistant", "content": "def file_stats(path):\n with open(path, \"r\", encoding=\"utf-8\") as f:\n text = f.read()\n lines = text.splitlines()\n return {\n \"lines\": len(lines),\n \"words\": len(text.split()),\n \"chars\": sum(len(line) for line in lines),\n ...
{ "topic": "working with files and paths", "difficulty": "easy", "provider": "together", "in_tokens": 237, "out_tokens": 1338, "latency_s": 21.6 }
[ { "role": "user", "content": "A wildlife researcher wants to install k camera traps along a straight forest trail, and there are n suitable mounting spots at integer positions along the trail. To prevent the cameras from interfering with each other, the researcher must choose exactly k of the spots so that ...
[ { "role": "assistant", "content": "import sys\n\ndef max_min_distance(positions, k):\n positions.sort()\n\n def can_place(d):\n count = 1\n last = positions[0]\n for p in positions[1:]:\n if p - last >= d:\n count += 1\n last = p\n ...
{ "topic": "sorting and searching problems", "difficulty": "medium", "provider": "together", "in_tokens": 236, "out_tokens": 2040, "latency_s": 34.9 }
[ { "role": "user", "content": "A frog is crossing a river by hopping across a row of n stepping stones, where each stone has a positive toll given in a list `costs`. The frog starts on the first stone (index 0), pays the toll of every stone it lands on (including the first and the last), and may jump either ...
[ { "role": "assistant", "content": "import sys\n\n\ndef min_crossing_cost(costs):\n n = len(costs)\n if n == 1:\n return costs[0]\n prev2 = costs[0]\n prev1 = costs[0] + costs[1]\n for i in range(2, n):\n cur = costs[i] + min(prev1, prev2)\n prev2, prev1 = prev1, cur\n ...
{ "topic": "dynamic programming exercises", "difficulty": "easy", "provider": "together", "in_tokens": 235, "out_tokens": 1136, "latency_s": 15.2 }
[ { "role": "user", "content": "Decorators are higher-order functions: they take a function as input and return a new function. Write a decorator called `count_calls` that wraps any function so it keeps track of how many times it has been invoked. The wrapped function must behave exactly like the original (sa...
[ { "role": "assistant", "content": "import functools\n\n\ndef count_calls(func):\n \"\"\"Decorator that counts how many times the wrapped function is called.\"\"\"\n @functools.wraps(func)\n def wrapper(*args, **kwargs):\n wrapper.call_count += 1\n return func(*args, **kwargs)\n wra...
{ "topic": "decorators and higher-order functions", "difficulty": "easy", "provider": "together", "in_tokens": 237, "out_tokens": 1396, "latency_s": 12 }
[ { "role": "user", "content": "Write a function `seal_message(message, shift)` that protects a secret message with a Caesar cipher plus an integrity tag. The `message` contains only lowercase letters (a-z) and spaces; shift each letter forward by `shift` positions in the alphabet, wrapping around (so 'z' shi...
[ { "role": "assistant", "content": "import hashlib\n\n\ndef seal_message(message, shift):\n shift %= 26\n encrypted_chars = []\n for ch in message:\n if ch == \" \":\n encrypted_chars.append(\" \")\n else:\n encrypted_chars.append(chr((ord(ch) - ord(\"a\") + shift...
{ "topic": "cryptography basics (hashing, ciphers)", "difficulty": "easy", "provider": "together", "in_tokens": 241, "out_tokens": 2269, "latency_s": 52.3 }
[ { "role": "user", "content": "Implement a keyword substitution cipher using only the Python standard library. Write a function build_alphabet(keyword) that returns a 26-character uppercase string: the unique ASCII letters of the keyword (uppercased, in order of first appearance, ignoring non-letters) follow...
[ { "role": "assistant", "content": "import hashlib\nimport string\n\n\ndef _normalized_letters(keyword):\n letters = []\n for ch in keyword.upper():\n if ch in string.ascii_uppercase and ch not in letters:\n letters.append(ch)\n return letters\n\n\ndef build_alphabet(keyword):\n ...
{ "topic": "cryptography basics (hashing, ciphers)", "difficulty": "medium", "provider": "together", "in_tokens": 241, "out_tokens": 4594, "latency_s": 38.9 }
[ { "role": "user", "content": "Write a function `total_size_by_extension(folder)` that takes a string path to a directory and returns a dictionary mapping each file extension (including the leading dot, lowercased) to the total size in bytes of all regular files with that extension located directly inside th...
[ { "role": "assistant", "content": "import os\nimport tempfile\n\n\ndef total_size_by_extension(folder):\n totals = {}\n for entry in os.scandir(folder):\n if not entry.is_file():\n continue\n ext = os.path.splitext(entry.name)[1].lower()\n if not ext:\n ext =...
{ "topic": "working with files and paths", "difficulty": "easy", "provider": "together", "in_tokens": 237, "out_tokens": 2082, "latency_s": 18.3 }
[ { "role": "user", "content": "Implement the Burrows-Wheeler transform (BWT) and its inverse in a functional style using only the standard library. The forward function bwt_encode(s) takes a string s that does not contain the sentinel character '$', appends '$', forms every cyclic rotation of the result, sor...
[ { "role": "assistant", "content": "from functools import reduce\n\n\ndef bwt_encode(s):\n if '$' in s:\n raise ValueError(\"input string must not contain the sentinel '$'\")\n t = s + '$'\n return ''.join(\n rotation[-1]\n for rotation in sorted(t[i:] + t[:i] for i in range(len...
{ "topic": "list comprehension and functional style tasks", "difficulty": "hard", "provider": "together", "in_tokens": 238, "out_tokens": 3972, "latency_s": 52 }
[ { "role": "user", "content": "Many recurring events are defined as the n-th weekday of a month — for example, U.S. Thanksgiving is the 4th Thursday of November. Write a function `nth_weekday_of_month(year, month, weekday, n)` that returns a `datetime.date` for the n-th occurrence of `weekday` (0 = Monday, ....
[ { "role": "assistant", "content": "import calendar\nfrom datetime import date\n\n\ndef nth_weekday_of_month(year, month, weekday, n):\n \"\"\"Return the date of the n-th `weekday` in the given month.\n\n weekday: 0 = Monday ... 6 = Sunday.\n n > 0 counts from the start of the month, n < 0 counts ba...
{ "topic": "datetime and calendar logic", "difficulty": "medium", "provider": "together", "in_tokens": 236, "out_tokens": 3705, "latency_s": 51.1 }
[ { "role": "user", "content": "Write a program that reads lines from standard input until end-of-file, where each line is expected to be a record in the form `name,age`. A record is valid only if it contains exactly one comma, the name (after stripping surrounding whitespace) is non-empty and consists solely...
[ { "role": "assistant", "content": "import sys\n\n\ndef parse_record(line):\n parts = line.split(\",\")\n if len(parts) != 2:\n return None\n name = parts[0].strip()\n age_text = parts[1].strip()\n if not name or not name.isalpha():\n return None\n if not age_text.isdigit():\n...
{ "topic": "parsing and validating user input", "difficulty": "easy", "provider": "together", "in_tokens": 237, "out_tokens": 1902, "latency_s": 19 }
[ { "role": "user", "content": "In a radix-2 Fast Fourier Transform, the input must be reordered by a bit-reversal permutation: the element at index i moves to the position obtained by reversing the k-bit binary representation of i, where the list length n equals 2**k. Write a function bit_reverse_permute(dat...
[ { "role": "assistant", "content": "def bit_reverse_permute(data):\n \"\"\"Return a new list where the element at index i moves to the index\n obtained by reversing the k-bit binary form of i (len(data) == 2**k).\"\"\"\n n = len(data)\n if n == 0 or (n & (n - 1)) != 0:\n raise ValueError(\...
{ "topic": "bit manipulation", "difficulty": "medium", "provider": "together", "in_tokens": 234, "out_tokens": 3676, "latency_s": 35.2 }
[ { "role": "user", "content": "A forest is represented as a list of equal-length strings where 'T' is a tree, 'F' is a burning cell, and '.' is empty ground. Each minute, every burning cell burns out and becomes empty, and every tree orthogonally adjacent (up, down, left, right) to a currently burning cell c...
[ { "role": "assistant", "content": "def trees_remaining(grid, wind, minutes):\n \"\"\"Simulate a wildfire with wind-blown embers and return trees left standing.\"\"\"\n DIRS = {\"N\": (-1, 0), \"S\": (1, 0), \"E\": (0, 1), \"W\": (0, -1)}\n dr, dc = DIRS[wind]\n g = [list(row) for row in grid]\n ...
{ "topic": "simulations (game logic, cellular automata)", "difficulty": "medium", "provider": "together", "in_tokens": 241, "out_tokens": 3279, "latency_s": 32.1 }
[ { "role": "user", "content": "A city marathon runs from time 0 to time T, and the organizers want every moment of the race broadcast live. They have a list of volunteer camera operators; operator i can film continuously during the interval [start_i, end_i], and coverage is considered seamless when one opera...
[ { "role": "assistant", "content": "def min_operators(T, intervals):\n intervals = sorted(intervals)\n n = len(intervals)\n i = 0\n covered = 0\n used = 0\n while covered < T:\n best = covered\n while i < n and intervals[i][0] <= covered:\n if intervals[i][1] > best...
{ "topic": "interval and scheduling problems", "difficulty": "medium", "provider": "together", "in_tokens": 236, "out_tokens": 2821, "latency_s": 29.5 }
[ { "role": "user", "content": "Write a function clean_and_format(records) that takes a list of (name, score) tuples and returns a single formatted string. Some names arrived as mojibake: they were UTF-8 text incorrectly decoded as Latin-1 (for example 'Renée' instead of 'Renée'), so repair each name by re-e...
[ { "role": "assistant", "content": "import unicodedata\n\n\ndef display_width(text):\n width = 0\n for ch in text:\n width += 2 if unicodedata.east_asian_width(ch) in ('W', 'F') else 1\n return width\n\n\ndef repair_mojibake(text):\n try:\n return text.encode('latin-1').decode('utf-...
{ "topic": "string encodings, unicode, and formatting", "difficulty": "medium", "provider": "baseten", "in_tokens": 240, "out_tokens": 2364, "latency_s": 14.9 }
[ { "role": "user", "content": "You are given a network of n servers, numbered from 0 to n-1, and a list of bidirectional connections between pairs of servers. A server can receive a message from another server if they are directly connected or indirectly linked through a chain of connections. Write a functio...
[ { "role": "assistant", "content": "from collections import deque\n\ndef reachable_servers(n, connections):\n if n <= 0:\n return []\n graph = [[] for _ in range(n)]\n for a, b in connections:\n graph[a].append(b)\n graph[b].append(a)\n visited = [False] * n\n visited[0] =...
{ "topic": "graph traversal (BFS/DFS)", "difficulty": "easy", "provider": "baseten", "in_tokens": 240, "out_tokens": 1390, "latency_s": 8.1 }
[ { "role": "user", "content": "Write a program that applies a JSON merge patch to a JSON document. The program reads two lines from standard input: the first line is the base JSON document and the second line is the patch JSON document. Merging follows these rules: if the patch value is not an object, it com...
[ { "role": "assistant", "content": "import json\nimport sys\n\n\ndef merge_patch(base, patch):\n if not isinstance(patch, dict):\n return patch\n if not isinstance(base, dict):\n base = {}\n result = dict(base)\n for key, value in patch.items():\n if value is None:\n ...
{ "topic": "JSON parsing and serialization", "difficulty": "medium", "provider": "together", "in_tokens": 236, "out_tokens": 2722, "latency_s": 42.9 }
[ { "role": "user", "content": "Write a function `parse_scores(text)` that parses a string of comma-separated exam scores into a list of integers. Split the input on commas and strip surrounding whitespace from each token; an empty or whitespace-only input string should produce an empty list. Every token must...
[ { "role": "assistant", "content": "def parse_scores(text):\n \"\"\"Parse a comma-separated string of exam scores into a list of ints.\n\n Each token must be digits only and in the range 0..100 inclusive.\n Raises ValueError with 'Invalid score: <token>' for any bad token.\n \"\"\"\n if not te...
{ "topic": "parsing and validating user input", "difficulty": "easy", "provider": "together", "in_tokens": 237, "out_tokens": 1367, "latency_s": 20.2 }
[ { "role": "user", "content": "Write a command-line tool wordfreq.py that prints the most frequent words in a text. A word is a maximal run of ASCII letters (A-Z, a-z); every other character is a separator, and matching is case-insensitive, so 'Dog' and 'dog' count as the same word and are reported in lowerc...
[ { "role": "assistant", "content": "import argparse\nimport re\nimport sys\nfrom collections import Counter\n\nWORD_RE = re.compile(r\"[A-Za-z]+\")\n\n\ndef count_words(stream, counts):\n for line in stream:\n counts.update(match.group(0).lower() for match in WORD_RE.finditer(line))\n\n\ndef main()...
{ "topic": "small command-line tool logic", "difficulty": "medium", "provider": "together", "in_tokens": 237, "out_tokens": 1993, "latency_s": 24 }
[ { "role": "user", "content": "Create a custom exception class named InvalidScoreError that inherits from ValueError. Then write a function add_score(scores, score) that appends score to the list scores and returns the list; if score is not an int or float between 0 and 100 inclusive, it must raise InvalidSc...
[ { "role": "assistant", "content": "class InvalidScoreError(ValueError):\n \"\"\"Custom exception raised for invalid scores or missing score data.\"\"\"\n pass\n\n\ndef add_score(scores, score):\n if isinstance(score, bool) or not isinstance(score, (int, float)) or not 0 <= score <= 100:\n ra...
{ "topic": "error handling and custom exceptions", "difficulty": "easy", "provider": "together", "in_tokens": 237, "out_tokens": 1438, "latency_s": 14.3 }
[ { "role": "user", "content": "A coastal survey maps a rectangular region as a grid of non-negative integers, where grid[r][c] is the elevation of cell (r, c); the grid has at most 100 rows and 100 columns and elevations between 0 and 100. The sea level w is a non-negative integer, a cell counts as dry land ...
[ { "role": "assistant", "content": "from collections import defaultdict\n\n\ndef count_islands(grid):\n \"\"\"Return a list ans where ans[w] is the number of islands at sea level w.\n\n A cell is dry land when its elevation is strictly greater than w, and an\n island is a maximal 4-directionally con...
{ "topic": "matrix and 2D-grid operations", "difficulty": "hard", "provider": "together", "in_tokens": 239, "out_tokens": 5556, "latency_s": 53.4 }
[ { "role": "user", "content": "A palindrome partition of a string s splits s into contiguous non-empty pieces that are each palindromes (for example 'aa|b' is a palindrome partition of 'aab'). Call a palindrome partition rhythmic if no two adjacent pieces have the same length. Given a string s of lowercase E...
[ { "role": "assistant", "content": "import sys\n\ndef main():\n data = sys.stdin.read().split()\n if not data:\n return\n s = data[0]\n n = len(s)\n MOD = 10**9 + 7\n\n # is_pal[l][r] == 1 iff s[l:r] is a palindrome (0 <= l < r <= n)\n is_pal = [bytearray(n + 1) for _ in range(n +...
{ "topic": "dynamic programming exercises", "difficulty": "hard", "provider": "baseten", "in_tokens": 235, "out_tokens": 5353, "latency_s": 34.8 }
[ { "role": "user", "content": "Implement a tamper-evident Vigenere cipher using only the Python standard library. Write two functions: encrypt(plaintext, key) and decrypt(token, key), where plaintext and key are non-empty strings of uppercase letters A-Z. Encryption shifts each plaintext letter forward in th...
[ { "role": "assistant", "content": "def _shift(ch, key_ch, decrypt=False):\n v = ord(ch) - ord('A')\n k = ord(key_ch) - ord('A')\n v = (v - k) % 26 if decrypt else (v + k) % 26\n return chr(v + ord('A'))\n\n\ndef _checksum(ciphertext):\n return sum((i + 1) * (ord(ch) - ord('A') + 1) for i, ch ...
{ "topic": "cryptography basics (hashing, ciphers)", "difficulty": "medium", "provider": "together", "in_tokens": 241, "out_tokens": 3613, "latency_s": 46.3 }
[ { "role": "user", "content": "A newly discovered alien language uses the same lowercase English letters, but with an unknown alphabetical order. You are given a list of words that are sorted according to this alien language's dictionary rules (as in a normal dictionary, a word that is a proper prefix of ano...
[ { "role": "assistant", "content": "import heapq\nfrom collections import defaultdict\n\n\ndef alien_order(words):\n \"\"\"Return the lexicographically smallest alphabet ordering consistent\n with the sorted alien dictionary `words`, or \"\" if none exists.\"\"\"\n letters = set()\n for word in w...
{ "topic": "unit-testable small algorithms", "difficulty": "hard", "provider": "together", "in_tokens": 237, "out_tokens": 5367, "latency_s": 49 }
[ { "role": "user", "content": "An astronomer has n telescopes mounted along a straight rail, and the i-th telescope sits at integer coordinate positions[i] (coordinates may repeat and are given in arbitrary order). For every unordered pair of telescopes, define their separation as the absolute difference of ...
[ { "role": "assistant", "content": "import sys\n\n\ndef kth_smallest_separation(positions, k):\n positions.sort()\n n = len(positions)\n\n def count_pairs_within(limit):\n # Count pairs (i, j) with i < j and positions[j] - positions[i] <= limit\n # using a sliding window over the sorte...
{ "topic": "sorting and searching problems", "difficulty": "hard", "provider": "together", "in_tokens": 236, "out_tokens": 2276, "latency_s": 34.4 }
[ { "role": "user", "content": "A support system scans messages for ticket codes. A valid ticket code consists of exactly two uppercase English letters (A-Z) immediately followed by exactly four digits (0-9), and it must not be part of a longer alphanumeric sequence (so 'AB12345' or 'XAB1234' do not count). W...
[ { "role": "assistant", "content": "import re\n\n\ndef find_ticket_codes(text):\n \"\"\"Return a list of all valid ticket codes found in text.\n\n A valid code is exactly two uppercase letters followed by exactly\n four digits, not embedded inside a longer alphanumeric sequence.\n The word-bounda...
{ "topic": "regular expressions", "difficulty": "easy", "provider": "together", "in_tokens": 234, "out_tokens": 1792, "latency_s": 13.5 }
[ { "role": "user", "content": "Write a function `unicode_report(text)` that takes a string and returns a formatted report with exactly one line per character. Each line must have the form `<char> U+<CODE> <UTF8>`, where `<char>` is the character itself, `<CODE>` is its Unicode code point as uppercase hexadec...
[ { "role": "assistant", "content": "def unicode_report(text):\n lines = []\n for ch in text:\n code_point = f\"U+{ord(ch):04X}\"\n utf8_bytes = \" \".join(f\"{byte:02x}\" for byte in ch.encode(\"utf-8\"))\n lines.append(f\"{ch} {code_point} {utf8_bytes}\")\n return \"\\n\".join(...
{ "topic": "string encodings, unicode, and formatting", "difficulty": "easy", "provider": "together", "in_tokens": 240, "out_tokens": 959, "latency_s": 10.3 }
[ { "role": "user", "content": "Write a function `common_counts(a, b)` that takes two lists of integers and returns a dictionary describing the numbers that appear in BOTH lists. For every integer that occurs in both `a` and `b`, the dictionary should map that integer to the total number of times it occurs ac...
[ { "role": "assistant", "content": "def common_counts(a, b):\n counts_a = {}\n counts_b = {}\n for x in a:\n counts_a[x] = counts_a.get(x, 0) + 1\n for x in b:\n counts_b[x] = counts_b.get(x, 0) + 1\n common = set(counts_a) & set(counts_b)\n return {x: counts_a[x] + counts_b[x...
{ "topic": "dictionary and set algorithms", "difficulty": "easy", "provider": "together", "in_tokens": 236, "out_tokens": 1305, "latency_s": 18.3 }
[ { "role": "user", "content": "Write a generator function `diagonal_product(a, b)` that takes two iterables—either of which may be infinite—and yields tuples `(x, y)` pairing one item from `a` with one from `b` in Cantor diagonal order: for each sum `s = 0, 1, 2, ...`, yield every pair `(a_i, b_j)` with `i +...
[ { "role": "assistant", "content": "from itertools import count, islice\n\n\ndef diagonal_product(a, b):\n \"\"\"Yield (a_i, b_j) pairs in Cantor diagonal order (grouped by i + j,\n then ordered by increasing i within each group).\n\n Both iterables are consumed lazily and at most once. Items pulled...
{ "topic": "iterators, generators, and itertools", "difficulty": "hard", "provider": "together", "in_tokens": 238, "out_tokens": 5206, "latency_s": 70.5 }
[ { "role": "user", "content": "Write a function `count_peaks(numbers)` that takes a list of integers and returns the number of 'peaks' in the list. A peak is an element that is strictly greater than both of its immediate neighbors; the first and last elements can never be peaks because they each have only on...
[ { "role": "assistant", "content": "def count_peaks(numbers):\n \"\"\"Return the number of elements strictly greater than both neighbors.\"\"\"\n return sum(\n 1\n for i in range(1, len(numbers) - 1)\n if numbers[i] > numbers[i - 1] and numbers[i] > numbers[i + 1]\n )\n\n\nif __...
{ "topic": "unit-testable small algorithms", "difficulty": "easy", "provider": "together", "in_tokens": 237, "out_tokens": 2307, "latency_s": 27.7 }
[ { "role": "user", "content": "You are given a list of order records returned by a fictional e-commerce API, where each record is a dict that may contain the keys \"id\", \"customer\" (a dict with \"name\" and optional \"tier\"), \"status\", and \"items\" (a list of dicts with \"qty\" and \"price_cents\"). W...
[ { "role": "assistant", "content": "def summarize_orders(orders):\n \"\"\"Aggregate API-style order records into per-customer summaries.\"\"\"\n counted_statuses = {\"shipped\", \"delivered\"}\n per_customer = {}\n\n for record in orders:\n if not isinstance(record, dict):\n con...
{ "topic": "API-like data transformation tasks", "difficulty": "medium", "provider": "together", "in_tokens": 237, "out_tokens": 3507, "latency_s": 54.4 }
[ { "role": "user", "content": "A clinic manages its check-in desk using a queue, a stack, and a heap. Write a function `process_checkins(patients)` where `patients` is a list of `(name, urgency)` tuples; `urgency` is an integer and a smaller value means the patient is more urgent. First, place every patient ...
[ { "role": "assistant", "content": "from collections import deque\nimport heapq\n\n\ndef process_checkins(patients):\n queue = deque()\n for index, (name, urgency) in enumerate(patients):\n queue.append((urgency, index, name))\n\n heap = []\n while queue:\n urgency, index, name = qu...
{ "topic": "queues, stacks, and heap-based algorithms", "difficulty": "easy", "provider": "together", "in_tokens": 240, "out_tokens": 2288, "latency_s": 23.8 }
[ { "role": "user", "content": "A legacy application stored names as UTF-8 bytes but later decoded them as Latin-1, producing mojibake such as 'café' instead of 'café'. Write a function repair_and_format(records) that takes a list of strings and attempts to repair each one by encoding it back to Latin-1 and ...
[ { "role": "assistant", "content": "import unicodedata\n\n\ndef repair_and_format(records):\n lines = []\n for record in records:\n try:\n repaired = record.encode(\"latin-1\").decode(\"utf-8\")\n except UnicodeError:\n repaired = record\n repaired = unicodeda...
{ "topic": "string encodings, unicode, and formatting", "difficulty": "medium", "provider": "together", "in_tokens": 240, "out_tokens": 2627, "latency_s": 49.2 }
[ { "role": "user", "content": "A prime chain of order n is a permutation of the integers 1 through n such that the sum of every two adjacent numbers is a prime number. Write a function prime_chain(n) that uses recursive backtracking to find the lexicographically smallest prime chain of order n and returns it...
[ { "role": "assistant", "content": "def prime_chain(n):\n # Return the lexicographically smallest permutation of 1..n whose\n # adjacent sums are all prime, or [] if no such permutation exists.\n\n def is_prime(x):\n if x < 2:\n return False\n if x == 2:\n return ...
{ "topic": "recursion and backtracking", "difficulty": "medium", "provider": "together", "in_tokens": 236, "out_tokens": 3042, "latency_s": 37.2 }
[ { "role": "user", "content": "Write a function compare_trees(left, right) that compares two directory trees containing only regular files and directories and returns a dictionary with the keys 'only_in_left', 'only_in_right', 'modified', 'identical', and 'type_conflict', each mapped to a list of relative pa...
[ { "role": "assistant", "content": "import hashlib\nimport os\nimport tempfile\n\n\ndef _hash_file(path, chunk_size=65536):\n '''Return the SHA-256 hex digest of a file's contents.'''\n digest = hashlib.sha256()\n with open(path, 'rb') as handle:\n while True:\n chunk = handle.read...
{ "topic": "working with files and paths", "difficulty": "hard", "provider": "baseten", "in_tokens": 237, "out_tokens": 5339, "latency_s": 30.4 }
[ { "role": "user", "content": "Given a list of non-negative integers nums, consider every unordered pair of distinct indices (i, j) with i < j and compute the bitwise AND nums[i] & nums[j]. Define the pair-AND-XOR of the list as the bitwise XOR of all these pairwise AND values; if the list contains fewer tha...
[ { "role": "assistant", "content": "import sys\n\n\ndef pair_and_xor(nums):\n \"\"\"Return the XOR of nums[i] & nums[j] over all pairs i < j.\n\n For each bit position b, nums[i] & nums[j] has bit b set exactly when\n both numbers have bit b set. If c numbers have bit b set, that gives\n c*(c-1)/...
{ "topic": "bit manipulation", "difficulty": "medium", "provider": "together", "in_tokens": 234, "out_tokens": 2005, "latency_s": 17.1 }
[ { "role": "user", "content": "At a one-day tech conference, several talks are scheduled, and each talk is given as an interval (start, end) measured in minutes from the start of the day. You can attend a talk only if you stay for its entire duration, and you cannot be in two talks at the same time. However,...
[ { "role": "assistant", "content": "def max_talks(intervals):\n count = 0\n last_end = None\n for start, end in sorted(intervals, key=lambda iv: iv[1]):\n if last_end is None or start >= last_end:\n count += 1\n last_end = end\n return count\n\n\nif __name__ == \"__ma...
{ "topic": "interval and scheduling problems", "difficulty": "easy", "provider": "together", "in_tokens": 236, "out_tokens": 2091, "latency_s": 41.8 }
End of preview. Expand in Data Studio

No dataset card yet

Downloads last month
43

Models trained or fine-tuned on gsultani/kimi-k3-python-distill