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 | complete | Algorithm | Algorithm_23886_C | from typing import List, Tuple
def shortestPathToCollectAllGarbage(grid: List[List[str]]) -> int:
""" Calculates the minimum steps needed for a garbage truck starting at the top-left corner
of the grid (0, 0) to visit all garbage dumps and return to the starting position.
The grid contains obstacles repres... | from typing import List, Tuple
from collections import deque
from itertools import permutations
def bfs(grid: List[List[str]], start: Tuple[int, int]) -> dict:
q = deque([start])
visited = set([start])
distances = {start: 0}
while q:
x, y = q.popleft()
for dx, dy in [(-1, 0), (1, 0), (0... | def test_no_garbage():
grid = [['.']]
assert shortestPathToCollectAllGarbage(grid) == 0
def test_one_garbage():
grid = [['.', 'G']]
assert shortestPathToCollectAllGarbage(grid) == 2
def test_two_garbage():
grid = [['.', 'G', '.'],
['.', 'X', 'G']]
assert shortestPathToCollectAllGar... | [
{
"docstring": null,
"function_declaration": "def bfs(grid, start):",
"function_name": "bfs",
"parameter_list": "(grid, start)"
},
{
"docstring": null,
"function_declaration": "def shortestPathToCollectAllGarbage(grid):",
"function_name": "shortestPathToCollectAllGarbage",
"param... | [
0,
0,
0,
0,
0,
0,
0,
0,
1,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List, Tuple\nfrom collections import deque\n\ndef shortestPathToCollectAllGarbage(grid: List[List[str]]) -> int:\n def bfs(start: Tuple[int... | trial_gpt4o_8 | {
"original_instruction": "### Scenario:\nYou are in charge of developing an algorithm to generate the most efficient route for garbage collection trucks in a city. The city map is represented as a grid with certain cells marked as garbage dumps.\n\n### Problem Description:\nImplement the function `shortestPathToColl... | 0.594332 | Algorithm_23886 | C | [
"bfs",
"shortestPathToCollectAllGarbage"
] | 2 | [
[
"shortestPathToCollectAllGarbage",
"bfs"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | c89bb83c6b45066fa477e0908ef8e38360b0669d | 6f77f1625bf13bbed63ec2ad65585a11dd11828e | |||
v1.0 | complete | Algorithm | Algorithm_37982_C | def kmp_search(text: str, pattern: str) -> list[int]:
""" Implement the KMP algorithm to find all occurrences of a pattern string within a text string.
>>> kmp_search("abracadabra", "abra")
[0, 7]
>>> kmp_search("hello", "ll")
[2]
>>> kmp_search("abcd", "ef")
[]
""" | def compute_lps(pattern):
lps = [0] * len(pattern)
length = 0
i = 1
while i < len(pattern):
if pattern[i] == pattern[length]:
length += 1
lps[i] = length
i += 1
else:
if length != 0:
length = lps[length - 1]
else... | from solution import kmp_search
def test_kmp_search_exact_match():
assert kmp_search("abracadabra", "abracadabra") == [0]
def test_kmp_search_multi_occurrences():
assert kmp_search("abracadabra", "abra") == [0, 7]
def test_kmp_search_single_occurrence():
assert kmp_search("hello", "ll") == [2]
def test_... | [
{
"docstring": null,
"function_declaration": "def compute_lps(pattern):",
"function_name": "compute_lps",
"parameter_list": "(pattern)"
},
{
"docstring": null,
"function_declaration": "def kmp_search(text, pattern):",
"function_name": "kmp_search",
"parameter_list": "(text, patte... | [
1,
1,
0,
0,
1,
1,
0,
0,
1
] | 5 | medium | 0.556 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def kmp_search(text: str, pattern: str) -> list[int]:\n \"\"\"\n Returns a list of starting indices where 'pattern' is found within 'text' using the KMP al... | trial_gpt4o_4 | {
"original_instruction": "## Challenge: Efficient String Matching with the KMP Algorithm\n\n#### Background\nString matching is a classic problem in computer science. The Knuth-Morris-Pratt (KMP) algorithm is an efficient string matching algorithm that searches for occurrences of a \"pattern\" string within a \"text... | 0.527519 | Algorithm_37982 | C | [
"compute_lps",
"kmp_search"
] | 2 | [
[
"kmp_search",
"compute_lps"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 35b894b427689af72d295b1d3181eae310176885 | 85caca44cdc2abe55da5ea7b5378b0d0644b8b40 | |||
v1.0 | complete | Algorithm | Algorithm_29209_C | import math
def next_prime(n: int) -> int:
""" Return the smallest prime number greater than `n`.
>>> next_prime(3) 5
>>> next_prime(11) 13
>>> next_prime(17) 19
>>> next_prime(24) 29
"""
pass
# Unit Tests
def test_next_prime_small_numbers():
assert next_prime(1) == 2
assert next_p... | import math
def is_prime(num):
"""
Efficient check if a number is prime.
"""
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:
retu... | from solution import next_prime
def test_next_prime_small_numbers():
assert next_prime(1) == 2
assert next_prime(2) == 3
assert next_prime(3) == 5
assert next_prime(4) == 5
def test_next_prime_reasonable_numbers():
assert next_prime(11) == 13
assert next_prime(17) == 19
assert next_prime(2... | [
{
"docstring": "Efficient check if a number is prime.",
"function_declaration": "def is_prime(num):",
"function_name": "is_prime",
"parameter_list": "(num)"
},
{
"docstring": "Returns the smallest prime number greater than n.",
"function_declaration": "def next_prime(n):",
"function_... | [
0,
1,
0,
1,
1,
0,
1,
0,
0,
0
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import math\n\ndef is_prime(number):\n \"\"\"\n Helper function to determine if a number is prime.\n \"\"\"\n if number <= 1:\n return False\n... | trial_gpt4o_1 | {
"original_instruction": "### Coding Assessment Question\n\nYou are tasked with writing a function `next_prime(n: int) -> int` which takes an integer `n` and returns the smallest prime number greater than `n`.\n\n**Function Signature**:\n```python\ndef next_prime(n: int) -> int:\n pass\n```\n\n### Input\n- An int... | 0.715871 | Algorithm_29209 | C | [
"is_prime",
"next_prime"
] | 2 | [
[
"next_prime",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f79deddf2f2af0983cd09821e86fe47fee354774 | 5532a4c675bc85db36205d2cd407724d3f288689 | |||
v1.0 | complete | Algorithm | Algorithm_28339_C | from typing import List
def is_prime(num: int) -> bool:
""" Check if a number is prime.
:param num: int - The number to check.
:return: bool - True if the number is prime, False otherwise.
"""
def prime_fibonacci(limit: int) -> List[int]:
""" Identify all prime Fibonacci numbers up to a given limi... | from typing import List
def is_prime(num: int) -> bool:
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:
return False
i += 6
retur... | from solution import prime_fibonacci
def test_prime_fibonacci_up_to_50():
assert prime_fibonacci(50) == [2, 3, 5, 13]
def test_prime_fibonacci_up_to_100():
assert prime_fibonacci(100) == [2, 3, 5, 13, 89]
def test_prime_fibonacci_up_to_0():
assert prime_fibonacci(0) == []
def test_prime_fibonacci_up_to_... | [
{
"docstring": null,
"function_declaration": "def is_prime(num):",
"function_name": "is_prime",
"parameter_list": "(num)"
},
{
"docstring": null,
"function_declaration": "def prime_fibonacci(limit):",
"function_name": "prime_fibonacci",
"parameter_list": "(limit)"
}
] | [
0,
0,
1,
1,
1,
0,
0,
0,
0,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef is_prime(num: int) -> bool:\n if num <= 1:\n return False\n if num <= 3:\n return True\n if num % 2 == 0 or... | trial_gpt4o_4 | {
"original_instruction": "### Fibonacci Prime Detection\n\n### Background\nThe Fibonacci sequence is a series of numbers in which each number is the sum of the two preceding ones, usually starting with 0 and 1. An interesting problem emerges when you try to identify which of these Fibonacci numbers are prime.\n\n###... | 0.796468 | Algorithm_28339 | C | [
"is_prime",
"prime_fibonacci"
] | 2 | [
[
"prime_fibonacci",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 3404836fdb213240784952562a93f7309eeb1df3 | 5edc712a7a8b6007ab3a3725baf00c40bd230f66 | |||
v1.0 | complete | Algorithm | Algorithm_16347_C | def kruskal_min_spanning_tree(graph, n):
""" Compute the minimum spanning tree (MST) of a graph using Kruskal's algorithm.
The function should return a tuple with two elements:
1. An integer representing the total weight of the MST.
2. A list of tuples representing the edges in the MST (u, v, w), w... | def find(parent, i):
if parent[i] == i:
return i
return find(parent, parent[i])
def union(parent, rank, x, y):
rootX = find(parent, x)
rootY = find(parent, y)
if rank[rootX] < rank[rootY]:
parent[rootX] = rootY
elif rank[rootX] > rank[rootY]:
parent[rootY] = rootX
... | def test_kruskal_min_spanning_tree():
test_graph1 = [
[0, 2, 0, 6, 0],
[2, 0, 3, 8, 5],
[0, 3, 0, 0, 7],
[6, 8, 0, 0, 9],
[0, 5, 7, 9, 0]
]
num_vertices1 = 5
expected1 = (16, [(0, 1, 2), (1, 2, 3), (1, 4, 5), (0, 3, 6)])
assert kruskal_min_spanning_tree(test_g... | [
{
"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,
0,
0,
1,
0,
0,
0,
0,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def find(parent, i):\n if parent[i] == i:\n return i\n return find(parent, parent[i])\n\ndef union(parent, rank, x, y):\n root_x = find(parent, x... | trial_gpt4o_3 | {
"original_instruction": "## Task\nQuestion Creation for Coding Assessment\n\n## Objective\nAnalyze the provided sample questions and create an additional question that aligns with the existing set in terms of style, complexity, and scope.\n\n## Guidelines\n\n### Question Style\n- Carefully examine the format and pr... | 0.645641 | Algorithm_16347 | C | [
"find",
"union",
"kruskal_min_spanning_tree"
] | 3 | [
[
"kruskal_min_spanning_tree",
"find"
],
[
"kruskal_min_spanning_tree",
"union"
],
[
"union",
"find"
]
] | 3 | [] | false | [] | false | pytest | false | [] | true | 5a825774e9d758c139842b42e33e7611aabd21b6 | 0bd1efee1530000240244ca9334cc4ca5a3b4c14 | |||
v1.0 | complete | Algorithm | Algorithm_33873_C | def read_lines(input_file: str) -> list:
"""
Reads all lines from the input file and returns a list of lines.
Parameters:
input_file (str): Path to the input file.
Returns:
list: List of lines from the file.
"""
pass
def sort_lines(lines: list) -> list:
"""
Sorts a lis... | def read_lines(input_file):
"""
Reads all lines from the input file and returns a list of lines.
Parameters:
input_file (str): Path to the input file.
Returns:
list: List of lines from the file.
"""
with open(input_file, 'r') as file:
lines = file.readlines()
return... | from solution import read_lines, sort_lines, write_lines, sort_large_text_file
import os
def test_read_lines(tmp_path):
# Arrange
input_file = tmp_path / "input.txt"
input_file.write_text("apple\nbanana\norange\napple banana\n")
# Act
lines = read_lines(input_file)
# Assert
assert... | [
{
"docstring": "Reads all lines from the input file and returns a list of lines.\n\nParameters:\ninput_file (str): Path to the input file.\n\nReturns:\nlist: List of lines from the file.",
"function_declaration": "def read_lines(input_file):",
"function_name": "read_lines",
"parameter_list": "(input... | [
1,
1,
0,
1,
1,
1,
1,
1,
1,
1
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def read_lines(input_file):\n \"\"\"\n Reads all lines from the input file.\n \n :param input_file: Path to the input file\n :return: List of line... | trial_gpt4o_9 | {
"original_instruction": "### Sorting Large Text Files\n\nYou are provided with a very large text file containing many lines of words. Each line is either a single word or consists of words separated by spaces. Your task is to create a Python script to sort all the lines of this file in alphabetical order and write ... | 0.53902 | Algorithm_33873 | C | [
"read_lines",
"sort_lines",
"write_lines",
"sort_large_text_file"
] | 4 | [
[
"sort_large_text_file",
"read_lines"
],
[
"sort_large_text_file",
"sort_lines"
],
[
"sort_large_text_file",
"write_lines"
]
] | 3 | [
"read_lines"
] | false | [] | false | pytest | true | [] | true | b3b03d4bc88af14dbf5eeea00f7c97577072967b | e967e043fa6b3c3926872573239ad22a5891eae6 | |||
v1.0 | complete | Algorithm | Algorithm_28467_C | def rank_students_by_average(student_records: list[tuple[int, list[int]]]) -> tuple[list[tuple[int, float]], float]:
"""
This function ranks students based on their average scores.
Parameters:
student_records (list[tuple[int, list[int]]]): The list of student records.
Returns:
tuple: A... | def calculate_average(scores):
return sum(scores) / len(scores)
def rank_students_by_average(student_records):
# Calculate average scores
student_averages = [
(student_id, round(calculate_average(scores), 2))
for student_id, scores in student_records
]
# Sort by average score d... | from solution import rank_students_by_average
def test_rank_students_basic():
student_records = [
(101, [75, 80, 85]),
(102, [90, 85, 80]),
(103, [80, 70, 80]),
(104, [65, 70, 60])
]
assert rank_students_by_average(student_records) == ([(102, 85.0), (101, 80.0), (103, 76.67)... | [
{
"docstring": null,
"function_declaration": "def calculate_average(scores):",
"function_name": "calculate_average",
"parameter_list": "(scores)"
},
{
"docstring": null,
"function_declaration": "def rank_students_by_average(student_records):",
"function_name": "rank_students_by_avera... | [
0,
0,
1,
0,
0,
0,
1,
0,
0
] | 2 | hard | 0.222 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def rank_students_by_average(student_records):\n \"\"\"\n This function ranks students based on their average scores.\n\n Parameters:\n student_r... | trial_gpt4o_7 | {
"original_instruction": "### Coding Assessment Question\n\nYou are given a list of student records, where each record contains the student ID and a list of their scores across multiple subjects. Your task is to calculate the average score for each student and then rank the students based on their average scores, wi... | 0.711489 | Algorithm_28467 | C | [
"calculate_average",
"rank_students_by_average"
] | 2 | [
[
"rank_students_by_average",
"calculate_average"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 3efa7370be961830dcd6cbafeb1e61449d587468 | ca3d9d9b7f8b4da90aff52c526704d068a437625 | |||
v1.0 | complete | Algorithm | Algorithm_35804_C | def count_primes_in_range(start: int, end: int) -> int:
""" Count the number of prime numbers in a given range of integers.
>>> count_primes_in_range(10, 30)
6
>>> count_primes_in_range(24, 28)
0
"""
pass
# Unit tests
def test_primes_in_small_range():
assert count_primes_in_range(10, 30... | import math
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 count_primes_in_range(start: ... | from solution import count_primes_in_range
def test_primes_in_small_range():
assert count_primes_in_range(10, 30) == 6 # Prime numbers: 11, 13, 17, 19, 23, 29
def test_primes_with_zero_range():
assert count_primes_in_range(10, 10) == 0 # No prime number in the range
def test_primes_with_large_numbers():
... | [
{
"docstring": null,
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def count_primes_in_range(start, end):",
"function_name": "count_primes_in_range",
"parameter_list": "(start, end... | [
0,
0,
0,
0,
0,
0,
0,
1,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_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 return Fals... | trial_gpt4o_7 | {
"original_instruction": "### Problem Scenario\nYou are tasked with developing a function that counts the number of prime numbers in a given range of integers. This will test your understanding of number theory and optimization techniques in algorithms.\n\n### Task\nWrite a function `count_primes_in_range(start: int... | 0.686161 | Algorithm_35804 | C | [
"is_prime",
"count_primes_in_range"
] | 2 | [
[
"count_primes_in_range",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 88418c8a74969f672de2b2301bc3c12218ed996c | 9a73c34ff43e79ece54cb4dd9e3ceb05600e2e4d | |||
v1.0 | complete | Algorithm | Algorithm_16680_C | def longest_palindromic_substring(s: str) -> str:
"""
Find the longest palindromic substring in s.
>>> longest_palindromic_substring("babad") in ["bab", "aba"]
>>> longest_palindromic_substring("cbbd") == "bb"
>>> longest_palindromic_substring("a") == "a"
>>> longest_palindromic_substring("ac") ... | def longest_palindromic_substring(s: str) -> str:
"""
Find the longest palindromic substring in s.
"""
if len(s) == 0:
return ""
start, end = 0, 0
for i in range(len(s)):
len1 = expand_around_center(s, i, i)
len2 = expand_around_center(s, i, i + 1)
max_len = max... | from solution import longest_palindromic_substring, word_pattern, character_frequency
def test_longest_palindromic_substring():
assert longest_palindromic_substring("babad") in ["bab", "aba"]
assert longest_palindromic_substring("cbbd") == "bb"
assert longest_palindromic_substring("a") == "a"
assert lo... | [
{
"docstring": "Find the longest palindromic substring in s.",
"function_declaration": "def longest_palindromic_substring(s):",
"function_name": "longest_palindromic_substring",
"parameter_list": "(s)"
},
{
"docstring": null,
"function_declaration": "def expand_around_center(s, left, rig... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 10 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def longest_palindromic_substring(s: str) -> str:\n n = len(s)\n if n == 0:\n return \"\"\n \n def expand_around_center(left: int, right: int)... | trial_gpt4o_9 | {
"original_instruction": "### Question: String Manipulation and Pattern Matching\n\n**Context:**\nYou are developing a string manipulation library and need to include functionality that addresses common text processing tasks. This library will handle operations involving word patterns, character sequences, and speci... | 0.741582 | Algorithm_16680 | C | [
"longest_palindromic_substring",
"expand_around_center",
"word_pattern",
"character_frequency"
] | 4 | [
[
"longest_palindromic_substring",
"expand_around_center"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 53f6ea09c6b9e9ff557949e26b1fd6f3ccf168a2 | 362c8660d30914792e27e4d5ef6ba99575c4315b | |||
v1.0 | complete | Algorithm | Algorithm_20232_C | Implement an Efficient Version of QuickSelect
The QuickSelect algorithm is used to find the k-th smallest element in an unordered list. Although effective, its performance can be improved by optimizing the partitioning step and mitigating poor pivot choices.
Hint: A median of medians or random pivot selection can imp... | import random
def partition(arr, low, high):
pivot_index = random.randint(low, high)
pivot = arr[pivot_index]
arr[pivot_index], arr[high] = arr[high], arr[pivot_index]
i = low - 1
for j in range(low, high):
if arr[j] <= pivot:
i += 1
arr[i], arr[j] = arr[j], arr[i]
... | from solution import efficient_quickselect
def test_quickselect_example_cases():
assert efficient_quickselect([3, 1, 5, 2, 4], 3) == 3
assert efficient_quickselect([10, 4, 5, 8, 6, 11, 26], 5) == 10
assert efficient_quickselect([2, 6, 10, 15], 1) == 2
assert efficient_quickselect([2, 6, 10, 15], 5) == ... | [
{
"docstring": null,
"function_declaration": "def partition(arr, low, high):",
"function_name": "partition",
"parameter_list": "(arr, low, high)"
},
{
"docstring": null,
"function_declaration": "def quickselect(arr, low, high, k):",
"function_name": "quickselect",
"parameter_list... | [
1,
1,
1,
1,
1,
0,
1,
1,
1,
1
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def efficient_quickselect(arr: list, k: int) -> int:\n \"\"\"\n Efficient QuickSelect implementation.\n\n :param arr: Unordered input list\n :param k... | trial_gpt4o_9 | {
"original_instruction": "### Question: Implement an Efficient Version of QuickSelect\n\nThe QuickSelect algorithm is used to find the k-th smallest element in an unordered list. Although effective, its performance can be improved by optimizing the partitioning step and mitigating poor pivot choices.\n\n#### Require... | 0.567931 | Algorithm_20232 | C | [
"partition",
"quickselect",
"efficient_quickselect"
] | 3 | [
[
"efficient_quickselect",
"quickselect"
],
[
"quickselect",
"partition"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 0cc7bb56c913bdf32f6acb27860f1695cfa99456 | 4c7ff0d42e91c82ec665da515c884f2ac8284ad3 | |||
v1.0 | complete | Algorithm | Algorithm_40197_C | from typing import List, Tuple
def calculate_distance(point1: Tuple[int, int], point2: Tuple[int, int]) -> float:
""" Calculates the Euclidean distance between two points. """
def nearest_neighbor_tsp(locations: List[Tuple[int, int]]) -> List[int]:
"""
Heuristic solution to find a TSP route using the nea... | import math
from typing import List, Tuple
def calculate_distance(point1: Tuple[int, int], point2: Tuple[int, int]) -> float:
return math.sqrt((point1[0] - point2[0]) ** 2 + (point1[1] - point2[1]) ** 2)
def nearest_neighbor_tsp(locations: List[Tuple[int, int]]) -> List[int]:
n = len(locations)
if n == 1:... | from solution import nearest_neighbor_tsp
def test_single_location():
assert nearest_neighbor_tsp([(0, 0)]) == [0, 0]
def test_two_locations():
assert nearest_neighbor_tsp([(0, 0), (1, 1)]) == [0, 1, 0]
def test_three_locations():
assert nearest_neighbor_tsp([(0, 0), (2, 3), (5, 4)]) == [0, 1, 2, 0]
def... | [
{
"docstring": null,
"function_declaration": "def calculate_distance(point1, point2):",
"function_name": "calculate_distance",
"parameter_list": "(point1, point2)"
},
{
"docstring": null,
"function_declaration": "def nearest_neighbor_tsp(locations):",
"function_name": "nearest_neighb... | [
0,
1,
1,
0,
1,
0,
0,
0,
0,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import math\n\ndef nearest_neighbor_tsp(locations):\n def distance(p1, p2):\n return math.sqrt((p2[0] - p1[0]) ** 2 + (p2[1] - p1[1]) ** 2)\n \n ... | trial_gpt4o_4 | {
"original_instruction": "### Problem Statement\n\nYou are managing a logistics company and need to optimize the daily delivery route for a single delivery truck. The truck starts from the depot (origin point) and must visit all customer locations exactly once and then return to the depot. This problem is conceptual... | 0.609085 | Algorithm_40197 | C | [
"calculate_distance",
"nearest_neighbor_tsp"
] | 2 | [
[
"nearest_neighbor_tsp",
"calculate_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | d1900cafd01b3ec9d9f709204c4bb8e23a28bb2d | d0461cff2380bf46e7dc6f010fab15db83a1883d | |||
v1.0 | complete | Algorithm | Algorithm_36523_C | from typing import List
def strassen_matrix_multiplication(A: List[List[int]], B: List[List[int]]) -> List[List[int]]:
"""
Perform matrix multiplication using the Strassen algorithm.
Parameters:
A (List[List[int]]): The first matrix as a list of lists, where each inner list represents a row.
... | from typing import List
def add_matrices(A, B):
return [[A[i][j] + B[i][j] for j in range(len(A))] for i in range(len(A))]
def subtract_matrices(A, B):
return [[A[i][j] - B[i][j] for j in range(len(A))] for i in range(len(A))]
def split_matrix(M):
mid = len(M) // 2
A11 = [row[:mid] for row in M[:mid]... | def test_strassen_example1():
A = [
[1, 0],
[0, 1]
]
B = [
[4, 1],
[2, 2]
]
expected = [
[4, 1],
[2, 2]
]
assert strassen_matrix_multiplication(A, B) == expected
def test_strassen_example2():
A = [
[1, 2],
[3, 4]
]
... | [
{
"docstring": null,
"function_declaration": "def add_matrices(A, B):",
"function_name": "add_matrices",
"parameter_list": "(A, B)"
},
{
"docstring": null,
"function_declaration": "def subtract_matrices(A, B):",
"function_name": "subtract_matrices",
"parameter_list": "(A, B)"
}... | [
0,
1,
1,
1,
1,
0,
1,
0,
1,
1
] | 7 | easy | 0.7 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef add_matrix(A, B):\n return [[A[i][j] + B[i][j] for j in range(len(A))] for i in range(len(A))]\n\ndef sub_matrix(A, B):\n re... | trial_gpt4o_9 | {
"original_instruction": "### Task\nYou are asked to implement a function to perform matrix multiplication using the Strassen algorithm. This algorithm is particularly effective for large matrices and reduces the time complexity compared to conventional methods.\n\n### Problem Statement\n\n**Function Signature**:\n`... | 0.502194 | Algorithm_36523 | C | [
"add_matrices",
"subtract_matrices",
"split_matrix",
"strassen_matrix_multiplication"
] | 4 | [
[
"strassen_matrix_multiplication",
"add_matrices"
],
[
"strassen_matrix_multiplication",
"split_matrix"
],
[
"strassen_matrix_multiplication",
"subtract_matrices"
]
] | 3 | [] | false | [] | false | pytest | false | [] | true | 49852fbe56e4ffb4f323f99fa8f4f4fc374062e3 | 459d09e6bf3e57af29e5c496ba3bd5677fad2131 | |||
v1.0 | complete | Algorithm | Algorithm_34807_C | from typing import List
def num_distinct_islands(grid: List[List[int]]) -> int:
"""Calculate the number of distinct island shapes in a given 2D grid.
An island is a group of connected 1s (land) connected horizontally or vertically (not diagonally).
Args:
grid (List[List[int]]): A 2D grid containin... | from typing import List, Set, Tuple
def rotate_90(shape):
""" Rotate the shape by 90 degrees """
return [(y, -x) for x, y in shape]
def reflect(shape):
""" Reflect the shape about the y-axis """
return [(-x, y) for x, y in shape]
def normalize_shape(shape):
""" Normalize the shape by rotating and... | import pytest
from solution import num_distinct_islands
def test_example_1():
grid = [
[1, 1, 0, 0, 0],
[1, 0, 0, 0, 1],
[0, 0, 0, 1, 1],
[0, 0, 0, 0, 0],
[1, 1, 0, 1, 1]
]
assert num_distinct_islands(grid) == 3
def test_example_2():
grid = [
[1, 1, 1],
... | [
{
"docstring": "Rotate the shape by 90 degrees ",
"function_declaration": "def rotate_90(shape):",
"function_name": "rotate_90",
"parameter_list": "(shape)"
},
{
"docstring": "Reflect the shape about the y-axis ",
"function_declaration": "def reflect(shape):",
"function_name": "refle... | [
0,
0,
0,
0,
1,
1,
0,
0,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List, Set, Tuple\n\ndef get_rotations_and_reflections(shape: List[Tuple[int, int]]) -> Set[Tuple[Tuple[int, int], ...]]:\n transformations ... | trial_gpt4o_5 | {
"original_instruction": "### Problem Statement\nYou are developing a new application that needs to compute the number of distinct island shapes in a given 2D grid. An island is a group of connected `1`s (land) connected horizontally or vertically (not diagonally). Two islands are considered distinct if one island's... | 0.55766 | Algorithm_34807 | C | [
"rotate_90",
"reflect",
"normalize_shape",
"num_distinct_islands"
] | 4 | [
[
"normalize_shape",
"reflect"
],
[
"normalize_shape",
"rotate_90"
],
[
"num_distinct_islands",
"normalize_shape"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 210d0653bb98e0f025039cf0860c2f420f77f332 | 1e6b558e16fb1716c7afd10239a996ea4982d1a6 | |||
v1.0 | complete | Algorithm | Algorithm_20651_C | class TreeNode:
def __init__(self, key: int):
self.key = key
self.left = None
self.right = None
def insert_into_bst(root: Optional[TreeNode], key: int) -> TreeNode:
"""Insert a node into a balanced BST while maintaining its balanced property."""
pass
def calculate_tree_height(root:... | class TreeNode:
def __init__(self, key: int):
self.key = key
self.left = None
self.right = None
self.height = 1 # New TreeNode is at height 1 (leaf)
def get_height(node):
return node.height if node else 0
def update_height(node):
if node:
node.height = 1 + max(get_... | from solution import TreeNode, insert_into_bst, calculate_tree_height, trace_heights_after_inserts
def test_insert_into_bst():
root = None
root = insert_into_bst(root, 10)
assert root.key == 10
root = insert_into_bst(root, 20)
assert root.right.key == 20
root = insert_into_bst(root, 5)
asse... | [] | [
1,
1,
0,
0,
0,
1,
1,
0,
1,
1
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "class TreeNode:\n def __init__(self, key: int):\n self.key = key\n self.left = None\n self.right = None\n self.height = 1 # Heigh... | trial_gpt4o_6 | {
"original_instruction": "### Coding Question\n\nA balanced binary search tree (BST) is a type of binary tree where the left subtree contains only nodes with keys less than the node's key, and the right subtree contains only nodes with keys greater than the node's key. Additionally, the tree is balanced to minimize ... | 0.589727 | Algorithm_20651 | C | [
"get_height",
"update_height",
"get_balance",
"left_rotate",
"right_rotate",
"insert_into_bst",
"calculate_tree_height",
"trace_heights_after_inserts"
] | 8 | [
[
"get_balance",
"get_height"
],
[
"insert_into_bst",
"get_balance"
],
[
"insert_into_bst",
"left_rotate"
],
[
"insert_into_bst",
"right_rotate"
],
[
"insert_into_bst",
"update_height"
],
[
"left_rotate",
"update_height"
],
[
"right_rotate"... | 10 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | fb3f18c6569dba27f1bb8748c6a6c2ed82f355df | a72f0e5faf3fa5f2805c209ff28feab003ba874b | |||
v1.0 | complete | Algorithm | Algorithm_46407_C | def is_palindrome(num: int) -> bool:
"""
Checks if a number is a palindrome.
>>> is_palindrome(121)
True
>>> is_palindrome(123)
False
>>> is_palindrome(1)
True
>>> is_palindrome(22)
True
"""
def is_prime(num: int) -> bool:
"""
Checks if a number is prime.
>>>... | def is_palindrome(num: int) -> bool:
"""
Checks if a number is a palindrome.
"""
return str(num) == str(num)[::-1]
def is_prime(num: int) -> bool:
"""
Checks if a number is prime.
"""
if num <= 1:
return False
if num <= 3:
return True
if num % 2 == 0 or num % 3 =... | from solution import is_palindrome, is_prime, smallest_prime_palindrome
def test_is_palindrome():
assert is_palindrome(121) == True
assert is_palindrome(123) == False
assert is_palindrome(1) == True
assert is_palindrome(22) == True
def test_is_prime():
assert is_prime(2) == True
assert is_prim... | [
{
"docstring": "Checks if a number is a palindrome.",
"function_declaration": "def is_palindrome(num):",
"function_name": "is_palindrome",
"parameter_list": "(num)"
},
{
"docstring": "Checks if a number is prime.",
"function_declaration": "def is_prime(num):",
"function_name": "is_pr... | [
0,
0,
1,
1,
0,
1,
0,
1,
0,
1
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def is_palindrome(num):\n \"\"\"\n Checks whether a given number is a palindrome.\n \"\"\"\n return str(num) == str(num)[::-1]\n\ndef is_prime(num):\... | trial_gpt4o_9 | {
"original_instruction": "### Prime Palindrome Challenge\n\n#### Overview:\nYou are given a positive integer `N`. Your task is to find the smallest prime number greater than or equal to `N` that is also a palindrome. A palindrome is a number that reads the same forward and backward, such as 121 or 797.\n\n#### Funct... | 0.71715 | Algorithm_46407 | C | [
"is_palindrome",
"is_prime",
"smallest_prime_palindrome"
] | 3 | [
[
"smallest_prime_palindrome",
"is_palindrome"
],
[
"smallest_prime_palindrome",
"is_prime"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 9f3913a9437b504a6983602428c59cc513c0f385 | 281c52c9f76b81ec31827926fc1f0f94846aa3a1 | |||
v1.0 | complete | Algorithm | Algorithm_5539_C | import json
import pickle
import xml.etree.ElementTree as ET
def json_serialize(obj):
"""
Serializes a Python data structure to a JSON formatted string.
"""
try:
return json.dumps(obj)
except (TypeError, ValueError) as e:
raise ValueError(f"Unable to serialize object to JSON: {str(e... | import json
import pickle
import xml.etree.ElementTree as ET
def json_serialize(obj):
"""
Serializes a Python data structure to a JSON formatted string.
"""
try:
return json.dumps(obj)
except (TypeError, ValueError) as e:
raise ValueError(f"Unable to serialize object to JSON: {str(e... | import pytest
from solution import json_serialize, json_deserialize, xml_serialize, xml_deserialize, binary_serialize, binary_deserialize
# JSON Tests
def test_json_serialize_deserialize():
data = {"name": "Alice", "age": 30, "city": "Wonderland"}
json_str = json_serialize(data)
result = json_deserialize(j... | [
{
"docstring": "Serializes a Python data structure to a JSON formatted string.",
"function_declaration": "def json_serialize(obj):",
"function_name": "json_serialize",
"parameter_list": "(obj)"
},
{
"docstring": "Deserializes a JSON formatted string to a Python data structure.",
"functio... | [
1,
1,
0,
0,
1,
0,
0,
0,
1,
0
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import json\nimport xml.etree.ElementTree as ET\nfrom xml.dom import minidom\nimport pickle\n\n# 1. JSON Serialization\ndef json_serialize(obj: any) -> str:\n ... | trial_gpt4o_8 | {
"original_instruction": "### Question\n\nYou have been tasked with implementing several data serialization and deserialization functions from scratch. These functions include JSON, XML, and binary serialization. Below is the detailed description of the functions you need to implement.\n\n1. **JSON Serialization**: ... | 0.801357 | Algorithm_5539 | C | [
"json_serialize",
"json_deserialize",
"dict_to_xml",
"xml_serialize",
"xml_deserialize",
"binary_serialize",
"binary_deserialize"
] | 7 | [
[
"xml_serialize",
"dict_to_xml"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 46f7ad9f65a488439bb7d16ee288156cd05a1354 | 3ecbdddf10cef01c5590745cafb096a506e8b305 | |||
v1.0 | complete | Algorithm | Algorithm_4442_C | import math
def rotate_point(x: float, y: float, theta: float) -> tuple[float, float]:
"""Rotates a point (x, y) by theta degrees around the origin.
>>> rotate_point(1.0, 0.0, 90.0) (0.0, 1.0)
>>> rotate_point(1.0, 0.0, 180.0) (-1.0, 0.0)
>>> rotate_point(1.0, 1.0, 45.0) # Result will be approximately ... | import math
def rotate_point(x: float, y: float, theta: float) -> tuple[float, float]:
"""
Rotates a point (x, y) by theta degrees around the origin.
Returns the rotated point coordinates (rotated_x, rotated_y).
"""
radians = math.radians(theta)
cos_theta = math.cos(radians)
sin_theta = mat... | from solution import rotate_point, translate_rotated_point
def test_rotate_point_90_degrees():
x, y = rotate_point(1.0, 0.0, 90.0)
assert math.isclose(x, 0.0, abs_tol=1e-9)
assert math.isclose(y, 1.0, abs_tol=1e-9)
def test_rotate_point_180_degrees():
x, y = rotate_point(1.0, 0.0, 180.0)
assert ma... | [
{
"docstring": "Rotates a point (x, y) by theta degrees around the origin.\nReturns the rotated point coordinates (rotated_x, rotated_y).",
"function_declaration": "def rotate_point(x, y, theta):",
"function_name": "rotate_point",
"parameter_list": "(x, y, theta)"
},
{
"docstring": "Rotates ... | [
1,
1,
0,
0,
0,
1,
0,
0,
0,
1
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import math\nfrom typing import Tuple\n\ndef convert_to_radians(degrees: float) -> float:\n return math.radians(degrees)\n\ndef rotate_point(x: float, y: floa... | trial_gpt4o_9 | {
"original_instruction": "### 2D Geometric Transformations\n\nYou are tasked with implementing functionality for 2D geometric transformations. Specifically, you need to create a function that rotates a 2D point around the origin and another function that translates the rotated points by a given offset.\n\n#### Requi... | 0.559635 | Algorithm_4442 | C | [
"rotate_point",
"translate_rotated_point"
] | 2 | [
[
"translate_rotated_point",
"rotate_point"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 3009d2d93461cf28db6d4a7e3b52ebe5099055bd | 98f498483a6418e52284741ea3669266b8469a9c | |||
v1.0 | complete | Algorithm | Algorithm_21438_C | from typing import List, Tuple
def optimal_delivery_route(locations: List[Tuple[int, int]], main_distribution_center: Tuple[int, int]) -> List[Tuple[int, int]]:
""" Find the optimal route to visit all given locations exactly once starting and ending at the main distribution center using a greedy algorithm.
... | from typing import List, Tuple
import math
def euclidean_distance(p1: Tuple[int, int], p2: Tuple[int, int]) -> float:
"""
Calculate the Euclidean distance between two points p1 and p2.
"""
return math.sqrt((p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2)
def optimal_delivery_route(locations: List[Tuple[in... | from solution import optimal_delivery_route
def test_simple_case():
assert optimal_delivery_route([(1, 1)], (0, 0)) == [(0, 0), (1, 1), (0, 0)]
def test_multiple_locations():
result = optimal_delivery_route([(1, 1), (2, 2), (3, 3)], (0, 0))
expected = [(0, 0), (1, 1), (2, 2), (3, 3), (0, 0)]
assert re... | [
{
"docstring": "Calculate the Euclidean distance between two points p1 and p2.",
"function_declaration": "def euclidean_distance(p1, p2):",
"function_name": "euclidean_distance",
"parameter_list": "(p1, p2)"
},
{
"docstring": "Finds the optimal route to visit all given locations exactly once... | [
1,
0,
1,
0,
0,
1,
1,
0,
1,
1
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List, Tuple\nimport math\n\ndef euclidean_distance(point1: Tuple[int, int], point2: Tuple[int, int]) -> float:\n return math.sqrt((point1[0... | trial_gpt4o_9 | {
"original_instruction": "### Context\n\nA delivery company needs to optimize its route planning software to minimize the travel distance for its drivers. They have a list of delivery locations and need to determine the optimal sequence of deliveries to minimize the total travel distance, starting and ending at the ... | 0.629929 | Algorithm_21438 | C | [
"euclidean_distance",
"optimal_delivery_route"
] | 2 | [
[
"optimal_delivery_route",
"euclidean_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 88e2b16c4b34fcba0b5121b8b18446c083976a89 | 13b68c648fb12edd86ff4bf5a63f5fe7bed96456 | |||
v1.0 | complete | Algorithm | Algorithm_11429_C | def is_palindrome_case_sensitive(s: str) -> bool:
"""
Checks if the given string is a palindrome considering case sensitivity.
>>> is_palindrome_case_sensitive("Madam") False
>>> is_palindrome_case_sensitive("madam") True
>>> is_palindrome_case_sensitive("12321") True
>>> is_palindrome_case_sen... | def is_palindrome_case_sensitive(s: str) -> bool:
"""
Checks if the given string is a palindrome considering case sensitivity.
"""
# Compare the string with its reverse
return s == s[::-1]
def is_palindrome_case_insensitive(s: str) -> bool:
"""
Checks if the given string is a palindrome wit... | from solution import is_palindrome_case_sensitive, is_palindrome_case_insensitive, palindrome_checker
def test_is_palindrome_case_sensitive():
assert is_palindrome_case_sensitive("Madam") == False
assert is_palindrome_case_sensitive("madam") == True
assert is_palindrome_case_sensitive("12321") == True
... | [
{
"docstring": "Checks if the given string is a palindrome considering case sensitivity.",
"function_declaration": "def is_palindrome_case_sensitive(s):",
"function_name": "is_palindrome_case_sensitive",
"parameter_list": "(s)"
},
{
"docstring": "Checks if the given string is a palindrome wi... | [
0,
1,
1,
0,
0,
1,
1,
1,
1,
1
] | 7 | easy | 0.7 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def is_palindrome_case_sensitive(s: str) -> bool:\n \"\"\"\n Checks if the given string is a palindrome considering case sensitivity.\n \"\"\"\n retu... | trial_gpt4o_9 | {
"original_instruction": "### Question: Implement a String Palindrome Checker with Case Sensitivity Control\n\nYou are tasked with implementing a system that checks if a given string is a palindrome. The system should support case sensitivity configuration. \n\n#### Functions to Implement:\n1. **Is Palindrome Case S... | 0.720311 | Algorithm_11429 | C | [
"is_palindrome_case_sensitive",
"is_palindrome_case_insensitive",
"palindrome_checker"
] | 3 | [
[
"palindrome_checker",
"is_palindrome_case_insensitive"
],
[
"palindrome_checker",
"is_palindrome_case_sensitive"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 309702f3b571b02ffb4c26f8060a6d59db755ca8 | 1d25f8f45c27e787f1df261b7f62d484d6cd37b1 | |||
v1.0 | complete | Algorithm | Algorithm_32865_C | def reverse_words_basic(sentence: str) -> str:
"""
Reverses the order of words in a sentence using basic string manipulation.
Args:
- sentence (str): The input sentence.
Returns:
- str: The sentence with the order of words reversed.
>>> reverse_words_basic("Hello world, this i... | import time
def reverse_words_basic(sentence: str) -> str:
"""
Reverses the order of words in a sentence using basic string manipulation.
Args:
- sentence (str): The input sentence.
Returns:
- str: The sentence with the order of words reversed.
"""
words = sentence.split()
reve... | import pytest
from solution import reverse_words_basic, reverse_words_optimized, compare_performance
def test_reverse_words_basic():
assert reverse_words_basic("Hello world, this is a test sentence!") == "sentence! test a is this world, Hello"
assert reverse_words_basic("") == ""
assert reverse_words_basic... | [
{
"docstring": "Reverses the order of words in a sentence using basic string manipulation.\nArgs:\n- sentence (str): The input sentence.\n\nReturns:\n- str: The sentence with the order of words reversed.",
"function_declaration": "def reverse_words_basic(sentence):",
"function_name": "reverse_words_basi... | [
0,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import time\n\ndef reverse_words_basic(sentence: str) -> str:\n \"\"\"\n Reverses the order of words in a given sentence using a basic approach.\n \"\"\... | trial_gpt4o_4 | {
"original_instruction": "### Performance Analysis of String Manipulation Algorithms\n\nWrite two Python functions to analyze the performance of different string manipulation techniques in reversing words within a sentence. \n\n#### Requirements:\n1. **Function 1**: `reverse_words_basic` which uses a basic approach ... | 0.611563 | Algorithm_32865 | C | [
"reverse_words_basic",
"reverse_words_optimized",
"compare_performance"
] | 3 | [
[
"compare_performance",
"reverse_words_basic"
],
[
"compare_performance",
"reverse_words_optimized"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 801f6686e5d54fe155e909d19a80eb8dffbff4d4 | 33f19bc2b218b8f8d65f6ed88cc3d992d243d0fe | |||
v1.0 | complete | Algorithm | Algorithm_27618_C | class TreeNode:
def __init__(self, val=0, left=None, right=None, parent=None):
self.val = val
self.left = left
self.right = right
self.parent = parent
def in_order_successor(node: TreeNode | None) -> TreeNode | None:
"""
Finds the in-order successor of the given node in a BS... | class TreeNode:
def __init__(self, val=0, left=None, right=None, parent=None):
self.val = val
self.left = left
self.right = right
self.parent = parent
def in_order_successor(node: TreeNode | None) -> TreeNode | None:
"""
Finds the in-order successor of the given node in a BS... | from solution import TreeNode, in_order_successor
def test_in_order_successor():
# Construct the BST as described in the problem statement
root = TreeNode(20)
root.left = TreeNode(8, parent=root)
root.right = TreeNode(22, parent=root)
root.left.left = TreeNode(4, parent=root.left)
root.left.rig... | [] | [
1,
0,
1,
1,
1,
0,
0,
1,
1,
1
] | 7 | easy | 0.7 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "class TreeNode:\n def __init__(self, val=0, left=None, right=None, parent=None):\n self.val = val\n self.left = left\n self.right = right... | trial_gpt4o_4 | {
"original_instruction": "### In-Order Successor in BST\n\n#### Objective:\nImplement a function to find the in-order successor of a given node in a Binary Search Tree (BST).\n\n#### Context:\nIn-order traversal of a BST yields nodes in ascending order. The in-order successor of a node is the next node in this seque... | 0.518678 | Algorithm_27618 | C | [
"in_order_successor",
"find_min"
] | 2 | [
[
"in_order_successor",
"find_min"
]
] | 1 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | ee0477a3ede19e1a724d9b14e8457afd33d52d93 | a4854ff1542ed4fcc30a819b453c778c9a6be5c0 | |||
v1.0 | complete | Algorithm | Algorithm_29987_C | from typing import List
def find_most_similar(word: str, dictionary: List[str]) -> str:
""" Find the most similar word from the dictionary based on the Levenshtein distance.
"""
pass
def correct_misspellings(text: str, dictionary: List[str]) -> str:
""" Correct misspelled words in the text using the g... | from typing import List
import difflib
def find_most_similar(word: str, dictionary: List[str]) -> str:
# Use difflib.get_close_matches to find the closest match from the dictionary
matches = difflib.get_close_matches(word, dictionary, n=1, cutoff=0.0)
if matches:
return matches[0]
else:
... | from solution import correct_misspellings
def test_correct_misspellings_basic():
assert correct_misspellings("Ths is a smple txt", ["This", "is", "a", "simple", "text"]) == "This is a simple text"
def test_correct_misspellings_hello_world():
assert correct_misspellings("Helo wrld", ["Hello", "world"]) == "Hel... | [
{
"docstring": null,
"function_declaration": "def find_most_similar(word, dictionary):",
"function_name": "find_most_similar",
"parameter_list": "(word, dictionary)"
},
{
"docstring": null,
"function_declaration": "def correct_misspellings(text, dictionary):",
"function_name": "corre... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
1
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List\nimport difflib\n\ndef find_most_similar(word: str, dictionary: List[str]) -> str:\n \"\"\"\n Find the most similar word in the dic... | trial_gpt4o_9 | {
"original_instruction": "### Question:\n\n#### Context:\nYou are tasked with creating a feature for a text editor that helps users find and correct common misspellings. Specifically, you need to correct words based on a given dictionary of correct words.\n\n#### Task:\nImplement a function `correct_misspellings(tex... | 0.630222 | Algorithm_29987 | C | [
"find_most_similar",
"correct_misspellings"
] | 2 | [
[
"correct_misspellings",
"find_most_similar"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 319ab59b309ac35d9f82e96b93223db0ef4a9f1f | c383a7344acbf2a1c984d494e8ca3e341358947c | |||
v1.0 | complete | Algorithm | Algorithm_21354_C | def initialize_population(population_size: int, chromosome_length: int) -> list[str]:
"""Initialize a population of random binary strings.
>>> len(initialize_population(10, 5)) == 10
>>> all(len(chromosome) == 5 for chromosome in initialize_population(10, 5))
"""
def fitness(chromosome: str) -> int:
... | import random
def initialize_population(population_size, chromosome_length):
return [''.join(random.choice('01') for _ in range(chromosome_length)) for _ in range(population_size)]
def fitness(chromosome):
return chromosome.count('1')
def select_parents(population, fitnesses):
total_fitness = sum(fitness... | from solution import evolve
def test_max_fitness_chromosome_length_10():
max_fitness, best_chromosome = evolve(10, 10, 0.01, 100)
assert max_fitness == 10
assert best_chromosome == '1111111111'
def test_max_fitness_chromosome_length_20():
max_fitness, best_chromosome = evolve(20, 20, 0.01, 200)
as... | [
{
"docstring": null,
"function_declaration": "def initialize_population(population_size, chromosome_length):",
"function_name": "initialize_population",
"parameter_list": "(population_size, chromosome_length)"
},
{
"docstring": null,
"function_declaration": "def fitness(chromosome):",
... | [
0,
1,
0,
0,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import random\n\ndef initialize_population(population_size, chromosome_length):\n population = []\n for _ in range(population_size):\n chromosome = ... | trial_gpt4o_1 | {
"original_instruction": "### Problem Statement\n\nYou are to implement a genetic algorithm (GA) to solve the OneMax problem, where the objective is to maximize the number of ones in a binary string. Write a function `evolve` that evolves a population of binary strings to find the optimal string consisting entirely ... | 0.422623 | Algorithm_21354 | C | [
"initialize_population",
"fitness",
"select_parents",
"crossover",
"mutate",
"evolve"
] | 6 | [
[
"evolve",
"crossover"
],
[
"evolve",
"fitness"
],
[
"evolve",
"initialize_population"
],
[
"evolve",
"mutate"
],
[
"evolve",
"select_parents"
]
] | 5 | [] | false | [] | false | pytest | true | [] | true | 54a22ed4e65e523fa6de0417a8cf717ed9497cc0 | 7385a5e8ab9f6392a7526f4389e4c0382c58698c | |||
v1.0 | complete | Algorithm | Algorithm_24934_C | def is_prime(num: int) -> bool:
""" Helper function to check if a given number is a prime.
>>> is_prime(2)
True
>>> is_prime(3)
True
>>> is_prime(4)
False
>>> is_prime(1)
False
"""
pass
def prime_pairs_sequence(n: int) -> list[tuple[int, int]]:
""" Returns a list of n pa... | def is_prime(num):
"""Helper function to check if a given number is a prime."""
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:
return Fal... | from solution import is_prime, prime_pairs_sequence
def test_is_prime():
assert is_prime(2)
assert is_prime(3)
assert not is_prime(4)
assert is_prime(5)
assert not is_prime(1)
assert not is_prime(0)
assert is_prime(13)
assert not is_prime(14)
def test_prime_pairs_sequence():
assert... | [
{
"docstring": "Helper function to check if a given number is a prime.",
"function_declaration": "def is_prime(num):",
"function_name": "is_prime",
"parameter_list": "(num)"
},
{
"docstring": "Returns a list of n pairs of consecutive prime numbers.",
"function_declaration": "def prime_pa... | [
0,
0,
1,
1,
0,
1,
0,
0,
1,
1
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def is_prime(num):\n \"\"\"\n Helper function to check if a given number is prime.\n \"\"\"\n if num <= 1:\n return False\n if num <= 3:\n ... | trial_gpt4o_8 | {
"original_instruction": "### Prime Pair Sequence\n\n#### Scenario\nYou are working on a cryptographic algorithm that makes use of prime numbers. A specific sequence of prime number pairs is required, where every pair consists of two consecutive prime numbers.\n\n#### Task\nWrite a function `prime_pairs_sequence` th... | 0.747748 | Algorithm_24934 | C | [
"is_prime",
"prime_pairs_sequence"
] | 2 | [
[
"prime_pairs_sequence",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 227c5f9f644f24bc72c0258b45d5bc32805f6d90 | 3a5031a1a766b625f7884b37f726f92adadc4fe5 | |||
v1.0 | complete | Algorithm | Algorithm_13055_C | def robot_path_exists(grid: list[list[int]], updates: list[tuple[int, int, int]]) -> bool:
""" Determines if there exists a path for a robot to move from the top-left corner (0, 0) to the bottom-right corner (N-1, N-1) on a dynamically changing grid.
Args:
grid (list[list[int]]): A 2D list represen... | from collections import deque
def is_valid(grid, x, y, N):
"""
Checks if the given coordinates are within the grid bounds and if the cell is not an obstacle.
"""
return 0 <= x < N and 0 <= y < N and grid[x][y] == 0
def bfs(grid, N):
"""
Performs BFS to find if there is a path from top-left cor... | from solution import robot_path_exists
def test_robot_path_exists_case1():
grid = [
[0, 1, 0],
[0, 0, 0],
[1, 0, 0]
]
updates = [(1, 1, 1), (2, 1, 1), (2, 2, 1)]
assert not robot_path_exists(grid, updates)
def test_robot_path_exists_case2():
grid = [
[0, 0, 1],
... | [
{
"docstring": "Checks if the given coordinates are within the grid bounds and if the cell is not an obstacle.",
"function_declaration": "def is_valid(grid, x, y, N):",
"function_name": "is_valid",
"parameter_list": "(grid, x, y, N)"
},
{
"docstring": "Performs BFS to find if there is a path... | [
1,
0,
0,
0,
0,
1,
0,
1,
1
] | 4 | medium | 0.444 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def robot_path_exists(grid: list[list[int]], updates: list[tuple[int, int, int]]) -> bool:\n from collections import deque\n\n def bfs(start, end, grid):\n... | trial_gpt4o_7 | {
"original_instruction": "### Question\n**Robot Path Navigator**\n\nYou are given a grid of `N x N` dimensions where each cell can either be empty (represented by `0`) or contain an obstacle (represented by `1`). Your task is to implement a function that determines if there exists a path for a robot to move from the... | 0.664706 | Algorithm_13055 | C | [
"is_valid",
"bfs",
"robot_path_exists"
] | 3 | [
[
"bfs",
"is_valid"
],
[
"robot_path_exists",
"bfs"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 744ec2afb79ecaef0134e9035fd5ca3dc141b13f | 6c4e7dce33623ea89848862a3c480318cb62f048 | |||
v1.0 | complete | Algorithm | Algorithm_8924_C | from typing import List, Tuple
def sieve_of_eratosthenes(limit: int) -> List[int]:
""" Generates all prime numbers up to the limit using the Sieve of Eratosthenes.
>>> sieve_of_eratosthenes(10)
[2, 3, 5, 7]
>>> sieve_of_eratosthenes(20)
[2, 3, 5, 7, 11, 13, 17, 19]
"""
pass
def consecutiv... | from typing import List, Tuple
def sieve_of_eratosthenes(limit: int) -> List[int]:
is_prime = [True] * limit
is_prime[0] = is_prime[1] = False
for start in range(2, int(limit**0.5) + 1):
if is_prime[start]:
for multiple in range(start*start, limit, start):
is_prime[... | from solution import sieve_of_eratosthenes, consecutive_primes_sum
def test_sieve_of_eratosthenes():
assert sieve_of_eratosthenes(10) == [2, 3, 5, 7]
assert sieve_of_eratosthenes(20) == [2, 3, 5, 7, 11, 13, 17, 19]
def test_consecutive_primes_sum():
assert consecutive_primes_sum(100) == (6, 41)
assert... | [
{
"docstring": null,
"function_declaration": "def sieve_of_eratosthenes(limit):",
"function_name": "sieve_of_eratosthenes",
"parameter_list": "(limit)"
},
{
"docstring": null,
"function_declaration": "def consecutive_primes_sum(n):",
"function_name": "consecutive_primes_sum",
"pa... | [
1,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List, Tuple\n\ndef sieve_of_eratosthenes(limit: int) -> List[int]:\n is_prime = [True] * limit\n is_prime[0] = is_prime[1] = False\n ... | trial_gpt4o_0 | {
"original_instruction": "**Consecutive Primes Sum**\n\n**Problem Statement**:\nYou are tasked with finding the longest sequence of consecutive prime numbers that adds up to a prime less than a given number `n`. Write a function to identify the length of this sequence and the corresponding sum.\n\n**Function Signatu... | 0.629941 | Algorithm_8924 | C | [
"sieve_of_eratosthenes",
"consecutive_primes_sum"
] | 2 | [
[
"consecutive_primes_sum",
"sieve_of_eratosthenes"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 20ff98ac3930a482bb1c1e1c3d82bc9a2c502539 | 3ab114aa619f3abc29ab33720c30437ead726eca | |||
v1.0 | complete | Algorithm | Algorithm_35958_C | from typing import List, Callable, Tuple
# Selection Methods
def tournament_selection(population: List, fitness: List, k: int) -> List:
""" Implements the tournament selection method for genetic algorithms.
Args:
population (List): List of individuals in the population.
fitness (List): List of ... | import random
from typing import List, Callable, Tuple
# Selection Methods
def tournament_selection(population: List, fitness: List, k: int) -> List:
selected = []
for _ in range(len(population)):
tournament = random.sample(list(zip(population, fitness)), k)
winner = max(tournament, key=lambda ... | from solution import (
tournament_selection,
rank_based_selection,
single_point_crossover,
two_point_crossover,
mutation,
genetic_algorithm
)
def sample_fitness_function(individual: List[int]) -> float:
return sum(individual)
def get_sample_population() -> List[List[int]]:
return [... | [
{
"docstring": null,
"function_declaration": "def tournament_selection(population, fitness, k):",
"function_name": "tournament_selection",
"parameter_list": "(population, fitness, k)"
},
{
"docstring": null,
"function_declaration": "def rank_based_selection(population, fitness):",
"f... | [
0,
0,
0,
0,
0,
0,
1,
1,
1,
1
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import random\nfrom typing import List, Callable\n\ndef tournament_selection(population: List, fitness: List, k: int) -> List:\n selected = []\n for _ in r... | trial_gpt4o_7 | {
"original_instruction": "### Genetic Algorithm Optimization\n\n#### Context\nYou are tasked with implementing and enhancing a Genetic Algorithm (GA) to solve optimization problems. This assessment will verify your understanding of components such as selection, crossover, mutation, and overall GA workflow.\n\n#### T... | 0.46082 | Algorithm_35958 | C | [
"tournament_selection",
"rank_based_selection",
"single_point_crossover",
"two_point_crossover",
"mutation",
"genetic_algorithm"
] | 6 | [
[
"genetic_algorithm",
"mutation"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 61a05b72bceb6aeb228c2c06bf8114bf58ae0830 | 23ac952b8dcdbdc787bd0fe838ccdc4a590541d6 | |||
v1.0 | complete | Algorithm | Algorithm_43288_C | import math
def euclidean_distance(point1: list, point2: list) -> float:
"""
Calculate the Euclidean distance between two points in a 2D plane.
Args:
point1 (list): List containing two integers representing the first point.
point2 (list): List containing two integers representing the ... | import math
def euclidean_distance(point1: list, point2: list) -> float:
"""
Calculate the Euclidean distance between two points in a 2D plane.
Args:
point1 (list): List containing two integers representing the first point.
point2 (list): List containing two integers representing the s... | from solution import euclidean_distance, is_integer_distance
def test_euclidean_distance():
# Test with standard points
assert math.isclose(euclidean_distance([0, 0], [3, 4]), 5.0, rel_tol=1e-9)
assert math.isclose(euclidean_distance([2, 3], [6, 8]), 6.403124, rel_tol=1e-6)
assert math.isclose(euclidea... | [
{
"docstring": "Calculate the Euclidean distance between two points in a 2D plane.\n\nArgs:\n point1 (list): List containing two integers representing the first point.\n point2 (list): List containing two integers representing the second point.\n\nReturns:\n float: Euclidean distance between the two po... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 10 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import math\n\ndef euclidean_distance(point1: list, point2: list) -> float:\n \"\"\"\n Computes the Euclidean distance between two points in a 2D plane.\n ... | trial_gpt4o_9 | {
"original_instruction": "### Problem Statement\n\nYou are given two lists of integers representing the coordinates of two points in a 2D plane. Your task is to compute the Euclidean distance between these two points and to determine whether the point represented by the second list is at an integer distance from the... | 0.647163 | Algorithm_43288 | C | [
"euclidean_distance",
"is_integer_distance"
] | 2 | [
[
"is_integer_distance",
"euclidean_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 2519ab6a7691cf7791876662bbb5bce98f5b751b | 851f2cef2d42ee512beceb509c774975f798ee0a | |||
v1.0 | complete | Algorithm | Algorithm_23088_C | from typing import List
def max_subarray_sum(arr: List[int]) -> int:
""" Find the sum of the maximum sum subarray using the divide-and-conquer approach.
## Parameters:
- arr: A list of integers representing the array.
## Returns:
- An integer representing the sum of the maximum sum subarr... | from typing import List
def max_crossing_sum(arr: List[int], left: int, mid: int, right: int) -> int:
left_sum = float('-inf')
curr_sum = 0
for i in range(mid, left - 1, -1):
curr_sum += arr[i]
if curr_sum > left_sum:
left_sum = curr_sum
right_sum = float('-inf')
curr_s... | def test_max_subarray_sum():
assert max_subarray_sum([-2, 1, -3, 4, -1, 2, 1, -5, 4]) == 6
assert max_subarray_sum([1, 2, 3, 4, 5]) == 15
assert max_subarray_sum([-1, -2, -3, -4]) == -1
assert max_subarray_sum([3, -2, 5, -1]) == 6
assert max_subarray_sum([1, -3, 2, 1, -1]) == 3
assert max_subarr... | [
{
"docstring": null,
"function_declaration": "def max_crossing_sum(arr, left, mid, right):",
"function_name": "max_crossing_sum",
"parameter_list": "(arr, left, mid, right)"
},
{
"docstring": null,
"function_declaration": "def max_subarray_sum_recursive(arr, left, right):",
"function... | [
1,
1,
1,
1,
1,
0,
1,
1,
0,
1
] | 8 | easy | 0.8 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef max_crossing_sum(arr: List[int], left: int, mid: int, right: int) -> int:\n # Include elements on left of mid.\n left_sum = ... | trial_gpt4o_9 | {
"original_instruction": "### Maximum Subarray Sum using Divide and Conquer\n\n#### Objective\nYou are given an integer array. Your task is to implement a function that finds the sum of the maximum sum subarray using the divide-and-conquer approach.\n\n#### Function Signature\n```python\ndef max_subarray_sum(arr: Li... | 0.767733 | Algorithm_23088 | C | [
"max_crossing_sum",
"max_subarray_sum_recursive",
"max_subarray_sum"
] | 3 | [
[
"max_subarray_sum",
"max_subarray_sum_recursive"
],
[
"max_subarray_sum_recursive",
"max_crossing_sum"
]
] | 2 | [] | false | [] | false | pytest | false | [] | true | 9435688a9d7c547fae5c2f3fbf45a9acd7ad6f91 | 1fb551fcc60a3f103a17605467ddfc50d319ca29 | |||
v1.0 | complete | Algorithm | Algorithm_43756_C | import time
from typing import List, Dict
def bubble_sort(arr: List[int]) -> List[int]:
""" Returns a sorted list using the Bubble Sort algorithm.
>>> bubble_sort([64, 34, 25, 12, 22, 11, 90]) [11, 12, 22, 25, 34, 64, 90]
>>> bubble_sort([38, 27, 43, 3, 9, 82, 10]) [3, 9, 10, 27, 38, 43, 82]
"""
# ... | import time
def bubble_sort(arr):
"""
Returns a sorted list using the Bubble Sort algorithm.
"""
n = len(arr)
for i in range(n):
for j in range(0, n-i-1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
return arr
def merge_sort(arr):
"""
... | from solution import bubble_sort, merge_sort, quick_sort, performance_comparison
def test_bubble_sort():
assert bubble_sort([64, 34, 25, 12, 22, 11, 90]) == [11, 12, 22, 25, 34, 64, 90]
assert bubble_sort([38, 27, 43, 3, 9, 82, 10]) == [3, 9, 10, 27, 38, 43, 82]
assert bubble_sort([5, 1, 4, 2, 8]) == [1, 2... | [
{
"docstring": "Returns a sorted list using the Bubble Sort algorithm.",
"function_declaration": "def bubble_sort(arr):",
"function_name": "bubble_sort",
"parameter_list": "(arr)"
},
{
"docstring": "Returns a sorted list using the Merge Sort algorithm.",
"function_declaration": "def merg... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 10 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import time\n\ndef bubble_sort(arr):\n \"\"\"\n Sorts the input list using the Bubble Sort algorithm.\n \n Parameters:\n arr (list of int): An... | trial_gpt4o_9 | {
"original_instruction": "### Sorting Algorithms Performance Comparison\n\n#### Scenario:\nYou are a software engineer at a tech company that needs to analyze and compare the performance of various sorting algorithms. Your team has decided to implement three different sorting algorithms and measure their execution t... | 0.518004 | Algorithm_43756 | C | [
"bubble_sort",
"merge_sort",
"quick_sort",
"performance_comparison"
] | 4 | [
[
"performance_comparison",
"bubble_sort"
],
[
"performance_comparison",
"merge_sort"
],
[
"performance_comparison",
"quick_sort"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 2135dbd52a5e0686bc2350133f9ff30481bc789a | 9b7e5a4a79d9a4aac253e810511596edddb88ef5 | |||
v1.0 | complete | Algorithm | Algorithm_947_C | from typing import List
def merge_sort_desc(arr: List[int]) -> List[int]:
""" Sort an array of integers in descending order using the Merge Sort algorithm.
>>> merge_sort_desc([5, 3, 8, 4, 2])
[8, 5, 4, 3, 2]
>>> merge_sort_desc([1])
[1]
>>> merge_sort_desc([])
[]
>>> merge_sort_desc([1... | from typing import List
def merge_sort_desc(arr: List[int]) -> List[int]:
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left_half = merge_sort_desc(arr[:mid])
right_half = merge_sort_desc(arr[mid:])
return merge_descending(left_half, right_half)
def merge_descending(left: List... | def test_merge_sort_desc_basic():
assert merge_sort_desc([5, 3, 8, 4, 2]) == [8, 5, 4, 3, 2]
def test_merge_sort_desc_single_element():
assert merge_sort_desc([1]) == [1]
def test_merge_sort_desc_empty():
assert merge_sort_desc([]) == []
def test_merge_sort_desc_already_sorted_desc():
assert merge_so... | [
{
"docstring": null,
"function_declaration": "def merge_sort_desc(arr):",
"function_name": "merge_sort_desc",
"parameter_list": "(arr)"
},
{
"docstring": null,
"function_declaration": "def merge_descending(left, right):",
"function_name": "merge_descending",
"parameter_list": "(l... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 10 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef merge_sort_desc(arr: List[int]) -> List[int]:\n \"\"\"\n Sorts an array in descending order using the Merge Sort algorithm.\... | trial_gpt4o_9 | {
"original_instruction": "**Context:** Sorting an array of integers is a fundamental task in computer science. Merge Sort is a well-known and efficient, comparison-based, divide-and-conquer sorting algorithm. Your task is to implement a variant of Merge Sort that sorts integers in descending order.\n\n**Question:** ... | 0.63976 | Algorithm_947 | C | [
"merge_sort_desc",
"merge_descending"
] | 2 | [
[
"merge_sort_desc",
"merge_descending"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 98279e654e8bfff1897262a1249249a2e38347e2 | e5b0d449a74cd0072f97ece1eeeaaa3b94b2e1a5 | |||
v1.0 | complete | Algorithm | Algorithm_8115_C | from typing import List, Union
def quickselect(arr: List[int], k: int) -> Union[int, None]:
"""Find the `k`-th smallest element in an unsorted list of integers using the Quickselect algorithm.
>>> quickselect([3, 2, 1, 5, 4], 1)
1
>>> quickselect([3, 2, 1, 5, 4], 3)
3
>>> quickselect([3, 2, 1, ... | from typing import List, Union
def partition(arr: List[int], low: int, high: int) -> int:
pivot = arr[high]
i = low - 1
for j in range(low, high):
if arr[j] <= pivot:
i += 1
arr[i], arr[j] = arr[j], arr[i]
arr[i + 1], arr[high] = arr[high], arr[i + 1]
return i + 1
d... | import pytest
from solution import quickselect
def test_quickselect_basic():
assert quickselect([3, 2, 1, 5, 4], 1) == 1
assert quickselect([3, 2, 1, 5, 4], 3) == 3
assert quickselect([3, 2, 1, 5, 4], 5) == 5
assert quickselect([3, 2, 1, 5, 4], 6) == None
def test_quickselect_more_cases():
assert ... | [
{
"docstring": null,
"function_declaration": "def partition(arr, low, high):",
"function_name": "partition",
"parameter_list": "(arr, low, high)"
},
{
"docstring": null,
"function_declaration": "def quickselect_helper(arr, low, high, k):",
"function_name": "quickselect_helper",
"... | [
1,
0,
1,
0,
1,
1,
0,
1,
1,
1
] | 7 | easy | 0.7 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List, Union\n\ndef partition(arr: List[int], left: int, right: int, pivot_index: int) -> int:\n pivot_value = arr[pivot_index]\n arr[piv... | trial_gpt4o_9 | {
"original_instruction": "### Problem Description\n\nYou are given an unsorted list of `n` integers `arr` and an integer `k`. Your task is to implement the Quickselect algorithm to find the `k`-th smallest element in the list. If `k` is out of the bounds of the list, return `None`.\n\n### Implementation Details\n\n1... | 0.541315 | Algorithm_8115 | C | [
"partition",
"quickselect_helper",
"quickselect"
] | 3 | [
[
"quickselect",
"quickselect_helper"
],
[
"quickselect_helper",
"partition"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | f928bd4f2fd37fece1f13265bd536e5e3754f8d2 | c4f50fedd62b97383fe3a47961dc9905fd1c600e | |||
v1.0 | complete | Algorithm | Algorithm_20165_C | from typing import List, Tuple
def check_meeting_conflict(existing_meetings: List[Tuple[int, int]], new_meeting: Tuple[int, int]) -> bool:
"""
Checks if a new meeting conflicts with any existing meetings.
:param existing_meetings: List of tuples where each tuple represents an existing meeting's start ... | from typing import List, Tuple
def check_meeting_conflict(existing_meetings: List[Tuple[int, int]], new_meeting: Tuple[int, int]) -> bool:
"""
Checks if a new meeting conflicts with any existing meetings.
:param existing_meetings: List of tuples where each tuple represents an existing meeting's start ... | from solution import check_meeting_conflict, add_meeting
def test_check_meeting_conflict_no_conflict():
existing_meetings = [(900, 1030), (1300, 1430), (1600, 1730)]
new_meeting = (1100, 1200)
assert check_meeting_conflict(existing_meetings, new_meeting) == False
def test_check_meeting_conflict_with_confl... | [
{
"docstring": "Checks if a new meeting conflicts with any existing meetings.\n\n:param existing_meetings: List of tuples where each tuple represents an existing meeting's start and end time.\n:param new_meeting: A tuple representing the new meeting's start and end time.\n:return: Boolean value indicating wheth... | [
1,
1,
1,
0,
0,
0,
1,
1,
1,
1
] | 7 | easy | 0.7 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List, Tuple\n\ndef check_meeting_conflict(existing_meetings: List[Tuple[int, int]], new_meeting: Tuple[int, int]) -> bool:\n new_start, new... | trial_gpt4o_9 | {
"original_instruction": "### **Meeting Scheduler**\n\n### Problem Statement:\nYou are required to build a meeting scheduler that checks if a proposed meeting time conflicts with any existing meetings. Your application will receive a list of existing meetings and a proposed new meeting time. Each meeting is defined ... | 0.586834 | Algorithm_20165 | C | [
"check_meeting_conflict",
"add_meeting"
] | 2 | [
[
"add_meeting",
"check_meeting_conflict"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 8a1277fbf1386da7faa17f98b941adb8fcfd07af | f0a7cc44991712cc4a201678703faa6fa0fc9754 | |||
v1.0 | complete | Algorithm | Algorithm_36611_C | def kruskal_mst(n: int, edges: list[tuple[int, int, int]]) -> list[tuple[int, int, int]]:
""" Implement Kruskal's algorithm to find the minimum spanning tree (MST) given a list of routes and travel times between cities.
Args:
- n: An integer representing the number of cities (nodes).
- edges: A lis... | 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 rank[xroot] < rank[yroot]:
parent[xroot] = yroot
elif rank[xroot] > rank[yroot]:
parent[yroot]... | from solution import kruskal_mst
def test_kruskal_mst_example1():
n = 4
edges = [(0, 1, 10), (0, 2, 6), (0, 3, 5), (1, 3, 15), (2, 3, 4)]
result = kruskal_mst(n, edges)
assert result == [(2, 3, 4), (0, 3, 5), (0, 1, 10)]
def test_kruskal_mst_example2():
n = 3
edges = [(0, 1, 1), (1, 2, 4), (0,... | [
{
"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,
0,
1,
0,
0,
0,
1,
1,
0
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "class UnionFind:\n def __init__(self, n):\n self.parent = list(range(n))\n self.rank = [0] * n\n \n def find(self, u):\n if self.pa... | trial_gpt4o_8 | {
"original_instruction": "### Question\n\n**Context**:\nYou are a software engineer at a logistics company that ensures timely delivery of packages across various cities. Your manager has assigned you the task of optimizing the delivery routes to minimize the total delivery time while ensuring all cities are connect... | 0.629274 | Algorithm_36611 | C | [
"find",
"union",
"kruskal_mst"
] | 3 | [
[
"kruskal_mst",
"find"
],
[
"kruskal_mst",
"union"
],
[
"union",
"find"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 83a44e919db33886c83168eef3ad13fc99b9f94b | 63e9c06282c092adc2e7c07434f0ce1fa959374d | |||
v1.0 | complete | Algorithm | Algorithm_24602_C | from typing import List
def is_self_dividing(n: int) -> bool:
""" Check if a number is self-dividing.
>>> is_self_dividing(1)
True
>>> is_self_dividing(128)
True
>>> is_self_dividing(12)
True
>>> is_self_dividing(102)
False
>>> is_self_dividing(120)
False
"""
def se... | from typing import List
def is_self_dividing(n: int) -> bool:
"""
Check if a number is self-dividing.
"""
original = n
while n > 0:
digit = n % 10
if digit == 0 or original % digit != 0:
return False
n //= 10
return True
def self_dividing_numbers(left: int, ... | from solution import self_dividing_numbers, is_self_dividing
def test_is_self_dividing():
assert is_self_dividing(1) == True
assert is_self_dividing(128) == True
assert is_self_dividing(12) == True
assert is_self_dividing(102) == False
assert is_self_dividing(120) == False
def test_self_dividing_n... | [
{
"docstring": "Check if a number is self-dividing.",
"function_declaration": "def is_self_dividing(n):",
"function_name": "is_self_dividing",
"parameter_list": "(n)"
},
{
"docstring": "Find all self-dividing numbers within the given range [left, right].",
"function_declaration": "def se... | [
0,
0,
0,
0,
0,
0,
1,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef self_dividing_numbers(left: int, right: int) -> List[int]:\n def is_self_dividing(num: int) -> bool:\n original_num = nu... | trial_gpt4o_6 | {
"original_instruction": "### Coding Assessment Question\n\n#### Task\nWrite a function that finds all \"self-dividing numbers\" within a given range. A self-dividing number is defined as a number that is divisible by each of its digits without any remainder. The function should return a list of all self-dividing nu... | 0.627401 | Algorithm_24602 | C | [
"is_self_dividing",
"self_dividing_numbers"
] | 2 | [
[
"self_dividing_numbers",
"is_self_dividing"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f1b29d7fcf3cc840561e5416a23413a096ca7185 | 650acb2b281f477cec24034762a298f5fca7ac29 | |||
v1.0 | complete | Algorithm | Algorithm_8724_C | def find_combinations(target: int, numbers: list) -> list:
""" Find all unique combinations of numbers in a list where the chosen numbers sum to a target value.
>>> find_combinations(7, [2, 3, 6, 7])
[[2, 2, 3], [7]]
>>> find_combinations(8, [2, 3, 5])
[[2, 2, 2, 2], [2, 3, 3], [3, 5]]
... | def combination_sum(target, numbers, start, combination, result):
"""
Uses backtracking to find combinations of numbers that add up to the target sum.
"""
if target == 0:
result.append(list(combination))
return
elif target < 0:
return
for i in range(start, len(number... | from solution import find_combinations
def test_find_combinations_example_1():
assert find_combinations(7, [2, 3, 6, 7]) == [[2, 2, 3], [7]]
def test_find_combinations_example_2():
assert find_combinations(8, [2, 3, 5]) == [[2, 2, 2, 2], [2, 3, 3], [3, 5]]
def test_find_combinations_example_3():
assert f... | [
{
"docstring": "Uses backtracking to find combinations of numbers that add up to the target sum.",
"function_declaration": "def combination_sum(target, numbers, start, combination, result):",
"function_name": "combination_sum",
"parameter_list": "(target, numbers, start, combination, result)"
},
... | [
1,
0,
0,
0,
1,
1,
0,
0,
0,
1
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def combination_sum(target, numbers, start, combination, result):\n # Base case: if the target is 0, we found a valid combination\n if target == 0:\n ... | trial_gpt4o_9 | {
"original_instruction": "### Question:\n\nYou are tasked with implementing a function `find_combinations(target: int, numbers: list) -> list` that finds all unique combinations of numbers in a list where the chosen numbers sum to a target value. Each number from the list can be used an unlimited number of times.\n\... | 0.703636 | Algorithm_8724 | C | [
"combination_sum",
"find_combinations"
] | 2 | [
[
"find_combinations",
"combination_sum"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ba332b620384dbcec39968795d50fa2eea85414a | 320541270e15a5694bfb774d861240a36d13d187 | |||
v1.0 | complete | Algorithm | Algorithm_21073_C | def is_prime(n: int) -> bool:
"""Returns True if n is a prime number, else False.
>>> is_prime(2)
True
>>> is_prime(3)
True
>>> is_prime(4)
False
>>> is_prime(131)
True
>>> is_prime(133)
False
>>> is_prime(1)
False
>>> is_prime(0)
False
>>> is_prime(-5)
... | def is_prime(n: int) -> bool:
"""
Returns True if n is a prime number, else 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 Fa... | from solution import is_prime, is_palindrome, palindromic_prime
def test_is_prime():
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(4) == False
assert is_prime(131) == True
assert is_prime(133) == False
assert is_prime(1) == False
assert is_prime(0) == False
asser... | [
{
"docstring": "Returns True if n is a prime number, else False.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Returns True if n is a palindrome, else False.",
"function_declaration": "def is_palindrome(n):",
"fu... | [
0,
1,
1,
1,
1,
1,
1,
1,
1,
0
] | 8 | easy | 0.8 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def is_prime(n: int) -> bool:\n \"\"\"\n Check if a number is a prime number.\n :param n: Integer to check for primality.\n :return: True if n is pri... | trial_gpt4o_6 | {
"original_instruction": "### Problem Statement\n\nYou are tasked with determining if the given number is a special type of number known as a 'Palindromic Prime'. A Palindromic Prime is a number that is both prime and reads the same forwards and backwards, such as 131 or 727.\n\n### Function Requirements\n\nYou need... | 0.749221 | Algorithm_21073 | C | [
"is_prime",
"is_palindrome",
"palindromic_prime"
] | 3 | [
[
"palindromic_prime",
"is_palindrome"
],
[
"palindromic_prime",
"is_prime"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | e117c2c235407cba491863f13d6093de986310f6 | 8f33731388125529ef54e0ee773ea5ac6cf59d87 | |||
v1.0 | complete | Algorithm | Algorithm_38687_C | def sum_first_n_primes(n: int) -> str:
""" Calculate the sum of the first `n` prime numbers.
>>> sum_first_n_primes(5)
'The sum of the first 5 primes is 28'
>>> sum_first_n_primes(0)
'Error: n should be a positive integer'
>>> sum_first_n_primes(-3)
'Error: n should be a positive integer'
... | def is_prime(num):
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:
return False
i += 6
return True
def sum_first_n_primes(n: int)... | from solution import sum_first_n_primes
def test_error_negative_input():
assert sum_first_n_primes(-3) == "Error: n should be a positive integer"
def test_error_zero_input():
assert sum_first_n_primes(0) == "Error: n should be a positive integer"
def test_sum_first_1_prime():
assert sum_first_n_primes(1)... | [
{
"docstring": null,
"function_declaration": "def is_prime(num):",
"function_name": "is_prime",
"parameter_list": "(num)"
},
{
"docstring": null,
"function_declaration": "def sum_first_n_primes(n):",
"function_name": "sum_first_n_primes",
"parameter_list": "(n)"
}
] | [
1,
0,
1,
1,
1,
1,
0,
1,
1,
1
] | 8 | easy | 0.8 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_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 False\n ... | trial_gpt4o_0 | {
"original_instruction": "### Problem Description\n\nYou are tasked with implementing a function to calculate the sum of the first `n` prime numbers. The function should handle edge cases where `n` is less than or equal to zero by returning an appropriate message.\n\n### Function to Implement\n\nWrite a Python funct... | 0.713944 | Algorithm_38687 | C | [
"is_prime",
"sum_first_n_primes"
] | 2 | [
[
"sum_first_n_primes",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 41c5b0e43ca90f505b9306705a05cc93e2a6870d | fb28bd98fc3e481bdf0bd9e71def1e5441404417 | |||
v1.0 | complete | Algorithm | Algorithm_10924_C | import requests
class PaymentProvider:
def __init__(self, name, api_url, api_key):
self.name = name
self.api_url = api_url
self.api_key = api_key
def execute_payment(self, payment_details):
try:
response = requests.post(self.api_url, json=payment_details, headers={'... | import requests
class PaymentProvider:
def __init__(self, name, api_url, api_key):
self.name = name
self.api_url = api_url
self.api_key = api_key
def execute_payment(self, payment_details):
try:
response = requests.post(self.api_url, json=payment_details, headers={'... | from solution import process_payment, validate_payment_details
def test_validate_payment_details():
valid_details = {
'card_number': '1234567812345678',
'expiry_date': '12/23',
'cvv': '123',
'amount': 100.0,
'currency': 'USD'
}
invalid_details_empty_field = {
... | [] | [
0,
0,
1,
0,
0,
1,
1,
0,
1,
0
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import random\n\nclass PaymentError(Exception):\n pass\n\ndef validate_payment_details(payment_details):\n \"\"\"\n Validate payment details such as car... | trial_gpt4o_2 | {
"original_instruction": "### Coding Assessment Question\n\nAs a software developer, you are assigned the task of extending an e-commerce platform's payment gateway integration to support multiple payment providers. Your goal is to create a more flexible and fault-tolerant system that can handle payment processing t... | 0.445243 | Algorithm_10924 | C | [
"validate_payment_details",
"process_payment"
] | 2 | [
[
"process_payment",
"validate_payment_details"
]
] | 1 | [] | false | [
"PaymentProvider"
] | true | pytest | true | [
"requests"
] | false | 834ad4f1de2a4aeed1d4a748c5c558cde77857a9 | baa3336e05e90d61a7a644727273fa2970bfbba8 | |||
v1.0 | complete | Algorithm | Algorithm_17738_C | from typing import List
def transpose_matrix(matrix: List[List[int]]) -> List[List[int]]:
"""
Transposes the given 2D matrix.
Params:
- matrix (List[List[int]]): A 2D list representing the matrix.
Returns:
- List[List[int]]: A 2D list representing the transposed matrix.
"""
pass
... | from typing import List
def transpose_matrix(matrix: List[List[int]]) -> List[List[int]]:
"""
Transposes the given 2D matrix.
Params:
- matrix (List[List[int]]): A 2D list representing the matrix.
Returns:
- List[List[int]]: A 2D list representing the transposed matrix.
"""
return... | def test_transpose_matrix():
matrix_1 = [
[1, 2, 3],
[4, 5, 6]
]
assert transpose_matrix(matrix_1) == [[1, 4], [2, 5], [3, 6]]
matrix_2 = [
[7]
]
assert transpose_matrix(matrix_2) == [[7]]
matrix_3 = [
[1, 4],
[2, 5],
[3, 6]
]
... | [
{
"docstring": "Transposes the given 2D matrix.\n\nParams:\n- matrix (List[List[int]]): A 2D list representing the matrix.\n\nReturns:\n- List[List[int]]: A 2D list representing the transposed matrix.",
"function_declaration": "def transpose_matrix(matrix):",
"function_name": "transpose_matrix",
"pa... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 10 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef transpose_matrix(matrix: List[List[int]]) -> List[List[int]]:\n \"\"\"\n Transpose the given matrix (2D list).\n \n Pa... | trial_gpt4o_9 | {
"original_instruction": "### Matrix Transpose and Sum\n\n**Problem Statement**: \nYou are required to implement two functions: one to transpose a given matrix and another to compute the sum of elements in the transposed matrix. Your task is to create functions `transpose_matrix` and `sum_transposed_matrix` to achi... | 0.549497 | Algorithm_17738 | C | [
"transpose_matrix",
"sum_transposed_matrix"
] | 2 | [
[
"sum_transposed_matrix",
"transpose_matrix"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 43c21965acf26dd0b0e89fb7289c6ecbf4bac60c | 87b5d0188e1b6ed66d96e7d45a94078459c3eb42 | |||
v1.0 | complete | Algorithm | Algorithm_41482_C | class TrieNode:
def __init__(self):
self.children = {}
self.is_end_of_word = False
def build_trie(words: list[str]) -> TrieNode:
""" Build a Trie from a given list of words.
Arguments:
words -- a list of strings representing the words.
Returns:
The root TrieNode of the cons... | class TrieNode:
def __init__(self):
self.children = {}
self.is_end_of_word = False
def build_trie(words):
root = TrieNode()
for word in words:
current = root
for letter in word:
if letter not in current.children:
current.children[letter] = TrieNod... | from solution import build_trie, autocomplete
def test_build_trie_and_autocomplete():
words = [
"apple",
"app",
"application",
"bat",
"ball",
"batman",
"ape"
]
trie_root = build_trie(words)
assert set(autocomplete("app", trie_root)) == {"appl... | [] | [
0,
1,
0,
0,
1,
0,
1,
1,
0,
1
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "class TrieNode:\n def __init__(self):\n self.children = {}\n self.is_end_of_word = False\n\ndef build_trie(words):\n root = TrieNode()\n f... | trial_gpt4o_9 | {
"original_instruction": "### Trie - Auto-Complete System\n\n#### Background:\nA Trie (prefix tree) is a data structure used to efficiently store and retrieve keys in a dataset of strings. This problem extends the Trie data structure to implement an auto-complete feature useful for applications like search engines.\... | 0.506819 | Algorithm_41482 | C | [
"build_trie",
"autocomplete",
"search_helper"
] | 3 | [
[
"autocomplete",
"search_helper"
]
] | 1 | [] | false | [
"TrieNode"
] | true | pytest | true | [] | true | b4272508853850837da4c84a3c55bbc4cd107239 | acbc45af49920cd58f8b76147a219fb0d8fade5f | |||
v1.0 | complete | Algorithm | Algorithm_24059_C | from typing import List
def split_array_minimized_max_sum(arr: List[int], k: int) -> int:
""" Split the array into `k` non-empty subarrays such that the largest sum among those subarrays is minimized.
>>> split_array_minimized_max_sum([7, 2, 5, 10, 8], 2)
18
>>> split_array_minimized_max_sum([1, 2, 3, ... | from typing import List
def can_partition(nums: List[int], k: int, max_sum: int) -> bool:
current_sum = 0
count = 1
for num in nums:
if current_sum + num > max_sum:
count += 1
current_sum = num
if count > k:
return False
else:
... | from solution import split_array_minimized_max_sum
def test_example_1():
assert split_array_minimized_max_sum([7, 2, 5, 10, 8], 2) == 18
def test_example_2():
assert split_array_minimized_max_sum([1, 2, 3, 4, 5], 2) == 9
def test_example_3():
assert split_array_minimized_max_sum([1, 4, 4], 3) == 4
def t... | [
{
"docstring": null,
"function_declaration": "def can_partition(nums, k, max_sum):",
"function_name": "can_partition",
"parameter_list": "(nums, k, max_sum)"
},
{
"docstring": null,
"function_declaration": "def split_array_minimized_max_sum(arr, k):",
"function_name": "split_array_mi... | [
0,
0,
1,
0,
0,
0,
1,
0,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef split_array_minimized_max_sum(arr: List[int], k: int) -> int:\n def can_split(max_sum):\n count, subarray_sum = 1, 0\n ... | trial_gpt4o_6 | {
"original_instruction": "### Problem Statement\n\nYou are given an array of integers `arr` and an integer `k`. Your task is to split the array into `k` non-empty subarrays such that the largest sum among those subarrays is minimized. Return the minimized largest sum.\n\n### Function Signature\n```python\ndef split_... | 0.673121 | Algorithm_24059 | C | [
"can_partition",
"split_array_minimized_max_sum"
] | 2 | [
[
"split_array_minimized_max_sum",
"can_partition"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 291b4a61f99884fa2e0a681130db6b11e6df9cb8 | 3407b06d6bf66ef51ae7b9afdf5864d65208adc1 | |||
v1.0 | complete | Algorithm | Algorithm_35417_C | def calculate_optimal_route(start: tuple, destinations: list) -> list:
"""
Determine the optimal delivery route starting and ending at the warehouse.
Parameters:
start (tuple): Coordinates of the starting location (latitude, longitude).
destinations (list): List of tuples representing the coordinat... | import math
def euclidean_distance(point1, point2):
"""
Calculate the Euclidean distance between two points in 2D space.
"""
return math.sqrt((point1[0] - point2[0]) ** 2 + (point1[1] - point2[1]) ** 2)
def calculate_optimal_route(start, destinations):
"""
Determine the optimal delivery route ... | from solution import calculate_optimal_route
def test_calculate_optimal_route_no_destinations():
start = (34.0522, -118.2437)
destinations = []
result = calculate_optimal_route(start, destinations)
assert result == [(34.0522, -118.2437), (34.0522, -118.2437)]
def test_calculate_optimal_route_single_de... | [
{
"docstring": "Calculate the Euclidean distance between two points in 2D space.",
"function_declaration": "def euclidean_distance(point1, point2):",
"function_name": "euclidean_distance",
"parameter_list": "(point1, point2)"
},
{
"docstring": "Determine the optimal delivery route starting a... | [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0
] | 8 | easy | 0.8 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def calculate_optimal_route(start: tuple, destinations: list) -> list:\n \"\"\"\n Calculate the optimal route for a delivery drone using the nearest neighb... | trial_gpt4o_7 | {
"original_instruction": "## Optimal Route Planning for Delivery Drones\n\nYou have been contracted to develop functionality for a delivery service utilizing drones to deliver packages within a city. The function should determine the shortest delivery route from the warehouse (starting point) to multiple delivery de... | 0.562935 | Algorithm_35417 | C | [
"euclidean_distance",
"calculate_optimal_route"
] | 2 | [
[
"calculate_optimal_route",
"euclidean_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c2e0b43671f268fdb77c42743a42e6b2592d3783 | f32aa841904fc214a684afa543fb63f4a39091f3 | |||
v1.0 | complete | Algorithm | Algorithm_10389_C | from typing import List, Tuple
def shortest_delivery_route(points: List[Tuple[int, int]]) -> List[Tuple[int, int]]:
""" Find the shortest route to visit all delivery points once and return to the starting point using the nearest neighbor heuristic.
Args:
points (List[Tuple[int, int]]): A list of tuple... | from typing import List, Tuple
import math
def distance(point1: Tuple[int, int], point2: Tuple[int, int]) -> float:
return math.sqrt((point1[0] - point2[0]) ** 2 + (point1[1] - point2[1]) ** 2)
def shortest_delivery_route(points: List[Tuple[int, int]]) -> List[Tuple[int, int]]:
if len(points) <= 1:
re... | from solution import shortest_delivery_route
def test_shortest_delivery_route_case1():
assert shortest_delivery_route([(0, 0), (1, 1), (2, 2)]) == [(0, 0), (1, 1), (2, 2), (0, 0)]
def test_shortest_delivery_route_case2():
assert shortest_delivery_route([(2, 3), (5, 4), (1, 1)]) == [(2, 3), (1, 1), (5, 4), (2,... | [
{
"docstring": null,
"function_declaration": "def distance(point1, point2):",
"function_name": "distance",
"parameter_list": "(point1, point2)"
},
{
"docstring": null,
"function_declaration": "def shortest_delivery_route(points):",
"function_name": "shortest_delivery_route",
"par... | [
1,
1,
1,
1,
0,
1,
0,
1,
0,
0
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List, Tuple\nimport math\n\ndef euclidean_distance(point1: Tuple[int, int], point2: Tuple[int, int]) -> float:\n \"\"\"\n Returns the Eu... | trial_gpt4o_7 | {
"original_instruction": "### Coding Assessment Question\n\n**Problem Context:**\n\nYou are developing a program to help a logistics company optimize their delivery routes. Given a set of delivery points, the objective is to determine the shortest route that visits each point exactly once and returns to the starting... | 0.642374 | Algorithm_10389 | C | [
"distance",
"shortest_delivery_route"
] | 2 | [
[
"shortest_delivery_route",
"distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | fdaf9a79a181c6df824cf526ce0d1a402bc95530 | 907a92b3e051911aa5a84daed0a583ab8f7e8991 | |||
v1.0 | complete | Algorithm | Algorithm_24006_C | def in_place_merge_sort(arr: list[int]) -> None:
""" In-Place Merge Sort Implementation.
Merge sort is a divide-and-conquer algorithm that divides the input array into two halves, recursively sorts them, and then merges the two sorted halves in place without using extra space.
Args:
arr (list[int]): Th... | def merge(arr, start, mid, end):
start2 = mid + 1
if arr[mid] <= arr[start2]: # Already in place
return
while start <= mid and start2 <= end:
if arr[start] <= arr[start2]:
start += 1
else:
value = arr[start2]
index = start2
while in... | from solution import in_place_merge_sort
def test_empty_array():
arr = []
in_place_merge_sort(arr)
assert arr == []
def test_single_element_array():
arr = [1]
in_place_merge_sort(arr)
assert arr == [1]
def test_sorted_array():
arr = [1, 2, 3, 4, 5]
in_place_merge_sort(arr)
assert ... | [
{
"docstring": null,
"function_declaration": "def merge(arr, start, mid, end):",
"function_name": "merge",
"parameter_list": "(arr, start, mid, end)"
},
{
"docstring": null,
"function_declaration": "def in_place_merge_sort_helper(arr, l, r):",
"function_name": "in_place_merge_sort_he... | [
1,
0,
1,
1,
1,
1,
1,
1,
0,
1
] | 8 | easy | 0.8 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def in_place_merge_sort(arr: list[int]) -> None:\n def merge(arr, start, mid, end):\n start2 = mid + 1\n \n # If the direct merge is already ... | trial_gpt4o_9 | {
"original_instruction": "### In-Place Merge Sort Implementation\n\nMerge sort is a divide-and-conquer algorithm that divides the input array into two halves, recursively sorts them, and then merges the two sorted halves. Traditionally, merge sort is not in-place and requires additional memory, but it can be adapted... | 0.62742 | Algorithm_24006 | C | [
"merge",
"in_place_merge_sort_helper",
"in_place_merge_sort"
] | 3 | [
[
"in_place_merge_sort",
"in_place_merge_sort_helper"
],
[
"in_place_merge_sort_helper",
"merge"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 436c6de0560283fe98379df1c537d6800c733729 | 72fa096647eab05f3082243e44d3c99ac5e5b64f | |||
v1.0 | complete | Algorithm | Algorithm_3391_C | def solve_sudoku(puzzle: list[list[int]]) -> bool:
"""
Solves the given Sudoku puzzle using backtracking algorithm.
Modifies the puzzle in place and returns True if a solution is found.
If the puzzle cannot be solved, returns False.
"""
# Implementation goes here
def find_empty_location(puzzle:... | def solve_sudoku(puzzle: list[list[int]]) -> bool:
"""
Solves the given Sudoku puzzle using backtracking algorithm.
Modifies the puzzle in place and returns True if a solution is found.
If the puzzle cannot be solved, returns False.
"""
empty_location = find_empty_location(puzzle)
if not emp... | def test_solve_sudoku():
puzzle = [
[5, 3, 0, 0, 7, 0, 0, 0, 0],
[6, 0, 0, 1, 9, 5, 0, 0, 0],
[0, 9, 8, 0, 0, 0, 0, 6, 0],
[8, 0, 0, 0, 6, 0, 0, 0, 3],
[4, 0, 0, 8, 0, 3, 0, 0, 1],
[7, 0, 0, 0, 2, 0, 0, 0, 6],
[0, 6, 0, 0, 0, 0, 2, 8, 0],
[0, 0, 0, 4, ... | [
{
"docstring": "Solves the given Sudoku puzzle using backtracking algorithm.\nModifies the puzzle in place and returns True if a solution is found.\nIf the puzzle cannot be solved, returns False.",
"function_declaration": "def solve_sudoku(puzzle):",
"function_name": "solve_sudoku",
"parameter_list"... | [
0,
1,
1,
0,
1,
1,
0,
1,
1,
0
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def is_valid(puzzle, row, col, num):\n \"\"\"\n Check if num can be placed in puzzle[row][col] without\n violating Sudoku rules.\n \"\"\"\n # Chec... | trial_gpt4o_8 | {
"original_instruction": "### Sudoku Solver\n\nYou are tasked with implementing a Sudoku solver in Python that solves a given 9x9 Sudoku puzzle using a backtracking algorithm. Write a function that takes a partially completed Sudoku puzzle and returns the completed puzzle.\n\n### Requirements:\n\n1. **Data Structure... | 0.522836 | Algorithm_3391 | C | [
"solve_sudoku",
"find_empty_location",
"is_valid"
] | 3 | [
[
"solve_sudoku",
"find_empty_location"
],
[
"solve_sudoku",
"is_valid"
]
] | 2 | [] | false | [] | false | pytest | false | [] | true | 3c2982a83d007d835644019d78834d034dc4755f | 949d72b70d19c26dac5e73d0de53c53ed60f9851 | |||
v1.0 | complete | Algorithm | Algorithm_23222_C | class Node:
def __init__(self, start, end, min_val, second_min_val):
self.start = start
self.end = end
self.min_val = min_val
self.second_min_val = second_min_val
self.left = None
self.right = None
def build_segment_tree(arr: List[int]) -> Node:
""" Build the Seg... | class Node:
def __init__(self, start, end, min_val, second_min_val):
self.start = start
self.end = end
self.min_val = min_val
self.second_min_val = second_min_val
self.left = None
self.right = None
def build_segment_tree(arr):
def build(start, end):
if st... | def test_build_segment_tree():
root = build_segment_tree([1, 3, 2, 7, 5, 4])
assert root.min_val == 1
assert root.second_min_val == 2
def test_second_min_single_element():
root = build_segment_tree([1, 3, 2, 7, 5, 4])
assert second_min(root, 1, 1) == -1
def test_second_min_entire_range():
root... | [] | [
0,
0,
0,
0,
0,
1,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "class SegmentTreeNode:\n def __init__(self, start, end):\n self.start = start\n self.end = end\n self.min_val = float('inf')\n sel... | trial_gpt4o_5 | {
"original_instruction": "### Question:\n\nYou are provided with an implementation of the Segment Tree data structure, which allows for efficient range queries and updates on an array. Your task is to extend this data structure by adding a new method to compute the second minimum value in a specified subarray range.... | 0.547132 | Algorithm_23222 | C | [
"build_segment_tree",
"second_min_query",
"second_min"
] | 3 | [
[
"second_min",
"second_min_query"
]
] | 1 | [] | false | [
"Node"
] | true | pytest | false | [] | true | 8bc90e1cba9f5e6aeb916e6960126bf7ef1c7232 | 0480df549c17ae84aacd0e974cd8bfabd6958bf3 | |||
v1.0 | complete | Algorithm | Algorithm_42461_C | def sum_of_digits(number: str) -> int:
"""
Compute the sum of the digits of the provided large integer.
"""
def max_sum_of_digits(filename: str = "numbers.txt") -> int:
"""
Compute the maximum sum of digits among all numbers in the given file.
"""
### Example:
Given an example file "examp... | def sum_of_digits(number: str) -> int:
"""
Compute the sum of the digits of the provided large integer.
"""
return sum(int(digit) for digit in number)
def max_sum_of_digits(filename: str = "numbers.txt") -> int:
"""
Compute the maximum sum of digits among all numbers in the given file.
"""
... | from solution import sum_of_digits, max_sum_of_digits
import tempfile
def test_sum_of_digits():
assert sum_of_digits("123456789") == 45
assert sum_of_digits("987654321") == 45
assert sum_of_digits("1111111111111111111111111111111111") == 34
assert sum_of_digits("0") == 0
assert sum_of_digits("99999... | [
{
"docstring": "Compute the sum of the digits of the provided large integer.",
"function_declaration": "def sum_of_digits(number):",
"function_name": "sum_of_digits",
"parameter_list": "(number)"
},
{
"docstring": "Compute the maximum sum of digits among all numbers in the given file.",
... | [
1,
0,
1,
1,
1,
0,
0,
0,
0,
0
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def sum_of_digits(number: str) -> int:\n \"\"\"\n Compute the sum of the digits of the provided large integer.\n \"\"\"\n return sum(int(digit) for d... | trial_gpt4o_4 | {
"original_instruction": "### Sum of Digits in Large Numbers\n\n**Objective**: In this task, you will implement a function that reads a file containing very large integers and calculates the sum of digits for each number provided, determining the maximum sum of digits among all numbers.\n\n### Problem Statement:\nYo... | 0.582469 | Algorithm_42461 | C | [
"sum_of_digits",
"max_sum_of_digits"
] | 2 | [
[
"max_sum_of_digits",
"sum_of_digits"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 398037c087e03709ed22f1656b04dd2a1d9c500c | eef742e16b8243bbcc59876ed862652ddb11af94 | |||
v1.0 | complete | Algorithm | Algorithm_48261_C | import numpy as np
def initialize_population(pop_size: int, num_items: int) -> np.ndarray:
"""
Initializes a population of potential solutions.
"""
pass
def fitness(solution: np.ndarray, item_weights: np.ndarray, item_values: np.ndarray, capacity: int) -> float:
"""
Evaluates the fitness of ... | import numpy as np
def initialize_population(pop_size: int, num_items: int) -> np.ndarray:
return np.random.randint(0, 2, (pop_size, num_items))
def fitness(solution: np.ndarray, item_weights: np.ndarray, item_values: np.ndarray, capacity: int) -> float:
total_weight = np.sum(solution * item_weights)
if t... | from solution import initialize_population, fitness, selection, crossover, mutation, genetic_algorithm
import numpy as np
def test_initialize_population():
pop_size = 10
num_items = 5
population = initialize_population(pop_size, num_items)
assert population.shape == (pop_size, num_items)
assert np.... | [
{
"docstring": null,
"function_declaration": "def initialize_population(pop_size, num_items):",
"function_name": "initialize_population",
"parameter_list": "(pop_size, num_items)"
},
{
"docstring": null,
"function_declaration": "def fitness(solution, item_weights, item_values, capacity):... | [
1,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import numpy as np\n\ndef initialize_population(pop_size: int, num_items: int) -> np.ndarray:\n return np.random.randint(0, 2, (pop_size, num_items))\n\ndef f... | trial_gpt4o_0 | {
"original_instruction": "### Genetic Algorithm for Knapsack Problem\n\nImplement a genetic algorithm to solve the 0/1 knapsack problem. The task involves finding the optimal subset of items to include in the knapsack such that their total weight does not exceed the given capacity and their total value is maximized.... | 0.461801 | Algorithm_48261 | C | [
"initialize_population",
"fitness",
"selection",
"crossover",
"mutation",
"genetic_algorithm"
] | 6 | [
[
"genetic_algorithm",
"crossover"
],
[
"genetic_algorithm",
"fitness"
],
[
"genetic_algorithm",
"initialize_population"
],
[
"genetic_algorithm",
"mutation"
],
[
"genetic_algorithm",
"selection"
]
] | 5 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | dfd5e19d909d27e85a9a37b1fd16d5d5dc73b641 | f64cfc669ea1ca0fb383209203414b85c3bad50a | |||
v1.0 | complete | Algorithm | Algorithm_39234_C | def is_palindrome(s: str) -> bool:
"""
Check if a given string is a palindrome.
"""
def rotate_string(s: str, n: int) -> str:
"""
Rotate a string s to the left by n positions.
"""
def is_rotated_palindrome(s: str) -> bool:
"""
Check if any rotation of the given string is a palindrome.
... | def is_palindrome(s: str) -> bool:
"""
Check if a given string is a palindrome.
"""
return s == s[::-1]
def rotate_string(s: str, n: int) -> str:
"""
Rotate a string s to the left by n positions.
"""
return s[n:] + s[:n]
def is_rotated_palindrome(s: str) -> bool:
"""
Check if a... | from solution import is_rotated_palindrome
def test_is_rotated_palindrome_simple():
assert is_rotated_palindrome("aabb") == True
assert is_rotated_palindrome("abcde") == False
assert is_rotated_palindrome("aba") == True
assert is_rotated_palindrome("abcabc") == False
def test_is_rotated_palindrome_edg... | [
{
"docstring": "Check if a given string is a palindrome.",
"function_declaration": "def is_palindrome(s):",
"function_name": "is_palindrome",
"parameter_list": "(s)"
},
{
"docstring": "Rotate a string s to the left by n positions.",
"function_declaration": "def rotate_string(s, n):",
... | [
1,
1,
1,
1,
0,
1,
0,
0,
1,
1
] | 7 | easy | 0.7 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def is_palindrome(s: str) -> bool:\n \"\"\"\n Checks if the given string is a palindrome.\n \"\"\"\n return s == s[::-1]\n\ndef rotate_string(s: str,... | trial_gpt4o_9 | {
"original_instruction": "### Problem Statement\n\nYou are tasked with implementing a function that checks if a provided string is a valid rotated palindrome. A rotated palindrome is a string that can be rotated (shifted circularly to the left or right) to form a palindrome. \n\n#### Function Signature\n```python\nd... | 0.791223 | Algorithm_39234 | C | [
"is_palindrome",
"rotate_string",
"is_rotated_palindrome"
] | 3 | [
[
"is_rotated_palindrome",
"is_palindrome"
],
[
"is_rotated_palindrome",
"rotate_string"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | eb8e7ebcece2c55b599c111aecd8225ac4287a8b | 4ce1bdfdebf5441d82119a0c3f0c97bac8665605 | |||
v1.0 | complete | Algorithm | Algorithm_10216_C | import re
def is_palindrome(s: str) -> bool:
"""
Check if the input string is a palindrome, considering only
alphabetical characters and ignoring spaces, punctuation, and case.
"""
s = re.sub(r'[^a-zA-Z]', '', s).lower()
return s == s[::-1]
def find_longest_palindrome(strings: list) -> str:
... | import re
def is_palindrome(s: str) -> bool:
"""
Check if the input string is a palindrome, considering only
alphabetical characters and ignoring spaces, punctuation, and case.
"""
s = re.sub(r'[^a-zA-Z]', '', s).lower()
return s == s[::-1]
def find_longest_palindrome(strings: list) -> str:
... | from solution import find_longest_palindrome
def test_single_palindrome():
assert find_longest_palindrome(["racecar"]) == "racecar"
def test_multiple_palindromes():
assert find_longest_palindrome(["racecar", "Madam", "noon"]) == "racecar"
def test_mixed_case():
assert find_longest_palindrome(["Aba", "aBb... | [
{
"docstring": "Check if the input string is a palindrome, considering only\nalphabetical characters and ignoring spaces, punctuation, and case.",
"function_declaration": "def is_palindrome(s):",
"function_name": "is_palindrome",
"parameter_list": "(s)"
},
{
"docstring": "Finds the longest p... | [
1,
0,
0,
0,
0,
0,
0,
1,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import re\n\ndef is_palindrome(s: str) -> bool:\n \"\"\"\n Checks if the given string s is a palindrome.\n A string is considered a palindrome if it rea... | trial_gpt4o_7 | {
"original_instruction": "### Problem Statement\n\nYou are provided with a utility function that checks whether a given string is a palindrome. A string is considered a palindrome if it reads the same backward as forward (ignoring spaces, punctuation, and case).\n\nYour task is to implement a new function `find_long... | 0.792661 | Algorithm_10216 | C | [
"is_palindrome",
"find_longest_palindrome"
] | 2 | [
[
"find_longest_palindrome",
"is_palindrome"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 0153845d8d8573b178da015202878af82ba333ae | 89ede85733bf7af2bf12376834477fda6cd8798a | |||
v1.0 | complete | Algorithm | Algorithm_7121_C | def monthly_payment(principal: float, annual_interest_rate: float, loan_term_years: float) -> float:
""" Calculate the monthly payment to be made over the term of the loan.
Input:
principal (float): The initial amount of the loan.
annual_interest_rate (float): The annual interest rate.
l... | def monthly_payment(principal: float, annual_interest_rate: float, loan_term_years: float) -> float:
"""
Calculate the monthly loan payment.
:param principal: The initial amount of the loan.
:param annual_interest_rate: The annual interest rate as a percentage.
:param loan_term_years: The duration ... | import pytest
from solution import monthly_payment, total_payment, repayment_schedule
def test_monthly_payment():
assert pytest.approx(monthly_payment(100000, 5, 30), 0.01) == 536.82
assert pytest.approx(monthly_payment(200000, 3.5, 15), 0.01) == 1427.53
assert pytest.approx(monthly_payment(150000, 0, 30),... | [
{
"docstring": "Calculate the monthly loan payment.\n\n:param principal: The initial amount of the loan.\n:param annual_interest_rate: The annual interest rate as a percentage.\n:param loan_term_years: The duration of the loan in years.\n:return: The monthly payment amount.",
"function_declaration": "def mo... | [
0,
0,
0,
1,
1,
0,
0,
0,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List, Tuple\n\ndef monthly_payment(principal: float, annual_interest_rate: float, loan_term_years: float) -> float:\n if principal <= 0 or ... | trial_gpt4o_3 | {
"original_instruction": "### Question: Calculate Loan Repayment Details\n\nYou are asked to write three functions to calculate different aspects of loan repayment: monthly payment, total payment over the loan term, and the breakdown of interest paid vs. principal repaid in each payment. Each function should handle ... | 0.540564 | Algorithm_7121 | C | [
"monthly_payment",
"total_payment",
"repayment_schedule"
] | 3 | [
[
"repayment_schedule",
"monthly_payment"
],
[
"total_payment",
"monthly_payment"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 36e6d1755a63d72df8537092b0687191a733f17a | aecaa78c863d1f3d220091753e3430ff89b64672 | |||
v1.0 | complete | Algorithm | Algorithm_48216_C | ref_counts = {}
def inc_ref(obj: str) -> None:
""" Increment the reference count for the given object. If the object is not already tracked, initialize its reference count to 1.
>>> inc_ref("object1")
>>> inc_ref("object1")
>>> dec_ref("object1")
>>> ref_counts
{"object1": 1}
"""
def dec_r... | ref_counts = {}
def inc_ref(obj: str) -> None:
global ref_counts
if obj in ref_counts:
ref_counts[obj] += 1
else:
ref_counts[obj] = 1
def dec_ref(obj: str) -> None:
global ref_counts
if obj in ref_counts:
ref_counts[obj] -= 1
if ref_counts[obj] == 0:
col... | import pytest
from solution import inc_ref, dec_ref, collect_garbage, ref_counts
def setup_function():
global ref_counts
ref_counts.clear()
def test_inc_ref_new_object():
inc_ref("object1")
assert ref_counts == {"object1": 1}
def test_inc_ref_existing_object():
inc_ref("object1")
inc_ref("obj... | [
{
"docstring": null,
"function_declaration": "def inc_ref(obj):",
"function_name": "inc_ref",
"parameter_list": "(obj)"
},
{
"docstring": null,
"function_declaration": "def dec_ref(obj):",
"function_name": "dec_ref",
"parameter_list": "(obj)"
},
{
"docstring": null,
"... | [
0,
0,
0,
0,
1,
1,
1,
0,
1,
0
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "# Global dictionary to maintain reference counts of objects\nref_counts = {}\n\ndef inc_ref(obj: str) -> None:\n \"\"\"\n Increment the reference count for... | trial_gpt4o_8 | {
"original_instruction": "Python Memory Management with Custom Reference Counting\n\nGiven the implementation of a custom reference counter for memory management, complete the provided functions for incrementing and decrementing reference counts, as well as for garbage collecting objects when their reference count d... | 0.380011 | Algorithm_48216 | C | [
"inc_ref",
"dec_ref",
"collect_garbage"
] | 3 | [
[
"dec_ref",
"collect_garbage"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | dc6e9ffae81c9b8315b1c160e4da29f575970d8f | 2d9edbaa7f31cf23b0aed357b1939a496d0cb058 | |||
v1.0 | complete | Algorithm | Algorithm_37650_C | from typing import List, Tuple
def graham_scan(points: List[Tuple[int, int]]) -> List[Tuple[int, int]]:
""" Compute the convex hull of a set of 2D points using the Graham scan method.
Args:
points: A list of tuples where each tuple represents a point on a 2D plane in the form (x, y).
Retu... | from typing import List, Tuple
def graham_scan(points: List[Tuple[int, int]]) -> List[Tuple[int, int]]:
# Step 1: Find the point with the lowest y-coordinate (pivot point)
pivot = min(points, key=lambda p: (p[1], p[0]))
# Step 2: Sort points based on the polar angle with pivot
def polar_angle(p):
... | from solution import graham_scan
def test_graham_scan_general_case():
points = [(0,0), (1,1), (2,2), (2,0), (1,2)]
assert graham_scan(points) == [(0, 0), (2, 0), (2, 2), (1, 2)]
def test_graham_scan_multiple_collinear_points():
points = [(0,0), (1,1), (2,2), (3,3), (4,4), (2,0)]
assert graham_scan(poi... | [
{
"docstring": null,
"function_declaration": "def graham_scan(points):",
"function_name": "graham_scan",
"parameter_list": "(points)"
},
{
"docstring": null,
"function_declaration": "def cross_product(o, a, b):",
"function_name": "cross_product",
"parameter_list": "(o, a, b)"
}... | [
0,
0,
0,
1,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List, Tuple\n\ndef graham_scan(points: List[Tuple[int, int]]) -> List[Tuple[int, int]]:\n \"\"\"\n Computes the convex hull of a set of ... | trial_gpt4o_3 | {
"original_instruction": "### Context\n\nIn the realm of computational geometry, it's important to understand fundamental geometric algorithms. One such algorithm is the Convex Hull algorithm which finds the smallest convex polygon that can contain a set of points on a plane.\n\n### Task\n\nYour task is to implement... | 0.502304 | Algorithm_37650 | C | [
"graham_scan",
"cross_product"
] | 2 | [
[
"graham_scan",
"cross_product"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 4db0464316ee887759aaf3bbda194b401587894f | 8b736416afe8c2312aa2fec763ec77b86bf86431 | |||
v1.0 | complete | Algorithm | Algorithm_3799_C | from typing import List
def max_subarray_sum(nums: List[int]) -> int:
"""
Find the maximum sum of a contiguous subarray using the divide and conquer approach.
Args:
nums (List[int]): List of integers
Returns:
int: Maximum sum of the contiguous subarray
>>> max_subarray_sum([-2,1... | from typing import List
def max_crossing_sum(nums: List[int], low: int, mid: int, high: int) -> int:
left_sum = float('-inf')
total = 0
for i in range(mid, low - 1, -1):
total += nums[i]
if total > left_sum:
left_sum = total
right_sum = float('-inf')
total = 0
f... | from solution import max_subarray_sum
def test_example_case():
nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
assert max_subarray_sum(nums) == 6
def test_single_element():
assert max_subarray_sum([1]) == 1
assert max_subarray_sum([-1]) == -1
def test_all_positive():
nums = [1, 2, 3, 4, 5]
assert max_... | [
{
"docstring": null,
"function_declaration": "def max_crossing_sum(nums, low, mid, high):",
"function_name": "max_crossing_sum",
"parameter_list": "(nums, low, mid, high)"
},
{
"docstring": null,
"function_declaration": "def max_subarray_sum_divide_and_conquer(nums, low, high):",
"fu... | [
1,
0,
0,
0,
1,
0,
0,
0,
0,
1
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef max_crossing_sum(nums: List[int], l: int, mid: int, h: int) -> int:\n # Include elements on left of mid\n left_sum = float('... | trial_gpt4o_9 | {
"original_instruction": "### Maximum Subarray Sum using Divide and Conquer\n\nYour task is to implement the algorithm to find the maximum sum of a contiguous subarray using the divide and conquer approach. This problem is a classic example known as \"Maximum Subarray Problem\" or \"Kadane's Algorithm using Divide a... | 0.771855 | Algorithm_3799 | C | [
"max_crossing_sum",
"max_subarray_sum_divide_and_conquer",
"max_subarray_sum"
] | 3 | [
[
"max_subarray_sum",
"max_subarray_sum_divide_and_conquer"
],
[
"max_subarray_sum_divide_and_conquer",
"max_crossing_sum"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 9bd91460bddfbe7b6f968e8316a059ffab8330ad | 34012ef24496c141b9432238b6b631fa88ec618b | |||
v1.0 | complete | Algorithm | Algorithm_21951_C | # Dictionary to simulate in-memory storage of user accounts
user_database = {}
def is_valid_username(username: str) -> bool:
"""
Validates if the given username meets the criteria:
- Between 3 to 20 characters long
- Only contains alphanumeric characters
Args:
username (str): The username ... | # Dictionary to simulate in-memory storage of user accounts
user_database = {}
def is_valid_username(username: str) -> bool:
if 3 <= len(username) <= 20 and username.isalnum():
return True
return False
def is_valid_password(password: str) -> bool:
if len(password) < 8:
return False
if ... | import pytest
from solution import register_user, user_database
def setup_function():
# Clean up user_database before each test
global user_database
user_database.clear()
def test_successful_registration():
assert register_user("JohnDoe", "Password1") == 0
assert "JohnDoe" in user_database
def te... | [
{
"docstring": null,
"function_declaration": "def is_valid_username(username):",
"function_name": "is_valid_username",
"parameter_list": "(username)"
},
{
"docstring": null,
"function_declaration": "def is_valid_password(password):",
"function_name": "is_valid_password",
"paramet... | [
1,
1,
1,
0,
0,
0,
0,
1,
1,
0
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "users_db = {}\n\ndef register_user(username: str, password: str) -> int:\n \"\"\"\n Registers a new user with the given username and password.\n \"\"\"\... | trial_gpt4o_8 | {
"original_instruction": "### User Account Registration System\n\nDesign and implement a user account registration system. The system should be able to create new user accounts, including necessary validation for user input. Each user account should have a unique username and password which satisfies specific securi... | 0.530113 | Algorithm_21951 | C | [
"is_valid_username",
"is_valid_password",
"register_user"
] | 3 | [
[
"register_user",
"is_valid_password"
],
[
"register_user",
"is_valid_username"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 22b2090b46801f5d6247438b04aa8f0c442f468f | 93fe99d9a900ed0d80a0c71f7eedc1b2c45b5cec | |||
v1.0 | complete | Algorithm | Algorithm_9945_C | [Completion Task in Python]
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def insert_into_bst(root: TreeNode, val: int) -> TreeNode:
"""
Insert a new value into the Binary Search Tree.
Args:
root (Tr... | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def insert_into_bst(root, val):
if root is None:
return TreeNode(val)
if val < root.val:
root.left = insert_into_bst(root.left, val)
else:... | import pytest
from solution import TreeNode, insert_into_bst, delete_from_bst, search_bst, find_min, find_max
def create_test_bst():
root = TreeNode(10)
root = insert_into_bst(root, 5)
root = insert_into_bst(root, 15)
root = insert_into_bst(root, 3)
root = insert_into_bst(root, 7)
root = insert... | [] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 10 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "class TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n \nd... | trial_gpt4o_0 | {
"original_instruction": "### Binary Search Tree (BST): Operations Analysis\n\n**Scenario**: You are given a binary search tree (BST) containing integer values. Your task is to implement a set of functions to perform various operations on the BST, including insertion, deletion, search, and finding the minimum and ma... | 0.565131 | Algorithm_9945 | C | [
"insert_into_bst",
"delete_from_bst",
"search_bst",
"find_min",
"find_max",
"get_min"
] | 6 | [
[
"delete_from_bst",
"get_min"
]
] | 1 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | 2edc796835d9cb197da601d81d9ad2e50fc3016e | 24be929b5fc3da16c07842b079d40d846d83b243 | |||
v1.0 | complete | Algorithm | Algorithm_6476_C | def bubble_sort(arr: list[int]) -> list[int]:
"""Sorts the list using the Bubble Sort algorithm and returns the sorted list.
>>> bubble_sort([64, 34, 25, 12, 22, 11, 90])
[11, 12, 22, 25, 34, 64, 90]
>>> bubble_sort([5, 1, 4, 2, 8])
[1, 2, 4, 5, 8]
"""
# Your code here
def insertion_sort(ar... | def bubble_sort(arr):
"""
Sorts the list using the Bubble Sort algorithm and returns the sorted list.
"""
n = len(arr)
for i in range(n):
swapped = False
for j in range(0, n-i-1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
sw... | from solution import bubble_sort, insertion_sort, merge_sort, multi_stage_sort
def test_bubble_sort():
assert bubble_sort([64, 34, 25, 12, 22, 11, 90]) == [11, 12, 22, 25, 34, 64, 90]
assert bubble_sort([5, 1, 4, 2, 8]) == [1, 2, 4, 5, 8]
assert bubble_sort([]) == []
assert bubble_sort([1]) == [1]
... | [
{
"docstring": "Sorts the list using the Bubble Sort algorithm and returns the sorted list.",
"function_declaration": "def bubble_sort(arr):",
"function_name": "bubble_sort",
"parameter_list": "(arr)"
},
{
"docstring": "Sorts the list using the Insertion Sort algorithm and returns the sorted... | [
1,
1,
0,
1,
1,
1,
1,
1,
1,
1
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def bubble_sort(arr):\n \"\"\"\n Sorts the list using the Bubble Sort algorithm and returns the sorted list.\n \"\"\"\n n = len(arr)\n for i in ra... | trial_gpt4o_9 | {
"original_instruction": "## Prompt:\nYou are hired to improve a sorting system that involves multiple stages of sorting using different algorithms. The final goal is to sort a list of integers using a series of sorting methods in a specified order.\n\n1. **Stage 1**: Sort the list using the Bubble Sort algorithm.\n... | 0.592323 | Algorithm_6476 | C | [
"bubble_sort",
"insertion_sort",
"merge_sort",
"multi_stage_sort"
] | 4 | [
[
"multi_stage_sort",
"bubble_sort"
],
[
"multi_stage_sort",
"insertion_sort"
],
[
"multi_stage_sort",
"merge_sort"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | adfcd76d41b2f63a68dbb8b954bc454c7ebe7bf3 | e2e268c0ee5406e782bede2a964a5a39db9ced1d | |||
v1.0 | complete | Algorithm | Algorithm_6098_C | def can_form_palindrome(s: str) -> bool:
"""
Determine if a given string can be rearranged to form a palindrome using a dictionary-based approach.
>>> can_form_palindrome("civic!")
True
>>> can_form_palindrome("ivicc")
True
>>> can_form_palindrome("hello")
False
>>> can_form_pal... | import time
from collections import Counter
def can_form_palindrome(s: str) -> bool:
"""
Determine if a given string can be rearranged to form a palindrome using a dictionary-based approach.
"""
s = ''.join(filter(str.isalpha, s)).lower()
count = Counter(s)
odd_count = sum(1 for cnt in count.va... | from solution import can_form_palindrome, can_form_palindrome_bit, benchmark_palindrome
def test_can_form_palindrome():
assert can_form_palindrome("civic!") == True
assert can_form_palindrome("ivicc") == True
assert can_form_palindrome("hello") == False
assert can_form_palindrome("A man, a plan, a cana... | [
{
"docstring": "Determine if a given string can be rearranged to form a palindrome using a dictionary-based approach.",
"function_declaration": "def can_form_palindrome(s):",
"function_name": "can_form_palindrome",
"parameter_list": "(s)"
},
{
"docstring": "Determine if a given string can be... | [
1,
1,
1,
1,
0,
1,
1,
1,
1,
1
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def can_form_palindrome(s: str) -> bool:\n \"\"\"\n Determine if a given string can be rearranged to form a palindrome using a dictionary-based approach.\n... | trial_gpt4o_9 | {
"original_instruction": "### Problem Statement\n\nYou are tasked with implementing a function that determines if a given string can be rearranged to form a palindrome. A palindrome is a word that reads the same forwards and backwards. The function should handle case insensitivity and disregard any non-alphabetical ... | 0.76845 | Algorithm_6098 | C | [
"can_form_palindrome",
"can_form_palindrome_bit",
"benchmark_palindrome"
] | 3 | [
[
"benchmark_palindrome",
"can_form_palindrome"
],
[
"benchmark_palindrome",
"can_form_palindrome_bit"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 237e0f87eac38212383409a2c62d9ef9c9768299 | 6be7d1e952ac73accaca1be4888e7343fc14e5ca | |||
v1.0 | complete | Algorithm | Algorithm_35923_C | import re
from collections import Counter
def sanitize_text(text: str) -> str:
"""
Remove punctuation from the text and convert it to lowercase.
>>> sanitize_text("Hello, world!") "hello world"
>>> sanitize_text("Good Morning! How's everything?") "good morning hows everything"
"""
pass
def wo... | import re
from collections import Counter
def sanitize_text(text: str) -> str:
"""
Remove punctuation from the text and convert it to lowercase.
"""
# Convert to lowercase
text = text.lower()
# Remove punctuation using regex
sanitized = re.sub(r'[^\w\s]', '', text)
return sanitized
def... | from solution import sanitize_text, word_frequency, most_common_words
def test_sanitize_text():
assert sanitize_text("Hello, world!") == "hello world"
assert sanitize_text("Hello everyone. This is a simple text, with punctuation.") == \
"hello everyone this is a simple text with pun... | [
{
"docstring": "Remove punctuation from the text and convert it to lowercase.",
"function_declaration": "def sanitize_text(text):",
"function_name": "sanitize_text",
"parameter_list": "(text)"
},
{
"docstring": "Count the frequency of each word in the sanitized text.",
"function_declarat... | [
1,
1,
1,
1,
0,
1,
0,
1,
1,
1
] | 8 | easy | 0.8 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import string\nfrom collections import Counter\n\ndef sanitize_text(text):\n \"\"\"\n Removes punctuation from text and converts all letters to lowercase.\... | trial_gpt4o_9 | {
"original_instruction": "In this exercise, you are asked to implement a word frequency analyzer that processes a given text and counts the occurrences of each unique word, ignoring case and punctuation.\n\n### Function to Implement\n1. **sanitize_text**: This function should remove punctuation and convert all lette... | 0.793196 | Algorithm_35923 | C | [
"sanitize_text",
"word_frequency",
"most_common_words"
] | 3 | [
[
"most_common_words",
"word_frequency"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 8393642e09704f085dadd97562f65170c5ef883b | 84954338dcb288e613162793a2379cbfaa206afe | |||
v1.0 | complete | Algorithm | Algorithm_26027_C | def find_substring_pattern(text: str, pattern: str) -> int:
""" Locate the starting index of the first occurrence of the specified substring pattern within the provided text.
Returns -1 if the pattern does not exist within the text.
>>> find_substring_pattern("abdabcababc", "abc")
3
>>> find_su... | def build_lps(pattern):
"""
Builds the Longest Prefix Suffix (LPS) array used in the KMP algorithm.
"""
lps = [0] * len(pattern)
length = 0 # length of the previous longest prefix suffix
i = 1
while i < len(pattern):
if pattern[i] == pattern[length]:
length += 1
... | from solution import find_substring_pattern
def test_find_substring_pattern_example1():
assert find_substring_pattern("abdabcababc", "abc") == 3
def test_find_substring_pattern_example2():
assert find_substring_pattern("abcdefg", "hij") == -1
def test_find_substring_pattern_example3():
assert find_substr... | [
{
"docstring": "Builds the Longest Prefix Suffix (LPS) array used in the KMP algorithm.",
"function_declaration": "def build_lps(pattern):",
"function_name": "build_lps",
"parameter_list": "(pattern)"
},
{
"docstring": "Finds the starting index of the first occurrence of the pattern in the t... | [
0,
1,
0,
1,
1,
0,
0,
1,
1,
0
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def build_lps(pattern):\n \"\"\"\n Helper function to build the Longest Prefix Suffix (LPS) array.\n This array is used to skip characters while matchin... | trial_gpt4o_8 | {
"original_instruction": "### Coding Assessment Question\n\n#### Context:\nYou are tasked with developing a function that identifies the first occurrence of a specific substring pattern within a given text. This problem is based on the idea of string matching algorithms and is similar to the well-known Knuth-Morris-... | 0.675089 | Algorithm_26027 | C | [
"build_lps",
"find_substring_pattern"
] | 2 | [
[
"find_substring_pattern",
"build_lps"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 9811d3f69bfad5f174a6112ca7c768919f7b7ff3 | da4d5cbbc858cbb557cf4912c210c89fe4ac2c9d | |||
v1.0 | complete | Algorithm | Algorithm_22679_C | from typing import Tuple
import numpy as np
def validate_knn_classifier(
train_data: np.ndarray,
train_labels: np.ndarray,
test_data: np.ndarray,
test_labels: np.ndarray,
k: int = 3
) -> bool:
"""
Validate the k-Nearest Neighbors classifier against scikit-learn's implementation.
Parame... | import numpy as np
from sklearn.neighbors import KNeighborsClassifier
def knn_classifier(train_data: np.ndarray, train_labels: np.ndarray, test_data: np.ndarray, k: int = 3) -> np.ndarray:
"""
A simple k-Nearest Neighbors classifier.
Parameters:
- train_data: A 2D numpy array of shape (num_train_sampl... | import numpy as np
from solution import validate_knn_classifier
def test_validate_knn_classifier_basic():
train_data = np.array([[1, 2], [2, 3], [8, 9], [5, 6], [3, 3]])
train_labels = np.array([0, 0, 1, 1, 0])
test_data = np.array([[2, 2], [6, 5]])
test_labels = np.array([0, 1])
assert valida... | [
{
"docstring": "A simple k-Nearest Neighbors classifier.\n\nParameters:\n- train_data: A 2D numpy array of shape (num_train_samples, num_features).\n- train_labels: A 1D numpy array of shape (num_train_samples,).\n- test_data: A 2D numpy array of shape (num_test_samples, num_features).\n- k: Number of neighbors... | [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0
] | 8 | easy | 0.8 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import Tuple\nimport numpy as np\nfrom sklearn.neighbors import KNeighborsClassifier\n\ndef knn_classifier(\n train_data: np.ndarray,\n train_l... | trial_gpt4o_7 | {
"original_instruction": "### Coding Assessment Question\n\n#### Problem Statement\n\nYou are given an implementation of the k-Nearest Neighbors (k-NN) classifier. Your task is to write a function that will apply this classifier to various input scenarios and compare the classification results with those obtained fr... | 0.569609 | Algorithm_22679 | C | [
"knn_classifier",
"validate_knn_classifier"
] | 2 | [
[
"validate_knn_classifier",
"knn_classifier"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy",
"sklearn"
] | false | faf390d519549ca4e2fbc5b6664f0371287433c3 | 1dbe43d276d06a9e1709343a6fbaee9bb00a21e5 | |||
v1.0 | complete | Algorithm | Algorithm_12815_C | from typing import List, Tuple, Dict
def convert_bulk_temperatures(temperatures: List[Tuple[float, str, str]]) -> Dict[str, List]:
"""
Convert a list of temperatures from one unit to another.
Parameters:
temperatures (List[Tuple[float, str, str]]): A list of tuples, each containing temperature val... | def convert_temperature(value: float, src_unit: str, tgt_unit: str) -> float:
"""Convert a temperature value from one unit to another."""
if src_unit == "C":
if tgt_unit == "F":
return value * 9.0 / 5.0 + 32
elif tgt_unit == "K":
return value + 273.15
elif src_unit ==... | def test_convert_bulk_temperatures_valid():
result = convert_bulk_temperatures([(100, 'C', 'F'), (273.15, 'K', 'C'), (-40, 'F', 'C')])
expected = {'conversions': [(100, 'C', 'F', 212.0), (273.15, 'K', 'C', 0.0), (-40, 'F', 'C', -40.0)], 'errors': []}
assert result == expected
def test_convert_bulk_temperat... | [
{
"docstring": "Convert a temperature value from one unit to another.",
"function_declaration": "def convert_temperature(value, src_unit, tgt_unit):",
"function_name": "convert_temperature",
"parameter_list": "(value, src_unit, tgt_unit)"
},
{
"docstring": null,
"function_declaration": "... | [
1,
0,
1,
0,
0,
0,
0,
1,
1,
0
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def convert_temperature(value: float, src_unit: str, tgt_unit: str) -> float:\n \"\"\"Convert a temperature value from one unit to another.\"\"\"\n if src_... | trial_gpt4o_0 | {
"original_instruction": "### Fine-tune Temperature Conversion Functionality\n\n#### Context\nYou are improving an existing temperature conversion utility that converts temperatures between Celsius, Fahrenheit, and Kelvin. The primary goal is to extend its functionality allowing bulk conversions and robust error han... | 0.630491 | Algorithm_12815 | C | [
"convert_temperature",
"convert_bulk_temperatures"
] | 2 | [
[
"convert_bulk_temperatures",
"convert_temperature"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 0b9d22ef80203ffa70ca924f9edacccdd2bb0ca0 | 0f53e62c9631ca816fbc818bb023cb34cfe25469 | |||
v1.0 | complete | Algorithm | Algorithm_28183_C | def is_prime(n: int, k: int = 5) -> bool:
""" Determine if a number n is prime using the Miller-Rabin primality test.
Args:
n: An integer to be tested for primality. Must be in the range [2, 10^9]
k: An optional integer representing the number of accuracy rounds. Default value is 5.
... | import math
def miller_rabin_test(d, n):
"""
Perform the Miller-Rabin test on the number n.
:param d: The odd part of n-1 (i.e., n-1 = 2^r * d).
:param n: The number to be tested for primality.
:return: False if n is composite, True otherwise.
"""
import random
a = 2 + (random.rand... | from solution import is_prime
def test_simple_primes():
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(5) == True
assert is_prime(7) == True
def test_composite_numbers():
assert is_prime(4) == False
assert is_prime(6) == False
assert is_prime(8) == False
assert i... | [
{
"docstring": "Perform the Miller-Rabin test on the number n.\n:param d: The odd part of n-1 (i.e., n-1 = 2^r * d).\n:param n: The number to be tested for primality.\n:return: False if n is composite, True otherwise.",
"function_declaration": "def miller_rabin_test(d, n):",
"function_name": "miller_rab... | [
0,
0,
0,
0,
0,
1,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import numpy as np\nfrom qiskit import Aer, QuantumCircuit, execute\n\ndef quantum_fourier_transform(number_of_qubits: int) -> dict:\n \"\"\"\n Constructs ... | trial_gpt4o_5 | {
"original_instruction": "## Questions for Coding Assessment\n\n\n\n### Context\nIn the realm of quantum computing, the Quantum Fourier Transform (QFT) is a pivotal algorithm similar to the classical discrete Fourier Transform (DFT). It is extensively employed in quantum algorithms, including Shor's algorithm for in... | 0.819798 | Algorithm_28183 | C | [
"miller_rabin_test",
"is_prime"
] | 2 | [
[
"is_prime",
"miller_rabin_test"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 086a84e4b9da12bf84dc8c85679ec17ec7e081a5 | c148b136f677eb51c6e31bc339596347e152bd5b | |||
v1.0 | complete | Algorithm | Algorithm_25946_C | from typing import Tuple
def gcd(a: int, b: int) -> int:
"""
Calculate the greatest common divisor (GCD) of two integers using the Euclidean algorithm.
If either `a` or `b` is less than zero, consider their absolute values for computation.
Parameters:
a (int): First integer
b (int): Second... | from typing import Tuple
def gcd(a: int, b: int) -> int:
"""
Calculate the greatest common divisor (GCD) of two integers using the Euclidean algorithm.
"""
a, b = abs(a), abs(b)
while b:
a, b = b, a % b
return a
def simplify_fraction(numerator: int, denominator: int) -> Tuple[int, int]... | def test_gcd():
assert gcd(48, 18) == 6
assert gcd(-48, 18) == 6
assert gcd(48, -18) == 6
assert gcd(-48, -18) == 6
assert gcd(0, 18) == 18
assert gcd(48, 0) == 48
def test_simplify_fraction():
assert simplify_fraction(42, 56) == (3, 4)
assert simplify_fraction(-42, 56) == (-3, 4)
a... | [
{
"docstring": "Calculate the greatest common divisor (GCD) of two integers using the Euclidean algorithm.",
"function_declaration": "def gcd(a, b):",
"function_name": "gcd",
"parameter_list": "(a, b)"
},
{
"docstring": "Simplify a fraction given by its numerator and denominator.\nReturn a t... | [
1,
1,
1,
0,
0,
1,
0,
0,
0,
0
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import Tuple\n\ndef gcd(a: int, b: int) -> int:\n \"\"\"\n Calculates the greatest common divisor (GCD) of two numbers.\n Uses the Euclidean... | trial_gpt4o_5 | {
"original_instruction": "### Problem Statement: Fraction Simplifier\n\nYou are required to design a function that simplifies a given fraction to its lowest terms. This involves reducing the numerator and the denominator by their greatest common divisor (GCD).\n\n**Context and Functions:**\n\nA fraction is composed ... | 0.722147 | Algorithm_25946 | C | [
"gcd",
"simplify_fraction"
] | 2 | [
[
"simplify_fraction",
"gcd"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 9e8e0347c61002c41c621cd7ecc78888188f95ef | 1df2908125ca3ca3b10eb252a1bda48e74ba1db7 | |||
v1.0 | complete | Algorithm | Algorithm_5830_C | import numpy as np
def analyze_traffic_density(frame: np.ndarray, model_path: str, low_threshold: int, high_threshold: int) -> str:
"""
Analyzes a video frame to determine traffic density.
Args:
- frame (np.ndarray): A single frame from the video feed represented as an array.
- model_path (str): P... | import numpy as np
def load_vehicle_detection_model(model_path):
"""
Assume this function loads the vehicle detection model.
Model loading logic is abstracted for this example.
"""
pass
def detect_vehicles(model, frame):
"""
Assume this function uses the loaded model to detect vehicles in ... | import numpy as np
from unittest.mock import patch
from solution import analyze_traffic_density
def mocked_load_vehicle_detection_model(model_path):
return "mocked_model"
def test_analyze_traffic_density_low():
frame = np.random.rand(480, 640, 3) # Dummy frame
model_path = "path/to/vehicle_detection_mod... | [
{
"docstring": "Assume this function loads the vehicle detection model.\nModel loading logic is abstracted for this example.",
"function_declaration": "def load_vehicle_detection_model(model_path):",
"function_name": "load_vehicle_detection_model",
"parameter_list": "(model_path)"
},
{
"docs... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
1
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import cv2\nimport numpy as np\n\ndef analyze_traffic_density(frame: np.ndarray, model_path: str, low_threshold: int, high_threshold: int) -> str:\n \"\"\"\n ... | trial_gpt4o_9 | {
"original_instruction": "### Coding Assessment Question: Real-Time Traffic Density Analysis\n\n#### Context:\nYou are working on a traffic monitoring system that analyzes live video feeds from various road segments. The goal is to estimate the current traffic density in real-time and classify it into categories suc... | 0.491536 | Algorithm_5830 | C | [
"load_vehicle_detection_model",
"detect_vehicles",
"analyze_traffic_density"
] | 3 | [
[
"analyze_traffic_density",
"detect_vehicles"
],
[
"analyze_traffic_density",
"load_vehicle_detection_model"
]
] | 2 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | b741f2a8827d26044842119c7de394bb0ef13681 | 5f3651fed1195f78e3973e157f04a04ebb5ff44f | |||
v1.0 | complete | Algorithm | Algorithm_38864_C | def compute_factorial(n: int, memo: dict={}) -> int:
"""
Computes the factorial of n using memoization to cache and reuse previously computed results.
>>> compute_factorial(5)
120
>>> compute_factorial(10)
3628800
Parameters:
- n (int): The integer for which to compute the factori... | def compute_factorial(n, memo={}):
"""
Computes the factorial of n using memoization to cache results.
Parameters:
- n (int): The integer for which to compute the factorial.
- memo (dict): A dictionary to store previously computed factorial values.
Returns:
- int: The factorial of ... | from solution import compute_factorial, factorial_sequence
def test_compute_factorial_base_case():
assert compute_factorial(0) == 1
def test_compute_factorial_small_numbers():
assert compute_factorial(1) == 1
assert compute_factorial(2) == 2
assert compute_factorial(3) == 6
def test_compute_factorial... | [
{
"docstring": "Computes the factorial of n using memoization to cache results.\n\nParameters:\n- n (int): The integer for which to compute the factorial.\n- memo (dict): A dictionary to store previously computed factorial values.\n\nReturns:\n- int: The factorial of n.",
"function_declaration": "def comput... | [
1,
1,
1,
1,
1,
1,
0,
1,
1,
1
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def compute_factorial(n, memo={}):\n # Base case: factorial of 0 is 1\n if n == 0:\n return 1\n \n # Check if the value is already calculated\... | trial_gpt4o_9 | {
"original_instruction": "### Factorial Calculation with Memoization\n\nYou are working on developing software that requires extensive use of factorial calculations. To improve efficiency, you decide to implement memoization to store previously calculated factorials.\n\nYou are required to implement two functions:\n... | 0.731197 | Algorithm_38864 | C | [
"compute_factorial",
"factorial_sequence"
] | 2 | [
[
"factorial_sequence",
"compute_factorial"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 1ce0e74c291f35a6a14b6d625653194e864ad296 | 9257ab333ddf5becb391cd5c2e47455bc0bf3c58 | |||
v1.0 | complete | Algorithm | Algorithm_27808_C | ### Problem Statement
You are tasked with implementing two functions to find the greatest common divisor (GCD) and least common multiple (LCM) of a list of integers.
#### Function Definitions
1. **gcd_list**:
- **Input**: A list of non-negative integers `nums`.
- **Output**: An integer representing the GCD o... | from math import gcd
from functools import reduce
def gcd_list(nums):
if not nums or any(not isinstance(n, int) or n < 0 for n in nums):
raise ValueError("List must contain only non-negative integers.")
def gcd_multiple(numbers):
return reduce(gcd, numbers)
return gcd_multiple(num... | import pytest
from solution import gcd_list, lcm_list
def test_gcd_list():
assert gcd_list([24, 36, 48]) == 12
assert gcd_list([5, 10, 15]) == 5
assert gcd_list([1, 1, 1]) == 1
assert gcd_list([17, 19, 23]) == 1
with pytest.raises(ValueError):
gcd_list([-24, 36, 48])
with pytest.raises(... | [
{
"docstring": null,
"function_declaration": "def gcd_list(nums):",
"function_name": "gcd_list",
"parameter_list": "(nums)"
},
{
"docstring": null,
"function_declaration": "def lcm(a, b):",
"function_name": "lcm",
"parameter_list": "(a, b)"
},
{
"docstring": null,
"fu... | [
0,
1,
1,
1,
1,
1,
1,
1,
1,
0
] | 8 | easy | 0.8 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import math\nfrom functools import reduce\n\ndef gcd_list(nums: list) -> int:\n def gcd(a, b):\n while b:\n a, b = b, a % b\n return ... | trial_gpt4o_8 | {
"original_instruction": "### Problem Statement\n\nYou are tasked with implementing two functions to find the greatest common divisor (GCD) and least common multiple (LCM) of a list of integers.\n\n#### Function Definitions\n\n1. **GCD Function (`gcd_list`)**:\n - **Input**: A list of non-negative integers `nums`.... | 0.684934 | Algorithm_27808 | C | [
"gcd_list",
"lcm",
"lcm_list"
] | 3 | [
[
"lcm_list",
"lcm"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 482691fbf85dcba4b0676c3996b166165b7cd7b8 | 9d43b3940ae126c626174aff9aa31cd1e304fe23 | |||
v1.0 | complete | Algorithm | Algorithm_21710_C | from typing import List
def max_flow(graph: List[List[int]], source: int, sink: int) -> int:
""" Calculates the maximum flow in a given flow network using the Ford-Fulkerson algorithm with the Edmonds-Karp implementation.
Args:
graph (List[List[int]]): A 2D list representing the adjacency matrix of th... | from typing import List
from collections import deque
def bfs(rGraph: List[List[int]], s: int, t: int, parent: List[int]) -> bool:
"""
Returns true if there is a path from source 's' to sink 't' in residual graph.
Also fills parent[] to store the path.
"""
visited = [False] * len(rGraph)
queue ... | from solution import max_flow
def test_example_case():
graph = [
[0, 16, 13, 0, 0, 0],
[0, 0, 10, 12, 0, 0],
[0, 4, 0, 0, 14, 0],
[0, 0, 9, 0, 0, 20],
[0, 0, 0, 7, 0, 4],
[0, 0, 0, 0, 0, 0]
]
source = 0
sink = 5
assert max_flow(graph, source, sink) ==... | [
{
"docstring": "Returns true if there is a path from source 's' to sink 't' in residual graph.\nAlso fills parent[] to store the path.",
"function_declaration": "def bfs(rGraph, s, t, parent):",
"function_name": "bfs",
"parameter_list": "(rGraph, s, t, parent)"
},
{
"docstring": "Returns the... | [
1,
1,
0,
0,
1,
1,
0,
1,
0,
0
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from collections import deque\n\ndef bfs(graph, residual_graph, source, sink, parent):\n visited = [False] * len(graph)\n queue = deque([source])\n visi... | trial_gpt4o_7 | {
"original_instruction": "Coding Assessment Question\n\n#### Context:\nYou are required to implement a function that calculates the maximum flow in a given flow network using the Ford-Fulkerson algorithm with the Edmonds-Karp implementation. This algorithm finds the maximal flow from a source vertex to a sink vertex... | 0.536683 | Algorithm_21710 | C | [
"bfs",
"max_flow"
] | 2 | [
[
"max_flow",
"bfs"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 1fc7039e2c80b4db412f4cc5fe633f2ff7fe9e7a | a99856b7358220eb45cace2acf1688a4b919e015 | |||
v1.0 | complete | Algorithm | Algorithm_17687_C | def rotate_array(arr: list[int], d: int, direction: str) -> None:
"""
Rotate an array by n positions in the specified direction.
:param arr: List of integers to rotate.
:param d: Number of positions to rotate.
:param direction: Direction of rotation, either 'left' or 'right'.
"""
n = len(arr... | def rotate_array(arr: list[int], d: int, direction: str) -> None:
"""
Rotate an array by `d` positions in the specified direction.
"""
n = len(arr)
if n == 0 or d == 0:
return
d = d % n # Handle cases where d is larger than the length of the array
if direction == "left":
... | from solution import rotate_array
def test_left_rotation():
arr = [1, 2, 3, 4, 5, 6, 7]
rotate_array(arr, 2, "left")
assert arr == [3, 4, 5, 6, 7, 1, 2]
def test_right_rotation():
arr = [1, 2, 3, 4, 5, 6, 7]
rotate_array(arr, 3, "right")
assert arr == [5, 6, 7, 1, 2, 3, 4]
def test_empty_arra... | [
{
"docstring": "Rotate an array by `d` positions in the specified direction.",
"function_declaration": "def rotate_array(arr, d, direction):",
"function_name": "rotate_array",
"parameter_list": "(arr, d, direction)"
},
{
"docstring": "Helper function to reverse elements in the array from sta... | [
1,
1,
1,
0,
0,
1,
1,
0,
1,
0
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def rotate_array(arr: list[int], d: int, direction: str) -> None:\n \"\"\"\n Rotates the elements of the array to the left or right by `d` positions.\n ... | trial_gpt4o_8 | {
"original_instruction": "### Array Rotation by d Positions\n\n#### Problem Statement\n\nImplement a function to rotate an array by `d` positions. The rotation should be performed in place, meaning you should not use any extra space for another array (other than a few extra variables). The function should be able to... | 0.716334 | Algorithm_17687 | C | [
"rotate_array",
"reverse"
] | 2 | [
[
"rotate_array",
"reverse"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | dd632317e97899a2eb9b9c427233c64a3df50f06 | 264bc07b91e13f3650ac92e84052f1239c7c63fc | |||
v1.0 | complete | Algorithm | Algorithm_16515_C | def merge_sort(arr: list[int]) -> list[int]:
""" Implement the merge sort algorithm to sort an array of integers in non-decreasing order.
>>> merge_sort([3, 6, 2, 7, 1, 5])
[1, 2, 3, 5, 6, 7]
>>> merge_sort([-3, -1, -2, -7, -5, -6])
[-7, -6, -5, -3, -2, -1]
>>> merge_sort([1])
[1]
>>> me... | def merge_sort(arr: list[int]) -> list[int]:
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left = merge_sort(arr[:mid])
right = merge_sort(arr[mid:])
return merge(left, right)
def merge(left: list[int], right: list[int]) -> list[int]:
result = []
i = j = 0
while i < le... | def test_merge_sort_with_duplicates():
assert merge_sort([9, 9, 9, 9]) == [9, 9, 9, 9]
def test_merge_sort_with_single_element():
assert merge_sort([1]) == [1]
def test_merge_sort_with_empty_list():
assert merge_sort([]) == []
def test_merge_sort_with_mixed_elements():
assert merge_sort([-10, 0, 5, -... | [
{
"docstring": null,
"function_declaration": "def merge_sort(arr):",
"function_name": "merge_sort",
"parameter_list": "(arr)"
},
{
"docstring": null,
"function_declaration": "def merge(left, right):",
"function_name": "merge",
"parameter_list": "(left, right)"
}
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 10 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def merge_sort(arr):\n if len(arr) <= 1:\n return arr\n\n def merge(left, right):\n sorted_list = []\n left_index, right_index = 0, 0\... | trial_gpt4o_9 | {
"original_instruction": "Coding Assessment Question\n\n#### Context:\nMerge sort is a classic divide-and-conquer algorithm that efficiently sorts an array by recursively dividing it into two halves, sorting each half, and then merging the sorted halves. Your task is to implement the merge sort algorithm to sort an ... | 0.659712 | Algorithm_16515 | C | [
"merge_sort",
"merge"
] | 2 | [
[
"merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | dc9b1a8eda47e37c1bc65a908a1300a11bc2d5f5 | 0715fee5efc5dcdfe5b4a2a864f51fdcc0903067 | |||
v1.0 | complete | Algorithm | Algorithm_18763_C | import numpy as np
from scipy.linalg import lu
def validate_linear_solvers(
matrices: list[np.ndarray],
vectors: list[np.ndarray],
tolerance: float = 1e-6,
max_iterations: int = 500
) -> bool:
"""
Validate the solution of linear systems using both LU decomposition
and Gauss-Seidel method ag... | import numpy as np
from scipy.linalg import lu
def lu_solve(A: np.ndarray, b: np.ndarray) -> np.ndarray:
P, L, U = lu(A)
y = np.linalg.solve(L, np.dot(P.T, b))
x = np.linalg.solve(U, y)
return x
def gauss_seidel_solve(A: np.ndarray, b: np.ndarray, tolerance: float, max_iterations: int) -> np.ndarray:
... | import numpy as np
from solution import validate_linear_solvers
def test_validate_linear_solvers():
matrices = [
np.array([[4, 1], [2, 3]]),
np.array([[10, 2, 3], [2, 10, 4], [3, 4, 6]])
]
vectors = [
np.array([1, 2]),
np.array([7, 8, 9])
]
assert validate_linear_s... | [
{
"docstring": null,
"function_declaration": "def lu_solve(A, b):",
"function_name": "lu_solve",
"parameter_list": "(A, b)"
},
{
"docstring": null,
"function_declaration": "def gauss_seidel_solve(A, b, tolerance, max_iterations):",
"function_name": "gauss_seidel_solve",
"paramete... | [
1,
1,
1,
0,
1,
0,
0,
1,
1,
1
] | 7 | easy | 0.7 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import numpy as np\nfrom scipy.linalg import lu\n\ndef lu_solve(A: np.ndarray, b: np.ndarray) -> np.ndarray:\n \"\"\" Solve system of linear equations using L... | trial_gpt4o_2 | {
"original_instruction": "### Coding Assessment Question\n\n#### Problem Statement\n\nYou are given the task of implementing a function to solve a system of linear equations using both the LU decomposition and the Gauss-Seidel iterative method. Your function should compare the results of these two methods with the b... | 0.499973 | Algorithm_18763 | C | [
"lu_solve",
"gauss_seidel_solve",
"validate_linear_solvers"
] | 3 | [
[
"validate_linear_solvers",
"gauss_seidel_solve"
],
[
"validate_linear_solvers",
"lu_solve"
]
] | 2 | [] | false | [] | false | pytest | true | [
"numpy",
"scipy"
] | false | 0056266cdb4490b8380f24aaf194349fde589262 | 90e327730d8dc71c46cd8654628eb8ee6ab831cb | |||
v1.0 | complete | Algorithm | Algorithm_17795_C | def path_exists(path: str, current_directory: dict) -> bool:
""" Checks if the given path exists in the current directory structure.
>>> path_exists("home/user/photos/2021", {
"home": {
"user": {
"documents": {},
"photos": {
"2021": {},
... | def path_exists(path, current_directory):
"""
Checks if the given path exists in the current directory structure.
"""
parts = path.strip("/").split("/")
current = current_directory
for part in parts:
if part not in current:
return False
current = current[part]
... | from solution import path_exists, get_full_path
def test_path_exists_existing_path():
current_directory = {
"home": {
"user": {
"documents": {},
"photos": {
"2021": {},
"2022": {}
}
},
... | [
{
"docstring": "Checks if the given path exists in the current directory structure.",
"function_declaration": "def path_exists(path, current_directory):",
"function_name": "path_exists",
"parameter_list": "(path, current_directory)"
},
{
"docstring": "Returns the full relative path from the ... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def path_exists(path: str, current_directory: dict) -> bool:\n \"\"\"\n Checks if the given path exists in the current directory.\n \"\"\"\n componen... | trial_gpt4o_8 | {
"original_instruction": "### Scenario\nYou are developing a file management system that needs to keep track of several files and directories. As part of this system, you want to check if the current directory has a specific path, and if that path exists, retrieve its complete relative path from the root directory.\... | 0.672728 | Algorithm_17795 | C | [
"path_exists",
"get_full_path"
] | 2 | [
[
"get_full_path",
"path_exists"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 607269a54f8c46167a1c9d1d4f4aedb922c6b930 | 2e82c6b18164f0fffbd5bcde37d38c436b236421 | |||
v1.0 | complete | Algorithm | Algorithm_20630_C | def longest_palindrome_substring(s: str) -> str:
""" Find the longest palindromic substring in the input string.
>>> longest_palindrome_substring("babad") in ["bab", "aba"]
True
>>> longest_palindrome_substring("cbbd")
'bb'
>>> longest_palindrome_substring("a")
'a'
>>> longest_palindrome... | def longest_palindrome_substring(s: str) -> str:
if not s:
return ""
start, end = 0, 0
for i in range(len(s)):
len1 = expand_around_center(s, i, i)
len2 = expand_around_center(s, i, i + 1)
max_len = max(len1, len2)
if max_len > end - start:
... | from solution import longest_palindrome_substring
def test_example_1():
assert longest_palindrome_substring("babad") in ["bab", "aba"]
def test_example_2():
assert longest_palindrome_substring("cbbd") == "bb"
def test_single_character():
assert longest_palindrome_substring("a") == "a"
def test_two_disti... | [
{
"docstring": null,
"function_declaration": "def longest_palindrome_substring(s):",
"function_name": "longest_palindrome_substring",
"parameter_list": "(s)"
},
{
"docstring": null,
"function_declaration": "def expand_around_center(s, left, right):",
"function_name": "expand_around_c... | [
0,
0,
1,
1,
1,
1,
1,
0,
1,
0
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def longest_palindrome_substring(s: str) -> str:\n \"\"\"\n Returns the longest palindromic substring in the input string.\n \n :param s: Input strin... | trial_gpt4o_8 | {
"original_instruction": "### Coding Question\n\n**Context:** String manipulation is a common task in programming that involves modifying, parsing, and interpreting text data. Efficiency in handling such tasks is important, especially when dealing with large text inputs or requiring swift processing in real-time app... | 0.778048 | Algorithm_20630 | C | [
"longest_palindrome_substring",
"expand_around_center"
] | 2 | [
[
"longest_palindrome_substring",
"expand_around_center"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 30a5c39df6a6b6fc3362bf19de5c2b66999c1c72 | 02c4e35681c21dc99cfbe3ddd6699cea0df172bb | |||
v1.0 | complete | Algorithm | Algorithm_16769_C | from typing import List, Tuple
def shortest_route(coordinates: List[Tuple[int, int]]) -> List[Tuple[int, int]]:
""" Implement a function that calculates the shortest path to visit all given delivery points
exactly once, starting and ending at a specified depot which is represented as the first point
in t... | from typing import List, Tuple
import itertools
def calculate_distance(p1: Tuple[int, int], p2: Tuple[int, int]) -> float:
"""
Helper function to calculate the Euclidean distance between two points.
"""
return ((p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2) ** 0.5
def total_route_distance(route: List[Tu... | from solution import shortest_route
def test_shortest_route_single_point():
assert shortest_route([(0, 0)]) == [(0, 0), (0, 0)]
def test_shortest_route_two_points():
assert shortest_route([(0, 0), (1, 1)]) == [(0, 0), (1, 1), (0, 0)]
def test_shortest_route_three_points():
assert shortest_route([(0, 0), ... | [
{
"docstring": "Helper function to calculate the Euclidean distance between two points.",
"function_declaration": "def calculate_distance(p1, p2):",
"function_name": "calculate_distance",
"parameter_list": "(p1, p2)"
},
{
"docstring": "Helper function to calculate the total distance of a giv... | [
1,
0,
0,
0,
0,
0,
1,
0,
1,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List, Tuple\nfrom itertools import permutations\n\ndef calculate_distance(p1: Tuple[int, int], p2: Tuple[int, int]) -> float:\n \"\"\"\n ... | trial_gpt4o_8 | {
"original_instruction": "### Scenario:\nAs a software developer for a logistics company, you are tasked with optimizing the route for delivering packages. The company maintains records of delivery points as a series of geographical coordinates. To facilitate the planning, you need to implement a function that calcu... | 0.676498 | Algorithm_16769 | C | [
"calculate_distance",
"total_route_distance",
"shortest_route"
] | 3 | [
[
"shortest_route",
"total_route_distance"
],
[
"total_route_distance",
"calculate_distance"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 82ca0412599d77472c9914361f924fba7a4ffab1 | b9239cccf31a4e85a18f5d8fd4eec2e0d7826275 | |||
v1.0 | complete | Algorithm | Algorithm_24319_C | from typing import List
def simulate_daylight(matrix: List[List[str]]) -> List[List[str]]:
""" Simulates the rotation of a square matrix representing a cityscape over one full daylight cycle.
Args:
matrix: List of lists where each element is 'U' for buildings, 'D' for gardens, or 'P' for parks.
R... | def rotate_90_clockwise(matrix):
"""
Rotates the given n x n matrix 90 degrees clockwise.
"""
n = len(matrix)
new_matrix = [[''] * n for _ in range(n)]
for i in range(n):
for j in range(n):
new_matrix[j][n - 1 - i] = matrix[i][j]
return new_matrix
def simulate_... | from solution import simulate_daylight
def test_simulate_daylight_2x2():
matrix = [
['U', 'D'],
['P', 'U']
]
expected = [
['U', 'D'],
['P', 'U']
]
assert simulate_daylight(matrix) == expected
def test_simulate_daylight_3x3():
matrix = [
['U', 'D', 'P'],
... | [
{
"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": "Simulates the rotation of the square matrix over one full daylight cycle ... | [
1,
1,
0,
0,
0,
0,
1,
1,
1,
1
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef rotate_90_clockwise(matrix: List[List[str]]) -> List[List[str]]:\n \"\"\"Helper function to rotate a matrix 90 degrees clockwis... | trial_gpt4o_9 | {
"original_instruction": "### Coding Question: Matrix Rotation and Daylight Cycles\n\nYou are required to implement a function that simulates the rotation of a square matrix representing a cityscape over one full daylight cycle. The matrix elements can be `U` for buildings, `D` for gardens, or `P` for parks. The mat... | 0.614421 | Algorithm_24319 | C | [
"rotate_90_clockwise",
"simulate_daylight"
] | 2 | [
[
"simulate_daylight",
"rotate_90_clockwise"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 9109ad74af8c406ae3a47813311ab9a36892d8d0 | 075fb918e86208213341060a06e26526ef28ae37 | |||
v1.0 | complete | Algorithm | Algorithm_622_C | def circular_prime_count(limit: int) -> int:
""" Write a function `circular_prime_count(limit)` that takes an integer `limit` and returns the count of circular primes that are less than the given `limit`.
>>> circular_prime_count(100)
13
>>> circular_prime_count(1000)
25
>>> circular_prime_... | from sympy import isprime
def rotate_string(s):
return [s[i:] + s[:i] for i in range(len(s))]
def is_circular_prime(n):
str_n = str(n)
rotations = rotate_string(str_n)
return all(isprime(int(r)) for r in rotations)
def circular_prime_count(limit):
count = 0
for num in range(2, limit):
... | from solution import circular_prime_count
def test_circular_prime_count_small_limits():
assert circular_prime_count(100) == 13
assert circular_prime_count(1000) == 25
def test_circular_prime_count_edge_cases():
assert circular_prime_count(1) == 0
assert circular_prime_count(2) == 0
assert circular... | [
{
"docstring": null,
"function_declaration": "def rotate_string(s):",
"function_name": "rotate_string",
"parameter_list": "(s)"
},
{
"docstring": null,
"function_declaration": "def is_circular_prime(n):",
"function_name": "is_circular_prime",
"parameter_list": "(n)"
},
{
... | [
1,
0,
1,
1,
0,
0,
1,
1,
1,
1
] | 7 | easy | 0.7 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def 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 return False\n i = 5\n ... | trial_gpt4o_9 | {
"original_instruction": "### Context:\nThere is a special set of prime numbers known as circular primes. A circular prime is a prime number that remains prime when its digits are rotated in any way. For example, 197 is a circular prime because 197, 971, and 719 are all prime.\n\n### Task:\nWrite a function `circula... | 0.735329 | Algorithm_622 | C | [
"rotate_string",
"is_circular_prime",
"circular_prime_count"
] | 3 | [
[
"circular_prime_count",
"is_circular_prime"
],
[
"is_circular_prime",
"rotate_string"
]
] | 2 | [] | false | [] | false | pytest | true | [
"sympy"
] | false | c6677e72f1bb04d537d1d5e6be6dfd1e6a9de0bc | 20806018507c12f7174e196d8799b24a44d94cf7 | |||
v1.0 | complete | Algorithm | Algorithm_38276_C | from typing import Any, Union, List
def filter_primes_over_ten(numbers: Any) -> Union[str, List[int]]:
"""Filter out the primes greater than 10 from the list of numbers.
>>> filter_primes_over_ten([11, 12, 13, 4, 5, 19])
[11, 13, 19]
>>> filter_primes_over_ten('12345')
"Error: Input should be ... | from typing import Any, Union, List
def is_prime(n: int) -> bool:
"""Check if an integer n is prime."""
if n <= 1:
return False
if n == 2 or 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:
... | def test_filter_primes_over_ten_valid_input():
assert filter_primes_over_ten([11, 12, 13, 4, 5, 19]) == [11, 13, 19]
assert filter_primes_over_ten([2, 3, 5, 7, 11, 13, 17, 19, 23]) == [11, 13, 17, 19, 23]
assert filter_primes_over_ten([0, 1, 4, 6, 8, 21, 22, 25]) == []
assert filter_primes_over_ten([23,... | [
{
"docstring": "Check if an integer n is prime.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Filter out the primes greater than 10 from the list of numbers.",
"function_declaration": "def filter_primes_over_ten(numb... | [
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 9 | easy | 1 | {
"trial_gpt4o_0": null,
"trial_gpt4o_1": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_1_results_combined.jsonl",
"solution_code": "from typing import Any, Union, List\n\ndef is_prime(n: int) -> bool:\n \"\"\"Check if a number n is prime.\"\"\"\n if n <= 1:\n ... | trial_gpt4o_7 | {
"original_instruction": "### Problem Description\n\nYou have been assigned to create a function that processes a list of integers to generate a new list that only contains the numbers which are both prime numbers and greater than 10. The function should gracefully handle any invalid input, such as non-integer eleme... | 0.679577 | Algorithm_38276 | C | [
"is_prime",
"filter_primes_over_ten"
] | 2 | [
[
"filter_primes_over_ten",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 8ec4e24e4119ee7bc542106efbabc09339535389 | a15c622e569da511d3a21825f7097a048d69582c | |||
v1.0 | complete | Algorithm | Algorithm_35493_C | ### Minimum Spanning Tree (MST) Detection using Kruskal's Algorithm
**Background**:
A telecommunications company is planning to lay out new fiber optic cables to connect multiple cities. To minimize the cost of the project, the company aims to find the minimum spanning tree (MST) of the city's network graph. You are r... | def find_parent(parent, i):
if parent[i] == i:
return i
return find_parent(parent, parent[i])
def union(parent, rank, x, y):
root_x = find_parent(parent, x)
root_y = find_parent(parent, y)
if rank[root_x] < rank[root_y]:
parent[root_x] = root_y
elif rank[root_x] > rank[root... | from solution import kruskal_mst
def test_kruskal_mst_basic():
edges = [
(0, 1, 10),
(0, 2, 6),
(0, 3, 5),
(1, 3, 15),
(2, 3, 4)
]
num_vertices = 4
mst = kruskal_mst(edges, num_vertices)
expected_mst = [(2, 3, 4), (0, 3, 5), (0, 1, 10)]
assert len(mst) ==... | [
{
"docstring": null,
"function_declaration": "def find_parent(parent, i):",
"function_name": "find_parent",
"parameter_list": "(parent, i)"
},
{
"docstring": null,
"function_declaration": "def union(parent, rank, x, y):",
"function_name": "union",
"parameter_list": "(parent, rank... | [
0,
0,
1,
1,
0,
0,
0,
0,
0,
1
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def find_parent(parent, i):\n if parent[i] == i:\n return i\n return find_parent(parent, parent[i])\n\ndef union(parent, rank, xroot, yroot):\n i... | trial_gpt4o_9 | {
"original_instruction": "### Minimum Spanning Tree (MST) Detection using Kruskal's Algorithm\n\n**Background**:\nA telecommunications company is planning to lay out new fiber optic cables to connect multiple cities. To minimize the cost of the project, the company aims to find the minimum spanning tree (MST) of the... | 0.729045 | Algorithm_35493 | C | [
"find_parent",
"union",
"kruskal_mst"
] | 3 | [
[
"kruskal_mst",
"find_parent"
],
[
"kruskal_mst",
"union"
],
[
"union",
"find_parent"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | cfcd2a0a25842fd304e9cf95d9dc3236389e00b5 | 8c6c5004f92091297d3a0141ba5a10a676bdedeb | |||
v1.0 | complete | Algorithm | Algorithm_27822_C | class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def reverse_k_group(head, k):
"""
Reverses the nodes of a linked list in k-group intervals.
Parameters:
head : ListNode
The head node of the linked list.
k : int
The size o... | class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def reverse_k_group(head, k):
"""
Reverses the nodes of a linked list in k-group intervals.
Parameters:
head : ListNode
The head node of the linked list.
k : int
The size o... | from solution import ListNode, reverse_k_group
def list_to_linked(lst):
if not lst:
return None
head = ListNode(lst[0])
current = head
for value in lst[1:]:
current.next = ListNode(value)
current = current.next
return head
def linked_to_list(node):
lst = []
while no... | [] | [
1,
1,
1,
1,
0,
1,
1,
1,
1,
1
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "class ListNode:\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\n\ndef reverse_k_group(head, k):\n \"\"\"\n Re... | trial_gpt4o_6 | {
"original_instruction": "### Question: Reverse a Linked List in K-Group Intervals\n\n**Context**:\nYou need to develop a function that reverses a linked list in groups of `k` nodes. This means that if the linked list has nodes 1 -> 2 -> 3 -> 4 -> 5 and `k` is 2, the linked list should be modified to 2 -> 1 -> 4 -> ... | 0.537838 | Algorithm_27822 | C | [
"reverse_k_group",
"reverse"
] | 2 | [
[
"reverse_k_group",
"reverse"
]
] | 1 | [] | false | [
"ListNode"
] | true | pytest | true | [] | true | 33bb22c5fadc19266fe5b7cc989567db88b9430b | 36d8a3957a3d27396e954fa5ce91a59cf3e5ffd4 | |||
v1.0 | complete | Algorithm | Algorithm_37585_C | KNOWN_DOMAINS = ["gmail.com", "yahoo.com", "outlook.com"]
def parse_email(input_str):
"""Extracts the username and domain from a given email address string.
Args:
input_str (str): Email address.
Returns:
tuple: A tuple containing the username and the domain.
Raises:
ValueErro... | KNOWN_DOMAINS = ["gmail.com", "yahoo.com", "outlook.com"]
def parse_email(input_str):
"""
Extracts the username and domain from an email address.
"""
input_str = input_str.strip()
if "@" not in input_str:
raise ValueError("Invalid email format: missing '@'")
username, domain = inpu... | from solution import parse_email, validate_email, normalize_email
def test_parse_email_valid():
assert parse_email("username@gmail.com") == ("username", "gmail.com")
assert parse_email("user.name@domain.co.uk") == ("user.name", "domain.co.uk")
assert parse_email(" user.name@domain.co.uk ") == ("user.name",... | [
{
"docstring": "Extracts the username and domain from an email address.",
"function_declaration": "def parse_email(input_str):",
"function_name": "parse_email",
"parameter_list": "(input_str)"
},
{
"docstring": "Validates the email address format and checks if the domain is known.",
"fun... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 10 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "KNOWN_DOMAINS = [\"gmail.com\", \"yahoo.com\", \"outlook.com\"]\n\ndef parse_email(input_str):\n \"\"\"\n Extract the username and domain from a given emai... | trial_gpt4o_9 | {
"original_instruction": "### Coding Assessment Question\n\n#### Context\nYou are developing a customer information management system for an e-commerce platform. One of the key features is recording and verifying email addresses to ensure they are in a valid format and associated with known domains.\n\n### Objective... | 0.624267 | Algorithm_37585 | C | [
"parse_email",
"validate_email",
"normalize_email"
] | 3 | [
[
"normalize_email",
"parse_email"
],
[
"validate_email",
"parse_email"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 8caa16b7738da6aaf152cb30526a14a83b3425f0 | 8e7e4992496f046d0f5a2341378cd317e785e8ee | |||
v1.0 | complete | Algorithm | Algorithm_20582_C | from typing import List
def merge_sort(arr: List[int]) -> List[int]:
""" Perform Merge Sort to sort a list of integers in ascending order.
>>> merge_sort([]) # Output: []
>>> merge_sort([1]) # Output: [1]
>>> merge_sort([3, 1, 4, 1, 5, 9, 2, 6]) # Output: [1, 1, 2, 3, 4, 5, 6, 9]
"""
def merge... | from typing import List
def merge_sort(arr: List[int]) -> List[int]:
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left_half = merge_sort(arr[:mid])
right_half = merge_sort(arr[mid:])
return merge(left_half, right_half)
def merge(left: List[int], right: List[int]) -> List[int]:
... | from solution import merge_sort
def test_merge_sort_empty_list():
assert merge_sort([]) == []
def test_merge_sort_single_element():
assert merge_sort([1]) == [1]
def test_merge_sort_already_sorted():
assert merge_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_merge_sort_reverse_sorted():
assert m... | [
{
"docstring": null,
"function_declaration": "def merge_sort(arr):",
"function_name": "merge_sort",
"parameter_list": "(arr)"
},
{
"docstring": null,
"function_declaration": "def merge(left, right):",
"function_name": "merge",
"parameter_list": "(left, right)"
}
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 10 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef merge_sort(arr: List[int]) -> List[int]:\n if len(arr) <= 1:\n return arr\n\n mid = len(arr) // 2\n left_half = me... | trial_gpt4o_9 | {
"original_instruction": "### Coding Assessment Question\n\n#### Context\nHaving efficient algorithms is crucial in computer science. One of the most common tasks is sorting an array. Now, it's time to implement one of the famous sorting algorithms - the Merge Sort. Your goal is to practice implementing the algorith... | 0.585044 | Algorithm_20582 | C | [
"merge_sort",
"merge"
] | 2 | [
[
"merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 62b3f04b49a3e3f8429dc8a8aa78bde6d939ebaf | f91ce4a1469d33c6b24ed5a644bc0fafdbe452e2 | |||
v1.0 | complete | Algorithm | Algorithm_35690_C | [Completion Task in Python]
def atbash_encrypt(message: str, alphabet: str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ") -> str:
""" Encrypts the message using the Atbash cipher with the given alphabet.
>>> atbash_encrypt("HELLO") "SVOOL"
>>> atbash_encrypt("ABCDEFGHIJKLMNOPQRSTUVWXYZ") "ZYXWVUTSRQPONMLKJIHGFEDCBA"
>... | def atbash_encrypt(message: str, alphabet: str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ") -> str:
"""
Encrypts the message using the Atbash cipher with the given alphabet.
"""
if not message:
return ""
if len(set(alphabet)) != len(alphabet):
raise ValueError("Alphabet must contain unique c... | from solution import atbash_encrypt, atbash_decrypt
def test_atbash_encrypt_default_alphabet():
assert atbash_encrypt("HELLO") == "SVOOL"
assert atbash_encrypt("ABCDEFGHIJKLMNOPQRSTUVWXYZ") == "ZYXWVUTSRQPONMLKJIHGFEDCBA"
def test_atbash_decrypt_default_alphabet():
assert atbash_decrypt("SVOOL") == "HELLO... | [
{
"docstring": "Encrypts the message using the Atbash cipher with the given alphabet.",
"function_declaration": "def atbash_encrypt(message, alphabet='ABCDEFGHIJKLMNOPQRSTUVWXYZ'):",
"function_name": "atbash_encrypt",
"parameter_list": "(message, alphabet='ABCDEFGHIJKLMNOPQRSTUVWXYZ')"
},
{
... | [
0,
0,
0,
0,
0,
1,
1,
1,
0,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def atbash_encrypt(message: str, alphabet: str = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\") -> str:\n \"\"\"\n Encrypts the message using the Atbash cipher.\n \n ... | trial_gpt4o_7 | {
"original_instruction": "### Problem Statement\n\nThe Atbash Cipher is a simple substitution cipher originally used for the Hebrew alphabet but can be used for any known alphabet. In Atbash, each letter in an alphabet is mapped to its reverse, so the first letter becomes the last letter, the second letter becomes t... | 0.590223 | Algorithm_35690 | C | [
"atbash_encrypt",
"atbash_decrypt"
] | 2 | [
[
"atbash_decrypt",
"atbash_encrypt"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a9a050d8cb99865f8d22a239131942f0c9950abe | 21e119976cb584be0472027da793408616458714 | |||
v1.0 | complete | Algorithm | Algorithm_8194_C | from collections import defaultdict
# Initialize visitor log
visitor_log = defaultdict(list)
def check_in(visitor_name: str, check_in_time: int) -> None:
"""
Log the check-in time for a visitor.
Args:
visitor_name (str): Name of the visitor.
check_in_time (int): Check-in time in minutes since... | from collections import defaultdict
# Store the check-in and check-out times
visitor_log = defaultdict(list)
def check_in(visitor_name, check_in_time):
"""
Log the check-in time for a visitor.
Args:
visitor_name (str): Name of the visitor.
check_in_time (int): Check-in time in minutes since m... | import pytest
from solution import check_in, check_out, total_time_spent, generate_report, visitor_log
def setup_function():
global visitor_log
visitor_log.clear()
def test_check_in_and_out():
setup_function()
check_in("Alice", 480)
check_out("Alice", 1020)
assert visitor_log == {"Alice": [(48... | [
{
"docstring": "Log the check-in time for a visitor.\n\nArgs:\nvisitor_name (str): Name of the visitor.\ncheck_in_time (int): Check-in time in minutes since midnight.",
"function_declaration": "def check_in(visitor_name, check_in_time):",
"function_name": "check_in",
"parameter_list": "(visitor_name... | [
1,
0,
0,
0,
0,
1,
0,
0,
0
] | 2 | hard | 0.222 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from collections import defaultdict\n\n# Store the check-in and check-out times\nvisitor_log = defaultdict(list)\n\ndef check_in(visitor_name, check_in_time):\n ... | trial_gpt4o_0 | {
"original_instruction": "### Visitor Log System\n\n#### Context\nIn a private library, you are responsible for keeping a log of visitors' check-ins and check-outs. Each visitor's entry and exit times must be recorded, and at the end of the day, a report summarizing the total time each visitor spent in the library i... | 0.550645 | Algorithm_8194 | C | [
"check_in",
"check_out",
"total_time_spent",
"generate_report"
] | 4 | [
[
"generate_report",
"total_time_spent"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c2f003f61b11e8d5f5e12a8f961ccbb327ec4ba7 | df03356d9151aa7eefeadfaeae20be867610c93c | |||
v1.0 | complete | Algorithm | Algorithm_36072_C | def calculate_formula(grid: List[List[Union[str, int]]]) -> List[List[Union[int, float]]]:
""" Evaluate and compute the values for all cells in a grid-based spreadsheet accurately, accounting for the dependencies between cells.
>>> calculate_formula([
... [5, '=A1 + 10'],
... [3, '=A1 * B1']
... | from typing import List, Union
def evaluate_expression(expr: str, grid, values_cache):
if expr in values_cache:
return values_cache[expr]
letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
def get_value(cell):
col = letters.index(cell[0])
row = int(cell[1:]) - 1
return evaluate_cell(gr... | def test_basic_arithmetic():
grid = [
[5, '=A1 + 10'],
[3, '=A1 * B1']
]
assert calculate_formula(grid) == [
[5, 15],
[3, 75]
]
def test_division_by_zero():
grid = [
[6, '=A1 / 0']
]
assert calculate_formula(grid) == [
[6, float('inf')]
]
... | [
{
"docstring": null,
"function_declaration": "def evaluate_expression(expr, grid, values_cache):",
"function_name": "evaluate_expression",
"parameter_list": "(expr, grid, values_cache)"
},
{
"docstring": null,
"function_declaration": "def evaluate_cell(cell, grid, values_cache):",
"f... | [
1,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List, Union\n\ndef evaluate_expression(expr: str, grid, values_cache):\n if expr in values_cache:\n return values_cache[expr]\n\n ... | trial_gpt4o_0 | {
"original_instruction": "### Coding Question: Dynamic Spreadsheet Formula Evaluator\n\nImagine you are developing a simplified spreadsheet application, and you need to implement a dynamic formula evaluator. The application should process and evaluate custom formulas inserted in a grid-based spreadsheet. \n\nImpleme... | 0.566371 | Algorithm_36072 | C | [
"evaluate_expression",
"evaluate_cell",
"calculate_formula"
] | 3 | [
[
"calculate_formula",
"evaluate_cell"
],
[
"evaluate_cell",
"evaluate_expression"
],
[
"evaluate_expression",
"evaluate_cell"
]
] | 3 | [] | false | [] | false | pytest | false | [] | true | 9cbd8a71b04803d566d1e5eaee8ea21c5ef65f65 | 7a28ca9b650d509a660c142e49640603d95b5c29 | |||
v1.0 | complete | Algorithm | Algorithm_37916_C | from typing import List
def matrix_determinant(matrix: List[List[int]]) -> int:
""" Returns the determinant of a square matrix.
Args:
matrix (List[List[int]]): A 2D list of integers representing a square matrix (n x n).
Returns:
int: An integer representing the determinant of the matrix.
Exa... | from typing import List
def matrix_cofactor(matrix: List[List[int]], i: int, j: int) -> List[List[int]]:
"""
Helper function to calculate the cofactor matrix
"""
return [row[:j] + row[j+1:] for row in (matrix[:i] + matrix[i+1:])]
def matrix_determinant(matrix: List[List[int]]) -> int:
"""
Retu... | from solution import matrix_determinant
def test_1x1_matrix():
assert matrix_determinant([[5]]) == 5
def test_2x2_matrix():
assert matrix_determinant([[1, 2], [3, 4]]) == -2
def test_3x3_matrix():
assert matrix_determinant([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) == 0
def test_4x4_matrix():
matrix = [
... | [
{
"docstring": "Helper function to calculate the cofactor matrix",
"function_declaration": "def matrix_cofactor(matrix, i, j):",
"function_name": "matrix_cofactor",
"parameter_list": "(matrix, i, j)"
},
{
"docstring": "Returns the determinant of a square matrix.",
"function_declaration":... | [
0,
0,
1,
1,
0,
0,
0,
0,
1
] | 3 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef matrix_determinant(matrix: List[List[int]]) -> int:\n def compute_determinant(mat):\n if len(mat) == 1:\n ret... | trial_gpt4o_9 | {
"original_instruction": "### Matrix Determinant Calculation\n\n**Context**:\nAs a software engineer, you are tasked with writing a function that computes the determinant of a square matrix. The determinant is a scalar value that is computed from the elements of a square matrix and has many applications in linear al... | 0.544946 | Algorithm_37916 | C | [
"matrix_cofactor",
"matrix_determinant"
] | 2 | [
[
"matrix_determinant",
"matrix_cofactor"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 0dfe62671de9894946b80643f7ba4cd150b1b5b2 | bdb18847e682ba6c3a7633d8651fb38cc051cc3b | |||
v1.0 | complete | Algorithm | Algorithm_36661_C | def validate_vehicle_number(vehicle_number: str) -> bool:
""" Validate the vehicle number to match format XX-1234.
>>> validate_vehicle_number("AB-1234")
True
>>> validate_vehicle_number("A1-234")
False
>>> validate_vehicle_number("1234")
False
>>> validate_vehicle_number("AB-123")
F... | from datetime import datetime
def validate_vehicle_number(vehicle_number: str) -> bool:
"""
Validate the vehicle number to match format XX-1234.
"""
import re
pattern = r"^[A-Z]{2}-\d{4}$"
if re.match(pattern, vehicle_number):
return True
return False
def vehicle_entry(vehicle_numb... | import pytest
from datetime import datetime
from solution import validate_vehicle_number, vehicle_entry, vehicle_exit
def test_validate_vehicle_number_valid():
assert validate_vehicle_number("AB-1234") == True
def test_validate_vehicle_number_invalid():
assert validate_vehicle_number("A1-234") == False
as... | [
{
"docstring": "Validate the vehicle number to match format XX-1234.",
"function_declaration": "def validate_vehicle_number(vehicle_number):",
"function_name": "validate_vehicle_number",
"parameter_list": "(vehicle_number)"
},
{
"docstring": "Register the vehicle in the parking lot dict afte... | [
1,
1,
1,
1,
1,
1,
1,
1,
0,
1
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import re\nfrom datetime import datetime\n\ndef validate_vehicle_number(vehicle_number):\n \"\"\"\n Validates the format of the vehicle number.\n \"\"\"... | trial_gpt4o_9 | {
"original_instruction": "### Coding Question\n\nYou are tasked with developing a small module to manage a parking lot system that operates on a first-come, first-served basis. The module should handle vehicle entries, exits, and maintain records of all parked vehicles along with their entry times.\n\n#### Objective... | 0.540153 | Algorithm_36661 | C | [
"validate_vehicle_number",
"vehicle_entry",
"vehicle_exit"
] | 3 | [
[
"vehicle_entry",
"validate_vehicle_number"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 0c8e2af19e769d745f224de01c5fbe6b4abaec8c | 57731ed3ce70303342065b344d3f99b409d67901 | |||
v1.0 | complete | Algorithm | Algorithm_268_C | def rotate_array(array: list[int], steps: int) -> list[int]:
"""
Rotates the array to the right by the given number of steps in place.
>>> rotate_array([1, 2, 3, 4, 5], 2)
[4, 5, 1, 2, 3]
>>> rotate_array([1, 2, 3, 4, 5], 5)
[1, 2, 3, 4, 5]
>>> rotate_array([], 3)
[]
>>> rotate_... | def rotate_array(array, steps):
"""
Rotates the array to the right by the given number of steps in place.
"""
if not array:
return array
n = len(array)
steps = steps % n # Handle cases where steps > n
# Reverse the entire array
reverse(array, 0, n - 1)
# Reverse the first ... | from solution import rotate_array
def test_rotate_array_normal_case():
assert rotate_array([1, 2, 3, 4, 5], 2) == [4, 5, 1, 2, 3]
def test_rotate_array_steps_equals_length():
assert rotate_array([1, 2, 3, 4, 5], 5) == [1, 2, 3, 4, 5]
def test_rotate_array_empty_array():
assert rotate_array([], 3) == []
... | [
{
"docstring": "Rotates the array to the right by the given number of steps in place.",
"function_declaration": "def rotate_array(array, steps):",
"function_name": "rotate_array",
"parameter_list": "(array, steps)"
},
{
"docstring": "Reverses the elements in the array from start to end indic... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 10 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def rotate_array(array: list[int], steps: int) -> list[int]:\n \"\"\"\n Rotates the array to the right by the given number of steps.\n \"\"\"\n if no... | trial_gpt4o_9 | {
"original_instruction": "### Array Rotation Challenge\n\nYou are given an array and a number of steps. Your task is to rotate the array to the right by the given number of steps. The rotation should be done in place, meaning that no additional arrays or data structures should be used.\n\n#### Detailed Instructions:... | 0.670935 | Algorithm_268 | C | [
"rotate_array",
"reverse"
] | 2 | [
[
"rotate_array",
"reverse"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | b9db950eac9d2a6c0b841db72be6b9a7ea700f12 | 8fdd6755cffacb7ec822e690b7ad5558bd7ce2f9 | |||
v1.0 | complete | Algorithm | Algorithm_1374_C | def fibonacci_a_b(a: int, b: int) -> list[int]:
"""
Generates a Fibonacci sequence starting with the values a and b.
:param a: int, the first number in the sequence.
:param b: int, the second number in the sequence.
:return: list[int], the Fibonacci sequence starting with a and b.
"""
pass
... | def fibonacci_a_b(a: int, b: int) -> list[int]:
"""
Generates a Fibonacci sequence starting with the values a and b.
:param a: int, the first number in the sequence.
:param b: int, the second number in the sequence.
:return: list[int], the Fibonacci sequence starting with a and b.
"""
sequen... | from solution import fibonacci_a_b, first_n_fibonacci
def test_fibonacci_a_b():
assert fibonacci_a_b(0, 1) == [0, 1]
assert fibonacci_a_b(2, 3) == [2, 3]
assert fibonacci_a_b(1, 1) == [1, 1]
def test_first_n_fibonacci():
assert first_n_fibonacci(1) == [0]
assert first_n_fibonacci(2) == [0, 1]
... | [
{
"docstring": "Generates a Fibonacci sequence starting with the values a and b.\n:param a: int, the first number in the sequence.\n:param b: int, the second number in the sequence.\n:return: list[int], the Fibonacci sequence starting with a and b.",
"function_declaration": "def fibonacci_a_b(a, b):",
"... | [
0,
1,
0,
1,
0,
0,
1,
0,
1,
0
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def fibonacci_a_b(a: int, b: int) -> list[int]:\n \"\"\"\n Generates a Fibonacci sequence starting with the values a and b.\n :param a: int, the first n... | trial_gpt4o_6 | {
"original_instruction": "### Fibonacci Sequence Generation\n\nYou have been asked to implement a function that generates the first `n` numbers in the Fibonacci sequence. The Fibonacci sequence is defined as follows:\n\n- `F(0) = 0`\n- `F(1) = 1`\n- For all `n ≥ 2`, `F(n) = F(n-1) + F(n-2)`\n\nYour tasks are to comp... | 0.824009 | Algorithm_1374 | C | [
"fibonacci_a_b",
"first_n_fibonacci"
] | 2 | [
[
"first_n_fibonacci",
"fibonacci_a_b"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 1d901dfa4aa805102f6f688475eca2f95fdedf01 | 3572f9091d97d5e594af2aaaa3b98010b6bc341d | |||
v1.0 | complete | Algorithm | Algorithm_38713_C | def shortest_delivery_route(depot: tuple, locations: list) -> list:
""" Determines the optimal delivery route starting and ending at the depot while visiting all other delivery locations exactly once.
>>> depot = (0, 0)
>>> locations = [(2, 1), (3, 5), (5, 2)]
>>> shortest_delivery_route(depot, location... | from itertools import permutations
def calculate_distance(p1, p2):
"""Calculate the Euclidean distance between two points p1 and p2."""
return ((p1[0] - p2[0])**2 + (p1[1] - p2[1])**2) ** 0.5
def shortest_delivery_route(depot, locations):
"""
Determines the shortest delivery route starting and ending ... | from solution import shortest_delivery_route
def test_single_location():
depot = (1, 1)
locations = [(2, 2)]
expected = [(1, 1), (2, 2), (1, 1)]
assert shortest_delivery_route(depot, locations) == expected
def test_multiple_locations():
depot = (0, 0)
locations = [(2, 1), (3, 5), (5, 2)]
#... | [
{
"docstring": "Calculate the Euclidean distance between two points p1 and p2.",
"function_declaration": "def calculate_distance(p1, p2):",
"function_name": "calculate_distance",
"parameter_list": "(p1, p2)"
},
{
"docstring": "Determines the shortest delivery route starting and ending at the... | [
0,
0,
1,
1,
1,
1,
0,
1,
1,
0
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import itertools\nimport math\n\ndef calculate_distance(point1, point2):\n \"\"\"\n Calculates the Euclidean distance between two points.\n \"\"\"\n ... | trial_gpt4o_8 | {
"original_instruction": "### Context\n\nA logistics company requires an optimized solution to manage their delivery routes effectively. They need a function that can determine the shortest delivery route passing through all the delivery locations (similar to the Traveling Salesman Problem) but with a constraint tha... | 0.561949 | Algorithm_38713 | C | [
"calculate_distance",
"shortest_delivery_route"
] | 2 | [
[
"shortest_delivery_route",
"calculate_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ead02926ff87bf3264dfa51fb26150e0964b7f07 | 2a004634d98eebd55e29545428b2af08f97da8c3 | |||
v1.0 | complete | Algorithm | Algorithm_41395_C | def radix_sort(arr: List[int]) -> List[int]:
""" Sort a list of non-negative integers using the radix sort algorithm.
>>> radix_sort([170, 45, 75, 90, 802, 24, 2, 66])
[2, 24, 45, 66, 75, 90, 170, 802]
>>> radix_sort([1])
[1]
>>> radix_sort([])
[]
>>> radix_sort([5, 5, 5, 5, 5])
[5, ... | from typing import List
def counting_sort(arr: List[int], exp: int) -> List[int]:
n = len(arr)
output = [0] * n
count = [0] * 10
for i in range(n):
index = arr[i] // exp
count[index % 10] += 1
for i in range(1, 10):
count[i] += count[i - 1]
i = n - 1
w... | from solution import radix_sort
def test_radix_sort_normal_case():
assert radix_sort([170, 45, 75, 90, 802, 24, 2, 66]) == [2, 24, 45, 66, 75, 90, 170, 802]
def test_radix_sort_single_element():
assert radix_sort([1]) == [1]
def test_radix_sort_empty_list():
assert radix_sort([]) == []
def test_radix_so... | [
{
"docstring": null,
"function_declaration": "def counting_sort(arr, exp):",
"function_name": "counting_sort",
"parameter_list": "(arr, exp)"
},
{
"docstring": null,
"function_declaration": "def radix_sort(arr):",
"function_name": "radix_sort",
"parameter_list": "(arr)"
}
] | [
1,
1,
0,
1,
1,
1,
1,
1,
1,
1
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef counting_sort(arr: List[int], exp: int) -> List[int]:\n n = len(arr)\n output = [0] * n\n count = [0] * 10\n\n # Store... | trial_gpt4o_9 | {
"original_instruction": "### Radix Sort Implementation\n\nYou are required to implement the `radix_sort` function to sort a list of non-negative integers using the radix sort algorithm. This sorting algorithm processes the integers digit by digit from the least significant to the most significant digit.\n\n#### Fun... | 0.709845 | Algorithm_41395 | C | [
"counting_sort",
"radix_sort"
] | 2 | [
[
"radix_sort",
"counting_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ba484ddcd537011ce51c12dda450292e7f802e04 | de6856cadf1595b99921e8919a371613e984b9cc | |||
v1.0 | complete | Algorithm | Algorithm_36006_C | import selectors
import socket
import types
import signal
import logging
def start_chat_server(port: int = 12345) -> None:
"""
Create a basic chat room server that handles multiple clients concurrently using non-blocking I/O operations.
The server listens for incoming client connections and broadcasts mess... | import selectors
import socket
import types
import signal
import logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(message)s')
selector = selectors.DefaultSelector()
def accept(sock):
conn, addr = sock.accept() # Should be ready to read
logging.info(f"Accepted connection from {addr}")
... | import socket
import threading
import time
from solution import start_chat_server
def run_server():
start_chat_server(12345)
def test_server_start():
# Start server in a separate thread
server_thread = threading.Thread(target=run_server, daemon=True)
server_thread.start()
# Give the server some ... | [
{
"docstring": null,
"function_declaration": "def accept(sock):",
"function_name": "accept",
"parameter_list": "(sock)"
},
{
"docstring": null,
"function_declaration": "def service_connection(key, mask):",
"function_name": "service_connection",
"parameter_list": "(key, mask)"
}... | [
0,
0,
0,
0,
0,
1,
0,
0,
0
] | 1 | hard | 0.111 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import socket\nimport selectors\nimport types\nimport signal\nimport logging\nimport threading\n\nlogging.basicConfig(level=logging.INFO, format='%(asctime)s - %... | trial_gpt4o_5 | {
"original_instruction": "### Chat Room Server with Non-Blocking I/O and Connection Management\n\nYou are tasked with creating a basic chat room server that handles multiple clients concurrently. The server should use non-blocking I/O operations to efficiently manage multiple connected clients and broadcast messages... | 0.712975 | Algorithm_36006 | C | [
"accept",
"service_connection",
"start_chat_server"
] | 3 | [
[
"start_chat_server",
"accept"
],
[
"start_chat_server",
"service_connection"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | ffae6e1b8c7b893fa871a76602349ca9ceb005d6 | f01531cb670f01664ddc94538a0517ec9b720385 | |||
v1.0 | complete | Algorithm | Algorithm_28139_C | def insertion_sort(arr: List[int], left: int, right: int) -> None:
""" Perform insertion sort on the subarray arr[left:right+1] """
pass
def merge(arr: List[int], left: int, mid: int, right: int) -> None:
""" Merge two sorted subarrays arr[left:mid+1] and arr[mid+1:right+1] """
pass
def hybrid_sort_re... | from typing import List
def insertion_sort(arr: List[int], left: int, right: int) -> None:
"""
Perform insertion sort on the subarray arr[left:right+1]
"""
for i in range(left + 1, right + 1):
key = arr[i]
j = i - 1
while j >= left and arr[j] > key:
arr[j + 1] = arr[... | def test_hybrid_sort_case_1():
assert hybrid_sort([38, 27, 43, 3, 9, 82, 10], 5) == [3, 9, 10, 27, 38, 43, 82]
def test_hybrid_sort_case_2():
assert hybrid_sort([1, 2, 3, 5, 4, 7, 6], 3) == [1, 2, 3, 4, 5, 6, 7]
def test_hybrid_sort_single_element():
assert hybrid_sort([1], 2) == [1]
def test_hybrid_sort... | [
{
"docstring": "Perform insertion sort on the subarray arr[left:right+1]",
"function_declaration": "def insertion_sort(arr, left, right):",
"function_name": "insertion_sort",
"parameter_list": "(arr, left, right)"
},
{
"docstring": "Merge two sorted subarrays arr[left:mid+1] and arr[mid+1:ri... | [
1,
1,
0,
1,
1,
0,
1,
1,
1,
1
] | 8 | easy | 0.8 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef insertion_sort(arr: List[int], left: int, right: int) -> None:\n for i in range(left + 1, right + 1):\n key = arr[i]\n ... | trial_gpt4o_9 | {
"original_instruction": "### Coding Assessment Question\n\nYou are provided with a basic implementation of a sorting algorithm. Your task is to extend this by implementing a hybrid sorting algorithm that combines the strengths of both Merge Sort and Insertion Sort for improved performance, particularly on nearly so... | 0.551415 | Algorithm_28139 | C | [
"insertion_sort",
"merge",
"hybrid_sort_recursive",
"hybrid_sort"
] | 4 | [
[
"hybrid_sort",
"hybrid_sort_recursive"
],
[
"hybrid_sort_recursive",
"insertion_sort"
],
[
"hybrid_sort_recursive",
"merge"
]
] | 3 | [] | false | [] | false | pytest | false | [] | true | c4641bf2593ebff5555f149043d5a54de8cdf0ad | a54b90f2dcad76ca7477f0106b4d9f14c5edfe97 | |||
v1.0 | complete | Algorithm | Algorithm_33322_C | import random
from typing import List, Tuple
def sigmoid(z: float) -> float:
"""
Calculate the sigmoid of z.
"""
return 1 / (1 + math.exp(-z))
def train_neuron(X: List[List[float]], y: List[int], learning_rate: float, epochs: int) -> Tuple[List[float], float]:
"""
Train a single neuron using g... | import random
import math
from typing import List, Tuple
def sigmoid(z: float) -> float:
"""
Calculate the sigmoid of z.
"""
return 1 / (1 + math.exp(-z))
def train_neuron(X: List[List[float]], y: List[int], learning_rate: float, epochs: int) -> Tuple[List[float], float]:
"""
Train a single ne... | from solution import train_neuron
import random
def test_training_neuron():
# Setting a random seed for reproducibility
random.seed(0)
X = [[0.1, 0.5], [0.2, 0.6], [0.3, 0.7], [0.4, 0.8], [0.5, 0.9]]
y = [0, 0, 1, 1, 1]
learning_rate = 0.1
epochs = 1000
W, b = train_neuron(X, y, learn... | [
{
"docstring": "Calculate the sigmoid of z.",
"function_declaration": "def sigmoid(z):",
"function_name": "sigmoid",
"parameter_list": "(z)"
},
{
"docstring": "Train a single neuron using gradient descent.\n\nArgs:\nX (List[List[float]]): The feature vectors.\ny (List[int]): The binary label... | [
1,
1,
1,
1,
0,
1,
1,
1,
1,
1
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import random\nimport math\nfrom typing import List, Tuple\n\ndef sigmoid(z: float) -> float:\n return 1 / (1 + math.exp(-z))\n\ndef train_neuron(X: List[List... | trial_gpt4o_9 | {
"original_instruction": "### Coding Assessment Question\n\n#### Scenario\nYou are tasked to implement a simplified artificial neural network (ANN) for binary classification purposes. The network consists of a single neuron with a sigmoid activation function. You need to construct and train this neuron to classify d... | 0.641903 | Algorithm_33322 | C | [
"sigmoid",
"train_neuron"
] | 2 | [
[
"train_neuron",
"sigmoid"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 1846ae2f3f25101cd059566c9c38622c54fc96b9 | cfe4dca330b89d0f333a709f3cab6bbd00c80df6 | |||
v1.0 | complete | Algorithm | Algorithm_46168_C | import matplotlib.pyplot as plt
from collections import Counter
def prime_factors(n):
""" Helper function to decompose the input number into its prime factors.
>>> prime_factors(360)
[2, 2, 2, 3, 3, 5]
>>> prime_factors(128)
[2, 2, 2, 2, 2, 2, 2]
"""
i = 2
factors = []
while i * i <... | import matplotlib.pyplot as plt
from collections import Counter
def prime_factors(n):
i = 2
factors = []
while i * i <= n:
if n % i:
i += 1
else:
n //= i
factors.append(i)
if n > 1:
factors.append(n)
return factors
def prime_factor_pie_ch... | import pytest
from solution import prime_factors, prime_factor_pie_chart
def test_prime_factors_360():
assert prime_factors(360) == [2, 2, 2, 3, 3, 5]
def test_prime_factors_128():
assert prime_factors(128) == [2]*7
def test_prime_factors_10007():
assert prime_factors(10007) == [10007] # 10007 is a prim... | [
{
"docstring": null,
"function_declaration": "def prime_factors(n):",
"function_name": "prime_factors",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def prime_factor_pie_chart(number):",
"function_name": "prime_factor_pie_chart",
"parameter_list": "(nu... | [
1,
0,
1,
1,
1,
1,
1,
1,
1,
1
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import matplotlib.pyplot as plt\nfrom collections import Counter\n\ndef prime_factors(n):\n \"\"\"\n Returns the list of prime factors of a given integer n... | trial_gpt4o_8 | {
"original_instruction": "### Question\n\n**Prime Factorization and Pie Chart Visualization**\n\nIn this challenge, you will implement a function that performs prime factorization of a given integer and then plots the result as a pie chart. This problem tests your ability to implement basic number theory algorithms ... | 0.67721 | Algorithm_46168 | C | [
"prime_factors",
"prime_factor_pie_chart"
] | 2 | [
[
"prime_factor_pie_chart",
"prime_factors"
]
] | 1 | [] | false | [] | false | pytest | true | [
"matplotlib"
] | false | c8e6246cef8bbf9f60b6aa07960f29cd8f08755d | 8c36645a338c79ded1b7f2538db93132d478bb0a | |||
v1.0 | complete | Algorithm | Algorithm_34342_C | def split_and_sort(input_file: str, chunk_size: int, temp_file_prefix: str) -> list[str]:
""" Splits the large input file into sorted chunks and returns a list of temporary file paths. """
pass
def merge_sorted_files(temp_files: list[str], output_file: str):
""" Merges the sorted temporary files into a sin... | import heapq
import os
import tempfile
def split_and_sort(input_file: str, chunk_size: int, temp_file_prefix: str) -> list[str]:
temp_files = []
with open(input_file, 'r') as f:
while True:
lines = f.readlines(chunk_size)
if not lines:
break
lines.sor... | import os
def create_test_file(file_name: str, lines: list[str]):
with open(file_name, 'w') as f:
f.writelines(lines)
def test_split_and_sort():
test_input = 'test_input.txt'
create_test_file(test_input, ["apple alpha\n", "zebra zoo\n", "banana beta\n", "cherry cherry\n"])
temp_files = split_a... | [
{
"docstring": null,
"function_declaration": "def split_and_sort(input_file, chunk_size, temp_file_prefix):",
"function_name": "split_and_sort",
"parameter_list": "(input_file, chunk_size, temp_file_prefix)"
},
{
"docstring": null,
"function_declaration": "def merge_sorted_files(temp_fil... | [
0,
0,
0,
1,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import os\nimport heapq\nimport tempfile\n\ndef split_and_sort(input_file: str, chunk_size: int, temp_file_prefix: str) -> list[str]:\n \"\"\" Splits the larg... | trial_gpt4o_3 | {
"original_instruction": "### Coding Assessment Question\n\n#### Sorting Large Files Split\n\n**Scenario**: You are tasked with sorting a very large file that cannot fit entirely into memory. The file contains lines of text, and each line is a record that needs to be sorted based on a specified key. The primary key ... | 0.542398 | Algorithm_34342 | C | [
"split_and_sort",
"merge_sorted_files",
"external_sort"
] | 3 | [
[
"external_sort",
"merge_sorted_files"
],
[
"external_sort",
"split_and_sort"
]
] | 2 | [] | false | [] | false | pytest | false | [] | true | 78152f5ddfca5f7af017f7326e7f80c9c499924f | 0d9da885e02be101519d55d9788df4adc145042d | |||
v1.0 | complete | Algorithm | Algorithm_42666_C | def find_pivot_index(arr: list[int]) -> int:
"""Find the index of the smallest element (pivot) in the rotated sorted array.
>>> find_pivot_index([4, 5, 6, 7, 0, 1, 2])
4
>>> find_pivot_index([12, 15, 18, 2, 3, 6])
3
>>> find_pivot_index([1])
0
>>> find_pivot_index([1, 2, 3, 4, 5])
... | def find_pivot_index(arr):
"""
Finds the index of the smallest element (pivot) in the rotated sorted array.
"""
left, right = 0, len(arr) - 1
while left < right:
mid = (left + right) // 2
if arr[mid] > arr[right]:
left = mid + 1
else:
right = mid
r... | def test_find_pivot_index():
assert find_pivot_index([4, 5, 6, 7, 0, 1, 2]) == 4
assert find_pivot_index([12, 15, 18, 2, 3, 6]) == 3
assert find_pivot_index([1]) == 0
assert find_pivot_index([1, 2, 3, 4, 5]) == 0
assert find_pivot_index([5, 1, 2, 3, 4]) == 1
def test_search_in_rotated_array():
... | [
{
"docstring": "Finds the index of the smallest element (pivot) in the rotated sorted array.",
"function_declaration": "def find_pivot_index(arr):",
"function_name": "find_pivot_index",
"parameter_list": "(arr)"
},
{
"docstring": "Searches for the target in the rotated sorted array and retur... | [
1,
1,
0,
1,
1,
1,
1,
1,
1
] | 8 | easy | 0.889 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def find_pivot_index(arr):\n \"\"\"\n Finds the index of the pivot (the smallest element) in the rotated sorted array.\n \"\"\"\n low, high = 0, len(... | trial_gpt4o_7 | {
"original_instruction": "### Coding Question: Identify Rotated Array's Pivot Index\n\nGiven a rotated sorted array of unique integers, your task is to implement two functions to identify the pivot point (index) and determine whether a given target is present in the array.\n\n1. **Function 1: `find_pivot_index(arr: ... | 0.65809 | Algorithm_42666 | C | [
"find_pivot_index",
"search_in_rotated_array"
] | 2 | [
[
"search_in_rotated_array",
"find_pivot_index"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 87f6a2810dbc96f5031641abc6c9836fa16a30a6 | fb095050f2e2604e5b40102f64c370157b17edc2 | |||
v1.0 | complete | Algorithm | Algorithm_46969_C | def find_closest_points(points: list[tuple[int, int]], k: int) -> list[tuple[int, int]]:
"""Finds the `k` closest points to the origin (0, 0) using the Euclidean distance.
Args:
points (list of tuple): List of tuples where each tuple contains two integers representing
the (x, y)... | import heapq
def euclidean_distance(point):
"""
Helper function to calculate the squared Euclidean distance from origin (0, 0).
Squared distance is used to avoid floating-point operations and preserve performance.
"""
x, y = point
return x * x + y * y
def find_closest_points(points, k):
""... | from solution import find_closest_points
def test_find_closest_points_example():
points = [(1, 3), (3, 4), (2, -1)]
k = 2
expected = {(1, 3), (2, -1)} # sets are used because the order does not matter
assert set(find_closest_points(points, k)) == expected
def test_find_closest_points_basic():
poi... | [
{
"docstring": "Helper function to calculate the squared Euclidean distance from origin (0, 0).\nSquared distance is used to avoid floating-point operations and preserve performance.",
"function_declaration": "def euclidean_distance(point):",
"function_name": "euclidean_distance",
"parameter_list": ... | [
0,
0,
0,
0,
0,
1,
0,
0,
0,
1
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import heapq\nimport math\n\ndef find_closest_points(points, k):\n \"\"\"\n Finds and returns the k closest points to the origin (0, 0).\n \n Args:\n... | trial_gpt4o_5 | {
"original_instruction": "### Question: Efficiently Find Closest Points\n\n#### Scenario\nYou are given a list of points in a 2D plane, each represented by their `(x, y)` coordinates. Your task is to find the `k` closest points to the origin `(0, 0)` using the Euclidean distance. This is a common problem in various ... | 0.710656 | Algorithm_46969 | C | [
"euclidean_distance",
"find_closest_points"
] | 2 | [
[
"find_closest_points",
"euclidean_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 6c506fa1f7d177e94f7955c501515aa0d4620015 | 8cadccd287b14544157d4a56e7adecb98bc8a398 | |||
v1.0 | complete | Algorithm | Algorithm_1153_C | def recursive_merge_sort(arr: list[int]) -> list[int]:
""" Implement a recursive merge sort algorithm to sort a list of integers in ascending order.
>>> recursive_merge_sort([3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5])
[1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]
>>> recursive_merge_sort([])
[]
>>> recursive_merge_s... | def recursive_merge_sort(arr: list[int]) -> list[int]:
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left_half = recursive_merge_sort(arr[:mid])
right_half = recursive_merge_sort(arr[mid:])
return merge(left_half, right_half)
def merge(left: list[int], right: list[int]) -> list[int]:
... | from solution import recursive_merge_sort
def test_empty_list():
assert recursive_merge_sort([]) == []
def test_single_element_list():
assert recursive_merge_sort([1]) == [1]
def test_sorted_list():
assert recursive_merge_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_reverse_sorted_list():
asser... | [
{
"docstring": null,
"function_declaration": "def recursive_merge_sort(arr):",
"function_name": "recursive_merge_sort",
"parameter_list": "(arr)"
},
{
"docstring": null,
"function_declaration": "def merge(left, right):",
"function_name": "merge",
"parameter_list": "(left, right)"... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 10 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def recursive_merge_sort(arr):\n \"\"\"\n Function to sort a list of integers in ascending order using the recursive merge sort algorithm.\n \"\"\"\n ... | trial_gpt4o_9 | {
"original_instruction": "### Question: Implement a Recursive Merge Sort\n\nYou have to implement the merge sort algorithm recursively. Given a list of integers, return the list sorted in ascending order using a recursive merge sort.\n\n#### Function Signature\n```python\ndef recursive_merge_sort(arr: list[int]) -> ... | 0.601249 | Algorithm_1153 | C | [
"recursive_merge_sort",
"merge"
] | 2 | [
[
"recursive_merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 99d96d66a0ff8135c9b33ba559f29857fccd10b8 | b7e937d594bddaf74bb49fb3e90b265a6f18cd11 | |||
v1.0 | complete | Algorithm | Algorithm_1937_C | import os
import re
def clean_and_merge_articles(article_dir: str, output_file: str, banned_words: list) -> None:
""" Clean up user-submitted articles by removing HTML tags, special characters, and banned words,
and then merge all cleaned articles into a single document.
Args:
article_dir (str): Path ... | import os
import re
def clean_html_tags(text):
"""Remove HTML tags from text"""
cleanr = re.compile('<.*?>')
return re.sub(cleanr, '', text)
def clean_special_characters(text):
"""Remove special characters, keeping only alphanumeric and whitespace"""
return re.sub(r'[^A-Za-z0-9\s]', '', text)
def... | import os
import tempfile
from solution import clean_and_merge_articles
def test_clean_and_merge_articles():
# Create temporary directory and files
with tempfile.TemporaryDirectory() as temp_dir:
file1_path = os.path.join(temp_dir, "article1.txt")
file2_path = os.path.join(temp_dir, "article2.t... | [
{
"docstring": "Remove HTML tags from text",
"function_declaration": "def clean_html_tags(text):",
"function_name": "clean_html_tags",
"parameter_list": "(text)"
},
{
"docstring": "Remove special characters, keeping only alphanumeric and whitespace",
"function_declaration": "def clean_sp... | [
0,
1,
0,
0,
0,
0,
1,
1,
0,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import os\nimport re\nfrom glob import glob\n\ndef clean_text(text, banned_words):\n # Remove HTML tags\n text = re.sub(r'<.*?>', ' ', text)\n # Remove ... | trial_gpt4o_7 | {
"original_instruction": "### Coding Assessment Question\n\n**Objective:** Implement a function to sanitize and merge user-submitted articles into a single document.\n\n#### Problem Statement\n\nYou are given a dataset of user-submitted articles stored in individual text files. Each article may contain HTML tags, sp... | 0.543072 | Algorithm_1937 | C | [
"clean_html_tags",
"clean_special_characters",
"remove_banned_words",
"clean_and_merge_articles"
] | 4 | [
[
"clean_and_merge_articles",
"clean_html_tags"
],
[
"clean_and_merge_articles",
"clean_special_characters"
],
[
"clean_and_merge_articles",
"remove_banned_words"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 160d106234a628459eebd07f61d8b8e52df9b39b | 28019c98be5f675d46e2ae43284f53e3ce179e04 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.