The full dataset viewer is not available (click to read why). Only showing a preview of the rows.
Error code: DatasetGenerationError
Exception: CastError
Message: Couldn't cast
id: string
prompt: string
tests: list<item: string>
child 0, item: string
kind: string
completion: string
to
{'prompt': Value('string'), 'completion': Value('string')}
because column names don't match
Traceback: Traceback (most recent call last):
File "/usr/local/lib/python3.14/site-packages/datasets/builder.py", line 1827, in _prepare_split_single
for key, table in generator:
^^^^^^^^^
File "/src/services/worker/src/worker/job_runners/config/parquet_and_info.py", line 613, in wrapped
for item in generator(*args, **kwargs):
~~~~~~~~~^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.14/site-packages/datasets/packaged_modules/json/json.py", line 343, in _generate_tables
self._cast_table(pa_table, json_field_paths=json_field_paths),
~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.14/site-packages/datasets/packaged_modules/json/json.py", line 132, in _cast_table
pa_table = table_cast(pa_table, self.info.features.arrow_schema)
File "/usr/local/lib/python3.14/site-packages/datasets/table.py", line 2378, in table_cast
return cast_table_to_schema(table, schema)
File "/usr/local/lib/python3.14/site-packages/datasets/table.py", line 2306, in cast_table_to_schema
raise CastError(
...<3 lines>...
)
datasets.table.CastError: Couldn't cast
id: string
prompt: string
tests: list<item: string>
child 0, item: string
kind: string
completion: string
to
{'prompt': Value('string'), 'completion': Value('string')}
because column names don't match
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/src/services/worker/src/worker/job_runners/config/parquet_and_info.py", line 1369, in compute_config_parquet_and_info_response
parquet_operations, partial, estimated_dataset_info = stream_convert_to_parquet(
~~~~~~~~~~~~~~~~~~~~~~~~~^
builder, max_dataset_size_bytes=max_dataset_size_bytes
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
)
^
File "/src/services/worker/src/worker/job_runners/config/parquet_and_info.py", line 948, in stream_convert_to_parquet
builder._prepare_split(split_generator=splits_generators[split], file_format="parquet")
~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.14/site-packages/datasets/builder.py", line 1694, in _prepare_split
for job_id, done, content in self._prepare_split_single(
~~~~~~~~~~~~~~~~~~~~~~~~~~^
gen_kwargs=gen_kwargs, job_id=job_id, **_prepare_split_args
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
):
^
File "/usr/local/lib/python3.14/site-packages/datasets/builder.py", line 1880, in _prepare_split_single
raise DatasetGenerationError("An error occurred while generating the dataset") from e
datasets.exceptions.DatasetGenerationError: An error occurred while generating the datasetNeed help to make the dataset viewer work? Make sure to review how to configure the dataset viewer, and open a discussion for direct support.
prompt string | completion string |
|---|---|
Implement the following Python function. Return ONLY the function definition, no explanation.
def count_word_frequencies(text_data: str) -> dict[str, int]:
"""
Counts the frequency of each unique word in a given string.
Words are case-insensitive. Punctuation (periods, commas, exclamation marks, question ... | import string
def count_word_frequencies(text_data: str) -> dict[str, int]:
word_counts = {}
# Create a translation table to remove punctuation
translator = str.maketrans('', '', string.punctuation)
# Split the text into words, convert to lowercase, and strip punctuation
words = text_data.lowe... |
Implement the following Python function. Return ONLY the function definition, no explanation.
def sum_of_divisors(n: int) -> int:
"""
Calculates the sum of all positive divisors of a given integer n.
A divisor of n is an integer that divides n without leaving a remainder.
For example, the divisors of 6... | def sum_of_divisors(n: int) -> int:
if n == 1:
return 1
total_sum = 0
for i in range(1, int(n**0.5) + 1):
if n % i == 0:
total_sum += i
if i * i != n:
total_sum += n // i
return total_sum |
Implement the following Python function. Return ONLY the function definition, no explanation.
def find_peak_elements(nums):
"""
Find all 'peak' elements in a list of numbers. A peak element is an element
that is strictly greater than its neighbors. For elements at the boundaries
(first and last), only ... | def find_peak_elements(nums):
if not nums:
return []
if len(nums) == 1:
return [nums[0]]
peaks = []
n = len(nums)
# Check first element
if nums[0] > nums[1]:
peaks.append(nums[0])
# Check middle elements
for i in range(1, n - 1):
if nums[i] > nums[i-1] ... |
Implement the following Python function. Return ONLY the function definition, no explanation.
def flatten_nested_list(nested_list):
"""
Recursively flattens a arbitrarily nested list of integers into a single flat list of integers.
The order of elements in the flattened list should be the same as their app... | def flatten_nested_list(nested_list):
flattened = []
for item in nested_list:
if isinstance(item, list):
flattened.extend(flatten_nested_list(item))
else:
flattened.append(item)
return flattened |
Implement the following Python function. Return ONLY the function definition, no explanation.
def rotate_matrix_90_clockwise(matrix):
"""
Rotates a given square matrix 90 degrees clockwise in-place.
The matrix is represented as a list of lists. The input matrix is guaranteed to be square
(number of ro... | def rotate_matrix_90_clockwise(matrix):
n = len(matrix)
# Transpose the matrix
for i in range(n):
for j in range(i, n):
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
# Reverse each row
for i in range(n):
matrix[i].reverse() |
Implement the following Python function. Return ONLY the function definition, no explanation.
def count_word_frequencies(text: str) -> dict[str, int]:
"""
Counts the frequency of each word in the given text.
Words are case-insensitive and should be converted to lowercase.
Punctuation (any character th... | import re
def count_word_frequencies(text: str) -> dict[str, int]:
"""
Counts the frequency of each word in the given text.
Words are case-insensitive and should be converted to lowercase.
Punctuation (any character that is not a letter or a number) should be removed.
The function should return a ... |
Implement the following Python function. Return ONLY the function definition, no explanation.
def reverse_words_preserve_spaces(text: str) -> str:
"""
Reverses the order of words in a string while preserving all whitespace characters
(including leading, trailing, and multiple consecutive spaces) in their o... | def reverse_words_preserve_spaces(text: str) -> str:
if not text:
return ""
# Split the string into words and space sequences
parts = []
current_part = []
is_in_word = False
for char in text:
if char.isspace():
if is_in_word:
parts.append("".join(cur... |
Implement the following Python function. Return ONLY the function definition, no explanation.
def find_median_sorted_arrays(nums1: list[int], nums2: list[int]) -> float:
"""
Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median
of the two sorted arrays. The overall run tim... | def find_median_sorted_arrays(nums1: list[int], nums2: list[int]) -> float:
m, n = len(nums1), len(nums2)
if m > n:
nums1, nums2, m, n = nums2, nums1, n, m
# Ensure nums1 is the shorter array for binary search efficiency
low, high = 0, m
median_pos = (m + n + 1) // 2
while low <= high... |
Implement the following Python function. Return ONLY the function definition, no explanation.
def merge_overlapping_intervals(intervals):
"""
Given a list of intervals, merge all overlapping intervals and return a list of the merged intervals.
An interval is a list or tuple of two integers [start, end].
... | def merge_overlapping_intervals(intervals):
if not intervals:
return []
# Sort intervals by their start times
intervals.sort(key=lambda x: x[0])
merged = []
for interval in intervals:
# If the merged list is empty or the current interval does not overlap
# with the previous... |
Implement the following Python function. Return ONLY the function definition, no explanation.
def sum_of_divisors(n: int) -> int:
"""
Calculates the sum of all positive divisors of a given positive integer n.
A divisor of n is an integer that divides n without leaving a remainder.
For example, the div... | def sum_of_divisors(n: int) -> int:
if n == 1:
return 1
total_sum = 0
for i in range(1, int(n**0.5) + 1):
if n % i == 0:
total_sum += i
if i * i != n:
total_sum += n // i
return total_sum |
Implement the following Python function. Return ONLY the function definition, no explanation.
def merge_overlapping_intervals(intervals: list[tuple[int, int]]) -> list[tuple[int, int]]:
"""
Merges a list of possibly overlapping intervals into a list of non-overlapping intervals.
Each interval is represent... | def merge_overlapping_intervals(intervals: list[tuple[int, int]]) -> list[tuple[int, int]]:
if not intervals:
return []
# Sort intervals by their start times
intervals.sort(key=lambda x: x[0])
merged = []
current_start, current_end = intervals[0]
for i in range(1, len(intervals)):
... |
Implement the following Python function. Return ONLY the function definition, no explanation.
def find_peak_elements(arr):
"""
Given a list of integers `arr`, find all "peak" elements and return them in a new list.
A peak element is an element that is strictly greater than its neighbors.
For elements a... | def find_peak_elements(arr):
if not arr:
return []
if len(arr) == 1:
return [arr[0]]
peaks = []
n = len(arr)
# Check first element
if arr[0] > arr[1]:
peaks.append(arr[0])
# Check middle elements
for i in range(1, n - 1):
if arr[i] > arr[i-1] and arr[i]... |
Implement the following Python function. Return ONLY the function definition, no explanation.
def flatten_nested_list(nested_list):
"""
Recursively flattens a nested list of integers into a single, one-dimensional list.
The input `nested_list` can contain integers directly or other lists.
These inner ... | def flatten_nested_list(nested_list):
flat_list = []
for item in nested_list:
if isinstance(item, list):
flat_list.extend(flatten_nested_list(item))
else:
flat_list.append(item)
return flat_list |
Implement the following Python function. Return ONLY the function definition, no explanation.
def decode_run_length(encoded_string: str) -> str:
"""
Decodes a run-length encoded string. The encoding format is 'count_char', where 'count'
is a positive integer representing the number of times 'char' appears ... | def decode_run_length(encoded_string: str) -> str:
decoded_parts = []
current_number = []
for char in encoded_string:
if char.isdigit():
current_number.append(char)
else:
if current_number:
count = int("".join(current_number))
decoded_... |
Implement the following Python function. Return ONLY the function definition, no explanation.
def sort_by_frequency_and_value(numbers: list[int]) -> list[int]:
"""
Sorts a list of integers based on two criteria:
1. Primary: Frequency of occurrence in descending order. Numbers that appear more often come fi... | from collections import Counter
def sort_by_frequency_and_value(numbers: list[int]) -> list[int]:
"""
Sorts a list of integers based on two criteria:
1. Primary: Frequency of occurrence in descending order. Numbers that appear more often come first.
2. Secondary: Value in ascending order. If two number... |
Implement the following Python function. Return ONLY the function definition, no explanation.
def sum_of_divisors(n: int) -> int:
"""
Calculates the sum of all positive divisors of a given positive integer n,
including 1 and n itself.
For example:
sum_of_divisors(1) == 1 (divisors: 1)
sum_of_... | def sum_of_divisors(n: int) -> int:
if not isinstance(n, int) or n <= 0:
raise ValueError("Input must be a positive integer.")
if n == 1:
return 1
total_sum = 0
for i in range(1, int(n**0.5) + 1):
if n % i == 0:
total_sum += i
if i * i != n:
... |
Implement the following Python function. Return ONLY the function definition, no explanation.
def count_word_frequencies(text: str) -> dict[str, int]:
"""
Counts the frequency of each word in a given text. Words are case-insensitive and
punctuation marks (periods, commas, exclamation points, question marks... | def count_word_frequencies(text: str) -> dict[str, int]:
"""
Counts the frequency of each word in a given text. Words are case-insensitive and
punctuation marks (periods, commas, exclamation points, question marks, semicolons,
colons) should be removed. The result should be a dictionary where keys are
... |
Implement the following Python function. Return ONLY the function definition, no explanation.
def rotate_matrix_clockwise(matrix):
"""
Rotates a 2D square matrix (list of lists) 90 degrees clockwise in-place.
The matrix is guaranteed to be square (N x N) and non-empty.
The elements can be of any t... | def rotate_matrix_clockwise(matrix):
n = len(matrix)
if n == 0 or n == 1:
return
# Transpose the matrix
for i in range(n):
for j in range(i, n):
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
# Reverse each row
for i in range(n):
matrix[i].reverse() |
Implement the following Python function. Return ONLY the function definition, no explanation.
def rotate_matrix_90_clockwise(matrix):
"""
Rotates a 2D square matrix 90 degrees clockwise in-place.
The function should modify the input matrix directly and not return a new one.
A square matrix means it ha... | def rotate_matrix_90_clockwise(matrix):
n = len(matrix)
if n == 0:
return
# Transpose the matrix
for i in range(n):
for j in range(i, n):
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
# Reverse each row
for i in range(n):
matrix[i].reverse() |
Implement the following Python function. Return ONLY the function definition, no explanation.
def find_median_sorted_arrays(nums1: list[int], nums2: list[int]) -> float:
"""
Given two sorted arrays nums1 and nums2 of size m and n respectively,
return the median of the two sorted arrays.
The overall ru... | def find_median_sorted_arrays(nums1: list[int], nums2: list[int]) -> float:
m, n = len(nums1), len(nums2)
if m > n:
nums1, nums2, m, n = nums2, nums1, n, m
# The total length of the merged array
total_len = m + n
# The target position for the left half's end element in the merged array
... |
Implement the following Python function. Return ONLY the function definition, no explanation.
def merge_overlapping_intervals(intervals):
"""
Merges a list of possibly overlapping intervals into a list of non-overlapping, sorted intervals.
Each interval is represented as a list or tuple of two integers: [... | def merge_overlapping_intervals(intervals):
if not intervals:
return []
# Sort intervals by their start times
intervals.sort(key=lambda x: x[0])
merged = []
for interval in intervals:
# If the merged list is empty or the current interval does not overlap with the last merged interv... |
Implement the following Python function. Return ONLY the function definition, no explanation.
def flatten_nested_list(nested_list):
"""
Recursively flattens a nested list of integers into a single, non-nested list of integers.
The input list can contain integers directly or other lists which may contain in... | def flatten_nested_list(nested_list):
flattened = []
for item in nested_list:
if isinstance(item, list):
flattened.extend(flatten_nested_list(item))
else:
flattened.append(item)
return flattened |
Implement the following Python function. Return ONLY the function definition, no explanation.
def merge_overlapping_intervals(intervals: list[tuple[int, int]]) -> list[tuple[int, int]]:
"""
Merges a list of possibly overlapping intervals into a list of non-overlapping intervals.
Each interval is represent... | def merge_overlapping_intervals(intervals: list[tuple[int, int]]) -> list[tuple[int, int]]:
if not intervals:
return []
# Sort intervals by their start times
intervals.sort(key=lambda x: x[0])
merged = []
current_start, current_end = intervals[0]
for i in range(1, len(intervals)):
... |
Implement the following Python function. Return ONLY the function definition, no explanation.
def min_cost_climbing_stairs(cost: list[int]) -> int:
"""
You are given an integer array `cost` where `cost[i]` is the cost of `i`-th step on a staircase.
Once you pay the cost, you can either climb one or two ste... | def min_cost_climbing_stairs(cost: list[int]) -> int:
n = len(cost)
if n == 0:
return 0
if n == 1:
return cost[0]
# dp[i] will store the minimum cost to reach step i
# The 'top' is considered one step beyond the last element of cost
# So, we need to find the min cost to reach in... |
Implement the following Python function. Return ONLY the function definition, no explanation.
def find_peak_elements(nums):
"""
Given a 0-indexed integer array 'nums', find all the 'peak elements' and return their indices
in a list, sorted in ascending order. A peak element is an element that is strictly g... | def find_peak_elements(nums):
peak_indices = []
n = len(nums)
if n == 1:
return [0]
for i in range(n):
is_peak = False
if i == 0: # First element
if nums[i] > nums[i+1]:
is_peak = True
elif i == n - 1: # Last element
if nums[i] ... |
Implement the following Python function. Return ONLY the function definition, no explanation.
def flatten_nested_list(nested_list):
"""
Recursively flattens a nested list of integers into a single, non-nested list.
The input `nested_list` can contain integers or other lists (which themselves
can c... | def flatten_nested_list(nested_list):
flattened = []
for item in nested_list:
if isinstance(item, list):
flattened.extend(flatten_nested_list(item))
else:
flattened.append(item)
return flattened |
Implement the following Python function. Return ONLY the function definition, no explanation.
def parse_key_value_string(data_string: str) -> dict:
"""
Parses a string containing key-value pairs separated by semicolons,
where each key and value are separated by an equals sign.
Keys and values can con... | def parse_key_value_string(data_string: str) -> dict:
"""
Parses a string containing key-value pairs separated by semicolons,
where each key and value are separated by an equals sign.
Keys and values can contain spaces. Leading/trailing whitespace around
keys and values should be stripped. Empty ... |
Implement the following Python function. Return ONLY the function definition, no explanation.
def find_median_sorted_arrays(nums1: list[int], nums2: list[int]) -> float:
"""
Given two sorted arrays nums1 and nums2 of size m and n respectively,
return the median of the two sorted arrays.
The overall ru... | def find_median_sorted_arrays(nums1: list[int], nums2: list[int]) -> float:
m, n = len(nums1), len(nums2)
if m > n:
nums1, nums2, m, n = nums2, nums1, n, m
imin, imax, half_len = 0, m, (m + n + 1) // 2
while imin <= imax:
i = (imin + imax) // 2
j = half_len - i
if i < ... |
Implement the following Python function. Return ONLY the function definition, no explanation.
def rotate_matrix_90_clockwise(matrix):
"""
Rotates a 2D square matrix 90 degrees clockwise in-place.
The matrix is represented as a list of lists. For an N x N matrix,
the rotation should transform matrix[ro... | def rotate_matrix_90_clockwise(matrix):
n = len(matrix)
if n == 0 or n == 1:
return
# Transpose the matrix
for i in range(n):
for j in range(i, n):
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
# Reverse each row
for i in range(n):
matrix[i].revers... |
Implement the following Python function. Return ONLY the function definition, no explanation.
def find_median_sorted_arrays(nums1: list[int], nums2: list[int]) -> float:
"""
Given two sorted arrays nums1 and nums2 of size m and n respectively,
return the median of the two sorted arrays.
The overall ru... | def find_median_sorted_arrays(nums1: list[int], nums2: list[int]) -> float:
m, n = len(nums1), len(nums2)
if m > n:
nums1, nums2, m, n = nums2, nums1, n, m
imin, imax, half_len = 0, m, (m + n + 1) // 2
while imin <= imax:
i = (imin + imax) // 2
j = half_len - i
if i < ... |
Implement the following Python function. Return ONLY the function definition, no explanation.
def merge_overlapping_intervals(intervals):
"""
Merges a list of possibly overlapping intervals into a list of non-overlapping intervals.
Each interval is represented as a list or tuple of two integers: [start, e... | def merge_overlapping_intervals(intervals):
if not intervals:
return []
# Sort intervals by their start times
intervals.sort(key=lambda x: x[0])
merged = []
current_start, current_end = intervals[0]
for i in range(1, len(intervals)):
next_start, next_end = intervals[i]
... |
Implement the following Python function. Return ONLY the function definition, no explanation.
def min_cost_climbing_stairs(cost: list[int]) -> int:
"""
You are given an integer array `cost` where `cost[i]` is the cost of `i`-th step
on a staircase. Once you pay the cost, you can either climb one or two ste... | def min_cost_climbing_stairs(cost: list[int]) -> int:
n = len(cost)
if n == 0:
return 0
if n == 1:
return cost[0]
dp = [0] * n
# Base cases
dp[0] = cost[0]
dp[1] = cost[1]
for i in range(2, n):
dp[i] = cost[i] + min(dp[i-1], dp[i-2])
# The top of the floor... |
Implement the following Python function. Return ONLY the function definition, no explanation.
def process_job_queue(jobs: list[tuple[str, int]], max_workers: int) -> list[tuple[str, int, int]]:
"""
Simulates processing a list of jobs with a limited number of workers.
Jobs are processed in the order they a... | import heapq
def process_job_queue(jobs: list[tuple[str, int]], max_workers: int) -> list[tuple[str, int, int]]:
"""
Simulates processing a list of jobs with a limited number of workers.
Jobs are processed in the order they appear in the input list. Each job
is a tuple (job_id, processing_time).
... |
Implement the following Python function. Return ONLY the function definition, no explanation.
def process_job_queue(job_priorities: list[int], max_concurrent_jobs: int) -> list[int]:
"""
Simulates processing a job queue where jobs are processed in order of their priority.
You are given a list of integ... | import heapq
def process_job_queue(job_priorities: list[int], max_concurrent_jobs: int) -> list[int]:
if not job_priorities:
return []
# Use a min-heap to simulate a max-priority queue.
# We store tuples: (-priority, original_index, job_priority)
# The negative priority ensures that the highes... |
Implement the following Python function. Return ONLY the function definition, no explanation.
def rot13_cipher(text: str) -> str:
"""
Applies the ROT13 substitution cipher to the input string.
ROT13 ("rotate by 13 places") is a simple letter substitution cipher that
replaces a letter with the 13... | def rot13_cipher(text: str) -> str:
result = []
for char in text:
if 'a' <= char <= 'z':
rotated_char = chr(((ord(char) - ord('a') + 13) % 26) + ord('a'))
result.append(rotated_char)
elif 'A' <= char <= 'Z':
rotated_char = chr(((ord(char) - ord('A') + 13) % 26... |
Implement the following Python function. Return ONLY the function definition, no explanation.
def flatten_nested_list(nested_list):
"""
Recursively flattens a nested list of integers into a single, flat list of integers.
The input list can contain integers or other lists, which in turn can contain integers... | def flatten_nested_list(nested_list):
flattened = []
for item in nested_list:
if isinstance(item, list):
flattened.extend(flatten_nested_list(item))
else:
flattened.append(item)
return flattened |
Implement the following Python function. Return ONLY the function definition, no explanation.
def rotate_matrix_90_degrees_clockwise(matrix):
"""
Rotates a given square matrix 90 degrees clockwise in-place.
The function modifies the input matrix directly and does not return a new one.
For example:
... | def rotate_matrix_90_degrees_clockwise(matrix):
n = len(matrix)
if n == 0 or n == 1:
return
# Transpose the matrix
for i in range(n):
for j in range(i, n):
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
# Reverse each row
for i in range(n):
matrix[i... |
Implement the following Python function. Return ONLY the function definition, no explanation.
def find_peak_elements(arr):
"""
Finds all 'peak' elements in a given list of numbers.
A peak element is defined as an element that is strictly greater than its neighbors.
For elements at the beginning or end... | def find_peak_elements(arr):
if not arr:
return []
if len(arr) == 1:
return [arr[0]]
peaks = []
n = len(arr)
# Check the first element
if arr[0] > arr[1]:
peaks.append(arr[0])
# Check intermediate elements
for i in range(1, n - 1):
if arr[i] > arr[i-1] ... |
Implement the following Python function. Return ONLY the function definition, no explanation.
def rotate_matrix_clockwise(matrix):
"""
Rotates a 2D square matrix 90 degrees clockwise.
The matrix is represented as a list of lists. Each inner list represents a row.
The matrix is guaranteed to be square ... | def rotate_matrix_clockwise(matrix):
n = len(matrix)
if n == 0:
return []
rotated = [[0] * n for _ in range(n)]
for i in range(n):
for j in range(n):
rotated[j][n - 1 - i] = matrix[i][j]
return rotated |
Implement the following Python function. Return ONLY the function definition, no explanation.
def flatten_nested_list(nested_list):
"""
Recursively flattens a nested list of integers into a single, non-nested list of integers.
The input `nested_list` can contain integers or other lists (which in turn ... | def flatten_nested_list(nested_list):
flat_list = []
for item in nested_list:
if isinstance(item, list):
flat_list.extend(flatten_nested_list(item))
else:
flat_list.append(item)
return flat_list |
Implement the following Python function. Return ONLY the function definition, no explanation.
def find_peak_elements(nums):
"""
Given a 0-indexed integer array `nums`, find all peak elements and return a list of their indices.
A peak element is an element that is strictly greater than its neighbors.
... | def find_peak_elements(nums):
if len(nums) < 2:
return []
peak_indices = []
n = len(nums)
# Check first element
if n > 1 and nums[0] > nums[1]:
peak_indices.append(0)
# Check middle elements
for i in range(1, n - 1):
if nums[i] > nums[i - 1] and nums[i] > nums[i + ... |
Implement the following Python function. Return ONLY the function definition, no explanation.
def find_peak_elements(nums):
"""
Finds all 'peak elements' in a list of numbers. A peak element is an element
that is strictly greater than its neighbors. For elements at the ends of the list,
we only conside... | def find_peak_elements(nums):
if not nums:
return []
if len(nums) == 1:
return [nums[0]]
peaks = []
n = len(nums)
# Check first element
if nums[0] > nums[1]:
peaks.append(nums[0])
# Check middle elements
for i in range(1, n - 1):
if nums[i] > nums[i - 1... |
Implement the following Python function. Return ONLY the function definition, no explanation.
def sort_and_find_median(numbers: list[int]) -> float:
"""
Sorts a list of integers in ascending order and returns its median.
The median of a finite list of numbers is the 'middle' number when those numbers
... | def sort_and_find_median(numbers: list[int]) -> float:
"""
Sorts a list of integers in ascending order and returns its median.
The median of a finite list of numbers is the 'middle' number when those numbers
are listed in order. If the list has an odd number of elements, the median is the
middl... |
Implement the following Python function. Return ONLY the function definition, no explanation.
def find_peak_elements(nums):
"""
Finds all 'peak elements' in a list of integers. A peak element is an element
that is strictly greater than its neighbors. For elements at the boundaries,
only one neighbor ne... | def find_peak_elements(nums):
"""
Finds all 'peak elements' in a list of integers. A peak element is an element
that is strictly greater than its neighbors. For elements at the boundaries,
only one neighbor needs to be considered. If the list is empty, return an empty list.
If the list has only one ... |
Implement the following Python function. Return ONLY the function definition, no explanation.
def max_subarray_sum_circular(nums: list[int]) -> int:
"""
Given a circular integer array 'nums' of length n, return the maximum possible sum of a non-empty subarray of 'nums'.
A circular array means the end of t... | def max_subarray_sum_circular(nums: list[int]) -> int:
n = len(nums)
if n == 0:
return 0
if n == 1:
return nums[0]
# Kadane's algorithm for non-circular max subarray sum
current_max = nums[0]
global_max = nums[0]
current_min = nums[0]
global_min = nums[0]
total_sum =... |
Implement the following Python function. Return ONLY the function definition, no explanation.
def process_job_queue(jobs, workers):
"""
Simulates processing jobs from a queue by a fixed number of workers.
Each job has a `start_time` and `duration`.
Workers become available at different times.
The... | import heapq
def process_job_queue(jobs, workers):
worker_availability = [(0, i) for i in range(workers)] # (available_time, worker_index)
heapq.heapify(worker_availability)
results = []
for job_index, job in enumerate(jobs):
job_start_time = job['start_time']
job_duration = job['dur... |
Implement the following Python function. Return ONLY the function definition, no explanation.
def merge_overlapping_intervals(intervals):
"""
Merges a list of possibly overlapping intervals into a list of non-overlapping intervals.
Each interval is represented as a list or tuple of two integers: [start, e... | def merge_overlapping_intervals(intervals):
if not intervals:
return []
# Sort intervals by their start times
intervals.sort(key=lambda x: x[0])
merged = []
for current_start, current_end in intervals:
if not merged or current_start > merged[-1][1]:
# If the merged list... |
Implement the following Python function. Return ONLY the function definition, no explanation.
def parse_key_value_string(data_string: str) -> dict:
"""
Parses a string containing key-value pairs separated by semicolons,
where each key and value are separated by an equals sign.
Keys and values can con... | def parse_key_value_string(data_string: str) -> dict:
"""
Parses a string containing key-value pairs separated by semicolons,
where each key and value are separated by an equals sign.
Keys and values can contain spaces. Keys are case-sensitive.
Empty keys or values are allowed but will be represen... |
Implement the following Python function. Return ONLY the function definition, no explanation.
def sum_of_divisors(n: int) -> int:
"""
Calculates the sum of all positive divisors of a given positive integer n.
A divisor includes 1 and n itself.
For example:
sum_of_divisors(1) == 1 (divisors: 1)
... | def sum_of_divisors(n: int) -> int:
if not isinstance(n, int) or n <= 0:
raise ValueError("Input n must be a positive integer.")
if n == 1:
return 1
total_sum = 0
for i in range(1, int(n**0.5) + 1):
if n % i == 0:
total_sum += i
if i * i != n:
... |
Implement the following Python function. Return ONLY the function definition, no explanation.
def flatten_nested_list(nested_list):
"""
Recursively flattens a nested list of integers into a single, non-nested list.
The input `nested_list` can contain integers or other lists.
Each inner list can al... | def flatten_nested_list(nested_list):
flattened = []
for item in nested_list:
if isinstance(item, list):
flattened.extend(flatten_nested_list(item))
else:
flattened.append(item)
return flattened |
Implement the following Python function. Return ONLY the function definition, no explanation.
def find_peak_elements(nums):
"""
Finds all 'peak elements' in a list of integers. A peak element is an element
that is strictly greater than its neighbors. For elements at the ends of the list,
only one neigh... | def find_peak_elements(nums):
"""
Finds all 'peak elements' in a list of integers. A peak element is an element
that is strictly greater than its neighbors. For elements at the ends of the list,
only one neighbor needs to be considered. If an element has no neighbors (list of size 1),
it is consider... |
Implement the following Python function. Return ONLY the function definition, no explanation.
def rotate_matrix_90_clockwise(matrix):
"""
Rotates a 2D square matrix 90 degrees clockwise in-place.
The matrix is represented as a list of lists. The rotation should modify
the input matrix directly (in-pla... | def rotate_matrix_90_clockwise(matrix):
n = len(matrix)
# Transpose the matrix
for i in range(n):
for j in range(i, n):
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
# Reverse each row
for i in range(n):
matrix[i].reverse()
return matrix |
Implement the following Python function. Return ONLY the function definition, no explanation.
def decode_run_length_string(encoded_string: str) -> str:
"""
Decodes a run-length encoded string. The encoded string consists of alternating
numbers (representing the count) and characters. For example, '3a2b1c' ... | def decode_run_length_string(encoded_string: str) -> str:
decoded_parts = []
i = 0
n = len(encoded_string)
while i < n:
count_str = ''
while i < n and encoded_string[i].isdigit():
count_str += encoded_string[i]
i += 1
if count_str:
cou... |
Implement the following Python function. Return ONLY the function definition, no explanation.
def rotate_matrix_90_clockwise(matrix):
"""
Rotates a given square matrix 90 degrees clockwise in-place.
The matrix is represented as a list of lists. For example:
[[1, 2, 3],
[4, 5, 6],
[7, 8, ... | def rotate_matrix_90_clockwise(matrix):
n = len(matrix)
# Transpose the matrix
for i in range(n):
for j in range(i, n):
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
# Reverse each row
for i in range(n):
matrix[i].reverse() |
Implement the following Python function. Return ONLY the function definition, no explanation.
def parse_key_value_string(data_string: str) -> dict:
"""
Parses a string containing key-value pairs separated by newlines,
where each key-value pair is separated by the first occurrence of an equals sign '='.
... | def parse_key_value_string(data_string: str) -> dict:
result = {}
lines = data_string.split('\n')
for line in lines:
line = line.strip()
if not line or '=' not in line:
continue
parts = line.split('=', 1)
if len(parts) == 2:
key = parts[0].strip()
... |
Implement the following Python function. Return ONLY the function definition, no explanation.
def find_median_sorted_arrays(nums1: list[int], nums2: list[int]) -> float:
"""
Given two sorted arrays nums1 and nums2 of size m and n respectively,
return the median of the two sorted arrays.
The overall ru... | def find_median_sorted_arrays(nums1: list[int], nums2: list[int]) -> float:
m, n = len(nums1), len(nums2)
# Ensure nums1 is the shorter array for simplicity in binary search
if m > n:
nums1, nums2 = nums2, nums1
m, n = n, m
low, high = 0, m
half_len = (m + n + 1) // 2
while lo... |
Implement the following Python function. Return ONLY the function definition, no explanation.
def flatten_nested_list(nested_list):
"""Flattens a list that can contain other lists as elements, recursively.
The function should take a nested list and return a single, flat list
containing all non-list elemen... | def flatten_nested_list(nested_list):
flat_list = []
for item in nested_list:
if isinstance(item, list):
flat_list.extend(flatten_nested_list(item))
else:
flat_list.append(item)
return flat_list |
Implement the following Python function. Return ONLY the function definition, no explanation.
def flatten_nested_list(nested_list):
"""
Recursively flattens a nested list of integers into a single, non-nested list of integers.
The order of elements should be preserved.
For example:
flatten_nested_... | def flatten_nested_list(nested_list):
"""
Recursively flattens a nested list of integers into a single, non-nested list of integers.
The order of elements should be preserved.
For example:
flatten_nested_list([1, [2, 3], 4]) == [1, 2, 3, 4]
flatten_nested_list([1, [2, [3, 4]], 5]) == [1, 2, 3, ... |
Implement the following Python function. Return ONLY the function definition, no explanation.
def merge_overlapping_intervals(intervals):
"""
Merges a list of possibly overlapping intervals into a list of non-overlapping intervals.
Each interval is represented as a list or tuple of two integers: [start, e... | def merge_overlapping_intervals(intervals):
if not intervals:
return []
# Sort intervals by their start times. If start times are equal, sort by end times.
intervals.sort(key=lambda x: (x[0], x[1]))
merged = []
current_start, current_end = intervals[0][0], intervals[0][1]
for i in ran... |
Implement the following Python function. Return ONLY the function definition, no explanation.
def min_cost_climbing_stairs(cost: list[int]) -> int:
"""
You are given an integer array `cost` where `cost[i]` is the cost of `i`-th step on a staircase.
Once you pay the cost, you can either climb one or two ste... | def min_cost_climbing_stairs(cost: list[int]) -> int:
n = len(cost)
if n == 2:
return min(cost[0], cost[1])
# dp[i] will store the minimum cost to reach step i
dp = [0] * n
# Base cases
dp[0] = cost[0]
dp[1] = cost[1]
for i in range(2, n):
dp[i] = cost[i] + min(dp[i-1... |
Implement the following Python function. Return ONLY the function definition, no explanation.
def flatten_nested_list(nested_list):
"""
Recursively flattens a nested list of integers into a single, flat list of integers.
The input list can contain integers or other lists, which in turn can contain integers... | def flatten_nested_list(nested_list):
flattened = []
for item in nested_list:
if isinstance(item, list):
flattened.extend(flatten_nested_list(item))
else:
flattened.append(item)
return flattened |
Implement the following Python function. Return ONLY the function definition, no explanation.
def merge_overlapping_intervals(intervals):
"""
Merges a list of possibly overlapping intervals into a list of non-overlapping intervals.
Each interval is represented as a list or tuple of two integers: [start, e... | def merge_overlapping_intervals(intervals):
if not intervals:
return []
# Sort intervals by their start times
intervals.sort(key=lambda x: x[0])
merged = []
for current_start, current_end in intervals:
if not merged or current_start > merged[-1][1]:
# If the merged list... |
Implement the following Python function. Return ONLY the function definition, no explanation.
def merge_overlapping_intervals(intervals):
"""
Merges a list of possibly overlapping intervals into a list of non-overlapping intervals.
Each interval is represented as a list or tuple of two integers: [start, e... | def merge_overlapping_intervals(intervals):
if not intervals:
return []
# Sort intervals by their start times
intervals.sort(key=lambda x: x[0])
merged = []
current_start, current_end = intervals[0]
for i in range(1, len(intervals)):
next_start, next_end = intervals[i]
... |
Implement the following Python function. Return ONLY the function definition, no explanation.
def is_prime(n: int) -> bool:
"""
Check if a given positive integer n is a prime number.
A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself.
Examples:
... | def is_prime(n: int) -> bool:
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
return True |
Implement the following Python function. Return ONLY the function definition, no explanation.
def sum_of_divisors(n: int) -> int:
"""
Calculates the sum of all positive divisors of a given positive integer n.
A divisor of n is an integer that divides n without leaving a remainder.
For example, the divi... | def sum_of_divisors(n: int) -> int:
if n == 1:
return 1
total_sum = 0
for i in range(1, int(n**0.5) + 1):
if n % i == 0:
total_sum += i
if i * i != n:
total_sum += n // i
return total_sum |
Implement the following Python function. Return ONLY the function definition, no explanation.
def flatten_nested_list(nested_list):
"""Flatten a potentially deeply nested list of integers into a single flat list of integers.
The input `nested_list` can contain integers or other lists. These inner lists can al... | def flatten_nested_list(nested_list):
flat_list = []
for item in nested_list:
if isinstance(item, list):
flat_list.extend(flatten_nested_list(item))
else:
flat_list.append(item)
return flat_list |
Implement the following Python function. Return ONLY the function definition, no explanation.
def flatten_nested_list(nested_list):
"""
Recursively flattens a nested list of integers into a single, non-nested list of integers.
The order of elements should be preserved.
For example:
flatten_nested_... | def flatten_nested_list(nested_list):
result = []
for item in nested_list:
if isinstance(item, list):
result.extend(flatten_nested_list(item))
else:
result.append(item)
return result |
Implement the following Python function. Return ONLY the function definition, no explanation.
def rotate_matrix_90_clockwise(matrix):
"""
Rotates a given square matrix 90 degrees clockwise in-place.
The matrix is represented as a list of lists. The input matrix will always be square
(N x N) and will c... | def rotate_matrix_90_clockwise(matrix):
n = len(matrix)
if n == 0 or n == 1:
return
# Transpose the matrix
for i in range(n):
for j in range(i, n):
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
# Reverse each row
for i in range(n):
matrix[i].revers... |
Implement the following Python function. Return ONLY the function definition, no explanation.
def most_frequent_words(text: str, k: int) -> list[str]:
"""
Given a string of text and an integer k, return a list of the k most frequent words.
Words should be case-insensitive, and the returned list should... | import re
from collections import Counter
def most_frequent_words(text: str, k: int) -> list[str]:
if not text:
return []
# Remove punctuation and convert to lowercase
cleaned_text = re.sub(r'[^a-zA-Z0-9\s]', '', text).lower()
words = cleaned_text.split()
if not words:
return []
... |
Implement the following Python function. Return ONLY the function definition, no explanation.
def find_median_sorted_arrays(nums1: list[int], nums2: list[int]) -> float:
"""
Given two sorted arrays nums1 and nums2 of size m and n respectively,
return the median of the two sorted arrays.
The overall ru... | def find_median_sorted_arrays(nums1: list[int], nums2: list[int]) -> float:
m, n = len(nums1), len(nums2)
if m > n:
nums1, nums2, m, n = nums2, nums1, n, m
low, high = 0, m
total_half = (m + n + 1) // 2
while low <= high:
partitionX = (low + high) // 2
partitionY = total_ha... |
Implement the following Python function. Return ONLY the function definition, no explanation.
def is_prime_factorable(n, prime_factors):
"""
Checks if a positive integer 'n' can be formed by multiplying only the given 'prime_factors'.
The prime_factors list contains distinct prime numbers. 'n' must be grea... | def is_prime_factorable(n, prime_factors):
if n == 1:
return True
if n <= 0:
raise ValueError("n must be a positive integer.")
temp_n = n
for p in sorted(prime_factors):
while temp_n % p == 0:
temp_n //= p
return temp_n == 1 |
Implement the following Python function. Return ONLY the function definition, no explanation.
def flatten_nested_list(nested_list):
"""
Recursively flattens a nested list of integers into a single, flat list of integers.
The input list can contain integers directly or other lists of integers (which can als... | def flatten_nested_list(nested_list):
flat_list = []
for item in nested_list:
if isinstance(item, list):
flat_list.extend(flatten_nested_list(item))
else:
flat_list.append(item)
return flat_list |
Implement the following Python function. Return ONLY the function definition, no explanation.
def reverse_words_preserve_spaces(text: str) -> str:
"""
Reverses the order of words in a string while preserving the exact position
and sequence of all whitespace characters.
A 'word' is defined as a contigu... | def reverse_words_preserve_spaces(text: str) -> str:
if not text:
return ""
words = []
spaces = []
current_word = []
current_space = []
for char in text:
if char.isspace():
if current_word:
words.append("".join(current_word))
current_... |
Implement the following Python function. Return ONLY the function definition, no explanation.
def find_peak_elements(arr):
"""
Finds all 'peak' elements in a given list of numbers.
A peak element is defined as an element that is strictly greater
than its immediate neighbors. For elements at the bounda... | def find_peak_elements(arr):
"""
Finds all 'peak' elements in a given list of numbers.
A peak element is defined as an element that is strictly greater
than its immediate neighbors. For elements at the boundaries (first
or last), they are considered a peak if they are strictly greater
than thei... |
Implement the following Python function. Return ONLY the function definition, no explanation.
def sum_of_divisors(n: int) -> int:
"""Calculates the sum of all positive divisors of a given positive integer n.
A divisor of n is an integer that divides n without leaving a remainder.
For example, the divisors ... | def sum_of_divisors(n: int) -> int:
if not isinstance(n, int) or n <= 0:
raise ValueError("n must be a positive integer.")
if n == 1:
return 1
total_sum = 0
for i in range(1, int(n**0.5) + 1):
if n % i == 0:
total_sum += i
if i * i != n:
... |
Implement the following Python function. Return ONLY the function definition, no explanation.
def process_queue_with_priority(tasks):
"""
Processes a list of tasks, simulating a queue where tasks with a higher priority (lower integer value)
are processed before tasks with lower priority. If two tasks have ... | import heapq
def process_queue_with_priority(tasks):
processed_order = []
# Use a min-heap to store tasks. Each item in the heap will be:
# (priority, original_index, task_id, duration)
# The original_index is crucial for maintaining FIFO order for same-priority tasks.
priority_queue = []
for ... |
Implement the following Python function. Return ONLY the function definition, no explanation.
def rotate_matrix_90_clockwise(matrix):
"""
Rotates a 2D square matrix 90 degrees clockwise in-place.
The matrix is represented as a list of lists. The rotation should modify
the input matrix directly (in-pla... | def rotate_matrix_90_clockwise(matrix):
n = len(matrix)
if n == 0 or n == 1:
return
# Transpose the matrix
for i in range(n):
for j in range(i, n):
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
# Reverse each row
for i in range(n):
matrix[i].revers... |
Implement the following Python function. Return ONLY the function definition, no explanation.
def parse_key_value_string(data_string: str) -> dict:
"""
Parses a string containing key-value pairs separated by semicolons,
where each key and value are separated by an equals sign.
Keys and values can con... | def parse_key_value_string(data_string: str) -> dict:
result = {}
if not data_string.strip():
return result
pairs = data_string.split(';')
for pair in pairs:
if '=' in pair:
key, value = pair.split('=', 1)
key = key.strip()
value = value.strip()
... |
Implement the following Python function. Return ONLY the function definition, no explanation.
def rotate_matrix_90_degrees(matrix):
"""
Rotates a 2D square matrix (list of lists) 90 degrees clockwise in-place.
The matrix is guaranteed to be square (N x N) and non-empty.
The elements can be any type.
... | def rotate_matrix_90_degrees(matrix):
n = len(matrix)
# Transpose the matrix
for i in range(n):
for j in range(i, n):
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
# Reverse each row
for i in range(n):
matrix[i].reverse() |
Implement the following Python function. Return ONLY the function definition, no explanation.
def sort_and_find_median(numbers: list[int]) -> int:
"""
Sorts a list of integers in ascending order and returns the median value.
If the list has an even number of elements, the median is defined as
the avera... | def sort_and_find_median(numbers: list[int]) -> int:
if not numbers:
raise ValueError("Input list cannot be empty.")
sorted_numbers = sorted(numbers)
n = len(sorted_numbers)
if n % 2 == 1:
# Odd number of elements, return the middle element
return sorted_numbers[n // 2]
els... |
Implement the following Python function. Return ONLY the function definition, no explanation.
def merge_overlapping_intervals(intervals):
"""
Merges a list of possibly overlapping intervals into a list of non-overlapping intervals.
Each interval is represented as a list or tuple of two integers: [start, e... | def merge_overlapping_intervals(intervals):
if not intervals:
return []
# Sort intervals by their start times
intervals.sort(key=lambda x: x[0])
merged = []
for interval in intervals:
# If the merged list is empty or the current interval does not overlap
# with the previous... |
Implement the following Python function. Return ONLY the function definition, no explanation.
def sum_of_divisors(n: int) -> int:
"""
Calculate the sum of all positive divisors of a given positive integer n.
A divisor of n is an integer that divides n without leaving a remainder.
For example:
- If... | def sum_of_divisors(n: int) -> int:
"""
Calculate the sum of all positive divisors of a given positive integer n.
A divisor of n is an integer that divides n without leaving a remainder.
For example:
- If n = 1, divisors are {1}, sum = 1.
- If n = 6, divisors are {1, 2, 3, 6}, sum = 1 + 2 + 3 +... |
Implement the following Python function. Return ONLY the function definition, no explanation.
def merge_overlapping_intervals(intervals):
"""
Merges a list of possibly overlapping intervals into a list of non-overlapping, sorted intervals.
Each interval is represented as a list or tuple of two integers: [... | def merge_overlapping_intervals(intervals):
if not intervals:
return []
# Sort the intervals by their start times
intervals.sort(key=lambda x: x[0])
merged = []
for interval in intervals:
# If the merged list is empty or the current interval does not overlap
# with the last... |
Implement the following Python function. Return ONLY the function definition, no explanation.
def sort_and_find_median_kth(data: list[int], k: int) -> int:
"""
Given a list of integers `data` and an integer `k`,
first sort the list in ascending order, then return the k-th smallest element.
If `k` is 1,... | def sort_and_find_median_kth(data: list[int], k: int) -> int:
"""
Given a list of integers `data` and an integer `k`,
first sort the list in ascending order, then return the k-th smallest element.
If `k` is 1, return the smallest element. If `k` is len(data), return the largest.
The list `data` is g... |
Implement the following Python function. Return ONLY the function definition, no explanation.
def flatten_nested_list(nested_list):
"""
Recursively flattens a nested list of integers into a single, non-nested list of integers.
The order of elements should be preserved.
For example:
flatten_nested_... | def flatten_nested_list(nested_list):
flat_list = []
for item in nested_list:
if isinstance(item, list):
flat_list.extend(flatten_nested_list(item))
else:
flat_list.append(item)
return flat_list |
Implement the following Python function. Return ONLY the function definition, no explanation.
def find_peak_elements(nums: list[int]) -> list[int]:
"""
A peak element is an element that is strictly greater than its neighbors.
Given an input list 'nums' of integers, return a list of all peak elements found ... | def find_peak_elements(nums: list[int]) -> list[int]:
peaks = []
n = len(nums)
if n == 0:
return []
if n == 1:
return [nums[0]]
for i in range(n):
is_peak = False
if i == 0: # First element
if nums[i] > nums[i+1]:
is_peak = True
... |
Implement the following Python function. Return ONLY the function definition, no explanation.
def sort_by_frequency(items: list) -> list:
"""
Sorts a list of items based on their frequency in descending order.
If two items have the same frequency, their original relative order should be preserved.
The... | from collections import Counter
def sort_by_frequency(items: list) -> list:
"""
Sorts a list of items based on their frequency in descending order.
If two items have the same frequency, their original relative order should be preserved.
The function should return a new list with items sorted as descri... |
Implement the following Python function. Return ONLY the function definition, no explanation.
def find_kth_smallest_in_merged_sorted_lists(list1: list[int], list2: list[int], k: int) -> int:
"""
Given two sorted lists of integers, `list1` and `list2`, and an integer `k`,
find the k-th smallest element in t... | def find_kth_smallest_in_merged_sorted_lists(list1: list[int], list2: list[int], k: int) -> int:
p1, p2 = 0, 0
current_val = 0
while k > 0:
if p1 < len(list1) and (p2 >= len(list2) or list1[p1] <= list2[p2]):
current_val = list1[p1]
p1 += 1
elif p2 < len(list2) and (... |
Implement the following Python function. Return ONLY the function definition, no explanation.
def reverse_words_preserve_spaces(text: str) -> str:
"""
Reverses the order of words in a string while preserving the exact original spacing
between words. Leading, trailing, and multiple internal spaces should re... | def reverse_words_preserve_spaces(text: str) -> str:
if not text:
return ""
parts = []
current_part = []
is_space = text[0].isspace()
for char in text:
if char.isspace() == is_space:
current_part.append(char)
else:
parts.append("".join(current_part))... |
Implement the following Python function. Return ONLY the function definition, no explanation.
def decode_run_length(encoded_string: str) -> str:
"""
Decodes a run-length encoded string. The encoding format is a sequence of
'count' followed by 'character'. 'count' is a digit or sequence of digits
repres... | def decode_run_length(encoded_string: str) -> str:
decoded_parts = []
i = 0
while i < len(encoded_string):
count_str = ""
while encoded_string[i].isdigit():
count_str += encoded_string[i]
i += 1
count = int(count_str)
char = encoded_string[i]
d... |
Implement the following Python function. Return ONLY the function definition, no explanation.
def flatten_nested_list(nested_list):
"""
Recursively flattens a nested list of integers into a single, non-nested list of integers.
The input `nested_list` can contain integers or other lists. These inner li... | def flatten_nested_list(nested_list):
flattened = []
for item in nested_list:
if isinstance(item, list):
flattened.extend(flatten_nested_list(item))
else:
flattened.append(item)
return flattened |
Implement the following Python function. Return ONLY the function definition, no explanation.
def count_common_elements(list_of_dictionaries: list[dict[str, list[str]]]) -> dict[str, int]:
"""
Counts the occurrences of common string elements across lists within dictionaries.
Given a list of dictionaries, ... | def count_common_elements(list_of_dictionaries: list[dict[str, list[str]]]) -> dict[str, int]:
all_elements_counts = {}
all_lists = []
# Collect all lists and count individual element occurrences
for d in list_of_dictionaries:
for key in d:
current_list = d[key]
all_list... |
Implement the following Python function. Return ONLY the function definition, no explanation.
def rotate_matrix_clockwise(matrix):
"""
Rotates a 2D square matrix clockwise by 90 degrees.
The rotation should be performed in-place if possible (by modifying the input list of lists),
but returning a new m... | def rotate_matrix_clockwise(matrix):
n = len(matrix)
if n == 0 or len(matrix[0]) == 0:
return []
rotated_matrix = [[0] * n for _ in range(n)]
for i in range(n):
for j in range(n):
rotated_matrix[j][n - 1 - i] = matrix[i][j]
return rotated_matrix |
Implement the following Python function. Return ONLY the function definition, no explanation.
def merge_overlapping_intervals(intervals):
"""
Merges a list of possibly overlapping intervals into a list of non-overlapping intervals.
Each interval is represented as a list or tuple of two integers: [start, e... | def merge_overlapping_intervals(intervals):
if not intervals:
return []
# Sort intervals by their start times
intervals.sort(key=lambda x: x[0])
merged = []
current_start, current_end = intervals[0]
for i in range(1, len(intervals)):
next_start, next_end = intervals[i]
... |
Implement the following Python function. Return ONLY the function definition, no explanation.
def parse_key_value_string(data_string: str) -> dict:
"""
Parses a string containing key-value pairs separated by newlines.
Each key-value pair is separated by the first occurrence of an equals sign ('=').
... | def parse_key_value_string(data_string: str) -> dict:
result = {}
lines = data_string.split('\n')
for line in lines:
if '=' in line:
parts = line.split('=', 1) # Split only on the first '='
key = parts[0].strip()
value = parts[1].strip()
if key:
... |
Implement the following Python function. Return ONLY the function definition, no explanation.
def sum_of_divisors(n: int) -> int:
"""
Calculates the sum of all positive divisors of a given positive integer n.
A divisor of n is an integer that divides n without leaving a remainder.
This includes 1 and n... | def sum_of_divisors(n: int) -> int:
if n < 1:
raise ValueError("Input must be a positive integer.")
total_sum = 0
for i in range(1, int(n**0.5) + 1):
if n % i == 0:
total_sum += i
if i * i != n:
total_sum += n // i
return total_sum |
Implement the following Python function. Return ONLY the function definition, no explanation.
def sum_of_divisors(n: int) -> int:
"""
Calculates the sum of all positive divisors of a given positive integer n.
A divisor of n is an integer that divides n without leaving a remainder.
For example, the divi... | def sum_of_divisors(n: int) -> int:
if not isinstance(n, int) or n <= 0:
raise ValueError("n must be a positive integer.")
if n == 1:
return 1
total_sum = 0
i = 1
while i * i <= n:
if n % i == 0:
total_sum += i
if i * i != n:
total_su... |
Implement the following Python function. Return ONLY the function definition, no explanation.
import collections
def process_job_queue(jobs_with_priorities):
"""
Processes a list of jobs with associated priorities using a priority queue logic.
Each job is represented as a tuple (job_id, priority), where ... | import collections
def process_job_queue(jobs_with_priorities):
"""
Processes a list of jobs with associated priorities using a priority queue logic.
Each job is represented as a tuple (job_id, priority), where job_id is a unique
string and priority is an integer. Higher priority numbers indicate high... |
Implement the following Python function. Return ONLY the function definition, no explanation.
def parse_key_value_string(data_string: str) -> dict:
"""
Parses a string containing key-value pairs separated by newlines.
Each key-value pair is separated by the first occurrence of an equals sign ('=').
... | def parse_key_value_string(data_string: str) -> dict:
result = {}
lines = data_string.split('\n')
for line in lines:
stripped_line = line.strip()
if not stripped_line:
continue
if '=' in stripped_line:
first_equals_index = stripped_line.find('=')
... |
Implement the following Python function. Return ONLY the function definition, no explanation.
def flatten_nested_list(nested_list):
"""
Recursively flattens a nested list of integers into a single, non-nested list of integers.
The order of elements in the flattened list should be the same as they appear
... | def flatten_nested_list(nested_list):
flattened = []
for item in nested_list:
if isinstance(item, list):
flattened.extend(flatten_nested_list(item))
else:
flattened.append(item)
return flattened |
OpenWorld · Coding Worlds (World-Time Compute)
A family of verified coding worlds — a function to implement plus a test-suite oracle — for the world-time-compute realism check: fine-tune on many worlds, generalize to held-out tasks (and HumanEval/MBPP).
Load it
from datasets import load_dataset
ds = load_dataset("Quome/openworld-coding") # sft train/test
# tasks = load_dataset("Quome/openworld-coding", "tasks") # all 219 verified tasks
A family of verified coding worlds — function-implementation tasks, each a world whose oracle is its test suite — for the world-time-compute realism check on a different use case than diagnosis (OpenWorld experiment E77; paper §"World-time compute").
What it is
Each task is a tiny verified-code world: a function to implement (prompt = signature +
docstring) and a set of assert-based unit tests that define correctness. A solution is
"right" iff it passes all tests — the cleanest possible oracle (this is the
HumanEval/MBPP setup). The transferable skill is coding; held-out tasks measure
generalization.
Provenance
Tasks are LLM-authored (Gemini 2.5 Flash) across 12 topics (strings, arrays, dicts,
math, recursion, sorting, parsing, matrices, intervals, stacks/queues, greedy, simple DP),
then verified in a sandboxed subprocess — the reference solution must pass its own tests
before the task is admitted (~58% of generated candidates passed verification and were
kept). This contrasts with the synthetic-parametric openworld-diagnosis family: here the
worlds are authored by a model (the "Claude-Code-style" realism check), and the oracle is
executable tests rather than a Bayes-optimal classifier.
Contents (JSONL)
| File | Rows | Schema |
|---|---|---|
tasks.jsonl |
219 | {name, topic, prompt, solution, tests[]} (all verified) |
sft_train.jsonl |
164 | {prompt, completion} — prompt = instruction + signature/docstring; completion = reference solution |
test_tasks.jsonl |
55 | {id, prompt, tests[], kind} — held-out tasks for pass@k |
Task-level (world-level) train/test split: the 55 test tasks are held out from fine-tuning.
How to use
Fine-tune on sft_train.jsonl; evaluate pass@1 / pass@k on test_tasks.jsonl (run the
model's code against each task's tests in a sandbox). For real-benchmark transfer, also
evaluate on HumanEval / MBPP (fetched by experiments/e77_gen.py's benchmark step;
adapters in experiments/e77_eval.py).
Reproduce
python experiments/e77_gen.py # author + verify tasks (needs GEMINI_API_KEY in .env)
python experiments/e77_data.py # split + SFT
Generation uses an LLM, so the exact task set is not bit-reproducible (unlike the seeded
diagnosis family); the committed tasks.jsonl is the canonical set used in E77.
Results (E77, paper §world-time compute)
experiments/results/e77_coding.json. Headline: world-time compute helps in-domain
pass@k at every model size (e.g. 7B pass@5 0.84→0.95) and transfers positively to
HumanEval at pass@5 (7B 0.866→0.909) from just 164 worlds — though it hurts greedy
pass@1 on HumanEval. Consistent with E76's world-count law (more worlds → more gain), 164
is below the threshold where transfer becomes strong.
License
Apache 2.0 (same as the OpenWorld repository). Tasks/tests are LLM-generated; treated as synthetic.
From the OpenWorld project
This dataset is produced by OpenWorld — a framework for verified symbolic world models, where a world's dynamics are explicit, auditable Python code (no training, no GPU). "World-time compute" is the idea that traversing many verified worlds of a domain and fine-tuning on that experience makes a model generalize to unseen worlds from fewer real examples.
- 💻 Code, experiments & paper: https://github.com/quome-cloud/openworld
Citation
@software{openworld_coding_2026,
title = {OpenWorld · Coding Worlds (World-Time Compute)},
author = {Schwoebel, Jim},
year = {2026},
url = {https://github.com/quome-cloud/openworld},
note = {Hugging Face dataset: Quome/openworld-coding}
}
- Downloads last month
- 3