version stringclasses 1
value | style stringclasses 2
values | subset stringclasses 12
values | question_id stringlengths 9 23 | question stringlengths 27 8.13k | solution stringlengths 99 5.97k | test stringlengths 105 4.45k | test_info listlengths 0 13 | gpt_pass_sequence listlengths 1 10 | gpt_pass_trial_num int64 1 10 | gpt_difficulty stringclasses 3
values | gpt_pass_percentage float64 0.1 1 | trials dict | chosen_trial stringclasses 10
values | metadata dict | benchmark_similarity float64 0.16 0.93 | benchmark_instruction stringclasses 1
value | benchmark_task_id stringclasses 1
value | filter_reason stringclasses 1
value | base_id stringlengths 7 21 | variant stringclasses 2
values | top_function_names listlengths 2 13 | n_top_functions int64 2 13 | helper_call_edges listlengths 1 16 | n_helper_call_edges int64 1 16 | harness_functions listlengths 0 3 | structural_wrapper bool 1
class | class_names listlengths 0 5 | has_class bool 2
classes | test_kind stringclasses 1
value | test_has_solution_import bool 2
classes | third_party_imports listlengths 0 5 | stdlib_only bool 2
classes | question_norm_sha1 stringlengths 40 40 | solution_ast_sha1 stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
v1.0 | instruct | Algorithm | Algorithm_47666_I | ### Question
You are required to create a password verification tool that aims to validate the strength of user-provided passwords. The tool should provide a comprehensive analysis of the password by checking several criteria and ensure it meets the defined standards for security.
#### Function Specifications:
1. **c... | def check_length(password: str) -> bool:
"""
Validates that the password length is greater or equal to 8 characters.
"""
return len(password) >= 8
def check_character_types(password: str) -> bool:
"""
Validates that the password contains at least:
* One uppercase alphabetic character (A-Z)
... | def test_check_length():
assert check_length("Password123!") == True
assert check_length("Pass1!") == False
def test_check_character_types():
assert check_character_types("Password123!") == True
assert check_character_types("password123") == False
assert check_character_types("PASSWORD123") == Fals... | [
{
"docstring": "Validates that the password length is greater or equal to 8 characters.",
"function_declaration": "def check_length(password):",
"function_name": "check_length",
"parameter_list": "(password)"
},
{
"docstring": "Validates that the password contains at least:\n* One uppercase ... | [
0,
0,
1,
0,
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": "def check_length(password: str) -> bool:\n \"\"\"\n Validates that the password length is greater or equal to 8 characters.\n \"\"\"\n return len(pas... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "0000047666",
"row_id": 47666,
"seed_ids": "[247]"
} | 0.603549 | Algorithm_47666 | I | [
"check_length",
"check_character_types",
"is_common_password",
"verify_password"
] | 4 | [
[
"verify_password",
"check_character_types"
],
[
"verify_password",
"check_length"
],
[
"verify_password",
"is_common_password"
]
] | 3 | [] | false | [] | false | pytest | false | [] | true | 44a205b55c57e5e0b167e067868d1e0a96e34de9 | 7544d63d81d7fb75d1a46ff3dcee84ae519f27f4 | |||
v1.0 | instruct | Algorithm | Algorithm_47696_I | ### Advanced Sorting Algorithms Implementation and Application
#### Objective
Develop and implement the Merge Sort and Quick Sort algorithms to sort arrays, and write a function that selects the appropriate sorting algorithm based on the input array size.
### Task Description
1. **Function Implementations**:
- Im... | from typing import List
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]:
sorted_list = []
wh... | def test_merge_sort():
assert merge_sort([]) == []
assert merge_sort([5]) == [5]
assert merge_sort([3, 1, 2]) == [1, 2, 3]
assert merge_sort([10, -1, 2, 5, 0]) == [-1, 0, 2, 5, 10]
def test_quick_sort():
assert quick_sort([]) == []
assert quick_sort([5]) == [5]
assert quick_sort([3, 1, 2]) ... | [
{
"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)"
},
{
"docst... | [
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 mid = len(arr) // 2\n left = merge_sort(arr[:mid])\n right = merge_sort(arr[mid:])\n ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000047696",
"row_id": 47696,
"seed_ids": "[4676]"
} | 0.705268 | Algorithm_47696 | I | [
"merge_sort",
"merge",
"quick_sort",
"sort_array"
] | 4 | [
[
"merge_sort",
"merge"
],
[
"sort_array",
"merge_sort"
],
[
"sort_array",
"quick_sort"
]
] | 3 | [] | false | [] | false | pytest | false | [] | true | b6cdc86ba393c2c8f60ef748e885d5df869fb295 | eb2a1ef976299b157dd0d38ddeef21cc8266b36c | |||
v1.0 | instruct | Algorithm | Algorithm_47729_I | ### Scenario:
You are engaged in the development of an e-commerce application that offers detailed product information to its users. One of the features requested by the client is a personalized product recommendation engine based on the user's past purchase history and wish list.
### Task:
Implement a Python functi... | import requests
from collections import Counter
from typing import List, Dict
def fetch_data(url: str) -> List[Dict[str, str]]:
"""
Fetch data from a given URL and return it as a list of dictionaries.
Handle errors and return an empty list in case of any issue.
"""
try:
response = requests.... | import pytest
from unittest.mock import patch
from solution import recommend_products
# Mock data fixtures
purchase_history_example = [
{'product_id': 'prod001', 'product_name': 'Wireless Mouse'},
{'product_id': 'prod002', 'product_name': 'Mechanical Keyboard'},
{'product_id': 'prod003', 'product_name': 'H... | [
{
"docstring": "Fetch data from a given URL and return it as a list of dictionaries.\nHandle errors and return an empty list in case of any issue.",
"function_declaration": "def fetch_data(url):",
"function_name": "fetch_data",
"parameter_list": "(url)"
},
{
"docstring": "Fetches the user's ... | [
0,
0,
1,
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 requests\nfrom collections import Counter, defaultdict\nfrom operator import itemgetter\n\ndef recommend_products(user_id):\n \"\"\"\n Retrieves a u... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "0000047729",
"row_id": 47729,
"seed_ids": "[2255]"
} | 0.507303 | Algorithm_47729 | I | [
"fetch_data",
"recommend_products"
] | 2 | [
[
"recommend_products",
"fetch_data"
]
] | 1 | [] | false | [] | false | pytest | true | [
"requests"
] | false | 14d57a1922a0ca40aae1895553381a5669b91801 | 080a69eb8affdb28165c509048c7307bc1bab96c | |||
v1.0 | instruct | Algorithm | Algorithm_47736_I | ### Question: Validate and Convert Fractional Strings
#### Context
You are developing a utility to process numerical data represented as strings for a financial application. Your task is to validate and convert these strings into their respective fractional and decimal forms. Specifically, you need to differentiate be... | def validate_fraction(fraction: str) -> bool:
"""
Takes in a string 'fraction'.
'fraction' is expected to be in the form 'numerator/denominator'.
Validate that both the numerator and the denominator are valid integers.
The denominator must not be zero.
Return True if the fraction is valid, Fals... | def test_validate_fraction():
assert validate_fraction("5/3") == True
assert validate_fraction("4/0") == False
assert validate_fraction("abc/3") == False
assert validate_fraction("10/5") == True
assert validate_fraction("8/4/2") == False
def test_fraction_to_decimal():
assert fraction_to_decima... | [
{
"docstring": "Takes in a string 'fraction'.\n'fraction' is expected to be in the form 'numerator/denominator'.\nValidate that both the numerator and the denominator are valid integers.\nThe denominator must not be zero.\n\nReturn True if the fraction is valid, False otherwise.",
"function_declaration": "d... | [
1,
1,
1,
0,
1,
0,
0,
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": "def validate_fraction(fraction: str) -> bool:\n \"\"\"\n Validates if the fraction string is in the form 'numerator/denominator'\n and both numerator an... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000047736",
"row_id": 47736,
"seed_ids": "[5269]"
} | 0.710712 | Algorithm_47736 | I | [
"validate_fraction",
"fraction_to_decimal",
"simplify_fraction"
] | 3 | [
[
"fraction_to_decimal",
"validate_fraction"
],
[
"simplify_fraction",
"validate_fraction"
]
] | 2 | [] | false | [] | false | pytest | false | [] | true | fc31ca2e5f771e4b6edf0bcbbf4bae5de37ca736 | d47659f50b85eb81b7407d4896722912be823d04 | |||
v1.0 | instruct | Algorithm | Algorithm_47763_I | ### Scenario
A library management system requires a feature to automatically categorize books based on their ISBN number. An ISBN (International Standard Book Number) is either a 10-digit or 13-digit number that uniquely identifies a book. The 10-digit ISBN has a modulo 11 checksum, while the 13-digit ISBN has a modulo... | def validate_isbn(isbn: str) -> bool:
"""
Validates the ISBN number for correctness.
The function returns True for valid ISBNs and False for invalid ones.
"""
if not isinstance(isbn, str):
raise TypeError(f"Expected string as input, found {type(isbn).__name__}")
clean_isbn = isbn.re... | import pytest
from solution import validate_isbn
def test_validate_isbn_valid_10_digit():
assert validate_isbn("0-306-40615-2") == True
assert validate_isbn("0306406152") == True
def test_validate_isbn_invalid_10_digit():
assert validate_isbn("0-306-40615-9") == False
assert validate_isbn("0306406159"... | [
{
"docstring": "Validates the ISBN number for correctness.\nThe function returns True for valid ISBNs and False for invalid ones.",
"function_declaration": "def validate_isbn(isbn):",
"function_name": "validate_isbn",
"parameter_list": "(isbn)"
},
{
"docstring": "Validates 10-digit ISBN usin... | [
0,
1,
1,
1,
0,
1,
1,
0,
0,
1
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def validate_isbn(isbn: str) -> bool:\n \"\"\"\n Validates an ISBN number, either 10 or 13 digits.\n ISBN can include dashes or spaces; the function wil... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "0000047763",
"row_id": 47763,
"seed_ids": "[1161]"
} | 0.566816 | Algorithm_47763 | I | [
"validate_isbn",
"validate_isbn_10",
"validate_isbn_13"
] | 3 | [
[
"validate_isbn",
"validate_isbn_10"
],
[
"validate_isbn",
"validate_isbn_13"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 577757e99bc541d70fca2f4157c912ded96c81c7 | 9a7c0a02c36eea7ab8df0a99adabfdcbb1dfe7e6 | |||
v1.0 | instruct | Algorithm | Algorithm_47779_I | ### Prime Sum Challenge
In this challenge, you will be required to find two prime numbers that sum up to a given integer. This problem is rooted in the famous Goldbach Conjecture which states that every even integer greater than 2 can be expressed as the sum of two prime numbers. However, for this challenge, we'll con... | import math
def is_prime(n: int) -> bool:
if n <= 1:
return False
if n == 2:
return True
if n % 2 == 0:
return False
for i in range(3, int(math.sqrt(n)) + 1, 2):
if n % i == 0:
return False
return True
def prime_pair_sum(num: int) -> tuple:
"""
T... | from solution import prime_pair_sum
def test_prime_pair_sum_4():
assert prime_pair_sum(4) == (2, 2)
def test_prime_pair_sum_10():
assert prime_pair_sum(10) in [(3, 7), (5, 5), (7, 3)]
def test_prime_pair_sum_7():
assert prime_pair_sum(7) in [(2, 5), (5, 2)]
def test_prime_pair_sum_18():
assert prime... | [
{
"docstring": null,
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "This function receives a single integer and finds two prime numbers that \nsum up to this integer, returning them as a tuple.\n\nArgs:\nnum (int): An integ... | [
1,
1,
0,
0,
0,
1,
0,
0,
0
] | 3 | medium | 0.333 | {
"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: int) -> bool:\n if n <= 1:\n return False\n if n == 2:\n return True\n if n % 2 == 0:\n return False... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "0000047779",
"row_id": 47779,
"seed_ids": "[5166]"
} | 0.703178 | Algorithm_47779 | I | [
"is_prime",
"prime_pair_sum"
] | 2 | [
[
"prime_pair_sum",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 8fb8e2f4dd3384df80032e08e34202d4c36aa0bb | e88e749019b2b611b9dde288b49309c83b20ab39 | |||
v1.0 | instruct | Algorithm | Algorithm_47847_I | ### Coding Assessment Question
**Scenario**:
You are working on a project that aims to compress large text files to save disk space. As part of this project, one of the key components you need is to generate Huffman Codes for characters based on their frequencies in the text file. Huffman Coding is a lossless data com... | import heapq
from collections import defaultdict
from typing import Dict
class HuffmanNode:
def __init__(self, char, freq):
self.char = char
self.freq = freq
self.left = None
self.right = None
# Comparing nodes for the priority queue
def __lt__(self, other):
ret... | from solution import generate_huffman_codes
def test_generate_huffman_codes_example():
frequencies = {'a': 5, 'b': 9, 'c': 12, 'd': 13, 'e': 16, 'f': 45}
output = generate_huffman_codes(frequencies)
expected_output = {'f': '0', 'c': '100', 'd': '101', 'a': '1100', 'b': '1101', 'e': '111'}
for char, cod... | [] | [
1,
0,
0,
1,
1,
1,
0,
1,
0,
1
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import heapq\nfrom typing import Dict, Tuple\n\nclass Node:\n def __init__(self, char=None, freq=None):\n self.char = char\n self.freq = freq\n ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000047847",
"row_id": 47847,
"seed_ids": "[4131]"
} | 0.538588 | Algorithm_47847 | I | [
"build_huffman_tree",
"generate_codes",
"generate_huffman_codes"
] | 3 | [
[
"generate_huffman_codes",
"build_huffman_tree"
],
[
"generate_huffman_codes",
"generate_codes"
]
] | 2 | [] | false | [
"HuffmanNode"
] | true | pytest | true | [] | true | 66dbe9756d8c18f30d260fdd0197d7d8c599684c | 0f5fb419bbf3e51289f7ac16093c079b2b1a535b | |||
v1.0 | instruct | Algorithm | Algorithm_47886_I | ### Question
You are tasked with developing a simple chat application that supports multiple clients communicating in real-time through a central server. The goal is to create a server that can handle multiple chat clients, manage user sessions, broadcast messages to all connected clients, and include error handling fo... | import socket
import threading
import logging
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
clients = []
def handle_client(client_socket, addr):
logging.info(f"New connection from {addr}")
clients.append(client_socket)
try:
while True:
me... | import socket
import threading
import time
from solution import chat_server
# Helper function to simulate a client
def simulate_client(port, messages):
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(('127.0.0.1', port))
for message in messages:
client.send(message.encode... | [
{
"docstring": null,
"function_declaration": "def handle_client(client_socket, addr):",
"function_name": "handle_client",
"parameter_list": "(client_socket, addr)"
},
{
"docstring": null,
"function_declaration": "def broadcast_message(sender_socket, message):",
"function_name": "broa... | [
0,
1,
1,
0,
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": "import socket\nimport threading\nimport logging\n\ndef handle_client(client_socket, client_address, clients, lock, logger):\n \"\"\"\n Handles interactions... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "0000047886",
"row_id": 47886,
"seed_ids": "[4386]"
} | 0.637466 | Algorithm_47886 | I | [
"handle_client",
"broadcast_message",
"chat_server"
] | 3 | [
[
"handle_client",
"broadcast_message"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 0baf5899636b15f1adccaafef23b4c9e02b1d9fa | d9ba94fccd717c7e3aade6ab75407ac4ccebadcc | |||
v1.0 | instruct | Algorithm | Algorithm_47927_I | ### Question: Operations on Fibonacci Numbers and Sums
**Context:**
You are contributing to an algorithm library focused on number sequences. One of the most significant sequences in mathematics and computer science is the Fibonacci sequence. The library will include functions for direct Fibonacci number calculation, ... | def fibonacci(n: int) -> int:
"""
Compute the n-th Fibonacci number using an iterative approach.
The 0th Fibonacci number is 0, the 1st is 1, and so on.
"""
if n == 0:
return 0
elif n == 1:
return 1
a, b = 0, 1
for _ in range(2, n + 1):
a, b = b, a + b
... | from solution import fibonacci, sum_of_fibonacci, sum_of_squares_of_fibonacci
def test_fibonacci():
assert fibonacci(0) == 0
assert fibonacci(1) == 1
assert fibonacci(2) == 1
assert fibonacci(3) == 2
assert fibonacci(4) == 3
assert fibonacci(10) == 55
assert fibonacci(20) == 6765
def test_... | [
{
"docstring": "Compute the n-th Fibonacci number using an iterative approach.\nThe 0th Fibonacci number is 0, the 1st is 1, and so on.",
"function_declaration": "def fibonacci(n):",
"function_name": "fibonacci",
"parameter_list": "(n)"
},
{
"docstring": "Compute the sum of the first n Fibon... | [
0,
1,
0,
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": "def fibonacci(n: int) -> int:\n if n <= 1:\n return n\n a, b = 0, 1\n for _ in range(n - 1):\n a, b = b, a + b\n return b\n\ndef sum_of... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "0000047927",
"row_id": 47927,
"seed_ids": "[3591]"
} | 0.689902 | Algorithm_47927 | I | [
"fibonacci",
"sum_of_fibonacci",
"sum_of_squares_of_fibonacci"
] | 3 | [
[
"sum_of_fibonacci",
"fibonacci"
],
[
"sum_of_squares_of_fibonacci",
"fibonacci"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | ea1c41a4d3bd42fb337d41c33b97906c1a9b8a1c | 1405f5bb047a2eab0fa90c574498a3a0f8e4ae07 | |||
v1.0 | instruct | Algorithm | Algorithm_47931_I | ### Problem Statement:
Implement an advanced data processing pipeline that can efficiently handle large datasets. Your task is to create a framework to process data in a memory-efficient manner. This involves implementing a custom data iterator and integrating it with a basic data processing function.
### Requirements... | import os
from typing import List
class DataIterator:
def __init__(self, file_path: str, chunk_size: int):
self.file_path = file_path
self.chunk_size = chunk_size
def __iter__(self):
with open(self.file_path, 'r') as file:
chunk = []
for line in file:
... | import os
from solution import DataIterator, process_data, process_large_file
def test_data_iterator():
test_file_path = 'test_input.txt'
with open(test_file_path, 'w') as test_file:
for i in range(10):
test_file.write(f"line {i}\n")
iterator = DataIterator(test_file_path, 3)
... | [] | [
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": "from typing import List\n\nclass DataIterator:\n def __init__(self, file_path: str, chunk_size: int):\n self.file_path = file_path\n self.chunk_... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000047931",
"row_id": 47931,
"seed_ids": "[5123]"
} | 0.399967 | Algorithm_47931 | I | [
"process_data",
"process_large_file"
] | 2 | [
[
"process_large_file",
"process_data"
]
] | 1 | [
"process_data"
] | false | [
"DataIterator"
] | true | pytest | true | [] | true | e92313db4f8f49866ccca32cbbd438f6a8f60cff | f4c1ed0cde746a661f0f03a9f7b0f3b74ca371eb | |||
v1.0 | instruct | Algorithm | Algorithm_47941_I | ### Problem Statement
Write a function that generates all possible permutations of a given string and returns them as a list of strings. You will also need to write a function to check if a given string is a palindrome and function to benchmark the performance of generating permutations for increasing string lengths.
... | from itertools import permutations
import time
def generate_permutations(s: str) -> list:
"""
Generate all permutations of a given string.
"""
if not s:
return ['']
return [''.join(p) for p in permutations(s)]
def is_palindrome(s: str) -> bool:
"""
Check if a given string is a pali... | from solution import generate_permutations, is_palindrome, benchmark_permutations
def test_generate_permutations():
assert generate_permutations("abc") == ['abc', 'acb', 'bac', 'bca', 'cab', 'cba']
assert generate_permutations("ab") == ['ab', 'ba']
assert generate_permutations("a") == ['a']
assert gene... | [
{
"docstring": "Generate all permutations of a given string.",
"function_declaration": "def generate_permutations(s):",
"function_name": "generate_permutations",
"parameter_list": "(s)"
},
{
"docstring": "Check if a given string is a palindrome.",
"function_declaration": "def is_palindro... | [
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 itertools\nimport time\n\ndef generate_permutations(s: str) -> list:\n \"\"\"\n Generate all permutations of a given string.\n \"\"\"\n if s =... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "0000047941",
"row_id": 47941,
"seed_ids": "[3159]"
} | 0.7076 | Algorithm_47941 | I | [
"generate_permutations",
"is_palindrome",
"benchmark_permutations"
] | 3 | [
[
"benchmark_permutations",
"generate_permutations"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 05aff9e5141a99501583d68e5ba74f89c1f39ccf | c2f2edc5b98fd4eac38d234048fc766ed1f7c269 | |||
v1.0 | instruct | Algorithm | Algorithm_48011_I | ### Coding Assessment Question
You have been hired by a logistics company to improve their package tracking system. The company previously used a simple, linear way to track the packages, but it has become inefficient due to the increasing data size.
Your tasks are:
1. **Implement a function to fetch package details... | import requests
from cachetools import LRUCache
import logging
from typing import List
import time
# Initialize logger
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger()
# Initialize LRU Cache
cache = None
def fetch_package_data(api_url: str, timeout: int):
"""
Function to fetch package det... | from solution import fetch_package_data, binary_search, get_package_details
import pytest
from unittest import mock
import requests
# Mock API Response
mock_response = [
{"package_id": "001", "origin": "A", "destination": "B", "status": "In Transit", "delivery_time": "2023-10-20", "last_update": "2023-10-10"},
... | [
{
"docstring": "Function to fetch package details from the optimized API endpoint.\n\n:param api_url: the API URL to fetch data from\n:param timeout: the timeout for the API request in seconds\n:return: List of package data in JSON format",
"function_declaration": "def fetch_package_data(api_url, timeout):"... | [
1,
1,
0,
1,
1,
0,
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": "import requests\nimport time\nfrom functools import lru_cache\n\nclass PackageNotFoundError(Exception):\n pass\n\nclass APIError(Exception):\n pass\n\nclas... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "0000048011",
"row_id": 48011,
"seed_ids": "[2421]"
} | 0.460653 | Algorithm_48011 | I | [
"fetch_package_data",
"binary_search",
"get_package_details"
] | 3 | [
[
"get_package_details",
"binary_search"
],
[
"get_package_details",
"fetch_package_data"
]
] | 2 | [] | false | [] | false | pytest | true | [
"cachetools",
"requests"
] | false | fd4ab1693e8369935d6a8aa74b310d4abe66a618 | 5e7ea7dfe23575e335397993703327981769b480 | |||
v1.0 | instruct | Algorithm | Algorithm_48087_I | ### Question
You are developing a file management application that needs to organize files within a directory based on their types. Your task is to create a Python script to scan a specified directory and move files into subdirectories categorized by their file extensions.
### Function Specification
**Task**:
* You n... | import os
import shutil
def create_subdirectories(base_path: str, extensions: list) -> None:
for ext in extensions:
dir_path = os.path.join(base_path, ext)
if not os.path.exists(dir_path):
os.makedirs(dir_path)
def organize_files(directory_path: str) -> None:
# Scan the directory a... | import os
import shutil
import pytest
from solution import create_subdirectories, organize_files
def setup_module(module):
"""
Setup a temporary testing directory structure.
"""
os.makedirs('test_dir', exist_ok=True)
open('test_dir/file1.txt', 'w').close()
open('test_dir/file2.jpg', 'w').close... | [
{
"docstring": null,
"function_declaration": "def create_subdirectories(base_path, extensions):",
"function_name": "create_subdirectories",
"parameter_list": "(base_path, extensions)"
},
{
"docstring": null,
"function_declaration": "def organize_files(directory_path):",
"function_nam... | [
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 os\nimport shutil\n\ndef create_subdirectories(base_path: str, extensions: list) -> None:\n \"\"\"\n Creates subdirectories for each file extension ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000048087",
"row_id": 48087,
"seed_ids": "[4126]"
} | 0.769074 | Algorithm_48087 | I | [
"create_subdirectories",
"organize_files"
] | 2 | [
[
"organize_files",
"create_subdirectories"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 9df2d717e95fb4ce1c6a05d9402e280ba0352a45 | 7f24cd308ff2603d154dc1e980563a666870491d | |||
v1.0 | instruct | Algorithm | Algorithm_48146_I | ### Coding Assessment Question
#### Problem Statement:
Implement a Python function `find_max_subarray(arr: List[int]) -> Tuple[int, int, int]` that finds the subarray with the maximum sum in a given list of integers using the divide-and-conquer approach.
#### Requirements:
* **Input Format**:
* `arr` (List[int]): ... | from typing import List, Tuple
def find_max_subarray(arr: List[int]) -> Tuple[int, int, int]:
if not arr:
return 0, 0, 0
return _find_max_subarray(arr, 0, len(arr) - 1)
def _find_max_subarray(arr: List[int], low: int, high: int) -> Tuple[int, int, int]:
if low == high:
return low, high, ar... | def test_find_max_subarray():
assert find_max_subarray([-2, 1, -3, 4, -1, 2, 1, -5, 4]) == (3, 6, 6)
assert find_max_subarray([1, 2, 3, 4, 5]) == (0, 4, 15)
assert find_max_subarray([-1, -2, -3, -4, -5]) == (0, 0, -1)
assert find_max_subarray([]) == (0, 0, 0)
assert find_max_subarray([4, -1, 2, 1]) ... | [
{
"docstring": null,
"function_declaration": "def find_max_subarray(arr):",
"function_name": "find_max_subarray",
"parameter_list": "(arr)"
},
{
"docstring": null,
"function_declaration": "def _find_max_subarray(arr, low, high):",
"function_name": "_find_max_subarray",
"parameter... | [
1,
1,
1,
0,
0,
1,
1,
1,
0
] | 6 | easy | 0.667 | {
"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 find_max_subarray(arr: List[int]) -> Tuple[int, int, int]:\n if not arr:\n return 0, 0, 0\n return _find_max_s... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000048146",
"row_id": 48146,
"seed_ids": "[4257]"
} | 0.744531 | Algorithm_48146 | I | [
"find_max_subarray",
"_find_max_subarray",
"_max_crossing_subarray"
] | 3 | [
[
"_find_max_subarray",
"_max_crossing_subarray"
],
[
"find_max_subarray",
"_find_max_subarray"
]
] | 2 | [] | false | [] | false | pytest | false | [] | true | b6bc5b59565f6b398044f477b68713c0f8225006 | 9431172518de02a129aa4b57cbcd90a879a88cf3 | |||
v1.0 | instruct | Algorithm | Algorithm_48168_I | ### Problem Statement:
#### Context:
In computer science, a common problem is checking whether a sequence of numbers can be arranged to form an arithmetic series. An arithmetic series is one in which the difference between consecutive terms is constant. Additionally, once identified, calculating the sum of such a seri... | def is_arithmetic_series(series):
"""
Check if the input series is arithmetic.
An arithmetic series is defined as a series where the difference between consecutive terms is constant.
"""
if len(series) <= 1:
return True # A series with 0 or 1 elements is trivially arithmetic
common_dif... | def test_is_arithmetic_series():
assert is_arithmetic_series([2, 4, 6, 8]) == True
assert is_arithmetic_series([5, 5, 5, 5]) == True
assert is_arithmetic_series([1, 2, 4, 8]) == False
assert is_arithmetic_series([10]) == True
assert is_arithmetic_series([]) == True
def test_sum_of_arithmetic_series... | [
{
"docstring": "Check if the input series is arithmetic.\nAn arithmetic series is defined as a series where the difference between consecutive terms is constant.",
"function_declaration": "def is_arithmetic_series(series):",
"function_name": "is_arithmetic_series",
"parameter_list": "(series)"
},
... | [
1,
0,
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_arithmetic_series(series):\n \"\"\"\n Returns True if the series forms an arithmetic series, else False.\n \"\"\"\n if len(series) < 2:\n ... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000048168",
"row_id": 48168,
"seed_ids": "[4088]"
} | 0.665507 | Algorithm_48168 | I | [
"is_arithmetic_series",
"sum_of_arithmetic_series"
] | 2 | [
[
"sum_of_arithmetic_series",
"is_arithmetic_series"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 8edb694bece7b45c53210fea467f1a72987ea618 | 36d7ce81e87e16a59974fae6b3a1b3a31cdddb37 | |||
v1.0 | instruct | Algorithm | Algorithm_48185_I | ### Sentence Substring Matching
Given a main sentence and a list of words, write functions to identify which words from the list appear as exact substrings in the main sentence, case-insensitively. Your task is to implement the following functions:
1. **`find_substrings(main_sentence: str, words: list[str]) -> list[s... | def find_substrings(main_sentence: str, words: list[str]) -> list[str]:
"""
Identify which words from the list appear as exact substrings in the main sentence, case-insensitively.
"""
main_sentence_lower = main_sentence.lower()
return [word for word in words if word.lower() in main_sentence_lower]
... | from solution import find_substrings, substring_occurrence_count, substring_presence_score
def test_find_substrings():
main_sentence = "The quick brown fox jumps over the lazy dog"
words = ["quick", "dog", "cat", "Fox"]
assert find_substrings(main_sentence, words) == ["quick", "dog", "Fox"]
def test_find_... | [
{
"docstring": "Identify which words from the list appear as exact substrings in the main sentence, case-insensitively.",
"function_declaration": "def find_substrings(main_sentence, words):",
"function_name": "find_substrings",
"parameter_list": "(main_sentence, words)"
},
{
"docstring": "Co... | [
1,
1,
1,
1,
0,
1,
1,
1,
0,
0
] | 7 | easy | 0.7 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def find_substrings(main_sentence: str, words: list[str]) -> list[str]:\n \"\"\"\n Finds and returns the words from the list that appear as exact substring... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "0000048185",
"row_id": 48185,
"seed_ids": "[1555]"
} | 0.704044 | Algorithm_48185 | I | [
"find_substrings",
"substring_occurrence_count",
"substring_presence_score"
] | 3 | [
[
"substring_presence_score",
"find_substrings"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 5cdcf16d95eba8bdd80bf10419a2faeedc936c43 | 0120044e04839888bfe00bc8aa17ca358802a25f | |||
v1.0 | instruct | Algorithm | Algorithm_48216_I | Python Memory Management with Custom Reference Counting
Given 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 drops to zero.
Implement the `i... | 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": "",
"prompt_id": "0000048216",
"row_id": 48216,
"seed_ids": "[4363]"
} | 0.416893 | Algorithm_48216 | I | [
"inc_ref",
"dec_ref",
"collect_garbage"
] | 3 | [
[
"dec_ref",
"collect_garbage"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 7515eb1ee7c75ffda42b08c2ab84f4d33ae8f30b | 2d9edbaa7f31cf23b0aed357b1939a496d0cb058 | |||
v1.0 | instruct | Algorithm | Algorithm_48219_I | ## Problem Statement
Create a function that implements the A* (A-star) algorithm for finding the shortest path in a grid. The grid is represented as a 2D list of integers, where `0` denotes a walkable cell and `1` denotes an obstacle. The function should find the shortest path from the top-left corner to the bottom-rig... | from heapq import heappop, heappush
def heuristic(a, b):
return abs(a[0] - b[0]) + abs(a[1] - b[1])
def a_star_search(grid):
rows, cols = len(grid), len(grid[0])
start = (0, 0)
end = (rows - 1, cols - 1)
open_set = []
heappush(open_set, (0 + heuristic(start, end), 0, start))
came_from... | def test_a_star_empty_grid():
grid = [[0, 0], [0, 0]]
assert a_star_search(grid) == [(0, 0), (0, 1), (1, 1)]
def test_a_star_no_path():
grid = [[0, 1], [1, 0]]
assert a_star_search(grid) == None
def test_a_star_larger_grid():
grid = [
[0, 0, 0, 0],
[1, 1, 0, 1],
[0, 0, 0, 0... | [
{
"docstring": null,
"function_declaration": "def heuristic(a, b):",
"function_name": "heuristic",
"parameter_list": "(a, b)"
},
{
"docstring": null,
"function_declaration": "def a_star_search(grid):",
"function_name": "a_star_search",
"parameter_list": "(grid)"
}
] | [
0,
0,
1,
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 heapq\n\ndef a_star_search(grid):\n def heuristic(a, b):\n return abs(a[0] - b[0]) + abs(a[1] - b[1])\n\n def get_neighbors(pos):\n di... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "0000048219",
"row_id": 48219,
"seed_ids": "[3447]"
} | 0.657246 | Algorithm_48219 | I | [
"heuristic",
"a_star_search"
] | 2 | [
[
"a_star_search",
"heuristic"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 95d5323a08fc697f6776333a6e7425b991f5b958 | 9e800050556cfbaae3725f22dbc5895cec4fe6f8 | |||
v1.0 | instruct | Algorithm | Algorithm_48261_I | ### Genetic Algorithm for Knapsack Problem
Implement 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.
### Function Descriptions
1.... | 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": "",
"prompt_id": "0000048261",
"row_id": 48261,
"seed_ids": "[770]"
} | 0.530308 | Algorithm_48261 | I | [
"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 | fabda60a923cf263ed2f3e8fe4bdb823c8588e3f | f64cfc669ea1ca0fb383209203414b85c3bad50a | |||
v1.0 | instruct | Algorithm | Algorithm_48267_I | ### AVL Tree Insertion and Rotation
#### Background:
AVL trees are a type of self-balancing binary search tree where the height difference between the left and right subtrees of any node is at most one. To maintain this property during insertions, AVL trees perform rotations to rebalance the tree.
#### Task:
You need... | class AVLTreeNode:
def __init__(self, value: int):
self.value = value
self.left = None
self.right = None
self.height = 1
def get_height(node: AVLTreeNode) -> int:
return node.height if node else 0
def get_balance(node: AVLTreeNode) -> int:
return get_height(node.left) - get... | from solution import AVLTreeNode, insert, rotate_left, rotate_right
def in_order_traversal(root, result=None):
if result is None:
result = []
if root:
in_order_traversal(root.left, result)
result.append(root.value)
in_order_traversal(root.right, result)
return result
def te... | [] | [
1,
1,
0,
0,
0,
0,
0,
0,
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": "class AVLTreeNode:\n def __init__(self, value: int):\n self.value = value\n self.left = None\n self.right = None\n self.height = 1... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "0000048267",
"row_id": 48267,
"seed_ids": "[336]"
} | 0.528659 | Algorithm_48267 | I | [
"get_height",
"get_balance",
"update_height",
"rotate_left",
"rotate_right",
"insert"
] | 6 | [
[
"get_balance",
"get_height"
],
[
"insert",
"get_balance"
],
[
"insert",
"rotate_left"
],
[
"insert",
"rotate_right"
],
[
"insert",
"update_height"
],
[
"rotate_left",
"update_height"
],
[
"rotate_right",
"update_height"
],
[
"... | 8 | [] | false | [
"AVLTreeNode"
] | true | pytest | true | [] | true | cfa0664711f1e9fefa656be7365b359332ce55b8 | b0e883468ea6c2ae10cc07cdb6e609eff6c79754 | |||
v1.0 | instruct | Algorithm | Algorithm_48289_I | ### Scenario
You have been given a list of integers and a series of commands to perform either updates or prefix sum queries on the list. Your task is to implement a data structure that efficiently handles these operations.
### Problem Statement
Your task is to implement two functions:
1. `update(fenwick_tree: list[... | def update(fenwick_tree: list[int], index: int, value: int) -> None:
index += 1 # Fenwick Tree uses 1-based indexing
while index < len(fenwick_tree):
fenwick_tree[index] += value
index += index & -index
def prefix_sum(fenwick_tree: list[int], index: int) -> int:
sum_ = 0
index += 1 # ... | from solution import update, prefix_sum, build_fenwick_tree
def test_initial_prefix_sum():
number_list = [3, 2, -1, 6, 5, 4, -3, 3, 7, 2, 3]
fenwick_tree = build_fenwick_tree(number_list)
assert prefix_sum(fenwick_tree, 4) == 15
def test_update_and_prefix_sum():
number_list = [3, 2, -1, 6, 5, 4, -3, 3... | [
{
"docstring": null,
"function_declaration": "def update(fenwick_tree, index, value):",
"function_name": "update",
"parameter_list": "(fenwick_tree, index, value)"
},
{
"docstring": null,
"function_declaration": "def prefix_sum(fenwick_tree, index):",
"function_name": "prefix_sum",
... | [
1,
1,
1,
1,
0,
1,
0,
0,
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": "def update(fenwick_tree: list[int], index: int, value: int) -> None:\n \"\"\"\n Updates the element at the specified index to the new value using a Fenwick... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "0000048289",
"row_id": 48289,
"seed_ids": "[2244]"
} | 0.504259 | Algorithm_48289 | I | [
"update",
"prefix_sum",
"build_fenwick_tree"
] | 3 | [
[
"build_fenwick_tree",
"update"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 067ab3d7874d6c33d91bc7c9520e66d5c557dd1b | 3b6b64c4f3fbbbe46339bd7486e6ed580499cd6a | |||
v1.0 | instruct | Data_Structure | Data_Structure_10_I | ### Question Title: Advanced Run-Length Encoding and Decoding with Validations
#### Description:
Implement an enhanced version of the Run-Length Encoding (RLE) and Decoding functions. In addition to encoding and decoding, your implementation needs to handle edge cases gracefully and include a validation mechanism to v... | def enhanced_encode_rle(input: str) -> str:
if not input:
return ""
encoded_str = []
i = 0
while i < len(input):
count = 1
while i + 1 < len(input) and input[i] == input[i + 1]:
i += 1
count += 1
encoded_str.append(f"{count}{input[i]}")
... | from solution import enhanced_encode_rle, enhanced_decode_rle, validate_encoded_rle
def test_enhanced_encode_rle():
assert enhanced_encode_rle("aaabbbcccaaa") == "3a3b3c3a"
assert enhanced_encode_rle("hhhhhaaann") == "5h3a2n"
assert enhanced_encode_rle("") == ""
assert enhanced_encode_rle("a") == "1a"
... | [
{
"docstring": null,
"function_declaration": "def enhanced_encode_rle(input):",
"function_name": "enhanced_encode_rle",
"parameter_list": "(input)"
},
{
"docstring": null,
"function_declaration": "def enhanced_decode_rle(input):",
"function_name": "enhanced_decode_rle",
"paramete... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def enhanced_encode_rle(input: str) -> str:\n if not input:\n return \"\"\n \n encoded_str = []\n i = 0\n\n while i < len(input):\n ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00000010",
"row_id": 10,
"seed_ids": "[334]"
} | 0.635774 | Data_Structure_10 | I | [
"enhanced_encode_rle",
"enhanced_decode_rle",
"validate_encoded_rle"
] | 3 | [
[
"enhanced_decode_rle",
"validate_encoded_rle"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 3fa95d723d36f9dcac90dc8657aec129df43bb40 | 1d437b8fc38fcabd662a928772286929f7e5018a | |||
v1.0 | instruct | Data_Structure | Data_Structure_14_I | **Problem Statement:**
You are given a list of integers. Your task is to construct a Binary Search Tree (BST) from the integers and implement a function to perform an in-order traversal of the BST. The traversal should be printed as a list of integers in ascending order.
**Function Signature:**
```python
def create_b... | 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)
elif val > ro... | from solution import create_bst, inorder_traversal
def test_example_1():
nums = [8, 3, 10, 1, 6, 14, 4, 7, 13]
root = create_bst(nums)
assert inorder_traversal(root) == [1, 3, 4, 6, 7, 8, 10, 13, 14]
def test_example_2():
nums = [20, 5, 25, 3, 8, 30]
root = create_bst(nums)
assert inorder_trav... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List, Optional\n\nclass TreeNode:\n def __init__(self, val: int):\n self.val = val\n self.left = None\n self.right ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00000014",
"row_id": 14,
"seed_ids": "[287]"
} | 0.484862 | Data_Structure_14 | I | [
"insert_into_bst",
"create_bst",
"inorder_traversal"
] | 3 | [
[
"create_bst",
"insert_into_bst"
]
] | 1 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | 50df004e2b6c484b2ae78e78adf97e392c952cb7 | baf1b603363f88e3b5e79cc62295eac67b7e0544 | |||
v1.0 | instruct | Data_Structure | Data_Structure_26_I | You are given a Markov Chain defined as described below. Implement two functions:
1. `generate_sequence(chain, start_state, iterations)`:
- **Input**:
- `chain`: A dictionary representing the Markov chain where keys are states and values are dictionaries of next state probabilities.
- `start_state`: The s... | import random
def generate_sequence(chain, start_state, iterations):
"""
Generates a sequence of states in a Markov Chain.
:param chain: Dictionary, the Markov chain.
:param start_state: The starting state.
:param iterations: Number of transitions to generate.
:return: List of states visit... | from solution import generate_sequence, is_valid_chain
def test_generate_sequence():
chain = {
'A': {'A': 0.6, 'B': 0.4},
'B': {'A': 0.7, 'B': 0.3}
}
sequence = generate_sequence(chain, 'A', 5)
assert len(sequence) == 6 # The initial state + 5 iterations
assert all(state in chain f... | [
{
"docstring": "Generates a sequence of states in a Markov Chain.\n\n:param chain: Dictionary, the Markov chain.\n:param start_state: The starting state.\n:param iterations: Number of transitions to generate.\n:return: List of states visited in sequence.",
"function_declaration": "def generate_sequence(chai... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef generate_sequence(chain, start_state, iterations):\n \"\"\"\n Generates a sequence of states in a Markov chain.\n \n Paramete... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00000026",
"row_id": 26,
"seed_ids": "[232]"
} | 0.521447 | Data_Structure_26 | I | [
"generate_sequence",
"_get_next_state",
"is_valid_chain"
] | 3 | [
[
"generate_sequence",
"_get_next_state"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 9b8a28d43d3e9957307c887f41f4b917e23c2c94 | bb755d449164e2f115fafea982b6d5fcd3617d48 | |||
v1.0 | instruct | Data_Structure | Data_Structure_56_I | Implement Bucket Sort with Enhanced Insertion Sort
Given a list of integers, implement the bucket sort algorithm. Your implementation should handle edge cases effectively and optimize for performance by incorporating any improvements you consider necessary.
### Input
- A list of integers `arr` where `1 <= len(arr) <=... | def insertion_sort(arr):
"""
A simple insertion sort. Effective for small arrays.
"""
for i in range(1, len(arr)):
key = arr[i]
j = i - 1
while j >= 0 and key < arr[j]:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
return arr
def bucket_sort(arr... | from solution import bucket_sort
def test_bucket_sort_normal_case():
arr = [19, 3, 15, 4, 6, 1, 13, 122, 47, 91]
expected = [1, 3, 4, 6, 13, 15, 19, 47, 91, 122]
assert bucket_sort(arr) == expected
def test_bucket_sort_single_element():
arr = [5]
expected = [5]
assert bucket_sort(arr) == expec... | [
{
"docstring": "A simple insertion sort. Effective for small arrays.",
"function_declaration": "def insertion_sort(arr):",
"function_name": "insertion_sort",
"parameter_list": "(arr)"
},
{
"docstring": "Bucket sort function which distributes elements into buckets,\nsorts each bucket with a p... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def insertion_sort(arr):\n \"\"\"\n Helper function to perform insertion sort on an array.\n \"\"\"\n for i in range(1, len(arr)):\n key = ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00000056",
"row_id": 56,
"seed_ids": "[26]"
} | 0.578955 | Data_Structure_56 | I | [
"insertion_sort",
"bucket_sort"
] | 2 | [
[
"bucket_sort",
"insertion_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 05b4e6a3bdb0bbd07280fa232bde9c835641f151 | 2d81aabb161e915723e46f751fcc9902468dba2e | |||
v1.0 | instruct | Data_Structure | Data_Structure_58_I | ### Intersection of Two Linked Lists
You are tasked with finding the intersection node of two singly linked lists. The intersection is defined based on reference, not value. Create a function `find_intersection` which takes the heads of two such linked lists and returns the intersecting node. If there's no intersectio... | class Node:
def __init__(self, val):
self.val = val
self.next = None
def get_length(head):
length = 0
current = head
while current:
length += 1
current = current.next
return length
def find_intersection(head1, head2):
# Get lengths of both lists
len1 = get_l... | from solution import Node, find_intersection
def test_intersection_node():
# Creating linked lists
# List 1: 1 -> 3 -> 5 -> 7 -> 9 -> 11
n1 = Node(1)
n3 = Node(3)
n5 = Node(5)
n7 = Node(7)
n9 = Node(9)
n11 = Node(11)
n1.next = n3
n3.next = n5
n5.next = n7
n7.next = n9
... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class Node:\n def __init__(self, val):\n self.val = val\n self.next = None\n\ndef get_length(head: Node) -> int:\n length = 0\n while h... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00000058",
"row_id": 58,
"seed_ids": "[245]"
} | 0.570252 | Data_Structure_58 | I | [
"get_length",
"find_intersection"
] | 2 | [
[
"find_intersection",
"get_length"
]
] | 1 | [] | false | [
"Node"
] | true | pytest | true | [] | true | 112502ff10bed5ac4ef748a0719c33925fb7358b | 6cd247a0c371f613cd093f096964a223736e9523 | |||
v1.0 | instruct | Data_Structure | Data_Structure_66_I | ### Question: Implement and Analyze Diffie-Hellman Key Exchange with Optimized Primality Testing
#### Description
Alice and Bob want to securely share data over an insecure channel using the Diffie-Hellman key exchange algorithm. Your task is to implement this key exchange mechanism, including optimized routines for p... | import random
def is_prime_miller_rabin(n, k=5):
"""Determine if n is a prime using Miller-Rabin Primality Test."""
if n in (2, 3):
return True
if n <= 1 or n % 2 == 0:
return False
# Write n-1 as 2^r * d
r, d = 0, n - 1
while d % 2 == 0:
r += 1
d //= 2
def... | from solution import (
is_prime_miller_rabin,
euler_totient_optimized,
find_order_optimized,
find_primitive_root_optimized,
diffie_hellman_key_exchange_optimized
)
def test_is_prime_miller_rabin():
assert is_prime_miller_rabin(23) == True
assert is_prime_miller_rabin(24) == False
assert... | [
{
"docstring": "Determine if n is a prime using Miller-Rabin Primality Test.",
"function_declaration": "def is_prime_miller_rabin(n, k=5):",
"function_name": "is_prime_miller_rabin",
"parameter_list": "(n, k=5)"
},
{
"docstring": "Calculate Euler's Totient function using optimized approach."... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef is_prime_miller_rabin(n, k=5):\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == 0:\n re... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00000066",
"row_id": 66,
"seed_ids": "[146]"
} | 0.462999 | Data_Structure_66 | I | [
"is_prime_miller_rabin",
"euler_totient_optimized",
"find_order_optimized",
"gcd",
"find_primitive_root_optimized",
"prime_factors",
"diffie_hellman_key_exchange_optimized"
] | 7 | [
[
"diffie_hellman_key_exchange_optimized",
"find_primitive_root_optimized"
],
[
"diffie_hellman_key_exchange_optimized",
"is_prime_miller_rabin"
],
[
"find_order_optimized",
"gcd"
],
[
"find_primitive_root_optimized",
"euler_totient_optimized"
],
[
"find_primitive... | 6 | [] | false | [] | false | pytest | true | [] | true | 3b798c68e0953b3b31e8c7b4a1890f9ac7efc4f6 | b8b2315774232c6da0f79d27d601997c082c3017 | |||
v1.0 | instruct | Data_Structure | Data_Structure_117_I | ### Markov Chain Simulator
**Scenario**:
You have been hired to build a simulation tool for weather prediction based on a Markov Chain model. The states in this model represent different weather conditions (e.g., Sunny, Rainy, Cloudy), with predefined transition probabilities for moving from one weather condition to a... | import random
def __choose_state(state_map):
choice = random.random()
probability_reached = 0
for state, probability in state_map.items():
probability_reached += probability
if probability_reached > choice:
return state
return None
def next_state(chain, current_state):
... | from solution import weather_simulation
def test_weather_simulation_single_step():
chain = {
'Sunny': {'Sunny': 0.7, 'Rainy': 0.2, 'Cloudy': 0.1},
'Rainy': {'Sunny': 0.3, 'Rainy': 0.4, 'Cloudy': 0.3},
'Cloudy': {'Sunny': 0.4, 'Rainy': 0.4, 'Cloudy': 0.2}
}
start_state = 'Sunny'
... | [
{
"docstring": null,
"function_declaration": "def __choose_state(state_map):",
"function_name": "__choose_state",
"parameter_list": "(state_map)"
},
{
"docstring": null,
"function_declaration": "def next_state(chain, current_state):",
"function_name": "next_state",
"parameter_lis... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef __choose_state(state_map):\n choice = random.random()\n probability_reached = 0\n for state, probability in state_map.items():\n... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00000117",
"row_id": 117,
"seed_ids": "[232]"
} | 0.49146 | Data_Structure_117 | I | [
"__choose_state",
"next_state",
"weather_simulation"
] | 3 | [
[
"next_state",
"__choose_state"
],
[
"weather_simulation",
"next_state"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 53ff6f504cbb983700764941e16fa8d99b88f54f | 015c725bb71c5614a6919085f5771b59a033b38f | |||
v1.0 | instruct | Data_Structure | Data_Structure_142_I | ### Bogo Sort Implementation and Analysis
#### Context:
Bogo Sort is often considered a joke among computer scientists due to its exceptionally poor performance characteristics and is rarely used in practice. However, it serves as an excellent didactic tool to highlight the importance of algorithmic efficiency and fe... | import random
def is_sorted(arr):
"""
Helper function to check if the array is sorted.
"""
return all(arr[i] <= arr[i + 1] for i in range(len(arr) - 1))
def bogo_sort_improved(arr, max_iterations=100000):
"""
Sorts the array using Bogo Sort with an iteration limit.
:param arr: List of inte... | from solution import bogo_sort_improved
def test_empty_list():
assert bogo_sort_improved([]) == ([], 0)
def test_single_element():
assert bogo_sort_improved([1]) == ([1], 0)
def test_sorted_list():
assert bogo_sort_improved([1, 2, 3], max_iterations=10) == ([1, 2, 3], 0)
def test_reverse_sorted_list... | [
{
"docstring": "Helper function to check if the array is sorted.",
"function_declaration": "def is_sorted(arr):",
"function_name": "is_sorted",
"parameter_list": "(arr)"
},
{
"docstring": "Sorts the array using Bogo Sort with an iteration limit.\n:param arr: List of integers to be sorted\n:p... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef is_sorted(arr):\n \"\"\"\n Helper function to check if the array is sorted.\n \"\"\"\n return all(arr[i] <= arr[i + 1] for i ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00000142",
"row_id": 142,
"seed_ids": "[16]"
} | 0.53632 | Data_Structure_142 | I | [
"is_sorted",
"bogo_sort_improved"
] | 2 | [
[
"bogo_sort_improved",
"is_sorted"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 322217ed6d083ee06200e3de5a1c095867293777 | a3f36c31afe6a127f8b3e40d75cec7734044f342 | |||
v1.0 | instruct | Data_Structure | Data_Structure_168_I | ### Question
You are tasked to implement a function that sorts a list of non-negative integers using the Radix Sort algorithm. Your implementation should maintain stability and efficiently handle lists with varying integer sizes.
#### Description
Write a function `radix_sort(arr)` that sorts a given list of non-negati... | 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
while i >... | from solution import radix_sort
def test_radix_sort_basic():
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([5]) == [5]
def test_radix_sort_sorted_array():
assert radix_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4,... | [
{
"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,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def counting_sort(arr, exp):\n \"\"\"\n A helper function to perform a counting sort based on the digit represented by exp.\n \"\"\"\n n = len(arr... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00000168",
"row_id": 168,
"seed_ids": "[15]"
} | 0.607465 | Data_Structure_168 | I | [
"counting_sort",
"radix_sort"
] | 2 | [
[
"radix_sort",
"counting_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | eb131c2ece344f7c8ab9502d0248eb79e075cc79 | bc07b0c22acb48d3f8bad4bc500f1678ae5a3fa3 | |||
v1.0 | instruct | Data_Structure | Data_Structure_199_I | ### Fenwick Tree / Binary Indexed Tree Implementation
#### Problem Statement
You are required to implement a Fenwick Tree (Binary Indexed Tree) for an integer array to efficiently perform the following operations:
1. Compute prefix sum up to a given index.
2. Update an element in the array.
#### Function Signatures
... | from typing import List
def construct(freq: List[int]) -> List[int]:
"""
Initializes a Fenwick Tree (Binary Indexed Tree) based on input frequency array.
Parameters:
freq (List[int]): The input list of integers representing the frequency array.
Returns:
List[int]: The BIT (Fenwick Tre... | from solution import construct, get_sum, update_bit
def test_construct_and_get_sum():
freq = [1, 2, 3, 4, 5]
bit_tree = construct(freq)
assert get_sum(bit_tree, 0) == 1 # sum of first element
assert get_sum(bit_tree, 1) == 3 # sum of first two elements
assert get_sum(bit_tree, 2) == 6 # sum of f... | [
{
"docstring": "Initializes a Fenwick Tree (Binary Indexed Tree) based on input frequency array.\n\nParameters:\nfreq (List[int]): The input list of integers representing the frequency array.\n\nReturns:\nList[int]: The BIT (Fenwick Tree) represented as a list.",
"function_declaration": "def construct(freq)... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef construct(freq: List[int]) -> List[int]:\n \"\"\"\n Constructs a Fenwick Tree (Binary Indexed Tree) from the given freque... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00000199",
"row_id": 199,
"seed_ids": "[305]"
} | 0.540569 | Data_Structure_199 | I | [
"construct",
"get_sum",
"update_bit"
] | 3 | [
[
"construct",
"update_bit"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | fc7810c8fff451b924101e4ad0e057c3eaf71a7c | d31f0488fe878ebc1ea15de9cc62004a40ce1060 | |||
v1.0 | instruct | Data_Structure | Data_Structure_313_I | ### Scenario
In this question, you will implement a version of Bogo Sort, notoriously known for its inefficiency. While this algorithm is not suitable for actual sorting tasks, it serves as an excellent exercise to demonstrate understanding of random permutations and algorithm design.
### Problem Description
Write a f... | import random
from typing import List
def is_sorted(arr: List[int]) -> bool:
"""
Helper function to check if the array is sorted in ascending order.
"""
for i in range(len(arr) - 1):
if arr[i] > arr[i + 1]:
return False
return True
def custom_bogo_sort(arr: List[int]) -> None:
... | from solution import custom_bogo_sort
def test_empty_array():
arr = []
custom_bogo_sort(arr)
assert arr == []
def test_single_element_array():
arr = [1]
custom_bogo_sort(arr)
assert arr == [1]
def test_sorted_array():
arr = [1, 2, 3]
custom_bogo_sort(arr)
assert arr == [1, 2, 3]
... | [
{
"docstring": "Helper function to check if the array is sorted in ascending order.",
"function_declaration": "def is_sorted(arr):",
"function_name": "is_sorted",
"parameter_list": "(arr)"
},
{
"docstring": "Sorts the array `arr` in-place using the Bogo Sort algorithm.",
"function_declar... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nfrom typing import List\n\ndef is_sorted(arr: List[int]) -> bool:\n \"\"\"\n Helper function to check if the array is sorted in ascending... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00000313",
"row_id": 313,
"seed_ids": "[16]"
} | 0.594387 | Data_Structure_313 | I | [
"is_sorted",
"custom_bogo_sort"
] | 2 | [
[
"custom_bogo_sort",
"is_sorted"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 3202e77a7a6e4c984b4fa2aefb3e7b688ead0902 | fe3cf6459a9051ef2498b23b962181d37ddfca25 | |||
v1.0 | instruct | Data_Structure | Data_Structure_346_I | ### Coding Challenge: Enhanced GCD and LCM with Edge Case Handling
#### Objective
Write a Python function to calculate both the GCD and the LCM of two non-negative integers with enhanced edge case handling and optimized performance.
#### Problem Statement
Given two non-negative integers `a` and `b`, implement two fun... | import math
def enhanced_gcd(a: int, b: int) -> int:
"""
Calculate the greatest common divisor (GCD) of two non-negative integers a and b.
"""
if a == 0:
return b
if b == 0:
return a
return math.gcd(a, b)
def enhanced_lcm(a: int, b: int) -> int:
"""
Calculate the least ... | from solution import enhanced_gcd, enhanced_lcm
def test_gcd_with_zeros():
assert enhanced_gcd(0, 0) == 0
assert enhanced_gcd(10, 0) == 10
assert enhanced_gcd(0, 10) == 10
def test_lcm_with_zeros():
assert enhanced_lcm(0, 0) == 0
assert enhanced_lcm(10, 0) == 0
assert enhanced_lcm(0, 10) == 0
... | [
{
"docstring": "Calculate the greatest common divisor (GCD) of two non-negative integers a and b.",
"function_declaration": "def enhanced_gcd(a, b):",
"function_name": "enhanced_gcd",
"parameter_list": "(a, b)"
},
{
"docstring": "Calculate the least common multiple (LCM) of two non-negative ... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def enhanced_gcd(a: int, b: int) -> int:\n \"\"\"\n Calculate the greatest common divisor (GCD) of two non-negative integers.\n Uses the Euclidean al... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00000346",
"row_id": 346,
"seed_ids": "[166]"
} | 0.640277 | Data_Structure_346 | I | [
"enhanced_gcd",
"enhanced_lcm"
] | 2 | [
[
"enhanced_lcm",
"enhanced_gcd"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ca5a716722ed51d92abfaf3792c19cbc59deab8c | cb8d228a0e99a83e59d05eb475e9cc8230706287 | |||
v1.0 | instruct | Data_Structure | Data_Structure_407_I | You are given a flow network represented by a capacity matrix, a source vertex, and a sink vertex. Your task is to implement a function to compute the maximum flow from the source to the sink using the **Edmonds-Karp** algorithm, which is an implementation of the Ford-Fulkerson method using BFS.
### Function Signature... | from collections import deque
from typing import List
def bfs(capacity: List[List[int]], source: int, sink: int, parent: List[int]) -> bool:
visited = [False] * len(capacity)
queue = deque([source])
visited[source] = True
while queue:
u = queue.popleft()
for v in range(len(capacity)):
... | from solution import maximum_flow
def test_maximum_flow_example():
capacity = [
[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 maximum_flow(capa... | [
{
"docstring": null,
"function_declaration": "def bfs(capacity, source, sink, parent):",
"function_name": "bfs",
"parameter_list": "(capacity, source, sink, parent)"
},
{
"docstring": null,
"function_declaration": "def maximum_flow(capacity, source, sink):",
"function_name": "maximum... | [
0,
0,
0,
1,
1,
0,
0,
1,
0,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from collections import deque\nfrom typing import List\n\ndef bfs(capacity: List[List[int]], source: int, sink: int, parent: List[int]) -> bool:\n \"\"\"\n... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00000407",
"row_id": 407,
"seed_ids": "[240]"
} | 0.515259 | Data_Structure_407 | I | [
"bfs",
"maximum_flow"
] | 2 | [
[
"maximum_flow",
"bfs"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 622e7b7d9a447cfaa4bf425c53565c906b4abd79 | ad7decf67751b418ee2f8f8b85321b3c2412754e | |||
v1.0 | instruct | Data_Structure | Data_Structure_481_I | Given an n x n matrix represented as a 2D list, write a function that computes its inverse. Your function should account for edge cases, such as non-square matrices and singular matrices (matrices with a determinant of zero). If such cases are encountered, your function should handle it gracefully by returning a specif... | from typing import List
def determinant(matrix: List[List[float]]) -> float:
n = len(matrix)
if n == 1:
return matrix[0][0]
if n == 2:
return matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0]
det = 0
for c in range(n):
det += ((-1) ** c) * matrix[0][c] * determi... | from solution import compute_matrix_inverse
def test_non_matrix_input():
assert compute_matrix_inverse("not a matrix") == [[-1]]
assert compute_matrix_inverse(12345) == [[-1]]
def test_non_square_matrix():
assert compute_matrix_inverse([[1, 2], [3, 4], [5, 6]]) == [[-2]]
assert compute_matrix_inverse(... | [
{
"docstring": null,
"function_declaration": "def determinant(matrix):",
"function_name": "determinant",
"parameter_list": "(matrix)"
},
{
"docstring": null,
"function_declaration": "def minor(matrix, i, j):",
"function_name": "minor",
"parameter_list": "(matrix, i, j)"
},
{
... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef compute_determinant(matrix: List[List[float]]) -> float:\n \"\"\"Computes the determinant of an n x n matrix.\"\"\"\n n =... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00000481",
"row_id": 481,
"seed_ids": "[347]"
} | 0.530834 | Data_Structure_481 | I | [
"determinant",
"minor",
"cofactor",
"transpose",
"inverse",
"compute_matrix_inverse"
] | 6 | [
[
"cofactor",
"determinant"
],
[
"cofactor",
"minor"
],
[
"compute_matrix_inverse",
"inverse"
],
[
"determinant",
"minor"
],
[
"inverse",
"cofactor"
],
[
"inverse",
"determinant"
],
[
"inverse",
"transpose"
]
] | 7 | [] | false | [] | false | pytest | true | [] | true | cfa48a2b010397b6e822597e7c280204589161be | 134796a0e7a112dff1b50524a6fe4d0c70b66997 | |||
v1.0 | instruct | Data_Structure | Data_Structure_485_I | Given the preorder and postorder traversal arrays of a full binary tree, write a Python function `construct_tree(pre, post)` that reconstructs the binary tree and returns its inorder traversal as a list.
### Input
- `pre`: A list of integers representing the preorder traversal of a full binary tree.
- `post`: A list o... | class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def construct_tree_from_pre_post(pre, post):
if not pre or not post:
return None
root = TreeNode(pre[0])
if len(pre) == 1:
return root
left_root_val = pre[1]
L = post.i... | from solution import construct_tree
def test_construct_tree_example():
pre = [1, 2, 4, 8, 9, 5, 3, 6, 7]
post = [8, 9, 4, 5, 2, 6, 7, 3, 1]
assert construct_tree(pre, post) == [8, 4, 9, 2, 5, 1, 6, 3, 7]
def test_construct_tree_single_node():
pre = [1]
post = [1]
assert construct_tree(pre, pos... | [] | [
1,
1
] | 2 | easy | 1 | {
"trial_gpt4o_0": null,
"trial_gpt4o_1": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared1_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 sel... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00000485",
"row_id": 485,
"seed_ids": "[300]"
} | 0.596932 | Data_Structure_485 | I | [
"construct_tree_from_pre_post",
"inorder_traversal",
"construct_tree"
] | 3 | [
[
"construct_tree",
"construct_tree_from_pre_post"
],
[
"construct_tree",
"inorder_traversal"
]
] | 2 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | 4ab4ead503bf05ae6ecc3cc7c321f9afdb704a32 | e8e8a82baa81fb269f3b1a059c3a87d35e2db6a8 | |||
v1.0 | instruct | Data_Structure | Data_Structure_583_I | **Problem Statement: Secure Communication with Diffie-Hellman Key Exchange**
Alice and Bob want to establish a secure communication channel by using the Diffie-Hellman key exchange algorithm. Your task is to implement the functions needed to carry out this cryptographic key exchange securely.
You are provided with th... | import random
def prime_check(num: int) -> bool:
"""
Returns True if num is a prime number.
"""
if num <= 1:
return False
for i in range(2, int(num**0.5)+1):
if num % i == 0:
return False
return True
def find_order(a: int, n: int) -> int:
"""
Returns the ord... | from solution import prime_check, find_order, euler_totient, find_primitive_root, perform_diffie_hellman_key_exchange
import pytest
def test_prime_check():
assert prime_check(2) == True
assert prime_check(4) == False
assert prime_check(23) == True
assert prime_check(1) == False
assert prime_check(0... | [
{
"docstring": "Returns True if num is a prime number.",
"function_declaration": "def prime_check(num):",
"function_name": "prime_check",
"parameter_list": "(num)"
},
{
"docstring": "Returns the order of a modulo n, or -1 if no order exists",
"function_declaration": "def find_order(a, n)... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef prime_check(num: int) -> bool:\n \"\"\"\n Returns True if num is a prime number.\n \"\"\"\n if num <= 1:\n return Fals... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00000583",
"row_id": 583,
"seed_ids": "[146]"
} | 0.461399 | Data_Structure_583 | I | [
"prime_check",
"find_order",
"euler_totient",
"find_primitive_root",
"perform_diffie_hellman_key_exchange"
] | 5 | [
[
"find_primitive_root",
"euler_totient"
],
[
"find_primitive_root",
"prime_check"
],
[
"perform_diffie_hellman_key_exchange",
"find_primitive_root"
],
[
"perform_diffie_hellman_key_exchange",
"prime_check"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | 2674ab3394972994073c0276a6c071a75f331285 | 127bb395b81b28dbfa1c4df550d8513863f22231 | |||
v1.0 | instruct | Data_Structure | Data_Structure_597_I | Binary Tree Path Sum Calculator
**Context**:
You have a binary tree and need to work with its structure by serializing it to a string and deserializing it back to a tree form. After reconstructing the tree, you need to implement a function that calculates the sum of all root-to-leaf paths in the tree, where each path ... | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def deserialize(data: str) -> TreeNode:
def helper(nodes):
val = next(nodes)
if val == "#":
return None
node = TreeNode(int(val))
... | from solution import tree_path_sum
def test_tree_path_sum_simple():
serialized = "1 2 # # 3 4 # # 5 # #"
assert tree_path_sum(serialized) == 281
def test_tree_path_sum_single_node():
serialized = "1 # #"
assert tree_path_sum(serialized) == 1
def test_tree_path_sum_left_skewed():
serialized = "1 2... | [] | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_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\ndef de... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00000597",
"row_id": 597,
"seed_ids": "[330]"
} | 0.57377 | Data_Structure_597 | I | [
"deserialize",
"tree_path_sum"
] | 2 | [
[
"tree_path_sum",
"deserialize"
]
] | 1 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | d5aafc6a6486d46f4a8e38652432d15a8f6e13b3 | 3ad8cfc0c4c418522945cae8056668c8e6d99194 | |||
v1.0 | instruct | Data_Structure | Data_Structure_620_I | ### Reversing a Hybrid Linked List
You are given a singly linked list where each node might contain a primary value and a pointer to a sub-linked list. Your task is to reverse the main list and each of the sub-linked lists. For instance:
```
1 --> 2 --> 3
↓ ↓ ↓
4 5→6 7→8→9
```
After reversa... | class ListNode:
def __init__(self, val=0, next=None, sublist=None):
self.val = val
self.next = next
self.sublist = sublist
def reverse_linked_list(head: ListNode) -> ListNode:
prev = None
current = head
while current:
next_node = current.next
current.next = prev
... | from solution import ListNode, reverse_hybrid_list
def list_to_string(head: ListNode) -> str:
result = []
while head:
sublist_as_string = '->'.join(
str(node.val) for node in iterate_list(head.sublist)) if head.sublist else ""
result.append(f"{head.val}:[{sublist_as_string}]")
... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class ListNode:\n def __init__(self, val=0, next=None, sublist=None):\n self.val = val\n self.next = next\n self.sublist = sublist\n\n... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00000620",
"row_id": 620,
"seed_ids": "[244]"
} | 0.578348 | Data_Structure_620 | I | [
"reverse_linked_list",
"reverse_sublist",
"reverse_hybrid_list"
] | 3 | [
[
"reverse_hybrid_list",
"reverse_linked_list"
],
[
"reverse_hybrid_list",
"reverse_sublist"
],
[
"reverse_sublist",
"reverse_linked_list"
]
] | 3 | [] | false | [
"ListNode"
] | true | pytest | true | [] | true | bc9d85695cdc8b89a8a842498993d28e4f794b03 | f03d61ca275473e8e49be50b4e033769b7a45e79 | |||
v1.0 | instruct | Data_Structure | Data_Structure_651_I | You are given two singly linked lists that may or may not intersect at some node. Your task is to implement a function that determines the node at which the intersection of two linked lists begins.
**Function Signature**
```python
def intersection(head1: Node, head2: Node) -> Node:
pass
```
### Input
- `head1`: T... | class Node:
def __init__(self, value=None):
self.value = value
self.next = None
def get_length(head: Node) -> int:
length = 0
current = head
while current:
length += 1
current = current.next
return length
def intersection(head1: Node, head2: Node) -> Node:
if no... | from solution import Node, intersection
def test_no_intersection():
h1 = Node(1)
h1.next = Node(2)
h1.next.next = Node(3)
h2 = Node(4)
h2.next = Node(5)
h2.next.next = Node(6)
assert intersection(h1, h2) is None
def test_intersection():
h1 = Node(1)
h1.next = Node(2)
h1.next.... | [] | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class Node:\n def __init__(self, value=None):\n self.value = value\n self.next = None\n\ndef get_length(head: Node) -> int:\n length = 0\n... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00000651",
"row_id": 651,
"seed_ids": "[245]"
} | 0.582792 | Data_Structure_651 | I | [
"get_length",
"intersection"
] | 2 | [
[
"intersection",
"get_length"
]
] | 1 | [] | false | [
"Node"
] | true | pytest | true | [] | true | 015de0f29b37e6f509d78a16c8978d62c6638fa9 | d11cb9e1c0d4fd0d77e3f7065ea28109bf712939 | |||
v1.0 | instruct | Data_Structure | Data_Structure_690_I | ### Quick Sort Implementation with Custom Pivot Selection
#### Context
Quick Sort is a popular and efficient sorting algorithm. However, its performance relies heavily on the choice of the pivot element. The provided implementation always selects the last element as the pivot, which can degrade performance in certain ... | import random
def custom_quick_sort(arr, pivot_strategy='last'):
"""
Sorts the array using Quick Sort with a custom pivot selection strategy.
Parameters:
arr (list of int): The array to be sorted.
pivot_strategy (str): The pivot selection strategy.
It can be 'first', ... | from solution import custom_quick_sort
def test_quick_sort_empty_array():
assert custom_quick_sort([], 'first') == []
assert custom_quick_sort([], 'last') == []
assert custom_quick_sort([], 'median') == []
assert custom_quick_sort([], 'random') == []
def test_quick_sort_single_element():
assert cu... | [
{
"docstring": "Sorts the array using Quick Sort with a custom pivot selection strategy.\n\nParameters:\narr (list of int): The array to be sorted.\npivot_strategy (str): The pivot selection strategy.\n It can be 'first', 'last', 'median', or 'random'.\nReturns:\nlist of int: The sorted arr... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def custom_quick_sort(arr, pivot_strategy='last'):\n import random\n \n def partition(arr, low, high):\n if pivot_strategy == 'first':\n ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00000690",
"row_id": 690,
"seed_ids": "[25]"
} | 0.54596 | Data_Structure_690 | I | [
"custom_quick_sort",
"select_pivot"
] | 2 | [
[
"custom_quick_sort",
"select_pivot"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 7580c1ea647101326a2722c68b50efc015331398 | 7cdd0d0581ee63997c802d655c43c4ed4edba62e | |||
v1.0 | instruct | Data_Structure | Data_Structure_695_I | **Problem Statement:**
Write a function, `insertion_sort`, that sorts an array of integers using the insertion sort algorithm. To handle the insertion efficiently, utilize a helper function `search_insert` that determines the appropriate index to insert each element.
**Function Signature:**
```python
def insertion_sor... | def search_insert(sorted_subarray, val):
"""
Binary search helper function to find the insertion index for the value `val`
in the sorted portion of array `sorted_subarray`.
Args:
sorted_subarray (list): The portion of the array that is already sorted.
val (int): The value to be inserted.
... | from solution import insertion_sort
def test_insertion_sort_with_unordered_elements():
assert insertion_sort([4, 2, 7, 1, 3]) == [1, 2, 3, 4, 7]
def test_insertion_sort_with_sorted_elements():
assert insertion_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_insertion_sort_with_reverse_sorted_elements():
... | [
{
"docstring": "Binary search helper function to find the insertion index for the value `val` \nin the sorted portion of array `sorted_subarray`.\n\nArgs:\nsorted_subarray (list): The portion of the array that is already sorted.\nval (int): The value to be inserted.\n\nReturns:\nint: The index where `val` shoul... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def search_insert(sorted_array, value):\n \"\"\"\n Helper function to find the index where `value` should be inserted in `sorted_array`.\n Uses binar... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00000695",
"row_id": 695,
"seed_ids": "[199]"
} | 0.56925 | Data_Structure_695 | I | [
"search_insert",
"insertion_sort"
] | 2 | [
[
"insertion_sort",
"search_insert"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 1c33efec732068741780191c4f16404a20b193c4 | ecc4f98895fb148ab4c3b619aa2883577e8676cf | |||
v1.0 | instruct | Data_Structure | Data_Structure_772_I | ### Pancake Sort with Enhanced Constraints
Imagine that you are a chef who loves sorting tasks as much as cooking delectable dishes. However, your sorting spatula (used to flip pancakes) is fragile and you can only use it a limited number of times. This introduces an additional constraint to the usual pancake sort alg... | def flip(arr, k):
"""Helper function to reverse the first k elements of array arr."""
return arr[:k][::-1] + arr[k:]
def find_max_index(arr, n):
"""Helper function to find the index of the maximum element in arr upto index n."""
return max(range(n), key=arr.__getitem__)
def limited_pancake_sort(arr, m... | def test_flip():
assert flip([3, 2, 4, 1], 3) == [4, 2, 3, 1]
def test_select_max():
assert find_max_index([1, 5, 4, 3, 2], 5) == 1
def test_limited_pancake_sort():
# Case where max_flips is enough to fully sort the array
assert limited_pancake_sort([3, 2, 4, 1], max_flips=10) == [1, 2, 3, 4]
... | [
{
"docstring": "Helper function to reverse the first k elements of array arr.",
"function_declaration": "def flip(arr, k):",
"function_name": "flip",
"parameter_list": "(arr, k)"
},
{
"docstring": "Helper function to find the index of the maximum element in arr upto index n.",
"function_... | [
0,
0,
0,
1,
0,
0,
0,
0,
1,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def flip(arr, k):\n \"\"\"Helper function to perform flip up to index k (inclusive)\"\"\"\n return arr[:k+1][::-1] + arr[k+1:]\n\ndef limited_pancake_so... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "00000772",
"row_id": 772,
"seed_ids": "[9]"
} | 0.618091 | Data_Structure_772 | I | [
"flip",
"find_max_index",
"limited_pancake_sort"
] | 3 | [
[
"limited_pancake_sort",
"find_max_index"
],
[
"limited_pancake_sort",
"flip"
]
] | 2 | [] | false | [] | false | pytest | false | [] | true | 724347072f0e31642b5c7a42f5fe1ad5292e7065 | cd5a99333d80fbedb848ba38712c5e0df26186f0 | |||
v1.0 | instruct | Data_Structure | Data_Structure_819_I | You are tasked to implement a simplified version of the RSA encryption algorithm. Only key generation and encryption/decryption functionalities are needed. Specifically, you will write functions: `generate_key()`, `encrypt()`, and `decrypt()`.
### Function Descriptions
1. **generate_key(k, seed=None)**:
- **Input*... | import random
from sympy import isprime, mod_inverse, nextprime
def generate_key(k, seed=None):
if seed is not None:
random.seed(seed)
# Generate two distinct prime numbers p and q
p = nextprime(random.getrandbits(k // 2))
q = nextprime(random.getrandbits(k // 2))
while p == q:
... | from solution import generate_key, encrypt, decrypt
def test_generate_key():
n, e, d = generate_key(16, seed=42)
assert n > 0
assert e > 0
assert d > 0
def test_encrypt_decrypt():
n, e, d = generate_key(16, seed=42)
data = 20
encrypted = encrypt(data, e, n)
decrypted = decrypt(encrypte... | [
{
"docstring": null,
"function_declaration": "def generate_key(k, seed=None):",
"function_name": "generate_key",
"parameter_list": "(k, seed=None)"
},
{
"docstring": null,
"function_declaration": "def encrypt(data, e, n):",
"function_name": "encrypt",
"parameter_list": "(data, e,... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nfrom sympy import isprime, mod_inverse\n\ndef generate_large_prime(bits):\n \"\"\"\n Generates a large prime number with the specified nu... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00000819",
"row_id": 819,
"seed_ids": "[154]"
} | 0.582423 | Data_Structure_819 | I | [
"generate_key",
"encrypt",
"decrypt",
"gcd"
] | 4 | [
[
"generate_key",
"gcd"
]
] | 1 | [] | false | [] | false | pytest | true | [
"sympy"
] | false | 795182e24367b85b1efc873427755d09d23d98e8 | 57511ec95e5f4c6516271238e203204cd4bbbaf5 | |||
v1.0 | instruct | Data_Structure | Data_Structure_866_I | ### Context
You are tasked with implementing a sorting functionality for a large dataset in a high-performance application. You decide to use the Quick Sort algorithm due to its average-case efficiency and in-place nature. However, you need to ensure your implementation can handle large input sizes and includes an opti... | from typing import List
def median_of_three(arr: List[int], low: int, high: int) -> int:
mid = (low + high) // 2
if arr[low] > arr[mid]:
arr[low], arr[mid] = arr[mid], arr[low]
if arr[mid] > arr[high]:
arr[mid], arr[high] = arr[high], arr[mid]
if arr[low] > arr[mid]:
arr[low], a... | from solution import optimized_quick_sort
def test_optimized_quick_sort_random_numbers():
assert optimized_quick_sort([3, 6, 8, 10, 1, 2, 1]) == [1, 1, 2, 3, 6, 8, 10]
def test_optimized_quick_sort_single_element():
assert optimized_quick_sort([1]) == [1]
def test_optimized_quick_sort_empty_list():
asser... | [
{
"docstring": null,
"function_declaration": "def median_of_three(arr, low, high):",
"function_name": "median_of_three",
"parameter_list": "(arr, low, high)"
},
{
"docstring": null,
"function_declaration": "def partition(arr, low, high):",
"function_name": "partition",
"parameter... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef optimized_quick_sort(arr: List[int]) -> List[int]:\n def median_of_three(a, b, c):\n if a > b:\n if a < c:... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00000866",
"row_id": 866,
"seed_ids": "[25]"
} | 0.573886 | Data_Structure_866 | I | [
"median_of_three",
"partition",
"quick_sort_recursive",
"optimized_quick_sort"
] | 4 | [
[
"optimized_quick_sort",
"quick_sort_recursive"
],
[
"partition",
"median_of_three"
],
[
"quick_sort_recursive",
"partition"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | b0784b9ab5e110cc2c6b66573b25572e8513d912 | 3e290e2168998f23ff38dfb308a91e0434d39ec5 | |||
v1.0 | instruct | Data_Structure | Data_Structure_1024_I | ### Task
You are tasked with implementing a more efficient sorting algorithm to replace the Bogo Sort algorithm for sorting a list of integers.
### Input and Output Formats
**Input**:
```python
arr: List[int]
```
* A list of integers that needs to be sorted.
**Output**:
```python
List[int]
```
* The sorted... | def merge_sort(arr):
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, right):
sorted_list = []
left_pointer = right_pointer = 0
while left_pointer < len(... | from solution import efficient_sort
def test_sorted_array():
assert efficient_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_reverse_sorted_array():
assert efficient_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5]
def test_empty_array():
assert efficient_sort([]) == []
def test_single_element_array():
a... | [
{
"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)"
},
{
"docst... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef efficient_sort(arr: List[int]) -> List[int]:\n \"\"\"\n Sorts a list of integers in ascending order using merge sort.\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00001024",
"row_id": 1024,
"seed_ids": "[16]"
} | 0.599857 | Data_Structure_1024 | I | [
"merge_sort",
"merge",
"efficient_sort"
] | 3 | [
[
"efficient_sort",
"merge_sort"
],
[
"merge_sort",
"merge"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 3fc064060a0bfb7d98d4027cb6da6efda6045269 | 13a490115d6491b6f79ba7da3b28f62576561b17 | |||
v1.0 | instruct | Data_Structure | Data_Structure_1043_I | ### Question: Insertion Sort with Binary Search
To assess your understanding of the insertion sort algorithm and binary search, your task is to implement the insertion sort algorithm with a twist. Use the `search_insert` helper method provided to find the correct position for each element to help reduce the number of ... | from typing import List
def search_insert(arr: List[int], value: int) -> int:
left, right = 0, len(arr)
while left < right:
mid = (left + right) // 2
if arr[mid] < value:
left = mid + 1
else:
right = mid
return left
def binary_insertion_sort(arr: List[int]) ... | import pytest
from solution import binary_insertion_sort
def test_empty_list():
assert binary_insertion_sort([]) == []
def test_single_element():
assert binary_insertion_sort([1]) == [1]
def test_sorted_list():
assert binary_insertion_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_reverse_sorted_list... | [
{
"docstring": null,
"function_declaration": "def search_insert(arr, value):",
"function_name": "search_insert",
"parameter_list": "(arr, value)"
},
{
"docstring": null,
"function_declaration": "def binary_insertion_sort(arr):",
"function_name": "binary_insertion_sort",
"paramete... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef search_insert(arr: List[int], left: int, right: int, target: int) -> int:\n \"\"\"\n Use binary search to find the index ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00001043",
"row_id": 1043,
"seed_ids": "[199]"
} | 0.612118 | Data_Structure_1043 | I | [
"search_insert",
"binary_insertion_sort"
] | 2 | [
[
"binary_insertion_sort",
"search_insert"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c8dcbc4a4b4b3f020e50559196e01b4016c520a7 | 5051ffcbfc24dccf62687368bd4193cad5f54170 | |||
v1.0 | instruct | Data_Structure | Data_Structure_1044_I | ### Question: Finding Primitive Roots for a Cryptographic Application
Your task is to implement a function that finds the primitive roots of a given integer n. The function should use Euler's Totient function and the order finding methodology to determine all the primitive roots of n. This is a critical task in crypto... | from typing import List
import math
def gcd(a, b):
"""
Helper function to return the greatest common divisor of a and b.
"""
while b:
a, b = b, a % b
return a
def euler_totient(n):
"""
Euler's Totient function to calculate the number of integers up to n that are coprime with n.
... | from solution import find_all_primitive_roots
def test_find_all_primitive_roots_10():
assert find_all_primitive_roots(10) == []
def test_find_all_primitive_roots_17():
assert sorted(find_all_primitive_roots(17)) == [3, 5, 6, 7, 10, 11, 12, 14]
def test_find_all_primitive_roots_2():
assert find_all_primit... | [
{
"docstring": "Helper function to return the greatest common divisor of a and b.",
"function_declaration": "def gcd(a, b):",
"function_name": "gcd",
"parameter_list": "(a, b)"
},
{
"docstring": "Euler's Totient function to calculate the number of integers up to n that are coprime with n.",
... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef gcd(a: int, b: int) -> int:\n while b:\n a, b = b, a % b\n return a\n\ndef euler_totient(n: int) -> int:\n resu... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00001044",
"row_id": 1044,
"seed_ids": "[160]"
} | 0.4875 | Data_Structure_1044 | I | [
"gcd",
"euler_totient",
"is_primitive_root",
"find_all_primitive_roots"
] | 4 | [
[
"find_all_primitive_roots",
"is_primitive_root"
],
[
"is_primitive_root",
"euler_totient"
],
[
"is_primitive_root",
"gcd"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | f4f63161f1ca783f39a2f0226a4f892dec910bf0 | 2426b3bdd8d8fe8136583d6ee733d33234f71b9d | |||
v1.0 | instruct | Data_Structure | Data_Structure_1078_I | **Context**:
Suppose you are a software engineer developing a system that requires matrix operations to solve linear equations. Your task is to write a function that can efficiently compute the inverse of a given \(n \times n\) matrix if it is invertible.
### Problem Statement:
You need to implement a function `invert... | from typing import List, Union
def get_determinant(matrix: List[List[Union[int, float]]]) -> Union[float, int]:
"""Helper function to calculate the determinant of a matrix."""
n = len(matrix)
if n == 1:
return matrix[0][0]
if n == 2:
return matrix[0][0]*matrix[1][1] - matrix[0][1]*matri... | from solution import invert_matrix
def test_square_invertible_matrix_2x2():
assert invert_matrix([[1, 2], [3, 4]]) == [[-2.0, 1.0], [1.5, -0.5]]
def test_square_invertible_matrix_3x3():
assert invert_matrix([[3, 0, 2], [2, 0, -2], [0, 1, 1]]) == [
[0.2, 0.2, 0.0],
[-0.2, 0.3, 1.0],
[0.... | [
{
"docstring": "Helper function to calculate the determinant of a matrix.",
"function_declaration": "def get_determinant(matrix):",
"function_name": "get_determinant",
"parameter_list": "(matrix)"
},
{
"docstring": "Helper function to get the minor matrix after removing the i-th row and j-th... | [
0,
0,
0,
1,
0,
1,
0,
0,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List, Union\n\ndef get_determinant(matrix: List[List[Union[int, float]]]) -> Union[float, int]:\n # Base case for 2x2 matrix:\n if le... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "00001078",
"row_id": 1078,
"seed_ids": "[347]"
} | 0.52412 | Data_Structure_1078 | I | [
"get_determinant",
"get_matrix_minor",
"get_matrix_of_minors",
"transpose_matrix",
"invert_matrix"
] | 5 | [
[
"get_determinant",
"get_matrix_minor"
],
[
"get_matrix_of_minors",
"get_determinant"
],
[
"get_matrix_of_minors",
"get_matrix_minor"
],
[
"invert_matrix",
"get_determinant"
],
[
"invert_matrix",
"get_matrix_of_minors"
],
[
"invert_matrix",
"trans... | 6 | [] | false | [] | false | pytest | true | [] | true | 3109853bd8d24801bb25f846eedb72d5b08d5cf6 | ffa84d4d3d28749793d2237f1ac11aa6029cb693 | |||
v1.0 | instruct | Data_Structure | Data_Structure_1079_I | You are given a graph represented as an adjacency list where each node has a list of its neighbors. Implement a function `compose_traversal_route(graph, start, method)` which performs graph traversal starting from a specified node using the selected method (`'dfs'`, `'bfs'`) and returns the ordered list of nodes as the... | from typing import List, Dict
def compose_traversal_route(graph: Dict[int, List[int]], start: int, method: str) -> List[int]:
if method == 'dfs':
return dfs_traversal(graph, start)
elif method == 'bfs':
return bfs_traversal(graph, start)
else:
raise ValueError("Method should be eith... | from solution import compose_traversal_route
def test_dfs_simple():
graph = {
1: [2, 3],
2: [4, 5],
3: [],
4: [],
5: []
}
assert compose_traversal_route(graph, 1, 'dfs') == [1, 2, 4, 5, 3]
def test_bfs_simple():
graph = {
1: [2, 3],
2: [4, 5],
... | [
{
"docstring": null,
"function_declaration": "def compose_traversal_route(graph, start, method):",
"function_name": "compose_traversal_route",
"parameter_list": "(graph, start, method)"
},
{
"docstring": null,
"function_declaration": "def dfs_traversal(graph, start):",
"function_name... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from collections import deque\nfrom typing import Dict, List\n\ndef compose_traversal_route(graph: Dict[int, List[int]], start: int, method: str) -> List[int]... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00001079",
"row_id": 1079,
"seed_ids": "[224]"
} | 0.587632 | Data_Structure_1079 | I | [
"compose_traversal_route",
"dfs_traversal",
"bfs_traversal"
] | 3 | [
[
"compose_traversal_route",
"bfs_traversal"
],
[
"compose_traversal_route",
"dfs_traversal"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 1104f16a8a87803b7ed801d8f5d0e75ce4e7aa60 | 350c3662e2c374de49ef053fae59eb18ff56e5cb | |||
v1.0 | instruct | Data_Structure | Data_Structure_1094_I | ### Bitonic Sort for Non-Power-of-2 Size Arrays
#### Objective:
You are required to implement a variant of the Bitonic Sort algorithm that can handle arrays of arbitrary sizes, not just powers of 2.
#### Problem Statement:
Given an array `arr` containing `n` integers, you need to sort the array in increasing order. T... | import math
def bitonic_sort_up(arr, start, length):
if length > 1:
k = length // 2
for i in range(start, start + k):
if arr[i] > arr[i + k]:
arr[i], arr[i + k] = arr[i + k], arr[i]
bitonic_sort_up(arr, start, k)
bitonic_sort_up(arr, start + k, k)
def bi... | from solution import bitonic_sort_general
def test_bitonic_sort_general_basic():
assert bitonic_sort_general([5, 3, 1, 2, 6, 4, 7]) == [1, 2, 3, 4, 5, 6, 7]
assert bitonic_sort_general([10]) == [10]
assert bitonic_sort_general([]) == []
assert bitonic_sort_general([9, 13, 3, 7]) == [3, 7, 9, 13]
def t... | [
{
"docstring": null,
"function_declaration": "def bitonic_sort_up(arr, start, length):",
"function_name": "bitonic_sort_up",
"parameter_list": "(arr, start, length)"
},
{
"docstring": null,
"function_declaration": "def bitonic_sort_down(arr, start, length):",
"function_name": "bitoni... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\n\ndef bitonic_sort_up(arr, start, length):\n if length > 1:\n k = length // 2\n for i in range(start, start + k):\n i... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00001094",
"row_id": 1094,
"seed_ids": "[17]"
} | 0.657705 | Data_Structure_1094 | I | [
"bitonic_sort_up",
"bitonic_sort_down",
"bitonic_merge",
"bitonic_sort",
"bitonic_sort_general"
] | 5 | [
[
"bitonic_sort",
"bitonic_merge"
],
[
"bitonic_sort_general",
"bitonic_sort"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | ebf98bb714746da7a490dcb6445371236b58724b | 682127bc8c529b6e30c36d3e8e232972b2e75397 | |||
v1.0 | instruct | Data_Structure | Data_Structure_1110_I | ### Question: Secure Communication with Diffie-Hellman
You are tasked with implementing an end-to-end Diffie-Hellman key exchange system, ensuring that Alice and Bob can securely establish a shared secret key over an unsecured network. Your implementation should involve the generation of private/public keys, the excha... | import random
from sympy import isprime, primerange
def prime_check(num):
"""
Verify if the given number is prime.
"""
return isprime(num)
def find_primitive_root(p):
"""
Find all primitive roots of the given prime number p.
"""
required_set = {num for num in range(1, p) if gcd(num, p)... | from solution import secure_diffie_hellman, prime_check, find_primitive_root
def test_prime_check():
assert prime_check(7) == True
assert prime_check(4) == False
assert prime_check(23) == True
assert prime_check(24) == False
def test_find_primitive_root():
assert find_primitive_root(7) == 3
... | [
{
"docstring": "Verify if the given number is prime.",
"function_declaration": "def prime_check(num):",
"function_name": "prime_check",
"parameter_list": "(num)"
},
{
"docstring": "Find all primitive roots of the given prime number p.",
"function_declaration": "def find_primitive_root(p)... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nfrom sympy import isprime, primerange\n\ndef prime_check(num):\n \"\"\"\n Verify if the given number is prime.\n \"\"\"\n return is... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00001110",
"row_id": 1110,
"seed_ids": "[146]"
} | 0.432584 | Data_Structure_1110 | I | [
"prime_check",
"find_primitive_root",
"gcd",
"generate_private_key",
"generate_public_key",
"compute_shared_key",
"secure_diffie_hellman"
] | 7 | [
[
"find_primitive_root",
"gcd"
],
[
"secure_diffie_hellman",
"compute_shared_key"
],
[
"secure_diffie_hellman",
"find_primitive_root"
],
[
"secure_diffie_hellman",
"generate_private_key"
],
[
"secure_diffie_hellman",
"generate_public_key"
],
[
"secure_... | 6 | [] | false | [] | false | pytest | true | [
"sympy"
] | false | 1b6a7e6e699f52d1c855a3d8818c060bac9ea271 | 2924959cb0a1bc3aaff886d48f8dd51f29273a4c | |||
v1.0 | instruct | Data_Structure | Data_Structure_1113_I | **Question**: Design an algorithm to determine the maximum flow from a specified source to a sink in a given flow network. Implement the algorithm using the Ford-Fulkerson method. The function signature should be:
```python
def ford_fulkerson(custom_capacity: List[List[int]], custom_source: int, custom_sink: int) -> i... | from collections import deque
from typing import List
def bfs(residual_capacity, source, sink, parent):
visited = [False] * len(residual_capacity)
queue = deque([source])
visited[source] = True
while queue:
u = queue.popleft()
for ind, val in enumerate(residual_capacity[u]):
... | from solution import ford_fulkerson
def test_small_graph():
custom_capacity = [
[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]
]
custom_source = 0
custom_sink = 5
assert for... | [
{
"docstring": null,
"function_declaration": "def bfs(residual_capacity, source, sink, parent):",
"function_name": "bfs",
"parameter_list": "(residual_capacity, source, sink, parent)"
},
{
"docstring": null,
"function_declaration": "def ford_fulkerson(custom_capacity, custom_source, cust... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\nfrom collections import deque\n\ndef bfs(residual_capacity: List[List[int]], source: int, sink: int, parent: List[int]) -> bool:\n ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00001113",
"row_id": 1113,
"seed_ids": "[240]"
} | 0.506117 | Data_Structure_1113 | I | [
"bfs",
"ford_fulkerson"
] | 2 | [
[
"ford_fulkerson",
"bfs"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 1d4ba811c2d2660c81dcc2183470175539fa6298 | 8a05d89bbcfd77e4e469533bc69e466e5c932924 | |||
v1.0 | instruct | Data_Structure | Data_Structure_1125_I | You are implementing a secure communication channel using the Diffie-Hellman Key Exchange method. You must write a function that simulates the key exchange process and verifies if both parties derive the same shared secret key.
#### Function Signature
```python
def secure_key_exchange(prime: int, root: int, print_ste... | import random
def is_prime(n):
"""Check if n is a prime number"""
if n <= 1:
return False
if n == 2:
return True
if n % 2 == 0:
return False
for i in range(3, int(n**0.5)+1, 2):
if n % i == 0:
return False
return True
def find_primitive_root(p):
... | from solution import secure_key_exchange
def test_secure_key_exchange_matching_keys():
assert secure_key_exchange(23, 5, print_steps=True) == True
def test_secure_key_exchange_invalid_prime():
try:
secure_key_exchange(24, 5, print_steps=False)
except ValueError as e:
assert str(e) == "The ... | [
{
"docstring": "Check if n is a prime number",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Find a primitive root for prime p",
"function_declaration": "def find_primitive_root(p):",
"function_name": "find_primiti... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef is_prime(n):\n \"\"\"Check if n is a prime number\"\"\"\n if n <= 1:\n return False\n if n == 2:\n return True\n ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00001125",
"row_id": 1125,
"seed_ids": "[146]"
} | 0.499206 | Data_Structure_1125 | I | [
"is_prime",
"find_primitive_root",
"gcd",
"secure_key_exchange"
] | 4 | [
[
"find_primitive_root",
"gcd"
],
[
"find_primitive_root",
"is_prime"
],
[
"secure_key_exchange",
"find_primitive_root"
],
[
"secure_key_exchange",
"is_prime"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | 7d59c8ff817d29ea241aaf48f193dc2e6cf9cf10 | 00ac0f277b0a5c8e20ddacc64e8445691249ddad | |||
v1.0 | instruct | Data_Structure | Data_Structure_1180_I | Magic Number Check
**Context**: In mystical number theory, some numbers are considered special or "magic" based on specific properties. One such property is when the sum of a number's digits repeatedly reduces to 1.
**Objective**: Write a function to determine whether a given number is a "magic number." A magic numbe... | def sum_of_digits(n):
"""
Helper function to calculate the sum of the digits of n.
"""
total = 0
while n > 0:
total += n % 10
n //= 10
return total
def magic_number(n):
"""
Determine whether a given number is a magic number.
A magic number is defined as a number that... | from solution import magic_number
def test_example_cases():
assert magic_number(50113) == True # 5+0+1+1+3=10 -> 1+0=1
assert magic_number(1234) == True # 1+2+3+4=10 -> 1+0=1
assert magic_number(199) == True # 1+9+9=19 -> 1+9=10 -> 1+0=1
assert magic_number(111) == False # 1+1+1=3
assert ma... | [
{
"docstring": "Helper function to calculate the sum of the digits of n.",
"function_declaration": "def sum_of_digits(n):",
"function_name": "sum_of_digits",
"parameter_list": "(n)"
},
{
"docstring": "Determine whether a given number is a magic number.\nA magic number is defined as a number ... | [
0,
0,
0,
0,
1,
0,
0,
0,
1,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def magic_number(n):\n \"\"\"\n Determines if a given number is a magic number, which repeatedly sums its digits to eventually become 1.\n \n Para... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00001180",
"row_id": 1180,
"seed_ids": "[132]"
} | 0.5916 | Data_Structure_1180 | I | [
"sum_of_digits",
"magic_number"
] | 2 | [
[
"magic_number",
"sum_of_digits"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | dfe52a757afc67a9169dfa740b670d3a2876f287 | 0964365c7bc804e979354ed12b74b94b4fd19d26 | |||
v1.0 | instruct | Data_Structure | Data_Structure_1188_I | Cosine Similarity Enhancement
Suppose you are working on a recommendation system and need to adjust the existing implementation for cosine similarity to handle more complex scenarios efficiently. You are provided the initial implementation of the cosine similarity calculation and are required to enhance it.
**Scenari... | import math
def cosine_similarity(v1, v2):
"""
Helper function to calculate cosine similarity between two vectors.
"""
sumxx, sumxy, sumyy = 0, 0, 0
for i in range(len(v1)):
x = v1[i]
y = v2[i]
sumxx += x * x
sumyy += y * y
sumxy += x * y
if sumxx == 0 or... | from solution import cosine_similarity_matrix
def test_cosine_similarity_basic():
matrix1 = [
[1, 1, 1],
[2, 2, 2]
]
matrix2 = [
[1, 2, -1],
[3, 0, 0]
]
expected_output = [
[0.47140452079103173, 0.5773502691896257],
[0.47140452079103173, 0.57735026918... | [
{
"docstring": "Helper function to calculate cosine similarity between two vectors.",
"function_declaration": "def cosine_similarity(v1, v2):",
"function_name": "cosine_similarity",
"parameter_list": "(v1, v2)"
},
{
"docstring": "Compute the cosine similarity matrix between two matrices.\n\n... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\n\ndef cosine_similarity(v1, v2):\n \"\"\"\n Helper function to calculate cosine similarity between two vectors.\n \"\"\"\n sumxx, sum... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00001188",
"row_id": 1188,
"seed_ids": "[149]"
} | 0.598853 | Data_Structure_1188 | I | [
"cosine_similarity",
"cosine_similarity_matrix"
] | 2 | [
[
"cosine_similarity_matrix",
"cosine_similarity"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 262f866dc503944f6b1bdd0b6c47dab2620e0f09 | e646c352729fbfdd989f606338097d9151f8ef14 | |||
v1.0 | instruct | Data_Structure | Data_Structure_1234_I | ### Problem Description
You are given a square matrix `mat` of dimension `d` and an integer `n`. Write a function `matrix_power(mat: List[List[int]], n: int) -> List[List[int]]` that computes the `n`-th power of the matrix using the strategy of repeated squaring. The function should use helper functions to perform mat... | from typing import List
def matrix_multiply(A: List[List[int]], B: List[List[int]]) -> List[List[int]]:
d = len(A)
result = [[0] * d for _ in range(d)]
for i in range(d):
for j in range(d):
for k in range(d):
result[i][j] += A[i][k] * B[k][j]
return result
def ident... | from solution import matrix_power
def test_matrix_power_exponent_0():
mat = [
[2, 3],
[4, 5]
]
result = matrix_power(mat, 0)
expected = [
[1, 0],
[0, 1]
]
assert result == expected
def test_matrix_power_exponent_1():
mat = [
[2, 3],
[4, 5]
... | [
{
"docstring": null,
"function_declaration": "def matrix_multiply(A, B):",
"function_name": "matrix_multiply",
"parameter_list": "(A, B)"
},
{
"docstring": null,
"function_declaration": "def identity_matrix(size):",
"function_name": "identity_matrix",
"parameter_list": "(size)"
... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef matrix_multiply(A: List[List[int]], B: List[List[int]]) -> List[List[int]]:\n \"\"\"\n Multiplies two matrices A and B.\n... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00001234",
"row_id": 1234,
"seed_ids": "[340]"
} | 0.52743 | Data_Structure_1234 | I | [
"matrix_multiply",
"identity_matrix",
"matrix_power"
] | 3 | [
[
"matrix_power",
"identity_matrix"
],
[
"matrix_power",
"matrix_multiply"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | e9ef352dad6639e2a4d3dc71fdff2f279b70d20a | d1552a4e5618c649bee98f142a140e701cb091f7 | |||
v1.0 | instruct | Data_Structure | Data_Structure_1255_I | You are given an array of integers and need to sort it using the Merge Sort algorithm. Your task is to implement the `merge_sort` function and its helper function `merge`, which will recursively sort the input array.
#### Function Signatures
```python
def merge_sort(arr: list) -> list:
"""
Sorts an array of i... | def merge_sort(arr: list) -> list:
"""
Sorts an array of integers using the merge sort algorithm.
Parameters:
arr (list): A list of integers to be sorted.
Returns:
list: A sorted list of integers.
"""
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left = merge_so... | from solution import merge_sort
def test_sort_empty_list():
assert merge_sort([]) == []
def test_sort_single_element_list():
assert merge_sort([1]) == [1]
def test_sort_sorted_list():
assert merge_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_sort_reverse_sorted_list():
assert merge_sort([5, 4, ... | [
{
"docstring": "Sorts an array of integers using the merge sort algorithm.\n\nParameters:\narr (list): A list of integers to be sorted.\n\nReturns:\nlist: A sorted list of integers.",
"function_declaration": "def merge_sort(arr):",
"function_name": "merge_sort",
"parameter_list": "(arr)"
},
{
... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def merge_sort(arr: list) -> list:\n \"\"\"\n Sorts an array of integers using the merge sort algorithm.\n\n Parameters:\n arr (list): A list of i... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00001255",
"row_id": 1255,
"seed_ids": "[12]"
} | 0.706755 | Data_Structure_1255 | I | [
"merge_sort",
"merge"
] | 2 | [
[
"merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | fdf67423b31ea44c0b0441842c9fe5667306a693 | 4fb7778dbc220028d26eb15117b91abe5960c351 | |||
v1.0 | instruct | Data_Structure | Data_Structure_1264_I | Implement a function `improved_bitonic_sort` that sorts an array using the Bitonic Sort algorithm. Your function should handle arrays that are not of size power of two by padding them with a high-value sentinel element (e.g., float('inf')) until they reach the next power of two. Additionally, optimize the merge step to... | import math
def next_power_of_two(n):
"""Return the next power of two greater than or equal to n."""
return 1 << (n - 1).bit_length()
def bitonic_compare_and_swap(arr, i, j, direction):
if (direction == (arr[i] > arr[j])):
arr[i], arr[j] = arr[j], arr[i]
def bitonic_merge(arr, low, cnt, direction... | from solution import improved_bitonic_sort
def test_improved_bitonic_sort_ascending():
input_array = [3, 7, 2, 5, 1]
assert improved_bitonic_sort(input_array, reverse=False) == [1, 2, 3, 5, 7]
def test_improved_bitonic_sort_descending():
input_array = [3, 7, 2, 5, 1]
assert improved_bitonic_sort(input... | [
{
"docstring": "Return the next power of two greater than or equal to n.",
"function_declaration": "def next_power_of_two(n):",
"function_name": "next_power_of_two",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def bitonic_compare_and_swap(arr, i, j, direction... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\n\ndef next_power_of_two(x):\n return 1 if x == 0 else 2**(x - 1).bit_length()\n\ndef bitonic_compare_and_swap(arr, i, j, direction):\n if (... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00001264",
"row_id": 1264,
"seed_ids": "[17]"
} | 0.661743 | Data_Structure_1264 | I | [
"next_power_of_two",
"bitonic_compare_and_swap",
"bitonic_merge",
"bitonic_sort",
"improved_bitonic_sort"
] | 5 | [
[
"bitonic_merge",
"bitonic_compare_and_swap"
],
[
"bitonic_sort",
"bitonic_merge"
],
[
"improved_bitonic_sort",
"bitonic_sort"
],
[
"improved_bitonic_sort",
"next_power_of_two"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | 9fdac89996a24fb44bf80cd83fbcbf6d235b5209 | be918c9b5499a9fe7e1c6da698cca650a216d26b | |||
v1.0 | instruct | Data_Structure | Data_Structure_1320_I | You are required to implement a function that computes the greatest common divisor (GCD) of two integers but with an additional twist: you should incorporate detecting efficient edge cases handling that improve the performance specifically focusing on using bitwise operations. Additionally, you need to extend the funct... | def efficient_gcd(a: int, b: int) -> int:
"""
Computes the greatest common divisor (GCD) of integers 'a' and 'b'
using efficient methods including bitwise operations.
Args:
a (int): First integer
b (int): Second integer
Returns:
int: The GCD of 'a' and 'b'
"""
if a ==... | from solution import efficient_gcd, efficient_lcm
def test_efficient_gcd_common():
assert efficient_gcd(48, 18) == 6
assert efficient_gcd(56, 98) == 14
assert efficient_gcd(1000000, 2) == 2
def test_efficient_gcd_zero():
assert efficient_gcd(0, 5) == 5
assert efficient_gcd(5, 0) == 5
assert ef... | [
{
"docstring": "Computes the greatest common divisor (GCD) of integers 'a' and 'b'\nusing efficient methods including bitwise operations.\nArgs:\n a (int): First integer\n b (int): Second integer\nReturns:\n int: The GCD of 'a' and 'b'",
"function_declaration": "def efficient_gcd(a, b):",
"func... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def efficient_gcd(a: int, b: int) -> int:\n \"\"\"\n Computes the greatest common divisor (GCD) of integers 'a' and 'b'\n using efficient methods inc... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00001320",
"row_id": 1320,
"seed_ids": "[166]"
} | 0.718104 | Data_Structure_1320 | I | [
"efficient_gcd",
"efficient_lcm"
] | 2 | [
[
"efficient_lcm",
"efficient_gcd"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 1680d274dcbbb63acd796e4e7c9f1611f859ca1b | 329e41279ef8ed620385fb4dd2533b6ee1064ac9 | |||
v1.0 | instruct | Data_Structure | Data_Structure_1324_I | ## Quick Sort Implementation and Optimization
In this exercise, you need to implement the quick sort algorithm but with a focus on optimizing its performance and handling edge cases. Specifically, you are required to:
1. Implement the quick sort algorithm with a randomized pivot selection to mitigate the risk of poor... | import random
def insertion_sort(arr, left, right):
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[j]
j -= 1
arr[j + 1] = key
def partition(arr, low, high):
pivot_index = random.randint(low,... | from solution import optimized_quick_sort
def test_optimized_quick_sort_regular_case():
assert optimized_quick_sort([3, 6, 8, 10, 1, 2, 1]) == [1, 1, 2, 3, 6, 8, 10]
def test_optimized_quick_sort_all_identical_elements():
assert optimized_quick_sort([1, 1, 1, 1]) == [1, 1, 1, 1]
def test_optimized_quick_sort... | [
{
"docstring": null,
"function_declaration": "def insertion_sort(arr, left, right):",
"function_name": "insertion_sort",
"parameter_list": "(arr, left, right)"
},
{
"docstring": null,
"function_declaration": "def partition(arr, low, high):",
"function_name": "partition",
"paramet... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef insertion_sort(arr, low, high):\n for i in range(low + 1, high + 1):\n key = arr[i]\n j = i - 1\n while j >= low ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00001324",
"row_id": 1324,
"seed_ids": "[25]"
} | 0.594904 | Data_Structure_1324 | I | [
"insertion_sort",
"partition",
"quick_sort_recursive",
"optimized_quick_sort"
] | 4 | [
[
"optimized_quick_sort",
"quick_sort_recursive"
],
[
"quick_sort_recursive",
"insertion_sort"
],
[
"quick_sort_recursive",
"partition"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | dfc7014fa157dbc3defb9ff2b93438942ba5f9e7 | b5eedc3f3a5cb3e634c6e5ac75738830095b03aa | |||
v1.0 | instruct | Data_Structure | Data_Structure_1340_I | You are tasked with improving and extending a utility that converts integers between different numeral systems (bases). The utility currently supports base conversions up to base 36 using digits and uppercase letters.
#### Requirements:
1. **Function 1**: Implement a function `int_to_base(num, base)` that:
- Conver... | def int_to_base(num, base):
"""
Converts an integer num to a string representation in the specified base.
Args:
num (int): The integer to convert.
base (int): The base to convert to.
Returns:
str: The string representation of num in the specified base.
"""
if base < 2 or ba... | def test_int_to_base():
assert int_to_base(5, 2) == '101'
assert int_to_base(-15, 16) == '-F'
assert int_to_base(0, 10) == '0'
assert int_to_base(255, 16) == 'FF'
assert int_to_base(123456789, 36) == '21I3V9'
assert int_to_base(-123456789, 36) == '-21I3V9'
def test_base_to_int():
assert bas... | [
{
"docstring": "Converts an integer num to a string representation in the specified base.\n\nArgs:\nnum (int): The integer to convert.\nbase (int): The base to convert to.\n\nReturns:\nstr: The string representation of num in the specified base.",
"function_declaration": "def int_to_base(num, base):",
"... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def int_to_base(num, base):\n \"\"\"\n Converts an integer num (base 10) to a string representation in the specified base.\n Handles bases from 2 to ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00001340",
"row_id": 1340,
"seed_ids": "[164]"
} | 0.764502 | Data_Structure_1340 | I | [
"int_to_base",
"int_to_char",
"base_to_int",
"char_to_int"
] | 4 | [
[
"base_to_int",
"char_to_int"
],
[
"int_to_base",
"int_to_char"
]
] | 2 | [] | false | [] | false | pytest | false | [] | true | 7aefa1828a773c06082cd26ea51abac491ce1162 | b693b56f07153e6733055fe26cd53a6388d722e6 | |||
v1.0 | instruct | Data_Structure | Data_Structure_1363_I | ### Question:
Write a function `find_order_with_print_steps(a, n)` that finds the order of a positive integer a modulo n as follows:
1. The function takes in two positive integers `a` and `n`.
2. The function should return the smallest positive integer k such that \(a^k ≡ 1 \mod n\). If no such k exists, return -1.
3... | def gcd(x, y):
while y:
x, y = y, x % y
return x
def find_order_with_print_steps(a, n):
"""
Finds the order of a modulo n and prints each step.
Parameters:
a (int): The base number.
n (int): The modulus.
Returns:
int: The smallest positive integer k such that a^k ≡... | from solution import find_order_with_print_steps
def test_find_order_with_print_steps_basic():
assert find_order_with_print_steps(2, 5) == 4 # Should print out steps and return 4
assert find_order_with_print_steps(3, 11) == 5 # Should print out steps and return 5
def test_find_order_with_print_steps_error()... | [
{
"docstring": null,
"function_declaration": "def gcd(x, y):",
"function_name": "gcd",
"parameter_list": "(x, y)"
},
{
"docstring": "Finds the order of a modulo n and prints each step.\n\nParameters:\na (int): The base number.\nn (int): The modulus.\n\nReturns:\nint: The smallest positive in... | [
0,
0,
0,
1,
0,
0,
1,
0,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\n\ndef find_order_with_print_steps(a: int, n: int) -> int:\n \"\"\"\n Finds the order of a positive integer a modulo n.\n \n Parameter... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "00001363",
"row_id": 1363,
"seed_ids": "[150]"
} | 0.572055 | Data_Structure_1363 | I | [
"gcd",
"find_order_with_print_steps"
] | 2 | [
[
"find_order_with_print_steps",
"gcd"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a1e639fb845780c0316c9158476ba87428d2eea9 | c8fa7046e0061926dbcb3523bcc2202fbea60cb7 | |||
v1.0 | instruct | Data_Structure | Data_Structure_1367_I | Demonstrate your understanding of optimized insertion sort by implementing a function that uses binary search to find the correct insertion position. You need to implement the optimized insertion sort algorithm utilizing the provided `search_insert` helper function.
### Function Signature
```python
def optimized_inser... | def search_insert(arr, val, start, end):
"""
Uses binary search to find the index where 'val' should be inserted in 'arr'
to maintain sorted order from indices 'start' to 'end'.
"""
if start == end:
if arr[start] > val:
return start
else:
return start + 1
... | from solution import optimized_insertion_sort
def test_sorted_array():
assert optimized_insertion_sort([5, 6, 11, 12, 13]) == [5, 6, 11, 12, 13]
def test_reverse_sorted_array():
assert optimized_insertion_sort([13, 12, 11, 6, 5]) == [5, 6, 11, 12, 13]
def test_unsorted_array():
assert optimized_insertion... | [
{
"docstring": "Uses binary search to find the index where 'val' should be inserted in 'arr'\nto maintain sorted order from indices 'start' to 'end'.",
"function_declaration": "def search_insert(arr, val, start, end):",
"function_name": "search_insert",
"parameter_list": "(arr, val, start, end)"
}... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def search_insert(arr, left, right, key):\n \"\"\"\n Uses binary search to find the index where 'key' should be inserted \n among existing elements i... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00001367",
"row_id": 1367,
"seed_ids": "[199]"
} | 0.641536 | Data_Structure_1367 | I | [
"search_insert",
"optimized_insertion_sort"
] | 2 | [
[
"optimized_insertion_sort",
"search_insert"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 70af0430f2db891a1c157205cbb60228af359fb6 | f324ff622e93aa717469e9af273e984c7e48bcd6 | |||
v1.0 | instruct | Data_Structure | Data_Structure_1390_I | ### Challenging Coding Assessment Question
#### Problem Statement
Given an array of floating-point numbers in the range [0, 1), implement a sorting function using the Bucket Sort algorithm. Each bucket should be sorted using the Merge Sort algorithm instead of the more straightforward Insertion Sort. This should help... | from typing import List
def merge_sort(arr: List[float]) -> List[float]:
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[float], right: List[float]) -> List[float]:
sorted_li... | from solution import bucket_sort
def test_bucket_sort_example_1():
assert bucket_sort([0.78, 0.17, 0.39, 0.26, 0.72, 0.94, 0.21, 0.12, 0.23, 0.68]) == \
[0.12, 0.17, 0.21, 0.23, 0.26, 0.39, 0.68, 0.72, 0.78, 0.94]
def test_bucket_sort_example_2():
assert bucket_sort([0.42, 0.32, 0.23, 0.52, 0.3, 0.... | [
{
"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)"
},
{
"docst... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef merge_sort(arr: List[float]) -> List[float]:\n if len(arr) <= 1:\n return arr\n \n mid = len(arr) // 2\n lef... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00001390",
"row_id": 1390,
"seed_ids": "[26]"
} | 0.536865 | Data_Structure_1390 | I | [
"merge_sort",
"merge",
"bucket_sort"
] | 3 | [
[
"bucket_sort",
"merge_sort"
],
[
"merge_sort",
"merge"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 9ea9ad428b73844cfe67e913079dd23fcf6deb3b | 87ef75177c0d7e14eb47cc10b417b6352ba28a72 | |||
v1.0 | instruct | Data_Structure | Data_Structure_1424_I | #### Scenario
Imagine you are working as a part of a development team responsible for developing a library of sorting algorithms. One of the fundamental algorithms you need to implement is Insertion Sort. You are provided with a helper function `search_insert` that determines the correct index to insert an element into... | def search_insert(array, val):
"""
Helper function using binary search to find the index where val should be inserted.
"""
low = 0
high = len(array) - 1
while low <= high:
mid = low + (high - low) // 2
if val > array[mid]:
low = mid + 1
else:
high ... | from solution import insertion_sort
def test_insertion_sort_already_sorted():
arr = [1, 2, 3, 4, 5, 6]
insertion_sort(arr)
assert arr == [1, 2, 3, 4, 5, 6]
def test_insertion_sort_reverse_sorted():
arr = [6, 5, 4, 3, 2, 1]
insertion_sort(arr)
assert arr == [1, 2, 3, 4, 5, 6]
def test_insertio... | [
{
"docstring": "Helper function using binary search to find the index where val should be inserted.",
"function_declaration": "def search_insert(array, val):",
"function_name": "search_insert",
"parameter_list": "(array, val)"
},
{
"docstring": "Sorts the array in-place using insertion sort ... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def search_insert(array, val):\n \"\"\"\n Helper function to determine the index where val should be inserted in the sorted part of the array.\n Uses... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00001424",
"row_id": 1424,
"seed_ids": "[199]"
} | 0.568802 | Data_Structure_1424 | I | [
"search_insert",
"insertion_sort"
] | 2 | [
[
"insertion_sort",
"search_insert"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 35297abe60d256912211ee667902bcb202af348e | 0a3314e9ca3a195b111dd1d1a2a19565847ee503 | |||
v1.0 | instruct | Data_Structure | Data_Structure_1430_I | Pancake Sort Implementation
**Context**:
Pancake sorting is a technique of sorting a sequence using only the prefix reversal operation, similar to flipping pancakes in a pan. Although it is not the most efficient sorting method by modern standards, it is a fascinating problem to understand the concepts of in-place so... | def flip(arr, k):
"""
Helper function to reverse the first k elements of the array.
"""
arr[:k] = arr[:k][::-1]
def pancake_sort(arr):
"""
Pancake sorting function to sort the input list using pancake sorting algorithm.
"""
n = len(arr)
for size in range(n, 1, -1):
# Find th... | from solution import pancake_sort
def test_pancake_sort_example_cases():
assert pancake_sort([3, 2, 4, 1]) == [1, 2, 3, 4]
assert pancake_sort([5, 1, 2]) == [1, 2, 5]
assert pancake_sort([1]) == [1]
assert pancake_sort([]) == []
def test_pancake_sort_already_sorted():
assert pancake_sort([1, 2, 3,... | [
{
"docstring": "Helper function to reverse the first k elements of the array.",
"function_declaration": "def flip(arr, k):",
"function_name": "flip",
"parameter_list": "(arr, k)"
},
{
"docstring": "Pancake sorting function to sort the input list using pancake sorting algorithm.",
"functi... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def flip(arr, k):\n \"\"\"\n Reverses the order of the first k elements of the list arr.\n \"\"\"\n arr[:k] = arr[:k][::-1]\n\ndef pancake_sort(ar... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00001430",
"row_id": 1430,
"seed_ids": "[9]"
} | 0.686523 | Data_Structure_1430 | I | [
"flip",
"pancake_sort"
] | 2 | [
[
"pancake_sort",
"flip"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 4cd371b744e6146e260f46b980d0d19cc6d56f3a | 8140b07f47b908dc8c738ba4d371e2475c6ac092 | |||
v1.0 | instruct | Data_Structure | Data_Structure_1436_I | ### Coding Problem: Huffman Coding Implementation
#### Objective:
Implement an algorithm to compress and decompress a given text file using Huffman coding. Your implementation should efficiently encode the input data and be capable of decoding it back to the original data.
#### Function Signature:
```python
def encod... | import heapq
import os
import pickle
class HuffmanNode:
def __init__(self, char=None, freq=None):
self.char = char
self.freq = freq
self.left = None
self.right = None
def __lt__(self, other):
return self.freq < other.freq
def build_frequency_dict(text):
frequency =... | import os
from solution import encode_file, decode_file
def test_huffman_encoding_decoding():
input_filename = 'test_input.txt'
encoded_filename = 'test_encoded.bin'
decoded_filename = 'test_decoded.txt'
# Prepare test input file
with open(input_filename, 'w') as file:
file.write("this... | [] | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import heapq\nfrom collections import defaultdict, Counter\n\nclass HuffmanNode:\n def __init__(self, char=None, freq=0):\n self.char = char\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00001436",
"row_id": 1436,
"seed_ids": "[335]"
} | 0.566499 | Data_Structure_1436 | I | [
"build_frequency_dict",
"build_huffman_tree",
"build_codes",
"encode_text",
"pad_encoded_text",
"get_byte_array",
"encode_file",
"remove_padding",
"decode_text",
"decode_file"
] | 10 | [
[
"decode_file",
"decode_text"
],
[
"decode_file",
"remove_padding"
],
[
"encode_file",
"build_codes"
],
[
"encode_file",
"build_frequency_dict"
],
[
"encode_file",
"build_huffman_tree"
],
[
"encode_file",
"encode_text"
],
[
"encode_file",
... | 8 | [] | false | [
"HuffmanNode"
] | true | pytest | true | [] | true | 1bafeccd564b1c65c78c52e5618ec4fef152ca70 | 016ae8b7334a59da4fcff1e14a6dea48cd22fbad | |||
v1.0 | instruct | Data_Structure | Data_Structure_1550_I | ## Question: Implement a Bucket Sort Algorithm
You are required to implement a Bucket Sort algorithm that sorts an array of integers. The goal is to demonstrate your understanding of the bucket sort concept, distribution mechanism, and sorting within buckets.
### Task:
1. Implement a bucket sort algorithm for an arra... | from typing import List
def insertion_sort(bucket):
"""
Helper function to perform insertion sort on a single bucket/list.
"""
for i in range(1, len(bucket)):
up = bucket[i]
j = i - 1
while j >= 0 and bucket[j] > up:
bucket[j + 1] = bucket[j]
j -= 1
... | from solution import bucket_sort
def test_bucket_sort_standard_case():
assert bucket_sort([29, 25, 3, 49, 9, 37, 21, 43]) == [3, 9, 21, 25, 29, 37, 43, 49]
def test_bucket_sort_with_duplicates():
assert bucket_sort([5, 1, 2, 2, 3, 5, 4]) == [1, 2, 2, 3, 4, 5, 5]
def test_bucket_sort_single_element():
ass... | [
{
"docstring": "Helper function to perform insertion sort on a single bucket/list.",
"function_declaration": "def insertion_sort(bucket):",
"function_name": "insertion_sort",
"parameter_list": "(bucket)"
},
{
"docstring": null,
"function_declaration": "def bucket_sort(arr):",
"functi... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef insertion_sort(bucket: List[int]) -> List[int]:\n for i in range(1, len(bucket)):\n key = bucket[i]\n j = i - ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00001550",
"row_id": 1550,
"seed_ids": "[26]"
} | 0.579881 | Data_Structure_1550 | I | [
"insertion_sort",
"bucket_sort"
] | 2 | [
[
"bucket_sort",
"insertion_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 6b02a3d8f8bb18524fdfbafe4433842cf717aadb | 32b2058536de18e00a5ac3b69dac775a9d43257e | |||
v1.0 | instruct | Data_Structure | Data_Structure_1571_I | ### Merge Sort Implementation with Advanced Features
Given the principles and characteristics of the merge sort algorithm, implement the `merge_sort` function and its helper `merge` which includes the following requirements:
1. **Input**: A list of integers `arr` of size `n` (0 <= n <= 10^5).
2. **Output**: The list ... | def insertion_sort(arr):
"""
Sorts the array in-place using insertion sort.
"""
for i in range(1, len(arr)):
key = arr[i]
j = i - 1
while j >= 0 and key < arr[j]:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
def merge(left, right):
"""
Merg... | from solution import merge_sort, merge, insertion_sort
def test_merge_sort_empty():
assert merge_sort([]) == []
def test_merge_sort_single_element():
assert merge_sort([1]) == [1]
def test_merge_sort_sorted_list():
assert merge_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_merge_sort_reverse_sorted_... | [
{
"docstring": "Sorts the array in-place using insertion sort.",
"function_declaration": "def insertion_sort(arr):",
"function_name": "insertion_sort",
"parameter_list": "(arr)"
},
{
"docstring": "Merges two sorted lists into a sorted list.",
"function_declaration": "def merge(left, righ... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def merge_sort(arr, k=10):\n if len(arr) <= 1:\n return arr\n\n if len(arr) < k:\n return insertion_sort(arr)\n\n mid = len(arr) // 2\n... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00001571",
"row_id": 1571,
"seed_ids": "[12]"
} | 0.625614 | Data_Structure_1571 | I | [
"insertion_sort",
"merge",
"merge_sort"
] | 3 | [
[
"merge_sort",
"insertion_sort"
],
[
"merge_sort",
"merge"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 12f20454a18b4c9c50e1ce0eb9270085b86da4da | c97b5644badac7f180eac3f549ccc9fba6c4a106 | |||
v1.0 | instruct | Data_Structure | Data_Structure_1599_I | ### Scenario
A company is developing a software to manage their dynamically changing contact list. The contact list should allow for efficient searching, adding, and removing of contact names based on their unique IDs. Each contact is represented as a unique ID associated with a name.
### Problem Statement
Implement a... | class TreeNode:
def __init__(self, key, value):
self.key = key
self.value = value
self.left = None
self.right = None
def insert(root, key, value):
if root is None:
return TreeNode(key, value)
elif key < root.key:
root.left = insert(root.left, key, value)
... | import pytest
from solution import TreeNode, insert, search, delete
def test_insert_and_search():
root = None
root = insert(root, 50, "John Doe")
root = insert(root, 30, "Jane Smith")
root = insert(root, 70, "Emily Davis")
assert search(root, 50) == "John Doe"
assert search(root, 30) == "Jane S... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class TreeNode:\n def __init__(self, key, value):\n self.key = key\n self.value = value\n self.left = None\n self.right = None\... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00001599",
"row_id": 1599,
"seed_ids": "[287]"
} | 0.467654 | Data_Structure_1599 | I | [
"insert",
"search",
"find_min",
"delete"
] | 4 | [
[
"delete",
"find_min"
]
] | 1 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | 197f7556f7454ade245e4c8c4ec7e33eab8c5c2f | 6f08f56f77116ebc320c352b8f6a62d700ad3640 | |||
v1.0 | instruct | Data_Structure | Data_Structure_1611_I | ### Task
You are required to implement a function that sorts a list of integers using the Radix Sort algorithm with a minor variation: instead of using base 10, you will use base 16 (hexadecimal).
### Function Signature
```python
def radix_sort_hex(arr: List[int]) -> List[int]:
```
### Input/Output Formats
* **Input... | from typing import List
def counting_sort_base(arr: List[int], exp: int, base: int) -> List[int]:
n = len(arr)
output = [0] * n
count = [0] * base
for i in range(n):
index = (arr[i] // exp) % base
count[index] += 1
for i in range(1, base):
count[i] += count[i - 1]
for... | from solution import radix_sort_hex
def test_radix_sort_hex_basic():
assert radix_sort_hex([170, 45, 75, 90, 802, 24, 2, 66]) == [2, 24, 45, 66, 75, 90, 170, 802]
def test_radix_sort_hex_single_element():
assert radix_sort_hex([15]) == [15]
def test_radix_sort_hex_sorted():
assert radix_sort_hex([1, 2, 3... | [
{
"docstring": null,
"function_declaration": "def counting_sort_base(arr, exp, base):",
"function_name": "counting_sort_base",
"parameter_list": "(arr, exp, base)"
},
{
"docstring": null,
"function_declaration": "def radix_sort_hex(arr):",
"function_name": "radix_sort_hex",
"para... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef counting_sort_hex(arr: List[int], exp: int, base: int) -> List[int]:\n n = len(arr)\n output = [0] * n\n count = [0] *... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00001611",
"row_id": 1611,
"seed_ids": "[15]"
} | 0.598485 | Data_Structure_1611 | I | [
"counting_sort_base",
"radix_sort_hex"
] | 2 | [
[
"radix_sort_hex",
"counting_sort_base"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f1030fb630ed9c0edba723d53c17d32b0310d38e | e16a52685fc887298223d8a40aa754c94e17e8f2 | |||
v1.0 | instruct | Data_Structure | Data_Structure_1630_I | ### RSA Encryption Key Generation and Data Encryption/Decryption
You are given an implementation of the RSA encryption algorithm which includes key generation, encryption, and decryption functions. The provided implementation generates RSA keys and uses them to encrypt and decrypt data. However, the current prime gene... | import random
def miller_rabin_primality_test(n, k):
"""Run the Miller-Rabin primality test `k` times to determine if `n` is a prime number."""
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0:
return False
# write (n - 1) as 2^r * d
r, d = 0, n - 1
... | from solution import generate_key, encrypt, decrypt
import random
def test_gen_prime():
for k in [16, 32, 64]:
assert len(bin(gen_prime(k))) - 2 == k
def test_generate_key():
n, e, d = generate_key(16)
assert isinstance(n, int)
assert isinstance(e, int)
assert isinstance(d, int)
assert... | [
{
"docstring": "Run the Miller-Rabin primality test `k` times to determine if `n` is a prime number.",
"function_declaration": "def miller_rabin_primality_test(n, k):",
"function_name": "miller_rabin_primality_test",
"parameter_list": "(n, k)"
},
{
"docstring": "Generate a prime with k bits ... | [
0,
0,
0,
0,
0,
0,
0,
0,
1,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nfrom math import gcd\n\ndef is_prime(n, k=5):\n \"\"\"Use Miller-Rabin primality test to test if a number is prime\"\"\"\n if n <= 1:\n ... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00001630",
"row_id": 1630,
"seed_ids": "[154]"
} | 0.582273 | Data_Structure_1630 | I | [
"miller_rabin_primality_test",
"gen_prime",
"gcd",
"modinv",
"generate_key",
"encrypt",
"decrypt"
] | 7 | [
[
"gen_prime",
"miller_rabin_primality_test"
],
[
"generate_key",
"gcd"
],
[
"generate_key",
"gen_prime"
],
[
"generate_key",
"modinv"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | 8cd4a91ca7b31d59d155c9b3c49231aa48344910 | 96d8be93f280a59068f950abbeeb931d07d2f567 | |||
v1.0 | instruct | Data_Structure | Data_Structure_1663_I | ### Prime Detection Assessment
Given the function `prime_check(n)`, design and implement a function `kth_prime(k)` that returns the `k`-th prime number. Implement this in a way that efficiently finds primes as needed, making use of the provided `prime_check(n)` function.
#### Input
* An integer `k` (1 ≤ k ≤ 10^5).
#... | def prime_check(n):
"""
Checks whether a number n is prime.
"""
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
... | from solution import kth_prime, prime_check
def test_kth_prime_first():
assert kth_prime(1) == 2
def test_kth_prime_fifth():
assert kth_prime(5) == 11
def test_kth_prime_tenth():
assert kth_prime(10) == 29
def test_prime_check_positive():
assert prime_check(2) is True
assert prime_check(3) is Tr... | [
{
"docstring": "Checks whether a number n is prime.",
"function_declaration": "def prime_check(n):",
"function_name": "prime_check",
"parameter_list": "(n)"
},
{
"docstring": "Returns the k-th prime number.",
"function_declaration": "def kth_prime(k):",
"function_name": "kth_prime",
... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\n\ndef prime_check(n):\n \"\"\"Returns True if n is a prime number, False otherwise.\"\"\"\n if n <= 1:\n return False\n if n <= 3... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00001663",
"row_id": 1663,
"seed_ids": "[143]"
} | 0.721821 | Data_Structure_1663 | I | [
"prime_check",
"kth_prime"
] | 2 | [
[
"kth_prime",
"prime_check"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | d3b2f8debc28b0aa6f80b1335099d19d204e3085 | 4de457ff3a7ffc2cc9f638a82b4ded52cc355ed3 | |||
v1.0 | instruct | Data_Structure | Data_Structure_1684_I | ## Problem: Implement Enhanced Radix Sort with Support for Negative Numbers
### Scenario
You have been contracted by a software company to improve their sorting functionality within their data processing pipeline. The company's data consists of integers that could be either positive or negative, and their current syst... | def counting_sort(arr, exp):
n = len(arr)
output = [0] * n # output array that will have sorted arr
count = [0] * 10 # count array to store count of occurrences
# Store count of occurrences in count[]
for i in range(n):
index = abs(arr[i]) // exp
count[index % 10] += 1
# Chan... | from solution import enhanced_radix_sort
def test_enhanced_radix_sort_mixed_numbers():
assert enhanced_radix_sort([170, 45, 75, -90, -802, 24, 2, 66]) == [-802, -90, 2, 24, 45, 66, 75, 170]
def test_enhanced_radix_sort_negative_and_zero():
assert enhanced_radix_sort([-5, -10, 0, -3, 8, 5, 4, -1]) == [-10, -5,... | [
{
"docstring": null,
"function_declaration": "def counting_sort(arr, exp):",
"function_name": "counting_sort",
"parameter_list": "(arr, exp)"
},
{
"docstring": null,
"function_declaration": "def radix_sort_non_negative(arr):",
"function_name": "radix_sort_non_negative",
"paramete... | [
0,
0,
0,
0,
1,
0,
0,
0,
1,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def enhanced_radix_sort(arr):\n \"\"\"\n Function to perform radix sort on a list of integers\n including negative numbers.\n \"\"\"\n \n de... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00001684",
"row_id": 1684,
"seed_ids": "[15]"
} | 0.576745 | Data_Structure_1684 | I | [
"counting_sort",
"radix_sort_non_negative",
"enhanced_radix_sort"
] | 3 | [
[
"enhanced_radix_sort",
"radix_sort_non_negative"
],
[
"radix_sort_non_negative",
"counting_sort"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 458544018d6165919752c653c82edd8bf4400933 | bfa9f7cdfd4bc68b6467b226659e3b4c2b3b07c3 | |||
v1.0 | instruct | Data_Structure | Data_Structure_1689_I | ### Question
You are given two functions, `serialize` and `deserialize`, for a binary tree.
#### Objective:
Implement a method to determine if two binary trees are identical using these functions.
#### Instructions:
1. Write a function `are_trees_identical(tree1, tree2)` that takes the serialized result of two bina... | # Assuming the TreeNode class and serialization/deserialization functions are defined as follows:
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def serialize(root):
def helper(node):
if not node:
... | def test_are_trees_identical_identical_trees():
tree1 = "1 2 # # 3 # #"
tree2 = "1 2 # # 3 # #"
assert are_trees_identical(tree1, tree2)
def test_are_trees_identical_different_trees():
tree1 = "1 2 # # 3 # #"
tree2 = "1 2 # # 4 # #"
assert not are_trees_identical(tree1, tree2)
def test_are_tre... | [] | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "# Assuming the TreeNode class and serialization/deserialization functions are defined as follows:\n\nclass TreeNode:\n def __init__(self, val=0, left=None,... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00001689",
"row_id": 1689,
"seed_ids": "[330]"
} | 0.515706 | Data_Structure_1689 | I | [
"serialize",
"deserialize",
"are_trees_identical"
] | 3 | [
[
"are_trees_identical",
"deserialize"
]
] | 1 | [] | false | [
"TreeNode"
] | true | pytest | false | [] | true | 91b5c1e0987710a17aaa50db545c1305d8a6c993 | 45d3daf3f8e1e64137ebf8b69637cb2c18c6e569 | |||
v1.0 | instruct | Data_Structure | Data_Structure_1720_I | ### Pancake Birthday Party
#### Context
You are organizing a birthday party and want to serve the pancakes in a neat, sorted stack based on their size. Given a stack of pancakes, your task is to sort them so that the smallest pancake is on top and the largest pancake is at the bottom using the pancake sort algorithm.
... | from typing import List
def flip(arr: List[int], k: int) -> None:
"""
Reverses the order of the first k elements in arr.
"""
arr[:k] = arr[:k][::-1]
def pancake_sort(arr: List[int]) -> List[int]:
"""
Sorts the given list of integers using the pancake sort technique.
Parameters:
ar... | from solution import pancake_sort
def test_pancake_sort_empty():
assert pancake_sort([]) == []
def test_pancake_sort_single_element():
assert pancake_sort([1]) == [1]
def test_pancake_sort_sorted_array():
assert pancake_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_pancake_sort_reverse_sorted_array(... | [
{
"docstring": "Reverses the order of the first k elements in arr.",
"function_declaration": "def flip(arr, k):",
"function_name": "flip",
"parameter_list": "(arr, k)"
},
{
"docstring": "Sorts the given list of integers using the pancake sort technique.\n\nParameters:\narr (List[int]): A lis... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef flip(arr: List[int], k: int) -> None:\n \"\"\"\n A helper function that reverses the order of the first k elements in the... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00001720",
"row_id": 1720,
"seed_ids": "[9]"
} | 0.701861 | Data_Structure_1720 | I | [
"flip",
"pancake_sort"
] | 2 | [
[
"pancake_sort",
"flip"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c81399a9fbb8580bb24dc39ed376bb45af805852 | 991b341e6672e87b274c15c74d0fa42c9220e1a0 | |||
v1.0 | instruct | Data_Structure | Data_Structure_1744_I | ### Nearest Neighbor Search
**Scenario**:
You are tasked with improving the security of a biometric authentication system. The system initially classifies a user's input based on their closest recorded biometric template using the Nearest Neighbor method.
### Task
Implement a function called `nearest_neighbor` that ... | import math
def distance(x, y):
"""
Computes the Euclidean distance between two vectors x and y.
"""
assert len(x) == len(y), "Vectors must have the same length"
return math.sqrt(sum((xi - yi) ** 2 for xi, yi in zip(x, y)))
def nearest_neighbor(x, tSet):
"""
Classifies an input vector x by... | from solution import nearest_neighbor
def test_example1():
x = (1.0, 2.0)
tSet = {
(1.0, 1.0): "Class A",
(2.0, 2.0): "Class B",
(3.0, 3.0): "Class C"
}
assert nearest_neighbor(x, tSet) == "Class A"
def test_example2():
x = (3.5, 4.5)
tSet = {
(1.0, 2.0): "Class... | [
{
"docstring": "Computes the Euclidean distance between two vectors x and y.",
"function_declaration": "def distance(x, y):",
"function_name": "distance",
"parameter_list": "(x, y)"
},
{
"docstring": "Classifies an input vector x by comparing it to a training set tSet using the nearest neigh... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\n\ndef distance(x, y):\n \"\"\"\n Returns the Euclidean distance between two vectors x and y.\n \"\"\"\n assert len(x) == len(y), \"Ve... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00001744",
"row_id": 1744,
"seed_ids": "[260]"
} | 0.563032 | Data_Structure_1744 | I | [
"distance",
"nearest_neighbor"
] | 2 | [
[
"nearest_neighbor",
"distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 86178eee8917e55c7e6bce8dc173a5d5ab41e8e0 | 4af1e8022ad94804bf9ccdb4a838768c359646c2 | |||
v1.0 | instruct | Data_Structure | Data_Structure_1752_I | Suppose you are building a cryptographic module that requires computing the order of a number modulo `n`. The order of `a` modulo `n` is defined as the smallest positive integer `k` such that `a^k ≡ 1 (mod n)`, provided `gcd(a, n) = 1`. If no such integer exists, return -1.
### Task
Write a function `find_order(a, n)... | import math
def gcd(a, b):
while b:
a, b = b, a % b
return a
def find_order(a: int, n: int) -> int:
"""
Find the order of `a` modulo `n`.
Parameters:
a (int): The base integer.
n (int): The modulus.
Returns:
int: The order of `a` modulo `n`, or -1 if n... | from solution import find_order
def test_find_order_example_cases():
assert find_order(3, 7) == 6
assert find_order(2, 4) == -1
assert find_order(10, 17) == 16
def test_find_order_non_coprime():
assert find_order(6, 12) == -1
def test_find_order_prime_modulus():
assert find_order(2, 11) == 10
... | [
{
"docstring": null,
"function_declaration": "def gcd(a, b):",
"function_name": "gcd",
"parameter_list": "(a, b)"
},
{
"docstring": "Find the order of `a` modulo `n`.\n\nParameters:\n a (int): The base integer.\n n (int): The modulus.\n\nReturns:\n int: The order of `a` modulo `n`, ... | [
0,
0,
0,
1,
0,
0,
0,
0,
0
] | 1 | hard | 0.111 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\n\ndef find_order(a: int, n: int) -> int:\n \"\"\"\n Computes the order of a modulo n.\n\n Args:\n a: An integer whose order modulo n ... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "00001752",
"row_id": 1752,
"seed_ids": "[150]"
} | 0.617692 | Data_Structure_1752 | I | [
"gcd",
"find_order"
] | 2 | [
[
"find_order",
"gcd"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | d1749ca05f3da43fd819383ac3f26df761f90c4b | a852cb74646fcb591dd357f07a4b91a74bdf6fd8 | |||
v1.0 | instruct | Data_Structure | Data_Structure_1764_I | A Red-Black Tree (RBTree) is a balanced binary search tree with distinct properties that ensure the tree remains balanced during insertions and deletions. You are required to implement certain functions to manipulate the RBTree. Specifically, you must:
1. Implement a function to determine if a given tree is a valid Re... | class RBNode:
def __init__(self, val, is_red, parent=None, left=None, right=None):
self.val = val
self.parent = parent
self.left = left
self.right = right
self.color = is_red # 1 for red, 0 for black
def is_valid_rbtree(root):
"""
Determine if a given tree is a vali... | from solution import RBNode, is_valid_rbtree, count_red_nodes, verify_properties
def test_is_valid_rbtree_valid():
root = RBNode(10, 0)
root.left = RBNode(5, 1, root)
root.right = RBNode(15, 1, root)
root.left.left = RBNode(2, 0, root.left)
root.left.right = RBNode(8, 0, root.left)
assert is_va... | [] | [
0,
0,
0,
1,
0,
0,
0,
0,
1
] | 2 | hard | 0.222 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class RBNode:\n def __init__(self, val, is_red, parent=None, left=None, right=None):\n self.val = val\n self.parent = parent\n self.le... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00001764",
"row_id": 1764,
"seed_ids": "[314]"
} | 0.582438 | Data_Structure_1764 | I | [
"is_valid_rbtree",
"count_red_nodes",
"verify_properties"
] | 3 | [
[
"verify_properties",
"is_valid_rbtree"
]
] | 1 | [] | false | [
"RBNode"
] | true | pytest | true | [] | true | 5b502f825930ce896040e39e75b469e2dcdb8bc9 | 9891e96198f7783707b8fda2d9aae7beb9806aad | |||
v1.0 | instruct | Data_Structure | Data_Structure_1777_I | Implement an Optimized Nearest Neighbor Algorithm
**Context:**
You are working on a machine learning project that involves classifying data points using the nearest neighbor algorithm. Given the limitations of the basic implementation provided, you need to optimize the algorithm to handle larger datasets more efficien... | import math
class KDTreeNode:
def __init__(self, point, left=None, right=None):
self.point = point
self.left = left
self.right = right
def kd_tree_insert(root, point, depth=0):
if root is None:
return KDTreeNode(point)
axis = depth % len(point)
if point[axis] ... | from solution import kd_tree_insert, kd_tree_nearest, optimized_nearest_neighbor
def test_kd_tree_insert_and_nearest():
points = [(1, 2), (3, 4), (5, 6), (7, 8)]
root = None
for point in points:
root = kd_tree_insert(root, point)
assert kd_tree_nearest(root, (4, 5)) == (3, 4)
assert kd... | [] | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\n\nclass KDTreeNode:\n def __init__(self, point, left=None, right=None):\n self.point = point\n self.left = left\n self.ri... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00001777",
"row_id": 1777,
"seed_ids": "[260]"
} | 0.654876 | Data_Structure_1777 | I | [
"kd_tree_insert",
"distance_squared",
"kd_tree_nearest",
"optimized_nearest_neighbor"
] | 4 | [
[
"kd_tree_nearest",
"distance_squared"
],
[
"optimized_nearest_neighbor",
"kd_tree_insert"
],
[
"optimized_nearest_neighbor",
"kd_tree_nearest"
]
] | 3 | [] | false | [
"KDTreeNode"
] | true | pytest | true | [] | true | c168cfb28491a57987b0f1a828e8fb066232dd66 | 8de8c08a3c6e52ade2fa9e5821d5056d452661cf | |||
v1.0 | instruct | Data_Structure | Data_Structure_1837_I | ### Scenario
Alice loves solving problems involving DNA sequences. She has a collection of DNA sequences and wants to find out how often a smaller DNA pattern appears in these sequences. DNA sequences are essentially very large strings, and patterns can vary in length. Alice heard about the Knuth-Morris-Pratt (KMP) alg... | from typing import List
def compute_lps(pattern: str) -> List[int]:
"""
Helper function that computes the Longest Prefix Suffix (LPS) array for KMP algorithm.
"""
lps = [0] * len(pattern)
length = 0 # length of the previous longest prefix suffix
i = 1
while i < len(pattern):
if pa... | from solution import dna_pattern_search
def test_dna_pattern_search_simple():
assert dna_pattern_search('ACGTACGTGACG', 'ACGT') == [0, 4]
def test_dna_pattern_search_no_match():
assert dna_pattern_search('ACGTACGTGACG', 'TGCA') == []
def test_dna_pattern_search_partial_match():
assert dna_pattern_search(... | [
{
"docstring": "Helper function that computes the Longest Prefix Suffix (LPS) array for KMP algorithm.",
"function_declaration": "def compute_lps(pattern):",
"function_name": "compute_lps",
"parameter_list": "(pattern)"
},
{
"docstring": "Implement the KMP algorithm to find all starting indi... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef compute_lps(pattern: str) -> List[int]:\n \"\"\"\n Computes the longest proper prefix which is also suffix array (lps) fo... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00001837",
"row_id": 1837,
"seed_ids": "[93]"
} | 0.531396 | Data_Structure_1837 | I | [
"compute_lps",
"dna_pattern_search"
] | 2 | [
[
"dna_pattern_search",
"compute_lps"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c07a26f855402a90a892df7d207167333989d898 | 700f875be0ad02002e29ace17dcf6e67eafdb195 | |||
v1.0 | instruct | Data_Structure | Data_Structure_1898_I | ### Bucket Sort Optimization Challenge
You are tasked with optimizing the Bucket Sort algorithm provided. The existing algorithm utilizes Insertion Sort for sorting the contents of each bucket. However, Insertion Sort may become inefficient for larger datasets. Your goal is to implement a more efficient sorting mechan... | def optimized_bucket_sort(arr):
if len(arr) == 0:
return arr
# Find the maximum value in the array to determine the number of buckets
max_value = max(arr)
size = max_value // len(arr) + 1
# Create buckets and distribute the elements
buckets = [[] for _ in range(size)]
for n... | from solution import optimized_bucket_sort
def test_optimized_bucket_sort_empty():
assert optimized_bucket_sort([]) == []
def test_optimized_bucket_sort_single_element():
assert optimized_bucket_sort([1]) == [1]
def test_optimized_bucket_sort_sorted():
assert optimized_bucket_sort([1, 2, 3, 4, 5]) == [1,... | [
{
"docstring": null,
"function_declaration": "def optimized_bucket_sort(arr):",
"function_name": "optimized_bucket_sort",
"parameter_list": "(arr)"
},
{
"docstring": null,
"function_declaration": "def merge_sort(arr):",
"function_name": "merge_sort",
"parameter_list": "(arr)"
}... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def optimized_bucket_sort(arr):\n ''' Optimized Bucket Sort '''\n if len(arr) == 0:\n return arr\n\n # Find the maximum value to know the rang... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00001898",
"row_id": 1898,
"seed_ids": "[26]"
} | 0.564533 | Data_Structure_1898 | I | [
"optimized_bucket_sort",
"merge_sort",
"merge"
] | 3 | [
[
"merge_sort",
"merge"
],
[
"optimized_bucket_sort",
"merge_sort"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | e531d4ebf8d1335754fec0b7aaa3b29a7d3da95f | 5140caec6c1a448c400fe1fdc485692c4bd42ee2 | |||
v1.0 | instruct | Data_Structure | Data_Structure_1900_I | ### Question
You are tasked with implementing the K-Nearest Neighbors (KNN) classification algorithm. KNN is an extension of the nearest neighbor algorithm provided in the code snippets. Instead of returning the closest single neighbor, KNN will return the most common class among the 'k' closest neighbors.
#### Requi... | import math
from collections import Counter
def distance(x, y):
assert len(x) == len(y), "The vectors must have the same length"
sum = 0
for i in range(len(x)):
sum += (x[i] - y[i]) ** 2
return math.sqrt(sum)
def knn_classifier(x, tSet, k):
assert isinstance(x, tuple) and isinstance(tSet, ... | from solution import knn_classifier
def test_knn_classifier_simple_case():
test_vector = (1.5, 2.5)
training_set = {
(1.0, 2.0): 'A',
(2.0, 3.0): 'B',
(3.0, 4.0): 'A'
}
k = 2
assert knn_classifier(test_vector, training_set, k) == 'A'
def test_knn_classifier_all_same_labels(... | [
{
"docstring": null,
"function_declaration": "def distance(x, y):",
"function_name": "distance",
"parameter_list": "(x, y)"
},
{
"docstring": null,
"function_declaration": "def knn_classifier(x, tSet, k):",
"function_name": "knn_classifier",
"parameter_list": "(x, tSet, k)"
}
] | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\nfrom collections import Counter\n\ndef distance(x,y):\n \"\"\"\n Compute the Euclidean distance between two vectors x and y.\n \"\"\"\n ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00001900",
"row_id": 1900,
"seed_ids": "[260]"
} | 0.642508 | Data_Structure_1900 | I | [
"distance",
"knn_classifier"
] | 2 | [
[
"knn_classifier",
"distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 2ca6ebc81a885be067a94c77f04e263753e29e56 | e4a881c2ce6298475fe413e6fdd0c2a9d487d8c2 | |||
v1.0 | instruct | Data_Structure | Data_Structure_1922_I | ### Coding Challenge: Bogo Sort Conceptual Implementation
#### Context
In this challenge, you are required to implement a simplified variant of the Bogo Sort algorithm. As you have studied, Bogo Sort is an inefficient sorting algorithm that sorts an array by repetitively shuffling it until it is sorted.
However, for... | import random
from typing import List, Tuple
def is_sorted(arr: List[int]) -> bool:
"""
Helper function to check if the array is sorted.
"""
return all(arr[i] <= arr[i + 1] for i in range(len(arr) - 1))
def bogo_sort_limited(arr: List[int], max_shuffles: int) -> Tuple[List[int], bool]:
"""
Bog... | from solution import bogo_sort_limited
def test_sorted_array():
arr = [1, 2, 3]
max_shuffles = 10
result = bogo_sort_limited(arr, max_shuffles)
assert result == ([1, 2, 3], True)
def test_unsorted_array_large_max_shuffles():
arr = [3, 1, 2]
max_shuffles = 10000
result = bogo_sort_limited(a... | [
{
"docstring": "Helper function to check if the array is sorted.",
"function_declaration": "def is_sorted(arr):",
"function_name": "is_sorted",
"parameter_list": "(arr)"
},
{
"docstring": "Bogo sort implementation with limited shuffles.\n\n:param arr: List of integers to be sorted\n:param ma... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nfrom typing import List, Tuple\n\ndef is_sorted(arr: List[int]) -> bool:\n \"\"\"\n Check if the given array is sorted in ascending order... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00001922",
"row_id": 1922,
"seed_ids": "[16]"
} | 0.577745 | Data_Structure_1922 | I | [
"is_sorted",
"bogo_sort_limited"
] | 2 | [
[
"bogo_sort_limited",
"is_sorted"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a7a872e69b75cf95c98fb01a167e5ba411f37493 | 26de1e5b5765e1db19f7c054b04b5aeed041a25e | |||
v1.0 | instruct | Data_Structure | Data_Structure_1959_I | ### Coding Task: Implement an Improved Radix Sort
You are required to implement an improved version of the Radix Sort algorithm. Your task involves enhancing the provided implementation to handle some of the common issues and edge cases described above.
### Function Signature:
```python
def improved_radix_sort(arr: L... | from typing import List
def improved_radix_sort(arr: List[int], simulation: bool = False) -> List[int]:
if not arr:
return arr
max_num = max(arr)
exp = 1
radix = 10
while max_num // exp > 0:
counting_sort(arr, exp, radix, simulation)
exp *= 10
return arr
def counting... | from solution import improved_radix_sort
def test_empty_list():
assert improved_radix_sort([]) == []
def test_single_element():
assert improved_radix_sort([1]) == [1]
assert improved_radix_sort([0]) == [0]
def test_multiple_elements():
assert improved_radix_sort([170, 45, 75, 90, 802, 24, 2, 66]) == ... | [
{
"docstring": null,
"function_declaration": "def improved_radix_sort(arr, simulation=False):",
"function_name": "improved_radix_sort",
"parameter_list": "(arr, simulation=False)"
},
{
"docstring": null,
"function_declaration": "def counting_sort(arr, exp, radix, simulation):",
"func... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def improved_radix_sort(arr, simulation=False):\n if len(arr) <= 1:\n return arr\n\n def counting_sort(arr, exp, simulation):\n n = len(ar... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00001959",
"row_id": 1959,
"seed_ids": "[15]"
} | 0.630235 | Data_Structure_1959 | I | [
"improved_radix_sort",
"counting_sort"
] | 2 | [
[
"improved_radix_sort",
"counting_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 90fe7f9cf5a2683306dafc8be1364e1ede457a95 | 8886fa5cbf4ce7966b170f583adf9099911e03d4 | |||
v1.0 | instruct | Data_Structure | Data_Structure_1961_I | Finding All Cliques in an Undirected Graph
#### Problem Statement
Given an undirected graph represented by a dictionary where the keys are vertex identifiers and the values are sets of vertices connected to the key vertex, write an algorithm to find all maximal cliques in the graph using the Bron-Kerbosch Algorithm.
... | from typing import Dict, Set, List
def bron_kerbosch(R: Set[int], P: Set[int], X: Set[int], result: List[List[int]], graph: Dict[int, Set[int]]):
if not P and not X:
result.append(list(R))
return
for v in list(P):
bron_kerbosch(R.union({v}), P.intersection(graph[v]), X.intersection(grap... | from solution import find_all_cliques
def test_single_vertex():
edges = {0: set()}
assert find_all_cliques(edges) == [[0]]
def test_no_edges():
edges = {
0: set(),
1: set(),
2: set()
}
assert find_all_cliques(edges) == [[0], [1], [2]]
def test_fully_connected():
edges ... | [
{
"docstring": null,
"function_declaration": "def bron_kerbosch(R, P, X, result, graph):",
"function_name": "bron_kerbosch",
"parameter_list": "(R, P, X, result, graph)"
},
{
"docstring": null,
"function_declaration": "def find_all_cliques(edges):",
"function_name": "find_all_cliques... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def find_all_cliques(edges):\n \"\"\"\n Finds all maximal cliques in an undirected graph using the Bron-Kerbosch algorithm.\n\n Parameters:\n edge... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00001961",
"row_id": 1961,
"seed_ids": "[236]"
} | 0.514368 | Data_Structure_1961 | I | [
"bron_kerbosch",
"find_all_cliques"
] | 2 | [
[
"find_all_cliques",
"bron_kerbosch"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 5648529a706b7cbbc511c8cbba35c778963ca3ba | b75f97d23d8a0a62603aa0b9f760100d26f4dc8d | |||
v1.0 | instruct | Data_Structure | Data_Structure_1996_I | ### Pancake Sorting Challenge
Pancake sorting is a fascinating algorithm that operates similarly to the game of sorting pancakes on a grill by flipping them with a spatula. The goal is to sort an array of numbers using only a series of flips.
A flip reverses the order of the elements in a prefix of the array, which m... | from typing import List
def flip(arr: List[int], k: int) -> None:
"""
Flip function to reverse the order of the first k elements of the array
"""
arr[:k] = arr[:k][::-1]
def pancake_sort(arr: List[int]) -> List[int]:
"""
Perform pancake sorting on the input array `arr` and return the sorted ar... | from solution import pancake_sort
def test_pancake_sort_normal_case():
assert pancake_sort([3, 2, 4, 1]) == [1, 2, 3, 4]
def test_pancake_sort_already_sorted():
assert pancake_sort([1, 2, 3, 4]) == [1, 2, 3, 4]
def test_pancake_sort_reverse_sorted():
assert pancake_sort([4, 3, 2, 1]) == [1, 2, 3, 4]
def... | [
{
"docstring": "Flip function to reverse the order of the first k elements of the array",
"function_declaration": "def flip(arr, k):",
"function_name": "flip",
"parameter_list": "(arr, k)"
},
{
"docstring": "Perform pancake sorting on the input array `arr` and return the sorted array.",
... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def flip(arr, k):\n \"\"\"\n Flips the first k elements of the array.\n \"\"\"\n return arr[:k][::-1] + arr[k:]\n\ndef find_max(arr, n):\n \"\"... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00001996",
"row_id": 1996,
"seed_ids": "[9]"
} | 0.71598 | Data_Structure_1996 | I | [
"flip",
"pancake_sort"
] | 2 | [
[
"pancake_sort",
"flip"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 6c006e30164f47903c625bd2850661f7e87446ee | 4e32c3db6212aaef1129ce91a390e6db57cd14fc | |||
v1.0 | instruct | Data_Structure | Data_Structure_2004_I | ### Question
#### Scenario
You are working on a problem that requires you to identify Krishnamurthy numbers within a given range. Your task is to write a function that can efficiently determine if numbers in that range are Krishnamurthy numbers.
#### Task
Write a function `find_krishnamurthy_numbers_in_range(start: i... | from typing import List
def find_factorial(n: int) -> int:
if n == 0 or n == 1:
return 1
result = 1
for i in range(2, n + 1):
result *= i
return result
# Precompute the factorials of digits 0-9
factorials = {i: find_factorial(i) for i in range(10)}
def is_krishnamurthy_number(n: int) ... | from solution import find_krishnamurthy_numbers_in_range
def test_find_krishnamurthy_numbers_in_range_1_to_150():
assert find_krishnamurthy_numbers_in_range(1, 150) == [1, 2, 145]
def test_find_krishnamurthy_numbers_in_range_100_to_50000():
assert find_krishnamurthy_numbers_in_range(100, 50000) == [145, 40585... | [
{
"docstring": null,
"function_declaration": "def find_factorial(n):",
"function_name": "find_factorial",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def is_krishnamurthy_number(n):",
"function_name": "is_krishnamurthy_number",
"parameter_list": "(n)"... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\n# Precompute factorial values for digits 0-9\nfactorials = [1] * 10\nfor i in range(2, 10):\n factorials[i] = factorials[i-1] * ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00002004",
"row_id": 2004,
"seed_ids": "[142]"
} | 0.545554 | Data_Structure_2004 | I | [
"find_factorial",
"is_krishnamurthy_number",
"find_krishnamurthy_numbers_in_range"
] | 3 | [
[
"find_krishnamurthy_numbers_in_range",
"is_krishnamurthy_number"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 0f79aa5a245f0eaba008f131b69312c4158ab1e5 | a54dcdb1e0b5bef95bfed3e7c77ffb6f09308946 | |||
v1.0 | instruct | Data_Structure | Data_Structure_2006_I | ### Problem Description
You are tasked with implementing the Interpolation Search algorithm, but with additional functionality to safeguard against performance degradation caused by non-uniform data distributions. Your enhanced version should switch to Binary Search if the calculated probable position is out of expect... | from typing import List
def binary_search(array: List[int], search_key: int) -> int:
low, high = 0, len(array) - 1
while low <= high:
mid = (low + high) // 2
if array[mid] == search_key:
return mid
elif array[mid] < search_key:
low = mid + 1
else:
... | from solution import enhanced_interpolation_search
def test_enhanced_interpolation_search_found():
array = [10, 12, 14, 17, 20, 21]
search_key = 17
assert enhanced_interpolation_search(array, search_key, 2) == 3
def test_enhanced_interpolation_search_not_found():
array = [1, 3, 5, 7, 8, 9, 11]
sea... | [
{
"docstring": null,
"function_declaration": "def binary_search(array, search_key):",
"function_name": "binary_search",
"parameter_list": "(array, search_key)"
},
{
"docstring": null,
"function_declaration": "def enhanced_interpolation_search(array, search_key, switch_threshold=3):",
... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef binary_search(array: List[int], search_key: int) -> int:\n low, high = 0, len(array) - 1\n while low <= high:\n mi... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00002006",
"row_id": 2006,
"seed_ids": "[192]"
} | 0.547723 | Data_Structure_2006 | I | [
"binary_search",
"enhanced_interpolation_search"
] | 2 | [
[
"enhanced_interpolation_search",
"binary_search"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 161832387fd356a09db55ed250d78abf2cf2a899 | dfda14880f3bdf9e1a604356603afde22a9e847a | |||
v1.0 | instruct | Data_Structure | Data_Structure_2056_I | Given an array of floating-point numbers uniformly distributed over the range [0, 1), implement a bucket sort algorithm to sort the array.
### Problem Description
**Function Signature**: `def bucket_sort(arr: List[float]) -> List[float]`
Write a Python function that sorts an array of floating-point numbers using the... | from typing import List
def insertion_sort(arr: List[float]) -> List[float]:
for i in range(1, len(arr)):
key = arr[i]
j = i - 1
while j >= 0 and key < arr[j]:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
return arr
def bucket_sort(arr: List[float]) -> Li... | from solution import bucket_sort
def test_bucket_sort_basic():
input_array = [0.78, 0.17, 0.39, 0.26, 0.72, 0.94, 0.21, 0.12, 0.23, 0.68]
expected = [0.12, 0.17, 0.21, 0.23, 0.26, 0.39, 0.68, 0.72, 0.78, 0.94]
assert bucket_sort(input_array) == expected
def test_bucket_sort_empty():
assert bucket_sort... | [
{
"docstring": null,
"function_declaration": "def insertion_sort(arr):",
"function_name": "insertion_sort",
"parameter_list": "(arr)"
},
{
"docstring": null,
"function_declaration": "def bucket_sort(arr):",
"function_name": "bucket_sort",
"parameter_list": "(arr)"
}
] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef insertion_sort(arr: List[float]) -> List[float]:\n for i in range(1, len(arr)):\n key = arr[i]\n j = i - 1\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00002056",
"row_id": 2056,
"seed_ids": "[26]"
} | 0.565332 | Data_Structure_2056 | I | [
"insertion_sort",
"bucket_sort"
] | 2 | [
[
"bucket_sort",
"insertion_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 024975bf457e38a44c35d21f2b12f44a5368e57e | 7ccdba1bf9c0ceffd2d72a710db48ae635a118ed | |||
v1.0 | instruct | Data_Structure | Data_Structure_2117_I | ### Palindromic Substring Partitioning
#### Objective
Design a function that computes all ways to part a given string into substrings where each substring is a palindrome. As a subsequent task, improve the performance of this function using dynamic programming.
#### Scenario
You are working on a text processing tool ... | def is_palindrome(s):
return s == s[::-1]
def palindromic_substrings(s):
def dfs(start, path, result):
if start == len(s):
result.append(path)
return
for end in range(start + 1, len(s) + 1):
if is_palindrome(s[start:end]):
dfs(end, path + [s[s... | def test_palindromic_substrings():
assert sorted(palindromic_substrings('abcbab')) == sorted([['a', 'bcb', 'a', 'b'], ['a', 'b', 'c', 'bab'], ['a', 'b', 'c', 'b', 'a', 'b'], ['abcba', 'b']])
assert palindromic_substrings('a') == [['a']]
assert palindromic_substrings('') == [[]]
def test_palindromic_substri... | [
{
"docstring": null,
"function_declaration": "def is_palindrome(s):",
"function_name": "is_palindrome",
"parameter_list": "(s)"
},
{
"docstring": null,
"function_declaration": "def palindromic_substrings(s):",
"function_name": "palindromic_substrings",
"parameter_list": "(s)"
}... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_palindrome(s):\n \"\"\"\n Helper function that checks if a string is a palindrome.\n \"\"\"\n return s == s[::-1]\n\ndef palindromic_substr... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00002117",
"row_id": 2117,
"seed_ids": "[113]"
} | 0.775159 | Data_Structure_2117 | I | [
"is_palindrome",
"palindromic_substrings",
"palindromic_substrings_dp"
] | 3 | [
[
"palindromic_substrings",
"is_palindrome"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | f59c15579ee654bf73d038663d7c886bba2585c0 | d322817de2765a51b93cf77718279f40a0cbbbe5 | |||
v1.0 | instruct | Data_Structure | Data_Structure_2190_I | ## Problem Statement
You are given a matrix `mat` of size `n x n` and an integer `k`. Your task is to implement a function that computes the `k`-th power of the matrix `mat`, denoted as `mat^k`. To achieve this, you should leverage matrix exponentiation by repeated squaring for efficiency.
### Function Signature
```py... | def matrix_multiply(mat1, mat2):
n = len(mat1)
result = [[0] * n for _ in range(n)]
for i in range(n):
for j in range(n):
for k in range(n):
result[i][j] += mat1[i][k] * mat2[k][j]
return result
def matrix_power(mat, k):
"""
Computes the k-th power of a given... | import pytest
from solution import matrix_power
def test_matrix_power_identity():
mat = [
[1, 2],
[3, 4]
]
k = 0
expected = [
[1, 0],
[0, 1]
]
assert matrix_power(mat, k) == expected
def test_matrix_power_one():
mat = [
[1, 2],
[3, 4]
]
... | [
{
"docstring": null,
"function_declaration": "def matrix_multiply(mat1, mat2):",
"function_name": "matrix_multiply",
"parameter_list": "(mat1, mat2)"
},
{
"docstring": "Computes the k-th power of a given matrix mat using matrix exponentiation by squaring.\n\nParameters:\n- mat (list of list ... | [
0,
0,
0,
1,
1,
0,
0,
1,
0,
1
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def matrix_mult(A, B):\n \"\"\"\n Multiplies two matrices A and B.\n \"\"\"\n n = len(A)\n C = [[0] * n for _ in range(n)]\n for i in range(... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00002190",
"row_id": 2190,
"seed_ids": "[340]"
} | 0.543271 | Data_Structure_2190 | I | [
"matrix_multiply",
"matrix_power"
] | 2 | [
[
"matrix_power",
"matrix_multiply"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | d0d2904f24b6a5db7a6449516edcdd42b124ca5f | 2e74320c22cb15ab0c89b084e24e701476eb3bd5 | |||
v1.0 | instruct | Data_Structure | Data_Structure_2191_I | You have been tasked to implement the Radix Sort algorithm to sort a list of non-negative integers without using any built-in sort functions. The algorithm should process each digit of the number starting from the least significant digit to the most significant digit.
### Function Definition:
Create a function `radix... | def counting_sort_for_radix(arr, exp, simulation, iteration):
n = len(arr)
output = [0] * n
count = [0] * 10
for i in range(n):
index = (arr[i] // exp) % 10
count[index] += 1
for i in range(1, 10):
count[i] += count[i - 1]
i = n - 1
while i >= 0:
index = (a... | from solution import radix_sort
def test_radix_sort_basic():
arr = [170, 45, 75, 90, 802, 24, 2, 66]
sorted_arr = [2, 24, 45, 66, 75, 90, 170, 802]
assert radix_sort(arr) == sorted_arr
def test_radix_sort_empty():
assert radix_sort([]) == []
def test_radix_sort_single_element():
assert radix_sort... | [
{
"docstring": null,
"function_declaration": "def counting_sort_for_radix(arr, exp, simulation, iteration):",
"function_name": "counting_sort_for_radix",
"parameter_list": "(arr, exp, simulation, iteration)"
},
{
"docstring": null,
"function_declaration": "def radix_sort(arr, simulation=... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef counting_sort(arr: List[int], exp: int, simulation: bool, iteration: int):\n n = len(arr)\n \n output = [0] * n \n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00002191",
"row_id": 2191,
"seed_ids": "[15]"
} | 0.627498 | Data_Structure_2191 | I | [
"counting_sort_for_radix",
"radix_sort"
] | 2 | [
[
"radix_sort",
"counting_sort_for_radix"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | bad5e8c38ce0919fd6d20a8e773bbcb5136df4ba | 07bd8a28be3d60a8a4ff92cd7a8ee57b9d3fc488 | |||
v1.0 | instruct | Data_Structure | Data_Structure_2229_I | You are given two large sparse vectors, potentially with millions of elements but only a small percentage of them being non-zero. To efficiently store these vectors and perform operations on them, a better data representation is required.
Write a Python function `sparse_vector_dot_product(vector1, vector2)` that compu... | from typing import List, Tuple
def vector_to_index_value_list(vector: List[float]) -> List[Tuple[int, float]]:
"""
Converts a dense vector to a sparse vector represented as a list of index-value pairs.
"""
return [(i, value) for i, value in enumerate(vector) if value != 0.0]
def sparse_vector_dot_prod... | from solution import sparse_vector_dot_product, vector_to_index_value_list
def test_vector_to_index_value_list():
assert vector_to_index_value_list([1.0, 0.0, 0.0, 3.0, 0.0]) == [(0, 1.0), (3, 3.0)]
assert vector_to_index_value_list([0.0, 0.0, 0.0]) == []
assert vector_to_index_value_list([0.0, 2.0, 0.0, 0... | [
{
"docstring": "Converts a dense vector to a sparse vector represented as a list of index-value pairs.",
"function_declaration": "def vector_to_index_value_list(vector):",
"function_name": "vector_to_index_value_list",
"parameter_list": "(vector)"
},
{
"docstring": "Computes the dot product ... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List, Tuple\n\ndef vector_to_index_value_list(vector: List[float]) -> List[Tuple[int, float]]:\n \"\"\"\n Converts a dense vector (li... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00002229",
"row_id": 2229,
"seed_ids": "[341]"
} | 0.440663 | Data_Structure_2229 | I | [
"vector_to_index_value_list",
"sparse_vector_dot_product"
] | 2 | [
[
"sparse_vector_dot_product",
"vector_to_index_value_list"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 5b29b67685b4d9236fb3120d701324acb7ebf10f | c4ac3e8c0fba21afd396ff0c06420cdd51789576 | |||
v1.0 | instruct | Data_Structure | Data_Structure_2234_I | ### Pancake Sort Challenge
As an aspiring programmer, you have encountered various sorting algorithms. Today, you will implement an interesting, lesser-known one called **Pancake Sort**. This is a sorting algorithm where you pick the maximum element and move it to its position by flipping (reversing) the subarray.
##... | def flip(arr, k):
"""
Reverses the sub-array arr[0:k+1]
"""
left = 0
right = k
while left < right:
arr[left], arr[right] = arr[right], arr[left]
left += 1
right -= 1
def find_max_index(arr, n):
"""
Finds the index of the maximum element in arr[0:n]
"""
ma... | from solution import pancake_sort
def test_pancake_sort_example1():
assert pancake_sort([3, 2, 4, 1]) == [1, 2, 3, 4]
def test_pancake_sort_example2():
assert pancake_sort([1, 2, 3]) == [1, 2, 3]
def test_pancake_sort_empty():
assert pancake_sort([]) == []
def test_pancake_sort_single_element():
ass... | [
{
"docstring": "Reverses the sub-array arr[0:k+1]",
"function_declaration": "def flip(arr, k):",
"function_name": "flip",
"parameter_list": "(arr, k)"
},
{
"docstring": "Finds the index of the maximum element in arr[0:n]",
"function_declaration": "def find_max_index(arr, n):",
"funct... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef flip(arr: List[int], k: int) -> None:\n \"\"\"\n Helper function to reverse the array up to index k.\n \"\"\"\n arr... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00002234",
"row_id": 2234,
"seed_ids": "[9]"
} | 0.684874 | Data_Structure_2234 | I | [
"flip",
"find_max_index",
"pancake_sort"
] | 3 | [
[
"pancake_sort",
"find_max_index"
],
[
"pancake_sort",
"flip"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 0a5fb761298632306c9310e7a45d0802d513fa6f | d0bc1499179a38d52dbf748aa029cdba3d91e1ef | |||
v1.0 | instruct | Data_Structure | Data_Structure_2239_I | ### Question:
As a programmer, your task is to enhance the Interpolation Search algorithm to address some of its limitations while maintaining its performance advantages.
#### Requirements:
1. Improve the function to handle and return appropriate results for all edge cases, specifically when:
- The array is empty.... | from typing import List
def interpolation_search(array: List[int], search_key: int) -> int:
low = 0
high = len(array) - 1
while low <= high and search_key >= array[low] and search_key <= array[high]:
if low == high:
if array[low] == search_key:
return low
re... | from solution import enhanced_interpolation_search
def test_empty_array():
assert enhanced_interpolation_search([], 10) == -1
def test_array_with_identical_elements():
assert enhanced_interpolation_search([10, 10, 10, 10], 10) == 0
assert enhanced_interpolation_search([10, 10, 10, 10], 5) == -1
def test_... | [
{
"docstring": null,
"function_declaration": "def interpolation_search(array, search_key):",
"function_name": "interpolation_search",
"parameter_list": "(array, search_key)"
},
{
"docstring": null,
"function_declaration": "def binary_search(array, search_key, low, high):",
"function_... | [
1,
0,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef enhanced_interpolation_search(array: List[int], search_key: int) -> int:\n \"\"\"\n Enhanced Interpolation Search:\n -... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00002239",
"row_id": 2239,
"seed_ids": "[192]"
} | 0.489576 | Data_Structure_2239 | I | [
"interpolation_search",
"binary_search",
"enhanced_interpolation_search"
] | 3 | [
[
"enhanced_interpolation_search",
"binary_search"
],
[
"enhanced_interpolation_search",
"interpolation_search"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | bdcc8cf4570030925e49b7afa1cfeae3528fdfd4 | 73740a1a217fe1b9337732a95d1f860affe82124 | |||
v1.0 | instruct | Data_Structure | Data_Structure_2249_I | Implement an Efficient Sorted Insert
You are tasked with writing a function `sorted_insert` that takes a sorted list and a value, and returns a new list with the value inserted at the correct position to maintain the sorted order. Use the `search_insert` helper function provided.
#### Function Signature
```python
def ... | from typing import List
def search_insert(array: List[int], val: int) -> int:
"""
Given a sorted array and a value, this function returns the index where val
should be inserted to maintain the sort order.
"""
left, right = 0, len(array)
while left < right:
mid = (left + right) // 2
... | from solution import sorted_insert
def test_sorted_insert_existing_value():
assert sorted_insert([1, 3, 5, 6], 5) == [1, 3, 5, 5, 6]
def test_sorted_insert_new_value_middle():
assert sorted_insert([1, 3, 5, 6], 2) == [1, 2, 3, 5, 6]
def test_sorted_insert_new_value_end():
assert sorted_insert([1, 3, 5, 6... | [
{
"docstring": "Given a sorted array and a value, this function returns the index where val \nshould be inserted to maintain the sort order.",
"function_declaration": "def search_insert(array, val):",
"function_name": "search_insert",
"parameter_list": "(array, val)"
},
{
"docstring": "Inser... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef search_insert(array: List[int], val: int) -> int:\n \"\"\"\n Helper function to find the index at which 'val' should be i... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00002249",
"row_id": 2249,
"seed_ids": "[199]"
} | 0.62283 | Data_Structure_2249 | I | [
"search_insert",
"sorted_insert"
] | 2 | [
[
"sorted_insert",
"search_insert"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 9e862cc0104147a699f78f6fa1a5251cbd0094ae | 4d43b6950bcf9261f7893fb23439e6bc5cfea5c2 | |||
v1.0 | instruct | Data_Structure | Data_Structure_2304_I | ### Longest Prefix Suffix (using KMP Algorithm)
You are given two strings, `haystack` and `needle`. Implement the `strStr()` function that returns the index of the first occurrence of `needle` in `haystack`, or `-1` if `needle` is not part of `haystack`.
To solve this problem more efficiently than the brute force app... | def computeLPS(pattern):
"""
Computes the Longest Prefix Suffix (LPS) array for the given pattern.
"""
M = len(pattern)
lps = [0] * M
length = 0
i = 1
while i < M:
if pattern[i] == pattern[length]:
length += 1
lps[i] = length
i += 1
el... | from solution import kmp_search
def test_kmp_search_found():
"""Test case where the needle is found in the haystack."""
assert kmp_search("hello", "ll") == 2
def test_kmp_search_not_found():
"""Test case where the needle is not found in the haystack."""
assert kmp_search("aaaaa", "bba") == -1
def tes... | [
{
"docstring": "Computes the Longest Prefix Suffix (LPS) array for the given pattern.",
"function_declaration": "def computeLPS(pattern):",
"function_name": "computeLPS",
"parameter_list": "(pattern)"
},
{
"docstring": "Returns the index of the first occurrence of `needle` in `haystack`, or ... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def kmp_search(haystack: str, needle: str) -> int:\n # Edge case: if needle is an empty string\n if not needle:\n return 0\n\n # Function to c... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00002304",
"row_id": 2304,
"seed_ids": "[86]"
} | 0.662055 | Data_Structure_2304 | I | [
"computeLPS",
"kmp_search"
] | 2 | [
[
"kmp_search",
"computeLPS"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 6a5a5503f4ae08b3c23aa73f2b3457a8761b52e4 | 27e2be27d57ebdd08804cd765e642c9fb6eb899d | |||
v1.0 | instruct | Data_Structure | Data_Structure_2336_I | ### Question: Implementing Optimized Insertion Sort
**Scenario**:
You are working as a software engineer at a logistics company that frequently deals with small datasets of shipment weights that need to be sorted for processing. You've been tasked with optimizing the sorting of these weights using an insertion sort th... | from typing import List
def binary_search(arr: List[int], val: int, start: int, end: int) -> int:
while start < end:
mid = (start + end) // 2
if arr[mid] < val:
start = mid + 1
else:
end = mid
return start
def optimized_insertion_sort(arr: List[int]) -> List[int... | from solution import optimized_insertion_sort
def test_optimized_insertion_sort():
# Test empty array
assert optimized_insertion_sort([]) == []
# Test single element array
assert optimized_insertion_sort([1]) == [1]
# Test already sorted array
assert optimized_insertion_sort([1, 2, 3, 4, 5]) ... | [
{
"docstring": null,
"function_declaration": "def binary_search(arr, val, start, end):",
"function_name": "binary_search",
"parameter_list": "(arr, val, start, end)"
},
{
"docstring": null,
"function_declaration": "def optimized_insertion_sort(arr):",
"function_name": "optimized_inse... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_data_structure_50000_1740122759_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef binary_search(arr: List[int], val: int, start: int, end: int) -> int:\n \"\"\"\n Helper function that uses binary search ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00002336",
"row_id": 2336,
"seed_ids": "[7]"
} | 0.574068 | Data_Structure_2336 | I | [
"binary_search",
"optimized_insertion_sort"
] | 2 | [
[
"optimized_insertion_sort",
"binary_search"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | efde378127c063cc99216cace3faf02b149136fd | dce75e76789ee21904016dbad311395595e3e737 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.