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_32071_I | ### Coding Assessment Question
#### Context and Scenario:
You are building a hospital management system where patient records are stored based on their unique identifiers. The list of patient IDs is sorted in ascending order. To ensure efficient data retrieval and updating, you need to implement search and modificatio... | def binary_search(collection, item):
"""
Searches for an item in a sorted collection using binary search.
:param collection: A list of integers in ascending order.
:param item: The integer item to search for.
:return: The index of the item if found, otherwise -1.
"""
left, right = 0, len(co... | from solution import binary_search, sorted_deletion
def test_binary_search_found():
collection = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
assert binary_search(collection, 14) == 6
assert binary_search(collection, 2) == 0
assert binary_search(collection, 20) == 9
def test_binary_search_not_found():
col... | [
{
"docstring": "Searches for an item in a sorted collection using binary search.\n\n:param collection: A list of integers in ascending order.\n:param item: The integer item to search for.\n:return: The index of the item if found, otherwise -1.",
"function_declaration": "def binary_search(collection, item):"... | [
1,
1,
1,
1,
1,
1,
1,
0,
1,
1
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def binary_search(collection, item):\n \"\"\"\n Searches for an item in a sorted collection using binary search.\n\n :param collection: A list of intege... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000032071",
"row_id": 32071,
"seed_ids": "[5367]"
} | 0.503042 | Algorithm_32071 | I | [
"binary_search",
"sorted_deletion"
] | 2 | [
[
"sorted_deletion",
"binary_search"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a27dfbb61bd61b214221c52430428be3e28f25b9 | 6019536eaf73586775f709ae77f45ed15e712ca1 | |||
v1.0 | instruct | Algorithm | Algorithm_32075_I | ### Question
You are given a problem to list all the pairs of prime numbers (p1, p2) such that p1 and p2 are twin primes and both lie within the range from 2 up to a specified limit. Twin primes are pairs of prime numbers that differ by 2 (e.g., (3, 5), (11, 13)).
#### Problem Statement
Write a function `list_twin_p... | from typing import List, Tuple
def sieve_of_eratosthenes(limit: int) -> List[bool]:
"""
Generates a list of boolean values corresponding to the primality of numbers from 0 to limit.
"""
is_prime = [True] * (limit + 1)
is_prime[0] = is_prime[1] = False # 0 and 1 are not prime numbers
p = 2
... | from solution import list_twin_primes
def test_list_twin_primes_small_range():
assert list_twin_primes(20) == [(3, 5), (5, 7), (11, 13), (17, 19)]
def test_list_twin_primes_medium_range():
assert list_twin_primes(50) == [(3, 5), (5, 7), (11, 13), (17, 19), (29, 31), (41, 43)]
def test_list_twin_primes_no_twi... | [
{
"docstring": "Generates a list of boolean values corresponding to the primality of numbers from 0 to limit.",
"function_declaration": "def sieve_of_eratosthenes(limit):",
"function_name": "sieve_of_eratosthenes",
"parameter_list": "(limit)"
},
{
"docstring": "Returns a list of all pairs of... | [
0,
1,
1,
1,
0,
0,
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": "from typing import List, Tuple\n\ndef sieve_of_eratosthenes(limit: int) -> List[int]:\n \"\"\"Returns a list of all primes up to the given limit using the Sie... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "0000032075",
"row_id": 32075,
"seed_ids": "[3101]"
} | 0.725534 | Algorithm_32075 | I | [
"sieve_of_eratosthenes",
"list_twin_primes"
] | 2 | [
[
"list_twin_primes",
"sieve_of_eratosthenes"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 8ee715d2591f6b99ab5afffd50137caf3d100c78 | e9b6f30159594c4a40090bc7f49bbac2ecb5aa4b | |||
v1.0 | instruct | Algorithm | Algorithm_32183_I | ### Coding Assessment Question: Custom XOR Encryption and Decryption
You've recently learned about basic encryption techniques and XOR operations in computer science. Now, your task is to apply this knowledge in creating a custom encryption-decryption algorithm using the XOR operation.
#### Scenario
You are working o... | def custom_xor_encrypt(message: bytes, key: bytes) -> bytes:
"""
Encrypts the message using XOR with the provided key.
"""
if not key:
return message
encrypted_message = bytearray()
key_length = len(key)
for i, byte in enumerate(message):
encrypted_message.append(byte ^ ... | from solution import custom_xor_encrypt, custom_xor_decrypt
def test_empty_message():
assert custom_xor_encrypt(b"", b"key") == b""
assert custom_xor_decrypt(b"", b"key") == b""
def test_empty_key():
message = b"hello"
assert custom_xor_encrypt(message, b"") == message
assert custom_xor_decrypt(me... | [
{
"docstring": "Encrypts the message using XOR with the provided key.",
"function_declaration": "def custom_xor_encrypt(message, key):",
"function_name": "custom_xor_encrypt",
"parameter_list": "(message, key)"
},
{
"docstring": "Decrypts the message that was encrypted using XOR with the pro... | [
0,
1,
1,
1,
0,
1,
1,
1,
0,
1
] | 7 | easy | 0.7 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def custom_xor_encrypt(message: bytes, key: bytes) -> bytes:\n \"\"\"\n Encrypts the message using XOR with the given key.\n If the message is longer th... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000032183",
"row_id": 32183,
"seed_ids": "[195]"
} | 0.483492 | Algorithm_32183 | I | [
"custom_xor_encrypt",
"custom_xor_decrypt"
] | 2 | [
[
"custom_xor_decrypt",
"custom_xor_encrypt"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 5ccf4360ce3daedd121a7c7107b4bf023beecb70 | b7bc96742dc619f59bf213d2a110783381dd78a6 | |||
v1.0 | instruct | Algorithm | Algorithm_32190_I | ### Question: Implement Merge Sort for Linked Lists
#### Problem Statement
Your task is to implement the merge sort algorithm for sorting a singly linked list. Merge sort is a divide and conquer algorithm that splits the list into halves, recursively sorts each half, and then merges the sorted halves.
You need to def... | class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def merge_sort(head: ListNode) -> ListNode:
if not head or not head.next:
return head
def find_middle(head):
slow, fast = head, head.next
while fast and fast.next:
slow = slow.next
... | from solution import ListNode, merge_sort
def list_to_linked_list(lst):
if not lst:
return None
head = ListNode(lst[0])
current = head
for value in lst[1:]:
current.next = ListNode(value)
current = current.next
return head
def linked_list_to_list(head):
lst = []
whi... | [] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 10 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "class ListNode:\n def __init__(self, x):\n self.val = x\n self.next = None\n\ndef merge_sort(head: ListNode) -> ListNode:\n if not head or no... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000032190",
"row_id": 32190,
"seed_ids": "[2168]"
} | 0.512881 | Algorithm_32190 | I | [
"merge_sort",
"merge"
] | 2 | [
[
"merge_sort",
"merge"
]
] | 1 | [] | false | [
"ListNode"
] | true | pytest | true | [] | true | 7c19da0c928b6baa5aacaeea9ef9acc67e5b6d56 | 3208e3bb8b925aef35e6a27652e5286cfd780294 | |||
v1.0 | instruct | Algorithm | Algorithm_32215_I | ### Scenario
You are developing a text editor that features an automatic spelling correction system. One of the most critical components of this system is identifying the most probable correct spelling of a given misspelled word from a provided dictionary of words.
### Task
Implement a function that, given a misspelle... | from typing import List
def levenshtein_distance(a: str, b: str) -> int:
"""
Compute the Levenshtein distance between two strings.
"""
if len(a) < len(b):
return levenshtein_distance(b, a)
if len(b) == 0:
return len(a)
previous_row = range(len(b) + 1)
for i, c1 in ... | from solution import spell_correct, levenshtein_distance
def test_levenshtein_distance():
assert levenshtein_distance("kitten", "sitting") == 3
assert levenshtein_distance("flaw", "lawn") == 2
assert levenshtein_distance("", "empty") == 5
assert levenshtein_distance("same", "same") == 0
assert leve... | [
{
"docstring": "Compute the Levenshtein distance between two strings.",
"function_declaration": "def levenshtein_distance(a, b):",
"function_name": "levenshtein_distance",
"parameter_list": "(a, b)"
},
{
"docstring": "Finds the word in the dictionary with the smallest Levenshtein distance to... | [
1,
0,
1,
1,
0,
1,
1,
1,
0,
1
] | 7 | easy | 0.7 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef levenshtein_distance(a: str, b: str) -> int:\n \"\"\"\n Calculate the Levenshtein distance between two strings a and b.\n ... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "0000032215",
"row_id": 32215,
"seed_ids": "[4162]"
} | 0.602434 | Algorithm_32215 | I | [
"levenshtein_distance",
"spell_correct"
] | 2 | [
[
"spell_correct",
"levenshtein_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 04a44226b24ff4174c0a2a301f08abe7a47c3d10 | 29b98def939e5f640ffdab4e4346b6c36d416530 | |||
v1.0 | instruct | Algorithm | Algorithm_32285_I | ### Find the Longest Word in Each Sentence
You are given a function `longest_word(sentence)` that returns the longest word in a given sentence. Your task is to implement the function `longest_words(sentences: list)` which accepts a list of sentences and returns a list of the longest words for each sentence.
### Const... | def longest_word(sentence: str) -> str:
words = sentence.split()
longest = ""
for word in words:
if len(word) > len(longest):
longest = word
elif len(word) == len(longest):
continue # continue to ensure first occurrence is taken
return longest
def longest_words(... | from solution import longest_word, longest_words
def test_single_sentence():
assert longest_word("The quick brown fox") == "quick"
assert longest_word("jumps over the lazy dog") == "jumps"
assert longest_word("Hello world") == "Hello"
assert longest_word("Equal size words have first") == "Equal"
def t... | [
{
"docstring": null,
"function_declaration": "def longest_word(sentence):",
"function_name": "longest_word",
"parameter_list": "(sentence)"
},
{
"docstring": "Find the longest word in each sentence.\n\n:param sentences: List of sentences\n:return: List of the longest words from each sentence... | [
1,
0,
1,
0,
0,
0,
0,
0,
0
] | 2 | hard | 0.222 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def longest_word(sentence: str) -> str:\n words = sentence.split()\n longest = \"\"\n for word in words:\n if len(word) > len(longest):\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "0000032285",
"row_id": 32285,
"seed_ids": "[3717]"
} | 0.739998 | Algorithm_32285 | I | [
"longest_word",
"longest_words"
] | 2 | [
[
"longest_words",
"longest_word"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 8e058712abb78b8ff8e22873c5478ad8e59bfaa5 | 471e6c360dc5e294bbf658cb29f4cd5ba4d7f9d8 | |||
v1.0 | instruct | Algorithm | Algorithm_32367_I | ### Escape the Maze with Dijkstra
Implement the Dijkstra algorithm in Python to find the shortest path through a maze represented by a grid. The maze consists of open cells and blocked cells. You will be provided with a 2D list representing the maze grid, where 0 represents an open cell that can be traversed, and 1 rep... | import heapq
from typing import List, Tuple
def is_valid_position(position, grid):
r, c = position
return 0 <= r < len(grid) and 0 <= c < len(grid[0]) and grid[r][c] == 0
def escape_maze(grid: List[List[int]], start: Tuple[int, int], goal: Tuple[int, int]) -> List[Tuple[int, int]]:
rows, cols = len(grid),... | import pytest
from solution import escape_maze
def test_escape_maze_simple_path():
grid = [
[0, 1],
[0, 0]
]
start = (0, 0)
goal = (1, 1)
expected_path = [(0, 0), (1, 0), (1, 1)]
assert escape_maze(grid, start, goal) == expected_path
def test_escape_maze_no_path():
grid = [... | [
{
"docstring": null,
"function_declaration": "def is_valid_position(position, grid):",
"function_name": "is_valid_position",
"parameter_list": "(position, grid)"
},
{
"docstring": null,
"function_declaration": "def escape_maze(grid, start, goal):",
"function_name": "escape_maze",
... | [
0,
1,
0,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.111 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import heapq\nfrom typing import List, Tuple\n\ndef escape_maze(grid: List[List[int]], start: Tuple[int, int], goal: Tuple[int, int]) -> List[Tuple[int, int]]:\n... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "0000032367",
"row_id": 32367,
"seed_ids": "[406]"
} | 0.671096 | Algorithm_32367 | I | [
"is_valid_position",
"escape_maze"
] | 2 | [
[
"escape_maze",
"is_valid_position"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | efc56f418785a5ee70318f95d5cfbe6f44cd47b6 | 7affc977dc0d10d2febd6fc0cd412acbef397929 | |||
v1.0 | instruct | Algorithm | Algorithm_32444_I | ### Coding Assessment: Implementing K-Means Clustering Algorithm
**Objective**: Implement the K-Means clustering algorithm to group a set of instances into specified clusters. You will use the provided utility functions as a reference to create new components to demonstrate your understanding.
### Problem Statement
G... | import random
import math
def initialize_centroids(features, k):
"""
Randomly initialize the centroids by selecting 'k' random features as initial centroids.
"""
return random.sample(features, k)
def assign_clusters(features, centroids):
"""
Assign each feature to the nearest centroid.
"""... | from solution import initialize_centroids, assign_clusters, update_centroids, k_means
def test_initialize_centroids():
features = [[1.0, 2.0], [1.5, 1.8], [5.0, 8.0], [8.0, 8.0], [1.2, 2.5], [8.2, 8.1]]
k = 2
centroids = initialize_centroids(features, k)
assert len(centroids) == k
for centroid in c... | [
{
"docstring": "Randomly initialize the centroids by selecting 'k' random features as initial centroids.",
"function_declaration": "def initialize_centroids(features, k):",
"function_name": "initialize_centroids",
"parameter_list": "(features, k)"
},
{
"docstring": "Assign each feature to th... | [
0,
1,
0,
1,
1,
1,
0,
1,
1,
1
] | 7 | easy | 0.7 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import random\n\ndef initialize_centroids(features, k):\n \"\"\"\n Returns k initial centroids randomly selected from the set of features.\n \"\"\"\n ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "0000032444",
"row_id": 32444,
"seed_ids": "[468]"
} | 0.67331 | Algorithm_32444 | I | [
"initialize_centroids",
"assign_clusters",
"update_centroids",
"euclidean_distance",
"k_means"
] | 5 | [
[
"assign_clusters",
"euclidean_distance"
],
[
"k_means",
"assign_clusters"
],
[
"k_means",
"initialize_centroids"
],
[
"k_means",
"update_centroids"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | f0db21759a23f35ed28c5cba891d87d07dc242a3 | 915040c33b236b6428f820146b1430ccf86e2964 | |||
v1.0 | instruct | Algorithm | Algorithm_32503_I | ### Question: Array Frequency Operations
You are required to implement two functions to analyze the frequency of elements in an array of integers.
#### Implement the Following Functions:
**1. Function `element_frequency(arr: list) -> dict`:**
* **Input**: A list of integers.
* **Output**: A dictionary where keys are... | def element_frequency(arr):
"""
Returns a dictionary where the keys are unique integers in the input list
and the values are the counts of their occurrences.
"""
if not arr:
raise ValueError("Input list is empty.")
frequency = {}
for element in arr:
if not isinstance(ele... | def test_element_frequency_normal():
assert element_frequency([1, 2, 2, 3, 3, 3, 4]) == {1: 1, 2: 2, 3: 3, 4: 1}
assert element_frequency([5, 5, 5, 5, 5]) == {5: 5}
def test_element_frequency_empty():
try:
element_frequency([])
except ValueError as e:
assert str(e) == "Input list is... | [
{
"docstring": "Returns a dictionary where the keys are unique integers in the input list\nand the values are the counts of their occurrences.",
"function_declaration": "def element_frequency(arr):",
"function_name": "element_frequency",
"parameter_list": "(arr)"
},
{
"docstring": "Returns t... | [
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 element_frequency(arr):\n \"\"\"\n Returns a dictionary where keys are the unique elements in the array\n and values are the counts of their occurre... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000032503",
"row_id": 32503,
"seed_ids": "[4188]"
} | 0.719765 | Algorithm_32503 | I | [
"element_frequency",
"most_frequent_element"
] | 2 | [
[
"most_frequent_element",
"element_frequency"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 084e805f018fdb2431ffdc11f3d34e9d42ef315e | a99e6db1684908e5cf6646bce15940776551a10d | |||
v1.0 | instruct | Algorithm | Algorithm_32519_I | ### [New Question] Prime Number and Matrix Manipulation
#### Objective
Given a matrix of integers, your task is to write a function that identifies all prime numbers within this matrix and replaces each prime number with its corresponding prime index, where the prime index of a prime number `p` is the count of prime n... | import numpy as np
def is_prime(n: int) -> bool:
"""
Check if a number is prime.
"""
if n <= 1:
return False
for i in range(2, int(np.sqrt(n)) + 1):
if n % i == 0:
return False
return True
def prime_index(n: int) -> int:
"""
Find number of primes less than o... | import numpy as np
from solution import replace_primes_with_indices
def test_replace_primes_with_indices():
matrix = np.array([
[2, 3, 4],
[5, 6, 7],
[8, 9, 10]
])
expected_output = np.array([
[1, 2, 4],
[3, 6, 4],
[8, 9, 10]
])
assert np.array_equal(... | [
{
"docstring": "Check if a number is prime.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Find number of primes less than or equal to n.",
"function_declaration": "def prime_index(n):",
"function_name": "prime_in... | [
1,
1,
0,
1,
1,
1,
1,
1,
1,
0
] | 8 | easy | 0.8 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import numpy as np\n\ndef is_prime(n: int) -> bool:\n if n <= 1:\n return False\n for i in range(2, int(np.sqrt(n)) + 1):\n if n % i == 0:\n ... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "0000032519",
"row_id": 32519,
"seed_ids": "[4660]"
} | 0.546666 | Algorithm_32519 | I | [
"is_prime",
"prime_index",
"replace_primes_with_indices"
] | 3 | [
[
"prime_index",
"is_prime"
],
[
"replace_primes_with_indices",
"is_prime"
],
[
"replace_primes_with_indices",
"prime_index"
]
] | 3 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | bab1f360dc5b8cb5cf4999e6d282270f24509cd9 | b42150efa216736017b50d8cbbdce73a58f7359c | |||
v1.0 | instruct | Algorithm | Algorithm_32532_I | ### Problem Statement
Given a collection of words and a specific word, find the longest word in the collection that can be constructed by deleting some characters of the specific word without rearranging the characters.
### Function Signature
```python
def find_longest_word(s: str, dictionary: List[str]) -> str:
```
... | from typing import List
def can_form_by_deleting(s: str, word: str) -> bool:
it = iter(s)
return all(char in it for char in word)
def find_longest_word(s: str, dictionary: List[str]) -> str:
possible_words = [
word for word in dictionary if can_form_by_deleting(s, word)
]
# Sort primarily ... | from solution import find_longest_word
def test_example_case():
s = "abpcplea"
dictionary = ["ale","apple","monkey","plea"]
assert find_longest_word(s, dictionary) == "apple"
def test_multiple_solution_lexicographically_smallest():
s = "abpcplea"
dictionary = ["a", "b", "c"]
assert find_longes... | [
{
"docstring": null,
"function_declaration": "def can_form_by_deleting(s, word):",
"function_name": "can_form_by_deleting",
"parameter_list": "(s, word)"
},
{
"docstring": null,
"function_declaration": "def find_longest_word(s, dictionary):",
"function_name": "find_longest_word",
... | [
1,
1,
0,
0,
1,
0,
1,
0,
0,
0
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef find_longest_word(s: str, dictionary: List[str]) -> str:\n def can_form(word):\n it = iter(s)\n return all(char i... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "0000032532",
"row_id": 32532,
"seed_ids": "[4556]"
} | 0.719061 | Algorithm_32532 | I | [
"can_form_by_deleting",
"find_longest_word"
] | 2 | [
[
"find_longest_word",
"can_form_by_deleting"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 670fba9640883d6cb66f59d2bd284fc46a59e675 | 61c283cdf23018c6cb8bed79ec23d903014692f1 | |||
v1.0 | instruct | Algorithm | Algorithm_32602_I | ## Question
Sorting algorithms form a fundamental part of computer science due to their efficiency and utility in data organization. Implement the Merge Sort algorithm, which sorts a given list of integers in ascending order.
### Function Signature
```python
def merge_sort(arr: list) -> list:
pass
```
### Input
*... | def merge_sort(arr: list) -> list:
if len(arr) <= 1:
return arr
# Split array into two halves
mid = len(arr) // 2
left_half = merge_sort(arr[:mid])
right_half = merge_sort(arr[mid:])
return merge(left_half, right_half)
def merge(left: list, right: list) -> list:
sorted_list = ... | from solution import merge_sort
def test_merge_sort_simple():
assert merge_sort([2, 1]) == [1, 2]
def test_merge_sort_with_duplicates():
assert merge_sort([5, 2, 9, 1, 5, 6]) == [1, 2, 5, 5, 6, 9]
def test_merge_sort_negative_numbers():
assert merge_sort([-12, 0, 45, -1, 56, 17, 8]) == [-12, -1, 0, 8, 17... | [
{
"docstring": null,
"function_declaration": "def merge_sort(arr):",
"function_name": "merge_sort",
"parameter_list": "(arr)"
},
{
"docstring": null,
"function_declaration": "def merge(left, right):",
"function_name": "merge",
"parameter_list": "(left, right)"
}
] | [
1,
1,
1,
1,
1,
1,
1,
1,
0
] | 8 | easy | 0.889 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def merge_sort(arr):\n \"\"\"\n Sorts the input list using the Merge Sort algorithm.\n \n Parameters:\n arr (list): List of integers to be sorted.... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "0000032602",
"row_id": 32602,
"seed_ids": "[2073]"
} | 0.657698 | Algorithm_32602 | I | [
"merge_sort",
"merge"
] | 2 | [
[
"merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 279b016baf9d4663a7aeb7d8e188adbf19626b3c | d12d5ecb5f4f9a07d715a1d741d71e26e0e2436c | |||
v1.0 | instruct | Algorithm | Algorithm_32631_I | ### Matrix Determinant Calculator
#### Context
You are tasked with developing a matrix calculator that determines the determinant of a square matrix. This function will be useful in various linear algebra applications such as solving systems of linear equations, finding inverse matrices, and more.
#### Task
Write a f... | from typing import List
def get_minor(matrix, i, j):
return [row[:j] + row[j+1:] for row in (matrix[:i] + matrix[i+1:])]
def calculate_determinant(matrix: List[List[float]]) -> float:
"""
Computes the determinant of a given square matrix.
Params:
- matrix (List[List[float]]): A list of lists repr... | import pytest
from solution import calculate_determinant
def test_1x1_matrix():
assert calculate_determinant([[5]]) == 5
def test_2x2_matrix():
assert calculate_determinant([[1, 2], [3, 4]]) == -2
def test_3x3_matrix():
assert calculate_determinant([[1, 2, 3], [0, 1, 4], [5, 6, 0]]) == 1
def test_4x4_ma... | [
{
"docstring": null,
"function_declaration": "def get_minor(matrix, i, j):",
"function_name": "get_minor",
"parameter_list": "(matrix, i, j)"
},
{
"docstring": "Computes the determinant of a given square matrix.\n\nParams:\n- matrix (List[List[float]]): A list of lists representing an NxN sq... | [
0,
0,
0,
0,
0,
0,
1,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef get_minor(matrix: List[List[float]], i: int, j: int) -> List[List[float]]:\n return [row[:j] + row[j+1:] for row in (matrix[:i]... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "0000032631",
"row_id": 32631,
"seed_ids": "[524]"
} | 0.469241 | Algorithm_32631 | I | [
"get_minor",
"calculate_determinant"
] | 2 | [
[
"calculate_determinant",
"get_minor"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 175368852d5e634bdc5f43e5612007a91b482b42 | 4f8dc65fe137306c978a01de69ce4a2a1fe8dbbc | |||
v1.0 | instruct | Algorithm | Algorithm_32632_I | ### URL Shortening Service
#### Context
URL shortening is a technique used to create shorter versions of long URLs for ease of sharing. A common format includes replacing a long URL with a shortened, unique key that redirects to the original URL when accessed.
You are required to implement a set of functions to creat... | import random
import string
url_mapping = {}
key_mapping = {}
def generate_key(n=6):
"""Generates a random n-character alphanumeric key."""
return ''.join(random.choices(string.ascii_letters + string.digits, k=n))
def shorten_url(original_url):
"""
Generates a unique shortened key for the given URL. ... | from solution import shorten_url, retrieve_url, is_valid_key
def test_shorten_url():
url = "https://example.com/page1"
key = shorten_url(url)
assert isinstance(key, str)
assert len(key) == 6
assert key.isalnum()
def test_retrieve_url():
url = "https://example.com/page2"
key = shorten_url(u... | [
{
"docstring": "Generates a random n-character alphanumeric key.",
"function_declaration": "def generate_key(n=6):",
"function_name": "generate_key",
"parameter_list": "(n=6)"
},
{
"docstring": "Generates a unique shortened key for the given URL. If the URL has been shortened before, \nit re... | [
0,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import random\nimport string\n\n# Dictionary to store the mapping between short keys and original URLs\nurl_mapping = {}\n\ndef shorten_url(original_url):\n \... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000032632",
"row_id": 32632,
"seed_ids": "[1136]"
} | 0.608676 | Algorithm_32632 | I | [
"generate_key",
"shorten_url",
"retrieve_url",
"is_valid_key"
] | 4 | [
[
"shorten_url",
"generate_key"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | b56f4a36a4a206d9bffef802aa3e02af7d92a276 | 3423cc5379cc6548a8f4286c42ffefd33af02b26 | |||
v1.0 | instruct | Algorithm | Algorithm_32683_I | ### Question: Implementing Merge Sort in Python
**Scenario:**
You have been tasked with implementing a well-known sorting algorithm, Merge Sort, which is particularly efficient for large datasets because of its O(n log n) time complexity. Unlike quick sort, merge sort is a stable sort and works well with linked lists ... | from typing import List
def merge_sort(arr: List[int]) -> List[int]:
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left_half = merge_sort(arr[:mid])
right_half = merge_sort(arr[mid:])
return merge(left_half, right_half)
def merge(left: List[int], right: List[int]) -> List[int]... | from solution import merge_sort
def test_merge_sort_basic():
assert merge_sort([38, 27, 43, 3, 9, 82, 10]) == [3, 9, 10, 27, 38, 43, 82]
assert merge_sort([5, 2, 9, 1, 5, 6]) == [1, 2, 5, 5, 6, 9]
def test_merge_sort_empty():
assert merge_sort([]) == []
def test_merge_sort_single_element():
assert me... | [
{
"docstring": null,
"function_declaration": "def merge_sort(arr):",
"function_name": "merge_sort",
"parameter_list": "(arr)"
},
{
"docstring": null,
"function_declaration": "def merge(left, right):",
"function_name": "merge",
"parameter_list": "(left, right)"
}
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 10 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef merge_sort(arr: List[int]) -> List[int]:\n if len(arr) <= 1:\n return arr\n \n mid = len(arr) // 2\n left_half ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000032683",
"row_id": 32683,
"seed_ids": "[4155]"
} | 0.569669 | Algorithm_32683 | I | [
"merge_sort",
"merge"
] | 2 | [
[
"merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c7cf469b372e67abb0162174a8f16eeb1ba542c1 | 5ab903200915641e0de6f6f632d6c25dd523ab36 | |||
v1.0 | instruct | Algorithm | Algorithm_32708_I | ### Problem Statement: LCM and GCD Calculator
You are tasked with creating a small utility library that helps in calculating the Least Common Multiple (LCM) and the Greatest Common Divisor (GCD) for given input values. This library should provide functions to compute these properties using the Euclidean algorithm for ... | def gcd(a: int, b: int) -> int:
"""
Computes the Greatest Common Divisor (GCD) of two positive integers a and b using the Euclidean algorithm.
Raises a ValueError if either a or b is non-positive.
"""
if a <= 0 or b <= 0:
raise ValueError("Both numbers must be positive")
while b:
... | from solution import gcd, lcm
def test_gcd_positive_numbers():
assert gcd(48, 18) == 6
assert gcd(100, 10) == 10
assert gcd(7, 5) == 1
assert gcd(20, 25) == 5
def test_gcd_with_non_positive_raises_error():
try:
gcd(-5, 10)
except ValueError as e:
assert str(e) == "Both numbers ... | [
{
"docstring": "Computes the Greatest Common Divisor (GCD) of two positive integers a and b using the Euclidean algorithm.\nRaises a ValueError if either a or b is non-positive.",
"function_declaration": "def gcd(a, b):",
"function_name": "gcd",
"parameter_list": "(a, b)"
},
{
"docstring": "... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def gcd(a, b):\n \"\"\"\n Returns the greatest common divisor (GCD) of two positive integers a and b using the Euclidean algorithm.\n Raises ValueError ... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000032708",
"row_id": 32708,
"seed_ids": "[824]"
} | 0.686595 | Algorithm_32708 | I | [
"gcd",
"lcm"
] | 2 | [
[
"lcm",
"gcd"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | da4b292b6c78582f72451d765df0ffb619bf8dc6 | caf9dab15dfe6f77777d78bafad0c380813796eb | |||
v1.0 | instruct | Algorithm | Algorithm_32865_I | ### Performance Analysis of String Manipulation Algorithms
Write two Python functions to analyze the performance of different string manipulation techniques in reversing words within a sentence.
#### Requirements:
1. **Function 1**: `reverse_words_basic` which uses a basic approach with simple loops and string opera... | import time
def reverse_words_basic(sentence: str) -> str:
"""
Reverses the order of words in a sentence using basic string manipulation.
Args:
- sentence (str): The input sentence.
Returns:
- str: The sentence with the order of words reversed.
"""
words = sentence.split()
reve... | import pytest
from solution import reverse_words_basic, reverse_words_optimized, compare_performance
def test_reverse_words_basic():
assert reverse_words_basic("Hello world, this is a test sentence!") == "sentence! test a is this world, Hello"
assert reverse_words_basic("") == ""
assert reverse_words_basic... | [
{
"docstring": "Reverses the order of words in a sentence using basic string manipulation.\nArgs:\n- sentence (str): The input sentence.\n\nReturns:\n- str: The sentence with the order of words reversed.",
"function_declaration": "def reverse_words_basic(sentence):",
"function_name": "reverse_words_basi... | [
0,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import time\n\ndef reverse_words_basic(sentence: str) -> str:\n \"\"\"\n Reverses the order of words in a given sentence using a basic approach.\n \"\"\... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "0000032865",
"row_id": 32865,
"seed_ids": "[3988]"
} | 0.63243 | Algorithm_32865 | I | [
"reverse_words_basic",
"reverse_words_optimized",
"compare_performance"
] | 3 | [
[
"compare_performance",
"reverse_words_basic"
],
[
"compare_performance",
"reverse_words_optimized"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 4a3c5f7f71025e972d221aee5dcf513c824854b4 | 33f19bc2b218b8f8d65f6ed88cc3d992d243d0fe | |||
v1.0 | instruct | Algorithm | Algorithm_32942_I | ### Introduction
You are enhancing a game where players control characters to perform various actions in a 2D grid-based world. One critical aspect is to accurately calculate the shortest path for a character to traverse from the starting position to a target position, considering any obstacles present on the grid.
##... | from typing import List, Tuple
import heapq
def heuristic(a: Tuple[int, int], b: Tuple[int, int]) -> int:
return abs(a[0] - b[0]) + abs(a[1] - b[1])
def find_shortest_path(
grid: List[List[int]], start: Tuple[int, int], target: Tuple[int, int]
) -> int:
rows, cols = len(grid), len(grid[0])
open_set = ... | from solution import find_shortest_path, is_path_possible
def test_find_shortest_path_example():
grid = [
[0, 0, 1, 0, 0],
[0, 1, 0, 0, 0],
[0, 0, 0, 1, 0],
[0, 1, 0, 0, 0],
[0, 0, 0, 0, 0]
]
start = (0, 0)
target = (4, 4)
assert find_shortest_path(grid, star... | [
{
"docstring": null,
"function_declaration": "def heuristic(a, b):",
"function_name": "heuristic",
"parameter_list": "(a, b)"
},
{
"docstring": null,
"function_declaration": "def find_shortest_path(grid, start, target):",
"function_name": "find_shortest_path",
"parameter_list": "... | [
0,
0,
1,
1,
0,
0,
1,
1,
0,
1
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import heapq\nfrom typing import List, Tuple\n\ndef heuristic(a: Tuple[int, int], b: Tuple[int, int]) -> int:\n return abs(a[0] - b[0]) + abs(a[1] - b[1])\n\n... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000032942",
"row_id": 32942,
"seed_ids": "[575]"
} | 0.717732 | Algorithm_32942 | I | [
"heuristic",
"find_shortest_path",
"is_path_possible"
] | 3 | [
[
"find_shortest_path",
"heuristic"
],
[
"is_path_possible",
"find_shortest_path"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 3e0239a57aa4f570acfd3e416a7e807060dc01a6 | 57f2a0ff193c87385108ca315c19e34d8d99fbe1 | |||
v1.0 | instruct | Algorithm | Algorithm_32953_I | ### Problem Statement
**Background**: Merge sort is a popular sorting algorithm that uses the divide-and-conquer strategy to sort an array. It works by recursively dividing the array into two halves until each half contains only one element, and then merging those halves in a sorted manner.
### Description
Implement... | def merge_sort(arr):
"""
Sorts a list of integers using the merge sort algorithm.
"""
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):
"... | from solution import merge_sort
def test_merge_sort_empty_list():
assert merge_sort([]) == []
def test_merge_sort_single_element():
assert merge_sort([1]) == [1]
def test_merge_sort_two_elements():
assert merge_sort([2, 1]) == [1, 2]
def test_merge_sort_multiple_elements():
assert merge_sort... | [
{
"docstring": "Sorts a list of integers using the merge sort algorithm.",
"function_declaration": "def merge_sort(arr):",
"function_name": "merge_sort",
"parameter_list": "(arr)"
},
{
"docstring": "Merges two sorted lists into a single sorted list.",
"function_declaration": "def merge(l... | [
1,
1,
0,
0,
1,
1,
1,
1,
1,
1
] | 8 | easy | 0.8 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef merge_sort(arr: List[int]) -> List[int]:\n \"\"\"\n Sorts a list of integers using the merge sort algorithm.\n \n Args... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000032953",
"row_id": 32953,
"seed_ids": "[1322]"
} | 0.631471 | Algorithm_32953 | I | [
"merge_sort",
"merge"
] | 2 | [
[
"merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 31f5889e6e38c7f6f57540b75da50eb0a9343bdb | 0b4536b97fd2f993bc31020e4adb8b078f9a54c1 | |||
v1.0 | instruct | Algorithm | Algorithm_32962_I | ### Question: Calculate the N-th Power of a Given Matrix
**Context**:
Matrix exponentiation is an important technique used in various fields such as computer graphics, cryptography, and solving linear recurrence relations. Given a square matrix, computing its power can be performed efficiently using an approach known ... | from typing import List
def identity_matrix(size: int) -> List[List[int]]:
"""
Generates an identity matrix of a given size.
"""
return [[1 if i == j else 0 for j in range(size)] for i in range(size)]
def multiply_matrices(a: List[List[int]], b: List[List[int]]) -> List[List[int]]:
"""
Multipl... | from solution import matrix_power
def test_matrix_power_identity():
matrix = [[1, 0], [0, 1]]
n = 5
assert matrix_power(matrix, n) == [[1, 0], [0, 1]]
def test_matrix_power_zero_exponent():
matrix = [[2, 3], [4, 5]]
n = 0
assert matrix_power(matrix, n) == [[1, 0], [0, 1]]
def test_matrix_powe... | [
{
"docstring": "Generates an identity matrix of a given size.",
"function_declaration": "def identity_matrix(size):",
"function_name": "identity_matrix",
"parameter_list": "(size)"
},
{
"docstring": "Multiplies two matrices a and b.",
"function_declaration": "def multiply_matrices(a, b):... | [
1,
0,
1,
0,
0,
0,
0,
1,
0,
1
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef identity_matrix(size: int) -> List[List[int]]:\n return [[1 if i == j else 0 for j in range(size)] for i in range(size)]\n\ndef... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000032962",
"row_id": 32962,
"seed_ids": "[2019]"
} | 0.540904 | Algorithm_32962 | I | [
"identity_matrix",
"multiply_matrices",
"matrix_power"
] | 3 | [
[
"matrix_power",
"identity_matrix"
],
[
"matrix_power",
"multiply_matrices"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | a6cfd86310ff132da83f4e1f8a21fbb97f0a5bc7 | 7a1c891f37428a051f2aabecab6432dff882ed58 | |||
v1.0 | instruct | Algorithm | Algorithm_33057_I | ### Sort the List: Iterative vs Recursive
You are given two algorithms to sort a list of numbers: an iterative approach using bubble sort and a recursive approach using merge sort. Your task is to implement a function that leverages these algorithms to sort the provided list of numbers in ascending order.
#### Requir... | def bubble_sort_iterative(nums: list[int | float]) -> list[int | float]:
"""
Sorts a list using iterative bubble sort algorithm.
"""
n = len(nums)
for i in range(n):
for j in range(0, n-i-1):
if nums[j] > nums[j+1]:
nums[j], nums[j+1] = nums[j+1], nums[j]
retu... | from solution import bubble_sort_iterative, merge_sort_recursive
def test_bubble_sort_iterative():
assert bubble_sort_iterative([3, 2, 1]) == [1, 2, 3]
assert bubble_sort_iterative([-3, -2, -1]) == [-3, -2, -1]
assert bubble_sort_iterative([3, -3, 0]) == [-3, 0, 3]
assert bubble_sort_iterative([3.0, 3.... | [
{
"docstring": "Sorts a list using iterative bubble sort algorithm.",
"function_declaration": "def bubble_sort_iterative(nums):",
"function_name": "bubble_sort_iterative",
"parameter_list": "(nums)"
},
{
"docstring": "Sorts a list using recursive merge sort algorithm.",
"function_declara... | [
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 bubble_sort_iterative(nums: list[int | float]) -> list[int | float]:\n \"\"\"\n Sorts a list of numbers using the bubble sort algorithm iteratively.\n ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000033057",
"row_id": 33057,
"seed_ids": "[3297]"
} | 0.563012 | Algorithm_33057 | I | [
"bubble_sort_iterative",
"merge_sort_recursive",
"merge"
] | 3 | [
[
"merge_sort_recursive",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 32cf1f33845f93421f24d77fa6f3d04699a5be83 | cc5816c35c82f12a13b1efaf9f38ca6766fe8716 | |||
v1.0 | instruct | Algorithm | Algorithm_33058_I | ### Prime Groupings
Write a function that takes a list of integers and returns a dictionary grouping the integers based on whether they are prime or non-prime.
#### Requirements:
1. Implement the `group_by_prime` function which accepts a list of integers.
2. The function should return a dictionary with two keys:
... | def is_prime(n: int) -> bool:
"""
Determine if the given integer is a prime number.
Parameters:
n (int): The integer to check for primality.
Returns:
bool: True if n is a prime number, otherwise False.
"""
if n <= 1:
return False
if n <= 3:
return True
i... | def test_is_prime():
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(4) == False
assert is_prime(5) == True
assert is_prime(-1) == False
assert is_prime(0) == False
assert is_prime(1) == False
assert is_prime(29) == True
assert is_prime(30) == False
def test_gr... | [
{
"docstring": "Determine if the given integer is a prime number.\n\nParameters:\nn (int): The integer to check for primality.\n\nReturns:\nbool: True if n is a prime number, otherwise False.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
... | [
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 is_prime(n: int) -> bool:\n \"\"\"\n Determine if the given integer is a prime number.\n \n Parameters:\n n (int): The integer to check for pr... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000033058",
"row_id": 33058,
"seed_ids": "[3363]"
} | 0.725872 | Algorithm_33058 | I | [
"is_prime",
"group_by_prime"
] | 2 | [
[
"group_by_prime",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 6141f198a2e17bf2320708791c9e5912d33fe1df | a38a0c9f957ee464bd9e2094b1ba850e878e7386 | |||
v1.0 | instruct | Algorithm | Algorithm_33075_I | **Perfect Number Finder**
#### Problem Statement:
A perfect number is a positive integer that is equal to the sum of its proper divisors (excluding the number itself). For example, 28 is a perfect number because its proper divisors are 1, 2, 4, 7, and 14, and their sum is 28. Your task is to write a function that iden... | def is_perfect_number(number: int) -> bool:
"""
Check if the given number is a perfect number.
"""
if number < 2:
return False
proper_divisors_sum = sum(i for i in range(1, number // 2 + 1) if number % i == 0)
return proper_divisors_sum == number
def perfect_numbers_sum() -> int:
""... | from solution import is_perfect_number, perfect_numbers_sum
def test_is_perfect_number():
assert is_perfect_number(6) == True
assert is_perfect_number(28) == True
assert is_perfect_number(496) == True
assert is_perfect_number(8128) == True
assert is_perfect_number(1) == False
assert is_perfect_... | [
{
"docstring": "Check if the given number is a perfect number.",
"function_declaration": "def is_perfect_number(number):",
"function_name": "is_perfect_number",
"parameter_list": "(number)"
},
{
"docstring": "Find all perfect numbers within the range 2 to 10000 and return their sum.",
"f... | [
1,
0,
0,
1,
0,
0,
1,
0,
0,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def is_perfect_number(number: int) -> bool:\n \"\"\"\n Checks if a given number is a perfect number.\n \"\"\"\n if number < 2:\n return False\... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "0000033075",
"row_id": 33075,
"seed_ids": "[2479]"
} | 0.669418 | Algorithm_33075 | I | [
"is_perfect_number",
"perfect_numbers_sum"
] | 2 | [
[
"perfect_numbers_sum",
"is_perfect_number"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a8e4a2dc56ce542af82fe13e13af7ebc73337d23 | bb976e0fb8e555daf463fdd00811e788f61ba2fa | |||
v1.0 | instruct | Algorithm | Algorithm_33076_I | ### Coding Problem: Identifying Palindromic Primes
#### Background
A palindromic number is a number that remains the same when its digits are reversed. A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. A palindromic prime is a number that is both a palindrome and ... | def is_prime(num):
if num <= 1:
return False
if num <= 3:
return True
if num % 2 == 0 or num % 3 == 0:
return False
i = 5
while i * i <= num:
if num % i == 0 or num % (i + 2) == 0:
return False
i += 6
return True
def is_palindrome(num):
re... | from solution import find_palindromic_primes
def test_find_first_five_palindromic_primes():
assert find_palindromic_primes(5) == [2, 3, 5, 7, 11]
def test_find_first_ten_palindromic_primes():
assert find_palindromic_primes(10) == [2, 3, 5, 7, 11, 101, 131, 151, 181, 191]
def test_find_single_palindromic_prim... | [
{
"docstring": null,
"function_declaration": "def is_prime(num):",
"function_name": "is_prime",
"parameter_list": "(num)"
},
{
"docstring": null,
"function_declaration": "def is_palindrome(num):",
"function_name": "is_palindrome",
"parameter_list": "(num)"
},
{
"docstring... | [
0,
1,
0,
0,
0,
1,
0,
0,
1,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def is_palindrome(num):\n \"\"\"\n Check if a given number is a palindrome.\n \"\"\"\n return str(num) == str(num)[reverse]\n\ndef is_prime(num):\n ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "0000033076",
"row_id": 33076,
"seed_ids": "[2627]"
} | 0.646167 | Algorithm_33076 | I | [
"is_prime",
"is_palindrome",
"find_palindromic_primes"
] | 3 | [
[
"find_palindromic_primes",
"is_palindrome"
],
[
"find_palindromic_primes",
"is_prime"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | f7fe43f26afc2cb1ad00a1285d082e5dd6b7230c | c52d34a996823e7d88c46dcde2883bdab8e5f518 | |||
v1.0 | instruct | Algorithm | Algorithm_33134_I | ### Sorting Algorithms - Challenge
You are tasked with implementing a classic sorting algorithm: Merge Sort. Merge Sort is a divide-and-conquer algorithm that works by recursively dividing the array into halves until each half contains a single element, and then merging these halves back together in sorted order.
###... | from typing import List
def merge_sort(arr: List[int]) -> List[int]:
"""
Sorts a list of integers in ascending order using the merge sort algorithm.
"""
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left = merge_sort(arr[:mid])
right = merge_sort(arr[mid:])
return merge(lef... | from solution import merge_sort
def test_merge_sort_with_unsorted_list():
assert merge_sort([4, 3, 1, 5, 6]) == [1, 3, 4, 5, 6]
def test_merge_sort_with_negative_numbers():
assert merge_sort([10, -1, 2, 5, 0, 6, 4, -5]) == [-5, -1, 0, 2, 4, 5, 6, 10]
def test_merge_sort_single_element():
assert merge_sor... | [
{
"docstring": "Sorts a list of integers in ascending order using the merge sort algorithm.",
"function_declaration": "def merge_sort(arr):",
"function_name": "merge_sort",
"parameter_list": "(arr)"
},
{
"docstring": "Merges two sorted lists into a single sorted list.",
"function_declara... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 10 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef merge_sort(arr: List[int]) -> List[int]:\n if len(arr) <= 1:\n return arr\n\n # Split the array into halves\n mid ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000033134",
"row_id": 33134,
"seed_ids": "[5306]"
} | 0.643654 | Algorithm_33134 | I | [
"merge_sort",
"merge"
] | 2 | [
[
"merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 15ef545d66de590480002c5e78ce0ba1f6c6d3ed | fed1516e990e736f649440ed6c9f687aacb56ef0 | |||
v1.0 | instruct | Algorithm | Algorithm_33147_I | ### Coding Assessment Question
#### Context
You are tasked to create an optimized file processing function that reads a large text file and identifies the longest word that is a palindrome.
#### Requirements
Develop the `find_longest_palindrome` function to:
1. Read and process the content of a text file line by line... | import re
def is_palindrome(word):
return word == word[::-1]
def find_longest_palindrome(file_path):
longest_palindrome = ""
with open(file_path, 'r') as file:
for line in file:
words = re.findall(r'\b\w+\b', line.lower())
for word in words:
if is_palindrome... | from solution import find_longest_palindrome
import tempfile
def test_find_longest_palindrome_single_line():
content = "Madam Arora teaches malayalam"
with tempfile.NamedTemporaryFile(delete=False, mode='w') as temp:
temp.write(content)
temp_path = temp.name
assert find_longest_palindrome(t... | [
{
"docstring": null,
"function_declaration": "def is_palindrome(word):",
"function_name": "is_palindrome",
"parameter_list": "(word)"
},
{
"docstring": null,
"function_declaration": "def find_longest_palindrome(file_path):",
"function_name": "find_longest_palindrome",
"parameter_... | [
1,
0,
1,
0,
1,
0,
0,
0,
0,
1
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import string\n\ndef is_palindrome(word):\n return word == word[::-1]\n\ndef find_longest_palindrome(file_path: str) -> str:\n longest_palindrome = \"\"\n ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000033147",
"row_id": 33147,
"seed_ids": "[3282]"
} | 0.692444 | Algorithm_33147 | I | [
"is_palindrome",
"find_longest_palindrome"
] | 2 | [
[
"find_longest_palindrome",
"is_palindrome"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 1c29b2b0af0bf58df729825d56ccfb8b69605a44 | 4b3a750d0c09ad46db72a5debf9a159a018eae69 | |||
v1.0 | instruct | Algorithm | Algorithm_33153_I | ### Question: Implement and Test Enhanced File Parsing System
#### Context:
You are tasked with developing a software component that reads and processes large log files. The existing solution processes one file at a time, which makes it slow, especially when dealing with multiple log files.
#### Requirements:
1. **Ba... | import os
from typing import List, Dict, Union
from concurrent.futures import ThreadPoolExecutor, as_completed
def count_lines_in_file(file_path: str) -> Union[int, str]:
"""
Helper function to count the number of lines in a file.
Handles file read errors and returns an error message if the file cannot be ... | import pytest
import os
from solution import process_log_files
def test_process_log_files_single_file(tmp_path):
# Create a temporary log file
log_content = "line1\nline2\nline3"
log_file = tmp_path / "log1.txt"
log_file.write_text(log_content)
expected_output = {str(log_file): 3}
assert p... | [
{
"docstring": "Helper function to count the number of lines in a file.\nHandles file read errors and returns an error message if the file cannot be read.\n\nParameters:\nfile_path (str): The path of the file to process.\n\nReturns:\nUnion[int, str]: The number of lines in the file or an error message.",
"f... | [
0,
1,
1,
1,
1,
1,
0,
1,
1,
1
] | 8 | easy | 0.8 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from multiprocessing import Pool, Manager\nfrom typing import List, Dict, Union\n\ndef process_single_file(file_path: str, return_dict: Dict[str, Union[int, str]... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "0000033153",
"row_id": 33153,
"seed_ids": "[2356]"
} | 0.602713 | Algorithm_33153 | I | [
"count_lines_in_file",
"process_log_files"
] | 2 | [
[
"process_log_files",
"count_lines_in_file"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 107b435d14c284c578342cd1e96b86365acc5901 | e228677f4b5e6802ae3d0ca7ae78324fad9cddb2 | |||
v1.0 | instruct | Algorithm | Algorithm_33299_I | ### Scenario
You are part of a team building a search engine backend, which requires an implementation of autocomplete functionality. When a user starts typing a query, the engine should provide a list of suggested complete words based on an input prefix.
### Task
Implement a function to construct the autocomplete mec... | from typing import List
class TrieNode:
def __init__(self):
self.children = {}
self.is_end_of_word = False
def build_trie(words: List[str]) -> TrieNode:
root = TrieNode()
for word in words:
current = root
for letter in word:
if letter not in current.child... | import pytest
from solution import build_trie, autocomplete
def test_build_trie_empty_case():
trie = build_trie([])
assert isinstance(trie, TrieNode) == True
def test_autocomplete_no_matching_prefix():
words = ["apple", "apricot", "banana", "bamboo", "ball", "cat", "cap", "cape"]
trie = build_trie(wor... | [] | [
0,
1,
0,
1,
1,
0,
1,
1,
1,
1
] | 7 | easy | 0.7 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List\n\nclass TrieNode:\n def __init__(self):\n self.children = {}\n self.is_end_of_word = False\n\ndef build_trie(words: Lis... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000033299",
"row_id": 33299,
"seed_ids": "[75]"
} | 0.526757 | Algorithm_33299 | I | [
"build_trie",
"autocomplete",
"_find_words_with_prefix"
] | 3 | [
[
"autocomplete",
"_find_words_with_prefix"
]
] | 1 | [] | false | [
"TrieNode"
] | true | pytest | true | [] | true | 3dd4baa2cdd46a7567f3f28a60dbbf35c1d46dd6 | 2f6e6569306e55258b0d9aabcd5532bdd6f7b8c2 | |||
v1.0 | instruct | Algorithm | Algorithm_33302_I | ### Coding Challenge: String Permutations with Constraints
You have been tasked with generating all distinct permutations of a given string that do not contain any palindrome as substrings. Your function should ensure it handles the permutations and palindrome checks efficiently.
**Function Signature**:
```python
def... | from itertools import permutations
from typing import List
def is_palindrome(s: str) -> bool:
"""
Check if a given string is a palindrome.
"""
return s == s[::-1]
def contains_palindrome_substring(s: str) -> bool:
"""
Check if a given string contains any palindromic substrings.
"""
len... | from solution import no_palindrome_permutations
def test_no_palindrome_permutations_abc():
assert sorted(no_palindrome_permutations("abc")) == sorted(['abc', 'acb', 'bac', 'bca', 'cab', 'cba'])
def test_no_palindrome_permutations_aab():
assert no_palindrome_permutations("aab") == []
def test_no_palindrome_pe... | [
{
"docstring": "Check if a given string is a palindrome.",
"function_declaration": "def is_palindrome(s):",
"function_name": "is_palindrome",
"parameter_list": "(s)"
},
{
"docstring": "Check if a given string contains any palindromic substrings.",
"function_declaration": "def contains_pa... | [
0,
0,
0,
1,
1,
0,
1,
0,
0,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from itertools import permutations\nfrom typing import List\n\ndef is_palindrome(s: str) -> bool:\n return s == s[::-1]\n\ndef contains_palindromic_substring(... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "0000033302",
"row_id": 33302,
"seed_ids": "[5074]"
} | 0.780325 | Algorithm_33302 | I | [
"is_palindrome",
"contains_palindrome_substring",
"no_palindrome_permutations"
] | 3 | [
[
"contains_palindrome_substring",
"is_palindrome"
],
[
"no_palindrome_permutations",
"contains_palindrome_substring"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 727e51640de1578881e2e18cf611f81e0f6d4e29 | 53c03781cc014c72f46090ec4c463c04a95910e0 | |||
v1.0 | instruct | Algorithm | Algorithm_33306_I | ### Prime Palindromes
Your task is to implement a function that generates a list of prime palindromes less than or equal to a given positive integer `n`. A palindrome is a number that reads the same forwards and backwards (e.g., 121, 131), and a prime number is a number greater than 1 that has no positive divisors oth... | def is_prime(num):
if num <= 1:
return False
if num <= 3:
return True
if num % 2 == 0 or num % 3 == 0:
return False
i = 5
while (i * i) <= num:
if num % i == 0 or num % (i + 2) == 0:
return False
i += 6
return True
def is_palindrome(num):
... | def test_prime_palindromes_with_valid_input():
assert prime_palindromes(100) == [2, 3, 5, 7, 11]
assert prime_palindromes(200) == [2, 3, 5, 7, 11, 101, 131, 151, 181, 191]
assert prime_palindromes(10) == [2, 3, 5, 7]
def test_prime_palindromes_with_negative_input():
try:
prime_palindromes(-10)
... | [
{
"docstring": null,
"function_declaration": "def is_prime(num):",
"function_name": "is_prime",
"parameter_list": "(num)"
},
{
"docstring": null,
"function_declaration": "def is_palindrome(num):",
"function_name": "is_palindrome",
"parameter_list": "(num)"
},
{
"docstring... | [
1,
1,
1,
0,
0,
1,
1,
1,
1
] | 7 | easy | 0.778 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def is_prime(num):\n if num < 2:\n return False\n for i in range(2, int(num**0.5) + 1):\n if num % i == 0:\n return False\n ret... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000033306",
"row_id": 33306,
"seed_ids": "[3691]"
} | 0.655734 | Algorithm_33306 | I | [
"is_prime",
"is_palindrome",
"prime_palindromes"
] | 3 | [
[
"prime_palindromes",
"is_palindrome"
],
[
"prime_palindromes",
"is_prime"
]
] | 2 | [] | false | [] | false | pytest | false | [] | true | 719acbb74d9e92943636f3f2c69d6705f0c4da6e | 7bff095988a7f4af87227fa3a29c837e22a3a977 | |||
v1.0 | instruct | Algorithm | Algorithm_33317_I | ### Combinatorial Selection
Write a function that calculates the total number of unique selections of `k` items from a set of `n` items. This is a classic problem of combinatorics, often referred to as "n choose k" or binomial coefficient, calculated as:
\[ C(n, k) = \frac{n!}{k!(n-k)!} \]
However, for this problem,... | def combinatorial_selection(n, k):
if k > n or n < 0 or k < 0:
raise ValueError("Invalid input: n and k must be such that 0 ≤ k ≤ n and both are non-negative integers.")
if k == 0 or k == n:
return 1
k = min(k, n - k) # Take advantage of symmetry C(n, k) == C(n, n-k)
result = ... | import pytest
from solution import combinatorial_selection, print_combinatorial_selection
def test_combinatorial_selection_basic():
assert combinatorial_selection(5, 3) == 10
assert combinatorial_selection(6, 2) == 15
assert combinatorial_selection(0, 0) == 1
assert combinatorial_selection(10, 0) == 1
... | [
{
"docstring": null,
"function_declaration": "def combinatorial_selection(n, k):",
"function_name": "combinatorial_selection",
"parameter_list": "(n, k)"
},
{
"docstring": null,
"function_declaration": "def print_combinatorial_selection(n, k):",
"function_name": "print_combinatorial_... | [
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 combinatorial_selection(n: int, k: int) -> int:\n \"\"\"\n Calculate the number of unique combinations of k items out of n items (C(n, k)).\n Uses a... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000033317",
"row_id": 33317,
"seed_ids": "[4951]"
} | 0.577206 | Algorithm_33317 | I | [
"combinatorial_selection",
"print_combinatorial_selection"
] | 2 | [
[
"print_combinatorial_selection",
"combinatorial_selection"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 27f883b1b7caa5cd2816b2e1852f99077ab5e5b7 | 69ab6b24d98f48b5e853f22992b02a983c216553 | |||
v1.0 | instruct | Algorithm | Algorithm_33322_I | ### Coding Assessment Question
#### Scenario
You are tasked to implement a simplified artificial neural network (ANN) for binary classification purposes. The network consists of a single neuron with a sigmoid activation function. You need to construct and train this neuron to classify data points accurately.
#### Tas... | import random
import math
from typing import List, Tuple
def sigmoid(z: float) -> float:
"""
Calculate the sigmoid of z.
"""
return 1 / (1 + math.exp(-z))
def train_neuron(X: List[List[float]], y: List[int], learning_rate: float, epochs: int) -> Tuple[List[float], float]:
"""
Train a single ne... | from solution import train_neuron
import random
def test_training_neuron():
# Setting a random seed for reproducibility
random.seed(0)
X = [[0.1, 0.5], [0.2, 0.6], [0.3, 0.7], [0.4, 0.8], [0.5, 0.9]]
y = [0, 0, 1, 1, 1]
learning_rate = 0.1
epochs = 1000
W, b = train_neuron(X, y, learn... | [
{
"docstring": "Calculate the sigmoid of z.",
"function_declaration": "def sigmoid(z):",
"function_name": "sigmoid",
"parameter_list": "(z)"
},
{
"docstring": "Train a single neuron using gradient descent.\n\nArgs:\nX (List[List[float]]): The feature vectors.\ny (List[int]): The binary label... | [
1,
1,
1,
1,
0,
1,
1,
1,
1,
1
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import random\nimport math\nfrom typing import List, Tuple\n\ndef sigmoid(z: float) -> float:\n return 1 / (1 + math.exp(-z))\n\ndef train_neuron(X: List[List... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000033322",
"row_id": 33322,
"seed_ids": "[5223]"
} | 0.603123 | Algorithm_33322 | I | [
"sigmoid",
"train_neuron"
] | 2 | [
[
"train_neuron",
"sigmoid"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 28a2179af245278b606a52725cdc7e6af6cbafc2 | cfe4dca330b89d0f333a709f3cab6bbd00c80df6 | |||
v1.0 | instruct | Algorithm | Algorithm_33368_I | ### Question: Implement a Basic RSA Encryption and Decryption
#### Problem Statement:
You are tasked with implementing a basic RSA encryption and decryption system. RSA is a widely used public-key cryptosystem that relies on the difficulty of factoring large integers. Your job is to write functions to generate public ... | 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(n ** 0.5) + 1, 2):
if n % i == 0:
return False
return True
def gcd(a: int, b: int) -> int:
while b:
a, b = b, a % b
... | import pytest
from solution import is_prime, gcd, modinv, generate_keys, encrypt, decrypt
def test_is_prime():
assert is_prime(2)
assert is_prime(3)
assert not is_prime(4)
assert is_prime(5)
assert is_prime(29)
assert not is_prime(30)
def test_gcd():
assert gcd(48, 18) == 6
assert gcd(... | [
{
"docstring": null,
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def gcd(a, b):",
"function_name": "gcd",
"parameter_list": "(a, b)"
},
{
"docstring": null,
"function... | [
0,
1,
1,
0,
0,
0,
0,
0,
1,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def 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\n for i in ... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000033368",
"row_id": 33368,
"seed_ids": "[369]"
} | 0.5692 | Algorithm_33368 | I | [
"is_prime",
"gcd",
"modinv",
"generate_keys",
"encrypt",
"decrypt"
] | 6 | [
[
"generate_keys",
"gcd"
],
[
"generate_keys",
"is_prime"
],
[
"generate_keys",
"modinv"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 823d39742cba0beab243c12af2036366beffb0d5 | ab7a8ba9120f9d9f00285001cc355a3178e3212f | |||
v1.0 | instruct | Algorithm | Algorithm_33380_I | ### Question
**Context**:
You are a software developer at a logistics company. Your team is working on optimizing the delivery routes for your drivers. Each delivery route should be planned such that the total distance traveled is minimized while visiting all required delivery locations. For simplicity, all locations ... | from math import sqrt
def euclidean_distance(p1, p2):
return sqrt((p1[0] - p2[0])**2 + (p1[1] - p2[1])**2)
def find_shortest_route(locations):
if not locations:
return []
# Start at the first location
current_location = locations[0]
route = [current_location]
unvisited = set(locat... | import pytest
from solution import find_shortest_route
def almost_equal_tuple(t1, t2, tol=1e-5):
return all(abs(a - b) < tol for a, b in zip(t1, t2))
def test_find_shortest_route_example1():
locations = [(0, 0), (2, 2), (3, 4), (8, 1)]
expected_routes = [
[(0, 0), (2, 2), (3, 4), (8, 1)],
... | [
{
"docstring": null,
"function_declaration": "def euclidean_distance(p1, p2):",
"function_name": "euclidean_distance",
"parameter_list": "(p1, p2)"
},
{
"docstring": null,
"function_declaration": "def find_shortest_route(locations):",
"function_name": "find_shortest_route",
"para... | [
1,
1,
1,
0,
1,
0,
1,
1,
0,
1
] | 7 | easy | 0.7 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import math\n\ndef find_shortest_route(locations: list[tuple[int, int]]) -> list[tuple[int, int]]:\n def euclidean_distance(p1, p2):\n return math.sqrt... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000033380",
"row_id": 33380,
"seed_ids": "[558]"
} | 0.676747 | Algorithm_33380 | I | [
"euclidean_distance",
"find_shortest_route"
] | 2 | [
[
"find_shortest_route",
"euclidean_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 2a42795b815f563d69733315dfcd3624dc60e0d3 | ca693cf5d54e89dec1e5d3e33677cffbb8d18c0b | |||
v1.0 | instruct | Algorithm | Algorithm_33398_I | ### Coding Assessment Question
#### Context:
Heap Sort is a comparison-based sorting algorithm that uses a binary heap data structure. It is similar to selection sort, where we first find the maximum element and place the maximum element at the end. We repeat the same process for the remaining elements.
#### Problem ... | from typing import List
def heapify(arr: List[int], n: int, i: int) -> None:
"""
Converts a subtree rooted with node i into a max heap, assuming the subtrees are already heaps.
"""
largest = i
left = 2 * i + 1
right = 2 * i + 2
if left < n and arr[i] < arr[left]:
largest = left
... | from solution import heap_sort
def test_heap_sort_empty():
assert heap_sort([]) == []
def test_heap_sort_single_element():
assert heap_sort([1]) == [1]
def test_heap_sort_two_elements():
assert heap_sort([2, 1]) == [1, 2]
assert heap_sort([1, 2]) == [1, 2]
def test_heap_sort_multiple_elements():
... | [
{
"docstring": "Converts a subtree rooted with node i into a max heap, assuming the subtrees are already heaps.",
"function_declaration": "def heapify(arr, n, i):",
"function_name": "heapify",
"parameter_list": "(arr, n, i)"
},
{
"docstring": null,
"function_declaration": "def heap_sort(... | [
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 9 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef heapify(arr: List[int], n: int, i: int):\n \"\"\"\n Helper function to maintain the heap property.\n \"\"\"\n largest ... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000033398",
"row_id": 33398,
"seed_ids": "[3415]"
} | 0.705462 | Algorithm_33398 | I | [
"heapify",
"heap_sort"
] | 2 | [
[
"heap_sort",
"heapify"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 66d9c6ced3aa6c89315008ae19d092758df991c0 | 381e0c47c3e0e2191941db4637ccf10414515f07 | |||
v1.0 | instruct | Algorithm | Algorithm_33415_I | ### Coding Assessment Question
#### Context
In number theory, a perfect number is a positive integer that is equal to the sum of its proper divisors (excluding itself). For example, 6 is a perfect number because its proper divisors are 1, 2, and 3, and 1 + 2 + 3 = 6. Given an integer \(n\), your task is to implement a... | from typing import List
def sum_of_proper_divisors(num: int) -> int:
"""
Returns the sum of proper divisors of num (excluding itself).
"""
if num < 2:
return 0
divisors_sum = 1 # 1 is a proper divisor for any number > 1
sqrt_num = int(num ** 0.5)
for i in range(2, sqrt_num + 1):
... | def test_sum_of_proper_divisors():
assert sum_of_proper_divisors(6) == 6 # 1 + 2 + 3
assert sum_of_proper_divisors(28) == 28 # 1 + 2 + 4 + 7 + 14
assert sum_of_proper_divisors(12) == 16 # 1 + 2 + 3 + 4 + 6
assert sum_of_proper_divisors(1) == 0 # No proper divisors
assert sum_of_proper_divisors(2... | [
{
"docstring": "Returns the sum of proper divisors of num (excluding itself).",
"function_declaration": "def sum_of_proper_divisors(num):",
"function_name": "sum_of_proper_divisors",
"parameter_list": "(num)"
},
{
"docstring": "Returns a list of all perfect numbers less than n.",
"functi... | [
1,
0,
1,
0,
0,
0,
1,
0,
1,
0
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef sum_of_proper_divisors(num: int) -> int:\n \"\"\"\n Returns the sum of proper divisors of a given number (excluding the numb... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000033415",
"row_id": 33415,
"seed_ids": "[2086]"
} | 0.670075 | Algorithm_33415 | I | [
"sum_of_proper_divisors",
"find_perfect_numbers"
] | 2 | [
[
"find_perfect_numbers",
"sum_of_proper_divisors"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 3e3dfdfe003457ad2ddf252c86264c3b06328f54 | 52dbe1564b7df5c20873ad0050abc7f7dcd3f113 | |||
v1.0 | instruct | Algorithm | Algorithm_33444_I | ### Coding Assessment Question:
Imagine you are working with a large dataset of hexadecimal numbers and you need to detect specific patterns within them.
**Problem Statement:**
You are provided with an algorithm that first generates all possible 4-digit hexadecimal numbers (ranging from `0000` to `FFFF`). For each h... | import math
def is_perfect_square(number: int) -> bool:
"""
Determine if the given number is a perfect square.
Args:
- number (int): An integer to check.
Returns:
- bool: True if the number is a perfect square, False otherwise.
"""
if number < 0:
return False
root ... | from solution import is_perfect_square, find_largest_hex_perfect_square
def test_is_perfect_square():
assert is_perfect_square(0) == True
assert is_perfect_square(1) == True
assert is_perfect_square(4) == True
assert is_perfect_square(16) == True
assert is_perfect_square(15) == False
assert is_... | [
{
"docstring": "Determine if the given number is a perfect square.\n\nArgs:\n- number (int): An integer to check.\n\nReturns:\n- bool: True if the number is a perfect square, False otherwise.",
"function_declaration": "def is_perfect_square(number):",
"function_name": "is_perfect_square",
"parameter... | [
0,
0,
0,
1,
1,
0,
1,
0,
0,
1
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import math\n\ndef is_perfect_square(number: int) -> bool:\n \"\"\"\n Check if a given number is a perfect square.\n \"\"\"\n if number < 0:\n ... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "0000033444",
"row_id": 33444,
"seed_ids": "[2456]"
} | 0.567898 | Algorithm_33444 | I | [
"is_perfect_square",
"find_largest_hex_perfect_square"
] | 2 | [
[
"find_largest_hex_perfect_square",
"is_perfect_square"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 60bd4a67d12bfd0f91c04398156d3f3908feab27 | 825ecc4a56ded89c6302fd472b84343f9640d104 | |||
v1.0 | instruct | Algorithm | Algorithm_33506_I | ### Problem Statement
Write a function that takes a string of parentheses and determines if it is valid. A valid string must follow these rules:
- Only the characters '(', ')', '{', '}', '[' and ']' are allowed.
- Every opening bracket must have a corresponding closing bracket of the same type.
- Opening brackets must... | def is_valid_parentheses(s: str) -> bool:
stack = []
bracket_map = {')': '(', '}': '{', ']': '['}
for char in s:
if char in bracket_map.values():
stack.append(char)
elif char in bracket_map.keys():
if stack == [] or bracket_map[char] != stack.pop():
re... | from solution import is_valid_parentheses, count_valid_substrings
def test_is_valid_parentheses_empty_string():
assert is_valid_parentheses("") == True
def test_is_valid_parentheses_single_pair():
assert is_valid_parentheses("()") == True
def test_is_valid_parentheses_nested_pairs():
assert is_valid_pare... | [
{
"docstring": null,
"function_declaration": "def is_valid_parentheses(s):",
"function_name": "is_valid_parentheses",
"parameter_list": "(s)"
},
{
"docstring": null,
"function_declaration": "def count_valid_substrings(s):",
"function_name": "count_valid_substrings",
"parameter_li... | [
0,
0,
0,
0,
0,
0,
0,
0,
1,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def is_valid_parentheses(s: str) -> bool:\n \"\"\"\n Given a string s containing parentheses characters, determine if the string is valid\n based on the... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000033506",
"row_id": 33506,
"seed_ids": "[4175]"
} | 0.81759 | Algorithm_33506 | I | [
"is_valid_parentheses",
"count_valid_substrings"
] | 2 | [
[
"count_valid_substrings",
"is_valid_parentheses"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | da4232bf886a5e887ac767c2f74aa7fd9bd97c63 | aeeb942cb3e4ad4976f506e48ce3cca7b10d758b | |||
v1.0 | instruct | Algorithm | Algorithm_33568_I | ### Question: Implement a Simple Neural Network for Binary Classification from Scratch
You are tasked with implementing a simple neural network from scratch to perform binary classification. The neural network should have one hidden layer with ReLU activation and an output layer with sigmoid activation. You need to im... | import numpy as np
from typing import Dict, Tuple
def initialize_parameters(n_x: int, n_h: int, n_y: int) -> Dict[str, np.ndarray]:
np.random.seed(1)
W1 = np.random.randn(n_h, n_x) * 0.01
b1 = np.zeros((n_h, 1))
W2 = np.random.randn(n_y, n_h) * 0.01
b2 = np.zeros((n_y, 1))
parameters = {"W... | import numpy as np
from solution import initialize_parameters, forward_propagation, compute_cost, backward_propagation, update_parameters, nn_model, predict
def test_initialize_parameters():
parameters = initialize_parameters(2, 4, 1)
assert parameters["W1"].shape == (4, 2)
assert parameters["b1"].shape ==... | [
{
"docstring": null,
"function_declaration": "def initialize_parameters(n_x, n_h, n_y):",
"function_name": "initialize_parameters",
"parameter_list": "(n_x, n_h, n_y)"
},
{
"docstring": null,
"function_declaration": "def forward_propagation(X, parameters):",
"function_name": "forward... | [
1,
0,
0,
0,
0,
0,
0,
1,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import numpy as np\n\ndef initialize_parameters(n_x: int, n_h: int, n_y: int) -> dict:\n \"\"\"Initialize the parameters for the neural network\"\"\"\n np.... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "0000033568",
"row_id": 33568,
"seed_ids": "[514]"
} | 0.583881 | Algorithm_33568 | I | [
"initialize_parameters",
"forward_propagation",
"compute_cost",
"backward_propagation",
"update_parameters",
"nn_model",
"predict"
] | 7 | [
[
"nn_model",
"backward_propagation"
],
[
"nn_model",
"compute_cost"
],
[
"nn_model",
"forward_propagation"
],
[
"nn_model",
"initialize_parameters"
],
[
"nn_model",
"update_parameters"
],
[
"predict",
"forward_propagation"
]
] | 6 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | c16155afa283eebc326b9a018ec17009f435d155 | e374f480f60ff15a552ea8ab3817bd9784f382c2 | |||
v1.0 | instruct | Algorithm | Algorithm_33696_I | ### Matrix Multiplication using Strassen's Algorithm
#### Context
Matrix multiplication is a fundamental operation in various scientific computations. Strassen's algorithm is an efficient algorithm for matrix multiplication that reduces the time complexity compared to the conventional algorithm.
#### Objective
Write... | def matrix_addition(A, B):
"""Add two matrices A and B."""
n = len(A)
return [[A[i][j] + B[i][j] for j in range(n)] for i in range(n)]
def matrix_subtraction(A, B):
"""Subtract matrix B from matrix A."""
n = len(A)
return [[A[i][j] - B[i][j] for j in range(n)] for i in range(n)]
def matrix_spl... | def test_matrix_addition():
A = [[1, 2], [3, 4]]
B = [[5, 6], [7, 8]]
expected = [[6, 8], [10, 12]]
assert matrix_addition(A, B) == expected
def test_matrix_subtraction():
A = [[5, 6], [7, 8]]
B = [[1, 2], [3, 4]]
expected = [[4, 4], [4, 4]]
assert matrix_subtraction(A, B) == expected
... | [
{
"docstring": "Add two matrices A and B.",
"function_declaration": "def matrix_addition(A, B):",
"function_name": "matrix_addition",
"parameter_list": "(A, B)"
},
{
"docstring": "Subtract matrix B from matrix A.",
"function_declaration": "def matrix_subtraction(A, B):",
"function_na... | [
1,
1,
1,
1,
1,
1,
0,
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 add_matrices(matrix1, matrix2):\n return [\n [\n matrix1[i][j] + matrix2[i][j]\n for j in range(len(matrix1))\n ]\n ... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "0000033696",
"row_id": 33696,
"seed_ids": "[3182]"
} | 0.589982 | Algorithm_33696 | I | [
"matrix_addition",
"matrix_subtraction",
"matrix_split",
"matrix_combine",
"strassen_multiply"
] | 5 | [
[
"strassen_multiply",
"matrix_addition"
],
[
"strassen_multiply",
"matrix_combine"
],
[
"strassen_multiply",
"matrix_split"
],
[
"strassen_multiply",
"matrix_subtraction"
]
] | 4 | [] | false | [] | false | pytest | false | [] | true | b97326b482fe509a137cb1e926109fcd9faccb5b | a1a2303d33ad8d7cf5ab2f627b389c2ee5a2f749 | |||
v1.0 | instruct | Algorithm | Algorithm_33759_I | ### Question: Implement a Simple Web Crawler
#### Problem Statement:
You are tasked with implementing a simple web crawler that extracts all unique URLs from a given webpage up to a certain depth. The crawler should visit each URL starting from the provided URL and continue upto the specified depth, collecting URLs at... | import requests
import re
from typing import List
from urllib.parse import urljoin
def extract_urls(html_content: str) -> List[str]:
"""
Extracts all unique URLs from the given HTML content.
Args:
html_content (str): A string containing the HTML content to parse.
Returns:
List[str]: A... | import pytest
from solution import extract_urls
def test_extract_urls_basic():
html_content = '<a href="http://example.com">Example</a>'
assert extract_urls(html_content) == ["http://example.com"]
def test_extract_urls_multiple():
html_content = '''
<a href="http://example.com">Example</a>
<a href... | [
{
"docstring": "Extracts all unique URLs from the given HTML content.\n\nArgs:\nhtml_content (str): A string containing the HTML content to parse.\n\nReturns:\nList[str]: A list of unique URLs found in the HTML content.",
"function_declaration": "def extract_urls(html_content):",
"function_name": "extra... | [
0,
0,
0,
1,
1,
0,
1,
0,
1,
1
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import requests\nimport re\nfrom typing import List, Set\nfrom urllib.parse import urljoin\n\ndef extract_urls(html_content: str) -> List[str]:\n \"\"\"\n ... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "0000033759",
"row_id": 33759,
"seed_ids": "[369]"
} | 0.622151 | Algorithm_33759 | I | [
"extract_urls",
"web_crawler"
] | 2 | [
[
"web_crawler",
"extract_urls"
]
] | 1 | [] | false | [] | false | pytest | true | [
"requests"
] | false | 3a35ba8b935e1c8fbef29ee78825c7a0c0f52f5a | 4c4c5586bff4f35e3f99c4c3b5ec79f1082bb0ad | |||
v1.0 | instruct | Algorithm | Algorithm_33812_I | ### Scenario:
You are developing a spell-checking feature for a word processor. The feature needs to suggest the closest correct spelling for a given word based on a dictionary of valid English words. The closeness is determined by the minimum number of single-character edits (insertions, deletions, or substitutions) r... | from typing import List
def edit_distance(word1: str, word2: str) -> int:
m, n = len(word1), len(word2)
dp = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(m + 1):
for j in range(n + 1):
if i == 0:
dp[i][j] = j
elif j == 0:
dp[i][j] = i... | from solution import spell_check
def test_spell_check_basic():
assert spell_check("speling", ["spelling", "spelt", "spell"]) == "spelling"
def test_spell_check_single_letter():
assert spell_check("a", ["a", "b", "c"]) == "a"
def test_spell_check_empty_word():
assert spell_check("", ["a", ""]) == ""
def ... | [
{
"docstring": null,
"function_declaration": "def edit_distance(word1, word2):",
"function_name": "edit_distance",
"parameter_list": "(word1, word2)"
},
{
"docstring": null,
"function_declaration": "def spell_check(word, dictionary):",
"function_name": "spell_check",
"parameter_l... | [
0,
1,
0,
0,
0,
1,
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": "from typing import List\n\ndef edit_distance(word1: str, word2: str) -> int:\n m, n = len(word1), len(word2)\n dp = [[0] * (n + 1) for _ in range(m + 1)]\n... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000033812",
"row_id": 33812,
"seed_ids": "[4354]"
} | 0.678217 | Algorithm_33812 | I | [
"edit_distance",
"spell_check"
] | 2 | [
[
"spell_check",
"edit_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 8ed78cd00a97259baa5d4ca4577b8a435cee3b8c | 6ab1a12f866bda3b277b31e8de38b362ad3b0f07 | |||
v1.0 | instruct | Algorithm | Algorithm_33823_I | ### Question: Monitor and Alert for Temperature Anomalies
In this task, you will handle temperature data from a weather monitoring service. Your goal is to implement two functions to fetch and analyze temperature data.
#### Task 1: **Calculate Average Temperature for a Date Range**
Write a function `calculate_averag... | import requests
from datetime import datetime, timedelta
API_URL = "https://api.weather.com/v1/location/{location}/observations/historical.json"
def get_temperature_data(start: str, end: str):
"""
Fetches temperature data from the weather API for the given date range.
Here, we are assuming that 'location'... | from solution import calculate_average_temperature, detect_temperature_drop
def mock_get_temperature_data(start: str, end: str):
"""
Mock function to simulate fetching temperature data.
"""
mock_data = {
"observations": [
{"validTimeLocal": "2021-06-01T00:00:00-0400", "temperature":... | [
{
"docstring": "Fetches temperature data from the weather API for the given date range.\nHere, we are assuming that 'location' and 'apiKey' are already defined.",
"function_declaration": "def get_temperature_data(start, end):",
"function_name": "get_temperature_data",
"parameter_list": "(start, end)... | [
0,
0,
0,
0,
0,
0,
0,
1,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import requests\nfrom datetime import datetime, timedelta\n\ndef fetch_temperature_data(start: str, end: str) -> list:\n \"\"\"\n Mock function to fetch te... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "0000033823",
"row_id": 33823,
"seed_ids": "[2358]"
} | 0.603387 | Algorithm_33823 | I | [
"get_temperature_data",
"calculate_average_temperature",
"detect_temperature_drop"
] | 3 | [
[
"calculate_average_temperature",
"get_temperature_data"
],
[
"detect_temperature_drop",
"get_temperature_data"
]
] | 2 | [] | false | [] | false | pytest | true | [
"requests"
] | false | 37922a8a88ca9869856edc8c6ed41d8e9983f12f | 874d953c0f094d1572756e3b04b08155301e5df9 | |||
v1.0 | instruct | Algorithm | Algorithm_33873_I | ### Sorting Large Text Files
You are provided with a very large text file containing many lines of words. Each line is either a single word or consists of words separated by spaces. Your task is to create a Python script to sort all the lines of this file in alphabetical order and write the sorted lines to a new file.... | def read_lines(input_file):
"""
Reads all lines from the input file and returns a list of lines.
Parameters:
input_file (str): Path to the input file.
Returns:
list: List of lines from the file.
"""
with open(input_file, 'r') as file:
lines = file.readlines()
return... | from solution import read_lines, sort_lines, write_lines, sort_large_text_file
import os
def test_read_lines(tmp_path):
# Arrange
input_file = tmp_path / "input.txt"
input_file.write_text("apple\nbanana\norange\napple banana\n")
# Act
lines = read_lines(input_file)
# Assert
assert... | [
{
"docstring": "Reads all lines from the input file and returns a list of lines.\n\nParameters:\ninput_file (str): Path to the input file.\n\nReturns:\nlist: List of lines from the file.",
"function_declaration": "def read_lines(input_file):",
"function_name": "read_lines",
"parameter_list": "(input... | [
1,
1,
0,
1,
1,
1,
1,
1,
1,
1
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def read_lines(input_file):\n \"\"\"\n Reads all lines from the input file.\n \n :param input_file: Path to the input file\n :return: List of line... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000033873",
"row_id": 33873,
"seed_ids": "[1431]"
} | 0.554695 | Algorithm_33873 | I | [
"read_lines",
"sort_lines",
"write_lines",
"sort_large_text_file"
] | 4 | [
[
"sort_large_text_file",
"read_lines"
],
[
"sort_large_text_file",
"sort_lines"
],
[
"sort_large_text_file",
"write_lines"
]
] | 3 | [
"read_lines"
] | false | [] | false | pytest | true | [] | true | 27882d448d4e4b660ab2d288463ebf443afd8ca6 | e967e043fa6b3c3926872573239ad22a5891eae6 | |||
v1.0 | instruct | Algorithm | Algorithm_33898_I | ### Coding Assessment Question
#### Context
Graph traversal and pathfinding are crucial concepts in computer science often applied in various domains such as navigation systems, networking, and game development. One common problem is to determine the shortest path in a weighted graph, which can involve heuristics for ... | import heapq
def a_star(graph, start, goal, heuristic):
"""
Performs the A* algorithm to find the shortest path in a weighted graph.
:param graph: A dictionary representing the adjacency list of the graph.
:param start: The starting node label.
:param goal: The goal node label.
:param heur... | from solution import a_star
def test_short_path():
graph = {
0: [(1, 1), (2, 4)],
1: [(0, 1), (2, 2), (3, 5)],
2: [(0, 4), (1, 2), (3, 1)],
3: [(1, 5), (2, 1)]
}
start = 0
goal = 3
heuristic = lambda n, g: abs(n - g)
assert a_star(graph, start, goal, heuristic) =... | [
{
"docstring": "Performs the A* algorithm to find the shortest path in a weighted graph.\n\n:param graph: A dictionary representing the adjacency list of the graph.\n:param start: The starting node label.\n:param goal: The goal node label.\n:param heuristic: A function that returns the heuristic estimate to the... | [
1,
1,
1,
1,
1,
1,
1,
0,
1,
1
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import heapq\n\ndef a_star(graph, start, goal, heuristic):\n \"\"\"\n Returns the shortest path from start to goal using the A* algorithm.\n \n Args:... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000033898",
"row_id": 33898,
"seed_ids": "[2307]"
} | 0.68894 | Algorithm_33898 | I | [
"a_star",
"reconstruct_path"
] | 2 | [
[
"a_star",
"reconstruct_path"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 2b550898d2b51733bd76aa3fcbe9614e8043a0d9 | 31976b22a27af4516b0b4f9efcca2f2a1ec1627d | |||
v1.0 | instruct | Algorithm | Algorithm_34062_I | ### Question
You have been given the task of developing a simple spell-checking tool that identifies and corrects common misspellings in a given text based on a provided dictionary.
#### Function Specifications:
1. **spell_check(text: str, dictionary: Set[str]) -> str**
* Takes a `text` string and a `dictionary` ... | def find_closest_word(word, dictionary):
"""
Finds and returns the closest word from the dictionary to the given word.
Uses one character edit distance (Levenshtein distance with a maximum of 1) to determine the closest word.
"""
min_distance = float('inf')
closest_word = word
def calcu... | from solution import spell_check, find_closest_word
def test_find_closest_word_single_substitution():
dictionary = {"this", "is", "a", "test", "message"}
assert find_closest_word("tst", dictionary) == "test"
def test_find_closest_word_single_insertion():
dictionary = {"this", "is", "a", "test", "message"}... | [
{
"docstring": "Finds and returns the closest word from the dictionary to the given word.\nUses one character edit distance (Levenshtein distance with a maximum of 1) to determine the closest word.",
"function_declaration": "def find_closest_word(word, dictionary):",
"function_name": "find_closest_word"... | [
1,
1,
1,
1,
0,
1,
1,
1,
0,
1
] | 8 | easy | 0.8 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def find_closest_word(word, dictionary):\n \"\"\"\n Finds and returns the closest word from the dictionary to the given word\n using one character edit ... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "0000034062",
"row_id": 34062,
"seed_ids": "[247]"
} | 0.58879 | Algorithm_34062 | I | [
"find_closest_word",
"spell_check"
] | 2 | [
[
"spell_check",
"find_closest_word"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | aeaad52650d7f173c40405fabea2ede7de02b65b | ca4ce6323bdb6443317f369d70e3bba496785e26 | |||
v1.0 | instruct | Algorithm | Algorithm_34074_I | ## Fibonacci Sequence Algorithm Optimization
### Objective
Implement a Python function that efficiently computes the nth Fibonacci number. You are required to write a function optimized for both space and time complexity.
### Description
The Fibonacci sequence is a series of numbers where each number is the sum of th... | def multiply_matrices(A, B):
"""
Multiplies two 2x2 matrices A and B.
"""
return [
[A[0][0] * B[0][0] + A[0][1] * B[1][0], A[0][0] * B[0][1] + A[0][1] * B[1][1]],
[A[1][0] * B[0][0] + A[1][1] * B[1][0], A[1][0] * B[0][1] + A[1][1] * B[1][1]]
]
def matrix_power(matrix, n):
"""
... | def test_optimized_fibonacci():
# Testing base cases
assert optimized_fibonacci(0) == 0
assert optimized_fibonacci(1) == 1
# Testing small values
assert optimized_fibonacci(2) == 1
assert optimized_fibonacci(3) == 2
assert optimized_fibonacci(4) == 3
assert optimized_fibonacci(5) ==... | [
{
"docstring": "Multiplies two 2x2 matrices A and B.",
"function_declaration": "def multiply_matrices(A, B):",
"function_name": "multiply_matrices",
"parameter_list": "(A, B)"
},
{
"docstring": "Performs matrix exponentiation. Returns matrix^n.",
"function_declaration": "def matrix_power... | [
1,
0,
0,
0,
1,
1,
0,
0,
0,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def multiply_matrices(A, B):\n \"\"\"\n Multiplies two 2x2 matrices A and B.\n \"\"\"\n return [\n [A[0][0] * B[0][0] + A[0][1] * B[1][0], A[0... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "0000034074",
"row_id": 34074,
"seed_ids": "[309]"
} | 0.720877 | Algorithm_34074 | I | [
"multiply_matrices",
"matrix_power",
"optimized_fibonacci"
] | 3 | [
[
"matrix_power",
"multiply_matrices"
],
[
"optimized_fibonacci",
"matrix_power"
]
] | 2 | [] | false | [] | false | pytest | false | [] | true | a0a25be3a7255db84f065a67cef269467a3bed51 | e9fba22b098123d2d1783342611cf3af2adaf85e | |||
v1.0 | instruct | Algorithm | Algorithm_34082_I | ## Question: Least Common Multiple (LCM) of Three Numbers
#### Scenario
Given three integers, determine the least common multiple (LCM) of these numbers. The least common multiple of three integers is the smallest positive integer that is divisible by all three of the given integers.
### Task
Write a function:
```py... | import math
def find_lcm(x, y):
"""
Helper function to find the least common multiple (LCM) of two numbers.
"""
return x * y // math.gcd(x, y)
def find_lcm_of_three(a: int, b: int, c: int) -> int:
"""
Determine and return the least common multiple (LCM) of three integers.
"""
lcm_ab = ... | from solution import find_lcm_of_three
def test_find_lcm_of_three():
assert find_lcm_of_three(4, 6, 8) == 24
assert find_lcm_of_three(12, 15, 20) == 60
assert find_lcm_of_three(7, 13, 19) == 1729
assert find_lcm_of_three(1, 1, 1) == 1
assert find_lcm_of_three(10, 20, 30) == 60
assert find_lcm_o... | [
{
"docstring": "Helper function to find the least common multiple (LCM) of two numbers.",
"function_declaration": "def find_lcm(x, y):",
"function_name": "find_lcm",
"parameter_list": "(x, y)"
},
{
"docstring": "Determine and return the least common multiple (LCM) of three integers.",
"f... | [
0,
0,
0,
0,
0,
0,
1,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import math\n\ndef lcm(x, y):\n \"\"\"\n Returns the least common multiple (LCM) of two integers x and y.\n \"\"\"\n return abs(x * y) // math.gcd(x,... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "0000034082",
"row_id": 34082,
"seed_ids": "[2176]"
} | 0.653864 | Algorithm_34082 | I | [
"find_lcm",
"find_lcm_of_three"
] | 2 | [
[
"find_lcm_of_three",
"find_lcm"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 8a06568f84f1efae7ec756e9f7ad1b5e0a5ab05e | abe3eef005c087b843869f478d44687582a514ec | |||
v1.0 | instruct | Algorithm | Algorithm_34302_I | ### Scenario
You are developing a module for a financial application that must handle and process dates efficiently. You need a function that calculates the difference between two given dates and returns the result in days. Given your understanding of date manipulation, implement this functionality without relying on a... | def is_leap_year(year):
"""Check if a year is a leap year."""
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
return True
else:
return False
return True
return False
def days_in_month(month, year):
"""Return the number of... | def test_is_leap_year():
assert is_leap_year(2020) == True
assert is_leap_year(2019) == False
assert is_leap_year(2000) == True
assert is_leap_year(1900) == False
def test_days_in_month():
assert days_in_month(1, 2020) == 31
assert days_in_month(2, 2020) == 29
assert days_in_month(2, 2021) ... | [
{
"docstring": "Check if a year is a leap year.",
"function_declaration": "def is_leap_year(year):",
"function_name": "is_leap_year",
"parameter_list": "(year)"
},
{
"docstring": "Return the number of days in a given month of a particular year.",
"function_declaration": "def days_in_mont... | [
1,
1,
1,
1,
0,
1,
0,
1,
0,
1
] | 7 | easy | 0.7 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def is_leap_year(year):\n \"\"\"\n Returns True if the given year is a leap year, otherwise False.\n \"\"\"\n if year % 4 == 0:\n if year % 10... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000034302",
"row_id": 34302,
"seed_ids": "[5161]"
} | 0.564655 | Algorithm_34302 | I | [
"is_leap_year",
"days_in_month",
"days_in_year_to_date",
"days_between_years",
"days_difference"
] | 5 | [
[
"days_between_years",
"is_leap_year"
],
[
"days_difference",
"days_between_years"
],
[
"days_difference",
"days_in_year_to_date"
],
[
"days_difference",
"is_leap_year"
],
[
"days_in_month",
"is_leap_year"
],
[
"days_in_year_to_date",
"days_in_mon... | 6 | [] | false | [] | false | pytest | false | [] | true | f555b335db0fec04f50f909c4bcb060cbc2ebec6 | b4f144da3844a09f5a73ba4c223902a1deb7bf2e | |||
v1.0 | instruct | Algorithm | Algorithm_34316_I | ### Problem Statement
You are asked to work with binary search trees (BSTs) and perform two primary operations: inserting new nodes into the BST while maintaining its properties, and finding the k-th smallest element in the BST. Implement the insertion function `insert_into_bst` and the k-th smallest element finder fun... | from typing import Optional
from dataclasses import dataclass
@dataclass
class TreeNode:
data: int
left: Optional['TreeNode'] = None
right: Optional['TreeNode'] = None
def insert_into_bst(root: Optional[TreeNode], data: int) -> TreeNode:
"""
Insert a new value into the BST and return the root of t... | from solution import TreeNode, insert_into_bst, find_kth_smallest
def test_insert_into_bst():
root = insert_into_bst(None, 50)
assert root.data == 50
root = insert_into_bst(root, 30)
assert root.left.data == 30
root = insert_into_bst(root, 70)
assert root.right.data == 70
roo... | [] | [
0,
0,
0,
1,
0,
1,
1,
0,
1,
0
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from dataclasses import dataclass\n\n@dataclass\nclass TreeNode:\n data: int\n left: 'TreeNode' | None = None\n right: 'TreeNode' | None = None\n\ndef i... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000034316",
"row_id": 34316,
"seed_ids": "[1739]"
} | 0.532637 | Algorithm_34316 | I | [
"insert_into_bst",
"in_order_traversal",
"find_kth_smallest"
] | 3 | [
[
"find_kth_smallest",
"in_order_traversal"
]
] | 1 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | f13e2a2d2dd636133ec45b6749441c6c9f579206 | 7cf2b43ef2c486d475cf2a35d63e13fa0e9eafd7 | |||
v1.0 | instruct | Algorithm | Algorithm_34342_I | ### Coding Assessment Question
#### Sorting Large Files Split
**Scenario**: You are tasked with sorting a very large file that cannot fit entirely into memory. The file contains lines of text, and each line is a record that needs to be sorted based on a specified key. The primary key for sorting will be the first wor... | import heapq
import os
import tempfile
def split_and_sort(input_file: str, chunk_size: int, temp_file_prefix: str) -> list[str]:
temp_files = []
with open(input_file, 'r') as f:
while True:
lines = f.readlines(chunk_size)
if not lines:
break
lines.sor... | import os
def create_test_file(file_name: str, lines: list[str]):
with open(file_name, 'w') as f:
f.writelines(lines)
def test_split_and_sort():
test_input = 'test_input.txt'
create_test_file(test_input, ["apple alpha\n", "zebra zoo\n", "banana beta\n", "cherry cherry\n"])
temp_files = split_a... | [
{
"docstring": null,
"function_declaration": "def split_and_sort(input_file, chunk_size, temp_file_prefix):",
"function_name": "split_and_sort",
"parameter_list": "(input_file, chunk_size, temp_file_prefix)"
},
{
"docstring": null,
"function_declaration": "def merge_sorted_files(temp_fil... | [
0,
0,
0,
1,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import os\nimport heapq\nimport tempfile\n\ndef split_and_sort(input_file: str, chunk_size: int, temp_file_prefix: str) -> list[str]:\n \"\"\" Splits the larg... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "0000034342",
"row_id": 34342,
"seed_ids": "[4027]"
} | 0.486113 | Algorithm_34342 | I | [
"split_and_sort",
"merge_sorted_files",
"external_sort"
] | 3 | [
[
"external_sort",
"merge_sorted_files"
],
[
"external_sort",
"split_and_sort"
]
] | 2 | [] | false | [] | false | pytest | false | [] | true | 8820158430c619b1c9ceac8f580029163e2bed71 | 0d9da885e02be101519d55d9788df4adc145042d | |||
v1.0 | instruct | Algorithm | Algorithm_34363_I | ### Task
You are tasked with implementing a function that efficiently finds the k-th smallest element in an unsorted list. The function should utilize the Quickselect algorithm, which is designed for this purpose.
### Function Signature
```python
def kth_smallest(nums: List[int], k: int) -> int:
...
```
### Inp... | from typing import List
import random
def partition(nums, left, right):
pivot_index = random.randint(left, right)
nums[pivot_index], nums[right] = nums[right], nums[pivot_index] # Swap pivot with right-most element
pivot = nums[right]
i = left
for j in range(left, right):
if nums[j] <... | def test_kth_smallest():
assert kth_smallest([3, 2, 1, 5, 4], 2) == 2
assert kth_smallest([7, 10, 4, 3, 20, 15], 3) == 7
assert kth_smallest([10, 4, 5, 8, 6, 11, 26], 5) == 10
assert kth_smallest([1], 1) == 1
assert kth_smallest([3, 2, 1, 5, 4, 1], 1) == 1
assert kth_smallest([3, 2, 1, 5, 4, 1],... | [
{
"docstring": null,
"function_declaration": "def partition(nums, left, right):",
"function_name": "partition",
"parameter_list": "(nums, left, right)"
},
{
"docstring": null,
"function_declaration": "def quickselect(nums, left, right, k_smallest):",
"function_name": "quickselect",
... | [
1,
1,
1,
0,
0,
0,
1,
0,
1,
0
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import random\nfrom typing import List\n\ndef kth_smallest(nums: List[int], k: int) -> int:\n def quickselect(left: int, right: int, k_smallest: int) -> int:\... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000034363",
"row_id": 34363,
"seed_ids": "[1608]"
} | 0.627635 | Algorithm_34363 | I | [
"partition",
"quickselect",
"kth_smallest"
] | 3 | [
[
"kth_smallest",
"quickselect"
],
[
"quickselect",
"partition"
]
] | 2 | [] | false | [] | false | pytest | false | [] | true | ab63ee87ada4af750fe662a4214e37182468b5d3 | 255071b3a21d71739ef4d1618e32aa4a25f687af | |||
v1.0 | instruct | Algorithm | Algorithm_34386_I | ### Question: Generate and Analyze Weather Data
You are tasked with creating a program that retrieves and analyzes weather data using the OpenWeatherMap API. Your program should have the following functionalities:
1. **Fetch current weather data** for a given city.
2. **Analyze temperature trends** for a list of citi... | import requests
API_KEY = 'YOUR_API_KEY_HERE' # You should replace this with your actual API key
BASE_URL = 'http://api.openweathermap.org/data/2.5/weather'
def get_current_weather(city: str) -> dict:
"""
Fetches the current weather data for a given city.
Args:
- city (str): The name of the city... | from solution import get_current_weather, get_average_temperature
import pytest
def test_get_current_weather(monkeypatch):
class MockResponse:
@staticmethod
def json():
return {'main': {'temp': 15.0, 'humidity': 80}, 'weather': [{'description': 'clear sky'}]}
@staticmet... | [
{
"docstring": "Fetches the current weather data for a given city.\n\nArgs:\n- city (str): The name of the city for which to fetch weather data.\n\nReturns:\n- dict: A dictionary containing temperature, humidity, and weather description.",
"function_declaration": "def get_current_weather(city):",
"funct... | [
1,
0,
0,
1,
0,
0,
0,
1,
1,
0
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import requests\n\nAPI_KEY = 'your_api_key_here'\nBASE_URL = 'http://api.openweathermap.org/data/2.5/weather'\n\n\ndef get_current_weather(city: str) -> dict:\n ... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000034386",
"row_id": 34386,
"seed_ids": "[1924]"
} | 0.623428 | Algorithm_34386 | I | [
"get_current_weather",
"get_average_temperature"
] | 2 | [
[
"get_average_temperature",
"get_current_weather"
]
] | 1 | [] | false | [] | false | pytest | true | [
"requests"
] | false | 2c9d02bcca167564ec235d9b93b983a31dfda005 | 547f0988f16b92f085f0bbcb536145f7235bb51e | |||
v1.0 | instruct | Algorithm | Algorithm_34411_I | **Text-Based File Parsing for Data Analysis**
You are developing a text-processing tool that reads a structured text file and performs various data analysis tasks, such as extracting specific fields, summarizing data, and generating custom outputs. The text files follow a consistent structure but require parsing and p... | import json
import csv
from typing import List, Dict, Union
def read_file(file_path: str) -> str:
"""
Reads the content of the given file and returns it as a string.
"""
with open(file_path, 'r') as file:
data = file.read()
return data
def extract_fields(data: str, keys: List[str]) -> Dict... | import pytest
from solution import read_file, extract_fields, summarize_data, generate_output, text_file_parser
def test_read_file(tmp_path):
file_content = "name:John, age:30, score:90\nname:Jane, age:27, score:85"
file_path = tmp_path / "test.txt"
file_path.write_text(file_content)
result = read... | [
{
"docstring": "Reads the content of the given file and returns it as a string.",
"function_declaration": "def read_file(file_path):",
"function_name": "read_file",
"parameter_list": "(file_path)"
},
{
"docstring": "Extracts specific fields from the data based on the given keys.\nReturns a d... | [
1,
1,
0,
1,
0,
1,
1,
1,
0,
0
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import json\n\ndef read_file(file_path: str) -> str:\n \"\"\"\n Reads the contents of a structured text file and returns it as a string.\n \"\"\"\n w... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "0000034411",
"row_id": 34411,
"seed_ids": "[4303]"
} | 0.608275 | Algorithm_34411 | I | [
"read_file",
"extract_fields",
"summarize_data",
"generate_output",
"text_file_parser"
] | 5 | [
[
"text_file_parser",
"extract_fields"
],
[
"text_file_parser",
"generate_output"
],
[
"text_file_parser",
"read_file"
],
[
"text_file_parser",
"summarize_data"
]
] | 4 | [
"generate_output"
] | false | [] | false | pytest | true | [] | true | bc6e08041067edfd99c40224b80ce313b5277218 | c4027c9f51ee8bb3b006350c960ff0c157e60156 | |||
v1.0 | instruct | Algorithm | Algorithm_34436_I | ### Coding Challenge: Find the Digit Sum Palindrome
#### Problem Statement
You are tasked with finding the smallest positive integer \( N \) such that the sum of the digits of \( N \) is a palindrome and \( N \) itself is also a palindrome.
#### Functional Requirements:
Write a function `find_digit_sum_palindrome()` ... | def is_palindrome(num: int) -> bool:
return str(num) == str(num)[::-1]
def digit_sum(num: int) -> int:
return sum(int(digit) for digit in str(num))
def find_digit_sum_palindrome() -> int:
num = 1
while True:
if is_palindrome(num) and is_palindrome(digit_sum(num)):
return num
... | from solution import find_digit_sum_palindrome, is_palindrome, digit_sum
def test_is_palindrome():
assert is_palindrome(121) == True
assert is_palindrome(123) == False
assert is_palindrome(4) == True
assert is_palindrome(44) == True
assert is_palindrome(10) == False
def test_digit_sum():
asser... | [
{
"docstring": null,
"function_declaration": "def is_palindrome(num):",
"function_name": "is_palindrome",
"parameter_list": "(num)"
},
{
"docstring": null,
"function_declaration": "def digit_sum(num):",
"function_name": "digit_sum",
"parameter_list": "(num)"
},
{
"docstri... | [
1,
0,
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": "def is_palindrome(num: int) -> bool:\n return str(num) == str(num)[::-1]\n\ndef digit_sum(num: int) -> int:\n return sum(int(digit) for digit in str(num))\... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "0000034436",
"row_id": 34436,
"seed_ids": "[2563]"
} | 0.741507 | Algorithm_34436 | I | [
"is_palindrome",
"digit_sum",
"find_digit_sum_palindrome"
] | 3 | [
[
"find_digit_sum_palindrome",
"digit_sum"
],
[
"find_digit_sum_palindrome",
"is_palindrome"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 30ef86c0b7a02199bececc58ce08717721993c8b | c68113a8de83e72f5db37724a3371832ed226bd5 | |||
v1.0 | instruct | Algorithm | Algorithm_34520_I | ### Scenario
You are tasked with creating a simplified recommendation system for a movie streaming service. Given user ratings for a set of movies, you need to implement a function that predicts the ratings for movies a user hasn't rated yet.
### Requirements
1. Implement a function `recommend_movies` that takes in tw... | from typing import Dict, List
import numpy as np
def cosine_similarity(vec1: List[float], vec2: List[float]) -> float:
dot_product = np.dot(vec1, vec2)
magnitude1 = np.sqrt(np.dot(vec1, vec1))
magnitude2 = np.sqrt(np.dot(vec2, vec2))
if magnitude1 == 0 or magnitude2 == 0:
return 0
return do... | from solution import recommend_movies
def test_recommend_movies_single_user():
user_ratings = {
1: {101: 5.0, 102: 3.0, 103: 4.0},
}
predicted_ratings = recommend_movies(user_ratings, 1)
assert predicted_ratings == {}
def test_recommend_movies_no_common_movies():
user_ratings = {
1... | [
{
"docstring": null,
"function_declaration": "def cosine_similarity(vec1, vec2):",
"function_name": "cosine_similarity",
"parameter_list": "(vec1, vec2)"
},
{
"docstring": null,
"function_declaration": "def recommend_movies(user_ratings, predict_for_user):",
"function_name": "recomme... | [
1,
0,
0,
1,
0,
1,
1,
0,
0,
0
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import Dict, List\nimport numpy as np\n\ndef cosine_similarity(vec1: List[float], vec2: List[float]) -> float:\n dot_product = np.dot(vec1, vec2)\... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "0000034520",
"row_id": 34520,
"seed_ids": "[623]"
} | 0.61909 | Algorithm_34520 | I | [
"cosine_similarity",
"recommend_movies"
] | 2 | [
[
"recommend_movies",
"cosine_similarity"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | 28d5841148907aa6f0c0005b40beed4976fa4a7a | e67a72a723232e272adcd28a7613e6b96259131c | |||
v1.0 | instruct | Algorithm | Algorithm_34564_I | ### Question
Create a function that takes in a list of integers and returns a new list containing all the elements of the original list that are powers of 2. Provide both an iterative and a recursive version of the function.
#### Function Signature
```python
def filter_powers_of_2_iterative(lst: List[int]) -> List[in... | from typing import List
def is_power_of_2(n: int) -> bool:
"""
Checks if a number is a power of 2.
"""
return n > 0 and (n & (n - 1)) == 0
def filter_powers_of_2_iterative(lst: List[int]) -> List[int]:
"""
Filters the given list to return only the elements that are powers of 2.
Iterative i... | from solution import filter_powers_of_2_iterative, filter_powers_of_2_recursive
def test_filter_powers_of_2_iterative():
assert filter_powers_of_2_iterative([1, 2, 3, 4, 5, 8, 16, 32, 64, 100]) == [1, 2, 4, 8, 16, 32, 64]
assert filter_powers_of_2_iterative([1, 7, 15, 16, 32, 64, 128, 9]) == [1, 16, 32, 64, 12... | [
{
"docstring": "Checks if a number is a power of 2.",
"function_declaration": "def is_power_of_2(n):",
"function_name": "is_power_of_2",
"parameter_list": "(n)"
},
{
"docstring": "Filters the given list to return only the elements that are powers of 2.\nIterative implementation.",
"funct... | [
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 9 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef is_power_of_2(n: int) -> bool:\n \"\"\"\n Determines if a number is a power of 2.\n \"\"\"\n return n > 0 and (n & (n ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000034564",
"row_id": 34564,
"seed_ids": "[3400]"
} | 0.585352 | Algorithm_34564 | I | [
"is_power_of_2",
"filter_powers_of_2_iterative",
"filter_powers_of_2_recursive"
] | 3 | [
[
"filter_powers_of_2_iterative",
"is_power_of_2"
],
[
"filter_powers_of_2_recursive",
"is_power_of_2"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 0e9606fc1a24693f6e3ba40e20cff2903080b7ad | 8bad3ab7c18e57c76ec5122a331867e76c107e5b | |||
v1.0 | instruct | Algorithm | Algorithm_34584_I | ### Coding Assessment: Implementing K-Means Clustering
**Objective**: Implement the K-Means clustering algorithm to cluster a set of instances. You will develop the necessary functions to fit the K-Means model, predict cluster assignments for new data, and evaluate the clustering quality.
### Problem Statement
Given ... | import random
from math import sqrt
def fit_kmeans_model(features: list[list[float]], k: int, max_iter: int) -> dict:
"""
Fits K-Means model to the input features
"""
# Initializing centroids randomly from the features
centroids = random.sample(features, k)
for _ in range(max_iter):
... | from solution import fit_kmeans_model, predict_clusters, calculate_silhouette_score
def test_fit_kmeans_model():
features = [
[1.0, 2.0],
[1.5, 1.8],
[5.0, 8.0],
[8.0, 8.0],
[1.2, 1.9],
[6.0, 7.0],
[7.0, 7.5],
]
k = 2
max_iter = 100
model = fi... | [
{
"docstring": "Fits K-Means model to the input features",
"function_declaration": "def fit_kmeans_model(features, k, max_iter):",
"function_name": "fit_kmeans_model",
"parameter_list": "(features, k, max_iter)"
},
{
"docstring": null,
"function_declaration": "def euclidean_distance(poin... | [
1,
0,
1,
1,
1,
1,
1,
1,
0,
1
] | 8 | easy | 0.8 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import random\nimport math\nfrom collections import defaultdict\n\ndef fit_kmeans_model(features, k, max_iter):\n \"\"\"\n Fits a K-Means model to the inpu... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000034584",
"row_id": 34584,
"seed_ids": "[468]"
} | 0.654285 | Algorithm_34584 | I | [
"fit_kmeans_model",
"euclidean_distance",
"predict_clusters",
"calculate_silhouette_score"
] | 4 | [
[
"fit_kmeans_model",
"euclidean_distance"
],
[
"predict_clusters",
"euclidean_distance"
]
] | 2 | [] | false | [] | false | pytest | true | [
"sklearn"
] | false | 14bafb64d21c05f37c596d41ac471d5d55a7c27e | 6526aab33eb5d131590885673c77741477975d72 | |||
v1.0 | instruct | Algorithm | Algorithm_34588_I | ### Coding Challenge: User Activity Analyzer
Your task is to create a Python function that analyzes user activity on a social media platform. The function should aggregate activities from two sources: user_posts and user_comments. The output should provide an overview of the user's engagement metrics, including total ... | from datetime import datetime
# Assuming these functions are given for fetching data
def user_posts(user_id, start_date, end_date):
# Mock data for demonstration purposes
return [
{"post_id": 1, "date": "2023-09-15"},
{"post_id": 2, "date": "2023-09-18"},
]
def user_comments(user_id, s... | import pytest
from solution import analyze_user_activity
# Mock the data fetching functions
def mock_user_posts(user_id, start_date, end_date):
if user_id == 1:
return [
{"post_id": 1, "date": "2023-09-15"},
{"post_id": 2, "date": "2023-09-18"},
]
if user_id == 2:
... | [
{
"docstring": null,
"function_declaration": "def user_posts(user_id, start_date, end_date):",
"function_name": "user_posts",
"parameter_list": "(user_id, start_date, end_date)"
},
{
"docstring": null,
"function_declaration": "def user_comments(user_id, start_date, end_date):",
"func... | [
0,
0,
1,
0,
0,
1,
1,
0,
0,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from datetime import datetime\n\ndef analyze_user_activity(user_id: int, start_date: str, end_date: str) -> dict:\n def validate_date(date_str):\n try:... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "0000034588",
"row_id": 34588,
"seed_ids": "[2556]"
} | 0.594421 | Algorithm_34588 | I | [
"user_posts",
"user_comments",
"analyze_user_activity"
] | 3 | [
[
"analyze_user_activity",
"user_comments"
],
[
"analyze_user_activity",
"user_posts"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 35caea13626055f3356d6ae2232eaf338bc1a12f | 84dc81505f1e06d5e3c88f75ba891a0ea31cdde5 | |||
v1.0 | instruct | Algorithm | Algorithm_34696_I | ### Log File Parser and Analyzer
You are given a log file in plain text format, where each line represents a log entry. Each log entry includes the timestamp, log level, and a message, all separated by a pipe (`|`) symbol. Your task is to implement a log file parser and analyzer with the following features:
* **Log Fi... | import datetime
def parse_log_line(line):
timestamp, level, message = line.strip().split('|', 2)
return datetime.datetime.strptime(timestamp, "%Y-%m-%d %H:%M:%S"), level, message
def filter_logs(file_path, log_level=None, start_time=None, end_time=None):
start_time = datetime.datetime.strptime(start_time,... | from solution import filter_logs, count_log_levels, parse_log_line
import datetime
# Create sample log file for tests
import tempfile
sample_log_content = """2023-10-01 14:45:00|INFO|Started processing
2023-10-01 14:46:01|ERROR|Failed to process request
2023-10-01 14:47:02|DEBUG|Running garbage collection
2023-10-01 ... | [
{
"docstring": null,
"function_declaration": "def parse_log_line(line):",
"function_name": "parse_log_line",
"parameter_list": "(line)"
},
{
"docstring": null,
"function_declaration": "def filter_logs(file_path, log_level=None, start_time=None, end_time=None):",
"function_name": "fil... | [
1,
1,
1,
0,
1,
1,
1,
0,
1,
1
] | 8 | easy | 0.8 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from datetime import datetime\n\ndef parse_log_line(line):\n \"\"\"\n Parses a single line of log entry.\n \n Parameters:\n line (str): A sing... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000034696",
"row_id": 34696,
"seed_ids": "[2300]"
} | 0.724121 | Algorithm_34696 | I | [
"parse_log_line",
"filter_logs",
"count_log_levels"
] | 3 | [
[
"count_log_levels",
"parse_log_line"
],
[
"filter_logs",
"parse_log_line"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 0268d4f61fc0c0602ec19ed2d6184b4d7be45b86 | 5ecac850f3a3c3b10083b471f2556dbc84764fc6 | |||
v1.0 | instruct | Algorithm | Algorithm_34723_I | ### Arm-strong Numbers: Check & List
#### Scenario
You need to write a program to identify and list Armstrong numbers within a given range. An Armstrong number (also known as a narcissistic number) is a number that is equal to the sum of its own digits each raised to the power of the number of digits.
#### Input and ... | def is_armstrong_number(num: int) -> bool:
"""
Check if the given number is an Armstrong number.
Args:
num (int): The number to check.
Returns:
bool: True if the number is an Armstrong number, False otherwise.
"""
digits = [int(d) for d in str(num)]
n = len(digits)
return num ==... | from solution import is_armstrong_number, list_armstrong_numbers
def test_is_armstrong_number():
assert is_armstrong_number(153) is True
assert is_armstrong_number(9474) is True
assert is_armstrong_number(123) is False
assert is_armstrong_number(0) is True
def test_list_armstrong_numbers():
assert... | [
{
"docstring": "Check if the given number is an Armstrong number.\nArgs:\nnum (int): The number to check.\n\nReturns:\nbool: True if the number is an Armstrong number, False otherwise.",
"function_declaration": "def is_armstrong_number(num):",
"function_name": "is_armstrong_number",
"parameter_list"... | [
1,
1,
0,
1,
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": "def is_armstrong_number(num: int) -> bool:\n \"\"\"\n Check if the given number is an Armstrong number.\n Args:\n num (int): The number to check.\n\n... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000034723",
"row_id": 34723,
"seed_ids": "[3220]"
} | 0.54015 | Algorithm_34723 | I | [
"is_armstrong_number",
"list_armstrong_numbers"
] | 2 | [
[
"list_armstrong_numbers",
"is_armstrong_number"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | fb9751ec234bcc0dc1e74525801197808fd4a665 | 24d626f1258ff10ab1213c8034174dee3a09daec | |||
v1.0 | instruct | Algorithm | Algorithm_34765_I | ### Coding Assessment Question
#### Problem:
You are provided with a library that can calculate basic arithmetic operations, along with functions to determine whether an integer is a prime number. Your task is to implement a function that identifies the smallest prime number greater than a given integer and utilizes t... | # Assume the library functions are imported from the library
# from library import is_prime, next_integer
def is_prime(x: int) -> bool:
"""
Mock function for library's is_prime.
This implementation is just for testing purposes.
"""
if x <= 1: return False
if x <= 3: return True
if x % 2 == ... | def test_next_prime_number_below_10():
assert next_prime_number(10) == 11
def test_next_prime_number_with_prime():
assert next_prime_number(11) == 13
def test_next_prime_number_large_gap():
assert next_prime_number(14) == 17
def test_next_prime_number_high_value():
assert next_prime_number(100) == 10... | [
{
"docstring": "Mock function for library's is_prime.\nThis implementation is just for testing purposes.",
"function_declaration": "def is_prime(x):",
"function_name": "is_prime",
"parameter_list": "(x)"
},
{
"docstring": "Mock function for library's next_integer\nThis implementation is just... | [
0,
1,
0,
0,
0,
1,
1,
1,
1,
0
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "# Assume prime_library is the hypothetical library that provides prime checking functions.\n# For the purposes of this task, a mock implementation is provided be... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "0000034765",
"row_id": 34765,
"seed_ids": "[728]"
} | 0.74169 | Algorithm_34765 | I | [
"is_prime",
"next_integer",
"next_prime_number"
] | 3 | [
[
"next_prime_number",
"is_prime"
],
[
"next_prime_number",
"next_integer"
]
] | 2 | [] | false | [] | false | pytest | false | [] | true | a3f95d7df17b69380e19956c8d17efec199efd81 | 9521aae22b1360eb9480a7d9139c00a9fd798a58 | |||
v1.0 | instruct | Algorithm | Algorithm_34783_I | ### Problem Statement
You have been given the task of improving the performance of string comparison operations within a dataset containing various strings. Your goal is to efficiently find the longest common prefix shared among a list of strings using a Divide and Conquer approach. This problem will evaluate your und... | from typing import List
def common_prefix(left: str, right: str) -> str:
min_length = min(len(left), len(right))
for i in range(min_length):
if left[i] != right[i]:
return left[:i]
return left[:min_length]
def longest_common_prefix_helper(strs: List[str], l: int, r: int) -> str:
if... | from solution import longest_common_prefix
def test_common_cases():
assert longest_common_prefix(["flower","flow","flight"]) == "fl"
assert longest_common_prefix(["dog","racecar","car"]) == ""
assert longest_common_prefix(["interspecies","interstellar","interstate"]) == "inters"
def test_edge_cases():
... | [
{
"docstring": null,
"function_declaration": "def common_prefix(left, right):",
"function_name": "common_prefix",
"parameter_list": "(left, right)"
},
{
"docstring": null,
"function_declaration": "def longest_common_prefix_helper(strs, l, r):",
"function_name": "longest_common_prefix... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 10 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef common_prefix(str1: str, str2: str) -> str:\n min_length = min(len(str1), len(str2))\n for i in range(min_length):\n ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000034783",
"row_id": 34783,
"seed_ids": "[4876]"
} | 0.767819 | Algorithm_34783 | I | [
"common_prefix",
"longest_common_prefix_helper",
"longest_common_prefix"
] | 3 | [
[
"longest_common_prefix",
"longest_common_prefix_helper"
],
[
"longest_common_prefix_helper",
"common_prefix"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 651345ebc350f74e42b89165d23097f2580b92dc | 9f886b12ecff2cdb01293c15caa62a9c787847d0 | |||
v1.0 | instruct | Algorithm | Algorithm_34807_I | ### Problem Statement
You are developing a new application that needs to compute the number of distinct island shapes in a given 2D grid. An island is a group of connected `1`s (land) connected horizontally or vertically (not diagonally). Two islands are considered distinct if one island's shape is different from anoth... | from typing import List, Set, Tuple
def rotate_90(shape):
""" Rotate the shape by 90 degrees """
return [(y, -x) for x, y in shape]
def reflect(shape):
""" Reflect the shape about the y-axis """
return [(-x, y) for x, y in shape]
def normalize_shape(shape):
""" Normalize the shape by rotating and... | import pytest
from solution import num_distinct_islands
def test_example_1():
grid = [
[1, 1, 0, 0, 0],
[1, 0, 0, 0, 1],
[0, 0, 0, 1, 1],
[0, 0, 0, 0, 0],
[1, 1, 0, 1, 1]
]
assert num_distinct_islands(grid) == 3
def test_example_2():
grid = [
[1, 1, 1],
... | [
{
"docstring": "Rotate the shape by 90 degrees ",
"function_declaration": "def rotate_90(shape):",
"function_name": "rotate_90",
"parameter_list": "(shape)"
},
{
"docstring": "Reflect the shape about the y-axis ",
"function_declaration": "def reflect(shape):",
"function_name": "refle... | [
0,
0,
0,
0,
1,
1,
0,
0,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List, Set, Tuple\n\ndef get_rotations_and_reflections(shape: List[Tuple[int, int]]) -> Set[Tuple[Tuple[int, int], ...]]:\n transformations ... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "0000034807",
"row_id": 34807,
"seed_ids": "[827]"
} | 0.610045 | Algorithm_34807 | I | [
"rotate_90",
"reflect",
"normalize_shape",
"num_distinct_islands"
] | 4 | [
[
"normalize_shape",
"reflect"
],
[
"normalize_shape",
"rotate_90"
],
[
"num_distinct_islands",
"normalize_shape"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 92e3d5b08eaba5defb63453ebe6cf02855a7eb9c | 1e6b558e16fb1716c7afd10239a996ea4982d1a6 | |||
v1.0 | instruct | Algorithm | Algorithm_35015_I | ### Matrix Rotation Checker
You are required to write a function that checks if two given matrices are rotations of each other by 90, 180, or 270 degrees. The matrices will be represented as lists of lists, with each inner list representing a row of the matrix.
### Function Definition
Implement the following functio... | from typing import List
def rotate_90(matrix: List[List[int]]) -> List[List[int]]:
n = len(matrix)
return [[matrix[n - 1 - j][i] for j in range(n)] for i in range(n)]
def rotate_180(matrix: List[List[int]]) -> List[List[int]]:
return rotate_90(rotate_90(matrix))
def rotate_270(matrix: List[List[int]]) ->... | from solution import are_rotations
def test_are_rotations_90_degree():
matrix1 = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
matrix2 = [
[7, 4, 1],
[8, 5, 2],
[9, 6, 3]
]
assert are_rotations(matrix1, matrix2) == True
def test_are_rotations_180_degree():
... | [
{
"docstring": null,
"function_declaration": "def rotate_90(matrix):",
"function_name": "rotate_90",
"parameter_list": "(matrix)"
},
{
"docstring": null,
"function_declaration": "def rotate_180(matrix):",
"function_name": "rotate_180",
"parameter_list": "(matrix)"
},
{
"d... | [
1,
1,
0,
1,
1,
1,
1,
0,
1,
1
] | 8 | easy | 0.8 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef rotate_90(matrix: List[List[int]]) -> List[List[int]]:\n \"\"\"\n Rotates the given matrix by 90 degrees clockwise.\n \"\... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000035015",
"row_id": 35015,
"seed_ids": "[4262]"
} | 0.489386 | Algorithm_35015 | I | [
"rotate_90",
"rotate_180",
"rotate_270",
"are_rotations"
] | 4 | [
[
"are_rotations",
"rotate_180"
],
[
"are_rotations",
"rotate_270"
],
[
"are_rotations",
"rotate_90"
],
[
"rotate_180",
"rotate_90"
],
[
"rotate_270",
"rotate_180"
],
[
"rotate_270",
"rotate_90"
]
] | 6 | [] | false | [] | false | pytest | true | [] | true | 1cb8ffbe34ef370264c8193d6514ef1e71b0fe6e | 8ed47c117c3cb4134270b731307e18cb873b6c93 | |||
v1.0 | instruct | Algorithm | Algorithm_35022_I | ### Problem Statement
A company has developed a custom sorting algorithm that sorts an array of integers based on the number of unique prime factors each integer contains. For integers with the same number of unique prime factors, the standard numerical sort is applied. Your task is to implement this custom sorting alg... | from typing import List
import math
def count_unique_prime_factors(n: int) -> int:
unique_primes = set()
if n < 2:
return 0
while n % 2 == 0:
unique_primes.add(2)
n //= 2
for i in range(3, int(math.sqrt(n)) + 1, 2):
while n % i == 0:
unique_primes.add(i)
... | from solution import unique_prime_sort
def test_unique_prime_sort_example_case():
arr = [15, 7, 8, 30, 21, 27, 10, 14]
expected = [7, 8, 27, 10, 14, 15, 21, 30]
assert unique_prime_sort(arr) == expected
def test_unique_prime_sort_single_element():
arr = [5]
expected = [5]
assert unique_prime_s... | [
{
"docstring": null,
"function_declaration": "def count_unique_prime_factors(n):",
"function_name": "count_unique_prime_factors",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def unique_prime_sort(arr):",
"function_name": "unique_prime_sort",
"paramete... | [
0,
0,
0,
0,
0,
1,
1,
0,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List\nimport math\n\ndef prime_factors(n: int) -> int:\n \"\"\"Returns the number of unique prime factors of n.\"\"\"\n if n < 2:\n ... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "0000035022",
"row_id": 35022,
"seed_ids": "[4964]"
} | 0.65366 | Algorithm_35022 | I | [
"count_unique_prime_factors",
"unique_prime_sort"
] | 2 | [
[
"unique_prime_sort",
"count_unique_prime_factors"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 923612f4507e4de4fc1f6558dd84ef882e69391b | f9b2326cbc58264ead52eb28e093143d16f977e7 | |||
v1.0 | instruct | Algorithm | Algorithm_35023_I | ### Question
**Problem Statement**:
You are provided with a function that calculates the factorial of a number using recursion. Your task is to extend this functionality to compute the double factorial of a number, also using recursion. A double factorial of a number \( n \), denoted as \( n!! \), is defined as the p... | def double_factorial(n: int) -> int:
"""
Returns the double factorial of a non-negative integer n.
"""
if n == 0 or n == -1:
return 1
if n < -1:
raise ValueError("The double factorial is not defined for negative integers other than -1.")
return n * double_factorial(n - 2)
def ge... | def test_double_factorial_positive_numbers():
assert double_factorial(7) == 105
assert double_factorial(8) == 384
assert double_factorial(5) == 15
def test_double_factorial_edge_cases():
assert double_factorial(0) == 1
assert double_factorial(-1) == 1
assert double_factorial(1) == 1
ass... | [
{
"docstring": "Returns the double factorial of a non-negative integer n.",
"function_declaration": "def double_factorial(n):",
"function_name": "double_factorial",
"parameter_list": "(n)"
},
{
"docstring": "Generates a list of double factorials from 0 to m.",
"function_declaration": "de... | [
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 double_factorial(n):\n \"\"\"\n Calculates the double factorial of n.\n \n Args:\n n (int): The number for which the double factorial is to be... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000035023",
"row_id": 35023,
"seed_ids": "[4163]"
} | 0.702832 | Algorithm_35023 | I | [
"double_factorial",
"generate_double_factorial_series"
] | 2 | [
[
"generate_double_factorial_series",
"double_factorial"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 53e87793ed78124b7823cf6e041ae80332271886 | 451840a89d743efdb3bbae7737df3de930ca4dbe | |||
v1.0 | instruct | Algorithm | Algorithm_35033_I | ### Coding Question: Implement an Automated Test Coverage Reporter
As part of your ongoing responsibilities to enhance code quality, you need to create a script that automatically calculates and reports test coverage for each Python script in your project whenever it's modified. This will help to maintain high code qu... | import os
import requests
import coverage
import json
import subprocess
def get_modified_files():
"""
Fetches the list of modified Python files in the latest commit using GitHub API.
"""
token = os.getenv('GITHUB_TOKEN')
repo = os.getenv('GITHUB_REPOSITORY')
headers = {
'Authorization'... | import os
from unittest.mock import patch, mock_open
from solution import get_modified_files, calculate_coverage, report_test_coverage
@patch('requests.get')
def test_get_modified_files(mock_get):
os.environ['GITHUB_TOKEN'] = 'fake_token'
os.environ['GITHUB_REPOSITORY'] = 'fake_user/fake_repo'
commit_data... | [
{
"docstring": "Fetches the list of modified Python files in the latest commit using GitHub API.",
"function_declaration": "def get_modified_files():",
"function_name": "get_modified_files",
"parameter_list": "()"
},
{
"docstring": "Runs the tests and calculates test coverage for the given P... | [
0,
0,
0,
1,
0,
1,
1,
0,
0,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import os\nimport requests\nimport coverage\nimport pytest\n\ndef get_modified_files() -> list[str]:\n \"\"\"\n Fetches the list of modified Python files i... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "0000035033",
"row_id": 35033,
"seed_ids": "[3967]"
} | 0.483663 | Algorithm_35033 | I | [
"get_modified_files",
"calculate_coverage",
"report_test_coverage"
] | 3 | [
[
"report_test_coverage",
"calculate_coverage"
],
[
"report_test_coverage",
"get_modified_files"
]
] | 2 | [] | false | [] | false | pytest | true | [
"coverage",
"requests"
] | false | 3b0552a28345d16c04cf1bfb4e8d7707c07033e6 | 2411576567e160165ff47197b54649c018fc058b | |||
v1.0 | instruct | Algorithm | Algorithm_35066_I | ### Coding Assessment Question:
#### Context:
You are designing an application to manage a library of books. Part of this application requires importing book data from various sources, consolidating the information, and presenting it in a user-friendly format. The data sources may vary in structure, sometimes includin... | import json
import xml.etree.ElementTree as ET
def parse_json(data):
"""
Parse JSON data and return a list of books.
"""
parsed = json.loads(data)
return parsed.get('books', [])
def parse_xml(data):
"""
Parse XML data and return a list of books.
"""
books = []
root = ET.fromstr... | def test_consolidate_books_data():
data_sources = [
{
"format": "json",
"content": '{"books":[{"title":"Book A","author":"Author 1","year":2020,"isbn":"1234"}]}'
},
{
"format": "xml",
"content": '<library><book><title>Book A</title><author>Auth... | [
{
"docstring": "Parse JSON data and return a list of books.",
"function_declaration": "def parse_json(data):",
"function_name": "parse_json",
"parameter_list": "(data)"
},
{
"docstring": "Parse XML data and return a list of books.",
"function_declaration": "def parse_xml(data):",
"fu... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
1
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import json\nimport xml.etree.ElementTree as ET\nfrom collections import defaultdict\n\ndef parse_json(data):\n return json.loads(data)\n\ndef parse_xml(data)... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000035066",
"row_id": 35066,
"seed_ids": "[2642]"
} | 0.556085 | Algorithm_35066 | I | [
"parse_json",
"parse_xml",
"parse_dict",
"normalize_book",
"consolidate_books_data"
] | 5 | [
[
"consolidate_books_data",
"normalize_book"
],
[
"consolidate_books_data",
"parse_dict"
],
[
"consolidate_books_data",
"parse_json"
],
[
"consolidate_books_data",
"parse_xml"
]
] | 4 | [] | false | [] | false | pytest | false | [] | true | 6519a52f4ea74324ee0e8e5fe8e39b737adcd31c | 2ee34e34ed020dd84df753f9a2022439d1b1155d | |||
v1.0 | instruct | Algorithm | Algorithm_35158_I | ### Problem Statement
#### Context
In modern software systems, efficient sorting algorithms are crucial in handling large datasets. One of the well-known algorithms is **Merge Sort**, which is a divide-and-conquer algorithm with a time complexity of O(n log n). For this task, you are required to implement the Merge So... | from typing import List
def merge_sort(arr: List[int]) -> List[int]:
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left_half = merge_sort(arr[:mid])
right_half = merge_sort(arr[mid:])
return merge(left_half, right_half)
def merge(left: List[int], right: List[int]) -> List[int]... | from solution import merge_sort
def test_merge_sort():
assert merge_sort([]) == []
assert merge_sort([1]) == [1]
assert merge_sort([2, 1]) == [1, 2]
assert merge_sort([5, 2, 4, 6, 1, 3]) == [1, 2, 3, 4, 5, 6]
assert merge_sort([38, 27, 43, 3, 9, 82, 10]) == [3, 9, 10, 27, 38, 43, 82]
assert mer... | [
{
"docstring": null,
"function_declaration": "def merge_sort(arr):",
"function_name": "merge_sort",
"parameter_list": "(arr)"
},
{
"docstring": null,
"function_declaration": "def merge(left, right):",
"function_name": "merge",
"parameter_list": "(left, right)"
}
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 10 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef merge_sort(arr: List[int]) -> List[int]:\n if len(arr) <= 1:\n return arr\n\n mid = len(arr) // 2\n left_half = me... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000035158",
"row_id": 35158,
"seed_ids": "[4755]"
} | 0.624656 | Algorithm_35158 | I | [
"merge_sort",
"merge"
] | 2 | [
[
"merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 0e01550bc8a0017a9afd0df63ef6d05b52c3a63d | 22488cac7c43bd57abf6a29c6a6dc52793ede9b2 | |||
v1.0 | instruct | Algorithm | Algorithm_35217_I | ### Question: Implement an Iterative Quick Sort
You have to implement the quick sort algorithm iteratively. Given a list of integers, return the list sorted in ascending order using an iterative quick sort.
#### Function Signature
```python
def iterative_quick_sort(arr: list[int]) -> list[int]:
pass
```
#### Inp... | def iterative_quick_sort(arr: list[int]) -> list[int]:
if len(arr) <= 1:
return arr
stack = [(0, len(arr) - 1)]
while stack:
start, end = stack.pop()
if start < end:
pivot_index = partition(arr, start, end)
if pivot_index - 1 > ... | from solution import iterative_quick_sort
def test_quick_sort_with_regular_list():
assert iterative_quick_sort([3, 6, 8, 10, 1, 2, 1]) == [1, 1, 2, 3, 6, 8, 10]
def test_quick_sort_with_duplicates():
assert iterative_quick_sort([1, 1, 1, 1, 1]) == [1, 1, 1, 1, 1]
def test_quick_sort_empty_list():
assert ... | [
{
"docstring": null,
"function_declaration": "def iterative_quick_sort(arr):",
"function_name": "iterative_quick_sort",
"parameter_list": "(arr)"
},
{
"docstring": null,
"function_declaration": "def partition(arr, low, high):",
"function_name": "partition",
"parameter_list": "(ar... | [
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 iterative_quick_sort(arr: list[int]) -> list[int]:\n \"\"\"\n Perform an iterative quick sort on the given list and return the sorted list.\n \"\"\"... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000035217",
"row_id": 35217,
"seed_ids": "[960]"
} | 0.576128 | Algorithm_35217 | I | [
"iterative_quick_sort",
"partition"
] | 2 | [
[
"iterative_quick_sort",
"partition"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 2c5f540beada7e35862cf69dce3df461ce356668 | 94068f6ccbb3ea8022bfde59e48783b495e71e29 | |||
v1.0 | instruct | Algorithm | Algorithm_35271_I | ### Problem Statement
Given a list of events with timestamps, write a function to identify overlapping events and return them in a specific format. Each event consists of a start time and an end time, both given as strings in "HH:MM" format. Overlapping events are events that share any part of their duration with anot... | from typing import List, Tuple
def parse_time(time_str: str) -> int:
"""Convert time string "HH:MM" into minutes since midnight."""
hours, minutes = map(int, time_str.split(":"))
return hours * 60 + minutes
def find_overlapping_events(events: List[Tuple[str, str]]) -> List[str]:
overlaps = []
... | def test_no_overlap():
events = [("09:00", "10:00"), ("10:30", "11:30"), ("12:00", "13:00")]
result = find_overlapping_events(events)
assert result == []
def test_single_overlap():
events = [("09:00", "11:00"), ("10:00", "12:00")]
result = find_overlapping_events(events)
expected = ["Event 1 [0... | [
{
"docstring": "Convert time string \"HH:MM\" into minutes since midnight.",
"function_declaration": "def parse_time(time_str):",
"function_name": "parse_time",
"parameter_list": "(time_str)"
},
{
"docstring": null,
"function_declaration": "def find_overlapping_events(events):",
"fun... | [
0,
0,
1,
0,
1,
1,
1,
1,
1,
1
] | 7 | easy | 0.7 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List, Tuple\n\ndef parse_time(time_str: str) -> int:\n \"\"\"\n Converts a time string in the format \"HH:MM\" to minutes since 00:00.\n... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000035271",
"row_id": 35271,
"seed_ids": "[1976]"
} | 0.552066 | Algorithm_35271 | I | [
"parse_time",
"find_overlapping_events"
] | 2 | [
[
"find_overlapping_events",
"parse_time"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 9aa20bb003597627203be90e4a276ae8c90c40f9 | ce9e1e882e575f2779bcfd4f4211df45f7bd3058 | |||
v1.0 | instruct | Algorithm | Algorithm_35277_I | ### Question: Palindrome Permutation Check
You are tasked with implementing two functions to determine if a given string is a permutation of a palindrome, and to generate one possible palindrome from the given string if it is a valid permutation of a palindrome.
#### Function 1: `is_palindrome_permutation(s: str) -> ... | def is_palindrome_permutation(s: str) -> bool:
"""
Check if any permutation of the input string can form a palindrome.
Ignore spaces and consider only lowercase letters.
"""
from collections import Counter
# Remove spaces and count characters
s = s.replace(' ', '')
char_count =... | from solution import is_palindrome_permutation, generate_palindrome
def test_is_palindrome_permutation():
assert is_palindrome_permutation("taco cat") == True
assert is_palindrome_permutation("racecar") == True
assert is_palindrome_permutation("hello world") == False
assert is_palindrome_permutation(""... | [
{
"docstring": "Check if any permutation of the input string can form a palindrome.\n\nIgnore spaces and consider only lowercase letters.",
"function_declaration": "def is_palindrome_permutation(s):",
"function_name": "is_palindrome_permutation",
"parameter_list": "(s)"
},
{
"docstring": "Ge... | [
0,
0,
0,
1,
1,
0,
1,
0,
0,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from collections import Counter\n\ndef is_palindrome_permutation(s: str) -> bool:\n \"\"\"\n Checks whether any permutation of the input string can form a ... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "0000035277",
"row_id": 35277,
"seed_ids": "[3473]"
} | 0.742264 | Algorithm_35277 | I | [
"is_palindrome_permutation",
"generate_palindrome"
] | 2 | [
[
"generate_palindrome",
"is_palindrome_permutation"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 1d176f0e71bb8636fbaccd6edc064a28055d7808 | 73be1e7783bc50ff32271459ab111c7bc03fdf03 | |||
v1.0 | instruct | Algorithm | Algorithm_35328_I | ### Pathfinding Algorithm with Diagonal Movements
In this coding challenge, you are asked to extend the traditional A* pathfinding algorithm to support diagonal movements in addition to the standard horizontal and vertical movements.
A* is a popular heuristic search algorithm for finding the shortest path between two... | import heapq
from typing import List, Tuple
import math
def heuristic(a: Tuple[int, int], b: Tuple[int, int]) -> float:
return math.sqrt((a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2)
def find_path(grid: List[List[int]], start: Tuple[int, int], goal: Tuple[int, int]) -> List[Tuple[int, int]]:
def neighbors(n):
... | from solution import find_path
def test_find_path_empty_grid():
grid = [
[0, 0, 0],
[0, 0, 0],
[0, 0, 0]
]
start = (0, 0)
goal = (2, 2)
path = find_path(grid, start, goal)
assert len(path) > 0
assert path[0] == start
assert path[-1] == goal
def test_find_path_wi... | [
{
"docstring": null,
"function_declaration": "def heuristic(a, b):",
"function_name": "heuristic",
"parameter_list": "(a, b)"
},
{
"docstring": null,
"function_declaration": "def find_path(grid, start, goal):",
"function_name": "find_path",
"parameter_list": "(grid, start, goal)"... | [
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 heapq\nfrom typing import List, Tuple\nimport math\n\ndef heuristic(a: Tuple[int, int], b: Tuple[int, int]) -> float:\n return math.sqrt((a[0] - b[0]) ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "0000035328",
"row_id": 35328,
"seed_ids": "[1332]"
} | 0.685434 | Algorithm_35328 | I | [
"heuristic",
"find_path"
] | 2 | [
[
"find_path",
"heuristic"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | d913c7bcf1ecb7a293a78b4367bbc04543b64f21 | f460965ddee32e47fede765127a4b1498a166fe7 | |||
v1.0 | instruct | Algorithm | Algorithm_35352_I | ### Coding Assessment Question
You are tasked with implementing two functions that handle and analyze sequences of integers with respect to prime numbers.
#### Task
**Function 1:** `is_prime_sequence(sequence: list) -> bool`
Implement a function to verify if a given list consists solely of prime numbers.
- **Input... | import math
def is_prime(num):
if num < 2:
return False
for i in range(2, int(math.sqrt(num)) + 1):
if num % i == 0:
return False
return True
def is_prime_sequence(sequence: list) -> bool:
"""
Returns True if all elements in the sequence are prime numbers, False otherwi... | from solution import is_prime_sequence, prime_count_upto
def test_is_prime_sequence_all_primes():
assert is_prime_sequence([2, 3, 5, 7, 11]) == True
def test_is_prime_sequence_includes_non_prime():
assert is_prime_sequence([2, 4, 6, 8]) == False
def test_is_prime_sequence_single_prime():
assert is_prime_... | [
{
"docstring": null,
"function_declaration": "def is_prime(num):",
"function_name": "is_prime",
"parameter_list": "(num)"
},
{
"docstring": "Returns True if all elements in the sequence are prime numbers, False otherwise.",
"function_declaration": "def is_prime_sequence(sequence):",
... | [
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 is_prime(n: int) -> bool:\n \"\"\"\n Checks if a given integer n is a prime number.\n \"\"\"\n if n <= 1:\n return False\n if n <= 3:\n... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000035352",
"row_id": 35352,
"seed_ids": "[4198]"
} | 0.742043 | Algorithm_35352 | I | [
"is_prime",
"is_prime_sequence",
"prime_count_upto"
] | 3 | [
[
"is_prime_sequence",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 8f9033ba5016c56fb393816cc8c89e0d220729b4 | 1f4642795fa521338cd128cfb1a460347a754929 | |||
v1.0 | instruct | Algorithm | Algorithm_35353_I | ### Genetic Algorithm for Optimizing Ackley Function
#### Context
You are a graduate student working on optimization techniques in your computational mathematics course. Your project is to implement a Genetic Algorithm to optimize the Ackley function, which is a popular test case for optimization algorithms.
The Ackl... | import random
import math
def ackley_function(x, y):
return -20 * math.exp(-0.2 * math.sqrt(0.5 * (x**2 + y**2))) - math.exp(0.5 * (math.cos(2 * math.pi * x) + math.cos(2 * math.pi * y))) + math.e + 20
def crossover(parent1, parent2, crossover_rate):
if random.random() < crossover_rate:
return (parent... | from solution import genetic_algorithm_ackley_minimization, ackley_function
def test_ackley_function():
assert ackley_function(0, 0) == 0
def test_genetic_algorithm_ackley_minimization():
initial_population = [(20, 30), (-10, -20), (15, 25)]
result = genetic_algorithm_ackley_minimization(initial_populatio... | [
{
"docstring": null,
"function_declaration": "def ackley_function(x, y):",
"function_name": "ackley_function",
"parameter_list": "(x, y)"
},
{
"docstring": null,
"function_declaration": "def crossover(parent1, parent2, crossover_rate):",
"function_name": "crossover",
"parameter_l... | [
0,
0,
0,
0,
0,
0,
0,
1,
0,
1
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import random\nimport math\n\ndef ackley_function(x, y):\n \"\"\"\n Ackley function defined for two input values x and y.\n \"\"\"\n part_1 = -20 * m... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000035353",
"row_id": 35353,
"seed_ids": "[5354]"
} | 0.432236 | Algorithm_35353 | I | [
"ackley_function",
"crossover",
"mutate",
"select",
"genetic_algorithm_ackley_minimization"
] | 5 | [
[
"genetic_algorithm_ackley_minimization",
"ackley_function"
],
[
"genetic_algorithm_ackley_minimization",
"crossover"
],
[
"genetic_algorithm_ackley_minimization",
"mutate"
],
[
"genetic_algorithm_ackley_minimization",
"select"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | 87f881646d7f2ddcad574094c8e2e98224294642 | bccf4d47ed0017c1f5cec65cd7ade4554951565c | |||
v1.0 | instruct | Algorithm | Algorithm_35417_I | ## Optimal Route Planning for Delivery Drones
You have been contracted to develop functionality for a delivery service utilizing drones to deliver packages within a city. The function should determine the shortest delivery route from the warehouse (starting point) to multiple delivery destinations and back to the ware... | import math
def euclidean_distance(point1, point2):
"""
Calculate the Euclidean distance between two points in 2D space.
"""
return math.sqrt((point1[0] - point2[0]) ** 2 + (point1[1] - point2[1]) ** 2)
def calculate_optimal_route(start, destinations):
"""
Determine the optimal delivery route ... | from solution import calculate_optimal_route
def test_calculate_optimal_route_no_destinations():
start = (34.0522, -118.2437)
destinations = []
result = calculate_optimal_route(start, destinations)
assert result == [(34.0522, -118.2437), (34.0522, -118.2437)]
def test_calculate_optimal_route_single_de... | [
{
"docstring": "Calculate the Euclidean distance between two points in 2D space.",
"function_declaration": "def euclidean_distance(point1, point2):",
"function_name": "euclidean_distance",
"parameter_list": "(point1, point2)"
},
{
"docstring": "Determine the optimal delivery route starting a... | [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0
] | 8 | easy | 0.8 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def calculate_optimal_route(start: tuple, destinations: list) -> list:\n \"\"\"\n Calculate the optimal route for a delivery drone using the nearest neighb... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "0000035417",
"row_id": 35417,
"seed_ids": "[1938]"
} | 0.622813 | Algorithm_35417 | I | [
"euclidean_distance",
"calculate_optimal_route"
] | 2 | [
[
"calculate_optimal_route",
"euclidean_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | d0ea0a9e793d7d02271905fb22419654d76cc8d4 | f32aa841904fc214a684afa543fb63f4a39091f3 | |||
v1.0 | instruct | Algorithm | Algorithm_35446_I | ### Data Normalization and Principal Component Analysis Implementation Assessment
#### Context
You are tasked with implementing data normalization techniques and enhancing a machine learning pre-processing pipeline with Principal Component Analysis (PCA). This will help ensure comprehension of aspects related to data ... | import numpy as np
def min_max_normalize(data: np.ndarray) -> np.ndarray:
"""
Apply Min-Max normalization to the data.
"""
min_val = np.min(data, axis=0)
max_val = np.max(data, axis=0)
return (data - min_val) / (max_val - min_val)
def z_score_standardize(data: np.ndarray) -> np.ndarray:
""... | import numpy as np
from solution import min_max_normalize, z_score_standardize, PCA, preprocess_data
def test_min_max_normalize():
data = np.array([[1, 2], [3, 4], [5, 6]])
normalized = min_max_normalize(data)
assert np.allclose(normalized, np.array([[0. , 0. ], [0.5, 0.5], [1. , 1. ]]))
def test_z_score_... | [] | [
0,
1,
1,
0,
1,
1,
1,
1,
0,
1
] | 7 | easy | 0.7 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import numpy as np\n\ndef min_max_normalize(data: np.ndarray) -> np.ndarray:\n min_vals = np.min(data, axis=0)\n max_vals = np.max(data, axis=0)\n retur... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "0000035446",
"row_id": 35446,
"seed_ids": "[4704]"
} | 0.74384 | Algorithm_35446 | I | [
"min_max_normalize",
"z_score_standardize",
"preprocess_data"
] | 3 | [
[
"preprocess_data",
"min_max_normalize"
],
[
"preprocess_data",
"z_score_standardize"
]
] | 2 | [] | false | [
"PCA"
] | true | pytest | true | [
"numpy"
] | false | 850e402701146cd8453119bcb5ccd7ef79bb0aee | b536e9e660933e2495574062f88454cb76963c54 | |||
v1.0 | instruct | Algorithm | Algorithm_35493_I | ### Minimum Spanning Tree (MST) Detection using Kruskal's Algorithm
**Background**:
A telecommunications company is planning to lay out new fiber optic cables to connect multiple cities. To minimize the cost of the project, the company aims to find the minimum spanning tree (MST) of the city's network graph. You are r... | def find_parent(parent, i):
if parent[i] == i:
return i
return find_parent(parent, parent[i])
def union(parent, rank, x, y):
root_x = find_parent(parent, x)
root_y = find_parent(parent, y)
if rank[root_x] < rank[root_y]:
parent[root_x] = root_y
elif rank[root_x] > rank[root... | from solution import kruskal_mst
def test_kruskal_mst_basic():
edges = [
(0, 1, 10),
(0, 2, 6),
(0, 3, 5),
(1, 3, 15),
(2, 3, 4)
]
num_vertices = 4
mst = kruskal_mst(edges, num_vertices)
expected_mst = [(2, 3, 4), (0, 3, 5), (0, 1, 10)]
assert len(mst) ==... | [
{
"docstring": null,
"function_declaration": "def find_parent(parent, i):",
"function_name": "find_parent",
"parameter_list": "(parent, i)"
},
{
"docstring": null,
"function_declaration": "def union(parent, rank, x, y):",
"function_name": "union",
"parameter_list": "(parent, rank... | [
0,
0,
1,
1,
0,
0,
0,
0,
0,
1
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def find_parent(parent, i):\n if parent[i] == i:\n return i\n return find_parent(parent, parent[i])\n\ndef union(parent, rank, xroot, yroot):\n i... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000035493",
"row_id": 35493,
"seed_ids": "[579]"
} | 0.73378 | Algorithm_35493 | I | [
"find_parent",
"union",
"kruskal_mst"
] | 3 | [
[
"kruskal_mst",
"find_parent"
],
[
"kruskal_mst",
"union"
],
[
"union",
"find_parent"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 8a41ae4105f100cc680ac84442a8675fa89c35f6 | 8c6c5004f92091297d3a0141ba5a10a676bdedeb | |||
v1.0 | instruct | Algorithm | Algorithm_35544_I | ### Question: Prime Number Pairs
**Background**: A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself.
**Problem**:
Given an integer `n`, find all pairs of prime numbers `(p1, p2)` such that:
- `p1` and `p2` are both prime numbers,
- `p1 + p2 = n`,
- and `p1 <= p2`.
... | from typing import List, Tuple
def sieve_of_eratosthenes(limit: int) -> List[bool]:
""" Generates a list of booleans representing primality of numbers up to limit. """
is_prime = [True] * (limit + 1)
is_prime[0], is_prime[1] = False, False # 0 and 1 are not primes
p = 2
while (p * p <= limit)... | from solution import prime_pairs
def test_prime_pairs_basic():
assert prime_pairs(10) == [(3, 7), (5, 5)]
assert prime_pairs(14) == [(3, 11), (7, 7)]
assert prime_pairs(5) == [(2, 3)]
def test_prime_pairs_no_pairs():
assert prime_pairs(1) == []
assert prime_pairs(0) == []
assert prime_pairs(-1... | [
{
"docstring": "Generates a list of booleans representing primality of numbers up to limit. ",
"function_declaration": "def sieve_of_eratosthenes(limit):",
"function_name": "sieve_of_eratosthenes",
"parameter_list": "(limit)"
},
{
"docstring": "Returns a list of tuples (p1, p2) where p1 and ... | [
0,
0,
0,
0,
1,
1,
0,
1,
0,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List, Tuple\n\ndef sieve_of_eratosthenes(n: int) -> List[bool]:\n \"\"\" Generates a list of booleans representing prime numbers up to n. \... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "0000035544",
"row_id": 35544,
"seed_ids": "[2477]"
} | 0.812031 | Algorithm_35544 | I | [
"sieve_of_eratosthenes",
"prime_pairs"
] | 2 | [
[
"prime_pairs",
"sieve_of_eratosthenes"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 035f4341013d277b8cddd97a4edb93e24836e23f | 32ce2b4d0c4aa64673c5d1217ecd219cd28cf26b | |||
v1.0 | instruct | Algorithm | Algorithm_35585_I | ### Problem Statement
**Scenario**: You are working on an algorithm to help a logistics company optimize their delivery processes. The company operates multiple delivery trucks, each capable of carrying packages of various weights. To balance the load across trucks, they aim to distribute the packages as evenly as poss... | from typing import List
def can_distribute(weights: List[int], k: int, max_weight: int) -> bool:
current_sum = 0
required_trucks = 1
for weight in weights:
if current_sum + weight > max_weight:
required_trucks += 1
current_sum = weight
if required_trucks > k... | from solution import load_balancer
def test_load_balancer_simple_case():
assert load_balancer([10, 20, 30, 40, 50], 2) == 90
def test_load_balancer_small_case():
assert load_balancer([1, 2, 3, 4, 5], 2) == 9
def test_load_balancer_large_k():
assert load_balancer([1, 1, 1, 1, 1], 5) == 1
def test_load_ba... | [
{
"docstring": null,
"function_declaration": "def can_distribute(weights, k, max_weight):",
"function_name": "can_distribute",
"parameter_list": "(weights, k, max_weight)"
},
{
"docstring": null,
"function_declaration": "def load_balancer(weights, k):",
"function_name": "load_balance... | [
1,
0,
0,
0,
0,
0,
0,
1,
0,
1
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef load_balancer(weights: List[int], k: int) -> int:\n def can_distribute(weights: List[int], k: int, max_load: int) -> bool:\n ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000035585",
"row_id": 35585,
"seed_ids": "[3873]"
} | 0.670168 | Algorithm_35585 | I | [
"can_distribute",
"load_balancer"
] | 2 | [
[
"load_balancer",
"can_distribute"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 54b4e931157f66aa440c2ee04dc23029197c220e | 21b5c096daf39eb4f6e45ecc7455b17434ee6b3e | |||
v1.0 | instruct | Algorithm | Algorithm_35586_I | ### Advanced Problem: Optimizing JSON Data Reduction with Multi-threading
#### Scenario
You are tasked with enhancing the provided implementation of a JSON data reduction algorithm. Specifically, you need to ensure that it processes the JSON objects more efficiently by leveraging multi-threading to parallelize the par... | import json
import threading
from concurrent.futures import ThreadPoolExecutor
def process_chunk(data_chunk, target_fields):
"""
Process a chunk of data by retaining only the target fields.
:param data_chunk: List of dictionaries to process.
:param target_fields: List of fields to retain.
:return:... | from solution import optimized_json_reduction
import json
import os
def create_test_json(filename, data):
with open(filename, 'w') as f:
json.dump(data, f)
def read_test_json(filename):
with open(filename, 'r') as f:
return json.load(f)
def cleanup_test_file(filename):
if os.path.exists(f... | [
{
"docstring": "Process a chunk of data by retaining only the target fields.\n\n:param data_chunk: List of dictionaries to process.\n:param target_fields: List of fields to retain.\n:return: Processed list of dictionaries.",
"function_declaration": "def process_chunk(data_chunk, target_fields):",
"funct... | [
1,
0,
0,
1,
1,
0,
0,
1,
0,
0
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import json\nimport threading\nfrom concurrent.futures import ThreadPoolExecutor\n\ndef process_chunk(chunk, target_fields):\n processed_chunk = []\n for i... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "0000035586",
"row_id": 35586,
"seed_ids": "[900]"
} | 0.629639 | Algorithm_35586 | I | [
"process_chunk",
"optimized_json_reduction"
] | 2 | [
[
"optimized_json_reduction",
"process_chunk"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c6515272434b7568e65603ec7fa04a59b7fda1d0 | 7ae177323a308b558216d2f82aed07786e470342 | |||
v1.0 | instruct | Algorithm | Algorithm_35593_I | ### Objective
Write functions to calculate the monthly mortgage payment and the total payment amount for a fixed-rate mortgage. The functions should take into consideration the principal amount, the annual interest rate, and the term of the loan in years.
### Question
You need to implement two functions: `monthly_mo... | def monthly_mortgage_payment(principal: float, annual_interest_rate: float, term_years: float) -> float:
"""
This function calculates the monthly mortgage payment given the principal, annual interest rate, and term years.
Raises ValueError for invalid inputs.
"""
if principal <= 0 or annual_interest... | import pytest
from solution import monthly_mortgage_payment, total_payment_amount
def test_monthly_mortgage_payment():
assert pytest.approx(monthly_mortgage_payment(200000.0, 5.0, 30), 0.01) == 1074.20
assert pytest.approx(monthly_mortgage_payment(300000.0, 4.0, 15), 0.01) == 2219.28
assert pytest.approx(m... | [
{
"docstring": "This function calculates the monthly mortgage payment given the principal, annual interest rate, and term years.\nRaises ValueError for invalid inputs.",
"function_declaration": "def monthly_mortgage_payment(principal, annual_interest_rate, term_years):",
"function_name": "monthly_mortga... | [
0,
0,
0,
0,
0,
0,
1,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def monthly_mortgage_payment(principal: float, annual_interest_rate: float, term_years: float) -> float:\n \"\"\"\n Calculate the monthly mortgage payment.... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "0000035593",
"row_id": 35593,
"seed_ids": "[5093]"
} | 0.521196 | Algorithm_35593 | I | [
"monthly_mortgage_payment",
"total_payment_amount"
] | 2 | [
[
"total_payment_amount",
"monthly_mortgage_payment"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 58784b4b8935f20a13bf0ec19abbea5b73e77851 | 313aa68121716ca0bae89a407266233233883c2d | |||
v1.0 | instruct | Algorithm | Algorithm_35633_I | ### Longest Palindromic Substring using Manacher's Algorithm
#### Context:
You are given a string representing a sequence of characters. Your task is to efficiently find the longest palindromic substring within the given sequence.
#### Task:
Implement an algorithm using Manacher's Algorithm to preprocess and find the... | def preprocess_string(s: str) -> str:
"""
Preprocess the string by adding delimiters (#) between characters
and at the boundaries to handle even-length palindromes uniformly.
"""
if not s:
return "^$"
return "^#" + "#".join(s) + "#$"
def longest_palindromic_substring(s: str) -> str:
... | from solution import preprocess_string, longest_palindromic_substring
def test_preprocess_string():
assert preprocess_string("babad") == "^#b#a#b#a#d#$"
assert preprocess_string("cbbd") == "^#c#b#b#d#$"
assert preprocess_string("a") == "^#a#$"
assert preprocess_string("") == "^$"
assert preprocess_... | [
{
"docstring": "Preprocess the string by adding delimiters (#) between characters\nand at the boundaries to handle even-length palindromes uniformly.",
"function_declaration": "def preprocess_string(s):",
"function_name": "preprocess_string",
"parameter_list": "(s)"
},
{
"docstring": "Use Ma... | [
0,
0,
0,
0,
1,
0,
1,
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": "def preprocess_string(s: str) -> str:\n \"\"\"\n Preprocess the input string by inserting a special character ('#') between\n each character and at the ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000035633",
"row_id": 35633,
"seed_ids": "[1683]"
} | 0.704107 | Algorithm_35633 | I | [
"preprocess_string",
"longest_palindromic_substring"
] | 2 | [
[
"longest_palindromic_substring",
"preprocess_string"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 29d5b4dbd41b5fa0645c584eb93d10c7a75435af | df0a5e8f529c7908cb6d8ae45560a4d6526d5740 | |||
v1.0 | instruct | Algorithm | Algorithm_35690_I | ### Problem Statement
The Atbash Cipher is a simple substitution cipher originally used for the Hebrew alphabet but can be used for any known alphabet. In Atbash, each letter in an alphabet is mapped to its reverse, so the first letter becomes the last letter, the second letter becomes the second last letter, and so o... | def atbash_encrypt(message: str, alphabet: str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ") -> str:
"""
Encrypts the message using the Atbash cipher with the given alphabet.
"""
if not message:
return ""
if len(set(alphabet)) != len(alphabet):
raise ValueError("Alphabet must contain unique c... | from solution import atbash_encrypt, atbash_decrypt
def test_atbash_encrypt_default_alphabet():
assert atbash_encrypt("HELLO") == "SVOOL"
assert atbash_encrypt("ABCDEFGHIJKLMNOPQRSTUVWXYZ") == "ZYXWVUTSRQPONMLKJIHGFEDCBA"
def test_atbash_decrypt_default_alphabet():
assert atbash_decrypt("SVOOL") == "HELLO... | [
{
"docstring": "Encrypts the message using the Atbash cipher with the given alphabet.",
"function_declaration": "def atbash_encrypt(message, alphabet='ABCDEFGHIJKLMNOPQRSTUVWXYZ'):",
"function_name": "atbash_encrypt",
"parameter_list": "(message, alphabet='ABCDEFGHIJKLMNOPQRSTUVWXYZ')"
},
{
... | [
0,
0,
0,
0,
0,
1,
1,
1,
0,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def atbash_encrypt(message: str, alphabet: str = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\") -> str:\n \"\"\"\n Encrypts the message using the Atbash cipher.\n \n ... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "0000035690",
"row_id": 35690,
"seed_ids": "[304]"
} | 0.681887 | Algorithm_35690 | I | [
"atbash_encrypt",
"atbash_decrypt"
] | 2 | [
[
"atbash_decrypt",
"atbash_encrypt"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 7c9e1c87a616930c4576e7838a2a82add36a27ef | 21e119976cb584be0472027da793408616458714 | |||
v1.0 | instruct | Algorithm | Algorithm_35772_I | ### Concurrent Real-time Chat Application
Your task is to implement a basic real-time chat application using socket programming that supports multiple clients communicating with each other simultaneously.
#### Requirements:
1. **Server Function**: Implement a server function `chat_server` that manages multiple client... | import socket
import threading
def broadcast_message(message, connections):
for conn in connections:
try:
conn.send(message.encode())
except Exception as e:
print(f"Error sending message: {e}")
connections.remove(conn)
def handle_client(conn, addr, connections):... | import threading
import time
from solution import chat_server, chat_client
def test_chat_application():
# Start chat server
server_thread = threading.Thread(target=chat_server, args=("127.0.0.1", 12345))
server_thread.daemon = True
server_thread.start()
time.sleep(1) # give the server time to star... | [
{
"docstring": null,
"function_declaration": "def broadcast_message(message, connections):",
"function_name": "broadcast_message",
"parameter_list": "(message, connections)"
},
{
"docstring": null,
"function_declaration": "def handle_client(conn, addr, connections):",
"function_name"... | [
1,
0,
0,
1,
1,
0,
0,
0,
1,
0
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import socket\nimport threading\n\ndef broadcast_message(message, connections):\n for conn in connections:\n try:\n conn.send(message.encode... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "0000035772",
"row_id": 35772,
"seed_ids": "[3988]"
} | 0.676064 | Algorithm_35772 | I | [
"broadcast_message",
"handle_client",
"chat_server",
"chat_client"
] | 4 | [
[
"handle_client",
"broadcast_message"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | e05c0b402418147be89cb46dab8601546f1bcd67 | 0529f1e9e2458dff273480e6272e9f7e0efa8552 | |||
v1.0 | instruct | Algorithm | Algorithm_35793_I | ## Problem Statement
You are tasked with writing a function that finds the k-th smallest element in an unsorted array. Your implementation should aim for an average-case time complexity of O(n).
### Requirements:
1. **Function Signature**:
```python
def find_kth_smallest(arr: list, k: int) -> int:
```
2. **I... | def partition(arr, low, high):
pivot = arr[high]
i = low - 1
for j in range(low, high):
if arr[j] <= pivot:
i += 1
arr[i], arr[j] = arr[j], arr[i]
arr[i + 1], arr[high] = arr[high], arr[i + 1]
return i + 1
def quickselect(arr, low, high, k):
if low < high:
... | from solution import find_kth_smallest
def test_find_kth_smallest():
assert find_kth_smallest([3, 2, 1, 5, 4], 3) == 3
assert find_kth_smallest([9, -1, 3, 5, 2], 2) == 2
assert find_kth_smallest([1], 1) == 1
assert find_kth_smallest([5, 5, 5, 5, 5], 3) == 5
assert find_kth_smallest([x for x in rang... | [
{
"docstring": null,
"function_declaration": "def partition(arr, low, high):",
"function_name": "partition",
"parameter_list": "(arr, low, high)"
},
{
"docstring": null,
"function_declaration": "def quickselect(arr, low, high, k):",
"function_name": "quickselect",
"parameter_list... | [
1,
0,
1,
1,
1,
1,
0,
1,
0,
0
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import random\n\ndef partition(arr, low, high):\n pivot = arr[high]\n i = low - 1\n for j in range(low, high):\n if arr[j] <= pivot:\n ... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "0000035793",
"row_id": 35793,
"seed_ids": "[1297]"
} | 0.669449 | Algorithm_35793 | I | [
"partition",
"quickselect",
"find_kth_smallest"
] | 3 | [
[
"find_kth_smallest",
"quickselect"
],
[
"quickselect",
"partition"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | def92f483dce4256dcc76d3e3f72f00251a78897 | 49f09f0d25c9109f8c56d10c33723d8c1c144291 | |||
v1.0 | instruct | Algorithm | Algorithm_35804_I | ### Problem Scenario
You are tasked with developing a function that counts the number of prime numbers in a given range of integers. This will test your understanding of number theory and optimization techniques in algorithms.
### Task
Write a function `count_primes_in_range(start: int, end: int) -> int`.
Your functi... | import math
def is_prime(n):
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
return True
def count_primes_in_range(start: ... | from solution import count_primes_in_range
def test_primes_in_small_range():
assert count_primes_in_range(10, 30) == 6 # Prime numbers: 11, 13, 17, 19, 23, 29
def test_primes_with_zero_range():
assert count_primes_in_range(10, 10) == 0 # No prime number in the range
def test_primes_with_large_numbers():
... | [
{
"docstring": null,
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def count_primes_in_range(start, end):",
"function_name": "count_primes_in_range",
"parameter_list": "(start, end... | [
0,
0,
0,
0,
0,
0,
0,
1,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import math\n\ndef is_prime(n):\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == 0 or n % 3 == 0:\n return Fals... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "0000035804",
"row_id": 35804,
"seed_ids": "[943]"
} | 0.710914 | Algorithm_35804 | I | [
"is_prime",
"count_primes_in_range"
] | 2 | [
[
"count_primes_in_range",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 7cd301c60a86f08de45883372b61a9898df61ef2 | 9a73c34ff43e79ece54cb4dd9e3ceb05600e2e4d | |||
v1.0 | instruct | Algorithm | Algorithm_35887_I | **Array Transformation and Analysis**
You are building a data processing tool that involves a series of transformations for numerical arrays. Your objective is to implement functions that perform four specific transformations and an evaluation step.
**Objective:**
Complete the missing implementations for these trans... | import numpy as np
def scale_array(array: np.ndarray, factor: float) -> np.ndarray:
"""
Scales the array by a given factor.
"""
return array * factor
def exponential_transform(array: np.ndarray) -> np.ndarray:
"""
Applies exponential transformation to the array.
"""
return np.exp(array... | import numpy as np
from solution import scale_array, exponential_transform, subtract_mean, smooth_array, compare_arrays, array_transformation_pipeline
def test_scale_array():
array = np.array([1, 2, 3, 4, 5])
factor = 2
result = scale_array(array, factor)
expected = np.array([2, 4, 6, 8, 10])
asser... | [
{
"docstring": "Scales the array by a given factor.",
"function_declaration": "def scale_array(array, factor):",
"function_name": "scale_array",
"parameter_list": "(array, factor)"
},
{
"docstring": "Applies exponential transformation to the array.",
"function_declaration": "def exponent... | [
1,
1,
0,
1,
0,
0,
0,
0,
0,
1
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import numpy as np\n\n# Function 1: Scaling Transformation\ndef scale_array(array: np.ndarray, factor: float) -> np.ndarray:\n return array * factor\n\n# Func... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000035887",
"row_id": 35887,
"seed_ids": "[4303]"
} | 0.632259 | Algorithm_35887 | I | [
"scale_array",
"exponential_transform",
"subtract_mean",
"smooth_array",
"compare_arrays",
"array_transformation_pipeline"
] | 6 | [
[
"array_transformation_pipeline",
"compare_arrays"
],
[
"array_transformation_pipeline",
"exponential_transform"
],
[
"array_transformation_pipeline",
"scale_array"
],
[
"array_transformation_pipeline",
"smooth_array"
],
[
"array_transformation_pipeline",
"su... | 5 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | ed7f212f730b0ebb4d6fbf1198233099c8a0878e | 40103be33ff71a88e30f4d52c46010ccce0cf463 | |||
v1.0 | instruct | Algorithm | Algorithm_35901_I | ### Problem Statement
You are tasked with implementing a function to evaluate the similarity between two strings using the Jaccard similarity coefficient. The Jaccard similarity coefficient is defined as the size of the intersection divided by the size of the union of the sample sets. In this context, the sample sets ... | def generate_ngrams(s, n):
"""Generate n-grams for a given string and length."""
return {s[i:i+n] for i in range(len(s) - n + 1)}
def jaccard_similarity(s1, s2, n):
"""
Returns the Jaccard similarity coefficient between two strings based on their n-grams.
"""
if n > len(s1) or n > len(s2):
... | def test_jaccard_similarity_simple_case():
s1 = "abcde"
s2 = "cdefg"
n = 2
assert jaccard_similarity(s1, s2, n) == 2 / 6
def test_jaccard_similarity_no_overlap():
s1 = "abc"
s2 = "def"
n = 1
assert jaccard_similarity(s1, s2, n) == 0.0
def test_jaccard_similarity_full_overlap():
s1 ... | [
{
"docstring": "Generate n-grams for a given string and length.",
"function_declaration": "def generate_ngrams(s, n):",
"function_name": "generate_ngrams",
"parameter_list": "(s, n)"
},
{
"docstring": "Returns the Jaccard similarity coefficient between two strings based on their n-grams.",
... | [
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": "def generate_ngrams(s: str, n: int):\n \"\"\"\n Generate n-grams from the given string.\n \"\"\"\n return {s[i:i+n] for i in range(len(s) - n + 1)}\n... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "0000035901",
"row_id": 35901,
"seed_ids": "[610]"
} | 0.718526 | Algorithm_35901 | I | [
"generate_ngrams",
"jaccard_similarity"
] | 2 | [
[
"jaccard_similarity",
"generate_ngrams"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | ee82a69e0bfb3c69fb8e64b64992733161389812 | 5612ce88dba50d9ecbd20e90fc5fd9059f60146f | |||
v1.0 | instruct | Algorithm | Algorithm_35923_I | In this exercise, you are asked to implement a word frequency analyzer that processes a given text and counts the occurrences of each unique word, ignoring case and punctuation.
### Function to Implement
1. **sanitize_text**: This function should remove punctuation and convert all letters to lowercase.
2. **word_freq... | import re
from collections import Counter
def sanitize_text(text: str) -> str:
"""
Remove punctuation from the text and convert it to lowercase.
"""
# Convert to lowercase
text = text.lower()
# Remove punctuation using regex
sanitized = re.sub(r'[^\w\s]', '', text)
return sanitized
def... | from solution import sanitize_text, word_frequency, most_common_words
def test_sanitize_text():
assert sanitize_text("Hello, world!") == "hello world"
assert sanitize_text("Hello everyone. This is a simple text, with punctuation.") == \
"hello everyone this is a simple text with pun... | [
{
"docstring": "Remove punctuation from the text and convert it to lowercase.",
"function_declaration": "def sanitize_text(text):",
"function_name": "sanitize_text",
"parameter_list": "(text)"
},
{
"docstring": "Count the frequency of each word in the sanitized text.",
"function_declarat... | [
1,
1,
1,
1,
0,
1,
0,
1,
1,
1
] | 8 | easy | 0.8 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import string\nfrom collections import Counter\n\ndef sanitize_text(text):\n \"\"\"\n Removes punctuation from text and converts all letters to lowercase.\... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000035923",
"row_id": 35923,
"seed_ids": "[301]"
} | 0.819699 | Algorithm_35923 | I | [
"sanitize_text",
"word_frequency",
"most_common_words"
] | 3 | [
[
"most_common_words",
"word_frequency"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 031628a75755d6b4037dba5385ba9f7517f3d5e4 | 84954338dcb288e613162793a2379cbfaa206afe | |||
v1.0 | instruct | Algorithm | Algorithm_35958_I | ### Genetic Algorithm Optimization
#### Context
You are tasked with implementing and enhancing a Genetic Algorithm (GA) to solve optimization problems. This assessment will verify your understanding of components such as selection, crossover, mutation, and overall GA workflow.
#### Task
1. **Implement and Enhance Se... | import random
from typing import List, Callable, Tuple
# Selection Methods
def tournament_selection(population: List, fitness: List, k: int) -> List:
selected = []
for _ in range(len(population)):
tournament = random.sample(list(zip(population, fitness)), k)
winner = max(tournament, key=lambda ... | from solution import (
tournament_selection,
rank_based_selection,
single_point_crossover,
two_point_crossover,
mutation,
genetic_algorithm
)
def sample_fitness_function(individual: List[int]) -> float:
return sum(individual)
def get_sample_population() -> List[List[int]]:
return [... | [
{
"docstring": null,
"function_declaration": "def tournament_selection(population, fitness, k):",
"function_name": "tournament_selection",
"parameter_list": "(population, fitness, k)"
},
{
"docstring": null,
"function_declaration": "def rank_based_selection(population, fitness):",
"f... | [
0,
0,
0,
0,
0,
0,
1,
1,
1,
1
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import random\nfrom typing import List, Callable\n\ndef tournament_selection(population: List, fitness: List, k: int) -> List:\n selected = []\n for _ in r... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "0000035958",
"row_id": 35958,
"seed_ids": "[4704]"
} | 0.433209 | Algorithm_35958 | I | [
"tournament_selection",
"rank_based_selection",
"single_point_crossover",
"two_point_crossover",
"mutation",
"genetic_algorithm"
] | 6 | [
[
"genetic_algorithm",
"mutation"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 0745f49cf9bbcb309e4cf6177140ff388ab2c4b0 | 23ac952b8dcdbdc787bd0fe838ccdc4a590541d6 | |||
v1.0 | instruct | Algorithm | Algorithm_35988_I | ### Coding Assessment Question
#### Context
You are working on a financial application that needs to manage and manipulate monetary values represented in dollars and cents. The application requires various utility functions for handling these amounts in different ways.
### Objective
Implement a set of functions to pa... | def parse_currency(amount_str):
"""
Parse a string representing a monetary amount and convert it to a float.
"""
if amount_str.startswith('$') and validate_currency(amount_str):
return float(amount_str[1:])
raise ValueError("Invalid currency format")
def validate_currency(amount_str):
"... | def test_parse_currency_valid_cases():
assert parse_currency("$123.45") == 123.45
assert parse_currency("$0.99") == 0.99
assert parse_currency("$0.00") == 0.00
def test_parse_currency_invalid_cases():
try:
parse_currency("123.45")
except ValueError:
assert True
else:
... | [
{
"docstring": "Parse a string representing a monetary amount and convert it to a float.",
"function_declaration": "def parse_currency(amount_str):",
"function_name": "parse_currency",
"parameter_list": "(amount_str)"
},
{
"docstring": "Validate if a given string is a correctly formatted mon... | [
1,
1,
0,
1,
1,
0,
1,
1,
1,
1
] | 8 | easy | 0.8 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def parse_currency(amount_str):\n \"\"\"\n Parse a string representing a monetary amount and convert it to a float.\n \n Parameters:\n amount_str ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000035988",
"row_id": 35988,
"seed_ids": "[1516]"
} | 0.552993 | Algorithm_35988 | I | [
"parse_currency",
"validate_currency",
"add_currency"
] | 3 | [
[
"parse_currency",
"validate_currency"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 49b04697c08ccbce032404d9b2a03f9fa5470d2e | 40dd109ba48252fd5c73aff8c849b20d9369cdee | |||
v1.0 | instruct | Algorithm | Algorithm_36006_I | ### Chat Room Server with Non-Blocking I/O and Connection Management
You are tasked with creating a basic chat room server that handles multiple clients concurrently. The server should use non-blocking I/O operations to efficiently manage multiple connected clients and broadcast messages received from any client to al... | import selectors
import socket
import types
import signal
import logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(message)s')
selector = selectors.DefaultSelector()
def accept(sock):
conn, addr = sock.accept() # Should be ready to read
logging.info(f"Accepted connection from {addr}")
... | import socket
import threading
import time
from solution import start_chat_server
def run_server():
start_chat_server(12345)
def test_server_start():
# Start server in a separate thread
server_thread = threading.Thread(target=run_server, daemon=True)
server_thread.start()
# Give the server some ... | [
{
"docstring": null,
"function_declaration": "def accept(sock):",
"function_name": "accept",
"parameter_list": "(sock)"
},
{
"docstring": null,
"function_declaration": "def service_connection(key, mask):",
"function_name": "service_connection",
"parameter_list": "(key, mask)"
}... | [
0,
0,
0,
0,
0,
1,
0,
0,
0
] | 1 | hard | 0.111 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import socket\nimport selectors\nimport types\nimport signal\nimport logging\nimport threading\n\nlogging.basicConfig(level=logging.INFO, format='%(asctime)s - %... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "0000036006",
"row_id": 36006,
"seed_ids": "[4273]"
} | 0.673424 | Algorithm_36006 | I | [
"accept",
"service_connection",
"start_chat_server"
] | 3 | [
[
"start_chat_server",
"accept"
],
[
"start_chat_server",
"service_connection"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 410ab90144a985bd852997fa2f007f9f05a3d231 | f01531cb670f01664ddc94538a0517ec9b720385 | |||
v1.0 | instruct | Algorithm | Algorithm_36041_I | ### Problem Statement
Given a string of letters, find the longest subsequence which forms a valid English word according to a provided dictionary. Return that word. If there are multiple words of the same maximum length, return the lexicographically smallest one.
A subsequence differs from a substring, as the charact... | from typing import List
def is_subsequence(s: str, word: str) -> bool:
"""
Helper function to check if 'word' is a subsequence of 's'.
"""
it = iter(s)
return all(char in it for char in word)
def find_longest_word_subsequence(s: str, dictionary: List[str]) -> str:
"""
Given a string `s` an... | def test_find_longest_word_subsequence():
s = "abppplee"
dictionary = ["able", "ale", "apple", "bale", "kangaroo"]
assert find_longest_word_subsequence(s, dictionary) == "apple"
s = "babgbag"
dictionary = ["bag", "bagger", "gab", "grab"]
assert find_longest_word_subsequence(s, dictionary) == "b... | [
{
"docstring": "Helper function to check if 'word' is a subsequence of 's'.",
"function_declaration": "def is_subsequence(s, word):",
"function_name": "is_subsequence",
"parameter_list": "(s, word)"
},
{
"docstring": "Given a string `s` and a list of strings `dictionary`, find the longest wo... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 10 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef is_subsequence(word, s):\n it = iter(s)\n return all(char in it for char in word)\n\ndef find_longest_word_subsequence(s: st... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000036041",
"row_id": 36041,
"seed_ids": "[2862]"
} | 0.783523 | Algorithm_36041 | I | [
"is_subsequence",
"find_longest_word_subsequence"
] | 2 | [
[
"find_longest_word_subsequence",
"is_subsequence"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | dbe36609eaf1f62b1ac2e1effe63c0e55577c356 | eb36a083a9c6ba68868cf8c7e1e10f383e185504 | |||
v1.0 | instruct | Algorithm | Algorithm_36072_I | ### Coding Question: Dynamic Spreadsheet Formula Evaluator
Imagine you are developing a simplified spreadsheet application, and you need to implement a dynamic formula evaluator. The application should process and evaluate custom formulas inserted in a grid-based spreadsheet.
Implement a function `calculate_formula`... | from typing import List, Union
def evaluate_expression(expr: str, grid, values_cache):
if expr in values_cache:
return values_cache[expr]
letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
def get_value(cell):
col = letters.index(cell[0])
row = int(cell[1:]) - 1
return evaluate_cell(gr... | def test_basic_arithmetic():
grid = [
[5, '=A1 + 10'],
[3, '=A1 * B1']
]
assert calculate_formula(grid) == [
[5, 15],
[3, 75]
]
def test_division_by_zero():
grid = [
[6, '=A1 / 0']
]
assert calculate_formula(grid) == [
[6, float('inf')]
]
... | [
{
"docstring": null,
"function_declaration": "def evaluate_expression(expr, grid, values_cache):",
"function_name": "evaluate_expression",
"parameter_list": "(expr, grid, values_cache)"
},
{
"docstring": null,
"function_declaration": "def evaluate_cell(cell, grid, values_cache):",
"f... | [
1,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List, Union\n\ndef evaluate_expression(expr: str, grid, values_cache):\n if expr in values_cache:\n return values_cache[expr]\n\n ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "0000036072",
"row_id": 36072,
"seed_ids": "[289]"
} | 0.512955 | Algorithm_36072 | I | [
"evaluate_expression",
"evaluate_cell",
"calculate_formula"
] | 3 | [
[
"calculate_formula",
"evaluate_cell"
],
[
"evaluate_cell",
"evaluate_expression"
],
[
"evaluate_expression",
"evaluate_cell"
]
] | 3 | [] | false | [] | false | pytest | false | [] | true | f96d20b81abdd3ae8ac8a1fd0082c931c60b45d8 | 7a28ca9b650d509a660c142e49640603d95b5c29 | |||
v1.0 | instruct | Algorithm | Algorithm_36080_I | ### Coding Assessment Question
#### Context:
In the world of competitive programming, understanding matrix operations can be crucial. A common operation is rotating an image represented as an `N x N` matrix, where each pixel in the image is an integer value.
#### Problem:
Write a function `rotate_matrix` that takes a... | from typing import List
def rotate_matrix(matrix: List[List[int]]) -> List[List[int]]:
"""
Rotates the given N x N matrix by 90 degrees clockwise.
"""
N = len(matrix)
rotated = [[0] * N for _ in range(N)]
for i in range(N):
for j in range(N):
rotated[j][N - i - 1] = matrix[i... | from solution import rotate_matrix, is_rotated_equal
def test_rotate_matrix_3x3():
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
expected = [
[7, 4, 1],
[8, 5, 2],
[9, 6, 3]
]
assert rotate_matrix(matrix) == expected
def test_rotate_matrix_2x2():
... | [
{
"docstring": "Rotates the given N x N matrix by 90 degrees clockwise.",
"function_declaration": "def rotate_matrix(matrix):",
"function_name": "rotate_matrix",
"parameter_list": "(matrix)"
},
{
"docstring": "Checks if the matrix rotated 90 degrees clockwise is equal to the target matrix.",... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 10 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef rotate_matrix(matrix: List[List[int]]) -> List[List[int]]:\n \"\"\"\n Rotates the given N x N matrix 90 degrees clockwise.\n... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000036080",
"row_id": 36080,
"seed_ids": "[478]"
} | 0.609742 | Algorithm_36080 | I | [
"rotate_matrix",
"is_rotated_equal"
] | 2 | [
[
"is_rotated_equal",
"rotate_matrix"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | bc72a257cc29375ebc75fcca8cfb7df59c786f32 | ff7969564a635481a273a65a933cfe1babb63c38 | |||
v1.0 | instruct | Algorithm | Algorithm_36116_I | ## Anagram Pair Finder
### Scenario
You are invited to take part in the development of a system that identifies pairs of words that are anagrams. Two words are considered anagrams if one word can be rearranged to form the other, using all the original letters exactly once.
### Function to Implement
Write a function... | def clean_word(word):
"""
Returns a cleaned version of the word with all letters in lowercase,
and all non-alphabetic characters removed.
"""
return ''.join(filter(str.isalpha, word)).lower()
def find_anagram_pairs(words):
"""
Returns a list of tuples. Each tuple contains two words that are... | from solution import find_anagram_pairs
def test_find_anagram_pairs_basic():
words = ["Listen", "Silent", "Dormitory", "Dirty room", "School master", "The classroom", "Hello", "Olelh"]
expected = [("Listen", "Silent"), ("Dormitory", "Dirty room"), ("School master", "The classroom"), ("Hello", "Olelh")]
ass... | [
{
"docstring": "Returns a cleaned version of the word with all letters in lowercase,\nand all non-alphabetic characters removed.",
"function_declaration": "def clean_word(word):",
"function_name": "clean_word",
"parameter_list": "(word)"
},
{
"docstring": "Returns a list of tuples. Each tupl... | [
1,
0,
1,
1,
1,
1,
1,
0,
1,
0
] | 7 | easy | 0.7 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import re\n\ndef find_anagram_pairs(words):\n def clean_word(word):\n return ''.join(sorted(re.sub(r'[^a-zA-Z]', '', word).lower()))\n\n found_pairs... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000036116",
"row_id": 36116,
"seed_ids": "[1418]"
} | 0.586504 | Algorithm_36116 | I | [
"clean_word",
"find_anagram_pairs"
] | 2 | [
[
"find_anagram_pairs",
"clean_word"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 631bf8cc6fa3ea811c5871fa50957076de69d027 | 6f73c02c24aaf1afe3f39193f472f2ddfeea37cf | |||
v1.0 | instruct | Algorithm | Algorithm_36146_I | ### Coding Assessment Question
#### Scenario
Sorting algorithms are fundamental in computer science and are widely used in various applications such as organizing data, improving search performance, and managing large datasets.
#### Task
Implement a hybrid sorting algorithm in Python that combines Merge Sort and Inse... | def insertion_sort(arr, left, right):
for i in range(left + 1, right + 1):
key = arr[i]
j = i - 1
while j >= left and key < arr[j]:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
def merge(arr, left, mid, right):
n1 = mid - left + 1
n2 = right - mid
... | from solution import hybrid_sort
def test_empty_list():
assert hybrid_sort([], 3) == []
def test_single_element_list():
assert hybrid_sort([1], 3) == [1]
def test_sort_with_small_threshold():
assert hybrid_sort([12, 11, 13, 5, 6, 7], 3) == [5, 6, 7, 11, 12, 13]
assert hybrid_sort([3, 0, 2, 5, -1, 4, ... | [
{
"docstring": null,
"function_declaration": "def insertion_sort(arr, left, right):",
"function_name": "insertion_sort",
"parameter_list": "(arr, left, right)"
},
{
"docstring": null,
"function_declaration": "def merge(arr, left, mid, right):",
"function_name": "merge",
"paramete... | [
1,
1,
1,
1,
0,
1,
1,
0,
1,
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 insertion_sort(arr, left, right):\n for i in range(left + 1, right + 1):\n key = arr[i]\n j = i - 1\n while j >= left and arr[j] > ke... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000036146",
"row_id": 36146,
"seed_ids": "[1816]"
} | 0.573673 | Algorithm_36146 | I | [
"insertion_sort",
"merge",
"hybrid_sort_recursive",
"hybrid_sort"
] | 4 | [
[
"hybrid_sort",
"hybrid_sort_recursive"
],
[
"hybrid_sort_recursive",
"insertion_sort"
],
[
"hybrid_sort_recursive",
"merge"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | caece9adb2d83a93bc5566f935d6364202053fde | d148775d998b7089ddc554264c4426f879a50156 | |||
v1.0 | instruct | Algorithm | Algorithm_36211_I | **Question:**
You are assigned to find the smallest positive integer `n` such that the product of the first `n` Fibonacci numbers is a perfect square. The Fibonacci sequence is defined as:
- F(1) = 1
- F(2) = 1
- F(n) = F(n-1) + F(n-2) for n > 2
Given that Fibonacci numbers grow exponentially, you need to come up wit... | import math
def is_perfect_square(x):
"""Check if x is a perfect square."""
s = int(math.isqrt(x))
return s * s == x
def smallest_fibonacci_square():
"""Find the smallest positive integer n such that the product of the first n Fibonacci numbers is a perfect square."""
# Initial variables
a, b ... | from solution import smallest_fibonacci_square
def test_smallest_fibonacci_square():
assert smallest_fibonacci_square() == 1
def test_smallest_fibonacci_square_larger_value():
# Manually verify for larger values
# n = 4: F(1) * F(2) * F(3) * F(4) = 1 * 1 * 2 * 3, not a perfect square
# Skipping a ... | [
{
"docstring": "Check if x is a perfect square.",
"function_declaration": "def is_perfect_square(x):",
"function_name": "is_perfect_square",
"parameter_list": "(x)"
},
{
"docstring": "Find the smallest positive integer n such that the product of the first n Fibonacci numbers is a perfect squ... | [
0,
0,
1,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.111 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from math import isqrt\nfrom functools import reduce\nfrom math import gcd\nfrom itertools import count\nfrom collections import Counter\n\ndef is_perfect_square... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "0000036211",
"row_id": 36211,
"seed_ids": "[2933]"
} | 0.654098 | Algorithm_36211 | I | [
"is_perfect_square",
"smallest_fibonacci_square"
] | 2 | [
[
"smallest_fibonacci_square",
"is_perfect_square"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | acdc86a351df040d0516103f198a1655f14ad337 | 2763d9195fdbe869a15e1815389830169d1f447f |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.