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_36214_I | ### Coding Assessment Question
You are required to extend the functionality of a program that monitors a cryptocurrency portfolio using a public API. The existing implementation calculates the current value of the portfolio based on real-time prices. Now, extend the functionality to include calculations of the highest... | import requests
from datetime import datetime, timedelta
def get_historical_price(api_key: str, symbol: str, date: str) -> float:
url = f"https://api.coingecko.com/api/v3/coins/{symbol}/history"
params = {'date': date.replace('-', ''), 'localization': 'false'}
try:
response = requests.get(url, para... | from solution import get_historical_price, get_portfolio_value_by_date_range, get_current_portfolio_value
import requests
def test_get_historical_price(monkeypatch):
class MockResponse:
@staticmethod
def json():
return {
"market_data": {
"current_pric... | [
{
"docstring": null,
"function_declaration": "def get_historical_price(api_key, symbol, date):",
"function_name": "get_historical_price",
"parameter_list": "(api_key, symbol, date)"
},
{
"docstring": null,
"function_declaration": "def get_portfolio_value_by_date_range(api_key, portfolio,... | [
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": "import requests\nfrom datetime import datetime, timedelta\n\ndef get_historical_price(api_key: str, symbol: str, date: str) -> float:\n url = f\"https://api.c... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000036214",
"row_id": 36214,
"seed_ids": "[2092]"
} | 0.565511 | Algorithm_36214 | I | [
"get_historical_price",
"get_portfolio_value_by_date_range",
"get_current_portfolio_value"
] | 3 | [
[
"get_portfolio_value_by_date_range",
"get_historical_price"
]
] | 1 | [] | false | [] | false | pytest | true | [
"requests"
] | false | a1cfd6b73b32675b1fb2e042a7c972f9923e2584 | 23c4d71093233766fb45233a150a7bb364157234 | |||
v1.0 | instruct | Algorithm | Algorithm_36216_I | ### Problem Statement
You have been tasked with implementing a basic spell-checking system that recognizes potentially incorrectly spelled words in a document. The system should be capable of suggesting possible correct words based on the given dictionary. The suggestion is based on edit distance (Levenshtein distance... | from typing import List, Tuple
import re
def edit_distance(word1: str, word2: str) -> int:
"""Computes the edit distance (Levenshtein distance) between two words."""
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):
... | from solution import spell_check, edit_distance
def test_edit_distance():
assert edit_distance("helo", "hello") == 1
assert edit_distance("word", "world") == 1
assert edit_distance("spel", "spell") == 1
assert edit_distance("", "a") == 1
assert edit_distance("abc", "yabd") == 2
def test_spell_chec... | [
{
"docstring": "Computes the edit distance (Levenshtein distance) between two words.",
"function_declaration": "def edit_distance(word1, word2):",
"function_name": "edit_distance",
"parameter_list": "(word1, word2)"
},
{
"docstring": "Spell check a document against a dictionary and suggest c... | [
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": "from typing import List, Tuple\nimport re\n\ndef edit_distance(word1: str, word2: str) -> int:\n \"\"\"\n Computes the Levenshtein distance between two wor... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "0000036216",
"row_id": 36216,
"seed_ids": "[4252]"
} | 0.592459 | Algorithm_36216 | I | [
"edit_distance",
"spell_check"
] | 2 | [
[
"spell_check",
"edit_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f5a0ee1ebcf465c7921557daf45cf2e2335d8e78 | 6e24209b12c4a027fb89f7791d2872f563bd9cb1 | |||
v1.0 | instruct | Algorithm | Algorithm_36221_I | **Scenario**:
You are working for a logistics company that deals with managing deliveries and maintaining an efficient schedule. One of the challenges is to sort the delivery list based on the delivery distance from the central warehouse.
The goal is to implement a sorting functionality that sorts the delivery package... | import math
from typing import List
class Package:
def __init__(self, x, y, details):
self.x = x
self.y = y
self.details = details
def calculate_distance(package: Package) -> float:
return math.sqrt(package.x ** 2 + package.y ** 2)
def merge_sort(packages: List[Package]) -> List[Packa... | from solution import Package, sort_packages
def test_single_package():
packages = [
Package(3, 4, "Package 1")
]
sorted_packages = sort_packages(packages)
assert [(pkg.x, pkg.y, pkg.details) for pkg in sorted_packages] == [(3, 4, "Package 1")]
def test_multiple_packages():
packages = [
... | [] | [
1,
1,
1,
0,
1,
1,
1,
0,
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\nimport math\n\nclass Package:\n def __init__(self, x, y, details):\n self.x = x\n self.y = y\n self.details = de... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000036221",
"row_id": 36221,
"seed_ids": "[2001]"
} | 0.520986 | Algorithm_36221 | I | [
"calculate_distance",
"merge_sort",
"merge",
"sort_packages"
] | 4 | [
[
"merge",
"calculate_distance"
],
[
"merge_sort",
"merge"
],
[
"sort_packages",
"merge_sort"
]
] | 3 | [] | false | [
"Package"
] | true | pytest | true | [] | true | 7d59b65605c284aa38b6e962ea2eac143fb9a79c | 8383c7913df0f01629a9fc4b6262cc274faba3e1 | |||
v1.0 | instruct | Algorithm | Algorithm_36225_I | ### Text Transformer and Entropy Calculations
In this task, you are required to implement a function that processes a list of strings, applies text transformations, computes Shannon entropy for each transformed string, and ranks the strings based on their entropy values.
### Function Requirements
You will implement t... | import math
from collections import Counter
def compute_entropy(text):
"""
Compute the Shannon entropy of a given text.
"""
if not text:
return 0.0
# Calculate the frequency of each character in the text
counter = Counter(text)
length = len(text)
# Shannon entropy computat... | from solution import rank_texts
def test_rank_texts_basic():
texts = ["hello world", "example text", "shannon entropy"]
transformations = {"e": "3", "o": "0", "a": "4"}
result = rank_texts(texts, transformations)
assert len(result) == 3
assert result[0][0] in [0, 2] # Both "hello world" and "shann... | [
{
"docstring": "Compute the Shannon entropy of a given text.",
"function_declaration": "def compute_entropy(text):",
"function_name": "compute_entropy",
"parameter_list": "(text)"
},
{
"docstring": "Apply the given transformations to the text.",
"function_declaration": "def apply_transfo... | [
0,
0,
0,
0,
1,
0,
0,
0,
0,
1
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from collections import Counter\nimport math\n\ndef compute_shannon_entropy(text):\n \"\"\"\n Computes the Shannon entropy of a given text.\n \"\"\"\n ... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "0000036225",
"row_id": 36225,
"seed_ids": "[4295]"
} | 0.641842 | Algorithm_36225 | I | [
"compute_entropy",
"apply_transformations",
"rank_texts"
] | 3 | [
[
"rank_texts",
"apply_transformations"
],
[
"rank_texts",
"compute_entropy"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | d4f1c632d9fa77080f0c25903285cbcdfd195ddf | ec9faea621d2ce85a0f359a7c725d74f89a17976 | |||
v1.0 | instruct | Algorithm | Algorithm_36253_I | ### Problem Statement
You are tasked with implementing a contact management system for small businesses. The initial framework for managing contacts is already in place, but several improvements are necessary. Specifically, you need to add functionality for importing contacts from a CSV file, exporting contacts to JSO... | import csv
import json
import re
def is_valid_email(email: str) -> bool:
"""
Helper function to validate email format using regex.
"""
regex = r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$'
return re.match(regex, email) is not None
def import_contacts(csv_file_path: str, existing_contacts: li... | import pytest
from solution import import_contacts, export_contacts, is_valid_email
def test_is_valid_email():
assert is_valid_email("test@example.com") == True
assert is_valid_email("invalid-email") == False
assert is_valid_email("another.test@domain.co.uk") == True
assert is_valid_email("yet@another@... | [
{
"docstring": "Helper function to validate email format using regex.",
"function_declaration": "def is_valid_email(email):",
"function_name": "is_valid_email",
"parameter_list": "(email)"
},
{
"docstring": "Reads contact details from a CSV file and adds them to the contact list.\nEnsures th... | [
0,
1,
1,
1,
0,
1,
1,
0,
0,
1
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import csv\nimport json\nimport re\n\ndef is_valid_email(email: str) -> bool:\n \"\"\"\n Helper function to validate email format.\n \n A basic regex... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000036253",
"row_id": 36253,
"seed_ids": "[1976]"
} | 0.520168 | Algorithm_36253 | I | [
"is_valid_email",
"import_contacts",
"export_contacts"
] | 3 | [
[
"import_contacts",
"is_valid_email"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 1727bd2f7d61165df944bc61b3f7a3d32b2f2ef9 | a76e8ad315ece17d22abd82ce96e3a2bebaa6efe | |||
v1.0 | instruct | Algorithm | Algorithm_36327_I | ### Problem Statement
A valid magic square is a grid of numbers where the sum of every row, column, and diagonal is the same. You are required to generate all possible 3x3 magic squares and count how many unique ones exist when arranging the numbers from 1 to 9 without repetition.
**Function to Implement**
Implement ... | from itertools import permutations
def is_magic_square(square):
"""
Check if a given 3x3 square is a magic square.
:param square: List of lists representing the 3x3 square.
:return: Boolean indicating if the square is a magic square.
"""
# Calculate the sums of rows, columns, and diagonals... | from solution import is_magic_square, count_magic_squares
def test_is_magic_square():
assert is_magic_square([[2, 7, 6], [9, 5, 1], [4, 3, 8]]) is True
assert is_magic_square([[8, 1, 6], [3, 5, 7], [4, 9, 2]]) is True
assert is_magic_square([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) is False
def test_count_magic_... | [
{
"docstring": "Check if a given 3x3 square is a magic square.\n\n:param square: List of lists representing the 3x3 square.\n:return: Boolean indicating if the square is a magic square.",
"function_declaration": "def is_magic_square(square):",
"function_name": "is_magic_square",
"parameter_list": "(... | [
1,
1,
0,
1,
1,
0,
0,
0,
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": "from itertools import permutations\n\ndef is_magic_square(square):\n # Check rows\n for i in range(0, 9, 3):\n if sum(square[i:i+3]) != 15:\n ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000036327",
"row_id": 36327,
"seed_ids": "[2862]"
} | 0.701387 | Algorithm_36327 | I | [
"is_magic_square",
"count_magic_squares"
] | 2 | [
[
"count_magic_squares",
"is_magic_square"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | e1d2f201979fc795e01ceec7a3a61f00bbd625c7 | e9da906dd0773bdb6e116463969ac8cb4af6ea5b | |||
v1.0 | instruct | Algorithm | Algorithm_36385_I | ### Question:
Implement a function `group_palindrome_anagrams` that groups a list of strings into subsets where each subset contains strings that are anagrams of each other and, when rearranged, can form a palindrome. Two strings are considered anagrams if one string can be rearranged to form the other. A string can b... | from collections import Counter
def can_form_palindrome(s):
"""
Determine if the string s can be rearranged to form a palindrome.
"""
char_count = Counter(s)
odd_count = sum(1 for count in char_count.values() if count % 2 != 0)
return odd_count <= 1
def group_palindrome_anagrams(words):
""... | from solution import group_palindrome_anagrams
def test_group_palindrome_anagrams_example_1():
words = ['civic', 'ivicc', 'aabb', 'bbaa', 'abc', 'cba', 'bca']
assert group_palindrome_anagrams(words) == [['civic', 'ivicc'], ['aabb', 'bbaa']]
def test_group_palindrome_anagrams_example_2():
words = ['aaa', '... | [
{
"docstring": "Determine if the string s can be rearranged to form a palindrome.",
"function_declaration": "def can_form_palindrome(s):",
"function_name": "can_form_palindrome",
"parameter_list": "(s)"
},
{
"docstring": "Group the strings into subsets where each subset contains strings that... | [
0,
0,
0,
0,
1,
1,
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": "from collections import defaultdict, Counter\n\ndef can_form_palindrome(word):\n count = Counter(word)\n odd_count = sum(1 for freq in count.values() if fr... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000036385",
"row_id": 36385,
"seed_ids": "[1832]"
} | 0.663687 | Algorithm_36385 | I | [
"can_form_palindrome",
"group_palindrome_anagrams"
] | 2 | [
[
"group_palindrome_anagrams",
"can_form_palindrome"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f6e768256d4a9d8f5c5b03d982ba5b083e85e290 | 683c1a0f2c3721996cb449e9233c491890c86ccf | |||
v1.0 | instruct | Algorithm | Algorithm_36429_I | ### Question
**Problem Statement**:
You are given a function to calculate the factorial of a number. Your task is to extend this functionality by writing two new functions: one to compute the factorial recursively and another to compute it iteratively. Additionally, you should compare the execution time of both metho... | import time
def factorial_recursive(n: int) -> int:
"""
Computes the factorial of n recursively.
"""
if n == 0:
return 1
return n * factorial_recursive(n - 1)
def factorial_iterative(n: int) -> int:
"""
Computes the factorial of n iteratively.
"""
result = 1
for i in ra... | from solution import factorial_recursive, factorial_iterative, compare_execution_time
def test_factorial_recursive():
assert factorial_recursive(0) == 1
assert factorial_recursive(1) == 1
assert factorial_recursive(5) == 120
assert factorial_recursive(10) == 3628800
def test_factorial_iterative():... | [
{
"docstring": "Computes the factorial of n recursively.",
"function_declaration": "def factorial_recursive(n):",
"function_name": "factorial_recursive",
"parameter_list": "(n)"
},
{
"docstring": "Computes the factorial of n iteratively.",
"function_declaration": "def factorial_iterative... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 10 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import time\n\ndef factorial_recursive(n: int) -> int:\n \"\"\"\n Returns the factorial of n using recursive approach.\n \"\"\"\n if n == 0:\n ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000036429",
"row_id": 36429,
"seed_ids": "[4163]"
} | 0.650796 | Algorithm_36429 | I | [
"factorial_recursive",
"factorial_iterative",
"compare_execution_time"
] | 3 | [
[
"compare_execution_time",
"factorial_iterative"
],
[
"compare_execution_time",
"factorial_recursive"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 192813af9828f43de1b477869138afa08ba6cb23 | 63fcb96ecaa7b0ef72839637bf14958b4a480994 | |||
v1.0 | instruct | Algorithm | Algorithm_36432_I | ### Problem: Finding Duplicate Files in a Directory
Write a program to detect duplicate files in a directory. Two files are considered duplicates if they have the same size and the same content.
Your program should resolve this problem using file comparison techniques and efficient file I/O operations.
#### Input
* ... | import os
import hashlib
from collections import defaultdict
def calculate_file_hash(file_path):
""" Calculate the hash of a file using SHA-256 """
hash_sha256 = hashlib.sha256()
with open(file_path, "rb") as f:
for chunk in iter(lambda: f.read(4096), b""):
hash_sha256.update(chunk)
... | import os
import shutil
import pytest
from solution import find_duplicate_files
def setup_test_directory_structure():
os.makedirs('test_directory/subdir1', exist_ok=True)
os.makedirs('test_directory/subdir2', exist_ok=True)
with open('test_directory/file1.txt', 'w') as f:
f.write('This is some... | [
{
"docstring": "Calculate the hash of a file using SHA-256 ",
"function_declaration": "def calculate_file_hash(file_path):",
"function_name": "calculate_file_hash",
"parameter_list": "(file_path)"
},
{
"docstring": "Find and return duplicate files in the directory ",
"function_declaratio... | [
1,
1,
0,
1,
0,
0,
1,
1,
0,
1
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import os\nimport hashlib\nfrom collections import defaultdict\n\ndef get_file_hash(file_path):\n \"\"\"Compute SHA-256 hash of the file.\"\"\"\n hash_algo... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "0000036432",
"row_id": 36432,
"seed_ids": "[2091]"
} | 0.633903 | Algorithm_36432 | I | [
"calculate_file_hash",
"find_duplicate_files"
] | 2 | [
[
"find_duplicate_files",
"calculate_file_hash"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 37a0732c9978b03805c33a919b0002065d82bd2c | a585fad7437b1b89699fe2d81054a37f91331342 | |||
v1.0 | instruct | Algorithm | Algorithm_36456_I | ### Coding Challenge
You have been asked to develop a system to monitor and alert unusual activity on a social media platform. The system will analyze historical post data to detect significant spikes in activity and notify when a spike is detected using two different methods.
#### Requirements:
1. **Implement** two ... | from scipy.stats import zscore
import numpy as np
from sklearn.cluster import DBSCAN
def z_score_detection(historical_data, today_count, threshold=3):
"""
Detect outlier using Z-score method.
An outlier is flagged if the Z-score is greater than the given threshold.
"""
historical_z_scores = zscore(... | from solution import z_score_detection, dbscan_detection, anomaly_notifier
def test_z_score_detection_no_anomaly():
historical_data = [50, 52, 53, 47, 48, 51, 45, 60, 49, 54, 55, 63, 42, 46, 58, 59, 57, 65, 62, 40, 53, 50, 55, 60, 61, 64, 51, 48, 52, 45]
today_count = 55
assert z_score_detection(historical... | [
{
"docstring": "Detect outlier using Z-score method.\nAn outlier is flagged if the Z-score is greater than the given threshold.",
"function_declaration": "def z_score_detection(historical_data, today_count, threshold=3):",
"function_name": "z_score_detection",
"parameter_list": "(historical_data, to... | [
0,
1,
1,
0,
0,
1,
0,
0,
1,
1
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import numpy as np\nfrom sklearn.cluster import DBSCAN\n\ndef z_score_detection(historical_post_data, todays_post_count, threshold=3):\n \"\"\"\n Detects a... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "0000036456",
"row_id": 36456,
"seed_ids": "[716]"
} | 0.506201 | Algorithm_36456 | I | [
"z_score_detection",
"dbscan_detection",
"anomaly_notifier"
] | 3 | [
[
"anomaly_notifier",
"dbscan_detection"
],
[
"anomaly_notifier",
"z_score_detection"
]
] | 2 | [] | false | [] | false | pytest | true | [
"numpy",
"scipy",
"sklearn"
] | false | 713fef95786da9cc126d25219ca6f4ac6b145e53 | 191776c49992ca922c939bc473f225aa1d7ad67e | |||
v1.0 | instruct | Algorithm | Algorithm_36467_I | ### Context
In data structures, trees represent hierarchical relationships and are pivotal for various applications like file systems, database indexing, and more. A Binary Search Tree (BST) is a binary tree where each node has at most two children generally referred to as the left child and right child. For each node... | class TreeNode:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
self.height = 1
def get_height(node):
if not node:
return 0
return node.height
def update_height(node):
node.height = 1 + max(get_height(node.left), get_height(node.right... | def test_insert_single_node():
root = insert_node(None, 10)
assert root.key == 10
assert root.left == None
assert root.right == None
assert root.height == 1
def test_insert_left_heavy():
root = insert_node(None, 20)
root = insert_node(root, 10)
root = insert_node(root, 5)
assert roo... | [] | [
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": "class TreeNode:\n def __init__(self, key):\n self.key = key\n self.left = None\n self.right = None\n self.height = 1 \n\ndef get_h... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "0000036467",
"row_id": 36467,
"seed_ids": "[2788]"
} | 0.598076 | Algorithm_36467 | I | [
"get_height",
"update_height",
"get_balance",
"right_rotate",
"left_rotate",
"insert_node"
] | 6 | [
[
"get_balance",
"get_height"
],
[
"insert_node",
"get_balance"
],
[
"insert_node",
"left_rotate"
],
[
"insert_node",
"right_rotate"
],
[
"insert_node",
"update_height"
],
[
"left_rotate",
"update_height"
],
[
"right_rotate",
"update_he... | 8 | [] | false | [
"TreeNode"
] | true | pytest | false | [] | true | 89b44828d9fbeb20f08a27d3b71e954efe804543 | b8468ae2a1711d40543c3e1b3bdcb7e3c04822af | |||
v1.0 | instruct | Algorithm | Algorithm_36523_I | ### Task
You are asked to implement a function to perform matrix multiplication using the Strassen algorithm. This algorithm is particularly effective for large matrices and reduces the time complexity compared to conventional methods.
### Problem Statement
**Function Signature**:
```python
def strassen_matrix_multip... | from typing import List
def add_matrices(A, B):
return [[A[i][j] + B[i][j] for j in range(len(A))] for i in range(len(A))]
def subtract_matrices(A, B):
return [[A[i][j] - B[i][j] for j in range(len(A))] for i in range(len(A))]
def split_matrix(M):
mid = len(M) // 2
A11 = [row[:mid] for row in M[:mid]... | def test_strassen_example1():
A = [
[1, 0],
[0, 1]
]
B = [
[4, 1],
[2, 2]
]
expected = [
[4, 1],
[2, 2]
]
assert strassen_matrix_multiplication(A, B) == expected
def test_strassen_example2():
A = [
[1, 2],
[3, 4]
]
... | [
{
"docstring": null,
"function_declaration": "def add_matrices(A, B):",
"function_name": "add_matrices",
"parameter_list": "(A, B)"
},
{
"docstring": null,
"function_declaration": "def subtract_matrices(A, B):",
"function_name": "subtract_matrices",
"parameter_list": "(A, B)"
}... | [
0,
1,
1,
1,
1,
0,
1,
0,
1,
1
] | 7 | easy | 0.7 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef add_matrix(A, B):\n return [[A[i][j] + B[i][j] for j in range(len(A))] for i in range(len(A))]\n\ndef sub_matrix(A, B):\n re... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000036523",
"row_id": 36523,
"seed_ids": "[4111]"
} | 0.470677 | Algorithm_36523 | I | [
"add_matrices",
"subtract_matrices",
"split_matrix",
"strassen_matrix_multiplication"
] | 4 | [
[
"strassen_matrix_multiplication",
"add_matrices"
],
[
"strassen_matrix_multiplication",
"split_matrix"
],
[
"strassen_matrix_multiplication",
"subtract_matrices"
]
] | 3 | [] | false | [] | false | pytest | false | [] | true | eeaec622d84327d780255289ba0e05eef346a4a7 | 459d09e6bf3e57af29e5c496ba3bd5677fad2131 | |||
v1.0 | instruct | Algorithm | Algorithm_36542_I | ### Question
You have been tasked with implementing several text processing functions from scratch. These functions include text normalization, tokenization, and various calculations. Below is the detailed description of the functions you need to implement.
1. **Text Normalization**: Write a function `normalize_text(... | import re
from collections import defaultdict
from typing import List, Dict, Tuple
import math
def normalize_text(text: str) -> str:
"""
Converts the input text to lowercase, removes punctuation, and strips any leading or trailing whitespace.
"""
text = text.lower()
text = re.sub(r'[^\w\s]', '', te... | import pytest
from solution import normalize_text, tokenize_text, word_frequency, generate_bigrams, tf_idf
def test_normalize_text():
assert normalize_text(" Hello, World! ") == "hello world"
assert normalize_text("Python's cool.") == "pythons cool"
assert normalize_text("") == ""
def test_tokenize_text()... | [
{
"docstring": "Converts the input text to lowercase, removes punctuation, and strips any leading or trailing whitespace.",
"function_declaration": "def normalize_text(text):",
"function_name": "normalize_text",
"parameter_list": "(text)"
},
{
"docstring": "Splits the input text into words, ... | [
0,
1,
0,
0,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import re\nfrom collections import defaultdict, Counter\nfrom typing import List, Dict, Tuple\nimport math\n\ndef normalize_text(text: str) -> str:\n \"\"\"\n... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "0000036542",
"row_id": 36542,
"seed_ids": "[4352]"
} | 0.672765 | Algorithm_36542 | I | [
"normalize_text",
"tokenize_text",
"word_frequency",
"generate_bigrams",
"tf_idf"
] | 5 | [
[
"generate_bigrams",
"normalize_text"
],
[
"generate_bigrams",
"tokenize_text"
],
[
"tf_idf",
"normalize_text"
],
[
"tf_idf",
"tokenize_text"
],
[
"tf_idf",
"word_frequency"
],
[
"word_frequency",
"normalize_text"
],
[
"word_frequency",
... | 7 | [] | false | [] | false | pytest | true | [] | true | aa18a320a40866746733a1a8ebd8effafd4e528c | 3f94e937ddfa604ff9afbdfd7dafe6105ee78522 | |||
v1.0 | instruct | Algorithm | Algorithm_36611_I | ### Question
**Context**:
You are a software engineer at a logistics company that ensures timely delivery of packages across various cities. Your manager has assigned you the task of optimizing the delivery routes to minimize the total delivery time while ensuring all cities are connected. Daily, you receive a list of... | def find(parent, i):
if parent[i] == i:
return i
else:
return find(parent, parent[i])
def union(parent, rank, x, y):
xroot = find(parent, x)
yroot = find(parent, y)
if rank[xroot] < rank[yroot]:
parent[xroot] = yroot
elif rank[xroot] > rank[yroot]:
parent[yroot]... | from solution import kruskal_mst
def test_kruskal_mst_example1():
n = 4
edges = [(0, 1, 10), (0, 2, 6), (0, 3, 5), (1, 3, 15), (2, 3, 4)]
result = kruskal_mst(n, edges)
assert result == [(2, 3, 4), (0, 3, 5), (0, 1, 10)]
def test_kruskal_mst_example2():
n = 3
edges = [(0, 1, 1), (1, 2, 4), (0,... | [
{
"docstring": null,
"function_declaration": "def find(parent, i):",
"function_name": "find",
"parameter_list": "(parent, i)"
},
{
"docstring": null,
"function_declaration": "def union(parent, rank, x, y):",
"function_name": "union",
"parameter_list": "(parent, rank, x, y)"
},
... | [
1,
1,
0,
1,
0,
0,
0,
1,
1,
0
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "class UnionFind:\n def __init__(self, n):\n self.parent = list(range(n))\n self.rank = [0] * n\n \n def find(self, u):\n if self.pa... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000036611",
"row_id": 36611,
"seed_ids": "[558]"
} | 0.666751 | Algorithm_36611 | I | [
"find",
"union",
"kruskal_mst"
] | 3 | [
[
"kruskal_mst",
"find"
],
[
"kruskal_mst",
"union"
],
[
"union",
"find"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 0bbb904906a7a230f609299beca9fe8b973faff5 | 63e9c06282c092adc2e7c07434f0ce1fa959374d | |||
v1.0 | instruct | Algorithm | Algorithm_36616_I | ### Prime Anagram Pair Checker
#### Problem Statement:
An anagram pair of two numbers is formed when one number can be rearranged to produce the other number. A pair of numbers is termed an anagram prime pair if both numbers are prime and are anagrams of each other. Your task is to implement a function that verifies ... | 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 is_prime_anagram_pair(number1: int, number... | from solution import is_prime_anagram_pair
def test_prime_anagram_pair_true():
assert is_prime_anagram_pair(13, 31) == True
assert is_prime_anagram_pair(17, 71) == True
assert is_prime_anagram_pair(1193, 1931) == True
def test_prime_anagram_pair_false():
assert is_prime_anagram_pair(23, 32) == False
... | [
{
"docstring": null,
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Determine if the given numbers form a prime anagram pair.\n\n:param number1: int: the first number to check\n:param number2: int: the second number to chec... | [
0,
1,
0,
0,
1,
1,
1,
1,
0,
0
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def is_prime(n):\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == 0 or n % 3 == 0:\n return False\n i = 5\n ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "0000036616",
"row_id": 36616,
"seed_ids": "[3456]"
} | 0.608759 | Algorithm_36616 | I | [
"is_prime",
"is_prime_anagram_pair"
] | 2 | [
[
"is_prime_anagram_pair",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 0e23c4d6504e54c89655d076aab7a90dff223bb1 | ca5f55a2ccf12dc9d50de5c1d2742721516a0a3d | |||
v1.0 | instruct | Algorithm | Algorithm_36625_I | ### Event Time Overlap
You are creating a function to determine the overlapping duration between two events. Each event is characterized by a start time and an end time.
The times are given in 24-hour format (HH:MM), and you need to implement a function that returns the total overlapping duration in minutes.
You mus... | from typing import Tuple
def time_to_minutes(time: str) -> int:
"""Convert time in "HH:MM" format to minutes since midnight."""
hours, minutes = map(int, time.split(":"))
return hours * 60 + minutes
def event_overlap(event1: Tuple[str, str], event2: Tuple[str, str]) -> int:
"""Calculate the overlap du... | from solution import event_overlap
def test_event_overlap_with_no_overlap():
assert event_overlap(("09:00", "10:00"), ("10:00", "11:00")) == 0
def test_event_overlap_with_partial_overlap():
assert event_overlap(("10:00", "12:30"), ("11:00", "13:00")) == 90
assert event_overlap(("14:00", "15:00"), ("13:30"... | [
{
"docstring": "Convert time in \"HH:MM\" format to minutes since midnight.",
"function_declaration": "def time_to_minutes(time):",
"function_name": "time_to_minutes",
"parameter_list": "(time)"
},
{
"docstring": "Calculate the overlap duration in minutes between two events.",
"function_... | [
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": "from typing import Tuple\n\ndef time_to_minutes(time: str) -> int:\n hours, minutes = map(int, time.split(\":\"))\n return hours * 60 + minutes\n\ndef even... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000036625",
"row_id": 36625,
"seed_ids": "[2542]"
} | 0.575687 | Algorithm_36625 | I | [
"time_to_minutes",
"event_overlap"
] | 2 | [
[
"event_overlap",
"time_to_minutes"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 7327266d871aeb46d4ef95457fd88d344ee3217d | e7a736b7ce31323b2b60a3ae5724acc4b4391858 | |||
v1.0 | instruct | Algorithm | Algorithm_36661_I | ### Coding Question
You are tasked with developing a small module to manage a parking lot system that operates on a first-come, first-served basis. The module should handle vehicle entries, exits, and maintain records of all parked vehicles along with their entry times.
#### Objective
Build functionalities to effici... | from datetime import datetime
def validate_vehicle_number(vehicle_number: str) -> bool:
"""
Validate the vehicle number to match format XX-1234.
"""
import re
pattern = r"^[A-Z]{2}-\d{4}$"
if re.match(pattern, vehicle_number):
return True
return False
def vehicle_entry(vehicle_numb... | import pytest
from datetime import datetime
from solution import validate_vehicle_number, vehicle_entry, vehicle_exit
def test_validate_vehicle_number_valid():
assert validate_vehicle_number("AB-1234") == True
def test_validate_vehicle_number_invalid():
assert validate_vehicle_number("A1-234") == False
as... | [
{
"docstring": "Validate the vehicle number to match format XX-1234.",
"function_declaration": "def validate_vehicle_number(vehicle_number):",
"function_name": "validate_vehicle_number",
"parameter_list": "(vehicle_number)"
},
{
"docstring": "Register the vehicle in the parking lot dict afte... | [
1,
1,
1,
1,
1,
1,
1,
1,
0,
1
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import re\nfrom datetime import datetime\n\ndef validate_vehicle_number(vehicle_number):\n \"\"\"\n Validates the format of the vehicle number.\n \"\"\"... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000036661",
"row_id": 36661,
"seed_ids": "[445]"
} | 0.558186 | Algorithm_36661 | I | [
"validate_vehicle_number",
"vehicle_entry",
"vehicle_exit"
] | 3 | [
[
"vehicle_entry",
"validate_vehicle_number"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 42c4de82799d49d398f07ccd66038eb96e317683 | 57731ed3ce70303342065b344d3f99b409d67901 | |||
v1.0 | instruct | Algorithm | Algorithm_36738_I | ### Question: Implementing Gradient Descent for Linear Regression
In this task, you will implement and utilize gradient descent to optimize a linear regression model. Understanding gradient descent and linear regression is fundamental for various machine learning and data science applications.
#### Objectives:
1. Im... | import numpy as np
def compute_cost(X: np.ndarray, y: np.ndarray, theta: np.ndarray) -> float:
"""
Compute the cost (mean squared error) for linear regression.
Parameters:
- X: Feature matrix (including the intercept term) of shape (n_samples, n_features).
- y: True labels of shape (n_samples,... | import numpy as np
from solution import compute_cost, gradient_descent_step, train_model
def test_compute_cost():
X = np.array([[1, 1], [1, 2], [1, 3]])
y = np.array([1, 2, 3])
theta = np.array([0, 1])
expected_cost = 0
assert np.isclose(compute_cost(X, y, theta), expected_cost), "Test case failed ... | [
{
"docstring": "Compute the cost (mean squared error) for linear regression.\n\nParameters:\n- X: Feature matrix (including the intercept term) of shape (n_samples, n_features).\n- y: True labels of shape (n_samples,).\n- theta: Model parameters of shape (n_features,).\n\nReturns:\n- float: The mean squared err... | [
0,
0,
0,
0,
0,
1,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import numpy as np\n\ndef compute_cost(X: np.ndarray, y: np.ndarray, theta: np.ndarray) -> float:\n \"\"\"\n Calculate the mean squared error for a given s... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "0000036738",
"row_id": 36738,
"seed_ids": "[498]"
} | 0.648725 | Algorithm_36738 | I | [
"compute_cost",
"gradient_descent_step",
"train_model"
] | 3 | [
[
"train_model",
"gradient_descent_step"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | 74ff592c2d77e0a3b26807c489ba313b98e4a652 | 4687c431cb74a269a13370d493e205177e9743e4 | |||
v1.0 | instruct | Algorithm | Algorithm_36798_I | ### Question: Sorting Integers with Custom Comparator
You are required to implement a custom sorting function for a list of integers. Your task is to sort the integers based on the sum of their digits. In case of a tie (i.e., two integers have the same sum of digits), the integers should be sorted by their natural ord... | from typing import List
def digit_sum(n: int) -> int:
return sum(int(d) for d in str(abs(n)))
def custom_sort(arr: List[int]) -> List[int]:
return sorted(arr, key=lambda x: (digit_sum(x), x)) | from solution import custom_sort
def test_example_cases():
assert custom_sort([56, 74, 35, 213, 92, 110]) == [110, 213, 35, 56, 74, 92]
assert custom_sort([6, 21, 30, 111, 100]) == [100, 21, 30, 111, 6]
def test_single_element():
assert custom_sort([5]) == [5]
assert custom_sort([0]) == [0]
def test_... | [
{
"docstring": null,
"function_declaration": "def digit_sum(n):",
"function_name": "digit_sum",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def custom_sort(arr):",
"function_name": "custom_sort",
"parameter_list": "(arr)"
}
] | [
0,
1,
0,
0,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef digit_sum(n: int) -> int:\n \"\"\"\n Calculate the sum of digits of the given number.\n \"\"\"\n return sum(int(digit)... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "0000036798",
"row_id": 36798,
"seed_ids": "[2270]"
} | 0.626575 | Algorithm_36798 | I | [
"digit_sum",
"custom_sort"
] | 2 | [
[
"custom_sort",
"digit_sum"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 5b779d055e6b527fb7562c3c9cb48a53cfb6f294 | 67b8420f8b7ee8f458de64991c3816165563dd30 | |||
v1.0 | instruct | Algorithm | Algorithm_36819_I | ### Coding Question: Generate Lexicographically Smallest String after Swaps
#### Context
Given a string and a list of pairs of indices in the string, you can swap the characters at these indices. The task is to determine the lexicographically smallest string that can be obtained by performing any number of swaps among... | from typing import List, Tuple
class UnionFind:
def __init__(self, n: int):
self.parent = list(range(n))
self.rank = [1] * n
def find(self, p: int) -> int:
if self.parent[p] != p:
self.parent[p] = self.find(self.parent[p]) # Path compression
return self.parent[p]
... | from solution import union_find_initialize, smallest_string_after_swaps
def test_union_find_initialize():
uf = union_find_initialize(5)
assert uf.find(0) == 0
assert uf.find(1) == 1
assert uf.find(4) == 4
def test_union():
uf = union_find_initialize(5)
uf.union(0, 1)
assert uf.find(0) == u... | [] | [
0,
0,
0,
1,
0,
0,
1,
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": "from typing import List, Tuple\n\nclass UnionFind:\n def __init__(self, size):\n self.parent = list(range(size))\n self.rank = [1] * size\n\n ... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "0000036819",
"row_id": 36819,
"seed_ids": "[3459]"
} | 0.722963 | Algorithm_36819 | I | [
"union_find_initialize",
"smallest_string_after_swaps"
] | 2 | [
[
"smallest_string_after_swaps",
"union_find_initialize"
]
] | 1 | [] | false | [
"UnionFind"
] | true | pytest | true | [] | true | 318faf1326258b8afeb8b58bfda0ad78b71255fc | 5a15d8b11506557648788436dac59126081c94f9 | |||
v1.0 | instruct | Algorithm | Algorithm_36822_I | ### Scenario
You're working on a data visualization tool that supports rendering 2D plots. A crucial feature of this tool is to create a heatmap based on a given set of data points. Each data point contributes to the heatmap with an influence that decreases with distance.
### Task
Given a list of data points and their... | import math
from typing import List, Tuple
def gaussian_kernel(k_size: int, sigma: float) -> List[List[float]]:
"""
Generates a Gaussian kernel given the size and standard deviation.
"""
kernel = [[0.0] * k_size for _ in range(k_size)]
mean = k_size // 2
sum_val = 0.0
for x in range(k_size)... | from solution import generate_heatmap
def test_single_data_point():
data_points = [(5, 5, 10)]
width = 10
height = 10
k_size = 3
sigma = 1.0
heatmap = generate_heatmap(data_points, width, height, k_size, sigma)
assert len(heatmap) == height
assert len(heatmap[0]) == width
asser... | [
{
"docstring": "Generates a Gaussian kernel given the size and standard deviation.",
"function_declaration": "def gaussian_kernel(k_size, sigma):",
"function_name": "gaussian_kernel",
"parameter_list": "(k_size, sigma)"
},
{
"docstring": "Generates a heatmap using Gaussian smoothing based on... | [
1,
1,
1,
1,
0,
1,
0,
1,
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 numpy as np\nfrom typing import List, Tuple\n\ndef generate_heatmap(data_points: List[Tuple[int, int, float]], width: int, height: int, k_size: int, sigma... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000036822",
"row_id": 36822,
"seed_ids": "[4283]"
} | 0.66674 | Algorithm_36822 | I | [
"gaussian_kernel",
"generate_heatmap"
] | 2 | [
[
"generate_heatmap",
"gaussian_kernel"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f0cb72df010786fa5b915cd914d93871365de3fe | 646e3ab039a56e8e3200967459e747058a6dc665 | |||
v1.0 | instruct | Algorithm | Algorithm_36898_I | ### Matrix Diagonal Sum
**Background**: You are working with square matrices (2D lists) and need to perform various operations on them. One such operation is calculating the sum of the elements along both diagonals of the matrix.
**Objective**: Implement the functionality to:
1. Calculate the sum of the main diagonal... | def main_diagonal_sum(matrix):
"""
Returns the sum of the main diagonal (from the top left to the bottom right).
"""
return sum(matrix[i][i] for i in range(len(matrix)))
def secondary_diagonal_sum(matrix):
"""
Returns the sum of the secondary diagonal (from the top right to the bottom left).
... | def test_main_diagonal_sum():
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
assert main_diagonal_sum(matrix) == 15 # 1 + 5 + 9
def test_secondary_diagonal_sum():
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
assert secondary_diagonal_sum(matrix) ==... | [
{
"docstring": "Returns the sum of the main diagonal (from the top left to the bottom right).",
"function_declaration": "def main_diagonal_sum(matrix):",
"function_name": "main_diagonal_sum",
"parameter_list": "(matrix)"
},
{
"docstring": "Returns the sum of the secondary diagonal (from the ... | [
1,
0,
1,
0,
1,
1,
1,
0,
0
] | 5 | medium | 0.556 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def main_diagonal_sum(matrix):\n \"\"\"\n Returns the sum of the main diagonal elements of a square matrix.\n \"\"\"\n n = len(matrix)\n return su... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "0000036898",
"row_id": 36898,
"seed_ids": "[1710]"
} | 0.600213 | Algorithm_36898 | I | [
"main_diagonal_sum",
"secondary_diagonal_sum",
"total_diagonal_sum"
] | 3 | [
[
"total_diagonal_sum",
"main_diagonal_sum"
],
[
"total_diagonal_sum",
"secondary_diagonal_sum"
]
] | 2 | [] | false | [] | false | pytest | false | [] | true | 35629fb1a642bebf9de6531ee2ac3874baf655a4 | 9e29f0dbba5ec0a74f3752ccfa7d60637d37c078 | |||
v1.0 | instruct | Algorithm | Algorithm_36972_I | ### Question
#### Problem Statement:
You are required to create a Python function that calculates the factorial of a given non-negative integer using both iterative and recursive methods.
Write a Python function `factorial(n: int, method: str) -> int` that computes the factorial based on the given method. The `meth... | def factorial(n: int, method: str) -> int:
"""
Compute the factorial of a given non-negative integer `n` using the specified method.
Parameters:
n (int): Non-negative integer for which the factorial is to be computed.
method (str): Method to use for computation, either 'iterative' or 'recursive... | from solution import factorial, iterative_factorial, recursive_factorial
def test_iterative_factorial():
assert iterative_factorial(0) == 1
assert iterative_factorial(1) == 1
assert iterative_factorial(5) == 120
assert iterative_factorial(12) == 479001600
def test_recursive_factorial():
assert rec... | [
{
"docstring": "Compute the factorial of a given non-negative integer `n` using the specified method.\n\nParameters:\nn (int): Non-negative integer for which the factorial is to be computed.\nmethod (str): Method to use for computation, either 'iterative' or 'recursive'.\n\nReturns:\nint: Factorial of the given... | [
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 factorial(n: int, method: str) -> int:\n \"\"\"\n Returns the factorial of n using the specified method ('iterative' or 'recursive').\n \"\"\"\n ... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000036972",
"row_id": 36972,
"seed_ids": "[3232]"
} | 0.700671 | Algorithm_36972 | I | [
"factorial",
"iterative_factorial",
"recursive_factorial"
] | 3 | [
[
"factorial",
"iterative_factorial"
],
[
"factorial",
"recursive_factorial"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | ffab90863cf69047de1b4633dbca91f63f21985f | aa28da1599f2485918e22066389cc79119d7de62 | |||
v1.0 | instruct | Algorithm | Algorithm_37027_I | ### Designing a File Integrity Checker
You are tasked with creating a file integrity checker tool that ensures the contents of files in a directory match their expected hashes. The tool should generate and verify hashes using the SHA-256 algorithm.
Implement the following two functions:
1. **generate_file_hash**: T... | import hashlib
import os
def generate_file_hash(file_path):
"""
Computes the SHA-256 hash of a given file.
Args:
- file_path (str): Path to the file
Returns:
- str: SHA-256 hash of the file
"""
try:
sha256 = hashlib.sha256()
with open(file_path, 'rb') as f:
... | from solution import generate_file_hash, verify_files
import pytest
import tempfile
import os
def create_temp_file(content):
temp_dir = tempfile.mkdtemp()
temp_file_path = os.path.join(temp_dir, "tempfile.txt")
with open(temp_file_path, 'w') as temp_file:
temp_file.write(content)
return temp_fi... | [
{
"docstring": "Computes the SHA-256 hash of a given file.\n\nArgs:\n- file_path (str): Path to the file\n\nReturns:\n- str: SHA-256 hash of the file",
"function_declaration": "def generate_file_hash(file_path):",
"function_name": "generate_file_hash",
"parameter_list": "(file_path)"
},
{
"d... | [
1,
0,
1,
0,
0,
1,
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 hashlib\nimport os\n\ndef generate_file_hash(file_path):\n \"\"\"\n Computes the SHA-256 hash of a given file.\n \n Args:\n file_path (... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "0000037027",
"row_id": 37027,
"seed_ids": "[2361]"
} | 0.705896 | Algorithm_37027 | I | [
"generate_file_hash",
"verify_files"
] | 2 | [
[
"verify_files",
"generate_file_hash"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 0f51984a0642ea6b96f5a9477bbffa40867ba0fc | 1f4d15a7170bf603374a01f2748ff6cb29fe979c | |||
v1.0 | instruct | Algorithm | Algorithm_37147_I | ### Coding Assessment Question
#### Problem Statement
You are tasked with implementing a logistics optimization algorithm for a delivery truck. The goal is to minimize the total distance traveled while delivering packages to several destinations. The destinations will be represented by coordinates on a Cartesian plan... | import math
def calculate_distance(point1, point2):
return math.sqrt((point1[0] - point2[0])**2 + (point1[1] - point2[1])**2)
def optimize_delivery_route(destinations):
if not destinations:
return ([], 0.0)
n = len(destinations)
visited = [False] * n
route = [0]
total_distance = 0.0
... | from solution import optimize_delivery_route
def test_optimize_delivery_route_basic():
destinations = [(0, 0), (2, 3), (5, 8), (6, 2), (8, 6), (1, 7)]
route, total_distance = optimize_delivery_route(destinations)
assert route[0] == 0 and route[-1] == 0
assert isinstance(total_distance, float)
asser... | [
{
"docstring": null,
"function_declaration": "def calculate_distance(point1, point2):",
"function_name": "calculate_distance",
"parameter_list": "(point1, point2)"
},
{
"docstring": null,
"function_declaration": "def optimize_delivery_route(destinations):",
"function_name": "optimize... | [
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": "import math\nimport random\n\ndef euclidean_distance(p1, p2):\n return math.sqrt((p1[0] - p2[0])**2 + (p1[1] - p2[1])**2)\n\ndef optimize_delivery_route(desti... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000037147",
"row_id": 37147,
"seed_ids": "[5253]"
} | 0.631608 | Algorithm_37147 | I | [
"calculate_distance",
"optimize_delivery_route"
] | 2 | [
[
"optimize_delivery_route",
"calculate_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 38b80b120c5ccaefedcea9a517c9895e82251995 | 3bb6ea3386f0ae479c2f8688fd9547cd7152ac10 | |||
v1.0 | instruct | Algorithm | Algorithm_37157_I | ### Question: Validate and Normalize Email Addresses
You are tasked with writing two functions to:
1. **Validate** and **normalize** a given email address string.
2. **Normalize** a list of email addresses by removing duplicates and maintaining valid ones only.
#### Function 1 Requirements: `validate_and_normalize_em... | import re
def validate_and_normalize_email(email: str) -> str:
# Regex pattern for validating email
email_pattern = r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$'
if not re.match(email_pattern, email):
return None
local, domain = email.split('@')
if domain.lower() == "gmail.com":... | from solution import validate_and_normalize_email, normalize_emails
def test_validate_and_normalize_email_valid_gmail():
assert validate_and_normalize_email("User.name@gmail.com") == "username@gmail.com"
assert validate_and_normalize_email("User.Name@GMAIL.com") == "username@gmail.com"
def test_validate_and_n... | [
{
"docstring": null,
"function_declaration": "def validate_and_normalize_email(email):",
"function_name": "validate_and_normalize_email",
"parameter_list": "(email)"
},
{
"docstring": null,
"function_declaration": "def normalize_emails(emails):",
"function_name": "normalize_emails",
... | [
0,
0,
0,
0,
0,
0,
1,
0,
1,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import re\n\ndef validate_and_normalize_email(email: str) -> str:\n \"\"\"\n Validates and normalizes a given email address.\n \n Parameters:\n ... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000037157",
"row_id": 37157,
"seed_ids": "[2891]"
} | 0.564081 | Algorithm_37157 | I | [
"validate_and_normalize_email",
"normalize_emails"
] | 2 | [
[
"normalize_emails",
"validate_and_normalize_email"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | d98bde4774bd893980dd8485b51540ffafb09bf5 | 0e694b9db1e12d13a1ec14971892b4a5d17e8b73 | |||
v1.0 | instruct | Algorithm | Algorithm_37159_I | ### **Problem Statement:**
You are tasked with designing a simple scheduling system that helps in managing the meeting schedules within a company. The system should avoid conflicts and allow for adding, removing, and checking meeting times.
### **Function Specification:**
1. **`add_meeting(schedule: dict[str, list[t... | def add_meeting(schedule: dict[str, list[tuple[int, int]]], day: str, start: int, end: int) -> bool:
"""
Adds a meeting to the schedule if there is no conflict.
schedule: dictionary with days as keys and meeting time intervals as values
day: day of the week
start: start time of the meeting
... | from solution import add_meeting, remove_meeting, check_meeting_conflict
def test_add_meeting_no_conflict():
schedule = {"Monday": [(9, 10)]}
assert add_meeting(schedule, "Monday", 10, 11) == True
assert schedule["Monday"] == [(9, 10), (10, 11)]
def test_add_meeting_with_conflict():
schedule = {"Monda... | [
{
"docstring": "Adds a meeting to the schedule if there is no conflict.\n\nschedule: dictionary with days as keys and meeting time intervals as values\nday: day of the week\nstart: start time of the meeting\nend: end time of the meeting\n\nReturns True if the meeting was added successfully, False if there was a... | [
0,
1,
1,
1,
1,
1,
1,
1,
1,
0
] | 8 | easy | 0.8 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def add_meeting(schedule: dict[str, list[tuple[int, int]]], day: str, start: int, end: int) -> bool:\n \"\"\"\n Adds a meeting to the schedule if there are... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "0000037159",
"row_id": 37159,
"seed_ids": "[438]"
} | 0.663016 | Algorithm_37159 | I | [
"add_meeting",
"remove_meeting",
"check_meeting_conflict"
] | 3 | [
[
"add_meeting",
"check_meeting_conflict"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | d480253b0d0a6fa05f070aa645b78823e6dd18b8 | 14340c9270a4ff1f7e4a8a9d8b56880a71b121cf | |||
v1.0 | instruct | Algorithm | Algorithm_37181_I | ### Problem Statement
You are given a rectangular grid of dimensions `n x m` filled with a mix of 0s and 1s. Your task is to find the largest rectangular sub-grid consisting entirely of 1s. Implement a function `largest_ones_rectangle(grid: List[List[int]]) -> int`. The function should return the area of the largest r... | from typing import List
def largest_histogram_area(heights: List[int]) -> int:
"""
Helper function to find the largest rectangle area in a histogram.
"""
stack = []
max_area = 0
index = 0
while index < len(heights):
if not stack or heights[index] >= heights[stack[-1]]:
... | from solution import largest_ones_rectangle
def test_single_row():
assert largest_ones_rectangle([[1, 0, 1, 1, 1]]) == 3
def test_single_column():
assert largest_ones_rectangle([[1], [1], [0], [1], [1]]) == 2
def test_mixed_grid():
assert largest_ones_rectangle([[1, 0, 1, 0, 0], [1, 0, 1, 1, 1], [1, 1, 1... | [
{
"docstring": "Helper function to find the largest rectangle area in a histogram.",
"function_declaration": "def largest_histogram_area(heights):",
"function_name": "largest_histogram_area",
"parameter_list": "(heights)"
},
{
"docstring": "Finds the largest rectangular sub-grid consisting e... | [
1,
1,
1,
1,
0,
0,
1,
1,
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": "from typing import List\n\ndef largest_histogram_area(heights: List[int]) -> int:\n \"\"\"\n Helper function to find the largest rectangle area in a histog... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "0000037181",
"row_id": 37181,
"seed_ids": "[2327]"
} | 0.728418 | Algorithm_37181 | I | [
"largest_histogram_area",
"largest_ones_rectangle"
] | 2 | [
[
"largest_ones_rectangle",
"largest_histogram_area"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 57f9bb5956c744878a54e01eb729ede305ad82a2 | b2ecb379b64ae6c091622cf5a7386270db82f941 | |||
v1.0 | instruct | Algorithm | Algorithm_37209_I | ### Problem Statement
Implement functions to perform matrix operations for checking if a given matrix is symmetric and computing the power of a symmetric matrix raised to a given integer exponent. These operations are commonly used in various domains like physics, statistics, and engineering for tasks involving symmet... | import numpy as np
def is_symmetric(matrix: np.ndarray) -> bool:
"""
Check if the given matrix is symmetric.
Parameters:
matrix (np.ndarray): A square matrix
Returns:
bool: True if the matrix is symmetric, False otherwise
"""
return np.array_equal(matrix, matrix.T)
def matrix... | from solution import is_symmetric, matrix_power
import numpy as np
def test_is_symmetric_true():
matrix = np.array([
[1, 7, 3],
[7, 4, -5],
[3, -5, 6]
])
assert is_symmetric(matrix) == True
def test_is_symmetric_false():
matrix = np.array([
[1, 0, 3],
[0, 4, -5]... | [
{
"docstring": "Check if the given matrix is symmetric.\n\nParameters:\nmatrix (np.ndarray): A square matrix\n\nReturns:\nbool: True if the matrix is symmetric, False otherwise",
"function_declaration": "def is_symmetric(matrix):",
"function_name": "is_symmetric",
"parameter_list": "(matrix)"
},
... | [
1,
1,
0,
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": "import numpy as np\n\ndef is_symmetric(matrix: np.ndarray) -> bool:\n \"\"\"\n Returns True if the given matrix is symmetric, False otherwise.\n \"\"\"\... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000037209",
"row_id": 37209,
"seed_ids": "[4326]"
} | 0.525267 | Algorithm_37209 | I | [
"is_symmetric",
"matrix_power"
] | 2 | [
[
"matrix_power",
"is_symmetric"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | 70eaf39d1eeaedb74706c45aa10d586f7babdbae | 2adf0303230c2d9895fa7cd17f71ef182fdc9f2f | |||
v1.0 | instruct | Algorithm | Algorithm_37255_I | ### Coding Assessment Question:
#### Context:
Large datasets often need to be processed in parallel to expedite completion times, particularly when the dataset is composed of independent tasks, such as image processing. Python's `multiprocessing` library enables the execution of code across multiple cores.
#### Task... | import os
from PIL import Image
from multiprocessing import Pool
from typing import List, Tuple
def process_image(args):
image_path, output_dir, size = args
try:
with Image.open(image_path) as img:
img = img.resize(size)
img.save(os.path.join(output_dir, os.path.basename(image_p... | import os
import shutil
from PIL import Image
from solution import parallel_image_processing
def test_parallel_image_processing(tmpdir):
# Setup
input_dir = tmpdir.mkdir("input")
output_dir = tmpdir.mkdir("output")
size = (100, 100)
# Create some test images
image_paths = []
for i in range... | [
{
"docstring": null,
"function_declaration": "def process_image(args):",
"function_name": "process_image",
"parameter_list": "(args)"
},
{
"docstring": null,
"function_declaration": "def parallel_image_processing(image_paths, output_dir, size):",
"function_name": "parallel_image_proc... | [
0,
0,
1,
0,
0,
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": "from typing import List, Tuple\nimport os\nfrom PIL import Image\nfrom multiprocessing import Pool\n\ndef process_image(args):\n image_path, output_dir, size ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "0000037255",
"row_id": 37255,
"seed_ids": "[2486]"
} | 0.581566 | Algorithm_37255 | I | [
"process_image",
"parallel_image_processing"
] | 2 | [
[
"parallel_image_processing",
"process_image"
]
] | 1 | [] | false | [] | false | pytest | true | [
"PIL"
] | false | 66c5eee2a373e51196f8371cf8e937eb0200d4ab | 1d4b6ac95267a43a719f4b585640936d21de674e | |||
v1.0 | instruct | Algorithm | Algorithm_37288_I | ### Efficient String Matching Using KMP Algorithm
You are required to implement the Knuth-Morris-Pratt (KMP) string matching algorithm. The KMP algorithm searches for occurrences of a "pattern" string within a "text" string efficiently by avoiding redundant comparisons.
#### Function Specifications:
1. Implement the f... | from typing import List
def computeLPSArray(pattern: str) -> List[int]:
"""Computes the Longest Prefix Suffix (LPS) array for the given pattern."""
length = 0 # Length of the previous longest prefix suffix
lps = [0] * len(pattern)
i = 1
while i < len(pattern):
if pattern[i] == pattern... | from solution import computeLPSArray, KMPSearch
def test_computeLPSArray_basic():
assert computeLPSArray("ababc") == [0, 0, 1, 2, 0]
assert computeLPSArray("aaaa") == [0, 1, 2, 3]
def test_computeLPSArray_edge_cases():
assert computeLPSArray("") == []
assert computeLPSArray("a") == [0]
assert comp... | [
{
"docstring": "Computes the Longest Prefix Suffix (LPS) array for the given pattern.",
"function_declaration": "def computeLPSArray(pattern):",
"function_name": "computeLPSArray",
"parameter_list": "(pattern)"
},
{
"docstring": "Searches for occurrences of the pattern string within the text... | [
1,
0,
0,
0,
0,
0,
1,
1,
0,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef computeLPSArray(pattern: str) -> List[int]:\n \"\"\"Computes the Longest Prefix Suffix (LPS) array for the given pattern.\"\"\"... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "0000037288",
"row_id": 37288,
"seed_ids": "[4735]"
} | 0.628054 | Algorithm_37288 | I | [
"computeLPSArray",
"KMPSearch"
] | 2 | [
[
"KMPSearch",
"computeLPSArray"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 6d6d710dcac57bf15623205f00a65e370596e507 | 10b205797bee84ae29cbaafa1d9d6b933ac18f4b | |||
v1.0 | instruct | Algorithm | Algorithm_37294_I | ### Celebrity Identification
You are tasked with creating an algorithm to identify a celebrity in a party scenario. A celebrity is someone who is known by everyone but knows no one at the party.
You need to implement the following functions:
1. `knows(a: int, b: int) -> bool`: This is a helper function provided to y... | # Helper function provided
def knows(a: int, b: int, party) -> bool:
"""
This function is provided to indicate if person `a` knows person `b`.
The `party` parameter is a 2D array (adjacency matrix) indicating who knows whom.
"""
return party[a][b]
def find_celebrity(n: int, party) -> int:
"""
... | def test_find_celebrity_example_party():
party = [
[False, True, False],
[False, False, False],
[True, True, False]
]
assert find_celebrity(3, party) == 1
def test_no_celebrity():
party = [
[False, False],
[False, False]
]
assert find_celebrity(2, party) ... | [
{
"docstring": "This function is provided to indicate if person `a` knows person `b`.\nThe `party` parameter is a 2D array (adjacency matrix) indicating who knows whom.",
"function_declaration": "def knows(a, b, party):",
"function_name": "knows",
"parameter_list": "(a, b, party)"
},
{
"docs... | [
1,
0,
0,
0,
1,
0,
0,
0,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def knows(a: int, b: int, party) -> bool:\n \"\"\"\n This function is a mock of the actual 'knows' function.\n It checks if person a knows person b base... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "0000037294",
"row_id": 37294,
"seed_ids": "[4951]"
} | 0.520864 | Algorithm_37294 | I | [
"knows",
"find_celebrity"
] | 2 | [
[
"find_celebrity",
"knows"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 2b9004be364653deb27f3c6fb269dee9bfb43a9e | 15dfd3230fe9de849d8f62b0e823a7e3f361fd25 | |||
v1.0 | instruct | Algorithm | Algorithm_37298_I | ### Problem Statement
You are given a task to process and analyze time-series data. The data is provided as a Pandas DataFrame, where each column represents a different feature over time. You need to implement a function that performs a specified set of preprocessing steps and feature extraction techniques on the inpu... | import pandas as pd
def normalize(df):
return (df - df.mean()) / df.std()
def process_time_series(data: pd.DataFrame, window_size: int, num_lags: int) -> pd.DataFrame:
if data.empty:
return pd.DataFrame()
# Step 1: Normalization
normalized_data = normalize(data)
# Step 2: Rolling Win... | import pandas as pd
from solution import process_time_series
def test_process_time_series_basic():
data = pd.DataFrame({
'feature1': [1, 2, 3, 4, 5],
'feature2': [5, 4, 3, 2, 1]
})
result = process_time_series(data, window_size=2, num_lags=1)
assert 'feature1_normalized' in result.... | [
{
"docstring": null,
"function_declaration": "def normalize(df):",
"function_name": "normalize",
"parameter_list": "(df)"
},
{
"docstring": null,
"function_declaration": "def process_time_series(data, window_size, num_lags):",
"function_name": "process_time_series",
"parameter_li... | [
0,
1,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.125 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import pandas as pd\n\ndef process_time_series(data: pd.DataFrame, window_size: int, num_lags: int) -> pd.DataFrame:\n \"\"\"\n Normalize the data, apply r... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "0000037298",
"row_id": 37298,
"seed_ids": "[676]"
} | 0.668351 | Algorithm_37298 | I | [
"normalize",
"process_time_series"
] | 2 | [
[
"process_time_series",
"normalize"
]
] | 1 | [] | false | [] | false | pytest | true | [
"pandas"
] | false | 805329ba21ff038ac8447d7de290c90bcad14086 | af4790aac570a131f43b7c6e38708bd32ed9713d | |||
v1.0 | instruct | Algorithm | Algorithm_37457_I | ### Problem Statement
#### Context:
You have been assigned the task of creating a program that can transform a given sentence into a simple cipher text by shifting each letter by a fixed number of positions in the alphabet.
#### Instructions:
1. **Modify the `caesar_cipher` function**:
- This function should take ... | def caesar_cipher(sentence: str, shift: int) -> str:
def shift_char(c, shift):
if c.isalpha():
start = ord('A') if c.isupper() else ord('a')
return chr((ord(c) - start + shift) % 26 + start)
return c
return ''.join(shift_char(c, shift) for c in sentence)
def caesar_... | from solution import caesar_cipher, caesar_decipher
def test_caesar_cipher():
# Test cases from the problem statement
assert caesar_cipher("hello world", 3) == 'khoor zruog'
assert caesar_cipher("abc xyz", 2) == 'cde zab'
assert caesar_cipher("Hello, World!", 5) == 'Mjqqt, Btwqi!'
# Additional... | [
{
"docstring": null,
"function_declaration": "def caesar_cipher(sentence, shift):",
"function_name": "caesar_cipher",
"parameter_list": "(sentence, shift)"
},
{
"docstring": null,
"function_declaration": "def caesar_decipher(cipher_text, shift):",
"function_name": "caesar_decipher",
... | [
1,
1,
0,
0,
1,
1,
0,
1,
1,
1
] | 7 | easy | 0.7 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def caesar_cipher(sentence: str, shift: int) -> str:\n def shift_char(c, shift):\n if 'a' <= c <= 'z':\n return chr((ord(c) - ord('a') + shi... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000037457",
"row_id": 37457,
"seed_ids": "[4105]"
} | 0.735369 | Algorithm_37457 | I | [
"caesar_cipher",
"caesar_decipher"
] | 2 | [
[
"caesar_decipher",
"caesar_cipher"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c37baf53ce5e94547b03a5a08a11685f2b904930 | 5148e6ffbfeaff9378dad3ba9d82491ad8166df6 | |||
v1.0 | instruct | Algorithm | Algorithm_37458_I | ### Problem Statement
You are required to implement a function that solves a common problem in competitive programming: finding the k-th smallest element in an unsorted list. Your solution should demonstrate good understanding of selection algorithms and efficient handling of large data sets.
### K-th Smallest Element... | import random
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):
... | from solution import kth_smallest_element
def test_kth_smallest_element_example1():
data = [7, 10, 4, 3, 20, 15]
k = 3
assert kth_smallest_element(data, k) == 7
def test_kth_smallest_element_example2():
data = [7, 10, 4, 3, 20, 15]
k = 4
assert kth_smallest_element(data, k) == 10
def test_kth... | [
{
"docstring": null,
"function_declaration": "def partition(arr, low, high):",
"function_name": "partition",
"parameter_list": "(arr, low, high)"
},
{
"docstring": null,
"function_declaration": "def quickselect(arr, low, high, k):",
"function_name": "quickselect",
"parameter_list... | [
1,
1,
1,
0,
0,
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": "import random\n\ndef partition(arr, low, high):\n pivot = arr[high]\n i = low - 1\n \n for j in range(low, high):\n if arr[j] <= pivot:\n ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000037458",
"row_id": 37458,
"seed_ids": "[4982]"
} | 0.674151 | Algorithm_37458 | I | [
"partition",
"quickselect",
"kth_smallest_element"
] | 3 | [
[
"kth_smallest_element",
"quickselect"
],
[
"quickselect",
"partition"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 8096b79fe7c647c240ab6ae2e24ae874ebfa9db3 | c6b35b86c58b1a2e977999fbc8469d902f5a6d5a | |||
v1.0 | instruct | Algorithm | Algorithm_37459_I | ### Question: Implement a Modified K-Means Clustering Algorithm
**Context**:
The K-Means clustering algorithm is used to partition a dataset into K distinct, non-overlapping subsets (clusters). This problem introduces a modification of K-Means where instead of specifying the number of clusters (K) beforehand, the algo... | import numpy as np
from typing import Tuple, List
def euclidean_distance(point1: np.ndarray, point2: np.ndarray) -> float:
return np.linalg.norm(point1 - point2)
def dynamic_k_means(
data_points: np.ndarray,
distance_threshold: float,
max_iterations: int = 100,
) -> Tuple[int, List[np.ndarray], np.nda... | import numpy as np
from solution import dynamic_k_means
def test_kmeans_basic():
data_points = np.array([[1.0, 2.0], [1.5, 1.8], [5.0, 8.0], [8.0, 8.0], [1.0, 0.6], [9.0, 11.0]])
distance_threshold = 3.0
num_clusters, clusters, centroids = dynamic_k_means(data_points, distance_threshold)
assert num_clu... | [
{
"docstring": null,
"function_declaration": "def euclidean_distance(point1, point2):",
"function_name": "euclidean_distance",
"parameter_list": "(point1, point2)"
},
{
"docstring": null,
"function_declaration": "def dynamic_k_means(data_points, distance_threshold, max_iterations=100):",... | [
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": "import numpy as np\nfrom typing import Tuple, List\n\ndef dynamic_k_means(\n data_points: np.ndarray,\n distance_threshold: float,\n max_iterations: int... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "0000037459",
"row_id": 37459,
"seed_ids": "[4330]"
} | 0.727518 | Algorithm_37459 | I | [
"euclidean_distance",
"dynamic_k_means"
] | 2 | [
[
"dynamic_k_means",
"euclidean_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | b64fdf9c26792f9087bd52cc3bc44c86db8594fb | 7c9af9887ea9f7f0ec51160cdff1f15a0635be13 | |||
v1.0 | instruct | Algorithm | Algorithm_37467_I | ### Context
You participated in a coding challenge where you encountered a problem involving prime factorization. The task evaluates your ability to implement efficient algorithms to determine the prime factors of a given number and perform arithmetic operations on these factors.
### Problem Statement
Write a Python f... | import math
def lcm(a, b):
"""
Returns the least common multiple of a and b.
"""
return abs(a*b) // math.gcd(a, b)
def smallest_multiple(n: int) -> int:
"""
Returns the smallest positive number that is evenly divisible by all numbers from 1 to n.
"""
smallest_mult = 1
for i in rang... | from solution import smallest_multiple
def test_smallest_multiple():
assert smallest_multiple(1) == 1
assert smallest_multiple(2) == 2
assert smallest_multiple(3) == 6
assert smallest_multiple(4) == 12
assert smallest_multiple(5) == 60
assert smallest_multiple(6) == 60
assert smallest_multi... | [
{
"docstring": "Returns the least common multiple of a and b.",
"function_declaration": "def lcm(a, b):",
"function_name": "lcm",
"parameter_list": "(a, b)"
},
{
"docstring": "Returns the smallest positive number that is evenly divisible by all numbers from 1 to n.",
"function_declaratio... | [
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 math import gcd\n\ndef lcm(a, b):\n \"\"\"\n Compute the Least Common Multiple of a and b\n \"\"\"\n return a * b // gcd(a, b)\n\ndef smallest_m... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000037467",
"row_id": 37467,
"seed_ids": "[2607]"
} | 0.746411 | Algorithm_37467 | I | [
"lcm",
"smallest_multiple"
] | 2 | [
[
"smallest_multiple",
"lcm"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | e35bdfac75f690c94b48319414d4cf113da74e7d | b9815e98a6bd6df10dbed681308c63170d305ee4 | |||
v1.0 | instruct | Algorithm | Algorithm_37539_I | ### Problem Statement
You are tasked with developing a feature for a fitness tracking application that monitors the user's running activity. The application needs to analyze the runner's data and provide insights and milestones based on their pace.
### Requirements
You are to implement three functions `calculate_spe... | def calculate_speed(distance_run, total_time):
"""
Calculate the average speed given a distance and total time.
Args:
distance_run: float : Distance run in kilometers.
total_time: float : Total time in minutes.
Returns:
float : Average speed in kilometers per hour.
"""
retu... | def test_calculate_speed():
assert calculate_speed(5, 25) == 12.0
assert calculate_speed(10, 60) == 10.0
assert calculate_speed(2.5, 30) == 5.0
assert calculate_speed(7, 35) == 12.0
def test_pace_analysis():
assert pace_analysis(5.0) == 'Slow pace'
assert pace_analysis(10.0) == 'Moderate pace'
... | [
{
"docstring": "Calculate the average speed given a distance and total time.\n\nArgs:\ndistance_run: float : Distance run in kilometers.\ntotal_time: float : Total time in minutes.\n\nReturns:\nfloat : Average speed in kilometers per hour.",
"function_declaration": "def calculate_speed(distance_run, total_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 calculate_speed(distance_run: float, total_time: float) -> float:\n \"\"\"\n Calculate the average speed in km/h.\n \n Arguments:\n distance_r... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000037539",
"row_id": 37539,
"seed_ids": "[640]"
} | 0.611909 | Algorithm_37539 | I | [
"calculate_speed",
"pace_analysis",
"running_summary",
"runner_insights"
] | 4 | [
[
"runner_insights",
"calculate_speed"
],
[
"runner_insights",
"pace_analysis"
],
[
"runner_insights",
"running_summary"
]
] | 3 | [] | false | [] | false | pytest | false | [] | true | 8ad768aaff9f063ec5a47d86be7ae49a3509e99f | 8f5d2561cc49647e683c025b3bef00e6c7f04645 | |||
v1.0 | instruct | Algorithm | Algorithm_37557_I | ### Question
**You are tasked to implement a feature for binary search trees (BSTs) that verifies if they can be transformed into complete binary search trees with a given number of rotations.**
### Objective
Your task is to write a function `can_be_complete_bst` that determines whether it's possible to convert a give... | class Node:
def __init__(self, key):
self.left = None
self.right = None
self.val = key
def is_complete_bst(root, index, number_of_nodes):
# Base case: An empty tree is complete
if root is None:
return True
# If index assigned to current node is greater than the numb... | def test_single_node_tree():
root = Node(1)
assert can_be_complete_bst(root, 0) == True
def test_already_complete_bst():
root = Node(10)
root.left = Node(5)
root.right = Node(15)
root.left.left = Node(3)
root.left.right = Node(7)
root.right.left = Node(12)
root.right.right = Node(18... | [] | [
1,
0,
0,
0,
0,
0,
0,
0,
0,
1
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "class Node:\n def __init__(self, key):\n self.left = None\n self.right = None\n self.val = key\n\ndef is_complete_bst(root, index, number... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "0000037557",
"row_id": 37557,
"seed_ids": "[1567]"
} | 0.576835 | Algorithm_37557 | I | [
"is_complete_bst",
"count_nodes",
"can_be_complete_bst"
] | 3 | [
[
"can_be_complete_bst",
"count_nodes"
],
[
"can_be_complete_bst",
"is_complete_bst"
]
] | 2 | [] | false | [
"Node"
] | true | pytest | false | [] | true | b314f077273c757b31a4ce861a43e848dbc72751 | 3ca97ff136f8f52a27024a611edc8784edb418c1 | |||
v1.0 | instruct | Algorithm | Algorithm_37575_I | ### Question: Improved Merge Sort for Large Datasets
#### Context
You are tasked with optimizing the classic merge sort algorithm for large datasets. The traditional merge sort has a time complexity of O(n log n), but in practice, dealing with very large arrays (e.g., millions of elements) can still be computationally... | def optimized_merge_sort(arr):
# Validate the input
if not isinstance(arr, list) or not all(isinstance(x, int) for x in arr):
raise ValueError("Input must be a list of integers")
# If the list is empty or has only one element, return it as it is already sorted
if len(arr) <= 1:
... | from solution import optimized_merge_sort
def test_optimized_merge_sort_empty():
assert optimized_merge_sort([]) == []
def test_optimized_merge_sort_single_element():
assert optimized_merge_sort([1]) == [1]
def test_optimized_merge_sort_sorted():
assert optimized_merge_sort([1, 2, 3, 4, 5]) == [1, 2, 3, ... | [
{
"docstring": null,
"function_declaration": "def optimized_merge_sort(arr):",
"function_name": "optimized_merge_sort",
"parameter_list": "(arr)"
},
{
"docstring": null,
"function_declaration": "def merge(left, right):",
"function_name": "merge",
"parameter_list": "(left, right)"... | [
1,
1,
0,
1,
0,
1,
1,
0,
0,
1
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def optimized_merge_sort(arr):\n if not isinstance(arr, list):\n raise ValueError(\"Input must be a list of integers\")\n if not all(isinstance(x, i... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "0000037575",
"row_id": 37575,
"seed_ids": "[3203]"
} | 0.565566 | Algorithm_37575 | I | [
"optimized_merge_sort",
"merge"
] | 2 | [
[
"optimized_merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a749a6686d24203f097c55b3c1269f18af2862dc | 9e5422b73c8aefaf6bb24b38da064649e739a16b | |||
v1.0 | instruct | Algorithm | Algorithm_37581_I | ### Question: Data Compression Decompressor
#### Objective:
As part of a data storage solution, you need to implement a data decompressor for a simplified run-length encoding (RLE) scheme. The RLE compression encodes sequences of the same character by storing the character followed by the count of repetitions.
#### P... | def decompress(encoded: str) -> str:
"""
Decompress a run-length encoded string.
Parameters:
encoded (str): The RLE-encoded string.
Returns:
str: The original decompressed string.
"""
if not is_valid_rle_format(encoded):
return ""
decoded = []
i = 0
while ... | def test_decompress():
assert decompress("a5b3c2") == 'aaaaabbbcc'
assert decompress("A1B2C3") == 'ABBCCC'
assert decompress("") == ''
assert decompress("z9") == 'zzzzzzzzz'
# Test invalid RLE formats
assert decompress("a5b") == ''
assert decompress("a!") == ''
assert decompress("a5b-2"... | [
{
"docstring": "Decompress a run-length encoded string.\n\nParameters:\nencoded (str): The RLE-encoded string.\n\nReturns:\nstr: The original decompressed string.",
"function_declaration": "def decompress(encoded):",
"function_name": "decompress",
"parameter_list": "(encoded)"
},
{
"docstrin... | [
1,
0,
0,
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": "def decompress(encoded: str) -> str:\n \"\"\"\n Decompress a run-length encoded string.\n \n Parameters:\n encoded (str): The RLE-encoded string.\... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "0000037581",
"row_id": 37581,
"seed_ids": "[5046]"
} | 0.640122 | Algorithm_37581 | I | [
"decompress",
"is_valid_rle_format"
] | 2 | [
[
"decompress",
"is_valid_rle_format"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 19b45c3117b752a3412408c69177561a6d10fb6b | 805d8e916537e6dfa32b9f9996cb539a9237b2a5 | |||
v1.0 | instruct | Algorithm | Algorithm_37583_I | ### Route Finder in a Directed Graph
#### Context
You are tasked with developing a route-finding functionality in a directed graph where nodes represent cities and edges represent one-way roads between these cities. Your objective is to determine if there is a path from a starting city to a destination city using Dept... | def dfs(graph, current, end, visited):
if current == end:
return True
visited.add(current)
for neighbor in graph.get(current, []):
if neighbor not in visited:
if dfs(graph, neighbor, end, visited):
return True
return False
def is_path_exist(graph, start, end)... | def test_path_exists_simple():
graph = {
"A": ["B", "C"],
"B": ["D"],
"C": ["E"],
"D": ["C"],
"E": ["D"]
}
assert is_path_exist(graph, "A", "E") == True
def test_path_not_exists():
graph = {
"A": ["B", "D"],
"B": ["C"],
"C": ["D"],
... | [
{
"docstring": null,
"function_declaration": "def dfs(graph, current, end, visited):",
"function_name": "dfs",
"parameter_list": "(graph, current, end, visited)"
},
{
"docstring": "Determines if there is a path from start city to end city using DFS.\n\nParameters:\n graph (dict): Dictiona... | [
1,
0,
0,
1,
1,
1,
0,
1,
0,
0
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def is_path_exist(graph, start, end):\n \"\"\"\n Returns True if there is a path from start to end in the graph, else False.\n Uses Depth-First Search a... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "0000037583",
"row_id": 37583,
"seed_ids": "[1148]"
} | 0.626773 | Algorithm_37583 | I | [
"dfs",
"is_path_exist"
] | 2 | [
[
"is_path_exist",
"dfs"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 649f96e47e41f4d3c8ffa7b9011c30bb4b3c74d6 | c2403c609bd14a5d50548f332da8e2f924b279ae | |||
v1.0 | instruct | Algorithm | Algorithm_37585_I | ### Coding Assessment Question
#### Context
You are developing a customer information management system for an e-commerce platform. One of the key features is recording and verifying email addresses to ensure they are in a valid format and associated with known domains.
### Objective
Implement the required functions ... | KNOWN_DOMAINS = ["gmail.com", "yahoo.com", "outlook.com"]
def parse_email(input_str):
"""
Extracts the username and domain from an email address.
"""
input_str = input_str.strip()
if "@" not in input_str:
raise ValueError("Invalid email format: missing '@'")
username, domain = inpu... | from solution import parse_email, validate_email, normalize_email
def test_parse_email_valid():
assert parse_email("username@gmail.com") == ("username", "gmail.com")
assert parse_email("user.name@domain.co.uk") == ("user.name", "domain.co.uk")
assert parse_email(" user.name@domain.co.uk ") == ("user.name",... | [
{
"docstring": "Extracts the username and domain from an email address.",
"function_declaration": "def parse_email(input_str):",
"function_name": "parse_email",
"parameter_list": "(input_str)"
},
{
"docstring": "Validates the email address format and checks if the domain is known.",
"fun... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 10 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "KNOWN_DOMAINS = [\"gmail.com\", \"yahoo.com\", \"outlook.com\"]\n\ndef parse_email(input_str):\n \"\"\"\n Extract the username and domain from a given emai... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000037585",
"row_id": 37585,
"seed_ids": "[1516]"
} | 0.584902 | Algorithm_37585 | I | [
"parse_email",
"validate_email",
"normalize_email"
] | 3 | [
[
"normalize_email",
"parse_email"
],
[
"validate_email",
"parse_email"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | c99311838752344f4c3b2c89ecafd53b1af6da94 | 8e7e4992496f046d0f5a2341378cd317e785e8ee | |||
v1.0 | instruct | Algorithm | Algorithm_37650_I | ### Context
In the realm of computational geometry, it's important to understand fundamental geometric algorithms. One such algorithm is the Convex Hull algorithm which finds the smallest convex polygon that can contain a set of points on a plane.
### Task
Your task is to implement the Convex Hull algorithm using th... | from typing import List, Tuple
def graham_scan(points: List[Tuple[int, int]]) -> List[Tuple[int, int]]:
# Step 1: Find the point with the lowest y-coordinate (pivot point)
pivot = min(points, key=lambda p: (p[1], p[0]))
# Step 2: Sort points based on the polar angle with pivot
def polar_angle(p):
... | from solution import graham_scan
def test_graham_scan_general_case():
points = [(0,0), (1,1), (2,2), (2,0), (1,2)]
assert graham_scan(points) == [(0, 0), (2, 0), (2, 2), (1, 2)]
def test_graham_scan_multiple_collinear_points():
points = [(0,0), (1,1), (2,2), (3,3), (4,4), (2,0)]
assert graham_scan(poi... | [
{
"docstring": null,
"function_declaration": "def graham_scan(points):",
"function_name": "graham_scan",
"parameter_list": "(points)"
},
{
"docstring": null,
"function_declaration": "def cross_product(o, a, b):",
"function_name": "cross_product",
"parameter_list": "(o, a, b)"
}... | [
0,
0,
0,
1,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List, Tuple\n\ndef graham_scan(points: List[Tuple[int, int]]) -> List[Tuple[int, int]]:\n \"\"\"\n Computes the convex hull of a set of ... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "0000037650",
"row_id": 37650,
"seed_ids": "[449]"
} | 0.536742 | Algorithm_37650 | I | [
"graham_scan",
"cross_product"
] | 2 | [
[
"graham_scan",
"cross_product"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 1114a8bedb166156a9d7c5b98222565d97a5078a | 8b736416afe8c2312aa2fec763ec77b86bf86431 | |||
v1.0 | instruct | Algorithm | Algorithm_37656_I | ### Challenging Coding Assessment Question
#### Context
String manipulation and text processing are essential skills in programming, with applications ranging from data munging to user interface development. One frequent operation is to analyze strings for repeated patterns and substrings.
#### Task
Implement a fun... | def build_suffix_array(s):
suffixes = [(s[i:], i) for i in range(len(s))]
suffixes.sort()
suffix_array = [suffix[1] for suffix in suffixes]
return suffix_array
def build_lcp_array(s, suffix_array):
n = len(s)
rank = [0] * n
for i, suffix in enumerate(suffix_array):
rank[suffix] = i
... | from solution import longest_repeated_substring
def test_basic_cases():
assert longest_repeated_substring("banana") == "ana"
assert longest_repeated_substring("abcdabc") == "abc"
assert longest_repeated_substring("abcdef") == ""
assert longest_repeated_substring("abababab") == "ababab"
def test_edge_c... | [
{
"docstring": null,
"function_declaration": "def build_suffix_array(s):",
"function_name": "build_suffix_array",
"parameter_list": "(s)"
},
{
"docstring": null,
"function_declaration": "def build_lcp_array(s, suffix_array):",
"function_name": "build_lcp_array",
"parameter_list":... | [
1,
0,
0,
1,
1,
1,
0,
0,
1,
1
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def longest_repeated_substring(s: str) -> str:\n \"\"\"\n Identifies and returns the longest substring that appears at least twice\n in the input string... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000037656",
"row_id": 37656,
"seed_ids": "[2816]"
} | 0.743515 | Algorithm_37656 | I | [
"build_suffix_array",
"build_lcp_array",
"longest_repeated_substring"
] | 3 | [
[
"longest_repeated_substring",
"build_lcp_array"
],
[
"longest_repeated_substring",
"build_suffix_array"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | b0ad0f14240b088464a92ffc93a2ddd928c6ef57 | 988032c4cdfd3574033055d375f16d746665a2f6 | |||
v1.0 | instruct | Algorithm | Algorithm_37666_I | ### Restaurant Order System
**Scenario**:
As a software developer for a restaurant, you have been given the task to create a system for managing and validating customer orders. Each order in the system is represented by a unique identifier and a list of items included in the order. Your task is to implement functional... | import re
def generate_valid_order(order_id: str, items: list) -> dict:
# Ensure order ID follows the correct pattern
if not re.match(r'^ORD\d{5}$', order_id):
# Pad with zeros if necessary
order_id = f"ORD{int(order_id[3:]):05d}" if order_id.startswith("ORD") else f"ORD{int(order_id):05d}"
... | from solution import generate_valid_order, correct_order
def test_generate_valid_order_with_correct_id_and_items():
assert generate_valid_order("ORD67890", ["pizza", "burger", "coke", "fries"]) == {
'order_id': 'ORD67890',
'items': ["pizza", "burger", "coke", "fries"]
}
def test_generate_valid... | [
{
"docstring": null,
"function_declaration": "def generate_valid_order(order_id, items):",
"function_name": "generate_valid_order",
"parameter_list": "(order_id, items)"
},
{
"docstring": null,
"function_declaration": "def correct_order(order):",
"function_name": "correct_order",
... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 10 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import re\n\ndef generate_valid_order(order_id: str, items: list) -> dict:\n \"\"\"\n Generates a valid order. Corrects order_id if needed and limits the n... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000037666",
"row_id": 37666,
"seed_ids": "[1160]"
} | 0.52953 | Algorithm_37666 | I | [
"generate_valid_order",
"correct_order"
] | 2 | [
[
"correct_order",
"generate_valid_order"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 40a2352600da0693614bc95c20f5dedca46885d4 | cc2f1d8ae9e2433a43d281900b1bdcec79b4fb90 | |||
v1.0 | instruct | Algorithm | Algorithm_37674_I | ### Question
**Problem Statement**:
You are provided with a basic implementation of a frequency counter for words in a string. However, the task for you is to extend this functionality to identify the k most frequent words from a text.
**Objective**:
1. Write a function called `count_word_frequencies(text: str) -> ... | from collections import Counter
import string
def count_word_frequencies(text: str) -> dict:
"""
Returns a dictionary where keys are words and values are their respective frequencies.
Words are case-insensitive, and punctuation is ignored.
"""
# Remove punctuation and make the text lowercase
tr... | def test_count_word_frequencies():
result = count_word_frequencies("Hello, hello! How are you? You are welcome.")
expected = {'hello': 2, 'how': 1, 'are': 2, 'you': 2, 'welcome': 1}
assert result == expected
def test_count_word_frequencies_mixed_case():
result = count_word_frequencies("Apple apple bana... | [
{
"docstring": "Returns a dictionary where keys are words and values are their respective frequencies.\nWords are case-insensitive, and punctuation is ignored.",
"function_declaration": "def count_word_frequencies(text):",
"function_name": "count_word_frequencies",
"parameter_list": "(text)"
},
... | [
1,
0,
1,
1,
1,
1,
0,
1,
1,
1
] | 8 | easy | 0.8 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from collections import Counter\nimport re\n\ndef count_word_frequencies(text: str) -> dict:\n \"\"\"\n Count the frequency of each word in the given text.... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000037674",
"row_id": 37674,
"seed_ids": "[4163]"
} | 0.760521 | Algorithm_37674 | I | [
"count_word_frequencies",
"k_most_frequent_words"
] | 2 | [
[
"k_most_frequent_words",
"count_word_frequencies"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 7fee52fe6c2daf571ef99b8536c58d777f4a4b12 | 4f73f67fb160ebe2371cab9ffe4e31e82fa85450 | |||
v1.0 | instruct | Algorithm | Algorithm_37676_I | ### Password Strength Checker
Create a password strength checker that assesses the strength of a given password based on multiple criteria. Your implementation should include functions to validate different aspects of a password and a final function to bring all checks together and print informative error messages if ... | def has_min_length(password: str) -> bool:
return len(password) >= 8
def has_uppercase(password: str) -> bool:
return any(char.isupper() for char in password)
def has_digit(password: str) -> bool:
return any(char.isdigit() for char in password)
def has_special_char(password: str) -> bool:
return any(... | from solution import has_min_length, has_uppercase, has_digit, has_special_char, password_strength_checker
def test_has_min_length():
assert has_min_length("abcdefgh") == True
assert has_min_length("abc") == False
def test_has_uppercase():
assert has_uppercase("Abcdefgh") == True
assert has_uppercase(... | [
{
"docstring": null,
"function_declaration": "def has_min_length(password):",
"function_name": "has_min_length",
"parameter_list": "(password)"
},
{
"docstring": null,
"function_declaration": "def has_uppercase(password):",
"function_name": "has_uppercase",
"parameter_list": "(pa... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 10 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def has_min_length(password: str) -> bool:\n \"\"\"Checks if the password is at least 8 characters long.\"\"\"\n return len(password) >= 8\n\ndef has_upper... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "0000037676",
"row_id": 37676,
"seed_ids": "[1172]"
} | 0.632453 | Algorithm_37676 | I | [
"has_min_length",
"has_uppercase",
"has_digit",
"has_special_char",
"password_strength_checker"
] | 5 | [
[
"password_strength_checker",
"has_digit"
],
[
"password_strength_checker",
"has_min_length"
],
[
"password_strength_checker",
"has_special_char"
],
[
"password_strength_checker",
"has_uppercase"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | 81937d2f47b902fff5304bdd48be8199c6b3de2d | 5ac233ba614e3459a61b16a430afa962b04485e3 | |||
v1.0 | instruct | Algorithm | Algorithm_37715_I | ### Question: Implement a Parallelized K-Means Clustering Algorithm
You are tasked with writing a function to implement a parallelized version of the K-Means Clustering algorithm. This exercise will test your understanding of clustering algorithms, parallel computing, and optimization techniques for performance improv... | import numpy as np
import threading
from multiprocessing import Pool
def initialize_centroids(data, k):
indices = np.random.choice(data.shape[0], k, replace=False)
return data[indices]
def assign_clusters(data, centroids):
distances = np.linalg.norm(data[:, np.newaxis] - centroids, axis=2)
return np.a... | import numpy as np
from solution import parallelized_k_means
def test_parallelized_k_means_basic():
data = np.array([[1.0, 2.0], [1.5, 1.8], [5.0, 8.0], [8.0, 8.0], [1.0, 0.6], [9.0, 11.0]])
centroids, labels = parallelized_k_means(data, k=2, max_iterations=100, tolerance=0.01)
assert len(centroids) == 2
... | [
{
"docstring": null,
"function_declaration": "def initialize_centroids(data, k):",
"function_name": "initialize_centroids",
"parameter_list": "(data, k)"
},
{
"docstring": null,
"function_declaration": "def assign_clusters(data, centroids):",
"function_name": "assign_clusters",
"... | [
0,
0,
0,
0,
0,
1,
1,
0,
1,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import numpy as np\nimport multiprocessing as mp\n\ndef initialize_centroids(data, k):\n \"\"\" Randomly initialize the centroids \"\"\"\n indices = np.ran... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "0000037715",
"row_id": 37715,
"seed_ids": "[4706]"
} | 0.747622 | Algorithm_37715 | I | [
"initialize_centroids",
"assign_clusters",
"update_centroids",
"parallelized_k_means"
] | 4 | [
[
"parallelized_k_means",
"assign_clusters"
],
[
"parallelized_k_means",
"initialize_centroids"
],
[
"parallelized_k_means",
"update_centroids"
]
] | 3 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | b0d8cbc1799ef0c757fbae4f24b0764a7e079c7f | 77b84b92e96f79b1fa960410a0e1f9dc2869d95b | |||
v1.0 | instruct | Algorithm | Algorithm_37736_I | ### Problem Statement
You are tasked with developing a function that determines the minimum number of steps required to convert a given binary indexed tree into a balanced binary indexed tree. A binary indexed tree is used in various algorithm problems to query and update elements of an array efficiently. A balanced b... | import math
from typing import List, Tuple
def height_of_tree(n: int) -> int:
if n == 0:
return 0
return math.ceil(math.log2(n + 1))
def is_balanced(height: int, low: int, high: int) -> bool:
return height >= low and height <= high
def minimum_steps_to_balance(bitr: List[int], action: int) -> Tup... | from solution import minimum_steps_to_balance
def test_minimum_steps_to_balance():
assert minimum_steps_to_balance([10, 12, 8, 15, 6, 9], 1) == (1, 6)
assert minimum_steps_to_balance([10, 12, 8, 15, 6, 9], -1) == (1, 5)
assert minimum_steps_to_balance([10, 12, 8, 15, 6], 0) == (0, -1)
assert minimum_st... | [
{
"docstring": null,
"function_declaration": "def height_of_tree(n):",
"function_name": "height_of_tree",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def is_balanced(height, low, high):",
"function_name": "is_balanced",
"parameter_list": "(height, low... | [
0,
0,
0,
0,
1,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List, Tuple\n\ndef minimum_steps_to_balance(bitr: List[int], action: int) -> Tuple[int, int]:\n def height(node_index: int) -> int:\n ... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "0000037736",
"row_id": 37736,
"seed_ids": "[2976]"
} | 0.683285 | Algorithm_37736 | I | [
"height_of_tree",
"is_balanced",
"minimum_steps_to_balance"
] | 3 | [
[
"minimum_steps_to_balance",
"height_of_tree"
],
[
"minimum_steps_to_balance",
"is_balanced"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 367c154dbff70a1a37a1be2929e1049b6ecf1059 | abba0349f5f38bc60953f91e7341953e83f85b8d | |||
v1.0 | instruct | Algorithm | Algorithm_37741_I | ### Context
Sorting algorithms are fundamental in computer science, with various methods available to sort an array effectively. Merge Sort is a popular, efficient, and stable algorithm known for its divide-and-conquer approach and consistent performance across different types of input arrays.
### Task
You are require... | def merge_sort(arr):
"""
Sorts an array of integers using the Merge Sort algorithm.
Args:
arr: A list of integers to be sorted.
Returns:
A new list of integers sorted in non-decreasing order.
"""
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left_half = merg... | from solution import merge_sort
def test_merge_sort_empty_array():
assert merge_sort([]) == []
def test_merge_sort_single_element():
assert merge_sort([5]) == [5]
def test_merge_sort_multiple_elements():
assert merge_sort([3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]) == [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]
def test_m... | [
{
"docstring": "Sorts an array of integers using the Merge Sort algorithm.\n\nArgs:\n arr: A list of integers to be sorted.\n\nReturns:\n A new list of integers sorted in non-decreasing order.",
"function_declaration": "def merge_sort(arr):",
"function_name": "merge_sort",
"parameter_list": "(... | [
1,
1,
1,
0,
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 merge_sort(arr):\n \"\"\"\n Sorts an array of integers using the Merge Sort algorithm.\n\n Args:\n arr: A list of integers to be sorted.\n\n ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000037741",
"row_id": 37741,
"seed_ids": "[3204]"
} | 0.706853 | Algorithm_37741 | I | [
"merge_sort",
"merge"
] | 2 | [
[
"merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c6277191970ad94c4d34b918769f3aa02fbe22b4 | 7c360f2bdb0ce6c39f1f3d1724d39bdbe47b7eef | |||
v1.0 | instruct | Algorithm | Algorithm_37838_I | ### Mastermind Game Solver
You are tasked with implementing a solver for the classic code-breaking game "Mastermind." The goal of the game is for the codebreaker to guess the secret code created by the codemaker. Your solver will attempt to guess the secret code, using feedback provided after each guess.
Specifically... | def make_guess(past_attempts, feedback):
"""
Generates a new guess for the Mastermind game based on past attempts and feedback.
"""
import random
if not past_attempts:
# If no past attempts, return a random guess
return [random.randint(0, 5) for _ in range(4)]
def is_valid_... | from solution import make_guess, provide_feedback
def test_provide_feedback():
assert provide_feedback([0, 1, 2, 3], [0, 1, 2, 3]) == (4, 0)
assert provide_feedback([0, 1, 2, 3], [3, 2, 1, 0]) == (0, 4)
assert provide_feedback([0, 1, 2, 3], [0, 0, 0, 0]) == (1, 0)
assert provide_feedback([0, 1, 2, 3], ... | [
{
"docstring": "Generates a new guess for the Mastermind game based on past attempts and feedback.",
"function_declaration": "def make_guess(past_attempts, feedback):",
"function_name": "make_guess",
"parameter_list": "(past_attempts, feedback)"
},
{
"docstring": "Provides feedback for a gue... | [
1,
1,
1,
1,
0,
0,
0,
0,
0,
0
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def provide_feedback(secret_code, guess):\n \"\"\"\n Provides feedback on the guess compared to the secret code.\n Returns a tuple of (hits, misses).\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "0000037838",
"row_id": 37838,
"seed_ids": "[473]"
} | 0.583463 | Algorithm_37838 | I | [
"make_guess",
"provide_feedback"
] | 2 | [
[
"make_guess",
"provide_feedback"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | cf8fe1e703f0c2d38a11eba5acac3bd26bb6356c | b67a90d1f1543a1721fad4f385b61e654ff31e13 | |||
v1.0 | instruct | Algorithm | Algorithm_37874_I | ### Context
In computer graphics, colors are often represented in the RGB color model. In this model, each color is described by three components - red, green, and blue - each ranging from 0 to 255. A common task in image processing is to adjust the brightness of an image, which can be done by modifying these RGB compo... | def clamp(value, min_value, max_value):
return max(min_value, min(value, max_value))
def adjust_brightness(image, factor):
if not image:
return []
adjusted_image = []
for row in image:
adjusted_row = []
for (red, green, blue) in row:
adjusted_red = clamp(int(red * f... | from solution import adjust_brightness
def test_brightness_increase():
image = [[(100, 100, 100), (50, 50, 50)], [(200, 200, 200), (25, 25, 25)]]
expected = [[(120, 120, 120), (60, 60, 60)], [(240, 240, 240), (30, 30, 30)]]
assert adjust_brightness(image, 1.2) == expected
def test_brightness_decrease():
... | [
{
"docstring": null,
"function_declaration": "def clamp(value, min_value, max_value):",
"function_name": "clamp",
"parameter_list": "(value, min_value, max_value)"
},
{
"docstring": null,
"function_declaration": "def adjust_brightness(image, factor):",
"function_name": "adjust_bright... | [
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 adjust_brightness(image: list[list[tuple[int, int, int]]], factor: float) -> list[list[tuple[int, int, int]]]:\n \"\"\"\n Adjust the brightness of a gi... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000037874",
"row_id": 37874,
"seed_ids": "[3273]"
} | 0.545387 | Algorithm_37874 | I | [
"clamp",
"adjust_brightness"
] | 2 | [
[
"adjust_brightness",
"clamp"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 0a471904d7256b58ad68466a8f7c511dac39dd03 | 153c2586a9e8aa42d5ecdc2d1b93f225ca2dc956 | |||
v1.0 | instruct | Algorithm | Algorithm_37882_I | ### Sentence Reversal with Constraints
#### Context:
Reversing words in a sentence is a common problem in string manipulation exercises. This advanced variation introduces constraints that make the problem more complex. You will need to reverse the words in the sentence while preserving the positions of the punctuatio... | def reverse_word(word):
"""
Helper function to reverse a single word, ignoring non-alphabetical characters.
"""
return word[::-1]
def reverse_sentence_with_constraints(sentence: str) -> str:
"""
Reverses words in a sentence while preserving the positions of punctuation marks and spaces.
"""... | from solution import reverse_sentence_with_constraints
def test_basic_example():
assert reverse_sentence_with_constraints("Hello, world! Check out this new feature.") == "olleH, dlrow! kcehC tuo siht wen erutaef."
def test_punctuation_only():
assert reverse_sentence_with_constraints("!,...??!") == "!,...??!"
... | [
{
"docstring": "Helper function to reverse a single word, ignoring non-alphabetical characters.",
"function_declaration": "def reverse_word(word):",
"function_name": "reverse_word",
"parameter_list": "(word)"
},
{
"docstring": "Reverses words in a sentence while preserving the positions of p... | [
0,
0,
0,
0,
0,
0,
0,
0,
1,
1
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def reverse_sentence_with_constraints(sentence: str) -> str:\n def reverse_words(words):\n return [word[::-1] for word in words]\n\n # Identifying a... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000037882",
"row_id": 37882,
"seed_ids": "[850]"
} | 0.622562 | Algorithm_37882 | I | [
"reverse_word",
"reverse_sentence_with_constraints"
] | 2 | [
[
"reverse_sentence_with_constraints",
"reverse_word"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 8c1861e2a7b0dd3341be38fa0b33612827a5938b | 2aa7b9da72231cdf404bdeb15f2eb3615cd6fdf2 | |||
v1.0 | instruct | Algorithm | Algorithm_37916_I | ### Matrix Determinant Calculation
**Context**:
As a software engineer, you are tasked with writing a function that computes the determinant of a square matrix. The determinant is a scalar value that is computed from the elements of a square matrix and has many applications in linear algebra, including solving linear ... | from typing import List
def matrix_cofactor(matrix: List[List[int]], i: int, j: int) -> List[List[int]]:
"""
Helper function to calculate the cofactor matrix
"""
return [row[:j] + row[j+1:] for row in (matrix[:i] + matrix[i+1:])]
def matrix_determinant(matrix: List[List[int]]) -> int:
"""
Retu... | from solution import matrix_determinant
def test_1x1_matrix():
assert matrix_determinant([[5]]) == 5
def test_2x2_matrix():
assert matrix_determinant([[1, 2], [3, 4]]) == -2
def test_3x3_matrix():
assert matrix_determinant([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) == 0
def test_4x4_matrix():
matrix = [
... | [
{
"docstring": "Helper function to calculate the cofactor matrix",
"function_declaration": "def matrix_cofactor(matrix, i, j):",
"function_name": "matrix_cofactor",
"parameter_list": "(matrix, i, j)"
},
{
"docstring": "Returns the determinant of a square matrix.",
"function_declaration":... | [
0,
0,
1,
1,
0,
0,
0,
0,
1
] | 3 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef matrix_determinant(matrix: List[List[int]]) -> int:\n def compute_determinant(mat):\n if len(mat) == 1:\n ret... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000037916",
"row_id": 37916,
"seed_ids": "[3752]"
} | 0.528879 | Algorithm_37916 | I | [
"matrix_cofactor",
"matrix_determinant"
] | 2 | [
[
"matrix_determinant",
"matrix_cofactor"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 56c47fe0b7816c7b78baed44dfb71f108a5a359f | bdb18847e682ba6c3a7633d8651fb38cc051cc3b | |||
v1.0 | instruct | Algorithm | Algorithm_37955_I | ### Coding Assessment Question
#### Scenario
You are developing a file management system to organize a directory of documents based on word frequency analysis. Each document contains text in English and needs to be preprocessed and analyzed to find the most common words. Additionally, documents should be ranked based... | import os
import string
from collections import Counter
from math import sqrt
from typing import List
def preprocess(text: str) -> List[str]:
"""
Preprocess the text by removing punctuation and converting to lowercase.
"""
translator = str.maketrans('', '', string.punctuation)
return text.translate... | import os
import pytest
from solution import organize_documents
def create_test_files():
os.makedirs('test_documents', exist_ok=True)
with open('test_documents/doc1.txt', 'w', encoding='utf-8') as f:
f.write("This is a test document. This document is for testing.")
with open('test_do... | [
{
"docstring": "Preprocess the text by removing punctuation and converting to lowercase.",
"function_declaration": "def preprocess(text):",
"function_name": "preprocess",
"parameter_list": "(text)"
},
{
"docstring": "Count the frequency of each word in the text and return\nthe top `n` most c... | [
0,
0,
1,
0,
0,
1,
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 os\nimport re\nimport math\nfrom collections import Counter\nfrom sklearn.metrics.pairwise import cosine_similarity\nfrom sklearn.feature_extraction.text ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000037955",
"row_id": 37955,
"seed_ids": "[4253]"
} | 0.63476 | Algorithm_37955 | I | [
"preprocess",
"word_frequencies",
"cosine_similarity",
"read_file",
"organize_documents"
] | 5 | [
[
"organize_documents",
"cosine_similarity"
],
[
"organize_documents",
"read_file"
],
[
"organize_documents",
"word_frequencies"
],
[
"word_frequencies",
"preprocess"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | c3c00dfe1e54e5f640ef51267b82a0b21c47d90f | b0ea29af731d628b8a62223c413beece56cd9eaf | |||
v1.0 | instruct | Algorithm | Algorithm_37982_I | ## Challenge: Efficient String Matching with the KMP Algorithm
#### Background
String matching is a classic problem in computer science. The Knuth-Morris-Pratt (KMP) algorithm is an efficient string matching algorithm that searches for occurrences of a "pattern" string within a "text" string. It runs in O(n + m) time ... | def compute_lps(pattern):
lps = [0] * len(pattern)
length = 0
i = 1
while i < len(pattern):
if pattern[i] == pattern[length]:
length += 1
lps[i] = length
i += 1
else:
if length != 0:
length = lps[length - 1]
else... | from solution import kmp_search
def test_kmp_search_exact_match():
assert kmp_search("abracadabra", "abracadabra") == [0]
def test_kmp_search_multi_occurrences():
assert kmp_search("abracadabra", "abra") == [0, 7]
def test_kmp_search_single_occurrence():
assert kmp_search("hello", "ll") == [2]
def test_... | [
{
"docstring": null,
"function_declaration": "def compute_lps(pattern):",
"function_name": "compute_lps",
"parameter_list": "(pattern)"
},
{
"docstring": null,
"function_declaration": "def kmp_search(text, pattern):",
"function_name": "kmp_search",
"parameter_list": "(text, patte... | [
1,
1,
0,
0,
1,
1,
0,
0,
1
] | 5 | medium | 0.556 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def kmp_search(text: str, pattern: str) -> list[int]:\n \"\"\"\n Returns a list of starting indices where 'pattern' is found within 'text' using the KMP al... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "0000037982",
"row_id": 37982,
"seed_ids": "[902]"
} | 0.6227 | Algorithm_37982 | I | [
"compute_lps",
"kmp_search"
] | 2 | [
[
"kmp_search",
"compute_lps"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | deccfdfad5db188fd6817747d1b0b77cbcb514eb | 85caca44cdc2abe55da5ea7b5378b0d0644b8b40 | |||
v1.0 | instruct | Algorithm | Algorithm_38199_I | ### Coding Challenge: Unique Characters Counter in Strings
#### Objective:
You are provided a list of strings. Your task is to determine how many strings in the list contain all unique characters and return this count.
#### Detailed Task Description:
1. **Function Implementation**:
- Implement `has_all_unique_cha... | from typing import List
def has_all_unique_characters(s: str) -> bool:
"""
Returns True if the string contains all unique characters, False otherwise.
"""
return len(set(s)) == len(s)
def count_unique_character_strings(strings: List[str]) -> int:
"""
Takes a list of strings and counts how many... | from solution import has_all_unique_characters, count_unique_character_strings
# Tests for has_all_unique_characters
def test_has_all_unique_characters_with_unique():
assert has_all_unique_characters("orange") == True
def test_has_all_unique_characters_with_duplicates():
assert has_all_unique_characters("app... | [
{
"docstring": "Returns True if the string contains all unique characters, False otherwise.",
"function_declaration": "def has_all_unique_characters(s):",
"function_name": "has_all_unique_characters",
"parameter_list": "(s)"
},
{
"docstring": "Takes a list of strings and counts how many stri... | [
1,
1,
0,
0,
0,
1,
1,
1,
0,
1
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef has_all_unique_characters(s: str) -> bool:\n \"\"\"\n Determine if a string contains all unique characters.\n \n Args:... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000038199",
"row_id": 38199,
"seed_ids": "[3325]"
} | 0.76919 | Algorithm_38199 | I | [
"has_all_unique_characters",
"count_unique_character_strings"
] | 2 | [
[
"count_unique_character_strings",
"has_all_unique_characters"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f3370d886de767b8c65e5d6fee0743474d334587 | 608a9c84e98f30529f60097e5270ccaad278f392 | |||
v1.0 | instruct | Algorithm | Algorithm_38247_I | ### Problem: Evaluate Sums of Unique Prime Factors
You are given a file containing several lines, each with a single positive integer. Your task is to write a program that reads these integers and calculates the sum of the unique prime factors for each integer.
#### Input
* A string `filename` which denotes the path... | from typing import List, Set
def prime_factors(n: int) -> Set[int]:
"""Helper function to find the unique prime factors of a given number"""
factors = set()
# Check for number of 2s in n
while n % 2 == 0:
factors.add(2)
n //= 2
# Check for odd factors from 3 upwards
for i in ran... | from solution import sum_unique_prime_factors
def test_prime_factors():
assert prime_factors(28) == {2, 7}
assert prime_factors(50) == {2, 5}
assert prime_factors(19) == {19}
assert prime_factors(30) == {2, 3, 5}
assert prime_factors(100) == {2, 5}
def test_sum_unique_prime_factors(tmp_path):
... | [
{
"docstring": "Helper function to find the unique prime factors of a given number",
"function_declaration": "def prime_factors(n):",
"function_name": "prime_factors",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def sum_unique_prime_factors(filename):",
"... | [
0,
1,
0,
0,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef sum_unique_prime_factors(filename: str) -> List[int]:\n def get_unique_prime_factors(n):\n factors = set()\n d = ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "0000038247",
"row_id": 38247,
"seed_ids": "[2091]"
} | 0.712386 | Algorithm_38247 | I | [
"prime_factors",
"sum_unique_prime_factors"
] | 2 | [
[
"sum_unique_prime_factors",
"prime_factors"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 00c2133e704b8af94bf84a2c99f1f90af4323ff7 | 0130c483cf5107025eab92b23f12ca3ed0a443d4 | |||
v1.0 | instruct | Algorithm | Algorithm_38276_I | ### Problem Description
You have been assigned to create a function that processes a list of integers to generate a new list that only contains the numbers which are both prime numbers and greater than 10. The function should gracefully handle any invalid input, such as non-integer elements or non-iterable input.
###... | from typing import Any, Union, List
def is_prime(n: int) -> bool:
"""Check if an integer n is prime."""
if n <= 1:
return False
if n == 2 or n == 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
... | def test_filter_primes_over_ten_valid_input():
assert filter_primes_over_ten([11, 12, 13, 4, 5, 19]) == [11, 13, 19]
assert filter_primes_over_ten([2, 3, 5, 7, 11, 13, 17, 19, 23]) == [11, 13, 17, 19, 23]
assert filter_primes_over_ten([0, 1, 4, 6, 8, 21, 22, 25]) == []
assert filter_primes_over_ten([23,... | [
{
"docstring": "Check if an integer n is prime.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Filter out the primes greater than 10 from the list of numbers.",
"function_declaration": "def filter_primes_over_ten(numb... | [
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 9 | easy | 1 | {
"trial_gpt4o_0": null,
"trial_gpt4o_1": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_1_results_combined.jsonl",
"solution_code": "from typing import Any, Union, List\n\ndef is_prime(n: int) -> bool:\n \"\"\"Check if a number n is prime.\"\"\"\n if n <= 1:\n ... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "0000038276",
"row_id": 38276,
"seed_ids": "[3407]"
} | 0.613193 | Algorithm_38276 | I | [
"is_prime",
"filter_primes_over_ten"
] | 2 | [
[
"filter_primes_over_ten",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 8d24b0df91792c8e85856490c1dfac062a94befb | a15c622e569da511d3a21825f7097a048d69582c | |||
v1.0 | instruct | Algorithm | Algorithm_38360_I | ### Prime Number Matrix
#### Objective
Create a function that identifies the largest prime number in each row of a given matrix and replaces all other elements in that row with zero.
#### Problem Statement
Given a matrix of integers, write a function to find the largest prime number in each row. Replace all non-prime... | def is_prime(n):
"""
Function to check if a number is prime.
"""
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
... | def test_prime_matrix_basic():
matrix = [
[2, 4, 6, 8],
[3, 5, 10, 15],
[1, 2, 3, 4]
]
result = prime_matrix(matrix)
assert result == [
[2, 0, 0, 0],
[0, 5, 0, 0],
[0, 0, 3, 0]
]
def test_prime_matrix_no_primes():
matrix = [
[4, 6, 8, 10],... | [
{
"docstring": "Function to check if a number is prime.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Function to replace all elements in each row of the matrix with zero\nexcept the largest prime number in that row.",
... | [
1,
1,
0,
1,
1,
0,
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": "def is_prime(n):\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 range(3, int(... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "0000038360",
"row_id": 38360,
"seed_ids": "[272]"
} | 0.54756 | Algorithm_38360 | I | [
"is_prime",
"prime_matrix"
] | 2 | [
[
"prime_matrix",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 9c91c3d99811dd45ed89f58a43b4508a259e4d0b | d3f6d886fdcc74cc8287c8e154c619ad66144ac2 | |||
v1.0 | instruct | Algorithm | Algorithm_38361_I | ### Coding Assessment Question: Implementing and Using a Radix Sort Algorithm
#### Context
You are tasked with improving the performance of a data processing pipeline that involves sorting large lists of non-negative integers. While the default sorting algorithms perform well in general, you identify that a specialize... | def counting_sort(arr, exp):
"""
A function to do counting sort of arr[] according to the digit represented by exp.
"""
n = len(arr)
output = [0] * n # output array
count = [0] * 10 # count array to store occurrences of digits (0 to 9)
# Store count of occurrences in count[]
for i in ... | def test_radix_sort_empty():
assert radix_sort([]) == []
def test_radix_sort_single_element():
assert radix_sort([1]) == [1]
def test_radix_sort_sorted_list():
assert radix_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_radix_sort_reversed_list():
assert radix_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4,... | [
{
"docstring": "A function to do counting sort of arr[] according to the digit represented by exp.",
"function_declaration": "def counting_sort(arr, exp):",
"function_name": "counting_sort",
"parameter_list": "(arr, exp)"
},
{
"docstring": "A function to implement radix sort.",
"function... | [
1,
1,
1,
1,
0,
0,
0,
0,
0,
0
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def counting_sort(arr, exp):\n n = len(arr)\n output = [0] * n\n count = [0] * 10 # Since we are dealing with digits 0-9\n\n for i in range(n):\n ... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "0000038361",
"row_id": 38361,
"seed_ids": "[4555]"
} | 0.617449 | Algorithm_38361 | I | [
"counting_sort",
"radix_sort"
] | 2 | [
[
"radix_sort",
"counting_sort"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | a44f04c61e24723a5343daca9851fe11e4ec2150 | 70d7cbf1ee42f24e5d50a4eb9f46d8dc1d621fd9 | |||
v1.0 | instruct | Algorithm | Algorithm_38364_I | ### Coding Assessment Question
#### Context
In this exercise, you will identify prime numbers that remain prime when their digits are rearranged in any permutation. Such prime numbers can be fascinating, and often involve exploring permutations and primality testing.
#### Problem Statement
Write a function `find_n_pr... | import itertools
def is_prime(num):
"""Check if a number is a prime number."""
if num <= 1:
return False
if num <= 3:
return True
if num % 2 == 0 or num % 3 == 0:
return False
i = 5
while i * i <= num:
if num % i == 0 or num % (i + 2) == 0:
return Fal... | from solution import find_n_prime_permutation
def test_find_n_prime_permutation():
assert find_n_prime_permutation(1) == 2
assert find_n_prime_permutation(2) == 3
assert find_n_prime_permutation(3) == 5
assert find_n_prime_permutation(4) == 7
assert find_n_prime_permutation(5) == 11
assert find... | [
{
"docstring": "Check if a number is a prime number.",
"function_declaration": "def is_prime(num):",
"function_name": "is_prime",
"parameter_list": "(num)"
},
{
"docstring": "Check if all permutations of the digits of prime are also prime.",
"function_declaration": "def has_all_prime_per... | [
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": "from itertools import permutations\n\ndef is_prime(num):\n if num <= 1:\n return False\n if num <= 3:\n return True\n if num % 2 == 0 or n... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "0000038364",
"row_id": 38364,
"seed_ids": "[2842]"
} | 0.655513 | Algorithm_38364 | I | [
"is_prime",
"has_all_prime_permutations",
"find_n_prime_permutation"
] | 3 | [
[
"find_n_prime_permutation",
"has_all_prime_permutations"
],
[
"find_n_prime_permutation",
"is_prime"
],
[
"has_all_prime_permutations",
"is_prime"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | ee6bea4c80e05d681ba9375c5bde13cadf117e95 | f516cd8793faafb612a9d00f574ff970dcead488 | |||
v1.0 | instruct | Algorithm | Algorithm_38382_I | ### Coding Assessment Question
#### Context
You are creating a tool that will assist with scheduling meetings based on participants' availability. The tool should find the earliest common slot that is at least 30 minutes long.
#### Task
Create a function `find_earliest_meeting_slot(schedule: List[Tuple[str, str]], du... | from typing import List, Tuple
def time_to_minutes(time: str) -> int:
h, m = map(int, time.split(':'))
return h * 60 + m
def minutes_to_time(minutes: int) -> str:
h = minutes // 60
m = minutes % 60
return f"{h:02d}:{m:02d}"
def find_earliest_meeting_slot(schedule: List[Tuple[str, str]], duration:... | from solution import find_earliest_meeting_slot
def test_earliest_slot_first_gap():
assert find_earliest_meeting_slot([("09:00", "09:30"), ("10:00", "11:00"), ("12:00", "13:00"), ("14:00", "15:00")], 30) == "09:30"
def test_earliest_slot_last_gap():
assert find_earliest_meeting_slot([("09:00", "10:30"), ("10:... | [
{
"docstring": null,
"function_declaration": "def time_to_minutes(time):",
"function_name": "time_to_minutes",
"parameter_list": "(time)"
},
{
"docstring": null,
"function_declaration": "def minutes_to_time(minutes):",
"function_name": "minutes_to_time",
"parameter_list": "(minut... | [
0,
0,
0,
1,
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": "from typing import List, Tuple\nfrom datetime import datetime, timedelta\n\ndef find_earliest_meeting_slot(schedule: List[Tuple[str, str]], duration: int = 30) -... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "0000038382",
"row_id": 38382,
"seed_ids": "[2336]"
} | 0.673539 | Algorithm_38382 | I | [
"time_to_minutes",
"minutes_to_time",
"find_earliest_meeting_slot"
] | 3 | [
[
"find_earliest_meeting_slot",
"minutes_to_time"
],
[
"find_earliest_meeting_slot",
"time_to_minutes"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 8880d089146a388dbc4aa80d24cc9f9e6d99e52d | 51adba01ec0bdcefeb2575eb3f7259be621a557d | |||
v1.0 | instruct | Algorithm | Algorithm_38392_I | ### Coding Assessment Question
**Scenario**: You are a data analyst at a logistics company. Your team needs to analyze route data to determine the most fuel-efficient path for delivery trucks. The company measures fuel consumption per mile for each segment of the route.
You need to calculate the total fuel consumptio... | def total_fuel_consumption(segments):
"""
Calculates the total fuel consumption for a given route.
Args:
segments (list of tuples): Each tuple contains a string (segment name) and a float (fuel consumption).
Returns:
float: Total fuel consumption.
"""
return sum(fuel for _, fue... | from solution import total_fuel_consumption, max_fuel_consumption_segment, average_fuel_consumption
def test_total_fuel_consumption():
segments = [("A-B", 3.2), ("B-C", 4.5), ("C-D", 2.8), ("D-E", 5.0)]
assert total_fuel_consumption(segments) == 15.5
def test_max_fuel_consumption_segment():
segments = [(... | [
{
"docstring": "Calculates the total fuel consumption for a given route.\n\nArgs:\nsegments (list of tuples): Each tuple contains a string (segment name) and a float (fuel consumption).\n\nReturns:\nfloat: Total fuel consumption.",
"function_declaration": "def total_fuel_consumption(segments):",
"functi... | [
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": "def total_fuel_consumption(segments):\n \"\"\"\n Returns the total fuel consumption for the given route segments.\n \n Parameters:\n segments (lis... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000038392",
"row_id": 38392,
"seed_ids": "[985]"
} | 0.562761 | Algorithm_38392 | I | [
"total_fuel_consumption",
"max_fuel_consumption_segment",
"average_fuel_consumption"
] | 3 | [
[
"average_fuel_consumption",
"total_fuel_consumption"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 5c19c6f03c5328f60221b2f37c92a10693694536 | c9550ce23009c6e67a5d4cb425604ba0f27f32cd | |||
v1.0 | instruct | Algorithm | Algorithm_38411_I | Implementation of a Simple Genetic Algorithm
You are required to implement a simple Genetic Algorithm (GA) to solve a binary string optimization problem. Your task is to implement the following functions:
1. **initialize_population** - To create an initial population of binary strings.
2. **fitness** - To evaluate th... | import random
def initialize_population(pop_size: int, string_length: int) -> list[str]:
"""
Generate the initial population of binary strings.
Args:
- pop_size (int): Number of individuals in the population.
- string_length (int): Length of each binary string.
Returns:
- list[str]: Li... | from solution import initialize_population, fitness, selection, crossover, mutation, evolve
def test_initialize_population():
pop_size = 10
string_length = 8
population = initialize_population(pop_size, string_length)
assert len(population) == pop_size
assert all(len(individual) == string_length fo... | [
{
"docstring": "Generate the initial population of binary strings.\nArgs:\n- pop_size (int): Number of individuals in the population.\n- string_length (int): Length of each binary string.\n\nReturns:\n- list[str]: List of binary strings representing the initial population.",
"function_declaration": "def ini... | [
1,
1,
1,
1,
0,
0,
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": "import random\n\ndef initialize_population(pop_size: int, string_length: int) -> list[str]:\n \"\"\"\n Generate the initial population of binary strings.\n... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "0000038411",
"row_id": 38411,
"seed_ids": "[699]"
} | 0.438268 | Algorithm_38411 | I | [
"initialize_population",
"fitness",
"selection",
"crossover",
"mutation",
"evolve"
] | 6 | [
[
"evolve",
"crossover"
],
[
"evolve",
"fitness"
],
[
"evolve",
"mutation"
],
[
"evolve",
"selection"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | a7cc9cbcbeb5d85db78a67b8f5bda152bc2c234a | 611e980f383f41f79b3530106a7bb2496aadd614 | |||
v1.0 | instruct | Algorithm | Algorithm_38435_I | ### Sorting and Searching Using Merge Sort
**Context**: You are handling a large dataset and need to efficiently sort and search the dataset to find specific elements. Using the Merge Sort algorithm ensures that the sort operation is performed efficiently. Once sorted, you will also implement a binary search function ... | def merge_sort(arr: list[int]) -> list[int]:
"""
Sorts a list of integers using the Merge Sort algorithm.
Args:
arr (list[int]): A list of integers to be sorted.
Returns:
list[int]: A new list with the sorted integers.
"""
if len(arr) <= 1:
return arr
mid = len... | from solution import merge_sort, binary_search
def test_merge_sort_empty():
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_so... | [
{
"docstring": "Sorts a list of integers using the Merge Sort algorithm.\n\nArgs:\narr (list[int]): A list of integers to be sorted.\n\nReturns:\nlist[int]: A new list with the sorted integers.",
"function_declaration": "def merge_sort(arr):",
"function_name": "merge_sort",
"parameter_list": "(arr)"... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 10 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def merge_sort(arr):\n if len(arr) <= 1:\n return arr\n \n # Split the array into two halves\n mid = len(arr) // 2\n left_half = merge_sort... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000038435",
"row_id": 38435,
"seed_ids": "[393]"
} | 0.548386 | Algorithm_38435 | I | [
"merge_sort",
"merge",
"binary_search"
] | 3 | [
[
"merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | defbd9955c07506b1c0e1bf2c3ecc5e1bfe6e27f | 981546f61658b3da302bc4b3700e0a63b9801124 | |||
v1.0 | instruct | Algorithm | Algorithm_38498_I | ### Problem: Optimized Pathfinding in a Grid
#### Context
You are tasked with developing a pathfinding algorithm for an autonomous robot navigating a warehouse grid. The grid consists of cells, some of which are empty, and others are obstacles. The robot needs to find the shortest path from its starting position to a ... | import heapq
def heuristic(a, b):
"""Compute the Manhattan distance heuristic."""
return abs(a[0] - b[0]) + abs(a[1] - b[1])
def find_shortest_path(grid, start, goal):
"""
Uses A* search algorithm to find the shortest path in a 2D grid.
"""
if start == goal:
return 0
rows, cols = ... | from solution import find_shortest_path
def test_simple_grid():
grid = [
[0, 0, 1, 0],
[1, 0, 0, 0],
[0, 1, 1, 0],
[0, 0, 0, 0]
]
start = (0, 0)
goal = (3, 3)
assert find_shortest_path(grid, start, goal) == 6
def test_no_path():
grid = [
[0, 1, 1, 0],
... | [
{
"docstring": "Compute the Manhattan distance heuristic.",
"function_declaration": "def heuristic(a, b):",
"function_name": "heuristic",
"parameter_list": "(a, b)"
},
{
"docstring": "Uses A* search algorithm to find the shortest path in a 2D grid.",
"function_declaration": "def find_sho... | [
1,
0,
1,
1,
0,
1,
0,
0,
0,
0
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import heapq\nfrom typing import List, Tuple\n\ndef manhattan_distance(p1: Tuple[int, int], p2: Tuple[int, int]) -> int:\n return abs(p1[0] - p2[0]) + abs(p1[... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "0000038498",
"row_id": 38498,
"seed_ids": "[331]"
} | 0.637977 | Algorithm_38498 | I | [
"heuristic",
"find_shortest_path"
] | 2 | [
[
"find_shortest_path",
"heuristic"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f37e503609cf6b1ded309712f7b7bb19776f3cb9 | cb062e617f446789eb6e03c5f1e60dbbaf8bbc7e | |||
v1.0 | instruct | Algorithm | Algorithm_38544_I | ### Problem Statement
You are asked to implement a Sudoku solver. The solver should fill in the empty cells of a given partially completed 9x9 Sudoku grid following the standard Sudoku rules.
### Requirements
1. **Sudoku Rules**: Each row, each column, and each 3x3 sub-grid must contain the digits from 1 to 9 without ... | from typing import List, Tuple
def find_empty_position(board: List[List[int]]) -> Tuple[int, int]:
for i in range(9):
for j in range(9):
if board[i][j] == 0:
return i, j
return -1, -1
def is_valid(board: List[List[int]], row: int, col: int, num: int) -> bool:
box_row_st... | from solution import solve_sudoku
def test_sudoku_solver():
input_board = [
[5, 3, 0, 0, 7, 0, 0, 0, 0],
[6, 0, 0, 1, 9, 5, 0, 0, 0],
[0, 9, 8, 0, 0, 0, 0, 6, 0],
[8, 0, 0, 0, 6, 0, 0, 0, 3],
[4, 0, 0, 8, 0, 3, 0, 0, 1],
[7, 0, 0, 0, 2, 0, 0, 0, 6],
[0, 6, 0,... | [
{
"docstring": null,
"function_declaration": "def find_empty_position(board):",
"function_name": "find_empty_position",
"parameter_list": "(board)"
},
{
"docstring": null,
"function_declaration": "def is_valid(board, row, col, num):",
"function_name": "is_valid",
"parameter_list"... | [
0,
0,
1,
1,
0,
0,
1,
0,
1
] | 4 | medium | 0.444 | {
"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_empty_location(board: List[List[int]]):\n \"\"\"Finds an empty location on the Sudoku board represented by 0.\"\"\"\n f... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "0000038544",
"row_id": 38544,
"seed_ids": "[1859]"
} | 0.63505 | Algorithm_38544 | I | [
"find_empty_position",
"is_valid",
"solve_sudoku"
] | 3 | [
[
"solve_sudoku",
"find_empty_position"
],
[
"solve_sudoku",
"is_valid"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | e747e55f85774826bb18438227bf0ce596804d24 | ef3965be46918ae4f5ef13f994dfb4075b43710c | |||
v1.0 | instruct | Algorithm | Algorithm_38572_I | ### Context
Sorting algorithms are a fundamental concept in computer science, essential for efficiently organizing data. Many types of sorting algorithms exist, each with its advantages and ideal use cases. One valuable class of sorting techniques is merge sort, which uses a divide-and-conquer approach to achieve excel... | from typing import List
def merge_sort(arr: List[int]) -> List[int]:
"""
Perform merge sort on a list of integers.
"""
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_ha... | from solution import merge_sort
def test_merge_sort_empty_list():
assert merge_sort([]) == []
def test_merge_sort_single_element():
assert merge_sort([5]) == [5]
def test_merge_sort_multiple_elements():
assert merge_sort([3, 5, 2, 9, 1]) == [1, 2, 3, 5, 9]
def test_merge_sort_with_negative_numbers():
... | [
{
"docstring": "Perform merge sort on a list of integers.",
"function_declaration": "def merge_sort(arr):",
"function_name": "merge_sort",
"parameter_list": "(arr)"
},
{
"docstring": "Merge two sorted lists into one sorted list.",
"function_declaration": "def merge(left, right):",
"f... | [
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 def merge(left: List[int], right: L... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000038572",
"row_id": 38572,
"seed_ids": "[4255]"
} | 0.645496 | Algorithm_38572 | I | [
"merge_sort",
"merge"
] | 2 | [
[
"merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a2902368762e1a7dbda7f3b4b6cf7e73f295b27b | 5e12af02bd7c0391d1e69e0a37596e640c299c53 | |||
v1.0 | instruct | Algorithm | Algorithm_38687_I | ### Problem Description
You are tasked with implementing a function to calculate the sum of the first `n` prime numbers. The function should handle edge cases where `n` is less than or equal to zero by returning an appropriate message.
### Function to Implement
Write a Python function `sum_first_n_primes(n: int) -> ... | def is_prime(num):
if num <= 1:
return False
if num <= 3:
return True
if num % 2 == 0 or num % 3 == 0:
return False
i = 5
while i * i <= num:
if num % i == 0 or num % (i + 2) == 0:
return False
i += 6
return True
def sum_first_n_primes(n: int)... | from solution import sum_first_n_primes
def test_error_negative_input():
assert sum_first_n_primes(-3) == "Error: n should be a positive integer"
def test_error_zero_input():
assert sum_first_n_primes(0) == "Error: n should be a positive integer"
def test_sum_first_1_prime():
assert sum_first_n_primes(1)... | [
{
"docstring": null,
"function_declaration": "def is_prime(num):",
"function_name": "is_prime",
"parameter_list": "(num)"
},
{
"docstring": null,
"function_declaration": "def sum_first_n_primes(n):",
"function_name": "sum_first_n_primes",
"parameter_list": "(n)"
}
] | [
1,
0,
1,
1,
1,
1,
0,
1,
1,
1
] | 8 | easy | 0.8 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def is_prime(num):\n if num <= 1:\n return False\n if num <= 3:\n return True\n if num % 2 == 0 or num % 3 == 0:\n return False\n ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "0000038687",
"row_id": 38687,
"seed_ids": "[3407]"
} | 0.70156 | Algorithm_38687 | I | [
"is_prime",
"sum_first_n_primes"
] | 2 | [
[
"sum_first_n_primes",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 9ac99360109e0893ca66439d0a25b7d46625dd17 | fb28bd98fc3e481bdf0bd9e71def1e5441404417 | |||
v1.0 | instruct | Algorithm | Algorithm_38688_I | ### 2D Array - Find Local Maxima
#### Problem Statement
You are given a 2D array of integers where each element represents the elevation at that point. Your task is to identify and return the positions of local maxima. A local maximum is an element that is greater than or equal to all of its 8 neighbors.
#### Require... | from typing import List, Tuple
def find_local_maxima(matrix: List[List[int]]) -> List[Tuple[int, int]]:
if not matrix or not matrix[0]:
return []
rows = len(matrix)
cols = len(matrix[0])
local_maxima = []
for i in range(rows):
for j in range(cols):
if is_local_... | from solution import find_local_maxima
def test_find_local_maxima_single_element():
matrix = [[5]]
assert find_local_maxima(matrix) == [(0, 0)]
def test_find_local_maxima_small():
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
assert find_local_maxima(matrix) == [(2, 2)]
def... | [
{
"docstring": null,
"function_declaration": "def find_local_maxima(matrix):",
"function_name": "find_local_maxima",
"parameter_list": "(matrix)"
},
{
"docstring": null,
"function_declaration": "def is_local_maxima(matrix, i, j, rows, cols):",
"function_name": "is_local_maxima",
... | [
1,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List, Tuple\n\ndef find_local_maxima(matrix: List[List[int]]) -> List[Tuple[int, int]]:\n if not matrix or not matrix[0]:\n return [... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "0000038688",
"row_id": 38688,
"seed_ids": "[1578]"
} | 0.649891 | Algorithm_38688 | I | [
"find_local_maxima",
"is_local_maxima"
] | 2 | [
[
"find_local_maxima",
"is_local_maxima"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | bad4c2cb7d5571f337f8353bf467d37f09827f62 | db28569202d7572f7bedd6b58b0f7dafd69bf0d7 | |||
v1.0 | instruct | Algorithm | Algorithm_38713_I | ### Context
A logistics company requires an optimized solution to manage their delivery routes effectively. They need a function that can determine the shortest delivery route passing through all the delivery locations (similar to the Traveling Salesman Problem) but with a constraint that the delivery must start and e... | from itertools import permutations
def calculate_distance(p1, p2):
"""Calculate the Euclidean distance between two points p1 and p2."""
return ((p1[0] - p2[0])**2 + (p1[1] - p2[1])**2) ** 0.5
def shortest_delivery_route(depot, locations):
"""
Determines the shortest delivery route starting and ending ... | from solution import shortest_delivery_route
def test_single_location():
depot = (1, 1)
locations = [(2, 2)]
expected = [(1, 1), (2, 2), (1, 1)]
assert shortest_delivery_route(depot, locations) == expected
def test_multiple_locations():
depot = (0, 0)
locations = [(2, 1), (3, 5), (5, 2)]
#... | [
{
"docstring": "Calculate the Euclidean distance between two points p1 and p2.",
"function_declaration": "def calculate_distance(p1, p2):",
"function_name": "calculate_distance",
"parameter_list": "(p1, p2)"
},
{
"docstring": "Determines the shortest delivery route starting and ending at the... | [
0,
0,
1,
1,
1,
1,
0,
1,
1,
0
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import itertools\nimport math\n\ndef calculate_distance(point1, point2):\n \"\"\"\n Calculates the Euclidean distance between two points.\n \"\"\"\n ... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000038713",
"row_id": 38713,
"seed_ids": "[5357]"
} | 0.657447 | Algorithm_38713 | I | [
"calculate_distance",
"shortest_delivery_route"
] | 2 | [
[
"shortest_delivery_route",
"calculate_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | edf7ef3699e361d6a547dbb1393ef453c353e173 | 2a004634d98eebd55e29545428b2af08f97da8c3 | |||
v1.0 | instruct | Algorithm | Algorithm_38723_I | ### K-Means Clustering Implementation and Cluster Visualization
#### Context
You are working as a data scientist for a retail company. Your task is to segment customers based on their purchasing behaviors to identify distinct customer clusters. To achieve this, you decide to use the K-Means clustering algorithm.
####... | import numpy as np
import matplotlib.pyplot as plt
def initialize_centroids(points, k, random_seed):
np.random.seed(random_seed)
random_indices = np.random.choice(points.shape[0], k, replace=False)
centroids = points[random_indices]
return centroids
def closest_centroid(points, centroids):
distanc... | import numpy as np
from solution import k_means_clustering
def test_k_means_clustering():
points = np.array([[1.0, 2.0], [1.5, 1.8], [5.0, 8.0], [8.0, 8.0],
[1.0, 0.6], [9.0, 11.0], [8.0, 2.0], [10.0, 2.0]])
k = 3
max_iters = 100
random_seed = 42
cluster_labels, centroids =... | [
{
"docstring": null,
"function_declaration": "def initialize_centroids(points, k, random_seed):",
"function_name": "initialize_centroids",
"parameter_list": "(points, k, random_seed)"
},
{
"docstring": null,
"function_declaration": "def closest_centroid(points, centroids):",
"functio... | [
1,
1,
1,
0,
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": "import numpy as np\nimport matplotlib.pyplot as plt\n\ndef initialize_centroids(points, k, random_seed):\n np.random.seed(random_seed)\n random_indices = n... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000038723",
"row_id": 38723,
"seed_ids": "[503]"
} | 0.760707 | Algorithm_38723 | I | [
"initialize_centroids",
"closest_centroid",
"move_centroids",
"k_means_clustering",
"plot_clusters"
] | 5 | [
[
"k_means_clustering",
"closest_centroid"
],
[
"k_means_clustering",
"initialize_centroids"
],
[
"k_means_clustering",
"move_centroids"
]
] | 3 | [] | false | [] | false | pytest | true | [
"matplotlib",
"numpy"
] | false | 89f1b36a686a28a019ebe2c0afbc47bf088ab903 | 82b56c21bab3bf0336a07ed92dbcb172b35bc587 | |||
v1.0 | instruct | Algorithm | Algorithm_38864_I | ### Factorial Calculation with Memoization
You are working on developing software that requires extensive use of factorial calculations. To improve efficiency, you decide to implement memoization to store previously calculated factorials.
You are required to implement two functions:
1. **compute_factorial(n: int, me... | def compute_factorial(n, memo={}):
"""
Computes the factorial of n using memoization to cache results.
Parameters:
- n (int): The integer for which to compute the factorial.
- memo (dict): A dictionary to store previously computed factorial values.
Returns:
- int: The factorial of ... | from solution import compute_factorial, factorial_sequence
def test_compute_factorial_base_case():
assert compute_factorial(0) == 1
def test_compute_factorial_small_numbers():
assert compute_factorial(1) == 1
assert compute_factorial(2) == 2
assert compute_factorial(3) == 6
def test_compute_factorial... | [
{
"docstring": "Computes the factorial of n using memoization to cache results.\n\nParameters:\n- n (int): The integer for which to compute the factorial.\n- memo (dict): A dictionary to store previously computed factorial values.\n\nReturns:\n- int: The factorial of n.",
"function_declaration": "def comput... | [
1,
1,
1,
1,
1,
1,
0,
1,
1,
1
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def compute_factorial(n, memo={}):\n # Base case: factorial of 0 is 1\n if n == 0:\n return 1\n \n # Check if the value is already calculated\... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000038864",
"row_id": 38864,
"seed_ids": "[1553]"
} | 0.63162 | Algorithm_38864 | I | [
"compute_factorial",
"factorial_sequence"
] | 2 | [
[
"factorial_sequence",
"compute_factorial"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 806bd27181d2cd005bef78df30d12c56dad4bb55 | 9257ab333ddf5becb391cd5c2e47455bc0bf3c58 | |||
v1.0 | instruct | Algorithm | Algorithm_38879_I | ### Route Optimization for Delivery Trucks
#### Context
You are a software engineer for a logistics company. The company wants to optimize the delivery routes for their trucks to minimize the total distance traveled. Each truck starts from the warehouse, makes deliveries to assigned locations, and returns to the wareh... | from itertools import permutations
from typing import List
def calculate_route_distance(route: List[int], distances: List[List[int]]) -> int:
total_distance = 0
for i in range(len(route) - 1):
total_distance += distances[route[i]][route[i + 1]]
return total_distance
def optimize_routes(distances: ... | from solution import optimize_routes
def test_single_truck():
distances = [
[0, 10, 15, 20],
[10, 0, 35, 25],
[15, 35, 0, 30],
[20, 25, 30, 0]
]
num_trucks = 1
truck_routes = [[1, 2, 3]]
assert optimize_routes(distances, num_trucks, truck_routes) == [[0, 1, 3, 2, 0]]... | [
{
"docstring": null,
"function_declaration": "def calculate_route_distance(route, distances):",
"function_name": "calculate_route_distance",
"parameter_list": "(route, distances)"
},
{
"docstring": null,
"function_declaration": "def optimize_routes(distances, num_trucks, truck_routes):",... | [
0,
0,
1,
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": "from typing import List\nimport itertools\n\ndef calculate_route_distance(route: List[int], distances: List[List[int]]) -> int:\n total_distance = 0\n for ... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000038879",
"row_id": 38879,
"seed_ids": "[503]"
} | 0.664268 | Algorithm_38879 | I | [
"calculate_route_distance",
"optimize_routes"
] | 2 | [
[
"optimize_routes",
"calculate_route_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 3970d8b743261ce9820f697e6b22c33572b28363 | 0ca4301590f2c5fb2c269526ff70ea0f94ee000e | |||
v1.0 | instruct | Algorithm | Algorithm_38889_I | ### Coding Challenge: Social Media Feed Image Downloader
Your task is to develop a Python function that downloads images from a user's social media feed. The function should integrate data from two different social media platforms: Instagram and Twitter. You should implement additional error handling and optimize the ... | import requests
import concurrent.futures
# Put your API key(s) here
INSTAGRAM_API_KEY = "your_instagram_api_key"
TWITTER_API_KEY = "your_twitter_api_key"
INSTAGRAM_URL_BASE = "https://graph.instagram.com/v12.0/"
TWITTER_URL_BASE = "https://api.twitter.com/2/"
def fetch_instagram_images(user_id):
try:
ur... | import pytest
from solution import download_images
def test_download_images_valid_user():
user_id = "valid_user_id"
result = download_images(user_id)
assert "Instagram" in result or "Instagram_error" in result
assert "Twitter" in result or "Twitter_error" in result
def test_download_images_invalid_use... | [
{
"docstring": null,
"function_declaration": "def fetch_instagram_images(user_id):",
"function_name": "fetch_instagram_images",
"parameter_list": "(user_id)"
},
{
"docstring": null,
"function_declaration": "def fetch_twitter_images(user_id):",
"function_name": "fetch_twitter_images",... | [
0,
1,
1,
1,
0,
1,
0,
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 requests\nimport concurrent.futures\nimport re\n\n# Put your API key(s) here\nINSTAGRAM_API_KEY = \"your_instagram_api_key\"\nTWITTER_API_KEY = \"your_twi... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "0000038889",
"row_id": 38889,
"seed_ids": "[2556]"
} | 0.61234 | Algorithm_38889 | I | [
"fetch_instagram_images",
"fetch_twitter_images",
"download_images"
] | 3 | [
[
"download_images",
"fetch_instagram_images"
],
[
"download_images",
"fetch_twitter_images"
]
] | 2 | [] | false | [] | false | pytest | true | [
"requests"
] | false | 2c376696ab8a1b3491c34ad80adb2acfbad3fee0 | dfa98278ab47d6ca801ef00fdb9ca475da848515 | |||
v1.0 | instruct | Algorithm | Algorithm_38911_I | ## Question: Implement a Custom Binary Search with Error Handling
Given your understanding of the binary search algorithm, your task is to implement a refined version that includes error handling for unsorted input arrays and log the steps taken during the search process.
Specifically:
1. **Implement a function `is_... | def is_sorted(arr: list[int]) -> bool:
"""
Checks if the given list is sorted in ascending order.
"""
for i in range(len(arr) - 1):
if arr[i] > arr[i + 1]:
return False
return True
def custom_binary_search(arr: list[int], target: int, log_steps: bool = False) -> tuple[int, list[... | import pytest
from solution import is_sorted, custom_binary_search
def test_is_sorted():
assert is_sorted([1, 2, 3, 4])
assert is_sorted([1])
assert is_sorted([])
assert not is_sorted([4, 3, 2, 1])
assert not is_sorted([1, 3, 2, 4])
assert is_sorted([-5, -1, 0, 2, 5])
def test_custom_binary_se... | [
{
"docstring": "Checks if the given list is sorted in ascending order.",
"function_declaration": "def is_sorted(arr):",
"function_name": "is_sorted",
"parameter_list": "(arr)"
},
{
"docstring": "Performs binary search on a sorted array with logging and error handling for unsorted arrays.\n\n... | [
0,
0,
0,
1,
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": "def is_sorted(arr: list[int]) -> bool:\n \"\"\"\n Checks if a list is sorted in ascending order.\n \"\"\"\n return all(arr[i] <= arr[i + 1] for i in ... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "0000038911",
"row_id": 38911,
"seed_ids": "[4251]"
} | 0.602283 | Algorithm_38911 | I | [
"is_sorted",
"custom_binary_search"
] | 2 | [
[
"custom_binary_search",
"is_sorted"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 56cd218d2668c0513857dc9c46475cc2ee247621 | 33101fe76ee730a887014492c3ffb219e492f010 | |||
v1.0 | instruct | Algorithm | Algorithm_38959_I | ### Problem Statement
You are tasked with implementing a scheduling system that detects conflicts between appointments. An appointment is represented by a tuple containing the start time and end time in 24-hour format (e.g., 14:30 for 2:30 PM).
Implement a function `detect_conflict(appointments)` that checks whether ... | from typing import List, Tuple
def time_to_minutes(time: str) -> int:
"""Convert a time string in HH:MM format to the number of minutes past midnight."""
hours, minutes = map(int, time.split(":"))
return hours * 60 + minutes
def detect_conflict(appointments: List[Tuple[str, str]]) -> bool:
"""
Che... | def test_time_to_minutes():
assert time_to_minutes("00:00") == 0
assert time_to_minutes("00:01") == 1
assert time_to_minutes("01:00") == 60
assert time_to_minutes("12:30") == 750
assert time_to_minutes("23:59") == 1439
def test_no_conflict():
appointments = [("09:00", "10:00"), ("10:30", "11:30... | [
{
"docstring": "Convert a time string in HH:MM format to the number of minutes past midnight.",
"function_declaration": "def time_to_minutes(time):",
"function_name": "time_to_minutes",
"parameter_list": "(time)"
},
{
"docstring": "Check if any two appointments conflict with each other.\n\n:... | [
1,
1,
1,
1,
1,
1,
0,
1,
1,
1
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List, Tuple\n\ndef time_to_minutes(time: str) -> int:\n \"\"\"\n Convert time in HH:MM format to total minutes from midnight.\n \"\"\... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000038959",
"row_id": 38959,
"seed_ids": "[2676]"
} | 0.59049 | Algorithm_38959 | I | [
"time_to_minutes",
"detect_conflict"
] | 2 | [
[
"detect_conflict",
"time_to_minutes"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 3dfe3a6e5008e02df09871886fd0d5bb40a17c64 | cf9cda5829fea9307f86aa35011d3df9b5afe0bb | |||
v1.0 | instruct | Algorithm | Algorithm_38977_I | ### R-Tree Implementation and Intersection Search
You are to implement an R-Tree, which is a tree data structure used for spatial access methods, i.e., for indexing multi-dimensional information.
#### Task 1: R-Tree Construction
Write a function, `build_rtree(rectangles: list[list[float]], M: int) -> RTreeNode | None... | class RTreeNode:
def __init__(self, mbrs=None, children=None, is_leaf=True):
self.mbrs = mbrs if mbrs else []
self.children = children if children else []
self.is_leaf = is_leaf
def build_rtree(rectangles, M):
if not rectangles:
return None
return _build_rtree_recursive(rect... | from solution import build_rtree, search_intersections, RTreeNode
def test_build_rtree_empty_input():
root = build_rtree([], 4)
assert root is None
def test_build_rtree_single_entry():
rectangles = [[1, 1, 2, 2]]
M = 4
root = build_rtree(rectangles, M)
assert root is not None
assert root.i... | [] | [
0,
1,
0,
0,
0,
0,
1,
1,
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": "class RTreeNode:\n def __init__(self, rectangles=None, children=None, parent=None, is_leaf=True):\n \"\"\"\n Initialize a node in the R-Tree\n ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000038977",
"row_id": 38977,
"seed_ids": "[1641]"
} | 0.580463 | Algorithm_38977 | I | [
"build_rtree",
"_build_rtree_recursive",
"get_mbr",
"search_intersections",
"_search_intersections_recursive",
"_intersects"
] | 6 | [
[
"_build_rtree_recursive",
"get_mbr"
],
[
"_search_intersections_recursive",
"_intersects"
],
[
"build_rtree",
"_build_rtree_recursive"
],
[
"search_intersections",
"_search_intersections_recursive"
]
] | 4 | [] | false | [
"RTreeNode"
] | true | pytest | true | [] | true | 088d483e06d321f8641108faadd8b14a571d4deb | 148f2369b7aa25717ad887b83f9f6f5d9b9e2037 | |||
v1.0 | instruct | Algorithm | Algorithm_38981_I | ### Question: Implement a File Content Sorting Utility
#### Context:
You have been assigned to create a utility tool that reads multiple text files, extracts their contents, and sorts the content lines alphabetically. The current implementation can handle only one file at a time, but now you need to extend the functio... | from typing import List, Dict, Union
import concurrent.futures
import os
def read_and_sort_file(file_path: str) -> Union[str, List[str]]:
"""
Reads and sorts the contents of a file.
Parameters:
file_path (str): Path to the file.
Returns:
Union[str, List[str]]: Sorted content lines of the file... | import pytest
from solution import sort_files_contents
# Mock the read_and_sort_file function to avoid actual file I/O
from unittest.mock import patch, mock_open
def mock_open_sorted_content(file_path, content):
"""
Creates a mock open object that returns the specified content.
"""
m = mock_open(read_... | [
{
"docstring": "Reads and sorts the contents of a file.\n\nParameters:\nfile_path (str): Path to the file.\n\nReturns:\nUnion[str, List[str]]: Sorted content lines of the file or an error message if the file could not be processed.",
"function_declaration": "def read_and_sort_file(file_path):",
"functio... | [
1,
1,
1,
0,
1,
0,
0,
1,
1
] | 6 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import os\nimport threading\nfrom typing import List, Dict, Union\n\ndef sort_files_contents(file_paths: List[str]) -> Dict[str, Union[str, List[str]]]:\n \"\... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "0000038981",
"row_id": 38981,
"seed_ids": "[2356]"
} | 0.59772 | Algorithm_38981 | I | [
"read_and_sort_file",
"sort_files_contents"
] | 2 | [
[
"sort_files_contents",
"read_and_sort_file"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | fbb2da13d11bbacafb8762080d2699bd1fc0eb78 | fc5f0ca477e2d645b4173accd3aa4e4dc1af186b | |||
v1.0 | instruct | Algorithm | Algorithm_39001_I | ### Problem Statement
Write a function that determines if a given number is a prime number and also finds the next prime number greater than the given number. A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself.
Create a function `next_prime_info(n: int) -> (bool, in... | from math import isqrt
def is_prime(num):
"""
Returns True if num is a prime number, otherwise False.
"""
if num <= 1:
return False
if num <= 3:
return True
if num % 2 == 0 or num % 3 == 0:
return False
i = 5
while i * i <= num:
if num % i == 0 or num % (... | import pytest
from solution import next_prime_info
def test_next_prime_info():
assert next_prime_info(10) == (False, 11)
assert next_prime_info(29) == (True, 31)
assert next_prime_info(1000000) == (False, 1000003)
assert next_prime_info(1) == (False, 2)
assert next_prime_info(2) == (True, 3)
as... | [
{
"docstring": "Returns True if num is a prime number, otherwise False.",
"function_declaration": "def is_prime(num):",
"function_name": "is_prime",
"parameter_list": "(num)"
},
{
"docstring": "Returns the next prime number greater than num.",
"function_declaration": "def next_prime(num)... | [
1,
0,
0,
1,
0,
1,
0,
1,
1,
1
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import math\n\ndef is_prime(num):\n if num <= 1:\n return False\n if num <= 3:\n return True\n if num % 2 == 0 or num % 3 == 0:\n r... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000039001",
"row_id": 39001,
"seed_ids": "[2129]"
} | 0.755315 | Algorithm_39001 | I | [
"is_prime",
"next_prime",
"next_prime_info"
] | 3 | [
[
"next_prime",
"is_prime"
],
[
"next_prime_info",
"is_prime"
],
[
"next_prime_info",
"next_prime"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 6f3b2acbeff1758752dc59663e9243228b4b9303 | be6c22f2c41e48ae254476954d878bc3c35d3194 | |||
v1.0 | instruct | Algorithm | Algorithm_39082_I | ### Task: Implement a Modified Quick Sort for Nearly Sorted Arrays
#### Scenario
You are presented with an algorithm challenge to implement a modified version of the Quick Sort algorithm. This variant should take advantage of the input array's almost sorted nature. The task requires you to create an algorithm that opt... | def insertion_sort(arr, left, right):
"""
Helper function to perform insertion sort on a subarray from left to right.
"""
for i in range(left + 1, right + 1):
key = arr[i]
j = i - 1
while j >= left and arr[j] > key:
arr[j + 1] = arr[j]
j -= 1
arr[j... | from solution import modified_quick_sort
def test_already_sorted():
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
modified_quick_sort(arr)
assert arr == [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
def test_reverse_sorted():
arr = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
modified_quick_sort(arr)
assert arr == [1, 2, 3, 4, ... | [
{
"docstring": "Helper function to perform insertion sort on a subarray from left to right.",
"function_declaration": "def insertion_sort(arr, left, right):",
"function_name": "insertion_sort",
"parameter_list": "(arr, left, right)"
},
{
"docstring": "Partition the array for quicksort using ... | [
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": "def modified_quick_sort(array, threshold=10):\n \"\"\"\n Sorts an array in place using a modified version of the Quick Sort algorithm\n optimized for ne... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "0000039082",
"row_id": 39082,
"seed_ids": "[3597]"
} | 0.532527 | Algorithm_39082 | I | [
"insertion_sort",
"modified_partition",
"modified_quick_sort_rec",
"modified_quick_sort"
] | 4 | [
[
"modified_quick_sort",
"modified_quick_sort_rec"
],
[
"modified_quick_sort_rec",
"insertion_sort"
],
[
"modified_quick_sort_rec",
"modified_partition"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 488667198e1e521ef6d92151e24d46caec38b950 | 0926f9eb0c01be4ae47e016a9cd67e7b9ebb115f | |||
v1.0 | instruct | Algorithm | Algorithm_39083_I | ### Coding Assessment Question
#### Context:
You are developing a library of functions related to matrices. An important feature of this library involves implementing the Strassen algorithm to multiply two matrices efficiently.
#### Task:
Implement the function `strassen_multiplication`, which multiplies two square ... | def add_matrices(matrix_a, matrix_b):
size = len(matrix_a)
return [[matrix_a[i][j] + matrix_b[i][j] for j in range(size)] for i in range(size)]
def subtract_matrices(matrix_a, matrix_b):
size = len(matrix_a)
return [[matrix_a[i][j] - matrix_b[i][j] for j in range(size)] for i in range(size)]
def split... | from solution import strassen_multiplication
def test_strassen_2x2():
matrix_a = [
[1, 2],
[3, 4]
]
matrix_b = [
[5, 6],
[7, 8]
]
expected = [
[19, 22],
[43, 50]
]
result = strassen_multiplication(matrix_a, matrix_b)
assert result == ex... | [
{
"docstring": null,
"function_declaration": "def add_matrices(matrix_a, matrix_b):",
"function_name": "add_matrices",
"parameter_list": "(matrix_a, matrix_b)"
},
{
"docstring": null,
"function_declaration": "def subtract_matrices(matrix_a, matrix_b):",
"function_name": "subtract_mat... | [
1,
0,
1,
1,
0,
1,
1,
0,
1
] | 6 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def add_matrix(A, B):\n \"\"\"\n Adds two matrices A and B.\n \"\"\"\n n = len(A)\n return [[A[i][j] + B[i][j] for j in range(n)] for i in range(n... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000039083",
"row_id": 39083,
"seed_ids": "[5218]"
} | 0.529093 | Algorithm_39083 | I | [
"add_matrices",
"subtract_matrices",
"split_matrix",
"merge_matrices",
"strassen_multiplication"
] | 5 | [
[
"strassen_multiplication",
"add_matrices"
],
[
"strassen_multiplication",
"merge_matrices"
],
[
"strassen_multiplication",
"split_matrix"
],
[
"strassen_multiplication",
"subtract_matrices"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | 033757900a4d625b578c297f2fe4bb82a7063d43 | 6c54da9ef61aa7a18252e0855c25cf58572878a9 | |||
v1.0 | instruct | Algorithm | Algorithm_39133_I | ### Question: Implement a Basic Banking Ledger
You are asked to write three functions to manage a basic banking ledger: add a transaction, retrieve the balance, and generate a statement of transactions. The ledger should handle multiple transactions and compute the balance accurately.
#### Function 1: `add_transactio... | def add_transaction(ledger, transaction_type, amount):
if transaction_type not in ['deposit', 'withdrawal']:
raise ValueError("Transaction type must be 'deposit' or 'withdrawal'")
if amount <= 0:
raise ValueError("Amount must be greater than 0")
current_balance = calculate_balance(ledger)
... | import pytest
from solution import add_transaction, calculate_balance, generate_statement
def test_add_transaction_deposit():
ledger = []
ledger = add_transaction(ledger, 'deposit', 100.0)
assert len(ledger) == 1
assert ledger[0] == {'type': 'deposit', 'amount': 100.0}
def test_add_transaction_withdra... | [
{
"docstring": null,
"function_declaration": "def add_transaction(ledger, transaction_type, amount):",
"function_name": "add_transaction",
"parameter_list": "(ledger, transaction_type, amount)"
},
{
"docstring": null,
"function_declaration": "def calculate_balance(ledger):",
"functio... | [
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 add_transaction(ledger, transaction_type, amount):\n \"\"\"\n Add a transaction to the banking ledger.\n\n :param ledger: list - The current ledger ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000039133",
"row_id": 39133,
"seed_ids": "[5350]"
} | 0.479558 | Algorithm_39133 | I | [
"add_transaction",
"calculate_balance",
"generate_statement"
] | 3 | [
[
"add_transaction",
"calculate_balance"
],
[
"generate_statement",
"calculate_balance"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 64a6e3f0ac94a6b4005f736d640e39e56184f65e | fb1413c0f5ed670fb151b3be1a7e270ddf287412 | |||
v1.0 | instruct | Algorithm | Algorithm_39234_I | ### Problem Statement
You are tasked with implementing a function that checks if a provided string is a valid rotated palindrome. A rotated palindrome is a string that can be rotated (shifted circularly to the left or right) to form a palindrome.
#### Function Signature
```python
def is_rotated_palindrome(s: str) ->... | def is_palindrome(s: str) -> bool:
"""
Check if a given string is a palindrome.
"""
return s == s[::-1]
def rotate_string(s: str, n: int) -> str:
"""
Rotate a string s to the left by n positions.
"""
return s[n:] + s[:n]
def is_rotated_palindrome(s: str) -> bool:
"""
Check if a... | from solution import is_rotated_palindrome
def test_is_rotated_palindrome_simple():
assert is_rotated_palindrome("aabb") == True
assert is_rotated_palindrome("abcde") == False
assert is_rotated_palindrome("aba") == True
assert is_rotated_palindrome("abcabc") == False
def test_is_rotated_palindrome_edg... | [
{
"docstring": "Check if a given string is a palindrome.",
"function_declaration": "def is_palindrome(s):",
"function_name": "is_palindrome",
"parameter_list": "(s)"
},
{
"docstring": "Rotate a string s to the left by n positions.",
"function_declaration": "def rotate_string(s, n):",
... | [
1,
1,
1,
1,
0,
1,
0,
0,
1,
1
] | 7 | easy | 0.7 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def is_palindrome(s: str) -> bool:\n \"\"\"\n Checks if the given string is a palindrome.\n \"\"\"\n return s == s[::-1]\n\ndef rotate_string(s: str,... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000039234",
"row_id": 39234,
"seed_ids": "[5344]"
} | 0.755406 | Algorithm_39234 | I | [
"is_palindrome",
"rotate_string",
"is_rotated_palindrome"
] | 3 | [
[
"is_rotated_palindrome",
"is_palindrome"
],
[
"is_rotated_palindrome",
"rotate_string"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 6a43b50261f4d8168a27c10c8850e4a9171f3b5d | 4ce1bdfdebf5441d82119a0c3f0c97bac8665605 | |||
v1.0 | instruct | Algorithm | Algorithm_39239_I | ### Coding Assessment Question
As a software engineer, you are tasked with enhancing the functionality of an e-commerce platform by implementing a solution that tracks customers' shopping carts and calculates the total cost including applied discounts. The current system does not account for various edge cases and lac... | def calculate_total_cost(cart: list[dict[str, int | float]]) -> float:
"""
Calculate the total cost of the shopping cart.
:param cart: A list of dictionaries containing items with 'price' (float) and 'quantity' (int).
:return: The total cost (float) of items in the cart.
"""
total = 0.0
for... | import pytest
from solution import calculate_total_cost, apply_discounts
def test_calculate_total_cost():
cart = [{'price': 10.0, 'quantity': 2}, {'price': 15.0, 'quantity': 1}]
assert calculate_total_cost(cart) == 35.0
def test_calculate_total_cost_empty_cart():
cart = []
assert calculate_total_cost(... | [
{
"docstring": "Calculate the total cost of the shopping cart.\n\n:param cart: A list of dictionaries containing items with 'price' (float) and 'quantity' (int).\n:return: The total cost (float) of items in the cart.",
"function_declaration": "def calculate_total_cost(cart):",
"function_name": "calculat... | [
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": "def calculate_total_cost(cart: list[dict[str, int | float]]) -> float:\n \"\"\"\n Calculate the total cost of the shopping cart.\n\n :param cart: List o... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "0000039239",
"row_id": 39239,
"seed_ids": "[2342]"
} | 0.579566 | Algorithm_39239 | I | [
"calculate_total_cost",
"apply_discounts"
] | 2 | [
[
"apply_discounts",
"calculate_total_cost"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 177cb550dd00f4dbefaf14173e2b696b0019791a | 534df54b57c91531f9adc67be609bac96350364e | |||
v1.0 | instruct | Algorithm | Algorithm_39261_I | ### Problem Statement:
Your task is to implement a **Graph Search Algorithm with Weight Adjustments** to efficiently find the shortest path in a weighted undirected graph while dynamically adjusting edge weights based on certain conditions.
### Requirements:
1. **Function to Adjust Edge Weights:**
- Implement a f... | import heapq
import time
from typing import Dict, List, Tuple
def adjust_edge_weights(graph: Dict[int, List[Tuple[int, int]]], conditions: List[Tuple[int, int, int]]) -> None:
for u, v, new_weight in conditions:
for index, (neighbor, weight) in enumerate(graph[u]):
if neighbor == v:
... | from solution import adjust_edge_weights, modified_dijkstra
def test_adjust_edge_weights():
graph = {
0: [(1, 4), (2, 1)],
1: [(0, 4), (3, 1), (4, 5)],
2: [(0, 1), (3, 2)],
3: [(1, 1), (2, 2), (4, 3)],
4: [(1, 5), (3, 3)]
}
conditions = [(1, 3, 2), (0, 2, 2)]
adj... | [
{
"docstring": null,
"function_declaration": "def adjust_edge_weights(graph, conditions):",
"function_name": "adjust_edge_weights",
"parameter_list": "(graph, conditions)"
},
{
"docstring": null,
"function_declaration": "def modified_dijkstra(graph, start, conditions, adjust_weights):",
... | [
0,
0,
1,
0,
0,
0,
0,
0,
0,
1
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import heapq\nimport time\nfrom typing import Dict, List, Tuple\n\ndef adjust_edge_weights(graph: Dict[int, List[Tuple[int, int]]], conditions: List[Tuple[int, i... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000039261",
"row_id": 39261,
"seed_ids": "[5123]"
} | 0.669567 | Algorithm_39261 | I | [
"adjust_edge_weights",
"modified_dijkstra"
] | 2 | [
[
"modified_dijkstra",
"adjust_edge_weights"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 46248877af8551b2f59f561365611eda59386e20 | f656918ea260ea7a85593a19dcc5c7a1f61863cb | |||
v1.0 | instruct | Algorithm | Algorithm_39289_I | ### Prime Number Generator with Concurrency
You are recruited by a company that requires a high-performance system to generate prime numbers. This system needs to leverage concurrent processing to quickly find prime numbers within a specified range. Your task is to develop a prime numbers generator that handles multip... | import threading
from typing import List
# Shared state for prime generation
class PrimeSystem:
def __init__(self):
self.max_num = 0
self.initialize = False
prime_system = PrimeSystem()
def initialize_prime_system(n: int):
"""Initializes the system state for prime number generation up to a ma... | from solution import initialize_prime_system, generate_primes, reset_prime_system
def test_initialize_prime_system():
initialize_prime_system(1000)
assert prime_system.max_num == 1000
assert prime_system.initialize == True
def test_generate_primes_valid_range():
initialize_prime_system(1000)
prime... | [] | [
1,
0,
0,
0,
0,
0,
0,
0,
0,
1
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from math import isqrt\nfrom concurrent.futures import ThreadPoolExecutor\nfrom threading import Lock\n\n# Global state\n_primes = []\n_lock = Lock()\n\ndef init... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000039289",
"row_id": 39289,
"seed_ids": "[1874]"
} | 0.537519 | Algorithm_39289 | I | [
"initialize_prime_system",
"is_prime",
"primes_in_range",
"generate_primes",
"reset_prime_system"
] | 5 | [
[
"generate_primes",
"primes_in_range"
],
[
"primes_in_range",
"is_prime"
]
] | 2 | [] | false | [
"PrimeSystem"
] | true | pytest | true | [] | true | 7e072e5c8595b3d13b1ab428608c7395e18027fa | 417f5a2eafea3204e009eafb48bf8f0ed4ca2c2a | |||
v1.0 | instruct | Algorithm | Algorithm_39296_I | ### Prime Factorization Visualization Art
#### Objective
You need to visualize the prime factorization of a natural number in a graphical representation. This visual representation will help to better understand the structure of the number in terms of its prime factors.
#### Task
Create a function that generates a gr... | from collections import Counter
import math
def factorize(n):
factors = []
# Check for the number of twos in n
while n % 2 == 0:
factors.append(2)
n //= 2
# n must be odd at this point, so check for odd factors from 3 onwards
for i in range(3, int(math.sqrt(n)) + 1, 2):
whil... | from solution import prime_factor_visualization
def test_prime_factors_of_60():
assert prime_factor_visualization(60) == "2: **\n3: *\n5: *"
def test_prime_factors_of_prime_number():
assert prime_factor_visualization(17) == "17: *"
def test_prime_factors_of_100():
assert prime_factor_visualization(100) =... | [
{
"docstring": null,
"function_declaration": "def factorize(n):",
"function_name": "factorize",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def prime_factor_visualization(number):",
"function_name": "prime_factor_visualization",
"parameter_list": "(nu... | [
1,
1,
1,
0,
0,
0,
0,
0,
1,
1
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def prime_factor_visualization(number: int) -> str:\n from collections import defaultdict\n import math\n\n def sieve(n):\n is_prime = [True] * (... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000039296",
"row_id": 39296,
"seed_ids": "[4709]"
} | 0.671672 | Algorithm_39296 | I | [
"factorize",
"prime_factor_visualization"
] | 2 | [
[
"prime_factor_visualization",
"factorize"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 6b2b9b56923a4ad031c1a9a0eee84127c03c7669 | d50f4144314b6d2e7e87d8643a81f989770a5a87 | |||
v1.0 | instruct | Algorithm | Algorithm_39356_I | ### Coding Question:
You are tasked with implementing a function that finds the smallest integer which, when its digits are squared and added together repeatedly, ends in 1. The goal is to test your understanding of mathematical sequences and iterative processes.
#### Function Signature:
```python
def smallest_happy_n... | def is_happy_number(n: int) -> bool:
"""
Checks whether a given number is a happy number.
Parameters:
n (int): The number to check.
Returns:
bool: True if `n` is a happy number, False otherwise.
"""
def next_number(num):
total_sum = 0
while num > 0:
... | from solution import is_happy_number, smallest_happy_number
def test_is_happy_number():
assert is_happy_number(1) == True
assert is_happy_number(7) == True
assert is_happy_number(19) == True
assert is_happy_number(2) == False # 2 will eventually loop in [4, 16, 37, 58, 89, 145, 42, 20]
def test_small... | [
{
"docstring": "Checks whether a given number is a happy number.\n\nParameters:\nn (int): The number to check.\n\nReturns:\nbool: True if `n` is a happy number, False otherwise.",
"function_declaration": "def is_happy_number(n):",
"function_name": "is_happy_number",
"parameter_list": "(n)"
},
{
... | [
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 is_happy_number(n: int) -> bool:\n \"\"\"\n Checks whether a given number is a happy number.\n \n Parameters:\n n (int): The number to check.\... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "0000039356",
"row_id": 39356,
"seed_ids": "[2762]"
} | 0.573065 | Algorithm_39356 | I | [
"is_happy_number",
"smallest_happy_number"
] | 2 | [
[
"smallest_happy_number",
"is_happy_number"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 956aa4f8680cd1bbf1d17a24d62566378e96f618 | f4f272b7f874c5dfcf3a23fbeffeb49f14e5f74a | |||
v1.0 | instruct | Algorithm | Algorithm_39441_I | ### Scenario
You are developing a ridesharing application, and an important feature is to match drivers with the nearest rider requests. To facilitate this, you need to compute the minimum distance a driver has to travel to reach a rider. Given a series of rider and driver locations on a 2D grid, determine the best mat... | from typing import List, Tuple
import math
def euclidean_distance(p1: Tuple[int, int], p2: Tuple[int, int]) -> float:
return math.sqrt((p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2)
def closest_rider(drivers: List[Tuple[int, int]], riders: List[Tuple[int, int]]) -> List[int]:
closest = [-1] * len(drivers)
r... | from solution import closest_rider
def test_closest_rider_basic_case():
drivers = [(0, 0), (1, 2), (2, 1)]
riders = [(2, 3), (0, 1), (1, 1)]
assert closest_rider(drivers, riders) == [1, 2, 0]
def test_closest_rider_all_same_location():
drivers = [(0, 0), (0, 0), (0, 0)]
riders = [(0, 0), (0, 0), (... | [
{
"docstring": null,
"function_declaration": "def euclidean_distance(p1, p2):",
"function_name": "euclidean_distance",
"parameter_list": "(p1, p2)"
},
{
"docstring": null,
"function_declaration": "def closest_rider(drivers, riders):",
"function_name": "closest_rider",
"parameter_... | [
0,
0,
1,
0,
1,
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": "from typing import List, Tuple\nimport math\n\ndef euclidean_distance(point1, point2):\n return math.sqrt((point1[0] - point2[0]) ** 2 + (point1[1] - point2[1... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "0000039441",
"row_id": 39441,
"seed_ids": "[140]"
} | 0.659492 | Algorithm_39441 | I | [
"euclidean_distance",
"closest_rider"
] | 2 | [
[
"closest_rider",
"euclidean_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f13e1fbdd51103ca866a449275fe5625fd3f9e88 | c82f4284df4f3b65c2f363171b83fa4a72733329 | |||
v1.0 | instruct | Algorithm | Algorithm_39454_I | ## Coding Assessment Question
**Question: Optimized Pathfinding with A* Algorithm**
You are tasked with implementing a pathfinding function using the A* algorithm, a popular and efficient algorithm for finding the shortest path between nodes in a weighted graph. Your function should be optimized to handle large gra... | import heapq
def heuristic(node: str, goal: str) -> int:
"""
Heuristic function used by A* algorithm. Here, we assume a uniform edge cost.
"""
return 0 # As we do not have specific heuristic information, using 0 as a placeholder.
def a_star_search(graph: dict, start: str, goal: str) -> list:
"""
... | from solution import a_star_search
def test_a_star_search_simple():
graph = {
"A": {"B": 1, "C": 4},
"B": {"C": 2, "D": 5},
"C": {"D": 1},
"D": {}
}
assert a_star_search(graph, "A", "D") == ["A", "B", "C", "D"]
def test_a_star_search_simple_direct():
graph = {
"... | [
{
"docstring": "Heuristic function used by A* algorithm. Here, we assume a uniform edge cost.",
"function_declaration": "def heuristic(node, goal):",
"function_name": "heuristic",
"parameter_list": "(node, goal)"
},
{
"docstring": "A* pathfinding algorithm to find the shortest path in a weig... | [
1,
0,
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": "from typing import Dict, List, Tuple\nimport heapq\n\ndef heuristic(node: str, goal: str) -> int:\n \"\"\"\n A simple heuristic function that estimates the... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000039454",
"row_id": 39454,
"seed_ids": "[970]"
} | 0.629714 | Algorithm_39454 | I | [
"heuristic",
"a_star_search"
] | 2 | [
[
"a_star_search",
"heuristic"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 71670039415657cf0af403e04ff49a276f3579ed | 55a799f34da8eb4d15ad42b0532fdedfd15251b0 | |||
v1.0 | instruct | Algorithm | Algorithm_39478_I | ## Problem Statement
You are given a text file containing several pairs of positive integers. Each line in the file represents one pair, with the integers separated by a space. Your task is to write a function that reads the file and, for each pair, determines if the two integers are coprime (i.e., their greatest comm... | import math
def is_coprime(a: int, b: int) -> bool:
"""
Determines if two numbers are coprime.
"""
return math.gcd(a, b) == 1
def count_coprime_pairs(filepath: str) -> int:
"""
Reads a file containing pairs of integers and counts how many pairs are coprime.
"""
coprime_count = 0
wi... | import os
from solution import is_coprime, count_coprime_pairs
def test_is_coprime():
assert is_coprime(14, 25) == True
assert is_coprime(18, 27) == False
assert is_coprime(35, 64) == True
assert is_coprime(1, 1) == True
assert is_coprime(12, 13) == True
assert is_coprime(20, 28) == False
def ... | [
{
"docstring": "Determines if two numbers are coprime.",
"function_declaration": "def is_coprime(a, b):",
"function_name": "is_coprime",
"parameter_list": "(a, b)"
},
{
"docstring": "Reads a file containing pairs of integers and counts how many pairs are coprime.",
"function_declaration"... | [
1,
1,
0,
0,
0,
1,
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 math\n\ndef is_coprime(a: int, b: int) -> bool:\n \"\"\"\n Returns True if a and b are coprime, False otherwise.\n \"\"\"\n return math.gcd(a,... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000039478",
"row_id": 39478,
"seed_ids": "[2026]"
} | 0.651815 | Algorithm_39478 | I | [
"is_coprime",
"count_coprime_pairs"
] | 2 | [
[
"count_coprime_pairs",
"is_coprime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ccbc414572cec7dcacec5506d2258a0a6978cbd0 | 4e11d9c1d47078f0a99a2fe778fee6c5f4da5b02 | |||
v1.0 | instruct | Algorithm | Algorithm_39584_I | ### Coding Assessment Question
#### Objective:
Write a function to parse, evaluate, and compare two boolean algebra expressions given in infix notation. The function should return whether the two expressions are logically equivalent.
#### Description:
You are given two boolean algebra expressions in infix notation. Y... | from itertools import product
import re
def parse_expression(expr):
# Function to parse and convert infix expression to Postfix (RPN)
precedence = {'!': 3, '&': 2, '|': 1, '(': 0, ')': 0}
output = []
operators = []
def greater_precedence(op1, op2):
return precedence[op1] > precedence[o... | from solution import are_boolean_expressions_equivalent
def test_equivalent_expressions():
expr1 = "(a & b) | !c"
expr2 = "(!c) | (b & a)"
assert are_boolean_expressions_equivalent(expr1, expr2) == True
def test_non_equivalent_expressions():
expr1 = "a & (b | c)"
expr2 = "(a & b) | c"
assert a... | [
{
"docstring": null,
"function_declaration": "def parse_expression(expr):",
"function_name": "parse_expression",
"parameter_list": "(expr)"
},
{
"docstring": null,
"function_declaration": "def evaluate_postfix(postfix, values):",
"function_name": "evaluate_postfix",
"parameter_li... | [
1,
0,
1,
0,
0,
1,
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 itertools\n\ndef eval_boolean_expression(expr, values):\n \"\"\" Evaluate boolean expression with given variable values \"\"\"\n for var, val in val... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "0000039584",
"row_id": 39584,
"seed_ids": "[3818]"
} | 0.549006 | Algorithm_39584 | I | [
"parse_expression",
"evaluate_postfix",
"are_boolean_expressions_equivalent"
] | 3 | [
[
"are_boolean_expressions_equivalent",
"evaluate_postfix"
],
[
"are_boolean_expressions_equivalent",
"parse_expression"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 067f6b851d1fadc0c2aa034af30f534825ea7f75 | 44de424191727d4666be3877ffb7ed82f9f2d58f | |||
v1.0 | instruct | Algorithm | Algorithm_39587_I | ### Question Title: Weather Data Aggregator with Caching and Rate Limiting
### Scenario
You are required to develop a script that retrieves current weather data for a list of cities from a weather API. To optimize performance and avoid exceeding API rate limits, implement caching to store previously fetched data, and... | import requests
import time
from collections import namedtuple
from typing import List, Dict
from cachetools import TTLCache
# Define the WeatherData named tuple
WeatherData = namedtuple('WeatherData', ['temperature', 'humidity', 'description'])
# Initialize cache with a TTL of 10 minutes (600 seconds)
cache = TTLCac... | import pytest
from unittest.mock import patch
from solution import get_weather_data, WeatherData
# Mocked response data
mocked_response = {
'main': {
'temp': 20,
'humidity': 60
},
'weather': [{
'description': 'clear sky'
}]
}
@patch('solution.requests.get')
def test_get_weather... | [
{
"docstring": null,
"function_declaration": "def fetch_weather_data(city):",
"function_name": "fetch_weather_data",
"parameter_list": "(city)"
},
{
"docstring": null,
"function_declaration": "def get_weather_data(cities):",
"function_name": "get_weather_data",
"parameter_list": ... | [
0,
0,
0,
0,
1,
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": "import requests\nfrom collections import namedtuple\nfrom datetime import datetime, timedelta\nfrom typing import List, Dict\nimport time\n\n# Define the named t... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "0000039587",
"row_id": 39587,
"seed_ids": "[2295]"
} | 0.558344 | Algorithm_39587 | I | [
"fetch_weather_data",
"get_weather_data"
] | 2 | [
[
"get_weather_data",
"fetch_weather_data"
]
] | 1 | [] | false | [] | false | pytest | true | [
"cachetools",
"requests"
] | false | 392b98a28c621bb18312d372c5bef7b756bca661 | 4887c8667ea62a5bf3b860a9a2c9bf87f9642e29 | |||
v1.0 | instruct | Algorithm | Algorithm_39654_I | ### Clustering with K-Means and Custom Distance Metric
You are given an implementation of the K-Means clustering algorithm. Your task is to extend its functionality by adding support for a custom distance metric, `manhattan_distance`. Also, implement a method to handle the possibility of empty clusters by reassigning ... | import numpy as np
def manhattan_distance(point1: np.ndarray, point2: np.ndarray) -> float:
"""
Computes the Manhattan distance between two points.
"""
return np.sum(np.abs(point1 - point2))
def k_means(data_points: np.ndarray, k: int, iterations: int, distance_metric: str = 'euclidean') -> (np.ndarra... | from solution import manhattan_distance, k_means
import numpy as np
def test_manhattan_distance():
point1 = np.array([2, 3])
point2 = np.array([5, 8])
assert manhattan_distance(point1, point2) == 8
def test_k_means_euclidean():
data_points = np.array([[2, 3], [5, 8], [1, 2], [8, 8], [9, 10], [10, 12]]... | [
{
"docstring": "Computes the Manhattan distance between two points.",
"function_declaration": "def manhattan_distance(point1, point2):",
"function_name": "manhattan_distance",
"parameter_list": "(point1, point2)"
},
{
"docstring": "K-means clustering algorithm supporting custom distance metr... | [
1,
1,
0,
1,
1,
0,
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": "import numpy as np\n\ndef manhattan_distance(point1: np.ndarray, point2: np.ndarray) -> float:\n \"\"\"\n Computes the Manhattan distance between two point... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "0000039654",
"row_id": 39654,
"seed_ids": "[601]"
} | 0.701224 | Algorithm_39654 | I | [
"manhattan_distance",
"k_means"
] | 2 | [
[
"k_means",
"manhattan_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | 849eab3fe4feaf9925650ddc418aebfc9c3bc2b1 | 3b8d4850f7d81eb2e7de4f0f8cc0e1c259d6bcd2 | |||
v1.0 | instruct | Algorithm | Algorithm_39671_I | ### Chemical Reaction Balancing
#### Problem Description
A chemical reaction must be balanced to satisfy the law of conservation of mass, which states that the number of atoms of each element must be the same on both sides of the reaction. You are given the unbalanced chemical reaction in the form of a string and need... | import re
from collections import defaultdict
from sympy import Matrix, lcm
def parse_formula(formula):
pattern = re.compile(r"([A-Z][a-z]*)(\d*)")
elements = defaultdict(int)
for element, sub in pattern.findall(formula):
elements[element] += int(sub) if sub else 1
return elements
def balance_... | from solution import balance_reaction
def test_balance_simple_reaction():
result = balance_reaction("H2, O2", "H2O")
assert result == {'reactants': {'H2': 2, 'O2': 1}, 'products': {'H2O': 2}}
def test_balance_hydrocarbon_combustion():
result = balance_reaction("CH4, O2", "CO2, H2O")
assert result == {... | [
{
"docstring": null,
"function_declaration": "def parse_formula(formula):",
"function_name": "parse_formula",
"parameter_list": "(formula)"
},
{
"docstring": null,
"function_declaration": "def balance_reaction(reactants, products):",
"function_name": "balance_reaction",
"paramete... | [
0,
0,
0,
1,
1,
0,
0,
0,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from sympy import symbols, Eq, solve\nimport re\n\ndef balance_reaction(reactants: str, products: str) -> dict[str, int]:\n def parse_formula(formula: str):\n... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "0000039671",
"row_id": 39671,
"seed_ids": "[925]"
} | 0.474419 | Algorithm_39671 | I | [
"parse_formula",
"balance_reaction"
] | 2 | [
[
"balance_reaction",
"parse_formula"
]
] | 1 | [] | false | [] | false | pytest | true | [
"sympy"
] | false | 9f77feceea33ab86820ad25faf072b323bdf9590 | 606a4a84731b5acb4da6b0f104fc66a4d601b387 | |||
v1.0 | instruct | Algorithm | Algorithm_39676_I | ### Problem Statement
You have been provided with three types of sorting algorithms: Bubble Sort, Quick Sort, and Merge Sort. For a performance evaluation experiment, you are required to implement a function that returns the time taken to sort an array using each algorithm.
### Task
Implement a function `evaluate_sort... | import time
def bubble_sort(data):
n = len(data)
arr = data.copy()
for i in range(n):
for j in range(0, n-i-1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
return arr
def quick_sort(data):
if len(data) <= 1:
return data
pivot = data[len... | from solution import evaluate_sorting_algorithms, bubble_sort, quick_sort, merge_sort
import time
def test_evaluate_sorting_algorithms():
data = [64, 34, 25, 12, 22, 11, 90]
timings = evaluate_sorting_algorithms(data)
assert "Bubble Sort" in timings
assert "Quick Sort" in timings
assert "Merge Sort... | [
{
"docstring": null,
"function_declaration": "def bubble_sort(data):",
"function_name": "bubble_sort",
"parameter_list": "(data)"
},
{
"docstring": null,
"function_declaration": "def quick_sort(data):",
"function_name": "quick_sort",
"parameter_list": "(data)"
},
{
"docst... | [
0,
0,
0,
0,
0,
0,
0,
0,
1
] | 1 | hard | 0.111 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_snippets-i2i_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import time\n\ndef bubble_sort(data):\n arr = data[:]\n n = len(arr)\n for i in range(n):\n for j in range(0, n - i - 1):\n if arr[j] ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000039676",
"row_id": 39676,
"seed_ids": "[5048]"
} | 0.55705 | Algorithm_39676 | I | [
"bubble_sort",
"quick_sort",
"merge_sort",
"merge",
"evaluate_sorting_algorithms"
] | 5 | [
[
"evaluate_sorting_algorithms",
"bubble_sort"
],
[
"evaluate_sorting_algorithms",
"merge_sort"
],
[
"evaluate_sorting_algorithms",
"quick_sort"
],
[
"merge_sort",
"merge"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | e57c25c636ddb61bafa930f17ae6aeb87cf244b8 | b19ca69288763f0db0d411d17f8afe7c240c6450 | |||
v1.0 | instruct | Algorithm | Algorithm_39699_I | ## Problem Statement
You are tasked with implementing a function that performs matrix transposition on a given 2D matrix and another function that finds the maximum value in the transposed matrix.
### Function Signature
```python
def transpose_matrix(matrix: list[list[int]]) -> list[list[int]]:
# Your implement... | def transpose_matrix(matrix: list[list[int]]) -> list[list[int]]:
"""
Returns the transpose of the given 2D matrix.
"""
return [list(row) for row in zip(*matrix)]
def max_in_transposed(matrix: list[list[int]]) -> int:
"""
Finds the maximum value in the transposed matrix of the given 2D matrix.
... | from solution import transpose_matrix, max_in_transposed
def test_transpose_square_matrix():
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
expected = [
[1, 4, 7],
[2, 5, 8],
[3, 6, 9]
]
assert transpose_matrix(matrix) == expected
def test_max_in_trans... | [
{
"docstring": "Returns the transpose of the given 2D matrix.",
"function_declaration": "def transpose_matrix(matrix):",
"function_name": "transpose_matrix",
"parameter_list": "(matrix)"
},
{
"docstring": "Finds the maximum value in the transposed matrix of the given 2D matrix.",
"functi... | [
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 transpose_matrix(matrix: list[list[int]]) -> list[list[int]]:\n \"\"\"\n Returns the transposed matrix of the given 2D matrix.\n In the transposed m... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "0000039699",
"row_id": 39699,
"seed_ids": "[3187]"
} | 0.55636 | Algorithm_39699 | I | [
"transpose_matrix",
"max_in_transposed"
] | 2 | [
[
"max_in_transposed",
"transpose_matrix"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | bce2177a99b22e9b4ae53217bde7f6aea981a559 | 80cec25852af4e1fb4ccd742e1cc8df9038a7de0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.