instruction
stringlengths
68
159
output
stringlengths
46
20k
Implement Prim's algorithm in Python with type hints. Return only the code.
from __future__ import annotations import heapq from collections.abc import Hashable, Mapping from itertools import count from typing import TypeVar Node = TypeVar("Node", bound=Hashable) Weight = TypeVar("Weight", int, float) Graph = Mapping[Node, Mapping[Node, Weight]] def prim(graph: Graph[Node, Weight], start: N...
Write a Python function that calculates the factorial of n. Return only the code.
def factorial(n: int) -> int: if n < 0: raise ValueError("Factorial is not defined for negative numbers.") result = 1 for i in range(2, n + 1): result *= i return result
Write a Python class that implements a graph with DFS and BFS. Return only the code.
from collections import deque class Graph: """Supports iterative depth-first and breadth-first traversal.""" def __init__(self, directed=False): self.directed = directed self.adjacency = {} def add_vertex(self, vertex): if vertex not in self.adjacency: self.adjacency[v...
Write a Python function that implements Kruskal's algorithm. Return only the code.
def kruskal(num_vertices, edges): """Return a minimum spanning tree as a list of (u, v, weight) edges. Vertices must be labeled 0 through num_vertices - 1. Edges must be (u, v, weight) tuples describing undirected edges. If the graph is disconnected, returns a minimum spanning forest. """ paren...
Write a Python class that implements a linked list with insert/delete/reverse. Return only the code.
class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None self._size = 0 def insert(self, data): """Insert a new node at the beginning of the list.""" new_node = Node(data) new_node...
Create a Python function that parses a CSV file safely. Return None on error. Only the code.
import csv def parse_csv(file_path): """Parse a UTF-8 CSV file, returning None on error.""" try: with open(file_path, "r", encoding="utf-8-sig", newline="") as file: return list(csv.reader(file, strict=True)) except (OSError, UnicodeError, csv.Error, TypeError, ValueError): retu...
Write a Python function that implements Kadane's algorithm. Return only the code.
def kadane(numbers): """Return the maximum sum of a contiguous subarray, or 0 if empty.""" current_sum = best_sum = next(numbers, 0) for number in numbers: current_sum = max(number, current_sum + number) best_sum = max(best_sum, current_sum) return best_sum
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 prime factors of n, including repeated factors.""" if n < 1: raise ValueError("n must be a positive integer.") factors = [] while n % 2 == 0: factors.append(2) n //= 2 divisor = 3 while divisor * divisor <= n: ...
Implement a Python function to calculates the LCM of two numbers. Output only the code.
from math import gcd def lcm(a: int, b: int) -> int: """Return the least common multiple of two integers.""" if a == 0 or b == 0: return 0 return abs(a * b) // gcd(a, b)
Fill in the body of this function: def read_file(data): # implements binary search Return only the code.
def read_file(data): """Binary-search sorted_values for target; data is (sorted_values, target).""" sorted_values, target = data low, high = 0, len(sorted_values) - 1 while low <= high: mid = (low + high) // 2 if sorted_values[mid] < target: low = mid + 1 elif sorted...
Write a Python function that implements the Knapsack problem. Return only the code.
def knapsack(weights, values, capacity): """Return the maximum value achievable using each item at most once. Args: weights: Sequence of non-negative integer item weights. values: Sequence of non-negative integer item values. capacity: Maximum total weight the knapsack can hold. Re...
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 abs(n) in ascending order.""" n = abs(n) if n < 2: return [] factors = [] if n % 2 == 0: factors.append(2) while n % 2 == 0: n //= 2 divisor = 3 while divisor * divisor <= n...
Implement a Python function to computes the edit distance between two strings. Output only the code.
def edit_distance(s1: str, s2: str) -> int: """Return the minimum number of insertions, deletions, and substitutions.""" # Keep the shorter string in the DP columns to minimize memory usage. if len(s2) > len(s1): s1, s2 = s2, s1 previous = list(range(len(s2) + 1)) for i, char1 in enumerate...
Write a Python class that implements a shopping cart with add/remove/total. Return only the code.
class ShoppingCart: def __init__(self) -> None: self._items = {} def add(self, item: str, price: float, quantity: int = 1) -> None: if price < 0: raise ValueError("Price must be nonnegative.") if quantity <= 0: raise ValueError("Quantity must be positive.") ...
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:]) result = [] i = j = 0 while i < len(left) and j < len(right): if left[i] <= right[j]: result.append(left[i]) ...
Write a Python function that finds the first non-repeating character. Return only the code.
def first_non_repeating_char(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 the coin change problem in Python with type hints. Return only the code.
from collections.abc import Sequence def coin_change(coins: Sequence[int], amount: int) -> int: """Return the fewest coins needed to make amount, or -1 if impossible.""" if amount < 0: return -1 unreachable = amount + 1 dp = [unreachable] * (amount + 1) dp[0] = 0 for total in range(1,...
Implement a Python function to computes the binomial coefficient. Output only the code.
def binomial(n: int, k: int) -> int: """Return the binomial coefficient C(n, k) for nonnegative integers.""" if n < 0 or k < 0 or k > n: raise ValueError("n must be nonnegative and k must satisfy 0 <= k <= n.") k = min(k, n - k) result = 1 for i in range(1, k + 1): result = result *...
Implement Bellman-Ford algorithm in Python with type hints. Return only the code.
from collections.abc import Hashable, Mapping from math import inf from typing import TypeVar Vertex = TypeVar("Vertex", bound=Hashable) def bellman_ford( graph: Mapping[Vertex, Mapping[Vertex, float]], source: Vertex, ) -> tuple[dict[Vertex, float], dict[Vertex, Vertex]]: """ Compute shortest paths f...
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, item, price): self.items[item] = price def remove(self, item): self.items.pop(item, None) def total(self): return sum(self.items.values())
Create a Python function that parses a text file line by line safely. Return None on error. Only the code.
def parse_text_file(file_path): """Return text lines without line endings, or None on error.""" try: with open(file_path, "r", encoding="utf-8") as file: return [line.rstrip("\r\n") for line in file] except Exception: return None
Write a Python class that implements a linked list with insert/delete/reverse. Return only the code.
class _Node: __slots__ = ("value", "next") def __init__(self, value=None): self.value = value self.next = None class LinkedList: def __init__(self, values=()): self.head = _Node() # Dummy head node self._size = 0 for value in values: self.insert(value) ...
Implement a Python solution for implements a URL shortener with in-memory storage. Return only the code.
import secrets import string import threading from typing import Dict, Optional class URLShortener: """Thread-safe URL shortener whose data is stored only in memory.""" _ALPHABET = string.ascii_letters + string.digits def __init__(self, code_length: int = 7) -> None: if ( isinstance(c...
Write a Python function that implements topological sorting. Return only the code.
from collections import deque def topological_sort(graph): """Return a topological ordering of a directed graph. Args: graph: Dictionary mapping each node to its outgoing neighbors. Raises: ValueError: If the graph contains a directed cycle. """ indegree = {node: 0 for node in gra...
Complete this Python function: def transform(n): """finds the first non-repeating character""" Return only the full function.
def transform(n): """Return the first non-repeating character, or None if there isn't one.""" counts = {} for char in n: counts[char] = counts.get(char, 0) + 1 for char in n: if counts[char] == 1: return char return None
Write a Python function that implements heap sort. Return only the code.
def heap_sort(arr): """Sort arr in place in ascending order and return it.""" n = len(arr) def sift_down(root, size): while True: largest = root left = 2 * root + 1 right = left + 1 if left < size and arr[left] > arr[largest]: largest...
Write a Python function that finds the longest increasing subsequence. Return only the code.
from bisect import bisect_left from typing import List, Sequence def longest_increasing_subsequence(sequence: Sequence[int]) -> List[int]: """Return a longest strictly increasing subsequence in O(n log n) time.""" tails: List[int] = [] tail_indices: List[int] = [] for index, value in enumerate(sequenc...
Implement a Python function to computes the edit distance between two strings. Output only the code.
def edit_distance(s1: str, s2: str) -> int: """Return the minimum number of insertions, deletions, and substitutions.""" 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 enume...
Fill in the body of this function: def write_output(lst): # implements a queue using two stacks Return only the code.
def write_output(lst): incoming = [] outgoing = [] for item in lst: incoming.append(item) if not outgoing: while incoming: outgoing.append(incoming.pop()) print(outgoing.pop())
Write a Python function that removes duplicates from a list. Return only the code.
def remove_duplicates(items): """Return a new list with duplicates removed, preserving their original order.""" return list(dict.fromkeys(items))
Implement a Python function to implements a queue using two stacks. Output only the code.
from typing import Generic, TypeVar T = TypeVar("T") class Queue(Generic[T]): def __init__(self) -> None: self._incoming: list[T] = [] self._outgoing: list[T] = [] def enqueue(self, item: T) -> None: self._incoming.append(item) def dequeue(self) -> T: self._refill_outgoin...
Complete this Python function: def validate(data): """finds the middle of a linked list""" Return only the full function.
def validate(data): """Return the middle node of a linked list, or None if it is empty.""" slow = fast = data while fast is not None and fast.next is not None: slow = slow.next fast = fast.next.next return slow
Write a Python class that implements a queue with enqueue/dequeue. Return only the code.
from collections import deque class Queue: def __init__(self): self._items = deque() def enqueue(self, item): self._items.append(item) def dequeue(self): return self._items.popleft()
Write a Python class that implements a matrix with linear algebra operations. Return only the code.
from numbers import Integral, Number from random import uniform class Matrix: """A dense matrix supporting arithmetic and linear algebra operations. Use + and - for elementwise arithmetic, * and / for scalar arithmetic, and @ or multiply() for matrix multiplication. """ def __init__(self, data=No...
Implement topological sorting in Python with type hints. Return only the code.
from collections import deque from collections.abc import Hashable, Mapping, Sequence from typing import TypeVar Node = TypeVar("Node", bound=Hashable) def topological_sort(graph: Mapping[Node, Sequence[Node]]) -> list[Node]: """Return a topological ordering of a directed graph. Each key is a node, and its s...
Implement merge sort in Python with type hints. Return only the code.
from typing import TypeVar T = TypeVar("T") def merge_sort(items: list[T]) -> list[T]: """Return a sorted copy of items using merge sort.""" if len(items) < 2: return items.copy() mid = len(items) // 2 left = merge_sort(items[:mid]) right = merge_sort(items[mid:]) merged: list[T] = [...
Implement Floyd-Warshall algorithm in Python with type hints. Return only the code.
from math import inf def floyd_warshall(graph: list[list[int | float]]) -> list[list[float]]: """ Compute all-pairs shortest-path distances from a square adjacency matrix. Missing edges must be represented by math.inf. The input is not modified. Raises ValueError if the matrix is not square or contain...
Complete this Python function: def read_file(s): """finds the longest increasing subsequence""" Return only the full function.
def read_file(s): """Return a longest strictly increasing subsequence of integers read from file s.""" from bisect import bisect_left with open(s, "r") as f: numbers = (int(token) for line in f for token in line.split()) tails = [] for number in numbers: index = bisect_left(tails, ...
Implement a Python class for a queue with enqueue/dequeue. Return only the class.
class Queue: def __init__(self): from collections import deque self._items = deque() def enqueue(self, item): self._items.append(item) def dequeue(self): if not self._items: raise IndexError("dequeue from empty queue") return self._items.popleft()
Write a Python class that implements a binary search tree with insert/delete/search. Return only the code.
class BinarySearchTree: """Binary search tree supporting unique keys.""" class _Node: def __init__(self, key): self.key = key self.left = None self.right = None def __init__(self): self.root = None def insert(self, key): """Insert a key. Ret...
Write a Python function that implements binary search. Return only the code.
def binary_search(arr, target): """Return the index of target in a 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 if arr[mid] < target: left = mid + 1 ...
Write a Python function that finds the longest common prefix of strings. Return only the code.
def longest_common_prefix(strings): if not strings: return "" prefix = strings[0] for string in strings[1:]: i = 0 while i < min(len(prefix), len(string)) and prefix[i] == string[i]: i += 1 prefix = prefix[:i] if not prefix: break return ...
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 = 65536) -> dict[str, int | str]: """Calculate a binary file's size and SHA-256 checksum without loading it all into memory.""" if chunk_size <= 0: raise ValueError("chunk_size must be greater than zero.") size = 0 checksum...
Write a complete Python module that implements a terminal-based todo list manager. Use functions and classes. Return only the code.
"""A persistent, terminal-based todo list manager. Examples: python todo_manager.py add "Buy groceries" python todo_manager.py list python todo_manager.py done ID_PREFIX python todo_manager.py undone ID_PREFIX python todo_manager.py remove ID_PREFIX python todo_manager.py clear-completed Use a...
Implement a Python class for a simple cache with LRU eviction. Return only the class.
class LRUCache: """A fixed-capacity cache that evicts the least recently used entry.""" def __init__(self, capacity: int = 128): if capacity <= 0: raise ValueError("capacity must be greater than zero") self.capacity = capacity self._entries = {} def get(self, key, defau...
Implement a Python function to finds the longest common prefix of strings. Output only the code.
def longest_common_prefix(strings): """Return the longest common prefix shared by an iterable of strings.""" prefix = "" for string in strings: i = 0 while i < len(prefix) and i < len(string) and prefix[i] == string[i]: i += 1 prefix = prefix[:i] if not prefix: ...
Fill in the body of this function: def read_file(arr, target): # computes the power of a number using fast exponentiation Return only the code.
def read_file(arr, target): if target < 0: raise ValueError("The exponent must be non-negative.") result = 1 base = arr while target: if target & 1: result *= base base *= base target >>= 1 return result
Create a Python function that parses an XML document safely. Return None on error. Only the code.
from defusedxml import ElementTree as ET from defusedxml.common import DefusedXmlException def parse_xml(xml): """Safely parse an XML string or bytes, returning None on error.""" try: return ET.fromstring( xml, forbid_dtd=True, forbid_entities=True, forbi...
Write a Python function that converts a decimal number to binary. Return only the code.
def decimal_to_binary(number: int) -> str: """Return the binary representation of a decimal integer.""" return format(number, "b")
Implement a Python function to implements the sieve of Eratosthenes. Output only the code.
from math import isqrt def sieve(n: int) -> list[int]: """Return 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 for p in range(2, isqrt(n) + 1): if is_prime[p]: for multiple in range(p * p...
Write a Python function that converts a decimal number to binary. Return only the code.
def decimal_to_binary(number: int) -> str: """Convert a decimal integer to its binary representation.""" if number == 0: return "0" sign = "-" if number < 0 else "" number = abs(number) binary = "" while number: binary = str(number % 2) + binary number //= 2 return...
Implement a Python function to calculates the LCM of two numbers. Output only the code.
from math import gcd def lcm(a: int, b: int) -> int: if a == 0 or b == 0: return 0 return abs(a * b) // gcd(a, b)
Write a complete Python module that implements a URL shortener with in-memory storage. Use functions and classes. Return only the code.
"""Thread-safe, in-memory URL shortening using only the standard library. Short codes and custom aliases are case-sensitive. Only absolute HTTP and HTTPS URLs are accepted. Storage is local to each URLShortener instance and is lost when the program exits. Example: shortener = URLShortener() code = shortener.s...
Fill in the body of this function: def read_file(lst): # finds all prime factors of a number Return only the code.
def read_file(lst): result = [] for num in lst: num = abs(num) factors = [] divisor = 2 while num > 1 and divisor * divisor <= num: while num % divisor == 0: factors.append(divisor) num //= divisor divisor = 3 if divisor ==...
Complete this Python function: def compute(n): """calculates the factorial of n""" Return only the full function.
def compute(n): """calculates the factorial of n""" result = 1 for i in range(2, n + 1): result *= i return result
Write a Python function that computes the Fibonacci sequence up to n. Return only the code.
def fibonacci(n: int) -> list[int]: """Return the first n Fibonacci numbers.""" sequence = [] a, b = 0, 1 for _ in range(n): sequence.append(a) a, b = b, a + b return sequence
Fill in the body of this function: def sort(n): # computes the power of a number using fast exponentiation Return only the code.
def sort(n): """Return n raised to the power n using fast exponentiation.""" result = -1 if n < 0 and n % 2 else 1 base = n exponent = abs(n) while exponent: if exponent & 1: result *= base base *= base exponent >>= 1 return result
Implement a Python function to implements binary search. Output only the code.
def binary_search(arr, target): """Return the index of target in an ascending-sorted array, or -1 if absent.""" low, high = 0, len(arr) - 1 while low <= high: mid = low + (high - low) // 2 if arr[mid] == target: return mid elif arr[mid] < target: low = mid +...
Implement the segment tree in Python with type hints. Return only the code.
from __future__ import annotations from typing import Callable, Generic, List, Sequence, TypeVar __all__ = ["SegmentTree"] T = TypeVar("T") class SegmentTree(Generic[T]): """Segment tree supporting point updates and range queries. The operation must be associative, and identity must be its neutral elem...
Implement a Python function to finds the longest common prefix of strings. Output only the code.
from collections.abc import Iterable def longest_common_prefix(strings: Iterable[str]) -> str: """Return the longest common prefix of an iterable of strings.""" iterator = iter(strings) try: prefix = next(iterator) except StopIteration: return "" length = len(prefix) for string...
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 = 65536) -> dict[str, int | str]: """Calculate a binary file's size and SHA-256 checksum using chunked reads.""" if not isinstance(chunk_size, int) or isinstance(chunk_size, bool) or chunk_size <= 0: raise ValueError("chunk_size mus...
Write a Python class that implements a binary search tree with insert/delete/search. Return only the code.
class BinarySearchTree: """Binary search tree that ignores duplicate keys.""" class _Node: __slots__ = ("key", "left", "right") def __init__(self, key): self.key = key self.left = None self.right = None def __init__(self): self.root = None ...
Write a Python class that implements a task scheduler with priorities. Return only the code.
from __future__ import annotations import heapq import threading from concurrent.futures import Future from itertools import count from typing import Any, Callable, Generic, NamedTuple, TypeVar T = TypeVar("T") class _Task(NamedTuple, Generic[T]): function: Callable[..., T] args: tuple[Any, ...] kwargs: ...
Implement a Python function to counts the frequency of words in a string. Output only the code.
def count_words(text: str) -> dict[str, int]: frequencies = {} for word in text.split(): frequencies[word] = frequencies.get(word, 0) + 1 return frequencies
Implement a Python function to finds the middle of a linked list. Output only the code.
def find_middle(head): """Return the middle node, or the second middle node if length is even.""" slow = fast = head while fast is not None and fast.next is not None: slow = slow.next fast = fast.next.next return slow
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 self.is_empty(): raise IndexError("Stack is empty") return self.items.pop() def peek(self): if self.is_empty(): raise IndexE...
Create a Python function that parses a YAML file safely. Return None on error. Only the code.
import yaml def parse_yaml_file(file_path: str): try: with open(file_path, "r", encoding="utf-8") as file: return yaml.safe_load(file) except Exception: return None
Implement a Python class for a linked list with insert/delete/reverse. Return only the class.
class LinkedList: """Singly linked list with insertion, deletion, and in-place reversal.""" class _Node: __slots__ = ("value", "next") def __init__(self, value): self.value = value self.next = None def __init__(self): self.head = None self.tail = No...
Complete this Python function: def find(arr, target): """reverses a linked list""" Return only the full function.
def find(arr, target): """Reverse the linked list and return its new head node.""" previous = None current = arr 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 number is prime. Output only the code.
from math import isqrt def is_prime(n: int) -> bool: if n < 2: return False if n % 2 == 0: return n == 2 for divisor in range(3, isqrt(n) + 1, 2): if n % divisor == 0: return False return True
Implement Dijkstra's algorithm in Python with type hints. Return only the code.
from collections.abc import Hashable, Mapping from heapq import heappop, heappush from itertools import count from typing import TypeVar, cast Node = TypeVar("Node", bound=Hashable) Weight = TypeVar("Weight", int, float) def dijkstra( graph: Mapping[Node, Mapping[Node, Weight]], start: Node, ) -> dict[Node, W...
Implement a Python class for a simple cache with LRU eviction. Return only the class.
class LRUCache: """A fixed-size cache that evicts the least recently used entry.""" def __init__(self, capacity: int) -> None: if capacity <= 0: raise ValueError("capacity must be positive") self.capacity = capacity self._cache = {} def get(self, key, default=None): ...
Write a Python function to process a text file line by line. Include error handling. Return only the code.
def process_text_file(file_path, transform=None): """ Read a UTF-8 text file line by line and optionally transform each line. Line endings are removed. Results are returned as a list. Raises RuntimeError if the file cannot be read or a line cannot be processed. """ try: with open(file_p...
Implement a Python function to sorts a list using quicksort. Output only the code.
def quicksort(values): if len(values) <= 1: return values pivot = values[len(values) // 2] lower = [value for value in values if value < pivot] upper = [value for value in values if value >= pivot] return quicksort(lower) + [pivot] + quicksort(upper)
Implement a Python function to reverses a linked list. Output only the code.
def reverse_linked_list(head): previous = None current = head while current is not None: next_node = current.next current.next = previous previous = current current = next_node return previous
Implement a Python class for a stack with push/pop/peek. Return only the class.
class Stack: def __init__(self): self._items = [] def push(self, item): self._items.append(item) def pop(self): return self._items.pop() def peek(self): return self._items[-1]
Write a Python function that computes the power of a number using fast exponentiation. Return only the code.
def fast_power(base, exponent): if exponent < 0: base = 1 / base exponent = -exponent result = 1 while exponent: if exponent & 1: result *= base base *= base exponent >>= 1 return result
Implement a Python solution for implements a URL shortener with in-memory storage. Return only the code.
import threading from urllib.parse import urlsplit class URLShortener: """Thread-safe URL shortener using process-local, non-persistent storage.""" _ALPHABET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" def __init__( self, code_length: int = 7, base_url: str ...
Implement a Python function to implements binary search. Output only the code.
def binary_search(arr, target): """Return target's index in an ascendingly sorted sequence, or -1 if absent.""" low, high = 0, len(arr) - 1 while low <= high: mid = (low + high) // 2 mid_value = arr[mid] if mid_value == target: return mid elif mid_value < target...
Implement a Python solution for implements a file watcher that logs changes. Return only the code.
#!/usr/bin/env python3 """Watch files for changes and log their creation, modification, deletion, or movement. Dependency: python -m pip install watchdog Examples: python file_watcher.py python file_watcher.py /path/to/watch --log-file changes.log python file_watcher.py /path/to/file /path/to/director...
Implement quicksort in Python with type hints. Return only the code.
from typing import TypeVar T = TypeVar("T") def quicksort(values: list[T]) -> list[T]: """Sort values in place in ascending order and return the list.""" stack: list[tuple[int, int]] = [(0, len(values) - 1)] while stack: left, right = stack.pop() if left >= right: continue ...
Implement Prim's algorithm in Python with type hints. Return only the code.
from collections.abc import Mapping from heapq import heappop, heappush from itertools import count from typing import Hashable, TypeVar Node = TypeVar("Node", bound=Hashable) def prim( graph: Mapping[Node, Mapping[Node, float]], start: Node | None = None, ) -> tuple[list[tuple[Node, Node, float]], float]: ...
Fill in the body of this function: def filter(arr, target): # computes the GCD of two numbers Return only the code.
def filter(arr, target): while target: arr, target = target, arr % target return abs(arr)
Fill in the body of this function: def load_config(s): # reverses a linked list Return only the code.
def load_config(s): reversed_head = None while s is not None: next_node = s.next s.next = reversed_head reversed_head = s s = next_node return reversed_head
Write a Python function that removes duplicates from a list. Return only the code.
def remove_duplicates(items): """Return a new list with duplicates removed, preserving order.""" seen = set() result = [] for item in items: if item not in seen: seen.add(item) result.append(item) return result
Create a Python function that parses a YAML file safely. Return None on error. Only the code.
import yaml def parse_yaml_file(file_path): try: with open(file_path, "r", encoding="utf-8") as file: return yaml.safe_load(file) except (yaml.YAMLError, OSError, UnicodeError): return None
Implement a Python class for a matrix with linear algebra operations. Return only the class.
class Matrix: """A rectangular matrix supporting common linear algebra operations.""" def __init__(self, data): if isinstance(data, Matrix): data = data.data try: rows = [list(row) for row in data] except TypeError as exc: raise TypeError("Matrix dat...
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_row = list(range(len(s2) + 1)) for i, char1 in enumerate(s1, start=1): current_row = [i] for j, char2 in enumerate(s2, star...
Implement a Python function to finds the longest common prefix of strings. Output only the code.
def longest_common_prefix(strings): """Return the longest common prefix of a nonempty collection of strings.""" if not strings: return "" shortest = min(strings, key=len) for i, char in enumerate(shortest): if any(string[i] != char for string in strings): return shortest[:i]...
Implement a Python function to computes the edit distance between two strings. Output only the code.
def edit_distance(s1: str, s2: str) -> int: """Return the Levenshtein distance between two strings.""" # Keep the shorter string as the columns to minimize memory usage. if len(s1) < len(s2): s1, s2 = s2, s1 n = len(s2) previous_row = list(range(n + 1)) for i, char1 in enumerate(s1, st...
Implement the longest common subsequence in Python with type hints. Return only the code.
from collections.abc import Sequence from typing import TypeVar T = TypeVar("T") def longest_common_subsequence(a: Sequence[T], b: Sequence[T]) -> list[T]: """Return an longest common subsequence of a and b in O(len(a) * len(b)) time.""" if len(a) < len(b): a, b = b, a m, n = len(a), len(b) d...
Implement heap sort in Python with type hints. Return only the code.
from typing import TypeVar T = TypeVar("T") def heap_sort(values: list[T]) -> list[T]: """Sort values in ascending order in place and return the list.""" n = len(values) def sift_down(root: int, size: int) -> None: while 2 * root + 1 < size: child = 2 * root + 1 if child ...
Write a Python function to process a log file. Include error handling. Return only the code.
from pathlib import Path def process_log_file(file_path: str | Path, encoding: str = "utf-8") -> dict: """ Count log entries by level. Entries must begin with a level followed by a message, such as 'INFO Service started' or '[ERROR] Connection failed'. Blank lines are ignored; malformed entries ar...
Implement a Python class for a graph with DFS and BFS. Return only the class.
class Graph: """A graph supporting iterative depth-first and breadth-first searches.""" def __init__(self, directed=False): self.directed = directed self.adj = {} def add_edge(self, u, v): """Add an edge, creating vertices automatically.""" self.adj.setdefault(u, []) ...
Write a Python function that implements heap sort. Return only the code.
def heap_sort(arr): """Sort arr in ascending order in place and return it.""" n = len(arr) def sift_down(root, size): while 2 * root + 1 < size: child = 2 * root + 1 if child + 1 < size and arr[child + 1] > arr[child]: child += 1 if arr[root] >= ...
Write a Python function that implements Bellman-Ford algorithm. Return only the code.
def bellman_ford(n, edges, source): """ Compute shortest distances from source using Bellman-Ford. Args: n: Number of vertices, labeled 0 through n - 1. edges: Iterable of (u, v, weight) tuples. source: Starting vertex. Returns: A dictionary mapping each vertex to its s...
Complete this Python function: def load_config(data): """computes the GCD of two numbers""" Return only the full function.
def load_config(data): """Compute the greatest common divisor of two integers.""" a, b = data while b: a, b = b, a % b return abs(a)
Fill in the body of this function: def calculate(data): # implements binary search Return only the code.
def calculate(data): """Return the index of target in a sorted sequence, or -1 if absent. data must be a (sorted_values, target) pair. """ values, target = data left, right = 0, len(values) - 1 while left <= right: mid = (left + right) // 2 if values[mid] == target: ...
Write a complete Python module that implements a file watcher that logs changes. Use functions and classes. Return only the code.
#!/usr/bin/env python3 """A portable, standard-library file watcher that logs changes. The watcher polls filesystem metadata, so changes are detected within the configured polling interval. Existing files establish a baseline without producing initial events. Files can be filtered with shell-style glob patterns. Exam...
Implement a Python function to checks if a year is a leap year. Output only the code.
def is_leap_year(year: int) -> bool: """Return whether a year is a leap year in the Gregorian calendar.""" return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)