id stringlengths 32 32 | problem stringlengths 207 3.86k | reference stringlengths 114 5.46k | tests listlengths 10 10 | function stringlengths 1 53 | signature stringlengths 9 432 | score float64 0.3 1 | domain stringclasses 2
values |
|---|---|---|---|---|---|---|---|
3390a0c7ea8f29471e3af9c131b11afc | You are given a list of integers. Your task is to implement a function `sort_odd_even` that processes this list by separating the odd and even numbers, sorting each group individually, and then returning a dictionary with the keys `'odd'` and `'even'`. Each key should map to a list of sorted numbers. For instance, if t... | def sort_odd_even(numbers):
"""
Separates the odd and even numbers from the input list, sorts them individually,
and returns a dictionary with keys 'odd' and 'even' mapping to the sorted lists.
:param numbers: List of integers to be processed.
:return: Dictionary with sorted odd and even number... | [
"assert sort_odd_even([3, 1, 4, 2, 5, 7]) == {'odd': [1, 3, 5, 7], 'even': [2, 4]}",
"assert sort_odd_even([10, 15, 20, 25, 30]) == {'odd': [15, 25], 'even': [10, 20, 30]}",
"assert sort_odd_even([1, 3, 5, 7, 9]) == {'odd': [1, 3, 5, 7, 9], 'even': []}",
"assert sort_odd_even([2, 4, 6, 8, 10]) == {'odd': [], ... | sort_odd_even | def sort_odd_even(numbers): | 1 | generic |
cc3c4af08ad12c106078ff34ee7e761e | You are tasked with implementing an efficient algorithm to compute the nth Fibonacci number. To optimize your solution, you must use memoization to avoid redundant calculations. Your function should handle large values of n efficiently.
**Input:**
- An integer `n` (0 ≤ n ≤ 50).
**Output:**
- The nth Fibonacci number.... | def fibonacci(n, memo=None):
"""
Calculate the nth Fibonacci number using memoization.
:param n: The position in the Fibonacci sequence (0-indexed).
:param memo: A dictionary to store previously computed Fibonacci numbers.
:return: The nth Fibonacci number.
"""
if memo is None:
memo... | [
"assert fibonacci(0) == 0",
"assert fibonacci(1) == 1",
"assert fibonacci(2) == 1",
"assert fibonacci(3) == 2",
"assert fibonacci(4) == 3",
"assert fibonacci(5) == 5",
"assert fibonacci(10) == 55",
"assert fibonacci(15) == 610",
"assert fibonacci(20) == 6765",
"assert fibonacci(25) == 75025"
] | fibonacci | def fibonacci(n, memo=None): | 1 | generic |
6873e18d76d98ed34c268930f78caa3a | You are given a dictionary where each key is associated with a list of integers. Your task is to write a function `sort_dict_values` that returns a new dictionary with the same keys, but with the values sorted in ascending order. The function should handle any dictionary of this form.
**Sample Input:**
```python
{'a':... | def sort_dict_values(input_dict):
"""
Sorts the values of each key in the input dictionary in ascending order.
Parameters:
input_dict (dict): A dictionary where each key is associated with a list of integers.
Returns:
dict: A new dictionary with the same keys and sorted values.
"""
ret... | [
"assert sort_dict_values({'a': [3, 1, 2], 'b': [5, 4]}) == {'a': [1, 2, 3], 'b': [4, 5]}",
"assert sort_dict_values({'x': [10, 9, 8], 'y': [7, 6, 5]}) == {'x': [8, 9, 10], 'y': [5, 6, 7]}",
"assert sort_dict_values({'z': [1], 'w': [2]}) == {'z': [1], 'w': [2]}",
"assert sort_dict_values({'m': [3, 3, 3], 'n': ... | sort_dict_values | def sort_dict_values(input_dict): | 1 | generic |
82e41b742749b30e0324bc07098489d3 | You are given a list of intervals, where each interval is represented as a tuple of two integers. Your task is to merge all overlapping intervals and return a new list of non-overlapping intervals sorted in ascending order based on their start times.
**Input:**
- A list of tuples, where each tuple represents an interv... | def merge_intervals(intervals):
"""
Merges all overlapping intervals from the given list and returns a new list of non-overlapping intervals.
:param intervals: List of tuples, where each tuple represents an interval [start, end].
:return: List of tuples representing the merged intervals.
"""
... | [
"assert merge_intervals([(1, 3), (2, 5), (8, 10)]) == [(1, 5), (8, 10)]",
"assert merge_intervals([(1, 2), (3, 4), (5, 6)]) == [(1, 2), (3, 4), (5, 6)]",
"assert merge_intervals([(1, 4), (4, 5)]) == [(1, 5)]",
"assert merge_intervals([(1, 3), (2, 6), (5, 7), (8, 10), (12, 16)]) == [(1, 7), (8, 10), (12, 16)]"... | merge_intervals | def merge_intervals(intervals): | 1 | generic |
9f1b8c6714ee7e0b93961402ffa24f94 | You are given a list of data sets, each characterized by its sum-of-squared-deviations (sosd), the number of items (num), and the degrees of freedom (ddof). Your task is to compute the variance for each data set if the number of items is a prime number. The variance is defined as the sum-of-squared-deviations divided b... | def is_prime(n):
"""Check if a number is a prime number."""
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
... | [
"assert calculate_variance(100, 7, 1) == 100 / (7 - 1)",
"assert calculate_variance(50, 11, 2) == 50 / (11 - 2)",
"assert calculate_variance(200, 13, 3) == 200 / (13 - 3)",
"assert calculate_variance(0, 17, 0) == 0 / (17 - 0)",
"assert calculate_variance(150, 4, 1) == None",
"assert calculate_variance(25,... | calculate_variance | def calculate_variance(sosd, num, ddof): | 1 | generic |
fe1244087aaf4997613ffe6585258c0a | You are given an array of integers `nums` and an integer `k`. Your task is to find the maximum sum of any contiguous subarray of length `k`. If `k` is larger than the length of the array, return `None`.
**Input:**
- The first line contains an integer `n` (1 ≤ n ≤ 10^5), the number of elements in the array.
- The secon... | def find_max_subarray_sum(nums, k):
"""
Finds the maximum sum of any contiguous subarray of length k.
:param nums: List[int] - The list of integers.
:param k: int - The length of the subarray.
:return: int or None - The maximum sum of any subarray of length k, or None if k is greater than the l... | [
"assert find_max_subarray_sum([1, 2, 3, 4, 5], 2) == 9",
"assert find_max_subarray_sum([1, 2, 3, 4, 5], 5) == 15",
"assert find_max_subarray_sum([1, 2, 3, 4, 5], 6) == None",
"assert find_max_subarray_sum([5, 1, 3, 2, 4], 3) == 10",
"assert find_max_subarray_sum([-1, -2, -3, -4, -5], 2) == -3",
"assert fi... | find_max_subarray_sum | def find_max_subarray_sum(nums, k): | 0.9 | generic |
2c703003ed920c5ce86160a9938d61f0 | You are given two integers `n` and `k`. Your task is to generate all possible combinations of `k` distinct numbers chosen from the range `[1, n]`. The combinations should be returned as a list of lists, where each inner list represents a unique combination. The order of combinations in the output list does not matter.
... | def generate_combinations(n, k):
"""
Generate all possible combinations of k numbers out of the range [1, n].
:param n: The upper bound of the range (inclusive).
:param k: The number of elements in each combination.
:return: A list of lists, where each inner list is a unique combination of k number... | [
"assert generate_combinations(4, 2) == [[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]]",
"assert generate_combinations(3, 2) == [[1, 2], [1, 3], [2, 3]]",
"assert generate_combinations(5, 3) == [[1, 2, 3], [1, 2, 4], [1, 2, 5], [1, 3, 4], [1, 3, 5], [1, 4, 5], [2, 3, 4], [2, 3, 5], [2, 4, 5], [3, 4, 5]]",
"a... | generate_combinations | def generate_combinations(n, k): | 1 | generic |
4321c0d4d41c6d4526c3a6dc7beeff5f | You are tasked with implementing a function `calculate_area` that computes the area of a rectangle given its width and height. The function should correctly multiply the width by the height to determine the area. Your implementation should handle positive integer inputs for both dimensions. Below is an erroneous versio... | def calculate_area(width, height):
"""
Calculate the area of a rectangle given its width and height.
Parameters:
width (int): The width of the rectangle.
height (int): The height of the rectangle.
Returns:
int: The area of the rectangle.
"""
return width * height | [
"assert calculate_area(5, 10) == 50",
"assert calculate_area(0, 10) == 0",
"assert calculate_area(7, 3) == 21",
"assert calculate_area(1, 1) == 1",
"assert calculate_area(10, 0) == 0",
"assert calculate_area(2.5, 4) == 10.0",
"assert calculate_area(3, 3.5) == 10.5",
"assert calculate_area(0, 0) == 0",... | calculate_area | def calculate_area(width, height): | 1 | generic |
47f547d4e5e9aaca56c14aba9891223a | You are given a nested dictionary that may contain other dictionaries and lists. Your task is to create a function that generates a unique string identifier for this dictionary. The identifier should be constructed by flattening the dictionary into a single string, where keys and values are separated by a colon (`:`), ... | def flatten_dict(d, parent_key='', sep='.'):
"""
Flattens a nested dictionary into a single-level dictionary with compound keys.
:param d: The dictionary to flatten.
:param parent_key: The base key string used in recursion.
:param sep: The separator between parent and child keys.
:return: A... | [
"assert generate_unique_identifier({'a': 1, 'b': 2}) == 'a:1,b:2'",
"assert generate_unique_identifier({'a': {'b': 2}}) == 'a.b:2'",
"assert generate_unique_identifier({'a': [1, 2, 3]}) == 'a[0]:1,a[1]:2,a[2]:3'",
"assert generate_unique_identifier({'a': [1, {'b': 2}]}) == 'a[0]:1,a[1].b:2'",
"assert genera... | generate_unique_identifier | def generate_unique_identifier(input_dict, key_val_sep=':', pair_sep=','): | 0.9 | generic |
158a98f866684cd485f609ef3b7ed67b | You are given a nested dictionary structure where each key-value pair can either be another dictionary or a value that is either a number or a string. Your task is to compute the sum of all numeric values within this structure. The structure can be arbitrarily deep. Write a recursive Python function to accomplish this.... | def sum_nested_numbers(data):
"""
Recursively computes the sum of all numeric values in a nested dictionary structure.
:param data: A nested dictionary or a numeric/string value.
:return: The sum of all numeric values in the structure.
"""
if isinstance(data, dict):
return sum(sum_neste... | [
"assert sum_nested_numbers({\"x\": 1, \"y\": {\"z\": 2, \"w\": 3}, \"a\": \"string\", \"b\": {\"c\": {\"d\": 4}}}) == 10",
"assert sum_nested_numbers({\"x\": 1, \"y\": 2, \"z\": 3}) == 6",
"assert sum_nested_numbers({\"x\": {\"y\": {\"z\": 1}}}) == 1",
"assert sum_nested_numbers({\"x\": \"string\", \"y\": \"a... | sum_nested_numbers | def sum_nested_numbers(data): | 1 | algorithmic |
ee10d41bf40f8a7f2413bf32e52a844e | You are given a list of integers, which may include both positive and negative numbers. Your task is to implement a function `count_duplicates` that returns a dictionary. The keys of this dictionary should be the integers from the list, and the corresponding values should represent the frequency of each integer in the ... | def count_duplicates(lst):
"""
Returns a dictionary with integers from the list as keys and their frequencies as values.
:param lst: List of integers
:return: Dictionary with integer frequencies
"""
counts = {}
for num in lst:
if num in counts:
counts[num] += 1
e... | [
"assert count_duplicates([1, 2, 2, 3, 3, 3]) == {1: 1, 2: 2, 3: 3}",
"assert count_duplicates([-1, -2, -2, -3, -3, -3]) == {-1: 1, -2: 2, -3: 3}",
"assert count_duplicates([0, 0, 0, 0]) == {0: 4}",
"assert count_duplicates([1, 1, 2, 2, 3, 3, 4, 4]) == {1: 2, 2: 2, 3: 2, 4: 2}",
"assert count_duplicates([]) ... | count_duplicates | def count_duplicates(lst): | 1 | generic |
da831c2b6a26e2fabcb59ac148a0f34d | Given a string `s`, your task is to write a function `generate_permutations(s)` that returns all unique permutations of the string in lexicographical order. You are not allowed to use any built-in functions that directly generate permutations.
**Input:**
- A single string `s` (1 ≤ |s| ≤ 8), consisting of lowercase Eng... | def generate_permutations(s):
"""
Generate all unique permutations of a given string s in lexicographical order.
:param s: A string consisting of lowercase English letters.
:return: A list of strings, each representing a unique permutation of s.
"""
def backtrack(start, end):
if sta... | [
"assert generate_permutations(\"a\") == [\"a\"]",
"assert generate_permutations(\"ab\") == [\"ab\", \"ba\"]",
"assert generate_permutations(\"abc\") == [\"abc\", \"acb\", \"bac\", \"bca\", \"cab\", \"cba\"]",
"assert generate_permutations(\"aabb\") == [\"aabb\", \"abab\", \"abba\", \"baab\", \"baba\", \"bbaa\... | generate_permutations | def generate_permutations(s): | 0.7 | generic |
e44602d306b85ef35140aa14e313326b | You are given an integer `number`. Your task is to determine whether this number is a palindrome. A number is considered a palindrome if it reads the same backward as forward. For example, 121, 12321, and 1221 are palindromes, whereas 123 is not.
**Input:**
- An integer `number` (0 ≤ number ≤ 10^9)
**Output:**
- Retu... | def is_palindrome_number(number):
"""
Determines if the given integer is a palindrome.
Args:
number (int): The integer to check.
Returns:
bool: True if the number is a palindrome, False otherwise.
"""
str_number = str(number)
return str_number == str_number[::-1] | [
"assert is_palindrome_number(121) == True",
"assert is_palindrome_number(12321) == True",
"assert is_palindrome_number(1221) == True",
"assert is_palindrome_number(123) == False",
"assert is_palindrome_number(0) == True",
"assert is_palindrome_number(10) == False",
"assert is_palindrome_number(1001) == ... | is_palindrome_number | def is_palindrome_number(number): | 1 | generic |
0be10a3545264a2640b0648c26780740 | You are tasked with developing a function for a non-profit organization that generates thank-you letters for different types of donations. The organization sends out three types of letters: individual, annual, and sustaining donations. Each letter has a specific format:
- **Individual Donation Letter:**
- Header: `S... | from datetime import datetime
def generate_letter(donation_type, donor_info):
"""
Generates a thank-you letter based on the type of donation and donor information.
Parameters:
donation_type (str): The type of donation ('individual', 'annual', or 'sustaining').
donor_info (dict): A dictionary conta... | [
"assert generate_letter('individual', {'name': 'John Doe', 'amount': '100'}) == f\"Seattle, WA {datetime.now().strftime('%B %d, %Y')}\\nDear John Doe,\\nThank you for your very kind donation of $100. It will be put to very good use.\\nSincerely,\\n-The Team\"",
"assert generate_letter('annual', {'name': 'Jane Smi... | generate_letter | def generate_letter(donation_type, donor_info): | 1 | generic |
5eb7c39df5cca0f680dfc7438067af98 | You are tasked with writing a Python script that processes a directory and its subdirectories to identify all `.csv` files. For each `.csv` file, your script should determine and output the number of rows and columns. Your script must handle potential errors gracefully, such as the directory not existing or `.csv` file... | import os
import csv
def get_csv_info(directory):
"""
Processes a directory and its subdirectories to identify all .csv files.
For each .csv file, prints the number of rows and columns.
Handles errors such as directory not existing or malformed .csv files.
:param directory: Path to the directory t... | [
"assert get_csv_info(\"/nonexistent_directory\") is None",
"assert get_csv_info(\"/path/to/directory/with/no/csv\") is None",
"assert get_csv_info(\"/path/to/directory/with/single/csv\") is None",
"assert get_csv_info(\"/path/to/directory/with/multiple/csv/files\") is None",
"assert get_csv_info(\"/path/to/... | get_csv_info | def get_csv_info(directory): | 1 | generic |
309528d81ec004742bb5f82c6ac9b21d | You are given a string `s` that contains multiple sentences. Your task is to implement a function `split_string_into_sentences(s)` that splits the string into individual sentences based on punctuation marks such as period (.), exclamation mark (!), and question mark (?). The function should ignore any spaces or punctua... | import re
def split_string_into_sentences(s):
"""
Splits a given string into sentences based on punctuation marks '.', '!', and '?'.
Ignores any spaces or punctuation marks that come immediately after these punctuation marks.
:param s: Input string containing multiple sentences.
:return: List ... | [
"assert split_string_into_sentences(\"Hello world! How are you doing today? I hope you're well. Alright then.\") == ['Hello world', 'How are you doing today', \"I hope you're well\", 'Alright then']",
"assert split_string_into_sentences(\"This is a test. This is only a test.\") == ['This is a test', 'This is only... | split_string_into_sentences | def split_string_into_sentences(s): | 1 | generic |
6271bfded21859e48b646e6ab32cf553 | You are given a string `s` and a target word `target`. Your task is to implement a function `find_target_indices(s, target)` that returns a list of starting indices of all occurrences of the target word within the string `s`. The search should be case-insensitive and consider only complete words. The input string `s` d... | def find_target_indices(s, target):
"""
Returns a list of starting indices of all occurrences of the target word within the string s.
:param s: The input string to search within.
:param target: The target word to find.
:return: A list of starting indices of all occurrences of the target word.
... | [
"assert find_target_indices(\"hello world\", \"world\") == [1]",
"assert find_target_indices(\"hello world\", \"hello\") == [0]",
"assert find_target_indices(\"hello world\", \"test\") == []",
"assert find_target_indices(\"the quick brown fox jumps over the lazy dog\", \"the\") == [0, 6]",
"assert find_targ... | find_target_indices | def find_target_indices(s, target): | 1 | generic |
17d3811545f72b19941b994de8cb96cb | You are tasked with writing a Python script that reads a JSON configuration file named `config.json` and extracts specific settings. The JSON file contains the following keys: `server_address`, `port`, `use_ssl`, and `timeout`. Your script should handle cases where some keys might be missing by providing a default valu... | import json
def read_config(file_name):
"""
Reads a JSON configuration file and extracts specific settings.
Handles missing keys by providing a default value of "Not specified".
Gracefully handles file not found and JSON decoding errors.
:param file_name: The name of the JSON configuration file.
... | [
"assert read_config('non_existent_file.json') == None",
"assert read_config('invalid_json_file.json') == None",
"assert read_config('config_with_missing_keys.json') == None",
"assert read_config('config_with_all_keys.json') == None",
"assert read_config('config_with_empty_values.json') == None",
"assert r... | read_config | def read_config(file_name): | 1 | generic |
704b2f7a891cbab827b4e0fec624b1d8 | You are given a list containing various types of objects. Your task is to implement a function `total_memory_usage` that computes the total memory usage of all objects in the list in bytes. The function should handle different data types such as integers, strings, lists, and dictionaries.
**Input:**
- A list of objec... | import sys
def total_memory_usage(obj_list):
"""
Calculate the total memory usage of all the objects stored in the given list.
Parameters:
obj_list (list): A list of objects whose memory usage needs to be calculated.
Returns:
int: The total memory usage of the objects in bytes.
""... | [
"assert total_memory_usage([]) == 0",
"assert total_memory_usage([1]) == sys.getsizeof(1)",
"assert total_memory_usage(['a']) == sys.getsizeof('a')",
"assert total_memory_usage([1, 'a']) == sys.getsizeof(1) + sys.getsizeof('a')",
"assert total_memory_usage([[], {}]) == sys.getsizeof([]) + sys.getsizeof({})"... | total_memory_usage | def total_memory_usage(obj_list): | 1 | generic |
19afdbd54676397f0509e62199b6abcd | You are given a list of integers `numbers`. Your task is to implement a function `remove_duplicates` that returns a new list containing only the unique elements from the original list, preserving the order of their first appearance.
**Input:**
- A list of integers `numbers` (1 ≤ len(numbers) ≤ 10^5), where each intege... | def remove_duplicates(numbers):
"""
Returns a new list containing only the unique elements from the original list,
preserving the order of their first appearance.
:param numbers: List of integers
:return: List of unique integers in the order of their first appearance
"""
seen = set()
un... | [
"assert remove_duplicates([1, 2, 2, 3, 4, 4, 5]) == [1, 2, 3, 4, 5]",
"assert remove_duplicates([10, 20, 20, 10, 30]) == [10, 20, 30]",
"assert remove_duplicates([1, 1, 1, 1, 1]) == [1]",
"assert remove_duplicates([]) == []",
"assert remove_duplicates([7, 8, 9]) == [7, 8, 9]",
"assert remove_duplicates([5... | remove_duplicates | def remove_duplicates(numbers): | 1 | generic |
93a441be39b1d1703893a91f7e4ebc3d | In a strategic game, two players take turns removing stones from a pile. Initially, there are `n` stones in the pile. During each turn, a player can remove a number of stones that is a power of 2 (i.e., 1, 2, 4, 8, ...). The player who removes the last stone wins. Both players play optimally. Determine the optimal move... | def compute_grundy_numbers(max_n):
"""
Computes the Grundy numbers for the game up to max_n stones.
:param max_n: The maximum number of stones to compute Grundy numbers for.
:return: A list of Grundy numbers up to max_n.
"""
grundy = [0] * (max_n + 1)
for i in range(1, max_n + 1):
... | [
"assert find_optimal_move(1) == 1",
"assert find_optimal_move(2) == 2",
"assert find_optimal_move(3) == 1",
"assert find_optimal_move(4) == 4",
"assert find_optimal_move(5) == 1",
"assert find_optimal_move(6) == 2",
"assert find_optimal_move(7) == 1",
"assert find_optimal_move(8) == 8",
"assert find... | find_optimal_move | def find_optimal_move(n): | 0.4 | generic |
898194bf1d8e9db09ebc66a8fdec84b4 | You are given a 3D grid defined by its bounds `(mx, Mx, my, My, mz, Mz)`, where `mx < Mx`, `my < My`, and `mz < Mz`. Each cell in the grid is identified by its coordinates `(x, y, z)`. Your task is to implement a function `find_adjacent_cells(bounds, position, query_cell_value)` that identifies all adjacent cells to a ... | def find_adjacent_cells(bounds, position, query_cell_value):
"""
Finds all adjacent cells to the given position within the grid boundaries
that contain a non-zero value.
:param bounds: A tuple (mx, Mx, my, My, mz, Mz) defining the grid boundaries.
:param position: A tuple (x, y, z) representing the... | [
"assert find_adjacent_cells((0, 3, 0, 3, 0, 3), (1, 1, 1), lambda bounds, pos: 1) == [(0, 0, 0), (0, 0, 1), (0, 0, 2), (0, 1, 0), (0, 1, 1), (0, 1, 2), (0, 2, 0), (0, 2, 1), (0, 2, 2), (1, 0, 0), (1, 0, 1), (1, 0, 2), (1, 1, 0), (1, 1, 2), (1, 2, 0), (1, 2, 1), (1, 2, 2), (2, 0, 0), (2, 0, 1), (2, 0, 2), (2, 1, 0),... | find_adjacent_cells | def find_adjacent_cells(bounds, position, query_cell_value): | 0.9 | generic |
b3790434e7feb3885bb2552566ea7d03 | You are given a list of integers `lst`. Your task is to implement a function `remove_duplicates(lst)` that returns a new list with all duplicate elements removed, while maintaining the original order of the elements. The input list may be empty and will only contain integers.
**Sample Input:**
```
[1, 2, 2, 3, 4, 4, 5... | def remove_duplicates(lst):
"""
Removes all duplicate elements from the given list lst and returns a new list
with duplicates removed, preserving the original order of elements.
:param lst: List of integers
:return: New list with duplicates removed
"""
seen = set()
result = []
f... | [
"assert remove_duplicates([1, 2, 2, 3, 4, 4, 5]) == [1, 2, 3, 4, 5]",
"assert remove_duplicates([1, 1, 1, 1, 1]) == [1]",
"assert remove_duplicates([]) == []",
"assert remove_duplicates([10, 20, 30, 40, 50]) == [10, 20, 30, 40, 50]",
"assert remove_duplicates([5, 4, 3, 2, 1, 1, 2, 3, 4, 5]) == [5, 4, 3, 2, ... | remove_duplicates | def remove_duplicates(lst): | 1 | generic |
8ec9d1aa4000b1dd5f49ac653a58b6a1 | You are given two sorted lists, `list1` and `list2`, consisting of integers and/or floating-point numbers. Your task is to implement a function `merge_sorted_lists` that merges these two lists into a single sorted list. The function should operate with a time complexity of O(n + m), where n and m are the lengths of `li... | def merge_sorted_lists(list1, list2):
"""
Merges two sorted lists into a single sorted list.
Parameters:
list1 (list): The first sorted list.
list2 (list): The second sorted list.
Returns:
list: A merged and sorted list containing all elements from list1 and list2.
"""
merg... | [
"assert merge_sorted_lists([1, 3, 5], [2, 4, 6]) == [1, 2, 3, 4, 5, 6]",
"assert merge_sorted_lists([], [1, 2, 3]) == [1, 2, 3]",
"assert merge_sorted_lists([1, 2, 3], []) == [1, 2, 3]",
"assert merge_sorted_lists([], []) == []",
"assert merge_sorted_lists([1.5, 2.5, 3.5], [1.2, 2.2, 3.2]) == [1.2, 1.5, 2.2... | merge_sorted_lists | def merge_sorted_lists(list1, list2): | 1 | generic |
c7280524a0d8cf8beffa947f31b4ab8f | You are tasked with implementing a function to find all prime numbers up to a given integer `n` using the Sieve of Eratosthenes algorithm. Your function should return a list of all prime numbers less than or equal to `n`.
**Input:**
- An integer `n` (1 ≤ n ≤ 10^6)
**Output:**
- A list of integers representing all pri... | def find_primes_up_to_n(n):
"""
Returns a list of all prime numbers less than or equal to n using the Sieve of Eratosthenes algorithm.
:param n: An integer representing the upper limit.
:return: A list of prime numbers less than or equal to n.
"""
if n < 2:
return []
is_prime =... | [
"assert find_primes_up_to_n(10) == [2, 3, 5, 7]",
"assert find_primes_up_to_n(1) == []",
"assert find_primes_up_to_n(2) == [2]",
"assert find_primes_up_to_n(19) == [2, 3, 5, 7, 11, 13, 17, 19]",
"assert find_primes_up_to_n(0) == []",
"assert find_primes_up_to_n(30) == [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]"... | find_primes_up_to_n | def find_primes_up_to_n(n): | 1 | generic |
34a3730599b238372ff020a976594b46 | You are given an undirected graph `G` with `N` nodes and `M` edges. The graph is represented as an adjacency list, where each node is an integer from `0` to `N-1`, and each edge is a pair of integers. Your task is to determine whether the graph contains a cycle. Write a function `has_cycle` that returns `True` if the g... | def has_cycle(G):
"""
Determines if the given undirected graph contains a cycle.
:param G: List of lists representing the adjacency list of the graph.
:return: True if the graph contains a cycle, False otherwise.
"""
def dfs(node, parent):
visited[node] = True
in_stack[node] = T... | [
"assert has_cycle([[], [2], [1]]) == False",
"assert has_cycle([[1], [2], [0]]) == True",
"assert has_cycle([[1, 2], [2], []]) == True",
"assert has_cycle([[], [], []]) == False",
"assert has_cycle([[1], [2], [3], [4], [0]]) == True",
"assert has_cycle([[1], [2], [3], [4], [5], [6], [7], [8], [9], [5]]) =... | has_cycle | def has_cycle(G): | 0.6 | generic |
d01db553f78e6c135f2e43232b2aa31e | You are given a list of integers `nums`. Your task is to implement a function `find_prime_factors(nums)` that returns a list of lists, where each sublist contains the prime factors of the corresponding integer in `nums`. A prime factor is a factor that is a prime number.
**Input:**
- A list of integers `nums` (1 ≤ len... | def find_prime_factors(nums):
"""
Returns a list of lists, where each sublist contains the prime factors of the corresponding integer in nums.
:param nums: List of integers
:return: List of lists containing prime factors
"""
def prime_factors(n):
"""
Returns a list of prime ... | [
"assert find_prime_factors([12, 15, 21]) == [[2, 2, 3], [3, 5], [3, 7]]",
"assert find_prime_factors([1, 2, 3]) == [[], [2], [3]]",
"assert find_prime_factors([4, 6, 8]) == [[2, 2], [2, 3], [2, 2, 2]]",
"assert find_prime_factors([9, 10, 11]) == [[3, 3], [2, 5], [11]]",
"assert find_prime_factors([13, 14, 1... | find_prime_factors | def find_prime_factors(nums): | 1 | generic |
6ad9241ee298572c9c5b1f5fd1a4f834 | You are given a string `text`. Your task is to implement a function `check_palindrome` that determines whether the string is a palindrome, considering only alphanumeric characters and ignoring case differences. A string is a palindrome if it reads the same backward as forward.
**Input:**
- A single string `text` (1 ≤ ... | def check_palindrome(text):
"""
Determines if the given string is a palindrome, considering only alphanumeric characters and ignoring case differences.
:param text: The input string to check.
:return: True if the string is a palindrome, False otherwise.
"""
# Remove non-alphanumeric charact... | [
"assert check_palindrome(\"A man, a plan, a canal, Panama\") == True",
"assert check_palindrome(\"racecar\") == True",
"assert check_palindrome(\"No lemon, no melon\") == True",
"assert check_palindrome(\"Was it a car or a cat I saw?\") == True",
"assert check_palindrome(\"Hello, World!\") == False",
"ass... | check_palindrome | def check_palindrome(text): | 1 | generic |
8bb3d567ab7a514ba38f2498fd3aea13 | You are given a string `s`. Your task is to write a function `reverse_vowels` that returns a new string where the order of the vowels ('a', 'e', 'i', 'o', 'u', both uppercase and lowercase) is reversed, while the order of all other characters remains unchanged.
**Constraints:**
- The length of the string `s` is betwe... | def reverse_vowels(s: str) -> str:
"""
Reverses the order of vowels in the given string while keeping other characters in their original positions.
:param s: Input string
:return: New string with vowels reversed
"""
vowels = "aeiouAEIOU"
s_list = list(s)
i, j = 0, len(s) - 1
wh... | [
"assert reverse_vowels(\"Hello, World!\") == \"Hollo, Werld!\"",
"assert reverse_vowels(\"Programming\") == \"Prigrammong\"",
"assert reverse_vowels(\"Python\") == \"Pythpn\"",
"assert reverse_vowels(\"AEIOU\") == \"UOIEA\"",
"assert reverse_vowels(\"aeiou\") == \"uoiea\"",
"assert reverse_vowels(\"abcdef... | reverse_vowels | def reverse_vowels(s: str) -> str: | 0.7 | generic |
7c6229706975bcbc5460293cd8974b62 | You are given a convolutional layer in a neural network with the following parameters: the number of input channels (`num_in`), the height and width of the input (`height_in`, `width_in`), the kernel size (`kernel_size`), the stride (`stride`), and the asymmetric padding (`padding_top`, `padding_bottom`, `padding_left`... | def calculate_output_shape(num_in, num_out, height_in, width_in, kernel_size, stride,
padding_top, padding_bottom, padding_left, padding_right):
"""
Calculate the shape of the output tensor after a convolution operation.
Parameters:
num_in (int): Number of input channels.
... | [
"assert calculate_output_shape(1, 32, 32, 32, 3, 1, 1, 1, 1, 1) == [32, 32, 32]",
"assert calculate_output_shape(3, 64, 224, 224, 3, 1, 1, 1, 1, 1) == [64, 224, 224]",
"assert calculate_output_shape(3, 64, 224, 224, 5, 2, 2, 2, 2, 2) == [64, 112, 112]",
"assert calculate_output_shape(1, 1, 28, 28, 2, 2, 0, 0,... | calculate_output_shape | def calculate_output_shape(num_in, num_out, height_in, width_in, kernel_size, stride,
padding_top, padding_bottom, padding_left, padding_right): | 1 | generic |
a24b6160f79a9d7022f577bbc5e21a17 | You are given a positive integer `n` greater than 1. Your task is to implement a function `find_largest_prime(n)` that returns the largest prime number less than or equal to `n`.
**Input:**
- A single integer `n` (2 ≤ n ≤ 10^6)
**Output:**
- A single integer representing the largest prime number less than or equal t... | def find_largest_prime(n):
"""
Finds the largest prime number less than or equal to a given number n.
Parameters:
n (int): A positive integer greater than 1.
Returns:
int: The largest prime number less than or equal to n.
"""
def is_prime(num):
"""
Checks if a number is... | [
"assert find_largest_prime(10) == 7",
"assert find_largest_prime(20) == 19",
"assert find_largest_prime(2) == 2",
"assert find_largest_prime(17) == 17",
"assert find_largest_prime(1) == None",
"assert find_largest_prime(100) == 97",
"assert find_largest_prime(30) == 29",
"assert find_largest_prime(50)... | find_largest_prime | def find_largest_prime(n): | 1 | generic |
8a4befdf818932808e35e9a76fc8ac84 | You are given a list of integers. Your task is to write a Python function that returns the two largest distinct numbers in the list. If the list contains fewer than two distinct numbers, the function should raise a `ValueError`.
**Input:**
- A list of integers `numbers` (1 ≤ len(numbers) ≤ 10^5), where each integer is... | def find_two_largest_numbers(numbers):
"""
Returns the two largest distinct numbers in the list.
:param numbers: List of integers
:return: Tuple of two largest distinct integers
:raises ValueError: If the list contains fewer than two distinct numbers
"""
if len(numbers) < 2:
rai... | [
"assert find_two_largest_numbers([1, 2]) == (2, 1)",
"assert find_two_largest_numbers([10, 20, 30, 40, 50]) == (50, 40)",
"assert find_two_largest_numbers([50, 40, 30, 20, 10]) == (50, 40)",
"assert find_two_largest_numbers([100, 100, 100, 100]) == (100, 100)",
"assert find_two_largest_numbers([-1, -2, -3, ... | find_two_largest_numbers | def find_two_largest_numbers(numbers): | 0.8 | algorithmic |
3c30e4606cc5da385d0f9a8370dbba15 | You are given a list of integers. Your task is to implement a function `find_min_max` that takes this list as input and returns a tuple containing the minimum and maximum values in the list. You are not allowed to use any built-in functions to determine the minimum or maximum values.
**Input:**
- A list of integers `n... | def find_min_max(numbers):
"""
Finds the minimum and maximum values in a list of integers without using built-in functions.
Parameters:
numbers (list): A list of integers.
Returns:
tuple: A tuple containing the minimum and maximum values in the list.
"""
# Initialize the first element ... | [
"assert find_min_max([3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]) == (1, 9)",
"assert find_min_max([100, 200, 300, 400, 500]) == (100, 500)",
"assert find_min_max([-10, -20, -30, -40, -50]) == (-50, -10)",
"assert find_min_max([0, 0, 0, 0, 0]) == (0, 0)",
"assert find_min_max([42]) == (42, 42)",
"assert find_min_ma... | find_min_max | def find_min_max(numbers): | 1 | generic |
7e564d03573b7c122cdbd74ea23fd68d | You are given a string that potentially contains a JSON array. The string may have leading or trailing whitespace and may not be properly formatted. Your task is to implement a function `parse_json_array` that processes the string and returns the corresponding Python list. If the string does not represent a valid JSON ... | import json
def parse_json_array(json_string):
"""
Parses a string containing a JSON array and returns the corresponding Python list.
If the string is not a valid JSON array, returns an empty list.
:param json_string: A string that may contain a JSON array.
:return: A Python list if the string... | [
"assert parse_json_array(' [1, 2, 3, 4, 5] ') == [1, 2, 3, 4, 5]",
"assert parse_json_array('{\"key\": \"value\"}') == []",
"assert parse_json_array(' [1, 2, \"three\", 4, 5] ') == [1, 2, \"three\", 4, 5]",
"assert parse_json_array('') == []",
"assert parse_json_array(' ') == []",
"assert parse_json_arr... | parse_json_array | def parse_json_array(json_string): | 1 | generic |
0d3b51ebed53b1bd2d80e63a6ffb652f | You are given a thermostat with a current temperature and a desired temperature range defined by a minimum and maximum temperature. The thermostat must adjust the current temperature to ensure it stays within the specified range. If the current temperature is below the minimum, it should be incremented in steps of 0.5 ... | def adjust_thermostat(current_temp, min_temp, max_temp):
"""
Adjusts the current temperature to ensure it stays within the specified range.
Parameters:
current_temp (float): The current temperature.
min_temp (float): The minimum temperature of the range.
max_temp (float): The maximum temper... | [
"assert adjust_thermostat(18.0, 20.0, 25.0) == 20.0",
"assert adjust_thermostat(22.0, 20.0, 25.0) == 22.0",
"assert adjust_thermostat(26.0, 20.0, 25.0) == 25.0",
"assert adjust_thermostat(19.5, 20.0, 25.0) == 20.0",
"assert adjust_thermostat(25.5, 20.0, 25.0) == 25.0",
"assert adjust_thermostat(15.0, 15.0... | adjust_thermostat | def adjust_thermostat(current_temp, min_temp, max_temp): | 1 | generic |
5933329b7d9d65742c8aecced1b09610 | You are tasked with implementing a function to generate all prime numbers up to a given integer `n` (inclusive) using the Sieve of Eratosthenes algorithm. Your function should return a list of these prime numbers. If `n` is less than 2, return an empty list.
**Input:**
- An integer `n` (0 ≤ n ≤ 10^6)
**Output:**
- A ... | def generate_primes(n):
"""Generate a list of prime numbers up to n (inclusive) using the Sieve of Eratosthenes algorithm.
Args:
n (int): The upper limit of the range to generate prime numbers for.
Returns:
list: A list of prime numbers up to n.
"""
if n < 2:
return... | [
"assert generate_primes(10) == [2, 3, 5, 7]",
"assert generate_primes(20) == [2, 3, 5, 7, 11, 13, 17, 19]",
"assert generate_primes(1) == []",
"assert generate_primes(2) == [2]",
"assert generate_primes(0) == []",
"assert generate_primes(30) == [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]",
"assert generate_pri... | generate_primes | def generate_primes(n): | 1 | generic |
ab4eac00663efcb04aff51f59063e004 | In the realm of quantum mechanics, the energy of an electron in a hydrogen atom can be determined using the formula \( E = -\frac{13.6}{n^2} \), where \( n \) is the principal quantum number and the energy is measured in electron volts (eV). Your task is to implement a function that computes this energy given the princ... | def calculate_energy(n):
"""
Calculate the energy of an electron in a hydrogen atom given the principal quantum number.
Parameters:
n (int): The principal quantum number (1 ≤ n ≤ 1000).
Returns:
float: The energy of the electron in electron volts (eV), rounded to five decimal places.
"""
... | [
"assert calculate_energy(1) == -13.6",
"assert calculate_energy(2) == -3.4",
"assert calculate_energy(3) == -1.51111",
"assert calculate_energy(4) == -0.85",
"assert calculate_energy(5) == -0.544",
"assert calculate_energy(10) == -0.136",
"assert calculate_energy(100) == -0.00136",
"assert calculate_e... | calculate_energy | def calculate_energy(n): | 1 | generic |
cc79836dc6ad3ce09b75e5c538a7d0ae | You are given an array of integers `arr` and a positive integer `k`. Your task is to implement a function `find_k_largest_elements(arr, k)` that returns a list containing any `k` largest elements from the array `arr`. The order of elements in the output list does not matter.
**Input:**
- The first argument is an array... | def find_k_largest_elements(arr, k):
"""
Returns a list of k largest elements from the array arr.
:param arr: List[int] - The input array of integers.
:param k: int - The number of largest elements to return.
:return: List[int] - A list containing any k largest elements from arr.
"""
re... | [
"assert find_k_largest_elements([3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5], 3) == [9, 6, 5]",
"assert find_k_largest_elements([10, 7, 11, 5, 2, 13, 1], 2) == [13, 11]",
"assert find_k_largest_elements([1, 2, 3, 4, 5], 5) == [5, 4, 3, 2, 1]",
"assert find_k_largest_elements([5, 5, 5, 5, 5], 3) == [5, 5, 5]",
"assert ... | find_k_largest_elements | def find_k_largest_elements(arr, k): | 0.9 | generic |
4ab5639f9c2276727548b7dc3a721732 | You are given a temperature in Fahrenheit and your task is to write a function `convert_to_celsius(fahrenheit)` that converts this temperature to Celsius using the formula `(Fahrenheit - 32) * 5/9`. Your function should return the temperature in Celsius as a floating-point number.
**Sample Input:**
```
68
```
**Sampl... | def convert_to_celsius(fahrenheit):
"""
Convert a temperature from Fahrenheit to Celsius.
Parameters:
fahrenheit (float): Temperature in Fahrenheit.
Returns:
float: Temperature in Celsius.
"""
celsius = (fahrenheit - 32) * 5 / 9
return celsius
# Example usage:
# celsius_temp = con... | [
"assert convert_to_celsius(32) == 0.0",
"assert convert_to_celsius(212) == 100.0",
"assert convert_to_celsius(98.6) == 37.0",
"assert convert_to_celsius(-40) == -40.0",
"assert convert_to_celsius(0) == -17.77777777777778",
"assert convert_to_celsius(100) == 37.77777777777778",
"assert convert_to_celsius... | convert_to_celsius | def convert_to_celsius(fahrenheit): | 1 | generic |
f382d93fd54c35e65d889499f8bdcb3a | You are given a positive integer `n`. Your task is to compute the factorial of `n` efficiently. The factorial of a non-negative integer `n` is the product of all positive integers less than or equal to `n`. For example, the factorial of 5 is `5 * 4 * 3 * 2 * 1 = 120`.
To optimize the performance, implement a memoizat... | def memoize(f):
"""
Decorator to memoize a function's results to avoid redundant calculations.
"""
memo = {}
def helper(x):
if x not in memo:
memo[x] = f(x)
return memo[x]
return helper
@memoize
def factorial(n):
"""
Compute the factorial of a giv... | [
"assert factorial(0) == 1",
"assert factorial(1) == 1",
"assert factorial(2) == 2",
"assert factorial(3) == 6",
"assert factorial(4) == 24",
"assert factorial(5) == 120",
"assert factorial(6) == 720",
"assert factorial(10) == 3628800",
"assert factorial(12) == 479001600",
"assert factorial(20) == ... | factorial | def factorial(n): | 1 | generic |
bf09d66c94ea15e4627daa8137bce06c | You are given a list of integers `data` and an integer `window_size`. Your task is to implement a function `calculate_moving_average(data, window_size)` that computes the moving average of the list using a sliding window of the specified size. The function should return a list of moving averages, where each element is ... | def calculate_moving_average(data, window_size):
"""
Calculate the moving average of a list of numbers using a sliding window.
:param data: List of integers representing the data.
:param window_size: Integer representing the size of the sliding window.
:return: List of floating-point numbers repres... | [
"assert calculate_moving_average([1, 2, 3, 4, 5], 2) == [1.5, 2.5, 3.5, 4.5]",
"assert calculate_moving_average([10, 20, 30, 40, 50], 3) == [20.0, 30.0, 40.0]",
"assert calculate_moving_average([5, 10, 15, 20, 25], 5) == [15.0]",
"assert calculate_moving_average([1, 2, 3], 4) == []",
"assert calculate_movin... | calculate_moving_average | def calculate_moving_average(data, window_size): | 1 | generic |
37f38016cbdb8a93f69729e897f47a78 | You are tasked with developing a function `find_keywords` for a text analysis tool. The function should process a given string `text` and return a list of the top 5 most frequent words. Words should be converted to lowercase, and all punctuation should be removed. The function should handle multiple sentences and varyi... | import re
from collections import Counter
def find_keywords(text):
"""
Extracts the top 5 most frequent words from the given text.
Parameters:
text (str): The input text from which to extract keywords.
Returns:
list: A list of the top 5 most frequent words in lowercase.
"""
# ... | [
"assert find_keywords(\"Hello, world! Hello, everyone. Welcome to the world of programming.\") == ['hello', 'world', 'welcome', 'everyone', 'programming']",
"assert find_keywords(\"Python is great. Python is fun. Python is powerful.\") == ['python', 'is', 'great', 'fun', 'powerful']",
"assert find_keywords(\"Da... | find_keywords | def find_keywords(text): | 0.8 | generic |
c5c667f76ad9a280a4d1cda2d19bd6fc | You are given a list of sessions, each represented as a tuple of two strings indicating the start and end times in the format "HH:MM:SS". Your task is to calculate the total time spent on a website by merging overlapping sessions and summing their durations. Implement the function `calculate_total_time(sessions)` witho... | def calculate_total_time(sessions):
"""
Calculate the total time spent on a website by merging overlapping sessions.
:param sessions: List of tuples, where each tuple contains two strings representing the start and end times of a session.
:return: A string representing the total time spent on the websi... | [
"assert calculate_total_time([(\"01:00:00\", \"02:00:00\"), (\"02:00:00\", \"03:00:00\")]) == \"2 hours 0 minutes 0 seconds\"",
"assert calculate_total_time([(\"09:00:00\", \"10:00:00\"), (\"10:00:00\", \"11:00:00\"), (\"11:00:00\", \"12:00:00\")]) == \"3 hours 0 minutes 0 seconds\"",
"assert calculate_total_ti... | calculate_total_time | def calculate_total_time(sessions): | 0.9 | generic |
148946f78813a6d6c5c75f74fa09f3cb | You are given a list of integers `numbers` representing the scores of students in a class. Your task is to implement a function `calculate_statistics` that computes the mean, median, and mode of the scores. The function should return a dictionary with the keys `"mean"`, `"median"`, and `"mode"` corresponding to the com... | from collections import Counter
from statistics import mean, median, mode
def calculate_statistics(numbers):
"""
Computes the mean, median, and mode of a list of integers.
Parameters:
numbers (list of int): A list of integers representing scores.
Returns:
dict: A dictionary with keys 'mean', ... | [
"assert calculate_statistics([85, 90, 78, 85, 92]) == {\"mean\": 86.0, \"median\": 85.0, \"mode\": 85}",
"assert calculate_statistics([100, 100, 100]) == {\"mean\": 100.0, \"median\": 100.0, \"mode\": 100}",
"assert calculate_statistics([50, 60, 70, 80, 90]) == {\"mean\": 70.0, \"median\": 70.0, \"mode\": 50}",... | calculate_statistics | def calculate_statistics(numbers): | 1 | generic |
046e57a8de193158b3f4011cdd65b3e7 | You are required to design a hash function for a custom string-to-integer dictionary. The hash function should map strings to integers in a way that minimizes collisions. The function must satisfy the following criteria:
- **Deterministic**: The same input string must always produce the same output integer.
- **Versat... | def custom_hash(s):
"""
Computes a hash value for a given string using a polynomial rolling hash function.
Parameters:
s (str): The input string to hash.
Returns:
int: The hash value of the string, guaranteed to be a 32-bit signed integer.
"""
base = 31
modulo = 2**31 - 1
... | [
"assert custom_hash(\"hello\") == custom_hash(\"hello\")",
"assert custom_hash(\"world\") == custom_hash(\"world\")",
"assert custom_hash(\"hello\") != custom_hash(\"world\")",
"assert custom_hash(\"a\") == custom_hash(\"a\")",
"assert custom_hash(\"!@#$%^&*()\") == custom_hash(\"!@#$%^&*()\")",
"assert c... | custom_hash | def custom_hash(s): | 1 | generic |
467e1cd93f4432879eac1e00d5378b20 | You are given a non-empty array of integers, `numbers`. Your task is to construct a new array, `result`, of the same length as `numbers` such that `result[i]` is the product of the absolute values of the maximum and minimum elements in the subarray `numbers[0..i]` (both inclusive).
**Constraints:**
- The length of `nu... | def product_of_extremes(numbers):
"""
Constructs a new array where each element at index i is the product of the absolute values
of the maximum and minimum elements in the subarray numbers[0..i].
:param numbers: List[int] - A non-empty list of integers.
:return: List[int] - A list of integers repre... | [
"assert product_of_extremes([2, -3, 4, -5]) == [6, 6, 12, 20]",
"assert product_of_extremes([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]",
"assert product_of_extremes([-1, -2, -3, -4, -5]) == [1, 2, 3, 4, 5]",
"assert product_of_extremes([5, 4, 3, 2, 1]) == [5, 8, 9, 8, 5]",
"assert product_of_extremes([-5, -4, -3, ... | product_of_extremes | def product_of_extremes(numbers): | 0.5 | generic |
e90d9fbd176e69e2ab056cc9750ee48d | You are given a dataset consisting of multiple data points. Each data point is represented as a list with three elements: a timestamp in the format "YYYY-MM-DD HH:MM:SS", a numeric value, and an altitude. Your task is to filter this dataset based on the altitude criteria and return a new list containing only the timest... | def is_prime(n):
"""Check if a number is a prime number."""
if n <= 1:
return False
if n == 2:
return True
if n % 2 == 0:
return False
for i in range(3, int(n**0.5) + 1, 2):
if n % i == 0:
return False
return True
def filter_by_altitude(data_points):
... | [
"assert filter_by_altitude([[\"2023-01-01 12:00:00\", 10.5, 29]]) == []",
"assert filter_by_altitude([[\"2023-01-01 12:01:00\", 11.5, 31]]) == [(\"2023-01-01 12:01:00\", 11.5)]",
"assert filter_by_altitude([[\"2023-01-01 12:02:00\", 12.5, 37]]) == [(\"2023-01-01 12:02:00\", 12.5)]",
"assert filter_by_altitude... | filter_by_altitude | def filter_by_altitude(data_points): | 1 | generic |
4964f369c1573e937316f93dd19cabc0 | You are given a list of non-empty strings `words`. Your task is to implement a function `longest_common_prefix` that determines the longest common prefix shared by all strings in the list. If no common prefix exists, the function should return an empty string.
**Constraints:**
- The list `words` contains at least one ... | def longest_common_prefix(words):
"""
Finds the longest common prefix among all the words in the list.
:param words: List of non-empty strings
:return: Longest common prefix string, or an empty string if no common prefix exists
"""
# Take the first word as the reference
prefix = words[0... | [
"assert longest_common_prefix([\"flower\", \"flow\", \"flight\"]) == \"fl\"",
"assert longest_common_prefix([\"dog\", \"racecar\", \"car\"]) == \"\"",
"assert longest_common_prefix([\"prefix\", \"preposition\", \"prevent\"]) == \"pre\"",
"assert longest_common_prefix([\"apple\", \"application\", \"appetite\"]... | longest_common_prefix | def longest_common_prefix(words): | 1 | generic |
c096f91b9436cbb4ffb1edd865066524 | You are given a sentence as a string. Your task is to implement a function `find_duplicate_words` that identifies and returns a list of duplicate words in the sentence. The function should treat words in a case-insensitive manner, meaning 'Word' and 'word' should be considered the same. Additionally, punctuation marks ... | import re
from collections import Counter
def find_duplicate_words(sentence):
"""
Identifies and returns a list of duplicate words and punctuation in a given sentence.
Parameters:
sentence (str): The input sentence containing words and punctuation.
Returns:
list: A list of duplicate w... | [
"assert find_duplicate_words(\"Hello, world! Hello, universe. Hello, world?\") == ['hello', 'world']",
"assert find_duplicate_words(\"This is a test. This test is only a test.\") == ['this', 'is', 'a', 'test']",
"assert find_duplicate_words(\"No duplicates here.\") == []",
"assert find_duplicate_words(\"A man... | find_duplicate_words | def find_duplicate_words(sentence): | 0.6 | generic |
fe995e4ea5901c6f8c38450efbc154f6 | You are given an array of integers `numbers` and an integer `target_sum`. Your task is to determine if there are any two distinct numbers in the array that add up to `target_sum`. If such a pair exists, return a tuple containing the two numbers in any order. If no such pair exists, return `None`.
**Constraints:**
- Th... | def find_pair_with_sum(numbers, target_sum):
"""
Determines if there are any two distinct numbers in the array that add up to the target_sum.
:param numbers: List[int] - A list of integers.
:param target_sum: int - The target sum to find in the list.
:return: Tuple[int, int] or None - A tuple o... | [
"assert find_pair_with_sum([2, 7, 11, 15], 9) == (2, 7)",
"assert find_pair_with_sum([3, 2, 4], 6) == (2, 4)",
"assert find_pair_with_sum([3, 3], 6) == (3, 3)",
"assert find_pair_with_sum([1, 2, 3, 4, 5], 10) == None",
"assert find_pair_with_sum([1, 2, 3, 4, 5], 8) == (3, 5)",
"assert find_pair_with_sum([... | find_pair_with_sum | def find_pair_with_sum(numbers, target_sum): | 1 | algorithmic |
aa58befebe81d0bb6486aed4209c323c | You are tasked with writing a Python function that reads the contents of a file using a context manager. Your function should handle exceptions that may occur during the file operation, such as the file not being found or other I/O errors. Your function should print the contents of the file if successful, or an appropr... | def read_file(file_path: str) -> None:
"""
Reads the contents of a file using a context manager and handles exceptions.
Args:
file_path (str): The path to the file to be read.
Returns:
None: Prints the file contents or an error message.
"""
try:
with open(file_path, 'r'... | [
"assert read_file('non_existent_file.txt') is None",
"assert read_file('') is None",
"assert read_file(None) is None",
"assert read_file('/invalid/path/to/file') is None",
"assert read_file('read_file_test.txt') is None # Assuming this file exists and is readable",
"assert read_file('read_file_test.txt')... | read_file | def read_file(file_path: str) -> None: | 1 | generic |
ea48f8f1a52179bb87b354b45b663ac9 | You are given a 2D binary matrix of size `n x m` consisting of 0s and 1s. Each 1 represents a piece of land, and each 0 represents water. An island is defined as a group of connected 1s, where two 1s are considered connected if they are adjacent horizontally, vertically, or diagonally. Your task is to determine the max... | def maxAreaOfIsland(matrix):
"""
Returns the maximum area of an island in the given 2D binary matrix.
:param matrix: List[List[int]] - A 2D list representing the binary matrix.
:return: int - The maximum area of an island.
"""
if not matrix or not matrix[0]:
return 0
num_ro... | [
"assert maxAreaOfIsland([[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0]]) == 0",
"assert maxAreaOfIsland([[1,1,0,0,0],[1,1,0,0,0],[0,0,0,1,1],[0,0,0,1,1]]) == 4",
"assert maxAreaOfIsland([[1,1,0,0,0],[1,1,0,0,0],[0,0,1,1,1],[0,0,1,1,1]]) == 6",
"assert maxAreaOfIsland([[1]]) == 1",
"assert maxAreaOfIsland(... | maxAreaOfIsland | def maxAreaOfIsland(matrix): | 0.3 | generic |
ede3c8438c7896bdb184c6865456e5d9 | You are given a piece of code. Your task is to classify it into one of the following programming paradigms: functional programming, object-oriented programming, or procedural programming. Provide the classification as the output.
**Sample Input:**
```python
def greet(name):
return "Hello, " + name
def main():
names... | def greet(name):
"""
Returns a greeting message for the given name.
Parameters:
name (str): The name of the person to greet.
Returns:
str: A greeting message.
"""
return "Hello, " + name
def main():
"""
Prints greeting messages for a list of names.
"""
names = ["Alice"... | [
"assert greet(\"Alice\") == \"Hello, Alice\"",
"assert greet(\"Bob\") == \"Hello, Bob\"",
"assert greet(\"Charlie\") == \"Hello, Charlie\"",
"assert greet(\"\") == \"Hello, \"",
"assert greet(\"123\") == \"Hello, 123\"",
"assert greet(\"!@#\") == \"Hello, !@#\"",
"assert greet(\" \") == \"Hello, \"",
... | greet | def greet(name): | 1 | algorithmic |
4430d088e17a9c761d292e819793cf2c | You are given a list of strings `words`. Your task is to implement a function `find_anagrams(words)` that returns a dictionary. Each key in the dictionary should be a sorted tuple of characters, and each value should be a list of words from the input that are anagrams of each other. The comparison should be case-insens... | def find_anagrams(words):
"""
Returns a dictionary where each key is a sorted tuple of characters,
and each value is a list of words that are anagrams of each other.
:param words: List of strings
:return: Dictionary with sorted tuples of characters as keys and lists of anagrams as values
""... | [
"assert find_anagrams(['listen', 'silent', 'enlist']) == {('e', 'i', 'l', 'n', 's', 't'): ['listen', 'silent', 'enlist']}",
"assert find_anagrams(['google', 'gooegl']) == {('e', 'g', 'g', 'l', 'o'): ['google', 'gooegl']}",
"assert find_anagrams(['apple']) == {('a', 'e', 'l', 'p', 'p'): ['apple']}",
"assert fi... | find_anagrams | def find_anagrams(words): | 0.7 | generic |
e4bb188dff44393ab7d0995f3329df97 | You are given a list of integers. Your task is to write a function that returns the second largest unique number from the list. If there is no such number, the function should return `None`.
**Input:**
- A list of integers `nums` (1 ≤ len(nums) ≤ 10^5), where each integer is in the range [-10^9, 10^9].
**Output:**
-... | def second_largest_unique(nums):
"""
Returns the second largest unique number from the list.
If there is no such number, returns None.
:param nums: List of integers
:return: Second largest unique integer or None
"""
unique_nums = set(nums)
if len(unique_nums) < 2:
return Non... | [
"assert second_largest_unique([1, 2, 2, 3, 4]) == 3",
"assert second_largest_unique([5, 5, 5, 5]) == None",
"assert second_largest_unique([10]) == None",
"assert second_largest_unique([1, 2]) == 1",
"assert second_largest_unique([4, 4, 3, 3, 2, 2, 1, 1]) == 3",
"assert second_largest_unique([7, 7, 7, 8, 8... | second_largest_unique | def second_largest_unique(nums): | 1 | generic |
adb0b394fa735c667a07f5aa14ae3de0 | You are given a nested list structure consisting of integers and other lists. Your task is to write a function `flatten_list` that takes this nested list as input and returns a single flattened list containing all the integers in the order they appear. The input list can be arbitrarily nested.
**Sample Input:**
```
[1... | def flatten_list(nested_list):
"""
Flattens a nested list structure into a single flat list.
Parameters:
nested_list (list): A list that may contain other lists.
Returns:
list: A flat list with all the elements.
"""
flat_list = []
for item in nested_list:
if isinsta... | [
"assert flatten_list([1, [2, [3, 4], 5], 6]) == [1, 2, 3, 4, 5, 6]",
"assert flatten_list([[1, 2], [3, 4], [5, 6]]) == [1, 2, 3, 4, 5, 6]",
"assert flatten_list([1, 2, [3, [4, 5], [6, 7]], 8, 9]) == [1, 2, 3, 4, 5, 6, 7, 8, 9]",
"assert flatten_list([1, [2, 3], [4, [5, 6]], 7]) == [1, 2, 3, 4, 5, 6, 7]",
"a... | flatten_list | def flatten_list(nested_list): | 1 | generic |
be8ac91b5a5bd0f2921a9f9a7d1d7919 | You are given a list of rectangles, each represented by a pair of integers indicating its width and height. Your task is to filter out rectangles where the length of the longest side is less than a specified minimum diameter. Ensure that each rectangle appears only once in the resulting list, even if it appears multipl... | def filter_rectangles(rectangles, min_diameter):
"""
Filters out rectangles with the longest side less than the specified minimum diameter.
Ensures no rectangle is included more than once in the resulting list.
:param rectangles: List of tuples, where each tuple contains two integers representing the w... | [
"assert filter_rectangles([(3, 5), (5, 3), (2, 2), (4, 4), (3, 5)], 4) == [(3, 5), (5, 3), (4, 4)]",
"assert filter_rectangles([(1, 1), (2, 2), (3, 3)], 4) == []",
"assert filter_rectangles([(4, 4), (4, 4), (4, 4)], 4) == [(4, 4)]",
"assert filter_rectangles([(5, 5), (5, 5), (5, 5)], 6) == []",
"assert filt... | filter_rectangles | def filter_rectangles(rectangles, min_diameter): | 0.4 | generic |
3a2fd6331149355af23c1e52aa562665 | You are given a string `bracket_seq` consisting solely of opening `(` and closing `)` parentheses. Your task is to determine if the parentheses in the string are correctly nested and if each pair of matching parentheses encloses at least one unique lowercase English letter that is not enclosed by any other pair of pare... | def validate_parentheses(bracket_seq):
"""
Validates if the parentheses in the given string are correctly nested and
each pair of matching parentheses encloses at least one unique lowercase
English letter not enclosed by another pair.
:param bracket_seq: A string containing only '(' and ')' charact... | [
"assert validate_parentheses(\"(a)\") == True",
"assert validate_parentheses(\"((ab))\") == True",
"assert validate_parentheses(\"(a)(b)\") == True",
"assert validate_parentheses(\"((a)(b))\") == True",
"assert validate_parentheses(\"()\") == False",
"assert validate_parentheses(\"(a(b)c)\") == True",
"... | validate_parentheses | def validate_parentheses(bracket_seq): | 0.3 | generic |
3e9b22a5b054918503567ee3e3c4ed9b | You are tasked with implementing a function to validate IPv4 addresses. An IPv4 address consists of four decimal numbers, each ranging from 0 to 255, separated by dots. Each number must not have leading zeros unless it is exactly zero. Your function should return `True` if the input string is a valid IPv4 address, and ... | def validate_ip_address(ip):
"""
Validates if the given string is a valid IPv4 address.
:param ip: A string representing the IP address to validate.
:return: True if the IP address is valid, False otherwise.
"""
parts = ip.split('.')
if len(parts) != 4:
return False
for... | [
"assert validate_ip_address(\"192.168.1.1\") == True",
"assert validate_ip_address(\"256.256.256.256\") == False",
"assert validate_ip_address(\"0.0.0.0\") == True",
"assert validate_ip_address(\"255.255.255.255\") == True",
"assert validate_ip_address(\"192.168.1\") == False",
"assert validate_ip_address... | validate_ip_address | def validate_ip_address(ip): | 1 | generic |
b1b60954d43f45797a7735eff69c50c6 | You are tasked with implementing a function for a natural language processing pipeline that performs tokenization. Given a string `input_text`, your function should return a list of tokens, where each token is a sequence of word characters (letters, digits, and underscores) separated by non-word characters.
**Input:*... | import re
def tokenize_text(input_text):
"""
Tokenizes the input text into a list of word tokens.
Parameters:
input_text (str): The text to be tokenized.
Returns:
list: A list of tokens, where each token is a sequence of word characters.
"""
# Use regular expression to split the text ... | [
"assert tokenize_text(\"Hello, world!\") == [\"Hello\", \"world\"]",
"assert tokenize_text(\"This is a test.\") == [\"This\", \"is\", \"a\", \"test\"]",
"assert tokenize_text(\"Let's tokenize this!\") == [\"Lets\", \"tokenize\", \"this\"]",
"assert tokenize_text(\"123 456 789\") == [\"123\", \"456\", \"789\"]... | tokenize_text | def tokenize_text(input_text): | 0.9 | generic |
c44b9323de707c11e782b2c21d8c52ac | You are given an unsorted array of integers `nums` and an integer `k`. Your task is to find the `k`th largest element in the array. You may assume that `k` is always valid, i.e., `1 <= k <= len(nums)`. Your solution should have an average time complexity of O(n).
**Input:**
- The first line contains an integer `n` (1 ... | import random
def partition(nums, left, right, pivot_index):
"""
Partitions the array around the pivot element such that elements greater than the pivot
are on the left and elements less than the pivot are on the right.
:param nums: List of integers to be partitioned.
:param left: Starting ind... | [
"assert find_kth_largest([3,2,1,5,6,4], 2) == 5",
"assert find_kth_largest([3,2,3,1,2,4,5,5,6], 4) == 4",
"assert find_kth_largest([1], 1) == 1",
"assert find_kth_largest([7,6,5,4,3,2,1], 7) == 1",
"assert find_kth_largest([1,2,3,4,5,6,7], 1) == 7",
"assert find_kth_largest([10,20,30,40,50], 3) == 30",
... | find_kth_largest | def find_kth_largest(nums, k): | 1 | generic |
442fc204f87e1747c0240a2be094ef02 | You are given a string representing a simple mathematical expression. The expression consists of an operation followed by two operands. The operation can be one of the following: 'add', 'subtract', 'multiply', or 'divide'. Each operand can be a positive integer or a floating-point number with up to two decimal places. ... | def parse_math_expression(expression):
"""
Parses a mathematical expression string and returns a list containing the operation
and the two operands as floats. Returns 'error' if the input is not in the correct format.
:param expression: A string representing a mathematical expression.
:return: ... | [
"assert parse_math_expression('add 3.14 5') == ['add', 3.14, 5.0]",
"assert parse_math_expression('multiply 4.25 6.00') == ['multiply', 4.25, 6.0]",
"assert parse_math_expression('divide 10 2') == ['divide', 10.0, 2.0]",
"assert parse_math_expression('subtract 7.5 3.25') == ['subtract', 7.5, 3.25]",
"assert... | parse_math_expression | def parse_math_expression(expression): | 1 | generic |
8bc9e2f5ccd6b9dab133f73fefe7527d | You are tasked with implementing a function `extract_phone_numbers_and_emails` that processes a given string of text and extracts all phone numbers and email addresses. Phone numbers can appear in the following formats: `(123) 456-7890`, `123-456-7890`, or `123.456.7890`. Email addresses should be in the format `user@d... | import re
def extract_phone_numbers_and_emails(text):
"""
Extracts phone numbers and email addresses from the given text.
Args:
text (str): The input text to search for phone numbers and email addresses.
Returns:
list: A list of strings, each representing a phone number or email addre... | [
"assert extract_phone_numbers_and_emails(\"My phone number is (123) 456-7890. You can also reach me at 123.456.7890.\") == [\"(123) 456-7890\", \"123.456.7890\"]",
"assert extract_phone_numbers_and_emails(\"I don't have a phone number.\") == []",
"assert extract_phone_numbers_and_emails(\"My phone numbers are 1... | extract_phone_numbers_and_emails | def extract_phone_numbers_and_emails(text): | 0.8 | generic |
8d9cbef37f8702af9cd5f8760b16f890 | You are given a string `s`. Your task is to transform the string such that the first letter of each word is capitalized and all other letters are in lowercase. A word is defined as a sequence of characters separated by spaces.
**Input:**
- A single string `s` (1 ≤ |s| ≤ 1000), consisting of lowercase and uppercase En... | def capitalize_words(input_string):
"""
Transforms the input string such that the first letter of each word is capitalized
and all other letters are in lowercase.
:param input_string: A string to be transformed.
:return: A transformed string with capitalized words.
"""
return input_stri... | [
"assert capitalize_words(\"hello world\") == \"Hello World\"",
"assert capitalize_words(\"HELLO WORLD\") == \"Hello World\"",
"assert capitalize_words(\"hElLo WoRlD\") == \"Hello World\"",
"assert capitalize_words(\"python programming\") == \"Python Programming\"",
"assert capitalize_words(\"123abc def456\"... | capitalize_words | def capitalize_words(input_string): | 1 | generic |
0ea62771c117a70b3910262baec5fa28 | You are given a list of integers that may include positive numbers, negative numbers, and zeros. Your task is to sort this list in ascending order using the insertion sort algorithm. Implement a function that takes a list of integers as input and returns the sorted list.
**Sample Input:**
```
[3, -1, 4, 0, -5, 2, 7, -... | def insertion_sort(arr):
"""
Sorts a list of integers in ascending order using the insertion sort algorithm.
Parameters:
arr (list): A list of integers to be sorted.
Returns:
list: The sorted list of integers.
"""
for i in range(1, len(arr)):
key = arr[i]
j = i - 1
... | [
"assert insertion_sort([3, -1, 4, 0, -5, 2, 7, -3]) == [-5, -3, -1, 0, 2, 3, 4, 7]",
"assert insertion_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]",
"assert insertion_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5]",
"assert insertion_sort([-1, -2, -3, -4, -5]) == [-5, -4, -3, -2, -1]",
"assert insertion_sort([0, 0, ... | insertion_sort | def insertion_sort(arr): | 1 | algorithmic |
0f96476a730355eeda56babb876dc76a | You are tasked with writing a Python script to process a CSV file named "sales_data.csv" located in the same directory as the script. The CSV file contains sales data with the following columns: product name, quantity sold, and unit price. Your program should compute the total sales by multiplying the quantity sold by ... | import csv
import os
def calculate_total_sales():
"""
Calculates the total sales from a CSV file named 'sales_data.csv'.
The CSV file should contain columns for product name, quantity sold, and unit price.
Prints the total sales or an error message if the file is not accessible.
"""
total_sales... | [
"assert calculate_total_sales() is None # Assuming the file does not exist or is not accessible, the function should return None",
"assert calculate_total_sales() is None # Assuming the file is not readable, the function should return None",
"assert calculate_total_sales() is None # Assuming the file is empt... | calculate_total_sales | def calculate_total_sales(): | 1 | generic |
8e6001e7018835ad821e1921c7f26e0a | You are given a list of strings. Your task is to implement a function that identifies and returns a new list containing only the strings that are palindromes. A palindrome is defined as a string that reads the same forwards and backwards. For example, "racecar" and "level" are palindromes, whereas "hello" and "world" a... | def find_palindromes(strings):
"""
Returns a list of strings that are palindromes from the input list.
:param strings: List of strings to be checked.
:return: List of palindromic strings.
"""
return [s for s in strings if s == s[::-1]]
# Example usage:
input_strings = ["racecar", "level", "hel... | [
"assert find_palindromes([\"racecar\", \"level\", \"hello\", \"world\", \"radar\", \"python\"]) == [\"racecar\", \"level\", \"radar\"]",
"assert find_palindromes([\"\", \"a\", \"bb\", \"abc\", \"aba\"]) == [\"\", \"a\", \"bb\", \"aba\"]",
"assert find_palindromes([\"noon\", \"civic\", \"rotor\", \"deified\", \"... | find_palindromes | def find_palindromes(strings): | 1 | generic |
f441438d8c5f064edb2c4f0590d539f2 | You are given a list of strings. Your task is to write a Python function that groups all the anagrams together. An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. The function should return a list of lists, where each su... | def group_anagrams(words):
"""
Groups all the anagrams together from the given list of strings.
:param words: List of strings to be grouped.
:return: A list of lists, where each sublist contains anagrams.
"""
anagrams = {}
for word in words:
sorted_word = ''.join(sorted(word))
... | [
"assert group_anagrams([\"listen\", \"silent\", \"enlist\"]) == [[\"listen\", \"silent\", \"enlist\"]]",
"assert group_anagrams([\"abc\", \"bca\", \"cab\", \"xyz\"]) == [[\"abc\", \"bca\", \"cab\"], [\"xyz\"]]",
"assert group_anagrams([\"a\", \"b\", \"c\", \"d\"]) == [[\"a\"], [\"b\"], [\"c\"], [\"d\"]]",
"as... | group_anagrams | def group_anagrams(words): | 0.9 | generic |
58a5a64d691db7d56ff0ea949393580c | You are given a dictionary `d` where keys are strings and values are integers. Your task is to write a function `find_keys_with_max_value` that returns a list of all keys that have the maximum value in the dictionary. If the dictionary is empty, return an empty list.
**Sample Input:**
```python
{'apple': 5, 'banana': ... | def find_keys_with_max_value(d):
"""
Returns a list of keys with the maximum value in the dictionary.
:param d: Dictionary with string keys and integer values.
:return: List of keys with the maximum value.
"""
if not d:
return []
max_value = max(d.values())
keys_with_ma... | [
"assert find_keys_with_max_value({'a': 1, 'b': 2, 'c': 2}) == ['b', 'c']",
"assert find_keys_with_max_value({'x': 3, 'y': 1, 'z': 3}) == ['x', 'z']",
"assert find_keys_with_max_value({'one': 10, 'two': 10, 'three': 10}) == ['one', 'two', 'three']",
"assert find_keys_with_max_value({'single': 42}) == ['single'... | find_keys_with_max_value | def find_keys_with_max_value(d): | 1 | algorithmic |
5ba3a946ac14f28a6416ae82b2ba790a | You are given an array `prices` where `prices[i]` is the price of a given stock on the `i-th` day. You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock. Return the maximum profit you can achieve from this transaction. If you cannot achi... | def max_profit(prices):
"""
Calculate the maximum profit from a single buy and sell transaction.
:param prices: List[int] - A list of integers representing the stock prices on consecutive days.
:return: int - The maximum profit that can be achieved. If no profit is possible, returns 0.
"""
if n... | [
"assert max_profit([7, 1, 5, 3, 6, 4]) == 5",
"assert max_profit([7, 6, 4, 3, 1]) == 0",
"assert max_profit([1, 2, 3, 4, 5]) == 4",
"assert max_profit([3, 3, 5, 0, 0, 3, 1, 4]) == 4",
"assert max_profit([1, 2]) == 1",
"assert max_profit([2, 1, 2, 1, 0, 1, 2]) == 2",
"assert max_profit([1]) == 0",
"ass... | max_profit | def max_profit(prices): | 1 | generic |
42f71a2468e4cb36a8e081c62fc736d9 | You are given a URL string as input. Your task is to implement a function `parse_query_params` that extracts and returns the query parameters from the URL as a dictionary. The function should correctly handle URL-encoded characters and support multiple values for a single parameter.
**Input:**
- A single string repres... | from urllib.parse import urlparse, parse_qs
def parse_query_params(url):
"""
Parses the query parameters from a given URL and returns them as a dictionary.
Args:
url (str): The URL string from which to extract query parameters.
Returns:
dict: A dictionary of query parameters, with sin... | [
"assert parse_query_params(\"https://example.com/path?name=John+Doe&age=25\") == {'name': 'John Doe', 'age': '25'}",
"assert parse_query_params(\"https://example.com/path?name=John+Doe&hobbies=reading&hobbies=writing\") == {'name': 'John Doe', 'hobbies': ['reading', 'writing']}",
"assert parse_query_params(\"ht... | parse_query_params | def parse_query_params(url): | 1 | algorithmic |
45d2b3bcfbd7053fb1632bd03b3a7618 | You are given a list of integers. Your task is to implement a function `second_smallest_unique` that determines the second smallest unique number in the list. If there is no such number, the function should return `None`. The function should be efficient and handle edge cases appropriately.
**Input:**
- A list of inte... | def second_smallest_unique(numbers):
"""
Returns the second smallest unique number in the list.
If there is no such number, returns None.
:param numbers: List of integers
:return: Second smallest unique integer or None
"""
unique_numbers = set(numbers)
if len(unique_numbers) < 2:
... | [
"assert second_smallest_unique([1, 2, 3, 4, 5]) == 2",
"assert second_smallest_unique([5, 1, 4, 3, 2]) == 2",
"assert second_smallest_unique([10, 10, 10]) == None",
"assert second_smallest_unique([1]) == None",
"assert second_smallest_unique([2, 2, 3, 1, 4, 4]) == 2",
"assert second_smallest_unique([7, 7,... | second_smallest_unique | def second_smallest_unique(numbers): | 1 | generic |
e1011eecc702cf1e44f1ac320a719852 | You are given a date in the format `year`, `month`, and `day`. Your task is to write a function `next_date` that calculates the next date after the given date, considering the number of days in each month and leap years. The function should handle dates from 1900-01-01 to 2100-12-31. A leap year is defined as a year th... | def next_date(year, month, day):
"""
Calculate the next date after the given date, considering leap years and the number of days in each month.
Parameters:
year (int): The year of the given date.
month (int): The month of the given date.
day (int): The day of the given date.
Return... | [
"assert next_date(2023, 2, 28) == (2023, 3, 1)",
"assert next_date(2020, 2, 29) == (2020, 3, 1)",
"assert next_date(2023, 12, 31) == (2024, 1, 1)",
"assert next_date(2000, 4, 30) == (2000, 5, 1)",
"assert next_date(1900, 2, 28) == (1900, 3, 1)",
"assert next_date(2004, 2, 28) == (2004, 2, 29)",
"assert ... | next_date | def next_date(year, month, day): | 1 | generic |
e3a2215520af09f840c2cca8ea61485f | You are given a list of dictionaries, where each dictionary represents a person with keys `name`, `age`, and `city`. Your task is to write a function that sorts this list of dictionaries based on a specified key. The key to sort by will be provided as an input parameter to the function.
**Input:**
- A list of diction... | def sort_people_by_key(people, key):
"""
Sorts a list of dictionaries representing people based on a specified key.
Parameters:
people (list of dict): A list where each dictionary contains 'name', 'age', and 'city' keys.
key (str): The key to sort the list by ('name', 'age', or 'city').
Return... | [
"assert sort_people_by_key([{'name': 'Alice', 'age': 30, 'city': 'New York'}, {'name': 'Bob', 'age': 25, 'city': 'Los Angeles'}, {'name': 'Charlie', 'age': 35, 'city': 'Chicago'}], 'age') == [{'name': 'Bob', 'age': 25, 'city': 'Los Angeles'}, {'name': 'Alice', 'age': 30, 'city': 'New York'}, {'name': 'Charlie', 'ag... | sort_people_by_key | def sort_people_by_key(people, key): | 1 | generic |
349f75f4a6d623d628f48075ad7f296c | You are tasked with implementing a function named `calculate_sum`. This function should accept two parameters, `x` and `y`. The function should return the sum of `x` and `y` if both are integers and fall within the inclusive range of -1000 to 1000. If either `x` or `y` does not meet these criteria, the function should ... | def calculate_sum(x, y):
"""
Returns the sum of x and y if both are integers within the range -1000 to 1000.
Otherwise, returns an error message.
Parameters:
x (int): The first integer.
y (int): The second integer.
Returns:
int or str: The sum of x and y if valid, otherwise an ... | [
"assert calculate_sum(500, 500) == 1000",
"assert calculate_sum(-500, 500) == 0",
"assert calculate_sum(1000, -1000) == 0",
"assert calculate_sum(0, 0) == 0",
"assert calculate_sum(1001, 1000) == \"Error: Both parameters must be integers within the range -1000 to 1000.\"",
"assert calculate_sum(-1001, -10... | calculate_sum | def calculate_sum(x, y): | 1 | generic |
958add9ba1696e6e633ff77af615cc72 | You are tasked with implementing a function `generate_prime_numbers` that efficiently generates the first `n` prime numbers. Your function should be optimized for performance to handle large values of `n`.
**Input:**
- An integer `n` (1 ≤ n ≤ 10^4), representing the number of prime numbers to generate.
**Output:**
- ... | def generate_prime_numbers(n):
"""
Generate a list of the first n prime numbers.
Parameters:
n (int): The number of prime numbers to generate.
Returns:
list: A list containing the first n prime numbers.
"""
def is_prime(num, known_primes):
"""Check if a number is prime usi... | [
"assert generate_prime_numbers(1) == [2]",
"assert generate_prime_numbers(5) == [2, 3, 5, 7, 11]",
"assert generate_prime_numbers(10) == [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]",
"assert generate_prime_numbers(0) == []",
"assert generate_prime_numbers(20) == [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43,... | generate_prime_numbers | def generate_prime_numbers(n): | 1 | generic |
43e30f635e3468f0bc233c2b1ee980cd | You are given a list of strings. Your task is to implement a function `remove_duplicates` that processes this list and returns a new list with all duplicate strings removed, preserving the order of their first occurrence. The comparison should be case-insensitive, meaning that strings differing only by case are conside... | def remove_duplicates(strings):
"""
Removes duplicate strings from the input list, preserving the order of their first occurrence.
The comparison is case-insensitive.
:param strings: List of strings to process.
:return: A new list with duplicates removed.
"""
seen = set()
result = []
... | [
"assert remove_duplicates([\"apple\", \"banana\", \"Apple\", \"orange\"]) == [\"apple\", \"banana\", \"orange\"]",
"assert remove_duplicates([\"dog\", \"cat\", \"Dog\", \"CAT\", \"bird\"]) == [\"dog\", \"cat\", \"bird\"]",
"assert remove_duplicates([\"hello\", \"world\", \"HELLO\", \"WORLD\"]) == [\"hello\", \"... | remove_duplicates | def remove_duplicates(strings): | 1 | generic |
7dd9f5035523f51321b3f25862052a7c | You are given a grid-based world represented by a 2D array `world` of size `n x m`. Each cell in the grid can be one of the following:
- 'E': An empty cell.
- 'T': A cell containing a treasure.
- 'M': A cell containing a monster.
The player starts at position (0, 0) and can move up, down, left, or right. The player's ... | from collections import deque
def play_game(world):
"""
Determines if the player can collect all treasures in the grid without encountering any monsters.
:param world: A 2D list representing the grid-based world.
:return: True if the player can collect all treasures, False otherwise.
"""
r... | [
"assert play_game([['E', 'E', 'E'], ['E', 'T', 'E'], ['E', 'E', 'E']]) == True",
"assert play_game([['E', 'E', 'E'], ['E', 'M', 'E'], ['E', 'E', 'E']]) == False",
"assert play_game([['E', 'T', 'E'], ['E', 'M', 'E'], ['E', 'T', 'E']]) == False",
"assert play_game([['T', 'E', 'E'], ['E', 'E', 'E'], ['E', 'E', '... | play_game | def play_game(world): | 0.5 | generic |
8c4dbcf4cbf4349f77e1b3e981295783 | You are given a list of integers. Your task is to implement a function that identifies the most frequently occurring element in the list. In the event of a tie, where multiple elements share the highest frequency, the function should return the smallest of these elements. Utilize Python's `collections` module to accomp... | from collections import Counter
def most_frequent(nums):
"""
Returns the most frequently occurring element in the list.
If there are multiple elements with the same highest frequency,
returns the smallest element among them.
:param nums: List of integers
:return: Integer, the most frequent... | [
"assert most_frequent([1, 2, 2, 3, 3]) == 2",
"assert most_frequent([4, 4, 4, 6, 6, 6, 7]) == 4",
"assert most_frequent([10, 10, 20, 20, 30]) == 10",
"assert most_frequent([1, 1, 2, 2, 3, 3, 4, 4]) == 1",
"assert most_frequent([5]) == 5",
"assert most_frequent([7, 8, 9, 9, 8, 7, 7]) == 7",
"assert most_... | most_frequent | def most_frequent(nums): | 0.9 | generic |
a9ccb9484d9666ae46ae6141125f3fef | You are given a list of integers. Your task is to generate a list of all prime numbers up to the maximum integer in the list using the Sieve of Eratosthenes algorithm.
**Input:**
- A list of integers `input_list` (1 ≤ len(input_list) ≤ 10^3, 1 ≤ input_list[i] ≤ 10^4).
**Output:**
- A list of prime numbers up to the ... | def sieve_of_eratosthenes(max_num):
"""
Generate a list of prime numbers up to max_num using the Sieve of Eratosthenes algorithm.
:param max_num: The upper limit for generating prime numbers.
:return: A list of prime numbers up to max_num.
"""
is_prime = [True] * (max_num + 1)
p = 2
... | [
"assert generate_primes([2, 15, 7, 10, 13]) == [2, 3, 5, 7, 11, 13]",
"assert generate_primes([1, 2, 3, 4, 5]) == [2, 3, 5]",
"assert generate_primes([10, 20, 30]) == [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]",
"assert generate_primes([31]) == [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31]",
"assert generate_primes([0... | generate_primes | def generate_primes(input_list): | 1 | algorithmic |
767bf45b25ba3582d282b42f86dce570 | You are given a string `song_info` representing metadata of a song, which includes multiple BPM (Beats Per Minute) values prefixed by "BPM:". Your task is to write a function `extract_bpm(song_info)` that extracts all BPM values, converts them to integers, and returns the highest BPM value found.
**Input:**
- A single... | def extract_bpm(song_info):
"""
Extracts and returns the highest BPM value from the given song metadata.
:param song_info: A string containing song metadata with BPM values.
:return: The highest BPM value as an integer.
"""
bpm_values = [s.split(':')[1] for s in song_info.split() if s.startswit... | [
"assert extract_bpm(\"BPM:100 BPM:200 BPM:150\") == 200",
"assert extract_bpm(\"Title: Song BPM:120\") == 120",
"assert extract_bpm(\"Artist: John Doe BPM:90 BPM:90 BPM:90\") == 90",
"assert extract_bpm(\"BPM:80 BPM:85 BPM:95 BPM:100 BPM:105\") == 105",
"assert extract_bpm(\"BPM:200 BPM:200 BPM:200\") == 20... | extract_bpm | def extract_bpm(song_info): | 1 | generic |
fdede94ff3b70114dd42aea14b7e1100 | You are given two non-empty strings, `str1` and `str2`. Your task is to implement a function `jaccard_similarity` that computes the Jaccard similarity between these two strings using only set operations available in Python. You must not convert the strings to sets directly. The comparison should be case-insensitive.
... | def jaccard_similarity(str1, str2):
"""
Calculate the Jaccard similarity between two strings using set operations.
Parameters:
str1 (str): The first input string.
str2 (str): The second input string.
Returns:
float: The Jaccard similarity between the two strings.
"""
# Conv... | [
"assert jaccard_similarity(\"hello\", \"HELLO\") == 1.0",
"assert jaccard_similarity(\"abc\", \"def\") == 0.0",
"assert jaccard_similarity(\"abc\", \"abc\") == 1.0",
"assert jaccard_similarity(\"abc\", \"abcd\") == 0.75",
"assert jaccard_similarity(\"aabbcc\", \"abc\") == 1.0",
"assert jaccard_similarity(... | jaccard_similarity | def jaccard_similarity(str1, str2): | 0.8 | generic |
0a13aefae2142fcdeac0f424a57e3609 | You are given two positive integers `a` and `b`. Your task is to write a function `calculate_gcd` that computes the greatest common divisor (GCD) of these two numbers using the Euclidean algorithm. The function should return the GCD as an integer.
**Input:**
- Two integers `a` and `b` (1 ≤ a, b ≤ 10^9)
**Output:**
- ... | def calculate_gcd(a, b):
"""Calculate the greatest common divisor of two numbers using the Euclidean algorithm."""
while b:
a, b = b, a % b
return a
# Example usage:
a = 48
b = 18
print(calculate_gcd(a, b)) # Output: 6 | [
"assert calculate_gcd(48, 18) == 6",
"assert calculate_gcd(101, 10) == 1",
"assert calculate_gcd(56, 98) == 14",
"assert calculate_gcd(270, 192) == 6",
"assert calculate_gcd(0, 5) == 5",
"assert calculate_gcd(5, 0) == 5",
"assert calculate_gcd(0, 0) == 0",
"assert calculate_gcd(1, 1) == 1",
"assert ... | calculate_gcd | def calculate_gcd(a, b): | 1 | generic |
8bf729bc3cfca75a7734ea5f70f897f7 | You are given a nested list `nested_list` consisting of integers and other nested lists. Your task is to implement a recursive function `flatten_list` that takes this nested list as input and returns a flattened list containing all the integers from the original nested list in the same order.
**Input:**
- A nested lis... | def flatten_list(nested_list):
"""
Recursively flattens a nested list of integers.
:param nested_list: List of integers and/or nested lists of integers.
:return: A flattened list of integers.
"""
flattened = []
for element in nested_list:
if isinstance(element, list):
fl... | [
"assert flatten_list([1, [2, 3], 4]) == [1, 2, 3, 4]",
"assert flatten_list([[1, 2, [3]], 4]) == [1, 2, 3, 4]",
"assert flatten_list([1, [2, [3, [4]]]]) == [1, 2, 3, 4]",
"assert flatten_list([1, 2, 3, 4]) == [1, 2, 3, 4]",
"assert flatten_list([]) == []",
"assert flatten_list([[], [], []]) == []",
"ass... | flatten_list | def flatten_list(nested_list): | 0.8 | generic |
7b2b890d3ddb31184bcbd515447aa521 | You are tasked with implementing a recursive function to compute the factorial of a given non-negative integer. The factorial of a non-negative integer \( n \) is the product of all positive integers less than or equal to \( n \). Your function should handle invalid inputs by raising a `ValueError`.
**Input:**
- A sin... | def factorial(n):
"""
Calculate the factorial of a given non-negative integer using recursion.
Parameters:
n (int): A non-negative integer whose factorial is to be computed.
Returns:
int: The factorial of the integer n.
Raises:
ValueError: If the input is a negative intege... | [
"assert factorial(0) == 1",
"assert factorial(1) == 1",
"assert factorial(2) == 2",
"assert factorial(3) == 6",
"assert factorial(4) == 24",
"assert factorial(5) == 120",
"assert factorial(6) == 720",
"assert factorial(10) == 3628800",
"assert factorial(15) == 1307674368000",
"assert factorial(20)... | factorial | def factorial(n): | 1 | generic |
0769c52cfce20dfe2bb470adc43bd7ae | You are given a dictionary representing a person's information. Your task is to write a Python function `convert_to_json` that converts this dictionary into a JSON formatted string. Use the `json` module for the conversion. Your function should handle any dictionary with string keys and values that are either strings, ... | import json
def convert_to_json(input_dict):
"""
Convert a dictionary to a JSON formatted string.
Parameters:
input_dict (dict): A dictionary with string keys and values that are either strings, integers, or booleans.
Returns:
str: A JSON formatted string representing the input dictionary.
... | [
"assert convert_to_json({\"name\": \"John\", \"age\": 30, \"city\": \"New York\"}) == '{\"name\": \"John\", \"age\": 30, \"city\": \"New York\"}'",
"assert convert_to_json({\"key\": \"value\"}) == '{\"key\": \"value\"}'",
"assert convert_to_json({}) == '{}'",
"assert convert_to_json({\"numbers\": [1, 2, 3, 4]... | convert_to_json | def convert_to_json(input_dict): | 0.9 | generic |
d85c71cdfe7a0184585f6d0d00e4b860 | You are given a list of integers. Your task is to write a Python function that returns the largest and smallest numbers in the list. If the list is empty, the function should return `None` for both values.
**Input:**
- A list of integers `numbers` (0 ≤ len(numbers) ≤ 10^3), where each integer is in the range [-10^6, 1... | def find_largest_and_smallest(numbers):
"""
Finds the largest and smallest numbers in a given list of integers.
Parameters:
numbers (list): A list of integers.
Returns:
tuple: A tuple containing the largest and smallest numbers in the list.
Returns (None, None) if the list i... | [
"assert find_largest_and_smallest([3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]) == (9, 1)",
"assert find_largest_and_smallest([100]) == (100, 100)",
"assert find_largest_and_smallest([-10, -20, -30, -40, -50]) == (-10, -50)",
"assert find_largest_and_smallest([0, 0, 0, 0, 0]) == (0, 0)",
"assert find_largest_and_small... | find_largest_and_smallest | def find_largest_and_smallest(numbers): | 1 | algorithmic |
c01482a3ec78d06059245d8e5e9b8e03 | You are given a text file named `input.txt`. Your task is to write a program that reads the file and prints its contents line by line to the standard output. If the file does not exist, your program should output an error message: "Error: The file 'input.txt' was not found." If any other I/O error occurs, your program ... | def read_and_print_file(filename):
"""
Reads a file and prints its contents line by line.
Parameters:
filename (str): The name of the file to be read.
Returns:
None
"""
try:
with open(filename, 'r') as file:
for line in file:
print(line, end=... | [
"assert read_and_print_file('non_existent_file.txt') is None",
"assert read_and_print_file('empty_file.txt') is None",
"assert read_and_print_file('single_line_file.txt') is None",
"assert read_and_print_file('multi_line_file.txt') is None",
"assert read_and_print_file('file_with_special_chars.txt') is None... | read_and_print_file | def read_and_print_file(filename): | 1 | generic |
97e5c760c2558f7179613f0f746f90c4 | You are developing a weather application that needs to minimize API calls to a weather service. Implement a function `get_weather(city)` that fetches the current weather data for a given city. The function should cache the results for cities queried within the last 30 minutes to avoid unnecessary API calls. The functio... | import time
# Simulated API call function
def fetch_weather_from_api(city: str) -> dict:
"""
Simulates fetching weather data from an API.
Parameters:
city (str): The name of the city.
Returns:
dict: A dictionary containing the weather data.
"""
return {
"city": city,
... | [
"assert get_weather(\"New York\") == {\"city\": \"New York\", \"temperature\": \"22°C\", \"humidity\": \"60%\", \"condition\": \"Sunny\"}",
"assert get_weather(\"London\") == {\"city\": \"London\", \"temperature\": \"22°C\", \"humidity\": \"60%\", \"condition\": \"Sunny\"}",
"assert get_weather(\"Paris\") == {\... | get_weather | def get_weather(city: str) -> dict: | 1 | generic |
e77f160cba2433f334f2eaf38b2d1c21 | You are given an array `prices` of length `n`, where `prices[i]` is the price of a given stock on the `i-th` day. You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock. Return the maximum profit you can achieve from this transaction. If ... | from typing import List
def calculate_max_profit(prices: List[int]) -> int:
"""
Calculate the maximum profit from a single buy and sell transaction.
:param prices: List of integers representing daily stock prices.
:return: Maximum profit that can be achieved.
"""
if not prices:
return ... | [
"assert calculate_max_profit([7, 1, 5, 3, 6, 4]) == 5",
"assert calculate_max_profit([7, 6, 4, 3, 1]) == 0",
"assert calculate_max_profit([1, 2, 3, 4, 5]) == 4",
"assert calculate_max_profit([3, 3, 5, 0, 0, 3, 1, 4]) == 4",
"assert calculate_max_profit([1, 2]) == 1",
"assert calculate_max_profit([2, 1, 2,... | calculate_max_profit | def calculate_max_profit(prices: List[int]) -> int: | 1 | generic |
d6fb68a91b877e9d3c1eca6923602e23 | You are given the task of implementing a function to determine if a string is a valid license plate number according to specific rules. A valid license plate number must satisfy the following conditions:
- It is a string of exactly 7 characters.
- It consists solely of alphanumeric characters.
- It does not start with ... | def is_valid_license_plate(license_plate: str) -> bool:
"""
Determines if the given string is a valid license plate number.
A valid license plate number must be a string of exactly 7 alphanumeric characters,
start with a letter, and alternate between letters and digits.
:param license_plat... | [
"assert is_valid_license_plate(\"A1B2C3D\") == True",
"assert is_valid_license_plate(\"1AB2C3D\") == False",
"assert is_valid_license_plate(\"AB12C3D\") == False",
"assert is_valid_license_plate(\"A1B2C3\") == False",
"assert is_valid_license_plate(\"A1B2C3D1\") == False",
"assert is_valid_license_plate(\... | is_valid_license_plate | def is_valid_license_plate(license_plate: str) -> bool: | 1 | generic |
e7a0b0cde97ca5488c79039a2336ef9f | You are given a string `s`. Your task is to find and return the longest palindromic substring within `s`. If there are multiple palindromic substrings of the same maximum length, return the one that appears first in the string.
**Constraints:**
- The length of the string `s` is between 1 and 1000, inclusive.
- The str... | def longest_palindrome(s: str) -> str:
"""
Finds and returns the longest palindromic substring in the given string.
If there are multiple palindromic substrings of the same maximum length,
returns the one that appears first in the string.
:param s: The input string.
:return: The longest palindr... | [
"assert longest_palindrome(\"babad\") == \"bab\"",
"assert longest_palindrome(\"cbbd\") == \"bb\"",
"assert longest_palindrome(\"a\") == \"a\"",
"assert longest_palindrome(\"ac\") == \"a\"",
"assert longest_palindrome(\"racecar\") == \"racecar\"",
"assert longest_palindrome(\"noon high it is\") == \"noon\... | longest_palindrome | def longest_palindrome(s: str) -> str: | 1 | algorithmic |
615b3bf6bdb79f1399af00132b5ac702 | You are tasked with implementing a function named `ensure_encoding` that processes a potentially nested structure of strings and bytes. The function should recursively traverse the structure and decode any bytes found using a specified encoding. The function should handle the following cases:
- If the input is a byte s... | from typing import Union, List
def ensure_encoding(s, encoding: str) -> Union[str, List[Union[str, List]]]:
"""
Recursively decodes bytes in a nested structure using the specified encoding.
Parameters:
s (Union[str, bytes, List[Union[str, bytes, List]]]): The input structure to process.
encoding (... | [
"assert ensure_encoding(b'hello', 'utf-8') == 'hello'",
"assert ensure_encoding('hello', 'utf-8') == 'hello'",
"assert ensure_encoding(b'world', 'ascii') == 'world'",
"assert ensure_encoding(['hello', b'world'], 'utf-8') == ['hello', 'world']",
"assert ensure_encoding([b'hello', [b'world', b'!']], 'utf-8') ... | ensure_encoding | def ensure_encoding(s, encoding: str) -> Union[str, List[Union[str, List]]]: | 0.9 | generic |
f685d95251dc57cf70cb5e1320d83d24 | You are given a list of tokens, where each token is a string that may contain underscores (`_`) or dashes (`-`). Your task is to write a function `convert_tokens` that processes each token by swapping underscores with dashes and vice versa, except for any occurrences within alphanumeric sequences of length greater than... | import re
def convert_tokens(tokens):
"""
Convert tokens by swapping underscores and dashes, except within
alphanumeric sequences of length greater than four.
:param tokens: List of strings to be converted.
:return: List of converted strings.
"""
def convert_token(token):
pattern =... | [
"assert convert_tokens([\"hello_world\"]) == [\"hello-world\"]",
"assert convert_tokens([\"good-bye\"]) == [\"good_bye\"]",
"assert convert_tokens([\"12345_67890\"]) == [\"12345_67890\"]",
"assert convert_tokens([\"abcdefghi\"]) == [\"abcdefghi\"]",
"assert convert_tokens([\"hello_world-test\"]) == [\"hello... | convert_tokens | def convert_tokens(tokens): | 0.3 | generic |
193326708a5f5a7acf070edf495e46c9 | You are given an integer `n`. Your task is to write a function `count_digits(n)` that returns a dictionary. The keys of the dictionary should be the digits present in `n` as consecutive sequences, and the values should be the counts of these sequences. The function should handle both positive and negative integers, but... | def count_digits(n):
"""
Returns a dictionary where the keys are the digits present in n as consecutive sequences,
and the values are the counts of these sequences. The function handles both positive and
negative integers, ignoring the negative sign when counting digits.
:param n: An integer
... | [
"assert count_digits(112233) == {'1': 2, '2': 2, '3': 2}",
"assert count_digits(-12321) == {'1': 1, '2': 1, '3': 1, '2': 1, '1': 1}",
"assert count_digits(111223) == {'1': 3, '2': 2, '3': 1}",
"assert count_digits(0) == {'0': 1}",
"assert count_digits(-1001) == {'1': 1, '0': 2, '1': 1}",
"assert count_dig... | count_digits | def count_digits(n): | 0.9 | generic |
b367f3debe6b7bf1346d91f8e0cead1e | You are given a list of strings. Your task is to implement a function that returns a dictionary with the frequency of each unique word in the list. Words should be treated in a case-insensitive manner, but punctuation should be considered part of the word.
**Input:**
- A list of strings, where each string can contain... | def word_frequencies(strings):
"""
Returns a dictionary with the frequency of each unique word in the list of strings.
Words are treated in a case-insensitive manner, but punctuation is considered part of the word.
:param strings: List of strings containing words.
:return: Dictionary with words as ... | [
"assert word_frequencies([\"Hello world\", \"hello\"]) == {'hello': 2, 'world': 1}",
"assert word_frequencies([\"Python is great\", \"python is fun\"]) == {'python': 2, 'is': 2, 'great': 1, 'fun': 1}",
"assert word_frequencies([\"A quick brown fox\", \"A lazy dog\"]) == {'a': 2, 'quick': 1, 'brown': 1, 'fox': 1... | word_frequencies | def word_frequencies(strings): | 1 | generic |
9ea7479ad0bc71125f060ed73dcb817f | You are given two lists of integers. Your task is to write a Python function `find_common_elements` that identifies and returns a list of common elements between the two lists. The function must not utilize any set operations. Instead, it should employ loops and basic list operations to determine the common elements. E... | def find_common_elements(list1, list2):
"""
Finds and returns a list of common elements between two lists without using set operations.
Parameters:
list1 (list): The first list of integers.
list2 (list): The second list of integers.
Returns:
list: A list of integers representing th... | [
"assert find_common_elements([1, 2, 3], [3, 4, 5]) == [3]",
"assert find_common_elements([1, 2, 2, 3, 4], [3, 4, 4, 5, 6]) == [3, 4]",
"assert find_common_elements([], [1, 2, 3]) == []",
"assert find_common_elements([1, 2, 3], []) == []",
"assert find_common_elements([], []) == []",
"assert find_common_el... | find_common_elements | def find_common_elements(list1, list2): | 1 | generic |
8f5d744c2a6c0cfabb9786ef034d19e0 | You are given a binary string `data` representing a series of HDLC frames, which may contain errors or missing LSAP fields. Each valid frame consists of a remote LSAP, a local LSAP, and an LLC quality byte. The remote and local LSAP fields are single bytes, and the LLC quality byte is always `0x00`. Your task is to par... | def extract_frames(data):
"""
Extracts valid HDLC frames from a binary string.
Parameters:
data (bytes): A binary string representing a series of HDLC frames.
Returns:
list of tuples: Each tuple contains the remote LSAP (as a byte) and the position of the next frame.
"""
frames = []
... | [
"assert extract_frames(b'\\x01\\x02\\x00') == [(b'\\x01', 3)]",
"assert extract_frames(b'\\x01\\x02\\x00\\x03\\x04\\x00') == [(b'\\x01', 3), (b'\\x03', 6)]",
"assert extract_frames(b'\\x01\\x02\\x01\\x03\\x04\\x00') == [(b'\\x03', 6)]",
"assert extract_frames(b'\\x01\\x02\\x00\\x03\\x04\\x01') == [(b'\\x01', ... | extract_frames | def extract_frames(data): | 1 | generic |
620c78f405685bf50aa6f0fb6bd93403 | You are given an unsorted list of integers `lst` and a target integer `target`. Your task is to implement a function `optimize_linear_search` that performs a linear search to find the first occurrence of `target` in `lst`. If `target` is found, return its index; otherwise, return -1. The list may contain duplicate valu... | def optimize_linear_search(lst, target):
"""
Perform a linear search to find the first occurrence of the target in the list.
Parameters:
lst (list of int): The list of integers to search through.
target (int): The target integer to find.
Returns:
int: The index of the first occurre... | [
"assert optimize_linear_search([1, 2, 3, 4, 5], 3) == 2",
"assert optimize_linear_search([10, 20, 30, 40, 50], 20) == 1",
"assert optimize_linear_search([5, 5, 5, 5, 5], 5) == 0",
"assert optimize_linear_search([1, 2, 3, 4, 5], 6) == -1",
"assert optimize_linear_search([], 1) == -1",
"assert optimize_line... | optimize_linear_search | def optimize_linear_search(lst, target): | 1 | generic |
282bd462b9b765312f91d69f5bca9f23 | You are tasked with implementing a recursive function in Python to compute the factorial of a given non-negative integer. Your function should handle invalid inputs gracefully by returning an appropriate error message. Specifically, your function should return an error message if the input is not an integer or if it is... | def factorial(n):
"""
Computes the factorial of a given non-negative integer n using recursion.
Handles invalid inputs by returning an appropriate error message.
:param n: A non-negative integer
:return: Factorial of integer n or an error message
"""
if not isinstance(n, int):
retur... | [
"assert factorial(5) == 120",
"assert factorial(1) == 1",
"assert factorial(0) == 1",
"assert factorial(-1) == \"Error: Input must be a non-negative integer.\"",
"assert factorial(2.5) == \"Error: Input must be an integer.\"",
"assert factorial(10) == 3628800",
"assert factorial(3) == 6",
"assert fact... | factorial | def factorial(n): | 1 | generic |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.