version stringclasses 1
value | style stringclasses 2
values | subset stringclasses 12
values | question_id stringlengths 9 23 | question stringlengths 27 8.13k | solution stringlengths 99 5.97k | test stringlengths 105 4.45k | test_info listlengths 0 13 | gpt_pass_sequence listlengths 1 10 | gpt_pass_trial_num int64 1 10 | gpt_difficulty stringclasses 3
values | gpt_pass_percentage float64 0.1 1 | trials dict | chosen_trial stringclasses 10
values | metadata dict | benchmark_similarity float64 0.16 0.93 | benchmark_instruction stringclasses 1
value | benchmark_task_id stringclasses 1
value | filter_reason stringclasses 1
value | base_id stringlengths 7 21 | variant stringclasses 2
values | top_function_names listlengths 2 13 | n_top_functions int64 2 13 | helper_call_edges listlengths 1 16 | n_helper_call_edges int64 1 16 | harness_functions listlengths 0 3 | structural_wrapper bool 1
class | class_names listlengths 0 5 | has_class bool 2
classes | test_kind stringclasses 1
value | test_has_solution_import bool 2
classes | third_party_imports listlengths 0 5 | stdlib_only bool 2
classes | question_norm_sha1 stringlengths 40 40 | solution_ast_sha1 stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
v1.0 | instruct | Code_Contests | Code_Contests_18861_I | Write a function `heap_sort` that performs heap sort on a given list of integers. The function should:
- Convert the input list to a max heap.
- Sort the list in ascending order using the properties of heaps.
You are required to implement the max heapify function and the main heap sort algorithm without using any bui... | from typing import List
def max_heapify(arr: List[int], n: int, i: int) -> None:
"""
Ensure the subtree rooted at index 'i' in the list 'arr' of size 'n' is a max heap.
"""
largest = i
left = 2 * i + 1
right = 2 * i + 2
if left < n and arr[left] > arr[largest]:
largest = left
... | def test_heap_sort_with_positive_numbers():
arr = [12, 11, 13, 5, 6, 7]
sorted_arr = heap_sort(arr.copy())
assert sorted_arr == [5, 6, 7, 11, 12, 13]
def test_heap_sort_with_negative_numbers():
arr = [-1, -12, -5, 0, 5, 3]
sorted_arr = heap_sort(arr.copy())
assert sorted_arr == [-12, -5, -1, 0,... | [
{
"docstring": "Ensure the subtree rooted at index 'i' in the list 'arr' of size 'n' is a max heap.",
"function_declaration": "def max_heapify(arr, n, i):",
"function_name": "max_heapify",
"parameter_list": "(arr, n, i)"
},
{
"docstring": "Rearrange the list 'arr' to satisfy max heap propert... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_code_contests-i2i_50000_1739866719_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef max_heapify(arr: List[int], n: int, i: int) -> None:\n largest = i # Initialize largest as root\n left = 2 * i + 1 #... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00018861",
"row_id": 18861,
"seed_ids": "[8905]"
} | 0.712394 | Code_Contests_18861 | I | [
"max_heapify",
"build_max_heap",
"heap_sort"
] | 3 | [
[
"build_max_heap",
"max_heapify"
],
[
"heap_sort",
"build_max_heap"
],
[
"heap_sort",
"max_heapify"
]
] | 3 | [] | false | [] | false | pytest | false | [] | true | 043c8847773bfb01be9ea607712bd425cafa1c32 | 0eb0a2ff58b738b8f06957fa40e31a30316cf9e1 | |||
v1.0 | instruct | Code_Contests | Code_Contests_18877_I | A logistics company is tasked with optimizing the delivery routes for its fleet of trucks. The company has a main warehouse and several delivery locations. Each delivery location can be connected to other delivery locations and the main warehouse through direct roads. The company wants to ensure that all delivery locat... | def find(parent, i):
if parent[i] == i:
return i
else:
return find(parent, parent[i])
def union(parent, rank, x, y):
xroot = find(parent, x)
yroot = find(parent, y)
if xroot != yroot:
if rank[xroot] < rank[yroot]:
parent[xroot] = yroot
elif rank[xroot] > ... | from solution import min_roads_to_connect
def test_min_roads_to_connect_3_1():
assert min_roads_to_connect(3, 1, [(1, 2)]) == 1
def test_min_roads_to_connect_4_2():
assert min_roads_to_connect(4, 2, [(1, 2), (2, 3)]) == 1
def test_min_roads_to_connect_1_0():
assert min_roads_to_connect(1, 0, []) == 0
de... | [
{
"docstring": null,
"function_declaration": "def find(parent, i):",
"function_name": "find",
"parameter_list": "(parent, i)"
},
{
"docstring": null,
"function_declaration": "def union(parent, rank, x, y):",
"function_name": "union",
"parameter_list": "(parent, rank, x, y)"
},
... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_code_contests-i2i_50000_1739866719_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def find(parent, i):\n if parent[i] != i:\n parent[i] = find(parent, parent[i])\n return parent[i]\n\ndef union(parent, rank, x, y):\n root... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00018877",
"row_id": 18877,
"seed_ids": "[10241]"
} | 0.71143 | Code_Contests_18877 | I | [
"find",
"union",
"min_roads_to_connect"
] | 3 | [
[
"min_roads_to_connect",
"find"
],
[
"min_roads_to_connect",
"union"
],
[
"union",
"find"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 0473250747fa138136550fc4ce92695f17c0316c | 34240fb458778fe9384b12c526f1fb7de1bc96cc | |||
v1.0 | instruct | Code_Contests | Code_Contests_18987_I | A city has developed a new system to manage its traffic lights in order to minimize the total waiting time at intersections. Each traffic light has a fixed cycle time, which is the total duration for the light to complete one full cycle of green, yellow, and red lights. The city wants to synchronize the traffic lights ... | import math
from functools import reduce
def lcm(a, b):
"""
Helper function to find the least common multiple (LCM) of two numbers.
"""
return abs(a*b) // math.gcd(a, b)
def find_min_time_to_sync(cycle_times):
"""
Given a list of traffic light cycle times, returns the smallest positive time du... | from solution import process_traffic_lights, find_min_time_to_sync
def test_find_min_time_to_sync():
assert find_min_time_to_sync([3, 4, 6]) == 12
assert find_min_time_to_sync([2, 3, 5, 8]) == 120
assert find_min_time_to_sync([1, 1, 1]) == 1
assert find_min_time_to_sync([7, 5, 3]) == 105
def test_proc... | [
{
"docstring": "Helper function to find the least common multiple (LCM) of two numbers.",
"function_declaration": "def lcm(a, b):",
"function_name": "lcm",
"parameter_list": "(a, b)"
},
{
"docstring": "Given a list of traffic light cycle times, returns the smallest positive time duration\naf... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_code_contests-i2i_50000_1739866719_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\nfrom functools import reduce\n\ndef lcm(a, b):\n return a * b // math.gcd(a, b)\n\ndef find_min_time_to_green_sync(n, cycles):\n return ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00018987",
"row_id": 18987,
"seed_ids": "[2402]"
} | 0.678479 | Code_Contests_18987 | I | [
"lcm",
"find_min_time_to_sync",
"process_traffic_lights"
] | 3 | [
[
"find_min_time_to_sync",
"lcm"
],
[
"process_traffic_lights",
"find_min_time_to_sync"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 6e7494752a730c595ba10b93ecf69363aa6fb51b | 9e8f99804ba7537b60e5ae329107e413b6fe7c26 | |||
v1.0 | instruct | Code_Contests | Code_Contests_18990_I | A palindrome is a sequence that reads the same backward as forward. For this question, consider only numeric palindromes and their formation by adding the original number to its reverse (complement). For example, starting with 195, reversing the digits to get 591, and adding these two numbers together (195 + 591) yield... | def reverse_number(n):
"""
Reverses the digits of the given number.
"""
return int(str(n)[::-1])
def is_palindrome(n):
"""
Checks whether the given number is a palindrome.
"""
return str(n) == str(n)[::-1]
def get_palindrome_steps_and_result(n):
"""
Returns the number of steps ... | from solution import solve_palindromes
def test_solve_palindromes():
assert solve_palindromes([195, 265, 34543, 123, 89]) == [
(4, 9339),
(5, 45254),
(0, 34543),
(1, 444),
(24, 8813200023188)
]
def test_single_palindrome():
assert solve_palindromes([1]) == [(0, 1)]
... | [
{
"docstring": "Reverses the digits of the given number.",
"function_declaration": "def reverse_number(n):",
"function_name": "reverse_number",
"parameter_list": "(n)"
},
{
"docstring": "Checks whether the given number is a palindrome.",
"function_declaration": "def is_palindrome(n):",
... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_code_contests-i2i_50000_1739866719_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def reverse_number(n):\n return int(str(n)[::-1])\n\ndef is_palindrome(n):\n return str(n) == str(n)[::-1]\n\ndef palindrome_steps(n):\n steps = 0... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00018990",
"row_id": 18990,
"seed_ids": "[5523]"
} | 0.74886 | Code_Contests_18990 | I | [
"reverse_number",
"is_palindrome",
"get_palindrome_steps_and_result",
"solve_palindromes"
] | 4 | [
[
"get_palindrome_steps_and_result",
"is_palindrome"
],
[
"get_palindrome_steps_and_result",
"reverse_number"
],
[
"solve_palindromes",
"get_palindrome_steps_and_result"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 979f3cb348c5c58cac8d92da33e02ca002c4fd46 | a502c80e8f5433092195267dc86092fca5bd23fd | |||
v1.0 | instruct | Code_Contests | Code_Contests_19038_I | ### Sally and Her Favorite Substrings
Sally loves exploring different properties of strings, and she is currently fascinated by palindromic substrings. A palindromic string is one that reads the same forwards and backwards. Sally's favorite activity is to find all the unique palindromic substrings within a given strin... | def count_distinct_palindromic_substrings(s):
"""
Returns the number of distinct palindromic substrings in the string `s`.
"""
unique_palindromes = set()
for i in range(len(s)):
# Find all odd-length palindromes centered at s[i]
expand_around_center(s, i, i, unique_palindromes)
... | from solution import count_distinct_palindromic_substrings, distinct_palindromic_substrings
def test_single_character_string():
assert count_distinct_palindromic_substrings("a") == 1
def test_distinct_characters():
assert count_distinct_palindromic_substrings("abc") == 3
def test_repetitive_characters():
... | [
{
"docstring": "Returns the number of distinct palindromic substrings in the string `s`.",
"function_declaration": "def count_distinct_palindromic_substrings(s):",
"function_name": "count_distinct_palindromic_substrings",
"parameter_list": "(s)"
},
{
"docstring": null,
"function_declarat... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_code_contests-i2i_50000_1739866719_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def count_unique_palindromic_substrings(s):\n \"\"\"\n Returns the number of unique palindromic substrings in the string s.\n \"\"\"\n n = len(... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00019038",
"row_id": 19038,
"seed_ids": "[3468]"
} | 0.760386 | Code_Contests_19038 | I | [
"count_distinct_palindromic_substrings",
"expand_around_center",
"distinct_palindromic_substrings"
] | 3 | [
[
"count_distinct_palindromic_substrings",
"expand_around_center"
],
[
"distinct_palindromic_substrings",
"count_distinct_palindromic_substrings"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | e4e45c4c7a4badd7098ebf0ebac135bc9c11ed14 | c1560abd14d06a1a363aadc87deee94a2402fc14 | |||
v1.0 | instruct | Code_Contests | Code_Contests_19080_I | Andria loves palindromic numbers. She gets fascinated when she reads numbers that look the same when read both from left to right and right to left. One day, she decided to find all the palindromic numbers in a given range.
A number is called palindromic if it remains the same when its digits are reversed.
You have... | def is_palindrome(n):
"""
Returns whether a number n is a palindrome.
"""
return str(n) == str(n)[::-1]
def count_palindromic_numbers_in_range(l, r):
"""
Returns the count of palindromic numbers in the range [l, r].
"""
count = 0
for number in range(l, r + 1):
if is_palindro... | from solution import is_palindrome, count_palindromic_numbers_in_range, process_palindromic_queries
def test_is_palindrome():
assert is_palindrome(1) == True
assert is_palindrome(121) == True
assert is_palindrome(123) == False
assert is_palindrome(101) == True
assert is_palindrome(10) == False
def... | [
{
"docstring": "Returns whether a number n is a palindrome.",
"function_declaration": "def is_palindrome(n):",
"function_name": "is_palindrome",
"parameter_list": "(n)"
},
{
"docstring": "Returns the count of palindromic numbers in the range [l, r].",
"function_declaration": "def count_p... | [
0,
0,
0,
0,
0,
0,
0,
1,
0
] | 1 | hard | 0.111 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_code_contests-i2i_50000_1739866719_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_palindromic(n):\n \"\"\"\n Check if a number is palindromic.\n \"\"\"\n return str(n) == str(n)[::-1]\n\ndef count_palindromic_numbers(L... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00019080",
"row_id": 19080,
"seed_ids": "[4749]"
} | 0.706943 | Code_Contests_19080 | I | [
"is_palindrome",
"count_palindromic_numbers_in_range",
"process_palindromic_queries"
] | 3 | [
[
"count_palindromic_numbers_in_range",
"is_palindrome"
],
[
"process_palindromic_queries",
"count_palindromic_numbers_in_range"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 98565b46baa420553e8be3b090378f7eb6f5f4dd | 0ab1997d019e6f22a1f976a15305f5f0379993bf | |||
v1.0 | instruct | Code_Contests | Code_Contests_19098_I | You are responsible for helping a warehouse organize its inventory. The warehouse has a variety of items, each identified by a unique code consisting of a single character (A-Z) followed by an integer (1-99). For instance, 'A12' could represent a specific item, and 'Z99' could represent another.
Your task is to write ... | def merge_sort(arr):
if len(arr) > 1:
mid = len(arr) // 2
L = arr[:mid]
R = arr[mid:]
merge_sort(L)
merge_sort(R)
i = j = k = 0
while i < len(L) and j < len(R):
if (L[i][0] < R[j][0]) or (L[i][0] == R[j][0] and int(L[i][1:]) <= int(R[j][1:])):
... | from solution import sort_inventory
def test_case_1():
input_items = ["D3", "A15", "B4", "A1"]
expected_merge_sorted = ["A1", "A15", "B4", "D3"]
expected_quick_sorted = ["A1", "A15", "B4", "D3"]
result = sort_inventory(4, input_items)
assert result["merge_sorted_items"] == expected_merge_sort... | [
{
"docstring": null,
"function_declaration": "def merge_sort(arr):",
"function_name": "merge_sort",
"parameter_list": "(arr)"
},
{
"docstring": null,
"function_declaration": "def partition(arr, low, high):",
"function_name": "partition",
"parameter_list": "(arr, low, high)"
},
... | [
0,
0,
0,
1,
0
] | 1 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_code_contests-i2i_50000_1739866719_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def merge_sort(arr):\n if len(arr) > 1:\n mid = len(arr) // 2\n L = arr[:mid]\n R = arr[mid:]\n\n # Recursive call on each h... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "00019098",
"row_id": 19098,
"seed_ids": "[6976]"
} | 0.551501 | Code_Contests_19098 | I | [
"merge_sort",
"partition",
"quick_sort",
"is_stable",
"sort_inventory"
] | 5 | [
[
"quick_sort",
"partition"
],
[
"sort_inventory",
"is_stable"
],
[
"sort_inventory",
"merge_sort"
],
[
"sort_inventory",
"quick_sort"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | c8e7db3e2a6748b4078c09bf3ebe24ef55d05cf6 | d0341a8206bac0d2eb676ae590f044d2d603c755 | |||
v1.0 | instruct | Code_Contests | Code_Contests_19133_I | You are given an integer array and a set of queries, each query asks you to find the sum of all the integer elements in a specified subarray. Your task is to answer each query efficiently.
Input
The first line of the input contains two integers, N and Q, where N is the number of elements in the array and Q is the numb... | def preprocess_array(arr):
"""
Precompute the prefix sums for the given array.
"""
N = len(arr)
prefix_sums = [0] * (N + 1)
for i in range(N):
prefix_sums[i + 1] = prefix_sums[i] + arr[i]
return prefix_sums
def query_sum(prefix_sums, L, R):
"""
Calculate the sum of elements ... | from solution import preprocess_array, query_sum, solve
def test_preprocess_array():
arr = [1, 2, 3, 4, 5]
assert preprocess_array(arr) == [0, 1, 3, 6, 10, 15]
def test_query_sum():
prefix_sums = [0, 1, 3, 6, 10, 15]
assert query_sum(prefix_sums, 1, 3) == 6
assert query_sum(prefix_sums, 2, 4) == 9... | [
{
"docstring": "Precompute the prefix sums for the given array.",
"function_declaration": "def preprocess_array(arr):",
"function_name": "preprocess_array",
"parameter_list": "(arr)"
},
{
"docstring": "Calculate the sum of elements from L to R using the prefix sums.",
"function_declarati... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_code_contests-i2i_50000_1739866719_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def preprocess_prefix_sums(arr):\n \"\"\"\n This function calculates the prefix sums for the input array.\n :param arr: List of integers represent... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00019133",
"row_id": 19133,
"seed_ids": "[5735]"
} | 0.684934 | Code_Contests_19133 | I | [
"preprocess_array",
"query_sum",
"solve"
] | 3 | [
[
"solve",
"preprocess_array"
],
[
"solve",
"query_sum"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | ece51083400d7966af613f740343b204eb5f1800 | e7886556a4fa2b24be6e9c2731cb4b207f1faa91 | |||
v1.0 | instruct | Code_Contests | Code_Contests_19203_I | You are given a list of 'n' strings. Each string consists of lowercase English letters. Your task is to find the number of pairs of integers (i, j) such that 1 ≤ i < j ≤ n and the concatenation of the ith string and the jth string is a palindrome.
A string is called palindrome if it reads the same forward and backward... | def is_palindrome(s):
return s == s[::-1]
def count_palindrome_pairs(strings):
count = 0
n = len(strings)
for i in range(n):
for j in range(i + 1, n):
if is_palindrome(strings[i] + strings[j]):
count += 1
return count | from solution import is_palindrome, count_palindrome_pairs
def test_is_palindrome():
assert is_palindrome("abcba") == True
assert is_palindrome("abccba") == True
assert is_palindrome("abcd") == False
assert is_palindrome("a") == True
assert is_palindrome("") == True
def test_count_palindrome_pairs... | [
{
"docstring": null,
"function_declaration": "def is_palindrome(s):",
"function_name": "is_palindrome",
"parameter_list": "(s)"
},
{
"docstring": null,
"function_declaration": "def count_palindrome_pairs(strings):",
"function_name": "count_palindrome_pairs",
"parameter_list": "(s... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_code_contests-i2i_50000_1739866719_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def count_palindrome_pairs(n, strings):\n \"\"\"\n This function counts the number of pairs (i, j) such that 1 ≤ i < j ≤ n \n and the concatenatio... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00019203",
"row_id": 19203,
"seed_ids": "[1072]"
} | 0.880395 | Code_Contests_19203 | I | [
"is_palindrome",
"count_palindrome_pairs"
] | 2 | [
[
"count_palindrome_pairs",
"is_palindrome"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 02adafcd5d6de711463293f179f4ff1cbbbcb13d | d4f8c0f9cae9ddb3533e964354f9c8a5907d01fa | |||
v1.0 | instruct | Code_Contests | Code_Contests_19204_I | A farm has a rectangular grid of size N x M, where each cell can either be fertile or barren. The farm is represented as a binary grid where a '1' indicates a fertile cell and '0' indicates a barren cell. Farmers want to create the largest possible contiguous rectangle of fertile land. Your task is to determine the are... | def maximalRectangle(matrix):
"""
Returns the area of the largest rectangle of only fertile cells (1s) in the given binary matrix.
"""
if not matrix:
return 0
max_area = 0
dp = [0] * len(matrix[0])
for row in matrix:
for j in range(len(row)):
dp[j] = dp[j] + 1 i... | import pytest
from solution import get_largest_rectangle_area
def test_single_element():
assert get_largest_rectangle_area(1, 1, [[1]]) == 1
assert get_largest_rectangle_area(1, 1, [[0]]) == 0
def test_multiple_elements():
assert get_largest_rectangle_area(4, 5, [[1, 0, 1, 0, 0], [1, 0, 1, 1, 1], [1, 1, 1... | [
{
"docstring": "Returns the area of the largest rectangle of only fertile cells (1s) in the given binary matrix.",
"function_declaration": "def maximalRectangle(matrix):",
"function_name": "maximalRectangle",
"parameter_list": "(matrix)"
},
{
"docstring": "Helper function to calculate the la... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_code_contests-i2i_50000_1739866719_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def maximalRectangle(grid):\n if not grid or not grid[0]:\n return 0\n \n def largestRectangleArea(heights):\n stack = []\n m... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00019204",
"row_id": 19204,
"seed_ids": "[9350]"
} | 0.713827 | Code_Contests_19204 | I | [
"maximalRectangle",
"largestRectangleArea",
"get_largest_rectangle_area"
] | 3 | [
[
"get_largest_rectangle_area",
"maximalRectangle"
],
[
"maximalRectangle",
"largestRectangleArea"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | de800574166f1d0def2c8fbc3cff8bb91a7824f1 | eadad27a2d3beb5b1fbe9ee38116c33e11e3103b | |||
v1.0 | instruct | Code_Contests | Code_Contests_19222_I | Given a matrix of size N x N, determine if it is a magic square. A magic square is a grid of numbers where the sum of numbers in each row, each column, and both main diagonals are the same.
### Constraints
* 1 ≤ N ≤ 50
* Each element in the matrix is an integer between -100 and 100.
### Input
The first line contain... | def is_magic_square(matrix):
N = len(matrix)
sum_diagonal1 = sum([matrix[i][i] for i in range(N)])
sum_diagonal2 = sum([matrix[i][N - i - 1] for i in range(N)])
if sum_diagonal1 != sum_diagonal2:
return "NOT MAGIC"
sum_row = sum(matrix[0])
for i in range(N):
if sum... | from solution import check_magic_square
def test_magic_square_3x3():
matrix = [
[2, 7, 6],
[9, 5, 1],
[4, 3, 8]
]
assert check_magic_square(3, matrix) == "MAGIC"
def test_not_magic_square_3x3():
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
assert... | [
{
"docstring": null,
"function_declaration": "def is_magic_square(matrix):",
"function_name": "is_magic_square",
"parameter_list": "(matrix)"
},
{
"docstring": "Determines whether a given N x N matrix is a magic square.\n\nParameters:\nN (int): Size of the matrix.\nmatrix (list of lists of i... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_code_contests-i2i_50000_1739866719_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_magic_square(matrix):\n \"\"\"\n Determines if the given matrix is a magic square.\n :param matrix: List of lists representing the NxN matr... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00019222",
"row_id": 19222,
"seed_ids": "[2189]"
} | 0.699952 | Code_Contests_19222 | I | [
"is_magic_square",
"check_magic_square"
] | 2 | [
[
"check_magic_square",
"is_magic_square"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | e3aa16629109c9308fce4234463003d94bf4098e | 0844ce419a10fa266740685a5eb53434cc0a1b9c | |||
v1.0 | instruct | Code_Contests | Code_Contests_19262_I | You are given a rectangular matrix filled with positive integers. Your task is to find the sum of the elements in the submatrix that has the largest sum among all possible submatrices of the given matrix.
Input
The first line contains two integers n and m (1 ≤ n, m ≤ 300), where n is the number of rows and m is the n... | def max_sum_submatrix(matrix):
n = len(matrix)
m = len(matrix[0])
max_sum = float('-inf')
for left in range(m):
temp_row = [0] * n
for right in range(left, m):
for i in range(n):
temp_row[i] += matrix[i][right]
max_s... | from solution import solution
def test_case1():
input_text = "3 3\n1 2 3\n4 5 6\n7 8 9"
assert solution(input_text) == 45
def test_case2():
input_text = "2 2\n-1 -2\n-3 -4"
assert solution(input_text) == -1
def test_case3():
input_text = "1 1\n1000"
assert solution(input_text) == 1000
de... | [
{
"docstring": null,
"function_declaration": "def max_sum_submatrix(matrix):",
"function_name": "max_sum_submatrix",
"parameter_list": "(matrix)"
},
{
"docstring": null,
"function_declaration": "def kadane(arr):",
"function_name": "kadane",
"parameter_list": "(arr)"
},
{
... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_code_contests-i2i_50000_1739866719_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def max_submatrix_sum(matrix, n, m):\n def kadane(array):\n max_sum = current_sum = array[0]\n for num in array[1:]:\n current_... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00019262",
"row_id": 19262,
"seed_ids": "[2985]"
} | 0.597651 | Code_Contests_19262 | I | [
"max_sum_submatrix",
"kadane",
"parse_input",
"solution"
] | 4 | [
[
"max_sum_submatrix",
"kadane"
],
[
"solution",
"max_sum_submatrix"
],
[
"solution",
"parse_input"
]
] | 3 | [
"parse_input"
] | false | [] | false | pytest | true | [] | true | ff6cd8bdeeeea213486a385d5b8c20ea1231e581 | 64226c94650d823c850efa7b6c0d7e216420935d | |||
v1.0 | instruct | Code_Contests | Code_Contests_19277_I | Tanya is a fan of prime numbers and recently she discovered an interesting property of them. She found that given a set of prime numbers, she could generate a "special prime number" by concatenating any two prime numbers from the set. If the resulting number is prime, she considers it a special prime number.
Assume yo... | def is_prime(n):
"""
Helper function to check whether a number is prime.
"""
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
... | from solution import can_form_special_prime
def test_can_form_special_prime_yes_case():
can_form_special_prime(4, [2, 3, 5, 7]) # Expected output: "YES"
def test_can_form_special_prime_no_case():
can_form_special_prime(3, [11, 13, 17]) # Expected output: "NO"
def test_can_form_special_prime_single_pair():
... | [
{
"docstring": "Helper function to check whether a number is prime.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Function to determine if there exists at least one pair of prime numbers \nfrom the list that concatenates... | [
0,
0,
0,
0,
0,
0,
1,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_code_contests-i2i_50000_1739866719_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\n\ndef is_prime(n):\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == 0 or n % 3 == 0:\n retur... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "00019277",
"row_id": 19277,
"seed_ids": "[3289]"
} | 0.676561 | Code_Contests_19277 | I | [
"is_prime",
"can_form_special_prime"
] | 2 | [
[
"can_form_special_prime",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 9f998bc0c012d5b6e047bccbc2c7f409c62bb9ec | 20579bf8043f298a29a2cf5b3408955402170983 | |||
v1.0 | instruct | Code_Contests | Code_Contests_19290_I | Lisa and Bob both have an interest in studying number theory. One day, they stumbled upon a fascinating topic called "Almost Prime Numbers." An almost prime number is defined as a number that has exactly two distinct prime factors. For example, 6=2*3 and 10=2*5 are almost prime numbers.
Lisa decided to challenge Bob t... | def sieve_of_eratosthenes(limit):
primes = []
is_prime = [True] * (limit + 1)
is_prime[0], is_prime[1] = False, False
for num in range(2, limit + 1):
if is_prime[num]:
primes.append(num)
for multiple in range(num * num, limit + 1, num):
is_prime[multiple]... | from solution import kth_almost_prime
def test_kth_almost_prime():
assert kth_almost_prime(1) == 6
assert kth_almost_prime(2) == 10
assert kth_almost_prime(3) == 14
assert kth_almost_prime(4) == 15
assert kth_almost_prime(5) == 21
assert kth_almost_prime(6) == 22
assert kth_almost_prime(7) ... | [
{
"docstring": null,
"function_declaration": "def sieve_of_eratosthenes(limit):",
"function_name": "sieve_of_eratosthenes",
"parameter_list": "(limit)"
},
{
"docstring": "Generate almost prime numbers until the k-th almost prime number is found.",
"function_declaration": "def generate_al... | [
0,
0,
0,
0,
0,
0,
1,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_code_contests-i2i_50000_1739866719_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from itertools import count\nfrom math import isqrt\n\ndef is_almost_prime(n):\n prime_factors = 0\n for i in range(2, isqrt(n) + 1):\n if n %... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "00019290",
"row_id": 19290,
"seed_ids": "[4312]"
} | 0.444646 | Code_Contests_19290 | I | [
"sieve_of_eratosthenes",
"generate_almost_prime_numbers",
"kth_almost_prime"
] | 3 | [
[
"generate_almost_prime_numbers",
"sieve_of_eratosthenes"
],
[
"kth_almost_prime",
"generate_almost_prime_numbers"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 023cd648bfdfe13f80c7da69a01ca44b03d17f76 | 5fe73bc294742f243db453e144166a71a1af8d71 | |||
v1.0 | instruct | Code_Contests | Code_Contests_19323_I | You are given an array of integers representing the number of flowers in each garden. Each garden can have zero or more flowers.
We define a "harmonious array" as an array where each garden either has zero flowers or has exactly one more flower than some other garden. Determine whether the given array can be made harm... | def is_harmonious(n, C, flowers):
from collections import Counter
if n == 1:
return True
flower_counts = Counter(flowers)
unique_flower_counts = sorted(flower_counts.keys())
min_cost = float('inf')
for i in range(len(unique_flower_counts) - 1):
curr_cost = 0
for coun... | def test_harmonious_array_case_1():
n, C, flowers = 3, 2, [2, 3, 4]
assert can_make_harmonious(n, C, flowers) == "Yes"
def test_harmonious_array_case_2():
n, C, flowers = 4, 4, [0, 4, 3, 1]
assert can_make_harmonious(n, C, flowers) == "No"
def test_harmonious_array_single_element():
n, C, flowers ... | [
{
"docstring": null,
"function_declaration": "def is_harmonious(n, C, flowers):",
"function_name": "is_harmonious",
"parameter_list": "(n, C, flowers)"
},
{
"docstring": null,
"function_declaration": "def can_make_harmonious(n, C, flowers):",
"function_name": "can_make_harmonious",
... | [
0,
0,
0,
0,
1
] | 1 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_code_contests-i2i_50000_1739866719_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def can_be_harmonious(n, C, flowers):\n from collections import Counter\n \n flower_count = Counter(flowers)\n min_flowers = min(flowers)\n ... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "00019323",
"row_id": 19323,
"seed_ids": "[8519]"
} | 0.611851 | Code_Contests_19323 | I | [
"is_harmonious",
"can_make_harmonious"
] | 2 | [
[
"can_make_harmonious",
"is_harmonious"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 9571d9b6ef2178d63fa259c46cf9db67484db0f2 | 61f92d4b04824c1eaff0c4ebceb6ebc0854a6a8d | |||
v1.0 | instruct | Code_Contests | Code_Contests_19333_I | Design a new **Coding Assessment Question** that matches the style and complexity of the existing questions:
During a geological survey, researchers observed that certain mineral deposits form unique polygonal shapes on a Cartesian plane, and they want to study the maximum possible area enclosed by such formations. Gi... | def cross_product(o, a, b):
""" Returns the cross product of vectors o->a and o->b.
Positive if b is to the left of a -> o,
negative if b is to the right of a -> o,
0 if they are collinear.
"""
return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0])
def convex_hull(po... | import pytest
from solution import main
def test_case_1():
input_data = """
5
1.0 1.0
2.0 5.0
3.0 3.0
5.0 3.0
3.5 1.0
0
"""
expected_output = """
1.00000 1.00000
3.50000 1.00000
5.00000 3.00000
2.00000 5.00000
"""
assert main(input_data).strip() == expected_output.strip()
def test_case_2():
input_data... | [
{
"docstring": "Returns the cross product of vectors o->a and o->b.\nPositive if b is to the left of a -> o, \nnegative if b is to the right of a -> o, \n0 if they are collinear.",
"function_declaration": "def cross_product(o, a, b):",
"function_name": "cross_product",
"parameter_list": "(o, a, b)"
... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_code_contests-i2i_50000_1739866719_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import sys\nfrom functools import cmp_to_key\n\ndef orientation(p, q, r):\n \"\"\"\n Returns the orientation of the triplet (p, q, r).\n 0 -> p, q... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00019333",
"row_id": 19333,
"seed_ids": "[12796]"
} | 0.552171 | Code_Contests_19333 | I | [
"cross_product",
"convex_hull",
"main"
] | 3 | [
[
"convex_hull",
"cross_product"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | e294d115b0680f21b1810daca3893feea577a9f5 | e7ea748aa21a09a4ecb9de3791b4b211fa6211dc | |||
v1.0 | instruct | Code_Contests | Code_Contests_19335_I | You are given an n x m matrix of integers. Your task is to handle q queries regarding submatrices of this matrix. Each query consists of four integers: r1, c1, r2, and c2, which define the top-left and bottom-right corners of a submatrix. For each query, you need to calculate the sum of all the elements within the subm... | def preprocess_matrix(matrix):
n = len(matrix)
m = len(matrix[0])
# Create prefix sum matrix
prefix_sum = [[0] * (m + 1) for _ in range(n + 1)]
for i in range(1, n + 1):
for j in range(1, m + 1):
prefix_sum[i][j] = (
matrix[i-1][j-1] +
pr... | def test_preprocess_matrix():
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
expected_prefix_sum = [
[0, 0, 0, 0],
[0, 1, 3, 6],
[0, 5, 12, 21],
[0, 12, 27, 45]
]
assert preprocess_matrix(matrix) == expected_prefix_sum
def test_query_sum():
... | [
{
"docstring": null,
"function_declaration": "def preprocess_matrix(matrix):",
"function_name": "preprocess_matrix",
"parameter_list": "(matrix)"
},
{
"docstring": null,
"function_declaration": "def query_sum(prefix_sum, r1, c1, r2, c2):",
"function_name": "query_sum",
"parameter... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_code_contests-i2i_50000_1739866719_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def preprocess_matrix(matrix, n, m):\n \"\"\"\n Preprocess the given matrix to create a prefix sum matrix.\n \"\"\"\n prefix_sum = [[0] * (m + ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00019335",
"row_id": 19335,
"seed_ids": "[8264]"
} | 0.630099 | Code_Contests_19335 | I | [
"preprocess_matrix",
"query_sum",
"process_queries"
] | 3 | [
[
"process_queries",
"preprocess_matrix"
],
[
"process_queries",
"query_sum"
]
] | 2 | [
"process_queries"
] | false | [] | false | pytest | false | [] | true | 04814f4e37e9bd79a473e835e1ac4441ba9f2b48 | 5442d5a1fc1b9a1af51b396b9e9e199042f47a1a | |||
v1.0 | instruct | Code_Contests | Code_Contests_19347_I | Background:
Rahul loves prime numbers and he recently found a unique way to transform an array using prime numbers. Rahul takes a list of n integers and applies a transformation function f(x) that takes an integer x and returns the smallest prime number which is greater than or equal to x. He wants to create a new arra... | def get_primes_up_to(n):
"""
Utility function that returns a list of prime numbers up to given number n.
Uses the Sieve of Eratosthenes algorithm.
"""
is_prime = [True] * (n + 1)
p = 2
while (p * p <= n):
if is_prime[p]:
for i in range(p * p, n + 1, p):
is... | from solution import get_primes_up_to, transform_array
def test_primes_up_to_2():
assert get_primes_up_to(2) == [2]
def test_primes_up_to_10():
assert get_primes_up_to(10) == [2, 3, 5, 7]
def test_primes_up_to_30():
assert get_primes_up_to(30) == [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
def test_transform_s... | [
{
"docstring": "Utility function that returns a list of prime numbers up to given number n.\nUses the Sieve of Eratosthenes algorithm.",
"function_declaration": "def get_primes_up_to(n):",
"function_name": "get_primes_up_to",
"parameter_list": "(n)"
},
{
"docstring": "Transformation function... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_code_contests-i2i_50000_1739866719_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def sieve_of_eratosthenes(limit):\n sieve = [True] * (limit + 1)\n p = 2\n while (p * p <= limit):\n if (sieve[p] == True):\n fo... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00019347",
"row_id": 19347,
"seed_ids": "[4950]"
} | 0.664154 | Code_Contests_19347 | I | [
"get_primes_up_to",
"f",
"transform_array"
] | 3 | [
[
"transform_array",
"f"
],
[
"transform_array",
"get_primes_up_to"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | e5a08275172918d4516bc8f63cb11c52f615065b | aa68329bfa6316cc657451840925d4b14079fa6b | |||
v1.0 | instruct | Code_Contests | Code_Contests_19383_I | A company has a network of computers connected by direct cables. Each direct cable connects exactly two computers. The company wants to monitor the network's stability by ensuring there is no single point of failure. To achieve this, they need to find the minimum number of computers that, when removed, will disconnect ... | def find_articulation_points(n, edges):
from collections import defaultdict
graph = defaultdict(list)
for u, v in edges:
graph[u].append(v)
graph[v].append(u)
disc = [-1] * (n + 1)
low = [-1] * (n + 1)
parent = [-1] * (n + 1)
articulation_points_set = set()
time = [0]
... | from solution import number_of_articulation_points
def test_example_case():
assert number_of_articulation_points(5, 5, [(1, 2), (1, 3), (3, 4), (3, 5), (4, 5)]) == 2
def test_no_articulation_points():
assert number_of_articulation_points(3, 3, [(1, 2), (2, 3), (3, 1)]) == 0
def test_single_articulation_point... | [
{
"docstring": null,
"function_declaration": "def find_articulation_points(n, edges):",
"function_name": "find_articulation_points",
"parameter_list": "(n, edges)"
},
{
"docstring": null,
"function_declaration": "def number_of_articulation_points(n, m, edges):",
"function_name": "num... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_code_contests-i2i_50000_1739866719_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def find_articulation_points(n, m, edges):\n from collections import defaultdict\n\n def dfs(v, visited, disc, low, parent, articulation_points):\n ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00019383",
"row_id": 19383,
"seed_ids": "[3664]"
} | 0.661835 | Code_Contests_19383 | I | [
"find_articulation_points",
"number_of_articulation_points"
] | 2 | [
[
"number_of_articulation_points",
"find_articulation_points"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 581d499f9ecdd9729e30cd6a660c4adb9c54c192 | 054029074e68c4f73c47a3683c7c28d9c86aa82d | |||
v1.0 | instruct | Code_Contests | Code_Contests_19463_I | ## Problem Statement
You've been hired to design a simplified version of a stock-trading simulation for a financial educational platform. In this simulation, players can execute stock trades based on a set of predefined trading rules. Each trading rule specifies an exchange between one unit of stock `S_i` and `y_i` un... | from collections import defaultdict
import heapq
def is_valid_trading(N, M, rules):
graph = defaultdict(list)
for S, T, y in rules:
graph[S].append((T, y))
graph[T].append((S, 1 / y))
def bellman_ford(source):
rates = [float('inf')] * (N + 1)
rates[source] = 1
for _... | from solution import trading_system
def test_valid_trading_example1():
assert trading_system(3, 3, [(1, 2, 3), (2, 3, 2), (1, 3, 6)]) == "Valid"
def test_invalid_trading_example2():
assert trading_system(2, 2, [(1, 2, 2), (2, 1, 3)]) == "Invalid"
def test_valid_trading_case():
assert trading_system(4, 3,... | [
{
"docstring": null,
"function_declaration": "def is_valid_trading(N, M, rules):",
"function_name": "is_valid_trading",
"parameter_list": "(N, M, rules)"
},
{
"docstring": null,
"function_declaration": "def trading_system(N, M, rules):",
"function_name": "trading_system",
"parame... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_code_contests-i2i_50000_1739866719_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_trade_valid(N, M, trades):\n from collections import defaultdict, deque\n import sys\n\n graph = defaultdict(list)\n \n # Create adja... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00019463",
"row_id": 19463,
"seed_ids": "[6767]"
} | 0.6278 | Code_Contests_19463 | I | [
"is_valid_trading",
"trading_system"
] | 2 | [
[
"trading_system",
"is_valid_trading"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | b88a49676a273e17701401a8cfe6a67be6a7e2f3 | eaa210472ca5f6795bde1635fb77e149304826a4 | |||
v1.0 | instruct | Code_Contests | Code_Contests_19503_I | John is a software developer who has recently been fascinated by the popular game Sudoku. He decided to create a function to validate Sudoku boards. A Sudoku board is a 9x9 grid, where each cell can have a digit from 1 to 9 or be empty, represented by a dot ('.'). The board is valid if the following rules hold:
- Each... | def is_valid_sudoku(board):
def is_valid_row(board):
for row in board:
if not is_valid_unit(row):
return False
return True
def is_valid_col(board):
for col in zip(*board):
if not is_valid_unit(col):
return False
return True... | def test_sudoku_valid_case_1():
board = [
"53..7....",
"6..195...",
".98....6.",
"8...6...3",
"4..8.3..1",
"7...2...6",
".6....28.",
"...419..5",
"....8..79"
]
assert validate_sudoku(board) == "YES"
def test_sudoku_invalid_case_1():
... | [
{
"docstring": null,
"function_declaration": "def is_valid_sudoku(board):",
"function_name": "is_valid_sudoku",
"parameter_list": "(board)"
},
{
"docstring": null,
"function_declaration": "def validate_sudoku(board):",
"function_name": "validate_sudoku",
"parameter_list": "(board... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_code_contests-i2i_50000_1739866719_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_valid_sudoku(board):\n \"\"\"\n Determine if a given Sudoku board is valid.\n \"\"\"\n def is_valid_block(block):\n block = [x fo... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00019503",
"row_id": 19503,
"seed_ids": "[12146]"
} | 0.626438 | Code_Contests_19503 | I | [
"is_valid_sudoku",
"validate_sudoku"
] | 2 | [
[
"validate_sudoku",
"is_valid_sudoku"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | cfbdfc7d5243e1a98bca01f345ca918302d6feb5 | fefce11bf8d5752a69ed5ece434b50d3ad11a665 | |||
v1.0 | instruct | Code_Contests | Code_Contests_19510_I | Sara loves collecting gemstones. There are N different types of gemstones, each represented by an uppercase alphabet letter from 'A' to 'Z'. Sara is planning to travel to M different shops numbered from 1 to M, to collect these gemstones. Each shop stocks a specific combination of gemstone types and each gem type is av... | from itertools import combinations
def max_unique_gemstones(N, M, K, gemstone_types, shops):
max_unique = 0
for c in combinations(shops, K):
collected_gemstones = set()
for shop in c:
collected_gemstones.update(shop)
max_unique = max(max_unique, len(collected_gemstones)... | import pytest
from solution import solve
def test_example_1():
N, M, K = 3, 4, 2
gemstone_types = ['A', 'B', 'C']
shops = [
[2, 'A', 'B'],
[3, 'A', 'B', 'C'],
[1, 'B'],
[1, 'C']
]
assert solve(N, M, K, gemstone_types, shops) == 3
def test_example_2():
N, M, K = ... | [
{
"docstring": null,
"function_declaration": "def max_unique_gemstones(N, M, K, gemstone_types, shops):",
"function_name": "max_unique_gemstones",
"parameter_list": "(N, M, K, gemstone_types, shops)"
},
{
"docstring": null,
"function_declaration": "def solve(N, M, K, gemstone_types, shop... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_code_contests-i2i_50000_1739866719_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from itertools import combinations\n\ndef max_unique_gemstones(N, M, K, gemstones, shops):\n max_unique = 0\n\n for shops_comb in combinations(shops,... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00019510",
"row_id": 19510,
"seed_ids": "[2735]"
} | 0.659752 | Code_Contests_19510 | I | [
"max_unique_gemstones",
"solve"
] | 2 | [
[
"solve",
"max_unique_gemstones"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 26c762dd10407f6456de00fccd298d11c127f58b | 8e0fbb57d331f76642ae43038cc67dc5e463147f | |||
v1.0 | instruct | Code_Contests | Code_Contests_19548_I | Marie loves working with matrices. One day, she encountered an interesting matrix-related problem and decided to solve it. Marie has a matrix where each element is either 0 or 1. A submatrix is any rectangular section of the matrix, possibly the entire matrix or just one element. Marie wants to find the largest submatr... | def maximalRectangle(matrix):
"""
Given a binary matrix, find the maximum area of a submatrix with all 1s.
"""
if not matrix or not matrix[0]:
return 0
max_area = 0
n = len(matrix)
m = len(matrix[0])
heights = [0] * m
for i in range(n):
for j in range(m):
... | from solution import maximalRectangle
def test_example_1():
matrix = [
[1, 0, 1, 0, 0],
[1, 0, 1, 1, 1],
[1, 1, 1, 1, 1],
[1, 0, 0, 1, 0]
]
assert maximalRectangle(matrix) == 6
def test_example_2():
matrix = [
[0, 0, 0],
[0, 1, 0],
[0, 0, 0]
... | [
{
"docstring": "Given a binary matrix, find the maximum area of a submatrix with all 1s.",
"function_declaration": "def maximalRectangle(matrix):",
"function_name": "maximalRectangle",
"parameter_list": "(matrix)"
},
{
"docstring": "Helper function to find the largest rectangle area in histo... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_code_contests-i2i_50000_1739866719_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def max_submatrix_area(n, m, matrix):\n if n == 0 or m == 0:\n return 0\n \n max_area = 0\n heights = [0] * (m + 1)\n \n for row i... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00019548",
"row_id": 19548,
"seed_ids": "[8579]"
} | 0.63278 | Code_Contests_19548 | I | [
"maximalRectangle",
"largestRectangleArea"
] | 2 | [
[
"maximalRectangle",
"largestRectangleArea"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ae8c19a41efb03d5b3207ee85f47ffedaa95a86e | 0168f5929d5528762d372dc8946b97d9b9bd134f | |||
v1.0 | instruct | Code_Contests | Code_Contests_19571_I | Alice has a sequence of integers that she wants to convert into a special arrangement. Specifically, she wants to rearrange the numbers such that the sequence becomes a palindrome, if possible. A sequence is a palindrome if it reads the same backward as forward.
The task is to determine if it's possible to rearrange t... | from collections import Counter
def can_form_palindrome(n, sequence):
count = Counter(sequence)
# Check for the number of odd occurrences
odd_count = sum(1 for x in count.values() if x % 2 != 0)
# For a sequence to be rearranged to a palindrome, it can have at most one odd count
if odd_co... | from solution import rearrange_sequence_into_palindrome
def test_palindrome_odd_length():
assert rearrange_sequence_into_palindrome(5, [1, 2, 3, 2, 1]) == "1 2 3 2 1"
def test_palindrome_even_length():
result = rearrange_sequence_into_palindrome(4, [4, 3, 3, 4])
# Two possible valid responses for the give... | [
{
"docstring": null,
"function_declaration": "def can_form_palindrome(n, sequence):",
"function_name": "can_form_palindrome",
"parameter_list": "(n, sequence)"
},
{
"docstring": null,
"function_declaration": "def rearrange_sequence_into_palindrome(n, sequence):",
"function_name": "re... | [
0,
0,
0,
0,
0,
0,
1,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_code_contests-i2i_50000_1739866719_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from collections import Counter\n\ndef rearrange_to_palindrome(n, sequence):\n \"\"\"\n Determine if it's possible to rearrange the sequence into a p... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "00019571",
"row_id": 19571,
"seed_ids": "[10783]"
} | 0.737746 | Code_Contests_19571 | I | [
"can_form_palindrome",
"rearrange_sequence_into_palindrome"
] | 2 | [
[
"rearrange_sequence_into_palindrome",
"can_form_palindrome"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 432952aadfe9f3cd021ba35c508d10acdc8e54a1 | b43a69adcb9fe99953885ca53aa47c2534327f28 | |||
v1.0 | instruct | Code_Contests | Code_Contests_19598_I | You are given an array of n integers. An inversion is a pair of indices (i, j) such that i < j and arr[i] > arr[j]. Write a program to count the number of inversions in the array. The program should work efficiently for large arrays.
Input
The first line contains a single integer t (1 ≤ t ≤ 10) — the number of test c... | def merge_and_count(arr, temp_arr, left, mid, right):
i = left # Starting index for left subarray
j = mid + 1 # Starting index for right subarray
k = left # Starting index to be sorted
inv_count = 0
# Conditions are checked to ensure that i doesn't exceed mid and j doesn't exceed right
w... | from solution import inversions_for_test_cases
def test_single_test_case():
assert inversions_for_test_cases(1, [(5, [1, 20, 6, 4, 5])]) == [5]
assert inversions_for_test_cases(1, [(3, [2, 3, 1])]) == [2]
def test_multiple_test_cases():
assert inversions_for_test_cases(2, [(5, [1, 20, 6, 4, 5]), (3, [2, 3... | [
{
"docstring": null,
"function_declaration": "def merge_and_count(arr, temp_arr, left, mid, right):",
"function_name": "merge_and_count",
"parameter_list": "(arr, temp_arr, left, mid, right)"
},
{
"docstring": null,
"function_declaration": "def merge_sort_and_count(arr, temp_arr, left, r... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_code_contests-i2i_50000_1739866719_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def merge_and_count(arr, temp_arr, left, mid, right):\n i = left # Starting index for left subarray\n j = mid + 1 # Starting index for right subar... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00019598",
"row_id": 19598,
"seed_ids": "[4511]"
} | 0.804202 | Code_Contests_19598 | I | [
"merge_and_count",
"merge_sort_and_count",
"count_inversions",
"inversions_for_test_cases"
] | 4 | [
[
"count_inversions",
"merge_sort_and_count"
],
[
"inversions_for_test_cases",
"count_inversions"
],
[
"merge_sort_and_count",
"merge_and_count"
]
] | 3 | [
"inversions_for_test_cases"
] | false | [] | false | pytest | true | [] | true | 0c153212061070236ed962975939eda48c1d85c2 | 71fd0c6203b7ac33d45574a8cfd0f4a43d3ec7c0 | |||
v1.0 | instruct | Code_Contests | Code_Contests_19620_I | You are given a binary tree, and your task is to determine the maximum path sum. The path can start and end at any two nodes in the tree, and it must go downwards (traveling only from parent nodes to child nodes, but it can only travel through each node once).
Input
The input is provided as a list of integers represen... | from typing import List, Optional
import math
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def build_tree(nodes: List[Optional[int]]) -> Optional[TreeNode]:
if not nodes or nodes[0] is None:
return None
... | import pytest
from solution import find_maximum_path_sum
def test_sample_input():
assert find_maximum_path_sum([1, 2, 3]) == 6
def test_single_node():
assert find_maximum_path_sum([5]) == 5
def test_all_negative_nodes():
assert find_maximum_path_sum([-10, -20, -30]) == -10
def test_multiple_levels():
... | [] | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_code_contests-i2i_50000_1739866719_sanitized_prepared0_results_combined.jsonl",
"solution_code": "# Define the Binary Tree Node class\nclass TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = le... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00019620",
"row_id": 19620,
"seed_ids": "[1114]"
} | 0.661242 | Code_Contests_19620 | I | [
"build_tree",
"max_path_sum",
"find_maximum_path_sum"
] | 3 | [
[
"find_maximum_path_sum",
"build_tree"
],
[
"find_maximum_path_sum",
"max_path_sum"
]
] | 2 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | 9db802daa8285bffae4b7d3fd608f2d86d911f2a | 36078337e9e5e16503d2b447e2cf709300e0095a | |||
v1.0 | instruct | Code_Contests | Code_Contests_19699_I | You are given a sequence of 'n' unique integers, and you want to transform it into a magical sequence. A sequence is magical if for every substring 'abc' comprising three consecutive elements in the sequence, the sum a + b + c is not divisible by '7'.
Your task is to find a permutation of the given sequence that is ma... | def is_magical_permutation(perm):
"""
Helper function to check if a given permutation is magical.
"""
for i in range(len(perm) - 2):
if (perm[i] + perm[i+1] + perm[i+2]) % 7 == 0:
return False
return True
def find_magical_permutation(n, sequence):
"""
Given a sequence of... | from solution import find_magical_permutation
def test_case_1():
assert find_magical_permutation(5, [1, 2, 3, 4, 5]) != "Not possible"
def test_case_2():
assert find_magical_permutation(4, [6, 1, 8, 5]) != "Not possible"
def test_case_3():
assert find_magical_permutation(3, [1, 6, 7]) == "Not possible"
... | [
{
"docstring": "Helper function to check if a given permutation is magical.",
"function_declaration": "def is_magical_permutation(perm):",
"function_name": "is_magical_permutation",
"parameter_list": "(perm)"
},
{
"docstring": "Given a sequence of 'n' unique integers, finds a permutation tha... | [
0,
0,
0,
0,
0,
0,
0,
1,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_code_contests-i2i_50000_1739866719_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def find_magical_permutation(n, sequence):\n def is_magical(seq):\n for i in range(n - 2):\n if (seq[i] + seq[i+1] + seq[i+2]) % 7 == ... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00019699",
"row_id": 19699,
"seed_ids": "[10118]"
} | 0.622231 | Code_Contests_19699 | I | [
"is_magical_permutation",
"find_magical_permutation"
] | 2 | [
[
"find_magical_permutation",
"is_magical_permutation"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 06e6ad23bc35d62ae6875cafa15f681e608378f5 | d45963632228155ce031699c3c3ceff041ce61e3 | |||
v1.0 | instruct | Code_Contests | Code_Contests_19710_I | A new feature has been introduced in an event management system called "event prioritization." Each event is assigned a priority level based on five categories: critical, high, medium, low, informational. The system processes events in queue in the order of their priorities. Events of the same priority are processed in... | def process_events(event_count, event_list):
"""
Processes events based on their priorities.
Parameters:
event_count (int): Number of events
event_list (list): List of tuples where each tuple contains (priority, description)
Returns:
list: List of descriptions of events in the order they s... | def test_process_events_example_1():
input_data = "5\nhigh ServerReboot\ncritical NetworkFailure\nmedium DiskSpaceLow\nlow DailyBackup\nhigh SecurityBreach"
expected_output = ["NetworkFailure", "ServerReboot", "SecurityBreach", "DiskSpaceLow", "DailyBackup"]
assert event_prioritization(input_data) == expect... | [
{
"docstring": "Processes events based on their priorities.\n\nParameters:\nevent_count (int): Number of events\nevent_list (list): List of tuples where each tuple contains (priority, description)\n\nReturns:\nlist: List of descriptions of events in the order they should be processed",
"function_declaration... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_code_contests-i2i_50000_1739866719_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def process_events(event_count, event_list):\n \"\"\"\n Processes events based on their priorities.\n\n Parameters:\n event_count (int): Number... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00019710",
"row_id": 19710,
"seed_ids": "[8638]"
} | 0.480054 | Code_Contests_19710 | I | [
"process_events",
"parse_input",
"event_prioritization"
] | 3 | [
[
"event_prioritization",
"parse_input"
],
[
"event_prioritization",
"process_events"
]
] | 2 | [
"parse_input"
] | false | [] | false | pytest | false | [] | true | ee0eb25c6562c4ecca4efc3f6444667de2d05f55 | 5d2cf8c807d9bb6698ae7f071b2f3b12199cffba | |||
v1.0 | instruct | Code_Contests | Code_Contests_19864_I | You are given a sequence of N integers. Your task is to determine if it is possible to reorder this sequence such that every adjacent pair of elements in the reordered sequence are coprime (i.e., the greatest common divisor of the two elements is 1).
Constraints:
* All values in input are integers.
* 2 \leq N \leq 2 ... | from math import gcd
from itertools import permutations
def can_reorder_to_coprime_sequence(n, arr):
"""
Determine if the sequence can be reordered so that every adjacent pair of elements are coprime.
"""
def are_all_adjacent_pairs_coprime(seq):
return all(gcd(seq[i], seq[i + 1]) == 1 for i in ... | from solution import reorder_sequence
def test_example_1():
assert reorder_sequence(4, [5, 6, 7, 8]) == "YES\n5 6 7 8"
def test_example_2():
assert reorder_sequence(3, [4, 6, 8]) == "NO"
def test_all_elements_coprime():
assert reorder_sequence(3, [2, 3, 5]) == "YES\n2 3 5"
def test_no_possible_reorder()... | [
{
"docstring": "Determine if the sequence can be reordered so that every adjacent pair of elements are coprime.",
"function_declaration": "def can_reorder_to_coprime_sequence(n, arr):",
"function_name": "can_reorder_to_coprime_sequence",
"parameter_list": "(n, arr)"
},
{
"docstring": null,
... | [
0,
0,
0,
1,
1
] | 2 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_code_contests-i2i_50000_1739866719_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import sys\nfrom math import gcd\nfrom collections import defaultdict\n\ndef can_reorder_to_coprime_sequence(N, arr):\n def is_reorder_possible(arr):\n ... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "00019864",
"row_id": 19864,
"seed_ids": "[1542]"
} | 0.650076 | Code_Contests_19864 | I | [
"can_reorder_to_coprime_sequence",
"reorder_sequence"
] | 2 | [
[
"reorder_sequence",
"can_reorder_to_coprime_sequence"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 49bc8bca1b0fe9b3dbb0ae33a5db6fb4e55f0663 | f490660ebf8d680be9a6a11ab8c6792c6b234b71 | |||
v1.0 | instruct | Code_Contests | Code_Contests_19882_I | Given an integer n, find the smallest integer greater than n that consists of unique digits only. For example, if the input is 1234, the next integer with all unique digits would be 1235, since 1234 already consists of unique digits. However, if the input is 1233, the next such integer would be 1234.
Write a function ... | def is_unique(n):
"""Helper function to check if all digits in a number are unique."""
digits = str(n)
return len(set(digits)) == len(digits)
def next_unique_digit_number(n: int) -> int:
"""
Given an integer n, find the smallest integer greater than n that consists of unique digits only.
"""
... | from solution import next_unique_digit_number
def test_next_unique_digit_number_case1():
assert next_unique_digit_number(1234) == 1235
def test_next_unique_digit_number_case2():
assert next_unique_digit_number(1233) == 1234
def test_next_unique_digit_number_case3():
assert next_unique_digit_number(987) =... | [
{
"docstring": "Helper function to check if all digits in a number are unique.",
"function_declaration": "def is_unique(n):",
"function_name": "is_unique",
"parameter_list": "(n)"
},
{
"docstring": "Given an integer n, find the smallest integer greater than n that consists of unique digits o... | [
0,
0,
0,
0,
0,
0,
0,
0,
1,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_code_contests-i2i_50000_1739866719_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def has_unique_digits(number):\n digits = list(str(number))\n return len(digits) == len(set(digits))\n\ndef next_unique_digit_number(n: int) -> int:\... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00019882",
"row_id": 19882,
"seed_ids": "[1535]"
} | 0.601907 | Code_Contests_19882 | I | [
"is_unique",
"next_unique_digit_number"
] | 2 | [
[
"next_unique_digit_number",
"is_unique"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a486e85fdf2127575941f9d6d155814a9d9297f1 | 461e97d0bc273f48c9718d616c26468de1533b95 | |||
v1.0 | instruct | Code_Contests | Code_Contests_19918_I | Given a list of products with their names and prices, you are required to sort the list in decreasing order of prices. If two products have the same price, they should be ordered in lexicographical manner of their names.
Input format:
The first line contains an integer M, denoting the number of products. Each of the n... | def sort_products(products):
"""
Sorts the products in decreasing order of prices. If two products have the same price,
they are ordered lexicographically by their names.
:param products: List of tuples, each containing the name and price of a product.
:return: Sorted list of products.
"""
... | def test_sort_products():
# Test case 1
products = [("Banana", 1.50), ("Apple", 2.00), ("Orange", 1.50), ("Mango", 3.00)]
sorted_products = sort_products(products)
assert sorted_products == [("Mango", 3.00), ("Apple", 2.00), ("Banana", 1.50), ("Orange", 1.50)]
# Test case 2: Same price, different n... | [
{
"docstring": "Sorts the products in decreasing order of prices. If two products have the same price,\nthey are ordered lexicographically by their names.\n\n:param products: List of tuples, each containing the name and price of a product.\n:return: Sorted list of products.",
"function_declaration": "def so... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_code_contests-i2i_50000_1739866719_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def sort_products(products):\n \"\"\"\n Sort the list of products in decreasing order of prices.\n If two products have the same price, they shoul... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00019918",
"row_id": 19918,
"seed_ids": "[7885]"
} | 0.613576 | Code_Contests_19918 | I | [
"sort_products",
"get_sorted_product_list"
] | 2 | [
[
"get_sorted_product_list",
"sort_products"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | d4f8aa366a5c42084bd15b337737331db88e35be | fa7125ce8abcf16c6e118613b034da8651e6b59b | |||
v1.0 | instruct | Code_Contests | Code_Contests_19931_I | Pranav is organizing a marathon coding competition, and he needs a function to help with validating the results. Each participant will provide a solution for a series of coding problems, and the function will have to verify the results based on different criteria. Each problem in the marathon has a unique identifier Pi... | import math
def is_even(n):
return n % 2 == 0
def is_prime(n):
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 ... | from solution import validate_results
def test_validate_results():
assert validate_results(5, [
(1, 48),
(2, 23),
(3, 25),
(1, 35),
(2, 49)
]) == ["Valid", "Valid", "Valid", "Invalid", "Invalid"]
def test_even_scores():
assert validate_results(2, [
(1, 2... | [
{
"docstring": null,
"function_declaration": "def is_even(n):",
"function_name": "is_even",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": null,
"functi... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_code_contests-i2i_50000_1739866719_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\n\ndef validate_scores(t, scores):\n results = []\n \n def is_prime(n):\n if n <= 1:\n return False\n if n <=... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00019931",
"row_id": 19931,
"seed_ids": "[12461]"
} | 0.615414 | Code_Contests_19931 | I | [
"is_even",
"is_prime",
"is_perfect_square",
"validate_results"
] | 4 | [
[
"validate_results",
"is_even"
],
[
"validate_results",
"is_perfect_square"
],
[
"validate_results",
"is_prime"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 50d3ade9eaf842320fd82527d293e3a30e9960fe | f80710e578ea23f0249f46bbd89b8d3c99fa3267 | |||
v1.0 | instruct | Code_Contests | Code_Contests_19948_I | You're tasked with designing a solution for a warehouse robot. The warehouse is organized in a grid of cells with dimensions NxM. Certain cells in the grid are marked as inaccessible due to obstacles. The robot can move up, down, left, or right, but not diagonally, and it cannot move through obstacles. Write a program ... | from collections import deque
def min_moves_to_target(grid, N, M):
if grid[0][0] == '#' or grid[N-1][M-1] == '#':
return -1
# Directions for up, down, left, right
directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]
# BFS initialization
queue = deque([(0, 0, 0)]) # (row, col, distance... | def test_example_case():
input_data = "5 5\n.....\n.#...\n..#..\n...#.\n....."
assert solve(input_data) == 8
def test_no_path_case():
input_data = "3 3\n.#.\n###\n..#"
assert solve(input_data) == -1
def test_empty_grid_case():
input_data = "3 3\n...\n...\n..."
assert solve(input_data) == 4
de... | [
{
"docstring": null,
"function_declaration": "def min_moves_to_target(grid, N, M):",
"function_name": "min_moves_to_target",
"parameter_list": "(grid, N, M)"
},
{
"docstring": null,
"function_declaration": "def solve(input_data):",
"function_name": "solve",
"parameter_list": "(in... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_code_contests-i2i_50000_1739866719_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from collections import deque\n\ndef min_moves(N, M, grid):\n # Define directions: right, down, left, up\n directions = [(0, 1), (1, 0), (0, -1), (-1... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00019948",
"row_id": 19948,
"seed_ids": "[5805]"
} | 0.733558 | Code_Contests_19948 | I | [
"min_moves_to_target",
"solve"
] | 2 | [
[
"solve",
"min_moves_to_target"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | add1176013978f0831a4f0c0bd75a25c02794179 | 2dc8692994babb748cc73250f1464a3fff400c9d | |||
v1.0 | instruct | Code_Contests | Code_Contests_19959_I | Bob loves playing with magic squares. A magic square is an n x n grid filled with distinct numbers such that the sum of the numbers in each row, column, and diagonal is the same.
Bob wants to create a list of numbers that can be used to fill in a magic square. A number is considered "magic" if it is a prime number. Yo... | def is_prime(n):
"""
Returns True if n is a prime number, otherwise False.
"""
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
... | from solution import is_prime, generate_magic_numbers, process_input
def test_is_prime():
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(4) == False
assert is_prime(29) == True
assert is_prime(31) == True
assert is_prime(1) == False
assert is_prime(0) == False
def te... | [
{
"docstring": "Returns True if n is a prime number, otherwise False.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Returns a list of the first k prime numbers.",
"function_declaration": "def generate_magic_numbers(k... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_code_contests-i2i_50000_1739866719_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(n):\n \"\"\"\n Helper function to check if a number is prime.\n \"\"\"\n if n <= 1:\n return False\n if n == 2:\n ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00019959",
"row_id": 19959,
"seed_ids": "[4652]"
} | 0.635145 | Code_Contests_19959 | I | [
"is_prime",
"generate_magic_numbers",
"process_input"
] | 3 | [
[
"generate_magic_numbers",
"is_prime"
],
[
"process_input",
"generate_magic_numbers"
]
] | 2 | [
"process_input"
] | false | [] | false | pytest | true | [] | true | 2b31d6b4421ec4c02c0e2e7c643c0b70f44e3ea6 | 377413864c217955320a3a5dd7b4f99d4c29089d | |||
v1.0 | instruct | Code_Contests | Code_Contests_19988_I | You are an editor at a news aggregator website. You have access to an archive of articles, and each article's content starts with a headline followed by a series of tags unique to that article. Each article's headline is a string, and each tag is a lowercase string without spaces or punctuation. Your task is to support... | def find_matching_headlines(n, articles, q, queries):
results = []
for query in queries:
query_set = set(query)
matching_headlines = []
for article in articles:
headline, tags = article
if query_set.issubset(tags):
matching_headlines.... | from solution import process_articles_and_queries
def test_example():
n = 3
input_articles = [
["Article1", 3, "sports", "health", "wellness"],
["Article2", 2, "technology", "innovation"],
["Article3", 3, "health", "sports", "technology"],
]
q = 2
input_queries = [
[... | [
{
"docstring": null,
"function_declaration": "def find_matching_headlines(n, articles, q, queries):",
"function_name": "find_matching_headlines",
"parameter_list": "(n, articles, q, queries)"
},
{
"docstring": null,
"function_declaration": "def process_articles_and_queries(n, input_artic... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_code_contests-i2i_50000_1739866719_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def find_articles(n, articles, q, queries):\n \"\"\"\n Finds article headlines matching given queries.\n \n Args:\n - n (int): The number of... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00019988",
"row_id": 19988,
"seed_ids": "[3881]"
} | 0.572331 | Code_Contests_19988 | I | [
"find_matching_headlines",
"process_articles_and_queries"
] | 2 | [
[
"process_articles_and_queries",
"find_matching_headlines"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 8c199f7a61decae98ed12610f8fcd1341bfe63d2 | 8a3023812122c836718d6906a07cc33ad11d89fb | |||
v1.0 | instruct | Code_Contests | Code_Contests_20032_I | Ravi and Ragini love playing crossword puzzles, but Ravi loves prime numbers just as much. To challenge Ragini, he came up with an interesting game that involves prime numbers. He defined a special sequence called the "Cumulative Prime Sequence."
The Cumulative Prime Sequence is defined as follows:
- The first number ... | import itertools
def is_prime(num):
"""
Checks if a given number is prime.
"""
if num < 2:
return False
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
return False
return True
def get_first_n_primes(n):
"""
Returns the first n prime numbers.
""... | from solution import is_prime, get_first_n_primes, cumulative_prime_sequence, process_test_cases
def test_is_prime():
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(4) == False
assert is_prime(5) == True
assert is_prime(1) == False
def test_get_first_n_primes():
assert g... | [
{
"docstring": "Checks if a given number is prime.",
"function_declaration": "def is_prime(num):",
"function_name": "is_prime",
"parameter_list": "(num)"
},
{
"docstring": "Returns the first n prime numbers.",
"function_declaration": "def get_first_n_primes(n):",
"function_name": "ge... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_code_contests-i2i_50000_1739866719_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(num):\n if num <= 1:\n return False\n if num <= 3:\n return True\n if num % 2 == 0 or num % 3 == 0:\n return Fal... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00020032",
"row_id": 20032,
"seed_ids": "[1217]"
} | 0.606966 | Code_Contests_20032 | I | [
"is_prime",
"get_first_n_primes",
"cumulative_prime_sequence",
"process_test_cases"
] | 4 | [
[
"cumulative_prime_sequence",
"get_first_n_primes"
],
[
"get_first_n_primes",
"is_prime"
],
[
"process_test_cases",
"cumulative_prime_sequence"
]
] | 3 | [
"process_test_cases"
] | false | [] | false | pytest | true | [] | true | 19ed9c13e3cb987a55126d791dc394f1a8927a66 | 007b9fbddb02a4dab0cf719a5125031671653190 | |||
v1.0 | instruct | Code_Contests | Code_Contests_20125_I | Given a directed graph G(V, E), find the Strongly Connected Components (SCCs) of the graph.
A strongly connected component (SCC) of a directed graph is a maximal strongly connected subgraph. In other words, every vertex is reachable from every other vertex in the subgraph.
Constraints
* 1 ≤ |V| ≤ 100,000
* 0 ≤ |E| ≤... | from collections import defaultdict, deque
def kosaraju_scc(V, edges):
"""
Function to find and return strongly connected components in a given directed graph using Kosaraju's algorithm.
"""
def dfs_stack_order(v, graph, visited, stack):
visited.add(v)
for neighbor in graph[v]:
... | from solution import find_sccs
def test_find_sccs_example1():
V, E = 5, 5
edges = [(0, 1), (1, 2), (2, 0), (1, 3), (3, 4)]
expected_result = [[0, 1, 2], [3], [4]]
assert find_sccs(V, edges) == expected_result
def test_find_sccs_example2():
V, E = 5, 6
edges = [(0, 1), (1, 2), (2, 0), (1, 3), (... | [
{
"docstring": "Function to find and return strongly connected components in a given directed graph using Kosaraju's algorithm.",
"function_declaration": "def kosaraju_scc(V, edges):",
"function_name": "kosaraju_scc",
"parameter_list": "(V, edges)"
},
{
"docstring": null,
"function_decla... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_code_contests-i2i_50000_1739866719_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from collections import defaultdict, deque\n\ndef kosaraju_scc(V, E, edges):\n def dfs1(v):\n visited[v] = True\n for neighbor in graph[v]... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00020125",
"row_id": 20125,
"seed_ids": "[1565]"
} | 0.588322 | Code_Contests_20125 | I | [
"kosaraju_scc",
"find_sccs"
] | 2 | [
[
"find_sccs",
"kosaraju_scc"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 6d35e3c55d55ef4ce5ec03a59fb465da853971ff | 8982d173a053b33a85405a29ec4eec06039c4666 | |||
v1.0 | instruct | Code_Contests | Code_Contests_20175_I | You are given a sequence of N integers where 1 \leq i \leq N. Consider for this sequence all possible contiguous sub-sequences.
Your task is to find the maximum possible average of any contiguous sub-sequence.
Note that the average of a sub-sequence is defined as the sum of the elements in the sub-sequence divided by... | def max_average_subsequence(arr):
current_sum = max_sum = arr[0]
for num in arr[1:]:
if current_sum < 0:
current_sum = num
else:
current_sum += num
if current_sum > max_sum:
max_sum = current_sum
return max_sum
def max_possible_average(N... | from solution import max_possible_average
def test_max_possible_average_all_positive():
assert max_possible_average(5, [1, 2, 3, 4, 5]) == 15.0
def test_max_possible_average_mix():
assert max_possible_average(4, [1, 12, -5, -6]) == 13.0
def test_max_possible_average_all_negative():
assert max_possible_av... | [
{
"docstring": null,
"function_declaration": "def max_average_subsequence(arr):",
"function_name": "max_average_subsequence",
"parameter_list": "(arr)"
},
{
"docstring": null,
"function_declaration": "def max_possible_average(N, A):",
"function_name": "max_possible_average",
"par... | [
0,
0,
0,
0,
0,
0,
1,
0,
0
] | 1 | hard | 0.111 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_code_contests-i2i_50000_1739866719_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def max_average_subsequence(N, A):\n \"\"\"\n Finds the maximum possible average of any contiguous sub-sequence.\n \n Args:\n N: int: Length... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00020175",
"row_id": 20175,
"seed_ids": "[603]"
} | 0.625854 | Code_Contests_20175 | I | [
"max_average_subsequence",
"max_possible_average"
] | 2 | [
[
"max_possible_average",
"max_average_subsequence"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 88b856f30acc571c79d454ddbae2b96f32960fe3 | cbf0da15fc9de5036264ea838b4caa9c8976cc44 | |||
v1.0 | instruct | Code_Contests | Code_Contests_20219_I | In a mountainous area, there are N villages connected by M roads. Each road connects exactly two villages and is bidirectional. During winter, the villages experience severe snowfall, and certain roads can become blocked.
You are tasked with ensuring that essential supplies can still be transported between a primary v... | from collections import defaultdict, deque
def find_min_roads_to_clear(N, M, V1, V2, roads):
def bfs(start, end):
visited = [False] * (N + 1)
distance = [float('inf')] * (N + 1)
queue = deque([start])
visited[start] = True
distance[start] = 0
while queue:
... | from solution import min_roads_to_clear
def test_case_1():
N, M = 5, 4
V1, V2 = 1, 5
roads = [(1, 2), (2, 3), (3, 4), (4, 5)]
assert min_roads_to_clear(N, M, V1, V2, roads) == 4
def test_case_2():
N, M = 6, 5
V1, V2 = 1, 6
roads = [(1, 2), (2, 3), (3, 4), (4, 5), (5, 6)]
assert min_roa... | [
{
"docstring": null,
"function_declaration": "def find_min_roads_to_clear(N, M, V1, V2, roads):",
"function_name": "find_min_roads_to_clear",
"parameter_list": "(N, M, V1, V2, roads)"
},
{
"docstring": null,
"function_declaration": "def min_roads_to_clear(N, M, V1, V2, edges):",
"fun... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_code_contests-i2i_50000_1739866719_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from collections import deque, defaultdict\n\ndef min_roads_to_clear(N, M, V1, V2, roads):\n if V1 == V2:\n return 0\n \n graph = defaultdi... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00020219",
"row_id": 20219,
"seed_ids": "[10389]"
} | 0.694028 | Code_Contests_20219 | I | [
"find_min_roads_to_clear",
"min_roads_to_clear"
] | 2 | [
[
"min_roads_to_clear",
"find_min_roads_to_clear"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 21c73b29408191027c2d237e6dc8a4596481a81a | a26ad7cf457c2dc0900d7995ac2a83dda0d34b70 | |||
v1.0 | instruct | Code_Contests | Code_Contests_20221_I | Consider an undirected graph with N nodes numbered 1 through N and M edges. Each edge connects two distinct nodes A and B, and has a weight W. Determine if it is possible to remove at most K edges so that the graph becomes a tree (a connected graph with no cycles).
Constraints
* 1 ≤ N ≤ 10^5
* 0 ≤ M ≤ 2 * 10^5
* 0 ≤ ... | def can_be_tree(N, M, K, edges):
"""
Determines if it is possible to remove at most K edges so that the graph becomes a tree.
A tree must have exactly N-1 edges and no cycles.
"""
# A tree needs exactly N-1 edges to be connected and acyclic.
min_required_edges = N - 1
# If there are les... | def test_can_be_tree_case1():
N, M, K = 4, 3, 1
edges = [(1, 2, 4), (2, 3, 2), (3, 4, 3)]
assert can_be_tree(N, M, K, edges) == "Yes"
def test_can_be_tree_case2():
N, M, K = 4, 5, 0
edges = [(1, 2, 1), (1, 3, 2), (1, 4, 3), (2, 3, 4), (2, 4, 5)]
assert can_be_tree(N, M, K, edges) == "No"
def t... | [
{
"docstring": "Determines if it is possible to remove at most K edges so that the graph becomes a tree.\nA tree must have exactly N-1 edges and no cycles.",
"function_declaration": "def can_be_tree(N, M, K, edges):",
"function_name": "can_be_tree",
"parameter_list": "(N, M, K, edges)"
},
{
... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_code_contests-i2i_50000_1739866719_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def can_become_tree(n, m, k, edges):\n # Our target is to check if we can remove k edges to make the graph a tree\n # A tree has exactly N-1 edges an... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00020221",
"row_id": 20221,
"seed_ids": "[12367]"
} | 0.721729 | Code_Contests_20221 | I | [
"can_be_tree",
"solve"
] | 2 | [
[
"solve",
"can_be_tree"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 96df64cffb24d156a60311982747aaa6869bda6a | e089f3e25be1455d39798713194280e6d3ed5971 | |||
v1.0 | instruct | Code_Contests | Code_Contests_20267_I | You are developing a simple spreadsheet application and need to implement a function to manage cell dependencies. Each cell can contain a numerical value or an expression involving other cells. The expressions use basic arithmetic operators (+, -, *, /), and cells are referenced by a letter for the column (A-Z) followe... | def token_to_value(token, cells):
if token.isdigit() or (token.startswith('-') and token[1:].isdigit()):
return int(token)
else:
return cells[token]
def evaluate_expression(expression, cells):
tokens = expression.replace('+', ' + ').replace('-', ' - ').replace('*', ' * ').replace('/', ' / '... | from solution import evaluate_spreadsheet
def test_single_number():
assert evaluate_spreadsheet(1, ["A1 5"], "A1") == 5
def test_simple_addition():
assert evaluate_spreadsheet(3, ["A1 5", "A2 3", "B1 A1+A2"], "B1") == 8
def test_simple_multiplication():
assert evaluate_spreadsheet(4, ["A1 5", "A2 3", "B1... | [
{
"docstring": null,
"function_declaration": "def token_to_value(token, cells):",
"function_name": "token_to_value",
"parameter_list": "(token, cells)"
},
{
"docstring": null,
"function_declaration": "def evaluate_expression(expression, cells):",
"function_name": "evaluate_expression... | [
0,
0,
0,
1,
0
] | 1 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_code_contests-i2i_50000_1739866719_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def evaluate_expression(expression, cell_values):\n \"\"\"\n Evaluates an arithmetic expression that may contain cell references.\n \"\"\"\n im... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "00020267",
"row_id": 20267,
"seed_ids": "[5093]"
} | 0.456121 | Code_Contests_20267 | I | [
"token_to_value",
"evaluate_expression",
"evaluate_spreadsheet"
] | 3 | [
[
"evaluate_expression",
"token_to_value"
],
[
"evaluate_spreadsheet",
"evaluate_expression"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | a1160169efd7e132c079127e34944a25d008a257 | 3fc5e1d36823f596eca51566a44be8f1bfa930be | |||
v1.0 | instruct | Code_Contests | Code_Contests_20329_I | A team of archaeologists has discovered an ancient binary cipher in a newly excavated site. The cipher consists of a sequence of binary strings written on a stone tablet. The researchers have determined that each sequence represents a set of instructions to operate an ancient device. Each binary string, when interprete... | import math
from functools import reduce
def binary_to_decimal(binary_str):
"""
Converts a binary string to its decimal equivalent.
"""
return int(binary_str, 2)
def gcd_of_list(numbers):
"""
Computes the GCD of a list of numbers.
"""
return reduce(math.gcd, numbers)
def device_activa... | from solution import binary_to_decimal, gcd_of_list, device_activation_time
def test_binary_to_decimal():
assert binary_to_decimal("110") == 6
assert binary_to_decimal("1010") == 10
assert binary_to_decimal("1001") == 9
assert binary_to_decimal("0") == 0
assert binary_to_decimal("1") == 1
def test... | [
{
"docstring": "Converts a binary string to its decimal equivalent.",
"function_declaration": "def binary_to_decimal(binary_str):",
"function_name": "binary_to_decimal",
"parameter_list": "(binary_str)"
},
{
"docstring": "Computes the GCD of a list of numbers.",
"function_declaration": "... | [
0,
0,
0,
0,
0,
1,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_code_contests-i2i_50000_1739866719_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\nfrom functools import reduce\n\ndef gcd_of_binaries(bin_strings):\n def binary_to_decimal(binary_str):\n \"\"\"\n Converts a ... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "00020329",
"row_id": 20329,
"seed_ids": "[12710]"
} | 0.5634 | Code_Contests_20329 | I | [
"binary_to_decimal",
"gcd_of_list",
"device_activation_time"
] | 3 | [
[
"device_activation_time",
"binary_to_decimal"
],
[
"device_activation_time",
"gcd_of_list"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | e37c9fd84ef2f9dd28adccf7d4c505de93367b00 | 0b2134e0cb194038b681f1e36c263f1b6b76a087 | |||
v1.0 | instruct | Code_Contests | Code_Contests_20331_I | Sarah loves programming and solving puzzles. She also enjoys going on hikes. Sarah created a unique way to challenge herself on the trails: she picks a positive integer $n$ at the start of her hike and attempts to divide it by certain integers while following specific rules.
Here are the steps she follows:
1. Start wi... | def min_steps_to_stop(n):
"""
Returns the minimum number of steps to reduce n such that it is no longer divisible by 2, 3, or 4.
"""
steps = 0
while n % 2 == 0 or n % 3 == 0 or n % 4 == 0:
if n % 4 == 0:
n //= 4
elif n % 3 == 0:
n //= 3
else:
... | from solution import min_steps_to_stop, min_steps_for_cases
def test_min_steps_to_stop():
assert min_steps_to_stop(10) == 1
assert min_steps_to_stop(15) == 1
assert min_steps_to_stop(24) == 3
assert min_steps_to_stop(1) == 0
assert min_steps_to_stop(2) == 1
assert min_steps_to_stop(3) == 1
... | [
{
"docstring": "Returns the minimum number of steps to reduce n such that it is no longer divisible by 2, 3, or 4.",
"function_declaration": "def min_steps_to_stop(n):",
"function_name": "min_steps_to_stop",
"parameter_list": "(n)"
},
{
"docstring": "Returns the results for multiple test cas... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_code_contests-i2i_50000_1739866719_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def min_steps_to_stop(n):\n \"\"\"\n Returns the minimum number of steps to reduce n such that it is no longer divisible by 2, 3, or 4.\n \"\"\"\n... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00020331",
"row_id": 20331,
"seed_ids": "[730]"
} | 0.662361 | Code_Contests_20331 | I | [
"min_steps_to_stop",
"min_steps_for_cases",
"process_input_output"
] | 3 | [
[
"min_steps_for_cases",
"min_steps_to_stop"
],
[
"process_input_output",
"min_steps_for_cases"
]
] | 2 | [
"process_input_output"
] | false | [] | false | pytest | true | [] | true | d5bf7e55eb6c7b5fb2e17528906784f7d59ba2ba | 760068cc88eaecfa97f3dedee12140d1615f87f6 | |||
v1.0 | instruct | Code_Contests | Code_Contests_20379_I | In a country with n cities and m bidirectional roads, a traveler wants to move from city 1 to city n. Each road has a time (in minutes) it takes to travel from one city to another and a cost (in dollars) associated with it.
The traveler has a limited budget, k dollars, and can only use the roads that cumulatively cost... | import heapq
from collections import defaultdict
def min_time_to_travel(n, m, k, roads):
# Create a graph dictionary
graph = defaultdict(list)
for u, v, t, c in roads:
graph[u].append((v, t, c))
graph[v].append((u, t, c))
# Min-Heap to store (total time, current city, total cost)
h... | from solution import travel_time_with_budget
def test_example_1():
input_data = "5 7 10\n1 2 3 4\n1 3 5 2\n2 3 2 5\n2 4 6 3\n3 4 1 4\n3 5 4 6\n4 5 2 8\n"
assert travel_time_with_budget(input_data) == 9
def test_example_2():
input_data = "4 4 5\n1 2 4 3\n2 3 2 2\n3 4 3 1\n1 4 10 6\n"
assert travel_time... | [
{
"docstring": null,
"function_declaration": "def min_time_to_travel(n, m, k, roads):",
"function_name": "min_time_to_travel",
"parameter_list": "(n, m, k, roads)"
},
{
"docstring": null,
"function_declaration": "def travel_time_with_budget(input_string):",
"function_name": "travel_t... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_code_contests-i2i_50000_1739866719_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import heapq\n\ndef min_travel_time(n, m, k, roads):\n # Adjacency list for the cities\n graph = [[] for _ in range(n + 1)]\n \n for u, v, t, c... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00020379",
"row_id": 20379,
"seed_ids": "[10997]"
} | 0.817631 | Code_Contests_20379 | I | [
"min_time_to_travel",
"travel_time_with_budget"
] | 2 | [
[
"travel_time_with_budget",
"min_time_to_travel"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 5c7816554ccb0650ad63507e890462a1dbdfa6e1 | e10353d432a860c7011292cdec044465d20ab747 | |||
v1.0 | instruct | Code_Contests | Code_Contests_20407_I | You are helping a researcher organize data for a database of the physical properties of stars. Each star is represented as a point in 3-dimensional space with coordinates (x, y, z). The researcher wants to group the stars into clusters such that the distance between any two stars within a cluster does not exceed a give... | import math
from collections import deque
def distance(star1, star2):
return math.sqrt((star1[0] - star2[0])**2 + (star1[1] - star2[1])**2 + (star1[2] - star2[2])**2)
def find_clusters(stars, n, d):
visited = [False] * n
clusters = 0
def bfs(start):
q = deque([start])
visited[star... | from solution import minimum_clusters
def test_example_case():
n = 5
d = 2.0
coordinates = [
(1.0, 2.0, 3.0),
(2.0, 2.0, 3.0),
(3.0, 2.0, 3.0),
(5.0, 5.0, 5.0),
(6.0, 5.0, 5.0)
]
assert minimum_clusters(n, d, coordinates) == 2
def test_single_star():
n =... | [
{
"docstring": null,
"function_declaration": "def distance(star1, star2):",
"function_name": "distance",
"parameter_list": "(star1, star2)"
},
{
"docstring": null,
"function_declaration": "def find_clusters(stars, n, d):",
"function_name": "find_clusters",
"parameter_list": "(sta... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_code_contests-i2i_50000_1739866719_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\nfrom collections import deque\n\ndef distance(star1, star2):\n return math.sqrt((star1[0] - star2[0])**2 + (star1[1] - star2[1])**2 + (star... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00020407",
"row_id": 20407,
"seed_ids": "[11601]"
} | 0.661107 | Code_Contests_20407 | I | [
"distance",
"find_clusters",
"minimum_clusters"
] | 3 | [
[
"find_clusters",
"distance"
],
[
"minimum_clusters",
"find_clusters"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 7718d7ca69c50141edd290fd60c410e2116c923e | ef91c4e203c104fafaf86683d31a2d003d957b0f | |||
v1.0 | instruct | Code_Contests | Code_Contests_20411_I | John loves playing with numbers. Recently, he came across a special type of number known as an Armstrong number. An Armstrong number for a given number of digits is an integer such that the sum of its own digits each raised to the power of the number of digits is equal to the number itself. For example, 153 is an Armst... | def is_armstrong_number(number):
"""
Check if a given number is an Armstrong number.
"""
digits = list(map(int, str(number)))
power = len(digits)
sum_of_powers = sum(digit ** power for digit in digits)
return sum_of_powers == number
def check_armstrong_numbers(count, numbers):
"""
R... | from solution import is_armstrong_number, check_armstrong_numbers
def test_is_armstrong_number():
assert is_armstrong_number(153) == True
assert is_armstrong_number(9474) == True
assert is_armstrong_number(123) == False
assert is_armstrong_number(0) == True
assert is_armstrong_number(1) == True
... | [
{
"docstring": "Check if a given number is an Armstrong number.",
"function_declaration": "def is_armstrong_number(number):",
"function_name": "is_armstrong_number",
"parameter_list": "(number)"
},
{
"docstring": "Return a list of \"YES\" or \"NO\" based on whether each number in numbers is ... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_code_contests-i2i_50000_1739866719_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_armstrong_number(num):\n \"\"\"\n Checks if a number is an Armstrong number.\n \n Args:\n num: int. The number to check.\n \n R... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00020411",
"row_id": 20411,
"seed_ids": "[6528]"
} | 0.488 | Code_Contests_20411 | I | [
"is_armstrong_number",
"check_armstrong_numbers"
] | 2 | [
[
"check_armstrong_numbers",
"is_armstrong_number"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | db77eae0040197a993e8e20a6d05a8d8cf8aecc5 | 862007b9ff7683b7a47d7a409fe84de7b0eb36eb | |||
v1.0 | instruct | Code_Contests | Code_Contests_20429_I | A company has a network of centralized servers. Each server is represented by a node, and each connection between servers is represented by an undirected and weighted edge. The network is represented as an undirected graph with n nodes (numbered from 1 to n) and m edges. You are required to deploy a monitoring system o... | def min_cost_to_monitor_network(n, m, costs, connections):
from collections import defaultdict
import sys
# Step 1: Create the graph using adjacency list representation
graph = defaultdict(list)
for u, v in connections:
graph[u].append(v)
graph[v].append(u)
vis... | def test_simple_case():
assert solve(4, 3, [4, 2, 6, 3], [(1, 2), (2, 3), (3, 4)]) == 2
def test_disconnected_case():
assert solve(6, 4, [4, 6, 3, 5, 8, 3], [(1, 2), (3, 4), (4, 5), (5, 6)]) == 7
def test_fully_connected_case():
assert solve(4, 6, [1, 2, 3, 4], [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3,... | [
{
"docstring": null,
"function_declaration": "def min_cost_to_monitor_network(n, m, costs, connections):",
"function_name": "min_cost_to_monitor_network",
"parameter_list": "(n, m, costs, connections)"
},
{
"docstring": null,
"function_declaration": "def solve(n, m, costs, connections):"... | [
0,
0,
0,
0,
0,
0,
0,
0,
1
] | 1 | hard | 0.111 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_code_contests-i2i_50000_1739866719_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def find_min_cost(n, m, costs, edges):\n from heapq import heappop, heappush\n from collections import defaultdict\n \n # Use union-find to fin... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00020429",
"row_id": 20429,
"seed_ids": "[8755]"
} | 0.686054 | Code_Contests_20429 | I | [
"min_cost_to_monitor_network",
"solve"
] | 2 | [
[
"solve",
"min_cost_to_monitor_network"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | da8b79fab388f1e6f799585247ba4a4439321af5 | 2c0516dfd86d2961ef5400a8b626319593285964 | |||
v1.0 | instruct | Code_Contests | Code_Contests_20435_I | You are given a list of integers. You need to implement a function that modifies the list such that the primes in the list are replaced by their next prime number greater than the original, and non-prime numbers remain unchanged.
A prime number is a natural number greater than 1 that has no positive divisors other tha... | def is_prime(n):
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
def next_prime(n):
if n <= 1:
retu... | from solution import replace_primes_with_next
def test_replace_primes_with_next():
assert replace_primes_with_next([3, 4, 11, 20]) == [5, 4, 13, 20]
assert replace_primes_with_next([7, 2, 15]) == [11, 3, 15]
assert replace_primes_with_next([1, 22, 13, 29, 30]) == [1, 22, 17, 31, 30]
assert replace_prim... | [
{
"docstring": null,
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def next_prime(n):",
"function_name": "next_prime",
"parameter_list": "(n)"
},
{
"docstring": null,
"... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_code_contests-i2i_50000_1739866719_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(n):\n \"\"\"\n Returns True if n is a prime number, False otherwise.\n \"\"\"\n if n <= 1:\n return False\n if n <= 3:\n... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00020435",
"row_id": 20435,
"seed_ids": "[4197]"
} | 0.58067 | Code_Contests_20435 | I | [
"is_prime",
"next_prime",
"replace_primes_with_next"
] | 3 | [
[
"next_prime",
"is_prime"
],
[
"replace_primes_with_next",
"is_prime"
],
[
"replace_primes_with_next",
"next_prime"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 8d2922d5f983e756a208373ee3481f0e12625c4c | 0eb45e79d8cf252cf7b5068f0080c90e9c14b2fb | |||
v1.0 | instruct | Code_Contests | Code_Contests_20469_I | A factory has an assembly line where robots build products. Each product goes through a specific number of stages, and each stage is assigned to a segment in the assembly line. Each robot covers a range of segments, where it can operate on any stage within those segments. The robots work simultaneously and independentl... | def min_robots_required(n, m, stages, robots):
segments = [0] * 1001
for stage in stages:
segments[stage] += 1
# Only consider segments that are actually used
relevant_segments = [i for i, count in enumerate(segments) if count > 0]
# If there are no stages, no robot is needed
... | from solution import process_assembly_line
def test_case_1():
assert process_assembly_line(8, 3, [3, 1, 4, 5, 2, 6, 8, 7], [(1, 5), (4, 8), (2, 6)]) == 2
def test_case_2():
assert process_assembly_line(5, 2, [1, 2, 3, 4, 5], [(2, 3), (3, 4)]) == -1
def test_case_3():
assert process_assembly_line(6, 4, [2... | [
{
"docstring": null,
"function_declaration": "def min_robots_required(n, m, stages, robots):",
"function_name": "min_robots_required",
"parameter_list": "(n, m, stages, robots)"
},
{
"docstring": null,
"function_declaration": "def process_assembly_line(n, m, segments, robots_ranges):",
... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_code_contests-i2i_50000_1739866719_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def min_robots_required(n, m, stage_segments, robot_ranges):\n stages_needed = set(stage_segments)\n robots_covering_segment = [set() for _ in range(... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00020469",
"row_id": 20469,
"seed_ids": "[9949]"
} | 0.717307 | Code_Contests_20469 | I | [
"min_robots_required",
"process_assembly_line"
] | 2 | [
[
"process_assembly_line",
"min_robots_required"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | d039d54c21e8ab44af500a2dbee7221f6bccd070 | 2e35b4f43b75518b92597b183b34c7431aac1201 | |||
v1.0 | instruct | Code_Contests | Code_Contests_20501_I | Write a program that takes an integer input N and prints the smallest palindrome number that is greater than N. A palindrome number is a number that remains the same when its digits are reversed.
Input
The first line contains an integer T, the total number of test cases. Each of the next T lines contains an integer N... | def is_palindrome(n):
"""
Helper function to check if a number is a palindrome.
"""
s = str(n)
return s == s[::-1]
def next_palindrome(n):
"""
Finds the smallest palindrome number greater than n.
"""
n += 1
while not is_palindrome(n):
n += 1
return n
def find_next_p... | def test_is_palindrome():
assert is_palindrome(121) == True
assert is_palindrome(123) == False
assert is_palindrome(99) == True
assert is_palindrome(101) == True
def test_next_palindrome():
assert next_palindrome(123) == 131
assert next_palindrome(808) == 818
assert next_palindrome(999) == ... | [
{
"docstring": "Helper function to check if a number is a palindrome.",
"function_declaration": "def is_palindrome(n):",
"function_name": "is_palindrome",
"parameter_list": "(n)"
},
{
"docstring": "Finds the smallest palindrome number greater than n.",
"function_declaration": "def next_p... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_code_contests-i2i_50000_1739866719_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_palindrome(number):\n \"\"\"\n Check if a given number is a palindrome.\n \"\"\"\n return str(number) == str(number)[::-1]\n\ndef next_p... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00020501",
"row_id": 20501,
"seed_ids": "[7084]"
} | 0.868024 | Code_Contests_20501 | I | [
"is_palindrome",
"next_palindrome",
"find_next_palindromes"
] | 3 | [
[
"find_next_palindromes",
"next_palindrome"
],
[
"next_palindrome",
"is_palindrome"
]
] | 2 | [] | false | [] | false | pytest | false | [] | true | c2a5944a1ac22e9924b8168ce64a46e2d332490a | a7f2d262a10915acb2271377bb70d0ed222bcff0 | |||
v1.0 | instruct | Code_Contests | Code_Contests_20666_I | Given a dataset of product reviews, each review contains an identifier, a product name, and the review text. For the purpose of this problem, each product belongs to one of four categories: 1 for Electronics, 2 for Home Appliances, 3 for Books, and 4 for Clothing.
You can download the training set of reviews from the... | from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.naive_bayes import MultinomialNB
import os
import zipfile
import requests
from io import BytesIO
# Define paths to the dataset directories
URL = 'http://example.com/train.zip'
CATEGORIES = ['Electronics', 'Home Appliances', 'Books', 'Clothing']
... | # Due to constraints, we use mock functions within the test environment
import pytest
from unittest.mock import patch, mock_open
from solution import classify_review
def mock_download_and_extract(*args, **kwargs):
pass # As we're mocking, no need to download anything
def mock_load_training_data():
# Simulat... | [
{
"docstring": null,
"function_declaration": "def download_and_extract(url):",
"function_name": "download_and_extract",
"parameter_list": "(url)"
},
{
"docstring": null,
"function_declaration": "def load_training_data():",
"function_name": "load_training_data",
"parameter_list": ... | [
0,
0,
0,
0,
0,
0,
0,
0,
1,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_code_contests-i2i_50000_1739866719_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\nimport re\nfrom collections import defaultdict\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.naive_bayes import Mul... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00020666",
"row_id": 20666,
"seed_ids": "[11905]"
} | 0.485392 | Code_Contests_20666 | I | [
"download_and_extract",
"load_training_data",
"preprocess_and_train",
"predict_category",
"classify_review"
] | 5 | [
[
"classify_review",
"download_and_extract"
],
[
"classify_review",
"load_training_data"
],
[
"classify_review",
"predict_category"
],
[
"classify_review",
"preprocess_and_train"
]
] | 4 | [] | false | [] | false | pytest | true | [
"requests",
"sklearn"
] | false | f2c3e61ca63629173a9540cb731fafc5943b29d8 | acf49b33617248a5f70d621d97b0b370f38b2ca9 | |||
v1.0 | instruct | Code_Contests | Code_Contests_20672_I | In a network of computers, some pairs of computers are directly connected through a cable. The network can be represented as an undirected graph, with computers as nodes and cables as edges. Evaluate the network structure to identify the longest possible path within the network, where the length of a path is defined as... | from collections import defaultdict, deque
def find_farthest_node(start_node, adj_list):
visited = set()
q = deque([(start_node, 0)]) # (node, distance)
farthest_node = start_node
max_distance = 0
visited.add(start_node)
while q:
current_node, distance = q.popleft()
if distanc... | from solution import longest_path
def test_single_edge():
assert longest_path(2, 1, [(1, 2)]) == 1
def test_no_edges():
assert longest_path(5, 0, []) == 0
def test_example_1():
assert longest_path(4, 3, [(1, 2), (2, 3), (3, 4)]) == 3
def test_example_2():
assert longest_path(5, 4, [(1, 2), (1, 3), (... | [
{
"docstring": null,
"function_declaration": "def find_farthest_node(start_node, adj_list):",
"function_name": "find_farthest_node",
"parameter_list": "(start_node, adj_list)"
},
{
"docstring": null,
"function_declaration": "def longest_path(N, M, edges):",
"function_name": "longest_... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_code_contests-i2i_50000_1739866719_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from collections import defaultdict, deque\n\ndef longest_path(n, edges):\n graph = defaultdict(list)\n for u, v in edges:\n graph[u].append(v... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00020672",
"row_id": 20672,
"seed_ids": "[7476]"
} | 0.698494 | Code_Contests_20672 | I | [
"find_farthest_node",
"longest_path"
] | 2 | [
[
"longest_path",
"find_farthest_node"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | da79cd039257178bff481a07ab886ddc1ac766ee | 7f6ffd4e90a1d3ef8945a3073c923e55f3418b9a | |||
v1.0 | instruct | Code_Contests | Code_Contests_20684_I | Alice has recently got interested in mathematics, especially prime numbers. She was given a sequence of integers and was asked to find the largest prime number in the sequence. However, Alice is a beginner and needs your help to solve this problem.
Input
The first line contains an integer n (1 ≤ n ≤ 105), representin... | def is_prime(num):
"""
Returns True if num is a prime number, otherwise False.
"""
if num <= 1:
return False
if num <= 3:
return True
if num % 2 == 0 or num % 3 == 0:
return False
i = 5
while i * i <= num:
if num % i == 0 or num % (i + 2) == 0:
... | from solution import is_prime, largest_prime_in_sequence
def test_is_prime():
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(4) == False
assert is_prime(5) == True
assert is_prime(1) == False
assert is_prime(0) == False
assert is_prime(17) == True
assert is_prime(... | [
{
"docstring": "Returns True if num is a prime number, otherwise False.",
"function_declaration": "def is_prime(num):",
"function_name": "is_prime",
"parameter_list": "(num)"
},
{
"docstring": "Returns the largest prime number in the given sequence.\nIf there are no prime numbers, returns -1... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_code_contests-i2i_50000_1739866719_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(n):\n \"\"\"\n Returns True if n is a prime number, False otherwise.\n \"\"\"\n if n <= 1:\n return False\n if n <= 3:\n... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00020684",
"row_id": 20684,
"seed_ids": "[12949]"
} | 0.625622 | Code_Contests_20684 | I | [
"is_prime",
"largest_prime_in_sequence"
] | 2 | [
[
"largest_prime_in_sequence",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | cff51d7cb1b469ce7be454dc80ccc5c25533f0eb | ef66cb091d464b728ca47d5906a72d97db7f7535 | |||
v1.0 | instruct | Code_Contests | Code_Contests_20707_I | Alice is an avid gardener and loves arranging flowers in her garden. She has a rectangular garden of size n x m (n rows and m columns). Each cell in the garden can contain one type of flower or be empty. The flowers in Alice's garden are represented by distinct uppercase letters ('A' to 'Z'), and the empty cells are re... | def rotate_90_degrees(garden, n, m):
return [[garden[n - 1 - i][j] for i in range(n)] for j in range(m)]
def rotate_garden(n, m, garden, k):
k = k % 4 # Since 4 rotations result in the same pattern
for _ in range(k):
garden = rotate_90_degrees(garden, n, m)
n, m = m, n
return garden | from solution import rotate_garden
def test_rotate_garden_once():
n = 4
m = 3
garden = [
['A', 'B', 'C'],
['D', 'E', 'F'],
['G', 'H', 'I'],
['J', 'K', 'L']
]
k = 1
expected = [
['J', 'G', 'D', 'A'],
['K', 'H', 'E', 'B'],
['L', 'I', 'F', 'C... | [
{
"docstring": null,
"function_declaration": "def rotate_90_degrees(garden, n, m):",
"function_name": "rotate_90_degrees",
"parameter_list": "(garden, n, m)"
},
{
"docstring": null,
"function_declaration": "def rotate_garden(n, m, garden, k):",
"function_name": "rotate_garden",
"... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_code_contests-i2i_50000_1739866719_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def rotate_garden(n, m, garden, k):\n \"\"\"\n Rotates the garden 90 degrees clockwise k times.\n \"\"\"\n def rotate_90_clockwise(grid):\n ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00020707",
"row_id": 20707,
"seed_ids": "[3061]"
} | 0.650571 | Code_Contests_20707 | I | [
"rotate_90_degrees",
"rotate_garden"
] | 2 | [
[
"rotate_garden",
"rotate_90_degrees"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a3441037949e683107d1e59b8a7424f9208cf881 | 64f1a207db33d4a0ac5c58abd66eddcb355c476c | |||
v1.0 | instruct | Code_Contests | Code_Contests_20742_I | A city grid consists of n x n intersections. At each intersection, there is a building with a certain height given in a matrix of integers where the elevation matrix[i][j] represents the height of the building at the i-th row and j-th column.
A robot starts at the top-left corner of the grid (0, 0) and its goal is to ... | def min_energy_path(grid):
import heapq
if not grid or not grid[0]:
return 0
n = len(grid)
directions = [(0, 1), (1, 0)] # Only right and down movements
heap = [(0, 0, 0)] # (energy, x, y)
visited = set((0, 0))
energy_matrix = [[float('inf')] * n for _ in range(n)]
en... | from solution import min_energy_path
def test_min_energy_path_1():
grid = [
[1, 3, 2],
[4, 3, 8],
[5, 3, 1]
]
assert min_energy_path(grid) == 4
def test_min_energy_path_2():
grid = [
[1, 2],
[3, 4]
]
assert min_energy_path(grid) == 3
def test_min_energy... | [
{
"docstring": null,
"function_declaration": "def min_energy_path(grid):",
"function_name": "min_energy_path",
"parameter_list": "(grid)"
},
{
"docstring": null,
"function_declaration": "def read_input_and_compute_min_energy():",
"function_name": "read_input_and_compute_min_energy",
... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_code_contests-i2i_50000_1739866719_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def min_energy(n, elevation):\n \"\"\"\n Finds the minimum energy required for the robot to traverse from the top-left corner\n to the bottom-righ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00020742",
"row_id": 20742,
"seed_ids": "[11586]"
} | 0.660822 | Code_Contests_20742 | I | [
"min_energy_path",
"read_input_and_compute_min_energy"
] | 2 | [
[
"read_input_and_compute_min_energy",
"min_energy_path"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f0162368732b588cef652f70b4cd72b738b332bd | d6bb7574586c2d16ab6713859413d191073240ea | |||
v1.0 | instruct | Code_Contests | Code_Contests_20789_I | You are given a sequence of brackets. Your task is to determine whether the sequence is valid. A valid sequence of brackets is one where every opening bracket has a corresponding closing bracket and the brackets are properly nested.
The following constraints apply:
- The brackets are limited to the characters '(', ')'... | def isValid(sequence):
"""
Returns 'Valid' if the bracket sequence is valid, otherwise 'Invalid'.
"""
stack = []
close_map = {')': '(', '}': '{', ']': '['}
for char in sequence:
if char in close_map.values():
stack.append(char)
elif char in close_map.keys():
... | from solution import isValid, validate_sequences
def test_isValid():
assert isValid("()") == "Valid"
assert isValid("()[]{}") == "Valid"
assert isValid("({[]})") == "Valid"
assert isValid("(]") == "Invalid"
assert isValid("([)]") == "Invalid"
assert isValid("") == "Valid"
assert isValid("((... | [
{
"docstring": "Returns 'Valid' if the bracket sequence is valid, otherwise 'Invalid'.",
"function_declaration": "def isValid(sequence):",
"function_name": "isValid",
"parameter_list": "(sequence)"
},
{
"docstring": "Takes a list of bracket sequences and returns a list with \"Valid\" or \"In... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_code_contests-i2i_50000_1739866719_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def isValid(sequence):\n \"\"\"\n Returns 'Valid' if the bracket sequence is valid, otherwise 'Invalid'.\n \"\"\"\n stack = []\n close_map =... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00020789",
"row_id": 20789,
"seed_ids": "[2182]"
} | 0.718913 | Code_Contests_20789 | I | [
"isValid",
"validate_sequences"
] | 2 | [
[
"validate_sequences",
"isValid"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | e00fd5eddfeda0c0e755914d83d050de30c71109 | eae04c7bf459a6850c45a2d216bbca69e29dac12 | |||
v1.0 | instruct | Code_Contests | Code_Contests_20813_I | In a distant galaxy, there is a species of creatures known as Terbongers, who communicate using sequences of colors. Each creature has a communication device that can emit sequences of colors represented by strings of lowercase letters where each letter corresponds to a specific color. The Terbongers have developed a s... | def is_subsequence(s, t):
"""
Determines if s is a subsequence of t.
"""
it = iter(t)
return all(char in it for char in s)
def check_subsequences(test_cases):
"""
For each test case, determines if the first string is a subsequence of the second.
"""
results = []
for s, t in test... | from solution import is_subsequence, check_subsequences, main, read_test_cases
def test_is_subsequence():
assert is_subsequence("abc", "ahbgdc") == True
assert is_subsequence("axc", "ahbgdc") == False
assert is_subsequence("ace", "abcde") == True
assert is_subsequence("aec", "abcde") == False
def test... | [
{
"docstring": "Determines if s is a subsequence of t.",
"function_declaration": "def is_subsequence(s, t):",
"function_name": "is_subsequence",
"parameter_list": "(s, t)"
},
{
"docstring": "For each test case, determines if the first string is a subsequence of the second.",
"function_de... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_code_contests-i2i_50000_1739866719_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_subsequence(s, t):\n \"\"\"\n Check if string s is a subsequence of string t.\n \"\"\"\n it = iter(t)\n return all(char in it for cha... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00020813",
"row_id": 20813,
"seed_ids": "[867]"
} | 0.665576 | Code_Contests_20813 | I | [
"is_subsequence",
"check_subsequences",
"read_test_cases",
"main"
] | 4 | [
[
"check_subsequences",
"is_subsequence"
]
] | 1 | [
"read_test_cases"
] | false | [] | false | pytest | true | [] | true | e6cff2e916c426408da10c1791d02fd978d1d422 | 7f9cdc09c8e2e3d2bdba79c5bbd590a4f0dd0bbb | |||
v1.0 | instruct | Code_Contests | Code_Contests_20844_I | Dave, an avid mathematician, is organizing a series of lectures on number theory. He has a peculiar way of planning his lectures in such a way that each lecture discusses a topic centered around a prime number. Dave wants to spread out his lectures over consecutive days, but he doesn't want to give more than one lectur... | def schedule_lectures(primes):
"""
Given a list of distinct prime numbers, returns the order in which lectures should be scheduled such that
the sum of differences between consecutive primes is minimized.
"""
primes.sort()
return primes
# Function to be called with the input
def optimal_lecture... | from solution import optimal_lecture_schedule
def test_example1():
n = 5
primes = [3, 5, 7, 11, 13]
diff_count, optimal_order = optimal_lecture_schedule(n, primes)
assert diff_count == 4
assert optimal_order == [3, 5, 7, 11, 13]
def test_example2():
n = 3
primes = [11, 7, 3]
diff_count... | [
{
"docstring": "Given a list of distinct prime numbers, returns the order in which lectures should be scheduled such that\nthe sum of differences between consecutive primes is minimized.",
"function_declaration": "def schedule_lectures(primes):",
"function_name": "schedule_lectures",
"parameter_list... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_code_contests-i2i_50000_1739866719_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def schedule_lectures(n, primes):\n \"\"\"\n Orders prime numbers such that the differences between any\n two consecutive primes are minimized.\n ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00020844",
"row_id": 20844,
"seed_ids": "[2644]"
} | 0.568512 | Code_Contests_20844 | I | [
"schedule_lectures",
"optimal_lecture_schedule"
] | 2 | [
[
"optimal_lecture_schedule",
"schedule_lectures"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | bc348d266ead436cc6bba7cd17efefa435219b9a | 78e374a640b5d7bbba6e78830d7f034f19218b5b | |||
v1.0 | instruct | Code_Contests | Code_Contests_20845_I | In a magical kingdom, there are n cities connected by m bidirectional roads such that there is a unique path between any two cities. A traveler wants to visit all the cities starting from city 1. Each city i has a certain level of happiness h_i that the traveler gains when visiting it for the first time, but if the tra... | def find(parent, i):
if parent[i] == i:
return i
else:
parent[i] = find(parent, parent[i])
return parent[i]
def union(parent, rank, x, y):
root_x = find(parent, x)
root_y = find(parent, y)
if rank[root_x] < rank[root_y]:
parent[root_x] = root_y
elif rank[roo... | def test_minimum_travel_cost_given_example1():
n, m = 3, 3
happiness = [5, 10, 15]
roads = [
(1, 2, 3),
(2, 3, 4),
(1, 3, 2)
]
assert minimum_travel_cost(n, m, happiness, roads) == 5
def test_minimum_travel_cost_given_example2():
n, m = 4, 4
happiness = [8, 2, 3, 5]
... | [
{
"docstring": null,
"function_declaration": "def find(parent, i):",
"function_name": "find",
"parameter_list": "(parent, i)"
},
{
"docstring": null,
"function_declaration": "def union(parent, rank, x, y):",
"function_name": "union",
"parameter_list": "(parent, rank, x, y)"
},
... | [
0,
0,
0,
1,
0
] | 1 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_code_contests-i2i_50000_1739866719_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import heapq\n\ndef minimum_travel_cost(n, m, happiness, roads):\n # Initialize graph as adjacency list\n graph = [[] for _ in range(n)]\n for u, ... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "00020845",
"row_id": 20845,
"seed_ids": "[8857]"
} | 0.735499 | Code_Contests_20845 | I | [
"find",
"union",
"kruskal",
"minimum_travel_cost"
] | 4 | [
[
"kruskal",
"find"
],
[
"kruskal",
"union"
],
[
"minimum_travel_cost",
"kruskal"
],
[
"union",
"find"
]
] | 4 | [] | false | [] | false | pytest | false | [] | true | f7ea00d87f9eee6badaed74a67a1ce8ab1a0086a | 5a5953cb99a4c5214784112332eb0bf81140d315 | |||
v1.0 | instruct | Code_Contests | Code_Contests_20866_I | You are given a binary tree with n nodes, each node having a unique value from 1 to n. Each node can have up to two children, but not necessarily both. Your task is to construct the tree using the provided node relationships and then determine the height of the tree. The height of a binary tree is the number of edges o... | class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def build_tree(edges):
nodes = {}
for u, v in edges:
if u not in nodes:
nodes[u] = TreeNode(u)
if v not in nodes:
nodes[v] = TreeNode(v)
if not node... | def test_single_node():
assert binary_tree_height(1, []) == 0
def test_linear_tree():
assert binary_tree_height(3, [(1, 2), (2, 3)]) == 2
def test_already_balanced_tree():
assert binary_tree_height(5, [(1, 2), (1, 3), (3, 4), (3, 5)]) == 2
def test_completely_balanced_tree():
assert binary_tree_heigh... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_code_contests-i2i_50000_1739866719_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from collections import defaultdict, deque\n\ndef calculate_tree_height(n, edges):\n if n == 1:\n return 0\n\n tree = defaultdict(list)\n f... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00020866",
"row_id": 20866,
"seed_ids": "[12641]"
} | 0.6103 | Code_Contests_20866 | I | [
"build_tree",
"find_root",
"height_of_tree",
"binary_tree_height"
] | 4 | [
[
"binary_tree_height",
"build_tree"
],
[
"binary_tree_height",
"find_root"
],
[
"binary_tree_height",
"height_of_tree"
]
] | 3 | [] | false | [
"TreeNode"
] | true | pytest | false | [] | true | 04e72eb64954af61f280702177c18adedcff28fe | 64a0813ad982232372982e2ebab0bc3231c3e5ad | |||
v1.0 | instruct | Code_Contests | Code_Contests_20876_I | Given an m x n matrix of integers, write a program to find the maximum sum of any submatrix. A submatrix is any continuous sub-section of the matrix that maintains the order of both rows and columns.
Input
The first line of input contains two integers m and n (1 ≤ m, n ≤ 200), the number of rows and columns of the m... | def max_submatrix_sum(matrix):
"""
Returns the maximum sum of any submatrix in the given m x n matrix.
"""
if not matrix or not matrix[0]:
return 0
m, n = len(matrix), len(matrix[0])
max_sum = float('-inf')
# Iterate over every pair of rows
for top in range(m):
... | from solution import max_submatrix_sum_from_input
def test_max_submatrix_sum_case1():
inputs = "4 5\n1 -2 0 3 4\n-5 6 7 -8 9\n3 -1 -4 2 -5\n5 2 -3 1 8"
assert max_submatrix_sum_from_input(inputs) == 23
def test_max_submatrix_sum_case2():
inputs = "3 3\n-1 -1 -1\n-1 -1 -1\n-1 -1 -1"
assert max_submatri... | [
{
"docstring": "Returns the maximum sum of any submatrix in the given m x n matrix.",
"function_declaration": "def max_submatrix_sum(matrix):",
"function_name": "max_submatrix_sum",
"parameter_list": "(matrix)"
},
{
"docstring": null,
"function_declaration": "def parse_input(inputs):",
... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_code_contests-i2i_50000_1739866719_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def max_sum_submatrix(matrix):\n \"\"\"\n Finds the maximum sum of any submatrix in the given matrix.\n \"\"\"\n if not matrix or not matrix[0]... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00020876",
"row_id": 20876,
"seed_ids": "[7523]"
} | 0.653528 | Code_Contests_20876 | I | [
"max_submatrix_sum",
"parse_input",
"max_submatrix_sum_from_input"
] | 3 | [
[
"max_submatrix_sum_from_input",
"max_submatrix_sum"
],
[
"max_submatrix_sum_from_input",
"parse_input"
]
] | 2 | [
"parse_input"
] | false | [] | false | pytest | true | [] | true | 01c556779771a6436b8e9ce0cdb92b8033be49a1 | d22a136252ce1971c74265df3deb08fb279205c5 | |||
v1.0 | instruct | Code_Contests | Code_Contests_20899_I | A: Spiral Matrix Traversal
problem
Given an m x n matrix, return all elements of the matrix in spiral order. The matrix traversal starts from the top left corner and follows a spiral pattern towards the center in a clockwise manner.
Input format
The input will begin with two integers m and n representing the number... | def spiralOrder(matrix):
"""
Returns a list of elements of the matrix in spiral order.
"""
res = []
while matrix:
res += matrix.pop(0)
if matrix and matrix[0]:
for row in matrix:
res.append(row.pop())
if matrix:
res += matrix.pop()[::-1... | from solution import spiralOrder, matrix_input, spiral_matrix_input
def test_spiralOrder_square_matrix():
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
assert spiralOrder(matrix) == [1, 2, 3, 6, 9, 8, 7, 4, 5]
def test_spiralOrder_rectangular_matrix():
matrix = [
[1, 2, ... | [
{
"docstring": "Returns a list of elements of the matrix in spiral order.",
"function_declaration": "def spiralOrder(matrix):",
"function_name": "spiralOrder",
"parameter_list": "(matrix)"
},
{
"docstring": null,
"function_declaration": "def matrix_input(m, n, elements):",
"function_... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_code_contests-i2i_50000_1739866719_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def spiralOrder(matrix):\n \"\"\"\n Returns the elements of the matrix in spiral order.\n \"\"\"\n if not matrix:\n return []\n \n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00020899",
"row_id": 20899,
"seed_ids": "[11346]"
} | 0.639383 | Code_Contests_20899 | I | [
"spiralOrder",
"matrix_input",
"spiral_matrix_input"
] | 3 | [
[
"spiral_matrix_input",
"matrix_input"
],
[
"spiral_matrix_input",
"spiralOrder"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 1a10537f6fe4a38920dc354995f4f3ef2de3cbfe | bb35bbf0d991425306f8751279b5767056fef84a | |||
v1.0 | instruct | Code_Contests | Code_Contests_20908_I | A delivery company has a set of delivery points in a grid and needs to find the shortest path that collects all items from different points and returns to the starting point. Points are connected, and each move from one point to another has an associated cost. The company wants to know the minimum cost required to coll... | import itertools
def calculate_min_cost(n, m, paths):
import sys
from itertools import permutations
# create adjacency matrix with costs as edge weights
cost = [[sys.maxsize] * (n + 1) for _ in range(n + 1)]
for u, v, w in paths:
cost[u][v] = w
cost[v][u] = w
# function to co... | from solution import shortest_delivery_route
def test_single_path():
assert shortest_delivery_route(2, 1, [(1, 2, 10)]) == 20
def test_example():
assert shortest_delivery_route(5, 7, [
(1, 2, 10),
(1, 3, 15),
(1, 4, 20),
(1, 5, 25),
(2, 5, 10),
(3, 4, 30),
... | [
{
"docstring": null,
"function_declaration": "def calculate_min_cost(n, m, paths):",
"function_name": "calculate_min_cost",
"parameter_list": "(n, m, paths)"
},
{
"docstring": null,
"function_declaration": "def shortest_delivery_route(n, m, connections):",
"function_name": "shortest_... | [
0,
0,
0,
0,
0,
1,
1,
0,
1,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_code_contests-i2i_50000_1739866719_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import itertools\n\ndef tsp_dp(graph, start):\n n = len(graph)\n dp = [[float('inf')] * n for _ in range(1 << n)]\n dp[1 << start][start] = 0\n ... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00020908",
"row_id": 20908,
"seed_ids": "[513]"
} | 0.730446 | Code_Contests_20908 | I | [
"calculate_min_cost",
"shortest_delivery_route"
] | 2 | [
[
"shortest_delivery_route",
"calculate_min_cost"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 316ef29a60f55515c89d730d739a0d3aae7739fe | bf23a3ee745256dd502e811cff4fcd40ca5fff5c | |||
v1.0 | instruct | Code_Contests | Code_Contests_20963_I | Given a positive integer n, Polycarp wants to create a new sequence of n positive integers such that the number of distinct divisors of the sequence elements are the same. Each element in the sequence should be within the range [1, nm], where nm is the maximum number of divisors an integer within this range can have.
... | def find_divisors(n):
"""
Returns a list of divisors of the given number n.
"""
divisors = []
for i in range(1, (n // 2) + 1):
if n % i == 0:
divisors.append(i)
divisors.append(n)
return divisors
def count_divisors(n):
"""
Returns the number of divisors of the gi... | from solution import sequence_with_same_divisors
def test_single_element():
assert sequence_with_same_divisors(1) == [1]
def test_five_elements():
result = sequence_with_same_divisors(5)
assert len(result) == 5
divisors_count = count_divisors(result[0])
for num in result:
assert count_divi... | [
{
"docstring": "Returns a list of divisors of the given number n.",
"function_declaration": "def find_divisors(n):",
"function_name": "find_divisors",
"parameter_list": "(n)"
},
{
"docstring": "Returns the number of divisors of the given number n.",
"function_declaration": "def count_div... | [
0,
0,
0,
0,
0,
0,
0,
0,
1,
1
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_code_contests-i2i_50000_1739866719_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def find_sequence(n):\n \"\"\"\n Returns a sequence of n positive integers such that each number has the same number of divisors.\n If it is impos... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00020963",
"row_id": 20963,
"seed_ids": "[10791]"
} | 0.67372 | Code_Contests_20963 | I | [
"find_divisors",
"count_divisors",
"generate_sequence",
"sequence_with_same_divisors"
] | 4 | [
[
"count_divisors",
"find_divisors"
],
[
"generate_sequence",
"count_divisors"
],
[
"sequence_with_same_divisors",
"generate_sequence"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 39ffd09d5dbb2aed9c38d246ba2643a5e2afa723 | 7e55783f5335caf7ed796bd42961f7c7930a1d08 | |||
v1.0 | instruct | Code_Contests | Code_Contests_21002_I | In a distant land, there are N villages connected with M bidirectional roads. Each road has a different construction cost, and you need to find the minimum cost to connect all the villages such that every village is reachable from every other village.
Your task is to find the minimum cost required to construct the roa... | def find(parent, x):
if parent[x] != x:
parent[x] = find(parent, parent[x])
return parent[x]
def union(parent, rank, x, y):
rootX = find(parent, x)
rootY = find(parent, y)
if rootX != rootY:
if rank[rootX] > rank[rootY]:
parent[rootY] = rootX
elif rank[rootX... | from solution import process_input, minimum_cost_to_connect_villages
def test_example_1():
input_text = "4 5\n1 2 1\n1 3 4\n2 3 2\n3 4 3\n4 1 6\n"
n, m, roads = process_input(input_text)
assert minimum_cost_to_connect_villages(n, m, roads) == 6
def test_example_2():
input_text = "3 3\n1 2 1\n2 3 2\n1 ... | [
{
"docstring": null,
"function_declaration": "def find(parent, x):",
"function_name": "find",
"parameter_list": "(parent, x)"
},
{
"docstring": null,
"function_declaration": "def union(parent, rank, x, y):",
"function_name": "union",
"parameter_list": "(parent, rank, x, y)"
},
... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_code_contests-i2i_50000_1739866719_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def find_min_cost_to_connect_villages(N, M, roads):\n \"\"\"\n Finds the minimum cost to connect all villages using Kruskal's algorithm.\n Returns... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00021002",
"row_id": 21002,
"seed_ids": "[6017]"
} | 0.728921 | Code_Contests_21002 | I | [
"find",
"union",
"minimum_cost_to_connect_villages",
"process_input"
] | 4 | [
[
"minimum_cost_to_connect_villages",
"find"
],
[
"minimum_cost_to_connect_villages",
"union"
],
[
"union",
"find"
]
] | 3 | [
"process_input"
] | false | [] | false | pytest | true | [] | true | 198acd8ff9af4cf73939b4c8d886d60b56ccaa1c | f332f7588863bae88d45f2421a6b837feb9816c0 | |||
v1.0 | instruct | Code_Contests | Code_Contests_21007_I | One day, the king decided to organize a contest in his kingdom. Each participant in the contest is given a unique positive integer ID. The king wants to reward the participants based on how special their ID is. An ID is considered special if the number of 1s in its binary representation is a prime number.
Your task is... | import math
def is_prime(n):
if n < 2:
return False
if n == 2:
return True
if n % 2 == 0:
return False
for i in range(3, int(math.sqrt(n)) + 1, 2):
if n % i == 0:
return False
return True
def count_1s_in_binary(n):
return bin(n).count('1')
def count... | def test_is_prime():
assert is_prime(1) == False
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(4) == False
assert is_prime(5) == True
assert is_prime(10) == False
assert is_prime(11) == True
def test_count_1s_in_binary():
assert count_1s_in_binary(5) == 2
ass... | [
{
"docstring": null,
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def count_1s_in_binary(n):",
"function_name": "count_1s_in_binary",
"parameter_list": "(n)"
},
{
"docstri... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_code_contests-i2i_50000_1739866719_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(num):\n \"\"\"\n Check if a number is a prime number.\n \"\"\"\n if num <= 1:\n return False\n if num <= 3:\n ret... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00021007",
"row_id": 21007,
"seed_ids": "[7362]"
} | 0.658052 | Code_Contests_21007 | I | [
"is_prime",
"count_1s_in_binary",
"count_special_ids",
"special_ids_count_for_cases"
] | 4 | [
[
"count_special_ids",
"count_1s_in_binary"
],
[
"count_special_ids",
"is_prime"
],
[
"special_ids_count_for_cases",
"count_special_ids"
]
] | 3 | [] | false | [] | false | pytest | false | [] | true | 8e7c50b7525a52f7a1794636b72a394601cac61f | 01616318a26385bd4fe6ce80b1520e667aa6d805 | |||
v1.0 | instruct | Code_Contests | Code_Contests_21008_I | Given a string `S`, we can write it as the concatenation of string `A`, string `B`, and string `C`, i.e., S = A + B + C. We are interested in the case where string `A` and `C` are reverses of each other and string `B` forms a palindrome by itself. Write a function that determines if `S` can be split into strings `A`, `... | def is_palindrome(s):
return s == s[::-1]
def can_be_split(S):
n = len(S)
for i in range(n):
for j in range(i, n):
A = S[:i]
B = S[i:j+1]
C = S[j+1:]
if A == C[::-1] and is_palindrome(B):
return "YES"
return "NO" | from solution import can_be_split
def test_can_be_split_example1():
assert can_be_split("abccba") == "YES"
def test_can_be_split_example2():
assert can_be_split("abcdecba") == "NO"
def test_can_be_split_example3():
assert can_be_split("aabcdefedcbaa") == "YES"
def test_can_be_split_single_char():
as... | [
{
"docstring": null,
"function_declaration": "def is_palindrome(s):",
"function_name": "is_palindrome",
"parameter_list": "(s)"
},
{
"docstring": null,
"function_declaration": "def can_be_split(S):",
"function_name": "can_be_split",
"parameter_list": "(S)"
}
] | [
0,
0,
0,
0,
0,
1,
1,
0,
1,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_code_contests-i2i_50000_1739866719_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def can_be_split(S):\n \"\"\"\n Determines if string S can be split into strings A, B, and C such that\n A and C are reverses of each other and B ... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00021008",
"row_id": 21008,
"seed_ids": "[7333]"
} | 0.810043 | Code_Contests_21008 | I | [
"is_palindrome",
"can_be_split"
] | 2 | [
[
"can_be_split",
"is_palindrome"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 0c29f2fee6f26d8801ac20e02bf955e3d8ca1c31 | 4efaa2bdf4d3cc262833a49f5239d032d474a42c | |||
v1.0 | instruct | Code_Contests | Code_Contests_21027_I | You are given a number `n` and you must generate the first `n` rows of Pascal's Triangle. Pascal's Triangle is a triangular array of numbers where the entries on the edges are always `1` and each number within the triangle is the sum of the two numbers directly above it.
For example, the first six rows of Pascal's Tri... | def generate_pascals_triangle(n):
"""
Generate the first `n` rows of Pascal's Triangle.
"""
if n <= 0:
return []
triangle = [[1]]
for row_num in range(1, n):
row = [1]
prev_row = triangle[row_num - 1]
for j in range(1, row_num):
row.... | from solution import generate_pascals_triangle, print_pascals_triangle
import builtins
def test_generate_pascals_triangle_1():
assert generate_pascals_triangle(1) == [[1]]
def test_generate_pascals_triangle_2():
assert generate_pascals_triangle(2) == [[1], [1, 1]]
def test_generate_pascals_triangle_3():
... | [
{
"docstring": "Generate the first `n` rows of Pascal's Triangle.",
"function_declaration": "def generate_pascals_triangle(n):",
"function_name": "generate_pascals_triangle",
"parameter_list": "(n)"
},
{
"docstring": "Print the first `n` rows of Pascal's Triangle.",
"function_declaration... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_code_contests-i2i_50000_1739866719_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def generate_pascals_triangle(n):\n \"\"\"\n Generate the first `n` rows of Pascal's Triangle.\n \"\"\"\n if n <= 0:\n return []\n \n... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00021027",
"row_id": 21027,
"seed_ids": "[3222]"
} | 0.559154 | Code_Contests_21027 | I | [
"generate_pascals_triangle",
"print_pascals_triangle"
] | 2 | [
[
"print_pascals_triangle",
"generate_pascals_triangle"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 647c9089b614b3c8b086249664396b1e89ad3303 | a403ab78448e47cf805f047ecd014fe8d3a28ba2 | |||
v1.0 | instruct | Code_Contests | Code_Contests_21084_I | Your company is working on an advanced search engine. As part of this project, one of the tasks is to implement a text compression algorithm using the Run-Length Encoding (RLE) technique to handle large text data efficiently.
Run-Length Encoding is a simple form of data compression where consecutive occurrences of the... | def run_length_encode(s):
"""
Perform Run-Length Encoding on the given string.
Args:
s: The input string
Returns:
The Run-Length Encoded string
"""
if not s:
return ""
encoded_string = []
count = 1
previous_char = s[0]
for char in s[1:]:
... | from solution import run_length_encode, process_strings
def test_run_length_encode():
assert run_length_encode("aabcccccaaa") == "a2bc5a3"
assert run_length_encode("abcd") == "abcd"
assert run_length_encode("aaabbbaaaacccddd") == "a3b3a4c3d3"
assert run_length_encode("a") == "a"
assert run_length_e... | [
{
"docstring": "Perform Run-Length Encoding on the given string.\n\nArgs:\ns: The input string\n\nReturns:\nThe Run-Length Encoded string",
"function_declaration": "def run_length_encode(s):",
"function_name": "run_length_encode",
"parameter_list": "(s)"
},
{
"docstring": "Process a list of ... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_code_contests-i2i_50000_1739866719_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def run_length_encoding(strings):\n def encode(s):\n if not s:\n return \"\"\n encoded = []\n count = 1\n previou... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00021084",
"row_id": 21084,
"seed_ids": "[10925]"
} | 0.654992 | Code_Contests_21084 | I | [
"run_length_encode",
"process_strings"
] | 2 | [
[
"process_strings",
"run_length_encode"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c461041903fb2c2b2710fe806f85434d7dafddf8 | 51dbe435c9cbe89559756a99f518ec309ff795b0 | |||
v1.0 | instruct | Code_Contests | Code_Contests_21164_I | In the land of loops and conditions, there exists a game titled "Prime Game," played by two friends, Alice and Bob. Being avid programmers, they love dealing with prime numbers. The game proceeds as follows:
1. Both players have an initial integer `N`.
2. During their turn, a player can subtract any prime number (grea... | def sieve_of_eratosthenes(n):
"""
Generate a list of all primes up to n using the Sieve of Eratosthenes.
"""
is_prime = [True] * (n + 1)
p = 2
while (p * p <= n):
if is_prime[p] == True:
for i in range(p * p, n + 1, p):
is_prime[i] = False
p += 1
r... | from solution import prime_game_winner
def test_prime_game_winner():
# Test case 1
T = 2
test_cases = [10, 15]
result = prime_game_winner(T, test_cases)
assert result == ["Alice", "Bob"]
# Test case 2
T = 3
test_cases = [1, 2, 3]
result = prime_game_winner(T, test_cases)
as... | [
{
"docstring": "Generate a list of all primes up to n using the Sieve of Eratosthenes.",
"function_declaration": "def sieve_of_eratosthenes(n):",
"function_name": "sieve_of_eratosthenes",
"parameter_list": "(n)"
},
{
"docstring": "Determine the winner of each prime game test case.",
"fun... | [
0,
0,
0,
0,
0,
0,
0,
1,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_code_contests-i2i_50000_1739866719_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(num):\n \"\"\"\n Determines if a number is prime.\n \"\"\"\n if num <= 1:\n return False\n if num <= 3:\n return ... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00021164",
"row_id": 21164,
"seed_ids": "[276]"
} | 0.734304 | Code_Contests_21164 | I | [
"sieve_of_eratosthenes",
"prime_game_winner"
] | 2 | [
[
"prime_game_winner",
"sieve_of_eratosthenes"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 289078aadca3ce5e0deb12c5f7d5c98a7a1c92f8 | c29775e40be9fb0122e11482068c76b94eef1493 | |||
v1.0 | instruct | Code_Contests | Code_Contests_21214_I | Jessica has recently learned about binary search trees (BST) and is fascinated by the property of BSTs where for any given node, the left child contains only nodes with values less than the parent node and the right child contains only nodes with values greater than the parent node. She decides to write a function that... | class TreeNode:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
def is_valid_bst(root, left=float('-inf'), right=float('inf')):
"""
Helper function to validate the BST.
"""
if not root:
return True
if not (l... | from solution import is_binary_search_tree
def test_case_1():
nodes = [
(10, 2, 3),
(5, 0, 0),
(20, 4, 5),
(15, 0, 0),
(25, 0, 0),
]
assert is_binary_search_tree(5, nodes) == "YES"
def test_case_2():
nodes = [
(10, 2, 3),
(5, 0, 0),
(9, 0... | [] | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_code_contests-i2i_50000_1739866719_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_valid_BST(n, nodes):\n if n == 0:\n return \"YES\"\n \n def validate(node_index, low, high):\n if node_index == 0:\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00021214",
"row_id": 21214,
"seed_ids": "[2032]"
} | 0.668069 | Code_Contests_21214 | I | [
"is_valid_bst",
"build_tree",
"is_binary_search_tree"
] | 3 | [
[
"is_binary_search_tree",
"build_tree"
],
[
"is_binary_search_tree",
"is_valid_bst"
]
] | 2 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | eb99143ded4641eb48d35e7809b9191179a0d823 | 442e3890c870c1ecb026245fe321214b1ba6b0ff | |||
v1.0 | instruct | Code_Contests | Code_Contests_21215_I | The soccer league is organizing a tournament with teams from different regions. Each team will play multiple matches throughout the tournament, and each match will yield a score. Your task is to write a program that calculates the ranking of teams based on their scores.
Each match played will have a record of the team... | def calculate_ranking(input_data):
def parse_input(input_data):
data = input_data.strip().split('\n')
datasets = []
i = 0
while i < len(data):
N, M = map(int, data[i].split())
if N == 0 and M == 0:
break
i += 1
teams = {... | import pytest
from solution import tournament_ranking
def test_tournament_ranking_example1():
input_data = "3 3\nTeamA 0\nTeamB 0\nTeamC 0\nTeamA TeamB 2 1\nTeamB TeamC 0 0\nTeamA TeamC 1 1\n0 0\n"
expected_output = "TeamA\nTeamC\nTeamB"
assert tournament_ranking(input_data) == expected_output
def test_to... | [
{
"docstring": null,
"function_declaration": "def calculate_ranking(input_data):",
"function_name": "calculate_ranking",
"parameter_list": "(input_data)"
},
{
"docstring": null,
"function_declaration": "def format_output(results):",
"function_name": "format_output",
"parameter_li... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_code_contests-i2i_50000_1739866719_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def rank_teams(datasets):\n results = []\n \n for dataset in datasets:\n teams = {}\n matches = dataset['matches']\n \n ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00021215",
"row_id": 21215,
"seed_ids": "[7074]"
} | 0.764999 | Code_Contests_21215 | I | [
"calculate_ranking",
"format_output",
"tournament_ranking"
] | 3 | [
[
"tournament_ranking",
"calculate_ranking"
],
[
"tournament_ranking",
"format_output"
]
] | 2 | [
"format_output"
] | false | [] | false | pytest | true | [] | true | 38228e60677a8ee53f769893d7112a4662e496c7 | e15cce5cc328115663a2e427215d5155e4667a61 | |||
v1.0 | instruct | Code_Contests | Code_Contests_21229_I | You are given a series of numbers and you need to determine the largest square number (a number which is the square of an integer) present in the series. A square number is always non-negative. In case there are no square numbers in the series, output -1.
Input
The first line contains an integer T, denoting the numbe... | import math
def is_square(n):
"""
Helper function to check if a number is a perfect square.
"""
if n < 0:
return False
sqrt_n = int(math.sqrt(n))
return sqrt_n * sqrt_n == n
def largest_square_series(T, series):
"""
This function takes the number of test cases T and the series ... | from solution import largest_square_series
def test_largest_square_series():
# Test case 1: Example case
assert largest_square_series(2, [[4, 16, 1, 3, 5], [10, 15, 21]]) == [16, -1]
# Test case 2: No square numbers
assert largest_square_series(1, [[13, 27, 35, 49, 50]]) == [49]
# Test ca... | [
{
"docstring": "Helper function to check if a number is a perfect square.",
"function_declaration": "def is_square(n):",
"function_name": "is_square",
"parameter_list": "(n)"
},
{
"docstring": "This function takes the number of test cases T and the series of integers \nand returns the larges... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_code_contests-i2i_50000_1739866719_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\n\ndef largest_square_number(T, series_list):\n def is_square(n):\n if n < 0:\n return False\n root = int(math.sqrt... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00021229",
"row_id": 21229,
"seed_ids": "[7395]"
} | 0.677354 | Code_Contests_21229 | I | [
"is_square",
"largest_square_series"
] | 2 | [
[
"largest_square_series",
"is_square"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | de56f5ec6bf4586b8ef6fcc0d6ab72e3b421ee72 | 8e6286e0b93b1677ae828014cea786b89950b4d2 | |||
v1.0 | instruct | Code_Contests | Code_Contests_21243_I | In the land of Palindromeia, words are considered magical if they read the same forwards and backwards. Amy, an inhabitant of Palindromeia, enjoys creating magical words and wonders if a given string can be transformed into a palindrome by rearranging its characters. She comes to you and asks for help to determine whet... | from collections import Counter
def can_form_palindrome(s):
"""
Determines if the characters of the string s can be rearranged to form a palindrome.
A string can be rearranged to form a palindrome if at most one character has an odd count.
"""
char_count = Counter(s)
odd_count = sum(1 for ... | from solution import can_form_palindrome, magical_words_possible
def test_can_form_palindrome():
assert can_form_palindrome('aabb') == True
assert can_form_palindrome('abc') == False
assert can_form_palindrome('aabbcc') == True
assert can_form_palindrome('a') == True
assert can_form_palindrome('aa'... | [
{
"docstring": "Determines if the characters of the string s can be rearranged to form a palindrome.\n\nA string can be rearranged to form a palindrome if at most one character has an odd count.",
"function_declaration": "def can_form_palindrome(s):",
"function_name": "can_form_palindrome",
"paramet... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_code_contests-i2i_50000_1739866719_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def can_form_palindrome(s):\n \"\"\"\n Determines if a given string can be rearranged to form a palindrome.\n \"\"\"\n from collections import ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00021243",
"row_id": 21243,
"seed_ids": "[522]"
} | 0.763163 | Code_Contests_21243 | I | [
"can_form_palindrome",
"magical_words_possible"
] | 2 | [
[
"magical_words_possible",
"can_form_palindrome"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 3db48b8140eab3ef5a0fd3c9ebcc7819dc6bb493 | 953681463794924ca7bbb30dbe6696ed83b56921 | |||
v1.0 | instruct | Code_Contests | Code_Contests_21261_I | You are given a grid of size MxN consisting of cells that are either walkable (denoted by '.') or blocked (denoted by '#'). Two points are given on this grid: the start point (Sx, Sy) and end point (Ex, Ey). You need to determine the minimum number of steps required to move from the start point to the end point. In eac... | from collections import deque
def valid_move(x, y, M, N, grid, visited):
return 0 <= x < M and 0 <= y < N and grid[x][y] == '.' and not visited[x][y]
def min_steps_in_grid(T, test_cases):
results = []
directions = [(-1, 0), (1, 0), (0, -1), (0, 1)] # Up, Down, Left, Right
for case in test_cases:
... | def test_min_steps_in_grid():
T = 2
test_cases = [
(5, 5, [
['.', '.', '#', '.', '.'],
['.', '#', '.', '.', '.'],
['.', '#', '#', '.', '.'],
['.', '.', '.', '.', '.'],
['.', '.', '.', '#', '.'],
], (0, 0), (4, 4)),
(3, ... | [
{
"docstring": null,
"function_declaration": "def valid_move(x, y, M, N, grid, visited):",
"function_name": "valid_move",
"parameter_list": "(x, y, M, N, grid, visited)"
},
{
"docstring": null,
"function_declaration": "def min_steps_in_grid(T, test_cases):",
"function_name": "min_ste... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_code_contests-i2i_50000_1739866719_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from collections import deque\n\ndef min_steps_to_reach_end(M, N, grid, start, end):\n def is_valid(x, y):\n return 0 <= x < M and 0 <= y < N and... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00021261",
"row_id": 21261,
"seed_ids": "[1116]"
} | 0.767284 | Code_Contests_21261 | I | [
"valid_move",
"min_steps_in_grid"
] | 2 | [
[
"min_steps_in_grid",
"valid_move"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 8c9ad5180427813a0c1ce7d8731117b2959bee3d | adf186fc6ea501a210e0739d602cd4ad2d100f1a | |||
v1.0 | instruct | Code_Contests | Code_Contests_21266_I | In a kingdom far, far away, there are P cities connected by Q bidirectional roads of various lengths. Every city in the kingdom can be reached from any other city directly or indirectly through a series of roads. The King has decided to build a new magic teleportation system to further improve transportation. This syst... | import heapq
def floyd_warshall(n, dist):
""" Apply Floyd Warshall algorithm to find all pairs shortest paths """
for k in range(n):
for i in range(n):
for j in range(n):
if dist[i][j] > dist[i][k] + dist[k][j]:
dist[i][j] = dist[i][k] + dist[k][j]
def f... | import pytest
from solution import smallest_maximum_distance
def test_example_1():
P = 4
Q = 4
roads = [(1, 2, 3), (2, 3, 1), (3, 4, 2), (4, 1, 4)]
result = smallest_maximum_distance(P, Q, roads)
# multiple correct answers are possible
assert result in [(1, 2), (2, 3), (3, 4), (4, 1)]
def ... | [
{
"docstring": "Apply Floyd Warshall algorithm to find all pairs shortest paths ",
"function_declaration": "def floyd_warshall(n, dist):",
"function_name": "floyd_warshall",
"parameter_list": "(n, dist)"
},
{
"docstring": null,
"function_declaration": "def find_optimal_teleportation(P, Q... | [
0,
0,
0,
1,
0
] | 1 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_code_contests-i2i_50000_1739866719_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import heapq\n\ndef find_best_teleportation(points, edges):\n def dijkstra(start, graph):\n dist = [float('inf')] * len(graph)\n dist[star... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "00021266",
"row_id": 21266,
"seed_ids": "[673]"
} | 0.702586 | Code_Contests_21266 | I | [
"floyd_warshall",
"find_optimal_teleportation",
"smallest_maximum_distance"
] | 3 | [
[
"find_optimal_teleportation",
"floyd_warshall"
],
[
"smallest_maximum_distance",
"find_optimal_teleportation"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 9bb74074d367423fb22a181e9eeeda7bf0e8ce2d | 4709452469671ec9a8a2dd0f46cb9561ffef1c92 | |||
v1.0 | instruct | Code_Contests | Code_Contests_21285_I | Jenny has recently started learning algorithms, and she is fascinated by prime numbers. As a challenge, she decides to write a program that finds the minimum number of prime numbers whose sum equals a given number N.
A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itsel... | def is_prime(n):
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
def min_prime_numbers_sum(N):
if is_prime(... | def test_min_prime_numbers_sum_10():
assert min_prime_numbers_sum(10) == 2
def test_min_prime_numbers_sum_28():
assert min_prime_numbers_sum(28) == 2
def test_min_prime_numbers_sum_3():
assert min_prime_numbers_sum(3) == 1
def test_min_prime_numbers_sum_prime():
assert min_prime_numbers_sum(17) == 1
... | [
{
"docstring": null,
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def min_prime_numbers_sum(N):",
"function_name": "min_prime_numbers_sum",
"parameter_list": "(N)"
}
] | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_code_contests-i2i_50000_1739866719_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def min_prime_sum(N):\n \"\"\"\n This function returns the minimum number of prime numbers whose sum equals N.\n \"\"\"\n if N == 2:\n r... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00021285",
"row_id": 21285,
"seed_ids": "[11264]"
} | 0.645879 | Code_Contests_21285 | I | [
"is_prime",
"min_prime_numbers_sum"
] | 2 | [
[
"min_prime_numbers_sum",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 722c98d69f0be549efd0a1dae84a3c51cabc14cf | 7e7ed4b60d12c8c4bd32982fc1dd2993a4c8a80a | |||
v1.0 | instruct | Code_Contests | Code_Contests_21293_I | A travel company is designing an itinerary-planning system. They need to help customers determine the shortest possible route that visits a list of cities and returns to the starting city. This problem is known as the "Traveling Salesman Problem." The company uses a simple heuristic to estimate the shortest route by al... | import math
def read_input():
import sys
input = sys.stdin.read
data = input().split()
N = int(data[0])
cities = []
for i in range(1, len(data), 2):
cities.append((int(data[i]), int(data[i+1])))
return N, cities
def euclidean_distance(city1, city2):
return math.sqrt((city2[0] -... | from solution import euclidean_distance, find_nearest_city, calculate_total_distance
def test_euclidean_distance():
assert euclidean_distance((0, 0), (0, 1)) == 1.0
assert euclidean_distance((0, 0), (1, 0)) == 1.0
assert euclidean_distance((0, 0), (1, 1)) == math.sqrt(2)
def test_find_nearest_city():
... | [
{
"docstring": null,
"function_declaration": "def read_input():",
"function_name": "read_input",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def euclidean_distance(city1, city2):",
"function_name": "euclidean_distance",
"parameter_list": "(city1, city2... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_code_contests-i2i_50000_1739866719_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\n\ndef calculate_distance(x1, y1, x2, y2):\n \"\"\"\n Returns the Euclidean distance between two points (x1, y1) and (x2, y2).\n \"\"\... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00021293",
"row_id": 21293,
"seed_ids": "[485]"
} | 0.685943 | Code_Contests_21293 | I | [
"read_input",
"euclidean_distance",
"find_nearest_city",
"calculate_total_distance",
"main"
] | 5 | [
[
"calculate_total_distance",
"euclidean_distance"
],
[
"calculate_total_distance",
"find_nearest_city"
],
[
"find_nearest_city",
"euclidean_distance"
]
] | 3 | [
"read_input"
] | false | [] | false | pytest | true | [] | true | 0ebf70504c542f5a3d3a6f7297477bfa3f7c70e7 | e48448363f7caf703adb9c5f3e0e69bb193d1298 | |||
v1.0 | instruct | Code_Contests | Code_Contests_21346_I | Liam is fascinated by binary trees and has embarked on a quest to find the "deepest leaves." A leaf is a node with no children, and the deepest leaves are the ones farthest from the root. Liam wants to determine the sum of the values of these deepest leaves for a given binary tree. Can you help him accomplish this?
Yo... | class TreeNode:
def __init__(self, value=0, left=None, right=None):
self.value = value
self.left = left
self.right = right
def build_tree_from_level_order(values):
if not values:
return None
root = TreeNode(values[0])
queue = [root]
index = 1
while index < len(va... | from solution import build_tree_from_level_order, deepest_leaves_sum, solve, main
import pytest
def test_single_node_tree():
tree = build_tree_from_level_order([10])
assert deepest_leaves_sum(tree) == 10
def test_tree_with_multiple_levels():
tree = build_tree_from_level_order([1, 2, 3, 4, 5])
assert d... | [] | [
0,
0,
0,
0,
1,
0,
0,
0,
0
] | 1 | hard | 0.111 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_code_contests-i2i_50000_1739866719_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from collections import deque\n\nclass TreeNode:\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\n... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "00021346",
"row_id": 21346,
"seed_ids": "[8925]"
} | 0.60204 | Code_Contests_21346 | I | [
"build_tree_from_level_order",
"deepest_leaves_sum",
"solve",
"main"
] | 4 | [
[
"solve",
"build_tree_from_level_order"
],
[
"solve",
"deepest_leaves_sum"
]
] | 2 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | 4ba4ec354de8343ae3646f1c76c4a5fd540a0abb | 710acb6a599e86bc00739761bb0797e068722bc9 | |||
v1.0 | instruct | Code_Contests | Code_Contests_21358_I | Ravi is a computer scientist who loves prime numbers. One day, he came across an interesting series of numbers while researching prime patterns. The series is constructed by taking a prime number and continuously adding the sum of its digits until the number is no longer prime. Ravi decided to write a program to automa... | def sum_of_digits(n):
"""
Returns the sum of digits of n.
"""
return sum(int(digit) for digit in str(n))
def is_prime(n):
"""
Determines if a number n is prime.
"""
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
... | def test_sum_of_digits():
assert sum_of_digits(123) == 6
assert sum_of_digits(0) == 0
assert sum_of_digits(987) == 24
def test_is_prime():
assert is_prime(2) == True
assert is_prime(4) == False
assert is_prime(13) == True
assert is_prime(1) == False
assert is_prime(17) == True
def test... | [
{
"docstring": "Returns the sum of digits of n.",
"function_declaration": "def sum_of_digits(n):",
"function_name": "sum_of_digits",
"parameter_list": "(n)"
},
{
"docstring": "Determines if a number n is prime.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime"... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_code_contests-i2i_50000_1739866719_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(num):\n if num <= 1:\n return False\n if num <= 3:\n return True\n if num % 2 == 0 or num % 3 == 0:\n return Fal... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00021358",
"row_id": 21358,
"seed_ids": "[6242]"
} | 0.635104 | Code_Contests_21358 | I | [
"sum_of_digits",
"is_prime",
"generate_prime_series"
] | 3 | [
[
"generate_prime_series",
"is_prime"
],
[
"generate_prime_series",
"sum_of_digits"
]
] | 2 | [] | false | [] | false | pytest | false | [] | true | d517e4d43eb5b1449dbd5742b7ba42c97f5aaa19 | e1df8ed815f5d6995e30709df8d843a9bce4c39a | |||
v1.0 | instruct | Code_Contests | Code_Contests_21438_I | You are given a tree consisting of n nodes labeled with numbers from 1 to n, and n-1 edges. Each edge has a weight assigned to it. A query on the tree asks for the greatest weight among the edges on the path between two given nodes u and v.
Write a program to answer q such queries efficiently.
Input
The first line o... | MAX_LOG = 17 # Since 2^17 > 10^5 (as 2^17 = 131072)
def dfs(graph, node, parent, depth, max_weight, log_parents, log_max_weights):
for neighbor, weight in graph[node]:
if neighbor != parent:
depth[neighbor] = depth[node] + 1
log_parents[neighbor][0] = node
log_max_weigh... | def test_example_case():
n = 5
q = 3
edges = [(1, 2, 4), (1, 3, 2), (2, 4, 3), (2, 5, 6)]
queries = [(1, 4), (4, 5), (3, 5)]
graph = [[] for _ in range(n + 1)]
for u, v, w in edges:
graph[u].append((v, w))
graph[v].append((u, w))
results = process_queries(n, graph, ... | [
{
"docstring": null,
"function_declaration": "def dfs(graph, node, parent, depth, max_weight, log_parents, log_max_weights):",
"function_name": "dfs",
"parameter_list": "(graph, node, parent, depth, max_weight, log_parents, log_max_weights)"
},
{
"docstring": null,
"function_declaration"... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_code_contests-i2i_50000_1739866719_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from collections import defaultdict\nimport sys\ninput = sys.stdin.read\nimport itertools\n\ndef max_edge_on_path(n, edges, queries):\n LOG = 17 # (2^17... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00021438",
"row_id": 21438,
"seed_ids": "[4604]"
} | 0.758143 | Code_Contests_21438 | I | [
"dfs",
"preprocess_lca",
"lca_max_weight",
"process_queries"
] | 4 | [
[
"preprocess_lca",
"dfs"
],
[
"process_queries",
"lca_max_weight"
],
[
"process_queries",
"preprocess_lca"
]
] | 3 | [
"process_queries"
] | false | [] | false | pytest | false | [] | true | 28a948a403a10ca82c5a6e3ff2973da71d7bc976 | 43c4832ea66fdfb5d8003727a8dab8ab765da14c | |||
v1.0 | instruct | Code_Contests | Code_Contests_21476_I | Riya loves to play with arrays and prime numbers. She defines a "prime subsequence" as a subsequence of an array where all the elements are prime numbers. Given an integer array of size N, Riya wants to know the length of the longest prime subsequence within the array. A subsequence is derived by deleting some or no el... | def is_prime(n):
"""
Helper function to check if a number is prime.
"""
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 +... | from solution import longest_prime_subsequence_length
def test_prime_subsequence():
assert longest_prime_subsequence_length([10, 3, 7, 8, 5, 2]) == 4
assert longest_prime_subsequence_length([1, 4, 6, 8, 10]) == 0
assert longest_prime_subsequence_length([2, 3, 5, 7, 11, 13, 17, 19, 23, 29]) == 10
assert... | [
{
"docstring": "Helper function to check if a number is prime.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Given an array, returns the length of the longest prime subsequence.",
"function_declaration": "def longest... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_code_contests-i2i_50000_1739866719_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(n):\n \"\"\"\n Returns True if n is a prime number, else False.\n \"\"\"\n if n <= 1:\n return False\n if n <= 3:\n ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00021476",
"row_id": 21476,
"seed_ids": "[10800]"
} | 0.740617 | Code_Contests_21476 | I | [
"is_prime",
"longest_prime_subsequence_length"
] | 2 | [
[
"longest_prime_subsequence_length",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 6bb0eec70fc1cb5847d9cb363a34abf8cfa7add3 | 0e3c4df419be3c98eb42258f56ea61de23b0bf31 | |||
v1.0 | instruct | Code_Contests | Code_Contests_21514_I | Highest Heart Rate
Dr. Fit is a fitness trainer who monitors the health data of his clients. He particularly pays attention to their heart rate data during exercise routines. Dr. Fit records the heart rate of his clients at regular intervals and wants to know the peak heart rate during each exercise session. However, s... | def categorize_heart_rate(h):
"""
Categorize the heart rate based on predefined thresholds.
"""
if h <= 100:
return "Low"
elif 101 <= h <= 150:
return "Moderate"
elif 151 <= h <= 200:
return "High"
else:
return "Very High"
def highest_heart_rate(clients_data)... | from solution import highest_heart_rate, categorize_heart_rate
def test_categorize_heart_rate():
assert categorize_heart_rate(100) == "Low"
assert categorize_heart_rate(101) == "Moderate"
assert categorize_heart_rate(150) == "Moderate"
assert categorize_heart_rate(151) == "High"
assert categorize_h... | [
{
"docstring": "Categorize the heart rate based on predefined thresholds.",
"function_declaration": "def categorize_heart_rate(h):",
"function_name": "categorize_heart_rate",
"parameter_list": "(h)"
},
{
"docstring": "Finds the highest heart rate and its category for each client.",
"func... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_code_contests-i2i_50000_1739866719_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def categorize_heart_rate(heart_rate):\n if heart_rate <= 100:\n return 'Low'\n elif 101 <= heart_rate <= 150:\n return 'Moderate'\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00021514",
"row_id": 21514,
"seed_ids": "[12915]"
} | 0.519086 | Code_Contests_21514 | I | [
"categorize_heart_rate",
"highest_heart_rate"
] | 2 | [
[
"highest_heart_rate",
"categorize_heart_rate"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | da855372561ed4e6aef03e8c15e6dd1c6fe8ff89 | e469e4af9385d806dee5cc8db1d56cfde7d419ed | |||
v1.0 | instruct | Code_Contests | Code_Contests_21527_I | Let's solve a matrix transformation problem that involves rotating a matrix clockwise by 90 degrees and checking if it matches a target matrix.
You are given two n x n matrices, A and B. Your task is to determine if matrix B is a 90-degree clockwise rotation of matrix A.
Input
The first line contains an integer t (1... | def rotate_90_clockwise(matrix):
"""
Rotates the given n x n matrix 90 degrees clockwise.
"""
n = len(matrix)
return [[matrix[n - j - 1][i] for j in range(n)] for i in range(n)]
def is_rotation(matrix1, matrix2):
"""
Checks if matrix2 is a 90-degree clockwise rotation of matrix1.
"""
... | from solution import solve, parse_input
def test_example_case_1():
input_data = """2
3
1 2 3
4 5 6
7 8 9
7 4 1
8 5 2
9 6 3
3
1 2 3
4 5 6
7 8 9
1 2 3
4 5 6
7 8 9"""
test_cases = parse_input(input_data)
results = solve(test_cases)
assert results == ["YES", "NO"]
def test_single_element_matrix():
inp... | [
{
"docstring": "Rotates the given n x n matrix 90 degrees clockwise.",
"function_declaration": "def rotate_90_clockwise(matrix):",
"function_name": "rotate_90_clockwise",
"parameter_list": "(matrix)"
},
{
"docstring": "Checks if matrix2 is a 90-degree clockwise rotation of matrix1.",
"fu... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_code_contests-i2i_50000_1739866719_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def rotate_90_degrees_clockwise(matrix):\n \"\"\"\n Rotates the given n x n matrix by 90 degrees clockwise.\n \"\"\"\n n = len(matrix)\n rot... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00021527",
"row_id": 21527,
"seed_ids": "[1492]"
} | 0.542487 | Code_Contests_21527 | I | [
"rotate_90_clockwise",
"is_rotation",
"solve",
"parse_input"
] | 4 | [
[
"is_rotation",
"rotate_90_clockwise"
],
[
"solve",
"is_rotation"
]
] | 2 | [
"parse_input"
] | false | [] | false | pytest | true | [] | true | 9bdf643e89a452e64528d7b1d5fa83011671e462 | 957640530520b5751cd6291f699414b0898279b3 | |||
v1.0 | instruct | Code_Contests | Code_Contests_21578_I | Implement a **spelling checker** that attempts to correct misspelled words in a text. The checker should use a provided dictionary of correctly spelled words to find the most likely correction.
For each misspelled word in the text, the spelling checker should choose the correction that has the smallest edit distance (... | def calculate_levenshtein_distance(word1, word2):
"""
Calculates the Levenshtein distance between two words.
"""
len1, len2 = len(word1), len(word2)
dp = [[0] * (len2 + 1) for _ in range(len1 + 1)]
for i in range(len1 + 1):
for j in range(len2 + 1):
if i == 0:
... | from solution import calculate_levenshtein_distance, correct_spelling
def test_calculate_levenshtein_distance():
assert calculate_levenshtein_distance("kitten", "sitting") == 3
assert calculate_levenshtein_distance("flaw", "lawn") == 2
assert calculate_levenshtein_distance("algorithm", "altruistic") == 6
... | [
{
"docstring": "Calculates the Levenshtein distance between two words.",
"function_declaration": "def calculate_levenshtein_distance(word1, word2):",
"function_name": "calculate_levenshtein_distance",
"parameter_list": "(word1, word2)"
},
{
"docstring": "Corrects the spelling of words in the... | [
0,
0,
0,
1,
1
] | 2 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_code_contests-i2i_50000_1739866719_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def edit_distance(word1, word2):\n m, n = len(word1), len(word2)\n dp = [[0] * (n + 1) for _ in range(m + 1)]\n\n for i in range(m + 1):\n ... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "00021578",
"row_id": 21578,
"seed_ids": "[9670]"
} | 0.635061 | Code_Contests_21578 | I | [
"calculate_levenshtein_distance",
"correct_spelling"
] | 2 | [
[
"correct_spelling",
"calculate_levenshtein_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | be43c7e274674ad09be71b9b94929a900f41ddca | 51dd05f0c937a4d7eb86b1c0820e5a09e8c9538a | |||
v1.0 | instruct | Code_Contests | Code_Contests_21590_I | Time Limit: 10 sec / Memory Limit: 128 MB
Given a collection of different words, your task is to find and output the longest word that can be formed by deleting some characters of a given string `s` without reordering the characters. If there is more than one possible longest word, select the one that is lexicographic... | def is_subsequence(word, s):
it = iter(s)
return all(char in it for char in word)
def find_longest_word(words, s):
words.sort(key=lambda word: (-len(word), word))
for word in words:
if is_subsequence(word, s):
return word
return "" | from solution import find_longest_word
def test_example_case():
words = ["able", "apple", "monkey", "plea"]
s = "abpcplea"
assert find_longest_word(words, s) == "apple"
def test_no_valid_subsequence():
words = ["able", "bale", "kangaroo"]
s = "abc"
assert find_longest_word(words, s) == ""
def... | [
{
"docstring": null,
"function_declaration": "def is_subsequence(word, s):",
"function_name": "is_subsequence",
"parameter_list": "(word, s)"
},
{
"docstring": null,
"function_declaration": "def find_longest_word(words, s):",
"function_name": "find_longest_word",
"parameter_list"... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_code_contests-i2i_50000_1739866719_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_subsequence(x, s):\n \"\"\"\n Returns True if x is a subsequence of s, False otherwise.\n \"\"\"\n it = iter(s)\n return all(c in it ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00021590",
"row_id": 21590,
"seed_ids": "[409]"
} | 0.696367 | Code_Contests_21590 | I | [
"is_subsequence",
"find_longest_word"
] | 2 | [
[
"find_longest_word",
"is_subsequence"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 7d7e8f797ebfd5eaa7d997aecaa2653a27b3b853 | 13746d320317a66ace1413d823a4cf4fb64899d3 | |||
v1.0 | instruct | Code_Contests | Code_Contests_21608_I | Create a program that reads a list of non-negative integers and outputs the median value. If the list has an even number of integers, the median is defined as the average of the two middle elements (you may assume the integer division and result will still be an integer). Each integer in the list is between 0 and 1000,... | def find_median(dataset):
"""
Finds the median of a list of non-negative integers.
If the list has an even number of elements, it returns the integer average of the two middle values.
"""
sorted_ds = sorted(dataset)
n = len(sorted_ds)
if n % 2 == 1: # odd length
return sorted_d... | from solution import find_median, median_of_datasets, process_input
def test_find_median_odd_length():
assert find_median([1, 3, 3, 6, 7, 8, 9]) == 6
def test_find_median_even_length():
assert find_median([7, 8, 3, 6, 1, 9]) == 6
def test_find_median_two_elements():
assert find_median([1, 2]) == 1
def t... | [
{
"docstring": "Finds the median of a list of non-negative integers.\nIf the list has an even number of elements, it returns the integer average of the two middle values.",
"function_declaration": "def find_median(dataset):",
"function_name": "find_median",
"parameter_list": "(dataset)"
},
{
... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_code_contests-i2i_50000_1739866719_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def find_median(arr):\n \"\"\"\n Given a list of non-negative integers, returns the median.\n If the list length is even, returns the average of t... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00021608",
"row_id": 21608,
"seed_ids": "[10709]"
} | 0.735073 | Code_Contests_21608 | I | [
"find_median",
"median_of_datasets",
"process_input"
] | 3 | [
[
"median_of_datasets",
"find_median"
],
[
"process_input",
"median_of_datasets"
]
] | 2 | [
"process_input"
] | false | [] | false | pytest | true | [] | true | 51a839d1f4b21b0850d38be14ff92b9501fb2bd0 | 295a47f2d3b5e4ac568ebfbb87b46cf85d5f6710 | |||
v1.0 | instruct | Code_Contests | Code_Contests_21617_I | You are given a binary tree where each node contains an integer value. Your task is to find the maximum width of the binary tree. The width of a binary tree is defined as the maximum width amongst all levels. The width of one level is defined as the length between the end-nodes (the leftmost and rightmost non-empty nod... | from collections import deque
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def build_tree(level_order_values):
if not level_order_values:
return None
index = 0
root = TreeNode(level_order_values[index])
index += 1
... | from solution import max_width_of_binary_tree
def test_example_case():
assert max_width_of_binary_tree(7, [1, 3, 2, 5, 3, -1, 9]) == 4
def test_single_node():
assert max_width_of_binary_tree(1, [1]) == 1
def test_two_levels():
assert max_width_of_binary_tree(3, [1, 2, 3]) == 2
def test_sparse_tree():
... | [] | [
0,
0,
0,
0,
0,
0,
1,
1,
0
] | 2 | hard | 0.222 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_code_contests-i2i_50000_1739866719_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from collections import deque\n\nclass TreeNode:\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\n... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00021617",
"row_id": 21617,
"seed_ids": "[4403]"
} | 0.574221 | Code_Contests_21617 | I | [
"build_tree",
"width_of_binary_tree",
"max_width_of_binary_tree"
] | 3 | [
[
"max_width_of_binary_tree",
"build_tree"
],
[
"max_width_of_binary_tree",
"width_of_binary_tree"
]
] | 2 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | 71a9253ccf2e6e2f602326e871e96451b9abcffa | 8c150fff3842bc72de0e30c3aa4d9652ae1937c1 | |||
v1.0 | instruct | Code_Contests | Code_Contests_21631_I | A large island nation consists of a network of cities connected by roads. The ruler of this nation wants to ensure that each city is prepared for any possible emergencies. A strategic plan needs to be developed so that each city can be reached from a designated central city in the shortest possible time. The designated... | import heapq
def compute_distances(N, roads, start):
distances = [float('inf')] * N
distances[start] = 0
priority_queue = [(0, start)]
while priority_queue:
current_distance, u = heapq.heappop(priority_queue)
if current_distance > distances[u]:
continue
... | def test_find_optimal_hub_city():
assert find_optimal_hub_city(5, 5, [
(1,2,3), (1,3,2), (2,4,4), (3,4,1), (4,5,2)
]) == 4
assert find_optimal_hub_city(7, 8, [
(1,2,5), (1,3,2), (3,4,1), (3,5,4), (2,4,3), (2,6,6), (5,7,2), (6,7,1)
]) == 3
assert find_optimal_hub_city(3, 3, [
... | [
{
"docstring": null,
"function_declaration": "def compute_distances(N, roads, start):",
"function_name": "compute_distances",
"parameter_list": "(N, roads, start)"
},
{
"docstring": null,
"function_declaration": "def find_optimal_hub_city(N, M, city_roads):",
"function_name": "find_o... | [
0,
0,
0,
1,
1
] | 2 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_code_contests-i2i_50000_1739866719_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import heapq\nimport sys\n\ndef dijkstra(n, start, adj):\n distances = [sys.maxsize] * (n + 1)\n distances[start] = 0\n pq = [(0, start)]\n \n ... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "00021631",
"row_id": 21631,
"seed_ids": "[3744]"
} | 0.66964 | Code_Contests_21631 | I | [
"compute_distances",
"find_optimal_hub_city"
] | 2 | [
[
"find_optimal_hub_city",
"compute_distances"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 807d39b7d3d3c7ab682102c48fcf079b8537cff8 | 4238f032be4ad13ef0d5cc6c4220afe89bd3d1fa | |||
v1.0 | instruct | Code_Contests | Code_Contests_21657_I | You are given a list of strings representing mathematical expressions composed of addition, subtraction, multiplication, division, and parentheses. Your task is to sort these expressions based on their evaluated results in ascending order. If two expressions evaluate to the same result, maintain their original order fr... | def evaluate_expression(expression):
"""
Evaluates the given mathematical expression and returns the result.
"""
return eval(expression)
def sort_expressions(expressions):
"""
Sorts the given list of expressions based on their evaluated result.
If two expressions evaluate to the same value,... | from solution import evaluate_expression, sort_expressions, sort_expressions_in_test_cases
def test_evaluate_expression():
assert evaluate_expression('1 + 2') == 3
assert evaluate_expression('4 * 5') == 20
assert evaluate_expression('3 - 2') == 1
assert evaluate_expression('5 / 5') == 1.0
assert ev... | [
{
"docstring": "Evaluates the given mathematical expression and returns the result.",
"function_declaration": "def evaluate_expression(expression):",
"function_name": "evaluate_expression",
"parameter_list": "(expression)"
},
{
"docstring": "Sorts the given list of expressions based on their... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_code_contests-i2i_50000_1739866719_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def sort_expressions(test_cases):\n results = []\n \n for test_case in test_cases:\n evaluated_expressions = [(expr, eval(expr)) for expr i... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00021657",
"row_id": 21657,
"seed_ids": "[6319]"
} | 0.547813 | Code_Contests_21657 | I | [
"evaluate_expression",
"sort_expressions",
"sort_expressions_in_test_cases"
] | 3 | [
[
"sort_expressions",
"evaluate_expression"
],
[
"sort_expressions_in_test_cases",
"sort_expressions"
]
] | 2 | [
"sort_expressions_in_test_cases"
] | false | [] | false | pytest | true | [] | true | 0aa07910541e3983773079d2354b88c4b71821bb | 6a309e94f017e04db08be7aa0044ee9737898af0 | |||
v1.0 | instruct | Code_Contests | Code_Contests_21684_I | You are managing a group of developers and want to track their task completion times. Each developer's tasks for the day are recorded with start and end times. You suspect that some tasks might overlap, leading to inefficient use of time. Your goal is to determine the total amount of time spent on tasks, considering th... | def parse_time(time_str):
"""Parse a time string "HH:MM" into a number of minutes since midnight."""
hours, minutes = map(int, time_str.split(':'))
return hours * 60 + minutes
def total_task_time(tasks):
"""
Calculate the total time spent on tasks, considering overlaps.
"""
# Convert task t... | from solution import total_task_time
def test_no_overlaps():
tasks = [("09:00", "10:30"), ("11:00", "12:00"), ("13:00", "14:00")]
assert total_task_time(tasks) == 210
def test_full_overlap():
tasks = [("09:00", "10:00"), ("09:30", "10:30"), ("10:00", "11:00")]
assert total_task_time(tasks) == 120
def... | [
{
"docstring": "Parse a time string \"HH:MM\" into a number of minutes since midnight.",
"function_declaration": "def parse_time(time_str):",
"function_name": "parse_time",
"parameter_list": "(time_str)"
},
{
"docstring": "Calculate the total time spent on tasks, considering overlaps.",
... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_code_contests-i2i_50000_1739866719_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def calculate_total_task_time(tasks):\n from datetime import datetime\n \n def to_minutes(time_str):\n hours, minutes = map(int, time_str.s... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00021684",
"row_id": 21684,
"seed_ids": "[10405]"
} | 0.611984 | Code_Contests_21684 | I | [
"parse_time",
"total_task_time"
] | 2 | [
[
"total_task_time",
"parse_time"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f57560d71d237deab6a4036473da3149fdce7748 | b3b8fa7348361b86153fabb3838c581545d4dc87 | |||
v1.0 | instruct | Code_Contests | Code_Contests_21705_I | Tom is fascinated by prime numbers and is particularly interested in prime gaps - the difference between two successive prime numbers. He is curious to find the longest gap between consecutive prime numbers within a given range. Could you help him with this?
Tom will provide you with multiple queries, each containing ... | def generate_primes_up_to(n):
""" Generate a list of primes up to n using the Sieve of Eratosthenes """
sieve = [True] * (n + 1)
sieve[0] = sieve[1] = False
for start in range(2, int(n**0.5) + 1):
if sieve[start]:
for multiple in range(start*start, n+1, start):
sieve[... | from solution import prime_gaps
def test_example_case():
t = 4
queries = [(2, 10), (10, 20), (20, 30), (100, 110)]
assert prime_gaps(t, queries) == [2, 4, 6, 4]
def test_single_query():
t = 1
queries = [(2, 10)]
assert prime_gaps(t, queries) == [2]
def test_no_primes_in_range():
t = 1
... | [
{
"docstring": "Generate a list of primes up to n using the Sieve of Eratosthenes ",
"function_declaration": "def generate_primes_up_to(n):",
"function_name": "generate_primes_up_to",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def prime_gaps(t, queries):",
... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_code_contests-i2i_50000_1739866719_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def generate_primes_up_to(n):\n \"\"\" Generate a list of primes up to n using the Sieve of Eratosthenes \"\"\"\n sieve = [True] * (n + 1)\n sieve... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00021705",
"row_id": 21705,
"seed_ids": "[332]"
} | 0.650931 | Code_Contests_21705 | I | [
"generate_primes_up_to",
"prime_gaps"
] | 2 | [
[
"prime_gaps",
"generate_primes_up_to"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | b803d6ac8cd706148d9baf5da35f8d679dc2bce9 | 89adaa1c68d7c957f5924b83250de6e4cbaf3998 | |||
v1.0 | instruct | Code_Contests | Code_Contests_21744_I | Develop a program that calculates the minimal number of swaps required to sort an array in non-decreasing order. Each swap should only involve adjacent elements, similar to the bubble sort algorithm.
Input
The first line of input contains an integer T denoting the number of test cases. Each of the following T lines de... | def bubble_sort_swap_count(arr):
"""
Function to calculate the number of adjacent swaps required to sort the array using a bubble sort algorithm.
"""
n = len(arr)
swap_count = 0
for i in range(n):
for j in range(0, n-i-1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1... | from solution import min_swaps_to_sort, parse_input
def test_bubble_sort_swap_count():
assert bubble_sort_swap_count([2, 3, 4, 1, 5]) == 3
assert bubble_sort_swap_count([1, 4, 3, 2]) == 3
assert bubble_sort_swap_count([3, 2, 1]) == 3
assert bubble_sort_swap_count([1, 2, 3, 4, 5]) == 0
def test_min_swa... | [
{
"docstring": "Function to calculate the number of adjacent swaps required to sort the array using a bubble sort algorithm.",
"function_declaration": "def bubble_sort_swap_count(arr):",
"function_name": "bubble_sort_swap_count",
"parameter_list": "(arr)"
},
{
"docstring": "Given a list of a... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
1
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_code_contests-i2i_50000_1739866719_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def count_minimal_swaps(arr):\n \"\"\"\n Calculate the minimal number of swaps required to sort the array in non-decreasing order.\n Swaps only in... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00021744",
"row_id": 21744,
"seed_ids": "[9480]"
} | 0.67736 | Code_Contests_21744 | I | [
"bubble_sort_swap_count",
"min_swaps_to_sort",
"parse_input"
] | 3 | [
[
"min_swaps_to_sort",
"bubble_sort_swap_count"
]
] | 1 | [
"parse_input"
] | false | [] | false | pytest | true | [] | true | 742ba4a9e349f75dc9a60cee12faf0fe601da794 | ac8a40fbaf9872b7c9df049ffaea4e0941ffb8ac | |||
v1.0 | instruct | Code_Contests | Code_Contests_21753_I | Alice is designing a new social network platform and needs to create a way to identify the shortest path users can take between any two given people in her network. The network is represented as an unweighted, undirected graph where each person is a node, and a friendship between two people is an edge between the corre... | from collections import deque
def bfs_shortest_path(graph, start, end):
"""
Use BFS to find the shortest path in an unweighted graph.
"""
visited = set()
queue = deque([(start, 0)]) # (current_node, current_distance)
while queue:
current, distance = queue.popleft()
... | from solution import shortest_paths
def test_shortest_paths():
n = 6
edges = [
(1, 2),
(1, 3),
(3, 4),
(2, 4),
(4, 5),
(5, 6),
(3, 6)
]
queries = [
(1, 5),
(6, 1),
(2, 6)
]
assert shortest_paths(n, edges, queries) ... | [
{
"docstring": "Use BFS to find the shortest path in an unweighted graph.",
"function_declaration": "def bfs_shortest_path(graph, start, end):",
"function_name": "bfs_shortest_path",
"parameter_list": "(graph, start, end)"
},
{
"docstring": "Build an undirected graph from edge list.",
"f... | [
0,
0,
0,
0,
1
] | 1 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_code_contests-i2i_50000_1739866719_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from collections import deque\n\ndef bfs_shortest_path(graph, start, end):\n \"\"\"\n Function to find the shortest path between start and end nodes ... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "00021753",
"row_id": 21753,
"seed_ids": "[9849]"
} | 0.696682 | Code_Contests_21753 | I | [
"bfs_shortest_path",
"build_graph",
"shortest_paths"
] | 3 | [
[
"shortest_paths",
"bfs_shortest_path"
],
[
"shortest_paths",
"build_graph"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | d67a5f05e6163b15e590824b9abe8d2d6031e4d1 | 8c0b788be4c4a358e8821a70b824e66464d9d8f4 | |||
v1.0 | instruct | Code_Contests | Code_Contests_21755_I | Write a program that calculates the minimum number of coins needed to make up a given amount with an infinite supply of coins of given denominations. Your solution should find the minimum coin count for each amount in a series of input datasets. If it is not possible to make up the amount with the given coin denominati... | def min_coins(n, amount, coins):
max_val = amount + 1
dp = [max_val] * (amount + 1)
dp[0] = 0
for coin in coins:
for x in range(coin, amount + 1):
dp[x] = min(dp[x], dp[x - coin] + 1)
return dp[amount] if dp[amount] != max_val else -1
def find_min_coins(datasets):
... | import pytest
from solution import parse_input_and_solve
def test_sample_case():
input_str = "3\n3 11\n1 2 5\n2 7\n2 4\n5 23\n2 5 10 1 2\n"
expected_output = "3\n-1\n4"
assert parse_input_and_solve(input_str) == expected_output
def test_single_coin():
input_str = "1\n1 10\n1\n"
expected_output = "... | [
{
"docstring": null,
"function_declaration": "def min_coins(n, amount, coins):",
"function_name": "min_coins",
"parameter_list": "(n, amount, coins)"
},
{
"docstring": null,
"function_declaration": "def find_min_coins(datasets):",
"function_name": "find_min_coins",
"parameter_lis... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_code_contests-i2i_50000_1739866719_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def min_coins(t, datasets):\n def find_min_coins(coins, amount):\n dp = [float('inf')] * (amount + 1)\n dp[0] = 0\n \n for c... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00021755",
"row_id": 21755,
"seed_ids": "[1027]"
} | 0.761206 | Code_Contests_21755 | I | [
"min_coins",
"find_min_coins",
"parse_input_and_solve"
] | 3 | [
[
"find_min_coins",
"min_coins"
],
[
"parse_input_and_solve",
"find_min_coins"
]
] | 2 | [
"parse_input_and_solve"
] | false | [] | false | pytest | true | [] | true | 9721182a28b27e931b30495aae2840d14b9ec659 | 4ae6cc502339b33c21d3e0d8459f2210aae70578 | |||
v1.0 | instruct | Code_Contests | Code_Contests_21786_I | The residents of a remote mountain village have successfully developed a unique method of encoding their messages using a blend of alphanumeric characters, but they fear their communications might be vulnerable to interception by outside forces. To ensure only the intended receiver can understand the message, they deci... | def shift_char(c, shift):
if 'a' <= c <= 'z':
return chr((ord(c) - ord('a') + shift) % 26 + ord('a'))
elif 'A' <= c <= 'Z':
return chr((ord(c) - ord('A') + shift) % 26 + ord('A'))
else:
return c
def encrypt_decrypt_message(S, M, mode):
if mode == "encrypt":
shift = S
... | from solution import encrypt_decrypt_message
def test_encrypt_simple_message():
assert encrypt_decrypt_message(3, "hello", "encrypt") == "khoor"
def test_decrypt_simple_message():
assert encrypt_decrypt_message(3, "khoor", "decrypt") == "hello"
def test_encrypt_with_wrap_around():
assert encrypt_decrypt_... | [
{
"docstring": null,
"function_declaration": "def shift_char(c, shift):",
"function_name": "shift_char",
"parameter_list": "(c, shift)"
},
{
"docstring": null,
"function_declaration": "def encrypt_decrypt_message(S, M, mode):",
"function_name": "encrypt_decrypt_message",
"paramet... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_code_contests-i2i_50000_1739866719_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def shift_char(c, shift, encrypt=True):\n '''\n Helper function to shift a single character `c` by `shift` positions.\n If `encrypt` is True, shif... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00021786",
"row_id": 21786,
"seed_ids": "[11833]"
} | 0.653904 | Code_Contests_21786 | I | [
"shift_char",
"encrypt_decrypt_message"
] | 2 | [
[
"encrypt_decrypt_message",
"shift_char"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 88efb02786eb5f05d6e19fe15076aa9ef7b9b6a1 | a43daa98a4a79120e9bbc633b04d9d3adfed727d | |||
v1.0 | instruct | Code_Contests | Code_Contests_21837_I | Amara is a gardener and loves to arrange her flower pots in a specific fashion. She wants to arrange the pots such that the number of flower pots in each row is strictly increasing by one from the previous row. For instance, if the first row has 1 flower pot, the second row should have 2 flower pots, the third row shou... | def max_complete_rows(N):
"""
Given a number of flower pots N, returns the maximum number of rows
that can be completely filled such that each row has an incremental
number of flower pots starting from 1.
"""
# The total number of pots needed for filling x rows is the sum of the first x natura... | from solution import max_complete_rows, max_rows_for_cases
def test_max_complete_rows():
assert max_complete_rows(7) == 3
assert max_complete_rows(10) == 4
assert max_complete_rows(1) == 1
assert max_complete_rows(15) == 5
assert max_complete_rows(6) == 3
assert max_complete_rows(0) == 0
as... | [
{
"docstring": "Given a number of flower pots N, returns the maximum number of rows \nthat can be completely filled such that each row has an incremental \nnumber of flower pots starting from 1.",
"function_declaration": "def max_complete_rows(N):",
"function_name": "max_complete_rows",
"parameter_l... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_code_contests-i2i_50000_1739866719_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def max_complete_rows(N):\n \"\"\"\n Given a number of flower pots N, returns the maximum number of rows \n that can be completely filled such tha... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00021837",
"row_id": 21837,
"seed_ids": "[834]"
} | 0.649253 | Code_Contests_21837 | I | [
"max_complete_rows",
"max_rows_for_cases",
"solve"
] | 3 | [
[
"max_rows_for_cases",
"max_complete_rows"
],
[
"solve",
"max_rows_for_cases"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 683dc9eec1cab55876176e05ed8d9686d6370541 | ff0e82fe4136c56d0153dd22bf69cba4ea7f9e88 | |||
v1.0 | instruct | Code_Contests | Code_Contests_21971_I | Johnny is trying out a new game on his phone where he needs to navigate through a grid. The grid is an n x m grid filled with non-negative integers. Johnny starts at the top-left corner (1,1) (which is position (0,0) in index programming) and he must reach the bottom-right corner (n,m) (which is position (n-1,m-1) in i... | def min_path_sum(grid):
n = len(grid)
m = len(grid[0])
# Initialize the dp array with the same dimensions as grid
dp = [[0] * m for _ in range(n)]
# Start with the top-left corner
dp[0][0] = grid[0][0]
# Fill the first row (can only move from the left)
for j in range(1, m)... | from solution import min_path_sum_from_input
def test_min_path_sum_case1():
assert min_path_sum_from_input(3, 3, [1, 3, 1, 1, 5, 1, 4, 2, 1]) == 7
def test_min_path_sum_case2():
assert min_path_sum_from_input(2, 2, [1, 2, 1, 1]) == 3
def test_min_path_sum_single_cell():
assert min_path_sum_from_input(1, ... | [
{
"docstring": null,
"function_declaration": "def min_path_sum(grid):",
"function_name": "min_path_sum",
"parameter_list": "(grid)"
},
{
"docstring": null,
"function_declaration": "def min_path_sum_from_input(n, m, grid_data):",
"function_name": "min_path_sum_from_input",
"parame... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_code_contests-i2i_50000_1739866719_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def min_path_sum(n, m, grid):\n \"\"\"\n Calculates the minimum sum of all numbers along the path from top-left to bottom-right corner of the grid.\n... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00021971",
"row_id": 21971,
"seed_ids": "[882]"
} | 0.710734 | Code_Contests_21971 | I | [
"min_path_sum",
"min_path_sum_from_input"
] | 2 | [
[
"min_path_sum_from_input",
"min_path_sum"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 43e1f1cbed4dc13b446547cb5042f73715835bf5 | b7dab0f8c83281f46789628eb825206dedffff6c | |||
v1.0 | instruct | Code_Contests | Code_Contests_22035_I | You are given a sequence of `n` integers. You have to perform a specific type of query on the sequence multiple times. Each query is defined by two integers `l` and `r` and requires you to find the maximum value in the subarray starting at index `l` and ending at index `r`. The task is to efficiently handle multiple su... | def preprocess_max_values(sequence):
"""
Preprocesses the sequence to provide a data structure enabling efficient range maximum queries.
Args:
- sequence (list of int): The list of integers representing the sequence.
Returns:
- list of list of int: Sparse table prepared for range maxim... | from solution import handle_queries
def test_handle_queries_example():
sequence = [1, 3, 5, 7, 9]
queries = [(1, 3), (2, 4), (1, 5)]
expected = [5, 7, 9]
assert handle_queries(sequence, queries) == expected
def test_handle_queries_single_element_subarray():
sequence = [1, 3, 5, 7, 9]
queries =... | [
{
"docstring": "Preprocesses the sequence to provide a data structure enabling efficient range maximum queries.\n\nArgs:\n- sequence (list of int): The list of integers representing the sequence.\n\nReturns:\n- list of list of int: Sparse table prepared for range maximum queries.",
"function_declaration": "... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_code_contests-i2i_50000_1739866719_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def find_max_in_subarray(sequence, queries):\n \"\"\"\n For each query, find the maximum value in the subarray specified by indices l and r.\n \n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00022035",
"row_id": 22035,
"seed_ids": "[12008]"
} | 0.722202 | Code_Contests_22035 | I | [
"preprocess_max_values",
"query_max_in_subarray",
"handle_queries"
] | 3 | [
[
"handle_queries",
"preprocess_max_values"
],
[
"handle_queries",
"query_max_in_subarray"
]
] | 2 | [
"handle_queries"
] | false | [] | false | pytest | true | [] | true | 911ba9e970b2d585f24fae431ac632832a562957 | d51b2a53420d3e80fceb329aada67f37cceec6e9 | |||
v1.0 | instruct | Code_Contests | Code_Contests_22092_I | Problem
You are given a two-dimensional grid. Each cell of the grid is identified by a pair of coordinates (i, j) and contains either a `1` or a `0`. You can move vertically or horizontally from one cell to another. A group of connected `1`s forms a cluster. You need to find the number of clusters of `1`s in the grid.... | def count_clusters(m, n, grid):
def dfs(i, j):
if i < 0 or i >= m or j < 0 or j >= n or grid[i][j] == 0:
return
grid[i][j] = 0 # Mark as visited
# explore all four directions
dfs(i-1, j)
dfs(i+1, j)
dfs(i, j-1)
dfs(i, j+1)
clusters = 0
fo... | import pytest
from solution import count_clusters_from_input
def test_example_case_1():
input_str = "3 3\n1 0 1\n0 1 0\n1 0 1"
assert count_clusters_from_input(input_str) == 5
def test_example_case_2():
input_str = "4 5\n1 0 0 1 0\n0 1 0 1 0\n0 0 1 0 1\n1 0 1 1 0"
assert count_clusters_from_input(inpu... | [
{
"docstring": null,
"function_declaration": "def count_clusters(m, n, grid):",
"function_name": "count_clusters",
"parameter_list": "(m, n, grid)"
},
{
"docstring": null,
"function_declaration": "def parse_input(input_str):",
"function_name": "parse_input",
"parameter_list": "(i... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_code_contests-i2i_50000_1739866719_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def num_clusters(m, n, grid):\n \"\"\"\n Returns the number of clusters of '1's in the given grid.\n \"\"\"\n def dfs(i, j):\n if i < 0 ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00022092",
"row_id": 22092,
"seed_ids": "[5511]"
} | 0.612276 | Code_Contests_22092 | I | [
"count_clusters",
"parse_input",
"count_clusters_from_input"
] | 3 | [
[
"count_clusters_from_input",
"count_clusters"
],
[
"count_clusters_from_input",
"parse_input"
]
] | 2 | [
"parse_input"
] | false | [] | false | pytest | true | [] | true | 77970436dbe71776640db01b9632ad72ade95495 | 42bdbcbf8aeb95edc7e13dc905621b5e4767adeb |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.