instruction stringlengths 68 159 | output stringlengths 46 20k |
|---|---|
Complete this Python function:
def parse_input(arr, target):
"""computes the edit distance between two strings"""
Return only the full function. | def parse_input(arr, target):
"""Computes the edit distance between two strings."""
if len(arr) < len(target):
arr, target = target, arr
previous_row = list(range(len(target) + 1))
for i, char_arr in enumerate(arr, start=1):
current_row = [i]
for j, char_target in enumerate(tar... |
Implement a Python class for a linked list with insert/delete/reverse. Return only the class. | class LinkedList:
"""Singly linked list supporting insertion, deletion, and reversal."""
class _Node:
__slots__ = ("value", "next")
def __init__(self, value):
self.value = value
self.next = None
def __init__(self):
self.head = None
self._size = 0
... |
Implement a Python function to finds all prime factors of a number. Output only the code. | def find_prime_factors(n: int) -> list[int]:
"""Return prime factors in ascending order, including repeated factors."""
n = abs(n)
if n == 0:
raise ValueError("Zero has no finite prime factorization.")
factors = []
while n % 2 == 0:
factors.append(2)
n //= 2
divisor = 3... |
Write a Python function that counts the frequency of words in a string. Return only the code. | from collections import Counter
def count_words(text: str) -> dict[str, int]:
return dict(Counter(text.split())) |
Implement a Python function to detects a cycle in a linked list. Output only the code. | def has_cycle(head) -> bool:
"""Return True if the linked list contains a cycle, otherwise False."""
slow = fast = head
while fast is not None and fast.next is not None:
slow = slow.next
fast = fast.next.next
if slow is fast:
return True
return False |
Implement binary search in Python with type hints. Return only the code. | def binary_search(items: Sequence[int], target: int) -> int:
"""Return the index of target in a sorted sequence, or -1 if not found."""
left, right = 0, len(items) - 1
while left <= right:
mid = left + (right - left) // 2
if items[mid] == target:
return mid
if items[mid... |
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
valid_coins = [coin for coin in coins if coin > 0]
unreachable = amount + 1
dp = [unreachable] ... |
Implement a Python solution for implements a task queue with worker threads. Return only the code. | import queue
import threading
from concurrent.futures import Future
class TaskQueue:
"""Execute submitted callables using a fixed pool of worker threads."""
def __init__(
self,
num_workers: int = 1,
*,
name_prefix: str = "task-worker",
daemon: bool = False,
):
... |
Complete this Python function:
def validate(n):
"""reverses a linked list"""
Return only the full function. | def validate(n):
"""Reverse the linked list starting at n and return its new head."""
previous = None
current = n
while current is not None:
next_node = current.next
current.next = previous
previous = current
current = next_node
return previous |
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 2 raised to n using fast exponentiation."""
if not isinstance(n, int) or n < 0:
raise ValueError("n must be a non-negative integer")
result = 1
base = 2
while n:
if n & 1:
result *= base
base *= base
n >>= 1
return result |
Create a Python function that parses a Parquet file safely. Return None on error. Only the code. | def parse_parquet(file_path):
"""Parse a Parquet file into an Arrow Table, returning None on failure."""
try:
import pyarrow.parquet as pq
return pq.read_table(file_path, memory_map=False, pre_buffer=False)
except Exception:
return None |
Write a Python class that implements a bank account with deposits and withdrawals. Return only the code. | class BankAccount:
"""A bank account supporting deposits and withdrawals."""
def __init__(self, initial_balance: float = 0.0) -> None:
self._balance = 0.0
self.deposit(initial_balance)
@property
def balance(self) -> float:
return self._balance
def deposit(self, amount: flo... |
Implement a Python function to checks if a number is prime. Output only the code. | def is_prime(number: int) -> bool:
if number < 2:
return False
if number == 2:
return True
if number % 2 == 0:
return False
divisor = 3
while divisor * divisor <= number:
if number % divisor == 0:
return False
divisor += 2
return True |
Write a Python class that implements a matrix with linear algebra operations. Return only the code. | from __future__ import annotations
from numbers import Number
from typing import Iterable, Sequence
class Matrix:
"""An immutable, nonempty rectangular matrix of numeric values.
+ and - perform elementwise addition and subtraction.
* and @ perform matrix multiplication; * also supports scalar multiplicat... |
Write a Python class that implements a task scheduler with priorities. Return only the code. | import heapq
import itertools
import threading
from concurrent.futures import Future
class TaskScheduler:
"""Execute callables asynchronously in priority order.
Lower priority values run first; equal priorities run in submission order.
Each task runs on one of the scheduler's worker threads.
submit()... |
Write a Python function to process an INI file. Include error handling. Return only the code. | import configparser
from pathlib import Path
from typing import Dict, Union
def process_ini_file(
file_path: Union[str, Path],
*,
encoding: str = "utf-8",
) -> Dict[str, Dict[str, str]]:
"""Read an INI file and return its sections and options as a dictionary.
Option names retain their original cas... |
Write a Python function to process a Parquet file. Include error handling. Return only the code. | from pathlib import Path
from typing import Optional
import pandas as pd
def process_parquet_file(
file_path: str,
columns: Optional[list[str]] = None,
output_path: Optional[str] = None,
) -> pd.DataFrame:
"""Read a Parquet file, optionally select columns, and optionally save the result.
Raises:
... |
Write a Python function that sorts a list using quicksort. Return only the code. | def quicksort(arr):
"""Sort a list in place using randomized three-way quicksort."""
from random import randint
stack = [(0, len(arr) - 1)]
while stack:
lo, hi = stack.pop()
if lo >= hi:
continue
pivot = arr[randint(lo, hi)]
lt, i, gt = lo, lo, hi
... |
Implement a Python function to computes the Fibonacci sequence up to n. Output only the code. | def fibonacci(n: int) -> list[int]:
"""Return the Fibonacci sequence from F_0 through F_n."""
if n < 0:
raise ValueError("n must be non-negative")
sequence = []
a, b = 0, 1
for _ in range(n + 1):
sequence.append(a)
a, b = b, a + b
return sequence |
Create a Python function that parses a log file safely. Return None on error. Only the code. | from __future__ import annotations
import json
import os
from typing import Any
def parse_log_file(path: str | os.PathLike[str]) -> list[dict[str, Any]] | None:
"""Parse UTF-8 plain-text or JSON-object-per-line logs.
Plain-text lines become {"message": line}; blank lines are skipped.
Return None for unre... |
Write a Python function that calculates the factorial of n. Return only the code. | def factorial(n: int) -> int:
if n < 0:
raise ValueError("n must be a non-negative integer")
result = 1
for i in range(2, n + 1):
result *= i
return result |
Write a Python class that implements a task scheduler with priorities. Return only the code. | from __future__ import annotations
import heapq
import itertools
import threading
from typing import Any, Callable, Generic, TypeVar
T = TypeVar("T")
class TaskScheduler(Generic[T]):
"""Execute queued callables in ascending priority order.
Lower priority values run first. Equal priorities run in submission ... |
Write a Python function that implements the segment tree. Return only the code. | def segment_tree(values, operation, identity):
"""
Return (query, update) functions for a segment tree.
Args:
values: A nonempty sequence of initial values.
operation: An associative function combining two adjacent values.
identity: The operation's neutral value.
query(left, ri... |
Implement a Python class for a priority queue using a heap. Return only the class. | class PriorityQueue:
"""Min-priority queue with FIFO ordering for equal priorities."""
def __init__(self):
import heapq
self._heap = []
self._counter = 0
def push(self, priority, value):
"""Insert a value. Lower priorities are removed first."""
import heapq
... |
Implement a Python function to finds the longest increasing subsequence. Output only the code. | from bisect import bisect_left
def longest_increasing_subsequence(sequence):
"""Return a longest strictly increasing subsequence in O(n log n) time."""
if not sequence:
return []
tails = []
tail_indices = []
previous = [None] * len(sequence)
for index, value in enumerate(sequence):
... |
Write a Python function that implements a queue using two stacks. Return only the code. | class Queue:
def __init__(self):
self._incoming = []
self._outgoing = []
def enqueue(self, item):
self._incoming.append(item)
def dequeue(self):
if not self._outgoing:
while self._incoming:
self._outgoing.append(self._incoming.pop())
if ... |
Create a Python function that parses a binary file safely. Return None on error. Only the code. | def parse_binary_file(file_path):
"""Return the file's binary contents, or None if it cannot be read."""
try:
with open(file_path, "rb") as file:
return file.read()
except Exception:
return None |
Write a Python function to process a JSON string. Include error handling. Return only the code. | import json
from typing import Any
def process_json(json_string: str) -> Any:
"""Parse a JSON string and return the resulting Python object.
Raises:
TypeError: If the input is not a string.
ValueError: If the input contains invalid JSON.
"""
if not isinstance(json_string, str):
... |
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 edit distance between two strings."""
# Keep the shorter string in the DP columns to minimize memory usage.
if len(s1) < len(s2):
s1, s2 = s2, s1
previous = list(range(len(s2) + 1))
for i, char1 in enumerate(s1, start=1)... |
Implement a Python class for a graph with DFS and BFS. Return only the class. | from collections import deque
from collections.abc import Hashable
class Graph:
"""An adjacency-list graph supporting depth-first and breadth-first search."""
def __init__(self, directed: bool = False) -> None:
self.directed = directed
self.adjacency: dict[Hashable, list[Hashable]] = {}
d... |
Implement a Python function to sorts a list using merge sort. Output only the code. | def merge_sort(items):
"""Return a sorted copy of the list using merge sort."""
if len(items) <= 1:
return items[:]
mid = len(items) // 2
left = merge_sort(items[:mid])
right = merge_sort(items[mid:])
merged = []
i = j = 0
while i < len(left) and j < len(right):
if lef... |
Implement a Python class for a graph with DFS and BFS. Return only the class. | class Graph:
"""Graph with iterative depth-first and breadth-first traversal.
Vertices must be hashable. Edges are undirected by default.
Both traversal methods return the visited vertices in traversal order.
If target is provided, traversal stops when that vertex is reached.
"""
def __init__(... |
Implement a Python function to sorts a list using quicksort. Output only the code. | def quicksort(arr):
"""Sort arr in place in ascending order and return it."""
def sort(low, high):
if low >= high:
return
pivot = arr[(low + high) // 2]
left, current, right = low, low, high
while current <= right:
if arr[current] < pivot:
... |
Write a Python class that implements a deck of cards with shuffle and deal. Return only the code. | from itertools import product
from random import shuffle
class Deck:
"""A standard 52-card deck that can be shuffled and dealt from."""
SUITS = ("Hearts", "Diamonds", "Clubs", "Spades")
RANKS = ("Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10",
"Jack", "Queen", "King")
def __init__(se... |
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 non-negative n."""
if n < 0:
raise ValueError("n must be non-negative")
if k < 0 or k > n:
return 0
k = min(k, n - k)
result = 1
for i in range(1, k + 1):
result = result * (n - k + i) //... |
Write a Python function that implements Kruskal's algorithm. Return only the code. | def kruskal(n, edges):
"""
Return a minimum spanning forest as a list of (u, v, weight) edges.
Args:
n: Number of vertices, labeled 0 through n - 1.
edges: Iterable of (u, v, weight) tuples.
If the graph is disconnected, return a minimum spanning forest.
"""
parent = list(range... |
Implement a Python function to sorts a list using quicksort. Output only the code. | def quicksort(values):
"""Sort a list in place using quicksort and return it."""
if len(values) < 2:
return values
stack = [(0, len(values) - 1)]
while stack:
low, high = stack.pop()
while low < high:
pivot = values[(low + high) // 2]
i, j = low, high
... |
Create a Python function that parses a text file line by line safely. Return None on error. Only the code. | def parse_file(file_path):
try:
with open(file_path, "r", encoding="utf-8") as file:
return [line.rstrip("\n") for line in file]
except (OSError, UnicodeError):
return None |
Fill in the body of this function:
def find(data):
# counts the frequency of words in a string
Return only the code. | def find(data):
counts = {}
for word in data.split():
counts[word] = counts.get(word, 0) + 1
return counts |
Complete this Python function:
def split(lst):
"""sorts a list using quicksort"""
Return only the full function. | def split(lst):
"""Sort a list using quicksort and return the sorted list."""
if len(lst) <= 1:
return lst[:]
pivot = lst[len(lst) // 2]
left = [item for item in lst if item < pivot]
equal = [item for item in lst if item == pivot]
right = [item for item in lst if item > pivot]
retu... |
Implement a Python class for a binary search tree with insert/delete/search. Return only the class. | class BinarySearchTree:
"""Binary search tree supporting insert, search, and deletion.
Duplicate values are ignored. Deleting a value removes one matching node.
"""
class _Node:
__slots__ = ("value", "left", "right")
def __init__(self, value):
self.value = value
... |
Write a Python function that implements the coin change problem. Return only the code. | def coin_change(coins: list[int], amount: int) -> int:
"""Return the fewest coins needed to make amount, or -1 if impossible.
Assumes all coin denominations are positive integers.
"""
if amount < 0:
return -1
unreachable = amount + 1
dp = [unreachable] * (amount + 1)
dp[0] = 0
... |
Implement the segment tree in Python with type hints. Return only the code. | from __future__ import annotations
from collections.abc import Callable, Sequence
from typing import Generic, TypeVar
T = TypeVar("T")
class SegmentTree(Generic[T]):
"""Segment tree supporting point updates and range queries.
The operation must be associative, and the identity must be a neutral
element ... |
Write a Python function that sorts a list using merge sort. Return only the code. | def merge_sort(items):
if len(items) <= 1:
return list(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])
... |
Implement a Python function to computes the Fibonacci sequence up to n. Output only the code. | def fibonacci(n):
"""Return a list containing the first n Fibonacci numbers."""
sequence = []
a, b = 0, 1
for _ in range(n):
sequence.append(a)
a, b = b, a + b
return sequence |
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 the 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 |
Complete this Python function:
def merge(lst):
"""checks if a year is a leap year"""
Return only the full function. | def merge(lst):
"""Return a boolean for each year indicating whether it is a leap year."""
return [
year % 400 == 0 or (year % 4 == 0 and year % 100 != 0)
for year in lst
] |
Complete this Python function:
def transform(x, y):
"""detects a cycle in a linked list"""
Return only the full function. | def transform(x, y):
"""detects a cycle in a linked list"""
if x is None:
return False
slow, fast = x, y
while fast is not None and fast.next is not None:
slow = slow.next
fast = fast.next.next
if slow is fast:
return True
return False |
Complete this Python function:
def split(x, y):
"""checks if a string is a palindrome"""
Return only the full function. | def split(x, y):
"""checks if a string is a palindrome"""
return x == x[::-1] |
Write a Python class that implements a matrix with linear algebra operations. Return only the code. | from __future__ import annotations
from collections.abc import Iterable
from numbers import Number
from typing import Union
MatrixInput = Union["Matrix", Iterable[Iterable[Number]]]
class Matrix:
"""A rectangular matrix supporting common linear algebra operations."""
def __init__(self, data: MatrixInput):
... |
Fill in the body of this function:
def load_config(data):
# finds the first non-repeating character
Return only the code. | from collections import Counter
def load_config(data):
counts = Counter(data)
for char in data:
if counts[char] == 1:
return char
return None |
Implement a Python function to computes the power of a number using fast exponentiation. Output only the code. | def power(base, exponent):
"""Return base raised to exponent using fast exponentiation."""
if exponent < 0:
base = 1 / base
exponent = -exponent
result = 1
while exponent:
if exponent & 1:
result *= base
base *= base
exponent >>= 1
return result |
Fill in the body of this function:
def search(s):
# implements a queue using two stacks
Return only the code. | def search(s):
"""Return a FIFO queue initialized with the items in s."""
class Queue:
def __init__(self, items):
self.incoming = []
self.outgoing = []
for item in items:
self.enqueue(item)
def enqueue(self, item):
self.incoming.a... |
Fill in the body of this function:
def sort(data):
# implements the sieve of Eratosthenes
Return only the code. | def sort(data):
from math import isqrt
data = list(data)
limit = max(data, default=1)
if limit < 2:
return []
is_prime = [True] * (limit + 1)
is_prime[0] = is_prime[1] = False
for p in range(2, isqrt(limit) + 1):
if is_prime[p]:
for multiple in range(p * p, lim... |
Implement a Python solution for implements a text-based adventure game engine. Return only the code. | Need command "wield lantern" not required. Hardcoded okay. General engine shouldn't be game-specific attack behavior, but lamp useful expected. Could keep attack default 2 + held `light` lit +2 as intuitive game rule documented. `HELP attack` say "Fight a hostile creature (lit light sources add 2 damage)." Engine reusa... |
Write a Python function that finds the middle of a linked list. Return only the code. | def find_middle(head):
"""Return the middle node, or None if the list is empty."""
slow = fast = head
while fast is not None and fast.next is not None:
slow = slow.next
fast = fast.next.next
return slow |
Write a complete Python module that implements a diff algorithm for text files. Use functions and classes. Return only the code. | """Line-oriented text diffing with structured results and unified output.
Uses the standard-library difflib.SequenceMatcher algorithm.
Supports strings, paths, and open text streams.
Example:
result = diff_files("before.txt", "after.txt", context=3)
print(result.unified_diff, end="")
"""
from __future__ impo... |
Implement a Python class for a matrix with linear algebra operations. Return only the class. | class Matrix:
"""A nonempty, rectangular, read-only matrix supporting common linear algebra operations."""
def __init__(self, data):
try:
rows = [list(row) for row in data]
except TypeError as exc:
raise TypeError("Matrix data must be a two-dimensional iterable.") from e... |
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 None if the linked list is empty."""
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 binary search. Output only the code. | def binary_search(arr, target):
"""Return target's index in a sorted array, or -1 if it is not present."""
left, right = 0, len(arr) - 1
while left <= right:
mid = (left + right) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
left = mid + 1
... |
Implement the coin change problem in Python with type hints. Return only the code. | def coin_change(coins: list[int], amount: int) -> int:
"""Return the minimum number of coins needed, or -1 if impossible.
Unlimited coins of each denomination are available.
"""
if amount < 0:
return -1
if any(coin <= 0 for coin in coins):
raise ValueError("Coin denominations must b... |
Complete this Python function:
def filter(arr, target):
"""finds the longest increasing subsequence"""
Return only the full function. | def filter(arr, target):
"""Return the longest strictly increasing subsequence of arr."""
from bisect import bisect_left
if not arr:
return []
tails = []
tail_indices = []
predecessors = [-1] * len(arr)
for i, value in enumerate(arr):
pos = bisect_left(tails, value)
... |
Create a Python function that parses an INI file safely. Return None on error. Only the code. | import configparser
def parse_ini_file(path, *, encoding="utf-8-sig"):
"""Return a dictionary of INI sections and options, or None on error."""
parser = configparser.ConfigParser(
interpolation=None,
strict=True,
delimiters=("=",),
inline_comment_prefixes=None,
allow_no_... |
Write a Python function that implements the Union-Find data structure. Return only the code. | class UnionFind:
"""Disjoint-set data structure with path compression and union by size."""
def __init__(self, n: int) -> None:
if n < 0:
raise ValueError("n must be non-negative")
self.parent = list(range(n))
self.size = [1] * n
self.component_count = n
def fi... |
Write a Python function that finds the longest increasing subsequence. Return only the code. | from bisect import bisect_left
def longest_increasing_subsequence(sequence):
"""Return a longest strictly increasing subsequence in O(n log n) time."""
tails = []
parent = [-1] * len(sequence)
for i, value in enumerate(sequence):
pos = bisect_left(tails, value)
if pos > 0:
... |
Implement the trie data structure in Python with type hints. Return only the code. | from __future__ import annotations
from collections.abc import Iterator
from typing import Optional
class _TrieNode:
__slots__ = ("children", "is_terminal")
def __init__(self) -> None:
self.children: dict[str, _TrieNode] = {}
self.is_terminal: bool = False
class Trie:
"""A prefix tree su... |
Write a Python class that implements a shopping cart with add/remove/total. Return only the code. | class ShoppingCart:
"""Stores item names and their prices."""
def __init__(self) -> None:
self._items: dict[str, float] = {}
def add(self, item: str, price: float) -> None:
self._items[item] = price
def remove(self, item: str) -> None:
del self._items[item]
def total(self... |
Write a Python class that implements a rate limiter with token bucket. Return only the code. | import math
import threading
import time
class TokenBucket:
"""Thread-safe token bucket that starts full and refills at a constant rate."""
def __init__(self, rate: float, capacity: float | None = None) -> None:
if not math.isfinite(rate) or rate <= 0:
raise ValueError("rate must be a posi... |
Implement Floyd-Warshall algorithm in Python with type hints. Return only the code. | from math import inf
def floyd_warshall(distances: list[list[float]]) -> list[list[float]]:
"""Compute all-pairs shortest paths in place and return the distance matrix.
Represent missing edges with math.inf and diagonal entries with 0.
The matrix must be square; no path exists between unreachable vertices... |
Write a Python function that computes the GCD of two numbers. Return only the code. | def gcd(a, b):
a, b = abs(a), abs(b)
while b:
a, b = b, a % b
return a |
Write a Python class that implements a rate limiter with token bucket. Return only the code. | import math
import threading
import time
class TokenBucket:
"""Thread-safe token bucket that refills continuously at a fixed rate.
Args:
rate: Number of tokens added per second. Must be positive.
capacity: Maximum number of tokens the bucket can hold.
initial_tokens: Starting balance; ... |
Write a Python function that sorts a list using quicksort. Return only the code. | def quicksort(items: list) -> list:
"""Return a new list sorted in ascending order using quicksort."""
if len(items) <= 1:
return items
pivot = items[len(items) // 2]
left = [item for item in items if item < pivot]
equal = [item for item in items if item == pivot]
right = [item for item... |
Write a Python function that implements the longest common subsequence. Return only the code. | def longest_common_subsequence(s1: str, s2: str) -> str:
"""Return one longest common subsequence of s1 and s2."""
m, n = len(s1), len(s2)
dp = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(m - 1, -1, -1):
for j in range(n - 1, -1, -1):
if s1[i] == s2[j]:
dp[i... |
Write a Python function to process a YAML file. Include error handling. Return only the code. | import yaml
from pathlib import Path
from typing import Any
def process_yaml_file(file_path: str | Path) -> Any:
"""Safely parse a YAML file into Python objects. Empty files return None.
Raises:
FileNotFoundError: If the file does not exist.
ValueError: If the file contains invalid YAML or inv... |
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, starting with 0 and 1."""
sequence = []
a, b = 0, 1
for _ in range(n):
sequence.append(a)
a, b = b, a + b
return sequence |
Write a Python function that implements the segment tree. Return only the code. | class SegmentTree:
"""Supports point updates and range queries on [left, right)."""
def __init__(self, values, operation="sum"):
values = list(values)
operations = {
"sum": (0, lambda a, b: a + b),
"min": (float("inf"), min),
"max": (float("-inf"), max),
... |
Write a Python function that finds the middle of a linked list. Return only the code. | def find_middle(head):
"""Return the middle node, or the second middle for an even-length list."""
slow = fast = head
while fast is not None and fast.next is not None:
slow = slow.next
fast = fast.next.next
return slow |
Complete this Python function:
def compute(data):
"""implements a queue using two stacks"""
Return only the full function. | def compute(data):
"""Process data in FIFO order using two stacks and return the queue."""
incoming = []
outgoing = []
for item in data:
incoming.append(item)
while incoming:
outgoing.append(incoming.pop())
queue = []
while outgoing:
queue.append(outgoing.pop())
... |
Write a Python function that implements the segment tree. Return only the code. | import operator
class SegmentTree:
"""Supports point updates and range queries in O(log n) time."""
def __init__(self, values, operation=operator.add, identity=0):
"""
Args:
values: Iterable of initial values.
operation: Associative merge operation, such as operator.add... |
Implement a Python class for a shopping cart with add/remove/total. Return only the class. | class ShoppingCart:
"""A cart of named items and their prices."""
def __init__(self) -> None:
self.items: dict[str, float] = {}
def add(self, item: str, price: float) -> None:
if price < 0:
raise ValueError("Price cannot be negative.")
self.items[item] = price
def ... |
Write a Python function that implements the longest common subsequence. Return only the code. | def longest_common_subsequence(s1: str, s2: str) -> str:
"""Return one longest common subsequence of s1 and s2."""
if len(s1) < len(s2):
s1, s2 = s2, s1
m, n = len(s1), len(s2)
dp = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(1, m + 1):
for j in range(1, n + 1):
... |
Implement a Python class for a hash map with collision handling. Return only the class. | class HashMap:
"""A hash map using separate chaining and automatic resizing."""
def __init__(self, initial_capacity=8, load_factor=0.75):
if initial_capacity < 1:
raise ValueError("initial_capacity must be positive")
if load_factor <= 0:
raise ValueError("load_factor mus... |
Complete this Python function:
def calculate(x, y):
"""detects a cycle in a linked list"""
Return only the full function. | def calculate(x, y):
"""Detects a cycle in a linked list."""
if y is None:
y = x
while y is not None:
if x is y:
return True
if x is None or y.next is None:
return False
x = x.next
y = y.next.next
return x is y |
Implement heap sort in Python with type hints. Return only the code. | from typing import List, TypeVar
T = TypeVar("T")
def heap_sort(values: List[T]) -> List[T]:
"""Sort values in place in ascending order and return the list."""
n = len(values)
def sift_down(root: int, heap_size: int) -> None:
while True:
left = 2 * root + 1
if left >= heap... |
Write a Python function to process a configuration file. Include error handling. Return only the code. | import configparser
import os
from pathlib import Path
from typing import Any
class ConfigurationError(Exception):
"""Raised when a configuration file cannot be read or parsed."""
def process_configuration_file(
file_path: str | os.PathLike[str],
) -> dict[str, dict[str, Any]]:
"""Read an INI configuratio... |
Complete this Python function:
def filter(data):
"""finds the first non-repeating character"""
Return only the full function. | def filter(data):
"""finds the first non-repeating character"""
counts = {}
for char in data:
counts[char] = counts.get(char, 0) + 1
for char in data:
if counts[char] == 1:
return char
return None |
Write a Python class that implements a priority queue using a heap. Return only the code. | import heapq
from typing import Generic, TypeVar
T = TypeVar("T")
class PriorityQueue(Generic[T]):
"""A min-priority queue backed by a binary heap."""
def __init__(self) -> None:
self._heap: list[T] = []
def push(self, item: T) -> None:
heapq.heappush(self._heap, item)
def pop(self)... |
Write a Python function that implements the Fenwick tree. Return only the code. | def fenwick_tree(size: int):
"""Return add, prefix_sum, and range_sum functions for a Fenwick tree."""
if size < 0:
raise ValueError("size must be non-negative")
tree = [0] * (size + 1)
def add(index: int, delta: int) -> None:
"""Add delta to the element at the 1-based index."""
... |
Write a complete Python module that implements a simple blockchain. Use functions and classes. Return only the code. | We need produce only code complete Python module implements simple blockchain uses functions classes. Need plan appropriate self-contained clear quality, not overengineer, no dependencies ideally hashlib, dataclasses, datetime or time, typing, json, threading optional. We must ensure return only code no markdown. We ha... |
Write a Python function that implements Prim's algorithm. Return only the code. | import heapq
from itertools import count
def prim(graph, start=None):
"""Return the minimum spanning tree as a list of (u, v, weight) edges.
Args:
graph: An undirected weighted graph represented as
{vertex: {neighbor: weight}}.
start: Optional starting vertex. If omitted, use any v... |
Write a Python function that implements the Fenwick tree. Return only the code. | class FenwickTree:
def __init__(self, values=()):
self.n = len(values)
self.tree = [0] + list(values)
for i in range(1, self.n + 1):
parent = i + (i & -i)
if parent <= self.n:
self.tree[parent] += self.tree[i]
def add(self, index, delta):
... |
Implement a Python class for a rate limiter with token bucket. Return only the class. | class TokenBucketRateLimiter:
"""Thread-safe, non-blocking token bucket rate limiter.
Args:
capacity: Maximum number of tokens the bucket can hold.
refill_rate: Tokens added per second.
initial_tokens: Starting token count; defaults to capacity.
clock: Optional monotonic time fu... |
Write a Python function that checks if two strings are anagrams. Return only the code. | from collections import Counter
def are_anagrams(s1: str, s2: str) -> bool:
return Counter(s1) == Counter(s2) |
Implement breadth-first search in Python with type hints. Return only the code. | from collections import deque
from collections.abc import Iterable, Mapping
from typing import TypeVar
T = TypeVar("T")
def breadth_first_search(graph: Mapping[T, Iterable[T]], start: T) -> list[T]:
"""Return the nodes reachable from start in breadth-first order."""
queue: deque[T] = deque([start])
visite... |
Implement Floyd-Warshall algorithm in Python with type hints. Return only the code. | from math import inf
from typing import TypeAlias
Number: TypeAlias = int | float
Matrix: TypeAlias = list[list[Number]]
def floyd_warshall(
distances: Matrix,
*,
detect_negative_cycles: bool = False,
) -> Matrix:
"""Compute all-pairs shortest paths in place.
Unreachable paths must be represented... |
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."""
return list(dict.fromkeys(items)) |
Implement a Python function to finds the first non-repeating character. Output only the code. | def first_non_repeating_character(s: str):
"""Return the first non-repeating character, or None if none exists."""
counts = {}
for char in s:
counts[char] = counts.get(char, 0) + 1
for char in s:
if counts[char] == 1:
return char
return None |
Write a Python function that implements a queue using two stacks. Return only the code. | class MyQueue:
def __init__(self):
self._incoming = []
self._outgoing = []
def enqueue(self, item):
self._incoming.append(item)
def dequeue(self):
if not self._outgoing:
while self._incoming:
self._outgoing.append(self._incoming.pop())
i... |
Write a Python function that computes the edit distance between two strings. Return only the code. | def edit_distance(s1: str, s2: str) -> int:
"""Return the Levenshtein edit distance between two strings."""
if len(s1) < len(s2):
s1, s2 = s2, s1
previous = list(range(len(s2) + 1))
for i, char1 in enumerate(s1, start=1):
current = [i] + [0] * len(s2)
for j, char2 in enumerate(... |
Write a complete Python module that implements a task queue with worker threads. Use functions and classes. Return only the code. | """A thread-safe, unbounded FIFO task queue backed by worker threads.
Each submitted task receives a concurrent.futures.Future. Exceptions raised by
tasks are stored in their futures and never escape the worker threads.
Example:
with TaskQueue(num_workers=4) as tasks:
future = tasks.submit(pow, 2, 10)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.