Spaces:
Running
Running
File size: 11,971 Bytes
ea917ba | 1 | [{"id": "aafeb62b8774", "topic": "shortest paths", "difficulty": "easy", "title": "Shortest Ferry Times", "entry_point": "shortest_ferry_times", "signature": "def shortest_ferry_times(routes: list[tuple[str, str, int]], origin: str) -> dict[str, int]:", "prompt": "## Shortest Ferry Times\n\nA ferry network connects ports. Each route is an undirected ferry crossing with a nonnegative travel time in minutes. Given a list of routes and an origin port, return the shortest travel time from the origin to every reachable port.\n\n### Function signature\n```python\ndef shortest_ferry_times(routes: list[tuple[str, str, int]], origin: str) -> dict[str, int]:\n```\n\n### Input\n- `routes`: a list of tuples `(port_a, port_b, minutes)`.\n- Port names are strings.\n- `minutes` is a nonnegative integer.\n- A route may be used in either direction.\n- Duplicate routes, self-loops, and zero-minute crossings are allowed.\n\n### Output\n- A dictionary mapping each reachable port to its minimum travel time from `origin`.\n- The origin is always included with time `0`, even if it has no routes.\n- Ports that are unreachable from the origin are omitted.\n- If multiple routes connect the same two ports, the shorter effective time is used automatically by shortest-path computation.\n\n### Constraints\n- `0 <= len(routes) <= 1000`\n- Port names contain at most 32 characters.\n- `0 <= minutes <= 10**6`\n- All route endpoints and the origin are valid port names.\n\n### Examples\n```python\nshortest_ferry_times([(\"A\", \"B\", 10), (\"B\", \"C\", 10), (\"A\", \"C\", 15)], \"A\")\n# {\"A\": 0, \"B\": 10, \"C\": 15}\n\nshortest_ferry_times([(\"X\", \"Y\", 7)], \"A\")\n# {\"A\": 0}\n```", "solution": "import heapq\n\n\ndef shortest_ferry_times(routes: list[tuple[str, str, int]], origin: str) -> dict[str, int]:\n \"\"\"Return shortest travel times from origin in an undirected weighted graph.\"\"\"\n graph: dict[str, list[tuple[str, int]]] = {}\n\n def add_edge(a: str, b: str, weight: int) -> None:\n graph.setdefault(a, []).append((b, weight))\n if a != b:\n graph.setdefault(b, []).append((a, weight))\n else:\n graph.setdefault(b, [])\n\n for port_a, port_b, minutes in routes:\n add_edge(port_a, port_b, minutes)\n\n distances: dict[str, int] = {origin: 0}\n priority_queue: list[tuple[int, str]] = [(0, origin)]\n\n while priority_queue:\n current_distance, current_port = heapq.heappop(priority_queue)\n if current_distance > distances.get(current_port, float(\"inf\")):\n continue\n\n for neighbor, weight in graph.get(current_port, []):\n candidate = current_distance + weight\n if candidate < distances.get(neighbor, float(\"inf\")):\n distances[neighbor] = candidate\n heapq.heappush(priority_queue, (candidate, neighbor))\n\n return distances\n", "public_tests": ["assert shortest_ferry_times([], \"A\") == {\"A\": 0}", "assert shortest_ferry_times([(\"A\", \"B\", 5)], \"A\") == {\"A\": 0, \"B\": 5}", "assert shortest_ferry_times([(\"A\", \"B\", 5)], \"B\") == {\"B\": 0, \"A\": 5}"], "hidden_tests": ["assert shortest_ferry_times([(\"A\", \"B\", 10), (\"B\", \"C\", 10), (\"A\", \"C\", 15)], \"A\") == {\"A\": 0, \"B\": 10, \"C\": 15}", "assert shortest_ferry_times([(\"A\", \"B\", 1), (\"C\", \"D\", 2)], \"A\") == {\"A\": 0, \"B\": 1}", "assert shortest_ferry_times([(\"A\", \"B\", 8), (\"A\", \"B\", 3)], \"A\") == {\"A\": 0, \"B\": 3}", "assert shortest_ferry_times([(\"A\", \"B\", 0), (\"B\", \"C\", 4)], \"A\") == {\"A\": 0, \"B\": 0, \"C\": 4}", "assert shortest_ferry_times([(\"A\", \"A\", 99), (\"A\", \"B\", 2)], \"A\") == {\"A\": 0, \"B\": 2}", "assert shortest_ferry_times([(\"X\", \"Y\", 7)], \"A\") == {\"A\": 0}", "assert shortest_ferry_times([(\"A\", \"B\", 2), (\"A\", \"C\", 2), (\"B\", \"D\", 2), (\"C\", \"D\", 2)], \"A\") == {\"A\": 0, \"B\": 2, \"C\": 2, \"D\": 4}", "assert shortest_ferry_times([(\"A\", \"B\", 0), (\"B\", \"C\", 0), (\"C\", \"A\", 0), (\"C\", \"D\", 1)], \"A\") == {\"A\": 0, \"B\": 0, \"C\": 0, \"D\": 1}", "assert shortest_ferry_times([(\"B\", \"A\", 6)], \"A\") == {\"A\": 0, \"B\": 6}", "assert shortest_ferry_times([(\"A\", \"B\", 1), (\"B\", \"C\", 1), (\"A\", \"C\", 3)], \"A\") == {\"A\": 0, \"B\": 1, \"C\": 2}", "assert shortest_ferry_times([(\"A\", \"B\", 10), (\"B\", \"C\", 10), (\"A\", \"C\", 25)], \"A\") == {\"A\": 0, \"B\": 10, \"C\": 20}"], "num_tests": 14, "source_model": "reflection/Beam-1.0-501B-A23B", "temperature": 0.8}, {"id": "ab37e43f0c9c", "topic": "version strings and semantic comparison", "difficulty": "medium", "title": "Semantic Version Comparator", "entry_point": "compare_versions", "signature": "def compare_versions(a: str, b: str) -> int:", "prompt": "## Semantic Version Comparator\n\nYou are comparing firmware release tags for a medical-device update service. Implement a function that compares two version strings according to semantic-version precedence.\n\n**Signature**\n\n```python\ndef compare_versions(a: str, b: str) -> int:\n```\n\n**Version grammar**\n\nA valid version string has the form:\n\n```\nMAJOR.MINOR.PATCH[-prerelease][+build]\n```\n\n- `MAJOR`, `MINOR`, and `PATCH` are non-negative integers without leading zeros.\n- `prerelease` is a dot-separated list of identifiers. Each identifier is either a non-negative integer without leading zeros, or an ASCII alphanumeric/hyphen string containing at least one non-digit.\n- `build` is a dot-separated list of ASCII alphanumeric/hyphen identifiers.\n- Inputs are guaranteed to be valid version strings.\n\n**Precedence rules**\n\n1. Compare `MAJOR`, then `MINOR`, then `PATCH` numerically.\n2. A version without a prerelease has higher precedence than the same core version with a prerelease.\n3. Prerelease identifiers are compared left to right:\n - Numeric identifiers are compared numerically.\n - Non-numeric identifiers are compared by ASCII lexicographic order.\n - Numeric identifiers always have lower precedence than non-numeric identifiers.\n - If all compared identifiers are equal, the prerelease with more identifiers has higher precedence.\n4. Build metadata is ignored for precedence.\n\n**Return value**\n\nReturn `-1` if `a` has lower precedence than `b`, `0` if they have equal precedence, and `1` if `a` has higher precedence.\n\n**Examples**\n\n- `compare_versions(\"1.2.3-rc.1\", \"1.2.3-rc.10\")` returns `-1` because `1 < 10` numerically.\n- `compare_versions(\"1.0.0+exp.42\", \"1.0.0\")` returns `0` because build metadata is ignored.", "solution": "import re\n\n_VERSION_RE = re.compile(\n r\"^(?P<core>(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*))\"\n r\"(?:-(?P<pre>[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*))?\"\n r\"(?:\\+(?P<build>[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*))?$\"\n)\n\n\ndef _parse(version: str):\n match = _VERSION_RE.fullmatch(version)\n if match is None:\n raise ValueError(f\"invalid version string: {version!r}\")\n core = tuple(int(part) for part in match.group(\"core\").split(\".\"))\n pre = match.group(\"pre\")\n prerelease = None if pre is None else pre.split(\".\")\n return core, prerelease\n\n\ndef _compare_identifier(left: str, right: str) -> int:\n left_numeric = left.isdigit()\n right_numeric = right.isdigit()\n if left_numeric and right_numeric:\n left_value = int(left)\n right_value = int(right)\n if left_value < right_value:\n return -1\n if left_value > right_value:\n return 1\n return 0\n if left_numeric != right_numeric:\n return -1 if left_numeric else 1\n if left < right:\n return -1\n if left > right:\n return 1\n return 0\n\n\ndef compare_versions(a: str, b: str) -> int:\n core_a, pre_a = _parse(a)\n core_b, pre_b = _parse(b)\n\n if core_a < core_b:\n return -1\n if core_a > core_b:\n return 1\n\n if pre_a is None and pre_b is None:\n return 0\n if pre_a is None:\n return 1\n if pre_b is None:\n return -1\n\n limit = min(len(pre_a), len(pre_b))\n for index in range(limit):\n result = _compare_identifier(pre_a[index], pre_b[index])\n if result != 0:\n return result\n\n if len(pre_a) == len(pre_b):\n return 0\n return -1 if len(pre_a) < len(pre_b) else 1\n", "public_tests": ["assert compare_versions('1.2.3', '1.2.4') == -1", "assert compare_versions('2.0.0', '1.9.9') == 1", "assert compare_versions('1.0.0', '1.0.0') == 0"], "hidden_tests": ["assert compare_versions('1.0.0-alpha', '1.0.0') == -1", "assert compare_versions('1.0.0', '1.0.0-alpha') == 1", "assert compare_versions('1.0.0-alpha', '1.0.0-beta') == -1", "assert compare_versions('1.0.0-rc.1', '1.0.0-rc.10') == -1", "assert compare_versions('1.0.0-1', '1.0.0-alpha') == -1", "assert compare_versions('1.0.0+build.2', '1.0.0+build.1') == 0", "assert compare_versions('1.0.0-alpha+build', '1.0.0-alpha') == 0", "assert compare_versions('1.0.0-rc.1.0', '1.0.0-rc.1') == 1", "assert compare_versions('1.0.0-alpha.1', '1.0.0-alpha.beta') == -1", "assert compare_versions('0.0.0', '0.0.1') == -1"], "num_tests": 13, "source_model": "reflection/Beam-1.0-501B-A23B", "temperature": 0.8}, {"id": "1bf5bda6cb2c", "topic": "text formatting and wrapping", "difficulty": "easy", "title": "Wrap Plain-Text Labels", "entry_point": "wrap_text", "signature": "def wrap_text(text: str, width: int) -> list[str]:", "prompt": "Write a function `wrap_text(text, width)` that wraps a single line of text into lines of at most `width` characters.\n\nWords are maximal runs of non-whitespace characters. Any whitespace separates words, and output lines contain single spaces between words. Words are packed greedily: put as many whole words on a line as possible without exceeding `width`. If a word is longer than `width`, split it into chunks of at most `width` characters. Empty or whitespace-only input returns `[]`. `width` must be a positive integer.\n\nExamples:\n- `wrap_text('ab cdefg hi', 4)` returns `['ab', 'cdef', 'g hi']`\n- `wrap_text('x abcdefghij y', 4)` returns `['x', 'abcd', 'efgh', 'ij y']`", "solution": "def wrap_text(text: str, width: int) -> list[str]:\n if not isinstance(width, int) or width < 1:\n raise ValueError('width must be a positive integer')\n\n words = text.split()\n lines = []\n current = ''\n\n for word in words:\n if current and len(current) + 1 + len(word) <= width:\n current += ' ' + word\n else:\n if current:\n lines.append(current)\n current = ''\n\n if len(word) <= width:\n current = word\n else:\n start = 0\n n = len(word)\n while start + width < n:\n lines.append(word[start:start + width])\n start += width\n current = word[start:]\n\n if current:\n lines.append(current)\n\n return lines\n", "public_tests": ["assert wrap_text('', 4) == []", "assert wrap_text(' \\t ', 4) == []", "assert wrap_text('hello', 5) == ['hello']"], "hidden_tests": ["assert wrap_text('hello', 3) == ['hel', 'lo']", "assert wrap_text('hello world', 5) == ['hello', 'world']", "assert wrap_text('a b c d e', 5) == ['a b c', 'd e']", "assert wrap_text(' a b ', 10) == ['a b']", "assert wrap_text('abc def', 3) == ['abc', 'def']", "assert wrap_text('abcdefghij', 4) == ['abcd', 'efgh', 'ij']", "assert wrap_text('ab cdefg hi', 4) == ['ab', 'cdef', 'g hi']", "assert wrap_text('x abcdefghij y', 4) == ['x', 'abcd', 'efgh', 'ij y']", "assert wrap_text('abcdefghij k', 4) == ['abcd', 'efgh', 'ij k']", "assert wrap_text('a bc', 1) == ['a', 'b', 'c']", "assert wrap_text('ab cdefghij k', 4) == ['ab', 'cdef', 'ghij', 'k']"], "num_tests": 14, "source_model": "reflection/Beam-1.0-501B-A23B", "temperature": 0.8}] |