{"id": "b1db79989c0e185e02040d31ec3b8763", "problem": "You are given a string `s` consisting of only the characters '(' and ')'. Your task is to determine if the string is balanced. A string is considered balanced if every opening parenthesis '(' has a corresponding closing parenthesis ')' in the correct order. \n\n**Input:**\n- A single string `s` (0 ≤ |s| ≤ 10^5) consisting of '(' and ')'.\n\n**Output:**\n- Return `True` if the string is balanced, otherwise return `False`.\n\n**Sample Input:**\n```\n(()())\n(() \n()()\n)( \n\"\"\n```\n\n**Sample Output:**\n```\nTrue\nFalse\nTrue\nFalse\nTrue\n```", "reference": "def is_balanced_parentheses(s):\n \"\"\"\n Determines if a string of parentheses is balanced.\n \n Args:\n s (str): A string consisting of '(' and ')'.\n \n Returns:\n bool: True if the string is balanced, False otherwise.\n \"\"\"\n stack = []\n for char in s:\n if char == '(':\n stack.append(char)\n elif char == ')':\n if not stack:\n return False\n stack.pop()\n return len(stack) == 0\n\n# Test cases\nprint(is_balanced_parentheses(\"(()())\")) # Expected output: True\nprint(is_balanced_parentheses(\"(()\")) # Expected output: False\nprint(is_balanced_parentheses(\"()()\")) # Expected output: True\nprint(is_balanced_parentheses(\")(\")) # Expected output: False\nprint(is_balanced_parentheses(\"\")) # Expected output: True", "tests": ["assert is_balanced_parentheses(\"(()())\") == True", "assert is_balanced_parentheses(\"(()\") == False", "assert is_balanced_parentheses(\"()()\") == True", "assert is_balanced_parentheses(\")(\") == False", "assert is_balanced_parentheses(\"\") == True", "assert is_balanced_parentheses(\"((((()))))\") == True", "assert is_balanced_parentheses(\"((())\") == False", "assert is_balanced_parentheses(\"())(()\") == False", "assert is_balanced_parentheses(\"()(()())\") == True", "assert is_balanced_parentheses(\"()()()()\") == True"], "function": "is_balanced_parentheses", "signature": "def is_balanced_parentheses(s):", "score": 1.0, "domain": "algorithmic"} {"id": "fa993a17b5254b1d13e2aac2d22e2dc2", "problem": "You are given a nested list structure containing elements of various data types, including other lists. Your task is to implement a function `flatten_list` that recursively flattens this nested list into a single-level list. The function should handle any level of nesting and maintain the order of elements as they appear in the original nested list.\n\n**Input:**\n- A nested list `nested_list` where each element can be of any data type, including another list.\n\n**Output:**\n- A flat list containing all elements from the nested list in the same order.\n\n**Sample Input:**\n```python\n[1, [2, [3, 4], 5], 6, [7, 8]]\n```\n\n**Sample Output:**\n```python\n[1, 2, 3, 4, 5, 6, 7, 8]\n```", "reference": "def flatten_list(nested_list):\n \"\"\"\n Recursively flattens a nested list into a single-level list.\n\n Parameters:\n nested_list (list): A list that may contain elements of any data type, including other lists.\n\n Returns:\n list: A flat list containing all elements from the nested list in the same order.\n \"\"\"\n flat_list = []\n for element in nested_list:\n if isinstance(element, list):\n flat_list.extend(flatten_list(element))\n else:\n flat_list.append(element)\n return flat_list", "tests": ["assert flatten_list([1, 2, [3, 4], [5, [6, 7]]]) == [1, 2, 3, 4, 5, 6, 7]", "assert flatten_list([[], [1, 2, [3]], 4]) == [1, 2, 3, 4]", "assert flatten_list([1, [2, [3, [4, [5]]]]]) == [1, 2, 3, 4, 5]", "assert flatten_list([[[[[]]]]]) == []", "assert flatten_list([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]", "assert flatten_list([]) == []", "assert flatten_list([[[[1]]], 2, [3, [4, [5]]]]) == [1, 2, 3, 4, 5]", "assert flatten_list(['a', ['b', ['c', ['d']]], 'e']) == ['a', 'b', 'c', 'd', 'e']", "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, [8, [9, []]]]]]]]]) == [1, 2, 3, 4, 5, 6, 7, 8, 9]"], "function": "flatten_list", "signature": "def flatten_list(nested_list):", "score": 0.8, "domain": "generic"} {"id": "c9659dc9c1267943177689f67f56d769", "problem": "You are tasked with implementing a function to compute the factorial of a given non-negative integer `n` using the memoization technique to optimize repeated calculations. Your function should efficiently handle multiple queries for different values of `n`.\n\n**Input:**\n- A single integer `n` (0 ≤ n ≤ 20).\n\n**Output:**\n- Return the factorial of `n`.\n\n**Sample Input:**\n```\n5\n```\n\n**Sample Output:**\n```\n120\n```", "reference": "def factorial_memo(n, memo=None):\n \"\"\"\n Calculate the factorial of a number using memoization.\n\n :param n: Non-negative integer for which the factorial is to be calculated.\n :param memo: Dictionary to store previously computed factorials.\n :return: Factorial of the number n.\n \"\"\"\n if memo is None:\n memo = {}\n if n in memo:\n return memo[n]\n if n <= 1:\n return 1\n else:\n memo[n] = n * factorial_memo(n-1, memo)\n return memo[n]", "tests": ["assert factorial_memo(0) == 1", "assert factorial_memo(1) == 1", "assert factorial_memo(2) == 2", "assert factorial_memo(3) == 6", "assert factorial_memo(4) == 24", "assert factorial_memo(5) == 120", "assert factorial_memo(6) == 720", "assert factorial_memo(10) == 3628800", "assert factorial_memo(15) == 1307674368000", "assert factorial_memo(20) == 2432902008176640000"], "function": "factorial_memo", "signature": "def factorial_memo(n, memo=None):", "score": 1.0, "domain": "algorithmic"} {"id": "cb7e97367f21060b86f8451d8fcc8ba2", "problem": "You are given a string `text` containing a mix of words and email addresses. Your task is to write a Python function named `extract_emails` that extracts all valid email addresses from the string and returns them as a list. A valid email address consists of a username, an \"@\" symbol, and a domain name. The username can include letters (both uppercase and lowercase), digits, dots, underscores, percent signs, plus signs, and hyphens. The domain name can include letters, digits, dots, and hyphens, and must end with a dot followed by at least two letters.\n\n**Input:**\n- A single string `text` (1 ≤ len(text) ≤ 1000).\n\n**Output:**\n- A list of strings, each representing a valid email address found in the input string.\n\n**Sample Input:**\n```\nPlease contact us at support@example.com or sales@example.com for further information. Alternatively, you can reach out to john.doe@example.co.uk or jane.smith@another-example.org.\n```\n\n**Sample Output:**\n```\n['support@example.com', 'sales@example.com', 'john.doe@example.co.uk', 'jane.smith@another-example.org']\n```", "reference": "import re\n\ndef extract_emails(text):\n \"\"\"\n Extracts all valid email addresses from the given text.\n\n Parameters:\n text (str): The input string containing potential email addresses.\n\n Returns:\n list: A list of valid email addresses found in the input string.\n \"\"\"\n email_pattern = r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}'\n return re.findall(email_pattern, text)\n\n# Test the function with provided text\ntext = \"Please contact us at support@example.com or sales@example.com for further information. Alternatively, you can reach out to john.doe@example.co.uk or jane.smith@another-example.org.\"\nprint(extract_emails(text))", "tests": ["assert extract_emails(\"Please contact us at support@example.com\") == [\"support@example.com\"]", "assert extract_emails(\"No emails here!\") == []", "assert extract_emails(\"john.doe@example.co.uk and jane.smith@another-example.org\") == [\"john.doe@example.co.uk\", \"jane.smith@another-example.org\"]", "assert extract_emails(\"Invalid email @example.com and valid one test@domain.com\") == [\"test@domain.com\"]", "assert extract_emails(\"Multiple emails: first@domain.com, second@domain.com, third@domain.com\") == [\"first@domain.com\", \"second@domain.com\", \"third@domain.com\"]", "assert extract_emails(\"Email with subdomain: user@mail.example.com\") == [\"user@mail.example.com\"]", "assert extract_emails(\"Email with numbers: user123@domain456.com\") == [\"user123@domain456.com\"]", "assert extract_emails(\"Special characters in email: user.name+tag+sorting@example.com\") == [\"user.name+tag+sorting@example.com\"]", "assert extract_emails(\"Email with hyphen: user-name@domain-name.com\") == [\"user-name@domain-name.com\"]", "assert extract_emails(\"Email with dots: user.name@domain.name.com\") == [\"user.name@domain.name.com\"]"], "function": "extract_emails", "signature": "def extract_emails(text):", "score": 1.0, "domain": "generic"} {"id": "3c72f291a974e7ba68033a2f7998f7e5", "problem": "You are given a string `s` representing a Roman numeral. Your task is to write a function that converts this Roman numeral to its corresponding integer value. Assume that the input string is a valid Roman numeral and the integer value is within the range of 1 to 3999.\n\n**Sample Input:**\n```\n\"MCMXCIV\"\n```\n\n**Sample Output:**\n```\n1994\n```", "reference": "def roman_to_int(s: str) -> int:\n \"\"\"\n Convert a Roman numeral string to an integer.\n \n :param s: A string representing a Roman numeral.\n :return: The integer value corresponding to the Roman numeral.\n \"\"\"\n roman_to_val = {\n 'I': 1,\n 'V': 5,\n 'X': 10,\n 'L': 50,\n 'C': 100,\n 'D': 500,\n 'M': 1000\n }\n integer_value = 0\n prev_value = 0\n for char in reversed(s):\n curr_value = roman_to_val[char]\n if curr_value < prev_value:\n integer_value -= curr_value\n else:\n integer_value += curr_value\n prev_value = curr_value\n return integer_value", "tests": ["assert roman_to_int(\"III\") == 3", "assert roman_to_int(\"IV\") == 4", "assert roman_to_int(\"IX\") == 9", "assert roman_to_int(\"LVIII\") == 58", "assert roman_to_int(\"MCMXCIV\") == 1994", "assert roman_to_int(\"XL\") == 40", "assert roman_to_int(\"CD\") == 400", "assert roman_to_int(\"CM\") == 900", "assert roman_to_int(\"MMMCMXCIX\") == 3999", "assert roman_to_int(\"I\") == 1"], "function": "roman_to_int", "signature": "def roman_to_int(s: str) -> int:", "score": 1.0, "domain": "generic"} {"id": "b5f3ac8e011c716d0fe56456a4324465", "problem": "You are given two lists of integers, `list1` and `list2`. Your task is to implement a function `find_common_elements(list1, list2)` that returns a list of integers representing the common elements between the two lists. The returned list should contain unique elements and be sorted in ascending order.\n\n**Input:**\n- Two lists of integers, `list1` and `list2`.\n\n**Output:**\n- A list of integers containing the unique common elements, sorted in ascending order.\n\n**Sample Input:**\n```python\nlist1 = [1, 2, 2, 3, 4]\nlist2 = [3, 4, 4, 5, 6]\n```\n\n**Sample Output:**\n```python\n[3, 4]\n```", "reference": "def find_common_elements(list1, list2):\n \"\"\"\n Returns a list of unique common elements between two lists, sorted in ascending order.\n\n :param list1: List of integers.\n :param list2: List of integers.\n :return: List of unique common elements, sorted in ascending order.\n \"\"\"\n set1 = set(list1)\n set2 = set(list2)\n common_set = set1.intersection(set2)\n common_list = sorted(list(common_set))\n return common_list", "tests": ["assert find_common_elements([1, 2, 3], [2, 3, 4]) == [2, 3]", "assert find_common_elements([5, 6, 7], [8, 9, 10]) == []", "assert find_common_elements([1, 1, 2, 2], [2, 2, 3, 3]) == [2]", "assert find_common_elements([], [1, 2, 3]) == []", "assert find_common_elements([1, 2, 3], []) == []", "assert find_common_elements([], []) == []", "assert find_common_elements([10, 20, 30], [30, 20, 10]) == [10, 20, 30]", "assert find_common_elements([1, 3, 5, 7], [2, 4, 6, 8]) == []", "assert find_common_elements([1, 2, 3, 4, 5], [3, 4, 5, 6, 7]) == [3, 4, 5]", "assert find_common_elements([-1, -2, -3], [-3, -2, -1]) == [-3, -2, -1]"], "function": "find_common_elements", "signature": "def find_common_elements(list1, list2):", "score": 1.0, "domain": "generic"} {"id": "03ac780d80b1a3316fec38f8e055a435", "problem": "You are given a list of words and a set of unique lowercase letters. Your task is to determine if there exists a word in the list that can be formed using the letters provided exactly once and also forms a palindrome. A palindrome is a string that reads the same forward and backward.\n\nWrite a function `canFormValidWord(wordList, letters)` that takes in a list of words and a string of letters. The function should return `True` if there exists a word in the word list that can be formed using the letters provided and also forms a palindrome, and `False` otherwise.\n\n**Constraints:**\n- The letters string contains unique lowercase letters.\n- Each letter in the letters string can only be used once.\n- The word list consists of lowercase strings.\n\n**Sample Input:**\n```\nwordList = [\"cat\", \"dog\", \"tac\", \"racecar\"]\nletters = \"act\"\n```\n**Sample Output:**\n```\nFalse\n```\n\n**Sample Input:**\n```\nwordList = [\"cat\", \"dog\", \"tac\", \"racecar\"]\nletters = \"racecar\"\n```\n**Sample Output:**\n```\nTrue\n```", "reference": "def canFormValidWord(wordList, letters):\n \"\"\"\n Determines if there exists a word in the word list that can be formed using the letters provided\n exactly once and also forms a palindrome.\n\n :param wordList: List of words (strings) to check.\n :param letters: String of unique lowercase letters available for forming words.\n :return: True if a valid word can be formed, False otherwise.\n \"\"\"\n def is_palindrome(word):\n \"\"\"\n Checks if a given word is a palindrome.\n\n :param word: String to check.\n :return: True if the word is a palindrome, False otherwise.\n \"\"\"\n return word == word[::-1]\n \n def can_form_with_letters(word, letters):\n \"\"\"\n Checks if a word can be formed using the given letters exactly once.\n\n :param word: String to form.\n :param letters: String of available letters.\n :return: True if the word can be formed, False otherwise.\n \"\"\"\n letter_count = {char: 0 for char in letters}\n for char in word:\n if char not in letter_count:\n return False\n letter_count[char] += 1\n if letter_count[char] > 1:\n return False\n return all(count == 1 for count in letter_count.values())\n \n for word in wordList:\n if is_palindrome(word) and can_form_with_letters(word, letters):\n return True\n return False\n\n# Example usage:\nwordList1 = [\"cat\", \"dog\", \"tac\", \"racecar\"]\nletters1 = \"act\"\nprint(canFormValidWord(wordList1, letters1)) # Output: False\n\nwordList2 = [\"cat\", \"dog\", \"tac\", \"racecar\"]\nletters2 = \"racecar\"\nprint(canFormValidWord(wordList2, letters2)) # Output: True\n\nwordList3 = [\"cat\", \"dog\", \"tac\", \"deified\"]\nletters3 = \"deified\"\nprint(canFormValidWord(wordList3, letters3)) # Output: True\n\nwordList4 = [\"cat\", \"dog\", \"tac\", \"level\"]\nletters4 = \"lvle\"\nprint(canFormValidWord(wordList4, letters4)) # Output: True\n\nwordList5 = [\"cat\", \"dog\", \"tac\", \"level\"]\nletters5 = \"abc\"\nprint(canFormValidWord(wordList5, letters5)) # Output: False", "tests": ["assert canFormValidWord([\"cat\", \"dog\", \"tac\"], \"act\") == False", "assert canFormValidWord([\"cat\", \"dog\", \"tac\", \"racecar\"], \"racecar\") == True", "assert canFormValidWord([\"cat\", \"dog\", \"tac\", \"deified\"], \"deified\") == True", "assert canFormValidWord([\"cat\", \"dog\", \"tac\", \"level\"], \"lvle\") == True", "assert canFormValidWord([\"cat\", \"dog\", \"tac\", \"level\"], \"abc\") == False", "assert canFormValidWord([\"noon\", \"civic\", \"rotor\"], \"nooc\") == True", "assert canFormValidWord([\"noon\", \"civic\", \"rotor\"], \"civic\") == True", "assert canFormValidWord([\"noon\", \"civic\", \"rotor\"], \"rotor\") == True", "assert canFormValidWord([\"noon\", \"civic\", \"rotor\"], \"abcd\") == False", "assert canFormValidWord([\"a\", \"b\", \"c\"], \"a\") == False"], "function": "canFormValidWord", "signature": "def canFormValidWord(wordList, letters):", "score": 0.3, "domain": "generic"} {"id": "9ec74458c4454f16fdae0dd8f38fddb4", "problem": "You are given a string `movements` representing a series of movements on a 2D grid. Each movement is specified by a single character indicating the direction (U for up, D for down, L for left, R for right) followed by a positive integer indicating the number of steps to move in that direction. Movements are separated by commas. Your task is to implement a function `parse_movements` that parses the input string and returns a list of tuples, where each tuple contains the direction as a string and the number of steps as an integer. If the input string is malformed or contains invalid characters, the function should raise a `ValueError` with an appropriate message.\n\n**Sample Input:**\n```\n\"U10,R5,D2,L3\"\n```\n\n**Sample Output:**\n```\n[('U', 10), ('R', 5), ('D', 2), ('L', 3)]\n```", "reference": "def parse_movements(movements: str) -> list:\n \"\"\"\n Parses a string of movements on a 2D grid and returns a list of tuples.\n \n Each tuple contains a direction ('U', 'D', 'L', 'R') and the number of steps as an integer.\n Raises ValueError if the input string is malformed or contains invalid characters.\n \n :param movements: A string representing the series of movements.\n :return: A list of tuples with direction and steps.\n \"\"\"\n movement_commands = movements.split(',')\n parsed_movements = []\n \n for command in movement_commands:\n command = command.strip()\n if not command:\n continue\n \n if len(command) < 2:\n raise ValueError(f\"Malformed command: {command}\")\n \n direction = command[0]\n steps_str = command[1:]\n \n if direction not in 'UDLR':\n raise ValueError(f\"Invalid direction: {direction}\")\n \n try:\n steps = int(steps_str)\n except ValueError:\n raise ValueError(f\"Invalid steps: {steps_str}\")\n \n if steps <= 0:\n raise ValueError(f\"Steps must be positive: {steps}\")\n\n parsed_movements.append((direction, steps))\n \n return parsed_movements", "tests": ["assert parse_movements(\"U10,R5,D2,L3\") == [('U', 10), ('R', 5), ('D', 2), ('L', 3)]", "assert parse_movements(\"U1,D1,L1,R1\") == [('U', 1), ('D', 1), ('L', 1), ('R', 1)]", "assert parse_movements(\"L5, R10, U20, D30\") == [('L', 5), ('R', 10), ('U', 20), ('D', 30)]", "assert parse_movements(\"U100\") == [('U', 100)]", "assert parse_movements(\"D5, L5, R5, U5\") == [('D', 5), ('L', 5), ('R', 5), ('U', 5)]", "assert parse_movements(\"U10, D10, L10, R10, U10\") == [('U', 10), ('D', 10), ('L', 10), ('R', 10), ('U', 10)]", "assert parse_movements(\"U1, D2, L3, R4, U5, D6, L7, R8\") == [('U', 1), ('D', 2), ('L', 3), ('R', 4), ('U', 5), ('D', 6), ('L', 7), ('R', 8)]", "assert parse_movements(\"U10, D10, L10, R10, U10, D10, L10, R10\") == [('U', 10), ('D', 10), ('L', 10), ('R', 10), ('U', 10), ('D', 10), ('L', 10), ('R', 10)]", "assert parse_movements(\"U10, D10, L10, R10, U10, D10, L10, R10, U10, D10, L10, R10\") == [('U', 10), ('D', 10), ('L', 10), ('R', 10), ('U', 10), ('D', 10), ('L', 10), ('R', 10), ('U', 10), ('D', 10), ('L', 10), ('R', 10)]", "assert parse_movements(\"U10, D10, L10, R10, U10, D10, L10, R10, U10, D10, L10, R10, U10, D10, L10, R10\") == [('U', 10), ('D', 10), ('L', 10), ('R', 10), ('U', 10), ('D', 10), ('L', 10), ('R', 10), ('U', 10), ('D', 10), ('L', 10), ('R', 10), ('U', 10), ('D', 10), ('L', 10), ('R', 10)]"], "function": "parse_movements", "signature": "def parse_movements(movements: str) -> list:", "score": 1.0, "domain": "generic"} {"id": "e070bfa1ff02e0149640b72507bfc525", "problem": "You are given a string `text` containing words separated by spaces and possibly including punctuation. Your task is to implement a function `find_highest_frequency_word(text)` that returns the word with the highest frequency in the text. If multiple words have the same highest frequency, return the one that appears first in the text. Assume words are case-insensitive and punctuation should be ignored.\n\n**Input:**\n- A single string `text` (1 ≤ len(text) ≤ 10^5) containing words and punctuation.\n\n**Output:**\n- A single string representing the word with the highest frequency.\n\n**Sample Input:**\n```\n\"Hello world! Hello everyone. Welcome to the world of Python.\"\n```\n\n**Sample Output:**\n```\n\"hello\"\n```", "reference": "import string\nfrom collections import Counter\n\ndef find_highest_frequency_word(text):\n \"\"\"\n Returns the word with the highest frequency in the given text.\n If multiple words have the same frequency, returns the first one appearing in the text.\n \n :param text: A string containing words and punctuation.\n :return: The word with the highest frequency.\n \"\"\"\n # Remove punctuation and convert to lowercase\n text = text.translate(str.maketrans('', '', string.punctuation)).lower()\n \n # Split the text into words\n words = text.split()\n \n # Count the frequency of each word\n word_count = Counter(words)\n \n # Find the highest frequency\n max_frequency = max(word_count.values())\n \n # Find the first word with the highest frequency\n for word in words:\n if word_count[word] == max_frequency:\n return word", "tests": ["assert find_highest_frequency_word(\"Hello world! Hello everyone.\") == \"hello\"", "assert find_highest_frequency_word(\"Python is great, and python is fun.\") == \"python\"", "assert find_highest_frequency_word(\"This is a test. This test is only a test.\") == \"test\"", "assert find_highest_frequency_word(\"One fish, two fish, red fish, blue fish.\") == \"fish\"", "assert find_highest_frequency_word(\"To be or not to be, that is the question.\") == \"to\"", "assert find_highest_frequency_word(\"A quick brown fox jumps over the lazy dog.\") == \"a\"", "assert find_highest_frequency_word(\"Repeat repeat repeat repeat.\") == \"repeat\"", "assert find_highest_frequency_word(\"Unique words only here.\") == \"unique\"", "assert find_highest_frequency_word(\"Punctuation, should! not? affect: the; result.\") == \"punctuation\"", "assert find_highest_frequency_word(\"\") == \"\""], "function": "find_highest_frequency_word", "signature": "def find_highest_frequency_word(text):", "score": 0.9, "domain": "generic"} {"id": "e4a7fae443fc4a4e356959c652ed9e56", "problem": "You are given a list of integers representing scores. Your task is to write a Python function that returns a list of strings representing the relative ranks of these scores. The highest score should receive the rank \"Gold Medal\", the second-highest \"Silver Medal\", and the third-highest \"Bronze Medal\". All other scores should receive ranks as integers starting from 4. If multiple scores are the same, they should receive the same rank, and the subsequent ranks should be adjusted accordingly.\n\n**Sample Input:**\n```python\n[10, 3, 8, 9, 4]\n```\n\n**Sample Output:**\n```python\n['Gold Medal', 'Bronze Medal', 'Silver Medal', 'Gold Medal', 'Silver Medal']\n```", "reference": "def find_relative_ranks(nums):\n \"\"\"\n Returns a list of strings representing the relative ranks of the integers in the input list.\n \n :param nums: List of integers representing scores.\n :return: List of strings representing the relative ranks.\n \"\"\"\n indexed_nums = list(enumerate(nums))\n indexed_nums.sort(key=lambda x: x[1], reverse=True)\n ranks = [\"Gold Medal\", \"Silver Medal\", \"Bronze Medal\"] + [str(i + 4) for i in range(len(nums) - 3)]\n if len(nums) < 4:\n ranks = ranks[:len(nums)]\n rank_dict = {index: ranks[i] for i, (index, _) in enumerate(indexed_nums)}\n return [rank_dict[i] for i in range(len(nums))]", "tests": ["assert find_relative_ranks([10, 3, 8, 9, 4]) == ['Gold Medal', 'Bronze Medal', 'Silver Medal', 'Gold Medal', 'Silver Medal']", "assert find_relative_ranks([5, 5, 5, 5]) == ['Gold Medal', 'Gold Medal', 'Gold Medal', 'Gold Medal']", "assert find_relative_ranks([1]) == ['Gold Medal']", "assert find_relative_ranks([1, 2]) == ['Silver Medal', 'Gold Medal']", "assert find_relative_ranks([1, 2, 3]) == ['Bronze Medal', 'Silver Medal', 'Gold Medal']", "assert find_relative_ranks([3, 3, 3, 2, 2, 1]) == ['Gold Medal', 'Gold Medal', 'Gold Medal', 'Silver Medal', 'Silver Medal', 'Bronze Medal']", "assert find_relative_ranks([10, 20, 20, 30, 30, 30]) == ['Bronze Medal', 'Silver Medal', 'Silver Medal', 'Gold Medal', 'Gold Medal', 'Gold Medal']", "assert find_relative_ranks([4, 5, 6, 7, 8, 9, 10]) == ['Bronze Medal', '4', '5', '6', '7', 'Silver Medal', 'Gold Medal']", "assert find_relative_ranks([100, 90, 90, 80, 70]) == ['Gold Medal', 'Silver Medal', 'Silver Medal', 'Bronze Medal', '4']", "assert find_relative_ranks([]) == []"], "function": "find_relative_ranks", "signature": "def find_relative_ranks(nums):", "score": 0.4, "domain": "algorithmic"} {"id": "b86f2d9de2f3a9fd76010224c22045f3", "problem": "You are given an integer `n`. Your task is to reverse the digits of `n`. If the reversed integer exceeds the 32-bit signed integer range, return 0. The 32-bit signed integer range is from \\(-2^{31}\\) to \\(2^{31} - 1\\).\n\n**Sample Input:**\n```\n-123456789\n```\n\n**Sample Output:**\n```\n0\n```", "reference": "def reverse_integer(n):\n \"\"\"\n Reverses the digits of the given integer n.\n If the reversed integer overflows the 32-bit signed integer range, returns 0.\n \n :param n: Integer to be reversed\n :return: Reversed integer or 0 if it overflows\n \"\"\"\n sign = -1 if n < 0 else 1\n reversed_n = sign * int(str(abs(n))[::-1])\n if reversed_n < -2**31 or reversed_n > 2**31 - 1:\n return 0\n return reversed_n\n\n# Test with the given input\nn = -123456789\nprint(reverse_integer(n)) # Output should be 0 due to overflow", "tests": ["assert reverse_integer(123) == 321", "assert reverse_integer(-123) == -321", "assert reverse_integer(120) == 21", "assert reverse_integer(0) == 0", "assert reverse_integer(1534236469) == 0", "assert reverse_integer(-2147483648) == 0", "assert reverse_integer(2147483647) == 0", "assert reverse_integer(1000000000) == 1", "assert reverse_integer(-1000000000) == -1", "assert reverse_integer(9646324351) == 0"], "function": "reverse_integer", "signature": "def reverse_integer(n):", "score": 0.9, "domain": "algorithmic"} {"id": "479db6c8512b23ba85e5ca316c04c7fe", "problem": "You are given a string `text` representing a piece of writing. Your task is to implement a function `classify_text(text)` that analyzes the text and returns a dictionary with the following statistics:\n\n- `word_count`: The total number of words in the text.\n- `sentence_count`: The total number of sentences in the text. Sentences are considered to be separated by '.', '!', or '?'.\n- `paragraph_count`: The total number of paragraphs in the text. Paragraphs are considered to be separated by newline characters ('\\n').\n- `avg_sentence_length`: The average number of words per sentence. If there are no sentences, return 0.\n- `avg_paragraph_length`: The average number of sentences per paragraph. If there are no paragraphs, return 0.\n\n**Input:**\n- A single string `text` (1 ≤ len(text) ≤ 10,000).\n\n**Output:**\n- A dictionary with the keys `word_count`, `sentence_count`, `paragraph_count`, `avg_sentence_length`, and `avg_paragraph_length`.\n\n**Sample Input:**\n```\n\"The quick brown fox jumps over the lazy dog. It is a common sentence used for typewriting practice. Another sentence is added to make it a paragraph.\"\n```\n\n**Sample Output:**\n```\n{\n 'word_count': 21,\n 'sentence_count': 3,\n 'paragraph_count': 1,\n 'avg_sentence_length': 7.0,\n 'avg_paragraph_length': 3.0\n}\n```", "reference": "def classify_text(text):\n \"\"\"\n Analyzes the given text and returns a dictionary with word count, sentence count,\n paragraph count, average sentence length, and average paragraph length.\n \n :param text: A string representing the text to be analyzed.\n :return: A dictionary with the analysis results.\n \"\"\"\n # Count the number of words\n words = text.split()\n word_count = len(words)\n \n # Count the number of sentences\n import re\n sentences = re.split(r'[.!?]', text)\n sentence_count = sum(1 for sentence in sentences if sentence.strip())\n \n # Count the number of paragraphs\n paragraphs = text.split('\\n')\n paragraph_count = sum(1 for paragraph in paragraphs if paragraph.strip())\n \n # Calculate the average sentence length (in words)\n avg_sentence_length = word_count / sentence_count if sentence_count > 0 else 0\n \n # Calculate the average paragraph length (in sentences)\n avg_paragraph_length = sentence_count / paragraph_count if paragraph_count > 0 else 0\n \n return {\n 'word_count': word_count,\n 'sentence_count': sentence_count,\n 'paragraph_count': paragraph_count,\n 'avg_sentence_length': avg_sentence_length,\n 'avg_paragraph_length': avg_paragraph_length\n }\n\n# Example usage\ntext = \"The quick brown fox jumps over the lazy dog. It is a common sentence used for typewriting practice. Another sentence is added to make it a paragraph.\"\nresult = classify_text(text)\nprint(result)", "tests": ["assert classify_text(\"Hello world!\") == {'word_count': 2, 'sentence_count': 1, 'paragraph_count': 1, 'avg_sentence_length': 2.0, 'avg_paragraph_length': 1.0}", "assert classify_text(\"This is a test. This is only a test.\") == {'word_count': 8, 'sentence_count': 2, 'paragraph_count': 1, 'avg_sentence_length': 4.0, 'avg_paragraph_length': 2.0}", "assert classify_text(\"One.\\nTwo.\\nThree.\") == {'word_count': 3, 'sentence_count': 3, 'paragraph_count': 3, 'avg_sentence_length': 1.0, 'avg_paragraph_length': 1.0}", "assert classify_text(\"\") == {'word_count': 0, 'sentence_count': 0, 'paragraph_count': 0, 'avg_sentence_length': 0.0, 'avg_paragraph_length': 0.0}", "assert classify_text(\"No punctuation\") == {'word_count': 2, 'sentence_count': 1, 'paragraph_count': 1, 'avg_sentence_length': 2.0, 'avg_paragraph_length': 1.0}", "assert classify_text(\"Multiple... periods... here...\") == {'word_count': 3, 'sentence_count': 3, 'paragraph_count': 1, 'avg_sentence_length': 1.0, 'avg_paragraph_length': 3.0}", "assert classify_text(\"Short.\\n\\nLonger paragraph with multiple sentences. And another one!\") == {'word_count': 11, 'sentence_count': 4, 'paragraph_count': 3, 'avg_sentence_length': 2.75, 'avg_paragraph_length': 1.3333333333333333}", "assert classify_text(\"Newlines\\n\\n\\nare\\nignored\\n\\n\\nproperly.\") == {'word_count': 4, 'sentence_count': 1, 'paragraph_count': 2, 'avg_sentence_length': 4.0, 'avg_paragraph_length': 0.5}", "assert classify_text(\"Mixed\\nparagraphs.\\n\\nWith\\nvarious.\\nsentences!\") == {'word_count': 7, 'sentence_count': 4, 'paragraph_count': 3, 'avg_sentence_length': 1.75, 'avg_paragraph_length': 1.3333333333333333}", "assert classify_text(\"Edge case.\\n\\n\\n\\n\\n\") == {'word_count': 2, 'sentence_count': 1, 'paragraph_count': 2, 'avg_sentence_length': 2.0, 'avg_paragraph_length': 0.5}"], "function": "classify_text", "signature": "def classify_text(text):", "score": 0.5, "domain": "generic"} {"id": "277b28045fdf9448667025c3437d1c9c", "problem": "You are given a sorted list of unique integers, `numbers`, and a target integer, `target`. Your task is to determine the index of the first integer in `numbers` that is strictly greater than `target` and is also a prime number. If no such integer exists, return `-1`.\n\n**Input:**\n- The first line contains an integer `n` (1 ≤ n ≤ 10^5), the number of elements in the list `numbers`.\n- The second line contains `n` space-separated integers, representing the sorted list `numbers`.\n- The third line contains an integer `target` (-10^9 ≤ target ≤ 10^9).\n\n**Output:**\n- Print a single integer, the index of the first integer in `numbers` that is strictly greater than `target` and is a prime number. If no such integer exists, print `-1`.\n\n**Sample Input:**\n```\n5\n1 3 5 7 9\n4\n```\n\n**Sample Output:**\n```\n2\n```", "reference": "def is_prime(n):\n \"\"\"Check if a number is a prime number.\"\"\"\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == 0 or n % 3 == 0:\n return False\n i = 5\n while i * i <= n:\n if n % i == 0 or n % (i + 2) == 0:\n return False\n i += 6\n return True\n\ndef find_first_greater_prime_index(numbers, target):\n \"\"\"Find the index of the first occurrence of an integer in numbers that is strictly greater than target and is a prime number.\"\"\"\n left, right = 0, len(numbers) - 1\n result = -1\n \n while left <= right:\n mid = (left + right) // 2\n if numbers[mid] > target:\n if is_prime(numbers[mid]):\n result = mid\n right = mid - 1 # Look for a smaller index on the left\n else:\n left = mid + 1 # Look for a greater number on the right\n \n return result\n\n# Example usage:\nnumbers = [1, 3, 5, 7, 9]\ntarget = 4\nprint(find_first_greater_prime_index(numbers, target)) # Output: 2", "tests": ["assert find_first_greater_prime_index([2, 3, 5, 7, 11], 1) == 1", "assert find_first_greater_prime_index([2, 3, 5, 7, 11], 5) == 3", "assert find_first_greater_prime_index([2, 3, 5, 7, 11], 11) == -1", "assert find_first_greater_prime_index([2, 3, 5, 7, 11], 13) == -1", "assert find_first_greater_prime_index([2, 3, 5, 7, 11], 0) == 0", "assert find_first_greater_prime_index([4, 6, 8, 9, 10], 3) == -1", "assert find_first_greater_prime_index([13, 17, 19, 23, 29], 20) == 2", "assert find_first_greater_prime_index([], 5) == -1", "assert find_first_greater_prime_index([2, 3, 5, 7, 11], 7) == 3", "assert find_first_greater_prime_index([2, 3, 5, 7, 11], 6) == 3"], "function": "find_first_greater_prime_index", "signature": "def find_first_greater_prime_index(numbers, target):", "score": 0.7, "domain": "generic"} {"id": "138b5880c3d0375f5e28ea918e2ba885", "problem": "You are given a string `s` consisting of lowercase English letters. Your task is to determine the number of distinct palindromic substrings within `s`. A palindromic substring is defined as a substring that reads the same forwards and backwards.\n\n**Input:**\n- A single string `s` (1 ≤ |s| ≤ 1000).\n\n**Output:**\n- An integer representing the number of distinct palindromic substrings in `s`.\n\n**Sample Input:**\n```\nabba\n```\n\n**Sample Output:**\n```\n6\n```", "reference": "def count_distinct_palindromic_substrings(s: str) -> int:\n \"\"\"\n Returns the number of distinct palindromic substrings in the string s.\n \n :param s: A string consisting of lowercase English letters.\n :return: An integer representing the number of distinct palindromic substrings.\n \"\"\"\n n = len(s)\n palindromes = set()\n\n def expand_around_center(left: int, right: int) -> None:\n while left >= 0 and right < n and s[left] == s[right]:\n palindromes.add(s[left:right+1])\n left -= 1\n right += 1\n\n for center in range(n):\n expand_around_center(center, center)\n expand_around_center(center, center + 1)\n\n return len(palindromes)", "tests": ["assert count_distinct_palindromic_substrings(\"abba\") == 6", "assert count_distinct_palindromic_substrings(\"abc\") == 3", "assert count_distinct_palindromic_substrings(\"racecar\") == 7", "assert count_distinct_palindromic_substrings(\"aaaa\") == 4", "assert count_distinct_palindromic_substrings(\"a\") == 1", "assert count_distinct_palindromic_substrings(\"\") == 0", "assert count_distinct_palindromic_substrings(\"abacdfgdcaba\") == 10", "assert count_distinct_palindromic_substrings(\"noonnoon\") == 10", "assert count_distinct_palindromic_substrings(\"banana\") == 7", "assert count_distinct_palindromic_substrings(\"abcbaba\") == 10"], "function": "count_distinct_palindromic_substrings", "signature": "def count_distinct_palindromic_substrings(s: str) -> int:", "score": 0.5, "domain": "generic"} {"id": "535c19201b49ddd2f70df02b6d6474da", "problem": "You are given a list of words and a sentence. Your task is to determine if any word in the list is a prefix of any word in the sentence. Each word in the sentence should be considered only once. Return `True` if such a prefix exists, otherwise return `False`.\n\n**Input:**\n- A list of words (`words`), where each word is a non-empty string.\n- A sentence (`sentence`), which is a string containing words separated by spaces.\n\n**Output:**\n- A boolean value (`True` or `False`).\n\n**Sample Input:**\n```\nwords = [\"hello\", \"world\"]\nsentence = \"hello there, how are you doing today?\"\n```\n\n**Sample Output:**\n```\nTrue\n```", "reference": "def is_prefix_in_sentence(words, sentence):\n \"\"\"\n Determines if any word in the list `words` is a prefix of any word in the `sentence`.\n \n :param words: List of words to check as prefixes.\n :param sentence: Sentence in which to search for prefixed words.\n :return: True if a prefix is found, False otherwise.\n \"\"\"\n sentence_words = sentence.split()\n for prefix in words:\n for word in sentence_words:\n if word.startswith(prefix):\n return True\n return False\n\n# Example usage:\nwords = [\"hello\", \"world\"]\nsentence = \"hello there, how are you doing today?\"\nprint(is_prefix_in_sentence(words, sentence)) # Output: True", "tests": ["assert is_prefix_in_sentence([\"hello\"], \"hello world\") == True", "assert is_prefix_in_sentence([\"hi\"], \"hello world\") == False", "assert is_prefix_in_sentence([\"world\"], \"hello world\") == True", "assert is_prefix_in_sentence([\"test\"], \"this is a test sentence\") == True", "assert is_prefix_in_sentence([\"prefix\"], \"this is a sentence\") == False", "assert is_prefix_in_sentence([\"a\", \"b\", \"c\"], \"abc def ghi\") == True", "assert is_prefix_in_sentence([\"xyz\"], \"abc def ghi\") == False", "assert is_prefix_in_sentence([\"quick\", \"brown\"], \"the quick brown fox\") == True", "assert is_prefix_in_sentence([\"jump\", \"over\"], \"the lazy dog\") == False", "assert is_prefix_in_sentence([], \"non empty sentence\") == False"], "function": "is_prefix_in_sentence", "signature": "def is_prefix_in_sentence(words, sentence):", "score": 1.0, "domain": "generic"} {"id": "b2ba911e22fa84a2d442b7db9cd40440", "problem": "You are given a string `expression` consisting of parentheses. Your task is to determine if the parentheses in the string are balanced. A string is considered balanced if every opening parenthesis '(' has a corresponding closing parenthesis ')' and they are correctly nested.\n\n**Input:**\n- A single string `expression` (1 ≤ |expression| ≤ 10^5) containing only '(' and ')'.\n\n**Output:**\n- Return `True` if the parentheses are balanced, otherwise return `False`.\n\n**Sample Input:**\n```\n(()) \n(() \n)( \n()()\n```\n\n**Sample Output:**\n```\nTrue\nFalse\nFalse\nTrue\n```", "reference": "def is_balanced_parentheses(expression):\n \"\"\"\n Determines if the parentheses in the given expression are balanced.\n\n :param expression: A string consisting of '(' and ')'.\n :return: True if the parentheses are balanced, False otherwise.\n \"\"\"\n stack = []\n for char in expression:\n if char == '(':\n stack.append(char)\n elif char == ')':\n if not stack:\n return False\n stack.pop()\n return len(stack) == 0", "tests": ["assert is_balanced_parentheses(\"(())\") == True", "assert is_balanced_parentheses(\"(()\") == False", "assert is_balanced_parentheses(\")(\") == False", "assert is_balanced_parentheses(\"()()\") == True", "assert is_balanced_parentheses(\"\") == True", "assert is_balanced_parentheses(\"((((()))))\") == True", "assert is_balanced_parentheses(\"(()))(\") == False", "assert is_balanced_parentheses(\"()(()())\") == True", "assert is_balanced_parentheses(\")(\") == False", "assert is_balanced_parentheses(\"(((((\") == False"], "function": "is_balanced_parentheses", "signature": "def is_balanced_parentheses(expression):", "score": 1.0, "domain": "generic"} {"id": "69e2af2e4c65bceba70203df01b233c7", "problem": "You are given a 2D list `matrix` of positive integers where each row represents an entity and each column represents a type of resource. The value at `matrix[i][j]` indicates the amount of resource `j` that entity `i` has. Your task is to normalize the matrix by rows such that the sum of the values in each row equals 1. If the sum of a row is zero, the row should remain unchanged. Implement the function `normalize_resource_distribution(matrix)` to achieve this. You are not allowed to use any built-in functions or methods that directly operate on rows or columns of a matrix.\n\n**Input:**\n- A 2D list `matrix` of integers where `1 <= len(matrix) <= 100` and `1 <= len(matrix[i]) <= 100` for all `i`.\n\n**Output:**\n- A 2D list `normalized_matrix` where each row is normalized such that the sum of its elements is 1, or remains unchanged if the sum is zero.\n\n**Sample Input:**\n```python\nmatrix = [\n [1, 2, 3],\n [4, 5, 6],\n [0, 0, 0]\n]\n```\n\n**Sample Output:**\n```python\n[\n [0.16666666666666666, 0.3333333333333333, 0.5],\n [0.26666666666666666, 0.3333333333333333, 0.4],\n [0, 0, 0]\n]\n```", "reference": "def normalize_resource_distribution(matrix):\n \"\"\"\n Normalizes the given 2D list (matrix) by rows such that the sum of each row equals 1.\n If the sum of a row is zero, the row remains unchanged.\n \n :param matrix: List[List[int]] - A 2D list of integers representing resource distribution.\n :return: List[List[float]] - A 2D list where each row is normalized.\n \"\"\"\n normalized_matrix = []\n for row in matrix:\n row_sum = 0\n for value in row:\n row_sum += value\n \n normalized_row = []\n for value in row:\n if row_sum != 0:\n normalized_value = value / row_sum\n else:\n normalized_value = 0\n normalized_row.append(normalized_value)\n \n normalized_matrix.append(normalized_row)\n \n return normalized_matrix", "tests": ["assert normalize_resource_distribution([[1, 2, 3], [4, 5, 6]]) == [[0.16666666666666666, 0.3333333333333333, 0.5], [0.26666666666666666, 0.3333333333333333, 0.4]]", "assert normalize_resource_distribution([[10, 20, 30], [5, 15, 25]]) == [[0.16666666666666666, 0.3333333333333333, 0.5], [0.1, 0.3, 0.6]]", "assert normalize_resource_distribution([[0, 0, 0], [1, 2, 3]]) == [[0, 0, 0], [0.16666666666666666, 0.3333333333333333, 0.5]]", "assert normalize_resource_distribution([[1, 1, 1], [1, 1, 1]]) == [[0.3333333333333333, 0.3333333333333333, 0.3333333333333333], [0.3333333333333333, 0.3333333333333333, 0.3333333333333333]]", "assert normalize_resource_distribution([[100]]) == [[1.0]]", "assert normalize_resource_distribution([[0]]) == [[0]]", "assert normalize_resource_distribution([[1, 2], [3, 4], [5, 6]]) == [[0.3333333333333333, 0.6666666666666666], [0.42857142857142855, 0.5714285714285714], [0.45454545454545453, 0.5454545454545454]]", "assert normalize_resource_distribution([[1, 0, 0], [0, 1, 0], [0, 0, 1]]) == [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]", "assert normalize_resource_distribution([[1, 2, 3], [0, 0, 0], [7, 8, 9]]) == [[0.16666666666666666, 0.3333333333333333, 0.5], [0, 0, 0], [0.21212121212121213, 0.24242424242424243, 0.5454545454545454]]", "assert normalize_resource_distribution([[1, 1], [2, 2], [3, 3]]) == [[0.5, 0.5], [0.5, 0.5], [0.5, 0.5]]"], "function": "normalize_resource_distribution", "signature": "def normalize_resource_distribution(matrix):", "score": 0.8, "domain": "generic"} {"id": "a4c48f56a8dc9cd442e57e8c150d38fd", "problem": "You are given a list of tuples, where each tuple represents a product with its ID, name, and price. Your task is to write a function that sorts this list of products first by price in ascending order, and then by product name in ascending order if the prices are the same. Return the sorted list.\n\n**Input:**\n- A list of tuples, where each tuple contains three elements: an integer (product ID), a string (product name), and a float (price).\n\n**Output:**\n- A list of tuples sorted by the specified criteria.\n\n**Sample Input:**\n```python\n[(101, \"Apple\", 1.50), (102, \"Banana\", 0.75), (103, \"Cherry\", 1.50)]\n```\n\n**Sample Output:**\n```python\n[(102, \"Banana\", 0.75), (101, \"Apple\", 1.50), (103, \"Cherry\", 1.50)]\n```", "reference": "def sort_products_by_price(products):\n \"\"\"\n Sorts a list of product tuples by price in ascending order.\n If two products have the same price, they are sorted by product name in ascending order.\n\n :param products: List of tuples, where each tuple contains (product ID, product name, price)\n :return: Sorted list of tuples based on the specified criteria\n \"\"\"\n return sorted(products, key=lambda product: (product[2], product[1]))\n\n# Example usage:\nproducts = [(101, \"Apple\", 1.50), (102, \"Banana\", 0.75), (103, \"Cherry\", 1.50)]\nsorted_products = sort_products_by_price(products)\nprint(sorted_products)", "tests": ["assert sort_products_by_price([(101, \"Apple\", 1.50), (102, \"Banana\", 0.75), (103, \"Cherry\", 1.50)]) == [(102, \"Banana\", 0.75), (101, \"Apple\", 1.50), (103, \"Cherry\", 1.50)]", "assert sort_products_by_price([(101, \"Apple\", 1.50), (102, \"Banana\", 1.50), (103, \"Cherry\", 1.50)]) == [(101, \"Apple\", 1.50), (102, \"Banana\", 1.50), (103, \"Cherry\", 1.50)]", "assert sort_products_by_price([(101, \"Apple\", 1.50), (102, \"Banana\", 1.50), (103, \"Cherry\", 1.50), (104, \"Date\", 0.75)]) == [(104, \"Date\", 0.75), (102, \"Banana\", 1.50), (101, \"Apple\", 1.50), (103, \"Cherry\", 1.50)]", "assert sort_products_by_price([(101, \"Apple\", 1.50), (102, \"Banana\", 1.50), (103, \"Cherry\", 1.50), (104, \"Date\", 1.50), (105, \"Elderberry\", 1.50)]) == [(102, \"Banana\", 1.50), (101, \"Apple\", 1.50), (103, \"Cherry\", 1.50), (104, \"Date\", 1.50), (105, \"Elderberry\", 1.50)]", "assert sort_products_by_price([(101, \"Apple\", 1.50), (102, \"Banana\", 1.50), (103, \"Cherry\", 1.50), (104, \"Date\", 1.50), (105, \"Elderberry\", 1.50), (106, \"Fig\", 0.75)]) == [(106, \"Fig\", 0.75), (104, \"Date\", 1.50), (102, \"Banana\", 1.50), (101, \"Apple\", 1.50), (103, \"Cherry\", 1.50), (105, \"Elderberry\", 1.50)]", "assert sort_products_by_price([(101, \"Apple\", 1.50), (102, \"Banana\", 1.50), (103, \"Cherry\", 1.50), (104, \"Date\", 1.50), (105, \"Elderberry\", 1.50), (106, \"Fig\", 1.50), (107, \"Grape\", 1.50)]) == [(106, \"Fig\", 0.75), (104, \"Date\", 1.50), (102, \"Banana\", 1.50), (101, \"Apple\", 1.50), (103, \"Cherry\", 1.50), (105, \"Elderberry\", 1.50), (107, \"Grape\", 1.50)]", "assert sort_products_by_price([(101, \"Apple\", 1.50), (102, \"Banana\", 1.50), (103, \"Cherry\", 1.50), (104, \"Date\", 1.50), (105, \"Elderberry\", 1.50), (106, \"Fig\", 1.50), (107, \"Grape\", 1.50), (108, \"Honeydew\", 0.75)]) == [(108, \"Honeydew\", 0.75), (106, \"Fig\", 0.75), (104, \"Date\", 1.50), (102, \"Banana\", 1.50), (101, \"Apple\", 1.50), (103, \"Cherry\", 1.50), (105, \"Elderberry\", 1.50), (107, \"Grape\", 1.50)]", "assert sort_products_by_price([(101, \"Apple\", 1.50), (102, \"Banana\", 1.50), (103, \"Cherry\", 1.50), (104, \"Date\", 1.50), (105, \"Elderberry\", 1.50), (106, \"Fig\", 1.50), (107, \"Grape\", 1.50), (108, \"Honeydew\", 1.50), (109, \"Kiwi\", 1.50)]) == [(108, \"Honeydew\", 0.75), (106, \"Fig\", 0.75), (104, \"Date\", 1.50), (102, \"Banana\", 1.50), (101, \"Apple\", 1.50), (103, \"Cherry\", 1.50), (105, \"Elderberry\", 1.50), (107, \"Grape\", 1.50), (109, \"Kiwi\", 1.50)]", "assert sort_products_by_price([(101, \"Apple\", 1.50), (102, \"Banana\", 1.50), (103, \"Cherry\", 1.50), (104, \"Date\", 1.50), (105, \"Elderberry\", 1.50), (106, \"Fig\", 1.50), (107, \"Grape\", 1.50), (108, \"Honeydew\", 1.50), (109, \"Kiwi\", 1.50), (110, \"Lemon\", 0.75)]) == [(110, \"Lemon\", 0.75), (108, \"Honeydew\", 0.75), (106, \"Fig\", 0.75), (104, \"Date\", 1.50), (102, \"Banana\", 1.50), (101, \"Apple\", 1.50), (103, \"Cherry\", 1.50), (105, \"Elderberry\", 1.50), (107, \"Grape\", 1.50), (109, \"Kiwi\", 1.50)]", "assert sort_products_by_price([]) == []"], "function": "sort_products_by_price", "signature": "def sort_products_by_price(products):", "score": 0.3, "domain": "generic"} {"id": "dcafe72d42ce186a48ae3cc056e2db8d", "problem": "You are given a string `s` consisting of lowercase English letters. Your task is to implement a function `longest_palindrome_substring` that returns the longest palindromic substring in `s`. If there are multiple palindromic substrings of the same maximum length, return the one that appears first in the string.\n\n**Input:**\n- A single string `s` (1 ≤ |s| ≤ 1000).\n\n**Output:**\n- A string representing the longest palindromic substring.\n\n**Sample Input:**\n```\nbabad\n```\n\n**Sample Output:**\n```\nbab\n```\n*Note: \"aba\" is also a valid output.*", "reference": "def longest_palindrome_substring(s):\n \"\"\"\n Finds the longest palindromic substring in the given string s.\n \n :param s: A string consisting of lowercase English letters.\n :return: The longest palindromic substring in s.\n \"\"\"\n if not s:\n return \"\"\n \n start, end = 0, 0\n \n for i in range(len(s)):\n len1 = expand_around_center(s, i, i)\n len2 = expand_around_center(s, i, i + 1)\n max_len = max(len1, len2)\n \n if max_len > end - start:\n start = i - (max_len - 1) // 2\n end = i + max_len // 2\n \n return s[start:end + 1]\n\ndef expand_around_center(s, left, right):\n \"\"\"\n Expands around the center indices left and right to find the length of the palindrome.\n \n :param s: The string in which to search for a palindrome.\n :param left: The left index of the center.\n :param right: The right index of the center.\n :return: The length of the palindrome found.\n \"\"\"\n while left >= 0 and right < len(s) and s[left] == s[right]:\n left -= 1\n right += 1\n return right - left - 1", "tests": ["assert longest_palindrome_substring(\"babad\") == \"bab\"", "assert longest_palindrome_substring(\"cbbd\") == \"bb\"", "assert longest_palindrome_substring(\"a\") == \"a\"", "assert longest_palindrome_substring(\"ac\") == \"a\"", "assert longest_palindrome_substring(\"racecar\") == \"racecar\"", "assert longest_palindrome_substring(\"noon high it is\") == \"noon\"", "assert longest_palindrome_substring(\"abacdfgdcaba\") == \"aba\"", "assert longest_palindrome_substring(\"aaaa\") == \"aaaa\"", "assert longest_palindrome_substring(\"\") == \"\"", "assert longest_palindrome_substring(\"abcba\") == \"abcba\""], "function": "longest_palindrome_substring", "signature": "def longest_palindrome_substring(s):", "score": 0.8, "domain": "generic"} {"id": "183849458b5a638cf1d9d2181b5cd748", "problem": "You are given a list of strings. Your task is to write a Python function that returns a list of tuples. Each tuple should consist of a string from the list and the number of times it appears in the list. The tuples should be sorted in descending order based on the count of occurrences. If two strings have the same count, their order relative to each other does not matter.\n\n**Sample Input:**\n```python\n[\"apple\", \"banana\", \"apple\", \"orange\", \"banana\", \"banana\"]\n```\n\n**Sample Output:**\n```python\n[('banana', 3), ('apple', 2), ('orange', 1)]\n```", "reference": "from collections import Counter\n\ndef count_and_sort_strings(strings):\n \"\"\"\n Takes a list of strings and returns a list of tuples.\n Each tuple contains a string and the number of times it appears in the list.\n The list is sorted by the number of occurrences in descending order.\n \n :param strings: List of strings\n :return: List of tuples (string, count) sorted by count in descending order\n \"\"\"\n count_dict = Counter(strings)\n sorted_counted_strings = sorted(count_dict.items(), key=lambda x: x[1], reverse=True)\n return sorted_counted_strings\n\n# Test the function with the given input\ninput_strings = [\"apple\", \"banana\", \"apple\", \"orange\", \"banana\", \"banana\"]\nresult = count_and_sort_strings(input_strings)\nprint(result)", "tests": ["assert count_and_sort_strings([\"apple\", \"banana\", \"apple\", \"orange\", \"banana\", \"banana\"]) == [(\"banana\", 3), (\"apple\", 2), (\"orange\", 1)]", "assert count_and_sort_strings([\"dog\", \"cat\", \"dog\", \"cat\", \"dog\"]) == [(\"dog\", 3), (\"cat\", 2)]", "assert count_and_sort_strings([\"one\", \"two\", \"three\", \"four\", \"five\"]) == [(\"one\", 1), (\"two\", 1), (\"three\", 1), (\"four\", 1), (\"five\", 1)]", "assert count_and_sort_strings([\"repeat\", \"repeat\", \"repeat\", \"repeat\"]) == [(\"repeat\", 4)]", "assert count_and_sort_strings([]) == []", "assert count_and_sort_strings([\"single\"]) == [(\"single\", 1)]", "assert count_and_sort_strings([\"tie\", \"tie\", \"break\", \"break\", \"tie\"]) == [(\"tie\", 3), (\"break\", 2)]", "assert count_and_sort_strings([\"a\", \"b\", \"c\", \"a\", \"b\", \"a\", \"b\", \"b\"]) == [(\"b\", 4), (\"a\", 3), (\"c\", 1)]", "assert count_and_sort_strings([\"same\", \"same\", \"same\", \"same\", \"same\"]) == [(\"same\", 5)]", "assert count_and_sort_strings([\"order\", \"order\", \"order\", \"chaos\"]) == [(\"order\", 3), (\"chaos\", 1)]"], "function": "count_and_sort_strings", "signature": "def count_and_sort_strings(strings):", "score": 1.0, "domain": "generic"} {"id": "4a69328d1e0fe288b9a03c87f2db837f", "problem": "You are given a list of integers which may include duplicates and can contain any integer value. Your task is to design an efficient function that identifies the smallest positive integer that is not present in the list. The function should be optimized for performance, considering that the input list can be very large.\n\n**Sample Input:**\n```\n[3, 4, -1, 1]\n```\n\n**Sample Output:**\n```\n2\n```\n\n**Sample Input:**\n```\n[1, 2, 0]\n```\n\n**Sample Output:**\n```\n3\n```", "reference": "def find_smallest_missing_integer(nums):\n \"\"\"\n Finds the smallest positive integer that is not present in the given list of integers.\n \n :param nums: List[int] - A list of integers which may include duplicates and can contain any integer value.\n :return: int - The smallest positive integer not present in the list.\n \"\"\"\n num_set = set(nums)\n smallest_missing = 1\n while smallest_missing in num_set:\n smallest_missing += 1\n return smallest_missing", "tests": ["assert find_smallest_missing_integer([1, 2, 3]) == 4", "assert find_smallest_missing_integer([3, 4, -1, 1]) == 2", "assert find_smallest_missing_integer([7, 8, 9, 11, 12]) == 1", "assert find_smallest_missing_integer([1, 2, 0]) == 3", "assert find_smallest_missing_integer([0, 0, 0, 0]) == 1", "assert find_smallest_missing_integer([-1, -2, -3]) == 1", "assert find_smallest_missing_integer([100, 200, 300]) == 1", "assert find_smallest_missing_integer([]) == 1", "assert find_smallest_missing_integer([1]) == 2", "assert find_smallest_missing_integer([1, 1, 2, 2, 3, 3]) == 4"], "function": "find_smallest_missing_integer", "signature": "def find_smallest_missing_integer(nums):", "score": 1.0, "domain": "algorithmic"} {"id": "9bbdc0e09a0ac759e7d676be532dbd9b", "problem": "You are given a list of integers. Your task is to implement a function `find_duplicates` that identifies and returns a list of integers that appear more than once in the input list. The function must be efficient and should not utilize any additional data structures such as sets or dictionaries. \n\n**Constraints:**\n- The list can contain up to 10^3 integers.\n- Each integer in the list is within the range of -10^3 to 10^3.\n\n**Sample Input:**\n```\n[1, 2, 3, 4, 5, 1, 2, 6]\n```\n\n**Sample Output:**\n```\n[1, 2]\n```", "reference": "def find_duplicates(nums):\n \"\"\"\n Returns a list of integers that appear more than once in the input list.\n \n :param nums: List of integers\n :return: List of integers that are duplicates\n \"\"\"\n duplicates = []\n for i in range(len(nums)):\n for j in range(i + 1, len(nums)):\n if nums[i] == nums[j] and nums[i] not in duplicates:\n duplicates.append(nums[i])\n return duplicates\n\n# Example usage:\n# print(find_duplicates([1, 2, 3, 4, 5, 1, 2, 6])) # Output: [1, 2]", "tests": ["assert find_duplicates([1, 2, 3, 4, 5, 1, 2, 6]) == [1, 2]", "assert find_duplicates([1, 1, 1, 1, 1]) == [1]", "assert find_duplicates([1, 2, 3, 4, 5]) == []", "assert find_duplicates([]) == []", "assert find_duplicates([10, 20, 30, 40, 50, 10, 30, 60]) == [10, 30]", "assert find_duplicates([5, 5, 5, 5, 5, 5, 5]) == [5]", "assert find_duplicates([7, 8, 9, 7, 10, 9, 11, 8]) == [7, 9, 8]", "assert find_duplicates([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) == []", "assert find_duplicates([1, 2, 2, 3, 3, 3, 4, 4, 4, 4]) == [2, 3, 4]", "assert find_duplicates([100, 200, 300, 400, 500, 100, 200, 300]) == [100, 200, 300]"], "function": "find_duplicates", "signature": "def find_duplicates(nums):", "score": 0.9, "domain": "generic"} {"id": "93289b566262fd9c01d7b969c81a7ad0", "problem": "You are given a list of strings representing lines of code. Your task is to write a function `filter_comments` that removes all single-line and multi-line comments from the code. Single-line comments start with `#` and continue until the end of the line, while multi-line comments start with `/*` and end with `*/`. The function should correctly handle nested comments within strings and escape characters for string delimiters.\n\n**Input:**\n- A list of strings `code_lines` where each string is a line of code.\n\n**Output:**\n- A list of strings with all comments removed.\n\n**Sample Input:**\n```python\n[\n 'print(\"This is a /* string */ with comments inside\")',\n 'print(\\'This is a \\'/* string */\\' with comments inside\\')',\n 'int a = 10; // This is a single-line comment',\n '/* This is a',\n 'multi-line comment */',\n 'int b = 20; /* inline comment */ int c = 30;'\n]\n```\n\n**Sample Output:**\n```python\n[\n 'print(\"This is a /* string */ with comments inside\")',\n \"print('This is a '/* string */' with comments inside')\",\n 'int a = 10;',\n '',\n '',\n 'int b = 20; int c = 30;'\n]\n```", "reference": "def filter_comments(code_lines):\n \"\"\"\n Removes all single-line and multi-line comments from the given list of code lines.\n \n :param code_lines: List of strings, where each string is a line of code.\n :return: List of strings with all comments removed.\n \"\"\"\n result = []\n in_multiline_comment = False\n string_type = None\n\n for line in code_lines:\n new_line = []\n i = 0\n\n while i < len(line):\n if in_multiline_comment:\n if line[i:i+2] == '*/':\n in_multiline_comment = False\n i += 1\n else:\n if string_type:\n if line[i] == string_type:\n string_type = None\n elif line[i] == '\\\\':\n i += 1\n new_line.append(line[i])\n else:\n if line[i:i+2] == '/*':\n in_multiline_comment = True\n i += 1\n elif line[i] == '#':\n break\n elif line[i] in ('\"', \"'\"):\n string_type = line[i]\n new_line.append(line[i])\n else:\n new_line.append(line[i])\n i += 1\n\n result.append(''.join(new_line))\n\n return result", "tests": ["assert filter_comments([\"print('Hello # World')\"]) == [\"print('Hello # World')\"]", "assert filter_comments([\"print(\\\"This is a /* string */ with comments inside\\\")\"]) == [\"print(\\\"This is a /* string */ with comments inside\\\")\"]", "assert filter_comments([\"print('This is a \\\\'/* string \\\\' with comments inside')\"]) == [\"print('This is a \\\\'/* string \\\\' with comments inside')\"]", "assert filter_comments([\"print(\\\"This is a \\\\\\\"/* string \\\\\\\" with comments inside\\\")\"]) == [\"print(\\\"This is a \\\\\\\"/* string \\\\\\\" with comments inside\\\")\"]", "assert filter_comments([\"# This is a comment\", \"print('Hello World')\"]) == [\"\", \"print('Hello World')\"]", "assert filter_comments([\"print('Hello World') # This is a comment\"]) == [\"print('Hello World') \"]", "assert filter_comments([\"/* This is a\", \"multiline comment */\", \"print('Hello World')\"]) == [\"\", \"\", \"print('Hello World')\"]", "assert filter_comments([\"print('Hello /* World */') /* This is a comment */\"]) == [\"print('Hello /* World */') \"]", "assert filter_comments([\"print('Hello World') /* This is a\", \"multiline comment */\"]) == [\"print('Hello World') \", \"\"]", "assert filter_comments([\"print('Hello /* World */') # This is a comment\"]) == [\"print('Hello /* World */') \"]"], "function": "filter_comments", "signature": "def filter_comments(code_lines):", "score": 0.8, "domain": "generic"} {"id": "25d3b3bca65b652f011448e0921ea428", "problem": "You are given a string `s` and a pattern `p`. Your task is to write a function `find_substrings` that returns a list of all starting indices of substrings in `s` that match the pattern `p`. The comparison should be case-insensitive.\n\n**Input:**\n- A string `s` (1 ≤ |s| ≤ 10^5)\n- A string `p` (1 ≤ |p| ≤ |s|)\n\n**Output:**\n- A list of integers representing the starting indices of substrings in `s` that match the pattern `p`.\n\n**Sample Input:**\n```\ns = \"HelloWorld\"\np = \"world\"\n```\n\n**Sample Output:**\n```\n[5]\n```", "reference": "def find_substrings(s, pattern):\n \"\"\"\n Returns a list of all starting indices of substrings in s that match the pattern p.\n The comparison is case-insensitive.\n\n :param s: The input string.\n :param pattern: The pattern to search for.\n :return: A list of starting indices of matching substrings.\n \"\"\"\n s = s.lower()\n pattern = pattern.lower()\n \n indices = []\n for i in range(len(s) - len(pattern) + 1):\n if s[i:i+len(pattern)] == pattern:\n indices.append(i)\n return indices", "tests": ["assert find_substrings(\"Hello World\", \"world\") == [6]", "assert find_substrings(\"abababa\", \"aba\") == [0, 2, 4]", "assert find_substrings(\"mississippi\", \"issi\") == [1, 4]", "assert find_substrings(\"aaaaa\", \"aa\") == [0, 1, 2, 3]", "assert find_substrings(\"Python Programming\", \"python\") == [0]", "assert find_substrings(\"abc\", \"d\") == []", "assert find_substrings(\"abcABCabc\", \"abc\") == [0, 3, 6]", "assert find_substrings(\"a\", \"a\") == [0]", "assert find_substrings(\"\", \"a\") == []", "assert find_substrings(\"abc\", \"\") == [0, 1, 2, 3]"], "function": "find_substrings", "signature": "def find_substrings(s, pattern):", "score": 1.0, "domain": "algorithmic"} {"id": "582f324b7a621586d50e2268cee8e844", "problem": "You are tasked with writing a program that extracts all email addresses from a given text and categorizes them based on their domain. Your program should output a dictionary where each key is a domain name and the corresponding value is a list of email addresses associated with that domain.\n\n**Input:**\n- A single string `text` containing the text from which email addresses need to be extracted.\n\n**Output:**\n- A dictionary where keys are domain names and values are lists of email addresses belonging to each domain.\n\n**Sample Input:**\n```\nPlease contact us at support@example.com or sales@example.org, and our HR team at hr@company.com.\n```\n\n**Sample Output:**\n```\n{'example.com': ['support@example.com'], 'example.org': ['sales@example.org'], 'company.com': ['hr@company.com']}\n```", "reference": "import re\n\ndef classify_emails_by_domain(text):\n \"\"\"\n Extracts email addresses from the given text and classifies them based on their domain.\n\n Parameters:\n text (str): The input text from which to extract email addresses.\n\n Returns:\n dict: A dictionary with domain names as keys and lists of email addresses as values.\n \"\"\"\n # Regular expression pattern to extract email addresses\n email_pattern = re.compile(r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}')\n # Find all email addresses in the text\n emails = email_pattern.findall(text)\n # Dictionary to hold domains as keys and list of emails as values\n domain_dict = {}\n\n # Loop through each email found\n for email in emails:\n # Split email to get the domain part\n domain = email.split('@')[1]\n # If domain is not in the dictionary, add it with the email as the first element of the list\n if domain not in domain_dict:\n domain_dict[domain] = [email]\n # If domain is already in the dictionary, append the email to the list\n else:\n domain_dict[domain].append(email)\n\n return domain_dict\n\n# Sample usage\ntext = \"Please contact us at support@example.com or sales@example.org, and our HR team at hr@company.com.\"\nresult = classify_emails_by_domain(text)\nprint(result)", "tests": ["assert classify_emails_by_domain(\"Please contact us at support@example.com or sales@example.org, and our HR team at hr@company.com.\") == {'example.com': ['support@example.com'], 'example.org': ['sales@example.org'], 'company.com': ['hr@company.com']}", "assert classify_emails_by_domain(\"No emails here!\") == {}", "assert classify_emails_by_domain(\"Multiple emails at same domain: user1@test.com, user2@test.com\") == {'test.com': ['user1@test.com', 'user2@test.com']}", "assert classify_emails_by_domain(\"Mixed case domains: User@Example.com, user@example.COM\") == {'example.com': ['User@Example.com', 'user@example.COM']}", "assert classify_emails_by_domain(\"Subdomains included: user@mail.example.com, admin@sub.domain.org\") == {'mail.example.com': ['user@mail.example.com'], 'sub.domain.org': ['admin@sub.domain.org']}", "assert classify_emails_by_domain(\"Special characters: user.name+tag+sorting@example.com\") == {'example.com': ['user.name+tag+sorting@example.com']}", "assert classify_emails_by_domain(\"Numbers in domain: user@123.456.789.com\") == {'123.456.789.com': ['user@123.456.789.com']}", "assert classify_emails_by_domain(\"Multiple domains: user1@domain1.com, user2@domain2.org, user3@domain3.net\") == {'domain1.com': ['user1@domain1.com'], 'domain2.org': ['user2@domain2.org'], 'domain3.net': ['user3@domain3.net']}", "assert classify_emails_by_domain(\"Edge case: user@.com, user@com, user@domain.c\") == {}", "assert classify_emails_by_domain(\"Long domain: user@this.is.a.very.long.domain.name.com\") == {'this.is.a.very.long.domain.name.com': ['user@this.is.a.very.long.domain.name.com']}"], "function": "classify_emails_by_domain", "signature": "def classify_emails_by_domain(text):", "score": 0.9, "domain": "generic"} {"id": "93cd2c837458efd2462c849ecbaa6085", "problem": "You are tasked with implementing a function `convert_to_json` that manually converts a given dictionary into its JSON string representation. The dictionary can contain keys and values of the following types: string, integer, float, list, dictionary, `None`, `True`, and `False`. Your function should not use any built-in JSON conversion functions such as `json.dumps`.\n\n**Input:**\n- A dictionary with keys as strings and values as valid JSON data types.\n\n**Output:**\n- A string representing the JSON format of the input dictionary.\n\n**Sample Input:**\n```python\n{\n \"name\": \"Alice\",\n \"age\": 30,\n \"is_student\": False,\n \"courses\": [\"Math\", \"Science\"],\n \"address\": {\"city\": \"Wonderland\", \"zip\": \"12345\"},\n \"nothing\": None\n}\n```\n\n**Sample Output:**\n```\n{\"name\": \"Alice\", \"age\": 30, \"is_student\": false, \"courses\": [\"Math\", \"Science\"], \"address\": {\"city\": \"Wonderland\", \"zip\": \"12345\"}, \"nothing\": null}\n```", "reference": "def convert_to_json(data):\n \"\"\"\n Convert a dictionary to its JSON string representation without using built-in JSON functions.\n \n :param data: A dictionary with keys as strings and values as valid JSON data types.\n :return: A string representing the JSON format of the input dictionary.\n \"\"\"\n if isinstance(data, str):\n return '\"' + data.replace('\\\\', '\\\\\\\\').replace('\"', '\\\\\"') + '\"'\n elif isinstance(data, (int, float)):\n return str(data)\n elif isinstance(data, list):\n return '[' + ', '.join(convert_to_json(item) for item in data) + ']'\n elif isinstance(data, dict):\n return '{' + ', '.join(f'{convert_to_json(key)}: {convert_to_json(value)}' for key, value in data.items()) + '}'\n elif data is None:\n return 'null'\n elif data is True:\n return 'true'\n elif data is False:\n return 'false'\n else:\n raise TypeError(f\"Type {type(data)} is not JSON serializable\")", "tests": ["assert convert_to_json({\"name\": \"Alice\"}) == '{\"name\": \"Alice\"}'", "assert convert_to_json({\"age\": 30}) == '{\"age\": 30}'", "assert convert_to_json({\"is_student\": False}) == '{\"is_student\": false}'", "assert convert_to_json({\"courses\": [\"Math\", \"Science\"]}) == '{\"courses\": [\"Math\", \"Science\"]}'", "assert convert_to_json({\"address\": {\"city\": \"Wonderland\", \"zip\": \"12345\"}}) == '{\"address\": {\"city\": \"Wonderland\", \"zip\": \"12345\"}}'", "assert convert_to_json({\"nothing\": None}) == '{\"nothing\": null}'", "assert convert_to_json({\"empty_list\": []}) == '{\"empty_list\": []}'", "assert convert_to_json({\"empty_dict\": {}}) == '{\"empty_dict\": {}}'", "assert convert_to_json({\"special_chars\": '\"\\\\/'}) == '{\"special_chars\": \"\\\\\"\\\\\\\\/\\\\\"\"}'", "assert convert_to_json({\"float_value\": 3.14159}) == '{\"float_value\": 3.14159}'"], "function": "convert_to_json", "signature": "def convert_to_json(data):", "score": 0.8, "domain": "generic"} {"id": "7c1e0a8b944663a6440eab08f309dd1b", "problem": "You are tasked with implementing a function to generate the Fibonacci sequence up to the nth number. The Fibonacci sequence is defined as follows: the first number is 0, the second number is 1, and each subsequent number is the sum of the two preceding ones. Your function should return a list containing the Fibonacci sequence up to the nth number. If n is less than or equal to 0, return an empty list.\n\n**Sample Input:**\n```\n10\n```\n\n**Sample Output:**\n```\n[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]\n```", "reference": "def fibonacci_sequence(n):\n \"\"\"\n Generate the Fibonacci sequence up to the nth number.\n \n Parameters:\n n (int): The number of terms in the Fibonacci sequence to generate.\n \n Returns:\n list: A list containing the Fibonacci sequence up to the nth number.\n \"\"\"\n if n <= 0:\n return []\n elif n == 1:\n return [0]\n elif n == 2:\n return [0, 1]\n\n sequence = [0, 1]\n for i in range(2, n):\n sequence.append(sequence[-1] + sequence[-2])\n return sequence", "tests": ["assert fibonacci_sequence(0) == []", "assert fibonacci_sequence(1) == [0]", "assert fibonacci_sequence(2) == [0, 1]", "assert fibonacci_sequence(3) == [0, 1, 1]", "assert fibonacci_sequence(5) == [0, 1, 1, 2, 3]", "assert fibonacci_sequence(10) == [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]", "assert fibonacci_sequence(15) == [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377]", "assert fibonacci_sequence(1) == [0]", "assert fibonacci_sequence(6) == [0, 1, 1, 2, 3, 5]", "assert fibonacci_sequence(20) == [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181]"], "function": "fibonacci_sequence", "signature": "def fibonacci_sequence(n):", "score": 1.0, "domain": "generic"} {"id": "2ce030fc95efbe8a91bedbebdc60524e", "problem": "You are given two lists, `list1` and `list2`, which may contain elements of any data type. Your task is to implement a function `find_common_elements(list1, list2)` that returns a list of elements that are common to both input lists. The order of elements in the resulting list does not matter.\n\n**Sample Input:**\n```python\nlist1 = [1, \"apple\", 3.14, \"banana\"]\nlist2 = [\"banana\", 2, 3.14, \"orange\"]\n```\n\n**Sample Output:**\n```python\n[3.14, \"banana\"]\n```", "reference": "def find_common_elements(list1, list2):\n \"\"\"\n Returns a list of common elements between two input lists.\n\n Parameters:\n list1 (list): The first list containing elements of any data type.\n list2 (list): The second list containing elements of any data type.\n\n Returns:\n list: A list of elements that are common to both list1 and list2.\n \"\"\"\n set1 = set(list1)\n set2 = set(list2)\n common_elements = set1.intersection(set2)\n return list(common_elements)\n\n# Example usage:\nlist1 = [1, \"apple\", 3.14, \"banana\"]\nlist2 = [\"banana\", 2, 3.14, \"orange\"]\nprint(find_common_elements(list1, list2)) # Output: [3.14, \"banana\"]", "tests": ["assert find_common_elements([1, 2, 3], [3, 4, 5]) == [3]", "assert find_common_elements([\"apple\", \"banana\", \"cherry\"], [\"banana\", \"cherry\", \"date\"]) == [\"banana\", \"cherry\"]", "assert find_common_elements([1, \"apple\", 3.14], [3.14, \"banana\", 1]) == [1, 3.14]", "assert find_common_elements([], [1, 2, 3]) == []", "assert find_common_elements([1, 2, 3], []) == []", "assert find_common_elements([], []) == []", "assert find_common_elements([True, False, None], [None, True, \"False\"]) == [True, None]", "assert find_common_elements([1, 2, 2, 3], [2, 3, 3, 4]) == [2, 3]", "assert find_common_elements([\"a\", \"b\", \"c\"], [\"d\", \"e\", \"f\"]) == []", "assert find_common_elements([1, \"apple\", 3.14, \"banana\"], [\"banana\", 2, 3.14, \"orange\"]) == [3.14, \"banana\"]"], "function": "find_common_elements", "signature": "def find_common_elements(list1, list2):", "score": 0.9, "domain": "algorithmic"} {"id": "92540da5259ee3e6e75d697a2c9ae406", "problem": "You are given a task to implement a function `is_authorized_user(user)` that determines whether a user has access to certain resources based on their properties. The `user` object contains the following attributes:\n\n- `is_admin`: A boolean value indicating whether the user has administrative privileges.\n- `user_id`: A string representing the user's unique identifier.\n\nThe function should return `True` if the user is not an administrator and their `user_id` meets the following criteria:\n- The `user_id` must consist solely of alphanumeric characters.\n- The `user_id` must have a length between 5 and 10 characters, inclusive.\n\nOtherwise, the function should return `False`.\n\n**Sample Input:**\n```python\nuser1 = {'is_admin': False, 'user_id': 'abc123'}\nuser2 = {'is_admin': True, 'user_id': 'abc123'}\nuser3 = {'is_admin': False, 'user_id': 'abc!23'}\nuser4 = {'is_admin': False, 'user_id': 'abcd'}\nuser5 = {'is_admin': False, 'user_id': 'abcdefghijk'}\n```\n\n**Sample Output:**\n```python\nTrue\nFalse\nFalse\nFalse\nFalse\n```", "reference": "import re\n\ndef is_authorized_user(user):\n \"\"\"\n Determines if a user is authorized based on their user_id and admin status.\n \n Parameters:\n user (dict): A dictionary containing 'is_admin' (bool) and 'user_id' (str).\n \n Returns:\n bool: True if the user is not an admin and has a valid user_id, False otherwise.\n \"\"\"\n if not user['is_admin'] and re.match('^[a-zA-Z0-9]{5,10}$', user['user_id']):\n return True\n return False", "tests": ["assert is_authorized_user({\"is_admin\": False, \"user_id\": \"abc123\"}) == True", "assert is_authorized_user({\"is_admin\": True, \"user_id\": \"abc123\"}) == False", "assert is_authorized_user({\"is_admin\": False, \"user_id\": \"a1b2c3d4e5\"}) == True", "assert is_authorized_user({\"is_admin\": False, \"user_id\": \"a1b2c3d4e5f\"}) == False", "assert is_authorized_user({\"is_admin\": False, \"user_id\": \"abcd\"}) == False", "assert is_authorized_user({\"is_admin\": False, \"user_id\": \"abc!123\"}) == False", "assert is_authorized_user({\"is_admin\": False, \"user_id\": \"abc_123\"}) == False", "assert is_authorized_user({\"is_admin\": False, \"user_id\": \"abc-123\"}) == False", "assert is_authorized_user({\"is_admin\": False, \"user_id\": \"abc 123\"}) == False", "assert is_authorized_user({\"is_admin\": False, \"user_id\": \"abc123456789\"}) == False"], "function": "is_authorized_user", "signature": "def is_authorized_user(user):", "score": 1.0, "domain": "generic"} {"id": "6ef2cbf49c3c28ec4266ea8cb9ce8015", "problem": "You are given a binary tree with `n` nodes, where each node has a unique integer value. Your task is to convert this binary tree into a balanced binary search tree (BBST). A binary search tree is balanced if the depth of the two subtrees of every node never differs by more than one. Return the root of the BBST.\n\n**Input:**\n- The input is a binary tree represented by its root node. Each node is defined by its value and pointers to its left and right children.\n\n**Output:**\n- Return the root node of the balanced binary search tree.\n\n**Constraints:**\n- `1 <= n <= 10^4`\n- Each node's value is unique and is an integer.\n\n**Sample Input:**\n```\n 1\n \\\n 2\n \\\n 3\n \\\n 4\n```\n\n**Sample Output:**\n```\n 3\n / \\\n 2 4\n /\n 1\n```", "reference": "class TreeNode:\n def __init__(self, val=0, left=None, right=None):\n \"\"\"\n Initializes a tree node with a given value and optional left and right children.\n \n :param val: The value of the node.\n :param left: The left child of the node.\n :param right: The right child of the node.\n \"\"\"\n self.val = val\n self.left = left\n self.right = right\n\ndef inorder_traversal(root):\n \"\"\"\n Performs an in-order traversal of the binary tree and returns the elements in sorted order.\n \n :param root: The root node of the binary tree.\n :return: A list of integers representing the in-order traversal of the tree.\n \"\"\"\n elements = []\n stack = []\n current = root\n while current or stack:\n while current:\n stack.append(current)\n current = current.left\n current = stack.pop()\n elements.append(current.val)\n current = current.right\n return elements\n\ndef sorted_array_to_bst(arr):\n \"\"\"\n Constructs a balanced binary search tree from a sorted array.\n \n :param arr: A list of integers representing the sorted elements.\n :return: The root node of the balanced binary search tree.\n \"\"\"\n if not arr:\n return None\n\n mid = len(arr) // 2\n root = TreeNode(arr[mid])\n root.left = sorted_array_to_bst(arr[:mid])\n root.right = sorted_array_to_bst(arr[mid+1:])\n return root\n\ndef convert_to_bst(tree):\n \"\"\"\n Converts the given binary tree into a balanced binary search tree.\n \n :param tree: The root node of the binary tree.\n :return: The root node of the balanced binary search tree.\n \"\"\"\n sorted_elements = inorder_traversal(tree)\n return sorted_array_to_bst(sorted_elements)", "tests": ["assert convert_to_bst(TreeNode(1, TreeNode(2, TreeNode(3)))) is not None", "assert convert_to_bst(TreeNode(1, TreeNode(2, TreeNode(3)))).val == 2", "assert convert_to_bst(TreeNode(1, TreeNode(2, TreeNode(3)))).left.val == 1", "assert convert_to_bst(TreeNode(1, TreeNode(2, TreeNode(3)))).right.val == 3", "assert convert_to_bst(TreeNode(10, TreeNode(5), TreeNode(15, TreeNode(12), TreeNode(20)))).val == 10", "assert convert_to_bst(TreeNode(10, TreeNode(5), TreeNode(15, TreeNode(12), TreeNode(20)))).left.val == 7.5", "assert convert_to_bst(TreeNode(10, TreeNode(5), TreeNode(15, TreeNode(12), TreeNode(20)))).right.val == 16", "assert convert_to_bst(TreeNode(1, None, TreeNode(2, None, TreeNode(3, None, TreeNode(4))))).val == 3", "assert convert_to_bst(TreeNode(1, None, TreeNode(2, None, TreeNode(3, None, TreeNode(4))))).left.val == 2", "assert convert_to_bst(None) is None"], "function": "convert_to_bst", "signature": "def convert_to_bst(tree):", "score": 0.5, "domain": "generic"} {"id": "f0d081bf09e7e7d14cddad8190cccbab", "problem": "You are given a string `s` consisting of uppercase and lowercase English letters. Your task is to implement a function `remove_vowels` that removes all vowels from the string and returns the resulting string. Vowels are defined as 'a', 'e', 'i', 'o', 'u' (both lowercase and uppercase).\n\n**Input:**\n- A single string `s` (1 ≤ |s| ≤ 10^5), where |s| denotes the length of the string.\n\n**Output:**\n- A string with all vowels removed.\n\n**Sample Input:**\n```\n\"Hello World\"\n```\n\n**Sample Output:**\n```\n\"Hll Wrld\"\n```", "reference": "def remove_vowels(input_string):\n \"\"\"\n Removes all vowels from the input string and returns the resulting string.\n \n :param input_string: A string from which vowels need to be removed.\n :return: A string with all vowels removed.\n \"\"\"\n vowels = \"aeiouAEIOU\"\n return ''.join(char for char in input_string if char not in vowels)", "tests": ["assert remove_vowels(\"hello\") == \"hll\"", "assert remove_vowels(\"HELLO\") == \"HLL\"", "assert remove_vowels(\"Python Programming\") == \"Pythn Prgrmmng\"", "assert remove_vowels(\"AEIOUaeiou\") == \"\"", "assert remove_vowels(\"Quick brown fox\") == \"Qck brwn fx\"", "assert remove_vowels(\"The quick brown fox jumps over the lazy dog\") == \"Th qck brwn fx jmps vr th lzy dg\"", "assert remove_vowels(\"\") == \"\"", "assert remove_vowels(\"12345\") == \"12345\"", "assert remove_vowels(\"!@#$%^&*()\") == \"!@#$%^&*()\"", "assert remove_vowels(\"AeIoU\") == \"\""], "function": "remove_vowels", "signature": "def remove_vowels(input_string):", "score": 1.0, "domain": "generic"} {"id": "d84a5bba7cd1d06ad3e22de0e8ee2acc", "problem": "You are given a string `s` consisting of uppercase and lowercase English letters, digits, and punctuation marks. Your task is to write a function `convert_to_uppercase` that transforms all lowercase letters in the string to their corresponding uppercase letters without using the built-in `str.upper()` method. The function should return the modified string. You must manually convert each character using a loop.\n\n**Input:**\n- A single string `s` (1 ≤ |s| ≤ 1000).\n\n**Output:**\n- A single string with all lowercase letters converted to uppercase.\n\n**Sample Input:**\n```\nHello, World!\n```\n\n**Sample Output:**\n```\nHELLO, WORLD!\n```", "reference": "def convert_to_uppercase(input_string):\n \"\"\"\n Convert all lowercase letters in the input string to uppercase.\n\n :param input_string: A string containing uppercase and lowercase letters, digits, and punctuation.\n :return: A new string with all lowercase letters converted to uppercase.\n \"\"\"\n result = \"\"\n for char in input_string:\n if 'a' <= char <= 'z': # Check if the character is a lowercase letter\n result += chr(ord(char) - ord('a') + ord('A')) # Convert to uppercase\n else:\n result += char # Keep the character as it is if it's not a lowercase letter\n return result\n\n# Test the function\nprint(convert_to_uppercase(\"Hello, World!\")) # Output: \"HELLO, WORLD!\"", "tests": ["assert convert_to_uppercase(\"hello\") == \"HELLO\"", "assert convert_to_uppercase(\"world\") == \"WORLD\"", "assert convert_to_uppercase(\"Python3.8\") == \"PYTHON3.8\"", "assert convert_to_uppercase(\"12345\") == \"12345\"", "assert convert_to_uppercase(\"!@#$%^&*()\") == \"!@#$%^&*()\"", "assert convert_to_uppercase(\"aBcDeFgHiJ\") == \"ABCDEFGHIJ\"", "assert convert_to_uppercase(\"HELLO\") == \"HELLO\"", "assert convert_to_uppercase(\"\") == \"\"", "assert convert_to_uppercase(\"mixedCASE123\") == \"MIXEDCASE123\"", "assert convert_to_uppercase(\"lower and UPPER\") == \"LOWER AND UPPER\""], "function": "convert_to_uppercase", "signature": "def convert_to_uppercase(input_string):", "score": 1.0, "domain": "generic"} {"id": "e209229668e757acbfe67014df965ec3", "problem": "You are given a list of sentences. Your task is to implement a function `classify_sentences` that categorizes each sentence into one of the following categories: positive, negative, or neutral. The classification should be based on the presence of predefined positive and negative keywords. The function should return a list of tuples, where each tuple consists of a sentence and its corresponding category. If the input list is empty, the function should return an empty list.\n\n**Sample Input:**\n```python\n[\"I love sunny days\", \"This is the worst experience ever\", \"The movie was okay\"]\n```\n\n**Sample Output:**\n```python\n[(\"I love sunny days\", \"positive\"), (\"This is the worst experience ever\", \"negative\"), (\"The movie was okay\", \"neutral\")]\n```", "reference": "def classify_sentences(sentences):\n \"\"\"\n Classifies each sentence in the input list into 'positive', 'negative', or 'neutral'\n based on the presence of predefined positive and negative keywords.\n\n :param sentences: List of sentences to be classified.\n :return: List of tuples, each containing a sentence and its category.\n \"\"\"\n if not sentences:\n return []\n\n positive_keywords = {'love', 'sunny', 'happy', 'good', 'great', 'excellent', 'nice', 'fantastic', 'wonderful'}\n negative_keywords = {'worst', 'bad', 'terrible', 'awful', 'horrible', 'poor', 'sad', 'unhappy', 'negative'}\n\n def classify_sentence(sentence):\n words = set(sentence.lower().split())\n positive_count = sum(1 for word in words if word in positive_keywords)\n negative_count = sum(1 for word in words if word in negative_keywords)\n\n if positive_count > negative_count:\n return 'positive'\n elif negative_count > positive_count:\n return 'negative'\n else:\n return 'neutral'\n\n return [(sentence, classify_sentence(sentence)) for sentence in sentences]", "tests": ["assert classify_sentences([\"I love sunny days\"]) == [(\"I love sunny days\", \"positive\")]", "assert classify_sentences([\"This is the worst experience ever\"]) == [(\"This is the worst experience ever\", \"negative\")]", "assert classify_sentences([\"The movie was okay\"]) == [(\"The movie was okay\", \"neutral\")]", "assert classify_sentences([\"I am very happy today\"]) == [(\"I am very happy today\", \"positive\")]", "assert classify_sentences([\"It is a bad day\"]) == [(\"It is a bad day\", \"negative\")]", "assert classify_sentences([\"No strong feelings here\"]) == [(\"No strong feelings here\", \"neutral\")]", "assert classify_sentences([]) == []", "assert classify_sentences([\"Great job\", \"Terrible mistake\"]) == [(\"Great job\", \"positive\"), (\"Terrible mistake\", \"negative\")]", "assert classify_sentences([\"Good morning\", \"Sad to leave\"]) == [(\"Good morning\", \"positive\"), (\"Sad to leave\", \"negative\")]", "assert classify_sentences([\"Wonderful experience\", \"Awful service\"]) == [(\"Wonderful experience\", \"positive\"), (\"Awful service\", \"negative\")]"], "function": "classify_sentences", "signature": "def classify_sentences(sentences):", "score": 1.0, "domain": "generic"} {"id": "26622dd6d7293e785b8a279b34f80d84", "problem": "You are given two sentences as input. Your task is to write a Python function `find_common_words(sentence1, sentence2)` that identifies and returns a set of common words between the two sentences. Words should be compared in a case-insensitive manner. \n\n**Input:**\n- Two strings, `sentence1` and `sentence2`, each containing words separated by spaces.\n\n**Output:**\n- A set of common words between `sentence1` and `sentence2`.\n\n**Sample Input:**\n```\nsentence1 = \"The quick brown fox jumps over the lazy dog\"\nsentence2 = \"The lazy dog sleeps in the afternoon\"\n```\n\n**Sample Output:**\n```\n{'the', 'lazy', 'dog'}\n```", "reference": "def find_common_words(sentence1, sentence2):\n \"\"\"\n Finds and returns a set of common words between two sentences.\n \n Parameters:\n sentence1 (str): The first sentence.\n sentence2 (str): The second sentence.\n \n Returns:\n set: A set of common words between the two sentences.\n \"\"\"\n # Split sentences into words and convert to lowercase\n words1 = set(sentence1.lower().split())\n words2 = set(sentence2.lower().split())\n \n # Find common words\n common_words = words1.intersection(words2)\n \n return common_words", "tests": ["assert find_common_words(\"Hello world\", \"world of wonders\") == {'world'}", "assert find_common_words(\"Python is great\", \"Great Python challenges\") == {'python', 'great'}", "assert find_common_words(\"OpenAI GPT-4\", \"GPT-4 is powerful\") == {'gpt-4'}", "assert find_common_words(\"Data Science\", \"Science of data\") == {'science', 'data'}", "assert find_common_words(\"Machine Learning\", \"Deep Learning\") == {'learning'}", "assert find_common_words(\"No common words\", \"Here either\") == set()", "assert find_common_words(\"Repeat repeat repeat\", \"repeat\") == {'repeat'}", "assert find_common_words(\"Case Insensitive CASE\", \"case insensitive\") == {'case', 'insensitive'}", "assert find_common_words(\"Punctuation, should! not? matter.\", \"Matter it should not\") == {'matter', 'it', 'should', 'not'}", "assert find_common_words(\"\", \"\") == set()"], "function": "find_common_words", "signature": "def find_common_words(sentence1, sentence2):", "score": 0.9, "domain": "generic"} {"id": "afd5069f704327fda6c29b2ae1609f9b", "problem": "You are given two lists of integers, `list1` and `list2`. Your task is to implement a function `custom_list_difference` that returns a new list containing only the elements that are present in `list1` but not in `list2`. Additionally, any element in `list1` that is a perfect square should be excluded from the new list regardless of its presence in `list2`. The order of elements in the new list should be the same as they appear in `list1`.\n\n**Input:**\n- Two lists of integers, `list1` and `list2`.\n\n**Output:**\n- A list of integers containing elements from `list1` that are not in `list2` and are not perfect squares.\n\n**Sample Input:**\n- `list1 = [1, 2, 3, 4, 5]`\n- `list2 = [4, 5, 6, 7, 8]`\n\n**Sample Output:**\n- `[2, 3]`", "reference": "def is_perfect_square(n):\n \"\"\"\n Check if a number is a perfect square.\n \n :param n: Integer to check.\n :return: True if n is a perfect square, False otherwise.\n \"\"\"\n return int(n**0.5) ** 2 == n\n\ndef custom_list_difference(list1, list2):\n \"\"\"\n Return a list of elements from list1 that are not in list2 and are not perfect squares.\n \n :param list1: List of integers.\n :param list2: List of integers.\n :return: List of integers.\n \"\"\"\n return [x for x in list1 if x not in list2 and not is_perfect_square(x)]\n\n# Example usage:\nlist1 = [1, 2, 3, 4, 5]\nlist2 = [4, 5, 6, 7, 8]\nresult = custom_list_difference(list1, list2)\nprint(result) # Output: [2, 3]", "tests": ["assert custom_list_difference([1, 2, 3, 4, 5], [4, 5, 6, 7, 8]) == [2, 3]", "assert custom_list_difference([9, 16, 25], [10, 20, 30]) == []", "assert custom_list_difference([1, 2, 3, 4, 5], [1, 2, 3, 4, 5]) == []", "assert custom_list_difference([10, 20, 30], [5, 15, 25]) == [10, 20, 30]", "assert custom_list_difference([1, 4, 9, 16, 25], [4, 9, 16]) == [1, 25]", "assert custom_list_difference([], [1, 2, 3]) == []", "assert custom_list_difference([1, 2, 3], []) == [1, 2, 3]", "assert custom_list_difference([0, 1, 2, 3, 4], [0, 4]) == [1, 2, 3]", "assert custom_list_difference([1, 3, 5, 7, 9], [2, 4, 6, 8, 10]) == [1, 3, 5, 7, 9]", "assert custom_list_difference([4, 9, 16, 25, 36], [4, 9, 16, 25, 36]) == []"], "function": "custom_list_difference", "signature": "def custom_list_difference(list1, list2):", "score": 0.6, "domain": "generic"} {"id": "a9eeb17f4b2b814933f1b78a567623c4", "problem": "You are tasked with implementing a function `calculate_discounted_price` that computes the final price of an item after applying a discount and then adding tax. The function should take three parameters: the original price of the item, the discount percentage, and the tax rate. The discount should be applied first, followed by the tax. Your function should return the final price rounded to two decimal places.\n\n**Input:**\n- The function will receive three arguments:\n - `original_price`: A float representing the original price of the item.\n - `discount_percentage`: A float representing the discount percentage to be applied.\n - `tax_rate`: A float representing the tax rate to be applied after the discount.\n\n**Output:**\n- The function should return a float representing the final price after applying the discount and adding the tax, rounded to two decimal places.\n\n**Sample Input:**\n- `original_price = 100.00`, `discount_percentage = 20.00`, `tax_rate = 8.00`\n\n**Sample Output:**\n- `96.00`", "reference": "def calculate_discounted_price(original_price, discount_percentage, tax_rate):\n \"\"\"\n Calculate the final price of an item after applying a discount and adding tax.\n\n Parameters:\n original_price (float): The original price of the item.\n discount_percentage (float): The discount percentage to be applied.\n tax_rate (float): The tax rate to be applied after the discount.\n\n Returns:\n float: The final price after applying the discount and adding the tax, rounded to two decimal places.\n \"\"\"\n # Apply the discount\n discounted_price = original_price * (1 - discount_percentage / 100)\n # Add tax to the discounted price\n final_price = discounted_price * (1 + tax_rate / 100)\n return round(final_price, 2)\n\n# Example usage:\nprint(calculate_discounted_price(100.00, 20.00, 8.00)) # Output: 96.00", "tests": ["assert calculate_discounted_price(100, 20, 8) == 96.0", "assert calculate_discounted_price(200, 10, 5) == 189.0", "assert calculate_discounted_price(50, 0, 10) == 55.0", "assert calculate_discounted_price(150, 50, 0) == 75.0", "assert calculate_discounted_price(0, 20, 8) == 0.0", "assert calculate_discounted_price(100, 100, 10) == 0.0", "assert calculate_discounted_price(100, 0, 0) == 100.0", "assert calculate_discounted_price(300, 25, 15) == 228.75", "assert calculate_discounted_price(120, 30, 20) == 100.8", "assert calculate_discounted_price(75, 15, 5) == 66.375"], "function": "calculate_discounted_price", "signature": "def calculate_discounted_price(original_price, discount_percentage, tax_rate):", "score": 0.7, "domain": "generic"} {"id": "76a29da1c9f0d1248eb3419b29880ed5", "problem": "You are given the task of computing the total damage inflicted by a magical explosion centered at a point. The explosion's impact is defined by its radius and a mystical power function that determines the power at any given distance from the center. The mystical power function is not accessible to you directly; instead, you can only obtain its value by invoking it with a specific distance.\n\nYour mission is to implement a function named `calculate_magical_explosion_damage` that accepts the explosion radius as an argument and returns the cumulative damage caused by the explosion. The cumulative damage is computed by summing the product of the mystical power at each distance and the distance itself, for all distances ranging from 1 to the explosion radius.\n\n**Function Signature:**\n```python\ndef calculate_magical_explosion_damage(radius: int, secret_function: callable) -> int:\n```\n\n**Constraints:**\n- 1 ≤ radius ≤ 1000\n\n**Sample Input:**\n```python\nradius = 3\nsecret_function = lambda x: x * x # Example secret function: power = distance^2\n```\n\n**Sample Output:**\n```\n14 # Explanation: (1*1) + (2*4) + (3*9) = 1 + 8 + 5 = 14\n```", "reference": "def calculate_magical_explosion_damage(radius: int, secret_function: callable) -> int:\n \"\"\"\n Calculate the total damage caused by a magical explosion.\n\n Parameters:\n radius (int): The radius of the explosion.\n secret_function (callable): A function that returns the magical power at a given distance.\n\n Returns:\n int: The total damage caused by the explosion.\n \"\"\"\n total_damage = 0\n for distance in range(1, radius + 1):\n magical_power = secret_function(distance)\n damage_at_distance = magical_power * distance\n total_damage += damage_at_distance\n return total_damage", "tests": ["assert calculate_magical_explosion_damage(1, lambda x: 1) == 1", "assert calculate_magical_explosion_damage(2, lambda x: x) == 5", "assert calculate_magical_explosion_damage(3, lambda x: x**2) == 14", "assert calculate_magical_explosion_damage(4, lambda x: 2*x) == 30", "assert calculate_magical_explosion_damage(5, lambda x: 3) == 45", "assert calculate_magical_explosion_damage(0, lambda x: 10) == 0", "assert calculate_magical_explosion_damage(6, lambda x: x + 1) == 91", "assert calculate_magical_explosion_damage(7, lambda x: 0) == 0", "assert calculate_magical_explosion_damage(8, lambda x: 2**x) == 504", "assert calculate_magical_explosion_damage(9, lambda x: x * (x - 1)) == 285"], "function": "calculate_magical_explosion_damage", "signature": "def calculate_magical_explosion_damage(radius: int, secret_function: callable) -> int:", "score": 0.5, "domain": "generic"} {"id": "8de9a7b597bcafc547414e6ccb612336", "problem": "You are given a byte string `data` and an integer `bsize`. Implement a function `custom_pad` that pads `data` to make its length a multiple of `bsize`. The padding should consist of bytes, each with a value equal to the number of padding bytes added. If `data`'s length is already a multiple of `bsize`, append a full block of padding bytes, each with a value equal to `bsize`. The function should handle both string and bytes input for `data`, encoding strings to UTF-8 before padding. Ensure the padding is reversible.\n\n**Input:**\n- `data`: A string or bytes object.\n- `bsize`: An integer representing the block size.\n\n**Output:**\n- A bytes object representing the padded data.\n\n**Sample Input:**\n- `data = \"hello\"`\n- `bsize = 8`\n\n**Sample Output:**\n- `b'hello\\x03\\x03\\x03'`\n\n**Constraints:**\n- `1 <= len(data) <= 1000`\n- `1 <= bsize <= 1000`", "reference": "def custom_pad(data, bsize):\n \"\"\"\n Pads the given data to make its length a multiple of the specified block size.\n \n Parameters:\n - data: A string or bytes object to be padded.\n - bsize: An integer representing the block size.\n \n Returns:\n - A bytes object representing the padded data.\n \"\"\"\n # Ensure data is in bytes\n if isinstance(data, str):\n data = data.encode('utf-8')\n \n # Calculate the length of the padding\n data_len = len(data)\n pad_len = bsize - (data_len % bsize)\n \n # If the length is already a multiple of bsize, we pad with a full block\n if pad_len == 0:\n pad_len = bsize\n \n # Create the padding\n padding = bytes([pad_len] * pad_len)\n \n # Return the padded data\n return data + padding", "tests": ["assert custom_pad(b\"hello\", 8) == b\"hello\\x03\\x03\\x03\"", "assert custom_pad(\"hello\", 8) == b\"hello\\x03\\x03\\x03\"", "assert custom_pad(b\"hello world\", 5) == b\"hello world\\x05\\x05\\x05\\x05\\x05\"", "assert custom_pad(\"hello world\", 5) == b\"hello world\\x05\\x05\\x05\\x05\\x05\"", "assert custom_pad(b\"abc\", 4) == b\"abc\\x01\"", "assert custom_pad(\"abc\", 4) == b\"abc\\x01\"", "assert custom_pad(b\"abcd\", 4) == b\"abcd\\x04\\x04\\x04\\x04\"", "assert custom_pad(\"abcd\", 4) == b\"abcd\\x04\\x04\\x04\\x04\"", "assert custom_pad(b\"\", 16) == b\"\\x10\\x10\\x10\\x10\\x10\\x10\\x10\\x10\\x10\\x10\\x10\\x10\\x10\\x10\\x10\\x10\"", "assert custom_pad(\"\", 16) == b\"\\x10\\x10\\x10\\x10\\x10\\x10\\x10\\x10\\x10\\x10\\x10\\x10\\x10\\x10\\x10\\x10\""], "function": "custom_pad", "signature": "def custom_pad(data, bsize):", "score": 0.8, "domain": "generic"} {"id": "ad13e9cd69a4cda9208a3bb46025a006", "problem": "You are given a binary tree where each node has an integer value. Your task is to determine if the binary tree is balanced. A binary tree is considered balanced if, for every node in the tree, the height difference between its left and right subtrees is at most 1. You are provided with a function `max_depth(root)` that calculates the maximum depth of the binary tree. Implement the function `is_balanced(root)` using the `max_depth` function.\n\n**Input:**\n- The input is a binary tree represented by its root node. Each node contains an integer value and pointers to its left and right children.\n\n**Output:**\n- Return `True` if the binary tree is balanced, otherwise return `False`.\n\n**Sample Input:**\n```\n 1\n / \\\n 2 3\n / \\\n4 5\n```\n\n**Sample Output:**\n```\nTrue\n```", "reference": "class TreeNode:\n def __init__(self, value=0, left=None, right=None):\n self.value = value\n self.left = left\n self.right = right\n\ndef max_depth(root):\n \"\"\"\n Calculate the maximum depth of a binary tree.\n\n :param root: TreeNode, the root of the binary tree\n :return: int, the maximum depth of the tree\n \"\"\"\n if root is None:\n return 0\n left_depth = max_depth(root.left)\n right_depth = max_depth(root.right)\n return max(left_depth, right_depth) + 1\n\ndef is_balanced(root):\n \"\"\"\n Determine if a binary tree is balanced.\n\n :param root: TreeNode, the root of the binary tree\n :return: bool, True if the tree is balanced, False otherwise\n \"\"\"\n if root is None:\n return True\n left_height = max_depth(root.left)\n right_height = max_depth(root.right)\n if abs(left_height - right_height) > 1:\n return False\n return is_balanced(root.left) and is_balanced(root.right)", "tests": ["assert is_balanced(None) == True", "assert is_balanced(TreeNode(1)) == True", "assert is_balanced(TreeNode(1, TreeNode(2))) == True", "assert is_balanced(TreeNode(1, TreeNode(2), TreeNode(3))) == True", "assert is_balanced(TreeNode(1, TreeNode(2, TreeNode(4), TreeNode(5)), TreeNode(3))) == True", "assert is_balanced(TreeNode(1, TreeNode(2, TreeNode(4, TreeNode(8), TreeNode(9)), TreeNode(5)), TreeNode(3))) == False", "assert is_balanced(TreeNode(1, TreeNode(2, TreeNode(4, TreeNode(8, TreeNode(16), TreeNode(17)), TreeNode(9)), TreeNode(5)), TreeNode(3))) == False", "assert is_balanced(TreeNode(1, TreeNode(2, TreeNode(4, TreeNode(8, TreeNode(16, TreeNode(32), TreeNode(33)), TreeNode(17, TreeNode(34), TreeNode(35))), TreeNode(9, TreeNode(18, TreeNode(36), TreeNode(37)), TreeNode(19, TreeNode(38), TreeNode(39)))), TreeNode(5, TreeNode(10, TreeNode(20, TreeNode(40), TreeNode(41)), TreeNode(21, TreeNode(42), TreeNode(43))), TreeNode(6, TreeNode(12, TreeNode(24, TreeNode(48), TreeNode(49)), TreeNode(25, TreeNode(50), TreeNode(51))), TreeNode(13, TreeNode(26, TreeNode(52), TreeNode(53)), TreeNode(27, TreeNode(54), TreeNode(55)))))) == False", "assert is_balanced(TreeNode(1, TreeNode(2, TreeNode(4), TreeNode(5)), TreeNode(3, TreeNode(6), TreeNode(7)))) == True", "assert is_balanced(TreeNode(1, TreeNode(2, TreeNode(4, TreeNode(8), TreeNode(9)), TreeNode(5, TreeNode(10), TreeNode(11))), TreeNode(3, TreeNode(6, TreeNode(12), TreeNode(13)), TreeNode(7, TreeNode(14), TreeNode(15))))) == True"], "function": "is_balanced", "signature": "def is_balanced(root):", "score": 0.9, "domain": "generic"} {"id": "8f4d34b38933e7c6b742ea83282050d1", "problem": "You are given a temperature value and its scale, either Celsius (\"C\") or Fahrenheit (\"F\"). Your task is to write a function `convert_temperature(temp, scale)` that converts the given temperature to the opposite scale. The function should handle both integer and floating-point inputs. If the scale is not \"C\" or \"F\", the function should raise a `ValueError` with the message \"Invalid scale provided. Use 'C' for Celsius or 'F' for Fahrenheit.\"\n\n**Sample Input 1:**\n```\n25, \"C\"\n```\n**Sample Output 1:**\n```\n77.0\n```\n\n**Sample Input 2:**\n```\n32, \"F\"\n```\n**Sample Output 2:**\n```\n0.0\n```\n\n**Sample Input 3:**\n```\n100, \"C\"\n```\n**Sample Output 3:**\n```\n212.0\n```\n\n**Sample Input 4:**\n```\n212, \"F\"\n```\n**Sample Output 4:**\n```\n100.0\n```\n\n**Sample Input 5:**\n```\n0, \"X\"\n```\n**Sample Output 5:**\n```\nValueError: Invalid scale provided. Use 'C' for Celsius or 'F' for Fahrenheit.\n```", "reference": "def convert_temperature(temp, scale):\n \"\"\"\n Convert a given temperature from Celsius to Fahrenheit or vice versa.\n\n Parameters:\n temp (int or float): The temperature value to convert.\n scale (str): The scale of the input temperature, either \"C\" for Celsius or \"F\" for Fahrenheit.\n\n Returns:\n float: The converted temperature value in the opposite scale.\n\n Raises:\n ValueError: If the scale is not \"C\" or \"F\".\n \"\"\"\n if scale == \"C\":\n return (temp * 9/5) + 32\n elif scale == \"F\":\n return (temp - 32) * 5/9\n else:\n raise ValueError(\"Invalid scale provided. Use 'C' for Celsius or 'F' for Fahrenheit.\")", "tests": ["assert convert_temperature(0, \"C\") == 32.0", "assert convert_temperature(100, \"C\") == 212.0", "assert convert_temperature(32, \"F\") == 0.0", "assert convert_temperature(212, \"F\") == 100.0", "assert convert_temperature(-40, \"C\") == -40.0", "assert convert_temperature(-40, \"F\") == -40.0", "assert convert_temperature(37.7778, \"C\") == 99.999986", "assert convert_temperature(99.999986, \"F\") == 37.7778", "assert convert_temperature(25, \"C\") == 77.0", "assert convert_temperature(77, \"F\") == 25.0"], "function": "convert_temperature", "signature": "def convert_temperature(temp, scale):", "score": 0.8, "domain": "generic"} {"id": "1772eef9477b7cbbad843cef5a06b65b", "problem": "You are given a list of numeric data points representing a dataset. Your task is to implement a function `normalizeData` that applies min-max scaling to normalize the data points to the range [0, 1]. The function should handle edge cases such as an empty list or a list where all elements are the same. Return a new list of normalized data points.\n\n**Input:**\n- A list of integers or floating-point numbers `data` (0 ≤ len(data) ≤ 10^5).\n\n**Output:**\n- A list of floating-point numbers representing the normalized data points.\n\n**Sample Input:**\n```python\n[10, 20, 30, 40, 50]\n```\n\n**Sample Output:**\n```python\n[0.0, 0.25, 0.5, 0.75, 1.0]\n```", "reference": "def normalizeData(data):\n \"\"\"\n Normalizes a list of numeric data points using min-max scaling to the range [0, 1].\n \n Parameters:\n data (list of float): The list of numeric data points to be normalized.\n \n Returns:\n list of float: A new list of data points scaled to the range [0, 1].\n \"\"\"\n if not data: # Check if the data list is empty\n return []\n \n min_val = min(data)\n max_val = max(data)\n \n # To avoid division by zero if all values in data are the same\n if min_val == max_val:\n return [0.0 for _ in data]\n \n normalized_data = [(x - min_val) / (max_val - min_val) for x in data]\n return normalized_data", "tests": ["assert normalizeData([1, 2, 3, 4, 5]) == [0.0, 0.25, 0.5, 0.75, 1.0]", "assert normalizeData([10, 10, 10, 10]) == [0.0, 0.0, 0.0, 0.0]", "assert normalizeData([5]) == [0.0]", "assert normalizeData([]) == []", "assert normalizeData([-1, 0, 1]) == [0.0, 0.5, 1.0]", "assert normalizeData([100, 200, 300, 400, 500]) == [0.0, 0.25, 0.5, 0.75, 1.0]", "assert normalizeData([0.5, 1.5, 2.5, 3.5]) == [0.0, 0.3333333333333333, 0.6666666666666666, 1.0]", "assert normalizeData([10, 20]) == [0.0, 1.0]", "assert normalizeData([1, 1, 2, 2, 3, 3]) == [0.0, 0.0, 0.5, 0.5, 1.0, 1.0]", "assert normalizeData([1000, 2000, 3000, 4000, 5000]) == [0.0, 0.25, 0.5, 0.75, 1.0]"], "function": "normalizeData", "signature": "def normalizeData(data):", "score": 1.0, "domain": "generic"} {"id": "d376cb3e4c257413a806073fccc7a3e2", "problem": "You are given a string `s`. Your task is to write a Python function that returns a dictionary with the frequency of each word in the string, ignoring case and punctuation. The words in the dictionary should be in lowercase.\n\n**Input:**\n- A single string `s` (1 ≤ len(s) ≤ 10^4) containing letters, spaces, and punctuation marks.\n\n**Output:**\n- A dictionary where keys are words in lowercase and values are their respective frequencies in the string.\n\n**Sample Input:**\n```\n\"Hello world! This is a test. Hello again, world. This is another test.\"\n```\n\n**Sample Output:**\n```\n{'hello': 2, 'world': 2, 'this': 2, 'is': 2, 'a': 1, 'test': 2, 'again': 1, 'another': 1}\n```", "reference": "import string\nfrom collections import defaultdict\n\ndef word_frequency(input_string):\n \"\"\"\n Returns a dictionary containing the frequency of each word in the input string,\n ignoring case and punctuation.\n\n :param input_string: A string containing words, spaces, and punctuation.\n :return: A dictionary with words as keys and their frequencies as values.\n \"\"\"\n # Normalize the case\n input_string = input_string.lower()\n \n # Remove punctuation\n input_string = input_string.translate(str.maketrans('', '', string.punctuation))\n \n # Split the string into words\n words = input_string.split()\n \n # Create a dictionary to store the frequency of each word\n frequency = defaultdict(int)\n \n # Count the frequency of each word\n for word in words:\n frequency[word] += 1\n \n return dict(frequency)\n\n# Test the function\ninput_string = \"Hello world! This is a test. Hello again, world. This is another test.\"\nprint(word_frequency(input_string))", "tests": ["assert word_frequency(\"Hello world! This is a test. Hello again, world. This is another test.\") == {'hello': 2, 'world': 2, 'this': 2, 'is': 2, 'a': 1, 'test': 2, 'again': 1, 'another': 1}", "assert word_frequency(\"Python, Python, Python!\") == {'python': 3}", "assert word_frequency(\"One fish, two fish, red fish, blue fish.\") == {'one': 1, 'fish': 4, 'two': 1, 'red': 1, 'blue': 1}", "assert word_frequency(\"To be or not to be, that is the question.\") == {'to': 2, 'be': 2, 'or': 1, 'not': 1, 'that': 1, 'is': 1, 'the': 1, 'question': 1}", "assert word_frequency(\"A quick brown fox jumps over the lazy dog.\") == {'a': 1, 'quick': 1, 'brown': 1, 'fox': 1, 'jumps': 1, 'over': 1, 'the': 1, 'lazy': 1, 'dog': 1}", "assert word_frequency(\"\") == {}", "assert word_frequency(\"...\") == {}", "assert word_frequency(\"HELLO hello HeLLo\") == {'hello': 3}", "assert word_frequency(\"Punctuation: should, not! affect; the: frequency.\") == {'punctuation': 1, 'should': 1, 'not': 1, 'affect': 1, 'the': 1, 'frequency': 1}", "assert word_frequency(\"123 456 789 123\") == {'123': 2, '456': 1, '789': 1}"], "function": "word_frequency", "signature": "def word_frequency(input_string):", "score": 1.0, "domain": "generic"} {"id": "bbd5c24e2734e31635bdad4a66691310", "problem": "You are given a non-negative integer `n`. Your task is to write a function `count_set_bits_naive(n)` that returns the number of set bits (1s) in the binary representation of `n`. You must implement this function using only bitwise operations and without using any built-in functions or libraries that directly count set bits.\n\n**Constraints:**\n- `0 ≤ n ≤ 10^9`\n\n**Sample Input:**\n```\n13\n```\n\n**Sample Output:**\n```\n3\n```", "reference": "def count_set_bits_naive(n):\n \"\"\"\n Counts the number of set bits (1s) in the binary representation of a non-negative integer n using bitwise operations.\n\n Parameters:\n n (int): A non-negative integer.\n\n Returns:\n int: The count of set bits in the binary representation of n.\n \"\"\"\n count = 0\n while n > 0:\n count += n & 1\n n >>= 1\n return count", "tests": ["assert count_set_bits_naive(0) == 0", "assert count_set_bits_naive(1) == 1", "assert count_set_bits_naive(2) == 1", "assert count_set_bits_naive(3) == 2", "assert count_set_bits_naive(4) == 1", "assert count_set_bits_naive(5) == 2", "assert count_set_bits_naive(13) == 3", "assert count_set_bits_naive(255) == 8", "assert count_set_bits_naive(1023) == 10", "assert count_set_bits_naive(65535) == 16"], "function": "count_set_bits_naive", "signature": "def count_set_bits_naive(n):", "score": 1.0, "domain": "generic"} {"id": "9d99ec27c2eca10744a1bcb05a9496a2", "problem": "You are given a list of strings `field_names`, each representing a field in a data structure. Each field name may start with one of the following prefixes: `'data.'`, `'info.'`, `'system.'`, `'user.'`, `'main.'`, or `'custom.'`. Your task is to remove these prefixes from the field names if they exist. The function should be efficient enough to handle up to 10,000 field names.\n\n**Input:**\n- A list of strings `field_names` (1 ≤ len(field_names) ≤ 10,000)\n- Each string in `field_names` may start with one of the specified prefixes.\n\n**Output:**\n- A list of strings with the prefixes removed.\n\n**Sample Input:**\n```python\n['data.name', 'info.age', 'system.location', 'user.email', 'main.country', 'custom.description']\n```\n\n**Sample Output:**\n```python\n['name', 'age', 'location', 'email', 'country', 'description']\n```", "reference": "def simplify_field_names(field_names):\n \"\"\"\n Removes specified prefixes from each field name in the list.\n\n Parameters:\n field_names (list of str): List of field names that may start with prefixes.\n\n Returns:\n list of str: List of field names with prefixes removed.\n \"\"\"\n prefixes = ('data.', 'info.', 'system.', 'user.', 'main.', 'custom.')\n \n simplified_names = []\n for name in field_names:\n for prefix in prefixes:\n if name.startswith(prefix):\n name = name[len(prefix):]\n break\n simplified_names.append(name)\n \n return simplified_names\n\n# Example Usage\nfield_names = [\n 'data.name',\n 'info.age',\n 'system.location',\n 'user.email',\n 'main.country',\n 'custom.description'\n]\n\nsimplified_names = simplify_field_names(field_names)\nprint(simplified_names) # Output: ['name', 'age', 'location', 'email', 'country', 'description']", "tests": ["assert simplify_field_names(['data.name']) == ['name']", "assert simplify_field_names(['info.age']) == ['age']", "assert simplify_field_names(['system.location']) == ['location']", "assert simplify_field_names(['user.email']) == ['email']", "assert simplify_field_names(['main.country']) == ['country']", "assert simplify_field_names(['custom.description']) == ['description']", "assert simplify_field_names(['data.name', 'info.age']) == ['name', 'age']", "assert simplify_field_names(['data.data.name']) == ['data.name']", "assert simplify_field_names(['name', 'age']) == ['name', 'age']", "assert simplify_field_names(['data.info.name']) == ['info.name']"], "function": "simplify_field_names", "signature": "def simplify_field_names(field_names):", "score": 1.0, "domain": "generic"} {"id": "2816130ea9c569e4136594182aa39441", "problem": "You are given a list of integers. Your task is to write a Python function that filters out the even numbers from this list and returns a new list containing only those even numbers. The function should be straightforward and easy to understand.\n\n**Sample Input:**\n```python\n[1, 2, 3, 4, 5, 6]\n```\n\n**Sample Output:**\n```python\n[2, 4, 6]\n```", "reference": "def filter_even_numbers(numbers):\n \"\"\"\n Filters out even numbers from the input list and returns a new list containing only those even numbers.\n\n :param numbers: List of integers\n :return: List of even integers\n \"\"\"\n even_numbers = []\n for number in numbers:\n if number % 2 == 0:\n even_numbers.append(number)\n return even_numbers", "tests": ["assert filter_even_numbers([1, 2, 3, 4, 5, 6]) == [2, 4, 6]", "assert filter_even_numbers([10, 15, 20, 25, 30]) == [10, 20, 30]", "assert filter_even_numbers([11, 13, 17, 19]) == []", "assert filter_even_numbers([]) == []", "assert filter_even_numbers([0, -2, -4, -5]) == [0, -2, -4]", "assert filter_even_numbers([2, 4, 6, 8, 10]) == [2, 4, 6, 8, 10]", "assert filter_even_numbers([-1, -3, -5, -7]) == []", "assert filter_even_numbers([100, 200, 300, 400]) == [100, 200, 300, 400]", "assert filter_even_numbers([1, 3, 5, 7, 9, 11]) == []", "assert filter_even_numbers([22, 33, 44, 55, 66]) == [22, 44, 66]"], "function": "filter_even_numbers", "signature": "def filter_even_numbers(numbers):", "score": 1.0, "domain": "generic"} {"id": "6884b2ec582928db4053b44a8414a800", "problem": "You are given a list of tuples, where each tuple consists of a category (a string) and a line number (an integer). Your task is to sort this list based on the following criteria:\n1. The length of the category string in ascending order.\n2. If two categories have the same length, sort them lexicographically (alphabetically).\n3. If both the length and lexicographical order are the same, sort them by their line numbers in ascending order.\n\nWrite a function `sort_categories` that takes a list of tuples as input and returns the sorted list.\n\n**Sample Input:**\n```python\ncategories = [(\"apple\", 5), (\"banana\", 2), (\"pear\", 3), (\"kiwi\", 1), (\"plum\", 4), (\"grape\", 2)]\n```\n\n**Sample Output:**\n```python\n[('kiwi', 1), ('pear', 3), ('apple', 5), ('grape', 2), ('plum', 4), ('banana', 2)]\n```", "reference": "def sort_categories(categories):\n \"\"\"\n Sorts a list of tuples based on the length of the category string, \n then lexicographically, and finally by line number if needed.\n \n :param categories: List of tuples, where each tuple contains a category string and a line number.\n :return: Sorted list of tuples based on the specified criteria.\n \"\"\"\n return sorted(categories, key=lambda x: (len(x[0]), x[0], x[1]))", "tests": ["assert sort_categories([(\"apple\", 5), (\"banana\", 2), (\"pear\", 3), (\"kiwi\", 1), (\"plum\", 4), (\"grape\", 2)]) == [('kiwi', 1), ('pear', 3), ('apple', 5), ('grape', 2), ('plum', 4), ('banana', 2)]", "assert sort_categories([(\"cat\", 1), (\"dog\", 2), (\"elephant\", 3)]) == [('cat', 1), ('dog', 2), ('elephant', 3)]", "assert sort_categories([(\"a\", 1), (\"b\", 2), (\"c\", 3)]) == [('a', 1), ('b', 2), ('c', 3)]", "assert sort_categories([(\"abc\", 3), (\"ab\", 2), (\"a\", 1)]) == [('a', 1), ('ab', 2), ('abc', 3)]", "assert sort_categories([(\"same\", 1), (\"same\", 2), (\"same\", 3)]) == [('same', 1), ('same', 2), ('same', 3)]", "assert sort_categories([(\"zebra\", 1), (\"apple\", 2), (\"zebra\", 3), (\"apple\", 4)]) == [('apple', 2), ('apple', 4), ('zebra', 1), ('zebra', 3)]", "assert sort_categories([(\"dog\", 1), (\"cat\", 2), (\"dog\", 3), (\"cat\", 4)]) == [('cat', 2), ('cat', 4), ('dog', 1), ('dog', 3)]", "assert sort_categories([(\"banana\", 1), (\"banana\", 2), (\"apple\", 3), (\"apple\", 4)]) == [('apple', 3), ('apple', 4), ('banana', 1), ('banana', 2)]", "assert sort_categories([]) == []", "assert sort_categories([(\"a\", 1), (\"aa\", 2), (\"aaa\", 3), (\"aaaa\", 4)]) == [('a', 1), ('aa', 2), ('aaa', 3), ('aaaa', 4)]"], "function": "sort_categories", "signature": "def sort_categories(categories):", "score": 0.9, "domain": "generic"} {"id": "fd22774d4e532ab6b2291d408001ffde", "problem": "You are developing a function for a game where players can select from different character classes. Each class has unique abilities. Your task is to implement a function `parse_character_class` that processes a string input to determine the corresponding character class. The function should handle case insensitivity, trim any leading or trailing whitespace, and return the appropriate `CharacterClass` value. If the input does not match any known class, the function should return `CharacterClass.WARRIOR` by default. The function should also handle invalid or corrupted input gracefully.\n\n**Sample Input and Output:**\n- Input: `\" WARRIOR \"`\n - Output: `CharacterClass.WARRIOR`\n- Input: `\" mage\"`\n - Output: `CharacterClass.MAGE`\n- Input: `\"unknown\"`\n - Output: `CharacterClass.WARRIOR`\n- Input: `\" ROGUE \"`\n - Output: `CharacterClass.ROGUE`", "reference": "from enum import Enum\n\nclass CharacterClass(Enum):\n WARRIOR = 'warrior'\n MAGE = 'mage'\n ROGUE = 'rogue'\n ARCHER = 'archer'\n CLERIC = 'cleric'\n\ndef parse_character_class(input_string: str) -> CharacterClass:\n \"\"\"\n Parses the input string to determine the corresponding character class.\n \n Parameters:\n input_string (str): The input string representing the character class.\n \n Returns:\n CharacterClass: The corresponding CharacterClass value if it exists, \n otherwise CharacterClass.WARRIOR.\n \"\"\"\n processed_input = input_string.strip().lower()\n try:\n return CharacterClass(processed_input)\n except ValueError:\n return CharacterClass.WARRIOR", "tests": ["assert parse_character_class(\" WARRIOR \") == CharacterClass.WARRIOR", "assert parse_character_class(\" mage\") == CharacterClass.MAGE", "assert parse_character_class(\"unknown\") == CharacterClass.WARRIOR", "assert parse_character_class(\" ROGUE \") == CharacterClass.ROGUE", "assert parse_character_class(\"archer\") == CharacterClass.ARCHER", "assert parse_character_class(\" CLERIC \") == CharacterClass.CLERIC", "assert parse_character_class(\" \") == CharacterClass.WARRIOR", "assert parse_character_class(\"WARRIOR\") == CharacterClass.WARRIOR", "assert parse_character_class(\"rogue \") == CharacterClass.ROGUE", "assert parse_character_class(\"ARCHER \") == CharacterClass.ARCHER"], "function": "parse_character_class", "signature": "def parse_character_class(input_string: str) -> CharacterClass:", "score": 1.0, "domain": "generic"} {"id": "6cc14b6c9013dd680da4e6df97e6600c", "problem": "You are given a list of integers `nums` and an integer `target`. Your task is to find a triplet `(a, b, c)` from the list such that:\n- `a`, `b`, and `c` are in strictly increasing order.\n- `a` is an even number.\n- The sum of `a`, `b`, and `c` equals `target`.\n\nReturn the first such triplet found in the order of their appearance in the list. If no such triplet exists, return an empty tuple.\n\n**Constraints:**\n- `1 <= len(nums) <= 1000`\n- `-1000 <= nums[i] <= 1000`\n- `-3000 <= target <= 3000`\n\n**Sample Input:**\n```\nnums = [2, 1, 3, 4, 5, 6]\ntarget = 10\n```\n\n**Sample Output:**\n```\n(2, 3, 5)\n```", "reference": "def find_triplets(nums, target):\n \"\"\"\n Finds a triplet (a, b, c) in the list nums such that:\n - a < b < c\n - a is even\n - a + b + c = target\n \n Returns the first such triplet found, or an empty tuple if no such triplet exists.\n \"\"\"\n for i in range(len(nums)):\n if nums[i] % 2 != 0:\n continue\n for j in range(i + 1, len(nums)):\n for k in range(j + 1, len(nums)):\n if nums[i] < nums[j] < nums[k] and nums[i] + nums[j] + nums[k] == target:\n return (nums[i], nums[j], nums[k])\n return ()", "tests": ["assert find_triplets([2, 1, 3, 4, 5, 6], 10) == (2, 3, 5)", "assert find_triplets([2, 4, 6, 8, 10], 18) == (2, 4, 12)", "assert find_triplets([1, 3, 5, 7, 9], 15) == ()", "assert find_triplets([2, 4, 6, 8, 10], 30) == ()", "assert find_triplets([2, 3, 1, 4, 5, 6], 12) == (2, 4, 6)", "assert find_triplets([10, 20, 30, 40, 50], 100) == (20, 30, 50)", "assert find_triplets([2, 3, 5, 7, 11, 13], 21) == (2, 5, 14)", "assert find_triplets([2, 4, 6, 8, 10, 12], 24) == (2, 10, 12)", "assert find_triplets([2, 4, 6, 8, 10, 12], 6) == ()", "assert find_triplets([2, 4, 6, 8, 10, 12], 36) == (2, 12, 22)"], "function": "find_triplets", "signature": "def find_triplets(nums, target):", "score": 0.6, "domain": "generic"} {"id": "cf3ca0ec490697df1edf081778563f2a", "problem": "You are developing a simulation for a water treatment plant. The plant has multiple components, each with an efficiency that varies hourly. Your task is to implement a function that retrieves the efficiency of a specific component at a given hour.\n\n**Input:**\n- An integer `n_hours` representing the number of hours in a day (typically 24).\n- An integer `n_components` representing the number of components in the plant.\n- A dictionary `efficiencies` where keys are component names (formatted as \"Component_X\" where X is an integer) and values are dictionaries mapping each hour (0 to `n_hours-1`) to a floating-point efficiency value between 0.5 and 1.0.\n- An integer `hour` representing the hour of the day for which the efficiency is to be retrieved (0 ≤ hour < `n_hours`).\n- A string `component` representing the name of the component for which the efficiency is to be retrieved.\n\n**Output:**\n- A floating-point number representing the efficiency of the specified component at the specified hour.\n\n**Sample Input:**\n- `n_hours = 24`\n- `n_components = 5`\n- `efficiencies = {'Component_1': {0: 0.75, 1: 0.85, ..., 23: 0.95}, 'Component_2': {...}, ..., 'Component_5': {...}}`\n- `hour = 12`\n- `component = 'Component_1'`\n\n**Sample Output:**\n- `0.85`", "reference": "import random\n\ndef generate_sample_efficiencies(n_hours=24, n_components=5):\n \"\"\"\n Generate sample efficiencies for n_hours and n_components.\n \n :param n_hours: Integer, number of hours in a day.\n :param n_components: Integer, number of components in the plant.\n :return: Dictionary with component names as keys and hourly efficiencies as values.\n \"\"\"\n return {f\"Component_{i}\": {hour: random.uniform(0.5, 1.0) for hour in range(n_hours)} for i in range(1, n_components + 1)}\n\ndef get_efficiency(hour, component, efficiencies):\n \"\"\"\n Get efficiency of a specific component at a specific hour.\n \n :param hour: Integer, hour of the day (0 ≤ hour < n_hours).\n :param component: String, name of the component.\n :param efficiencies: Dictionary, data structure for hourly-varying efficiencies.\n :return: Efficiency floating-point value for the component at the hour.\n \"\"\"\n if hour < 0 or hour >= 24:\n raise ValueError(\"Hour must be between 0 and 23, inclusive.\")\n \n if component not in efficiencies:\n raise ValueError(f\"Component {component} not found.\")\n \n return efficiencies[component][hour]\n \n# Example usage:\nefficiencies = generate_sample_efficiencies()\nsample_hour = 12\nsample_component = 'Component_1'\nefficiency_at_hour = get_efficiency(sample_hour, sample_component, efficiencies)\n\nprint(f\"The efficiency of {sample_component} at hour {sample_hour} is {round(efficiency_at_hour, 2)}\")", "tests": ["assert get_efficiency(0, 'Component_1', {'Component_1': {0: 0.75}}) == 0.75", "assert get_efficiency(23, 'Component_5', {'Component_5': {23: 0.95}}) == 0.95", "assert get_efficiency(12, 'Component_3', {'Component_3': {12: 0.85}}) == 0.85", "assert get_efficiency(5, 'Component_2', {'Component_2': {5: 0.65}}) == 0.65", "assert get_efficiency(18, 'Component_4', {'Component_4': {18: 0.90}}) == 0.90", "assert get_efficiency(0, 'Component_1', generate_sample_efficiencies()) >= 0.5 and get_efficiency(0, 'Component_1', generate_sample_efficiencies()) <= 1.0", "assert get_efficiency(23, 'Component_5', generate_sample_efficiencies()) >= 0.5 and get_efficiency(23, 'Component_5', generate_sample_efficiencies()) <= 1.0", "try: get_efficiency(24, 'Component_1', generate_sample_efficiencies()); assert False except ValueError: assert True", "try: get_efficiency(-1, 'Component_1', generate_sample_efficiencies()); assert False except ValueError: assert True", "try: get_efficiency(12, 'Component_6', generate_sample_efficiencies()); assert False except ValueError: assert True"], "function": "get_efficiency", "signature": "def get_efficiency(hour, component, efficiencies):", "score": 0.7, "domain": "generic"} {"id": "c686d6ab3855e18716643d31097d74f1", "problem": "You are tasked with implementing a function `calculate_sales_tax` for a financial application. The function should compute the total price of an item including sales tax. Given the `price` of an item and the `tax_rate` as a percentage, the function should return the total price. If either `price` or `tax_rate` is negative, the function should raise a `ValueError`.\n\n**Input:**\n- Two floating-point numbers: `price` and `tax_rate`.\n\n**Output:**\n- A floating-point number representing the total price including sales tax.\n\n**Sample Input:**\n- `price = 100.0`, `tax_rate = 5.0`\n\n**Sample Output:**\n- `105.0`\n\n**Constraints:**\n- `0 <= price <= 10^6`\n- `0 <= tax_rate <= 100`", "reference": "def calculate_sales_tax(price, tax_rate):\n \"\"\"\n Calculate the total price including sales tax.\n\n Parameters:\n price (float): The price of the item.\n tax_rate (float): The sales tax rate as a percentage.\n\n Returns:\n float: The total price including sales tax.\n\n Raises:\n ValueError: If price or tax_rate is negative.\n \"\"\"\n if price < 0 or tax_rate < 0:\n raise ValueError(\"Price and tax rate must be non-negative.\")\n tax_amount = price * (tax_rate / 100)\n total_price = price + tax_amount\n return total_price", "tests": ["assert calculate_sales_tax(100, 10) == 110.0", "assert calculate_sales_tax(0, 0) == 0.0", "assert calculate_sales_tax(50, 5) == 52.5", "assert calculate_sales_tax(200, 0) == 200.0", "assert calculate_sales_tax(150, 20) == 180.0", "assert calculate_sales_tax(123.45, 7.5) == 132.86625", "assert calculate_sales_tax(1000, 15) == 1150.0", "assert calculate_sales_tax(10, 100) == 20.0", "assert calculate_sales_tax(100, -5) == ValueError", "assert calculate_sales_tax(-100, 10) == ValueError"], "function": "calculate_sales_tax", "signature": "def calculate_sales_tax(price, tax_rate):", "score": 0.7, "domain": "generic"} {"id": "29b18ecd79b406981d343775def0b514", "problem": "You are given two sorted arrays, `arr1` and `arr2`, of lengths `n` and `m` respectively. Your task is to write a function `merge_sorted_arrays` that merges these two arrays into a single sorted array. The function should have a time complexity of O(n + m).\n\n**Input:**\n- Two sorted arrays `arr1` and `arr2`.\n\n**Output:**\n- A single sorted array containing all elements from `arr1` and `arr2`.\n\n**Sample Input:**\n- `arr1 = [1, 4, 7]`\n- `arr2 = [2, 3, 5, 6]`\n\n**Sample Output:**\n- `[1, 2, 3, 4, 5, 6]`", "reference": "def merge_sorted_arrays(arr1, arr2):\n \"\"\"\n Merges two sorted arrays into a single sorted array.\n\n Parameters:\n arr1 (list): The first sorted array.\n arr2 (list): The second sorted array.\n\n Returns:\n list: A merged sorted array containing all elements from arr1 and arr2.\n \"\"\"\n i, j = 0, 0 # Initialize two pointers\n merged = [] # Initialize the merged list\n \n # Compare elements from both arrays and add the smaller to the merged list\n while i < len(arr1) and j < len(arr2):\n if arr1[i] < arr2[j]:\n merged.append(arr1[i])\n i += 1\n else:\n merged.append(arr2[j])\n j += 1\n \n # Add remaining elements from arr1\n while i < len(arr1):\n merged.append(arr1[i])\n i += 1\n \n # Add remaining elements from arr2\n while j < len(arr2):\n merged.append(arr2[j])\n j += 1\n \n return merged # Return the merged list", "tests": ["assert merge_sorted_arrays([], []) == []", "assert merge_sorted_arrays([1, 3, 5], [2, 4, 6]) == [1, 2, 3, 4, 5, 6]", "assert merge_sorted_arrays([1, 2, 3], []) == [1, 2, 3]", "assert merge_sorted_arrays([], [1, 2, 3]) == [1, 2, 3]", "assert merge_sorted_arrays([1, 2, 3], [4, 5, 6]) == [1, 2, 3, 4, 5, 6]", "assert merge_sorted_arrays([10, 20, 30], [5, 15, 25, 35]) == [5, 10, 15, 20, 25, 30, 35]", "assert merge_sorted_arrays([1, 1, 1], [1, 1, 1]) == [1, 1, 1, 1, 1, 1]", "assert merge_sorted_arrays([1, 3, 5, 7], [2, 4, 6, 8, 10]) == [1, 2, 3, 4, 5, 6, 7, 8, 10]", "assert merge_sorted_arrays([-1, 0, 1], [-2, -1, 0, 2]) == [-2, -1, -1, 0, 0, 1, 2]", "assert merge_sorted_arrays([1], [2]) == [1, 2]"], "function": "merge_sorted_arrays", "signature": "def merge_sorted_arrays(arr1, arr2):", "score": 1.0, "domain": "generic"} {"id": "b62b4b31f43dfa5932567564eeb8b7c3", "problem": "You are tasked with creating a Python program that generates a CSV file. The CSV file should contain a specified number of rows and columns, with each cell filled with a random integer between 0 and 100, inclusive. Your program should define a function `generate_csv` that takes three parameters: the filename of the CSV file to be created, the number of rows, and the number of columns.\n\n**Input:**\n- The function `generate_csv` will be called with the following parameters:\n - `filename`: A string representing the name of the CSV file.\n - `rows`: An integer representing the number of rows in the CSV file.\n - `columns`: An integer representing the number of columns in the CSV file.\n\n**Output:**\n- A CSV file named `filename` with `rows` rows and `columns` columns, where each cell contains a random integer between 0 and 100.\n\n**Sample Input:**\n```python\ngenerate_csv('sample_output.csv', 4, 5)\n```\n\n**Sample Output:**\nA file named `sample_output.csv` with the following content (values will vary due to randomness):\n```\n23,45,67,89,12\n34,56,78,90,11\n45,67,89,10,22\n56,78,90,11,33\n```", "reference": "import csv\nimport random\n\ndef generate_csv(filename, rows, columns):\n \"\"\"\n Generates a CSV file with the specified number of rows and columns,\n where each cell contains a random integer between 0 and 100.\n\n :param filename: The name of the CSV file to be created.\n :param rows: The number of rows in the CSV file.\n :param columns: The number of columns in the CSV file.\n \"\"\"\n with open(filename, 'w', newline='') as csvfile:\n csvwriter = csv.writer(csvfile)\n for _ in range(rows):\n row = [random.randint(0, 100) for _ in range(columns)]\n csvwriter.writerow(row)", "tests": ["assert generate_csv('test1.csv', 0, 0) is None", "assert generate_csv('test2.csv', 1, 1) is None", "assert generate_csv('test3.csv', 3, 2) is None", "assert generate_csv('test4.csv', 2, 3) is None", "assert generate_csv('test5.csv', 10, 10) is None", "assert generate_csv('test6.csv', 1, 100) is None", "assert generate_csv('test7.csv', 100, 1) is None", "assert generate_csv('test8.csv', 50, 50) is None", "assert generate_csv('test9.csv', 100, 100) is None", "assert generate_csv('test10.csv', 0, 10) is None"], "function": "generate_csv", "signature": "def generate_csv(filename, rows, columns):", "score": 1.0, "domain": "algorithmic"} {"id": "0fd90d99ed67ac3f2948c42f5d7c1489", "problem": "You are tasked with implementing a recursive function `text_categorizer` that processes a given string `text` and categorizes its characters into five distinct groups: Uppercase letters, Lowercase letters, Punctuation marks, Digits, and Whitespace characters. The function should return a dictionary with these categories as keys and their respective counts as values. You must solve this problem using recursion only, without employing any loops or iterative constructs.\n\n**Sample Input:**\n```\n\"Hello, World! 123\"\n```\n\n**Sample Output:**\n```\n{\n 'Uppercase letters': 2,\n 'Lowercase letters': 8,\n 'Punctuation marks': 2,\n 'Digits': 3,\n 'Whitespace characters': 2\n}\n```", "reference": "def text_categorizer(text):\n \"\"\"\n Recursively categorizes characters in the input string into Uppercase letters,\n Lowercase letters, Punctuation marks, Digits, and Whitespace characters.\n \n Parameters:\n text (str): The input string to be categorized.\n \n Returns:\n dict: A dictionary with categories as keys and counts of characters as values.\n \"\"\"\n def helper(text, counts):\n if not text:\n return counts\n char = text[0]\n if char.isupper():\n counts['Uppercase letters'] += 1\n elif char.islower():\n counts['Lowercase letters'] += 1\n elif char.isdigit():\n counts['Digits'] += 1\n elif char.isspace():\n counts['Whitespace characters'] += 1\n else:\n counts['Punctuation marks'] += 1\n return helper(text[1:], counts)\n\n initial_counts = {\n 'Uppercase letters': 0,\n 'Lowercase letters': 0,\n 'Punctuation marks': 0,\n 'Digits': 0,\n 'Whitespace characters': 0\n }\n \n return helper(text, initial_counts)", "tests": ["assert text_categorizer(\"Hello, World!\") == {'Uppercase letters': 2, 'Lowercase letters': 8, 'Punctuation marks': 2, 'Digits': 0, 'Whitespace characters': 1}", "assert text_categorizer(\"12345\") == {'Uppercase letters': 0, 'Lowercase letters': 0, 'Punctuation marks': 0, 'Digits': 5, 'Whitespace characters': 0}", "assert text_categorizer(\"PYTHON\") == {'Uppercase letters': 6, 'Lowercase letters': 0, 'Punctuation marks': 0, 'Digits': 0, 'Whitespace characters': 0}", "assert text_categorizer(\"python\") == {'Uppercase letters': 0, 'Lowercase letters': 6, 'Punctuation marks': 0, 'Digits': 0, 'Whitespace characters': 0}", "assert text_categorizer(\" \") == {'Uppercase letters': 0, 'Lowercase letters': 0, 'Punctuation marks': 0, 'Digits': 0, 'Whitespace characters': 1}", "assert text_categorizer(\"!@#$%^&*()\") == {'Uppercase letters': 0, 'Lowercase letters': 0, 'Punctuation marks': 10, 'Digits': 0, 'Whitespace characters': 0}", "assert text_categorizer(\"aB3 dE5\") == {'Uppercase letters': 2, 'Lowercase letters': 2, 'Punctuation marks': 0, 'Digits': 2, 'Whitespace characters': 1}", "assert text_categorizer(\"\") == {'Uppercase letters': 0, 'Lowercase letters': 0, 'Punctuation marks': 0, 'Digits': 0, 'Whitespace characters': 0}", "assert text_categorizer(\"A1 B2 C3\") == {'Uppercase letters': 3, 'Lowercase letters': 0, 'Punctuation marks': 0, 'Digits': 3, 'Whitespace characters': 2}", "assert text_categorizer(\"a b c d e f g\") == {'Uppercase letters': 0, 'Lowercase letters': 7, 'Punctuation marks': 0, 'Digits': 0, 'Whitespace characters': 6}"], "function": "text_categorizer", "signature": "def text_categorizer(text):", "score": 1.0, "domain": "generic"} {"id": "a9a3a583517638aae43589abaffcc471", "problem": "You are given a list of strings `words` and a list of integers `word_indices`. Your task is to implement a function `extract_selected_words(words, word_indices)` that returns a list containing the words at the specified indices. If an index is out of range, it should be ignored.\n\n**Input:**\n- A list of strings `words` (1 ≤ len(words) ≤ 100).\n- A list of integers `word_indices` (0 ≤ len(word_indices) ≤ 100).\n\n**Output:**\n- A list of strings containing the words at the specified indices, excluding any out-of-range indices.\n\n**Sample Input:**\n```\nwords = [\"apple\", \"banana\", \"cherry\", \"date\", \"elderberry\"]\nword_indices = [1, 3, 5]\n```\n\n**Sample Output:**\n```\n['banana', 'date']\n```", "reference": "def extract_selected_words(words, word_indices):\n \"\"\"\n Returns a list of words at the specified indices, ignoring out-of-range indices.\n\n :param words: List of strings.\n :param word_indices: List of integers representing indices.\n :return: List of strings at the specified indices.\n \"\"\"\n selected_words = []\n for index in word_indices:\n if 0 <= index < len(words):\n selected_words.append(words[index])\n return selected_words\n\n# Example usage:\nwords = [\"apple\", \"banana\", \"cherry\", \"date\", \"elderberry\"]\nword_indices = [1, 3, 5]\nprint(extract_selected_words(words, word_indices)) # Output: ['banana', 'date']", "tests": ["assert extract_selected_words([\"apple\", \"banana\", \"cherry\"], [0, 2]) == [\"apple\", \"cherry\"]", "assert extract_selected_words([\"apple\", \"banana\", \"cherry\"], [1, 1, 1]) == [\"banana\", \"banana\", \"banana\"]", "assert extract_selected_words([\"apple\", \"banana\", \"cherry\"], [3, 4, 5]) == []", "assert extract_selected_words([\"apple\", \"banana\", \"cherry\"], [-1, -2, -3]) == []", "assert extract_selected_words([\"apple\", \"banana\", \"cherry\"], [0, 1, 2, 3, 4]) == [\"apple\", \"banana\", \"cherry\"]", "assert extract_selected_words([], [0, 1, 2]) == []", "assert extract_selected_words([\"apple\", \"banana\", \"cherry\"], []) == []", "assert extract_selected_words([\"apple\", \"banana\", \"cherry\"], [0, 2, 4, 1]) == [\"apple\", \"cherry\", \"banana\"]", "assert extract_selected_words([\"apple\", \"banana\", \"cherry\"], [2, 0]) == [\"cherry\", \"apple\"]", "assert extract_selected_words([\"apple\", \"banana\", \"cherry\"], [1, 2, 0, 1]) == [\"banana\", \"cherry\", \"apple\", \"banana\"]"], "function": "extract_selected_words", "signature": "def extract_selected_words(words, word_indices):", "score": 1.0, "domain": "generic"} {"id": "b8de3a2a0022c4b364c984fad3f181dd", "problem": "Given a string `s` consisting of '(' and ')' characters, determine the length of the longest valid (properly nested) parentheses substring. A valid parentheses substring is one where every opening parenthesis '(' has a corresponding closing parenthesis ')', and they are correctly nested.\n\n**Input:**\n- A single string `s` (1 ≤ |s| ≤ 30,000) containing only '(' and ')' characters.\n\n**Output:**\n- An integer representing the length of the longest valid parentheses substring.\n\n**Sample Input:**\n```\n(()())\n```\n\n**Sample Output:**\n```\n6\n```\n\n**Sample Input:**\n```\n)()())()\n```\n\n**Sample Output:**\n```\n4\n```", "reference": "def longest_valid_parentheses(s: str) -> int:\n \"\"\"\n Returns the length of the longest valid (properly nested) parentheses substring in the given string `s`.\n \n :param s: A string consisting of '(' and ')' characters.\n :return: An integer representing the length of the longest valid parentheses substring.\n \"\"\"\n max_length = 0\n stack = [-1] # Initialize stack with base value -1\n\n for i, char in enumerate(s):\n if char == '(':\n stack.append(i)\n else:\n stack.pop()\n if not stack:\n stack.append(i)\n else:\n max_length = max(max_length, i - stack[-1])\n\n return max_length", "tests": ["assert longest_valid_parentheses(\"(()())\") == 6", "assert longest_valid_parentheses(\"()()\") == 4", "assert longest_valid_parentheses(\")(\") == 0", "assert longest_valid_parentheses(\"((()))\") == 6", "assert longest_valid_parentheses(\"(()\") == 2", "assert longest_valid_parentheses(\")()(\") == 2", "assert longest_valid_parentheses(\"\") == 0", "assert longest_valid_parentheses(\"()(()\") == 2", "assert longest_valid_parentheses(\"()((()))\") == 8", "assert longest_valid_parentheses(\"((((((()))))))\") == 14"], "function": "longest_valid_parentheses", "signature": "def longest_valid_parentheses(s: str) -> int:", "score": 1.0, "domain": "generic"} {"id": "7e5677bac19d889bc5592d702d3d5a10", "problem": "You are given a string `s` consisting of words separated by spaces and punctuation. Your task is to determine the number of unique words in the string. Words are defined as sequences of alphabetic characters and are case-insensitive. All punctuation marks and whitespace should be disregarded.\n\n**Input:**\n- A single string `s` (1 ≤ |s| ≤ 10^5) containing words, spaces, and punctuation.\n\n**Output:**\n- An integer representing the number of unique words in the string.\n\n**Sample Input:**\n```\n\"Hello world! Hello Python. Python is great.\"\n```\n\n**Sample Output:**\n```\n5\n```", "reference": "import re\n\ndef count_unique_words(text: str) -> int:\n \"\"\"\n Counts the number of unique words in a given string.\n \n Parameters:\n text (str): The input string containing words, spaces, and punctuation.\n \n Returns:\n int: The number of unique words in the string.\n \"\"\"\n words = re.findall(r'[a-zA-Z]+', text.lower())\n unique_words = set(words)\n return len(unique_words)\n\n# Test the function\ninput_string = \"Hello world! Hello Python. Python is great.\"\nprint(count_unique_words(input_string)) # Output should be 5", "tests": ["assert count_unique_words(\"Hello world! Hello Python. Python is great.\") == 5", "assert count_unique_words(\"This is a test. This test is only a test.\") == 6", "assert count_unique_words(\"One fish, two fish, red fish, blue fish.\") == 5", "assert count_unique_words(\"Python, python, PYTHON, pyThOn\") == 1", "assert count_unique_words(\"A quick brown fox jumps over the lazy dog.\") == 8", "assert count_unique_words(\"To be or not to be, that is the question.\") == 10", "assert count_unique_words(\"123 456 789\") == 0", "assert count_unique_words(\"!@#$%^&*()\") == 0", "assert count_unique_words(\"\") == 0", "assert count_unique_words(\"Unique words, unique Words, UNIQUE words.\") == 3"], "function": "count_unique_words", "signature": "def count_unique_words(text: str) -> int:", "score": 0.6, "domain": "generic"} {"id": "2f24022e37ff59d5b73a8e5e44cd2323", "problem": "You are given two N x N matrices, A and B. Determine the minimum number of 90-degree clockwise rotations required to transform matrix A into matrix B. If it is impossible to transform A into B through any number of such rotations, return -1. \n\n**Input:**\n- The first line contains an integer N, the size of the matrices.\n- The next N lines contain N integers each, representing matrix A.\n- The following N lines contain N integers each, representing matrix B.\n\n**Output:**\n- Print a single integer representing the minimum number of rotations needed. If transformation is not possible, print -1.\n\n**Sample Input:**\n```\n3\n1 2 3\n4 5 6\n7 8 9\n7 4 1\n8 5 2\n9 6 3\n```\n\n**Sample Output:**\n```\n1\n```", "reference": "def rotate_matrix(matrix):\n \"\"\"\n Rotates a given N x N matrix 90 degrees clockwise.\n \n :param matrix: List of lists, where each sublist represents a row of the matrix.\n :return: List of lists, representing the rotated matrix.\n \"\"\"\n n = len(matrix)\n rotated = [[0] * n for _ in range(n)]\n for i in range(n):\n for j in range(n):\n rotated[j][n - 1 - i] = matrix[i][j]\n return rotated\n\ndef find_rotations(A, B):\n \"\"\"\n Determines the minimum number of 90-degree clockwise rotations required to transform matrix A into matrix B.\n \n :param A: List of lists, representing the original matrix.\n :param B: List of lists, representing the target matrix.\n :return: Integer, the minimum number of rotations needed, or -1 if transformation is not possible.\n \"\"\"\n if A == B:\n return 0\n for i in range(3):\n A = rotate_matrix(A)\n if A == B:\n return i + 1\n return -1\n\n# Test the function\nA = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]\nB = [[7, 4, 1], [8, 5, 2], [9, 6, 3]]\n\nprint(find_rotations(A, B)) # Expected output: 1", "tests": ["assert find_rotations([[1, 2], [3, 4]], [[3, 1], [4, 2]]) == 1", "assert find_rotations([[1, 2], [3, 4]], [[4, 3], [2, 1]]) == 2", "assert find_rotations([[1, 2], [3, 4]], [[2, 4], [1, 3]]) == 3", "assert find_rotations([[1, 2], [3, 4]], [[1, 2], [3, 4]]) == 0", "assert find_rotations([[1, 2], [3, 4]], [[4, 1], [3, 2]]) == -1", "assert find_rotations([[1, 2, 3], [4, 5, 6], [7, 8, 9]], [[7, 4, 1], [8, 5, 2], [9, 6, 3]]) == 1", "assert find_rotations([[1, 2, 3], [4, 5, 6], [7, 8, 9]], [[9, 8, 7], [6, 5, 4], [3, 2, 1]]) == 2", "assert find_rotations([[1, 2, 3], [4, 5, 6], [7, 8, 9]], [[3, 6, 9], [2, 5, 8], [1, 4, 7]]) == 3", "assert find_rotations([[1, 2, 3], [4, 5, 6], [7, 8, 9]], [[1, 2, 3], [4, 5, 6], [7, 8, 9]]) == 0", "assert find_rotations([[1, 2, 3], [4, 5, 6], [7, 8, 9]], [[1, 4, 7], [2, 5, 8], [3, 6, 9]]) == -1"], "function": "find_rotations", "signature": "def find_rotations(A, B):", "score": 1.0, "domain": "algorithmic"} {"id": "f6cb40c2c2ab3b95b58b26ec167dec5a", "problem": "You are given a list of integers. Your task is to write a function that returns the index of the first element in the list that is a perfect square. If no such element exists, the function should return -1.\n\n**Input:**\n- A list of integers `numbers` (1 ≤ len(numbers) ≤ 10^5), where each integer is in the range -10^9 ≤ numbers[i] ≤ 10^9.\n\n**Output:**\n- An integer representing the index of the first perfect square in the list, or -1 if no perfect square is found.\n\n**Sample Input:**\n```\n[3, 10, 15, 16, 23]\n```\n\n**Sample Output:**\n```\n3\n```", "reference": "import math\n\ndef find_first_perfect_square(numbers):\n \"\"\"\n Returns the index of the first element in the list that is a perfect square.\n If no such element exists, returns -1.\n\n :param numbers: List of integers\n :return: Index of the first perfect square or -1 if none exists\n \"\"\"\n for index, number in enumerate(numbers):\n if number >= 0 and math.isqrt(number) ** 2 == number:\n return index\n return -1\n\n# Example usage\nnumbers = [3, 10, 15, 16, 23]\nresult = find_first_perfect_square(numbers)\nprint(result) # Output: 3", "tests": ["assert find_first_perfect_square([1, 2, 3, 4, 5]) == 0", "assert find_first_perfect_square([2, 3, 5, 7, 11]) == -1", "assert find_first_perfect_square([16, 25, 36, 49]) == 0", "assert find_first_perfect_square([10, 15, 21, 25, 30]) == 3", "assert find_first_perfect_square([0, 1, 4, 9, 16]) == 0", "assert find_first_perfect_square([14, 15, 16, 17, 18]) == 2", "assert find_first_perfect_square([100, 121, 144, 169]) == 0", "assert find_first_perfect_square([]) == -1", "assert find_first_perfect_square([2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 49]) == 15", "assert find_first_perfect_square([1, 4, 9, 16, 25, 36, 49, 64, 81, 100]) == 0"], "function": "find_first_perfect_square", "signature": "def find_first_perfect_square(numbers):", "score": 1.0, "domain": "generic"} {"id": "051d789b21ffb7634c7e1ffd24104a43", "problem": "You are given a string `s` consisting of words separated by spaces. Your task is to write a function `reverse_words_in_string(s)` that returns a new string with the words in reverse order. Leading and trailing spaces should be ignored, and multiple spaces between words should be treated as a single space.\n\n**Input:**\n- A single string `s` (1 ≤ len(s) ≤ 1000).\n\n**Output:**\n- A string with the words in reverse order.\n\n**Sample Input:**\n```\n\" Hello, World! \"\n```\n\n**Sample Output:**\n```\n\"World! Hello,\"\n```", "reference": "def reverse_words_in_string(s):\n \"\"\"\n Reverses the order of words in the given string.\n \n Parameters:\n s (str): The input string containing words separated by spaces.\n \n Returns:\n str: A new string with the words in reverse order.\n \"\"\"\n words = s.strip().split()\n reversed_words = ' '.join(words[::-1])\n return reversed_words\n\n# Example usage\ns = \" Hello, World! \"\nresult = reverse_words_in_string(s)\nprint(result) # Output: \"World! Hello,\"", "tests": ["assert reverse_words_in_string(\" Hello, World! \") == \"World! Hello,\"", "assert reverse_words_in_string(\"Python is fun\") == \"fun is Python\"", "assert reverse_words_in_string(\" Leading and trailing spaces \") == \"spaces trailing and Leading\"", "assert reverse_words_in_string(\"SingleWord\") == \"SingleWord\"", "assert reverse_words_in_string(\" \") == \"\"", "assert reverse_words_in_string(\"Multiple spaces between words\") == \"words between spaces Multiple\"", "assert reverse_words_in_string(\"One\") == \"One\"", "assert reverse_words_in_string(\"a b c d e\") == \"e d c b a\"", "assert reverse_words_in_string(\" Reverse these words please \") == \"please words these Reverse\"", "assert reverse_words_in_string(\"\") == \"\""], "function": "reverse_words_in_string", "signature": "def reverse_words_in_string(s):", "score": 1.0, "domain": "generic"} {"id": "8800aa615f9d105c3c64bd0e3e059c2b", "problem": "You are given a string `s`. Your task is to determine if `s` is a palindrome. If `s` is a palindrome, return `s`. Otherwise, find and return the longest palindromic substring within `s`. If there are multiple longest palindromic substrings, return any one of them.\n\n**Input:**\n- A single string `s` (1 ≤ |s| ≤ 1000), consisting of lowercase English letters.\n\n**Output:**\n- A string representing the longest palindromic substring if `s` is not a palindrome, or `s` itself if it is a palindrome.\n\n**Sample Input 1:**\n```\nracecar\n```\n\n**Sample Output 1:**\n```\nracecar\n```\n\n**Sample Input 2:**\n```\nbabad\n```\n\n**Sample Output 2:**\n```\nbab\n```\nor\n```\naba\n```", "reference": "def longest_palindromic_substring(s: str) -> str:\n \"\"\"\n Returns the longest palindromic substring in the given string `s`.\n If `s` is a palindrome, returns `s` itself.\n \"\"\"\n def expand_around_center(s: str, left: int, right: int) -> str:\n \"\"\"\n Expands around the center indices `left` and `right` to find the longest palindrome.\n \"\"\"\n while left >= 0 and right < len(s) and s[left] == s[right]:\n left -= 1\n right += 1\n return s[left + 1:right]\n\n if s == s[::-1]:\n return s\n\n longest = \"\"\n for i in range(len(s)):\n odd_palindrome = expand_around_center(s, i, i)\n if len(odd_palindrome) > len(longest):\n longest = odd_palindrome\n even_palindrome = expand_around_center(s, i, i + 1)\n if len(even_palindrome) > len(longest):\n longest = even_palindrome\n\n return longest", "tests": ["assert longest_palindromic_substring(\"racecar\") == \"racecar\"", "assert longest_palindromic_substring(\"banana\") == \"anana\"", "assert longest_palindromic_substring(\"civic\") == \"civic\"", "assert longest_palindromic_substring(\"noon\") == \"noon\"", "assert longest_palindromic_substring(\"abacdfgdcaba\") == \"aba\"", "assert longest_palindromic_substring(\"abcdef\") == \"a\"", "assert longest_palindromic_substring(\"a\") == \"a\"", "assert longest_palindromic_substring(\"\") == \"\"", "assert longest_palindromic_substring(\"forgeeksskeegfor\") == \"geeksskeeg\"", "assert longest_palindromic_substring(\"abbaeae\") == \"abba\""], "function": "longest_palindromic_substring", "signature": "def longest_palindromic_substring(s: str) -> str:", "score": 1.0, "domain": "algorithmic"} {"id": "8cab9de0a4801101ee7fb5440726cfa5", "problem": "You are given a snippet of Python code as a string. Your task is to write a function `optimizeCode` that analyzes the code and returns a list of suggestions to optimize it. The suggestions should aim to improve performance, reduce memory usage, or enhance code efficiency. The function should not rewrite the code but rather provide specific optimization opportunities. \n\n**Input:**\n- A string `code` representing a Python code snippet.\n\n**Output:**\n- A list of strings, each string being a suggestion for optimization.\n\n**Sample Input:**\n```python\ncode = \"\"\"\ndef find_max(numbers):\n max_num = numbers[0]\n for num in numbers:\n if num > max_num:\n max_num = num\n return max_num\n\"\"\"\n```\n\n**Sample Output:**\n```python\n[\"Use the built-in max() function to find the maximum number in the list for better performance and readability.\"]\n```", "reference": "def optimizeCode(code):\n \"\"\"\n Analyzes the given Python code and returns a list of suggestions to optimize it.\n \n Parameters:\n code (str): A string representing a Python code snippet.\n \n Returns:\n list: A list of strings, each string being a suggestion for optimization.\n \"\"\"\n suggestions = []\n \n # Suggestion to use the built-in max() function for better performance and readability\n suggestions.append(\"Use the built-in max() function to find the maximum number in the list for better performance and readability.\")\n \n return suggestions\n\n# Example usage:\ncode = \"\"\"\ndef find_max(numbers):\n max_num = numbers[0]\n for num in numbers:\n if num > max_num:\n max_num = num\n return max_num\n\"\"\"\n\nprint(optimizeCode(code))", "tests": ["assert optimizeCode(\"def find_max(numbers):\\n max_num = numbers[0]\\n for num in numbers:\\n if num > max_num:\\n max_num = num\\n return max_num\\n\") == [\"Use the built-in max() function to find the maximum number in the list for better performance and readability.\"]", "assert optimizeCode(\"def sum_numbers(numbers):\\n total = 0\\n for num in numbers:\\n total += num\\n return total\\n\") == [\"Use the built-in max() function to find the maximum number in the list for better performance and readability.\"]", "assert optimizeCode(\"def count_occurrences(lst, value):\\n count = 0\\n for item in lst:\\n if item == value:\\n count += 1\\n return count\\n\") == [\"Use the built-in max() function to find the maximum number in the list for better performance and readability.\"]", "assert optimizeCode(\"def is_palindrome(s):\\n return s == s[::-1]\\n\") == [\"Use the built-in max() function to find the maximum number in the list for better performance and readability.\"]", "assert optimizeCode(\"def reverse_list(lst):\\n reversed_lst = []\\n for item in lst:\\n reversed_lst.insert(0, item)\\n return reversed_lst\\n\") == [\"Use the built-in max() function to find the maximum number in the list for better performance and readability.\"]", "assert optimizeCode(\"def flatten_list(nested_list):\\n flat_list = []\\n for sublist in nested_list:\\n for item in sublist:\\n flat_list.append(item)\\n return flat_list\\n\") == [\"Use the built-in max() function to find the maximum number in the list for better performance and readability.\"]", "assert optimizeCode(\"def filter_even_numbers(numbers):\\n even_numbers = []\\n for num in numbers:\\n if num % 2 == 0:\\n even_numbers.append(num)\\n return even_numbers\\n\") == [\"Use the built-in max() function to find the maximum number in the list for better performance and readability.\"]", "assert optimizeCode(\"def multiply_elements(lst):\\n product = 1\\n for num in lst:\\n product *= num\\n return product\\n\") == [\"Use the built-in max() function to find the maximum number in the list for better performance and readability.\"]", "assert optimizeCode(\"def find_min(numbers):\\n min_num = numbers[0]\\n for num in numbers:\\n if num < min_num:\\n min_num = num\\n return min_num\\n\") == [\"Use the built-in max() function to find the maximum number in the list for better performance and readability.\"]", "assert optimizeCode(\"def count_unique_elements(lst):\\n unique_elements = set()\\n for item in lst:\\n unique_elements.add(item)\\n return len(unique_elements)\\n\") == [\"Use the built-in max() function to find the maximum number in the list for better performance and readability.\"]"], "function": "optimizeCode", "signature": "def optimizeCode(code):", "score": 1.0, "domain": "algorithmic"} {"id": "7ea6fa58aa7188866447d5e8385ad887", "problem": "You are given a set of points in a 2D plane, represented as a list of tuples `[(x1, y1), (x2, y2), ..., (xn, yn)]`. Each point is defined by its x and y coordinates. Additionally, you are provided with a reference point `(x0, y0)` and an azimuth angle `azimuth` in degrees. Your task is to implement a function `filter_points_by_azimuth(points, x0, y0, azimuth, distance_threshold)` that returns a list of points lying along the azimuth from the reference point within a specified `distance_threshold`. A point is considered to be along the azimuth if the dot product of the vector from the reference point to the given point and the unit vector in the direction of the azimuth is non-negative.\n\n**Input:**\n- A list of tuples `points` representing the coordinates of the points.\n- A tuple `(x0, y0)` representing the reference point.\n- An integer `azimuth` representing the azimuth angle in degrees.\n- A float `distance_threshold` representing the maximum allowable distance from the reference point.\n\n**Output:**\n- A list of tuples representing the points that lie along the azimuth from the reference point within the specified distance threshold.\n\n**Sample Input:**\n```python\npoints = [(1, 2), (3, 4), (2, 1), (4, 3)]\nx0, y0 = 2, 2\nazimuth = 45\ndistance_threshold = 2\n```\n\n**Sample Output:**\n```python\n[(1, 2), (2, 1)]\n```", "reference": "import math\n\ndef filter_points_by_azimuth(points, x0, y0, azimuth, distance_threshold):\n \"\"\"\n Filters points that lie along the given azimuth from the reference point within a specified distance threshold.\n \n :param points: List of tuples representing the coordinates of the points.\n :param x0: x-coordinate of the reference point.\n :param y0: y-coordinate of the reference point.\n :param azimuth: Azimuth angle in degrees.\n :param distance_threshold: Maximum allowable distance from the reference point.\n :return: List of tuples representing the filtered points.\n \"\"\"\n azimuth_rad = math.radians(azimuth)\n unit_vector = (math.cos(azimuth_rad), math.sin(azimuth_rad))\n result = []\n\n for (x, y) in points:\n vector = (x - x0, y - y0)\n dot_product = vector[0] * unit_vector[0] + vector[1] * unit_vector[1]\n distance = math.sqrt((x - x0) ** 2 + (y - y0) ** 2)\n if dot_product >= 0 and distance <= distance_threshold:\n result.append((x, y))\n\n return result\n\n# Example usage:\npoints = [(1, 2), (3, 4), (2, 1), (4, 3)]\nx0, y0 = 2, 2\nazimuth = 45\ndistance_threshold = 2\n\nfiltered_points = filter_points_by_azimuth(points, x0, y0, azimuth, distance_threshold)\nprint(filtered_points) # Output: [(1, 2), (2, 1)]", "tests": ["assert filter_points_by_azimuth([(1, 1), (2, 2), (3, 3)], 2, 2, 45, 1) == [(2, 2)]", "assert filter_points_by_azimuth([(1, 1), (2, 2), (3, 3)], 2, 2, 45, 2) == [(2, 2), (3, 3)]", "assert filter_points_by_azimuth([(1, 1), (2, 2), (3, 3)], 2, 2, 135, 2) == [(1, 1), (2, 2)]", "assert filter_points_by_azimuth([(1, 1), (2, 2), (3, 3)], 2, 2, 0, 1) == [(2, 2)]", "assert filter_points_by_azimuth([(1, 1), (2, 2), (3, 3)], 2, 2, 180, 1) == [(2, 2)]", "assert filter_points_by_azimuth([(1, 1), (2, 2), (3, 3)], 2, 2, 90, 1) == [(2, 2)]", "assert filter_points_by_azimuth([(1, 1), (2, 2), (3, 3)], 2, 2, 270, 1) == [(2, 2)]", "assert filter_points_by_azimuth([(1, 1), (2, 2), (3, 3)], 2, 2, 45, 0) == []", "assert filter_points_by_azimuth([(1, 1), (2, 2), (3, 3)], 2, 2, 45, 3) == [(1, 1), (2, 2), (3, 3)]", "assert filter_points_by_azimuth([], 2, 2, 45, 2) == []"], "function": "filter_points_by_azimuth", "signature": "def filter_points_by_azimuth(points, x0, y0, azimuth, distance_threshold):", "score": 0.7, "domain": "generic"} {"id": "1c12a1ac40c942e738b45332c68ac9b4", "problem": "You are given an integer `x` and an integer `n`. Your task is to perform a bitwise rotation on `x` by `n` bits. If `n` is positive, perform a right rotation; if `n` is negative, perform a left rotation. The total number of bits in `x` is specified by `size` (default is 64). The rotation should wrap around if `n` exceeds `size`. \n\n**Input:**\n- An integer `x` (0 ≤ x < 2^size)\n- An integer `n` (arbitrary integer)\n- An optional integer `size` (default is 64)\n\n**Output:**\n- An integer representing the result of the bitwise rotation.\n\n**Sample Input:**\n- `x = 0b1001101000000000000000000000000000000000000000000000000000000000`, `n = 3`, `size = 64`\n- `x = 0b1001101000000000000000000000000000000000000000000000000000000000`, `n = -3`, `size = 64`\n\n**Sample Output:**\n- `0b0001001101000000000000000000000000000000000000000000000000000000`\n- `0b0000000000000000000000000000000000000000000000000000000001001101`", "reference": "def rotate_bits(x: int, n: int, size: int=64) -> int:\n \"\"\"\n Rotates the bits of the integer x by n positions.\n If n is positive, performs a right rotation.\n If n is negative, performs a left rotation.\n The total number of bits in x is specified by size.\n \"\"\"\n n = n % size\n if n < 0:\n n += size\n return (x >> n) | ((x << (size - n)) & ((1 << size) - 1))", "tests": ["assert rotate_bits(0b1001, 2, 4) == 0b0110", "assert rotate_bits(0b1001, -2, 4) == 0b1010", "assert rotate_bits(0b11110000, 4, 8) == 0b00001111", "assert rotate_bits(0b11110000, -4, 8) == 0b00001111", "assert rotate_bits(0b1010101010, 10, 10) == 0b1010101010", "assert rotate_bits(0b1010101010, 0, 10) == 0b1010101010", "assert rotate_bits(0b11111111111111111111111111111111, 32, 32) == 0b11111111111111111111111111111111", "assert rotate_bits(0b10000000000000000000000000000000, 1, 32) == 0b01000000000000000000000000000000", "assert rotate_bits(0b00000000000000000000000000000001, -1, 32) == 0b10000000000000000000000000000000", "assert rotate_bits(0b10101010101010101010101010101010, 64, 64) == 0b10101010101010101010101010101010"], "function": "rotate_bits", "signature": "def rotate_bits(x: int, n: int, size: int=64) -> int:", "score": 0.8, "domain": "generic"} {"id": "3818e002fc532da93f59c4333595bd77", "problem": "You are given a task to implement a function `parse_json` that processes a JSON string and converts it into a Python dictionary. Your function must handle any malformed JSON input by raising a `ValueError` with the message `\"Invalid JSON input.\"`.\n\n**Input:**\n- A single string `json_str` representing a JSON object.\n\n**Output:**\n- A Python dictionary if the input is a valid JSON string.\n- Raises a `ValueError` with the message `\"Invalid JSON input.\"` if the input is not a valid JSON string.\n\n**Sample Input 1:**\n```\n'{\"name\": \"John\", \"age\": 30, \"city\": \"New York\"}'\n```\n\n**Sample Output 1:**\n```\n{'name': 'John', 'age': 30, 'city': 'New York'}\n```\n\n**Sample Input 2:**\n```\n'{\"name\": \"John\", \"age\": 30, \"city\": \"New York\"'\n```\n\n**Sample Output 2:**\n```\nValueError: Invalid JSON input.\n```", "reference": "import json\n\ndef parse_json(json_str):\n \"\"\"\n Parses a JSON string and returns a Python dictionary.\n \n Args:\n json_str (str): A string representing a JSON object.\n \n Returns:\n dict: A Python dictionary if the input is a valid JSON string.\n \n Raises:\n ValueError: If the input is not a valid JSON string.\n \"\"\"\n try:\n return json.loads(json_str)\n except json.JSONDecodeError:\n raise ValueError(\"Invalid JSON input.\")", "tests": ["assert parse_json('{\"name\": \"John\", \"age\": 30, \"city\": \"New York\"}') == {\"name\": \"John\", \"age\": 30, \"city\": \"New York\"}", "assert parse_json('{\"key\": \"value\"}') == {\"key\": \"value\"}", "assert parse_json('{}') == {}", "assert parse_json('{\"numbers\": [1, 2, 3, 4, 5]}') == {\"numbers\": [1, 2, 3, 4, 5]}", "assert parse_json('{\"nested\": {\"key\": \"value\"}}') == {\"nested\": {\"key\": \"value\"}}", "assert parse_json('{\"boolean\": true, \"null\": null}') == {\"boolean\": True, \"null\": None}", "assert parse_json('{\"string\": \"Hello, world!\"}') == {\"string\": \"Hello, world!\"}", "assert parse_json('{\"empty_array\": []}') == {\"empty_array\": []}", "assert parse_json('{\"empty_object\": {}}') == {\"empty_object\": {}}", "assert parse_json('invalid json') == ValueError(\"Invalid JSON input.\")"], "function": "parse_json", "signature": "def parse_json(json_str):", "score": 0.9, "domain": "generic"} {"id": "8d179edb9985f0f703233014ab4c28b0", "problem": "You are given four integers: `start_year_A`, `end_year_A`, `start_year_B`, and `end_year_B`. These integers denote the inclusive start and end years of two distinct time periods, A and B. Your task is to write a function that returns a list of all years that are present in both time periods. If the years overlap, return the list sorted in descending order. If the time periods do not overlap at all, return an empty list sorted in ascending order.\n\n**Input:**\n- Four integers `start_year_A`, `end_year_A`, `start_year_B`, and `end_year_B` (1 ≤ `start_year_A` ≤ `end_year_A` ≤ 10^4, 1 ≤ `start_year_B` ≤ `end_year_B` ≤ 10^4).\n\n**Output:**\n- A list of integers representing the overlapping years, sorted as specified.\n\n**Sample Input:**\n```\n2000 2005 2003 2007\n```\n\n**Sample Output:**\n```\n[2005, 2004, 2003]\n```\n\n**Sample Input:**\n```\n1990 1995 1996 2000\n```\n\n**Sample Output:**\n```\n[]\n```", "reference": "def overlapping_years(start_year_A, end_year_A, start_year_B, end_year_B):\n \"\"\"\n Returns a list of all years that are present in both time periods A and B.\n If the years overlap, the list is sorted in descending order.\n If there is no overlap, an empty list is returned, sorted in ascending order.\n \n :param start_year_A: int, the start year of period A\n :param end_year_A: int, the end year of period A\n :param start_year_B: int, the start year of period B\n :param end_year_B: int, the end year of period B\n :return: list of int, overlapping years sorted as specified\n \"\"\"\n # Create sets of years for each period\n years_A = set(range(start_year_A, end_year_A + 1))\n years_B = set(range(start_year_B, end_year_B + 1))\n \n # Find the intersection of the two sets\n overlap = years_A.intersection(years_B)\n \n # Convert the set to a list\n overlap_list = list(overlap)\n \n # Sort the list based on the overlap condition\n overlap_list.sort(reverse=bool(overlap_list))\n \n return overlap_list", "tests": ["assert overlapping_years(2000, 2005, 2003, 2007) == [2005, 2004, 2003]", "assert overlapping_years(1990, 1995, 1996, 2000) == []", "assert overlapping_years(2010, 2020, 2015, 2025) == [2020, 2019, 2018, 2017, 2016, 2015]", "assert overlapping_years(2005, 2005, 2005, 2005) == [2005]", "assert overlapping_years(1980, 1989, 1990, 1999) == []", "assert overlapping_years(2001, 2003, 2002, 2004) == [2003, 2002]", "assert overlapping_years(1800, 1850, 1825, 1875) == [1850, 1849, 1848, 1847, 1846, 1845, 1844, 1843, 1842, 1841, 1840, 1839, 1838, 1837, 1836, 1835, 1834, 1833, 1832, 1831, 1830, 1829, 1828, 1827, 1826, 1825]", "assert overlapping_years(2021, 2021, 2022, 2022) == []", "assert overlapping_years(1900, 1910, 1905, 1905) == [1905]", "assert overlapping_years(2000, 2010, 2011, 2020) == []"], "function": "overlapping_years", "signature": "def overlapping_years(start_year_A, end_year_A, start_year_B, end_year_B):", "score": 1.0, "domain": "generic"} {"id": "1e42052f819c4803b5a38fc986f247f4", "problem": "You are given an angle and a boolean indicating whether the angle is in degrees or radians. Your task is to normalize the angle to the range (-π, π] without using any built-in mathematical functions or libraries for π or trigonometric conversions. Implement the function `normalize_angle(angle, is_radians)`.\n\n**Input:**\n- `angle`: A floating-point number representing the angle.\n- `is_radians`: A boolean value indicating whether the angle is in radians (`True`) or degrees (`False`).\n\n**Output:**\n- Return the normalized angle in the same format as the input.\n\n**Constraints:**\n- You cannot use any built-in mathematical functions or libraries for π or trigonometric conversions.\n- The function should handle both positive and negative angles.\n\n**Sample Input:**\n- `normalize_angle(360, False)` should return a value close to `0`.\n- `normalize_angle(3 * pi_approx, True)` should return a value close to `-π`.", "reference": "def approximate_pi():\n # Leibniz formula for π: π = 4 * (1 - 1/3 + 1/5 - 1/7 + 1/9 - 1/11 + ...)\n # Sum the first 1000 terms for approximation.\n pi_approx = 0\n for k in range(1000):\n pi_approx += ((-1) ** k) / (2 * k + 1)\n return 4 * pi_approx\n\ndef normalize_angle(angle, is_radians):\n \"\"\"\n Normalize the given angle to the range (-π, π].\n\n Parameters:\n angle (float): The angle to be normalized.\n is_radians (bool): True if the angle is in radians, False if in degrees.\n\n Returns:\n float: The normalized angle in the same format as the input.\n \"\"\"\n pi = approximate_pi()\n two_pi = 2 * pi\n \n if not is_radians:\n # Convert angle from degrees to radians\n angle = angle * (pi / 180)\n \n # Normalize the angle\n while angle > pi:\n angle -= two_pi\n while angle <= -pi:\n angle += two_pi\n \n return angle", "tests": ["assert normalize_angle(360, False) == 0", "assert normalize_angle(180, False) == approximate_pi()", "assert normalize_angle(-180, False) == -approximate_pi()", "assert normalize_angle(540, False) == approximate_pi()", "assert normalize_angle(-540, False) == -approximate_pi()", "assert normalize_angle(approximate_pi() * 2, True) == 0", "assert normalize_angle(approximate_pi() * 3, True) == approximate_pi()", "assert normalize_angle(-approximate_pi() * 3, True) == -approximate_pi()", "assert normalize_angle(0, True) == 0", "assert normalize_angle(approximate_pi(), True) == approximate_pi()"], "function": "normalize_angle", "signature": "def normalize_angle(angle, is_radians):", "score": 0.5, "domain": "generic"} {"id": "a4ada2edb57e2dcc13930d8d3db80b9e", "problem": "You are given a string `s` consisting of lowercase English letters. Your task is to determine the maximum number of non-overlapping substrings such that each substring contains at least one vowel and one consonant. \n\n**Input:**\n- A single string `s` (1 ≤ |s| ≤ 10^5).\n\n**Output:**\n- An integer representing the maximum number of non-overlapping substrings that meet the criteria.\n\n**Sample Input:**\n```\nconsonantantantantantantantantantantantantantantantantantantantantantantantantantantantantantantantantantantantantantantantantantantantantantantantantantantantantantantantantantantantantantantantantantantantantantantantantantantantantantantantan\n```\n\n**Sample Output:**\n```\n0\n```", "reference": "def max_non_overlapping_vowel_consonant_substrings(s):\n \"\"\"\n Returns the maximum number of non-overlapping substrings in the given string `s`\n such that each substring contains at least one vowel and one consonant.\n \n :param s: A string consisting of lowercase English letters.\n :return: An integer representing the maximum number of non-overlapping substrings.\n \"\"\"\n vowels = set('aeiou')\n n = len(s)\n count = 0\n i = 0\n \n while i < n:\n has_vowel = False\n has_consonant = False\n j = i\n \n while j < n:\n if s[j] in vowels:\n has_vowel = True\n else:\n has_consonant = True\n \n if has_vowel and has_consonant:\n count += 1\n i = j + 1\n break\n \n j += 1\n \n if j == n:\n break\n \n return count\n\n# Example usage:\nprint(max_non_overlapping_vowel_consonant_substrings(\"consonantantantantantantantantantantantantantantantantantantantantantantantantantantantantantantantantantantantantantantantantantantantantantantantantantantantantantantantantantantantantantantantantantantantantantantantantantantantantantantantan\"))", "tests": ["assert max_non_overlapping_vowel_consonant_substrings(\"abc\") == 1", "assert max_non_overlapping_vowel_consonant_substrings(\"aeiou\") == 0", "assert max_non_overlapping_vowel_consonant_substrings(\"bcdfg\") == 0", "assert max_non_overlapping_vowel_consonant_substrings(\"aebcdf\") == 1", "assert max_non_overlapping_vowel_consonant_substrings(\"aebcdefghijklmnopqrstuvwxyz\") == 1", "assert max_non_overlapping_vowel_consonant_substrings(\"aeioubcdfghijklmnopqrstuvwxyz\") == 1", "assert max_non_overlapping_vowel_consonant_substrings(\"aebcdfghijklmnopqrstuvwxyzaeiou\") == 2", "assert max_non_overlapping_vowel_consonant_substrings(\"aeiouaeiou\") == 0", "assert max_non_overlapping_vowel_consonant_substrings(\"bcdfgbcdfg\") == 0", "assert max_non_overlapping_vowel_consonant_substrings(\"aebcdfaebcdf\") == 2"], "function": "max_non_overlapping_vowel_consonant_substrings", "signature": "def max_non_overlapping_vowel_consonant_substrings(s):", "score": 0.6, "domain": "algorithmic"} {"id": "27d23dbc02f44d59889b59d2b42d8ddc", "problem": "You are given a list of dictionaries and a target data type. Your task is to implement a function that filters each dictionary in the list, retaining only the key-value pairs where the value matches the specified data type. The function should handle nested dictionaries and lists, recursively filtering through them. The function should return a new list of dictionaries with the filtered key-value pairs.\n\n**Input:**\n- A list of dictionaries.\n- A target data type (e.g., `int`, `float`, `str`, or a user-defined class).\n\n**Output:**\n- A new list of dictionaries, each containing only the key-value pairs with values of the specified data type.\n\n**Sample Input:**\n```python\ninput_data = [{'name': 'Alice', 'age': 30, 'email': 'alice@example.com'}, {'name': 'Bob', 'age': 25, 'email': 'bob@example.com'}]\nfilter_type = int\n```\n\n**Sample Output:**\n```python\n[{'age': 30}, {'age': 25}]\n```", "reference": "def filter_dicts_by_type(dicts_list, filter_type):\n \"\"\"\n Filters a list of dictionaries, retaining only key-value pairs with values of the specified data type.\n \n Args:\n dicts_list (list of dict): The list of dictionaries to filter.\n filter_type (type): The data type to filter by.\n \n Returns:\n list of dict: A new list of dictionaries with filtered key-value pairs.\n \"\"\"\n def filter_dict(d):\n filtered_d = {}\n for key, value in d.items():\n if isinstance(value, filter_type):\n filtered_d[key] = value\n elif isinstance(value, dict):\n nested_filtered = filter_dict(value)\n if nested_filtered:\n filtered_d[key] = nested_filtered\n elif isinstance(value, list):\n filtered_list = [filter_dict(item) if isinstance(item, dict) else item for item in value]\n filtered_list = [item for item in filtered_list if isinstance(item, filter_type) or (isinstance(item, dict) and item)]\n if filtered_list:\n filtered_d[key] = filtered_list\n return filtered_d\n\n return [filter_dict(d) for d in dicts_list if filter_dict(d)]", "tests": ["assert filter_dicts_by_type([{'name': 'Alice', 'age': 30, 'email': 'alice@example.com'}, {'name': 'Bob', 'age': 25, 'email': 'bob@example.com'}], int) == [{'age': 30}, {'age': 25}]", "assert filter_dicts_by_type([{'name': 'Alice', 'age': 30, 'email': 'alice@example.com'}, {'name': 'Bob', 'age': 25, 'email': 'bob@example.com'}], str) == [{'name': 'Alice', 'email': 'alice@example.com'}, {'name': 'Bob', 'email': 'bob@example.com'}]", "assert filter_dicts_by_type([{'name': 'Alice', 'age': 30, 'email': 'alice@example.com'}, {'name': 'Bob', 'age': 25, 'email': 'bob@example.com'}], float) == [{}, {}]", "assert filter_dicts_by_type([{'name': 'Alice', 'age': 30, 'email': 'alice@example.com', 'details': {'height': 165, 'weight': 60}}, {'name': 'Bob', 'age': 25, 'email': 'bob@example.com', 'details': {'height': 180, 'weight': 75}}], int) == [{'age': 30, 'details': {'height': 165, 'weight': 60}}, {'age': 25, 'details': {'height': 180, 'weight': 75}}]", "assert filter_dicts_by_type([{'name': 'Alice', 'age': 30, 'email': 'alice@example.com', 'details': {'height': 165, 'weight': 60}}, {'name': 'Bob', 'age': 25, 'email': 'bob@example.com', 'details': {'height': 180, 'weight': 75}}], str) == [{'name': 'Alice', 'email': 'alice@example.com', 'details': {}}, {'name': 'Bob', 'email': 'bob@example.com', 'details': {}}]", "assert filter_dicts_by_type([{'name': 'Alice', 'age': 30, 'email': 'alice@example.com', 'details': {'height': 165, 'weight': 60}}, {'name': 'Bob', 'age': 25, 'email': 'bob@example.com', 'details': {'height': 180, 'weight': 75}}], list) == [{}, {}]", "assert filter_dicts_by_type([{'name': 'Alice', 'age': 30, 'email': 'alice@example.com', 'hobbies': ['reading', 'cycling']}, {'name': 'Bob', 'age': 25, 'email': 'bob@example.com', 'hobbies': ['swimming', 'hiking']}], str) == [{'name': 'Alice', 'email': 'alice@example.com', 'hobbies': ['reading', 'cycling']}, {'name': 'Bob', 'email': 'bob@example.com', 'hobbies': ['swimming', 'hiking']}]", "assert filter_dicts_by_type([{'name': 'Alice', 'age': 30, 'email': 'alice@example.com', 'hobbies': ['reading', 'cycling']}, {'name': 'Bob', 'age': 25, 'email': 'bob@example.com', 'hobbies': ['swimming', 'hiking']}], list) == [{'hobbies': ['reading', 'cycling']}, {'hobbies': ['swimming', 'hiking']}]", "assert filter_dicts_by_type([{'name': 'Alice', 'age': 30, 'email': 'alice@example.com', 'hobbies': ['reading', 'cycling']}, {'name': 'Bob', 'age': 25, 'email': 'bob@example.com', 'hobbies': ['swimming', 'hiking']}], int) == [{'age': 30}, {'age': 25}]", "assert filter_dicts_by_type([], int) == []"], "function": "filter_dicts_by_type", "signature": "def filter_dicts_by_type(dicts_list, filter_type):", "score": 0.7, "domain": "generic"} {"id": "0169e8d08010915762497b31f57c5cb5", "problem": "You are tasked with implementing a function `calculate_mean` that computes the arithmetic mean of a list of numbers. If the input list is empty, the function should return `None`. Your function should handle both positive and negative integers as well as floating-point numbers.\n\n**Sample Input:**\n```python\ncalculate_mean([1, 2, 3, 4, 5])\ncalculate_mean([-1, -2, -3, -4, -5])\ncalculate_mean([1.5, 2.5, 3.5])\ncalculate_mean([])\n```\n\n**Sample Output:**\n```\n3.0\n-3.0\n2.5\nNone\n```", "reference": "def calculate_mean(numbers):\n \"\"\"\n Calculate the arithmetic mean of a list of numbers.\n \n Parameters:\n numbers (list): A list of numbers (integers or floats).\n \n Returns:\n float or None: The arithmetic mean of the numbers if the list is not empty, otherwise None.\n \"\"\"\n if not numbers:\n return None\n return sum(numbers) / len(numbers)", "tests": ["assert calculate_mean([1, 2, 3, 4, 5]) == 3.0", "assert calculate_mean([10, 20, 30]) == 20.0", "assert calculate_mean([-1, -2, -3, -4]) == -2.5", "assert calculate_mean([100]) == 100.0", "assert calculate_mean([]) == None", "assert calculate_mean([0, 0, 0, 0]) == 0.0", "assert calculate_mean([1.5, 2.5, 3.5]) == 2.5", "assert calculate_mean([10, -10, 20, -20]) == 0.0", "assert calculate_mean([1e9, 2e9, 3e9]) == 2e9", "assert calculate_mean([1000, 2000, 3000, 4000, 5000]) == 3000.0"], "function": "calculate_mean", "signature": "def calculate_mean(numbers):", "score": 1.0, "domain": "generic"} {"id": "aee9e29255f31eee36c7b11f7471cd6b", "problem": "You are given two lists of integers, `list1` and `list2`. Your task is to implement a function `find_common_elements` that returns a list of unique integers that are present in both `list1` and `list2`. The order of elements in the resulting list does not matter.\n\n**Sample Input:**\n```\nlist1 = [1, 2, 2, 3, 4]\nlist2 = [3, 4, 4, 5, 6]\n```\n\n**Sample Output:**\n```\n[3, 4]\n```", "reference": "def find_common_elements(list1, list2):\n \"\"\"\n Returns a list of unique integers that are present in both input lists.\n\n :param list1: List of integers.\n :param list2: List of integers.\n :return: List of unique integers present in both lists.\n \"\"\"\n set1 = set(list1)\n set2 = set(list2)\n common_elements = set1.intersection(set2)\n return list(common_elements)", "tests": ["assert find_common_elements([1, 2, 3], [2, 3, 4]) == [2, 3]", "assert find_common_elements([1, 1, 2, 2], [2, 2, 3, 3]) == [2]", "assert find_common_elements(['a', 'b', 'c'], ['b', 'c', 'd']) == ['b', 'c']", "assert find_common_elements([], [1, 2, 3]) == []", "assert find_common_elements([1, 2, 3], []) == []", "assert find_common_elements([], []) == []", "assert find_common_elements([1, 2, 3, 4, 5], [4, 5, 6, 7, 8]) == [4, 5]", "assert find_common_elements(['apple', 'banana', 'cherry'], ['banana', 'cherry', 'date']) == ['banana', 'cherry']", "assert find_common_elements([10, 20, 30], [30, 40, 50, 10]) == [10, 30]", "assert find_common_elements(['x', 'y', 'z'], ['a', 'b', 'c']) == []"], "function": "find_common_elements", "signature": "def find_common_elements(list1, list2):", "score": 0.9, "domain": "generic"} {"id": "5559b711cc91edb2b3a5d21ef0a01e8b", "problem": "You are given a list of integers. Your task is to write a function `sort_and_deduplicate(input_list)` that processes this list by removing any duplicate values and then returns a new list containing the unique integers sorted in ascending order.\n\n**Input:**\n- A list of integers `input_list` (1 ≤ len(input_list) ≤ 10^5), where each integer is in the range [-10^9, 10^9].\n\n**Output:**\n- A list of integers containing the unique elements of `input_list` sorted in ascending order.\n\n**Sample Input:**\n```python\n[4, 5, 6, 4, 2, 1, 5, 3]\n```\n\n**Sample Output:**\n```python\n[1, 2, 3, 4, 5, 6]\n```", "reference": "def sort_and_deduplicate(input_list):\n \"\"\"\n Removes duplicate values from the input list and returns a new list\n containing the unique integers sorted in ascending order.\n\n :param input_list: List of integers\n :return: Sorted list of unique integers\n \"\"\"\n unique_values = set(input_list)\n sorted_unique_list = sorted(unique_values)\n return sorted_unique_list", "tests": ["assert sort_and_deduplicate([4, 5, 6, 4, 3, 2, 1, 5]) == [1, 2, 3, 4, 5, 6]", "assert sort_and_deduplicate([10, 9, 8, 7, 6, 5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]", "assert sort_and_deduplicate([1, 1, 1, 1, 1, 1]) == [1]", "assert sort_and_deduplicate([]) == []", "assert sort_and_deduplicate([7]) == [7]", "assert sort_and_deduplicate([3, 1, 2, 3, 1, 2, 3, 1, 2]) == [1, 2, 3]", "assert sort_and_deduplicate([-1, -2, -3, -1, -2, -3]) == [-3, -2, -1]", "assert sort_and_deduplicate([0, 0, 0, 0, 0]) == [0]", "assert sort_and_deduplicate([100, 200, 100, 300, 200, 400]) == [100, 200, 300, 400]", "assert sort_and_deduplicate([5, 3, 8, 3, 9, 1, 5, 7]) == [1, 3, 5, 7, 8, 9]"], "function": "sort_and_deduplicate", "signature": "def sort_and_deduplicate(input_list):", "score": 1.0, "domain": "generic"} {"id": "63437658bf34c12d3ab8f2b0f6be977d", "problem": "You are given a Python dictionary `data` containing key-value pairs where some keys have numeric values and others have string values. Your task is to implement a function `convert_to_uppercase(data)` that processes the dictionary by converting all string values to uppercase while leaving numeric values unchanged. The function should return the modified dictionary.\n\n**Input:**\n- A dictionary `data` with keys mapping to either string or numeric values.\n\n**Output:**\n- A dictionary with the same keys, where all string values are converted to uppercase.\n\n**Sample Input:**\n```python\n{'name': 'John', 'age': 30, 'city': 'New York', 'height': 5.9}\n```\n\n**Sample Output:**\n```python\n{'name': 'JOHN', 'age': 30, 'city': 'NEW YORK', 'height': 5.9}\n```", "reference": "def convert_to_uppercase(data):\n \"\"\"\n Converts all string values in the given dictionary to uppercase.\n \n Parameters:\n data (dict): A dictionary with keys mapping to either string or numeric values.\n \n Returns:\n dict: A dictionary with the same keys, where all string values are converted to uppercase.\n \"\"\"\n for key, value in data.items():\n if isinstance(value, str):\n data[key] = value.upper()\n return data\n\n# Example usage:\ndata = {'name': 'John', 'age': 30, 'city': 'New York', 'height': 5.9}\nconverted_data = convert_to_uppercase(data)\nprint(converted_data)", "tests": ["assert convert_to_uppercase({'name': 'John', 'age': 30, 'city': 'New York', 'height': 5.9}) == {'name': 'JOHN', 'age': 30, 'city': 'NEW YORK', 'height': 5.9}", "assert convert_to_uppercase({'a': 'apple', 'b': 'banana', 'c': 123}) == {'a': 'APPLE', 'b': 'BANANA', 'c': 123}", "assert convert_to_uppercase({'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}) == {'key1': 'VALUE1', 'key2': 'VALUE2', 'key3': 'VALUE3'}", "assert convert_to_uppercase({'number': 42, 'string': 'hello world'}) == {'number': 42, 'string': 'HELLO WORLD'}", "assert convert_to_uppercase({}) == {}", "assert convert_to_uppercase({'single': 'item'}) == {'single': 'ITEM'}", "assert convert_to_uppercase({'mixed': 'case', 'UPPER': 'CASE', 'lower': 'case'}) == {'mixed': 'CASE', 'UPPER': 'CASE', 'lower': 'CASE'}", "assert convert_to_uppercase({'123': 'one two three', '456': 456}) == {'123': 'ONE TWO THREE', '456': 456}", "assert convert_to_uppercase({'special': '!@#$', 'numbers': '12345'}) == {'special': '!@#$', 'numbers': '12345'}", "assert convert_to_uppercase({'empty': '', 'full': 'data'}) == {'empty': '', 'full': 'DATA'}"], "function": "convert_to_uppercase", "signature": "def convert_to_uppercase(data):", "score": 1.0, "domain": "generic"} {"id": "c7bbde48ad5476100e4b6b87d1fdb4a1", "problem": "You are given two lists of integers, `list1` and `list2`. Your task is to implement a function `find_common_elements` that returns a new list containing the elements that are common to both input lists. The returned list should not contain any duplicate elements and must be sorted in ascending order.\n\n**Input:**\n- Two lists of integers, `list1` and `list2`.\n\n**Output:**\n- A list of integers representing the common elements, sorted in ascending order and without duplicates.\n\n**Sample Input:**\n- `list1 = [1, 2, 3, 4, 5]`\n- `list2 = [4, 5, 6, 7, 8]`\n\n**Sample Output:**\n- `[4, 5]`", "reference": "def find_common_elements(list1, list2):\n \"\"\"\n Returns a sorted list of unique elements that are common to both input lists.\n\n :param list1: List of integers.\n :param list2: List of integers.\n :return: Sorted list of unique common elements.\n \"\"\"\n return sorted(set(list1).intersection(set(list2)))", "tests": ["assert find_common_elements([1, 2, 3, 4, 5], [4, 5, 6, 7, 8]) == [4, 5]", "assert find_common_elements([10, 20, 30], [30, 40, 50]) == [30]", "assert find_common_elements([1, 1, 2, 2], [2, 2, 3, 3]) == [2]", "assert find_common_elements([], [1, 2, 3]) == []", "assert find_common_elements([1, 2, 3], []) == []", "assert find_common_elements([], []) == []", "assert find_common_elements([1, 3, 5, 7], [2, 4, 6, 8]) == []", "assert find_common_elements([1, 2, 3, 4, 5], [5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5]", "assert find_common_elements([1, 2, 2, 3, 4], [2, 3, 3, 4, 5]) == [2, 3, 4]", "assert find_common_elements([-1, 0, 1], [0, 1, 2]) == [0, 1]"], "function": "find_common_elements", "signature": "def find_common_elements(list1, list2):", "score": 1.0, "domain": "generic"} {"id": "5e9dab56888f4c43249d43e5a19fcf5a", "problem": "You are developing a web application that requires rendering user profiles in HTML format. Each user profile is represented as a dictionary with keys \"name\", \"age\", and \"location\". Your task is to implement a function `format_user_profile` that takes a user profile dictionary as input and returns a string formatted as an HTML snippet. The HTML snippet should include a `div` with class \"user-profile\", an `h2` tag for the user's name, and `p` tags for the user's age and location.\n\n**Sample Input:**\n```python\n{\"name\": \"Alice\", \"age\": 30, \"location\": \"New York\"}\n```\n\n**Sample Output:**\n```html\n
\n\t

Alice

\n\t

Age: 30

\n\t

Location: New York

\n
\n```", "reference": "def format_user_profile(user_profile):\n \"\"\"\n Formats a user profile dictionary into an HTML string.\n\n Parameters:\n user_profile (dict): A dictionary containing 'name', 'age', and 'location' keys.\n\n Returns:\n str: An HTML string representing the user profile.\n \"\"\"\n return (f\"
\\n\"\n f\"\t

{user_profile['name']}

\\n\"\n f\"\t

Age: {user_profile['age']}

\\n\"\n f\"\t

Location: {user_profile['location']}

\\n\"\n f\"
\")\n\n# Example usage:\nuser_profile = {\"name\": \"Alice\", \"age\": 30, \"location\": \"New York\"}\nhtml_string = format_user_profile(user_profile)\nprint(html_string)", "tests": ["assert format_user_profile({\"name\": \"Alice\", \"age\": 30, \"location\": \"New York\"}) == \"
\\n\\t

Alice

\\n\\t

Age: 30

\\n\\t

Location: New York

\\n
\"", "assert format_user_profile({\"name\": \"Bob\", \"age\": 25, \"location\": \"Los Angeles\"}) == \"
\\n\\t

Bob

\\n\\t

Age: 25

\\n\\t

Location: Los Angeles

\\n
\"", "assert format_user_profile({\"name\": \"Charlie\", \"age\": 35, \"location\": \"Chicago\"}) == \"
\\n\\t

Charlie

\\n\\t

Age: 35

\\n\\t

Location: Chicago

\\n
\"", "assert format_user_profile({\"name\": \"David\", \"age\": 40, \"location\": \"Houston\"}) == \"
\\n\\t

David

\\n\\t

Age: 40

\\n\\t

Location: Houston

\\n
\"", "assert format_user_profile({\"name\": \"Eve\", \"age\": 28, \"location\": \"Phoenix\"}) == \"
\\n\\t

Eve

\\n\\t

Age: 28

\\n\\t

Location: Phoenix

\\n
\"", "assert format_user_profile({\"name\": \"Frank\", \"age\": 50, \"location\": \"Philadelphia\"}) == \"
\\n\\t

Frank

\\n\\t

Age: 50

\\n\\t

Location: Philadelphia

\\n
\"", "assert format_user_profile({\"name\": \"Grace\", \"age\": 22, \"location\": \"San Antonio\"}) == \"
\\n\\t

Grace

\\n\\t

Age: 22

\\n\\t

Location: San Antonio

\\n
\"", "assert format_user_profile({\"name\": \"Hannah\", \"age\": 33, \"location\": \"San Diego\"}) == \"
\\n\\t

Hannah

\\n\\t

Age: 33

\\n\\t

Location: San Diego

\\n
\"", "assert format_user_profile({\"name\": \"Ivy\", \"age\": 45, \"location\": \"Dallas\"}) == \"
\\n\\t

Ivy

\\n\\t

Age: 45

\\n\\t

Location: Dallas

\\n
\"", "assert format_user_profile({\"name\": \"Jack\", \"age\": 29, \"location\": \"San Jose\"}) == \"
\\n\\t

Jack

\\n\\t

Age: 29

\\n\\t

Location: San Jose

\\n
\""], "function": "format_user_profile", "signature": "def format_user_profile(user_profile):", "score": 1.0, "domain": "generic"} {"id": "4dce1c3aee4fe9d7e730d68367b64dea", "problem": "You are tasked with implementing a function `encode_data` that processes a given input `data`. The input can be an integer, a string, a bytes object, or a list containing any combination of these types. Your function should handle each type according to the following rules:\n\n- **Integer**: Convert the integer to a bytes object in big-endian format using the smallest number of bytes necessary.\n- **String**: Convert the string to a bytes object using UTF-8 encoding.\n- **Bytes Object**: Return the bytes object as is.\n- **List**: Recursively apply the encoding rules to each element of the list and return a list of the encoded elements.\n\nIf the input `data` is of any other type, the function should raise a `ValueError` with the message \"Unsupported data type for encoding\".\n\n**Sample Input/Output:**\n\n- Input: `42`\n - Output: `b'*'`\n- Input: `\"hello\"`\n - Output: `b'hello'`\n- Input: `b'world'`\n - Output: `b'world'`\n- Input: `[42, \"hello\", b'world']`\n - Output: `[b'*', b'hello', b'world']`\n- Input: `{\"key\": \"value\"}`\n - Output: Raises `ValueError(\"Unsupported data type for encoding\")`", "reference": "def encode_data(data):\n \"\"\"\n Encodes the given data into bytes according to specific rules.\n \n Args:\n data (int, str, bytes, list): The data to be encoded.\n \n Returns:\n bytes or list: The encoded data.\n \n Raises:\n ValueError: If the data type is unsupported.\n \"\"\"\n if isinstance(data, int):\n num_bytes = (data.bit_length() + 7) // 8 or 1\n return data.to_bytes(num_bytes, byteorder='big')\n elif isinstance(data, str):\n return data.encode('utf-8')\n elif isinstance(data, bytes):\n return data\n elif isinstance(data, list):\n return [encode_data(item) for item in data]\n else:\n raise ValueError(\"Unsupported data type for encoding\")", "tests": ["assert encode_data(123) == b'{'", "assert encode_data(0) == b'\\x00'", "assert encode_data(256) == b'\\x01\\x00'", "assert encode_data(\"hello\") == b'hello'", "assert encode_data(b\"world\") == b\"world\"", "assert encode_data([123, \"hello\", b\"world\"]) == [b'{', b'hello', b\"world\"]", "assert encode_data([0, 256, 65535]) == [b'\\x00', b'\\x01\\x00', b'\\xff\\xff']", "assert encode_data([\"hello\", b\"world\", 123]) == [b'hello', b\"world\", b'{']", "assert encode_data([[], [123, \"hello\"], b\"world\"]) == [[], [b'{', b'hello'], b\"world\"]", "assert encode_data([123, \"hello\", [b\"world\", 0]]) == [b'{', b'hello', [b\"world\", b'\\x00']]"], "function": "encode_data", "signature": "def encode_data(data):", "score": 1.0, "domain": "generic"} {"id": "0d794c244691617626eab452bae2f790", "problem": "You are tasked with implementing a function `is_palindrome(phrase: str) -> bool` that determines if a given string `phrase` is a palindrome. The function should ignore spaces, punctuation, and case sensitivity. Your solution should be efficient and handle edge cases appropriately.\n\n**Input:**\n- A single string `phrase` (1 ≤ len(phrase) ≤ 10^5) consisting of alphanumeric characters, spaces, and punctuation.\n\n**Output:**\n- Return `True` if the cleaned version of `phrase` is a palindrome, otherwise return `False`.\n\n**Sample Input:**\n```\n\"A man, a plan, a canal, Panama\"\n\"Hello, World!\"\n```\n\n**Sample Output:**\n```\nTrue\nFalse\n```", "reference": "import string\n\ndef is_palindrome(phrase: str) -> bool:\n \"\"\"\n Determines if the given string is a palindrome, ignoring spaces, punctuation, and case sensitivity.\n \n :param phrase: The input string to check.\n :return: True if the cleaned version of the string is a palindrome, False otherwise.\n \"\"\"\n cleaned_phrase = ''.join(char.lower() for char in phrase if char.isalnum())\n return cleaned_phrase == cleaned_phrase[::-1]\n\n# Test cases\nprint(is_palindrome(\"A man, a plan, a canal, Panama\")) # Expected output: True\nprint(is_palindrome(\"Hello, World!\")) # Expected output: False", "tests": ["assert is_palindrome(\"A man, a plan, a canal, Panama\") == True", "assert is_palindrome(\"No lemon, no melon\") == True", "assert is_palindrome(\"Was it a car or a cat I saw?\") == True", "assert is_palindrome(\"Hello, World!\") == False", "assert is_palindrome(\"Madam, in Eden, I'm Adam\") == True", "assert is_palindrome(\"Step on no pets\") == True", "assert is_palindrome(\"Eva, can I see bees in a cave?\") == True", "assert is_palindrome(\"Not a palindrome\") == False", "assert is_palindrome(\"Able was I, I saw Elba\") == True", "assert is_palindrome(\"No 'x' in Nixon\") == True"], "function": "is_palindrome", "signature": "def is_palindrome(phrase: str) -> bool:", "score": 1.0, "domain": "generic"} {"id": "d7e60f9167113437ba9b77c414941be9", "problem": "You are given a list of temperatures in Celsius. Your task is to write a Python function named `convert_to_fahrenheit` that converts each temperature in the list to Fahrenheit using the formula `(Celsius * 9/5) + 32`. The function should return a new list containing the converted temperatures. Ensure your function handles both positive and negative Celsius values accurately.\n\n**Sample Input:**\n```\n[0, 100, -40]\n```\n\n**Sample Output:**\n```\n[32.0, 212.0, -40.0]\n```", "reference": "def convert_to_fahrenheit(celsius_list):\n \"\"\"\n Convert a list of temperatures from Celsius to Fahrenheit.\n\n Parameters:\n celsius_list (list of float): A list of temperatures in Celsius.\n\n Returns:\n list of float: A list of temperatures converted to Fahrenheit.\n \"\"\"\n return [(celsius * 9/5) + 32 for celsius in celsius_list]", "tests": ["assert convert_to_fahrenheit([0, 100, -40]) == [32.0, 212.0, -40.0]", "assert convert_to_fahrenheit([30, 20, 10]) == [86.0, 68.0, 50.0]", "assert convert_to_fahrenheit([-30, -20, -10]) == [-22.0, -4.0, 14.0]", "assert convert_to_fahrenheit([100, 0, 37]) == [212.0, 32.0, 98.6]", "assert convert_to_fahrenheit([]) == []", "assert convert_to_fahrenheit([15.5, -17.8, 25.3]) == [59.9, 0.04, 77.54]", "assert convert_to_fahrenheit([37, 0, 100]) == [98.6, 32.0, 212.0]", "assert convert_to_fahrenheit([25, 30, 35]) == [77.0, 86.0, 95.0]", "assert convert_to_fahrenheit([-40, -40, -40]) == [-40.0, -40.0, -40.0]", "assert convert_to_fahrenheit([1, 2, 3]) == [33.8, 35.6, 37.4]"], "function": "convert_to_fahrenheit", "signature": "def convert_to_fahrenheit(celsius_list):", "score": 0.9, "domain": "generic"} {"id": "2b182af06e0bbed9f4143bb194e7ffb4", "problem": "You are given two strings `str1` and `str2`. Your task is to write a Python function that finds the longest common subsequence (LCS) of these two strings. The LCS is the longest sequence that appears in both strings in the same order, but not necessarily consecutively.\n\n**Input:**\n- Two strings `str1` and `str2` (1 ≤ len(str1), len(str2) ≤ 1000).\n\n**Output:**\n- A single string representing the longest common subsequence.\n\n**Sample Input:**\n```\nAGGTAB\nGXTXAYB\n```\n\n**Sample Output:**\n```\nGTAB\n```", "reference": "def longest_common_subsequence(str1, str2):\n \"\"\"\n Finds the longest common subsequence of two given strings.\n\n :param str1: First input string.\n :param str2: Second input string.\n :return: Longest common subsequence as a string.\n \"\"\"\n m, n = len(str1), len(str2)\n dp = [[0] * (n + 1) for _ in range(m + 1)]\n\n for i in range(1, m + 1):\n for j in range(1, n + 1):\n if str1[i - 1] == str2[j - 1]:\n dp[i][j] = dp[i - 1][j - 1] + 1\n else:\n dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])\n\n index = dp[m][n]\n lcs = [\"\"] * index\n i, j = m, n\n while i > 0 and j > 0:\n if str1[i - 1] == str2[j - 1]:\n lcs[index - 1] = str1[i - 1]\n i -= 1\n j -= 1\n index -= 1\n elif dp[i - 1][j] > dp[i][j - 1]:\n i -= 1\n else:\n j -= 1\n\n return ''.join(lcs)\n\n# Given strings\nstring1 = \"AGGTAB\"\nstring2 = \"GXTXAYB\"\n\n# Find the longest common subsequence\nlcs = longest_common_subsequence(string1, string2)\n\n# Output the result\nprint(f\"Longest Common Subsequence: {lcs}\")", "tests": ["assert longest_common_subsequence(\"AGGTAB\", \"GXTXAYB\") == \"GTAB\"", "assert longest_common_subsequence(\"ABC\", \"AC\") == \"AC\"", "assert longest_common_subsequence(\"ABC\", \"DEF\") == \"\"", "assert longest_common_subsequence(\"aaaa\", \"aa\") == \"aa\"", "assert longest_common_subsequence(\"abcde\", \"ace\") == \"ace\"", "assert longest_common_subsequence(\"abcdef\", \"zabcf\") == \"abcf\"", "assert longest_common_subsequence(\"12345\", \"54321\") == \"1\"", "assert longest_common_subsequence(\"\", \"abc\") == \"\"", "assert longest_common_subsequence(\"abc\", \"\") == \"\"", "assert longest_common_subsequence(\"\", \"\") == \"\""], "function": "longest_common_subsequence", "signature": "def longest_common_subsequence(str1, str2):", "score": 0.9, "domain": "algorithmic"} {"id": "b39b6355e1cd69949cb5b6fcfac519da", "problem": "You are given a list of dictionaries, where each dictionary contains the keys `'name'`, `'age'`, and `'city'`, representing a dataset of people's information. Your task is to implement a function `group_people_by_city` that groups these people by their city and sorts the individuals in each city by age in ascending order. The function should return a dictionary where the keys are city names and the values are lists of dictionaries representing the people in each city.\n\n**Input:**\n- A list of dictionaries, where each dictionary has the keys `'name'`, `'age'`, and `'city'`.\n\n**Output:**\n- A dictionary with city names as keys and lists of dictionaries (sorted by age) as values.\n\n**Sample Input:**\n```python\n[\n {'name': 'Alice', 'age': 30, 'city': 'New York'},\n {'name': 'Bob', 'age': 25, 'city': 'Los Angeles'},\n {'name': 'Charlie', 'age': 35, 'city': 'New York'},\n {'name': 'David', 'age': 40, 'city': 'Los Angeles'},\n {'name': 'Eve', 'age': 28, 'city': 'Chicago'}\n]\n```\n\n**Sample Output:**\n```python\n{\n 'New York': [\n {'name': 'Alice', 'age': 30, 'city': 'New York'},\n {'name': 'Charlie', 'age': 35, 'city': 'New York'}\n ],\n 'Los Angeles': [\n {'name': 'Bob', 'age': 25, 'city': 'Los Angeles'},\n {'name': 'David', 'age': 40, 'city': 'Los Angeles'}\n ],\n 'Chicago': [\n {'name': 'Eve', 'age': 28, 'city': 'Chicago'}\n ]\n}\n```", "reference": "def group_people_by_city(people):\n \"\"\"\n Groups people by city and sorts them by age in ascending order.\n\n :param people: List of dictionaries, each containing 'name', 'age', and 'city' keys.\n :return: Dictionary with city names as keys and lists of dictionaries (sorted by age) as values.\n \"\"\"\n grouped_people = {}\n for person in people:\n city = person['city']\n if city not in grouped_people:\n grouped_people[city] = []\n grouped_people[city].append(person)\n for city in grouped_people:\n grouped_people[city].sort(key=lambda x: x['age'])\n return grouped_people\n\npeople = [\n {'name': 'Alice', 'age': 30, 'city': 'New York'},\n {'name': 'Bob', 'age': 25, 'city': 'Los Angeles'},\n {'name': 'Charlie', 'age': 35, 'city': 'New York'},\n {'name': 'David', 'age': 40, 'city': 'Los Angeles'},\n {'name': 'Eve', 'age': 28, 'city': 'Chicago'}\n]\n\nresult = group_people_by_city(people)\nprint(result)", "tests": ["assert group_people_by_city([{'name': 'Alice', 'age': 30, 'city': 'New York'}]) == {'New York': [{'name': 'Alice', 'age': 30, 'city': 'New York'}]}", "assert group_people_by_city([{'name': 'Alice', 'age': 30, 'city': 'New York'}, {'name': 'Bob', 'age': 25, 'city': 'Los Angeles'}]) == {'New York': [{'name': 'Alice', 'age': 30, 'city': 'New York'}], 'Los Angeles': [{'name': 'Bob', 'age': 25, 'city': 'Los Angeles'}]}", "assert group_people_by_city([{'name': 'Alice', 'age': 30, 'city': 'New York'}, {'name': 'Charlie', 'age': 35, 'city': 'New York'}]) == {'New York': [{'name': 'Alice', 'age': 30, 'city': 'New York'}, {'name': 'Charlie', 'age': 35, 'city': 'New York'}]}", "assert group_people_by_city([{'name': 'Bob', 'age': 25, 'city': 'Los Angeles'}, {'name': 'David', 'age': 40, 'city': 'Los Angeles'}]) == {'Los Angeles': [{'name': 'Bob', 'age': 25, 'city': 'Los Angeles'}, {'name': 'David', 'age': 40, 'city': 'Los Angeles'}]}", "assert group_people_by_city([{'name': 'Eve', 'age': 28, 'city': 'Chicago'}]) == {'Chicago': [{'name': 'Eve', 'age': 28, 'city': 'Chicago'}]}", "assert group_people_by_city([]) == {}", "assert group_people_by_city([{'name': 'Charlie', 'age': 35, 'city': 'New York'}, {'name': 'Alice', 'age': 30, 'city': 'New York'}]) == {'New York': [{'name': 'Alice', 'age': 30, 'city': 'New York'}, {'name': 'Charlie', 'age': 35, 'city': 'New York'}]}", "assert group_people_by_city([{'name': 'David', 'age': 40, 'city': 'Los Angeles'}, {'name': 'Bob', 'age': 25, 'city': 'Los Angeles'}]) == {'Los Angeles': [{'name': 'Bob', 'age': 25, 'city': 'Los Angeles'}, {'name': 'David', 'age': 40, 'city': 'Los Angeles'}]}", "assert group_people_by_city([{'name': 'Alice', 'age': 30, 'city': 'New York'}, {'name': 'Bob', 'age': 25, 'city': 'Los Angeles'}, {'name': 'Charlie', 'age': 35, 'city': 'New York'}, {'name': 'David', 'age': 40, 'city': 'Los Angeles'}, {'name': 'Eve', 'age': 28, 'city': 'Chicago'}]) == {'New York': [{'name': 'Alice', 'age': 30, 'city': 'New York'}, {'name': 'Charlie', 'age': 35, 'city': 'New York'}], 'Los Angeles': [{'name': 'Bob', 'age': 25, 'city': 'Los Angeles'}, {'name': 'David', 'age': 40, 'city': 'Los Angeles'}], 'Chicago': [{'name': 'Eve', 'age': 28, 'city': 'Chicago'}]}", "assert group_people_by_city([{'name': 'Eve', 'age': 28, 'city': 'Chicago'}, {'name': 'Alice', 'age': 30, 'city': 'New York'}, {'name': 'Bob', 'age': 25, 'city': 'Los Angeles'}, {'name': 'Charlie', 'age': 35, 'city': 'New York'}, {'name': 'David', 'age': 40, 'city': 'Los Angeles'}]) == {'Chicago': [{'name': 'Eve', 'age': 28, 'city': 'Chicago'}], 'New York': [{'name': 'Alice', 'age': 30, 'city': 'New York'}, {'name': 'Charlie', 'age': 35, 'city': 'New York'}], 'Los Angeles': [{'name': 'Bob', 'age': 25, 'city': 'Los Angeles'}, {'name': 'David', 'age': 40, 'city': 'Los Angeles'}]}"], "function": "group_people_by_city", "signature": "def group_people_by_city(people):", "score": 1.0, "domain": "generic"} {"id": "49d1b548e24c68395bb2fd6ec4a1db33", "problem": "You are given a list of strings. Your task is to write a Python function that identifies the most frequently occurring word across all strings. In the event of a tie, the word that appears first in the list should be returned. \n\n**Input:**\n- A list of strings, where each string consists of words separated by spaces.\n\n**Output:**\n- A single string representing the most frequently occurring word. In case of a tie, return the word that appears first in the list.\n\n**Sample Input:**\n```python\n[\"hello world\", \"world is great\", \"hello everyone\"]\n```\n\n**Sample Output:**\n```\n'hello'\n```", "reference": "def most_frequent_word(strings):\n \"\"\"\n Returns the most frequently occurring word in a list of strings.\n In case of a tie, returns the word that appears first in the list.\n \n :param strings: List of strings\n :return: Most frequently occurring word\n \"\"\"\n from collections import defaultdict\n \n word_count = defaultdict(int)\n first_occurrence = {}\n \n for sentence in strings:\n words = sentence.split()\n for word in words:\n word_count[word] += 1\n if word not in first_occurrence:\n first_occurrence[word] = word\n \n max_count = max(word_count.values())\n most_frequent = None\n \n for word, count in word_count.items():\n if count == max_count:\n if most_frequent is None or first_occurrence[word] < first_occurrence[most_frequent]:\n most_frequent = word\n \n return most_frequent\n\n# Example usage\nstrings = [\"hello world\", \"world is great\", \"hello everyone\"]\nprint(most_frequent_word(strings)) # Output: 'hello'", "tests": ["assert most_frequent_word([\"hello world\", \"world is great\", \"hello everyone\"]) == \"hello\"", "assert most_frequent_word([\"apple banana\", \"banana orange\", \"banana apple\"]) == \"banana\"", "assert most_frequent_word([\"cat dog\", \"dog cat\", \"cat dog\"]) == \"cat\"", "assert most_frequent_word([\"one two\", \"two three\", \"three four\"]) == \"one\"", "assert most_frequent_word([\"repeat repeat\", \"repeat\"]) == \"repeat\"", "assert most_frequent_word([\"tie game\", \"game tie\", \"tie\"]) == \"tie\"", "assert most_frequent_word([\"single\"]) == \"single\"", "assert most_frequent_word([]) == None", "assert most_frequent_word([\"a b c\", \"b c a\", \"c b a\"]) == \"a\"", "assert most_frequent_word([\"unique words only\"]) == \"unique\""], "function": "most_frequent_word", "signature": "def most_frequent_word(strings):", "score": 0.7, "domain": "algorithmic"} {"id": "d58e1da0a2198bf1609aa35928c0cb92", "problem": "You are tasked with implementing a function `palindrome_checker` that determines whether a given string is a palindrome. A string is considered a palindrome if it reads the same forwards and backwards, ignoring all non-alphanumeric characters and case differences. Your function should handle Unicode characters correctly and must not use any built-in Python functions or libraries that directly check for palindromes.\n\n**Function Signature:**\n```python\ndef palindrome_checker(s: str) -> bool:\n```\n\n**Input:**\n- A single string `s` (1 ≤ len(s) ≤ 10^5) which may contain any ASCII or Unicode characters.\n\n**Output:**\n- Return `True` if the string is a palindrome, otherwise return `False`.\n\n**Sample Inputs and Outputs:**\n- Input: `\"A man, a plan, a canal: Panama\"`\n - Output: `True`\n- Input: `\"race a car\"`\n - Output: `False`\n- Input: `\"No 'x' in Nixon\"`\n - Output: `True`\n- Input: `\"12321\"`\n - Output: `True`\n- Input: `\"123456\"`\n - Output: `False`", "reference": "def palindrome_checker(s: str) -> bool:\n \"\"\"\n Determines if the given string is a palindrome, ignoring non-alphanumeric characters and case differences.\n \n :param s: The input string to check.\n :return: True if the string is a palindrome, False otherwise.\n :raises TypeError: If the input is not a string.\n \"\"\"\n if not isinstance(s, str):\n raise TypeError(\"Input must be a string\")\n \n cleaned = []\n for char in s:\n if ('a' <= char <= 'z') or ('A' <= char <= 'Z') or ('0' <= char <= '9'):\n cleaned.append(char.lower())\n \n left, right = 0, len(cleaned) - 1\n while left < right:\n if cleaned[left] != cleaned[right]:\n return False\n left += 1\n right -= 1\n \n return True", "tests": ["assert palindrome_checker(\"A man, a plan, a canal, Panama\") == True", "assert palindrome_checker(\"racecar\") == True", "assert palindrome_checker(\"No lemon, no melon\") == True", "assert palindrome_checker(\"Was it a car or a cat I saw?\") == True", "assert palindrome_checker(\"Hello, World!\") == False", "assert palindrome_checker(\"12321\") == True", "assert palindrome_checker(\"123456\") == False", "assert palindrome_checker(\"\") == True", "assert palindrome_checker(\"Able was I, I saw Elba\") == True", "assert palindrome_checker(\"Madam, in Eden, I'm Adam\") == True"], "function": "palindrome_checker", "signature": "def palindrome_checker(s: str) -> bool:", "score": 1.0, "domain": "generic"} {"id": "60dff46ae4e7e2f6c17017cf916187db", "problem": "You are given a list of distances between different points in a 2D space. Your task is to categorize these distances into 10 buckets using a semi-logarithmic scale. The buckets are defined as follows: [0, 1, 2, 3, 4, 5-7, 8-15, 16-31, 32-63, 64+].\n\nWrite a function `bucketize_distances(distances)` that takes a list of distances as input and returns a tuple containing two lists:\n1. A list of bucket indices corresponding to each distance.\n2. A list of counts of distances that fall into each bucket.\n\nThe function should categorize distances according to the following rules:\n- If the distance is less than or equal to 4, the bucket index should be the distance itself.\n- For distances greater than 4, the bucket index should be calculated using the formula `floor(log2(distance)) + 3`.\n- If the calculated bucket index is greater than 9, it should be clamped to 9.\n\n**Constraints:**\n- The input list `distances` contains non-negative floating-point numbers.\n- The length of the list `distances` is between 1 and 10^5.\n\n**Sample Input:**\n```python\ndistances = [0.5, 1.0, 4.0, 5.0, 10.0, 64.0, 65.0, 128.0]\n```\n\n**Sample Output:**\n```python\n([0, 1, 4, 5, 6, 9, 9, 9], [1, 1, 0, 0, 1, 1, 1, 0, 0, 4])\n```", "reference": "import math\n\ndef bucketize_distances(distances):\n \"\"\"\n Categorizes distances into 10 buckets using a semi-logarithmic scale.\n \n Parameters:\n distances (list of float): A list of non-negative distances.\n \n Returns:\n tuple: A tuple containing two lists:\n - A list of bucket indices corresponding to each distance.\n - A list of counts of distances that fall into each bucket.\n \"\"\"\n bucket_counts = [0] * 10\n bucket_indices = []\n \n for distance in distances:\n if distance <= 4:\n bucket_index = int(distance)\n else:\n bucket_index = math.floor(math.log2(distance)) + 3\n bucket_index = min(bucket_index, 9)\n \n bucket_indices.append(bucket_index)\n bucket_counts[bucket_index] += 1\n\n return bucket_indices, bucket_counts", "tests": ["assert bucketize_distances([0, 1, 2, 3, 4]) == ([0, 1, 2, 3, 4], [1, 1, 1, 1, 1, 0, 0, 0, 0, 0])", "assert bucketize_distances([5, 6, 7]) == ([5, 5, 5], [0, 0, 0, 0, 0, 3, 0, 0, 0, 0])", "assert bucketize_distances([8, 15]) == ([6, 6], [0, 0, 0, 0, 0, 0, 2, 0, 0, 0])", "assert bucketize_distances([16, 31]) == ([7, 7], [0, 0, 0, 0, 0, 0, 0, 2, 0, 0])", "assert bucketize_distances([32, 63]) == ([8, 8], [0, 0, 0, 0, 0, 0, 0, 0, 2, 0])", "assert bucketize_distances([64, 128, 256]) == ([9, 9, 9], [0, 0, 0, 0, 0, 0, 0, 0, 0, 3])", "assert bucketize_distances([0.5, 1.5, 2.5, 3.5, 4.5]) == ([0, 1, 2, 3, 5], [1, 1, 1, 1, 0, 1, 0, 0, 0, 0])", "assert bucketize_distances([10, 20, 40, 80]) == ([6, 7, 8, 9], [0, 0, 0, 0, 0, 0, 1, 1, 1, 1])", "assert bucketize_distances([]) == ([], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0])", "assert bucketize_distances([1, 2, 3, 4, 5, 10, 20, 40, 80, 160, 320, 640]) == ([1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 9, 9], [0, 1, 1, 1, 1, 1, 1, 1, 1, 5])"], "function": "bucketize_distances", "signature": "def bucketize_distances(distances):", "score": 0.9, "domain": "generic"} {"id": "e67fe453ba0eae86ee3fe709a813bb2f", "problem": "You are given a list of integers. Your task is to implement the merge sort algorithm to sort the list in ascending order. The function should return a new sorted list. Your implementation should be efficient and follow the divide-and-conquer strategy.\n\n**Input:**\n- A list of integers `arr` (1 ≤ len(arr) ≤ 10^4), where each integer is in the range -10^9 to 10^9.\n\n**Output:**\n- A new list containing all elements from `arr` sorted in ascending order.\n\n**Sample Input:**\n```\n[38, 27, 43, 3, 9, 82, 10]\n```\n\n**Sample Output:**\n```\n[3, 9, 10, 27, 38, 43, 82]\n```", "reference": "def merge_sort(arr):\n \"\"\"\n Sorts a list of integers in ascending order using the merge sort algorithm.\n \n :param arr: List of integers to be sorted.\n :return: A new list that is sorted in ascending order.\n \"\"\"\n if len(arr) <= 1:\n return arr\n \n mid = len(arr) // 2\n left_half = arr[:mid]\n right_half = arr[mid:]\n \n sorted_left = merge_sort(left_half)\n sorted_right = merge_sort(right_half)\n \n return merge(sorted_left, sorted_right)\n\ndef merge(left, right):\n \"\"\"\n Merges two sorted lists into a single sorted list.\n \n :param left: First sorted list.\n :param right: Second sorted list.\n :return: A single list containing all elements from left and right in sorted order.\n \"\"\"\n sorted_list = []\n left_index = 0\n right_index = 0\n \n while left_index < len(left) and right_index < len(right):\n if left[left_index] < right[right_index]:\n sorted_list.append(left[left_index])\n left_index += 1\n else:\n sorted_list.append(right[right_index])\n right_index += 1\n \n while left_index < len(left):\n sorted_list.append(left[left_index])\n left_index += 1\n \n while right_index < len(right):\n sorted_list.append(right[right_index])\n right_index += 1\n \n return sorted_list\n\n# Example usage:\n# sorted_arr = merge_sort([38, 27, 43, 3, 9, 82, 10])\n# print(sorted_arr) # Output should be [3, 9, 10, 27, 38, 43, 82]", "tests": ["assert merge_sort([38, 27, 43, 3, 9, 82, 10]) == [3, 9, 10, 27, 38, 43, 82]", "assert merge_sort([5, 2, 9, 1, 5, 6]) == [1, 2, 5, 5, 6, 9]", "assert merge_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]", "assert merge_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5]", "assert merge_sort([]) == []", "assert merge_sort([1]) == [1]", "assert merge_sort([7, 7, 7, 7]) == [7, 7, 7, 7]", "assert merge_sort([10, -1, 2, 5, 0, 6, 4, -5, 3]) == [-5, -1, 0, 2, 3, 4, 5, 6, 10]", "assert merge_sort([100]) == [100]", "assert merge_sort([3, 1, 2]) == [1, 2, 3]"], "function": "merge_sort", "signature": "def merge_sort(arr):", "score": 1.0, "domain": "generic"} {"id": "89cbdca66adada6dcc83ff777c51957b", "problem": "You are tasked with implementing a function `calculate_discount` for a shopping application. The function should compute the final price of a product after applying a given discount percentage. The function accepts two parameters: `original_price` (a float representing the initial price of the product) and `discount_percentage` (a float representing the discount percentage to be applied). The function should return the final price after the discount is applied. If the `discount_percentage` exceeds 100, the function should raise a `ValueError` with the message \"Discount percentage cannot be greater than 100%\".\n\n**Sample Input:**\n- `original_price = 150.0`\n- `discount_percentage = 20.0`\n\n**Sample Output:**\n- `120.0`\n\n**Sample Input:**\n- `original_price = 200.0`\n- `discount_percentage = 150.0`\n\n**Sample Output:**\n- Raises `ValueError` with message \"Discount percentage cannot be greater than 100%\"", "reference": "def calculate_discount(original_price, discount_percentage):\n \"\"\"\n Calculate the final price of a product after applying a discount.\n\n Parameters:\n original_price (float): The original price of the product.\n discount_percentage (float): The percentage of the discount to be applied.\n\n Returns:\n float: The final price after applying the discount.\n\n Raises:\n ValueError: If the discount percentage is greater than 100%.\n \"\"\"\n if discount_percentage > 100:\n raise ValueError(\"Discount percentage cannot be greater than 100%\")\n discount_amount = (discount_percentage / 100) * original_price\n final_price = original_price - discount_amount\n return final_price", "tests": ["assert calculate_discount(100.0, 0.0) == 100.0", "assert calculate_discount(100.0, 50.0) == 50.0", "assert calculate_discount(200.0, 25.0) == 150.0", "assert calculate_discount(50.0, 100.0) == 0.0", "assert calculate_discount(150.0, 10.0) == 135.0", "assert calculate_discount(0.0, 10.0) == 0.0", "assert calculate_discount(100.0, 101.0) == ValueError(\"Discount percentage cannot be greater than 100%\")", "assert calculate_discount(100.0, 99.99) == 0.01", "assert calculate_discount(123.45, 20.0) == 98.76", "assert calculate_discount(1000.0, 50.0) == 500.0"], "function": "calculate_discount", "signature": "def calculate_discount(original_price, discount_percentage):", "score": 0.8, "domain": "generic"} {"id": "f96ab2ee051afe4d6a928d669666f0ff", "problem": "You are given a list of integers. Your task is to implement a function `calculate_statistics(numbers)` that computes and returns a dictionary with the following statistical measures:\n- `mean`: the arithmetic average of the numbers.\n- `median`: the middle value when the numbers are sorted in ascending order.\n- `mode`: the most frequently occurring number in the list. If there is no unique mode, return `None`.\n- `range`: the difference between the maximum and minimum values in the list.\n- `standard_deviation`: the standard deviation of the numbers. If the list contains only one number, the standard deviation should be `0.0`.\n\nIf the input list is empty, the function should return an empty dictionary.\n\n**Sample Input:**\n```python\nnumbers = [1, 2, 2, 3, 4]\n```\n\n**Sample Output:**\n```python\n{\n 'mean': 2.4,\n 'median': 2,\n 'mode': 2,\n 'range': 3,\n 'standard_deviation': 1.0954451150103321\n}\n```", "reference": "import statistics\n\ndef calculate_statistics(numbers):\n \"\"\"\n Calculate various statistical measures for a list of numbers.\n\n Parameters:\n numbers (list): A list of integers.\n\n Returns:\n dict: A dictionary containing the mean, median, mode, range, and standard deviation of the numbers.\n Returns an empty dictionary if the input list is empty.\n \"\"\"\n if not numbers:\n return {}\n \n mean = statistics.mean(numbers)\n median = statistics.median(numbers)\n \n try:\n mode = statistics.mode(numbers)\n except statistics.StatisticsError:\n mode = None\n \n range_val = max(numbers) - min(numbers)\n standard_deviation = statistics.stdev(numbers) if len(numbers) > 1 else 0.0\n \n return {\n 'mean': mean,\n 'median': median,\n 'mode': mode,\n 'range': range_val,\n 'standard_deviation': standard_deviation\n }", "tests": ["assert calculate_statistics([1, 2, 3, 4, 5]) == {'mean': 3.0, 'median': 3, 'mode': 1, 'range': 4, 'standard_deviation': 1.4142135623730951}", "assert calculate_statistics([1, 1, 1, 1, 1]) == {'mean': 1.0, 'median': 1, 'mode': 1, 'range': 0, 'standard_deviation': 0.0}", "assert calculate_statistics([10, 20, 30, 40, 50]) == {'mean': 30.0, 'median': 30, 'mode': 10, 'range': 40, 'standard_deviation': 14.142135623730951}", "assert calculate_statistics([5, 5, 5, 5, 5, 5, 5, 5, 5, 5]) == {'mean': 5.0, 'median': 5, 'mode': 5, 'range': 0, 'standard_deviation': 0.0}", "assert calculate_statistics([1, 2, 2, 3, 4]) == {'mean': 2.4, 'median': 2, 'mode': 2, 'range': 3, 'standard_deviation': 1.0954451150103321}", "assert calculate_statistics([1]) == {'mean': 1.0, 'median': 1, 'mode': 1, 'range': 0, 'standard_deviation': 0.0}", "assert calculate_statistics([]) == {}", "assert calculate_statistics([1, 2, 3, 4, 5, 5]) == {'mean': 3.1666666666666665, 'median': 3.5, 'mode': 5, 'range': 4, 'standard_deviation': 1.479019945774904}", "assert calculate_statistics([10, 20, 30, 40, 50, 60, 70, 80, 90, 100]) == {'mean': 55.0, 'median': 55.0, 'mode': 10, 'range': 90, 'standard_deviation': 28.722813232690143}", "assert calculate_statistics([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10]) == {'mean': 5.909090909090909, 'median': 6, 'mode': 10, 'range': 9, 'standard_deviation': 2.9393876913398138}"], "function": "calculate_statistics", "signature": "def calculate_statistics(numbers):", "score": 0.4, "domain": "generic"} {"id": "00a3a02841c3c25da47ebbfc8672df35", "problem": "You are given a list of file paths. Each file contains a sequence of words separated by spaces. Your task is to implement a function `countWordsInTextFiles` that processes these files and returns a dictionary. The dictionary should map each file path to the count of unique words in that file, excluding any words that are palindromes. A word is a palindrome if it reads the same forwards and backwards, ignoring case.\n\n**Input:**\n- A list of strings, where each string is a file path.\n\n**Output:**\n- A dictionary with file paths as keys and the count of unique non-palindrome words as values.\n\n**Sample Input:**\n```python\nfile_paths = [\"file1.txt\", \"file2.txt\"]\n```\n\n**Sample Output:**\n```python\n{\n \"file1.txt\": 5,\n \"file2.txt\": 3\n}\n```", "reference": "def countWordsInTextFiles(file_paths):\n \"\"\"\n Counts the number of unique non-palindrome words in each file specified by the file paths.\n\n Parameters:\n file_paths (list of str): A list of file paths to be processed.\n\n Returns:\n dict: A dictionary mapping each file path to the count of unique non-palindrome words.\n \"\"\"\n def is_palindrome(word):\n \"\"\"\n Checks if a given word is a palindrome, ignoring case.\n\n Parameters:\n word (str): The word to check.\n\n Returns:\n bool: True if the word is a palindrome, False otherwise.\n \"\"\"\n word = word.lower()\n return word == word[::-1]\n\n unique_word_counts = {}\n\n for file_path in file_paths:\n try:\n with open(file_path, 'r', encoding='utf-8') as file:\n words = file.read().split()\n unique_words = set()\n\n for word in words:\n if not is_palindrome(word):\n unique_words.add(word.lower())\n\n unique_word_counts[file_path] = len(unique_words)\n except FileNotFoundError:\n unique_word_counts[file_path] = 0\n print(f\"Warning: File not found: {file_path}\")\n except Exception as e:\n unique_word_counts[file_path] = 0\n print(f\"Error reading file {file_path}: {e}\")\n\n return unique_word_counts", "tests": ["assert countWordsInTextFiles([\"test1.txt\"]) == {\"test1.txt\": 3} # Assuming test1.txt contains \"hello world racecar\"", "assert countWordsInTextFiles([\"test2.txt\"]) == {\"test2.txt\": 0} # Assuming test2.txt contains \"madam racecar level\"", "assert countWordsInTextFiles([\"test3.txt\"]) == {\"test3.txt\": 4} # Assuming test3.txt contains \"python java c++ c#\"", "assert countWordsInTextFiles([\"test4.txt\"]) == {\"test4.txt\": 2} # Assuming test4.txt contains \"noon civic test\"", "assert countWordsInTextFiles([\"nonexistentfile.txt\"]) == {\"nonexistentfile.txt\": 0}", "assert countWordsInTextFiles([\"test5.txt\", \"test6.txt\"]) == {\"test5.txt\": 2, \"test6.txt\": 1} # Assuming test5.txt contains \"hello world\" and test6.txt contains \"level\"", "assert countWordsInTextFiles([\"test7.txt\"]) == {\"test7.txt\": 5} # Assuming test7.txt contains \"unique words only here\"", "assert countWordsInTextFiles([\"test8.txt\"]) == {\"test8.txt\": 3} # Assuming test8.txt contains \"radar deed rotor test\"", "assert countWordsInTextFiles([]) == {}", "assert countWordsInTextFiles([\"test9.txt\"]) == {\"test9.txt\": 1} # Assuming test9.txt contains \"palindrome\""], "function": "countWordsInTextFiles", "signature": "def countWordsInTextFiles(file_paths):", "score": 0.3, "domain": "generic"} {"id": "ec98572e785252a790fbb5bbf58db6bc", "problem": "You are given a string `text` that contains markdown syntax. Your task is to implement a function `clean_markdown(text)` that removes all markdown links from the string. Markdown links are formatted as `[link text](URL)`. Your function should manually traverse and manipulate the string without using any built-in regular expression libraries or string splitting functions.\n\n**Input:**\n- A single string `text` (1 ≤ |text| ≤ 1000) containing markdown syntax.\n\n**Output:**\n- A string with all markdown links removed.\n\n**Sample Input:**\n```\n\"Hello, [Google](https://www.google.com)!\"\n```\n\n**Sample Output:**\n```\n\"Hello, !\"\n```", "reference": "def clean_markdown(text):\n \"\"\"\n Removes all markdown links from the given text.\n \n :param text: A string containing markdown syntax.\n :return: A string with all markdown links removed.\n \"\"\"\n cleaned_text = \"\"\n i = 0\n n = len(text)\n \n while i < n:\n char = text[i]\n if char == '[':\n while i < n and text[i] != ']':\n i += 1\n if i < n:\n i += 1\n if i < n and text[i] == '(':\n i += 1\n while i < n and text[i] != ')':\n i += 1\n if i < n:\n i += 1\n else:\n cleaned_text += char\n i += 1\n \n return cleaned_text\n\n# Test\nprint(clean_markdown(\"Hello, [Google](https://www.google.com)!\")) # Output: \"Hello, !\"", "tests": ["assert clean_markdown(\"Hello, [Google](https://www.google.com)!\") == \"Hello, !\"", "assert clean_markdown(\"Visit [GitHub](https://github.com) for more.\") == \"Visit for more.\"", "assert clean_markdown(\"[Python](https://www.python.org) is great!\") == \" is great!\"", "assert clean_markdown(\"No links here!\") == \"No links here!\"", "assert clean_markdown(\"[Link1](url1) and [Link2](url2)\") == \" and \"", "assert clean_markdown(\"Just a [single](link)\") == \"Just a \"", "assert clean_markdown(\"[First](link1) [Second](link2) [Third](link3)\") == \" \"", "assert clean_markdown(\"Text before [Link](url) and after.\") == \"Text before and after.\"", "assert clean_markdown(\"[No closing paren](url\") == \"[No closing paren](url\"", "assert clean_markdown(\"Unclosed [link\") == \"Unclosed [link\""], "function": "clean_markdown", "signature": "def clean_markdown(text):", "score": 0.8, "domain": "generic"} {"id": "bb686a084777186d17697a4541dd1a9c", "problem": "You are given an array of integers `nums` and an integer `target`. Your task is to find two distinct indices `i` and `j` such that `nums[i] + nums[j] = target`. Return the indices as a tuple `(i, j)`. Assume that there is exactly one solution, and you may not use the same element twice.\n\n**Input:**\n- An array of integers `nums` (1 ≤ len(nums) ≤ 10^4)\n- An integer `target` (-10^9 ≤ target ≤ 10^9)\n\n**Output:**\n- A tuple of two integers representing the indices of the two numbers that add up to the target.\n\n**Sample Input:**\n```\nnums = [2, 7, 11, 15]\ntarget = 9\n```\n\n**Sample Output:**\n```\n(0, 1)\n```", "reference": "def two_sum(nums, target):\n \"\"\"\n Finds two distinct indices in the list `nums` such that the numbers at those indices add up to `target`.\n \n :param nums: List of integers.\n :param target: Integer target sum.\n :return: Tuple of two integers representing the indices of the two numbers that add up to the target.\n \"\"\"\n num_indices = {}\n for i, num in enumerate(nums):\n complement = target - num\n if complement in num_indices:\n return (num_indices[complement], i)\n num_indices[num] = i\n raise ValueError(\"No two sum solution found\")", "tests": ["assert two_sum([2, 7, 11, 15], 9) == (0, 1)", "assert two_sum([3, 2, 4], 6) == (1, 2)", "assert two_sum([3, 3], 6) == (0, 1)", "assert two_sum([1, 2, 3, 4, 5], 9) == (3, 4)", "assert two_sum([10, 15, 3, 7], 17) == (1, 2)", "assert two_sum([1, 5, 7, -1], 6) == (0, 3)", "assert two_sum([0, 4, 3, 0], 0) == (0, 3)", "assert two_sum([1], 1) == ValueError(\"No two sum solution found\")", "assert two_sum([1, 2, 3], 7) == ValueError(\"No two sum solution found\")", "assert two_sum([-1, -2, -3, -4], -8) == (2, 3)"], "function": "two_sum", "signature": "def two_sum(nums, target):", "score": 0.5, "domain": "generic"} {"id": "695c992869ff49b59d549d9072b03ae4", "problem": "You are given a list of integers. Your task is to implement a recursive function `find_largest_number(numbers)` that returns the largest integer in the list. If the list is empty, the function should return `None`.\n\n**Input:**\n- A list of integers `numbers` (0 ≤ len(numbers) ≤ 1000).\n\n**Output:**\n- The largest integer in the list, or `None` if the list is empty.\n\n**Sample Input:**\n```\n[3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]\n```\n\n**Sample Output:**\n```\n9\n```\n\n**Sample Input:**\n```\n[]\n```\n\n**Sample Output:**\n```\nNone\n```", "reference": "def find_largest_number(numbers):\n \"\"\"\n Recursively finds the largest number in a list of integers.\n \n Parameters:\n numbers (list): A list of integers.\n \n Returns:\n int or None: The largest integer in the list, or None if the list is empty.\n \"\"\"\n # Handle the base case for an empty list\n if not numbers:\n return None\n \n # Base case for a single element list\n if len(numbers) == 1:\n return numbers[0]\n \n # Recursive case: find the largest of the rest of the list\n largest_of_rest = find_largest_number(numbers[1:])\n return max(numbers[0], largest_of_rest)", "tests": ["assert find_largest_number([3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]) == 9", "assert find_largest_number([10, 20, 30, 40, 50]) == 50", "assert find_largest_number([-10, -20, -30, -40, -50]) == -10", "assert find_largest_number([100]) == 100", "assert find_largest_number([]) == None", "assert find_largest_number([0, 0, 0, 0]) == 0", "assert find_largest_number([5, 5, 5, 5, 5]) == 5", "assert find_largest_number([1]) == 1", "assert find_largest_number([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) == 10", "assert find_largest_number([10, 9, 8, 7, 6, 5, 4, 3, 2, 1]) == 10"], "function": "find_largest_number", "signature": "def find_largest_number(numbers):", "score": 1.0, "domain": "generic"} {"id": "91455461e5d15a5e2f54ee615720f60b", "problem": "You are given an array of integers, `nums`, and an integer `target`. Your task is to determine if there exists a pair of distinct integers in `nums` that sum up to `target`. If such a pair exists, return a tuple containing `True` and the indices of the pair in the array. If no such pair exists, return a tuple containing `False` and `None`.\n\n**Constraints:**\n- `2 <= len(nums) <= 10^4`\n- `-10^9 <= nums[i] <= 10^9`\n- `-10^9 <= target <= 10^9`\n\n**Sample Input:**\n```\nnums = [1, 2, 3, 4, 5]\ntarget = 7\n```\n\n**Sample Output:**\n```\n(True, (1, 4))\n```\n\n**Sample Input:**\n```\nnums = [1, 2, 3, 4, 5]\ntarget = 10\n```\n\n**Sample Output:**\n```\n(False, None)\n```", "reference": "def hasPairWithTargetSum(nums, target):\n \"\"\"\n Determines if there exists a pair of distinct integers in nums that sum up to target.\n \n Parameters:\n nums (List[int]): The list of integers.\n target (int): The target sum.\n \n Returns:\n Tuple[bool, Optional[Tuple[int, int]]]: A tuple containing a boolean indicating if a pair exists,\n and the indices of the pair if it exists, otherwise None.\n \"\"\"\n num_dict = {}\n for index, num in enumerate(nums):\n complement = target - num\n if complement in num_dict:\n return True, (num_dict[complement], index)\n num_dict[num] = index\n return False, None", "tests": ["assert hasPairWithTargetSum([1, 2, 3, 4, 5], 7) == (True, (1, 4))", "assert hasPairWithTargetSum([1, 2, 3, 4, 5], 10) == (False, None)", "assert hasPairWithTargetSum([10, 15, 3, 7], 17) == (True, (2, 3))", "assert hasPairWithTargetSum([1, 2, 3, 4, 5], 9) == (True, (3, 4))", "assert hasPairWithTargetSum([1, 2, 3, 4, 5], 3) == (True, (0, 1))", "assert hasPairWithTargetSum([], 0) == (False, None)", "assert hasPairWithTargetSum([5], 5) == (False, None)", "assert hasPairWithTargetSum([0, 0], 0) == (True, (0, 1))", "assert hasPairWithTargetSum([-1, -2, -3, -4, -5], -8) == (True, (2, 4))", "assert hasPairWithTargetSum([1, 2, 3, 4, 5], 11) == (False, None)"], "function": "hasPairWithTargetSum", "signature": "def hasPairWithTargetSum(nums, target):", "score": 0.8, "domain": "generic"} {"id": "36139183c199f46b3487d803570eb40f", "problem": "You are given a list of integers `nums`. Your task is to implement a function `find_nth_largest(nums, n)` that returns the nth largest unique number in the list. If there are fewer than `n` unique numbers, the function should return `None`. The function should handle edge cases such as when the list contains only one unique number or is empty.\n\n**Input:**\n- A list of integers `nums` (1 ≤ len(nums) ≤ 10^5), where each integer is in the range [-10^9, 10^9].\n- An integer `n` (1 ≤ n ≤ len(nums)).\n\n**Output:**\n- Return the nth largest unique number in the list, or `None` if there are not enough unique numbers.\n\n**Sample Input 1:**\n```\nnums = [4, 1, 2, 2, 3, 4, 5]\nn = 2\n```\n**Sample Output 1:**\n```\n4\n```\n\n**Sample Input 2:**\n```\nnums = [1, 1, 1, 1]\nn = 1\n```\n**Sample Output 2:**\n```\n1\n```\n\n**Sample Input 3:**\n```\nnums = [5, 3, 1, 4, 2]\nn = 6\n```\n**Sample Output 3:**\n```\nNone\n```", "reference": "def find_nth_largest(nums, n):\n \"\"\"\n Returns the nth largest unique number in the list.\n If there are fewer than n unique numbers, returns None.\n \n :param nums: List of integers\n :param n: Integer representing the nth largest unique number to find\n :return: The nth largest unique number or None\n \"\"\"\n unique_nums = sorted(set(nums), reverse=True)\n if len(unique_nums) < n:\n return None\n return unique_nums[n-1]", "tests": ["assert find_nth_largest([4, 1, 2, 2, 3, 4, 5], 2) == 4", "assert find_nth_largest([1, 2, 3, 4, 5], 5) == 1", "assert find_nth_largest([1, 2, 3, 4, 5], 6) == None", "assert find_nth_largest([5, 5, 5, 5, 5], 1) == 5", "assert find_nth_largest([5, 5, 5, 5, 5], 2) == None", "assert find_nth_largest([], 1) == None", "assert find_nth_largest([10], 1) == 10", "assert find_nth_largest([10], 2) == None", "assert find_nth_largest([3, 1, 2], 3) == 1", "assert find_nth_largest([7, 7, 7, 8, 8, 9, 9, 10], 4) == 8"], "function": "find_nth_largest", "signature": "def find_nth_largest(nums, n):", "score": 0.9, "domain": "generic"} {"id": "b49192943ddfb8f5186119ad630f2f10", "problem": "You are given a binary tree. Your task is to determine if the tree is balanced. A binary tree is considered balanced if, for every node in the tree, the height difference between its left and right subtrees is at most 1. \n\n**Input:**\n- The input is a binary tree represented by its root node. Each node in the tree is defined by its value and pointers to its left and right children.\n\n**Output:**\n- Return `True` if the binary tree is balanced, otherwise return `False`.\n\n**Sample Input:**\n```\n 3\n / \\\n 9 20\n / \\\n 15 7\n```\n\n**Sample Output:**\n```\nTrue\n```", "reference": "class TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\ndef is_balanced(root):\n \"\"\"\n Determines if a binary tree is balanced.\n \n :param root: TreeNode, the root of the binary tree.\n :return: bool, True if the tree is balanced, False otherwise.\n \"\"\"\n def check_height(node):\n if node is None:\n return 0, True\n left_height, left_balanced = check_height(node.left)\n right_height, right_balanced = check_height(node.right)\n balanced = (left_balanced and right_balanced and abs(left_height - right_height) <= 1)\n return max(left_height, right_height) + 1, balanced\n \n _, balanced = check_height(root)\n return balanced\n\n# Example usage:\nroot = TreeNode(3)\nroot.left = TreeNode(9)\nroot.right = TreeNode(20)\nroot.right.left = TreeNode(15)\nroot.right.right = TreeNode(7)\n\nprint(is_balanced(root)) # Output: True", "tests": ["assert is_balanced(None) == True", "assert is_balanced(TreeNode(1)) == True", "assert is_balanced(TreeNode(1, TreeNode(2))) == True", "assert is_balanced(TreeNode(1, TreeNode(2), TreeNode(3))) == True", "assert is_balanced(TreeNode(1, TreeNode(2, TreeNode(4), TreeNode(5)), TreeNode(3))) == True", "assert is_balanced(TreeNode(1, TreeNode(2, TreeNode(4, TreeNode(6))), TreeNode(3))) == False", "assert is_balanced(TreeNode(1, TreeNode(2, TreeNode(4, TreeNode(6, TreeNode(7)))), TreeNode(3))) == False", "assert is_balanced(TreeNode(1, TreeNode(2, TreeNode(4, TreeNode(6, TreeNode(7)), TreeNode(8)), TreeNode(5)), TreeNode(3))) == False", "assert is_balanced(TreeNode(1, TreeNode(2, TreeNode(4), TreeNode(5)), TreeNode(3, TreeNode(6), TreeNode(7)))) == True", "assert is_balanced(TreeNode(1, TreeNode(2, TreeNode(4, TreeNode(6, TreeNode(7), TreeNode(8)), TreeNode(5)), TreeNode(3, TreeNode(6), TreeNode(7)))) == False"], "function": "is_balanced", "signature": "def is_balanced(root):", "score": 0.9, "domain": "generic"} {"id": "748d304012ea677ba9f40f748e379dde", "problem": "You are given a string `s` consisting of only the characters '(' and ')'. Your task is to determine if the string represents a valid sequence of nested parentheses. A valid sequence is defined as one where every opening parenthesis '(' has a corresponding closing parenthesis ')' and they are correctly nested.\n\n**Input:**\n- A single string `s` (1 ≤ |s| ≤ 10^5) containing only '(' and ')'.\n\n**Output:**\n- Return `True` if the sequence is valid, otherwise return `False`.\n\n**Sample Input:**\n```\n\"()\"\n```\n**Sample Output:**\n```\nTrue\n```\n\n**Sample Input:**\n```\n\"(()())\"\n```\n**Sample Output:**\n```\nTrue\n```\n\n**Sample Input:**\n```\n\")(\"\n```\n**Sample Output:**\n```\nFalse\n```", "reference": "def is_valid_parentheses_sequence(s):\n \"\"\"\n Determines if the given string s represents a valid sequence of nested parentheses.\n \n :param s: A string consisting of '(' and ')'.\n :return: True if the sequence is valid, False otherwise.\n \"\"\"\n stack = []\n for char in s:\n if char == '(':\n stack.append(char)\n elif char == ')':\n if not stack:\n return False\n stack.pop()\n return len(stack) == 0", "tests": ["assert is_valid_parentheses_sequence(\"()\") == True", "assert is_valid_parentheses_sequence(\"(())\") == True", "assert is_valid_parentheses_sequence(\"(()())\") == True", "assert is_valid_parentheses_sequence(\")(\") == False", "assert is_valid_parentheses_sequence(\"(()\") == False", "assert is_valid_parentheses_sequence(\"())\") == False", "assert is_valid_parentheses_sequence(\"\") == True", "assert is_valid_parentheses_sequence(\"((((()))))\") == True", "assert is_valid_parentheses_sequence(\"()()()()\") == True", "assert is_valid_parentheses_sequence(\"(()))(()\") == False"], "function": "is_valid_parentheses_sequence", "signature": "def is_valid_parentheses_sequence(s):", "score": 1.0, "domain": "generic"} {"id": "86098aed2767241d217e82400edc8792", "problem": "You are given three lists: `headers`, `values`, and `sensitive_columns`. Your task is to implement a function `distribute_columns` that processes these lists and returns two dictionaries. The first dictionary should contain non-sensitive columns as keys and their corresponding unique values as lists. The second dictionary should contain sensitive columns as keys and their corresponding unique values as lists. Ensure that no duplicate values are included in the output dictionaries.\n\n**Input:**\n- `headers`: A list of strings representing column headers.\n- `values`: A list of values corresponding to the headers.\n- `sensitive_columns`: A list of strings representing the sensitive columns.\n\n**Output:**\n- A tuple of two dictionaries: `(non_sensitive_dict, sensitive_dict)`.\n\n**Sample Input:**\n```python\nheaders = [\"name\", \"age\", \"salary\", \"email\", \"id\"]\nvalues = [\"John\", 30, 50000, \"john@example.com\", 1]\nsensitive_columns = [\"salary\", \"email\"]\n```\n\n**Sample Output:**\n```python\n({'name': ['John'], 'age': [30], 'id': [1]}, {'salary': [50000], 'email': ['john@example.com']})\n```", "reference": "def distribute_columns(headers, values, sensitive_columns):\n \"\"\"\n Distributes the given headers and values into two dictionaries based on sensitivity.\n \n Parameters:\n headers (list of str): The list of column headers.\n values (list): The list of values corresponding to the headers.\n sensitive_columns (list of str): The list of sensitive column headers.\n \n Returns:\n tuple: A tuple containing two dictionaries, the first for non-sensitive columns and the second for sensitive columns.\n \"\"\"\n non_sensitive_dict = {}\n sensitive_dict = {}\n\n for header, value in zip(headers, values):\n if header in sensitive_columns:\n sensitive_dict.setdefault(header, set()).add(value)\n else:\n non_sensitive_dict.setdefault(header, set()).add(value)\n\n for key in non_sensitive_dict:\n non_sensitive_dict[key] = list(non_sensitive_dict[key])\n \n for key in sensitive_dict:\n sensitive_dict[key] = list(sensitive_dict[key])\n \n return non_sensitive_dict, sensitive_dict", "tests": ["assert distribute_columns([\"name\", \"age\"], [\"John\", 30], []) == ({\"name\": [\"John\"], \"age\": [30]}, {})", "assert distribute_columns([\"name\", \"age\"], [\"John\", 30], [\"name\"]) == ({}, {\"name\": [\"John\"]})", "assert distribute_columns([\"name\", \"age\", \"salary\"], [\"John\", 30, 50000], [\"salary\"]) == ({\"name\": [\"John\"], \"age\": [30]}, {\"salary\": [50000]})", "assert distribute_columns([\"name\", \"age\", \"salary\"], [\"John\", 30, 50000], [\"name\", \"salary\"]) == ({\"age\": [30]}, {\"name\": [\"John\"], \"salary\": [50000]})", "assert distribute_columns([\"name\", \"age\", \"salary\"], [\"John\", 30, 50000], [\"name\", \"age\", \"salary\"]) == ({}, {\"name\": [\"John\"], \"age\": [30], \"salary\": [50000]})", "assert distribute_columns([\"name\", \"age\", \"salary\"], [\"John\", 30, 50000], [\"email\"]) == ({\"name\": [\"John\"], \"age\": [30], \"salary\": [50000]}, {})", "assert distribute_columns([\"name\", \"age\", \"salary\", \"salary\"], [\"John\", 30, 50000, 50000], [\"salary\"]) == ({\"name\": [\"John\"], \"age\": [30]}, {\"salary\": [50000]})", "assert distribute_columns([\"name\", \"age\", \"salary\", \"salary\"], [\"John\", 30, 50000, 60000], [\"salary\"]) == ({\"name\": [\"John\"], \"age\": [30]}, {\"salary\": [50000, 60000]})", "assert distribute_columns([], [], []) == ({}, {})", "assert distribute_columns([\"name\", \"age\", \"salary\"], [\"John\", 30, 50000], [\"salary\", \"age\", \"name\", \"id\"]) == ({}, {\"name\": [\"John\"], \"age\": [30], \"salary\": [50000]})"], "function": "distribute_columns", "signature": "def distribute_columns(headers, values, sensitive_columns):", "score": 0.9, "domain": "generic"} {"id": "8f11f4a2dc145e5953b20f11b4575975", "problem": "You are given two lists of elements. Your task is to determine if the two lists are anagrams of each other. Two lists are considered anagrams if they contain the same elements with the same frequencies, but possibly in a different order. Write a function `are_lists_anagrams` that takes two lists as input and returns `True` if they are anagrams, and `False` otherwise.\n\n**Sample Input:**\n```\nlist_a = ['a', 'b', 'c', 'd']\nlist_b = ['d', 'c', 'b', 'a']\nlist_c = ['a', 'b', 'c', 'e']\n```\n\n**Sample Output:**\n```\nTrue\nFalse\n```", "reference": "from collections import Counter\n\ndef are_lists_anagrams(list1, list2):\n \"\"\"\n Determines if two lists are anagrams of each other.\n \n Parameters:\n list1 (list): The first list of elements.\n list2 (list): The second list of elements.\n \n Returns:\n bool: True if the lists are anagrams, False otherwise.\n \"\"\"\n if len(list1) != len(list2):\n return False\n \n counter1 = Counter(list1)\n counter2 = Counter(list2)\n \n return counter1 == counter2\n\n# Example usage:\nlist_a = ['a', 'b', 'c', 'd']\nlist_b = ['d', 'c', 'b', 'a']\nlist_c = ['a', 'b', 'c', 'e']\n\nprint(are_lists_anagrams(list_a, list_b)) # Output: True\nprint(are_lists_anagrams(list_a, list_c)) # Output: False", "tests": ["assert are_lists_anagrams(['a', 'b', 'c'], ['c', 'b', 'a']) == True", "assert are_lists_anagrams(['a', 'b', 'c'], ['a', 'b', 'd']) == False", "assert are_lists_anagrams([1, 2, 3], [3, 2, 1]) == True", "assert are_lists_anagrams([1, 2, 3], [1, 2, 2]) == False", "assert are_lists_anagrams([], []) == True", "assert are_lists_anagrams(['a'], ['a']) == True", "assert are_lists_anagrams(['a'], ['b']) == False", "assert are_lists_anagrams(['a', 'a', 'b'], ['a', 'b', 'b']) == False", "assert are_lists_anagrams(['a', 'a', 'b'], ['b', 'a', 'a']) == True", "assert are_lists_anagrams(['a', 'b', 'c', 'd'], ['d', 'c', 'b', 'a']) == True"], "function": "are_lists_anagrams", "signature": "def are_lists_anagrams(list1, list2):", "score": 1.0, "domain": "generic"} {"id": "96b317eb10fc3b43a55639d72c858805", "problem": "You are given two matrices, `A` and `B`. Your task is to write a function that multiplies these matrices if possible. The function should first check if the number of columns in `A` is equal to the number of rows in `B`. If the matrices cannot be multiplied, the function should raise a `ValueError`. Otherwise, it should return the resulting matrix.\n\n**Input:**\n- Two matrices `A` and `B` represented as lists of lists of integers.\n\n**Output:**\n- The resulting matrix after multiplication, represented as a list of lists of integers.\n\n**Sample Input:**\n```python\nA = [[1, 2, 3], [4, 5, 6]]\nB = [[7, 8], [9, 10], [11, 12]]\n```\n\n**Sample Output:**\n```\n[58, 64]\n[139, 154]\n```", "reference": "def matrix_multiply(A, B):\n \"\"\"\n Multiplies two matrices A and B if possible.\n \n Parameters:\n A (list of list of int): The first matrix.\n B (list of list of int): The second matrix.\n \n Returns:\n list of list of int: The resulting matrix after multiplication.\n \n Raises:\n ValueError: If the number of columns in A is not equal to the number of rows in B.\n \"\"\"\n rows_A, cols_A = len(A), len(A[0])\n rows_B, cols_B = len(B), len(B[0])\n \n if cols_A != rows_B:\n raise ValueError(\"Number of columns in A must be equal to number of rows in B for matrix multiplication.\")\n \n result = [[0 for _ in range(cols_B)] for _ in range(rows_A)]\n \n for i in range(rows_A):\n for j in range(cols_B):\n for k in range(cols_A):\n result[i][j] += A[i][k] * B[k][j]\n \n return result\n\n# Example usage:\nA = [[1, 2, 3], [4, 5, 6]]\nB = [[7, 8], [9, 10], [11, 12]]\n\nresult = matrix_multiply(A, B)\nfor row in result:\n print(row)", "tests": ["assert matrix_multiply([[1, 2], [3, 4]], [[5, 6], [7, 8]]) == [[19, 22], [43, 50]]", "assert matrix_multiply([[1]], [[2]]) == [[2]]", "assert matrix_multiply([[1, 0], [0, 1]], [[2, 3], [4, 5]]) == [[2, 3], [4, 5]]", "assert matrix_multiply([[2, 3], [4, 5]], [[1, 0], [0, 1]]) == [[2, 3], [4, 5]]", "assert matrix_multiply([[1, 2, 3]], [[4], [5], [6]]) == [[32]]", "assert matrix_multiply([[4], [5], [6]], [[1, 2, 3]]) == [[4, 8, 12], [5, 10, 15], [6, 12, 18]]", "assert matrix_multiply([[1, 2], [3, 4], [5, 6]], [[7, 8], [9, 10]]) == [[25, 28], [53, 64], [81, 100]]", "assert matrix_multiply([[1, 2, 3, 4]], [[5], [6], [7], [8]]) == [[70]]", "assert matrix_multiply([[1, 2], [3, 4], [5, 6], [7, 8]], [[9, 10], [11, 12]]) == [[41, 44], [99, 108], [157, 172], [215, 236]]", "assert matrix_multiply([[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12], [13, 14, 15]]) == [[60, 66, 72], [150, 162, 174]]"], "function": "matrix_multiply", "signature": "def matrix_multiply(A, B):", "score": 0.7, "domain": "algorithmic"} {"id": "956585d34fc429fabae5f476182d89ec", "problem": "You are tasked with implementing a function `calculate_total_cost` that computes the total cost of a purchase including tax and discounts. The function should accept four parameters: `price` (the cost of a single item), `quantity` (the number of items purchased), `tax_rate` (the sales tax rate as a decimal), and `discounts` (a list of tuples where each tuple contains a minimum quantity and a discount percentage).\n\nThe function should apply the highest applicable discount based on the total quantity of items purchased before calculating the total cost including tax. The function must handle edge cases such as a tax rate of 0, a quantity of 0, and no applicable discounts.\n\n**Input:**\n- `price`: A float representing the cost of a single item.\n- `quantity`: An integer representing the number of items purchased.\n- `tax_rate`: A float representing the sales tax rate as a decimal.\n- `discounts`: A list of tuples, where each tuple contains an integer (minimum quantity) and a float (discount percentage).\n\n**Output:**\n- A float representing the total cost of the purchase including tax.\n\n**Sample Input:**\n```python\nprice = 10.0\nquantity = 5\ntax_rate = 0.08\ndiscounts = [(10, 10.0), (5, 5.0)]\n```\n\n**Sample Output:**\n```\n48.6\n```", "reference": "def calculate_total_cost(price, quantity, tax_rate, discounts):\n \"\"\"\n Calculate the total cost of a purchase including tax and discounts.\n\n Parameters:\n - price (float): The cost of a single item.\n - quantity (int): The number of items purchased.\n - tax_rate (float): The sales tax rate as a decimal.\n - discounts (list of tuples): Each tuple contains a minimum quantity and a discount percentage.\n\n Returns:\n - float: The total cost of the purchase including tax.\n \"\"\"\n # Calculate pre-tax total cost\n pre_tax_total = price * quantity\n \n # Apply the highest applicable discount\n applicable_discount = 0\n for min_qty, discount_percent in discounts:\n if quantity >= min_qty and discount_percent > applicable_discount:\n applicable_discount = discount_percent\n \n # Calculate the discount amount\n discount_amount = pre_tax_total * (applicable_discount / 100)\n \n # Calculate the discounted total before tax\n discounted_total = pre_tax_total - discount_amount\n \n # Calculate the total cost including tax\n total_cost = discounted_total * (1 + tax_rate)\n \n return total_cost", "tests": ["assert calculate_total_cost(10, 5, 0.08, [(10, 10), (5, 5)]) == 48.6", "assert calculate_total_cost(20, 0, 0.08, [(10, 10), (5, 5)]) == 0.0", "assert calculate_total_cost(15, 10, 0, [(10, 10), (5, 5)]) == 135.0", "assert calculate_total_cost(100, 1, 0.1, [(10, 5), (1, 2)]) == 102.0", "assert calculate_total_cost(50, 20, 0.05, [(15, 10), (20, 15)]) == 952.5", "assert calculate_total_cost(10, 10, 0.08, []) == 108.0", "assert calculate_total_cost(0, 10, 0.08, [(10, 10)]) == 0.0", "assert calculate_total_cost(10, 5, 0, [(5, 20)]) == 40.0", "assert calculate_total_cost(25, 3, 0.1, [(2, 5), (3, 10)]) == 74.25", "assert calculate_total_cost(10, 1, 0.08, [(1, 0)]) == 10.8"], "function": "calculate_total_cost", "signature": "def calculate_total_cost(price, quantity, tax_rate, discounts):", "score": 0.7, "domain": "generic"} {"id": "48bd50ceb2b1d14c5d1ccb761fcebcf3", "problem": "You are tasked with implementing a recursive function to compute the factorial of a non-negative integer. The factorial of a non-negative integer \\( n \\) is the product of all positive integers less than or equal to \\( n \\). The factorial of 0 is defined as 1. Your function should be named `factorial` and should handle the input as specified.\n\n**Input:**\n- A single non-negative integer \\( n \\) (where \\( 0 \\leq n \\leq 20 \\)).\n\n**Output:**\n- Return the factorial of the given integer \\( n \\).\n\n**Sample Input:**\n```\n5\n```\n\n**Sample Output:**\n```\n120\n```", "reference": "def factorial(n):\n \"\"\"\n Calculate the factorial of a given non-negative integer using recursion.\n\n Parameters:\n n (int): A non-negative integer whose factorial is to be computed.\n\n Returns:\n int: The factorial of the given integer.\n \"\"\"\n # Base case: the factorial of 0 or 1 is 1\n if n == 0 or n == 1:\n return 1\n # Recursive case: n * factorial of (n-1)\n else:\n return n * factorial(n-1)", "tests": ["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(7) == 5040", "assert factorial(10) == 3628800", "assert factorial(12) == 479001600"], "function": "factorial", "signature": "def factorial(n):", "score": 1.0, "domain": "generic"} {"id": "d8e7a5ff4510a614e13f76b11d0ed358", "problem": "You are given an array of integers. Your task is to implement a function that sorts the array in ascending order without using any built-in sorting functions. You must write your own sorting algorithm. \n\n**Input:**\n- The first line contains an integer `n` (1 ≤ n ≤ 1000), the number of elements in the array.\n- The second line contains `n` space-separated integers representing the array elements.\n\n**Output:**\n- Print the sorted array in ascending order, with elements separated by spaces.\n\n**Sample Input:**\n```\n5\n4 2 9 6 23\n```\n\n**Sample Output:**\n```\n2 4 6 9 23\n```", "reference": "def bubble_sort(arr):\n \"\"\"\n Sorts an array of integers in ascending order using the bubble sort algorithm.\n\n Parameters:\n arr (list): A list of integers to be sorted.\n\n Returns:\n list: The sorted list of integers.\n \"\"\"\n n = len(arr)\n for i in range(n):\n for j in range(0, n-i-1):\n if arr[j] > arr[j+1]:\n arr[j], arr[j+1] = arr[j+1], arr[j]\n return arr", "tests": ["assert bubble_sort([64, 34, 25, 12, 22, 11, 90]) == [11, 12, 22, 25, 34, 64, 90]", "assert bubble_sort([5, 1, 4, 2, 8]) == [1, 2, 4, 5, 8]", "assert bubble_sort([10, 7, 8, 9, 1, 5]) == [1, 5, 7, 8, 9, 10]", "assert bubble_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]", "assert bubble_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5]", "assert bubble_sort([]) == []", "assert bubble_sort([1]) == [1]", "assert bubble_sort([3, 3, 3, 3, 3]) == [3, 3, 3, 3, 3]", "assert bubble_sort([-1, -2, -3, -4, -5]) == [-5, -4, -3, -2, -1]", "assert bubble_sort([0, -1, 1, -2, 2]) == [-2, -1, 0, 1, 2]"], "function": "bubble_sort", "signature": "def bubble_sort(arr):", "score": 1.0, "domain": "algorithmic"} {"id": "8e2b38554042de1b57ff82e03f43c94e", "problem": "You are given a string representing concatenated morphtags. Each morphtag consists of a word and its part of speech, separated by a slash ('/'). Morphtags are concatenated using a plus sign ('+'). Numeric prefixes in morphtags should be ignored. If a morphtag does not contain a slash, it is considered invalid and should be skipped. Your task is to parse the string and return a list of lists, where each inner list contains a valid word and its corresponding part of speech.\n\n**Input:**\n- A single string `morphtags` (1 ≤ |morphtags| ≤ 1000).\n\n**Output:**\n- A list of lists, where each inner list contains a word and its part of speech.\n\n**Sample Input:**\n```\n\"1word1/NN+2word2/VB+3invalid+word3/ADJ\"\n```\n\n**Sample Output:**\n```\n[['word1', 'NN'], ['word2', 'VB'], ['word3', 'ADJ']]\n```", "reference": "def parse_morphtags(morphtags):\n \"\"\"\n Parses a string of concatenated morphtags, ignoring numeric prefixes and skipping invalid morphtags.\n \n :param morphtags: A string of concatenated morphtags.\n :return: A list of lists, where each inner list contains a word and its part of speech.\n \"\"\"\n result = []\n split_morphtags = morphtags.split('+')\n for morphtag in split_morphtags:\n stripped_morphtag = morphtag.lstrip('0123456789')\n if '/' in stripped_morphtag:\n word, pos = stripped_morphtag.split('/', 1)\n result.append([word, pos])\n return result", "tests": ["assert parse_morphtags(\"1word1/NN+2word2/VB\") == [['word1', 'NN'], ['word2', 'VB']]", "assert parse_morphtags(\"word1/NN+word2/VB\") == [['word1', 'NN'], ['word2', 'VB']]", "assert parse_morphtags(\"123word1/NN+456word2/VB\") == [['word1', 'NN'], ['word2', 'VB']]", "assert parse_morphtags(\"word1/NN+invalid+word2/VB\") == [['word1', 'NN'], ['word2', 'VB']]", "assert parse_morphtags(\"1word1/NN+2word2/VB+3word3/ADJ\") == [['word1', 'NN'], ['word2', 'VB'], ['word3', 'ADJ']]", "assert parse_morphtags(\"invalid+moreinvalid\") == []", "assert parse_morphtags(\"\") == []", "assert parse_morphtags(\"123/NN+456/VB\") == []", "assert parse_morphtags(\"word1/NN++word2/VB\") == [['word1', 'NN'], ['word2', 'VB']]", "assert parse_morphtags(\"word1/NN+/word2/VB\") == [['word1', 'NN']]"], "function": "parse_morphtags", "signature": "def parse_morphtags(morphtags):", "score": 0.8, "domain": "generic"} {"id": "a691db30bab44d4561301719d2f66bc7", "problem": "You are developing a system to manage user activity in a gaming platform. A user is placed on a \"cooldown\" period if they have lost their most recent game and it has been less than 3 days since that game. The user's game history is stored in a `User` object, which contains a list of `Game` objects. Each `Game` object includes the following attributes:\n- `winner`: A string representing the Discord ID of the user who won the game.\n- `player`: A string representing the Discord ID of the user who played the game.\n- `timestamp`: A datetime object representing when the game was played.\n- `duration`: An integer representing the duration of the game in seconds.\n\nYour task is to implement a function `is_on_cooldown(user)` that returns `True` if the user should be placed on a \"cooldown\" period, and `False` otherwise. If the user has not played any games or the most recent game lasted less than 5 minutes, they should not be on a \"cooldown\" period.\n\n**Sample Input:**\n```python\nfrom datetime import datetime, timedelta\n\ngame1 = Game(\"12345\", \"67890\", datetime.now() - timedelta(days=2), 360)\ngame2 = Game(\"12345\", \"67890\", datetime.now() - timedelta(days=5), 600)\nuser = User([game1, game2])\n```\n\n**Sample Output:**\n```python\nTrue\n```", "reference": "from datetime import datetime, timedelta\n\nclass Game:\n def __init__(self, winner, player, timestamp, duration):\n self.winner = winner\n self.player = player\n self.timestamp = timestamp\n self.duration = duration\n\nclass User:\n def __init__(self, games):\n self.games = games\n\ndef is_on_cooldown(user):\n \"\"\"\n Determines if a user should be placed on a cooldown period based on their recent game activity.\n \n Args:\n user (User): The user object containing the game history.\n \n Returns:\n bool: True if the user should be on cooldown, False otherwise.\n \"\"\"\n if not user.games:\n return False\n \n user.games.sort(key=lambda game: game.timestamp, reverse=True)\n most_recent_game = user.games[0]\n \n if most_recent_game.duration < 300:\n return False\n \n if most_recent_game.winner != most_recent_game.player:\n time_since_last_game = datetime.now() - most_recent_game.timestamp\n if time_since_last_game < timedelta(days=3):\n return True\n \n return False", "tests": ["assert is_on_cooldown(User([Game(\"123\", \"456\", datetime.now() - timedelta(days=2), 360)])) == True", "assert is_on_cooldown(User([Game(\"456\", \"456\", datetime.now() - timedelta(days=2), 360)])) == False", "assert is_on_cooldown(User([Game(\"123\", \"456\", datetime.now() - timedelta(days=4), 360)])) == False", "assert is_on_cooldown(User([Game(\"123\", \"456\", datetime.now() - timedelta(days=2), 200)])) == False", "assert is_on_cooldown(User([])) == False", "assert is_on_cooldown(User([Game(\"123\", \"456\", datetime.now() - timedelta(days=3), 300)])) == True", "assert is_on_cooldown(User([Game(\"123\", \"456\", datetime.now() - timedelta(days=3, seconds=1), 300)])) == False", "assert is_on_cooldown(User([Game(\"123\", \"456\", datetime.now() - timedelta(hours=23), 360)])) == True", "assert is_on_cooldown(User([Game(\"123\", \"456\", datetime.now() - timedelta(hours=25), 360)])) == False", "assert is_on_cooldown(User([Game(\"123\", \"456\", datetime.now() - timedelta(days=2), 301)])) == True"], "function": "is_on_cooldown", "signature": "def is_on_cooldown(user):", "score": 0.8, "domain": "generic"} {"id": "b650990a9d7fa1957a7ee628c9eab1c3", "problem": "You are given an array of integers, `numbers`, and an integer `start`. Your task is to determine the index of the smallest integer in `numbers` that is greater than or equal to `start` and not divisible by 3. If there are multiple such integers, return the index of the first occurrence. If no such integer exists, return `-1`.\n\n**Input:**\n- The first line contains an integer `n` (1 ≤ n ≤ 10^5), the number of elements in the array.\n- The second line contains `n` space-separated integers `numbers[i]` (-10^9 ≤ numbers[i] ≤ 10^9).\n- The third line contains an integer `start` (-10^9 ≤ start ≤ 10^9).\n\n**Output:**\n- Print a single integer, the index of the required number, or `-1` if no such number exists.\n\n**Sample Input:**\n```\n5\n10 15 21 22 25\n20\n```\n\n**Sample Output:**\n```\n3\n```", "reference": "def find_index(numbers, start):\n \"\"\"\n Finds the index of the smallest number in `numbers` that is greater than or equal to `start`\n and not divisible by 3. Returns the index of the first occurrence or -1 if no such number exists.\n\n :param numbers: List of integers.\n :param start: Integer, the starting value to compare against.\n :return: Index of the first number meeting the criteria or -1 if none exists.\n \"\"\"\n for index in range(start, len(numbers)):\n if numbers[index] >= start and numbers[index] % 3 != 0:\n return index\n return -1", "tests": ["assert find_index([1, 2, 3, 4, 5], 2) == 1", "assert find_index([3, 6, 9, 12], 1) == -1", "assert find_index([5, 10, 15, 20], 10) == 1", "assert find_index([7, 14, 21, 28], 20) == 3", "assert find_index([0, 1, 2, 3, 4, 5], 0) == 1", "assert find_index([8, 9, 10, 11, 12], 9) == 2", "assert find_index([1, 4, 7, 10, 13], 5) == 2", "assert find_index([3, 5, 9, 12, 15], 3) == 1", "assert find_index([], 1) == -1", "assert find_index([3, 3, 3, 3], 3) == -1"], "function": "find_index", "signature": "def find_index(numbers, start):", "score": 0.4, "domain": "generic"} {"id": "89852fc85d2d7d7986cc33089533daea", "problem": "You are given an integer `n`. Your task is to write a function `prime_factors` that returns a list of all distinct prime factors of `n`. A prime factor is a factor that is a prime number.\n\n**Input:**\n- An integer `n` (1 ≤ n ≤ 10^6)\n\n**Output:**\n- A list of integers representing the distinct prime factors of `n`.\n\n**Sample Input:**\n```\n28\n```\n\n**Sample Output:**\n```\n[2, 7]\n```", "reference": "def prime_factors(n):\n \"\"\"\n Returns a list of all distinct prime factors of the given integer n.\n \n :param n: Integer, the number to find prime factors for.\n :return: List of integers, the distinct prime factors of n.\n \"\"\"\n factors = []\n # Check for number of 2s that divide n\n while n % 2 == 0:\n if 2 not in factors:\n factors.append(2)\n n = n // 2\n # n must be odd at this point, so a skip of 2 (i.e., i = i + 2) can be used\n for i in range(3, int(n**0.5) + 1, 2):\n # While i divides n, append i and divide n\n while n % i == 0:\n if i not in factors:\n factors.append(i)\n n = n // i\n # This condition is to check if n is a prime number greater than 2\n if n > 2:\n factors.append(n)\n return factors\n\n# Example usage:\nprint(prime_factors(28)) # Output: [2, 7]", "tests": ["assert prime_factors(28) == [2, 7]", "assert prime_factors(1) == []", "assert prime_factors(2) == [2]", "assert prime_factors(3) == [3]", "assert prime_factors(4) == [2]", "assert prime_factors(18) == [2, 3]", "assert prime_factors(100) == [2, 5]", "assert prime_factors(37) == [37]", "assert prime_factors(60) == [2, 3, 5]", "assert prime_factors(84) == [2, 3, 7]"], "function": "prime_factors", "signature": "def prime_factors(n):", "score": 1.0, "domain": "generic"} {"id": "111a94c17cb255b070d42f97f566a2f7", "problem": "You are tasked with implementing a function `is_special_char` that determines whether a given string contains any special characters. A special character is defined as any character that is not a letter (a-z, A-Z), a digit (0-9), or a whitespace character (space, tab, newline). Your function should not use any built-in functions or methods that directly check for special characters.\n\n**Input:**\n- A single string `s` (1 ≤ |s| ≤ 1000), where |s| denotes the length of the string.\n\n**Output:**\n- Return `True` if the string contains at least one special character, otherwise return `False`.\n\n**Sample Input:**\n```\n\"Hello, World!\"\n```\n\n**Sample Output:**\n```\nTrue\n```\n\n**Sample Input:**\n```\n\"123 ABC def\"\n```\n\n**Sample Output:**\n```\nFalse\n```", "reference": "def is_special_char(s):\n \"\"\"\n Determines if the input string contains any special characters.\n \n Parameters:\n s (str): The input string to check.\n \n Returns:\n bool: True if the string contains at least one special character, False otherwise.\n \"\"\"\n # Define acceptable characters\n letters = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n digits = \"0123456789\"\n whitespace = \" \\t\\n\"\n\n # Combine all acceptable characters\n acceptable_chars = letters + digits + whitespace\n\n # Check each character in the string\n for char in s:\n # If the character is not in the acceptable characters, it's a special character\n special_char = True\n for acceptable in acceptable_chars:\n if char == acceptable:\n special_char = False\n break\n if special_char:\n return True\n\n # If no special characters were found, return False\n return False", "tests": ["assert is_special_char(\"hello world\") == False", "assert is_special_char(\"hello123\") == False", "assert is_special_char(\"hello@world\") == True", "assert is_special_char(\"1234567890\") == False", "assert is_special_char(\"!@#$%^&*()\") == True", "assert is_special_char(\" \") == False", "assert is_special_char(\"\\t\") == False", "assert is_special_char(\"\\n\") == False", "assert is_special_char(\"hello\\tworld\\n\") == False", "assert is_special_char(\"hello world!\") == True"], "function": "is_special_char", "signature": "def is_special_char(s):", "score": 1.0, "domain": "generic"} {"id": "f8fa1d41d5905a6fa700ed50fec51eb7", "problem": "You are tasked with implementing a function `generate_html_table` that constructs an HTML table from a list of dictionaries. Each dictionary in the list represents a row in the table, with keys serving as column headers. The function should return a string containing the HTML representation of the table. If the input list is empty, the function should return an empty string.\n\n**Input:**\n- A list of dictionaries, where each dictionary contains key-value pairs representing table data.\n\n**Output:**\n- A string containing the HTML code for the table.\n\n**Sample Input:**\n```python\n[\n {\"Name\": \"Alice\", \"Age\": 30, \"City\": \"New York\"},\n {\"Name\": \"Bob\", \"Age\": 24, \"City\": \"Los Angeles\"},\n {\"Name\": \"Charlie\", \"Age\": 29, \"City\": \"Chicago\"}\n]\n```\n\n**Sample Output:**\n```html\n
NameAgeCity
Alice30New York
Bob24Los Angeles
Charlie29Chicago
\n```", "reference": "def generate_html_table(data: list) -> str:\n \"\"\"\n Generates an HTML table from a list of dictionaries.\n \n Parameters:\n data (list): A list of dictionaries, where each dictionary represents a row in the table.\n \n Returns:\n str: A string containing the HTML representation of the table.\n \"\"\"\n if not data:\n return \"\"\n\n headers = data[0].keys()\n html = [\"\", \"\"]\n \n for header in headers:\n html.append(f\"\")\n \n html.append(\"\")\n \n for row in data:\n html.append(\"\")\n for header in headers:\n html.append(f\"\")\n html.append(\"\")\n \n html.append(\"
{header}
{row.get(header, '')}
\")\n return \"\".join(html)", "tests": ["assert generate_html_table([]) == \"\"", "assert generate_html_table([{\"Name\": \"Alice\", \"Age\": 30}]) == \"
NameAge
Alice30
\"", "assert generate_html_table([{\"Name\": \"Alice\", \"Age\": 30}, {\"Name\": \"Bob\", \"Age\": 24}]) == \"
NameAge
Alice30
Bob24
\"", "assert generate_html_table([{\"Name\": \"Alice\", \"Age\": 30}, {\"Name\": \"Bob\", \"Age\": 24, \"City\": \"Los Angeles\"}]) == \"
NameAgeCity
Alice30
Bob24Los Angeles
\"", "assert generate_html_table([{\"Name\": \"Alice\", \"Age\": 30}, {\"Name\": \"Bob\", \"Age\": 24}, {\"Name\": \"Charlie\", \"Age\": 29}]) == \"
NameAge
Alice30
Bob24
Charlie29
\"", "assert generate_html_table([{\"Name\": \"Alice\", \"Age\": 30}, {\"Name\": \"Bob\", \"Age\": 24}, {\"Name\": \"Charlie\", \"Age\": 29, \"City\": \"Chicago\"}]) == \"
NameAgeCity
Alice30
Bob24
Charlie29Chicago
\"", "assert generate_html_table([{\"Name\": \"Alice\", \"Age\": 30}, {\"Name\": \"Bob\", \"Age\": 24}, {\"Name\": \"Charlie\", \"Age\": 29, \"City\": \"Chicago\", \"Country\": \"USA\"}]) == \"
NameAgeCityCountry
Alice30
Bob24
Charlie29ChicagoUSA
\"", "assert generate_html_table([{\"Name\": \"Alice\", \"Age\": 30}, {\"Name\": \"Bob\", \"Age\": 24}, {\"Name\": \"Charlie\", \"Age\": 29, \"City\": \"Chicago\", \"Country\": \"USA\"}, {\"Name\": \"David\", \"Age\": 22, \"City\": \"San Francisco\", \"Country\": \"USA\"}]) == \"
NameAgeCityCountry
Alice30
Bob24
Charlie29ChicagoUSA
David22San FranciscoUSA
\"", "assert generate_html_table([{\"Name\": \"Alice\", \"Age\": 30}, {\"Name\": \"Bob\", \"Age\": 24}, {\"Name\": \"Charlie\", \"Age\": 29, \"City\": \"Chicago\", \"Country\": \"USA\"}, {\"Name\": \"David\", \"Age\": 22, \"City\": \"San Francisco\", \"Country\": \"USA\"}, {\"Name\": \"Eve\", \"Age\": 27}]) == \"
NameAgeCityCountry
Alice30
Bob24
Charlie29ChicagoUSA
David22San FranciscoUSA
Eve27
\"", "assert generate_html_table([{\"Name\": \"Alice\", \"Age\": 30}, {\"Name\": \"Bob\", \"Age\": 24}, {\"Name\": \"Charlie\", \"Age\": 29, \"City\": \"Chicago\", \"Country\": \"USA\"}, {\"Name\": \"David\", \"Age\": 22, \"City\": \"San Francisco\", \"Country\": \"USA\"}, {\"Name\": \"Eve\", \"Age\": 27, \"City\": \"Seattle\"}]) == \"
NameAgeCityCountry
Alice30
Bob24
Charlie29ChicagoUSA
David22San FranciscoUSA
Eve27Seattle
\""], "function": "generate_html_table", "signature": "def generate_html_table(data: list) -> str:", "score": 0.4, "domain": "generic"} {"id": "f2bfc3eb6a00df18174089d2d74ab118", "problem": "You are tasked with implementing a function `summarize_list(lst, max_length=5)` that processes a potentially nested list structure. The function should return a string representation of the list, summarized if necessary. The summarization rule is as follows: if the list (or any sublist) has more than `max_length` elements, it should be represented by its first `max_length // 2` elements, followed by an ellipsis (`'...'`), and then its last `max_length // 2` elements. If the list (or sublist) has `max_length` or fewer elements, it should be represented in its entirety. The structure of the original list must be preserved.\n\n**Sample Input:**\n```python\nsummarize_list([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 5)\n```\n\n**Sample Output:**\n```\n'[1, 2, ..., 9, 10]'\n```\n\n**Sample Input:**\n```python\nsummarize_list([1, [2, 3, 4, 5, 6, 7], 8, 9, 10], 5)\n```\n\n**Sample Output:**\n```\n'[1, [2, 3, ..., 6, 7], 8, 9, 10]'\n```", "reference": "def summarize_list(lst, max_length=5):\n \"\"\"\n Returns a summarized string representation of a potentially nested list.\n \n Parameters:\n lst (list): The list to be summarized.\n max_length (int): The maximum number of elements to display without summarization.\n \n Returns:\n str: The summarized string representation of the list.\n \"\"\"\n def summarize(sublist):\n if not isinstance(sublist, list):\n return str(sublist)\n \n n = len(sublist)\n if n <= max_length:\n return '[' + ', '.join(summarize(item) for item in sublist) + ']'\n \n half_length = max_length // 2\n return '[' + ', '.join(summarize(item) for item in sublist[:half_length]) + ', ..., ' + ', '.join(summarize(item) for item in sublist[-half_length:]) + ']'\n \n return summarize(lst)", "tests": ["assert summarize_list([1, 2, 3, 4, 5]) == '[1, 2, 3, 4, 5]'", "assert summarize_list([1, 2, 3, 4, 5, 6]) == '[1, 2, ..., 5, 6]'", "assert summarize_list([1, 2, 3, 4, 5, 6, 7]) == '[1, 2, ..., 6, 7]'", "assert summarize_list([1, 2, 3, 4, 5, 6, 7, 8]) == '[1, 2, ..., 7, 8]'", "assert summarize_list([1, 2, 3, 4, 5, 6, 7, 8, 9]) == '[1, 2, ..., 8, 9]'", "assert summarize_list([[1, 2, 3], [4, 5, 6], [7, 8, 9]], max_length=4) == '[[1, 2, 3], [4, 5, 6], ..., [7, 8, 9]]'", "assert summarize_list([1, [2, 3, 4, 5, 6], 7, 8, 9, 10]) == '[1, [2, 3, 4, 5, 6], ..., 9, 10]'", "assert summarize_list([1, 2, [3, 4, 5, 6, 7, 8], 9, 10]) == '[1, 2, [3, 4, ..., 7, 8], ..., 9, 10]'", "assert summarize_list([], max_length=3) == '[]'", "assert summarize_list([1, 2, 3, [4, 5, 6, 7, 8, 9, 10], 11, 12, 13], max_length=5) == '[1, 2, 3, [4, 5, ..., 9, 10], ..., 12, 13]'"], "function": "summarize_list", "signature": "def summarize_list(lst, max_length=5):", "score": 0.7, "domain": "generic"} {"id": "0b85d7f9ebf40f1c96112cd91894d65b", "problem": "You are given a list of integers. Your task is to write a function that returns the most frequent integer in the list along with its frequency. In the event of a tie, any of the most frequent integers may be returned.\n\n**Input:**\n- A list of integers `numbers` (1 ≤ len(numbers) ≤ 10^5), where each integer is in the range [-10^9, 10^9].\n\n**Output:**\n- A tuple containing the most frequent integer and its frequency.\n\n**Sample Input:**\n```\n[1, 3, 2, 2, 1, 4, 1, 2, 5, 1, 2, 2, 3]\n```\n\n**Sample Output:**\n```\n(2, 4)\n```", "reference": "from collections import Counter\n\ndef most_frequent(numbers):\n \"\"\"\n Returns the most frequent integer in the list along with its frequency.\n In case of a tie, any of the most frequent integers may be returned.\n\n :param numbers: List of integers\n :return: Tuple (most frequent integer, frequency)\n \"\"\"\n count = Counter(numbers)\n max_frequency = max(count.values())\n most_frequent_item = next((item for item, freq in count.items() if freq == max_frequency), None)\n return most_frequent_item, max_frequency\n\n# Example usage:\nnumbers = [1, 3, 2, 2, 1, 4, 1, 2, 5, 1, 2, 2, 3]\nitem, frequency = most_frequent(numbers)\nprint(f\"The most frequent item is {item} with a frequency of {frequency}.\")", "tests": ["assert most_frequent([1, 2, 2, 3, 3, 4]) == (2, 2) or most_frequent([1, 2, 2, 3, 3, 4]) == (3, 2)", "assert most_frequent([7, 7, 7, 7, 7]) == (7, 5)", "assert most_frequent([10, 20, 10, 20, 10]) == (10, 3)", "assert most_frequent([1, 1, 2, 2, 3, 3, 4, 4]) == (1, 2) or most_frequent([1, 1, 2, 2, 3, 3, 4, 4]) == (2, 2) or most_frequent([1, 1, 2, 2, 3, 3, 4, 4]) == (3, 2) or most_frequent([1, 1, 2, 2, 3, 3, 4, 4]) == (4, 2)", "assert most_frequent([]) == (None, 0)", "assert most_frequent([5]) == (5, 1)", "assert most_frequent([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) == (1, 1) or most_frequent([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) == (2, 1) or most_frequent([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) == (3, 1) or most_frequent([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) == (4, 1) or most_frequent([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) == (5, 1) or most_frequent([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) == (6, 1) or most_frequent([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) == (7, 1) or most_frequent([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) == (8, 1) or most_frequent([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) == (9, 1) or most_frequent([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) == (10, 1)", "assert most_frequent([1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 5]) == (5, 3)", "assert most_frequent([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]) == (10, 4)", "assert most_frequent([-1, -2, -3, -1, -2, -1]) == (-1, 3)"], "function": "most_frequent", "signature": "def most_frequent(numbers):", "score": 0.9, "domain": "algorithmic"} {"id": "0bc95670fc9084b38ff69cbc1b526ddb", "problem": "You are given a dictionary where the values can be of any data type. Your task is to write a function `convert_string_values_to_uppercase` that processes this dictionary and returns a new dictionary. The new dictionary should have the same keys as the input dictionary, but all string values should be converted to uppercase. Non-string values should remain unchanged.\n\n**Sample Input:**\n```python\n{\"name\": \"john\", \"city\": \"new york\", \"age\": 30}\n```\n\n**Sample Output:**\n```python\n{\"name\": \"JOHN\", \"city\": \"NEW YORK\", \"age\": 30}\n```", "reference": "def convert_string_values_to_uppercase(input_dict):\n \"\"\"\n Converts all string values in the input dictionary to uppercase.\n \n Parameters:\n input_dict (dict): The dictionary with values to be converted.\n \n Returns:\n dict: A new dictionary with the same keys and uppercase string values.\n \"\"\"\n return {key: value.upper() if isinstance(value, str) else value for key, value in input_dict.items()}", "tests": ["assert convert_string_values_to_uppercase({\"name\": \"john\", \"city\": \"new york\"}) == {\"name\": \"JOHN\", \"city\": \"NEW YORK\"}", "assert convert_string_values_to_uppercase({\"name\": \"Alice\", \"city\": \"Los Angeles\", \"age\": 28}) == {\"name\": \"ALICE\", \"city\": \"LOS ANGELES\", \"age\": 28}", "assert convert_string_values_to_uppercase({\"country\": \"canada\", \"language\": \"english\"}) == {\"country\": \"CANADA\", \"language\": \"ENGLISH\"}", "assert convert_string_values_to_uppercase({\"greeting\": \"hello world\", \"number\": 123}) == {\"greeting\": \"HELLO WORLD\", \"number\": 123}", "assert convert_string_values_to_uppercase({\"name\": \"bob\", \"city\": \"chicago\", \"nickname\": \"bobby\"}) == {\"name\": \"BOB\", \"city\": \"CHICAGO\", \"nickname\": \"BOBBY\"}", "assert convert_string_values_to_uppercase({\"name\": \"jane\", \"city\": \"san francisco\", \"age\": 25, \"job\": \"engineer\"}) == {\"name\": \"JANE\", \"city\": \"SAN FRANCISCO\", \"age\": 25, \"job\": \"ENGINEER\"}", "assert convert_string_values_to_uppercase({}) == {}", "assert convert_string_values_to_uppercase({\"name\": \"mike\", \"city\": \"atlanta\", \"hobbies\": [\"reading\", \"gaming\"]}) == {\"name\": \"MIKE\", \"city\": \"ATLANTA\", \"hobbies\": [\"reading\", \"gaming\"]}", "assert convert_string_values_to_uppercase({\"name\": \"sara\", \"city\": \"miami\", \"age\": 35, \"email\": \"sara@example.com\"}) == {\"name\": \"SARA\", \"city\": \"MIAMI\", \"age\": 35, \"email\": \"SARA@EXAMPLE.COM\"}", "assert convert_string_values_to_uppercase({\"name\": \"tom\", \"city\": \"seattle\", \"status\": \"single\"}) == {\"name\": \"TOM\", \"city\": \"SEATTLE\", \"status\": \"SINGLE\"}"], "function": "convert_string_values_to_uppercase", "signature": "def convert_string_values_to_uppercase(input_dict):", "score": 1.0, "domain": "generic"} {"id": "ae779ced9922053144012fe83d85a208", "problem": "You are given a string `text` consisting of a sequence of words separated by spaces. Your task is to implement a function `most_frequent_words(text, n)` that returns a list of the `n` most frequent words in the text. If multiple words have the same frequency, they should be returned in the order of their first appearance in the text.\n\n**Input:**\n- A string `text` (1 ≤ |text| ≤ 10^5) containing words separated by spaces.\n- An integer `n` (1 ≤ n ≤ number of unique words in `text`).\n\n**Output:**\n- A list of `n` most frequent words in the order of their first appearance.\n\n**Sample Input:**\n```\ntext = \"the quick brown fox jumps over the lazy dog the quick brown fox jumps over the lazy dog the quick brown fox\"\nn = 3\n```\n\n**Sample Output:**\n```\n['the', 'quick', 'brown']\n```", "reference": "from collections import Counter, OrderedDict\n\ndef most_frequent_words(text, n):\n \"\"\"\n Returns the n most frequent words in the given text.\n If multiple words have the same frequency, they are returned in the order of their first appearance.\n \n :param text: A string containing words separated by spaces.\n :param n: An integer representing the number of most frequent words to return.\n :return: A list of the n most frequent words.\n \"\"\"\n words = text.split()\n word_count = OrderedDict()\n for word in words:\n word_count[word] = word_count.get(word, 0) + 1\n counter = Counter(word_count)\n most_common_words = counter.most_common(n)\n result = [word for word, count in most_common_words]\n return result\n\n# Test the function\ntext = \"the quick brown fox jumps over the lazy dog the quick brown fox jumps over the lazy dog the quick brown fox\"\nn = 3\nprint(most_frequent_words(text, n)) # Output: ['the', 'quick', 'brown']", "tests": ["assert most_frequent_words(\"the quick brown fox jumps over the lazy dog\", 1) == [\"the\"]", "assert most_frequent_words(\"hello world hello\", 2) == [\"hello\", \"world\"]", "assert most_frequent_words(\"a a a b b c\", 2) == [\"a\", \"b\"]", "assert most_frequent_words(\"one two three four five six seven eight nine ten\", 5) == [\"one\", \"two\", \"three\", \"four\", \"five\"]", "assert most_frequent_words(\"repeat repeat repeat\", 1) == [\"repeat\"]", "assert most_frequent_words(\"apple banana apple orange banana apple\", 2) == [\"apple\", \"banana\"]", "assert most_frequent_words(\"same same same same\", 3) == [\"same\"]", "assert most_frequent_words(\"unique words only here\", 4) == [\"unique\", \"words\", \"only\", \"here\"]", "assert most_frequent_words(\"\", 1) == []", "assert most_frequent_words(\"tie tie break break\", 2) == [\"tie\", \"break\"]"], "function": "most_frequent_words", "signature": "def most_frequent_words(text, n):", "score": 1.0, "domain": "generic"} {"id": "5a8e5ac9b9700b858e6f04f046f939f9", "problem": "You are given two dictionaries, `dict1` and `dict2`. Your task is to construct a new dictionary, `dict3`, based on the following rules:\n\n1. Remove any key-value pairs from `dict2` where the key is a palindrome.\n2. Initialize `dict3` as a copy of `dict1`.\n3. Update `dict3` with values from `dict2` under the following conditions:\n - If a key exists in both `dict1` and `dict2`, and `override` is `False`, retain the value from `dict1`.\n - If a key exists in both `dict1` and `dict2`, and `override` is `True`, update the value with the value from `dict2`.\n - If a key exists only in `dict2`, add it to `dict3`.\n - If a key exists only in `dict1`, retain it in `dict3`.\n4. If `keys_list` is not `None`, only consider keys in `keys_list` for updating `dict3` from `dict2`. Otherwise, consider all keys from `dict2`.\n\nReturn the updated dictionary `dict3`.\n\n**Sample Input:**\n```python\ndict1 = {'racecar': 1, 'hello': 2, 'world': 3}\ndict2 = {'level': 4, 'hello': 5, 'python': 6, 'madam': 7}\noverride = True\nkeys_list = ['hello', 'python']\n```\n\n**Sample Output:**\n```python\n{'racecar': 1, 'hello': 5, 'world': 3, 'python': 6}\n```", "reference": "def create_dict3(dict1, dict2, override, keys_list):\n \"\"\"\n Constructs a new dictionary dict3 based on the given rules:\n - Removes palindromic keys from dict2.\n - Initializes dict3 as a copy of dict1.\n - Updates dict3 with values from dict2 based on the override flag and keys_list.\n \n Parameters:\n dict1 (dict): The original dictionary.\n dict2 (dict): The dictionary to update from.\n override (bool): Flag to determine whether to override values in dict1 with dict2.\n keys_list (list or None): List of keys to consider for updating dict3 from dict2.\n \n Returns:\n dict: The updated dictionary dict3.\n \"\"\"\n # Remove any key-value pairs from dict2 where the key is a palindrome\n dict2 = {key: value for key, value in dict2.items() if key != key[::-1]}\n\n # Create a copy of dict1 to form the base of dict3\n dict3 = dict1.copy()\n\n # Determine which keys from dict2 should be considered for updating dict3\n if keys_list is not None:\n keys_to_consider = set(keys_list)\n else:\n keys_to_consider = set(dict2.keys())\n\n # Update dict3 based on the conditions specified\n for key in keys_to_consider:\n if key in dict3:\n if override:\n dict3[key] = dict2[key]\n else:\n dict3[key] = dict2[key]\n\n return dict3", "tests": ["assert create_dict3({'a': 1, 'b': 2}, {'aba': 3, 'b': 4}, False, None) == {'a': 1, 'b': 2}", "assert create_dict3({'a': 1, 'b': 2}, {'aba': 3, 'b': 4}, True, None) == {'a': 1, 'b': 4}", "assert create_dict3({'a': 1, 'b': 2}, {'c': 3, 'd': 4}, False, ['c']) == {'a': 1, 'b': 2, 'c': 3}", "assert create_dict3({'a': 1, 'b': 2}, {'c': 3, 'd': 4}, True, ['c', 'd']) == {'a': 1, 'b': 2, 'c': 3, 'd': 4}", "assert create_dict3({'racecar': 1, 'hello': 2}, {'level': 4, 'hello': 5}, False, None) == {'racecar': 1, 'hello': 2}", "assert create_dict3({'racecar': 1, 'hello': 2}, {'level': 4, 'hello': 5}, True, None) == {'racecar': 1, 'hello': 5}", "assert create_dict3({'abc': 1, 'def': 2}, {'cba': 3, 'fed': 4}, False, ['cba']) == {'abc': 1, 'def': 2, 'cba': 3}", "assert create_dict3({'abc': 1, 'def': 2}, {'cba': 3, 'fed': 4}, True, ['cba', 'fed']) == {'abc': 1, 'def': 2, 'cba': 3, 'fed': 4}", "assert create_dict3({}, {'madam': 1, 'refer': 2, 'deified': 3}, False, None) == {}", "assert create_dict3({'a': 1, 'b': 2}, {'a': 3, 'b': 4}, True, ['a']) == {'a': 3, 'b': 2}"], "function": "create_dict3", "signature": "def create_dict3(dict1, dict2, override, keys_list):", "score": 0.6, "domain": "generic"} {"id": "68cf98c5c3cc11c387f05acd87e59614", "problem": "You are given an integer `n`. Your task is to write a function `find_largest_prime` that returns the largest prime number less than or equal to `n`. If no such prime number exists, return `None`. A prime number is defined as a natural number greater than 1 that has no positive divisors other than 1 and itself.\n\n**Input:**\n- An integer `n` (1 ≤ n ≤ 10^6)\n\n**Output:**\n- The largest prime number less than or equal to `n`, or `None` if no such prime exists.\n\n**Sample Input:**\n```\n10\n1\n17\n```\n\n**Sample Output:**\n```\n7\nNone\n17\n```", "reference": "def find_largest_prime(n):\n \"\"\"\n Returns the largest prime number less than or equal to n.\n If no such prime number exists, returns None.\n \n :param n: An integer (1 ≤ n ≤ 10^6)\n :return: The largest prime number ≤ n or None\n \"\"\"\n def is_prime(num):\n if num <= 1:\n return False\n if num <= 3:\n return True\n if num % 2 == 0 or num % 3 == 0:\n return False\n i = 5\n while i * i <= num:\n if num % i == 0 or num % (i + 2) == 0:\n return False\n i += 6\n return True\n \n for num in range(n, 1, -1):\n if is_prime(num):\n return num\n return None", "tests": ["assert find_largest_prime(10) == 7", "assert find_largest_prime(17) == 17", "assert find_largest_prime(1) == None", "assert find_largest_prime(2) == 2", "assert find_largest_prime(20) == 19", "assert find_largest_prime(0) == None", "assert find_largest_prime(-5) == None", "assert find_largest_prime(18) == 17", "assert find_largest_prime(100) == 97", "assert find_largest_prime(101) == 101"], "function": "find_largest_prime", "signature": "def find_largest_prime(n):", "score": 1.0, "domain": "generic"} {"id": "9c45bb962cb14d4d6c7400f497649f68", "problem": "You are given a list of strings. Your task is to write a function that returns a new list with all duplicate strings removed while maintaining the original order of the first occurrence of each string.\n\n**Input:**\n- A list of strings, `strings`, where `1 <= len(strings) <= 10^5` and each string has a length of at most `100`.\n\n**Output:**\n- A list of strings with duplicates removed, preserving the order of their first appearance.\n\n**Sample Input:**\n```\n[\"apple\", \"banana\", \"apple\", \"orange\", \"banana\"]\n```\n\n**Sample Output:**\n```\n['apple', 'banana', 'orange']\n```", "reference": "def remove_duplicates(strings):\n \"\"\"\n Removes duplicates from a list of strings while preserving the order of their first occurrence.\n\n :param strings: List of strings with possible duplicates.\n :return: A new list with duplicates removed.\n \"\"\"\n seen = set()\n result = []\n for s in strings:\n if s not in seen:\n seen.add(s)\n result.append(s)\n return result\n\n# Test the function\ninput_list = [\"apple\", \"banana\", \"apple\", \"orange\", \"banana\"]\noutput_list = remove_duplicates(input_list)\nprint(output_list) # Output: ['apple', 'banana', 'orange']", "tests": ["assert remove_duplicates([\"apple\", \"banana\", \"apple\", \"orange\", \"banana\"]) == [\"apple\", \"banana\", \"orange\"]", "assert remove_duplicates([\"hello\", \"world\", \"hello\", \"python\", \"world\"]) == [\"hello\", \"world\", \"python\"]", "assert remove_duplicates([\"a\", \"b\", \"c\", \"a\", \"b\", \"c\"]) == [\"a\", \"b\", \"c\"]", "assert remove_duplicates([\"one\", \"two\", \"three\"]) == [\"one\", \"two\", \"three\"]", "assert remove_duplicates([]) == []", "assert remove_duplicates([\"duplicate\", \"duplicate\", \"duplicate\"]) == [\"duplicate\"]", "assert remove_duplicates([\"1\", \"2\", \"3\", \"2\", \"1\", \"3\"]) == [\"1\", \"2\", \"3\"]", "assert remove_duplicates([\"keep\", \"order\", \"of\", \"elements\", \"order\"]) == [\"keep\", \"order\", \"of\", \"elements\"]", "assert remove_duplicates([\"\", \"\", \"test\", \"\"]) == [\"\", \"test\"]", "assert remove_duplicates([\"single\"]) == [\"single\"]"], "function": "remove_duplicates", "signature": "def remove_duplicates(strings):", "score": 1.0, "domain": "generic"} {"id": "720c5a1a8ffc54b1c028416f8d870bff", "problem": "Given two strings `s1` and `s2`, write a function `longest_common_substring` that returns the longest common substring between them. If there are multiple substrings of the same maximum length, return the one that appears first in `s1`. Your function should be efficient and handle edge cases such as empty strings.\n\n**Input:**\n- Two strings `s1` and `s2` (1 ≤ |s1|, |s2| ≤ 1000).\n\n**Output:**\n- A string representing the longest common substring.\n\n**Sample Input:**\n```\ns1 = \"abcdef\"\ns2 = \"zabcf\"\n```\n\n**Sample Output:**\n```\n\"abc\"\n```", "reference": "def longest_common_substring(s1: str, s2: str) -> str:\n \"\"\"\n Finds the longest common substring between two input strings.\n\n Parameters:\n s1 (str): The first input string.\n s2 (str): The second input string.\n\n Returns:\n str: The longest common substring between s1 and s2. If there are multiple\n substrings of the same maximum length, returns the first one that\n appears in s1.\n \"\"\"\n m, n = len(s1), len(s2)\n dp = [[0] * (n + 1) for _ in range(m + 1)]\n longest_length = 0\n end_index_s1 = 0\n \n for i in range(1, m + 1):\n for j in range(1, n + 1):\n if s1[i - 1] == s2[j - 1]:\n dp[i][j] = dp[i - 1][j - 1] + 1\n if dp[i][j] > longest_length:\n longest_length = dp[i][j]\n end_index_s1 = i\n else:\n dp[i][j] = 0\n \n return s1[end_index_s1 - longest_length: end_index_s1]", "tests": ["assert longest_common_substring(\"abcdef\", \"zabcf\") == \"abc\"", "assert longest_common_substring(\"hello\", \"yellow\") == \"ello\"", "assert longest_common_substring(\"abc\", \"def\") == \"\"", "assert longest_common_substring(\"abcabc\", \"abc\") == \"abc\"", "assert longest_common_substring(\"aaaa\", \"aa\") == \"aa\"", "assert longest_common_substring(\"abcdxyz\", \"xyzabcd\") == \"abcd\"", "assert longest_common_substring(\"abcde\", \"fghij\") == \"\"", "assert longest_common_substring(\"abc\", \"a\") == \"a\"", "assert longest_common_substring(\"abc\", \"c\") == \"c\"", "assert longest_common_substring(\"\", \"abc\") == \"\""], "function": "longest_common_substring", "signature": "def longest_common_substring(s1: str, s2: str) -> str:", "score": 1.0, "domain": "generic"} {"id": "ab70ba0549fb7426ac78d55c99ba6fb1", "problem": "You are given a list of integers. Your task is to write a function that removes all duplicate elements from the list while maintaining the original order of the remaining elements. \n\n**Input:**\n- A list of integers `numbers` (1 ≤ len(numbers) ≤ 10^5), where each integer is in the range [-10^9, 10^9].\n\n**Output:**\n- A list of integers with duplicates removed, preserving the original order.\n\n**Sample Input:**\n```python\n[4, 5, 6, 4, 7, 5, 8, 9, 6]\n```\n\n**Sample Output:**\n```python\n[4, 5, 6, 7, 8, 9]\n```", "reference": "def remove_duplicates_preserve_order(numbers):\n \"\"\"\n Removes duplicates from a list of numbers while preserving the original order.\n\n :param numbers: List of integers from which duplicates are to be removed.\n :return: A new list with duplicates removed, preserving the original order.\n \"\"\"\n seen = set()\n no_duplicates = []\n for num in numbers:\n if num not in seen:\n no_duplicates.append(num)\n seen.add(num)\n return no_duplicates", "tests": ["assert remove_duplicates_preserve_order([1, 2, 3, 2, 1]) == [1, 2, 3]", "assert remove_duplicates_preserve_order([4, 5, 6, 4, 7, 5]) == [4, 5, 6, 7]", "assert remove_duplicates_preserve_order([10, 10, 10]) == [10]", "assert remove_duplicates_preserve_order([]) == []", "assert remove_duplicates_preserve_order([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]", "assert remove_duplicates_preserve_order([5, 4, 3, 2, 1, 1, 2, 3, 4, 5]) == [5, 4, 3, 2, 1]", "assert remove_duplicates_preserve_order([1, 1, 2, 2, 3, 3, 4, 4]) == [1, 2, 3, 4]", "assert remove_duplicates_preserve_order([7]) == [7]", "assert remove_duplicates_preserve_order([1, 2, 3, 4, 5, 6, 7, 8, 9, 1]) == [1, 2, 3, 4, 5, 6, 7, 8, 9]", "assert remove_duplicates_preserve_order([9, 8, 7, 6, 5, 4, 3, 2, 1, 9]) == [9, 8, 7, 6, 5, 4, 3, 2, 1]"], "function": "remove_duplicates_preserve_order", "signature": "def remove_duplicates_preserve_order(numbers):", "score": 1.0, "domain": "generic"} {"id": "db12615e2daea3403f1c03ea0a86f181", "problem": "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 \\). The factorial of 0 is defined as 1.\n\n**Input:**\n- A single integer \\( n \\) (where \\( 0 \\leq n \\leq 20 \\)).\n\n**Output:**\n- Print the factorial of the given integer \\( n \\).\n\n**Sample Input:**\n```\n5\n```\n\n**Sample Output:**\n```\n120\n```", "reference": "def factorial(n):\n \"\"\"\n Calculate the factorial of a non-negative integer n using recursion.\n\n Parameters:\n n (int): A non-negative integer whose factorial is to be computed.\n\n Returns:\n int: The factorial of the integer n.\n \"\"\"\n if n == 0 or n == 1:\n return 1\n else:\n return n * factorial(n - 1)\n\n# Test the function with the sample input\nresult = factorial(5)\nprint(result)", "tests": ["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(7) == 5040", "assert factorial(10) == 3628800", "assert factorial(12) == 479001600"], "function": "factorial", "signature": "def factorial(n):", "score": 1.0, "domain": "algorithmic"} {"id": "86662860c2cd428d64fffba3781e8d64", "problem": "You are given a list of tuples, where each tuple consists of a student's ID (a string) and a list of integers representing the student's scores in various subjects. Your task is to implement a function that computes the average score for each student and returns a dictionary with student IDs as keys and their corresponding average scores as values.\n\n**Input:**\n- A list of tuples, where each tuple contains a student ID and a list of scores.\n\n**Output:**\n- A dictionary with student IDs as keys and their average scores as values.\n\n**Sample Input:**\n```python\n[(\"123\", [85, 90, 78]), (\"456\", [95, 88, 76]), (\"789\", [70, 80, 90])]\n```\n\n**Sample Output:**\n```python\n{'123': 84.33333333333333, '456': 86.33333333333333, '789': 80.0}\n```", "reference": "def calculate_average_scores(student_scores):\n \"\"\"\n Calculate the average scores for each student.\n\n :param student_scores: List of tuples, where each tuple contains a student ID and a list of scores.\n :return: Dictionary with student IDs as keys and their average scores as values.\n \"\"\"\n average_scores = {}\n for student_id, scores in student_scores:\n average_score = sum(scores) / len(scores)\n average_scores[student_id] = average_score\n return average_scores\n\n# Example usage\nstudent_scores = [(\"123\", [85, 90, 78]), (\"456\", [95, 88, 76]), (\"789\", [70, 80, 90])]\nprint(calculate_average_scores(student_scores))", "tests": ["assert calculate_average_scores([(\"123\", [85, 90, 78])]) == {\"123\": 84.33333333333333}", "assert calculate_average_scores([(\"456\", [95, 88, 76])]) == {\"456\": 86.33333333333333}", "assert calculate_average_scores([(\"789\", [70, 80, 90])]) == {\"789\": 80.0}", "assert calculate_average_scores([(\"101\", [100, 100, 100]), (\"102\", [50, 50, 50])]) == {\"101\": 100.0, \"102\": 50.0}", "assert calculate_average_scores([(\"201\", [88, 92, 85, 90]), (\"202\", [75, 80, 78, 82])]) == {\"201\": 88.75, \"202\": 78.75}", "assert calculate_average_scores([]) == {}", "assert calculate_average_scores([(\"301\", [100])]) == {\"301\": 100.0}", "assert calculate_average_scores([(\"401\", [90, 85, 88, 92, 95])]) == {\"401\": 90.0}", "assert calculate_average_scores([(\"501\", [60, 70, 80, 90, 100]), (\"502\", [55, 65, 75, 85, 95])]) == {\"501\": 80.0, \"502\": 75.0}", "assert calculate_average_scores([(\"601\", [85, 85, 85, 85, 85, 85])]) == {\"601\": 85.0}"], "function": "calculate_average_scores", "signature": "def calculate_average_scores(student_scores):", "score": 1.0, "domain": "generic"} {"id": "bfdb4611cc3cc6baa15641e0bb5f21a3", "problem": "You are given a string `s` and a list of string patterns `patterns`. Your task is to implement a function `find_occurrences(s, patterns)` that returns a list of dictionaries. Each dictionary should contain a pattern from the `patterns` list as the key and the number of non-overlapping occurrences of that pattern in `s` as the value. \n\n**Input:**\n- A string `s` (1 ≤ |s| ≤ 10^3) consisting of lowercase English letters.\n- A list of strings `patterns` (1 ≤ |patterns| ≤ 10^2), where each pattern consists of lowercase English letters and has a length of at most 10.\n\n**Output:**\n- A list of dictionaries, where each dictionary contains a pattern from `patterns` as the key and the number of non-overlapping occurrences of that pattern in `s` as the value.\n\n**Sample Input:**\n```\ns = \"hello world\"\npatterns = [\"hello\", \"world\"]\n```\n\n**Sample Output:**\n```\n[{\"hello\": 1}, {\"world\": 1}]\n```", "reference": "def find_occurrences(s, patterns):\n \"\"\"\n Returns a list of dictionaries with each pattern from the patterns list as the key\n and the number of non-overlapping occurrences of that pattern in the string s as the value.\n \n :param s: The input string where patterns are to be searched.\n :param patterns: A list of string patterns to search for in the input string.\n :return: A list of dictionaries with pattern counts.\n \"\"\"\n return [{pattern: s.count(pattern)} for pattern in patterns]", "tests": ["assert find_occurrences(\"hello world\", [\"hello\", \"world\"]) == [{\"hello\": 1}, {\"world\": 1}]", "assert find_occurrences(\"abababa\", [\"aba\", \"ab\"]) == [{\"aba\": 3}, {\"ab\": 3}]", "assert find_occurrences(\"test test test\", [\"test\"]) == [{\"test\": 3}]", "assert find_occurrences(\"aaaa\", [\"aa\"]) == [{\"aa\": 3}]", "assert find_occurrences(\"abc\", [\"d\", \"e\", \"f\"]) == [{\"d\": 0}, {\"e\": 0}, {\"f\": 0}]", "assert find_occurrences(\"\", [\"a\", \"b\", \"c\"]) == [{\"a\": 0}, {\"b\": 0}, {\"c\": 0}]", "assert find_occurrences(\"abcabcabc\", [\"abc\", \"cab\"]) == [{\"abc\": 3}, {\"cab\": 0}]", "assert find_occurrences(\"mississippi\", [\"issi\", \"iss\"]) == [{\"issi\": 1}, {\"iss\": 2}]", "assert find_occurrences(\"banana\", [\"na\", \"an\"]) == [{\"na\": 2}, {\"an\": 1}]", "assert find_occurrences(\"overlap\", [\"lap\", \"lapo\"]) == [{\"lap\": 1}, {\"lapo\": 0}]"], "function": "find_occurrences", "signature": "def find_occurrences(s, patterns):", "score": 0.6, "domain": "generic"} {"id": "b036a194e2435503758414ba484d5941", "problem": "You are given a list of date strings in the format \"MM/DD/YYYY\". Some of these date strings may be incomplete, missing either the day or the month. Your task is to identify the earliest complete date in the list. If no complete dates are present, return the index of the first date in the list. Consider leap years when validating dates in February.\n\n**Input:**\n- A list of strings, where each string represents a date in the format \"MM/DD/YYYY\" or a partial date.\n\n**Output:**\n- An integer representing the index of the earliest complete date in the list. If no complete dates are found, return the index of the first date.\n\n**Sample Input:**\n```python\n[\"02/\", \"02/15/2022\", \"01/\", \"12/31/2021\", \"03/01/2022\"]\n```\n\n**Sample Output:**\n```python\n3\n```\n\n**Sample Input:**\n```python\n[\"02/\", \"02/29/2020\", \"01/\", \"12/31/2021\", \"03/01/2022\"]\n```\n\n**Sample Output:**\n```python\n1\n```", "reference": "from datetime import datetime\n\ndef is_valid_date(date_str):\n \"\"\"\n Checks if the given date string is a valid date in the format 'MM/DD/YYYY'.\n \n :param date_str: A string representing a date.\n :return: True if the date is valid, False otherwise.\n \"\"\"\n try:\n datetime.strptime(date_str, '%m/%d/%Y')\n return True\n except ValueError:\n return False\n\ndef find_earliest_date(dates):\n \"\"\"\n Finds the index of the earliest complete date in the list. If no complete dates are found,\n returns the index of the first date.\n \n :param dates: A list of date strings.\n :return: The index of the earliest complete date or the index of the first date if no complete dates are found.\n \"\"\"\n earliest_date = None\n earliest_index = 0\n \n for index, date in enumerate(dates):\n if is_valid_date(date):\n current_date = datetime.strptime(date, '%m/%d/%Y')\n if earliest_date is None or current_date < earliest_date:\n earliest_date = current_date\n earliest_index = index\n\n return earliest_index if earliest_date is not None else 0", "tests": ["assert find_earliest_date([\"02/\", \"02/15/2022\", \"01/\", \"12/31/2021\", \"03/01/2022\"]) == 3", "assert find_earliest_date([\"02/\", \"02/29/2020\", \"01/\", \"12/31/2021\", \"03/01/2022\"]) == 1", "assert find_earliest_date([\"02/15/2022\", \"02/15/2021\", \"02/15/2023\"]) == 1", "assert find_earliest_date([\"02/15/2022\", \"02/15/2022\", \"02/15/2022\"]) == 0", "assert find_earliest_date([\"02/\", \"01/\", \"12/\", \"03/\"]) == 0", "assert find_earliest_date([\"\", \"\", \"\"]) == 0", "assert find_earliest_date([\"02/29/2024\", \"02/29/2020\", \"02/28/2021\"]) == 1", "assert find_earliest_date([\"02/29/2024\", \"02/28/2024\", \"02/29/2020\"]) == 1", "assert find_earliest_date([\"02/29/2024\", \"02/28/2024\", \"02/28/2024\"]) == 1", "assert find_earliest_date([\"02/29/2024\", \"02/29/2024\", \"02/29/2024\"]) == 0"], "function": "find_earliest_date", "signature": "def find_earliest_date(dates):", "score": 0.9, "domain": "generic"} {"id": "79a57e92c4b5286218a56090f7f93d7d", "problem": "You are given two lists: `data` and `weights`. Your task is to implement a function `weighted_mean(data, weights)` that computes the weighted mean of the `data` list using the corresponding `weights` list. The function should handle floating-point arithmetic issues and return `None` if the lengths of the lists do not match or if the sum of the weights is zero.\n\n**Input:**\n- `data`: A list of floating-point numbers.\n- `weights`: A list of floating-point numbers representing the weights for each data point.\n\n**Output:**\n- A floating-point number representing the weighted mean, or `None` if the input is invalid.\n\n**Sample Input:**\n```python\ndata = [1.0, 2.0, 3.0]\nweights = [0.2, 0.3, 0.5]\n```\n\n**Sample Output:**\n```python\n2.3\n```", "reference": "def weighted_mean(data, weights):\n \"\"\"\n Calculate the weighted mean of a given list of data points with corresponding weights.\n \n Parameters:\n data (list of float): The list of data points.\n weights (list of float): The list of weights corresponding to each data point.\n \n Returns:\n float or None: The weighted mean of the data points, or None if input is invalid.\n \"\"\"\n if len(data) != len(weights):\n return None\n \n total_weight = sum(weights)\n if total_weight == 0:\n return None\n \n weighted_sum = sum(d * w for d, w in zip(data, weights))\n return weighted_sum / total_weight", "tests": ["assert weighted_mean([1, 2, 3], [1, 1, 1]) == 2.0", "assert weighted_mean([10, 20, 30], [1, 2, 3]) == 23.333333333333332", "assert weighted_mean([1, 1, 1], [0, 0, 0]) == None", "assert weighted_mean([1, 2], [1]) == None", "assert weighted_mean([], []) == None", "assert weighted_mean([5, 10, 15], [2, 1, 2]) == 10.0", "assert weighted_mean([1.5, 2.5, 3.5], [1, 1, 1]) == 2.5", "assert weighted_mean([100, 200, 300], [0.1, 0.2, 0.7]) == 260.0", "assert weighted_mean([1, 2, 3, 4, 5], [5, 4, 3, 2, 1]) == 3.0", "assert weighted_mean([10, 20, 30, 40], [1, 1, 1, 1]) == 25.0"], "function": "weighted_mean", "signature": "def weighted_mean(data, weights):", "score": 0.9, "domain": "generic"} {"id": "0ed960c34304472cc4b54ad369843560", "problem": "You are given a list of `n` points in a 2D plane. Each point is represented as a tuple `(x, y)`. Your task is to find the indices of the two closest points in the list. The function should return a tuple `(i, j)` where `i` and `j` are the indices of the closest pair of points. If there are multiple pairs with the same minimum distance, return any one of them.\n\n**Input:**\n- A list of tuples, where each tuple represents the coordinates of a point in 2D space.\n\n**Output:**\n- A tuple `(i, j)` representing the indices of the two closest points.\n\n**Constraints:**\n- `2 <= n <= 1000`\n- `-10^9 <= x, y <= 10^9`\n\n**Sample Input:**\n```python\npoints = [(0, 0), (1, 1), (2, 2), (3, 3), (2, 1)]\n```\n\n**Sample Output:**\n```python\n(3, 4)\n```", "reference": "import math\n\ndef find_closest_pair(points):\n \"\"\"\n Finds the indices of the two closest points in a list of 2D points.\n\n :param points: List of tuples, where each tuple represents the coordinates of a point.\n :return: Tuple of two integers representing the indices of the closest pair of points.\n \"\"\"\n min_distance = float('inf')\n closest_pair = (0, 1)\n \n for i in range(len(points)):\n for j in range(i + 1, len(points)):\n x1, y1 = points[i]\n x2, y2 = points[j]\n distance = math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)\n if distance < min_distance:\n min_distance = distance\n closest_pair = (i, j)\n \n return closest_pair", "tests": ["assert find_closest_pair([(0, 0), (1, 1), (2, 2), (3, 3), (2, 1)]) in [(3, 4), (4, 3)]", "assert find_closest_pair([(0, 0), (1, 1)]) in [(0, 1), (1, 0)]", "assert find_closest_pair([(0, 0), (0, 1), (1, 0), (1, 1)]) in [(0, 1), (1, 0)]", "assert find_closest_pair([(1, 2), (3, 4), (5, 6), (7, 8), (1, 3)]) in [(0, 4), (4, 0)]", "assert find_closest_pair([(10, 10), (20, 20), (10, 11)]) in [(0, 2), (2, 0)]", "assert find_closest_pair([(0, 0), (0, 0)]) in [(0, 1), (1, 0)]", "assert find_closest_pair([(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6), (7, 7), (8, 8), (9, 9), (10, 10)]) in [(0, 1), (1, 0)]", "assert find_closest_pair([(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6), (7, 7), (8, 8), (9, 9), (10, 10), (1, 2)]) in [(0, 10), (10, 0)]", "assert find_closest_pair([(0, 0)]) == (0, 0) # Edge case with a single point", "assert find_closest_pair([(0, 0), (100, 100), (50, 50)]) in [(0, 2), (2, 0)]"], "function": "find_closest_pair", "signature": "def find_closest_pair(points):", "score": 0.8, "domain": "generic"} {"id": "345f1f64d331324d678782c8fa6e686f", "problem": "You are given a string `text` consisting of various characters. Your task is to implement a function `remove_special_characters(text: str) -> str` that processes this string and returns a new string with all special characters removed. Special characters are defined as any character that is not a letter (uppercase or lowercase, including non-ASCII letters), a digit, or a whitespace character.\n\nThe function should handle both ASCII and non-ASCII characters, and it should be able to remove special characters from any language. You must manually check each character to determine if it should be included in the result. Do not use any built-in string manipulation functions such as `str.replace()`, `str.isalpha()`, `str.isdigit()`, `str.isspace()`, etc.\n\n**Input:**\n- A single string `text` (1 ≤ len(text) ≤ 10^5).\n\n**Output:**\n- A string with all special characters removed.\n\n**Sample Input:**\n```\n\"Hello, World! 123 @#€ abc åäö\"\n```\n\n**Sample Output:**\n```\n\"Hello World 123 abc åäö\"\n```", "reference": "def remove_special_characters(text: str) -> str:\n \"\"\"\n Removes all special characters from the input string `text`.\n Special characters are defined as any character that is not a letter (uppercase or lowercase, including non-ASCII letters),\n a digit, or a whitespace character.\n \n :param text: The input string to process.\n :return: A new string with all special characters removed.\n \"\"\"\n result = []\n for char in text:\n if (0x41 <= ord(char) <= 0x5A) or (0x61 <= ord(char) <= 0x7A) or (0x30 <= ord(char) <= 0x39) or (0x20 == ord(char)):\n result.append(char)\n elif (0xC0 <= ord(char) <= 0xFF):\n result.append(char)\n return ''.join(result)\n\n# Example usage\nexample_text = \"Hello, World! 123 @#€ abc åäö\"\nclean_text = remove_special_characters(example_text)\nprint(clean_text) # Output: \"Hello World 123 abc åäö\"", "tests": ["assert remove_special_characters(\"Hello, World! 123 @#€ abc åäö\") == \"Hello World 123 abc åäö\"", "assert remove_special_characters(\"Python3.8\") == \"Python38\"", "assert remove_special_characters(\"NoSpecialCharsHere\") == \"NoSpecialCharsHere\"", "assert remove_special_characters(\"1234567890\") == \"1234567890\"", "assert remove_special_characters(\"!@#$%^&*()_+\") == \"\"", "assert remove_special_characters(\" Leading and trailing spaces \") == \" Leading and trailing spaces \"", "assert remove_special_characters(\"Café Münster\") == \"Café Münster\"", "assert remove_special_characters(\"こんにちは、世界!\") == \"こんにちは世界\"", "assert remove_special_characters(\"😊🚀\") == \"\"", "assert remove_special_characters(\"\") == \"\""], "function": "remove_special_characters", "signature": "def remove_special_characters(text: str) -> str:", "score": 0.9, "domain": "generic"} {"id": "2fb2af6a3303eca9732b8b0a98861af1", "problem": "You are tasked with implementing a recursive function named `calculate_factorial` in Python. This function should compute the factorial of a non-negative integer `n`. If the input `n` is negative, the function should return `None`. Your solution should be efficient and handle edge cases appropriately.\n\n**Sample Input and Output:**\n- Input: `5`\n- Output: `120`\n- Input: `-3`\n- Output: `None`\n- Input: `0`\n- Output: `1`", "reference": "def calculate_factorial(n):\n \"\"\"\n Computes the factorial of a given non-negative integer n using recursion.\n Returns None if the input is negative.\n \n :param n: Integer, the number to compute the factorial of\n :return: Integer, factorial of n if n is non-negative, otherwise None\n \"\"\"\n if n < 0:\n return None\n elif n == 0 or n == 1:\n return 1\n else:\n return n * calculate_factorial(n - 1)", "tests": ["assert calculate_factorial(5) == 120", "assert calculate_factorial(0) == 1", "assert calculate_factorial(1) == 1", "assert calculate_factorial(-1) == None", "assert calculate_factorial(-5) == None", "assert calculate_factorial(3) == 6", "assert calculate_factorial(10) == 3628800", "assert calculate_factorial(7) == 5040", "assert calculate_factorial(20) == 2432902008176640000", "assert calculate_factorial(15) == 1307674368000"], "function": "calculate_factorial", "signature": "def calculate_factorial(n):", "score": 1.0, "domain": "generic"} {"id": "0408e6f44fdd165f946f7e1196224277", "problem": "You are given a dictionary `d` where each key is associated with a value that can be a list, string, set, or any other type. Your task is to implement a function `sort_dict_values(d)` that returns a new dictionary with the same keys. The values should be sorted as follows:\n- If the value is a list, sort the list in ascending order.\n- If the value is a string, sort the characters in the string in ascending order.\n- If the value is a set, leave it unchanged.\n- For any other type, convert the value to a string, then sort the characters in the string in ascending order.\n\n**Input:**\n- A dictionary `d` with keys and values as described above.\n\n**Output:**\n- A new dictionary with the same keys and sorted values as per the rules above.\n\n**Sample Input:**\n```python\n{\"names\": [\"John\", \"Alice\", \"Bob\"], \"numbers\": {3, 1, 2}, \"mixed\": {1, \"a\", 2.5}}\n```\n\n**Sample Output:**\n```python\n{'names': ['Alice', 'Bob', 'John'], 'numbers': {1, 2, 3}, 'mixed': {1, 'a', 2.5}}\n```", "reference": "def sort_dict_values(d):\n \"\"\"\n Sorts the values of a dictionary according to specific rules:\n - Lists are sorted in ascending order.\n - Strings have their characters sorted in ascending order.\n - Sets remain unchanged.\n - Other types are converted to strings and then sorted.\n\n :param d: Dictionary with keys and values to be sorted.\n :return: A new dictionary with sorted values.\n \"\"\"\n def sort_value(value):\n if isinstance(value, list):\n return sorted(value)\n elif isinstance(value, str):\n return ''.join(sorted(value))\n elif isinstance(value, set):\n return value\n else:\n return ''.join(sorted(str(value)))\n \n return {key: sort_value(value) for key, value in d.items()}", "tests": ["assert sort_dict_values({\"names\": [\"John\", \"Alice\", \"Bob\"]}) == {\"names\": [\"Alice\", \"Bob\", \"John\"]}", "assert sort_dict_values({\"numbers\": {3, 1, 2}}) == {\"numbers\": {1, 2, 3}}", "assert sort_dict_values({\"mixed\": {1, \"a\", 2.5}}) == {\"mixed\": {1, \"a\", 2.5}}", "assert sort_dict_values({\"string\": \"cba\"}) == {\"string\": \"abc\"}", "assert sort_dict_values({\"integer\": 123}) == {\"integer\": \"123\"}", "assert sort_dict_values({\"float\": 3.14}) == {\"float\": \"13.4\"}", "assert sort_dict_values({\"empty_list\": []}) == {\"empty_list\": []}", "assert sort_dict_values({\"empty_string\": \"\"}) == {\"empty_string\": \"\"}", "assert sort_dict_values({\"multiple_types\": [3, \"abc\", 1.5]}) == {\"multiple_types\": [1.5, 3, \"abc\"]}", "assert sort_dict_values({\"nested_dict\": {\"key\": \"value\"}}) == {\"nested_dict\": \"{'key': 'value'}\"}"], "function": "sort_dict_values", "signature": "def sort_dict_values(d):", "score": 0.7, "domain": "generic"} {"id": "af75b4f18c78a6908f788134222897ce", "problem": "You are given a programming challenge to design a function `get_sha256_identifier` that computes a unique identifier for a given input. The identifier is derived from the SHA-256 hash of the input. The function must adhere to the following rules:\n\n1. If the input is an empty string, compute the SHA-256 hash of the string \"EMPTY\".\n2. If the input is not a string, convert it to a string before hashing.\n3. The function should return the hexadecimal representation of the SHA-256 hash.\n4. The function must be thread-safe, ensuring consistent results when called by multiple threads simultaneously.\n\nYour function should handle various input types, including strings, bytes, and other data types.\n\n**Sample Input/Output:**\n\n- Input: `\"\"`\n - Output: `\"5d41402abc4b2a76b9719d911017c592\"`\n- Input: `12345`\n - Output: `\"827ccb0eea8a706c4c34a16891f84e7b\"`\n- Input: `b\"hello\"`\n - Output: `\"2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824\"`", "reference": "import hashlib\nimport threading\n\n# Creating a thread-safe lock\nlock = threading.Lock()\n\ndef get_sha256_identifier(input_data):\n \"\"\"\n Computes a SHA-256 hash-based unique identifier for the given input.\n \n Parameters:\n input_data (any): The input data to be hashed. Can be of any type.\n \n Returns:\n str: The hexadecimal representation of the SHA-256 hash.\n \"\"\"\n with lock: # Ensuring thread-safe execution\n if not isinstance(input_data, str):\n input_data = str(input_data)\n \n if input_data == \"\":\n input_data = \"EMPTY\"\n \n # Creating a SHA-256 hash object\n sha256_hash = hashlib.sha256()\n \n # Updating the hash object with the bytes of the input string\n sha256_hash.update(input_data.encode('utf-8'))\n \n # Returning the hexadecimal representation of the hash\n return sha256_hash.hexdigest()", "tests": ["assert get_sha256_identifier(\"\") == hashlib.sha256(\"EMPTY\".encode('utf-8')).hexdigest()", "assert get_sha256_identifier(\"hello\") == hashlib.sha256(\"hello\".encode('utf-8')).hexdigest()", "assert get_sha256_identifier(123) == hashlib.sha256(\"123\".encode('utf-8')).hexdigest()", "assert get_sha256_identifier(b\"bytes\") == hashlib.sha256(\"b'bytes'\".encode('utf-8')).hexdigest()", "assert get_sha256_identifier(None) == hashlib.sha256(\"None\".encode('utf-8')).hexdigest()", "assert get_sha256_identifier(True) == hashlib.sha256(\"True\".encode('utf-8')).hexdigest()", "assert get_sha256_identifier([1, 2, 3]) == hashlib.sha256(\"[1, 2, 3]\".encode('utf-8')).hexdigest()", "assert get_sha256_identifier({\"key\": \"value\"}) == hashlib.sha256(\"{'key': 'value'}\".encode('utf-8')).hexdigest()", "assert get_sha256_identifier(3.14159) == hashlib.sha256(\"3.14159\".encode('utf-8')).hexdigest()", "assert get_sha256_identifier(\" \") == hashlib.sha256(\" \".encode('utf-8')).hexdigest()"], "function": "get_sha256_identifier", "signature": "def get_sha256_identifier(input_data):", "score": 1.0, "domain": "generic"} {"id": "619cde5371054244ad817b28f37627df", "problem": "You are given a list of integers. Your task is to implement a function that removes all duplicate elements from the list while preserving the order of their first appearance. The function should return a new list containing only the unique elements.\n\n**Input:**\n- A list of integers, `input_list`.\n\n**Output:**\n- A list of integers, `unique_list`, where each element appears only once and in the order of their first occurrence in `input_list`.\n\n**Sample Input:**\n```python\n[4, 5, 6, 4, 7, 5, 8, 9, 6]\n```\n\n**Sample Output:**\n```python\n[4, 5, 6, 7, 8, 9]\n```", "reference": "def remove_duplicates(input_list):\n \"\"\"\n Removes all duplicate elements from the input list while preserving the order of their first appearance.\n\n Parameters:\n input_list (list of int): The list of integers from which duplicates need to be removed.\n\n Returns:\n list of int: A new list containing only the unique elements in the order of their first occurrence.\n \"\"\"\n seen = set()\n unique_list = []\n for element in input_list:\n if element not in seen:\n seen.add(element)\n unique_list.append(element)\n return unique_list", "tests": ["assert remove_duplicates([1, 2, 3, 2, 1]) == [1, 2, 3]", "assert remove_duplicates([4, 5, 6, 4, 5, 6]) == [4, 5, 6]", "assert remove_duplicates([7, 8, 9]) == [7, 8, 9]", "assert remove_duplicates([]) == []", "assert remove_duplicates([10, 10, 10, 10]) == [10]", "assert remove_duplicates([1, 1, 2, 2, 3, 3, 4, 4]) == [1, 2, 3, 4]", "assert remove_duplicates([1, 2, 3, 4, 5, 6, 7, 8, 9, 1]) == [1, 2, 3, 4, 5, 6, 7, 8, 9]", "assert remove_duplicates(['a', 'b', 'c', 'a', 'b', 'c']) == ['a', 'b', 'c']", "assert remove_duplicates(['x', 'y', 'z']) == ['x', 'y', 'z']", "assert remove_duplicates([True, False, True, True, False]) == [True, False]"], "function": "remove_duplicates", "signature": "def remove_duplicates(input_list):", "score": 1.0, "domain": "algorithmic"} {"id": "38334c54c0ec99012f68bb4b2a1d9ec3", "problem": "You are tasked with implementing a function `parse_json_file` that reads a JSON file and returns the data as a dictionary. Your function should handle potential errors such as file not found or invalid JSON format. The function should be robust enough to handle any other unexpected errors gracefully.\n\n**Function Signature:**\n```python\ndef parse_json_file(file_name: str = 'data.json') -> dict:\n```\n\n**Input:**\n- A string `file_name` representing the name of the JSON file to be read. The default file name is \"data.json\".\n\n**Output:**\n- A dictionary containing the data from the JSON file if successful.\n- `None` if an error occurs during file reading or parsing.\n\n**Sample Input:**\n- Assume a file named \"data.json\" exists with the following content:\n```json\n{\n \"name\": \"John Doe\",\n \"age\": 30,\n \"is_student\": false\n}\n```\n\n**Sample Output:**\n- The function should return:\n```python\n{\n \"name\": \"John Doe\",\n \"age\": 30,\n \"is_student\": False\n}\n```", "reference": "import json\n\ndef parse_json_file(file_name: str = 'data.json') -> dict:\n \"\"\"\n Reads a JSON file and returns the data as a dictionary.\n \n Parameters:\n file_name (str): The name of the JSON file to be read. Defaults to 'data.json'.\n \n Returns:\n dict: The data from the JSON file if successful, None otherwise.\n \"\"\"\n try:\n with open(file_name, 'r', encoding='utf-8') as file:\n data = json.load(file)\n return data\n except FileNotFoundError:\n print(f\"Error: {file_name} not found.\")\n except json.JSONDecodeError:\n print(f\"Error: {file_name} is not a valid JSON file.\")\n except Exception as e:\n print(f\"An unexpected error occurred: {e}\")\n return None", "tests": ["assert parse_json_file(\"non_existent_file.json\") == None", "assert parse_json_file(\"invalid_json_file.json\") == None", "assert parse_json_file(\"data.json\") == {\"key\": \"value\"}", "assert parse_json_file(\"empty_file.json\") == {}", "assert parse_json_file(\"data.json\") != []", "assert parse_json_file(\"data.json\") != \"string\"", "assert parse_json_file(\"data.json\") != 12345", "assert parse_json_file(\"data.json\") != {\"wrong_key\": \"wrong_value\"}", "assert parse_json_file(\"data.json\") == {\"nested\": {\"key\": \"value\"}}", "assert parse_json_file(\"data.json\") == {\"list\": [1, 2, 3, 4, 5]}"], "function": "parse_json_file", "signature": "def parse_json_file(file_name: str = 'data.json') -> dict:", "score": 0.5, "domain": "generic"} {"id": "7778ec5133c14ee75c4b4d3ba71e163d", "problem": "You are given a dataset consisting of `N` text documents. Your task is to compute the Term Frequency-Inverse Document Frequency (TF-IDF) scores for each word in each document. The TF-IDF score for a word in a document is calculated using the formula: `TF-IDF = TF * IDF`, where `TF` is the term frequency of the word in the document, and `IDF` is the inverse document frequency of the word across all documents. The term frequency `TF` of a word in a document is the number of times the word appears in the document divided by the total number of words in the document. The inverse document frequency `IDF` of a word is the logarithm of the total number of documents `N` divided by the number of documents containing the word plus one.\n\nWrite a function `calculate_tf_idf(documents)` that takes a list of strings `documents` as input and returns a dictionary where the keys are the document indices and the values are dictionaries containing the word indices and their corresponding TF-IDF scores.\n\n**Input:**\n- A list of strings `documents` where each string represents a document.\n\n**Output:**\n- A dictionary where the keys are document indices and the values are dictionaries containing word indices and their corresponding TF-IDF scores.\n\n**Sample Input:**\n```python\ndocuments = [\n \"text mining is fascinating\",\n \"fascinating text mining techniques\",\n \"data mining are text-based techniques\"\n]\n```\n\n**Sample Output:**\n```python\n{\n 0: {'text': 0.28768207245178085, 'mining': 0.28768207245178085, 'is': 0.5753641449035617, 'fascinating': 0.28768207245178085},\n 1: {'fascinating': 0.28768207245178085, 'text': 0.28768207245178085, 'mining': 0.28768207245178085, 'techniques': 0.5753641449035617},\n 2: {'data': 0.5753641449035617, 'mining': 0.28768207245178085, 'are': 0.5753641449035617, 'text-based': 0.5753641449035617, 'techniques': 0.5753641449035617}\n}\n```", "reference": "import math\nfrom collections import defaultdict, Counter\n\ndef calculate_tf_idf(documents):\n \"\"\"\n Calculate the Term Frequency-Inverse Document Frequency (TF-IDF) scores for each word in each document.\n \n Parameters:\n documents (list of str): A list of strings where each string represents a document.\n \n Returns:\n dict: A dictionary where the keys are document indices and the values are dictionaries containing word indices and their corresponding TF-IDF scores.\n \"\"\"\n N = len(documents) # total number of documents\n\n # Count the word appearance in each document\n doc_word_count = [Counter(doc.split()) for doc in documents]\n \n # Count the number of documents each word appears in\n word_doc_count = defaultdict(int)\n for doc in doc_word_count:\n for word in doc.keys():\n word_doc_count[word] += 1\n\n # Calculate IDF for each word\n idf = {word: math.log(N / (word_doc_count[word] + 1)) for word in word_doc_count}\n\n # Calculate TF-IDF\n tf_idf = defaultdict(dict)\n\n for i, doc in enumerate(doc_word_count):\n total_terms = sum(doc.values()) # number of terms in the document\n for word, freq in doc.items():\n tf = freq / total_terms # term frequency\n tf_idf[i][word] = tf * idf[word]\n\n return tf_idf", "tests": ["assert calculate_tf_idf([\"hello world\", \"world of code\"]) == {0: {'hello': 0.5 * math.log(2 / (1 + 1)), 'world': 0.5 * math.log(2 / (2 + 1))}, 1: {'world': 0.5 * math.log(2 / (2 + 1)), 'of': 0.5 * math.log(2 / (1 + 1)), 'code': 0.5 * math.log(2 / (1 + 1))}}", "assert calculate_tf_idf([\"a a a\", \"b b\", \"c\"]) == {0: {'a': 1.0 * math.log(3 / (1 + 1))}, 1: {'b': 1.0 * math.log(3 / (1 + 1))}, 2: {'c': 1.0 * math.log(3 / (1 + 1))}}", "assert calculate_tf_idf([\"single\"]) == {0: {'single': 1.0 * math.log(1 / (1 + 1))}}", "assert calculate_tf_idf([]) == {}", "assert calculate_tf_idf([\"repeat repeat\", \"repeat\"]) == {0: {'repeat': 1.0 * math.log(2 / (2 + 1))}, 1: {'repeat': 1.0 * math.log(2 / (2 + 1))}}", "assert calculate_tf_idf([\"unique words\", \"different words\"]) == {0: {'unique': 0.5 * math.log(2 / (1 + 1)), 'words': 0.5 * math.log(2 / (2 + 1))}, 1: {'different': 0.5 * math.log(2 / (1 + 1)), 'words': 0.5 * math.log(2 / (2 + 1))}}", "assert calculate_tf_idf([\"one\", \"two\", \"three\"]) == {0: {'one': 1.0 * math.log(3 / (1 + 1))}, 1: {'two': 1.0 * math.log(3 / (1 + 1))}, 2: {'three': 1.0 * math.log(3 / (1 + 1))}}", "assert calculate_tf_idf([\"same same\", \"same same\", \"same same\"]) == {0: {'same': 1.0 * math.log(3 / (3 + 1))}, 1: {'same': 1.0 * math.log(3 / (3 + 1))}, 2: {'same': 1.0 * math.log(3 / (3 + 1))}}", "assert calculate_tf_idf([\"a b c\", \"a b\", \"a\"]) == {0: {'a': 1/3 * math.log(3 / (3 + 1)), 'b': 1/3 * math.log(3 / (2 + 1)), 'c': 1/3 * math.log(3 / (1 + 1))}, 1: {'a': 1/2 * math.log(3 / (3 + 1)), 'b': 1/2 * math.log(3 / (2 + 1))}, 2: {'a': 1.0 * math.log(3 / (3 + 1))}}", "assert calculate_tf_idf([\"doc1 word1\", \"doc2 word2\", \"doc3 word3\", \"doc4 word4\"]) == {0: {'doc1': 0.5 * math.log(4 / (1 + 1)), 'word1': 0.5 * math.log(4 / (1 + 1))}, 1: {'doc2': 0.5 * math.log(4 / (1 + 1)), 'word2': 0.5 * math.log(4 / (1 + 1))}, 2: {'doc3': 0.5 * math.log(4 / (1 + 1)), 'word3': 0.5 * math.log(4 / (1 + 1))}, 3: {'doc4': 0.5 * math.log(4 / (1 + 1)), 'word4': 0.5 * math.log(4 / (1 + 1))}}"], "function": "calculate_tf_idf", "signature": "def calculate_tf_idf(documents):", "score": 0.9, "domain": "generic"} {"id": "af8118f241803609f348d42e581ce2ae", "problem": "You are given a string `s`. Your task is to implement a function `count_vowels(s)` that returns the number of vowels in the string, considering both uppercase and lowercase vowels. The function should be case-insensitive.\n\n**Input:**\n- A single string `s` (1 ≤ |s| ≤ 10^5), which may contain letters, digits, punctuation, and whitespace.\n\n**Output:**\n- An integer representing the number of vowels in the string.\n\n**Sample Input:**\n```\n\"Hello, World!\"\n```\n\n**Sample Output:**\n```\n3\n```", "reference": "def count_vowels(s):\n \"\"\"\n Counts the number of vowels in the given string, ignoring case.\n\n Parameters:\n s (str): The input string.\n\n Returns:\n int: The number of vowels in the string.\n \"\"\"\n vowels = set('aeiouAEIOU')\n return sum(1 for char in s if char in vowels)", "tests": ["assert count_vowels(\"Hello, World!\") == 3", "assert count_vowels(\"Python Programming\") == 4", "assert count_vowels(\"AEIOUaeiou\") == 10", "assert count_vowels(\"\") == 0", "assert count_vowels(\"bcdfghjklmnpqrstvwxyz\") == 0", "assert count_vowels(\"abcdefghijklmnopqrstuvwxyz\") == 5", "assert count_vowels(\"A quick brown fox jumps over the lazy dog\") == 11", "assert count_vowels(\"1234567890\") == 0", "assert count_vowels(\"!@#$%^&*()\") == 0", "assert count_vowels(\"HELLO WORLD\") == 3"], "function": "count_vowels", "signature": "def count_vowels(s):", "score": 1.0, "domain": "generic"} {"id": "c3d8cb7796d06d35d8e63ec16442796b", "problem": "You are given a binary tree represented as a nested list in Python. Each node in the tree is a list containing three elements: the node's value, its left subtree, and its right subtree. The left and right subtrees are also represented as nested lists in the same format, or as empty lists if the subtree is absent. Your task is to write a function that calculates the total sum of all the values in the tree.\n\n**Input:**\n- A nested list representing a binary tree. Each node is a list `[value, left_subtree, right_subtree]`.\n\n**Output:**\n- An integer representing the total sum of all the values in the tree.\n\n**Sample Input:**\n```\n[1, [2, [3, [], []], []], [4, [], [5, [], []]]]\n```\n\n**Sample Output:**\n```\n15\n```", "reference": "def sum_binary_tree(tree):\n \"\"\"\n Calculate the total sum of all the values in a binary tree represented as a nested list.\n\n :param tree: A nested list representing a binary tree, where each node is a list [value, left_subtree, right_subtree].\n :return: An integer representing the total sum of all the values in the tree.\n \"\"\"\n if not tree:\n return 0\n value, left, right = tree\n return value + sum_binary_tree(left) + sum_binary_tree(right)\n\n# Test the function with the given example\ntree = [1, [2, [3, [], []], []], [4, [], [5, [], []]]]\nprint(sum_binary_tree(tree)) # Output should be 15", "tests": ["assert sum_binary_tree([1, [2, [3, [], []], []], [4, [], [5, [], []]]]) == 15", "assert sum_binary_tree([1, [], []]) == 1", "assert sum_binary_tree([0, [0, [0, [], []], []], [0, [], [0, [], []]]]) == 0", "assert sum_binary_tree([10, [20, [30, [], []], []], [40, [], [50, [], []]]]) == 150", "assert sum_binary_tree([5, [10, [15, [], []], [20, [], []]], [25, [30, [], []], [35, [], []]]]) == 140", "assert sum_binary_tree([]) == 0", "assert sum_binary_tree([100, [], []]) == 100", "assert sum_binary_tree([1, [2, [4, [], []], [5, [], []]], [3, [6, [], []], [7, [], []]]]) == 28", "assert sum_binary_tree([1, [2, [3, [4, [], []], []], []], []]) == 10", "assert sum_binary_tree([1, [], [2, [], [3, [], [4, [], [5, [], []]]]]]) == 15"], "function": "sum_binary_tree", "signature": "def sum_binary_tree(tree):", "score": 1.0, "domain": "algorithmic"} {"id": "0fd24fca74bd8a5f5128b4b2fb8b874f", "problem": "You are given a string `s`. Your task is to implement a function `remove_vowels` that processes this string by removing all vowels (a, e, i, o, u) in a case-insensitive manner and also discards any whitespace characters. The function should return the resulting string.\n\n**Input:**\n- A single string `s` (1 ≤ |s| ≤ 10^5), which may contain uppercase and lowercase letters, digits, punctuation, and whitespace.\n\n**Output:**\n- A string with all vowels and whitespace characters removed.\n\n**Sample Input:**\n```\n\"Remove the vowels from this sentence, please.\"\n```\n\n**Sample Output:**\n```\n\"Rmvthvwlfrmsnthscn,plss.\"\n```", "reference": "def remove_vowels(input_string):\n \"\"\"\n Removes all vowels (case-insensitive) and whitespace characters from the input string.\n\n Parameters:\n input_string (str): The string from which vowels and whitespace should be removed.\n\n Returns:\n str: The resulting string with vowels and whitespace removed.\n \"\"\"\n vowels = \"aeiouAEIOU\"\n return ''.join([char for char in input_string if char not in vowels and not char.isspace()])\n\n# Example usage\nexample_string = \"Remove the vowels from this sentence, please.\"\nresulting_string = remove_vowels(example_string)\nprint(resulting_string) # Output: \"Rmvthvwlfrmsnthscn,plss.\"", "tests": ["assert remove_vowels(\"Hello World\") == \"HllWrld\"", "assert remove_vowels(\"AEIOUaeiou\") == \"\"", "assert remove_vowels(\"Python Programming\") == \"PythnPrgrmmng\"", "assert remove_vowels(\" Leading and trailing spaces \") == \"Ldngndtrllngspcs\"", "assert remove_vowels(\"Quick brown fox\") == \"Qckbrwnfx\"", "assert remove_vowels(\"abcdefghijklmnopqrstuvwxyz\") == \"bcdfghjklmnpqrstvwxyz\"", "assert remove_vowels(\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\") == \"BCDFGHJKLMNPQRSTVWXYZ\"", "assert remove_vowels(\"12345\") == \"12345\"", "assert remove_vowels(\"!@#$%^&*()\") == \"!@#$%^&*()\"", "assert remove_vowels(\"\") == \"\""], "function": "remove_vowels", "signature": "def remove_vowels(input_string):", "score": 0.9, "domain": "generic"} {"id": "6db50758dc0c3a2c012471b154567eb1", "problem": "You are given a JSON file named `movies.json` located in the same directory as your script. The file contains a list of movies, where each movie is represented as a dictionary with the following keys: `title`, `year`, and `genre`. Your task is to write a Python script that reads this JSON file, filters the movies by a specified genre, and prints the titles of the movies that belong to that genre. If the genre is not found or the JSON file is not properly formatted, your script should handle these cases gracefully and print an appropriate error message.\n\n**Sample Input (movies.json):**\n```json\n[\n {\"title\": \"Die Hard\", \"year\": 1988, \"genre\": \"Action\"},\n {\"title\": \"The Godfather\", \"year\": 1972, \"genre\": \"Crime\"},\n {\"title\": \"Mad Max: Fury Road\", \"year\": 2015, \"genre\": \"Action\"}\n]\n```\n\n**Sample Output for Genre \"Action\":**\n```\nMovies in the genre 'Action':\nDie Hard\nMad Max: Fury Road\n```\n\n**Sample Output for Genre \"Drama\":**\n```\nNo movies found in the genre: Drama\n```\n\n**Sample Output for Invalid JSON:**\n```\nError reading file movies.json: Expecting value: line 1 column 1 (char 0)\n```", "reference": "import json\n\ndef filter_movies_by_genre(json_filename, genre):\n \"\"\"\n Filters movies by a specified genre and prints their titles.\n \n Args:\n json_filename (str): The name of the JSON file containing the list of movies.\n genre (str): The genre to filter the movies by.\n \"\"\"\n try:\n with open(json_filename, 'r') as file:\n movies = json.load(file)\n except (FileNotFoundError, json.JSONDecodeError) as e:\n print(f\"Error reading file {json_filename}: {e}\")\n return\n\n if not isinstance(movies, list):\n print(\"The JSON file does not contain a list of movies.\")\n return\n\n filtered_movies = [movie['title'] for movie in movies if movie.get('genre') == genre]\n\n if not filtered_movies:\n print(f\"No movies found in the genre: {genre}\")\n else:\n print(f\"Movies in the genre '{genre}':\")\n for title in filtered_movies:\n print(title)\n\n# Usage\nfilter_movies_by_genre('movies.json', 'Action')", "tests": ["assert filter_movies_by_genre('movies.json', 'Action') is None", "assert filter_movies_by_genre('nonexistent.json', 'Action') is None", "assert filter_movies_by_genre('movies.json', 'NonExistentGenre') is None", "assert filter_movies_by_genre('movies.json', '') is None", "assert filter_movies_by_genre('movies.json', 'Drama') is None", "assert filter_movies_by_genre('movies.json', 'Comedy') is None", "assert filter_movies_by_genre('movies.json', 'Horror') is None", "assert filter_movies_by_genre('movies.json', 'Sci-Fi') is None", "assert filter_movies_by_genre('movies.json', 'Thriller') is None", "assert filter_movies_by_genre('movies.json', 'Romance') is None"], "function": "filter_movies_by_genre", "signature": "def filter_movies_by_genre(json_filename, genre):", "score": 1.0, "domain": "generic"} {"id": "260f467e0977b9a557964a3259fe3e3d", "problem": "You are given a string `s`. Your task is to implement a function that returns a new string where each alphabetic character in `s` is shifted by 3 positions forward in the ASCII table. Non-alphabetic characters should remain unchanged. The function should handle both uppercase and lowercase letters appropriately.\n\n**Sample Input:**\n```\n\"Hello, World!\"\n```\n\n**Sample Output:**\n```\n\"Khoor, Zruog!\"\n```", "reference": "def shift_string(s):\n \"\"\"\n Shifts each alphabetic character in the string s by 3 positions forward in the ASCII table.\n Non-alphabetic characters remain unchanged.\n\n :param s: Input string to be shifted.\n :return: New string with shifted alphabetic characters.\n \"\"\"\n result = []\n for char in s:\n if char.isalpha():\n offset = 65 if char.isupper() else 97\n shifted_char = chr((ord(char) - offset + 3) % 26 + offset)\n result.append(shifted_char)\n else:\n result.append(char)\n return ''.join(result)\n\n# Test the function\nprint(shift_string(\"Hello, World!\")) # Outputs: \"Khoor, Zruog!\"", "tests": ["assert shift_string(\"Hello, World!\") == \"Khoor, Zruog!\"", "assert shift_string(\"abc\") == \"def\"", "assert shift_string(\"xyz\") == \"abc\"", "assert shift_string(\"ABC\") == \"DEF\"", "assert shift_string(\"XYZ\") == \"ABC\"", "assert shift_string(\"123\") == \"123\"", "assert shift_string(\"!@#\") == \"!@#\"", "assert shift_string(\"aBcDeFgHiJkLmNoPqRsTuVwXyZ\") == \"dEfGhIjKlMnOpQrStUvWxYzAbCdEf\"", "assert shift_string(\"Python3.8\") == \"Sbwkrq3.8\"", "assert shift_string(\"\") == \"\""], "function": "shift_string", "signature": "def shift_string(s):", "score": 0.9, "domain": "algorithmic"} {"id": "8fa51edb8de1441aa0e5ec751864cd74", "problem": "You are given a string `s` consisting of digits representing a large integer. Your task is to find the maximum sum of any contiguous substring of length `n` within `s`. You must not use any built-in functions for summation or slicing. If `n` is greater than the length of `s` or `s` contains non-digit characters, return \"Invalid input\".\n\n**Sample Input:**\n```\ns = \"123456789\"\nn = 3\n```\n\n**Sample Output:**\n```\n24\n```", "reference": "def max_sum_of_substring(s, n):\n \"\"\"\n Finds the maximum sum of any contiguous substring of length n in the string s.\n \n Parameters:\n s (str): A string consisting of digits.\n n (int): The length of the substring to consider.\n \n Returns:\n int or str: The maximum sum of any contiguous substring of length n, or \"Invalid input\" if conditions are not met.\n \"\"\"\n if n > len(s) or not s.isdigit():\n return \"Invalid input\"\n \n max_sum = 0\n current_sum = 0\n \n for i in range(n):\n current_sum += int(s[i])\n \n max_sum = current_sum\n \n for i in range(n, len(s)):\n current_sum += int(s[i]) - int(s[i - n])\n \n if current_sum > max_sum:\n max_sum = current_sum\n \n return max_sum\n\n# Example usage:\ns = \"123456789\"\nn = 3\nprint(max_sum_of_substring(s, n)) # Output: 24", "tests": ["assert max_sum_of_substring(\"123456789\", 3) == 24", "assert max_sum_of_substring(\"987654321\", 2) == 17", "assert max_sum_of_substring(\"111111111\", 4) == 4", "assert max_sum_of_substring(\"505050505\", 5) == 25", "assert max_sum_of_substring(\"123\", 4) == \"Invalid input\"", "assert max_sum_of_substring(\"abc\", 2) == \"Invalid input\"", "assert max_sum_of_substring(\"12345\", 0) == \"Invalid input\"", "assert max_sum_of_substring(\"\", 1) == \"Invalid input\"", "assert max_sum_of_substring(\"9\", 1) == 9", "assert max_sum_of_substring(\"1234567890\", 10) == 45"], "function": "max_sum_of_substring", "signature": "def max_sum_of_substring(s, n):", "score": 0.8, "domain": "generic"} {"id": "f708a28e9f8035d22963df2eb16534cc", "problem": "You are given a list of integers `lst`. Your task is to implement a function `find_duplicate_indices(lst)` that identifies all integers in the list that appear at least three times and returns a list of lists. Each sublist should contain the indices of all occurrences of such integers in the order they appear in the input list. The order of the sublists should correspond to the order of the first occurrence of each integer that meets the criteria.\n\n**Constraints:**\n- The length of the list `lst` will be between 1 and 10^5.\n- Each integer in the list will be between -10^9 and 10^9.\n\n**Sample Input:**\n```python\nlst = [1, 2, 3, 2, 4, 2, 5, 3, 3, 3, 6]\n```\n\n**Sample Output:**\n```python\n[[1, 3, 5], [2, 7, 8, 9]]\n```", "reference": "def find_duplicate_indices(lst):\n \"\"\"\n Finds indices of integers that appear at least three times in the list.\n \n Parameters:\n lst (list of int): The input list of integers.\n \n Returns:\n list of list of int: A list of lists where each sublist contains the indices of integers\n that appear at least three times in the input list.\n \"\"\"\n index_dict = {}\n for index, value in enumerate(lst):\n if value in index_dict:\n index_dict[value].append(index)\n else:\n index_dict[value] = [index]\n \n result = [indices for value, indices in index_dict.items() if len(indices) >= 3]\n \n return result", "tests": ["assert find_duplicate_indices([1, 2, 3, 4, 5]) == []", "assert find_duplicate_indices([1, 2, 2, 3, 3, 3, 4, 4, 4, 4]) == [[3, 4, 5], [6, 7, 8, 9]]", "assert find_duplicate_indices([1, 1, 1, 2, 2, 3, 3, 3, 3]) == [[0, 1, 2], [6, 7, 8, 9]]", "assert find_duplicate_indices([5, 5, 5, 5, 5, 5]) == [[0, 1, 2, 3, 4, 5]]", "assert find_duplicate_indices([1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5]) == []", "assert find_duplicate_indices([10, 20, 10, 20, 10, 20, 10]) == [[0, 2, 4, 6]]", "assert find_duplicate_indices([7, 8, 9, 7, 8, 9, 7, 8, 9, 7]) == [[0, 3, 6, 9]]", "assert find_duplicate_indices([1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10]) == []", "assert find_duplicate_indices([1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2]) == []", "assert find_duplicate_indices([1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3]) == [[0, 1, 2], [3, 4, 5, 6], [7, 8, 9, 10, 11]]"], "function": "find_duplicate_indices", "signature": "def find_duplicate_indices(lst):", "score": 0.5, "domain": "generic"} {"id": "188d73162086251280696215f3b93e51", "problem": "You are given a list of integers. Your task is to implement a function `sum_of_pairs` that calculates the sum of all unique pairs of numbers in the list. A pair is considered unique if the two numbers in the pair are distinct. For example, for the input list `[1, 2, 3]`, the function should return `12` because the sum of the unique pairs `(1, 2)`, `(1, 3)`, and `(2, 3)` is `3 + 4 + 5 = 12`.\n\n**Sample Input 1:**\n```\n[1, 2, 3]\n```\n**Sample Output 1:**\n```\n12\n```\n\n**Sample Input 2:**\n```\n[1, 1, 1]\n```\n**Sample Output 2:**\n```\n0\n```\n\n**Sample Input 3:**\n```\n[1, 2, 2, 3]\n```\n**Sample Output 3:**\n```\n16\n```", "reference": "def sum_of_pairs(numbers):\n \"\"\"\n Calculate the sum of all unique pairs of numbers in the list.\n \n :param numbers: List of integers\n :return: Sum of all unique pairs\n \"\"\"\n unique_pairs_sum = 0\n n = len(numbers)\n \n for i in range(n):\n for j in range(i + 1, n):\n if numbers[i] != numbers[j]:\n unique_pairs_sum += numbers[i] + numbers[j]\n \n return unique_pairs_sum\n\n# Test cases\nprint(sum_of_pairs([1, 2, 3])) # Output: 12\nprint(sum_of_pairs([1, 1, 1])) # Output: 0\nprint(sum_of_pairs([1, 2, 2, 3])) # Output: 16", "tests": ["assert sum_of_pairs([1, 2, 3]) == 12", "assert sum_of_pairs([1, 1, 1]) == 0", "assert sum_of_pairs([1, 2, 2, 3]) == 16", "assert sum_of_pairs([5, 5, 5, 5]) == 0", "assert sum_of_pairs([1, 2, 3, 4, 5]) == 44", "assert sum_of_pairs([10, 20, 30]) == 60", "assert sum_of_pairs([]) == 0", "assert sum_of_pairs([1]) == 0", "assert sum_of_pairs([1, 2]) == 3", "assert sum_of_pairs([0, 0, 0, 1]) == 0"], "function": "sum_of_pairs", "signature": "def sum_of_pairs(numbers):", "score": 0.6, "domain": "generic"} {"id": "6378bf5264381d09a3d58536b90eb79f", "problem": "You are given a list of integers `nums`. Your task is to determine the number of ways to partition the list into two subsets such that the sum of the elements in both subsets is equal. The list can contain both positive and negative integers. If no such partition exists, return 0.\n\n**Input:**\n- A list of integers `nums` (1 ≤ len(nums) ≤ 100, -100 ≤ nums[i] ≤ 100).\n\n**Output:**\n- An integer representing the number of ways to partition the list into two subsets with equal sum.\n\n**Sample Input:**\n```\n[1, 5, 11, 5]\n```\n\n**Sample Output:**\n```\n2\n```", "reference": "def count_partitions(nums):\n \"\"\"\n Counts the number of ways to partition the list into two subsets with equal sum.\n \n :param nums: List of integers\n :return: Number of ways to partition the list into two subsets with equal sum\n \"\"\"\n total_sum = sum(nums)\n \n if total_sum % 2 != 0:\n return 0\n \n target = total_sum // 2\n n = len(nums)\n \n dp = [[0] * (target + 1) for _ in range(n + 1)]\n \n for i in range(n + 1):\n dp[i][0] = 1\n \n for i in range(1, n + 1):\n for j in range(target + 1):\n dp[i][j] = dp[i - 1][j]\n if j >= nums[i - 1]:\n dp[i][j] += dp[i - 1][j - nums[i - 1]]\n \n return dp[n][target]\n\n# Example usage with the provided test case\nnums = [1, 5, 11, 5]\nprint(count_partitions(nums)) # Output should be 2", "tests": ["assert count_partitions([1, 5, 11, 5]) == 2", "assert count_partitions([1, 2, 3, 5]) == 0", "assert count_partitions([0, 0, 0, 0]) == 16", "assert count_partitions([1, 2, 3, 4, 5, 6]) == 32", "assert count_partitions([-1, -1, 1, 1]) == 6", "assert count_partitions([100]) == 0", "assert count_partitions([0]) == 1", "assert count_partitions([1, 1, 1, 1, 1, 1, 1, 1, 1, 1]) == 512", "assert count_partitions([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) == 512", "assert count_partitions([]) == 1"], "function": "count_partitions", "signature": "def count_partitions(nums):", "score": 0.5, "domain": "algorithmic"} {"id": "4bf8a0e84c95d81ce4e9531bb39df0b8", "problem": "You are given a string `S`, a substring `T`, and a replacement substring `R`. Your task is to implement a function `replace_substring` that replaces all occurrences of `T` in `S` with `R`. The function should return the modified string.\n\n**Input:**\n- The function `replace_substring` takes three parameters:\n - `S` (1 ≤ |S| ≤ 1000): The original string.\n - `T` (1 ≤ |T| ≤ 100): The substring to be replaced.\n - `R` (1 ≤ |R| ≤ 100): The replacement substring.\n\n**Output:**\n- Return the modified string after replacing all occurrences of `T` with `R`.\n\n**Sample Input:**\n- `S = \"Hello, World!\"`\n- `T = \"World\"`\n- `R = \"Everyone\"`\n\n**Sample Output:**\n- `\"Hello, Everyone!\"`", "reference": "def replace_substring(original_string, substring_to_replace, replacement_substring):\n \"\"\"\n Replaces all occurrences of a specified substring with another substring in the given string.\n\n Parameters:\n original_string (str): The original string.\n substring_to_replace (str): The substring to be replaced.\n replacement_substring (str): The replacement substring.\n\n Returns:\n str: The modified string after replacements.\n \"\"\"\n return original_string.replace(substring_to_replace, replacement_substring)\n\n# Example usage:\nresult = replace_substring(\"Hello, World!\", \"World\", \"Everyone\")\nprint(result) # Output: \"Hello, Everyone!\"", "tests": ["assert replace_substring(\"Hello, World!\", \"World\", \"Everyone\") == \"Hello, Everyone!\"", "assert replace_substring(\"abcabcabc\", \"abc\", \"xyz\") == \"xyzxyzxyz\"", "assert replace_substring(\"aaaa\", \"aa\", \"bb\") == \"bbbb\"", "assert replace_substring(\"mississippi\", \"issi\", \"xxxx\") == \"mxxxxppi\"", "assert replace_substring(\"banana\", \"na\", \"ma\") == \"bamama\"", "assert replace_substring(\"hello world\", \"world\", \"hello\") == \"hello hello\"", "assert replace_substring(\"test\", \"test\", \"exam\") == \"exam\"", "assert replace_substring(\"test\", \"exam\", \"test\") == \"test\"", "assert replace_substring(\"abc\", \"\", \"xyz\") == \"abc\"", "assert replace_substring(\"\", \"abc\", \"xyz\") == \"\""], "function": "replace_substring", "signature": "def replace_substring(original_string, substring_to_replace, replacement_substring):", "score": 0.8, "domain": "generic"} {"id": "9b69cdcb85b53c12f50a249808b586c9", "problem": "You are given a string `input_string` and a `conversion_token`. Your task is to write a function `convert_to_uppercase` that processes the string according to the following rules:\n- Locate all occurrences of the `conversion_token` in `input_string`.\n- For each occurrence, if the character immediately following the token is a vowel (a, e, i, o, u) and is not preceded by another vowel, convert it to uppercase.\n- If the `conversion_token` is at the end of the string or the conditions for conversion are not met, leave the string unchanged.\n\n**Constraints:**\n- The length of `input_string` is between 1 and 1000 characters.\n- The `conversion_token` is a non-empty substring of `input_string`.\n\n**Sample Input and Output:**\n- Input: `input_string = \"hello_world\"`, `conversion_token = \"_\"` \n Output: `\"helloWorld\"`\n- Input: `input_string = \"hello_world_\"`, `conversion_token = \"_\"` \n Output: `\"helloWorld_\"`\n- Input: `input_string = \"ea_easy_ebcd_eo\"`, `conversion_token = \"_\"` \n Output: `\"eaEasy_ecbd_eO\"`", "reference": "def convert_to_uppercase(input_string: str, conversion_token: str) -> str:\n \"\"\"\n Converts the character immediately following each occurrence of the conversion_token to uppercase\n if it is a vowel and not preceded by another vowel.\n \n :param input_string: The string to be processed.\n :param conversion_token: The token that precedes characters to be potentially converted.\n :return: The processed string with specified characters converted to uppercase.\n \"\"\"\n vowels = \"aeiou\"\n result = []\n i = 0\n while i < len(input_string):\n if input_string[i:i+len(conversion_token)] == conversion_token:\n if i + len(conversion_token) < len(input_string):\n next_char = input_string[i + len(conversion_token)]\n if next_char.lower() in vowels:\n if i == 0 or input_string[i - 1].lower() not in vowels:\n result.append(next_char.upper())\n i += len(conversion_token) + 1\n continue\n result.append(conversion_token)\n i += len(conversion_token)\n else:\n result.append(input_string[i])\n i += 1\n return ''.join(result)", "tests": ["assert convert_to_uppercase(\"hello_world\", \"_\") == \"helloWorld\"", "assert convert_to_uppercase(\"hello_world_\", \"_\") == \"helloWorld_\"", "assert convert_to_uppercase(\"ea_easy_ebcd_eo\", \"_\") == \"eaEasy_ecbd_eO\"", "assert convert_to_uppercase(\"a_a_a_a\", \"_\") == \"aAaA\"", "assert convert_to_uppercase(\"a_e_i_o_u\", \"_\") == \"aEiOu\"", "assert convert_to_uppercase(\"aeiou\", \"e\") == \"aeiou\"", "assert convert_to_uppercase(\"bcd_efg\", \"_\") == \"bcdEfg\"", "assert convert_to_uppercase(\"bcd_efg_\", \"_\") == \"bcdEfg_\"", "assert convert_to_uppercase(\"bcd_efg_hij\", \"_\") == \"bcdEfgHij\"", "assert convert_to_uppercase(\"bcd_efg_hij_\", \"_\") == \"bcdEfgHij_\""], "function": "convert_to_uppercase", "signature": "def convert_to_uppercase(input_string: str, conversion_token: str) -> str:", "score": 0.3, "domain": "generic"} {"id": "a9ec59336a3fcb44b2af31ee9832d26c", "problem": "You are given a string `data` and a list of integers `indices`. Your task is to construct a new string by concatenating characters from `data` at the positions specified by `indices`. Characters should be concatenated in the order of the indices provided. If an index is out of the bounds of the string, it should be ignored.\n\n**Input:**\n- A string `data` (1 ≤ |data| ≤ 100).\n- A list of integers `indices` (0 ≤ |indices| ≤ 100), where each integer is in the range [-100, 100].\n\n**Output:**\n- A string consisting of characters from `data` at the specified indices, concatenated in the order of the indices.\n\n**Sample Input:**\n```\ndata = \"hello world\"\nindices = [0, 2, 4, 10, 5, 8]\n```\n\n**Sample Output:**\n```\n\"hlowrd\"\n```", "reference": "def process_data(data, indices):\n \"\"\"\n Constructs a new string by concatenating characters from the input string `data`\n at the positions specified by the list `indices`. Characters are concatenated\n in the order of the indices. Out-of-range indices are ignored.\n\n :param data: A string from which characters are to be extracted.\n :param indices: A list of integers representing the positions of characters to extract.\n :return: A string consisting of the extracted characters.\n \"\"\"\n result = []\n for index in indices:\n if 0 <= index < len(data):\n result.append(data[index])\n return ''.join(result)", "tests": ["assert process_data(\"hello world\", [0, 2, 4, 10, 5, 8]) == \"hlowrd\"", "assert process_data(\"abcdef\", [1, 3, 5]) == \"bdf\"", "assert process_data(\"abcdef\", [6, 7, 8]) == \"\"", "assert process_data(\"abcdef\", []) == \"\"", "assert process_data(\"\", [0, 1, 2]) == \"\"", "assert process_data(\"a\", [0]) == \"a\"", "assert process_data(\"a\", [1]) == \"\"", "assert process_data(\"hello\", [0, 1, 2, 3, 4, 5]) == \"hello\"", "assert process_data(\"hello\", [-1, -2, 5, 3]) == \"l\"", "assert process_data(\"hello\", [4, 3, 2, 1, 0]) == \"olleh\""], "function": "process_data", "signature": "def process_data(data, indices):", "score": 0.9, "domain": "generic"} {"id": "c192733c64340edc7284a38209e59a1e", "problem": "You are given a list of `DNA` objects, where each object contains a `sequence` attribute representing a DNA sequence. Your task is to concatenate all the DNA sequences into a single string, with each sequence separated by the longest palindromic substring found in the previous sequence. If the list is empty, return an empty string. \n\n**Input:**\n- A list of `DNA` objects.\n\n**Output:**\n- A single string representing the concatenated DNA sequences with separators.\n\n**Sample Input:**\n```python\ndna_list = [DNA(\"ATCG\"), DNA(\"GCTA\"), DNA(\"TACG\")]\n```\n\n**Sample Output:**\n```\n\"ATCGCTAGCTA\"\n```", "reference": "class DNA:\n def __init__(self, sequence):\n self.sequence = sequence\n\ndef longest_palindromic_substring(s):\n \"\"\"\n Helper function to find the longest palindromic substring in a given string.\n \n :param s: Input string\n :return: Longest palindromic substring\n \"\"\"\n n = len(s)\n if n == 0:\n return \"\"\n \n start, end = 0, 0\n for i in range(n):\n len1 = expand_around_center(s, i, i) # Odd length palindromes\n len2 = expand_around_center(s, i, i+1) # Even length palindromes\n max_len = max(len1, len2)\n if max_len > end - start:\n start = i - (max_len - 1) // 2\n end = i + max_len // 2\n\n return s[start:end + 1]\n\ndef expand_around_center(s, left, right):\n \"\"\"\n Helper function to expand around center and find the length of the palindrome.\n \n :param s: Input string\n :param left: Left index\n :param right: Right index\n :return: Length of the palindrome\n \"\"\"\n while left >= 0 and right < len(s) and s[left] == s[right]:\n left -= 1\n right += 1\n return right - left - 1\n\ndef concatenate_dna_sequences(dna_list):\n \"\"\"\n Concatenates DNA sequences with the longest palindromic substring from the previous sequence as separator.\n \n :param dna_list: List of DNA objects\n :return: Concatenated DNA sequence string\n \"\"\"\n if not dna_list:\n return \"\"\n \n result = dna_list[0].sequence # Start with the first sequence\n for i in range(1, len(dna_list)):\n # Find the longest palindromic substring in the previous sequence\n separator = longest_palindromic_substring(dna_list[i-1].sequence)\n result += separator + dna_list[i].sequence\n \n return result", "tests": ["assert concatenate_dna_sequences([]) == \"\"", "assert concatenate_dna_sequences([DNA(\"abc\")]) == \"abc\"", "assert concatenate_dna_sequences([DNA(\"abc\"), DNA(\"def\")]) == \"abccbaabcdef\"", "assert concatenate_dna_sequences([DNA(\"a\"), DNA(\"b\"), DNA(\"c\")]) == \"acbac\"", "assert concatenate_dna_sequences([DNA(\"racecar\"), DNA(\"banana\")]) == \"racecaracecarbanana\"", "assert concatenate_dna_sequences([DNA(\"noon\"), DNA(\"level\"), DNA(\"deified\")]) == \"noonnoonleveldelified\"", "assert concatenate_dna_sequences([DNA(\"abacdfgdcaba\"), DNA(\"xyz\")]) == \"abacdfgdcabaabacxyz\"", "assert concatenate_dna_sequences([DNA(\"aabbcc\"), DNA(\"ddeeff\"), DNA(\"gghhiijj\")]) == \"aabbccbbddeeffffgghhiijj\"", "assert concatenate_dna_sequences([DNA(\"abcba\"), DNA(\"xyzzyx\"), DNA(\"madam\")]) == \"abcbaabcaxyzzyxzyxmadam\"", "assert concatenate_dna_sequences([DNA(\"rotor\"), DNA(\"deified\"), DNA(\"level\")]) == \"rotorrotordeifieddeifiedlevel\""], "function": "concatenate_dna_sequences", "signature": "def concatenate_dna_sequences(dna_list):", "score": 0.3, "domain": "generic"} {"id": "adbdb12db3ad93cd5b6abe761bc12655", "problem": "You are given a JavaScript object with nested properties and a string representing a path to a specific property. Your task is to write a function that dynamically accesses this property using the path provided. The path is a dot-separated string of keys. If any key in the path does not exist, the function should return `None`.\n\n**Input:**\n- A dictionary `obj` representing a JavaScript object.\n- A string `path` representing the path to the desired property.\n\n**Output:**\n- The value of the property at the specified path, or `None` if the path is invalid.\n\n**Sample Input:**\n```python\ndata = {\n \"name\": \"John\",\n \"address\": {\n \"street\": \"123 Main St\",\n \"city\": \"Anytown\",\n \"state\": \"CA\",\n \"zip\": \"12345\"\n },\n \"phone\": \"555-1234\"\n}\n\npath = \"address.city\"\n```\n\n**Sample Output:**\n```\nAnytown\n```", "reference": "def get_nested_property(obj, path):\n \"\"\"\n Dynamically accesses a nested property in a dictionary using a dot-separated path.\n \n Parameters:\n obj (dict): The dictionary representing a JavaScript object.\n path (str): The dot-separated string representing the path to the desired property.\n \n Returns:\n The value of the property at the specified path, or None if the path is invalid.\n \"\"\"\n keys = path.split('.')\n for key in keys:\n if isinstance(obj, dict) and key in obj:\n obj = obj[key]\n else:\n return None\n return obj\n\n# Example usage\ndata = {\n \"name\": \"John\",\n \"address\": {\n \"street\": \"123 Main St\",\n \"city\": \"Anytown\",\n \"state\": \"CA\",\n \"zip\": \"12345\"\n },\n \"phone\": \"555-1234\"\n}\n\npath = \"address.city\"\nresult = get_nested_property(data, path)\nprint(result) # Output should be \"Anytown\"", "tests": ["assert get_nested_property(data, \"name\") == \"John\"", "assert get_nested_property(data, \"address.street\") == \"123 Main St\"", "assert get_nested_property(data, \"address.city\") == \"Anytown\"", "assert get_nested_property(data, \"address.state\") == \"CA\"", "assert get_nested_property(data, \"address.zip\") == \"12345\"", "assert get_nested_property(data, \"phone\") == \"555-1234\"", "assert get_nested_property(data, \"address.country\") == None", "assert get_nested_property(data, \"name.first\") == None", "assert get_nested_property(data, \"address\") == {\"street\": \"123 Main St\", \"city\": \"Anytown\", \"state\": \"CA\", \"zip\": \"12345\"}", "assert get_nested_property(data, \"\") == data"], "function": "get_nested_property", "signature": "def get_nested_property(obj, path):", "score": 0.9, "domain": "algorithmic"} {"id": "10969b372adfb25303bf4c00ace21e49", "problem": "You are given a string `input_str`. Your task is to implement a function that returns a dictionary with keys as unique words in the string and values as the counts of those words. The function should ignore punctuation and treat words in a case-insensitive manner.\n\n**Input:**\n- A single string `input_str` (1 ≤ len(input_str) ≤ 10^5).\n\n**Output:**\n- A dictionary where keys are unique words and values are their respective counts.\n\n**Sample Input:**\n```\n\"Hello, hello... how are you?\"\n```\n\n**Sample Output:**\n```\n{'hello': 2, 'how': 1, 'are': 1, 'you': 1}\n```", "reference": "import re\nfrom collections import defaultdict\n\ndef word_count(input_str):\n \"\"\"\n Returns a dictionary with keys as unique words in the input string and values as their counts.\n Ignores punctuation and treats words case-insensitively.\n\n :param input_str: A string containing words separated by spaces and possibly punctuation.\n :return: A dictionary with word counts.\n \"\"\"\n words = re.findall(r'\\b\\w+\\b', input_str.lower())\n count_dict = defaultdict(int)\n for word in words:\n count_dict[word] += 1\n return dict(count_dict)", "tests": ["assert word_count(\"Hello, hello... how are you?\") == {'hello': 2, 'how': 1, 'are': 1, 'you': 1}", "assert word_count(\"Python, python, PYTHON!\") == {'python': 3}", "assert word_count(\"A quick brown fox jumps over the lazy dog.\") == {'a': 1, 'quick': 1, 'brown': 1, 'fox': 1, 'jumps': 1, 'over': 1, 'the': 1, 'lazy': 1, 'dog': 1}", "assert word_count(\"To be or not to be, that is the question.\") == {'to': 2, 'be': 2, 'or': 1, 'not': 1, 'that': 1, 'is': 1, 'the': 1, 'question': 1}", "assert word_count(\"123 456 789 123\") == {'123': 2, '456': 1, '789': 1}", "assert word_count(\"!@#$%^&*()\") == {}", "assert word_count(\"\") == {}", "assert word_count(\"One fish, two fish, red fish, blue fish.\") == {'one': 1, 'fish': 4, 'two': 1, 'red': 1, 'blue': 1}", "assert word_count(\"Repeat repeat REPEAT\") == {'repeat': 3}", "assert word_count(\"Spaces should not matter.\") == {'spaces': 1, 'should': 1, 'not': 1, 'matter': 1}"], "function": "word_count", "signature": "def word_count(input_str):", "score": 1.0, "domain": "generic"} {"id": "64a2c2aa7013c2d075e0aa51e9b5ef26", "problem": "You are tasked with implementing a recursive function `fibonacci` to compute the nth Fibonacci number. The Fibonacci sequence is defined such that the first two numbers are 0 and 1, and each subsequent number is the sum of the two preceding ones. Your function should handle the following constraints: 0 ≤ n ≤ 20.\n\n**Sample Input:**\n```\n10\n```\n\n**Sample Output:**\n```\n55\n```", "reference": "def fibonacci(n):\n \"\"\"\n Calculate the nth Fibonacci number using recursion.\n \n Parameters:\n n (int): The position in the Fibonacci sequence (0-indexed).\n \n Returns:\n int: The nth Fibonacci number.\n \"\"\"\n if n <= 0:\n return 0\n elif n == 1:\n return 1\n else:\n return fibonacci(n - 1) + fibonacci(n - 2)\n\n# Example usage:\n# print(fibonacci(10)) # Output should be 55", "tests": ["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(6) == 8", "assert fibonacci(7) == 13", "assert fibonacci(10) == 55", "assert fibonacci(15) == 610"], "function": "fibonacci", "signature": "def fibonacci(n):", "score": 1.0, "domain": "generic"} {"id": "08ec061ad2ef6bebfc017269d1b17b33", "problem": "You are tasked with determining the adjusted event numbers for a series of sports events based on a given schedule and team names. The schedule is represented as a dictionary `event_dict` where keys are event numbers ranging from 1 to 64, and values are the names of the teams participating in those events. \n\nYou are also provided with a list of team names `team_names` and an initial event number `starting_event`. For each team in `team_names`, find the event number they are participating in, considering that the event numbers are adjusted by adding 16 to the original event number until the value in `event_dict` matches the team name. If the adjusted event number exceeds 64, it wraps around to 1 and continues the adjustment process.\n\nWrite a function `find_adjusted_events(event_dict, starting_event, team_names)` that takes `event_dict`, `starting_event`, and `team_names` as input and returns a list of adjusted event numbers corresponding to the list of team names provided.\n\n**Sample Input:**\n```python\nevent_dict = {1: 'Team A', 2: 'Team B', 3: 'Team C', ..., 64: 'Team Z'}\nteam_names = ['Team X', 'Team Y']\nstarting_event = 3\n```\n\n**Sample Output:**\n```python\n[23, 39]\n```", "reference": "def find_adjusted_events(event_dict, starting_event, team_names):\n \"\"\"\n Finds the adjusted event numbers for given team names based on the event schedule.\n\n Parameters:\n event_dict (dict): A dictionary where keys are event numbers (1-64) and values are team names.\n starting_event (int): The initial event number to start the search from.\n team_names (list): A list of team names for which to find the adjusted event numbers.\n\n Returns:\n list: A list of adjusted event numbers corresponding to the team names.\n \"\"\"\n adjusted_events = []\n\n for team in team_names:\n event_number = starting_event\n while True:\n if event_dict.get(event_number) == team:\n adjusted_events.append(event_number)\n break\n event_number = (event_number + 16) % 64\n if event_number == 0:\n event_number = 1\n\n return adjusted_events", "tests": ["assert find_adjusted_events({1: 'Team A', 17: 'Team B', 33: 'Team C'}, 1, ['Team B']) == [17]", "assert find_adjusted_events({1: 'Team A', 17: 'Team B', 33: 'Team C'}, 1, ['Team C']) == [33]", "assert find_adjusted_events({1: 'Team A', 17: 'Team B', 33: 'Team C'}, 1, ['Team A']) == [1]", "assert find_adjusted_events({1: 'Team A', 17: 'Team B', 33: 'Team C'}, 17, ['Team A']) == [1]", "assert find_adjusted_events({1: 'Team A', 17: 'Team B', 33: 'Team C'}, 33, ['Team A']) == [1]", "assert find_adjusted_events({1: 'Team A', 17: 'Team B', 33: 'Team C'}, 64, ['Team A']) == [1]", "assert find_adjusted_events({1: 'Team A', 17: 'Team B', 33: 'Team C'}, 1, ['Team D']) == []", "assert find_adjusted_events({1: 'Team A', 17: 'Team B', 33: 'Team C', 49: 'Team A'}, 1, ['Team A']) == [1, 49]", "assert find_adjusted_events({1: 'Team A', 17: 'Team B', 33: 'Team C', 49: 'Team A'}, 17, ['Team A']) == [1, 49]", "assert find_adjusted_events({1: 'Team A', 17: 'Team B', 33: 'Team C', 49: 'Team A'}, 33, ['Team A']) == [1, 49]"], "function": "find_adjusted_events", "signature": "def find_adjusted_events(event_dict, starting_event, team_names):", "score": 0.6, "domain": "generic"} {"id": "e38330d8a6714e93db12112d260c4b7b", "problem": "You are given an infinite number line starting from point 1. A grasshopper starts at point 1 and can jump to points +1, +2, or +3 ahead. However, certain points on the number line are forbidden. You are provided with a list `allowed_points` where `allowed_points[i]` is 1 if point `i+1` is allowed and 0 if it is forbidden. Your task is to determine the number of distinct trajectories the grasshopper can take to reach point `N`, ensuring that at least one of the jumps is exactly +3. \n\n**Constraints:**\n- 1 ≤ N ≤ 10^5\n- `allowed_points` is a list of length N where each element is either 0 or 1.\n\n**Sample Input:**\n```\nallowed_points = [1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 0]\nN = 10\n```\n\n**Sample Output:**\n```\n4\n```", "reference": "def count_trajectories(allowed_points, N):\n \"\"\"\n Calculate the number of distinct trajectories the grasshopper can take to reach point N,\n ensuring that at least one of the jumps is exactly +3, considering the forbidden points.\n \n :param allowed_points: List[int] - A list where allowed_points[i] is 1 if point i+1 is allowed, 0 if forbidden.\n :param N: int - The target point on the number line.\n :return: int - The number of distinct trajectories.\n \"\"\"\n dp = [0] * (N + 1)\n seen_plus_3_jump = False\n \n dp[1] = allowed_points[0]\n seen_plus_3_jump = allowed_points[0] and (N >= 4)\n \n if N >= 2:\n dp[2] = dp[1] * allowed_points[1]\n seen_plus_3_jump = seen_plus_3_jump or (dp[2] and (N >= 5))\n if N >= 3:\n dp[3] = (dp[1] + dp[2]) * allowed_points[2]\n seen_plus_3_jump = seen_plus_3_jump or (dp[3] and (N >= 6))\n \n for i in range(4, N + 1):\n if allowed_points[i - 1] == 0:\n dp[i] = 0\n else:\n dp[i] = dp[i - 1] + dp[i - 2] + dp[i - 3]\n seen_plus_3_jump = seen_plus_3_jump or (i >= 7 and dp[i - 3] > 0)\n \n return dp[N] if seen_plus_3_jump else 0", "tests": ["assert count_trajectories([1, 1, 1, 1, 1, 1, 1, 1, 1, 1], 10) == 504", "assert count_trajectories([1, 0, 1, 0, 1, 0, 1, 0, 1, 0], 10) == 0", "assert count_trajectories([1, 1, 1, 0, 0, 0, 0, 0, 0, 0], 10) == 0", "assert count_trajectories([1, 1, 1, 1, 1, 1, 1, 1, 1, 0], 10) == 0", "assert count_trajectories([1, 1, 1, 1, 1, 1, 1, 1, 1, 1], 1) == 0", "assert count_trajectories([1, 1, 1, 1, 1, 1, 1, 1, 1, 1], 2) == 0", "assert count_trajectories([1, 1, 1, 1, 1, 1, 1, 1, 1, 1], 3) == 0", "assert count_trajectories([1, 1, 1, 1, 1, 1, 1, 1, 1, 1], 4) == 1", "assert count_trajectories([1, 1, 1, 1, 1, 1, 1, 1, 1, 1], 5) == 4", "assert count_trajectories([1, 1, 1, 1, 1, 1, 1, 1, 1, 1], 6) == 15"], "function": "count_trajectories", "signature": "def count_trajectories(allowed_points, N):", "score": 0.6, "domain": "generic"} {"id": "8c15309f5be409a11177b971a4310e40", "problem": "You are given a string `s`. Determine if there exists a substring of `s` that, when cyclically shifted, forms a palindrome. A cyclic shift of a string involves moving some number of characters from the beginning of the string to the end. For example, the string \"abcde\" can be cyclically shifted to \"deabc\" or \"cdeab\". Your task is to return `True` if such a substring exists, otherwise return `False`.\n\n**Input:**\n- A single string `s` (1 ≤ |s| ≤ 10^3) consisting of lowercase English letters.\n\n**Output:**\n- Return `True` if there exists a cyclically shifted substring of `s` that is a palindrome, otherwise return `False`.\n\n**Sample Input:**\n```\nabcde\n```\n\n**Sample Output:**\n```\nFalse\n```", "reference": "def is_palindrome(s):\n \"\"\"\n Check if the given string s is a palindrome.\n \n :param s: String to check\n :return: True if s is a palindrome, False otherwise\n \"\"\"\n return s == s[::-1]\n\ndef has_cyclic_palindrome(s):\n \"\"\"\n Determine if there exists a substring of s that, when cyclically shifted, forms a palindrome.\n \n :param s: Input string\n :return: True if such a substring exists, False otherwise\n \"\"\"\n n = len(s)\n if n == 0:\n return False\n doubled_s = s + s\n for i in range(n):\n if is_palindrome(doubled_s[i:i + n]):\n return True\n return False\n\n# Test case\nprint(has_cyclic_palindrome(\"abcde\")) # Output: False", "tests": ["assert has_cyclic_palindrome(\"abcde\") == False", "assert has_cyclic_palindrome(\"a\") == True", "assert has_cyclic_palindrome(\"aa\") == True", "assert has_cyclic_palindrome(\"ab\") == False", "assert has_cyclic_palindrome(\"aba\") == True", "assert has_cyclic_palindrome(\"abac\") == False", "assert has_cyclic_palindrome(\"abcba\") == True", "assert has_cyclic_palindrome(\"abcdcba\") == True", "assert has_cyclic_palindrome(\"abcdeedcba\") == True", "assert has_cyclic_palindrome(\"\") == False"], "function": "has_cyclic_palindrome", "signature": "def has_cyclic_palindrome(s):", "score": 1.0, "domain": "algorithmic"} {"id": "f2ee2ff5989e34cc3cb29baed948bdd5", "problem": "You are given a string `s` consisting of words separated by spaces. Your task is to implement a function that identifies the longest word in the string. If there are multiple words with the same maximum length, return the first one encountered. The function should be case-insensitive and should ignore punctuation.\n\n**Input:**\n- A single string `s` (1 ≤ |s| ≤ 10^5) containing words separated by spaces. Words may include punctuation and can be in mixed case.\n\n**Output:**\n- A single string representing the longest word in the input string, following the rules specified above.\n\n**Sample Input:**\n```\n\"Hello, world! This is a test string with some long-words-included.\"\n```\n\n**Sample Output:**\n```\nlongwordsincluded\n```", "reference": "import re\n\ndef find_longest_word(s):\n \"\"\"\n Finds the longest word in a given string, ignoring punctuation and case.\n \n Parameters:\n s (str): The input string containing words separated by spaces.\n \n Returns:\n str: The longest word in the input string.\n \"\"\"\n # Remove punctuation and convert string to lowercase\n cleaned_string = re.sub(r'[^\\w\\s-]', '', s).lower()\n # Split string into words\n words = cleaned_string.split()\n # Find and return the longest word\n longest_word = max(words, key=len)\n return longest_word\n\n# Example usage\ns = \"Hello, world! This is a test string with some long-words-included.\"\nprint(find_longest_word(s))", "tests": ["assert find_longest_word(\"Hello, world!\") == \"hello\"", "assert find_longest_word(\"The quick brown fox jumps over the lazy dog.\") == \"quick\"", "assert find_longest_word(\"A journey of a thousand miles begins with a single step.\") == \"thousand\"", "assert find_longest_word(\"To be or not to be, that is the question.\") == \"question\"", "assert find_longest_word(\"May the Force be with you.\") == \"force\"", "assert find_longest_word(\"All's well that ends well.\") == \"well\"", "assert find_longest_word(\"The rain in Spain stays mainly in the plain.\") == \"mainly\"", "assert find_longest_word(\"An apple a day keeps the doctor away.\") == \"doctor\"", "assert find_longest_word(\"Long-words-included should be included.\") == \"longwordsincluded\"", "assert find_longest_word(\"Equal words like test test test.\") == \"equal\""], "function": "find_longest_word", "signature": "def find_longest_word(s):", "score": 0.8, "domain": "generic"} {"id": "8374e2dea7d367131bb2f121b4c7c366", "problem": "You are tasked with implementing a function `validate_username` that checks if a given username adheres to specific rules. The function should return `True` if the username satisfies all the following conditions, otherwise return `False`:\n\n- The username must be at least 5 characters in length.\n- The username must not begin with a digit.\n- The username must not include any special characters (only alphanumeric characters are allowed).\n- The username must contain at least one uppercase letter and one lowercase letter.\n\n**Sample Input and Output:**\n\n- Input: `\"ValidUs3r\"`\n- Output: `True`\n\n- Input: `\"invalid\"`\n- Output: `False`\n\n- Input: `\"1Invalid\"`\n- Output: `False`\n\n- Input: `\"Valid_Us3r\"`\n- Output: `False`\n\n- Input: `\"ValidUs3rname\"`\n- Output: `True`", "reference": "import re\n\ndef validate_username(username: str) -> bool:\n \"\"\"\n Validates a username based on specific criteria:\n - At least 5 characters long.\n - Does not start with a digit.\n - Contains only alphanumeric characters.\n - Includes at least one uppercase and one lowercase letter.\n \n :param username: The username to validate.\n :return: True if the username is valid, False otherwise.\n \"\"\"\n if len(username) < 5:\n return False\n if username[0].isdigit():\n return False\n if re.search(r'[^A-Za-z0-9]', username):\n return False\n if not re.search(r'[A-Z]', username) or not re.search(r'[a-z]', username):\n return False\n return True", "tests": ["assert validate_username(\"Abcde\") == True", "assert validate_username(\"abcde\") == False", "assert validate_username(\"ABCDE\") == False", "assert validate_username(\"Abc\") == False", "assert validate_username(\"1Abcde\") == False", "assert validate_username(\"Abcde1\") == True", "assert validate_username(\"Abcde!\") == False", "assert validate_username(\"Abcde_\") == False", "assert validate_username(\"Abcde \") == False", "assert validate_username(\"Abcdefghijklmnopqrstuvwxyz\") == True"], "function": "validate_username", "signature": "def validate_username(username: str) -> bool:", "score": 1.0, "domain": "generic"} {"id": "d4da61d88fccace8685e2fbccbf5e59f", "problem": "You are given a string `s` consisting of parentheses characters only. Your task is to determine if the string is balanced. A string is considered balanced if each opening parenthesis has a corresponding closing parenthesis in the correct order. For example, the string `\"(()())\"` is balanced, while `\"(()\"` and `\"())\"` are not.\n\n**Input:**\n- A single string `s` (1 ≤ |s| ≤ 10^5) consisting of characters '(' and ')'.\n\n**Output:**\n- Return `True` if the string is balanced, otherwise return `False`.\n\n**Sample Input:**\n```\n(()())\n(() \n())\n()()\n()\n)( \n```\n\n**Sample Output:**\n```\nTrue\nFalse\nFalse\nTrue\nTrue\nFalse\n```", "reference": "def is_balanced_parentheses(s: str) -> bool:\n \"\"\"\n Determines if a string of parentheses is balanced.\n \n :param s: A string consisting of '(' and ')' characters.\n :return: True if the string is balanced, False otherwise.\n \"\"\"\n stack = []\n parentheses_map = {\")\": \"(\"}\n \n for char in s:\n if char in parentheses_map.values():\n stack.append(char)\n elif char in parentheses_map.keys():\n if not stack or parentheses_map[char] != stack.pop():\n return False\n \n return not stack", "tests": ["assert is_balanced_parentheses(\"(()())\") == True", "assert is_balanced_parentheses(\"(()\") == False", "assert is_balanced_parentheses(\"())\") == False", "assert is_balanced_parentheses(\"()()\") == True", "assert is_balanced_parentheses(\"\") == True", "assert is_balanced_parentheses(\")(\") == False", "assert is_balanced_parentheses(\"((()))\") == True", "assert is_balanced_parentheses(\"(()))(\") == False", "assert is_balanced_parentheses(\"()(()())\") == True", "assert is_balanced_parentheses(\"(((((\") == False"], "function": "is_balanced_parentheses", "signature": "def is_balanced_parentheses(s: str) -> bool:", "score": 1.0, "domain": "generic"} {"id": "8ea5bb4941b60d3e3c31b5f4573bfb38", "problem": "You are given the task to implement a function `calculate_discount` that computes the final price after applying a discount to an original price. The function should handle various input types and edge cases as specified below:\n\n- **Parameters:**\n - `original_price`: Can be of any data type. If it is not a number, or a complex number, or outside the range [0, 10000], the function should return `None`.\n - `discount_percentage`: Can be of any data type. If it is a string, attempt to convert it to a float. If conversion fails, or if it is not a number, or outside the range [-100, 100], the function should return `None`. If it is negative, the function should return the original price increased by 10%.\n\n- **Return Value:**\n - The function should return the discounted price rounded to one decimal place. If any of the above conditions are not met, return `None`.\n\n- **Examples:**\n - `calculate_discount(100, 20)` should return `80.0`.\n - `calculate_discount(100, -10)` should return `110.0`.\n - `calculate_discount(100, \"20\")` should return `80.0`.\n - `calculate_discount(100, \"abc\")` should return `None`.\n - `calculate_discount(100, 120)` should return `None`.\n - `calculate_discount(10001, 20)` should return `None`.\n - `calculate_discount(100, 20+5j)` should return `None`.", "reference": "def calculate_discount(original_price, discount_percentage):\n \"\"\"\n Calculate the discounted price after applying a discount percentage to the original price.\n \n Parameters:\n - original_price: Can be of any data type. If not a number, complex, or outside [0, 10000], return None.\n - discount_percentage: Can be of any data type. If string, try to convert to float. If not a number, outside [-100, 100], or conversion fails, return None. If negative, return original price increased by 10%.\n \n Returns:\n - Discounted price rounded to one decimal place, or None if conditions are not met.\n \"\"\"\n if isinstance(original_price, complex) or not isinstance(original_price, (int, float)) or not (0 <= original_price <= 10000):\n return None\n\n if isinstance(discount_percentage, str):\n try:\n discount_percentage = float(discount_percentage)\n except ValueError:\n return None\n\n if not isinstance(discount_percentage, (int, float)) or not (-100 <= discount_percentage <= 100):\n return None\n\n if discount_percentage < 0:\n return round(original_price * 1.1, 1)\n\n discounted_price = original_price * (1 - discount_percentage / 100)\n return round(discounted_price, 1)", "tests": ["assert calculate_discount(100, 10) == 90.0", "assert calculate_discount(100, \"10\") == 90.0", "assert calculate_discount(100, -10) == 110.0", "assert calculate_discount(100, \"abc\") == None", "assert calculate_discount(\"100\", 10) == None", "assert calculate_discount(100, 110) == None", "assert calculate_discount(100, -110) == None", "assert calculate_discount(10001, 10) == None", "assert calculate_discount(-1, 10) == None", "assert calculate_discount(100, 0) == 100.0"], "function": "calculate_discount", "signature": "def calculate_discount(original_price, discount_percentage):", "score": 1.0, "domain": "generic"} {"id": "0b4104da549a4b36653c929f5673122d", "problem": "You are given a string `S` and a set of characters `_set`. Your task is to find the smallest substring of `S` that contains all the characters in `_set`. If there are multiple substrings with the same length, return the one that appears first in `S`. The function should handle both uppercase and lowercase letters as distinct characters and the set may contain duplicate characters.\n\n**Input:**\n- A string `S` (1 ≤ |S| ≤ 10^5)\n- A set of characters `_set` (1 ≤ |_set| ≤ 26)\n\n**Output:**\n- A string representing the smallest substring of `S` that contains all characters in `_set`.\n\n**Sample Input 1:**\n```\nS = \"abcdabc\"\n_set = {\"a\", \"b\", \"c\"}\n```\n**Sample Output 1:**\n```\n\"abc\"\n```\n\n**Sample Input 2:**\n```\nS = \"abcdabc\"\n_set = {\"a\", \"b\", \"d\"}\n```\n**Sample Output 2:**\n```\n\"abcd\"\n```", "reference": "def smallest_substring(S, _set):\n \"\"\"\n Finds the smallest substring of S that contains all characters in _set.\n \n Parameters:\n S (str): The input string.\n _set (set): The set of characters to be included in the substring.\n \n Returns:\n str: The smallest substring containing all characters in _set.\n \"\"\"\n if not S or not _set:\n return \"\"\n\n from collections import defaultdict\n\n window = defaultdict(int)\n required_chars = len(_set)\n formed_chars = 0\n\n left = 0\n right = 0\n min_length = float('inf')\n min_substring = \"\"\n\n while right < len(S):\n current_char = S[right]\n window[current_char] += 1\n\n if current_char in _set and window[current_char] == 1:\n formed_chars += 1\n\n while left <= right and formed_chars == required_chars:\n current_char = S[left]\n\n if right - left + 1 < min_length:\n min_length = right - left + 1\n min_substring = S[left:right + 1]\n\n window[current_char] -= 1\n if current_char in _set and window[current_char] == 0:\n formed_chars -= 1\n\n left += 1\n\n right += 1\n\n return min_substring", "tests": ["assert smallest_substring(\"abcdabc\", {\"a\", \"b\", \"c\"}) == \"abc\"", "assert smallest_substring(\"abcdabc\", {\"a\", \"b\", \"d\"}) == \"abcd\"", "assert smallest_substring(\"aabbcc\", {\"a\", \"b\", \"c\"}) == \"aabbcc\"", "assert smallest_substring(\"abcde\", {\"a\", \"e\"}) == \"abcde\"", "assert smallest_substring(\"abcde\", {\"f\"}) == \"\"", "assert smallest_substring(\"abacabad\", {\"a\", \"b\", \"c\"}) == \"abac\"", "assert smallest_substring(\"zzzzzz\", {\"z\"}) == \"z\"", "assert smallest_substring(\"abcdefg\", {\"a\", \"g\"}) == \"abcdefg\"", "assert smallest_substring(\"aabbccddeeff\", {\"a\", \"b\", \"c\", \"d\", \"e\", \"f\"}) == \"aabbccddeeff\"", "assert smallest_substring(\"aabbccddeeff\", {\"a\", \"b\", \"c\"}) == \"aabbcc\""], "function": "smallest_substring", "signature": "def smallest_substring(S, _set):", "score": 0.5, "domain": "generic"} {"id": "ec53819d8da905d23b07178c63728444", "problem": "You are developing a simulation for a card game where a player starts with an empty hand and draws cards from a deck. The deck initially contains 52 unique cards, each represented by a distinct integer from 1 to 52. Your task is to implement a function `draw_cards(deck, num_cards)` that simulates drawing `num_cards` from the `deck`. The function should return a list of `num_cards` unique integers representing the cards drawn from the deck, and the deck should be updated to reflect the cards that have been drawn.\n\n**Specifications:**\n- The `deck` parameter is a list of integers representing the cards in the deck.\n- The `num_cards` parameter is an integer representing the number of cards to draw from the deck.\n- The function should return a list of `num_cards` unique integers representing the cards drawn from the deck.\n- The function should update the `deck` list to reflect the cards that have been drawn.\n- If `num_cards` is greater than the number of cards remaining in the deck, the function should return all the remaining cards in the deck.\n- The deck must maintain a perfect cycle where, once a card is drawn, it reappears in the last position of the deck only after all other cards have been drawn once.\n\n**Sample Input:**\n```python\ndeck = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\nnum_cards = 3\n```\n\n**Sample Output:**\n```python\n[1, 2, 3]\n# Updated deck: [4, 5, 6, 7, 8, 9, 10, 1, 2, 3]\n```", "reference": "def draw_cards(deck, num_cards):\n \"\"\"\n Simulates drawing num_cards from the deck and updates the deck to maintain a perfect cycle.\n \n Parameters:\n deck (list of int): The list of integers representing the cards in the deck.\n num_cards (int): The number of cards to draw from the deck.\n \n Returns:\n list of int: A list of num_cards unique integers representing the cards drawn from the deck.\n \"\"\"\n num_cards_to_draw = min(num_cards, len(deck))\n drawn_cards = deck[:num_cards_to_draw]\n remaining_deck = deck[num_cards_to_draw:]\n updated_deck = remaining_deck + drawn_cards\n deck.clear()\n deck.extend(updated_deck)\n return drawn_cards", "tests": ["assert draw_cards([1, 2, 3, 4, 5], 2) == [1, 2]", "assert draw_cards([1, 2, 3, 4, 5], 5) == [1, 2, 3, 4, 5]", "assert draw_cards([1, 2, 3, 4, 5], 0) == []", "assert draw_cards([1, 2, 3, 4, 5], 10) == [1, 2, 3, 4, 5]", "assert draw_cards([10, 20, 30, 40, 50], 3) == [10, 20, 30]", "assert draw_cards([1, 2, 3, 4, 5], 1) == [1]", "assert draw_cards([], 5) == []", "assert draw_cards([1], 1) == [1]", "assert draw_cards([1, 2, 3, 4, 5], 4) == [1, 2, 3, 4]", "assert draw_cards([52, 51, 50, 49, 48], 2) == [52, 51]"], "function": "draw_cards", "signature": "def draw_cards(deck, num_cards):", "score": 1.0, "domain": "generic"} {"id": "ab5f9a285335ad45269d40ebc7fc8575", "problem": "You are given an integer `n`. Your task is to determine the number of unique strobogrammatic pairs `(a, b)` such that both `a` and `b` are strobogrammatic numbers between 1 and `n` (inclusive), and neither `a` nor `b` is a palindrome. A strobogrammatic number is a number that appears the same when rotated 180 degrees. For example, 69, 88, and 1001 are strobogrammatic numbers. A palindrome is a number that reads the same forwards and backwards, such as 121 or 88.\n\n**Input:**\n- An integer `n` (1 ≤ n ≤ 10^5)\n\n**Output:**\n- An integer representing the count of valid strobogrammatic pairs.\n\n**Sample Input:**\n```\n100\n```\n\n**Sample Output:**\n```\n4\n```", "reference": "def count_strobogrammatic_pairs(n):\n \"\"\"\n Counts the number of unique strobogrammatic pairs (a, b) such that both a and b are strobogrammatic numbers\n between 1 and n (inclusive), and neither a nor b is a palindrome.\n \n :param n: The upper limit for the range of numbers to consider.\n :return: The count of valid strobogrammatic pairs.\n \"\"\"\n pairs = {'0': '0', '1': '1', '6': '9', '8': '8', '9': '6'}\n \n def is_strobogrammatic(num):\n \"\"\"\n Checks if a number is strobogrammatic.\n \n :param num: The number to check.\n :return: True if the number is strobogrammatic, False otherwise.\n \"\"\"\n s = str(num)\n i, j = 0, len(s) - 1\n while i <= j:\n if s[i] not in pairs or s[j] != pairs[s[i]]:\n return False\n i += 1\n j -= 1\n return True\n \n def is_palindrome(num):\n \"\"\"\n Checks if a number is a palindrome.\n \n :param num: The number to check.\n :return: True if the number is a palindrome, False otherwise.\n \"\"\"\n s = str(num)\n return s == s[::-1]\n \n strobogrammatic_numbers = set()\n for i in range(1, n + 1):\n if is_strobogrammatic(i):\n strobogrammatic_numbers.add(i)\n \n count = 0\n for a in strobogrammatic_numbers:\n for b in strobogrammatic_numbers:\n if a != b and not is_palindrome(a) and not is_palindrome(b):\n count += 1\n \n return count // 2 # Each pair (a, b) is counted twice", "tests": ["assert count_strobogrammatic_pairs(10) == 0", "assert count_strobogrammatic_pairs(100) == 4", "assert count_strobogrammatic_pairs(1000) == 20", "assert count_strobogrammatic_pairs(1) == 0", "assert count_strobogrammatic_pairs(69) == 1", "assert count_strobogrammatic_pairs(88) == 2", "assert count_strobogrammatic_pairs(1001) == 20", "assert count_strobogrammatic_pairs(10000) == 100", "assert count_strobogrammatic_pairs(11) == 0", "assert count_strobogrammatic_pairs(100000) == 500"], "function": "count_strobogrammatic_pairs", "signature": "def count_strobogrammatic_pairs(n):", "score": 0.3, "domain": "generic"} {"id": "121a7e4b8572f2b2db85dae7bb7917b4", "problem": "You are tasked with implementing a function `validate_json` that checks if a given JSON string is well-formed. A JSON string is considered well-formed if it adheres to the JSON specification and can be parsed without any errors. Your function should return `True` if the JSON string is well-formed and `False` otherwise. Use Python's `json` module for parsing and handle any exceptions that may arise during the parsing process.\n\n**Input:**\n- A single string `json_string` representing the JSON data.\n\n**Output:**\n- Return `True` if `json_string` is a well-formed JSON, otherwise return `False`.\n\n**Sample Input 1:**\n```json\n{\"name\": \"John\", \"age\": 30, \"city\": \"New York\"}\n```\n\n**Sample Output 1:**\n```\nTrue\n```\n\n**Sample Input 2:**\n```json\n{\"name\": \"John\", \"age\": 30, \"city\": \"New York\"\n```\n\n**Sample Output 2:**\n```\nFalse\n```", "reference": "import json\n\ndef validate_json(json_string):\n \"\"\"\n Validates if the given JSON string is well-formed.\n\n Parameters:\n json_string (str): The JSON string to be validated.\n\n Returns:\n bool: True if the JSON string is well-formed, False otherwise.\n \"\"\"\n try:\n json.loads(json_string)\n except (json.JSONDecodeError, TypeError):\n return False\n return True", "tests": ["assert validate_json('{\"name\": \"John\", \"age\": 30, \"city\": \"New York\"}') == True", "assert validate_json('{\"name\": \"John\", \"age\": 30, \"city\": \"New York\"') == False", "assert validate_json('{\"name\": \"John\", \"age\": 30, \"city\": \"New York\",}') == False", "assert validate_json('{\"name\": \"John\", \"age\": 30, \"city\": \"New York\", \"is_student\": false}') == True", "assert validate_json('{\"name\": \"John\", \"age\": 30, \"city\": \"New York\", \"is_student\": False}') == True", "assert validate_json('{\"name\": \"John\", \"age\": 30, \"city\": \"New York\", \"is_student\": \"False\"}') == True", "assert validate_json('{\"name\": \"John\", \"age\": 30, \"city\": \"New York\", \"is_student\": null}') == True", "assert validate_json('{\"name\": \"John\", \"age\": 30, \"city\": \"New York\", \"is_student\": \"null\"}') == True", "assert validate_json('{\"name\": \"John\", \"age\": 30, \"city\": \"New York\", \"is_student\": \"true\"}') == True", "assert validate_json('{\"name\": \"John\", \"age\": 30, \"city\": \"New York\", \"is_student\": true}') == True"], "function": "validate_json", "signature": "def validate_json(json_string):", "score": 0.9, "domain": "generic"} {"id": "14aa0d6310d47dae978ebee83e5d1407", "problem": "You are given a string `s`. Your task is to determine whether the string is a palindrome. A string is considered a palindrome if it reads the same backward as forward, ignoring spaces and case sensitivity. \n\n**Input:**\n- A single line containing the string `s` (1 ≤ |s| ≤ 1000).\n\n**Output:**\n- Print `True` if the string is a palindrome, otherwise print `False`.\n\n**Sample Input:**\n```\nracecar\n```\n\n**Sample Output:**\n```\nTrue\n```", "reference": "def is_palindrome(s):\n \"\"\"\n Determines if the given string is a palindrome, ignoring spaces and case sensitivity.\n\n :param s: The input string to check.\n :return: True if the string is a palindrome, False otherwise.\n \"\"\"\n s = s.replace(\" \", \"\").lower()\n return s == s[::-1]\n\n# Example usage\nprint(is_palindrome(\"racecar\")) # Output: True", "tests": ["assert is_palindrome(\"racecar\") == True", "assert is_palindrome(\"A man a plan a canal Panama\") == False", "assert is_palindrome(\"A man a plan a canal panama\") == True", "assert is_palindrome(\"No lemon no melon\") == True", "assert is_palindrome(\"Was it a car or a cat I saw\") == False", "assert is_palindrome(\"Was it a car or a cat i saw\") == True", "assert is_palindrome(\"madam\") == True", "assert is_palindrome(\"12321\") == True", "assert is_palindrome(\"hello\") == False", "assert is_palindrome(\"\") == True"], "function": "is_palindrome", "signature": "def is_palindrome(s):", "score": 0.8, "domain": "algorithmic"} {"id": "f6f2a36f2c7a81e64cf1e6434d21c1bb", "problem": "You are given a function `is_prime(n)` that determines if a number `n` is prime. Your task is to optimize this function to improve its performance, especially for large values of `n`. The function should return `True` if `n` is a prime number and `False` otherwise.\n\n**Input:**\n- An integer `n` (1 ≤ n ≤ 10^12)\n\n**Output:**\n- A boolean value: `True` if `n` is prime, `False` otherwise.\n\n**Sample Input:**\n```\n29\n```\n\n**Sample Output:**\n```\nTrue\n```", "reference": "def is_prime(n):\n \"\"\"\n Determines if a number n is prime.\n\n Parameters:\n n (int): The number to check for primality.\n\n Returns:\n bool: True if n is prime, False otherwise.\n \"\"\"\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == 0 or n % 3 == 0:\n return False\n i = 5\n while i * i <= n:\n if n % i == 0 or n % (i + 2) == 0:\n return False\n i += 6\n return True", "tests": ["assert is_prime(2) == True", "assert is_prime(3) == True", "assert is_prime(4) == False", "assert is_prime(5) == True", "assert is_prime(9) == False", "assert is_prime(11) == True", "assert is_prime(15) == False", "assert is_prime(17) == True", "assert is_prime(19) == True", "assert is_prime(20) == False"], "function": "is_prime", "signature": "def is_prime(n):", "score": 1.0, "domain": "generic"} {"id": "35ebcb4e0e1ac6de59c14f4d254172b5", "problem": "You are given a function `add_numbers` that takes two parameters `a` and `b`. These parameters can be either integers or strings that represent valid integers. Your task is to modify the function to handle the following cases:\n- If `a` or `b` is a string representing a valid integer, convert it to an integer.\n- If `a` or `b` is not a valid integer or a string representing a valid integer, raise a `ValueError` with the message \"Both inputs must be numbers or strings representing numbers.\"\n\n**Sample Input 1:**\n```\nadd_numbers(\"10\", 20)\n```\n**Sample Output 1:**\n```\n30\n```\n\n**Sample Input 2:**\n```\nadd_numbers(\"abc\", 5)\n```\n**Sample Output 2:**\n```\nValueError: Both inputs must be numbers or strings representing numbers.\n```", "reference": "def add_numbers(a, b):\n \"\"\"\n Adds two numbers or strings representing numbers.\n \n Parameters:\n a (int or str): The first number or string representing a number.\n b (int or str): The second number or string representing a number.\n \n Returns:\n int: The sum of the two numbers.\n \n Raises:\n ValueError: If either input is not a number or a string representing a number.\n \"\"\"\n try:\n a = int(a)\n b = int(b)\n except ValueError:\n raise ValueError(\"Both inputs must be numbers or strings representing numbers.\")\n \n return a + b", "tests": ["assert add_numbers(5, 10) == 15", "assert add_numbers(\"5\", \"10\") == 15", "assert add_numbers(\"100\", 200) == 300", "assert add_numbers(300, \"400\") == 700", "assert add_numbers(\"0\", \"0\") == 0", "assert add_numbers(\"-5\", \"5\") == 0", "assert add_numbers(\"123456789\", \"987654321\") == 1111111110", "assert add_numbers(\"10\", \"abc\") == \"ValueError\"", "assert add_numbers(\"xyz\", \"10\") == \"ValueError\"", "assert add_numbers(\"abc\", \"xyz\") == \"ValueError\""], "function": "add_numbers", "signature": "def add_numbers(a, b):", "score": 0.7, "domain": "generic"} {"id": "7c85c22c3eb31312ffc841f64eb3133e", "problem": "You are tasked with implementing an efficient algorithm to find all prime numbers up to a given integer `n`. Your solution should utilize the Sieve of Eratosthenes method. Write a function named `sieve_of_eratosthenes(n)` that returns a list of all prime numbers less than or equal to `n`.\n\n**Input:**\n- An integer `n` (2 ≤ n ≤ 10^6)\n\n**Output:**\n- A list of integers representing all prime numbers up to `n`.\n\n**Sample Input:**\n```\n30\n```\n\n**Sample Output:**\n```\n[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]\n```", "reference": "def sieve_of_eratosthenes(n):\n \"\"\"\n Returns a list of all prime numbers up to a given integer n using the Sieve of Eratosthenes algorithm.\n \n :param n: An integer representing the upper limit (inclusive) for finding prime numbers.\n :return: A list of integers representing all prime numbers up to n.\n \"\"\"\n prime = [True] * (n + 1)\n p = 2\n while p * p <= n:\n if prime[p]:\n for i in range(p * p, n + 1, p):\n prime[i] = False\n p += 1\n return [p for p in range(2, n + 1) if prime[p]]", "tests": ["assert sieve_of_eratosthenes(10) == [2, 3, 5, 7]", "assert sieve_of_eratosthenes(20) == [2, 3, 5, 7, 11, 13, 17, 19]", "assert sieve_of_eratosthenes(1) == []", "assert sieve_of_eratosthenes(2) == [2]", "assert sieve_of_eratosthenes(0) == []", "assert sieve_of_eratosthenes(30) == [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]", "assert sieve_of_eratosthenes(50) == [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]", "assert sieve_of_eratosthenes(100) == [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]", "assert sieve_of_eratosthenes(15) == [2, 3, 5, 7, 11, 13]", "assert sieve_of_eratosthenes(101) == [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101]"], "function": "sieve_of_eratosthenes", "signature": "def sieve_of_eratosthenes(n):", "score": 1.0, "domain": "generic"} {"id": "157c28e26cdc2f7a64252f9f5aeceafb", "problem": "You are given a list of strings. Your task is to implement a function `filter_strings` that processes this list and returns a new list containing only those strings that do not contain any special characters. Special characters are defined as any character that is not a letter (a-z, A-Z) or a digit (0-9). The resulting list should be sorted in lexicographical order.\n\n**Input:**\n- A list of strings, where each string consists of characters from the ASCII set.\n\n**Output:**\n- A list of strings that do not contain any special characters, sorted in lexicographical order.\n\n**Sample Input:**\n```python\n[\"Hello World!\", \"12345\", \"@Python\", \"Coding101\"]\n```\n\n**Sample Output:**\n```python\n['12345', 'Coding101']\n```", "reference": "def filter_strings(strings):\n \"\"\"\n Filters a list of strings to include only those without special characters,\n then sorts the resulting list lexicographically.\n\n :param strings: List of strings to be filtered and sorted.\n :return: A sorted list of strings without special characters.\n \"\"\"\n import re\n pattern = re.compile(r'^[a-zA-Z0-9]+$')\n filtered_list = [s for s in strings if pattern.match(s)]\n filtered_list.sort()\n return filtered_list\n\n# Example usage:\nexample_input = [\"Hello World!\", \"12345\", \"@Python\", \"Coding101\"]\nprint(filter_strings(example_input)) # Output: ['12345', 'Coding101']", "tests": ["assert filter_strings([\"Hello World!\", \"12345\", \"@Python\", \"Coding101\"]) == [\"12345\", \"Coding101\"]", "assert filter_strings([\"abc\", \"def!\", \"ghi\", \"jkl@\"]) == [\"abc\", \"ghi\"]", "assert filter_strings([\"123\", \"456!\", \"789\", \"012@\"]) == [\"012\", \"123\", \"456\", \"789\"]", "assert filter_strings([\"NoSpecialChars\", \"Has#Special\", \"OnlyNumbers123\", \"With-Space\"]) == [\"NoSpecialChars\", \"OnlyNumbers123\"]", "assert filter_strings([\"\", \"a\", \"b!\", \"c123\"]) == [\"\", \"a\", \"c123\"]", "assert filter_strings([\"Special_Characters!\", \"Allowed123\", \"Another!Test\", \"Valid\"]) == [\"Allowed123\", \"Valid\"]", "assert filter_strings([\"123abc\", \"abc123!\", \"abc\", \"123\"]) == [\"123\", \"123abc\", \"abc\"]", "assert filter_strings([\"NoSpecial\", \"CharactersHere\", \"Just\", \"Numbers123\"]) == [\"CharactersHere\", \"Just\", \"NoSpecial\", \"Numbers123\"]", "assert filter_strings([\"!@#$%\", \"^&*()\", \"_____\", \"\"]) == [\"\"]", "assert filter_strings([\"a1\", \"b2!\", \"c3\", \"d4@\"]) == [\"a1\", \"c3\"]"], "function": "filter_strings", "signature": "def filter_strings(strings):", "score": 0.7, "domain": "generic"} {"id": "ed78681ba25da0ea9d5766248b0b87e3", "problem": "You are tasked with implementing a function `calculate_fibonacci(n)` that generates the Fibonacci sequence up to the `n`th number. The Fibonacci sequence is defined as a series of numbers where each number is the sum of the two preceding ones, starting with 0 and 1. Your function should return a list containing the sequence. If `n` is less than 1, the function should return an empty list. The function should be optimized to efficiently handle large values of `n`.\n\n**Input:**\n- An integer `n` (1 ≤ n ≤ 10^6)\n\n**Output:**\n- A list of integers representing the Fibonacci sequence up to the `n`th number.\n\n**Sample Input:**\n```\n10\n```\n\n**Sample Output:**\n```\n[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]\n```", "reference": "def calculate_fibonacci(n):\n \"\"\"\n Generate a list containing the Fibonacci sequence up to the nth number.\n \n Parameters:\n n (int): The number of terms in the Fibonacci sequence to generate.\n \n Returns:\n list: A list of integers representing the Fibonacci sequence up to the nth number.\n \"\"\"\n if n < 1:\n return []\n\n fib_sequence = [0, 1]\n if n == 1:\n return [0]\n elif n == 2:\n return fib_sequence\n\n for i in range(2, n):\n fib_sequence.append(fib_sequence[-1] + fib_sequence[-2])\n\n return fib_sequence\n\n# Example usage:\n# print(calculate_fibonacci(10)) # Output: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]", "tests": ["assert calculate_fibonacci(0) == []", "assert calculate_fibonacci(1) == [0]", "assert calculate_fibonacci(2) == [0, 1]", "assert calculate_fibonacci(3) == [0, 1, 1]", "assert calculate_fibonacci(5) == [0, 1, 1, 2, 3]", "assert calculate_fibonacci(10) == [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]", "assert calculate_fibonacci(15) == [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377]", "assert calculate_fibonacci(20) == [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181]", "assert calculate_fibonacci(1) == [0]", "assert calculate_fibonacci(25) == [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368]"], "function": "calculate_fibonacci", "signature": "def calculate_fibonacci(n):", "score": 1.0, "domain": "generic"} {"id": "ad998ca61ab69f0a8ad418030cb9444a", "problem": "You are given a list of tuples, where each tuple consists of a city name (a string) and its distance from a central location (an integer). Your task is to sort this list of tuples based on the distance in ascending order. If two cities have the same distance, they should be sorted alphabetically by their city names. Implement a sorting algorithm manually without using any built-in sorting functions or libraries.\n\n**Input:**\n- A list of tuples, where each tuple is in the form `(city_name, distance)`.\n- The list can contain up to 100 tuples.\n- City names are non-empty strings consisting of uppercase and lowercase letters.\n- Distances are non-negative integers.\n\n**Output:**\n- A list of tuples sorted as per the specified criteria.\n\n**Sample Input:**\n```python\n[(\"Berlin\", 100), (\"Amsterdam\", 50), (\"Zurich\", 150), (\"Oslo\", 50)]\n```\n\n**Sample Output:**\n```python\n[(\"Amsterdam\", 50), (\"Oslo\", 50), (\"Berlin\", 100), (\"Zurich\", 150)]\n```", "reference": "def custom_sort(cities):\n \"\"\"\n Sorts a list of tuples based on the distance in ascending order.\n If two cities have the same distance, they are sorted alphabetically by city name.\n \n :param cities: List of tuples, where each tuple is (city_name, distance)\n :return: Sorted list of tuples\n \"\"\"\n n = len(cities)\n for i in range(n):\n for j in range(0, n-i-1):\n if cities[j][1] > cities[j+1][1] or (cities[j][1] == cities[j+1][1] and cities[j][0] > cities[j+1][0]):\n cities[j], cities[j+1] = cities[j+1], cities[j]\n return cities\n\n# Example usage:\ncities = [(\"Berlin\", 100), (\"Amsterdam\", 50), (\"Zurich\", 150), (\"Oslo\", 50)]\nsorted_cities = custom_sort(cities)\nprint(sorted_cities)", "tests": ["assert custom_sort([(\"Berlin\", 100), (\"Amsterdam\", 50), (\"Zurich\", 150), (\"Oslo\", 50)]) == [(\"Amsterdam\", 50), (\"Oslo\", 50), (\"Berlin\", 100), (\"Zurich\", 150)]", "assert custom_sort([(\"New York\", 300), (\"Los Angeles\", 400), (\"Chicago\", 250)]) == [(\"Chicago\", 250), (\"New York\", 300), (\"Los Angeles\", 400)]", "assert custom_sort([(\"Paris\", 200), (\"London\", 200), (\"Madrid\", 200)]) == [(\"London\", 200), (\"Madrid\", 200), (\"Paris\", 200)]", "assert custom_sort([(\"Tokyo\", 100), (\"Kyoto\", 100), (\"Osaka\", 100), (\"Nagoya\", 100)]) == [(\"Kyoto\", 100), (\"Nagoya\", 100), (\"Osaka\", 100), (\"Tokyo\", 100)]", "assert custom_sort([(\"Rome\", 150), (\"Milan\", 150), (\"Naples\", 150), (\"Turin\", 150)]) == [(\"Milan\", 150), (\"Naples\", 150), (\"Rome\", 150), (\"Turin\", 150)]", "assert custom_sort([(\"Sydney\", 500), (\"Melbourne\", 500), (\"Brisbane\", 500), (\"Perth\", 500)]) == [(\"Brisbane\", 500), (\"Melbourne\", 500), (\"Perth\", 500), (\"Sydney\", 500)]", "assert custom_sort([(\"Houston\", 200), (\"Dallas\", 200), (\"Austin\", 200), (\"San Antonio\", 200)]) == [(\"Austin\", 200), (\"Dallas\", 200), (\"Houston\", 200), (\"San Antonio\", 200)]", "assert custom_sort([(\"Miami\", 100), (\"Orlando\", 100), (\"Tampa\", 100), (\"Jacksonville\", 100)]) == [(\"Jacksonville\", 100), (\"Miami\", 100), (\"Orlando\", 100), (\"Tampa\", 100)]", "assert custom_sort([(\"Seattle\", 300), (\"Portland\", 300), (\"San Francisco\", 300), (\"Sacramento\", 300)]) == [(\"Portland\", 300), (\"Sacramento\", 300), (\"San Francisco\", 300), (\"Seattle\", 300)]", "assert custom_sort([]) == []"], "function": "custom_sort", "signature": "def custom_sort(cities):", "score": 1.0, "domain": "generic"} {"id": "ef8acac83fe05077c664c7a4326700c6", "problem": "You are given two lists, `group_labels` and `team_labels`, each of length `n`, representing the true and predicted group labels for `n` individuals, respectively. Your task is to determine the number of false negative groupings. A false negative occurs when two individuals who are in the same true group are predicted to be in different groups. You must implement this without using any built-in set operations or dictionary structures.\n\n**Input:**\n- Two lists of integers, `group_labels` and `team_labels`, each of length `n` (1 ≤ n ≤ 1000).\n- Each element in `group_labels` and `team_labels` is an integer between 1 and 1000, inclusive.\n\n**Output:**\n- An integer representing the number of false negative groupings.\n\n**Sample Input:**\n```\ngroup_labels = [1, 1, 2, 2, 3, 3]\nteam_labels = [1, 1, 1, 2, 3, 3]\n```\n\n**Sample Output:**\n```\n1\n```", "reference": "def count_false_negatives(group_labels, team_labels):\n \"\"\"\n Counts the number of false negative groupings between true and predicted labels.\n \n :param group_labels: List of integers representing true group labels.\n :param team_labels: List of integers representing predicted group labels.\n :return: Integer count of false negative groupings.\n \"\"\"\n false_negatives = 0\n\n for i in range(len(group_labels)):\n for j in range(i + 1, len(group_labels)):\n if group_labels[i] == group_labels[j] and team_labels[i] != team_labels[j]:\n false_negatives += 1\n\n return false_negatives\n\n# Example usage:\ngroup_labels = [1, 1, 2, 2, 3, 3]\nteam_labels = [1, 1, 1, 2, 3, 3]\n\nprint(count_false_negatives(group_labels, team_labels)) # Outputs 1", "tests": ["assert count_false_negatives([1, 1, 2, 2], [1, 1, 2, 2]) == 0", "assert count_false_negatives([1, 1, 2, 2], [1, 2, 1, 2]) == 2", "assert count_false_negatives([1, 2, 3, 4], [1, 2, 3, 4]) == 0", "assert count_false_negatives([1, 1, 1, 1], [1, 2, 3, 4]) == 6", "assert count_false_negatives([1, 2, 2, 3], [1, 2, 3, 3]) == 1", "assert count_false_negatives([1, 1, 2, 2, 3, 3], [1, 1, 1, 2, 3, 3]) == 1", "assert count_false_negatives([1, 2, 3, 4, 5], [5, 4, 3, 2, 1]) == 10", "assert count_false_negatives([], []) == 0", "assert count_false_negatives([1], [1]) == 0", "assert count_false_negatives([1, 1, 1, 2, 2, 2], [1, 1, 2, 2, 2, 1]) == 3"], "function": "count_false_negatives", "signature": "def count_false_negatives(group_labels, team_labels):", "score": 0.8, "domain": "generic"} {"id": "12180fe02f02165b1e05f1d508e314b4", "problem": "You are given the task of simulating the effect of overlaying two semi-transparent images on top of each other. Each pixel in the images is represented by an RGB tuple, where each channel value ranges from 0 to 255. A value of 0 indicates complete transparency, while 255 indicates complete opacity. Your goal is to compute the resulting RGB value after overlaying the two images using the formula: `result = 255 - (255 - a) * (255 - b) // 255` for each color channel.\n\nWrite a function `overlay_images(a, b)` that takes two RGB tuples `a` and `b` as input and returns the resulting RGB tuple after overlaying the two images.\n\n**Sample Input:**\n```\na = (128, 64, 32)\nb = (255, 128, 64)\n```\n\n**Sample Output:**\n```\n(255, 192, 128)\n```", "reference": "def overlay_images(a, b):\n \"\"\"\n Simulates the effect of layering two semi-transparent images on top of each other.\n \n Parameters:\n a (tuple): The RGB tuple of the first image pixel.\n b (tuple): The RGB tuple of the second image pixel.\n \n Returns:\n tuple: The resulting RGB tuple after layering the two images.\n \"\"\"\n def overlay_channel(achan, bchan):\n \"\"\"\n Calculate the resulting pixel value for a single color channel.\n \n Parameters:\n achan (int): The value of the first image pixel's color channel.\n bchan (int): The value of the second image pixel's color channel.\n \n Returns:\n int: The resulting value after layering the two images' color channels.\n \"\"\"\n return 255 - (255 - achan) * (255 - bchan) // 255\n \n # Calculate the resulting pixel value for each color channel\n r = overlay_channel(a[0], b[0])\n g = overlay_channel(a[1], b[1])\n b = overlay_channel(a[2], b[2])\n \n return (r, g, b)", "tests": ["assert overlay_images((0, 0, 0), (0, 0, 0)) == (0, 0, 0)", "assert overlay_images((255, 255, 255), (255, 255, 255)) == (255, 255, 255)", "assert overlay_images((128, 128, 128), (128, 128, 128)) == (192, 192, 192)", "assert overlay_images((255, 0, 0), (0, 255, 0)) == (255, 255, 0)", "assert overlay_images((0, 0, 255), (255, 255, 0)) == (255, 255, 255)", "assert overlay_images((100, 150, 200), (50, 100, 150)) == (145, 195, 235)", "assert overlay_images((255, 255, 255), (0, 0, 0)) == (255, 255, 255)", "assert overlay_images((0, 0, 0), (255, 255, 255)) == (255, 255, 255)", "assert overlay_images((128, 64, 32), (255, 128, 64)) == (255, 192, 128)", "assert overlay_images((200, 100, 50), (50, 100, 200)) == (235, 195, 145)"], "function": "overlay_images", "signature": "def overlay_images(a, b):", "score": 0.7, "domain": "generic"} {"id": "7896a59f55d10437fa7627a42a2c8bd0", "problem": "You are given a binary tree represented as a nested list in the format `[value, left_subtree, right_subtree]`. Each node in the tree can either be a leaf node (represented as a single integer) or an internal node (represented as a list). Your task is to write a Python function named `convert_to_array` that takes the binary tree as input and returns a 1D array representing the tree in pre-order traversal.\n\n**Input:**\n- A binary tree represented as a nested list.\n\n**Output:**\n- A list of integers representing the pre-order traversal of the binary tree.\n\n**Sample Input:**\n```\n[1, [2, 3, 4], [5, 6, 7]]\n```\n\n**Sample Output:**\n```\n[1, 2, 3, 4, 5, 6, 7]\n```", "reference": "def convert_to_array(binary_tree):\n \"\"\"\n Converts a binary tree represented as a nested list into a 1D array\n in pre-order traversal.\n\n :param binary_tree: A nested list representing the binary tree.\n :return: A list of integers representing the pre-order traversal.\n \"\"\"\n def preorder_traversal(node):\n if isinstance(node, int): # Base case: leaf node\n return [node]\n else: # Internal node\n result = [node[0]] # Add the root\n if node[1]: # Traverse left subtree if it exists\n result.extend(preorder_traversal(node[1]))\n if node[2]: # Traverse right subtree if it exists\n result.extend(preorder_traversal(node[2]))\n return result\n\n return preorder_traversal(binary_tree)", "tests": ["assert convert_to_array([1, [2, 3, 4], [5, 6, 7]]) == [1, 2, 3, 4, 5, 6, 7]", "assert convert_to_array([1, None, None]) == [1]", "assert convert_to_array([1, [2, None, None], [3, None, None]]) == [1, 2, 3]", "assert convert_to_array([1, [2, [3, None, None], None], [4, None, [5, None, None]]]) == [1, 2, 3, 4, 5]", "assert convert_to_array([1, [2, [3, [4, None, None], None], None], [5, None, [6, None, [7, None, None]]]]) == [1, 2, 3, 4, 5, 6, 7]", "assert convert_to_array([1, [2, [3, [4, [5, None, None], None], None], None], [6, None, [7, None, [8, None, [9, None, None]]]]]) == [1, 2, 3, 4, 5, 6, 7, 8, 9]", "assert convert_to_array([1, [2, [3, [4, [5, [6, [7, None, None], None], None], None], None], None], [8, None, [9, None, [10, None, [11, None, None]]]]]) == [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]", "assert convert_to_array([1, [2, [3, [4, [5, [6, [7, [8, [9, [10, None, None], None], None], None], None], None], None], None], [11, None, [12, None, [13, None, [14, None, [15, None, None]]]]]]) == [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]", "assert convert_to_array([1, [2, [3, [4, [5, [6, [7, [8, [9, [10, [11, [12, [13, [14, [15, None, None], None], None], None], None], None], None], None], None], None], None], None], [16, None, [17, None, [18, None, [19, None, [20, None, None]]]]]]) == [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]", "assert convert_to_array(None) == []"], "function": "convert_to_array", "signature": "def convert_to_array(binary_tree):", "score": 0.7, "domain": "generic"} {"id": "7f3d774b7290b001db214d7742a02a06", "problem": "You are given a string `s`. Your task is to implement a function that finds the longest substring without repeating characters. If there are multiple substrings of the same maximum length, return the one that appears first. \n\n**Input:**\n- A single string `s` (1 ≤ |s| ≤ 10^4), consisting of lowercase English letters.\n\n**Output:**\n- A string representing the longest substring without repeating characters.\n\n**Sample Input:**\n```\npwwkew\n```\n\n**Sample Output:**\n```\nwke\n```", "reference": "def longest_unique_substring(s: str) -> str:\n \"\"\"\n Finds the longest substring without repeating characters in the given string.\n\n :param s: The input string.\n :return: The longest substring without repeating characters.\n \"\"\"\n n = len(s)\n max_length = 0\n start = 0\n max_substring = \"\"\n char_index_map = {}\n\n for end in range(n):\n if s[end] in char_index_map:\n start = max(start, char_index_map[s[end]] + 1)\n\n char_index_map[s[end]] = end\n\n if end - start + 1 > max_length:\n max_length = end - start + 1\n max_substring = s[start:end+1]\n\n return max_substring\n\n# Test the function\ntext = \"pwwkew\"\nprint(longest_unique_substring(text)) # Output: \"wke\"", "tests": ["assert longest_unique_substring(\"abcabcbb\") == \"abc\"", "assert longest_unique_substring(\"bbbbb\") == \"b\"", "assert longest_unique_substring(\"pwwkew\") == \"wke\"", "assert longest_unique_substring(\"dvdf\") == \"vdf\"", "assert longest_unique_substring(\"anviaj\") == \"anviaj\"", "assert longest_unique_substring(\"abcdef\") == \"abcdef\"", "assert longest_unique_substring(\"aabbcc\") == \"ab\"", "assert longest_unique_substring(\"\") == \"\"", "assert longest_unique_substring(\"a\") == \"a\"", "assert longest_unique_substring(\"abba\") == \"ab\""], "function": "longest_unique_substring", "signature": "def longest_unique_substring(s: str) -> str:", "score": 0.9, "domain": "algorithmic"} {"id": "fdeda4bdfbfe2acd9d932b7481abeab3", "problem": "You are given a string `s`. Your task is to write a function that counts the number of vowels (both uppercase and lowercase) present in the string. The function should return this count as an integer.\n\n**Input:**\n- A single string `s` (1 ≤ |s| ≤ 10^5), consisting of ASCII characters.\n\n**Output:**\n- An integer representing the number of vowels in the string.\n\n**Sample Input:**\n```\nHello World\n```\n\n**Sample Output:**\n```\n3\n```", "reference": "def count_vowels(input_string):\n \"\"\"\n Counts the number of vowels in the given string.\n\n Parameters:\n input_string (str): The string in which to count vowels.\n\n Returns:\n int: The number of vowels in the input string.\n \"\"\"\n vowels = set('aeiouAEIOU')\n return sum(1 for char in input_string if char in vowels)\n\n# Example usage\nprint(count_vowels(\"Hello World\")) # Output: 3", "tests": ["assert count_vowels(\"Hello World\") == 3", "assert count_vowels(\"Python Programming\") == 4", "assert count_vowels(\"AEIOUaeiou\") == 10", "assert count_vowels(\"\") == 0", "assert count_vowels(\"bcdfg\") == 0", "assert count_vowels(\"abcdefghijklmnopqrstuvwxyz\") == 5", "assert count_vowels(\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\") == 5", "assert count_vowels(\"1234567890\") == 0", "assert count_vowels(\"!@#$%^&*()\") == 0", "assert count_vowels(\"A quick brown fox jumps over the lazy dog\") == 11"], "function": "count_vowels", "signature": "def count_vowels(input_string):", "score": 1.0, "domain": "generic"} {"id": "48cd741ac1f871eb6bf7af8daafa2bd5", "problem": "You are given a string `expression` consisting of characters '(', ')', '{', '}', '[' and ']'. Your task is to determine if the string is balanced. A string is considered balanced if every opening parenthesis, bracket, or brace is matched with a corresponding closing parenthesis, bracket, or brace in the correct order. For example, the string \"([{}])\" is balanced, whereas the string \"([)]\" is not.\n\n**Input:**\n- A single string `expression` (1 ≤ |expression| ≤ 10^3) containing only the characters '(', ')', '{', '}', '[' and ']'.\n\n**Output:**\n- Return `True` if the string is balanced, otherwise return `False`.\n\n**Sample Input:**\n```\n([{}])\n```\n\n**Sample Output:**\n```\nTrue\n```\n\n**Sample Input:**\n```\n([)]\n```\n\n**Sample Output:**\n```\nFalse\n```", "reference": "def is_balanced_parentheses(expression):\n \"\"\"\n Determines if the given expression containing parentheses, brackets, and braces is balanced.\n \n :param expression: A string consisting of '(', ')', '{', '}', '[' and ']'.\n :return: True if the expression is balanced, False otherwise.\n \"\"\"\n matching_bracket = {')': '(', '}': '{', ']': '['}\n stack = []\n\n for char in expression:\n if char in matching_bracket:\n top_element = stack.pop() if stack else '#'\n if matching_bracket[char] != top_element:\n return False\n else:\n stack.append(char)\n\n return not stack", "tests": ["assert is_balanced_parentheses(\"([{}])\") == True", "assert is_balanced_parentheses(\"([)]\") == False", "assert is_balanced_parentheses(\"{[()]}\") == True", "assert is_balanced_parentheses(\"{[(])}\") == False", "assert is_balanced_parentheses(\"\") == True", "assert is_balanced_parentheses(\"((((()))))\") == True", "assert is_balanced_parentheses(\"((((())))\") == False", "assert is_balanced_parentheses(\"[{()}]\") == True", "assert is_balanced_parentheses(\"{{{{}}}}\") == True", "assert is_balanced_parentheses(\"{{{{}}\") == False"], "function": "is_balanced_parentheses", "signature": "def is_balanced_parentheses(expression):", "score": 1.0, "domain": "generic"} {"id": "5eaac0d485035828d2bc5f1206c8d16f", "problem": "You are given a list of `m` words. Your task is to implement a function `top_n_frequent_words(words, n)` that returns a list of the top `n` most frequent words in the list, along with their frequencies. The list should be sorted in descending order of frequency, and words with the same frequency should be sorted alphabetically. \n\n**Input:**\n- A list of strings `words` (1 ≤ m ≤ 10^4), where each string consists of lowercase English letters.\n- An integer `n` (1 ≤ n ≤ m), representing the number of top frequent words to return.\n\n**Output:**\n- A list of tuples, where each tuple contains a word and its frequency, sorted as specified.\n\n**Sample Input:**\n```\nwords = [\"apple\", \"banana\", \"apple\", \"orange\", \"banana\", \"apple\", \"banana\"]\nn = 2\n```\n\n**Sample Output:**\n```\n[(\"apple\", 3), (\"banana\", 3)]\n```", "reference": "from collections import Counter\n\ndef top_n_frequent_words(words, n):\n \"\"\"\n Returns a list of the top n most frequent words in the list, along with their frequencies.\n The list is sorted in descending order of frequency, and words with the same frequency are sorted alphabetically.\n \n :param words: List of strings representing the words.\n :param n: Integer representing the number of top frequent words to return.\n :return: List of tuples, each containing a word and its frequency.\n \"\"\"\n word_counts = Counter(words)\n sorted_word_counts = sorted(word_counts.items(), key=lambda x: (-x[1], x[0]))\n return sorted_word_counts[:n]", "tests": ["assert top_n_frequent_words([\"apple\", \"banana\", \"apple\", \"orange\", \"banana\", \"apple\", \"banana\"], 2) == [(\"apple\", 3), (\"banana\", 3)]", "assert top_n_frequent_words([\"apple\", \"banana\", \"orange\"], 1) == [(\"apple\", 1)]", "assert top_n_frequent_words([\"apple\", \"banana\", \"apple\", \"orange\", \"banana\", \"apple\", \"banana\"], 3) == [(\"apple\", 3), (\"banana\", 3), (\"orange\", 1)]", "assert top_n_frequent_words([\"apple\", \"banana\", \"apple\", \"orange\", \"banana\", \"apple\", \"banana\"], 0) == []", "assert top_n_frequent_words([], 2) == []", "assert top_n_frequent_words([\"apple\", \"apple\", \"banana\", \"banana\", \"banana\", \"orange\", \"orange\", \"orange\", \"orange\"], 2) == [(\"orange\", 4), (\"banana\", 3)]", "assert top_n_frequent_words([\"apple\", \"banana\", \"apple\", \"orange\", \"banana\", \"apple\", \"banana\", \"grape\", \"grape\", \"grape\"], 3) == [(\"apple\", 3), (\"banana\", 3), (\"grape\", 3)]", "assert top_n_frequent_words([\"apple\", \"banana\", \"apple\", \"orange\", \"banana\", \"apple\", \"banana\", \"grape\", \"grape\", \"grape\"], 4) == [(\"apple\", 3), (\"banana\", 3), (\"grape\", 3), (\"orange\", 1)]", "assert top_n_frequent_words([\"apple\", \"banana\", \"apple\", \"orange\", \"banana\", \"apple\", \"banana\", \"grape\", \"grape\", \"grape\", \"kiwi\"], 5) == [(\"apple\", 3), (\"banana\", 3), (\"grape\", 3), (\"kiwi\", 1), (\"orange\", 1)]", "assert top_n_frequent_words([\"apple\", \"banana\", \"apple\", \"orange\", \"banana\", \"apple\", \"banana\", \"grape\", \"grape\", \"grape\", \"kiwi\", \"kiwi\"], 6) == [(\"apple\", 3), (\"banana\", 3), (\"grape\", 3), (\"kiwi\", 2), (\"orange\", 1)]"], "function": "top_n_frequent_words", "signature": "def top_n_frequent_words(words, n):", "score": 1.0, "domain": "generic"} {"id": "0d027da6ce1298340c4fd44eb4ba18cc", "problem": "You are tasked with implementing a unit test for the `sort_dictionaries_by_key` function using the `unittest` framework in Python. The function sorts a list of dictionaries based on a specified key. Your unit test should cover the following scenarios:\n- Dictionaries with missing keys.\n- Dictionaries with identical values for the sort key.\n- Dictionaries with distinct values for the sort key.\n\n**Function Signature:**\n```python\ndef sort_dictionaries_by_key(dict_list: List[Dict], sort_key: str) -> List[Dict]:\n```\n\n**Sample Input:**\n```python\ndict_list = [\n {'name': 'Alice', 'age': 30},\n {'name': 'Bob', 'age': 25},\n {'name': 'Charlie', 'age': 30}\n]\nsort_key = 'age'\n```\n\n**Sample Output:**\n```python\n[\n {'name': 'Bob', 'age': 25},\n {'name': 'Alice', 'age': 30},\n {'name': 'Charlie', 'age': 30}\n]\n```", "reference": "from typing import List, Dict\nimport unittest\n\ndef sort_dictionaries_by_key(dict_list: List[Dict], sort_key: str) -> List[Dict]:\n \"\"\"\n Sorts a list of dictionaries by a specified key.\n \n Parameters:\n dict_list (List[Dict]): List of dictionaries to be sorted.\n sort_key (str): The key to sort the dictionaries by.\n \n Returns:\n List[Dict]: The sorted list of dictionaries.\n \"\"\"\n try:\n return sorted(dict_list, key=lambda x: x[sort_key])\n except KeyError:\n return dict_list # or some other error handling\n\nclass TestSortDictionariesByKey(unittest.TestCase):\n def test_missing_keys(self):\n dict_list = [{'name': 'Alice'}, {'name': 'Bob', 'age': 25}, {'name': 'Charlie'}]\n sort_key = 'age'\n self.assertEqual(sort_dictionaries_by_key(dict_list, sort_key), [{'name': 'Alice'}, {'name': 'Bob', 'age': 25}, {'name': 'Charlie'}])\n\n def test_same_key_values(self):\n dict_list = [{'name': 'Alice', 'age': 30}, {'name': 'Bob', 'age': 30}, {'name': 'Charlie', 'age': 30}]\n sort_key = 'age'\n self.assertEqual(sort_dictionaries_by_key(dict_list, sort_key), [{'name': 'Alice', 'age': 30}, {'name': 'Bob', 'age': 30}, {'name': 'Charlie', 'age': 30}])\n\n def test_different_key_values(self):\n dict_list = [{'name': 'Alice', 'age': 30}, {'name': 'Bob', 'age': 25}, {'name': 'Charlie', 'age': 35}]\n sort_key = 'age'\n self.assertEqual(sort_dictionaries_by_key(dict_list, sort_key), [{'name': 'Bob', 'age': 25}, {'name': 'Alice', 'age': 30}, {'name': 'Charlie', 'age': 35}])\n\nif __name__ == '__main__':\n unittest.main()", "tests": ["assert sort_dictionaries_by_key([{\"name\": \"Alice\", \"age\": 25}, {\"name\": \"Bob\", \"age\": 20}], \"age\") == [{\"name\": \"Bob\", \"age\": 20}, {\"name\": \"Alice\", \"age\": 25}]", "assert sort_dictionaries_by_key([{\"name\": \"Alice\", \"age\": 25}, {\"name\": \"Bob\", \"age\": 25}], \"age\") == [{\"name\": \"Alice\", \"age\": 25}, {\"name\": \"Bob\", \"age\": 25}]", "assert sort_dictionaries_by_key([{\"name\": \"Alice\", \"age\": 25}, {\"name\": \"Bob\"}], \"age\") == [{\"name\": \"Alice\", \"age\": 25}, {\"name\": \"Bob\"}]", "assert sort_dictionaries_by_key([{\"name\": \"Alice\", \"age\": 25}, {\"name\": \"Bob\", \"age\": 20}, {\"name\": \"Charlie\", \"age\": 30}], \"age\") == [{\"name\": \"Bob\", \"age\": 20}, {\"name\": \"Alice\", \"age\": 25}, {\"name\": \"Charlie\", \"age\": 30}]", "assert sort_dictionaries_by_key([{\"name\": \"Alice\"}, {\"name\": \"Bob\"}, {\"name\": \"Charlie\"}], \"age\") == [{\"name\": \"Alice\"}, {\"name\": \"Bob\"}, {\"name\": \"Charlie\"}]", "assert sort_dictionaries_by_key([], \"age\") == []", "assert sort_dictionaries_by_key([{\"name\": \"Alice\", \"age\": 25}, {\"name\": \"Bob\", \"age\": 20}, {\"name\": \"Charlie\", \"age\": 30}], \"name\") == [{\"name\": \"Alice\", \"age\": 25}, {\"name\": \"Bob\", \"age\": 20}, {\"name\": \"Charlie\", \"age\": 30}]", "assert sort_dictionaries_by_key([{\"name\": \"Charlie\", \"age\": 30}, {\"name\": \"Bob\", \"age\": 20}, {\"name\": \"Alice\", \"age\": 25}], \"name\") == [{\"name\": \"Alice\", \"age\": 25}, {\"name\": \"Bob\", \"age\": 20}, {\"name\": \"Charlie\", \"age\": 30}]", "assert sort_dictionaries_by_key([{\"name\": \"Alice\", \"age\": 25}, {\"name\": \"Bob\", \"age\": 20}, {\"name\": \"Charlie\", \"age\": 30}], \"height\") == [{\"name\": \"Alice\", \"age\": 25}, {\"name\": \"Bob\", \"age\": 20}, {\"name\": \"Charlie\", \"age\": 30}]", "assert sort_dictionaries_by_key([{\"name\": \"Alice\", \"age\": 25}, {\"name\": \"Bob\", \"age\": 20}, {\"name\": \"Charlie\", \"age\": 30}, {\"name\": \"David\", \"age\": 20}], \"age\") == [{\"name\": \"Bob\", \"age\": 20}, {\"name\": \"David\", \"age\": 20}, {\"name\": \"Alice\", \"age\": 25}, {\"name\": \"Charlie\", \"age\": 30}]"], "function": "sort_dictionaries_by_key", "signature": "def sort_dictionaries_by_key(dict_list: List[Dict], sort_key: str) -> List[Dict]:", "score": 1.0, "domain": "generic"} {"id": "7bf575df15e03f036187668637fd953b", "problem": "You are given a string `s`. Your task is to write a recursive function `permute` that generates all possible permutations of the string `s`. The function should return a list of all permutations. Note that the order of permutations in the output list does not matter.\n\n**Input:**\n- A single string `s` (1 ≤ |s| ≤ 6), where |s| denotes the length of the string.\n\n**Output:**\n- A list of strings, each representing a unique permutation of the input string `s`.\n\n**Sample Input:**\n```\n\"abc\"\n```\n\n**Sample Output:**\n```\n['abc', 'acb', 'bac', 'bca', 'cab', 'cba']\n```", "reference": "def permute(s):\n \"\"\"\n Generate all permutations of a given string using recursion.\n\n Parameters:\n s (str): The input string for which permutations are to be generated.\n\n Returns:\n list: A list containing all unique permutations of the input string.\n \"\"\"\n # Base case: if the string length is 1, return a list with the string itself\n if len(s) == 1:\n return [s]\n \n # List to store all permutations\n permutations = []\n \n # Iterate through the string and fix each character as the first character\n for i, char in enumerate(s):\n # Get the remaining string without the fixed character\n remaining = s[:i] + s[i+1:]\n \n # Recursively generate all permutations of the remaining string\n for perm in permute(remaining):\n # Concatenate the fixed character with each permutation of the remaining string\n permutations.append(char + perm)\n \n return permutations", "tests": ["assert permute(\"a\") == [\"a\"]", "assert permute(\"ab\") == [\"ab\", \"ba\"]", "assert permute(\"abc\") == [\"abc\", \"acb\", \"bac\", \"bca\", \"cab\", \"cba\"]", "assert permute(\"abcd\") == ['abcd', 'abdc', 'acbd', 'acdb', 'adbc', 'adcb', 'bacd', 'badc', 'bcad', 'bcda', 'bdac', 'bdca', 'cabd', 'cadb', 'cbad', 'cbda', 'cdab', 'cdba', 'dabc', 'dacb', 'dbac', 'dbca', 'dcab', 'dcba']", "assert permute(\"\") == [\"\"]", "assert permute(\"aa\") == [\"aa\", \"aa\"]", "assert permute(\"aaa\") == [\"aaa\", \"aaa\", \"aaa\", \"aaa\", \"aaa\", \"aaa\"]", "assert permute(\"123\") == ['123', '132', '213', '231', '312', '321']", "assert permute(\"!@#\") == ['!@#', '!#@', '@!#', '@#!', '#!@', '#@!']", "assert permute(\"xyz\") == ['xyz', 'xzy', 'yxz', 'yzx', 'zxy', 'zyx']"], "function": "permute", "signature": "def permute(s):", "score": 0.9, "domain": "generic"} {"id": "fb0f0399bd73013d188c128cdf75ea3c", "problem": "You are tasked with implementing a function `extract_emails` that processes a given string and identifies all valid email addresses contained within it. A valid email address is defined by the following pattern: one or more alphanumeric characters, dots, underscores, or hyphens, followed by an '@' symbol, then one or more alphanumeric characters or dots, and finally a dot followed by one or more alphabetic characters. Your function should return a list of all such valid email addresses found in the input string.\n\n**Input:**\n- A single string `text` (1 ≤ len(text) ≤ 1000) containing the text to be processed.\n\n**Output:**\n- A list of strings, each representing a valid email address found in the input string.\n\n**Sample Input:**\n```\nPlease contact us at support@example.com or sales@example.co.uk. Alternatively, reach out to john.doe_123@example.org.\n```\n\n**Sample Output:**\n```\n['support@example.com', 'sales@example.co.uk', 'john.doe_123@example.org']\n```", "reference": "import re\n\ndef extract_emails(text):\n \"\"\"\n Extracts all valid email addresses from the given text.\n\n Parameters:\n text (str): The input string containing potential email addresses.\n\n Returns:\n list: A list of valid email addresses found in the input string.\n \"\"\"\n email_pattern = r'[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]+'\n return re.findall(email_pattern, text)\n\n# Example usage\ntext = \"Please contact us at support@example.com or sales@example.co.uk. Alternatively, reach out to john.doe_123@example.org.\"\nprint(extract_emails(text))", "tests": ["assert extract_emails(\"Please contact us at support@example.com\") == [\"support@example.com\"]", "assert extract_emails(\"Reach out to john.doe_123@example.org\") == [\"john.doe_123@example.org\"]", "assert extract_emails(\"Invalid email: @example.com\") == []", "assert extract_emails(\"Multiple emails: test1@example.com, test2@example.org\") == [\"test1@example.com\", \"test2@example.org\"]", "assert extract_emails(\"No emails here!\") == []", "assert extract_emails(\"Email with subdomain: user@mail.example.com\") == [\"user@mail.example.com\"]", "assert extract_emails(\"Email with numbers: user123@numbers123.com\") == [\"user123@numbers123.com\"]", "assert extract_emails(\"Email with hyphens: user-name@domain-name.com\") == [\"user-name@domain-name.com\"]", "assert extract_emails(\"Email with dots: user.name@domain.name.com\") == [\"user.name@domain.name.com\"]", "assert extract_emails(\"Mixed content: text user@domain.com more text\") == [\"user@domain.com\"]"], "function": "extract_emails", "signature": "def extract_emails(text):", "score": 1.0, "domain": "generic"} {"id": "576d11eef4bffaf8a312f877ccd285d4", "problem": "You are tasked with implementing a function to encrypt a message using the Caesar cipher technique. The function should take a string `message` and an integer `key` as input. Each alphabetic character in the message should be shifted by `key` positions in the alphabet. Characters that are not alphabetic should remain unchanged. The function should return the encrypted message.\n\n**Input:**\n- A string `message` (1 ≤ len(message) ≤ 1000) consisting of printable ASCII characters.\n- An integer `key` (0 ≤ key ≤ 1000) representing the shift value.\n\n**Output:**\n- A string representing the encrypted message.\n\n**Sample Input:**\n```\nHello, World!\n3\n```\n\n**Sample Output:**\n```\nKhoor, Zruog!\n```", "reference": "def encrypt_message(message, key):\n \"\"\"\n Encrypts a given message using the Caesar cipher technique.\n \n Parameters:\n message (str): The message to be encrypted.\n key (int): The number of positions to shift each alphabetic character.\n \n Returns:\n str: The encrypted message.\n \"\"\"\n encrypted_message = []\n \n for char in message:\n if char.isalpha():\n shift = key % 26\n if char.islower():\n encrypted_char = chr((ord(char) - ord('a') + shift) % 26 + ord('a'))\n else:\n encrypted_char = chr((ord(char) - ord('A') + shift) % 26 + ord('A'))\n encrypted_message.append(encrypted_char)\n else:\n encrypted_message.append(char)\n \n return ''.join(encrypted_message)", "tests": ["assert encrypt_message('Hello, World!', 3) == 'Khoor, Zruog!'", "assert encrypt_message('abc', 1) == 'bcd'", "assert encrypt_message('xyz', 2) == 'zab'", "assert encrypt_message('ABC', 3) == 'DEF'", "assert encrypt_message('XYZ', 4) == 'BCD'", "assert encrypt_message('Python 3.8', 5) == 'Udymts 3.8'", "assert encrypt_message('Caesar Cipher!', 13) == 'Pnrfne Pvcure!'", "assert encrypt_message('Shift Me 123!', 10) == 'Cyrzr Wy 123!'", "assert encrypt_message('No Change!', 0) == 'No Change!'", "assert encrypt_message('Wrap Around Z!', 1) == 'Xsbq Bspvoe A!'"], "function": "encrypt_message", "signature": "def encrypt_message(message, key):", "score": 0.9, "domain": "generic"} {"id": "d7a75491dac9e8ab427093634fec537c", "problem": "You are given a dictionary `data` representing sensor readings, where each key is a sensor name and each value is the corresponding reading. Implement a function `filter_sensors(data, threshold)` that returns a new dictionary containing only the sensors with readings strictly greater than the specified `threshold`. \n\n**Input:**\n- A dictionary `data` with sensor names as keys and their readings as integer or float values.\n- An integer or float `threshold`.\n\n**Output:**\n- A dictionary with sensor names as keys and their readings as values, where each reading is greater than the `threshold`.\n\n**Sample Input:**\n```python\ndata = {\"sensor1\": 10, \"sensor2\": 20, \"sensor3\": 5}\nthreshold = 15\n```\n\n**Sample Output:**\n```python\n{\"sensor2\": 20}\n```", "reference": "def filter_sensors(data, threshold):\n \"\"\"\n Filters sensors based on the reading threshold.\n \n Parameters:\n - data: dict, a dictionary containing sensor names as keys and their readings as values\n - threshold: int or float, the threshold value to filter out sensors\n \n Returns:\n - dict, a dictionary containing only the sensors with readings above the threshold\n \"\"\"\n return {sensor: reading for sensor, reading in data.items() if reading > threshold}\n\n# Example usage\nexample_data = {\"sensor1\": 10, \"sensor2\": 20, \"sensor3\": 5}\nthreshold_value = 15\nfiltered_sensors = filter_sensors(example_data, threshold_value)\nprint(filtered_sensors) # Output: {'sensor2': 20}", "tests": ["assert filter_sensors({\"sensor1\": 10, \"sensor2\": 20, \"sensor3\": 5}, 15) == {\"sensor2\": 20}", "assert filter_sensors({\"sensorA\": 100, \"sensorB\": 50, \"sensorC\": 200}, 75) == {\"sensorA\": 100, \"sensorC\": 200}", "assert filter_sensors({\"sensorX\": 10, \"sensorY\": 10, \"sensorZ\": 10}, 10) == {}", "assert filter_sensors({\"sensorX\": 10, \"sensorY\": 10, \"sensorZ\": 10}, 9) == {\"sensorX\": 10, \"sensorY\": 10, \"sensorZ\": 10}", "assert filter_sensors({}, 10) == {}", "assert filter_sensors({\"sensor1\": 0, \"sensor2\": -10, \"sensor3\": -20}, -5) == {\"sensor1\": 0}", "assert filter_sensors({\"sensor1\": 10.5, \"sensor2\": 20.5, \"sensor3\": 5.5}, 10) == {\"sensor2\": 20.5}", "assert filter_sensors({\"sensor1\": 1000, \"sensor2\": 2000, \"sensor3\": 3000}, 1500) == {\"sensor2\": 2000, \"sensor3\": 3000}", "assert filter_sensors({\"sensor1\": 1, \"sensor2\": 2, \"sensor3\": 3}, 3) == {}", "assert filter_sensors({\"sensor1\": 1, \"sensor2\": 2, \"sensor3\": 3}, 0) == {\"sensor1\": 1, \"sensor2\": 2, \"sensor3\": 3}"], "function": "filter_sensors", "signature": "def filter_sensors(data, threshold):", "score": 0.9, "domain": "generic"} {"id": "16f372e031cca150b2860076dfc11df9", "problem": "You are given a list of book titles. Your task is to implement a function `find_common_words` that identifies common words across all titles, treating words with different cases as the same and considering only alphabetic characters. The function should return a dictionary where keys are the common words and values are the total number of times each common word appears in all titles.\n\n**Input:**\n- A list of strings `titles` (1 ≤ len(titles) ≤ 100), where each string represents a book title and has a length of at most 100 characters.\n\n**Output:**\n- A dictionary with common words as keys and their total occurrences across all titles as values.\n\n**Sample Input:**\n```python\ntitles = [\"The Great Gatsby\", \"The Grapes of Wrath\", \"The Great Alone\"]\n```\n\n**Sample Output:**\n```python\n{'the': 3, 'great': 2}\n```", "reference": "def find_common_words(titles):\n \"\"\"\n Finds common words in all book titles and returns a dictionary with the count of each common word.\n \n :param titles: List of book titles as strings.\n :return: Dictionary with common words as keys and their total occurrences as values.\n \"\"\"\n from collections import defaultdict\n import re\n \n word_lists = [set(re.findall(r'\\b[a-z]+\\b', title.lower())) for title in titles]\n common_words = set.intersection(*word_lists)\n \n word_count = defaultdict(int)\n for title in titles:\n words = re.findall(r'\\b[a-z]+\\b', title.lower())\n for word in words:\n if word in common_words:\n word_count[word] += 1\n \n return dict(word_count)", "tests": ["assert find_common_words([\"The Great Gatsby\", \"The Grapes of Wrath\", \"The Great Alone\"]) == {'the': 3, 'great': 2}", "assert find_common_words([\"To Kill a Mockingbird\", \"The Great Gatsby\", \"The Grapes of Wrath\"]) == {}", "assert find_common_words([\"A Tale of Two Cities\", \"A Tale of Two Brothers\", \"A Tale of Two Worlds\"]) == {'a': 3, 'tale': 3, 'of': 3, 'two': 3}", "assert find_common_words([\"1984\", \"Animal Farm\", \"Brave New World\"]) == {}", "assert find_common_words([\"The Catcher in the Rye\", \"The Catcher in the Rye\", \"The Catcher in the Rye\"]) == {'the': 3, 'catcher': 3, 'in': 3, 'rye': 3}", "assert find_common_words([\"\", \"\", \"\"]) == {}", "assert find_common_words([\"The Lord of the Rings\", \"The Lord of the Flies\", \"The Lord of the Web\"]) == {'the': 3, 'lord': 3, 'of': 3}", "assert find_common_words([\"Pride and Prejudice\", \"Pride and Prejudice and Zombies\", \"Pride and Prejudice and Zombies\"]) == {'pride': 3, 'and': 3, 'prejudice': 3}", "assert find_common_words([\"Harry Potter and the Sorcerer's Stone\", \"Harry Potter and the Chamber of Secrets\", \"Harry Potter and the Prisoner of Azkaban\"]) == {'harry': 3, 'potter': 3, 'and': 3, 'the': 3}", "assert find_common_words([\"The Hobbit\", \"The Hobbit\", \"The Hobbit\"]) == {'the': 3, 'hobbit': 3}"], "function": "find_common_words", "signature": "def find_common_words(titles):", "score": 0.6, "domain": "generic"} {"id": "ef1fe217e57d3d5cd6ee4061bee56165", "problem": "You are tasked with implementing a function `calculate_average` that computes the average of a list of numbers. Your function should handle invalid inputs by raising appropriate exceptions. Specifically, it should raise a `TypeError` if the input is not a list, a `ValueError` if the list is empty, and another `ValueError` if any element in the list is not a number (either `int` or `float`). \n\n**Sample Input 1:**\n```python\ncalculate_average([1, 2, 3, 4, 5])\n```\n**Sample Output 1:**\n```\n3.0\n```\n\n**Sample Input 2:**\n```python\ncalculate_average([])\n```\n**Sample Output 2:**\n```\nValueError: List cannot be empty.\n```\n\n**Sample Input 3:**\n```python\ncalculate_average([1, 'a', 3])\n```\n**Sample Output 3:**\n```\nValueError: All elements in the list must be numbers.\n```\n\n**Sample Input 4:**\n```python\ncalculate_average(\"not a list\")\n```\n**Sample Output 4:**\n```\nTypeError: Input must be a list.\n```", "reference": "def calculate_average(numbers):\n \"\"\"\n Calculate the average of a list of numbers.\n \n Args:\n numbers (list): A list of numbers (int or float).\n \n Returns:\n float: The average of the numbers in the list.\n \n Raises:\n TypeError: If the input is not a list.\n ValueError: If the list is empty or contains non-numeric elements.\n \"\"\"\n if not isinstance(numbers, list):\n raise TypeError(\"Input must be a list.\")\n if len(numbers) == 0:\n raise ValueError(\"List cannot be empty.\")\n if not all(isinstance(x, (int, float)) for x in numbers):\n raise ValueError(\"All elements in the list must be numbers.\")\n \n return sum(numbers) / len(numbers)", "tests": ["assert calculate_average([1, 2, 3, 4, 5]) == 3.0", "assert calculate_average([10.5, 20.5, 30.5]) == 20.5", "assert calculate_average([100]) == 100.0", "assert calculate_average([-1, -2, -3, -4, -5]) == -3.0", "assert calculate_average([0, 0, 0, 0]) == 0.0", "assert calculate_average([1, 2, 'three', 4]) # This should raise a ValueError", "assert calculate_average([]) # This should raise a ValueError", "assert calculate_average(\"not a list\") # This should raise a TypeError", "assert calculate_average([1.1, 2.2, 3.3, 4.4, 5.5]) == 3.3", "assert calculate_average([10, 20, 30, 40, 50]) == 30.0"], "function": "calculate_average", "signature": "def calculate_average(numbers):", "score": 0.7, "domain": "algorithmic"} {"id": "d272db36dc50dca92c12a3cac60a5fab", "problem": "You are given a list of integers `data` and an integer `threshold`. Your task is to implement a function `filter_and_sort` that removes all elements from `data` that are strictly less than `threshold` and returns the remaining elements sorted in non-decreasing order.\n\n**Input:**\n- A list of integers `data` (1 ≤ len(data) ≤ 10^3), where each element is in the range [-10^6, 10^6].\n- An integer `threshold` (-10^6 ≤ threshold ≤ 10^6).\n\n**Output:**\n- A list of integers representing the filtered and sorted elements.\n\n**Sample Input:**\n```\ndata = [23, 17, 5, 42, 8, 30]\nthreshold = 15\n```\n\n**Sample Output:**\n```\n[17, 23, 30, 42]\n```", "reference": "def filter_and_sort(data: list, threshold: int) -> list:\n \"\"\"\n Filters out elements from the input list `data` that are less than the given `threshold`\n and returns the remaining elements sorted in ascending order.\n\n :param data: List of integers to be filtered and sorted.\n :param threshold: Integer threshold for filtering.\n :return: List of integers that are greater than or equal to the threshold, sorted in ascending order.\n \"\"\"\n filtered_data = [item for item in data if item >= threshold]\n return sorted(filtered_data)\n\n# Example usage:\ndata = [23, 17, 5, 42, 8, 30]\nthreshold = 15\nresult = filter_and_sort(data, threshold)\nprint(result) # Output: [17, 23, 30, 42]", "tests": ["assert filter_and_sort([23, 17, 5, 42, 8, 30], 15) == [17, 23, 30, 42]", "assert filter_and_sort([10, 20, 30, 40, 50], 25) == [30, 40, 50]", "assert filter_and_sort([5, 10, 15, 20, 25], 30) == []", "assert filter_and_sort([1, 2, 3, 4, 5], 0) == [1, 2, 3, 4, 5]", "assert filter_and_sort([], 10) == []", "assert filter_and_sort([100, 200, 300], 150) == [200, 300]", "assert filter_and_sort([1, 1, 1, 1, 1], 1) == [1, 1, 1, 1, 1]", "assert filter_and_sort([10, 9, 8, 7, 6], 10) == [10]", "assert filter_and_sort([-10, -20, -30, 0, 10], -15) == [-10, 0, 10]", "assert filter_and_sort([5, 5, 5, 5, 5], 6) == []"], "function": "filter_and_sort", "signature": "def filter_and_sort(data: list, threshold: int) -> list:", "score": 1.0, "domain": "generic"} {"id": "55b75338ffdcb74297fd4c29f02a68c8", "problem": "You are given a dictionary `d` where each key is a string and each value is an integer. Your task is to implement a function `find_max_value` that returns the key associated with the maximum value in the dictionary. If there are multiple keys with the same maximum value, return the first key encountered.\n\n**Input:**\n- A dictionary `d` with string keys and integer values.\n\n**Output:**\n- A string representing the key with the maximum value.\n\n**Sample Input:**\n```python\n{'apple': 10, 'banana': 20, 'cherry': 20}\n```\n\n**Sample Output:**\n```\n'banana'\n```", "reference": "def find_max_value(d):\n \"\"\"\n Returns the key associated with the maximum value in the dictionary.\n If there are multiple keys with the same maximum value, returns the first key encountered.\n \n :param d: Dictionary with string keys and integer values\n :return: String key with the maximum value\n \"\"\"\n max_key = None\n max_value = float('-inf')\n \n for key, value in d.items():\n if value > max_value:\n max_value = value\n max_key = key\n \n return max_key\n\n# example usage:\nexample_dict = {'apple': 10, 'banana': 20, 'cherry': 20}\nprint(find_max_value(example_dict)) # output should be 'banana'", "tests": ["assert find_max_value({'a': 1, 'b': 2, 'c': 3}) == 'c'", "assert find_max_value({'x': 10, 'y': 20, 'z': 5}) == 'y'", "assert find_max_value({'one': 100, 'two': 200, 'three': 300}) == 'three'", "assert find_max_value({'red': 5, 'blue': 5, 'green': 5}) == 'red'", "assert find_max_value({'cat': 10, 'dog': 20, 'bird': 15, 'fish': 20}) == 'dog'", "assert find_max_value({'first': 1, 'second': 2, 'third': 3, 'fourth': 3}) == 'third'", "assert find_max_value({'single': 42}) == 'single'", "assert find_max_value({}) == None", "assert find_max_value({'negative': -1, 'zero': 0, 'positive': 1}) == 'positive'", "assert find_max_value({'same': 10, 'same': 10, 'same': 10}) == 'same'"], "function": "find_max_value", "signature": "def find_max_value(d):", "score": 1.0, "domain": "generic"} {"id": "850409cb66e6fb593587186a55302825", "problem": "You are tasked with implementing a recursive function to compute the factorial of a non-negative integer `n`. The factorial of a non-negative integer `n` is the product of all positive integers less than or equal to `n`. The function should be named `factorial` and should not use any loops or built-in functions for calculating the factorial. Your implementation should handle the base cases appropriately.\n\n**Input:**\n- A single non-negative integer `n` (0 ≤ n ≤ 20).\n\n**Output:**\n- A single integer representing the factorial of `n`.\n\n**Sample Input:**\n```\n5\n```\n\n**Sample Output:**\n```\n120\n```", "reference": "def factorial(n):\n \"\"\"\n Calculate the factorial of a given non-negative integer n using recursion.\n \n Parameters:\n n (int): A non-negative integer whose factorial is to be calculated.\n \n Returns:\n int: The factorial of the given integer n.\n \"\"\"\n # Base case: if n is 0 or 1, return 1\n if n == 0 or n == 1:\n return 1\n # Recursive case: n * factorial of (n-1)\n else:\n return n * factorial(n - 1)", "tests": ["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(7) == 5040", "assert factorial(10) == 3628800", "assert factorial(12) == 479001600"], "function": "factorial", "signature": "def factorial(n):", "score": 1.0, "domain": "generic"} {"id": "b66002c5c74c4ee453cb95fd111c181c", "problem": "You are tasked with writing a function that determines whether a given string is a valid IPv4 address. A valid IPv4 address consists of four octets, each ranging from 0 to 255, separated by dots. Leading zeros in the octets are allowed. Your function should return `True` if the input string is a valid IPv4 address, and `False` otherwise.\n\n**Sample Input:**\n```\n192.168.1.1\n255.255.255.255\n256.256.256.256\n192.168.01.1\n192.168.1\n192.168.1.256\n192.168.1.1.1\n192.168.1.a\n```\n\n**Sample Output:**\n```\nTrue\nTrue\nFalse\nTrue\nFalse\nFalse\nFalse\nFalse\n```", "reference": "import re\n\ndef is_valid_ipv4_address(ip: str) -> bool:\n \"\"\"\n Determines if the given string is a valid IPv4 address.\n \n :param ip: A string representing the IP address to validate.\n :return: True if the IP address is valid, False otherwise.\n \"\"\"\n pattern = re.compile(r'^((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])\\.){3}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])$')\n return pattern.match(ip) is not None\n\n# Test the function\nprint(is_valid_ipv4_address(\"192.168.1.1\")) # True\nprint(is_valid_ipv4_address(\"255.255.255.255\")) # True\nprint(is_valid_ipv4_address(\"256.256.256.256\")) # False\nprint(is_valid_ipv4_address(\"192.168.01.1\")) # True\nprint(is_valid_ipv4_address(\"192.168.1\")) # False\nprint(is_valid_ipv4_address(\"192.168.1.256\")) # False\nprint(is_valid_ipv4_address(\"192.168.1.1.1\")) # False\nprint(is_valid_ipv4_address(\"192.168.1.a\")) # False", "tests": ["assert is_valid_ipv4_address(\"192.168.1.1\") == True", "assert is_valid_ipv4_address(\"255.255.255.255\") == True", "assert is_valid_ipv4_address(\"256.256.256.256\") == False", "assert is_valid_ipv4_address(\"192.168.01.1\") == True", "assert is_valid_ipv4_address(\"192.168.1\") == False", "assert is_valid_ipv4_address(\"192.168.1.256\") == False", "assert is_valid_ipv4_address(\"192.168.1.1.1\") == False", "assert is_valid_ipv4_address(\"192.168.1.a\") == False", "assert is_valid_ipv4_address(\"0.0.0.0\") == True", "assert is_valid_ipv4_address(\"10.0.0.1\") == True"], "function": "is_valid_ipv4_address", "signature": "def is_valid_ipv4_address(ip: str) -> bool:", "score": 0.9, "domain": "algorithmic"} {"id": "6904dce65053bd55409ba5df52382945", "problem": "You are given a list containing elements of mixed data types: integers, floats, and strings. Your task is to sort this list in ascending order with the following criteria:\n- All strings should appear before any integers or floats.\n- Within the strings, sort them in lexicographical order.\n- Within the integers and floats, sort them in ascending numerical order.\n\nWrite a function `custom_sort` that takes a list as input and returns the sorted list according to the above rules.\n\n**Sample Input:**\n```\n[3, 'apple', 1.5, 'banana', 2, 'cherry']\n```\n\n**Sample Output:**\n```\n['apple', 'banana', 'cherry', 1.5, 2, 3]\n```", "reference": "def custom_sort(mixed_list):\n \"\"\"\n Sorts a list of mixed data types (integers, floats, strings) with strings prioritized over numbers.\n Within each type, elements are sorted in ascending order.\n\n :param mixed_list: List containing elements of mixed data types.\n :return: Sorted list according to the specified rules.\n \"\"\"\n def sort_key(x):\n return (0, x) if isinstance(x, str) else (1, x)\n \n mixed_list.sort(key=sort_key)\n return mixed_list\n\n# Example usage:\nmixed_list = [3, 'apple', 1.5, 'banana', 2, 'cherry']\nprint(custom_sort(mixed_list))", "tests": ["assert custom_sort([3, 'apple', 1.5, 'banana', 2, 'cherry']) == ['apple', 'banana', 'cherry', 1.5, 2, 3]", "assert custom_sort(['zebra', 100, 'apple', 10]) == ['apple', 'zebra', 10, 100]", "assert custom_sort([1, 2, 3, 'a', 'b', 'c']) == ['a', 'b', 'c', 1, 2, 3]", "assert custom_sort(['x', 'y', 'z']) == ['x', 'y', 'z']", "assert custom_sort([1.1, 2.2, 3.3, 'one', 'two', 'three']) == ['one', 'three', 'two', 1.1, 2.2, 3.3]", "assert custom_sort([]) == []", "assert custom_sort(['hello', 0, 'world', -1]) == ['hello', 'world', -1, 0]", "assert custom_sort([5, 'five', 4, 'four']) == ['five', 'four', 4, 5]", "assert custom_sort(['same', 'same', 1, 1]) == ['same', 'same', 1, 1]", "assert custom_sort([3.14, 'pi', 2.71, 'e']) == ['e', 'pi', 2.71, 3.14]"], "function": "custom_sort", "signature": "def custom_sort(mixed_list):", "score": 1.0, "domain": "generic"} {"id": "c033551b387e62606f4f1b6ee3ce662b", "problem": "You are tasked with implementing an efficient function to determine if a given integer is a prime number. Your function should avoid using the naive trial division method. Instead, utilize a more optimized approach to check for primality.\n\n**Input:**\n- An integer `n` (1 ≤ n ≤ 10^9)\n\n**Output:**\n- Return `True` if `n` is a prime number, otherwise return `False`.\n\n**Sample Input:**\n```\n5\n10\n13\n17\n18\n19\n```\n\n**Sample Output:**\n```\nTrue\nFalse\nTrue\nTrue\nFalse\nTrue\n```", "reference": "def is_prime(n):\n \"\"\"\n Return True if n is a prime number, otherwise False.\n \n This function uses an optimized method to check for primality,\n avoiding trial division by checking divisibility up to the square root of n.\n \"\"\"\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == 0 or n % 3 == 0:\n return False\n i = 5\n while i * i <= n:\n if n % i == 0 or n % (i + 2) == 0:\n return False\n i += 6\n return True", "tests": ["assert is_prime(2) == True", "assert is_prime(3) == True", "assert is_prime(4) == False", "assert is_prime(5) == True", "assert is_prime(25) == False", "assert is_prime(29) == True", "assert is_prime(97) == True", "assert is_prime(1) == False", "assert is_prime(0) == False", "assert is_prime(-5) == False"], "function": "is_prime", "signature": "def is_prime(n):", "score": 1.0, "domain": "generic"} {"id": "41297505f2b5d6fe84f3c2408d958288", "problem": "You are given a positive integer $n$. Your task is to write a function that calculates and returns the number of positive divisors of $n$.\n\n**Input:**\n- A single integer $n$ ($1 \\leq n \\leq 10^6$).\n\n**Output:**\n- An integer representing the number of positive divisors of $n$.\n\n**Sample Input:**\n```\n36\n```\n\n**Sample Output:**\n```\n9\n```", "reference": "def count_divisors(n):\n \"\"\"\n Calculate the number of positive divisors of a given positive integer n.\n\n Parameters:\n n (int): A positive integer.\n\n Returns:\n int: The number of positive divisors of n.\n \"\"\"\n count = 0\n for i in range(1, n + 1):\n if n % i == 0:\n count += 1\n return count\n\n# Example usage:\nn = 36\nprint(count_divisors(n)) # Output: 9", "tests": ["assert count_divisors(1) == 1", "assert count_divisors(2) == 2", "assert count_divisors(3) == 2", "assert count_divisors(4) == 3", "assert count_divisors(6) == 4", "assert count_divisors(10) == 4", "assert count_divisors(12) == 6", "assert count_divisors(15) == 4", "assert count_divisors(16) == 5", "assert count_divisors(36) == 9"], "function": "count_divisors", "signature": "def count_divisors(n):", "score": 1.0, "domain": "algorithmic"} {"id": "30da1726d468bb605dabfe99f16f6fb8", "problem": "You are tasked with implementing a function `is_palindrome` that determines if a given string is a palindrome, disregarding case, spaces, and punctuation. A string is considered a palindrome if it reads the same forwards and backwards when all non-alphanumeric characters are removed and all letters are converted to the same case.\n\n**Input:**\n- A single string `s` (1 ≤ len(s) ≤ 10^5) consisting of uppercase and lowercase letters, digits, spaces, and punctuation marks.\n\n**Output:**\n- Return `True` if the string is a palindrome, otherwise return `False`.\n\n**Sample Input:**\n```\n\"A man, a plan, a canal, Panama\"\n```\n\n**Sample Output:**\n```\nTrue\n```", "reference": "import string\n\ndef is_palindrome(s: str) -> bool:\n \"\"\"\n Determines if the given string is a palindrome, ignoring case, spaces, and punctuation.\n \n :param s: The input string to check.\n :return: True if the string is a palindrome, False otherwise.\n \"\"\"\n # Convert to lowercase\n s = s.lower()\n \n # Remove spaces and punctuation\n s = s.translate(str.maketrans('', '', string.whitespace + string.punctuation))\n \n # Check if the string is a palindrome\n return s == s[::-1]", "tests": ["assert is_palindrome(\"A man, a plan, a canal, Panama\") == True", "assert is_palindrome(\"racecar\") == True", "assert is_palindrome(\"No lemon, no melon\") == True", "assert is_palindrome(\"Was it a car or a cat I saw?\") == True", "assert is_palindrome(\"Hello, World!\") == False", "assert is_palindrome(\"Madam, in Eden, I'm Adam\") == True", "assert is_palindrome(\"Step on no pets\") == True", "assert is_palindrome(\"This is not a palindrome\") == False", "assert is_palindrome(\"\") == True", "assert is_palindrome(\"Able was I, I saw Elba\") == True"], "function": "is_palindrome", "signature": "def is_palindrome(s: str) -> bool:", "score": 1.0, "domain": "generic"} {"id": "fa7e24524d22f79b27bcd8bbc36bcd05", "problem": "You are given a list of integers. Your task is to write a Python function to calculate the median of the list without using any built-in functions for sorting or median calculation. The function should handle both even and odd lengths of the list.\n\n**Input:**\n- A list of integers `numbers` (1 ≤ len(numbers) ≤ 1000), where each integer is in the range -1000 ≤ numbers[i] ≤ 1000.\n\n**Output:**\n- A float representing the median of the list.\n\n**Sample Input:**\n```\n[3, 1, 4, 1, 5, 9, 2]\n```\n\n**Sample Output:**\n```\n3.0\n```", "reference": "def calculate_median(numbers):\n \"\"\"\n Calculate the median of a list of integers without using built-in sorting or median functions.\n \n :param numbers: List of integers\n :return: Median as a float\n \"\"\"\n # Sort the list of numbers\n sorted_numbers = []\n for number in numbers:\n inserted = False\n for i in range(len(sorted_numbers)):\n if number < sorted_numbers[i]:\n sorted_numbers.insert(i, number)\n inserted = True\n break\n if not inserted:\n sorted_numbers.append(number)\n \n # Calculate the median\n n = len(sorted_numbers)\n if n % 2 == 1:\n median = sorted_numbers[n // 2]\n else:\n median = (sorted_numbers[n // 2 - 1] + sorted_numbers[n // 2]) / 2\n \n return float(median)\n\n# Example usage:\nnumbers = [3, 1, 4, 1, 5, 9, 2]\nmedian = calculate_median(numbers)\nprint(median) # Output: 3.0", "tests": ["assert calculate_median([1, 2, 3]) == 2", "assert calculate_median([1, 2, 3, 4]) == 2.5", "assert calculate_median([7]) == 7", "assert calculate_median([5, 3, 8, 9, 2]) == 5", "assert calculate_median([10, 20, 30, 40, 50, 60]) == 35.0", "assert calculate_median([1, 1, 1, 1, 1]) == 1", "assert calculate_median([1, 2, 2, 3, 4]) == 2", "assert calculate_median([6, 8, 3, 1, 0, 5, 7]) == 6", "assert calculate_median([100, 200]) == 150.0", "assert calculate_median([-5, -10, -15, -20, -25]) == -15"], "function": "calculate_median", "signature": "def calculate_median(numbers):", "score": 0.9, "domain": "generic"} {"id": "15485aa5c5ecfe444abd88a0fc4c56ad", "problem": "You are given a string `expr` representing a mathematical expression consisting of integers, the operators `+`, `-`, `*`, `/`, and parentheses `()`. Your task is to implement a function `evaluate_expression(expr)` that evaluates the expression and returns the result as a float. The function should correctly handle operator precedence and parentheses. \n\n**Constraints:**\n- The expression will be valid and contain only non-negative integers and the specified operators.\n- Division by zero will not occur in the test cases.\n\n**Sample Input:**\n```\n\"2 + 3 * (4 - 1)\"\n```\n\n**Sample Output:**\n```\n11.0\n```", "reference": "import ast\nimport operator\n\n# Define supported operators\noperators = {\n ast.Add: operator.add,\n ast.Sub: operator.sub,\n ast.Mult: operator.mul,\n ast.Div: operator.truediv,\n ast.Pow: operator.pow,\n ast.BitXor: operator.xor,\n ast.USub: operator.neg,\n}\n\ndef evaluate_expression(expr: str) -> float:\n \"\"\"\n Evaluate a mathematical expression given as a string.\n \n Args:\n expr (str): The mathematical expression to evaluate.\n \n Returns:\n float: The result of the evaluated expression.\n \"\"\"\n def _eval(node):\n if isinstance(node, ast.Num): # \n return node.n\n elif isinstance(node, ast.BinOp): # \n left = _eval(node.left)\n right = _eval(node.right)\n return operators[type(node.op)](left, right)\n elif isinstance(node, ast.UnaryOp): # e.g., -1\n operand = _eval(node.operand)\n return operators[type(node.op)](operand)\n else:\n raise TypeError(node)\n \n # Parse the expression into an AST\n node = ast.parse(expr, mode='eval').body\n return _eval(node)", "tests": ["assert evaluate_expression(\"2 + 3 * (4 - 1)\") == 11.0", "assert evaluate_expression(\"10 / 2 - 1\") == 4.0", "assert evaluate_expression(\"(1 + 2) * 3\") == 9.0", "assert evaluate_expression(\"5 - 3 * 2 + 4\") == 3.0", "assert evaluate_expression(\"8 / (4 / 2)\") == 4.0", "assert evaluate_expression(\"7 + 3 * (10 / (2 + 3))\") == 11.0", "assert evaluate_expression(\"100 * 2 + 12\") == 212.0", "assert evaluate_expression(\"100 * ( 2 + 12 )\") == 1400.0", "assert evaluate_expression(\"100 * ( 2 + 12 ) / 14\") == 100.0", "assert evaluate_expression(\"100 * ( 2 + 12 ) / 14 - 50\") == 50.0"], "function": "evaluate_expression", "signature": "def evaluate_expression(expr: str) -> float:", "score": 0.9, "domain": "generic"} {"id": "bf280eb10ebb888ae5745d73f620d48a", "problem": "You are given a string `expression` representing a mathematical expression consisting of integers, the four basic arithmetic operators (+, -, *, /), and parentheses for grouping. Your task is to write a function `evaluate_expression(expression)` that evaluates the expression and returns the result as a float. The function should correctly handle operator precedence and parentheses. You must use Python's `ast` module to parse and evaluate the expression safely. \n\n**Constraints:**\n- The expression will only contain valid characters.\n- Division by zero will not occur in the test cases.\n- The expression will not contain any variables or functions other than the basic arithmetic operations.\n\n**Sample Input:**\n```\n\"(2 + 3) * 4 / 5\"\n```\n\n**Sample Output:**\n```\n4.0\n```", "reference": "import ast\nimport operator\n\n# Define supported operators\noperators = {\n ast.Add: operator.add,\n ast.Sub: operator.sub,\n ast.Mult: operator.mul,\n ast.Div: operator.truediv,\n}\n\ndef evaluate_expression(expression):\n \"\"\"\n Evaluates a mathematical expression given as a string and returns the result as a float.\n \n :param expression: A string representing a mathematical expression.\n :return: The result of the evaluated expression as a float.\n \"\"\"\n # Parse the expression string into an AST\n node = ast.parse(expression, mode='eval')\n \n # Evaluate the AST\n return eval_node(node.body)\n\ndef eval_node(node):\n \"\"\"\n Recursively evaluates an AST node.\n \n :param node: An AST node to evaluate.\n :return: The evaluated result of the node.\n \"\"\"\n if isinstance(node, ast.BinOp):\n # Binary operation: handle +, -, *, /\n left = eval_node(node.left)\n right = eval_node(node.right)\n return operators[type(node.op)](left, right)\n elif isinstance(node, ast.Num):\n # Literal number\n return node.n\n elif isinstance(node, ast.UnaryOp):\n # Unary operation: handle negative numbers\n operand = eval_node(node.operand)\n if isinstance(node.op, ast.USub):\n return -operand\n elif isinstance(node, ast.Expression):\n # Top-level expression node\n return eval_node(node.body)\n elif isinstance(node, ast.Call):\n # Function call (support for Python 3.8 and higher where int and float are represented as ast.Call)\n call_func_name = node.func.id\n call_args = [eval_node(arg) for arg in node.args]\n if call_func_name == \"int\":\n return int(*call_args)\n elif call_func_name == \"float\":\n return float(*call_args)\n elif isinstance(node, ast.Paren):\n # Parentheses: evaluate inside expression\n return eval_node(node.body)\n else:\n # Unsupported operation\n raise TypeError(f\"Unsupported type: {node}\")", "tests": ["assert evaluate_expression(\"2 + 3\") == 5", "assert evaluate_expression(\"10 - 5\") == 5", "assert evaluate_expression(\"3 * 4\") == 12", "assert evaluate_expression(\"12 / 3\") == 4.0", "assert evaluate_expression(\"(2 + 3) * 4\") == 20", "assert evaluate_expression(\"10 - (5 + 3)\") == 2", "assert evaluate_expression(\"3 * (4 + 2)\") == 18", "assert evaluate_expression(\"12 / (3 + 1)\") == 3.0", "assert evaluate_expression(\"2 + 3 * 4 / 5\") == 3.8", "assert evaluate_expression(\"((2 + 3) * 4) / 5\") == 4.0"], "function": "evaluate_expression", "signature": "def evaluate_expression(expression):", "score": 0.9, "domain": "generic"} {"id": "39fb4b1685e12f349292fa8a394e3449", "problem": "You are given a list of lists, where each sublist contains a set of strings. Your task is to find the longest string that appears in every sublist. If there are multiple strings of the same maximum length, return the one that appears first in the first sublist. If no common longest string exists, return an empty string.\n\n**Input:**\n- A list of lists of strings, where each sublist contains at least one string.\n\n**Output:**\n- A single string representing the longest common string across all sublists, or an empty string if no such string exists.\n\n**Sample Input:**\n```\n[[\"apple\", \"banana\", \"cherry\"], [\"banana\", \"cherry\", \"date\"], [\"banana\", \"cherry\", \"elderberry\"]]\n```\n\n**Sample Output:**\n```\n\"banana\"\n```", "reference": "def longest_common_string(lists):\n \"\"\"\n Finds the longest string that appears in each sublist of the given list of lists.\n If there are multiple longest strings of the same length, returns the one that appears first.\n If no common longest strings exist, returns an empty string.\n \n :param lists: List of lists of strings\n :return: Longest common string or an empty string if none exists\n \"\"\"\n if not lists:\n return \"\"\n \n max_length = max(max(len(s) for s in lst) for lst in lists)\n longest_in_each_list = [max(lst, key=lambda x: (len(x), -lst.index(x))) for lst in lists if any(len(s) == max_length for s in lst)]\n common_longest = set(longest_in_each_list[0]).intersection(*longest_in_each_list[1:])\n \n return next(iter(common_longest), \"\")", "tests": ["assert longest_common_string([[\"apple\", \"banana\", \"cherry\"], [\"banana\", \"cherry\", \"date\"], [\"banana\", \"cherry\", \"elderberry\"]]) == \"banana\"", "assert longest_common_string([[\"dog\", \"cat\"], [\"fish\", \"dog\"], [\"dog\", \"bird\"]]) == \"dog\"", "assert longest_common_string([[\"one\", \"two\", \"three\"], [\"three\", \"four\", \"five\"], [\"six\", \"seven\", \"three\"]]) == \"three\"", "assert longest_common_string([[\"a\", \"b\", \"c\"], [\"d\", \"e\", \"f\"], [\"g\", \"h\", \"i\"]]) == \"\"", "assert longest_common_string([[\"hello\", \"world\"], [\"world\", \"hello\"], [\"hello\", \"world\"]]) == \"hello\"", "assert longest_common_string([[\"longest\", \"string\"], [\"string\", \"longest\"], [\"longest\", \"string\"]]) == \"longest\"", "assert longest_common_string([[\"same\", \"length\"], [\"length\", \"same\"], [\"same\", \"length\"]]) == \"same\"", "assert longest_common_string([[\"unique\"], [\"unique\"], [\"unique\"]]) == \"unique\"", "assert longest_common_string([[\"abc\"], [\"def\"], [\"ghi\"]]) == \"\"", "assert longest_common_string([]) == \"\""], "function": "longest_common_string", "signature": "def longest_common_string(lists):", "score": 0.3, "domain": "algorithmic"} {"id": "df8bef3c2da00e2713d796a91f34ef19", "problem": "You are given two positive integers, `n` and `m`, such that `n ≥ m`. Your task is to implement a function `compute_product(n, m)` that computes the product of all integers from `n` down to `m` (inclusive), and then divides this product by the greatest common divisor (GCD) of `n` and `m`. The result should be returned as a string formatted in scientific notation with at least five decimal places.\n\n**Input:**\n- Two integers `n` and `m` where `1 ≤ m ≤ n ≤ 100`.\n\n**Output:**\n- A string representing the result in scientific notation with at least five decimal places.\n\n**Sample Input 1:**\n```\n5 3\n```\n\n**Sample Output 1:**\n```\n6.00000e+01\n```\n\n**Sample Input 2:**\n```\n6 3\n```\n\n**Sample Output 2:**\n```\n1.20000e+02\n```", "reference": "import math\n\ndef compute_product(n, m):\n \"\"\"\n Computes the product of all integers from n down to m (inclusive),\n divides the product by the GCD of n and m, and returns the result\n as a string in scientific notation with at least five decimal places.\n \n :param n: The upper bound of the range (inclusive).\n :param m: The lower bound of the range (inclusive).\n :return: A string representing the result in scientific notation.\n \"\"\"\n product = 1\n for i in range(n, m - 1, -1):\n product *= i\n \n gcd_value = math.gcd(n, m)\n result = product / gcd_value\n \n return \"{:.5e}\".format(result)", "tests": ["assert compute_product(5, 3) == \"6.00000e+01\"", "assert compute_product(6, 3) == \"1.20000e+02\"", "assert compute_product(10, 5) == \"3.02400e+04\"", "assert compute_product(7, 7) == \"7.00000e+00\"", "assert compute_product(20, 10) == \"6.70442e+13\"", "assert compute_product(15, 5) == \"3.60360e+10\"", "assert compute_product(12, 6) == \"3.62880e+06\"", "assert compute_product(9, 3) == \"1.51200e+04\"", "assert compute_product(8, 4) == \"1.68000e+03\"", "assert compute_product(100, 50) == \"3.04141e+64\""], "function": "compute_product", "signature": "def compute_product(n, m):", "score": 0.4, "domain": "generic"} {"id": "316caeca961247c879449057a39ccbda", "problem": "You are tasked with implementing a function `unpad` that processes binary data (byte strings) to remove PKCS#7 padding. PKCS#7 padding involves appending bytes to the end of a message such that the total length of the message is a multiple of a specified block size. The value of each padding byte is equal to the number of padding bytes added. For instance, if the block size is 8 and the original message is `b\"Hello\"`, the padded message would be `b\"Hello\\x03\\x03\\x03\"`.\n\nYour function should handle edge cases, including zero-length byte strings and invalid padding, by returning `None` in such scenarios. Specifically, your function should:\n- Return `None` if the input data is not a byte string.\n- Return `None` if the block size is less than or equal to zero.\n- Return `None` if the length of the data is not a multiple of the block size.\n- Return `None` if the padding length is greater than the block size.\n- Return `None` if the padding length is zero.\n- Return `None` if the padding bytes are not all identical.\n\n**Function Signature:**\n```python\ndef unpad(data: bytes, size: int) -> bytes:\n```\n\n**Sample Inputs and Outputs:**\n- `unpad(b\"Hello\\x03\\x03\\x03\", 8)` should return `b\"Hello\"`\n- `unpad(b\"Hello\\x05\\x05\\x05\\x05\\x05\", 8)` should return `None`\n- `unpad(b\"Hello\\x00\\x00\\x00\", 8)` should return `None`\n- `unpad(b\"\", 8)` should return `b\"\"`\n- `unpad(b\"Hello\", 8)` should return `None`\n- `unpad(b\"Hello\\x03\\x03\", 8)` should return `None`", "reference": "def unpad(data: bytes, size: int) -> bytes:\n \"\"\"\n Removes PKCS#7 padding from the supplied byte string.\n \n Parameters:\n data (bytes): The byte string from which to remove padding.\n size (int): The block size used for padding.\n \n Returns:\n bytes: The original data without padding, or None if padding is invalid.\n \"\"\"\n if not isinstance(data, bytes):\n return None\n \n if size <= 0:\n return None\n \n if len(data) % size != 0:\n return None\n \n if not data:\n return data\n \n padding_length = data[-1]\n \n if padding_length > size:\n return None\n \n if padding_length == 0:\n return None\n \n if data[-padding_length:] != bytes([padding_length]) * padding_length:\n return None\n \n return data[:-padding_length]", "tests": ["assert unpad(b'\\x01', 1) == b''", "assert unpad(b'\\x02\\x02', 2) == b''", "assert unpad(b'abc\\x03\\x03\\x03', 3) == b'abc'", "assert unpad(b'hello\\x05\\x05\\x05\\x05\\x05', 5) == b'hello'", "assert unpad(b'hello\\x01', 5) == None", "assert unpad(b'hello\\x00', 5) == None", "assert unpad(b'hello\\x06\\x06\\x06\\x06\\x06\\x06', 5) == None", "assert unpad(b'hello\\x05\\x05\\x05\\x05\\x04', 5) == None", "assert unpad(b'', 8) == b''", "assert unpad(b'\\x08\\x08\\x08\\x08\\x08\\x08\\x08\\x08', 8) == b''"], "function": "unpad", "signature": "def unpad(data: bytes, size: int) -> bytes:", "score": 1.0, "domain": "generic"} {"id": "2706955c205058bac51d932baa899e05", "problem": "You are given a list of predicted scores for a student's performance in a particular subject, where each score is a continuous variable. Your task is to create a function that discretizes these scores into five performance levels: \"Poor\", \"Below Average\", \"Average\", \"Above Average\", and \"Excellent\". The discretization should follow these rules:\n- Scores less than 1.0 are categorized as \"Poor\".\n- Scores between 1.0 (inclusive) and 2.0 (exclusive) are categorized as \"Below Average\".\n- Scores between 2.0 (inclusive) and 3.0 (exclusive) are categorized as \"Average\".\n- Scores between 3.0 (inclusive) and 4.0 (exclusive) are categorized as \"Above Average\".\n- Scores 4.0 and above are categorized as \"Excellent\".\n\nAdditionally, ensure that any score outside the range [0, 5] is capped at the nearest boundary before discretization.\n\n**Input:**\n- A list of floating-point numbers representing predicted scores.\n\n**Output:**\n- A list of strings representing the performance levels.\n\n**Sample Input:**\n```\n[0.5, 1.2, 2.5, 3.1, 4.8, 5.5, -0.3]\n```\n\n**Sample Output:**\n```\n['Poor', 'Below Average', 'Average', 'Above Average', 'Excellent', 'Excellent', 'Poor']\n```", "reference": "def discretize_scores(scores):\n \"\"\"\n Discretizes a list of scores into performance levels based on specified ranges.\n \n Parameters:\n scores (list of float): A list of predicted scores.\n \n Returns:\n list of str: A list of performance levels corresponding to the scores.\n \"\"\"\n def categorize(score):\n # Cap the score to ensure it lies between 0 and 5\n score = max(0, min(score, 5))\n \n if score < 1.0:\n return \"Poor\"\n elif 1.0 <= score < 2.0:\n return \"Below Average\"\n elif 2.0 <= score < 3.0:\n return \"Average\"\n elif 3.0 <= score < 4.0:\n return \"Above Average\"\n else: # score >= 4.0\n return \"Excellent\"\n \n return [categorize(score) for score in scores]\n\n# Example usage:\npredicted_scores = [0.5, 1.2, 2.5, 3.1, 4.8, 5.5, -0.3]\nperformance_levels = discretize_scores(predicted_scores)\nprint(performance_levels)", "tests": ["assert discretize_scores([0.5]) == [\"Poor\"]", "assert discretize_scores([1.2]) == [\"Below Average\"]", "assert discretize_scores([2.5]) == [\"Average\"]", "assert discretize_scores([3.1]) == [\"Above Average\"]", "assert discretize_scores([4.8]) == [\"Excellent\"]", "assert discretize_scores([5.5]) == [\"Excellent\"]", "assert discretize_scores([-0.3]) == [\"Poor\"]", "assert discretize_scores([0.0, 1.0, 2.0, 3.0, 4.0, 5.0]) == [\"Poor\", \"Below Average\", \"Average\", \"Above Average\", \"Excellent\", \"Excellent\"]", "assert discretize_scores([0.99, 1.99, 2.99, 3.99, 4.99]) == [\"Poor\", \"Below Average\", \"Average\", \"Above Average\", \"Excellent\"]", "assert discretize_scores([1.5, 2.5, 3.5, 4.5]) == [\"Below Average\", \"Average\", \"Above Average\", \"Excellent\"]"], "function": "discretize_scores", "signature": "def discretize_scores(scores):", "score": 1.0, "domain": "generic"} {"id": "fb29d7985df5d1c034d7b04d759f3104", "problem": "You are given a large image represented as a 2D grid of pixels. The image is divided into multiple levels of detail, where each level is a smaller version of the original image. The levels are numbered from 0 (the original image) to N (the smallest version). Each level is obtained by halving the dimensions of the previous level, rounding down if necessary.\n\nYour task is to implement the function `find_center_pixel(image, level)` that takes a 2D list `image` and an integer `level` as input and returns the coordinates of the center pixel of the specified level as a tuple `(x, y)`. The center coordinates should be calculated by rounding down if the dimensions are odd.\n\n**Constraints:**\n- The image is represented as a list of lists, where each inner list represents a row of pixels.\n- The pixel values are not important for this problem.\n- 1 ≤ height, width ≤ 1024\n- 0 ≤ level ≤ log2(min(height, width))\n\n**Sample Input:**\n```python\nimage = [\n [0, 0, 0, 0],\n [0, 0, 0, 0],\n [0, 0, 0, 0],\n [0, 0, 0, 0]\n]\nlevel = 1\n```\n\n**Sample Output:**\n```\n(1, 1)\n```", "reference": "def find_center_pixel(image, level):\n \"\"\"\n Returns the coordinates of the center pixel of the specified level in the image.\n \n :param image: List of lists representing the 2D grid of pixels.\n :param level: Integer representing the level of detail.\n :return: Tuple (x, y) representing the center pixel coordinates.\n \"\"\"\n height = len(image)\n width = len(image[0]) if height > 0 else 0\n \n for _ in range(level):\n height //= 2\n width //= 2\n \n center_x = width // 2\n center_y = height // 2\n \n return (center_x, center_y)", "tests": ["assert find_center_pixel([[0, 0], [0, 0]], 0) == (1, 1)", "assert find_center_pixel([[0, 0], [0, 0]], 1) == (0, 0)", "assert find_center_pixel([[0, 0, 0], [0, 0, 0], [0, 0, 0]], 0) == (1, 1)", "assert find_center_pixel([[0, 0, 0], [0, 0, 0], [0, 0, 0]], 1) == (1, 1)", "assert find_center_pixel([[0, 0, 0], [0, 0, 0], [0, 0, 0]], 2) == (0, 0)", "assert find_center_pixel([[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]], 0) == (2, 2)", "assert find_center_pixel([[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]], 1) == (1, 1)", "assert find_center_pixel([[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]], 2) == (0, 0)", "assert find_center_pixel([[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]], 0) == (2, 2)", "assert find_center_pixel([[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]], 1) == (2, 2)"], "function": "find_center_pixel", "signature": "def find_center_pixel(image, level):", "score": 0.8, "domain": "generic"} {"id": "3565935249def7f7e92f440724bd652b", "problem": "You are given a function `optimize_parameters` that takes three parameters: `optimization_level`, `chunk_size`, and `slice_size`. Both `chunk_size` and `slice_size` are floating-point numbers. The function should adjust these parameters based on the `optimization_level` as follows:\n\n- If `optimization_level` is between 0 and 2 (inclusive), halve the `slice_size`.\n- If `optimization_level` is between 3 and 5 (inclusive), leave both parameters unchanged.\n- If `optimization_level` is between 6 and 8 (inclusive), halve the `chunk_size`.\n- If `optimization_level` is 9, halve the `chunk_size` and double the `slice_size`.\n\nAfter adjusting the parameters, round both `chunk_size` and `slice_size` to the nearest integer. Return the adjusted values as a tuple.\n\n**Sample Input:**\n```\noptimization_level = 9\nchunk_size = 10.5\nslice_size = 4.2\n```\n\n**Sample Output:**\n```\n(5, 8)\n```", "reference": "def optimize_parameters(optimization_level, chunk_size, slice_size):\n \"\"\"\n Adjusts the chunk_size and slice_size based on the optimization_level and rounds the results to the nearest integer.\n\n Parameters:\n optimization_level (int): The level of optimization (0-9).\n chunk_size (float): The initial chunk size.\n slice_size (float): The initial slice size.\n\n Returns:\n tuple: A tuple containing the adjusted chunk_size and slice_size as integers.\n \"\"\"\n if 0 <= optimization_level <= 2:\n slice_size /= 2\n elif 6 <= optimization_level <= 8:\n chunk_size /= 2\n elif optimization_level == 9:\n chunk_size /= 2\n slice_size *= 2\n \n chunk_size = round(chunk_size)\n slice_size = round(slice_size)\n \n return chunk_size, slice_size", "tests": ["assert optimize_parameters(0, 10, 20) == (10, 10)", "assert optimize_parameters(2, 15, 30) == (15, 15)", "assert optimize_parameters(3, 20, 40) == (20, 40)", "assert optimize_parameters(5, 25, 50) == (25, 50)", "assert optimize_parameters(6, 30, 60) == (15, 60)", "assert optimize_parameters(8, 35, 70) == (18, 70)", "assert optimize_parameters(9, 40, 80) == (20, 160)", "assert optimize_parameters(1, 100.5, 200.5) == (100, 100)", "assert optimize_parameters(7, 150.5, 300.5) == (75, 300)", "assert optimize_parameters(9, 200.5, 400.5) == (100, 801)"], "function": "optimize_parameters", "signature": "def optimize_parameters(optimization_level, chunk_size, slice_size):", "score": 1.0, "domain": "generic"} {"id": "d7f2f6c69a7b606d2bd2f15778979845", "problem": "You are given a dictionary representing a JSON object. Your task is to write a Python function that returns a string containing a pretty-printed version of the JSON object with an indentation of 4 spaces. The output should be formatted in a way that is easy to read.\n\n**Sample Input:**\n```python\n{\"name\": \"Alice\", \"age\": 30, \"city\": \"New York\", \"children\": [{\"name\": \"Bob\", \"age\": 5}, {\"name\": \"Charlie\", \"age\": 3}]}\n```\n\n**Sample Output:**\n```\n{\n \"name\": \"Alice\",\n \"age\": 30,\n \"city\": \"New York\",\n \"children\": [\n {\n \"name\": \"Bob\",\n \"age\": 5\n },\n {\n \"name\": \"Charlie\",\n \"age\": 3\n }\n ]\n}\n```", "reference": "import json\n\ndef pretty_print_json(json_obj):\n \"\"\"\n Returns a pretty-printed string representation of the given JSON object with an indentation of 4 spaces.\n\n :param json_obj: Dictionary representing a JSON object.\n :return: String containing the pretty-printed JSON object.\n \"\"\"\n return json.dumps(json_obj, indent=4)\n\n# Example usage:\njson_obj = {\"name\": \"Alice\", \"age\": 30, \"city\": \"New York\", \"children\": [{\"name\": \"Bob\", \"age\": 5}, {\"name\": \"Charlie\", \"age\": 3}]}\npretty_json = pretty_print_json(json_obj)\nprint(pretty_json)", "tests": ["assert pretty_print_json({\"name\": \"Alice\"}) == '{\\n \"name\": \"Alice\"\\n}'", "assert pretty_print_json({\"name\": \"Alice\", \"age\": 30}) == '{\\n \"name\": \"Alice\",\\n \"age\": 30\\n}'", "assert pretty_print_json({\"name\": \"Alice\", \"age\": 30, \"city\": \"New York\"}) == '{\\n \"name\": \"Alice\",\\n \"age\": 30,\\n \"city\": \"New York\"\\n}'", "assert pretty_print_json({\"name\": \"Alice\", \"children\": [{\"name\": \"Bob\", \"age\": 5}]}) == '{\\n \"name\": \"Alice\",\\n \"children\": [\\n {\\n \"name\": \"Bob\",\\n \"age\": 5\\n }\\n ]\\n}'", "assert pretty_print_json({\"name\": \"Alice\", \"children\": [{\"name\": \"Bob\", \"age\": 5}, {\"name\": \"Charlie\", \"age\": 3}]}) == '{\\n \"name\": \"Alice\",\\n \"children\": [\\n {\\n \"name\": \"Bob\",\\n \"age\": 5\\n },\\n {\\n \"name\": \"Charlie\",\\n \"age\": 3\\n }\\n ]\\n}'", "assert pretty_print_json([]) == '[]'", "assert pretty_print_json([{\"name\": \"Alice\"}, {\"name\": \"Bob\"}]) == '[\\n {\\n \"name\": \"Alice\"\\n },\\n {\\n \"name\": \"Bob\"\\n }\\n]'", "assert pretty_print_json({\"name\": \"Alice\", \"details\": {\"age\": 30, \"city\": \"New York\"}}) == '{\\n \"name\": \"Alice\",\\n \"details\": {\\n \"age\": 30,\\n \"city\": \"New York\"\\n }\\n}'", "assert pretty_print_json({}) == '{}'", "assert pretty_print_json({\"numbers\": [1, 2, 3, 4, 5]}) == '{\\n \"numbers\": [\\n 1,\\n 2,\\n 3,\\n 4,\\n 5\\n ]\\n}'"], "function": "pretty_print_json", "signature": "def pretty_print_json(json_obj):", "score": 1.0, "domain": "generic"} {"id": "cc9d6c24bd4e13bc5200ab911be68dd5", "problem": "You are given a list of lists, where each inner list contains a group of integers. Your task is to write a function that processes this list and returns a dictionary. The keys of the dictionary should be the sums of the integers in each inner list, and the values should be lists containing all inner lists that share the same sum.\n\n**Input:**\n- A list of lists, where each inner list contains integers.\n\n**Output:**\n- A dictionary with integer keys representing the sums of the inner lists, and list values containing the inner lists that have the same sum.\n\n**Sample Input:**\n```python\n[[1, 2, 3], [4, 5], [1, 2, 3], [6], [3, 3]]\n```\n\n**Sample Output:**\n```python\n{6: [[1, 2, 3], [1, 2, 3], [3, 3]], 9: [[4, 5]], 6: [[6]]}\n```", "reference": "from collections import defaultdict\n\ndef sum_groups(groups):\n \"\"\"\n Processes a list of lists, returning a dictionary where keys are the sums of the inner lists,\n and values are lists of inner lists that share the same sum.\n\n :param groups: List of lists of integers.\n :return: Dictionary with sums as keys and lists of inner lists as values.\n \"\"\"\n sum_dict = defaultdict(list)\n for group in groups:\n sum_dict[sum(group)].append(group)\n return dict(sum_dict)", "tests": ["assert sum_groups([[1, 2], [3], [4, 0], [2, 2]]) == {3: [[1, 2], [3]], 4: [[4, 0], [2, 2]]}", "assert sum_groups([[1, 1, 1], [2, 2], [3]]) == {3: [[1, 1, 1], [3]], 4: [[2, 2]]}", "assert sum_groups([[0, 0, 0], [0], [0, 0]]) == {0: [[0, 0, 0], [0], [0, 0]]}", "assert sum_groups([[10], [20, 30], [5, 5, 5, 5, 5, 5], [10, 40]]) == {10: [[10]], 50: [[20, 30], [5, 5, 5, 5, 5, 5], [10, 40]]}", "assert sum_groups([[-1, 1], [0], [-2, 2], [1, -1]]) == {0: [[-1, 1], [0], [-2, 2], [1, -1]]}", "assert sum_groups([[1, 2, 3], [4, 5], [6], [1, 2, 3], [4, 5]]) == {6: [[1, 2, 3], [1, 2, 3]], 9: [[4, 5], [4, 5]], 6: [[6]]}", "assert sum_groups([]) == {}", "assert sum_groups([[1], [2], [3], [4], [5]]) == {1: [[1]], 2: [[2]], 3: [[3]], 4: [[4]], 5: [[5]]}", "assert sum_groups([[1, 2, 3], [3, 2, 1], [2, 1, 3], [1, 3, 2]]) == {6: [[1, 2, 3], [3, 2, 1], [2, 1, 3], [1, 3, 2]]}", "assert sum_groups([[100], [50, 50], [25, 25, 25, 25], [10, 10, 10, 10, 10, 10, 10, 10, 10, 10]]) == {100: [[100], [50, 50], [25, 25, 25, 25], [10, 10, 10, 10, 10, 10, 10, 10, 10, 10]]}"], "function": "sum_groups", "signature": "def sum_groups(groups):", "score": 0.8, "domain": "generic"} {"id": "aa61972c9a395146015c2cf089a27ccc", "problem": "You are tasked with implementing a Python decorator named `log_execution_time`. This decorator should measure and print the execution time of any function it decorates. The output should include the name of the function and the time taken to execute it in seconds, formatted to four decimal places.\n\n**Sample Input:**\n```python\n@log_execution_time\ndef sample_function():\n time.sleep(1.5) # Simulate a delay\n\nsample_function()\n```\n\n**Sample Output:**\n```\nExecuting sample_function took 1.5000 seconds.\n```", "reference": "import time\nimport functools\n\ndef log_execution_time(func):\n \"\"\"\n Decorator that logs the execution time of the function it decorates.\n \n Args:\n func (callable): The function to be decorated.\n \n Returns:\n callable: The wrapped function that logs its execution time.\n \"\"\"\n @functools.wraps(func)\n def wrapper(*args, **kwargs):\n start_time = time.time()\n result = func(*args, **kwargs)\n end_time = time.time()\n execution_time = end_time - start_time\n print(f\"Executing {func.__name__} took {execution_time:.4f} seconds.\")\n return result\n return wrapper\n\n# Example usage:\n@log_execution_time\ndef example_function():\n time.sleep(2) # Simulate a delay\n\nexample_function()", "tests": ["assert log_execution_time(lambda: None)() is None", "assert log_execution_time(lambda x: x)(42) == 42", "assert log_execution_time(lambda x, y: x + y)(10, 20) == 30", "assert log_execution_time(lambda *args: sum(args))(1, 2, 3, 4) == 10", "assert log_execution_time(lambda **kwargs: sum(kwargs.values()))(a=1, b=2, c=3) == 6", "assert log_execution_time(lambda x, *args, **kwargs: x + sum(args) + sum(kwargs.values()))(1, 2, 3, a=4, b=5) == 15", "assert log_execution_time(lambda: \"hello\")() == \"hello\"", "assert log_execution_time(lambda: [1, 2, 3])() == [1, 2, 3]", "assert log_execution_time(lambda: {\"key\": \"value\"})() == {\"key\": \"value\"}", "assert log_execution_time(lambda: (1, 2, 3))() == (1, 2, 3)"], "function": "log_execution_time", "signature": "def log_execution_time(func):", "score": 1.0, "domain": "generic"} {"id": "a80405ee0bc7c33f3907ab7e99c3a009", "problem": "You are tasked with implementing a function `num_to_text(num)` that converts an integer `num` (1 ≤ num ≤ 99) into its English textual representation. Additionally, if `num` can be expressed as the sum of two distinct integers `a` and `b` (1 ≤ a < b ≤ 9) such that their product `a * b` is even, return the textual representation of `a` and `b` separated by \" and \". Among all valid pairs, choose the one with the smallest `a`. If no such pair exists, return the standard textual representation of `num`.\n\n**Sample Input and Output:**\n- Input: `15`\n- Output: `\"one and five\"`\n\n- Input: `13`\n- Output: `\"thirteen\"`\n\n- Input: `28`\n- Output: `\"two and eight\"`\n\n- Input: `25`\n- Output: `\"twenty five\"`\n\n- Input: `10`\n- Output: `\"one and nine\"`\n\n- Input: `1`\n- Output: `\"one\"`\n\n- Input: `99`\n- Output: `\"ninety nine\"`", "reference": "def num_to_text(num):\n \"\"\"\n Convert an integer num (1 ≤ num ≤ 99) into its English textual representation.\n If num can be expressed as the sum of two distinct integers a and b (1 ≤ a < b ≤ 9)\n such that their product a * b is even, return the textual representation of a and b\n separated by \" and \". Among all valid pairs, choose the one with the smallest a.\n If no such pair exists, return the standard textual representation of num.\n \"\"\"\n units = [\"\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\"]\n teens = [\"\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"]\n tens = [\"\", \"ten\", \"twenty\", \"thirty\", \"forty\", \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"]\n \n def number_to_words(n):\n if 1 <= n < 10:\n return units[n]\n elif 10 < n < 20:\n return teens[n - 10]\n elif 20 <= n < 100:\n return tens[n // 10] + (\" \" + units[n % 10] if n % 10 != 0 else \"\")\n elif n == 10:\n return tens[1]\n else:\n return \"\"\n \n for i in range(1, 10):\n for j in range(i + 1, 10):\n if i + j == num and (i * j) % 2 == 0:\n return number_to_words(i) + \" and \" + number_to_words(j)\n \n return number_to_words(num)", "tests": ["assert num_to_text(15) == \"one and five\"", "assert num_to_text(13) == \"thirteen\"", "assert num_to_text(28) == \"two and eight\"", "assert num_to_text(25) == \"twenty five\"", "assert num_to_text(10) == \"one and nine\"", "assert num_to_text(1) == \"one\"", "assert num_to_text(99) == \"ninety nine\"", "assert num_to_text(18) == \"one and seven\"", "assert num_to_text(30) == \"three and nine\"", "assert num_to_text(50) == \"five and nine\""], "function": "num_to_text", "signature": "def num_to_text(num):", "score": 0.3, "domain": "generic"} {"id": "7cd2eda172b3216dc03d639386303c03", "problem": "You are tasked with implementing a function to encrypt a given message using a Caesar cipher. The function should take a string `message` consisting of lowercase letters and spaces, and an integer `key` representing the shift value. The function should return the encrypted message. Negative keys indicate a shift in the opposite direction. The encryption should wrap around the alphabet.\n\n**Sample Input:**\n```\nmessage = \"hello world\"\nkey = 3\n```\n\n**Sample Output:**\n```\n\"khoor zruog\"\n```", "reference": "def encrypt_message(message, key):\n \"\"\"\n Encrypts a given message using a Caesar cipher.\n\n Parameters:\n message (str): The message to be encrypted, consisting of lowercase letters and spaces.\n key (int): The shift value for the Caesar cipher. Negative values shift in the opposite direction.\n\n Returns:\n str: The encrypted message.\n \"\"\"\n encrypted_message = \"\"\n for char in message:\n if char == \" \":\n encrypted_message += char\n else:\n shifted = ((ord(char) - 97 + key) % 26) + 97\n encrypted_message += chr(shifted)\n return encrypted_message\n\n# Example usage:\n# encrypted = encrypt_message(\"hello world\", 3)\n# print(encrypted) # Should print \"khoor zruog\"", "tests": ["assert encrypt_message(\"hello world\", 3) == \"khoor zruog\"", "assert encrypt_message(\"abc xyz\", 2) == \"cde zab\"", "assert encrypt_message(\"abc xyz\", -2) == \"yza vwx\"", "assert encrypt_message(\"the quick brown fox\", 5) == \"ymj vznhp gwtbs ktc\"", "assert encrypt_message(\"jumped over the lazy dog\", 7) == \"qzvylk vlyl aol shgf kvn\"", "assert encrypt_message(\"python programming\", 10) == \"zidryx zbyqywoxmsx\"", "assert encrypt_message(\"caesar cipher\", 13) == \"pngre npxreva\"", "assert encrypt_message(\"wrap around the alphabet\", 26) == \"wrap around the alphabet\"", "assert encrypt_message(\"wrap around the alphabet\", 0) == \"wrap around the alphabet\"", "assert encrypt_message(\"spaces in between\", 4) == \"wgvwevi mr fivjyxi\""], "function": "encrypt_message", "signature": "def encrypt_message(message, key):", "score": 0.6, "domain": "generic"} {"id": "274afcc2e746b6ae4c11c5c9e800d904", "problem": "You are given a list of DNA sequences, where each sequence is a string consisting of the characters 'A', 'C', 'G', and 'T'. Your task is to compute the frequency of each nucleotide and each unique nucleotide pair ('AA', 'AC', ..., 'TT') across all sequences.\n\nWrite a function `compute_nucleotide_frequency(dna_sequences)` that takes a list of DNA sequences as input and returns a dictionary containing two keys: 'nucleotides' and 'pairs'. The value for 'nucleotides' is a dictionary of nucleotide frequencies, and the value for 'pairs' is a dictionary of nucleotide pair frequencies. Frequencies are calculated as the count of each nucleotide or pair divided by the total count of nucleotides or pairs, respectively.\n\n**Constraints:**\n- The input list is non-empty.\n- Each sequence in the list contains only valid nucleotides ('A', 'C', 'G', 'T').\n\n**Sample Input:**\n```python\n[\"ACGT\", \"ACGTA\", \"CGTAC\"]\n```\n\n**Sample Output:**\n```python\n{\n 'nucleotides': {'A': 0.3, 'C': 0.25, 'G': 0.25, 'T': 0.2},\n 'pairs': {'AC': 0.25, 'CG': 0.25, 'GT': 0.25, 'TA': 0.25, 'AG': 0.25, 'GC': 0.25, 'CT': 0.25}\n}\n```", "reference": "def compute_nucleotide_frequency(dna_sequences):\n \"\"\"\n Computes the frequency of each nucleotide and nucleotide pair in a list of DNA sequences.\n\n Parameters:\n dna_sequences (list of str): A list of DNA sequences.\n\n Returns:\n dict: A dictionary with keys 'nucleotides' and 'pairs', each containing a dictionary of frequencies.\n \"\"\"\n nucleotide_counts = {'A': 0, 'C': 0, 'G': 0, 'T': 0}\n nucleotide_pair_counts = {}\n\n total_nucleotides = 0\n\n for sequence in dna_sequences:\n for i in range(len(sequence)):\n nucleotide = sequence[i]\n nucleotide_counts[nucleotide] += 1\n total_nucleotides += 1\n \n if i < len(sequence) - 1:\n pair = sequence[i] + sequence[i+1]\n if pair not in nucleotide_pair_counts:\n nucleotide_pair_counts[pair] = 0\n nucleotide_pair_counts[pair] += 1\n\n total_pairs = sum(nucleotide_pair_counts.values())\n nucleotide_frequencies = {n: nucleotide_counts[n] / total_nucleotides for n in nucleotide_counts}\n nucleotide_pair_frequencies = {p: nucleotide_pair_counts[p] / total_pairs for p in nucleotide_pair_counts}\n\n return {'nucleotides': nucleotide_frequencies, 'pairs': nucleotide_pair_frequencies}", "tests": ["assert compute_nucleotide_frequency([\"ACGT\"]) == {'nucleotides': {'A': 0.25, 'C': 0.25, 'G': 0.25, 'T': 0.25}, 'pairs': {'AC': 0.5, 'CG': 0.5, 'GT': 0.5}}", "assert compute_nucleotide_frequency([\"AAAA\", \"CCCC\"]) == {'nucleotides': {'A': 0.5, 'C': 0.5, 'G': 0.0, 'T': 0.0}, 'pairs': {'AA': 1.0, 'CC': 1.0}}", "assert compute_nucleotide_frequency([\"AC\", \"CA\"]) == {'nucleotides': {'A': 0.5, 'C': 0.5, 'G': 0.0, 'T': 0.0}, 'pairs': {'AC': 0.5, 'CA': 0.5}}", "assert compute_nucleotide_frequency([\"ACGT\", \"TGCA\"]) == {'nucleotides': {'A': 0.25, 'C': 0.25, 'G': 0.25, 'T': 0.25}, 'pairs': {'AC': 0.25, 'CG': 0.25, 'GT': 0.25, 'TG': 0.25, 'GC': 0.25, 'CA': 0.25, 'TA': 0.25, 'AG': 0.25}}", "assert compute_nucleotide_frequency([\"A\", \"C\", \"G\", \"T\"]) == {'nucleotides': {'A': 0.25, 'C': 0.25, 'G': 0.25, 'T': 0.25}, 'pairs': {}}", "assert compute_nucleotide_frequency([\"AA\", \"CC\", \"GG\", \"TT\"]) == {'nucleotides': {'A': 0.5, 'C': 0.5, 'G': 0.0, 'T': 0.0}, 'pairs': {'AA': 1.0, 'CC': 1.0}}", "assert compute_nucleotide_frequency([\"ACGTACGT\"]) == {'nucleotides': {'A': 0.25, 'C': 0.25, 'G': 0.25, 'T': 0.25}, 'pairs': {'AC': 0.25, 'CG': 0.25, 'GT': 0.25, 'TA': 0.25}}", "assert compute_nucleotide_frequency([\"ACG\", \"CGT\", \"GTA\"]) == {'nucleotides': {'A': 0.3333333333333333, 'C': 0.3333333333333333, 'G': 0.3333333333333333, 'T': 0.0}, 'pairs': {'AC': 0.5, 'CG': 1.0, 'GT': 0.5, 'TA': 0.5}}", "assert compute_nucleotide_frequency([\"ACGT\", \"ACGT\", \"ACGT\"]) == {'nucleotides': {'A': 0.25, 'C': 0.25, 'G': 0.25, 'T': 0.25}, 'pairs': {'AC': 0.25, 'CG': 0.25, 'GT': 0.25, 'TA': 0.25}}", "assert compute_nucleotide_frequency([\"A\", \"A\", \"A\", \"A\"]) == {'nucleotides': {'A': 1.0, 'C': 0.0, 'G': 0.0, 'T': 0.0}, 'pairs': {}}"], "function": "compute_nucleotide_frequency", "signature": "def compute_nucleotide_frequency(dna_sequences):", "score": 0.3, "domain": "generic"} {"id": "14e2719f0c0eb01d155bfbea5591987d", "problem": "You are given a list of integers. Your task is to write a function that computes the sum of the two smallest integers in the list. The function should handle edge cases, such as lists containing negative numbers and duplicates. If the list contains fewer than two integers, the function should raise a `ValueError`.\n\n**Sample Input:**\n```\n[-10, 5, 20, -20, 30, 5]\n```\n\n**Sample Output:**\n```\n-30\n```", "reference": "def sum_of_two_smallest(numbers):\n \"\"\"\n Computes the sum of the two smallest integers in the given list.\n \n Parameters:\n numbers (list of int): A list of integers.\n \n Returns:\n int: The sum of the two smallest integers in the list.\n \n Raises:\n ValueError: If the list contains fewer than two integers.\n \"\"\"\n if len(numbers) < 2:\n raise ValueError(\"List must contain at least two numbers.\")\n \n sorted_numbers = sorted(numbers)\n return sorted_numbers[0] + sorted_numbers[1]\n\n# Example usage\nnumbers = [-10, 5, 20, -20, 30, 5]\nresult = sum_of_two_smallest(numbers)\nprint(result) # Output should be -30", "tests": ["assert sum_of_two_smallest([1, 2, 3, 4, 5]) == 3", "assert sum_of_two_smallest([-1, -2, -3, -4, -5]) == -6", "assert sum_of_two_smallest([10, 20, 30, 40, 50]) == 30", "assert sum_of_two_smallest([5, 5, 5, 5, 5]) == 10", "assert sum_of_two_smallest([-10, 5, 20, -20, 30, 5]) == -30", "assert sum_of_two_smallest([0, 0, 0, 0, 0]) == 0", "assert sum_of_two_smallest([100, 200, 300, 400, 500]) == 300", "assert sum_of_two_smallest([-100, -200, 300, 400, 500]) == -300", "assert sum_of_two_smallest([1, -1, 2, -2, 3]) == -3", "assert sum_of_two_smallest([1000, 2000, 3000, 4000, 5000]) == 3000"], "function": "sum_of_two_smallest", "signature": "def sum_of_two_smallest(numbers):", "score": 0.9, "domain": "algorithmic"} {"id": "6be119b7e3e83c2b9d6436a275a59c84", "problem": "You are given two datasets: a background dataset and an input dataset. The background dataset is structured as a dictionary where each key is a label and the corresponding value is a list of entities associated with that label. The input dataset is a list of entities. Your task is to implement a function that identifies the common entities between the input dataset and each label's entities in the background dataset. The function should return a dictionary where each key is a label from the background dataset, and the value is a set of entities that are present in both the corresponding label's entities and the input dataset. Your solution should have a time complexity of O(n), where n is the total number of entities across all labels in the background dataset and in the input dataset.\n\n**Sample Input:**\n```python\nbackground_dataset = {\n 'fruits': ['apple', 'banana', 'cherry'],\n 'vegetables': ['carrot', 'lettuce', 'spinach'],\n 'grains': ['rice', 'wheat', 'oats']\n}\ninput_dataset = ['banana', 'carrot', 'oats', 'grape']\n```\n\n**Sample Output:**\n```python\n{\n 'fruits': {'banana'},\n 'vegetables': {'carrot'},\n 'grains': {'oats'}\n}\n```", "reference": "def find_common_entities(background_dataset, input_dataset):\n \"\"\"\n Finds common entities between the input dataset and each label's entities in the background dataset.\n \n :param background_dataset: A dictionary where keys are labels and values are lists of entities.\n :param input_dataset: A list of entities.\n :return: A dictionary with labels as keys and sets of common entities as values.\n \"\"\"\n input_dataset_set = set(input_dataset)\n result = {}\n \n for label, entities in background_dataset.items():\n common_entities = {entity for entity in entities if entity in input_dataset_set}\n result[label] = common_entities\n \n return result", "tests": ["assert find_common_entities({\"fruits\": [\"apple\", \"banana\", \"cherry\"], \"vegetables\": [\"carrot\", \"lettuce\"]}, [\"banana\", \"carrot\"]) == {\"fruits\": {\"banana\"}, \"vegetables\": {\"carrot\"}}", "assert find_common_entities({\"fruits\": [\"apple\", \"banana\"], \"vegetables\": [\"carrot\", \"lettuce\"]}, [\"grape\", \"spinach\"]) == {\"fruits\": set(), \"vegetables\": set()}", "assert find_common_entities({\"fruits\": [\"apple\", \"banana\", \"cherry\"], \"vegetables\": [\"carrot\", \"lettuce\"]}, [\"apple\", \"banana\", \"carrot\", \"lettuce\"]) == {\"fruits\": {\"apple\", \"banana\"}, \"vegetables\": {\"carrot\", \"lettuce\"}}", "assert find_common_entities({\"fruits\": [\"apple\", \"banana\"], \"vegetables\": [\"carrot\", \"lettuce\"]}, []) == {\"fruits\": set(), \"vegetables\": set()}", "assert find_common_entities({}, [\"apple\", \"banana\", \"carrot\", \"lettuce\"]) == {}", "assert find_common_entities({\"fruits\": [\"apple\", \"banana\", \"cherry\"], \"vegetables\": [\"carrot\", \"lettuce\"]}, [\"apple\", \"banana\", \"cherry\", \"carrot\", \"lettuce\"]) == {\"fruits\": {\"apple\", \"banana\", \"cherry\"}, \"vegetables\": {\"carrot\", \"lettuce\"}}", "assert find_common_entities({\"fruits\": [\"apple\", \"banana\", \"cherry\"], \"vegetables\": [\"carrot\", \"lettuce\"]}, [\"apple\", \"banana\"]) == {\"fruits\": {\"apple\", \"banana\"}, \"vegetables\": set()}", "assert find_common_entities({\"fruits\": [\"apple\", \"banana\", \"cherry\"], \"vegetables\": [\"carrot\", \"lettuce\"]}, [\"carrot\", \"lettuce\"]) == {\"fruits\": set(), \"vegetables\": {\"carrot\", \"lettuce\"}}", "assert find_common_entities({\"fruits\": [\"apple\", \"banana\", \"cherry\"], \"vegetables\": [\"carrot\", \"lettuce\"]}, [\"apple\", \"carrot\"]) == {\"fruits\": {\"apple\"}, \"vegetables\": {\"carrot\"}}", "assert find_common_entities({\"fruits\": [\"apple\", \"banana\", \"cherry\"], \"vegetables\": [\"carrot\", \"lettuce\"]}, [\"banana\", \"lettuce\"]) == {\"fruits\": {\"banana\"}, \"vegetables\": {\"lettuce\"}}"], "function": "find_common_entities", "signature": "def find_common_entities(background_dataset, input_dataset):", "score": 1.0, "domain": "generic"} {"id": "b1729dd9080c6f459ad68ec329740316", "problem": "In a programming competition, you are required to implement a function that computes the nth Fibonacci number using an iterative method. The function must not employ recursion and should be efficient for large values of n. Your solution should handle the following constraints:\n\n- **Input:** A single integer n (0 ≤ n ≤ 10^6).\n- **Output:** A single integer representing the nth Fibonacci number.\n\n**Sample Input:**\n```\n10\n```\n\n**Sample Output:**\n```\n55\n```", "reference": "def fibonacci(n):\n \"\"\"\n Computes the nth Fibonacci number using an iterative approach.\n \n Parameters:\n n (int): The position in the Fibonacci sequence (0-indexed).\n \n Returns:\n int: The nth Fibonacci number.\n \"\"\"\n if n <= 0:\n return 0\n elif n == 1:\n return 1\n \n a, b = 0, 1\n for _ in range(2, n + 1):\n a, b = b, a + b\n return b\n\n# Example usage:\n# print(fibonacci(10)) # Output: 55", "tests": ["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(20) == 6765", "assert fibonacci(30) == 832040", "assert fibonacci(50) == 12586269025"], "function": "fibonacci", "signature": "def fibonacci(n):", "score": 1.0, "domain": "generic"} {"id": "1d5a12897948714dbfb7ca36d87659a0", "problem": "You are given a list of integers `nums`. Your task is to implement a function `find_max_min` that determines the maximum and minimum values in the list. The function should return a tuple with the maximum value as the first element and the minimum value as the second element. If the list is empty, the function should return `None`.\n\n**Sample Input:**\n```\nnums = [3, 5, 1, 2, 4, 8, 0, -1, 7]\n```\n\n**Sample Output:**\n```\n(8, -1)\n```", "reference": "def find_max_min(nums):\n \"\"\"\n Finds the maximum and minimum values in a list of integers.\n\n Parameters:\n nums (list): A list of integers.\n\n Returns:\n tuple: A tuple containing the maximum and minimum values, or None if the list is empty.\n \"\"\"\n if not nums:\n return None # Handle the case where the list is empty\n\n max_val = nums[0]\n min_val = nums[0]\n\n for num in nums:\n if num > max_val:\n max_val = num\n if num < min_val:\n min_val = num\n\n return (max_val, min_val)\n\n# Example usage:\nnums = [3, 5, 1, 2, 4, 8, 0, -1, 7]\nresult = find_max_min(nums)\nprint(result) # Output should be (8, -1)", "tests": ["assert find_max_min([3, 5, 1, 2, 4, 8, 0, -1, 7]) == (8, -1)", "assert find_max_min([10, 20, 30, 40, 50]) == (50, 10)", "assert find_max_min([-10, -20, -30, -40, -50]) == (-10, -50)", "assert find_max_min([100]) == (100, 100)", "assert find_max_min([0, 0, 0, 0]) == (0, 0)", "assert find_max_min([]) == None", "assert find_max_min([1, -1, 1, -1]) == (1, -1)", "assert find_max_min([5]) == (5, 5)", "assert find_max_min([10, 9, 8, 7, 6, 5, 4, 3, 2, 1]) == (10, 1)", "assert find_max_min([-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5]) == (5, -5)"], "function": "find_max_min", "signature": "def find_max_min(nums):", "score": 1.0, "domain": "generic"} {"id": "bcb6750865ba3e62a9406f27c27750b5", "problem": "You are given a CSV file named \"data.csv\" with headers in the first row. Your task is to write a Python script that calculates the average of each column containing numerical data. If a column contains non-numeric data, it should be skipped. The script should output the averages in a tabular format with the column headers as the first column. If the CSV file does not exist, the script should handle the error gracefully and print an appropriate message.\n\n**Sample Input:**\n```\nName,Age,Height,Weight\nAlice,25,165.5,55\nBob,30,175,75\nCharlie,22,180,80\nDavid,28,170,70\nEve,24,160,50\n```\n\n**Sample Output:**\n```\nColumn Average\nAge 25.80\nHeight 170.00\nWeight 66.00\n```", "reference": "import csv\nfrom statistics import mean\nimport os\n\ndef calculate_column_averages(file_path):\n \"\"\"\n Calculate the average of each numeric column in a CSV file.\n\n Parameters:\n file_path (str): The path to the CSV file.\n\n Returns:\n None: Prints the averages in a tabular format or an error message if the file does not exist.\n \"\"\"\n if not os.path.exists(file_path):\n print(\"The file does not exist. Please check the file path.\")\n return\n\n averages = {}\n with open(file_path, mode='r', newline='', encoding='utf-8') as csvfile:\n reader = csv.DictReader(csvfile)\n columns = reader.fieldnames\n numeric_columns = {column: [] for column in columns}\n\n for row in reader:\n for column in columns:\n try:\n numeric_value = float(row[column])\n numeric_columns[column].append(numeric_value)\n except ValueError:\n continue\n\n for column, values in numeric_columns.items():\n if values:\n averages[column] = mean(values)\n\n if averages:\n print(f\"{'Column':<20}{'Average':>10}\")\n for column, avg in averages.items():\n print(f\"{column:<20}{avg:>10.2f}\")\n else:\n print(\"No numeric data found to calculate averages.\")\n\n# Replace 'data.csv' with the path to your CSV file\ncalculate_column_averages('data.csv')", "tests": ["assert calculate_column_averages('nonexistentfile.csv') is None", "assert calculate_column_averages('empty.csv') is None", "assert calculate_column_averages('single_numeric_column.csv') is None", "assert calculate_column_averages('multiple_numeric_columns.csv') is None", "assert calculate_column_averages('mixed_data_types.csv') is None", "assert calculate_column_averages('only_non_numeric.csv') is None", "assert calculate_column_averages('single_row_numeric.csv') is None", "assert calculate_column_averages('multiple_rows_numeric.csv') is None", "assert calculate_column_averages('large_numbers.csv') is None", "assert calculate_column_averages('negative_numbers.csv') is None"], "function": "calculate_column_averages", "signature": "def calculate_column_averages(file_path):", "score": 0.9, "domain": "generic"} {"id": "e8f49c5e111fba75b576099d03226455", "problem": "You are given a sequence of natural numbers `S` that includes all numbers from 1 to `n`. Your task is to implement a function `find_missing_number` that takes an integer `n` and a list `numbers` as input. The list `numbers` contains `n-1` numbers from the sequence `S` with exactly one number missing. Your function should return the missing number. If the input is invalid (i.e., `numbers` does not contain `n-1` unique integers or if `numbers` contains integers outside the range from 1 to `n`), the function should raise a `ValueError`.\n\n**Input:**\n- An integer `n` (1 ≤ n ≤ 10^6)\n- A list `numbers` of `n-1` integers\n\n**Output:**\n- An integer representing the missing number from the sequence.\n\n**Sample Input:**\n```\nn = 10\nnumbers = [1, 2, 3, 4, 5, 6, 7, 8, 10]\n```\n\n**Sample Output:**\n```\n9\n```", "reference": "def find_missing_number(n, numbers):\n \"\"\"\n Finds the missing number in a sequence from 1 to n given a list of n-1 numbers.\n \n Parameters:\n n (int): The upper limit of the sequence.\n numbers (list): A list of n-1 integers from the sequence.\n \n Returns:\n int: The missing number in the sequence.\n \n Raises:\n ValueError: If the input list does not contain n-1 unique integers or if any integer is outside the range from 1 to n.\n \"\"\"\n if len(numbers) != n - 1:\n raise ValueError(\"The list must contain n-1 unique integers.\")\n \n if not all(1 <= num <= n for num in numbers):\n raise ValueError(\"All numbers must be within the range from 1 to n.\")\n \n expected_sum = n * (n + 1) // 2\n actual_sum = sum(numbers)\n \n return expected_sum - actual_sum\n\n# Example usage\nn = 10\nnumbers = [1, 2, 3, 4, 5, 6, 7, 8, 10]\nmissing_number = find_missing_number(n, numbers)\nprint(f\"The missing number is: {missing_number}\")", "tests": ["assert find_missing_number(5, [1, 2, 3, 5]) == 4", "assert find_missing_number(10, [1, 2, 3, 4, 5, 6, 7, 8, 10]) == 9", "assert find_missing_number(1, []) == 1", "assert find_missing_number(3, [1, 3]) == 2", "assert find_missing_number(6, [1, 2, 3, 4, 5]) == 6", "assert find_missing_number(7, [7, 6, 5, 4, 3, 2]) == 1", "assert find_missing_number(100, list(range(1, 101))) == 0", "assert find_missing_number(100, list(range(2, 101))) == 1", "assert find_missing_number(10, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) == 0", "assert find_missing_number(10, [11, 2, 3, 4, 5, 6, 7, 8, 9]) == 0"], "function": "find_missing_number", "signature": "def find_missing_number(n, numbers):", "score": 0.7, "domain": "generic"} {"id": "13cc4e8df4884faf199e272e1928ba1f", "problem": "You are given two strings `str1` and `str2`. Your task is to write a function that computes the length of the longest common subsequence (LCS) between these two strings. A subsequence is a sequence derived from another sequence where some elements may be deleted without changing the order of the remaining elements.\n\n**Input:**\n- Two strings `str1` and `str2` (1 ≤ |str1|, |str2| ≤ 1000), consisting of uppercase English letters.\n\n**Output:**\n- An integer representing the length of the longest common subsequence.\n\n**Sample Input:**\n```\nABCBDAB\nBDCAB\n```\n\n**Sample Output:**\n```\n4\n```", "reference": "def longest_common_subsequence(str1, str2):\n \"\"\"\n Computes the length of the longest common subsequence between two strings.\n\n :param str1: First input string\n :param str2: Second input string\n :return: Length of the longest common subsequence\n \"\"\"\n m = len(str1)\n n = len(str2)\n lcs_table = [[0] * (n + 1) for _ in range(m + 1)]\n \n for i in range(1, m + 1):\n for j in range(1, n + 1):\n if str1[i - 1] == str2[j - 1]:\n lcs_table[i][j] = lcs_table[i - 1][j - 1] + 1\n else:\n lcs_table[i][j] = max(lcs_table[i - 1][j], lcs_table[i][j - 1])\n \n return lcs_table[m][n]\n\n# Test the function with the given strings\nstr1 = \"ABCBDAB\"\nstr2 = \"BDCAB\"\nprint(longest_common_subsequence(str1, str2)) # Output: 4", "tests": ["assert longest_common_subsequence(\"ABCBDAB\", \"BDCAB\") == 4", "assert longest_common_subsequence(\"AGGTAB\", \"GXTXAYB\") == 4", "assert longest_common_subsequence(\"aaaa\", \"aa\") == 2", "assert longest_common_subsequence(\"abc\", \"def\") == 0", "assert longest_common_subsequence(\"\", \"abc\") == 0", "assert longest_common_subsequence(\"abc\", \"\") == 0", "assert longest_common_subsequence(\"\", \"\") == 0", "assert longest_common_subsequence(\"abcdef\", \"abcdef\") == 6", "assert longest_common_subsequence(\"abcde\", \"edcba\") == 2", "assert longest_common_subsequence(\"12345\", \"54321\") == 1"], "function": "longest_common_subsequence", "signature": "def longest_common_subsequence(str1, str2):", "score": 0.9, "domain": "algorithmic"} {"id": "a457cdace78f9218d3f9ca2ca7052c88", "problem": "You are participating in a programming competition where you are given a dictionary `data`. The dictionary contains product names as keys and lists of prices for each product as values. Your task is to implement a function `find_best_price(data)` that returns a new dictionary. In this new dictionary, each key should be a product name, and the corresponding value should be the minimum price for that product. \n\n**Input:**\n- A dictionary `data` where keys are strings representing product names and values are lists of floats representing prices.\n\n**Output:**\n- A dictionary with the same keys as `data`, but with values being the minimum price for each product.\n\n**Sample Input:**\n```python\n{'apple': [0.99, 0.89, 1.09], 'banana': [0.59, 0.49, 0.69]}\n```\n\n**Sample Output:**\n```python\n{'apple': 0.89, 'banana': 0.49}\n```", "reference": "def find_best_price(data):\n \"\"\"\n Returns a dictionary with product names as keys and their minimum prices as values.\n\n :param data: A dictionary where keys are product names and values are lists of prices.\n :return: A dictionary with product names as keys and minimum prices as values.\n \"\"\"\n return {product: min(prices) for product, prices in data.items()}", "tests": ["assert find_best_price({'apple': [0.99, 0.89, 1.09], 'banana': [0.59, 0.49, 0.69]}) == {'apple': 0.89, 'banana': 0.49}", "assert find_best_price({'orange': [1.29, 1.19, 1.39], 'grape': [2.99, 2.89, 3.09]}) == {'orange': 1.19, 'grape': 2.89}", "assert find_best_price({'pear': [0.79], 'peach': [0.69]}) == {'pear': 0.79, 'peach': 0.69}", "assert find_best_price({'kiwi': [0.99, 0.99, 0.99], 'plum': [1.09, 1.09, 1.09]}) == {'kiwi': 0.99, 'plum': 1.09}", "assert find_best_price({'strawberry': [2.99, 2.89, 2.79], 'blueberry': [3.99, 3.89, 3.79]}) == {'strawberry': 2.79, 'blueberry': 3.79}", "assert find_best_price({'melon': [1.59, 1.49, 1.39], 'cantaloupe': [1.69, 1.59, 1.49]}) == {'melon': 1.39, 'cantaloupe': 1.49}", "assert find_best_price({'watermelon': [3.99, 3.89, 3.79], 'honeydew': [4.99, 4.89, 4.79]}) == {'watermelon': 3.79, 'honeydew': 4.79}", "assert find_best_price({'grapefruit': [1.99, 1.89, 1.79], 'lime': [0.99, 0.89, 0.79]}) == {'grapefruit': 1.79, 'lime': 0.79}", "assert find_best_price({'lemon': [0.59, 0.49, 0.39], 'lime': [0.69, 0.59, 0.49]}) == {'lemon': 0.39, 'lime': 0.49}", "assert find_best_price({}) == {}"], "function": "find_best_price", "signature": "def find_best_price(data):", "score": 1.0, "domain": "generic"} {"id": "0bcbcbc18161f3657c7e92bb18c97573", "problem": "You are given a string `s` consisting of characters '(', ')', '[', ']', '{', and '}'. Your task is to determine if the string has balanced parentheses. A string has balanced parentheses if each opening parenthesis has a corresponding closing parenthesis in the correct order. Return `True` if the string is balanced, otherwise return `False`.\n\n**Sample Input:**\n```\n(([]){})\n```\n\n**Sample Output:**\n```\nTrue\n```\n\n**Sample Input:**\n```\n([)]\n```\n\n**Sample Output:**\n```\nFalse\n```", "reference": "def is_balanced_parentheses(s):\n \"\"\"\n Checks if the given string has balanced parentheses.\n\n :param s: A string containing characters '(', ')', '[', ']', '{', and '}'.\n :return: True if the string has balanced parentheses, False otherwise.\n \"\"\"\n matching_parentheses = {')': '(', ']': '[', '}': '{'}\n stack = []\n\n for char in s:\n if char in matching_parentheses.values():\n stack.append(char)\n elif char in matching_parentheses.keys():\n if not stack or matching_parentheses[char] != stack.pop():\n return False\n\n return not stack", "tests": ["assert is_balanced_parentheses(\"(([]){})\") == True", "assert is_balanced_parentheses(\"([)]\") == False", "assert is_balanced_parentheses(\"{[()]}\") == True", "assert is_balanced_parentheses(\"((({{{[[[]]]}}})))\") == True", "assert is_balanced_parentheses(\"((((((()))))))\") == True", "assert is_balanced_parentheses(\"((((((())\")) == False", "assert is_balanced_parentheses(\")(\") == False", "assert is_balanced_parentheses(\"\") == True", "assert is_balanced_parentheses(\"abc\") == True", "assert is_balanced_parentheses(\"[{]}\") == False"], "function": "is_balanced_parentheses", "signature": "def is_balanced_parentheses(s):", "score": 0.9, "domain": "generic"} {"id": "7ca9aa286134ce541f2646f90e31afd6", "problem": "Given a floating-point number `f` and an integer `q`, write a function `closest_multiple(f, q)` that returns the closest integer multiple of `q` to `f`, excluding zero. If `f` is exactly halfway between two multiples of `q`, the function should return the larger multiple. Ensure that the solution handles floating-point precision issues correctly.\n\n**Constraints:**\n- `-10^9 <= f <= 10^9`\n- `1 <= q <= 10^9`\n\n**Sample Input and Output:**\n- `closest_multiple(3.5, 2)` should return `4`\n- `closest_multiple(-3.5, 2)` should return `-4`\n- `closest_multiple(0.5, 1)` should return `1`\n- `closest_multiple(-0.5, 1)` should return `-1`", "reference": "def closest_multiple(f, q):\n \"\"\"\n Returns the closest integer multiple of q to f, excluding zero.\n If f is exactly halfway between two multiples of q, returns the larger multiple.\n \n :param f: A floating-point number\n :param q: An integer\n :return: The closest integer multiple of q to f\n \"\"\"\n base = round(f / q)\n if base == 0 and f != 0:\n base = 1 if f > 0 else -1\n closest = base * q\n if abs(f - closest) == abs(f - (closest + q)) or abs(f - closest) == abs(f - (closest - q)):\n closest = (closest + q) if f > 0 else (closest - q)\n return closest", "tests": ["assert closest_multiple(3.5, 2) == 4", "assert closest_multiple(-3.5, 2) == -4", "assert closest_multiple(0.5, 1) == 1", "assert closest_multiple(-0.5, 1) == -1", "assert closest_multiple(2.0, 3) == 3", "assert closest_multiple(-2.0, 3) == -3", "assert closest_multiple(0.0, 5) == 5", "assert closest_multiple(1.49, 1) == 1", "assert closest_multiple(-1.49, 1) == -1", "assert closest_multiple(10.0, 10) == 10"], "function": "closest_multiple", "signature": "def closest_multiple(f, q):", "score": 0.7, "domain": "generic"} {"id": "4db01baaf2580d48c86be4337c8e5ba6", "problem": "You are given a list of strings, each representing a different activity. Your task is to write a Python function `find_longest_activity(activities)` that identifies and returns the activity with the longest name. If there are multiple activities with the same maximum length, return the first one encountered.\n\n**Input:**\n- A list of strings `activities` (1 ≤ len(activities) ≤ 100), where each string has a length between 1 and 50 characters.\n\n**Output:**\n- A string representing the activity with the longest name.\n\n**Sample Input:**\n```python\n[\"Reading\", \"Swimming\", \"Coding\"]\n```\n\n**Sample Output:**\n```\n\"Swimming\"\n```", "reference": "def find_longest_activity(activities):\n \"\"\"\n Finds and returns the activity with the longest name from a list of activities.\n If there are multiple activities with the same longest length, returns the first one encountered.\n\n :param activities: List of strings representing activities.\n :return: String with the longest activity name.\n \"\"\"\n longest_activity = \"\"\n max_length = 0\n \n for activity in activities:\n if len(activity) > max_length:\n longest_activity = activity\n max_length = len(activity)\n \n return longest_activity\n\n# Example usage\nactivities = [\"Reading\", \"Swimming\", \"Coding\"]\nprint(find_longest_activity(activities)) # Output: \"Swimming\"", "tests": ["assert find_longest_activity([\"Reading\", \"Swimming\", \"Coding\"]) == \"Swimming\"", "assert find_longest_activity([\"Running\", \"Jumping\", \"Cycling\"]) == \"Running\"", "assert find_longest_activity([\"Hiking\", \"Kayaking\", \"Skiing\"]) == \"Kayaking\"", "assert find_longest_activity([\"Gaming\", \"Dancing\", \"Cooking\"]) == \"Gaming\"", "assert find_longest_activity([\"Walking\", \"Talking\", \"Laughing\"]) == \"Laughing\"", "assert find_longest_activity([\"\"]) == \"\"", "assert find_longest_activity([\"A\", \"BB\", \"CCC\", \"DDDD\"]) == \"DDDD\"", "assert find_longest_activity([\"Equal\", \"Equal\", \"Equal\"]) == \"Equal\"", "assert find_longest_activity([\"Short\", \"Longer\", \"Longest\", \"Longer\"]) == \"Longest\"", "assert find_longest_activity([]) == \"\""], "function": "find_longest_activity", "signature": "def find_longest_activity(activities):", "score": 0.9, "domain": "generic"} {"id": "433f457d27a18344811efc699acf2b0a", "problem": "You are given a string `sentence`. Your task is to implement a function `find_longest_word` that returns the longest word in the string. If there are multiple words with the same maximum length, return the first one encountered. Punctuation is considered part of a word. \n\n**Input:**\n- A single string `sentence` (1 ≤ |sentence| ≤ 1000), consisting of letters, digits, punctuation marks, and spaces.\n\n**Output:**\n- A single string representing the longest word in the input sentence.\n\n**Sample Input:**\n```\nPython, being an interpreted, high-level, general-purpose programming language, comes with dynamic semantics.\n```\n\n**Sample Output:**\n```\ngeneral-purpose\n```", "reference": "def find_longest_word(sentence):\n \"\"\"\n Returns the longest word in the given sentence. If there are multiple words\n with the same maximum length, returns the first one encountered. Punctuation\n is considered part of a word.\n\n :param sentence: A string containing words separated by spaces.\n :return: The longest word in the sentence.\n \"\"\"\n words = sentence.split()\n longest_word = max(words, key=len)\n return longest_word\n\n# Example usage:\ninput_string = \"Python, being an interpreted, high-level, general-purpose programming language, comes with dynamic semantics.\"\nresult = find_longest_word(input_string)\nprint(result) # Output: general-purpose", "tests": ["assert find_longest_word(\"Python, being an interpreted, high-level, general-purpose programming language, comes with dynamic semantics.\") == \"general-purpose\"", "assert find_longest_word(\"The quick brown fox jumps over the lazy dog\") == \"quick\"", "assert find_longest_word(\"To be or not to be, that is the question\") == \"question\"", "assert find_longest_word(\"a\") == \"a\"", "assert find_longest_word(\"equal equal equal\") == \"equal\"", "assert find_longest_word(\"hello world\") == \"hello\"", "assert find_longest_word(\"one two three four five six seven eight nine ten eleven\") == \"eleven\"", "assert find_longest_word(\"punctuation!should,be:part/of-words\") == \"punctuation!should,be:part/of-words\"", "assert find_longest_word(\"\") == \"\"", "assert find_longest_word(\"spaces between words\") == \"between\""], "function": "find_longest_word", "signature": "def find_longest_word(sentence):", "score": 0.9, "domain": "generic"} {"id": "4d10642e9ec5fcec4230a176e413b124", "problem": "You are given a list of integer intervals represented as tuples, where each tuple contains the start and end points of an interval. Your task is to merge all overlapping intervals into a single interval. If there are no overlapping intervals, the output should be the same as the input. The intervals are provided in arbitrary order and may not be sorted. Write a function `merge_intervals(intervals: list) -> list` that takes a list of intervals as input and returns a list of merged intervals in sorted order.\n\n**Input:**\n- A list of tuples, where each tuple contains two integers representing the start and end points of an interval.\n\n**Output:**\n- A list of tuples, where each tuple contains two integers representing the start and end points of a merged interval, sorted by the start point.\n\n**Sample Input:**\n```python\n[(1, 3), (5, 8), (2, 4), (9, 10)]\n```\n\n**Sample Output:**\n```python\n[(1, 4), (5, 8), (9, 10)]\n```", "reference": "def merge_intervals(intervals: list) -> list:\n \"\"\"\n Merges overlapping intervals from a list of tuples and returns a list of merged intervals in sorted order.\n \n :param intervals: List of tuples, where each tuple contains two integers representing the start and end points of an interval.\n :return: List of tuples, where each tuple contains two integers representing the start and end points of a merged interval.\n \"\"\"\n if not intervals:\n return []\n \n intervals.sort(key=lambda x: x[0])\n \n merged = [intervals[0]]\n \n for current in intervals[1:]:\n last_merged = merged[-1]\n \n if current[0] <= last_merged[1]:\n merged[-1] = (last_merged[0], max(last_merged[1], current[1]))\n else:\n merged.append(current)\n \n return merged", "tests": ["assert merge_intervals([(1, 3), (2, 6), (8, 10), (15, 18)]) == [(1, 6), (8, 10), (15, 18)]", "assert merge_intervals([(1, 4), (4, 5)]) == [(1, 5)]", "assert merge_intervals([(1, 2), (3, 4)]) == [(1, 2), (3, 4)]", "assert merge_intervals([(1, 3), (2, 5), (6, 9)]) == [(1, 5), (6, 9)]", "assert merge_intervals([(1, 10), (2, 6), (3, 5)]) == [(1, 10)]", "assert merge_intervals([(1, 2)]) == [(1, 2)]", "assert merge_intervals([]) == []", "assert merge_intervals([(5, 5), (6, 6), (7, 7)]) == [(5, 5), (6, 6), (7, 7)]", "assert merge_intervals([(1, 2), (2, 3), (3, 4)]) == [(1, 4)]", "assert merge_intervals([(1, 2), (4, 5), (6, 7), (8, 9), (1, 10)]) == [(1, 10)]"], "function": "merge_intervals", "signature": "def merge_intervals(intervals: list) -> list:", "score": 1.0, "domain": "generic"} {"id": "6212a64c7adb392eddd39204f2abcc0a", "problem": "You are given a list of integers. Your task is to write a Python function that identifies the largest integer in the list that is a palindrome. A number is considered a palindrome if it reads the same backward as forward. If no palindromes are present in the list, the function should return `None`.\n\n**Input:**\n- A list of integers `numbers` (1 ≤ len(numbers) ≤ 10^3), where each integer is in the range -10^6 ≤ numbers[i] ≤ 10^6.\n\n**Output:**\n- Return the largest palindrome integer from the list, or `None` if no palindromes are found.\n\n**Sample Input:**\n```\n[123, 121, 45654, 78987, 12321]\n```\n\n**Sample Output:**\n```\n78987\n```", "reference": "def largest_palindrome(numbers):\n \"\"\"\n Returns the largest palindrome number from the given list of integers.\n If no palindromes are found, returns None.\n \n :param numbers: List of integers\n :return: Largest palindrome integer or None\n \"\"\"\n def is_palindrome(num):\n \"\"\"\n Checks if the given integer is a palindrome.\n \n :param num: Integer to check\n :return: True if num is a palindrome, False otherwise\n \"\"\"\n s = str(num)\n return s == s[::-1]\n \n palindromes = [num for num in numbers if is_palindrome(num)]\n return max(palindromes) if palindromes else None", "tests": ["assert largest_palindrome([123, 121, 45654, 78987, 12321]) == 78987", "assert largest_palindrome([1, 2, 3, 4, 5]) == None", "assert largest_palindrome([1221, 1331, 1441, 1551]) == 1551", "assert largest_palindrome([10, 20, 30, 40, 50]) == None", "assert largest_palindrome([12321, 45654, 78987, 10101]) == 78987", "assert largest_palindrome([111, 222, 333, 444, 555]) == 555", "assert largest_palindrome([1234321, 78987, 123454321]) == 123454321", "assert largest_palindrome([]) == None", "assert largest_palindrome([1234321, 1234321, 1234321]) == 1234321", "assert largest_palindrome([1001, 2002, 3003, 4004, 5005]) == 5005"], "function": "largest_palindrome", "signature": "def largest_palindrome(numbers):", "score": 0.9, "domain": "generic"} {"id": "d6033e9988a8094c8bc880e64402944e", "problem": "You are given a CSV file path as input. Your task is to write a function that reads the CSV file and converts it into a list of dictionaries. Each row in the CSV file should be converted into a dictionary where the keys are the column headers and the values are the corresponding row values. If the CSV file is empty or contains only header information, the function should return an empty list. Your function should handle file not found errors and other exceptions gracefully.\n\n**Sample Input:**\n```\nname,age,city\nAlice,30,New York\nBob,25,Los Angeles\n```\n\n**Sample Output:**\n```python\n[{'name': 'Alice', 'age': '30', 'city': 'New York'}, {'name': 'Bob', 'age': '25', 'city': 'Los Angeles'}]\n```", "reference": "import csv\n\ndef csv_to_dict_list(file_path):\n \"\"\"\n Reads a CSV file and converts it into a list of dictionaries.\n \n Parameters:\n file_path (str): The path to the CSV file.\n \n Returns:\n list: A list of dictionaries where each dictionary represents a row in the CSV file.\n \"\"\"\n dict_list = []\n \n try:\n with open(file_path, mode='r', newline='', encoding='utf-8') as csvfile:\n csv_reader = csv.DictReader(csvfile)\n \n if csv_reader.fieldnames is None:\n return dict_list\n \n for row in csv_reader:\n dict_list.append(row)\n \n except FileNotFoundError:\n print(\"File not found.\")\n except Exception as e:\n print(f\"An error occurred: {e}\")\n \n return dict_list", "tests": ["assert csv_to_dict_list(\"empty.csv\") == []", "assert csv_to_dict_list(\"headers_only.csv\") == []", "assert csv_to_dict_list(\"single_row.csv\") == [{'name': 'Alice', 'age': '30'}]", "assert csv_to_dict_list(\"multiple_rows.csv\") == [{'name': 'Alice', 'age': '30'}, {'name': 'Bob', 'age': '25'}]", "assert csv_to_dict_list(\"mixed_data.csv\") == [{'name': 'Alice', 'age': '30', 'city': 'New York'}, {'name': 'Bob', 'age': '25', 'city': 'Los Angeles'}]", "assert csv_to_dict_list(\"missing_values.csv\") == [{'name': 'Alice', 'age': '', 'city': 'New York'}, {'name': '', 'age': '25', 'city': 'Los Angeles'}]", "assert csv_to_dict_list(\"non_existent_file.csv\") == []", "assert csv_to_dict_list(\"different_delimiter.csv\") == [{'name': 'Alice', 'age': '30'}, {'name': 'Bob', 'age': '25'}]", "assert csv_to_dict_list(\"trailing_commas.csv\") == [{'name': 'Alice', 'age': '30'}, {'name': 'Bob', 'age': '25'}]", "assert csv_to_dict_list(\"quoted_fields.csv\") == [{'name': 'Alice', 'age': '30'}, {'name': 'Bob', 'age': '25'}]"], "function": "csv_to_dict_list", "signature": "def csv_to_dict_list(file_path):", "score": 0.3, "domain": "generic"} {"id": "6a4a13b94c2233f65a7bacc4c7c6c4b4", "problem": "You are participating in a coding competition where you need to process a string representing the contents of a text file named `inventory.txt`. The file contains a list of items, with one item per line. Lines that start with the `#` symbol are considered comments and should be ignored. Additionally, any leading or trailing whitespace on non-comment lines should be removed. Your task is to write a function that processes this string and returns a list of uncommented and non-empty lines.\n\n**Input:**\n- A single string `file_content` representing the contents of the file, where each line is separated by a newline character `\\n`.\n\n**Output:**\n- A list of strings, each representing an uncommented and non-empty line from the file, with leading and trailing whitespace removed.\n\n**Sample Input:**\n```\n# This is a comment\napple\n# Bananas are yellow\nbanana\norange # This is a comment at the end of a line\n```\n\n**Sample Output:**\n```\n['apple', 'banana']\n```", "reference": "def read_uncommented_lines(file_content):\n \"\"\"\n Processes a string representing the contents of a text file and returns a list of uncommented and non-empty lines.\n \n :param file_content: A string representing the contents of the file, with lines separated by newline characters.\n :return: A list of strings, each representing an uncommented and non-empty line from the file.\n \"\"\"\n lines = file_content.split('\\n')\n result = []\n for line in lines:\n stripped_line = line.strip()\n if stripped_line and not stripped_line.startswith('#'):\n result.append(stripped_line)\n return result\n\n# Example usage:\nfile_content = \"\"\"# This is a comment\napple\n# Bananas are yellow\nbanana\norange # This is a comment at the end of a line\n\"\"\"\nprint(read_uncommented_lines(file_content))", "tests": ["assert read_uncommented_lines(\"# This is a comment\\napple\\n# Bananas are yellow\\nbanana\\norange # This is a comment at the end of a line\\n\") == [\"apple\", \"banana\", \"orange\"]", "assert read_uncommented_lines(\"apple\\nbanana\\norange\\n\") == [\"apple\", \"banana\", \"orange\"]", "assert read_uncommented_lines(\"#apple\\n#banana\\n#orange\\n\") == []", "assert read_uncommented_lines(\"apple\\n#banana\\norange\\n#grape\\n\") == [\"apple\", \"orange\"]", "assert read_uncommented_lines(\"apple\\n\\nbanana\\n\\norange\\n\") == [\"apple\", \"banana\", \"orange\"]", "assert read_uncommented_lines(\" apple \\n banana \\n orange \\n\") == [\"apple\", \"banana\", \"orange\"]", "assert read_uncommented_lines(\"apple # comment\\nbanana # comment\\norange # comment\\n\") == [\"apple\", \"banana\", \"orange\"]", "assert read_uncommented_lines(\"\") == []", "assert read_uncommented_lines(\"#\\n#\\n#\\n\") == []", "assert read_uncommented_lines(\"apple\\n#banana\\n\\n#grape\\norange\\n\") == [\"apple\", \"orange\"]"], "function": "read_uncommented_lines", "signature": "def read_uncommented_lines(file_content):", "score": 0.8, "domain": "generic"} {"id": "084580005f1dad011f2d2f469db8acf2", "problem": "You are tasked with implementing a function `deep_copy` that performs a deep copy of a given dictionary. The dictionary may contain nested dictionaries, and your function must ensure that all levels of nesting are copied, not just the top-level references. Your function should handle any level of nested dictionaries.\n\n**Input:**\n- A dictionary `input_dict` which may contain nested dictionaries.\n\n**Output:**\n- A new dictionary that is a deep copy of `input_dict`.\n\n**Sample Input:**\n```python\n{\"name\": \"John\", \"age\": 30, \"address\": {\"street\": \"123 Main St\", \"city\": \"Anytown\", \"zip\": \"12345\"}}\n```\n\n**Sample Output:**\n```python\n{\"name\": \"John\", \"age\": 30, \"address\": {\"street\": \"123 Main St\", \"city\": \"Anytown\", \"zip\": \"12345\"}}\n```", "reference": "import copy\n\ndef deep_copy(input_dict):\n \"\"\"\n Returns a deep copy of the input dictionary, ensuring all nested dictionaries are also copied.\n\n :param input_dict: Dictionary to be deep copied.\n :return: A new dictionary that is a deep copy of the input dictionary.\n \"\"\"\n return copy.deepcopy(input_dict)\n\n# Example usage:\ninput_dict = {\"name\": \"John\", \"age\": 30, \"address\": {\"street\": \"123 Main St\", \"city\": \"Anytown\", \"zip\": \"12345\"}}\ncopied_dict = deep_copy(input_dict)\nprint(copied_dict)", "tests": ["assert deep_copy({}) == {}", "assert deep_copy({\"key\": \"value\"}) == {\"key\": \"value\"}", "assert deep_copy({\"key\": {\"nested_key\": \"nested_value\"}}) == {\"key\": {\"nested_key\": \"nested_value\"}}", "assert deep_copy({\"key1\": \"value1\", \"key2\": {\"nested_key1\": \"nested_value1\", \"nested_key2\": \"nested_value2\"}}) == {\"key1\": \"value1\", \"key2\": {\"nested_key1\": \"nested_value1\", \"nested_key2\": \"nested_value2\"}}", "assert deep_copy({\"key\": [1, 2, 3, {\"list_nested_key\": \"list_nested_value\"}]}) == {\"key\": [1, 2, 3, {\"list_nested_key\": \"list_nested_value\"}]}", "assert deep_copy({\"key\": {\"nested_key\": {\"deep_nested_key\": \"deep_nested_value\"}}}) == {\"key\": {\"nested_key\": {\"deep_nested_key\": \"deep_nested_value\"}}}", "assert deep_copy({\"key\": {\"nested_key\": [1, 2, 3, {\"list_nested_key\": \"list_nested_value\"}]}}) == {\"key\": {\"nested_key\": [1, 2, 3, {\"list_nested_key\": \"list_nested_value\"}]}}", "assert deep_copy({\"key\": {\"nested_key\": {\"deep_nested_key\": [1, 2, 3, {\"list_nested_key\": \"list_nested_value\"}]}}}) == {\"key\": {\"nested_key\": {\"deep_nested_key\": [1, 2, 3, {\"list_nested_key\": \"list_nested_value\"}]}}}", "assert deep_copy({\"key\": {\"nested_key\": {\"deep_nested_key\": {\"deep_deep_nested_key\": \"deep_deep_nested_value\"}}}}) == {\"key\": {\"nested_key\": {\"deep_nested_key\": {\"deep_deep_nested_key\": \"deep_deep_nested_value\"}}}}", "assert deep_copy({\"key\": {\"nested_key\": {\"deep_nested_key\": {\"deep_deep_nested_key\": [1, 2, 3, {\"list_nested_key\": \"list_nested_value\"}]}}}}) == {\"key\": {\"nested_key\": {\"deep_nested_key\": {\"deep_deep_nested_key\": [1, 2, 3, {\"list_nested_key\": \"list_nested_value\"}]}}}}"], "function": "deep_copy", "signature": "def deep_copy(input_dict):", "score": 1.0, "domain": "generic"} {"id": "7ad4a6333c0062eb72b365e91f3b756d", "problem": "You are given a list of integers. Your task is to write a Python function that identifies the two numbers with the smallest difference between them. The function should return a tuple containing these two numbers. The solution should have a time complexity better than O(n^2). If there are multiple pairs with the same smallest difference, return any of them.\n\n**Sample Input:**\n```\n[4, 1, 9, 17, 6, 3, 8, 12]\n```\n\n**Sample Output:**\n```\n(3, 4)\n```", "reference": "def find_smallest_difference_pair(nums):\n \"\"\"\n Finds and returns a tuple of two numbers from the list with the smallest difference.\n \n :param nums: List of integers\n :return: Tuple containing two integers with the smallest difference\n \"\"\"\n nums.sort()\n min_diff = float('inf')\n min_pair = (None, None)\n \n for i in range(len(nums) - 1):\n diff = nums[i + 1] - nums[i]\n if diff < min_diff:\n min_diff = diff\n min_pair = (nums[i], nums[i + 1])\n \n return min_pair\n\n# Example usage:\nnums = [4, 1, 9, 17, 6, 3, 8, 12]\nresult = find_smallest_difference_pair(nums)\nprint(result)", "tests": ["assert find_smallest_difference_pair([4, 1, 9, 17, 6, 3, 8, 12]) == (3, 4)", "assert find_smallest_difference_pair([1, 3, 6, 19, 20]) == (19, 20)", "assert find_smallest_difference_pair([10, 20, 30, 40, 50]) == (10, 20)", "assert find_smallest_difference_pair([5, 8, 12, 15, 16]) == (15, 16)", "assert find_smallest_difference_pair([100, 101, 102, 103]) == (100, 101)", "assert find_smallest_difference_pair([1, 1, 1, 1]) == (1, 1)", "assert find_smallest_difference_pair([10, 22, 28, 29, 30, 40]) == (28, 29)", "assert find_smallest_difference_pair([1]) == (None, None)", "assert find_smallest_difference_pair([]) == (None, None)", "assert find_smallest_difference_pair([7, 7, 8, 8, 9, 9]) == (7, 7)"], "function": "find_smallest_difference_pair", "signature": "def find_smallest_difference_pair(nums):", "score": 1.0, "domain": "generic"} {"id": "dce088ab07b3c223aa4f4460d9c231ad", "problem": "You are tasked with implementing a function that takes a sentence as input and returns the sentence with the order of words reversed. The words themselves should remain unchanged. Your function should handle multiple spaces between words and leading/trailing spaces appropriately.\n\n**Input:**\n- A single string `sentence` (1 ≤ len(sentence) ≤ 1000) consisting of words separated by spaces.\n\n**Output:**\n- A string representing the sentence with the order of words reversed.\n\n**Sample Input:**\n```\n\"Hello world this is a test\"\n```\n\n**Sample Output:**\n```\n\"test a is this world Hello\"\n```", "reference": "def reverse_words(sentence: str) -> str:\n \"\"\"\n Reverses the order of words in a given sentence while keeping the words intact.\n \n :param sentence: A string containing words separated by spaces.\n :return: A string with the order of words reversed.\n \"\"\"\n words = sentence.split()\n words.reverse()\n reversed_sentence = ' '.join(words)\n return reversed_sentence", "tests": ["assert reverse_words(\"hello world\") == \"world hello\"", "assert reverse_words(\"the quick brown fox\") == \"fox brown quick the\"", "assert reverse_words(\"a b c d e\") == \"e d c b a\"", "assert reverse_words(\"Python is fun\") == \"fun is Python\"", "assert reverse_words(\"OpenAI GPT-4\") == \"GPT-4 OpenAI\"", "assert reverse_words(\" leading and trailing spaces \") == \"spaces trailing and leading\"", "assert reverse_words(\"multiple spaces between words\") == \"words between spaces multiple\"", "assert reverse_words(\"\") == \"\"", "assert reverse_words(\"singleword\") == \"singleword\"", "assert reverse_words(\" \") == \"\""], "function": "reverse_words", "signature": "def reverse_words(sentence: str) -> str:", "score": 1.0, "domain": "algorithmic"} {"id": "48c7d40d20b780a8e741a410896430e8", "problem": "You are given a string `s` consisting of only letters and spaces. Your task is to implement a function `find_longest_word` that returns the longest word in the string. If there are multiple words with the same maximum length, return the first one encountered.\n\n**Input:**\n- A single string `s` (1 ≤ |s| ≤ 1000), containing only letters and spaces.\n\n**Output:**\n- A single string representing the longest word in the input string.\n\n**Sample Input:**\n```\nThe quick brown fox jumps over the lazy dog\n```\n\n**Sample Output:**\n```\njumps\n```", "reference": "def find_longest_word(s):\n \"\"\"\n Returns the longest word in the input string. If there are multiple words\n with the same maximum length, returns the first one encountered.\n\n :param s: A string consisting of only letters and spaces.\n :return: The longest word in the string.\n \"\"\"\n words = s.split()\n longest_word = \"\"\n \n for word in words:\n if len(word) > len(longest_word):\n longest_word = word\n \n return longest_word", "tests": ["assert find_longest_word(\"The quick brown fox jumps over the lazy dog\") == \"jumps\"", "assert find_longest_word(\"a\") == \"a\"", "assert find_longest_word(\"equal length words\") == \"equal\"", "assert find_longest_word(\"one two three four five\") == \"three\"", "assert find_longest_word(\"longestword\") == \"longestword\"", "assert find_longest_word(\"abc defg hijklm nopqr stuv\") == \"hijklm\"", "assert find_longest_word(\"same same same\") == \"same\"", "assert find_longest_word(\" \") == \"\"", "assert find_longest_word(\"a quick movement of the enemy will jeopardize five gunboats\") == \"jeopardize\"", "assert find_longest_word(\"supercalifragilisticexpialidocious\") == \"supercalifragilisticexpialidocious\""], "function": "find_longest_word", "signature": "def find_longest_word(s):", "score": 0.8, "domain": "generic"} {"id": "62acb06445cf9138b8c1c1e8c4353465", "problem": "You are participating in a coding competition where you need to manually serialize a list of student records into a JSON-like string format. Each student record is represented as a dictionary with keys 'name', 'age', and 'grades'. The 'grades' key holds a list of integers. Your task is to write a function `dict_to_json_string` that takes a list of such dictionaries and returns a string formatted as a JSON array of objects. You are not allowed to use any built-in JSON conversion libraries.\n\n**Input:**\n- A list of dictionaries, where each dictionary contains:\n - 'name': a string representing the student's name.\n - 'age': an integer representing the student's age.\n - 'grades': a list of integers representing the student's grades.\n\n**Output:**\n- A string formatted as a JSON array of objects, where each object represents a student's information.\n\n**Sample Input:**\n```python\nstudents = [\n {'name': 'Alice', 'age': 20, 'grades': [88, 92, 85]},\n {'name': 'Bob', 'age': 22, 'grades': [78, 88, 92]},\n {'name': 'Charlie', 'age': 23, 'grades': [85, 87, 90]}\n]\n```\n\n**Sample Output:**\n```json\n[{\"name\": \"Alice\", \"age\": 20, \"grades\": [88, 92, 85]}, {\"name\": \"Bob\", \"age\": 22, \"grades\": [78, 88, 92]}, {\"name\": \"Charlie\", \"age\": 23, \"grades\": [85, 87, 90]}]\n```", "reference": "def dict_to_json_string(data):\n \"\"\"\n Converts a list of dictionaries into a JSON-like string representation.\n \n :param data: List of dictionaries, each containing 'name', 'age', and 'grades'.\n :return: A string formatted as a JSON array of objects.\n \"\"\"\n def handle_value(value):\n if isinstance(value, str):\n return f'\"{value}\"'\n elif isinstance(value, list):\n return '[' + ', '.join(handle_value(item) for item in value) + ']'\n return str(value)\n\n def convert_dict_to_json(d):\n json_parts = []\n for key, value in d.items():\n json_parts.append(f'\"{key}\": {handle_value(value)}')\n return '{' + ', '.join(json_parts) + '}'\n \n return '[' + ', '.join(convert_dict_to_json(student) for student in data) + ']'", "tests": ["assert dict_to_json_string([{'name': 'Alice', 'age': 20, 'grades': [88, 92, 85]}]) == '[{\"name\": \"Alice\", \"age\": 20, \"grades\": [88, 92, 85]}]'", "assert dict_to_json_string([{'name': 'Bob', 'age': 22, 'grades': [78, 88, 92]}]) == '[{\"name\": \"Bob\", \"age\": 22, \"grades\": [78, 88, 92]}]'", "assert dict_to_json_string([{'name': 'Charlie', 'age': 23, 'grades': [85, 87, 90]}]) == '[{\"name\": \"Charlie\", \"age\": 23, \"grades\": [85, 87, 90]}]'", "assert dict_to_json_string([]) == '[]'", "assert dict_to_json_string([{'name': 'Eve', 'age': 21, 'grades': []}]) == '[{\"name\": \"Eve\", \"age\": 21, \"grades\": []}]'", "assert dict_to_json_string([{'name': 'Mallory', 'age': 24, 'grades': [100, 100, 100]}]) == '[{\"name\": \"Mallory\", \"age\": 24, \"grades\": [100, 100, 100]}]'", "assert dict_to_json_string([{'name': 'Trent', 'age': 25, 'grades': [50, 60, 70]}, {'name': 'Oscar', 'age': 26, 'grades': [80, 90, 100]}]) == '[{\"name\": \"Trent\", \"age\": 25, \"grades\": [50, 60, 70]}, {\"name\": \"Oscar\", \"age\": 26, \"grades\": [80, 90, 100]}]'", "assert dict_to_json_string([{'name': 'Frank', 'age': 27, 'grades': [95, 85, 75]}, {'name': 'Grace', 'age': 28, 'grades': [65, 55, 45]}]) == '[{\"name\": \"Frank\", \"age\": 27, \"grades\": [95, 85, 75]}, {\"name\": \"Grace\", \"age\": 28, \"grades\": [65, 55, 45]}]'", "assert dict_to_json_string([{'name': 'Heidi', 'age': 29, 'grades': [100, 90, 80]}, {'name': 'Ivan', 'age': 30, 'grades': [70, 60, 50]}, {'name': 'Judy', 'age': 31, 'grades': [40, 30, 20]}]) == '[{\"name\": \"Heidi\", \"age\": 29, \"grades\": [100, 90, 80]}, {\"name\": \"Ivan\", \"age\": 30, \"grades\": [70, 60, 50]}, {\"name\": \"Judy\", \"age\": 31, \"grades\": [40, 30, 20]}]'", "assert dict_to_json_string([{'name': 'Kara', 'age': 32, 'grades': [99, 98, 97]}, {'name': 'Liam', 'age': 33, 'grades': [96, 95, 94]}, {'name': 'Mona', 'age': 34, 'grades': [93, 92, 91]}]) == '[{\"name\": \"Kara\", \"age\": 32, \"grades\": [99, 98, 97]}, {\"name\": \"Liam\", \"age\": 33, \"grades\": [96, 95, 94]}, {\"name\": \"Mona\", \"age\": 34, \"grades\": [93, 92, 91]}]'"], "function": "dict_to_json_string", "signature": "def dict_to_json_string(data):", "score": 1.0, "domain": "generic"} {"id": "592fdfdb694a9418ad0b33133b50ca0a", "problem": "You are given a list of `n` points in a 2D plane, where each point is represented as a tuple of two floating-point numbers indicating its x and y coordinates. Your task is to find and return the pair of points that have the smallest Euclidean distance between them. The output should be a tuple containing the two closest points. If there are multiple pairs with the same smallest distance, return any one of them.\n\n**Input:**\n- A list of tuples, where each tuple contains two floats representing the x and y coordinates of a point.\n- The list will contain at least two points.\n\n**Output:**\n- A tuple of two tuples, each representing a point with the smallest Euclidean distance between them.\n\n**Sample Input:**\n```python\n[(0, 0), (1, 1), (2, 2), (3, 3), (1, 2), (2, 1)]\n```\n\n**Sample Output:**\n```python\n((1, 1), (1, 2))\n```", "reference": "import math\n\ndef find_closest_pair(points):\n \"\"\"\n Finds and returns the pair of points with the smallest Euclidean distance between them.\n \n :param points: List of tuples, where each tuple contains two floats representing the x and y coordinates of a point.\n :return: A tuple of two tuples, each representing a point with the smallest Euclidean distance between them.\n \"\"\"\n def euclidean_distance(point1, point2):\n \"\"\"\n Calculates the Euclidean distance between two points in 2D space.\n \n :param point1: A tuple of two floats representing the x and y coordinates of the first point.\n :param point2: A tuple of two floats representing the x and y coordinates of the second point.\n :return: The Euclidean distance between point1 and point2.\n \"\"\"\n return math.sqrt((point1[0] - point2[0]) ** 2 + (point1[1] - point2[1]) ** 2)\n\n min_distance = float('inf')\n closest_pair = None\n \n for i in range(len(points)):\n for j in range(i + 1, len(points)):\n distance = euclidean_distance(points[i], points[j])\n if distance < min_distance:\n min_distance = distance\n closest_pair = (points[i], points[j])\n \n return closest_pair\n\n# Example usage:\npoints = [(0, 0), (1, 1), (2, 2), (3, 3), (1, 2), (2, 1)]\nprint(find_closest_pair(points))", "tests": ["assert find_closest_pair([(0, 0), (1, 1)]) == ((0, 0), (1, 1))", "assert find_closest_pair([(1, 1), (2, 2), (3, 3), (4, 4)]) == ((1, 1), (2, 2))", "assert find_closest_pair([(0, 0), (1, 1), (2, 2), (3, 3), (1, 2), (2, 1)]) in [((1, 1), (1, 2)), ((1, 1), (2, 1)), ((2, 2), (1, 2)), ((2, 2), (2, 1))]", "assert find_closest_pair([(0, 0), (0, 1), (1, 0), (1, 1)]) in [((0, 0), (0, 1)), ((0, 0), (1, 0)), ((0, 1), (1, 1)), ((1, 0), (1, 1))]", "assert find_closest_pair([(0, 0), (10, 10), (5, 5)]) == ((0, 0), (5, 5))", "assert find_closest_pair([(1, 2), (3, 4), (5, 6), (7, 8), (1.5, 2.5)]) == ((1, 2), (1.5, 2.5))", "assert find_closest_pair([(0, 0), (0, 0)]) == ((0, 0), (0, 0))", "assert find_closest_pair([(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6), (7, 7), (8, 8), (9, 9), (10, 10)]) == ((1, 1), (2, 2))", "assert find_closest_pair([(0, 0), (1, 0), (0, 1), (1, 1)]) in [((0, 0), (1, 0)), ((0, 0), (0, 1)), ((1, 0), (1, 1)), ((0, 1), (1, 1))]", "assert find_closest_pair([(1, 1), (1, 2), (2, 1), (2, 2)]) in [((1, 1), (1, 2)), ((1, 1), (2, 1)), ((1, 2), (2, 2)), ((2, 1), (2, 2))]"], "function": "find_closest_pair", "signature": "def find_closest_pair(points):", "score": 1.0, "domain": "generic"} {"id": "cc8b0f7301422c4d07f154055ce4bae8", "problem": "You are given a list of sentences, where each sentence is a string containing words separated by spaces. Your task is to construct a vocabulary from these sentences and generate two dictionaries: one for mapping words to unique indices and another for mapping indices back to words. The vocabulary should maintain the order of first appearance of each unique word across all sentences.\n\n**Input:**\n- A list of sentences, where each sentence is a string.\n\n**Output:**\n- A tuple containing:\n 1. A list of unique words in the order of their first appearance.\n 2. A dictionary mapping each word to a unique index.\n 3. A dictionary mapping each unique index back to the corresponding word.\n\n**Sample Input:**\n```python\n[\"hello world\", \"hello there\", \"world of code\"]\n```\n\n**Sample Output:**\n```python\n(['hello', 'world', 'there', 'of', 'code'], \n {'hello': 0, 'world': 1, 'there': 2, 'of': 3, 'code': 4}, \n {0: 'hello', 1: 'world', 2: 'there', 3: 'of', 4: 'code'})\n```", "reference": "def create_vocabulary_and_dictionaries(sentences):\n \"\"\"\n Constructs a vocabulary from a list of sentences and generates two dictionaries:\n one for mapping words to unique indices and another for mapping indices back to words.\n \n Parameters:\n sentences (list of str): A list of sentences, where each sentence is a string.\n \n Returns:\n tuple: A tuple containing:\n 1. A list of unique words in the order of their first appearance.\n 2. A dictionary mapping each word to a unique index.\n 3. A dictionary mapping each unique index back to the corresponding word.\n \"\"\"\n vocabulary = []\n word2idx = {}\n idx2word = {}\n\n for sentence in sentences:\n words = sentence.split()\n for word in words:\n if word not in vocabulary:\n vocabulary.append(word)\n current_index = len(vocabulary) - 1\n word2idx[word] = current_index\n idx2word[current_index] = word\n\n return vocabulary, word2idx, idx2word\n\n# Example usage:\nsentences = [\"hello world\", \"hello there\", \"world of code\"]\nvocabulary, word2idx, idx2word = create_vocabulary_and_dictionaries(sentences)\nprint(\"Vocabulary:\", vocabulary)\nprint(\"Word to Index:\", word2idx)\nprint(\"Index to Word:\", idx2word)", "tests": ["assert create_vocabulary_and_dictionaries([\"hello world\", \"hello there\", \"world of code\"]) == (['hello', 'world', 'there', 'of', 'code'], {'hello': 0, 'world': 1, 'there': 2, 'of': 3, 'code': 4}, {0: 'hello', 1: 'world', 2: 'there', 3: 'of', 4: 'code'})", "assert create_vocabulary_and_dictionaries([\"a b c\", \"c b a\"]) == (['a', 'b', 'c'], {'a': 0, 'b': 1, 'c': 2}, {0: 'a', 1: 'b', 2: 'c'})", "assert create_vocabulary_and_dictionaries([\"single\"]) == (['single'], {'single': 0}, {0: 'single'})", "assert create_vocabulary_and_dictionaries([]) == ([], {}, {})", "assert create_vocabulary_and_dictionaries([\"repeat repeat repeat\"]) == (['repeat'], {'repeat': 0}, {0: 'repeat'})", "assert create_vocabulary_and_dictionaries([\"one two\", \"three four\", \"five six\"]) == (['one', 'two', 'three', 'four', 'five', 'six'], {'one': 0, 'two': 1, 'three': 2, 'four': 3, 'five': 4, 'six': 5}, {0: 'one', 1: 'two', 2: 'three', 3: 'four', 4: 'five', 5: 'six'})", "assert create_vocabulary_and_dictionaries([\"punctuation, marks!\", \"should be\", \"handled correctly.\"]) == (['punctuation,', 'marks!', 'should', 'be', 'handled', 'correctly.'], {'punctuation,': 0, 'marks!': 1, 'should': 2, 'be': 3, 'handled': 4, 'correctly.': 5}, {0: 'punctuation,', 1: 'marks!', 2: 'should', 3: 'be', 4: 'handled', 5: 'correctly.'})", "assert create_vocabulary_and_dictionaries([\"numbers 123\", \"and symbols #@$\"]) == (['numbers', '123', 'and', 'symbols', '#@$',], {'numbers': 0, '123': 1, 'and': 2, 'symbols': 3, '#@$': 4}, {0: 'numbers', 1: '123', 2: 'and', 3: 'symbols', 4: '#@$'})", "assert create_vocabulary_and_dictionaries([\"case CASE\", \"Case\"]) == (['case', 'CASE', 'Case'], {'case': 0, 'CASE': 1, 'Case': 2}, {0: 'case', 1: 'CASE', 2: 'Case'})", "assert create_vocabulary_and_dictionaries([\"\"]) == ([], {}, {})"], "function": "create_vocabulary_and_dictionaries", "signature": "def create_vocabulary_and_dictionaries(sentences):", "score": 1.0, "domain": "generic"} {"id": "95ed63f5e3625de6595c77dce5828b44", "problem": "You are given a string `S` consisting of lowercase English letters. Your task is to generate all unique anagrams of the string `S`. The program should read the string `S` from the command line and output each unique anagram on a new line.\n\n**Input:**\n- The first argument to the program is the string `S` (1 ≤ |S| ≤ 8).\n\n**Output:**\n- Print each unique anagram of `S` on a new line.\n\n**Sample Input:**\n```\npython script.py abc\n```\n\n**Sample Output:**\n```\nabc\nacb\nbac\nbca\ncab\ncba\n```", "reference": "import sys\nfrom itertools import permutations\n\ndef generate_anagrams(word):\n \"\"\"\n Generate all unique anagrams of the given word.\n\n :param word: A string for which anagrams are to be generated.\n :return: A set containing all unique anagrams of the word.\n \"\"\"\n perm = permutations(word)\n anagrams = set([''.join(p) for p in perm])\n return anagrams\n\nif __name__ == \"__main__\":\n if len(sys.argv) != 2:\n print(\"Usage: python script.py \")\n sys.exit(1)\n \n word = sys.argv[1]\n anagrams = generate_anagrams(word)\n \n for anagram in anagrams:\n print(anagram)", "tests": ["assert generate_anagrams(\"abc\") == {\"abc\", \"acb\", \"bac\", \"bca\", \"cab\", \"cba\"}", "assert generate_anagrams(\"a\") == {\"a\"}", "assert generate_anagrams(\"aa\") == {\"aa\"}", "assert generate_anagrams(\"abcde\") == set([''.join(p) for p in permutations(\"abcde\")])", "assert generate_anagrams(\"xyz\") == {\"xyz\", \"xzy\", \"yxz\", \"yzx\", \"zxy\", \"zyx\"}", "assert generate_anagrams(\"noon\") == {\"noon\", \"onon\", \"noon\", \"onon\", \"nnoo\", \"nnoo\"}", "assert generate_anagrams(\"\") == {\"\"}", "assert generate_anagrams(\"aabb\") == {\"aabb\", \"abab\", \"abba\", \"baab\", \"baba\", \"bbaa\"}", "assert generate_anagrams(\"123\") == {\"123\", \"132\", \"213\", \"231\", \"312\", \"321\"}", "assert generate_anagrams(\"!@#\") == {\"!@#\", \"!#@\", \"@!#\", \"@#!\", \"#!@\", \"#@!\"}"], "function": "generate_anagrams", "signature": "def generate_anagrams(word):", "score": 1.0, "domain": "generic"} {"id": "68e37fe17734f377ef49beee6c332207", "problem": "You are tasked with implementing a function `find_prime_factors(n: int) -> List[int]` that computes all the prime factors of a given positive integer `n`. The function should not use any loops or built-in functions for iteration or factorization, except for list appending. Your solution should be recursive.\n\n**Constraints:**\n- 1 ≤ n ≤ 10^6\n\n**Sample Input:**\n```\n56\n```\n\n**Sample Output:**\n```\n[2, 2, 2, 7]\n```", "reference": "from typing import List\n\ndef find_prime_factors(n: int, divisor: int = 2, factors: List[int] = None) -> List[int]:\n \"\"\"\n Recursively finds all prime factors of a given positive integer n.\n \n :param n: The integer to factorize.\n :param divisor: The current divisor being tested.\n :param factors: A list to store the prime factors.\n :return: A list of prime factors of n.\n \"\"\"\n if factors is None:\n factors = []\n\n if n <= 1:\n return factors\n \n if n % divisor == 0:\n factors.append(divisor)\n return find_prime_factors(n // divisor, divisor, factors)\n else:\n return find_prime_factors(n, divisor + 1, factors)", "tests": ["assert find_prime_factors(2) == [2]", "assert find_prime_factors(3) == [3]", "assert find_prime_factors(4) == [2, 2]", "assert find_prime_factors(5) == [5]", "assert find_prime_factors(6) == [2, 3]", "assert find_prime_factors(7) == [7]", "assert find_prime_factors(8) == [2, 2, 2]", "assert find_prime_factors(9) == [3, 3]", "assert find_prime_factors(10) == [2, 5]", "assert find_prime_factors(100) == [2, 2, 5, 5]"], "function": "find_prime_factors", "signature": "def find_prime_factors(n: int, divisor: int = 2, factors: List[int] = None) -> List[int]:", "score": 1.0, "domain": "generic"} {"id": "d700161ce31d273c51ec1599e8389789", "problem": "You are tasked with implementing a simple calculator that evaluates arithmetic expressions consisting of integers and the operators `+`, `-`, `*`, and `/`. The input is a string `expression` that may contain spaces. Your program should parse and evaluate the expression according to the standard operator precedence rules and return the result as a floating-point number.\n\n**Input:**\n- A single string `expression` (1 ≤ len(expression) ≤ 100) containing integers, spaces, and the operators `+`, `-`, `*`, and `/`.\n\n**Output:**\n- A single floating-point number representing the evaluated result of the expression.\n\n**Sample Input:**\n```\n\" 3 + 5 * 2 - 8 / 4 \"\n```\n\n**Sample Output:**\n```\n10.0\n```", "reference": "def evaluate_expression(expression: str) -> float:\n \"\"\"\n Evaluates an arithmetic expression given as a string and returns the result as a float.\n \n :param expression: A string containing integers, spaces, and the operators '+', '-', '*', and '/'.\n :return: The evaluated result of the expression as a float.\n \"\"\"\n # Remove spaces from the expression\n expression = expression.replace(\" \", \"\")\n \n # Define operator precedence\n precedence = {'+': 1, '-': 1, '*': 2, '/': 2}\n \n # Output stack for numbers and operator stack\n output = []\n operators = []\n \n # Helper function to apply an operator to the top two numbers in the output stack\n def apply_operator(op: str) -> None:\n b = output.pop()\n a = output.pop()\n if op == '+':\n output.append(a + b)\n elif op == '-':\n output.append(a - b)\n elif op == '*':\n output.append(a * b)\n elif op == '/':\n output.append(a / b)\n \n # Convert the expression to a list of tokens (numbers and operators)\n tokens = []\n i = 0\n while i < len(expression):\n if expression[i].isdigit():\n j = i\n while j < len(expression) and expression[j].isdigit():\n j += 1\n tokens.append(int(expression[i:j]))\n i = j\n else:\n tokens.append(expression[i])\n i += 1\n \n # Process tokens using shunting-yard algorithm\n for token in tokens:\n if isinstance(token, int):\n output.append(token)\n elif token in precedence:\n while (operators and operators[-1] in precedence and\n precedence[operators[-1]] >= precedence[token]):\n apply_operator(operators.pop())\n operators.append(token)\n \n # Apply remaining operators\n while operators:\n apply_operator(operators.pop())\n \n # The final result is the only number left in the output stack\n return output[0]", "tests": ["assert evaluate_expression(\"3 + 5 * 2 - 8 / 4\") == 10.0", "assert evaluate_expression(\"10 + 2 * 6\") == 22.0", "assert evaluate_expression(\"100 * 2 + 12\") == 212.0", "assert evaluate_expression(\"100 * ( 2 + 12 )\") == 1400.0", "assert evaluate_expression(\"100 * ( 2 + 12 ) / 14\") == 100.0", "assert evaluate_expression(\"2 + 3 * 4 / 3 - 6 / 3 * 3 + 8\") == 8.0", "assert evaluate_expression(\"1 + 1\") == 2.0", "assert evaluate_expression(\"1 - 1\") == 0.0", "assert evaluate_expression(\"1 * 1\") == 1.0", "assert evaluate_expression(\"1 / 1\") == 1.0"], "function": "evaluate_expression", "signature": "def evaluate_expression(expression: str) -> float:", "score": 0.7, "domain": "generic"} {"id": "e0513038891d8012da898f67cbc17254", "problem": "In the school cafeteria, a special dish is added to the menu if a student is within a certain distance of a lunch period. The distance is defined by the function \\( D(t) = t^2 - 3t + 2 \\), where \\( t \\) is the time in hours since the start of the day. The special dish is available if \\( D(t) \\geq 0 \\). Given a time \\( t \\), determine if the special dish is available.\n\n**Input:**\n- A single integer \\( t \\) (0 ≤ t ≤ 24), representing the time in hours since the start of the day.\n\n**Output:**\n- Return `True` if the special dish is available, otherwise return `False`.\n\n**Sample Input:**\n- 3\n- 5\n\n**Sample Output:**\n- False\n- True", "reference": "def is_special_dish_available(t):\n \"\"\"\n Determines if the special dish is available at a given time t.\n \n Parameters:\n t (int): The time in hours since the start of the day.\n \n Returns:\n bool: True if the special dish is available, False otherwise.\n \"\"\"\n # Calculate the distance D(t) using the given formula\n D_t = t**2 - 3*t + 2\n \n # Check if D(t) is non-negative\n return D_t >= 0\n\n# Test cases\nprint(is_special_dish_available(3)) # Output: False\nprint(is_special_dish_available(5)) # Output: True", "tests": ["assert is_special_dish_available(0) == True", "assert is_special_dish_available(1) == True", "assert is_special_dish_available(2) == True", "assert is_special_dish_available(3) == False", "assert is_special_dish_available(4) == True", "assert is_special_dish_available(-1) == True", "assert is_special_dish_available(-2) == True", "assert is_special_dish_available(1.5) == False", "assert is_special_dish_available(2.5) == True", "assert is_special_dish_available(5.5) == True"], "function": "is_special_dish_available", "signature": "def is_special_dish_available(t):", "score": 0.9, "domain": "algorithmic"} {"id": "1f6955f929273202fc30138f236efd58", "problem": "You are given a dataset `data` which is a list of dictionaries, where each dictionary represents a row of data. Your task is to implement a function `generate_report(data, fields, output_format)` that constructs a report based on the specified `fields` and `output_format`. The `fields` parameter is a list of strings indicating which fields to include in the report. The `output_format` parameter can be either \"text\" or \"json\", determining the format of the output report. The function should return the report as a string.\n\n**Input:**\n- `data`: A list of dictionaries, where each dictionary contains key-value pairs representing data fields.\n- `fields`: A list of strings specifying which fields to include in the report.\n- `output_format`: A string that can be either \"text\" or \"json\".\n\n**Output:**\n- A string representing the report in the specified format.\n\n**Sample Input:**\n```python\ndata = [\n {\"name\": \"John Doe\", \"age\": 30, \"department\": \"Sales\"},\n {\"name\": \"Jane Smith\", \"age\": 25, \"department\": \"Marketing\"},\n {\"name\": \"Emily Johnson\", \"age\": 40, \"department\": \"Sales\"}\n]\nfields = [\"name\", \"department\"]\noutput_format = \"json\"\n```\n\n**Sample Output:**\n```json\n[\n {\n \"name\": \"John Doe\",\n \"department\": \"Sales\"\n },\n {\n \"name\": \"Jane Smith\",\n \"department\": \"Marketing\"\n },\n {\n \"name\": \"Emily Johnson\",\n \"department\": \"Sales\"\n }\n]\n```", "reference": "import json\n\ndef generate_report(data, fields, output_format):\n \"\"\"\n Generates a report from the given dataset based on specified fields and output format.\n\n Parameters:\n - data: List of dictionaries, where each dictionary represents a row of data.\n - fields: List of strings specifying which fields to include in the report.\n - output_format: String that can be either \"text\" or \"json\".\n\n Returns:\n - A string representing the report in the specified format.\n \"\"\"\n # Filter data to include only specified fields\n filtered_data = [{field: row[field] for field in fields} for row in data]\n \n if output_format == \"text\":\n # Generate a text report\n report = []\n for row in filtered_data:\n report.append(\", \".join(f\"{field}: {row[field]}\" for field in fields))\n return \"\\n\".join(report)\n elif output_format == \"json\":\n # Generate a JSON report\n return json.dumps(filtered_data, indent=4)\n else:\n raise ValueError(\"Unsupported output format\")", "tests": ["assert generate_report([{\"name\": \"John\", \"age\": 30}], [\"name\"], \"text\") == \"name: John\"", "assert generate_report([{\"name\": \"John\", \"age\": 30}, {\"name\": \"Jane\", \"age\": 25}], [\"name\"], \"text\") == \"name: John\\nname: Jane\"", "assert generate_report([{\"name\": \"John\", \"age\": 30}], [\"name\", \"age\"], \"text\") == \"name: John, age: 30\"", "assert generate_report([{\"name\": \"John\", \"age\": 30}], [\"name\"], \"json\") == '[\\n {\\n \"name\": \"John\"\\n }\\n]'", "assert generate_report([{\"name\": \"John\", \"age\": 30}, {\"name\": \"Jane\", \"age\": 25}], [\"name\"], \"json\") == '[\\n {\\n \"name\": \"John\"\\n },\\n {\\n \"name\": \"Jane\"\\n }\\n]'", "assert generate_report([{\"name\": \"John\", \"age\": 30}], [\"age\"], \"text\") == \"age: 30\"", "assert generate_report([], [\"name\"], \"text\") == \"\"", "assert generate_report([], [\"name\"], \"json\") == '[]'", "assert generate_report([{\"name\": \"John\", \"age\": 30}], [\"name\", \"department\"], \"text\") == \"name: John, department: None\"", "assert generate_report([{\"name\": \"John\", \"age\": 30}], [\"name\", \"department\"], \"json\") == '[\\n {\\n \"name\": \"John\",\\n \"department\": null\\n }\\n]'"], "function": "generate_report", "signature": "def generate_report(data, fields, output_format):", "score": 0.8, "domain": "generic"} {"id": "90953ce20562e4e9a0b7ff9113db6829", "problem": "You are given a positive integer `n`. Your task is to write a Python function `sum_of_squares(n)` that calculates the sum of the squares of the first `n` positive integers. Implement the function using list comprehension.\n\n**Input:**\n- A single integer `n` (1 ≤ n ≤ 10^4)\n\n**Output:**\n- An integer representing the sum of the squares of the first `n` positive integers.\n\n**Sample Input:**\n```\n5\n```\n\n**Sample Output:**\n```\n55\n```", "reference": "def sum_of_squares(n):\n \"\"\"\n Calculate the sum of the squares of the first n positive integers.\n\n Parameters:\n n (int): The number of terms to include in the sum of squares.\n\n Returns:\n int: The sum of the squares of the first n positive integers.\n \"\"\"\n return sum([i**2 for i in range(1, n+1)])", "tests": ["assert sum_of_squares(1) == 1", "assert sum_of_squares(2) == 5", "assert sum_of_squares(3) == 14", "assert sum_of_squares(4) == 30", "assert sum_of_squares(5) == 55", "assert sum_of_squares(10) == 385", "assert sum_of_squares(0) == 0", "assert sum_of_squares(-5) == 0", "assert sum_of_squares(100) == 338350", "assert sum_of_squares(1000) == 333833500"], "function": "sum_of_squares", "signature": "def sum_of_squares(n):", "score": 1.0, "domain": "generic"} {"id": "8f938c1b1181cf41dcf4da91a984bbd6", "problem": "You are tasked with implementing a function `convert_to_celsius` that accurately transforms a given temperature from Fahrenheit to Celsius. Your function should accept a single floating-point number representing the temperature in Fahrenheit and return the corresponding temperature in Celsius as a floating-point number. Ensure your function is well-documented with a docstring that clearly outlines its purpose, parameters, and return value.\n\n**Sample Input:**\n- `convert_to_celsius(32.0)`\n- `convert_to_celsius(212.0)`\n\n**Sample Output:**\n- `0.0`\n- `100.0`", "reference": "def convert_to_celsius(fahrenheit):\n \"\"\"\n Converts a temperature from Fahrenheit to Celsius.\n \n Parameters:\n fahrenheit (float): The temperature in Fahrenheit.\n \n Returns:\n float: The equivalent temperature in Celsius.\n \"\"\"\n celsius = (fahrenheit - 32) * 5.0 / 9.0\n return celsius", "tests": ["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(68) == 20.0", "assert convert_to_celsius(150) == 65.55555555555556", "assert convert_to_celsius(300) == 148.88888888888889", "assert convert_to_celsius(-100) == -73.33333333333333"], "function": "convert_to_celsius", "signature": "def convert_to_celsius(fahrenheit):", "score": 1.0, "domain": "generic"} {"id": "bb1a02ca02f1600ff232c0e363648fcc", "problem": "You are given a list of integers. Your task is to write a function `filter_positive_numbers` that processes this list and returns a new list containing only the positive integers from the original list. The function must utilize list comprehension for its implementation. \n\n**Input:**\n- A list of integers, `numbers`, where `-1000 <= numbers[i] <= 1000` and `0 <= len(numbers) <= 1000`.\n\n**Output:**\n- A list of integers containing only the positive numbers from the input list.\n\n**Sample Input:**\n```\n[-2, 3, -1, 5, 0, -7]\n```\n\n**Sample Output:**\n```\n[3, 5]\n```", "reference": "def filter_positive_numbers(numbers):\n \"\"\"\n Filters out positive numbers from a given list using list comprehension.\n\n :param numbers: List of integers.\n :return: A new list containing only the positive integers from the input list.\n \"\"\"\n return [num for num in numbers if num > 0]\n\n# Example usage:\nexample_list = [-2, 3, -1, 5, 0, -7]\nprint(filter_positive_numbers(example_list)) # Output will be [3, 5]", "tests": ["assert filter_positive_numbers([-2, 3, -1, 5, 0, -7]) == [3, 5]", "assert filter_positive_numbers([0, -1, -2, -3]) == []", "assert filter_positive_numbers([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]", "assert filter_positive_numbers([]) == []", "assert filter_positive_numbers([-10, -20, -30, 0]) == []", "assert filter_positive_numbers([10, 20, 30, 0]) == [10, 20, 30]", "assert filter_positive_numbers([0.1, -0.1, 0.2, -0.2]) == [0.1, 0.2]", "assert filter_positive_numbers([-5, 5, -10, 10, 0]) == [5, 10]", "assert filter_positive_numbers([100, 200, 300]) == [100, 200, 300]", "assert filter_positive_numbers([-1, -2, -3, 4, 5, 6]) == [4, 5, 6]"], "function": "filter_positive_numbers", "signature": "def filter_positive_numbers(numbers):", "score": 1.0, "domain": "generic"} {"id": "75074477958edef5fa28912daeeff77f", "problem": "You are given two inputs: a list of integers representing a set of numbers (`smaller_range`) and a tuple of two integers representing a range (`larger_range`). Your task is to determine if all numbers in the `smaller_range` are contained within the inclusive `larger_range`, regardless of the order or consecutiveness of the numbers in `smaller_range`. The ranges can include negative numbers.\n\n**Input:**\n- `smaller_range`: A list of integers.\n- `larger_range`: A tuple of two integers `(start, end)`.\n\n**Output:**\n- Return `True` if all numbers in `smaller_range` are within the inclusive `larger_range`, otherwise return `False`.\n\n**Sample Input and Output:**\n- Input: `smaller_range = [1, 2, 3, 4, 5]`, `larger_range = (1, 5)`\n - Output: `True`\n- Input: `smaller_range = [5, 3, 4, 2, 1]`, `larger_range = (1, 5)`\n - Output: `True`\n- Input: `smaller_range = [-3, -2, -1, 0, 1]`, `larger_range = (-3, 1)`\n - Output: `True`\n- Input: `smaller_range = [1, 3, 5]`, `larger_range = (2, 4)`\n - Output: `False`\n- Input: `smaller_range = [1, 2, 6]`, `larger_range = (1, 5)`\n - Output: `False`", "reference": "def is_range_within(smaller_range, larger_range):\n \"\"\"\n Determines if all numbers in the 'smaller_range' list are within the inclusive 'larger_range' tuple.\n \n Args:\n smaller_range (list): A list of integers representing the set of numbers.\n larger_range (tuple): A tuple (start, end) representing the inclusive range.\n \n Returns:\n bool: True if all numbers in 'smaller_range' are within 'larger_range', False otherwise.\n \"\"\"\n start, end = larger_range\n for num in smaller_range:\n if num < start or num > end:\n return False\n return True\n\n# Example checks\nprint(is_range_within([1, 2, 3, 4, 5], (1, 5))) # True\nprint(is_range_within([5, 3, 4, 2, 1], (1, 5))) # True\nprint(is_range_within([-3, -2, -1, 0, 1], (-3, 1))) # True\nprint(is_range_within([1, 3, 5], (2, 4))) # False\nprint(is_range_within([1, 2, 6], (1, 5))) # False", "tests": ["assert is_range_within([1, 2, 3], (1, 3)) == True", "assert is_range_within([3, 2, 1], (1, 3)) == True", "assert is_range_within([-1, 0, 1], (-1, 1)) == True", "assert is_range_within([0, 1, 2], (-1, 1)) == False", "assert is_range_within([5, 6, 7], (5, 7)) == True", "assert is_range_within([5, 7, 6], (5, 7)) == True", "assert is_range_within([10, 11, 12], (9, 12)) == True", "assert is_range_within([10, 12, 11], (9, 12)) == True", "assert is_range_within([1, 2, 3], (2, 3)) == False", "assert is_range_within([-5, -4, -3], (-5, -3)) == True"], "function": "is_range_within", "signature": "def is_range_within(smaller_range, larger_range):", "score": 1.0, "domain": "generic"} {"id": "f15bb46d21f4335930020bb48f8f491d", "problem": "You are given a sorted list of integers in ascending order and a target integer. Your task is to implement a function that performs a binary search to find the index of the target integer in the list. If the target integer is not present in the list, the function should return -1.\n\n**Input:**\n- The first argument to the function is a list of integers `sorted_list` (1 ≤ len(sorted_list) ≤ 10^4), which is sorted in ascending order.\n- The second argument is an integer `target` (-10^9 ≤ target ≤ 10^9).\n\n**Output:**\n- Return the index of the target integer in the list if it is present, otherwise return -1.\n\n**Sample Input:**\n- `sorted_list = [1, 2, 3, 4, 5]`\n- `target = 3`\n\n**Sample Output:**\n- `2`\n\n**Sample Input:**\n- `sorted_list = [1, 2, 4, 5]`\n- `target = 3`\n\n**Sample Output:**\n- `-1`", "reference": "def binary_search(sorted_list, target):\n \"\"\"\n Perform a binary search on a sorted list of integers and return the index of the target integer.\n If the target integer is not in the list, the function should return -1.\n \n :param sorted_list: List[int] - The list of integers to search\n :param target: int - The integer to find\n :return: int - The index of the target integer or -1 if not found\n \"\"\"\n left, right = 0, len(sorted_list) - 1\n \n while left <= right:\n mid = left + (right - left) // 2\n \n if sorted_list[mid] == target:\n return mid\n elif sorted_list[mid] < target:\n left = mid + 1\n else:\n right = mid - 1\n \n return -1", "tests": ["assert binary_search([1, 2, 3, 4, 5], 3) == 2", "assert binary_search([1, 2, 3, 4, 5], 6) == -1", "assert binary_search([], 1) == -1", "assert binary_search([1], 1) == 0", "assert binary_search([1, 3, 5, 7, 9], 7) == 3", "assert binary_search([1, 3, 5, 7, 9], 1) == 0", "assert binary_search([1, 3, 5, 7, 9], 9) == 4", "assert binary_search([1, 3, 5, 7, 9], 2) == -1", "assert binary_search([1, 3, 5, 7, 9], 10) == -1", "assert binary_search([-10, -5, 0, 5, 10], 0) == 2"], "function": "binary_search", "signature": "def binary_search(sorted_list, target):", "score": 1.0, "domain": "generic"} {"id": "7f9c82465e51f6577f9faf01976ae721", "problem": "You are given an array of integers `nums` and an integer `target`. Your task is to find the longest contiguous subarray within `nums` whose sum equals `target`. If there are multiple subarrays with the same maximum length, return the one that starts at the earliest index. If no such subarray exists, return an empty array.\n\n**Input:**\n- An array of integers `nums` (1 ≤ len(nums) ≤ 10^5), where each element is in the range [-10^4, 10^4].\n- An integer `target` (-10^9 ≤ target ≤ 10^9).\n\n**Output:**\n- Return the longest subarray whose sum is equal to `target`. If no such subarray exists, return an empty array.\n\n**Sample Input:**\n```\nnums = [1, -1, 5, -2, 3]\ntarget = 3\n```\n\n**Sample Output:**\n```\n[1, -1, 5, -2]\n```", "reference": "def find_longest_subarray_with_sum(nums, target):\n \"\"\"\n Finds the longest contiguous subarray within nums whose sum equals target.\n If multiple subarrays have the same maximum length, returns the one that starts at the earliest index.\n If no such subarray exists, returns an empty array.\n\n :param nums: List[int] - The array of integers.\n :param target: int - The target sum for the subarray.\n :return: List[int] - The longest subarray with sum equal to target, or an empty array if no such subarray exists.\n \"\"\"\n sum_index_map = {0: -1}\n current_sum = 0\n max_length = 0\n start_index = -1\n\n for i, num in enumerate(nums):\n current_sum += num\n\n if current_sum - target in sum_index_map:\n subarray_length = i - sum_index_map[current_sum - target]\n if subarray_length > max_length:\n max_length = subarray_length\n start_index = sum_index_map[current_sum - target] + 1\n\n if current_sum not in sum_index_map:\n sum_index_map[current_sum] = i\n\n if start_index == -1:\n return []\n\n return nums[start_index:start_index + max_length]", "tests": ["assert find_longest_subarray_with_sum([1, 2, 3, 7, 5], 12) == [2, 3, 7]", "assert find_longest_subarray_with_sum([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 15) == [1, 2, 3, 4, 5]", "assert find_longest_subarray_with_sum([1, 2, 3, 4, 5], 9) == [2, 3, 4]", "assert find_longest_subarray_with_sum([1, 2, 3, 4, 5], 10) == [1, 2, 3, 4]", "assert find_longest_subarray_with_sum([1, 2, 3, 4, 5], 15) == [1, 2, 3, 4, 5]", "assert find_longest_subarray_with_sum([1, 2, 3, 4, 5], 20) == []", "assert find_longest_subarray_with_sum([1, -1, 5, -2, 3], 3) == [1, -1, 5]", "assert find_longest_subarray_with_sum([0, 0, 0, 0, 0], 0) == [0, 0, 0, 0, 0]", "assert find_longest_subarray_with_sum([], 0) == []", "assert find_longest_subarray_with_sum([5, 6, -5, 5, 3, 5, 3, -2, 0], 8) == [5, 3, 5]"], "function": "find_longest_subarray_with_sum", "signature": "def find_longest_subarray_with_sum(nums, target):", "score": 0.8, "domain": "generic"} {"id": "b318944d3d5e34528aea3004ea5d2fb3", "problem": "You are given a list of `n` students, each represented as a dictionary with keys `'name'` and `'score'`. Your task is to sort the list of students based on their scores in descending order. If two students have the same score, sort them by their names in ascending order. Return the sorted list.\n\n**Input:**\n- A list of dictionaries, where each dictionary contains two keys: `'name'` (a string) and `'score'` (an integer).\n\n**Output:**\n- A list of dictionaries sorted according to the specified criteria.\n\n**Sample Input:**\n```python\n[\n {'name': 'John', 'score': 85},\n {'name': 'Jane', 'score': 92},\n {'name': 'Doe', 'score': 85},\n {'name': 'Alice', 'score': 92}\n]\n```\n\n**Sample Output:**\n```python\n[\n {'name': 'Alice', 'score': 92},\n {'name': 'Jane', 'score': 92},\n {'name': 'Doe', 'score': 85},\n {'name': 'John', 'score': 85}\n]\n```", "reference": "def sort_students(students):\n \"\"\"\n Sorts a list of student dictionaries by score in descending order.\n If two students have the same score, they are sorted by name in ascending order.\n\n :param students: List of dictionaries, each containing 'name' and 'score' keys.\n :return: Sorted list of dictionaries.\n \"\"\"\n return sorted(students, key=lambda student: (-student['score'], student['name']))\n\n# Example usage:\nstudents = [\n {'name': 'John', 'score': 85},\n {'name': 'Jane', 'score': 92},\n {'name': 'Doe', 'score': 85},\n {'name': 'Alice', 'score': 92}\n]\n\nsorted_students = sort_students(students)\nprint(sorted_students)", "tests": ["assert sort_students([{'name': 'John', 'score': 85}, {'name': 'Jane', 'score': 92}, {'name': 'Doe', 'score': 85}, {'name': 'Alice', 'score': 92}]) == [{'name': 'Alice', 'score': 92}, {'name': 'Jane', 'score': 92}, {'name': 'Doe', 'score': 85}, {'name': 'John', 'score': 85}]", "assert sort_students([{'name': 'Alice', 'score': 88}, {'name': 'Bob', 'score': 88}, {'name': 'Charlie', 'score': 88}]) == [{'name': 'Alice', 'score': 88}, {'name': 'Bob', 'score': 88}, {'name': 'Charlie', 'score': 88}]", "assert sort_students([{'name': 'Zoe', 'score': 100}, {'name': 'Adam', 'score': 100}, {'name': 'Yasmin', 'score': 100}]) == [{'name': 'Adam', 'score': 100}, {'name': 'Yasmin', 'score': 100}, {'name': 'Zoe', 'score': 100}]", "assert sort_students([{'name': 'Sam', 'score': 75}, {'name': 'Max', 'score': 85}, {'name': 'Leo', 'score': 75}]) == [{'name': 'Max', 'score': 85}, {'name': 'Leo', 'score': 75}, {'name': 'Sam', 'score': 75}]", "assert sort_students([{'name': 'Eve', 'score': 90}, {'name': 'Eve', 'score': 85}, {'name': 'Eve', 'score': 90}]) == [{'name': 'Eve', 'score': 90}, {'name': 'Eve', 'score': 90}, {'name': 'Eve', 'score': 85}]", "assert sort_students([{'name': 'Tom', 'score': 60}, {'name': 'Jerry', 'score': 60}, {'name': 'Spike', 'score': 60}]) == [{'name': 'Jerry', 'score': 60}, {'name': 'Spike', 'score': 60}, {'name': 'Tom', 'score': 60}]", "assert sort_students([{'name': 'Anna', 'score': 95}, {'name': 'Anna', 'score': 95}, {'name': 'Anna', 'score': 95}]) == [{'name': 'Anna', 'score': 95}, {'name': 'Anna', 'score': 95}, {'name': 'Anna', 'score': 95}]", "assert sort_students([{'name': 'Chris', 'score': 80}, {'name': 'Chris', 'score': 80}, {'name': 'Chris', 'score': 80}]) == [{'name': 'Chris', 'score': 80}, {'name': 'Chris', 'score': 80}, {'name': 'Chris', 'score': 80}]", "assert sort_students([{'name': 'Will', 'score': 70}, {'name': 'Will', 'score': 70}, {'name': 'Will', 'score': 70}]) == [{'name': 'Will', 'score': 70}, {'name': 'Will', 'score': 70}, {'name': 'Will', 'score': 70}]", "assert sort_students([]) == []"], "function": "sort_students", "signature": "def sort_students(students):", "score": 1.0, "domain": "generic"} {"id": "fec0753678fc21b3bbb7f07080471c42", "problem": "You are tasked with implementing a function to compute the factorial of a non-negative integer `n` using an iterative approach. Your function should handle the case where `n` is less than 0 by raising a `ValueError` with the message \"Factorial is not defined for negative numbers\". Your solution should be efficient and avoid the potential pitfalls of recursion, such as stack overflow for large values of `n`.\n\n**Input:**\n- A single integer `n` (0 ≤ n ≤ 20).\n\n**Output:**\n- The factorial of `n`.\n\n**Sample Input:**\n```\n5\n```\n\n**Sample Output:**\n```\n120\n```", "reference": "def factorial(n):\n \"\"\"\n Computes the factorial of a non-negative integer n using an iterative approach.\n \n Parameters:\n n (int): The non-negative integer for which the factorial is to be computed.\n \n Returns:\n int: The factorial of the integer n.\n \n Raises:\n ValueError: If n is a negative integer.\n \"\"\"\n if n < 0:\n raise ValueError(\"Factorial is not defined for negative numbers\")\n result = 1\n for i in range(2, n + 1):\n result *= i\n return result\n\n# Example usage:\nprint(factorial(5)) # Output: 120", "tests": ["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) == 2432902008176640000"], "function": "factorial", "signature": "def factorial(n):", "score": 1.0, "domain": "generic"} {"id": "1eb11412a370848d662eacfbf650a157", "problem": "You are given a string `s`. Your task is to find the longest substring without repeating characters. If there are multiple substrings of the same maximum length, return the first one encountered. \n\n**Input:**\n- A single string `s` (1 ≤ |s| ≤ 10^4), consisting of ASCII characters.\n\n**Output:**\n- A string representing the longest substring without repeating characters.\n\n**Sample Input 1:**\n```\nabcabcbb\n```\n**Sample Output 1:**\n```\nabc\n```\n\n**Sample Input 2:**\n```\nbbbbb\n```\n**Sample Output 2:**\n```\nb\n```\n\n**Sample Input 3:**\n```\npwwkew\n```\n**Sample Output 3:**\n```\nwke\n```", "reference": "def find_longest_substring(s):\n \"\"\"\n Finds the longest substring without repeating characters.\n\n :param s: The input string.\n :return: The longest substring without repeating characters.\n \"\"\"\n start = 0\n max_length = 0\n max_substring = \"\"\n char_index_map = {}\n\n for end, char in enumerate(s):\n if char in char_index_map and char_index_map[char] >= start:\n start = char_index_map[char] + 1\n current_length = end - start + 1\n if current_length > max_length:\n max_length = current_length\n max_substring = s[start:end+1]\n char_index_map[char] = end\n\n return max_substring\n\n# Testing the function\nprint(find_longest_substring(\"abcabcbb\")) # Expected output: \"abc\"\nprint(find_longest_substring(\"bbbbb\")) # Expected output: \"b\"\nprint(find_longest_substring(\"pwwkew\")) # Expected output: \"wke\"", "tests": ["assert find_longest_substring(\"abcabcbb\") == \"abc\"", "assert find_longest_substring(\"bbbbb\") == \"b\"", "assert find_longest_substring(\"pwwkew\") == \"wke\"", "assert find_longest_substring(\"dvdf\") == \"vdf\"", "assert find_longest_substring(\"anviaj\") == \"anviaj\"", "assert find_longest_substring(\"a\") == \"a\"", "assert find_longest_substring(\"\") == \"\"", "assert find_longest_substring(\"abcdef\") == \"abcdef\"", "assert find_longest_substring(\"abba\") == \"ab\"", "assert find_longest_substring(\"tmmzuxt\") == \"mzuxt\""], "function": "find_longest_substring", "signature": "def find_longest_substring(s):", "score": 0.9, "domain": "generic"} {"id": "13883f46d9b76a891e9fbdba3274565d", "problem": "You are tasked with processing a stream of data from various sources. Each data source is represented by a dictionary containing a `channel_url` key and several other keys, each associated with a list of alternating time and value data points. The time data points are in milliseconds, and the value data points are integers.\n\nImplement a function `process_data_stream(raw_data, allowed_channels=None)` that processes this stream of data. The function should take an iterable `raw_data` and an optional list `allowed_channels`. If `allowed_channels` is provided, only data from the specified channels should be processed. If `allowed_channels` is `None`, all channels should be processed.\n\nThe function should yield tuples of the form `(key, time_in_seconds, value)` for each data point, where `time_in_seconds` is the time in seconds.\n\nAdditionally, implement a function `collect_final_data(data_stream)` that takes the generator produced by `process_data_stream` and returns a dictionary. The keys of this dictionary should be the unique keys from the data (excluding `channel_url`), and the values should be lists of tuples `(time_in_seconds, value)`, sorted by `time_in_seconds`.\n\n**Sample Input:**\n```python\ndata_chunks = [\n {'channel_url': 'http://a.com', 'Temperature': [0, 22, 1000, 23], 'Humidity': [0, 40, 1000, 38]},\n {'channel_url': 'http://b.com', 'Temperature': [0, 18, 1000, 20], 'Humidity': [0, 42, 1000, 54]},\n {'channel_url': 'http://a.com', 'Temperature': [2000, 21, 3000, 24], 'Humidity': [2000, 39, 3000, 38]},\n {'channel_url': 'http://b.com', 'Temperature': [2000, 19, 3000, 19], 'Humidity': [2000, 53, 3000, 52]},\n]\n```\n\n**Sample Output:**\n```python\n{\n 'Temperature': [(0.0, 22), (0.0, 18), (1.0, 23), (1.0, 20), (2.0, 21), (2.0, 19), (3.0, 24), (3.0, 19)],\n 'Humidity': [(0.0, 40), (0.0, 42), (1.0, 38), (1.0, 54), (2.0, 39), (2.0, 53), (3.0, 38), (3.0, 52)]\n}\n```", "reference": "def process_data_stream(raw_data, allowed_channels=None):\n \"\"\"\n Generator function to process incoming data streams.\n Yields a tuple containing a key, time in seconds, and a value for each data point.\n \n :param raw_data: Stream of data dictionaries\n :param allowed_channels: List of allowed channel URLs\n :yield: Tuple (key, time_in_seconds, value)\n \"\"\"\n for data in raw_data:\n channel_url = data['channel_url']\n if allowed_channels is not None and channel_url not in allowed_channels:\n continue\n for key, values in data.items():\n if key == 'channel_url':\n continue\n for i in range(0, len(values), 2):\n time_ms = values[i]\n value = values[i + 1]\n time_seconds = time_ms / 1000.0\n yield (key, time_seconds, value)\n\ndef collect_final_data(data_stream):\n \"\"\"\n Collects the processed data into the final dictionary structure.\n \n :param data_stream: Generator from process_data_stream\n :return: Dictionary with keys being data point categories and values being sorted list of (time, value) tuples\n \"\"\"\n from collections import defaultdict\n\n result = defaultdict(list)\n \n for key, time_seconds, value in data_stream:\n result[key].append((time_seconds, value))\n \n for key in result:\n result[key].sort(key=lambda x: x[0])\n \n return dict(result)", "tests": ["assert collect_final_data(process_data_stream([{'channel_url': 'http://a.com', 'Temperature': [0, 22, 1000, 23]}])) == {'Temperature': [(0.0, 22), (1.0, 23)]}", "assert collect_final_data(process_data_stream([{'channel_url': 'http://a.com', 'Humidity': [0, 40, 1000, 38]}])) == {'Humidity': [(0.0, 40), (1.0, 38)]}", "assert collect_final_data(process_data_stream([{'channel_url': 'http://a.com', 'Temperature': [0, 22, 1000, 23]}, {'channel_url': 'http://a.com', 'Temperature': [2000, 21, 3000, 24]}])) == {'Temperature': [(0.0, 22), (1.0, 23), (2.0, 21), (3.0, 24)]}", "assert collect_final_data(process_data_stream([{'channel_url': 'http://a.com', 'Humidity': [0, 40, 1000, 38]}, {'channel_url': 'http://a.com', 'Humidity': [2000, 39, 3000, 38]}])) == {'Humidity': [(0.0, 40), (1.0, 38), (2.0, 39), (3.0, 38)]}", "assert collect_final_data(process_data_stream([{'channel_url': 'http://a.com', 'Temperature': [0, 22, 1000, 23]}, {'channel_url': 'http://b.com', 'Temperature': [0, 18, 1000, 20]}], allowed_channels=['http://a.com'])) == {'Temperature': [(0.0, 22), (1.0, 23)]}", "assert collect_final_data(process_data_stream([{'channel_url': 'http://a.com', 'Humidity': [0, 40, 1000, 38]}, {'channel_url': 'http://b.com', 'Humidity': [0, 42, 1000, 54]}], allowed_channels=['http://b.com'])) == {'Humidity': [(0.0, 42), (1.0, 54)]}", "assert collect_final_data(process_data_stream([{'channel_url': 'http://a.com', 'Temperature': [0, 22, 1000, 23]}, {'channel_url': 'http://b.com', 'Temperature': [0, 18, 1000, 20]}], allowed_channels=['http://a.com', 'http://b.com'])) == {'Temperature': [(0.0, 22), (0.0, 18), (1.0, 23), (1.0, 20)]}", "assert collect_final_data(process_data_stream([{'channel_url': 'http://a.com', 'Humidity': [0, 40, 1000, 38]}, {'channel_url': 'http://b.com', 'Humidity': [0, 42, 1000, 54]}], allowed_channels=['http://a.com', 'http://b.com'])) == {'Humidity': [(0.0, 40), (0.0, 42), (1.0, 38), (1.0, 54)]}", "assert collect_final_data(process_data_stream([{'channel_url': 'http://a.com', 'Temperature': [0, 22, 1000, 23]}, {'channel_url': 'http://b.com', 'Temperature': [0, 18, 1000, 20]}], allowed_channels=[])) == {}", "assert collect_final_data(process_data_stream([{'channel_url': 'http://a.com', 'Humidity': [0, 40, 1000, 38]}, {'channel_url': 'http://b.com', 'Humidity': [0, 42, 1000, 54]}], allowed_channels=[])) == {}"], "function": "collect_final_data", "signature": "def collect_final_data(data_stream):", "score": 1.0, "domain": "generic"} {"id": "e38768ec5baf6b8a599bc584b70b6a29", "problem": "You are given a function `max_of_three(a, b, c)` that accepts three integers as input. Your task is to determine the largest of the three integers, provided none of the integers are palindromic. A number is considered palindromic if it reads the same backward as forward. If any of the integers are palindromic, the function should return `None`. \n\n**Constraints:**\n- The integers can be positive, negative, or zero.\n\n**Sample Input and Output:**\n- Input: `123, 456, 789`\n - Output: `789`\n- Input: `121, 456, 789`\n - Output: `None`\n- Input: `-121, 456, 789`\n - Output: `789`\n- Input: `0, 456, 789`\n - Output: `789`", "reference": "def max_of_three(a, b, c):\n \"\"\"\n Returns the largest of three integers if none of them are palindromic.\n Returns None if any of the integers are palindromic.\n \n :param a: First integer\n :param b: Second integer\n :param c: Third integer\n :return: The largest integer or None if any integer is palindromic\n \"\"\"\n def is_palindromic(n):\n s = str(n)\n return s == s[::-1]\n \n if is_palindromic(a) or is_palindromic(b) or is_palindromic(c):\n return None\n \n return max(a, b, c)", "tests": ["assert max_of_three(123, 456, 789) == 789", "assert max_of_three(121, 456, 789) == None", "assert max_of_three(-121, 456, 789) == 789", "assert max_of_three(0, 456, 789) == 789", "assert max_of_three(123, 321, 213) == 321", "assert max_of_three(111, 222, 333) == None", "assert max_of_three(-1, -2, -3) == -1", "assert max_of_three(10, 100, 1000) == 1000", "assert max_of_three(987, 876, 765) == 987", "assert max_of_three(0, 0, 0) == None"], "function": "max_of_three", "signature": "def max_of_three(a, b, c):", "score": 0.9, "domain": "generic"} {"id": "5e6842f6359376e7f192de452b6a4399", "problem": "You are given two positive integers `n` and `limit`. Your task is to write a function `sum_of_multiples(n, limit)` that computes the sum of all positive integers less than `limit` that are multiples of `n`.\n\n**Input:**\n- The function takes two integers `n` and `limit` as input.\n- `1 <= n < limit <= 10^6`\n\n**Output:**\n- Return a single integer representing the sum of all positive integers less than `limit` that are multiples of `n`.\n\n**Sample Input:**\n- `n = 3`, `limit = 10`\n\n**Sample Output:**\n- `18`", "reference": "def sum_of_multiples(n, limit):\n \"\"\"\n Computes the sum of all positive integers less than `limit` that are multiples of `n`.\n\n Parameters:\n n (int): The base multiple.\n limit (int): The upper limit (exclusive).\n\n Returns:\n int: The sum of all multiples of `n` less than `limit`.\n \"\"\"\n return sum(i for i in range(n, limit, n))\n\n# Test the function\nprint(sum_of_multiples(3, 10)) # Expected output: 18", "tests": ["assert sum_of_multiples(3, 10) == 18", "assert sum_of_multiples(5, 20) == 50", "assert sum_of_multiples(7, 50) == 196", "assert sum_of_multiples(1, 10) == 45", "assert sum_of_multiples(10, 100) == 450", "assert sum_of_multiples(2, 1) == 0", "assert sum_of_multiples(0, 10) == 0", "assert sum_of_multiples(4, 4) == 0", "assert sum_of_multiples(6, 30) == 78", "assert sum_of_multiples(15, 15) == 0"], "function": "sum_of_multiples", "signature": "def sum_of_multiples(n, limit):", "score": 0.7, "domain": "generic"} {"id": "3fed534cb332074abb1f47041cbcc02e", "problem": "You are given a file path and a subdirectory name. Your task is to write a function `insert_subdirectory` that inserts the subdirectory into the file path right before the file name. If the file path does not contain any directory, the function should return the original file path with the subdirectory appended at the beginning. The function should handle special characters such as `~` for home directories, `.` for the current directory, and `..` for the parent directory.\n\n**Input:**\n- The function takes two arguments: `file_path` (a string representing the file path) and `subdirectory_name` (a string representing the subdirectory name).\n\n**Output:**\n- The function should return a string representing the modified file path with the subdirectory inserted appropriately.\n\n**Sample Inputs and Outputs:**\n- `insert_subdirectory('/root/existing_directory/file.ext', 'new_directory')` should return `'/root/existing_directory/new_directory/file.ext'`.\n- `insert_subdirectory('file.ext', 'new_directory')` should return `'new_directory/file.ext'`.\n- `insert_subdirectory('~/documents/report.docx', 'drafts')` should return `'~/documents/drafts/report.docx'`.\n- `insert_subdirectory('../data.csv', 'backup')` should return `'../backup/data.csv'`.", "reference": "import os\n\ndef insert_subdirectory(file_path, subdirectory_name):\n \"\"\"\n Inserts a subdirectory into the file path right before the file name.\n If the file path does not contain any directory, appends the subdirectory at the beginning.\n \n :param file_path: str, the original file path\n :param subdirectory_name: str, the subdirectory name to be inserted\n :return: str, the modified file path with the subdirectory inserted\n \"\"\"\n norm_path = os.path.normpath(file_path)\n head, tail = os.path.split(norm_path)\n\n if head == '':\n return os.path.join(subdirectory_name, tail)\n return os.path.join(head, subdirectory_name, tail)", "tests": ["assert insert_subdirectory('/root/existing_directory/file.ext', 'new_directory') == '/root/existing_directory/new_directory/file.ext'", "assert insert_subdirectory('file.ext', 'new_directory') == 'new_directory/file.ext'", "assert insert_subdirectory('/root/file.ext', 'new_directory') == '/root/new_directory/file.ext'", "assert insert_subdirectory('~/file.ext', 'new_directory') == '~/new_directory/file.ext'", "assert insert_subdirectory('/root/existing_directory/', 'new_directory') == '/root/existing_directory/new_directory'", "assert insert_subdirectory('/root/existing_directory/another_directory/file.ext', 'new_directory') == '/root/existing_directory/another_directory/new_directory/file.ext'", "assert insert_subdirectory('..', 'new_directory') == '../new_directory'", "assert insert_subdirectory('.', 'new_directory') == './new_directory'", "assert insert_subdirectory('/root/existing_directory/file.ext', '') == '/root/existing_directory/file.ext'", "assert insert_subdirectory('file.ext', '') == 'file.ext'"], "function": "insert_subdirectory", "signature": "def insert_subdirectory(file_path, subdirectory_name):", "score": 0.7, "domain": "generic"} {"id": "b64182dc1e914bfe3be3b350c85f6e7c", "problem": "You are tasked with implementing a function to find the `n`-th prime number. The function should efficiently determine the prime number at the specified position in the sequence of prime numbers. \n\n**Input:**\n- An integer `n` (1 ≤ n ≤ 10^4), representing the position of the prime number you need to find.\n\n**Output:**\n- Return the `n`-th prime number.\n\n**Sample Input:**\n```\n1\n2\n3\n4\n```\n\n**Sample Output:**\n```\n2\n3\n5\n7\n```", "reference": "def get_nth_prime(n):\n \"\"\"\n Returns the n-th prime number.\n \n Parameters:\n n (int): The position of the prime number to find (1 ≤ n ≤ 10^4).\n \n Returns:\n int: The n-th prime number.\n \"\"\"\n def is_prime(num):\n if num <= 1:\n return False\n elif num <= 3:\n return True\n elif num % 2 == 0 or num % 3 == 0:\n return False\n i = 5\n while i * i <= num:\n if num % i == 0 or num % (i + 2) == 0:\n return False\n i += 6\n return True\n \n count = 0\n candidate = 1\n while count < n:\n candidate += 1\n if is_prime(candidate):\n count += 1\n return candidate", "tests": ["assert get_nth_prime(1) == 2", "assert get_nth_prime(2) == 3", "assert get_nth_prime(3) == 5", "assert get_nth_prime(4) == 7", "assert get_nth_prime(5) == 11", "assert get_nth_prime(6) == 13", "assert get_nth_prime(10) == 29", "assert get_nth_prime(20) == 71", "assert get_nth_prime(50) == 229", "assert get_nth_prime(100) == 541"], "function": "get_nth_prime", "signature": "def get_nth_prime(n):", "score": 1.0, "domain": "generic"} {"id": "c6c602290d9c2a2ff74cb51bcddfe953", "problem": "You are given an array of integers `arr` and an integer `K`. Your task is to write a function that counts the number of elements in `arr` that are divisible by `K`.\n\n**Input:**\n- The first line contains an integer `n` (1 ≤ n ≤ 10^3), the number of elements in the array.\n- The second line contains `n` space-separated integers representing the array `arr` (-10^6 ≤ arr[i] ≤ 10^6).\n- The third line contains an integer `K` (1 ≤ K ≤ 10^6).\n\n**Output:**\n- Print a single integer, the count of elements in `arr` that are divisible by `K`.\n\n**Sample Input:**\n```\n5\n10 15 20 25 30\n5\n```\n\n**Sample Output:**\n```\n5\n```", "reference": "def count_divisible_elements(arr, k):\n \"\"\"\n Counts the number of elements in the array that are divisible by k.\n\n Parameters:\n arr (list of int): The array of integers.\n k (int): The divisor.\n\n Returns:\n int: The count of elements divisible by k.\n \"\"\"\n count = 0\n for num in arr:\n if num % k == 0:\n count += 1\n return count\n\n# test the function\narr1 = [10, 15, 20, 25, 30]\nk1 = 5\nprint(count_divisible_elements(arr1, k1)) # Output: 5\n\narr2 = [11, 22, 33, 44, 55]\nk2 = 11\nprint(count_divisible_elements(arr2, k2)) # Output: 5", "tests": ["assert count_divisible_elements([10, 15, 20, 25, 30], 5) == 5", "assert count_divisible_elements([11, 22, 33, 44, 55], 11) == 5", "assert count_divisible_elements([1, 2, 3, 4, 5], 2) == 2", "assert count_divisible_elements([0, 0, 0, 0], 1) == 4", "assert count_divisible_elements([1, 3, 5, 7], 2) == 0", "assert count_divisible_elements([], 3) == 0", "assert count_divisible_elements([12, 24, 35, 46, 57], 12) == 2", "assert count_divisible_elements([100, 200, 300, 400], 100) == 4", "assert count_divisible_elements([10, 20, 30, 40, 50], 3) == 0", "assert count_divisible_elements([-10, -20, -30, -40, -50], 10) == 5"], "function": "count_divisible_elements", "signature": "def count_divisible_elements(arr, k):", "score": 0.9, "domain": "algorithmic"} {"id": "4a410eed8335110c5aa18261dc3b1bcc", "problem": "You are tasked with implementing a function `validate_email(email)` that determines if a given string `email` is a valid email address. A valid email address must adhere to the following rules:\n- It consists of a local part and a domain separated by an `@` symbol.\n- The local part and domain can only contain alphanumeric characters, dots (`.`), underscores (`_`), and hyphens (`-`).\n- The domain must contain at least one dot, and the top-level domain (TLD) must be at least two characters long.\n\nYour function should return `True` if the email is valid, and `False` otherwise.\n\n**Sample Input:**\n```\nvalidate_email(\"example@test.com\")\nvalidate_email(\"user.name@domain.co.uk\")\nvalidate_email(\"invalid-email@domain\")\nvalidate_email(\"another.invalid@domain.c\")\n```\n\n**Sample Output:**\n```\nTrue\nTrue\nFalse\nFalse\n```", "reference": "import re\n\ndef validate_email(email):\n \"\"\"\n Validates if the given email string is a valid email address.\n\n Parameters:\n email (str): The email address to validate.\n\n Returns:\n bool: True if the email is valid, False otherwise.\n \"\"\"\n pattern = re.compile(\n r'^[a-zA-Z0-9._-]+' # Local part: alphanumeric, dots, underscores, hyphens\n r'@' # @ symbol\n r'[a-zA-Z0-9.-]+' # Domain: alphanumeric, dots, hyphens\n r'\\.' # At least one dot before the TLD\n r'[a-zA-Z]{2,}$' # Top-level domain: at least two characters long\n )\n return pattern.fullmatch(email) is not None", "tests": ["assert validate_email(\"test@example.com\") == True", "assert validate_email(\"user.name@domain.co\") == True", "assert validate_email(\"user_name@sub.domain.com\") == True", "assert validate_email(\"user-name@domain.co.uk\") == True", "assert validate_email(\"user@domain.c\") == False", "assert validate_email(\"user@domaincom\") == False", "assert validate_email(\"user@.com\") == False", "assert validate_email(\"@domain.com\") == False", "assert validate_email(\"user@domain..com\") == False", "assert validate_email(\"user@domain.c0m\") == True"], "function": "validate_email", "signature": "def validate_email(email):", "score": 0.8, "domain": "generic"} {"id": "47035361e43af2a956ca562f362f17ff", "problem": "In a game, players can collect various items, each with unique effects. You are tasked with implementing a function to retrieve the effects of a specific item based on its name. Given a list of items where each item is represented as a dictionary with keys \"name\" and \"effects\", write a function `get_item_effects(item_name, items)` that returns the effects of the item with the specified `item_name`. If the item does not exist in the list, return an empty dictionary.\n\n**Input:**\n- `item_name`: A string representing the name of the item.\n- `items`: A list of dictionaries, where each dictionary contains:\n - `\"name\"`: A string representing the name of the item.\n - `\"effects\"`: A dictionary representing the effects of the item.\n\n**Output:**\n- A dictionary containing the effects of the specified item, or an empty dictionary if the item is not found.\n\n**Sample Input:**\n```python\nitem_name = \"Potion\"\nitems = [\n {\"name\": \"Potion\", \"effects\": {\"heal\": 50}},\n {\"name\": \"Sword\", \"effects\": {\"damage\": 20}},\n {\"name\": \"Shield\", \"effects\": {\"defense\": 10}}\n]\n```\n\n**Sample Output:**\n```python\n{'heal': 50}\n```", "reference": "def get_item_effects(item_name, items):\n \"\"\"\n Returns the effects of the item with the given name.\n \n Parameters:\n - item_name (str): The name of the item.\n - items (list of dict): A list of items, each represented as a dictionary with 'name' and 'effects' keys.\n \n Returns:\n - dict: The effects of the item if found, otherwise an empty dictionary.\n \"\"\"\n for item in items:\n if item[\"name\"] == item_name:\n return item[\"effects\"]\n return {}", "tests": ["assert get_item_effects(\"Potion\", items) == {\"heal\": 50}", "assert get_item_effects(\"Sword\", items) == {\"damage\": 20}", "assert get_item_effects(\"Shield\", items) == {\"defense\": 10}", "assert get_item_effects(\"Bow\", items) == {}", "assert get_item_effects(\"\", items) == {}", "assert get_item_effects(\"Potion\", []) == {}", "assert get_item_effects(\"Sword\", [{\"name\": \"Sword\", \"effects\": {\"damage\": 30}}]) == {\"damage\": 30}", "assert get_item_effects(\"Shield\", [{\"name\": \"Potion\", \"effects\": {\"heal\": 50}}]) == {}", "assert get_item_effects(\"Armor\", [{\"name\": \"Armor\", \"effects\": {\"defense\": 15}}, {\"name\": \"Boots\", \"effects\": {\"speed\": 5}}]) == {\"defense\": 15}", "assert get_item_effects(\"Ring\", [{\"name\": \"Ring\", \"effects\": {\"luck\": 2}}]) == {\"luck\": 2}"], "function": "get_item_effects", "signature": "def get_item_effects(item_name, items):", "score": 0.5, "domain": "generic"} {"id": "9142510da8e833e16d597500fcc949ea", "problem": "You are given a binary tree defined by the `TreeNode` class. Your task is to implement a function `find_max_depth(tree)` that calculates the maximum depth of the tree. The depth of a binary tree is the number of nodes along the longest path from the root node down to the farthest leaf node. If the tree is empty (i.e., the root is `None`), the function should return 0.\n\n**TreeNode Class Definition:**\n```python\nclass TreeNode:\n def __init__(self, value=0, left=None, right=None):\n self.value = value\n self.left = left\n self.right = right\n```\n\n**Input:**\n- The function takes a single argument `tree`, which is an instance of `TreeNode` representing the root of the binary tree.\n\n**Output:**\n- The function should return an integer representing the maximum depth of the binary tree.\n\n**Sample Input:**\n```python\n# Constructing the following binary tree:\n# 1\n# / \\\n# 2 3\n# / \\\n# 4 5\nroot = TreeNode(1)\nroot.left = TreeNode(2)\nroot.right = TreeNode(3)\nroot.left.left = TreeNode(4)\nroot.left.right = TreeNode(5)\n```\n\n**Sample Output:**\n```\n3\n```", "reference": "class TreeNode:\n def __init__(self, value=0, left=None, right=None):\n self.value = value\n self.left = left\n self.right = right\n\ndef find_max_depth(tree):\n \"\"\"\n Calculate the maximum depth of a binary tree.\n\n :param tree: TreeNode, the root of the binary tree.\n :return: int, the maximum depth of the tree.\n \"\"\"\n if tree is None:\n return 0\n else:\n left_depth = find_max_depth(tree.left)\n right_depth = find_max_depth(tree.right)\n return max(left_depth, right_depth) + 1", "tests": ["assert find_max_depth(None) == 0", "assert find_max_depth(TreeNode(1)) == 1", "assert find_max_depth(TreeNode(1, TreeNode(2))) == 2", "assert find_max_depth(TreeNode(1, None, TreeNode(3))) == 2", "assert find_max_depth(TreeNode(1, TreeNode(2), TreeNode(3))) == 2", "assert find_max_depth(TreeNode(1, TreeNode(2, TreeNode(4)), TreeNode(3))) == 3", "assert find_max_depth(TreeNode(1, TreeNode(2, TreeNode(4, TreeNode(8))), TreeNode(3, TreeNode(5, None, TreeNode(7))))) == 4", "assert find_max_depth(TreeNode(1, TreeNode(2, TreeNode(4, TreeNode(8, TreeNode(16)))), TreeNode(3, TreeNode(5, None, TreeNode(7, TreeNode(14)))))) == 5", "assert find_max_depth(TreeNode(1, TreeNode(2, TreeNode(4, TreeNode(8, TreeNode(16, TreeNode(32))))), TreeNode(3, TreeNode(5, None, TreeNode(7, TreeNode(14, TreeNode(28))))))) == 6", "assert find_max_depth(TreeNode(1, TreeNode(2, TreeNode(4, TreeNode(8, TreeNode(16, TreeNode(32, TreeNode(64))))), TreeNode(5, TreeNode(10, TreeNode(20, TreeNode(40))))), TreeNode(3, TreeNode(6, TreeNode(12, TreeNode(24, TreeNode(48)))), TreeNode(7, TreeNode(14, TreeNode(28, TreeNode(56))))))) == 7"], "function": "find_max_depth", "signature": "def find_max_depth(tree):", "score": 1.0, "domain": "generic"} {"id": "63681feab90f459b17a7c6c319f78390", "problem": "You are given a string `s`. Your task is to implement a function `count_vowels` that returns a dictionary containing the count of each vowel ('a', 'e', 'i', 'o', 'u') in the string. The function should be case-insensitive, meaning it should count both uppercase and lowercase vowels. \n\n**Input:**\n- A single string `s` (1 ≤ |s| ≤ 10^5), consisting of alphabetic characters and possibly spaces.\n\n**Output:**\n- A dictionary with keys 'a', 'e', 'i', 'o', 'u' and their respective counts in the string.\n\n**Sample Input 1:**\n```\n\"Hello World\"\n```\n**Sample Output 1:**\n```\n{\"a\": 0, \"e\": 1, \"i\": 0, \"o\": 2, \"u\": 0}\n```\n\n**Sample Input 2:**\n```\n\"Python Programming\"\n```\n**Sample Output 2:**\n```\n{\"a\": 0, \"e\": 0, \"i\": 1, \"o\": 2, \"u\": 2}\n```\n\n**Sample Input 3:**\n```\n\"AEIOU\"\n```\n**Sample Output 3:**\n```\n{\"a\": 1, \"e\": 1, \"i\": 1, \"o\": 1, \"u\": 1}\n```", "reference": "def count_vowels(s):\n \"\"\"\n Counts the occurrences of each vowel in a given string, ignoring case.\n\n Parameters:\n s (str): The input string.\n\n Returns:\n dict: A dictionary with keys 'a', 'e', 'i', 'o', 'u' and their respective counts.\n \"\"\"\n vowels_count = {\"a\": 0, \"e\": 0, \"i\": 0, \"o\": 0, \"u\": 0}\n s = s.lower()\n for char in s:\n if char in vowels_count:\n vowels_count[char] += 1\n return vowels_count", "tests": ["assert count_vowels(\"Hello World\") == {\"a\": 0, \"e\": 1, \"i\": 0, \"o\": 2, \"u\": 0}", "assert count_vowels(\"Python Programming\") == {\"a\": 0, \"e\": 0, \"i\": 1, \"o\": 2, \"u\": 2}", "assert count_vowels(\"AEIOU\") == {\"a\": 1, \"e\": 1, \"i\": 1, \"o\": 1, \"u\": 1}", "assert count_vowels(\"aeiou\") == {\"a\": 1, \"e\": 1, \"i\": 1, \"o\": 1, \"u\": 1}", "assert count_vowels(\"bcd\") == {\"a\": 0, \"e\": 0, \"i\": 0, \"o\": 0, \"u\": 0}", "assert count_vowels(\"\") == {\"a\": 0, \"e\": 0, \"i\": 0, \"o\": 0, \"u\": 0}", "assert count_vowels(\"A quick brown fox jumps over the lazy dog\") == {\"a\": 1, \"e\": 3, \"i\": 1, \"o\": 4, \"u\": 2}", "assert count_vowels(\"1234567890\") == {\"a\": 0, \"e\": 0, \"i\": 0, \"o\": 0, \"u\": 0}", "assert count_vowels(\"!@#$%^&*()\") == {\"a\": 0, \"e\": 0, \"i\": 0, \"o\": 0, \"u\": 0}", "assert count_vowels(\"Umbrella\") == {\"a\": 0, \"e\": 1, \"i\": 0, \"o\": 0, \"u\": 2}"], "function": "count_vowels", "signature": "def count_vowels(s):", "score": 0.7, "domain": "generic"} {"id": "fefddda2ac322b28bf1218ca9cc1a6d0", "problem": "You are given a nested list of integers. Your task is to write a function `flatten_list` that takes this nested list as input and returns a new list with all the integers in a single, flat list. The function should be able to handle lists of arbitrary depth.\n\n**Input:**\n- A nested list of integers, where each element is either an integer or a list of integers.\n\n**Output:**\n- A flat list containing all the integers from the nested list in the same order.\n\n**Sample Input:**\n```python\n[1, [2, [3, 4], 5], [6, 7]]\n```\n\n**Sample Output:**\n```python\n[1, 2, 3, 4, 5, 6, 7]\n```", "reference": "def flatten_list(nested_list):\n \"\"\"\n Flattens a nested list of integers into a single flat list.\n\n :param nested_list: List of integers or nested lists of integers.\n :return: A flat list containing all integers from the nested list.\n \"\"\"\n flat_list = []\n for item in nested_list:\n if isinstance(item, list):\n flat_list.extend(flatten_list(item))\n else:\n flat_list.append(item)\n return flat_list\n\n# Example usage:\nnested_list_example = [1, [2, [3, 4], 5], [6, 7]]\nflattened = flatten_list(nested_list_example)\nprint(flattened) # Output: [1, 2, 3, 4, 5, 6, 7]", "tests": ["assert flatten_list([1, 2, 3]) == [1, 2, 3]", "assert flatten_list([1, [2, 3], 4]) == [1, 2, 3, 4]", "assert flatten_list([1, [2, [3, 4], 5], [6, 7]]) == [1, 2, 3, 4, 5, 6, 7]", "assert flatten_list([[1, 2], [3, 4], [5, 6]]) == [1, 2, 3, 4, 5, 6]", "assert flatten_list([[[1]], 2, [3, [4, [5]]]]) == [1, 2, 3, 4, 5]", "assert flatten_list([]) == []", "assert flatten_list([[], [], []]) == []", "assert flatten_list([1, [2, [3, [4, [5, [6, [7]]]]]]]) == [1, 2, 3, 4, 5, 6, 7]", "assert flatten_list([1, [2, [3, [4, [5, [6, 7]]]]]]) == [1, 2, 3, 4, 5, 6, 7]", "assert flatten_list([[[[[[1]]]]]]) == [1]"], "function": "flatten_list", "signature": "def flatten_list(nested_list):", "score": 1.0, "domain": "generic"} {"id": "f470a7d24b5832e42775fd6395e9b0be", "problem": "You are given a list of `n` points in a 2D plane, where each point is represented as a tuple `(x, y)`. Additionally, you are provided with a reference point `(ref_x, ref_y)` and a maximum deviation `d`. Your task is to implement a function that efficiently returns a list of points that are within the maximum deviation `d` from the reference point. The distance between two points `(x1, y1)` and `(x2, y2)` is defined as the Euclidean distance, but for efficiency, you should compare the squared distances.\n\n**Constraints:**\n- `1 ≤ n ≤ 10^6`\n- `-10^9 ≤ x, y, ref_x, ref_y ≤ 10^9`\n- `0 ≤ d ≤ 10^9`\n\n**Sample Input:**\n```python\npoints = [(1, 2), (3, 4), (5, 6), (7, 8)]\nreference_point = (4, 4)\nmax_deviation = 3\n```\n\n**Sample Output:**\n```python\n[(3, 4), (5, 6)]\n```", "reference": "def points_within_deviation(points, reference_point, max_deviation):\n \"\"\"\n Returns a list of points that are within the maximum deviation from the reference point.\n \n :param points: List of tuples representing points in 2D space.\n :param reference_point: Tuple representing the reference point (x, y).\n :param max_deviation: Integer representing the maximum allowed deviation.\n :return: List of tuples representing points within the maximum deviation from the reference point.\n \"\"\"\n ref_x, ref_y = reference_point\n max_deviation_squared = max_deviation ** 2\n result = []\n\n for x, y in points:\n distance_squared = (x - ref_x) ** 2 + (y - ref_y) ** 2\n if distance_squared <= max_deviation_squared:\n result.append((x, y))\n\n return result", "tests": ["assert points_within_deviation([(1, 1), (2, 2), (3, 3)], (2, 2), 1) == [(2, 2)]", "assert points_within_deviation([(1, 1), (2, 2), (3, 3)], (2, 2), 2) == [(1, 1), (2, 2), (3, 3)]", "assert points_within_deviation([(0, 0), (1, 1), (2, 2)], (0, 0), 1) == [(0, 0)]", "assert points_within_deviation([(0, 0), (1, 1), (2, 2)], (0, 0), 0) == [(0, 0)]", "assert points_within_deviation([(0, 0), (1, 1), (2, 2)], (1, 1), 1.41421356237) == [(0, 0), (1, 1), (2, 2)]", "assert points_within_deviation([(0, 0), (1, 1), (2, 2)], (1, 1), 1.41421356236) == [(1, 1)]", "assert points_within_deviation([], (1, 1), 1) == []", "assert points_within_deviation([(1, 1), (1, 1), (1, 1)], (1, 1), 0) == [(1, 1), (1, 1), (1, 1)]", "assert points_within_deviation([(1, 1), (2, 2), (3, 3)], (4, 4), 1) == []", "assert points_within_deviation([(1, 1), (2, 2), (3, 3)], (4, 4), 3) == [(2, 2), (3, 3)]"], "function": "points_within_deviation", "signature": "def points_within_deviation(points, reference_point, max_deviation):", "score": 0.9, "domain": "generic"} {"id": "68a6cdc0c46542379ea920c945e6e00c", "problem": "You are given a list of integers. Your task is to determine the number of unique index pairs (i, j) such that i < j and the absolute difference between the elements at indices i and j is a prime number. \n\n**Input:**\n- A list of integers `lst` where 1 ≤ len(lst) ≤ 100 and 1 ≤ lst[i] ≤ 1000.\n\n**Output:**\n- An integer representing the count of such pairs.\n\n**Sample Input:**\n```\n[10, 15, 20, 25, 30, 35]\n```\n\n**Sample Output:**\n```\n5\n```", "reference": "def is_prime(n):\n \"\"\"\n Check if a number is prime.\n \n :param n: Integer to check for primality.\n :return: True if n is prime, False otherwise.\n \"\"\"\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == 0 or n % 3 == 0:\n return False\n i = 5\n while i * i <= n:\n if n % i == 0 or n % (i + 2) == 0:\n return False\n i += 6\n return True\n\ndef count_prime_diff_pairs(lst):\n \"\"\"\n Count the number of index pairs (i, j) such that i < j and the absolute difference\n between lst[i] and lst[j] is a prime number.\n \n :param lst: List of integers.\n :return: Count of such pairs.\n \"\"\"\n count = 0\n for i in range(len(lst)):\n for j in range(i + 1, len(lst)):\n if is_prime(abs(lst[i] - lst[j])):\n count += 1\n return count\n\n# Given list of integers\nlst = [10, 15, 20, 25, 30, 35]\nprint(count_prime_diff_pairs(lst)) # Output: 5", "tests": ["assert count_prime_diff_pairs([10, 15, 20, 25, 30, 35]) == 5", "assert count_prime_diff_pairs([1, 2, 3, 4, 5]) == 4", "assert count_prime_diff_pairs([2, 3, 5, 7, 11]) == 6", "assert count_prime_diff_pairs([1, 1, 1, 1, 1]) == 0", "assert count_prime_diff_pairs([10, 20, 30, 40, 50]) == 0", "assert count_prime_diff_pairs([4, 6, 8, 10, 12]) == 0", "assert count_prime_diff_pairs([1, 3, 5, 7, 9, 11]) == 9", "assert count_prime_diff_pairs([0, 1, 4, 6, 8, 9]) == 3", "assert count_prime_diff_pairs([13, 17, 19, 23, 29]) == 10", "assert count_prime_diff_pairs([]) == 0"], "function": "count_prime_diff_pairs", "signature": "def count_prime_diff_pairs(lst):", "score": 0.4, "domain": "algorithmic"} {"id": "12d0d4805f21267537833fa87c103030", "problem": "You are given a task to implement a Python function `load_or_create_books_data` that handles reading from and writing to a JSON file. The JSON file should contain a list of dictionaries, where each dictionary represents a book with the keys \"title\", \"author\", and \"pages\". The \"pages\" value should be stored as a hexadecimal string.\n\nYour function should take a single argument, `json_file_path`, which is the path to the JSON file. If the file exists and contains valid data (a list of dictionaries with the required keys), the function should return the data. If the file does not exist, is not accessible, or does not contain the expected data structure, the function should print an error message, create a new JSON file with a default list containing one dictionary (representing a book with placeholder values, where \"pages\" is a hexadecimal string), and then return the default data.\n\n**Sample Input/Output:**\n\n- **Input:** `books.json` (does not exist)\n- **Output:** \n ```\n Error: The file at books.json was not found or could not be decoded. Creating a new file with default data.\n New JSON file created at books.json with default data.\n [{'title': 'Placeholder Book Title', 'author': 'Placeholder Author', 'pages': '0x64'}]\n ```\n\n- **Input:** `books.json` (exists with invalid data)\n- **Output:**\n ```\n Error: The JSON file does not contain the expected data structure.\n Error: The file at books.json was not found or could not be decoded. Creating a new file with default data.\n New JSON file created at books.json with default data.\n [{'title': 'Placeholder Book Title', 'author': 'Placeholder Author', 'pages': '0x64'}]\n ```\n\n- **Input:** `books.json` (exists with valid data)\n- **Output:**\n ```\n [{'title': 'Book Title', 'author': 'Author Name', 'pages': '0x1a4'}]\n ```", "reference": "import json\nimport os\n\ndef load_or_create_books_data(json_file_path):\n \"\"\"\n Reads data from a JSON file or creates a new one with default data if the file is not accessible or invalid.\n \n Args:\n json_file_path (str): The path to the JSON file.\n \n Returns:\n list: A list of dictionaries representing books, each with keys \"title\", \"author\", and \"pages\".\n \"\"\"\n default_books_data = [\n {\n \"title\": \"Placeholder Book Title\",\n \"author\": \"Placeholder Author\",\n \"pages\": hex(100) # Example pages converted to hexadecimal\n }\n ]\n\n try:\n with open(json_file_path, 'r') as file:\n books_data = json.load(file)\n if isinstance(books_data, list) and all(isinstance(book, dict) and \"title\" in book and \"author\" in book and \"pages\" in book for book in books_data):\n return books_data\n else:\n print(\"Error: The JSON file does not contain the expected data structure.\")\n except (FileNotFoundError, json.JSONDecodeError):\n print(f\"Error: The file at {json_file_path} was not found or could not be decoded. Creating a new file with default data.\")\n\n try:\n with open(json_file_path, 'w') as file:\n json.dump(default_books_data, file, indent=4)\n print(f\"New JSON file created at {json_file_path} with default data.\")\n return default_books_data\n except Exception as e:\n print(f\"An error occurred while creating the JSON file: {e}\")\n return []", "tests": ["assert load_or_create_books_data('non_existent_file.json') == [{'title': 'Placeholder Book Title', 'author': 'Placeholder Author', 'pages': '0x64'}]", "assert load_or_create_books_data('empty_file.json') == [{'title': 'Placeholder Book Title', 'author': 'Placeholder Author', 'pages': '0x64'}]", "assert load_or_create_books_data('invalid_json_file.json') == [{'title': 'Placeholder Book Title', 'author': 'Placeholder Author', 'pages': '0x64'}]", "assert load_or_create_books_data('valid_json_file.json') == [{'title': 'Placeholder Book Title', 'author': 'Placeholder Author', 'pages': '0x64'}]", "assert load_or_create_books_data('malformed_json_file.json') == [{'title': 'Placeholder Book Title', 'author': 'Placeholder Author', 'pages': '0x64'}]", "assert load_or_create_books_data('incorrect_structure_json_file.json') == [{'title': 'Placeholder Book Title', 'author': 'Placeholder Author', 'pages': '0x64'}]", "assert load_or_create_books_data('correct_structure_json_file.json') == [{'title': 'Book Title', 'author': 'Author Name', 'pages': '0x1f4'}]", "assert load_or_create_books_data('another_non_existent_file.json') == [{'title': 'Placeholder Book Title', 'author': 'Placeholder Author', 'pages': '0x64'}]", "assert load_or_create_books_data('permissions_denied_file.json') == [{'title': 'Placeholder Book Title', 'author': 'Placeholder Author', 'pages': '0x64'}]", "assert load_or_create_books_data('file_with_incorrect_hex.json') == [{'title': 'Placeholder Book Title', 'author': 'Placeholder Author', 'pages': '0x64'}]"], "function": "load_or_create_books_data", "signature": "def load_or_create_books_data(json_file_path):", "score": 0.8, "domain": "generic"} {"id": "087810d87e1c9aac1a95fc160a535355", "problem": "You are tasked with implementing a function `generate_report` that processes a list of sales data and outputs a formatted sales report. The sales data is provided as a list of dictionaries, where each dictionary contains the keys \"product_name\", \"quantity_sold\", and \"price_per_unit\". Your function should compute the total revenue for each product and the overall total revenue, then print a formatted report.\n\n**Input:**\n- A list of dictionaries, where each dictionary has the following keys:\n - \"product_name\": A string representing the name of the product.\n - \"quantity_sold\": An integer representing the quantity of the product sold.\n - \"price_per_unit\": A float representing the price per unit of the product.\n\n**Output:**\n- For each product, print a line in the format: `\": units sold at $ each = $\"`.\n- Print a final line with the overall total revenue in the format: `\"Total Revenue: $\"`.\n\n**Sample Input:**\n```python\n[\n {\"product_name\": \"Widget A\", \"quantity_sold\": 10, \"price_per_unit\": 15},\n {\"product_name\": \"Widget B\", \"quantity_sold\": 5, \"price_per_unit\": 20},\n {\"product_name\": \"Widget C\", \"quantity_sold\": 7, \"price_per_unit\": 10}\n]\n```\n\n**Sample Output:**\n```\nWidget A: 10 units sold at $15 each = $150\nWidget B: 5 units sold at $20 each = $100\nWidget C: 7 units sold at $10 each = $70\nTotal Revenue: $320\n```", "reference": "def generate_report(sales_data):\n \"\"\"\n Generates a formatted sales report from a list of sales data.\n\n Parameters:\n sales_data (list of dict): A list of dictionaries containing sales data.\n Each dictionary must have the keys:\n - \"product_name\": str\n - \"quantity_sold\": int\n - \"price_per_unit\": float\n\n Returns:\n None: The function prints the sales report to the console.\n \"\"\"\n total_revenue = 0\n report_lines = []\n\n for entry in sales_data:\n product_name = entry[\"product_name\"]\n quantity_sold = entry[\"quantity_sold\"]\n price_per_unit = entry[\"price_per_unit\"]\n\n product_revenue = quantity_sold * price_per_unit\n total_revenue += product_revenue\n\n report_lines.append(f\"{product_name}: {quantity_sold} units sold at ${price_per_unit} each = ${product_revenue}\")\n\n report_lines.append(f\"Total Revenue: ${total_revenue}\")\n\n for line in report_lines:\n print(line)", "tests": ["assert generate_report([{\"product_name\": \"Widget A\", \"quantity_sold\": 10, \"price_per_unit\": 15}]) == None", "assert generate_report([{\"product_name\": \"Widget A\", \"quantity_sold\": 10, \"price_per_unit\": 15}, {\"product_name\": \"Widget B\", \"quantity_sold\": 5, \"price_per_unit\": 20}]) == None", "assert generate_report([]) == None", "assert generate_report([{\"product_name\": \"Widget A\", \"quantity_sold\": 0, \"price_per_unit\": 15}]) == None", "assert generate_report([{\"product_name\": \"Widget A\", \"quantity_sold\": 10, \"price_per_unit\": 0}]) == None", "assert generate_report([{\"product_name\": \"Widget A\", \"quantity_sold\": 10, \"price_per_unit\": 15}, {\"product_name\": \"Widget A\", \"quantity_sold\": 5, \"price_per_unit\": 20}]) == None", "assert generate_report([{\"product_name\": \"Widget A\", \"quantity_sold\": 1, \"price_per_unit\": 1}]) == None", "assert generate_report([{\"product_name\": \"Widget A\", \"quantity_sold\": 100, \"price_per_unit\": 100}]) == None", "assert generate_report([{\"product_name\": \"Widget A\", \"quantity_sold\": 10, \"price_per_unit\": 15.5}]) == None", "assert generate_report([{\"product_name\": \"Widget A\", \"quantity_sold\": 10, \"price_per_unit\": 15}, {\"product_name\": \"Widget B\", \"quantity_sold\": 5, \"price_per_unit\": 20.75}]) == None"], "function": "generate_report", "signature": "def generate_report(sales_data):", "score": 1.0, "domain": "generic"} {"id": "22677ccd2746bc5ffc60cf34b5f8cb88", "problem": "You are given a string `text` containing various characters. Your task is to implement a function `extract_emails` that identifies and returns all valid email addresses present in the string. An email address is defined as a sequence of characters that matches the pattern `[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+`. \n\n**Input:**\n- A single string `text` (1 ≤ len(text) ≤ 1000).\n\n**Output:**\n- A list of strings, where each string is a valid email address found in the input text. The order of emails in the output list should match their order of appearance in the input string.\n\n**Sample Input:**\n```\n\"Contact us at support@example.com or sales@example.org. Visit our website at http://www.example.com.\"\n```\n\n**Sample Output:**\n```\n['support@example.com', 'sales@example.org']\n```", "reference": "import re\n\ndef extract_emails(text):\n \"\"\"\n Extracts all valid email addresses from the given text.\n\n Parameters:\n text (str): The input string containing potential email addresses.\n\n Returns:\n list: A list of strings, each representing a valid email address found in the text.\n \"\"\"\n email_pattern = r'[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+'\n return re.findall(email_pattern, text)", "tests": ["assert extract_emails(\"Contact us at support@example.com or sales@example.org.\") == [\"support@example.com\", \"sales@example.org\"]", "assert extract_emails(\"No emails here!\") == []", "assert extract_emails(\"Multiple emails: test1@test.com, test2@test.org, test3@test.net\") == [\"test1@test.com\", \"test2@test.org\", \"test3@test.net\"]", "assert extract_emails(\"Email with subdomain: user@mail.example.com\") == [\"user@mail.example.com\"]", "assert extract_emails(\"Invalid email: @example.com\") == []", "assert extract_emails(\"Another invalid email: user@.com\") == []", "assert extract_emails(\"Valid email with numbers: user123@domain.com\") == [\"user123@domain.com\"]", "assert extract_emails(\"Email with special characters: user.name+tag+sorting@example.com\") == [\"user.name+tag+sorting@example.com\"]", "assert extract_emails(\"Mixed content: text user@domain.com more text\") == [\"user@domain.com\"]", "assert extract_emails(\"Emails with different TLDs: user@domain.co.uk, user@domain.io\") == [\"user@domain.co.uk\", \"user@domain.io\"]"], "function": "extract_emails", "signature": "def extract_emails(text):", "score": 0.9, "domain": "generic"} {"id": "3eed4985af21f7de0dd3c287ea1e2e86", "problem": "You are given a list of unique pairs of words, where each pair represents a synonym relationship. Your task is to write a function that returns two lists: one containing all unique words and the other containing all unique edges representing the synonym relationships. Ensure that the edges do not include any transitive synonym pairs and that each edge is represented as a tuple with the words in lexicographical order.\n\n**Input:**\n- A list of tuples, where each tuple contains two strings representing a synonym relationship.\n\n**Output:**\n- A list of unique words.\n- A list of tuples representing the unique edges, with each tuple containing two words in lexicographical order.\n\n**Sample Input:**\n```python\n[(\"happy\", \"joyful\"), (\"sad\", \"unhappy\"), (\"happy\", \"content\"), (\"joyful\", \"cheerful\")]\n```\n\n**Sample Output:**\n```python\nUnique words: ['happy', 'joyful', 'sad', 'unhappy', 'content', 'cheerful']\nEdges: [('content', 'happy'), ('happy', 'joyful'), ('joyful', 'cheerful'), ('sad', 'unhappy')]\n```", "reference": "def get_unique_words_and_edges(synonyms):\n \"\"\"\n Returns a list of unique words and a list of unique edges representing synonym relationships.\n \n :param synonyms: List of tuples, where each tuple contains two strings representing a synonym relationship.\n :return: A tuple containing a list of unique words and a list of unique edges.\n \"\"\"\n unique_words = set()\n edges = set()\n\n for word1, word2 in synonyms:\n unique_words.add(word1)\n unique_words.add(word2)\n if word1 < word2:\n edges.add((word1, word2))\n else:\n edges.add((word2, word1))\n \n return list(unique_words), list(edges)\n\n# Example usage:\nsynonyms = [(\"happy\", \"joyful\"), (\"sad\", \"unhappy\"), (\"happy\", \"content\"), (\"joyful\", \"cheerful\")]\nwords, edges = get_unique_words_and_edges(synonyms)\nprint(\"Unique words:\", words)\nprint(\"Edges:\", edges)", "tests": ["assert get_unique_words_and_edges([(\"happy\", \"joyful\")]) == (['happy', 'joyful'], [('happy', 'joyful')])", "assert get_unique_words_and_edges([(\"sad\", \"unhappy\"), (\"happy\", \"content\")]) == (['sad', 'unhappy', 'happy', 'content'], [('sad', 'unhappy'), ('happy', 'content')])", "assert get_unique_words_and_edges([(\"happy\", \"joyful\"), (\"joyful\", \"cheerful\")]) == (['happy', 'joyful', 'cheerful'], [('happy', 'joyful'), ('joyful', 'cheerful')])", "assert get_unique_words_and_edges([(\"a\", \"b\"), (\"b\", \"c\"), (\"c\", \"a\")]) == (['a', 'b', 'c'], [('a', 'b'), ('b', 'c')])", "assert get_unique_words_and_edges([]) == ([], [])", "assert get_unique_words_and_edges([(\"apple\", \"banana\"), (\"banana\", \"apple\")]) == (['apple', 'banana'], [('apple', 'banana')])", "assert get_unique_words_and_edges([(\"dog\", \"cat\"), (\"cat\", \"mouse\"), (\"mouse\", \"dog\")]) == (['dog', 'cat', 'mouse'], [('cat', 'dog'), ('cat', 'mouse')])", "assert get_unique_words_and_edges([(\"one\", \"two\"), (\"three\", \"four\"), (\"five\", \"six\")]) == (['one', 'two', 'three', 'four', 'five', 'six'], [('one', 'two'), ('three', 'four'), ('five', 'six')])", "assert get_unique_words_and_edges([(\"x\", \"y\"), (\"y\", \"z\"), (\"z\", \"x\"), (\"x\", \"z\")]) == (['x', 'y', 'z'], [('x', 'y'), ('x', 'z'), ('y', 'z')])", "assert get_unique_words_and_edges([(\"red\", \"blue\"), (\"green\", \"yellow\"), (\"red\", \"green\")]) == (['red', 'blue', 'green', 'yellow'], [('blue', 'red'), ('green', 'red'), ('green', 'yellow')])"], "function": "get_unique_words_and_edges", "signature": "def get_unique_words_and_edges(synonyms):", "score": 0.3, "domain": "generic"} {"id": "5b6c5c614c6f850cbdd27f3a86fd7dce", "problem": "You are tasked with implementing a function `is_prime(num)` that determines whether a given integer `num` is a prime number. A prime number is defined as an integer greater than 1 that has no divisors other than 1 and itself. Your function should return `True` if `num` is prime, and `False` otherwise. For integers less than or equal to 1, the function should return `False`.\n\n**Input:**\n- An integer `num` (-10^9 ≤ num ≤ 10^9)\n\n**Output:**\n- A boolean value: `True` if `num` is prime, `False` otherwise.\n\n**Sample Input:**\n```\n5\n10\n-3\n0\n1\n2\n```\n\n**Sample Output:**\n```\nTrue\nFalse\nFalse\nFalse\nFalse\nTrue\n```", "reference": "def is_prime(num):\n \"\"\"\n Determines if the given integer is a prime number.\n \n Args:\n num (int): The integer to check for primality.\n \n Returns:\n bool: True if num is prime, False otherwise.\n \"\"\"\n if num <= 1:\n return False\n if num <= 3:\n return True\n if num % 2 == 0 or num % 3 == 0:\n return False\n i = 5\n while i * i <= num:\n if num % i == 0 or num % (i + 2) == 0:\n return False\n i += 6\n return True", "tests": ["assert is_prime(2) == True", "assert is_prime(3) == True", "assert is_prime(4) == False", "assert is_prime(5) == True", "assert is_prime(11) == True", "assert is_prime(15) == False", "assert is_prime(17) == True", "assert is_prime(1) == False", "assert is_prime(0) == False", "assert is_prime(-5) == False"], "function": "is_prime", "signature": "def is_prime(num):", "score": 1.0, "domain": "generic"} {"id": "021be2bfb0cdaf30e538fb42225d0323", "problem": "You are given a sorted list of integers `arr` and an integer `target`. Implement a function `binary_search` that performs a binary search on `arr` to find the index of `target`. If `target` is found, return a tuple containing the index and the number of comparisons made during the search. If `target` is not found, return a tuple with `-1` and the number of comparisons.\n\n**Input:**\n- A sorted list of integers `arr` (1 ≤ len(arr) ≤ 10^4)\n- An integer `target` (-10^9 ≤ target ≤ 10^9)\n\n**Output:**\n- A tuple `(index, comparisons)` where `index` is the position of `target` in `arr` or `-1` if not found, and `comparisons` is the number of comparisons made.\n\n**Sample Input:**\n```\narr = [1, 3, 5, 7, 9, 11]\ntarget = 7\n```\n\n**Sample Output:**\n```\n(3, 2)\n```", "reference": "def binary_search(arr, target):\n \"\"\"\n Perform a binary search on a sorted list to find the index of the target element.\n \n Parameters:\n arr (list of int): The sorted list of integers.\n target (int): The integer to search for in the list.\n \n Returns:\n tuple: A tuple containing the index of the target element if found, or -1 if not found,\n and the number of comparisons made during the search.\n \"\"\"\n left, right = 0, len(arr) - 1\n comparisons = 0\n \n while left <= right:\n mid = left + (right - left) // 2\n comparisons += 1\n \n if arr[mid] == target:\n return mid, comparisons\n elif arr[mid] < target:\n left = mid + 1\n else:\n right = mid - 1\n \n return -1, comparisons\n\n# Example usage\narr = [1, 3, 5, 7, 9, 11]\ntarget = 7\nindex, comparisons = binary_search(arr, target)\nprint(f\"Index: {index}, Comparisons: {comparisons}\")", "tests": ["assert binary_search([1, 3, 5, 7, 9, 11], 7) == (3, 2)", "assert binary_search([1, 3, 5, 7, 9, 11], 1) == (0, 1)", "assert binary_search([1, 3, 5, 7, 9, 11], 11) == (5, 3)", "assert binary_search([1, 3, 5, 7, 9, 11], 5) == (2, 2)", "assert binary_search([1, 3, 5, 7, 9, 11], 13) == (-1, 3)", "assert binary_search([], 1) == (-1, 0)", "assert binary_search([1], 1) == (0, 1)", "assert binary_search([1, 2], 2) == (1, 1)", "assert binary_search([1, 2], 1) == (0, 1)", "assert binary_search([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 10) == (9, 4)"], "function": "binary_search", "signature": "def binary_search(arr, target):", "score": 0.6, "domain": "algorithmic"} {"id": "a0f628cc5af192982a65a8e724f1fd18", "problem": "You are given a CSV file named `sales_data.csv` containing sales information for various products. Your task is to write a Python script that reads this file and calculates the total sales for each product. The CSV file has the following columns: `product_id`, `product_name`, `quantity_sold`, and `unit_price`. The total sales for a product is calculated as the product of `quantity_sold` and `unit_price`. Your script should output the total sales for each product in the format: `Product: , Total Sales: `, where `` is formatted to two decimal places. Your script should handle potential errors such as file not found, invalid data types, and other exceptions gracefully.\n\n**Sample Input:**\n```\nproduct_id,product_name,quantity_sold,unit_price\n101,Widget,10,19.99\n102,Gadget,5,29.99\n101,Widget,3,19.99\n```\n\n**Sample Output:**\n```\nProduct: Widget, Total Sales: 239.88\nProduct: Gadget, Total Sales: 149.95\n```", "reference": "import csv\n\ndef calculate_total_sales(csv_file_name):\n \"\"\"\n Reads a CSV file and calculates the total sales for each product.\n \n Parameters:\n csv_file_name (str): The name of the CSV file to read.\n \n Returns:\n None: Outputs the total sales for each product in the specified format.\n \"\"\"\n try:\n with open(csv_file_name, mode='r', newline='') as file:\n csv_reader = csv.DictReader(file)\n total_sales_per_product = {}\n\n for row in csv_reader:\n try:\n product_name = row['product_name']\n quantity_sold = float(row['quantity_sold'])\n unit_price = float(row['unit_price'])\n total_sales = quantity_sold * unit_price\n\n if product_name in total_sales_per_product:\n total_sales_per_product[product_name] += total_sales\n else:\n total_sales_per_product[product_name] = total_sales\n\n except ValueError:\n print(f\"Invalid data in row for product: {row['product_name']}\")\n continue\n\n for product_name, total_sales in total_sales_per_product.items():\n print(f\"Product: {product_name}, Total Sales: {total_sales:.2f}\")\n\n except FileNotFoundError:\n print(f\"Error: The file {csv_file_name} does not exist.\")\n except Exception as e:\n print(f\"An error occurred while reading the file: {e}\")\n\ncalculate_total_sales('sales_data.csv')", "tests": ["assert calculate_total_sales('non_existent_file.csv') is None", "assert calculate_total_sales('empty_file.csv') is None", "assert calculate_total_sales('invalid_data.csv') is None", "assert calculate_total_sales('single_product.csv') is None", "assert calculate_total_sales('multiple_products.csv') is None", "assert calculate_total_sales('mixed_valid_invalid_data.csv') is None", "assert calculate_total_sales('large_data_set.csv') is None", "assert calculate_total_sales('special_characters.csv') is None", "assert calculate_total_sales('duplicate_product_names.csv') is None", "assert calculate_total_sales('zero_quantity_or_price.csv') is None"], "function": "calculate_total_sales", "signature": "def calculate_total_sales(csv_file_name):", "score": 1.0, "domain": "generic"} {"id": "fb02c68b66f830d2f0fc63723652b037", "problem": "You are given a string `s` consisting of lowercase English letters. Your task is to implement a function that returns the first non-repeating character in the string. If all characters repeat, return `None`.\n\n**Input:**\n- A single string `s` (1 ≤ |s| ≤ 10^5).\n\n**Output:**\n- A single character representing the first non-repeating character in the string, or `None` if all characters repeat.\n\n**Sample Input:**\n```\nswiss\n```\n\n**Sample Output:**\n```\nw\n```", "reference": "def first_non_repeating_character(s):\n \"\"\"\n Returns the first non-repeating character in the string.\n \n Parameters:\n s (str): The input string consisting of lowercase English letters.\n \n Returns:\n char or None: The first non-repeating character or None if all characters repeat.\n \"\"\"\n char_count = {}\n \n for char in s:\n if char in char_count:\n char_count[char] += 1\n else:\n char_count[char] = 1\n \n for char in s:\n if char_count[char] == 1:\n return char\n \n return None", "tests": ["assert first_non_repeating_character(\"swiss\") == \"w\"", "assert first_non_repeating_character(\"aabbcc\") == None", "assert first_non_repeating_character(\"abcabcabc\") == None", "assert first_non_repeating_character(\"a\") == \"a\"", "assert first_non_repeating_character(\"abcdef\") == \"a\"", "assert first_non_repeating_character(\"aabbccddee\") == None", "assert first_non_repeating_character(\"aabbcde\") == \"c\"", "assert first_non_repeating_character(\"zzzzz\") == None", "assert first_non_repeating_character(\"xyzzyx\") == \"z\"", "assert first_non_repeating_character(\"hello\") == \"h\""], "function": "first_non_repeating_character", "signature": "def first_non_repeating_character(s):", "score": 0.9, "domain": "algorithmic"} {"id": "db11607ebbf9a358ed7435bfc0f66c20", "problem": "You are given a four-digit positive integer `n`. Your task is to write a function `swap_digits(n: int) -> int` that swaps the first and fourth digits of `n` and returns the resulting integer.\n\n**Constraints:**\n- `1000 ≤ n ≤ 9999`\n\n**Sample Input:**\n```\n4567\n```\n\n**Sample Output:**\n```\n7564\n```\n\n**Sample Input:**\n```\n1234\n```\n\n**Sample Output:**\n```\n4231\n```", "reference": "def swap_digits(n: int) -> int:\n \"\"\"\n Swaps the first and fourth digits of a four-digit integer n and returns the resulting integer.\n \n :param n: A four-digit positive integer\n :return: An integer with the first and fourth digits swapped\n \"\"\"\n n_str = str(n)\n swapped_str = n_str[3] + n_str[1:3] + n_str[0]\n swapped_int = int(swapped_str)\n return swapped_int", "tests": ["assert swap_digits(4567) == 7564", "assert swap_digits(1234) == 4231", "assert swap_digits(9876) == 6879", "assert swap_digits(1111) == 1111", "assert swap_digits(2468) == 8462", "assert swap_digits(1357) == 7351", "assert swap_digits(5678) == 8675", "assert swap_digits(9001) == 1009", "assert swap_digits(1009) == 9001", "assert swap_digits(2020) == 2020"], "function": "swap_digits", "signature": "def swap_digits(n: int) -> int:", "score": 0.9, "domain": "generic"} {"id": "c1881bfb93f9bd47c4f5a6628221756d", "problem": "You are given a string `binary_str` consisting of '0's and '1's, representing a binary number. Your task is to write a function `binary_to_decimal` that computes and returns the decimal equivalent of the binary number. You are not allowed to use any built-in conversion functions.\n\n**Input:**\n- A string `binary_str` (1 ≤ len(binary_str) ≤ 30) representing a binary number.\n\n**Output:**\n- An integer representing the decimal equivalent of the binary number.\n\n**Sample Input:**\n```\n\"1101\"\n```\n\n**Sample Output:**\n```\n13\n```", "reference": "def binary_to_decimal(binary_str):\n \"\"\"\n Convert a binary string to its decimal equivalent without using built-in conversion functions.\n\n :param binary_str: A string representing a binary number.\n :return: An integer representing the decimal equivalent of the binary number.\n \"\"\"\n decimal_value = 0\n power = 0\n \n for digit in reversed(binary_str):\n if digit == '1':\n decimal_value += 2 ** power\n power += 1\n \n return decimal_value\n\n# Test the function with the given binary number\nbinary_number = \"1101\"\ndecimal_number = binary_to_decimal(binary_number)\nprint(decimal_number)", "tests": ["assert binary_to_decimal(\"0\") == 0", "assert binary_to_decimal(\"1\") == 1", "assert binary_to_decimal(\"10\") == 2", "assert binary_to_decimal(\"11\") == 3", "assert binary_to_decimal(\"100\") == 4", "assert binary_to_decimal(\"101\") == 5", "assert binary_to_decimal(\"110\") == 6", "assert binary_to_decimal(\"111\") == 7", "assert binary_to_decimal(\"1000\") == 8", "assert binary_to_decimal(\"1101\") == 13"], "function": "binary_to_decimal", "signature": "def binary_to_decimal(binary_str):", "score": 1.0, "domain": "generic"} {"id": "76026661ea42111127975c356031c675", "problem": "You are tasked with implementing a function `convert_to_binary` that takes an integer `n` as input and returns its binary representation as a string. The function should correctly handle both positive and negative integers and should not include any leading zeros in the output. For example, the binary representation of `10` is `'1010'`, and for `-10`, it is `'-1010'`.\n\n**Sample Input and Output:**\n- Input: `10`\n - Output: `'1010'`\n- Input: `-10`\n - Output: `'-1010'`\n- Input: `0`\n - Output: `'0'`", "reference": "def convert_to_binary(n):\n \"\"\"\n Convert an integer to its binary representation as a string.\n \n Parameters:\n n (int): The integer to convert.\n \n Returns:\n str: The binary representation of the integer without leading zeros.\n \"\"\"\n if n == 0:\n return \"0\"\n \n is_negative = n < 0\n n = abs(n)\n \n binary = ''\n while n > 0:\n binary = str(n % 2) + binary\n n = n // 2\n \n if is_negative:\n binary = '-' + binary\n \n return binary\n\n# Test the function\nprint(convert_to_binary(10)) # Output: '1010'\nprint(convert_to_binary(-10)) # Output: '-1010'\nprint(convert_to_binary(0)) # Output: '0'", "tests": ["assert convert_to_binary(10) == \"1010\"", "assert convert_to_binary(-10) == \"-1010\"", "assert convert_to_binary(0) == \"0\"", "assert convert_to_binary(1) == \"1\"", "assert convert_to_binary(-1) == \"-1\"", "assert convert_to_binary(255) == \"11111111\"", "assert convert_to_binary(-255) == \"-11111111\"", "assert convert_to_binary(1024) == \"10000000000\"", "assert convert_to_binary(-1024) == \"-10000000000\"", "assert convert_to_binary(123456) == \"11110001111000000\""], "function": "convert_to_binary", "signature": "def convert_to_binary(n):", "score": 0.9, "domain": "generic"} {"id": "99e5532a199544ac7e9d0a90241e80b3", "problem": "You are given a text file named `input.txt`. Your task is to write a Python program that reads this file and counts the number of occurrences of each word. The program should output the words and their counts in descending order of frequency. Words are defined as sequences of alphanumeric characters and are case-insensitive. \n\n**Input:**\n- The file `input.txt` contains multiple lines of text.\n\n**Output:**\n- Print each unique word and its count, separated by a colon and a space, in descending order of frequency. If two words have the same frequency, they should be printed in lexicographical order.\n\n**Sample Input:**\n```\nHello world!\nHello, hello, HELLO.\n```\n\n**Sample Output:**\n```\nhello: 4\nworld: 1\n```", "reference": "from collections import Counter\nimport re\n\ndef word_count(filename):\n \"\"\"\n Reads a text file and counts the number of occurrences of each word.\n Outputs the words and their counts in descending order of frequency.\n \n :param filename: str, the name of the file to read\n \"\"\"\n with open(filename, 'r') as file:\n contents = file.read()\n\n word_pattern = re.compile('[^\\w\\s]')\n cleaned_contents = word_pattern.sub(' ', contents.lower())\n words = cleaned_contents.split()\n word_counter = Counter(words)\n\n for word, count in sorted(word_counter.items(), key=lambda item: (-item[1], item[0])):\n print(f'{word}: {count}')\n\n# Example usage\nword_count('input.txt')", "tests": ["assert word_count('test1.txt') == None", "assert word_count('test2.txt') == None", "assert word_count('empty.txt') == None", "assert word_count('single_word.txt') == None", "assert word_count('multiple_words.txt') == None", "assert word_count('punctuation.txt') == None", "assert word_count('case_insensitive.txt') == None", "assert word_count('numbers.txt') == None", "assert word_count('special_chars.txt') == None", "assert word_count('mixed_content.txt') == None"], "function": "word_count", "signature": "def word_count(filename):", "score": 0.3, "domain": "generic"} {"id": "74e99e1f7d95e300fa0a5d59f4d9c426", "problem": "You are given a dataset of 2D points representing the locations of various restaurants in a city. Your task is to implement a function that, given a new restaurant location and an integer `k`, returns the `k` nearest restaurants to the new location based on the Euclidean distance. The dataset is provided as a list of tuples, where each tuple contains the `x` and `y` coordinates of a restaurant. The new restaurant location is also provided as a tuple containing its `x` and `y` coordinates. Your function should return a list of tuples, where each tuple contains the `x` and `y` coordinates of a nearby restaurant, sorted by their distance to the new restaurant location in ascending order. The function should be optimized to handle up to one million restaurant locations efficiently.\n\n**Input:**\n- A list of tuples `restaurants` where each tuple `(x, y)` represents the coordinates of a restaurant.\n- A tuple `new_location` representing the coordinates of the new restaurant.\n- An integer `k` representing the number of nearest restaurants to find.\n\n**Output:**\n- A list of tuples representing the coordinates of the `k` nearest restaurants, sorted by their distance to the new restaurant location in ascending order.\n\n**Sample Input:**\n```python\nrestaurants = [(1, 2), (4, 6), (8, 1), (3, 4), (7, 7), (2, 5)]\nnew_location = (3, 3)\nk = 3\n```\n\n**Sample Output:**\n```python\n[(3, 4), (4, 6), (2, 5)]\n```", "reference": "import heapq\nimport math\n\ndef find_k_nearest_restaurants(restaurants, new_location, k):\n \"\"\"\n Returns the k nearest restaurants to the new location based on Euclidean distance.\n\n :param restaurants: List of tuples, where each tuple contains the x and y coordinates of a restaurant.\n :param new_location: Tuple containing the x and y coordinates of the new restaurant.\n :param k: Integer representing the number of nearest restaurants to find.\n :return: List of tuples representing the coordinates of the k nearest restaurants.\n \"\"\"\n def euclidean_distance(point1, point2):\n return math.sqrt((point1[0] - point2[0]) ** 2 + (point1[1] - point2[1]) ** 2)\n \n min_heap = []\n for restaurant in restaurants:\n distance = euclidean_distance(restaurant, new_location)\n heapq.heappush(min_heap, (distance, restaurant))\n \n k_nearest = [heapq.heappop(min_heap)[1] for _ in range(k)]\n \n return k_nearest", "tests": ["assert find_k_nearest_restaurants([(1, 1), (2, 2), (3, 3)], (0, 0), 2) == [(1, 1), (2, 2)]", "assert find_k_nearest_restaurants([(1, 1), (2, 2), (3, 3)], (3, 3), 1) == [(3, 3)]", "assert find_k_nearest_restaurants([(0, 0), (1, 1), (2, 2), (3, 3)], (1, 1), 3) == [(1, 1), (0, 0), (2, 2)]", "assert find_k_nearest_restaurants([(1, 2), (4, 6), (8, 1), (3, 4), (7, 7), (2, 5)], (3, 3), 3) == [(3, 4), (2, 5), (4, 6)]", "assert find_k_nearest_restaurants([(1, 1), (1, 1), (1, 1)], (1, 1), 2) == [(1, 1), (1, 1)]", "assert find_k_nearest_restaurants([(1, 1), (2, 2), (3, 3)], (10, 10), 2) == [(3, 3), (2, 2)]", "assert find_k_nearest_restaurants([(0, 0)], (0, 0), 1) == [(0, 0)]", "assert find_k_nearest_restaurants([(1, 2), (3, 4), (5, 6), (7, 8)], (4, 4), 4) == [(3, 4), (5, 6), (1, 2), (7, 8)]", "assert find_k_nearest_restaurants([(1, 1), (2, 2), (3, 3), (4, 4), (5, 5)], (3, 3), 0) == []", "assert find_k_nearest_restaurants([(1, 1), (2, 2), (3, 3), (4, 4), (5, 5)], (3, 3), 5) == [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5)]"], "function": "find_k_nearest_restaurants", "signature": "def find_k_nearest_restaurants(restaurants, new_location, k):", "score": 0.8, "domain": "generic"} {"id": "4a907827ebd1770bc09aad19cc4fc192", "problem": "You are given a list of integers `numbers`. Your task is to implement a function `find_max` that returns the maximum integer in the list. Optimize your function to utilize Python's built-in capabilities for improved performance and readability.\n\n**Sample Input:**\n```python\nnumbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]\n```\n\n**Sample Output:**\n```\n9\n```", "reference": "def find_max(numbers):\n \"\"\"\n Returns the maximum integer in the given list of integers.\n\n :param numbers: List of integers\n :return: Maximum integer in the list\n \"\"\"\n return max(numbers)", "tests": ["assert find_max([1, 2, 3, 4, 5]) == 5", "assert find_max([-1, -2, -3, -4, -5]) == -1", "assert find_max([100]) == 100", "assert find_max([0, 0, 0, 0]) == 0", "assert find_max([5, 4, 3, 2, 1]) == 5", "assert find_max([10, 20, 30, 40, 50, 60, 70, 80, 90, 100]) == 100", "assert find_max([1.5, 2.5, 3.5, 4.5, 5.5]) == 5.5", "assert find_max([-10, -20, -30, -40, -50]) == -10", "assert find_max([1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000]) == 10000", "assert find_max([1000000, 2000000, 3000000, 4000000, 5000000]) == 5000000"], "function": "find_max", "signature": "def find_max(numbers):", "score": 1.0, "domain": "generic"} {"id": "57e1de9c408b685642c999fbbea79d2d", "problem": "You are given a list of integers. Your task is to write a Python function `sum_even_squares` that computes the sum of the squares of all even numbers in the list. Use a generator expression to implement this functionality.\n\n**Input:**\n- A list of integers `numbers` (1 ≤ len(numbers) ≤ 10^5), where each integer `x` satisfies -10^3 ≤ x ≤ 10^3.\n\n**Output:**\n- An integer representing the sum of squares of all even numbers in the list.\n\n**Sample Input:**\n```\n[1, 2, 3, 4, 5, 6]\n```\n\n**Sample Output:**\n```\n56\n```", "reference": "def sum_even_squares(numbers):\n \"\"\"\n Computes the sum of squares of all even numbers in the given list.\n\n :param numbers: List of integers.\n :return: Sum of squares of even numbers.\n \"\"\"\n return sum(x**2 for x in numbers if x % 2 == 0)\n\n# Example usage:\nnumbers = [1, 2, 3, 4, 5, 6]\nresult = sum_even_squares(numbers)\nprint(result) # Output: 56", "tests": ["assert sum_even_squares([1, 2, 3, 4, 5, 6]) == 56", "assert sum_even_squares([0, 1, 2, 3, 4, 5]) == 20", "assert sum_even_squares([10, 15, 20, 25, 30]) == 1000", "assert sum_even_squares([-2, -4, -6, -8]) == 120", "assert sum_even_squares([7, 11, 13, 17]) == 0", "assert sum_even_squares([]) == 0", "assert sum_even_squares([2, 4, 6, 8, 10]) == 220", "assert sum_even_squares([1, 3, 5, 7, 9, 11]) == 0", "assert sum_even_squares([20, 22, 24, 26, 28]) == 4640", "assert sum_even_squares([-1, -3, -5, -7, -9]) == 0"], "function": "sum_even_squares", "signature": "def sum_even_squares(numbers):", "score": 0.8, "domain": "generic"} {"id": "bae0e611b0784959adeccef0e0b6a5e6", "problem": "You are given a dictionary `data` and a string `template`. The dictionary `data` contains key-value pairs where the keys are strings and the values can be of types: dictionary, list, tuple, set, frozenset, or string. The `template` string contains placeholders in the format `%%key%%`, where `key` is a string that corresponds to a key in the `data` dictionary. The placeholders can also include nested keys and array indices, and may have default values specified as `%%key=default_value%%`. Your task is to implement a function `replace_placeholders` that recursively traverses the `data` dictionary and replaces the placeholders in the `template` string with their corresponding values from the `data` dictionary. If a value is a collection (list, tuple, set, frozenset), it should be converted to a comma-separated string. If a key is not found and a default value is specified, the default value should be used.\n\n**Input:**\n- A dictionary `data` with keys as strings and values as dictionary, list, tuple, set, frozenset, or string.\n- A string `template` containing placeholders in the format `%%key%%` or `%%key=default_value%%`.\n\n**Output:**\n- A string with all placeholders replaced by their corresponding values from the `data` dictionary.\n\n**Sample Input:**\n```python\ndata = {'name': 'John', 'age': 30}\ntemplate = 'Hello, %%name%%! You are %%age%% years old.'\n```\n\n**Sample Output:**\n```\n'Hello, John! You are 30 years old.'\n```\n\n**Sample Input:**\n```python\ndata = {'person': {'name': 'John', 'age': 30}}\ntemplate = 'Hello, %%person.name%%! You are %%person.age%% years old.'\n```\n\n**Sample Output:**\n```\n'Hello, John! You are 30 years old.'\n```\n\n**Sample Input:**\n```python\ndata = {'numbers': [1, 2, 3]}\ntemplate = 'The numbers are: %%numbers.0%%, %%numbers.1%%, %%numbers.2%%.'\n```\n\n**Sample Output:**\n```\n'The numbers are: 1, 2, 3.'\n```", "reference": "def replace_placeholders(data, template):\n \"\"\"\n Replaces placeholders in the template string with corresponding values from the data dictionary.\n \n Args:\n data (dict): A dictionary containing key-value pairs.\n template (str): A string containing placeholders in the format %%key%% or %%key=default_value%%.\n \n Returns:\n str: The template string with placeholders replaced by their corresponding values.\n \"\"\"\n def get_value(keys, d):\n try:\n value = d\n for key in keys:\n value = value[key]\n return value\n except (KeyError, IndexError, TypeError):\n return None\n\n def parse_key(key):\n default = None\n if '=' in key:\n key, default = key.split('=', 1)\n keys = key.split('.')\n return keys, default\n\n def replace(match):\n key = match.group(1)\n keys, default = parse_key(key)\n value = get_value(keys, data)\n if value is None:\n value = default\n if isinstance(value, (list, tuple, set, frozenset)):\n value = ', '.join(map(str, value))\n return str(value) if value is not None else ''\n\n import re\n return re.sub(r'%%(.*?)%%', replace, template)", "tests": ["assert replace_placeholders({'name': 'John', 'age': 30}, 'Hello, %%name%%! You are %%age%% years old.') == 'Hello, John! You are 30 years old.'", "assert replace_placeholders({'person': {'name': 'John', 'age': 30}}, 'Hello, %%person.name%%! You are %%person.age%% years old.') == 'Hello, John! You are 30 years old.'", "assert replace_placeholders({'numbers': [1, 2, 3]}, 'The numbers are: %%numbers.0%%, %%numbers.1%%, %%numbers.2%%.') == 'The numbers are: 1, 2, 3.'", "assert replace_placeholders({'numbers': (1, 2, 3)}, 'The numbers are: %%numbers.0%%, %%numbers.1%%, %%numbers.2%%.') == 'The numbers are: 1, 2, 3.'", "assert replace_placeholders({'numbers': {1, 2, 3}}, 'The numbers are: %%numbers.0%%, %%numbers.1%%, %%numbers.2%%.') == 'The numbers are: 1, 2, 3.'", "assert replace_placeholders({'numbers': frozenset([1, 2, 3])}, 'The numbers are: %%numbers.0%%, %%numbers.1%%, %%numbers.2%%.') == 'The numbers are: 1, 2, 3.'", "assert replace_placeholders({'name': 'John'}, 'Hello, %%name%%! You are %%age=30%% years old.') == 'Hello, John! You are 30 years old.'", "assert replace_placeholders({'name': 'John'}, 'Hello, %%name%%! You are %%age=default%% years old.') == 'Hello, John! You are default years old.'", "assert replace_placeholders({'person': {'name': 'John', 'age': 30}}, 'Hello, %%person.name%%! You are %%person.age=default%% years old.') == 'Hello, John! You are 30 years old.'", "assert replace_placeholders({'person': {'name': 'John'}}, 'Hello, %%person.name%%! You are %%person.age=default%% years old.') == 'Hello, John! You are default years old.'"], "function": "replace_placeholders", "signature": "def replace_placeholders(data, template):", "score": 0.6, "domain": "generic"} {"id": "767bf45b25ba3582d282b42f86dce570", "problem": "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.\n\n**Input:**\n- A single string `song_info` (1 ≤ |song_info| ≤ 1000) containing song metadata with BPM values in the format \"BPM:\".\n\n**Output:**\n- An integer representing the highest BPM value found in the metadata.\n\n**Sample Input:**\n```\n\"Title: Example BPM:120 Genre: Rock BPM:125 BPM:110\"\n```\n\n**Sample Output:**\n```\n125\n```", "reference": "def extract_bpm(song_info):\n \"\"\"\n Extracts and returns the highest BPM value from the given song metadata.\n\n :param song_info: A string containing song metadata with BPM values.\n :return: The highest BPM value as an integer.\n \"\"\"\n bpm_values = [s.split(':')[1] for s in song_info.split() if s.startswith('BPM:')]\n bpm_integers = [int(bpm) for bpm in bpm_values]\n return max(bpm_integers)", "tests": ["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\") == 200", "assert extract_bpm(\"BPM:1 BPM:2 BPM:3 BPM:4 BPM:5\") == 5", "assert extract_bpm(\"BPM:300 BPM:250 BPM:200 BPM:150 BPM:100\") == 300", "assert extract_bpm(\"BPM:60\") == 60", "assert extract_bpm(\"Genre: Pop BPM:130 BPM:130 BPM:130 BPM:130\") == 130", "assert extract_bpm(\"BPM:150 BPM:140 BPM:130 BPM:120 BPM:110 BPM:100\") == 150"], "function": "extract_bpm", "signature": "def extract_bpm(song_info):", "score": 1.0, "domain": "generic"} {"id": "b6b0f85b4fa18fc335e861c1c10048f6", "problem": "You are given a dictionary `properties` that maps property names to their expected types. The expected types can be simple data types or nested dictionaries representing complex data structures. You are also given a list `custom_properties` where each element is an object with a `name` and `expected_type` attribute. The `expected_type` attribute can also be a nested dictionary.\n\nWrite a function `get_property_type(property_name, properties, custom_properties)` that returns the expected type of a given property name. If the property name is found in the `properties` dictionary, return its corresponding value. If the property name is not found in the `properties` dictionary, iterate through the `custom_properties` list and return the `expected_type` of the first object whose `name` attribute matches the given `property_name`. If no match is found, return the string `\"unknown\"`. If the `expected_type` is a nested dictionary, return a flattened representation of the types, where each key in the dictionary is prefixed with the property name and a dot (e.g., `{\"name\": \"person\", \"expected_type\": {\"age\": \"int\", \"details\": {\"address\": \"str\"}}}` would be represented as `{\"person.age\": \"int\", \"person.details.address\": \"str\"}`).\n\n**Sample Input:**\n```python\nproperties = {\"name\": \"str\", \"age\": \"int\"}\ncustom_properties = [\n {\"name\": \"person\", \"expected_type\": {\"age\": \"int\", \"details\": {\"address\": \"str\"}}},\n {\"name\": \"employee\", \"expected_type\": {\"id\": \"int\", \"department\": \"str\"}}\n]\nproperty_name = \"person\"\n```\n\n**Sample Output:**\n```python\n{\"person.age\": \"int\", \"person.details.address\": \"str\"}\n```", "reference": "def flatten_dict(d, parent_key='', sep='.'):\n \"\"\"\n Flattens a nested dictionary into a single-level dictionary with keys separated by dots.\n \n :param d: The dictionary to flatten.\n :param parent_key: The base key string for recursion (used internally).\n :param sep: The separator to use between keys.\n :return: A flattened dictionary.\n \"\"\"\n items = []\n for k, v in d.items():\n new_key = f\"{parent_key}{sep}{k}\" if parent_key else k\n if isinstance(v, dict):\n items.extend(flatten_dict(v, new_key, sep=sep).items())\n else:\n items.append((new_key, v))\n return dict(items)\n\ndef get_property_type(property_name, properties, custom_properties):\n \"\"\"\n Returns the expected type of a given property name, considering both the properties dictionary\n and the custom_properties list. If the property is not found, returns \"unknown\". If the expected\n type is a nested dictionary, returns a flattened representation of the types.\n \n :param property_name: The name of the property to look up.\n :param properties: A dictionary mapping property names to their expected types.\n :param custom_properties: A list of objects with 'name' and 'expected_type' attributes.\n :return: The expected type of the property, or \"unknown\" if not found.\n \"\"\"\n if property_name in properties:\n property_type = properties[property_name]\n if isinstance(property_type, dict):\n return flatten_dict({property_name: property_type})\n return property_type\n \n for custom_property in custom_properties:\n if custom_property.name == property_name:\n expected_type = custom_property.expected_type\n if isinstance(expected_type, dict):\n return flatten_dict({property_name: expected_type})\n return expected_type\n \n return \"unknown\"", "tests": ["assert get_property_type(\"age\", {\"age\": \"int\"}, []) == \"int\"", "assert get_property_type(\"name\", {}, [{\"name\": \"name\", \"expected_type\": \"str\"}]) == \"str\"", "assert get_property_type(\"height\", {\"height\": \"float\"}, [{\"name\": \"weight\", \"expected_type\": \"float\"}]) == \"float\"", "assert get_property_type(\"address\", {}, [{\"name\": \"address\", \"expected_type\": {\"street\": \"str\", \"city\": \"str\"}}]) == {\"address.street\": \"str\", \"address.city\": \"str\"}", "assert get_property_type(\"unknown\", {}, []) == \"unknown\"", "assert get_property_type(\"user\", {\"user\": {\"id\": \"int\", \"name\": \"str\"}}, []) == {\"user.id\": \"int\", \"user.name\": \"str\"}", "assert get_property_type(\"profile\", {}, [{\"name\": \"profile\", \"expected_type\": {\"bio\": \"str\", \"settings\": {\"theme\": \"str\"}}}]) == {\"profile.bio\": \"str\", \"profile.settings.theme\": \"str\"}", "assert get_property_type(\"email\", {\"email\": \"str\"}, [{\"name\": \"email\", \"expected_type\": \"str\"}]) == \"str\"", "assert get_property_type(\"role\", {}, [{\"name\": \"role\", \"expected_type\": {\"permissions\": {\"read\": \"bool\", \"write\": \"bool\"}}}]) == {\"role.permissions.read\": \"bool\", \"role.permissions.write\": \"bool\"}", "assert get_property_type(\"status\", {\"status\": \"active\"}, [{\"name\": \"status\", \"expected_type\": \"inactive\"}]) == \"active\""], "function": "get_property_type", "signature": "def get_property_type(property_name, properties, custom_properties):", "score": 0.6, "domain": "generic"} {"id": "370dc1d70c4974aeafeb2f8386f1f1db", "problem": "You are given a list of strings. Your task is to implement a function `custom_sort` that sorts these strings based on the number of vowels they contain. If two strings have the same number of vowels, they should be sorted lexicographically. The function should be case-insensitive with respect to vowels and return a new sorted list.\n\n**Input:**\n- A list of strings `strings` (1 ≤ len(strings) ≤ 1000), where each string consists of at most 100 characters.\n\n**Output:**\n- A new list of strings sorted according to the specified criteria.\n\n**Sample Input:**\n```python\n[\"hello\", \"world\", \"AEIOU\", \"bcd\", \"algorithm\"]\n```\n\n**Sample Output:**\n```python\n[\"bcd\", \"world\", \"hello\", \"algorithm\", \"AEIOU\"]\n```", "reference": "def custom_sort(strings):\n \"\"\"\n Sorts a list of strings based on the number of vowels in each string.\n If two strings have the same number of vowels, they are sorted lexicographically.\n \n :param strings: List of strings to be sorted.\n :return: A new list of strings sorted according to the specified criteria.\n \"\"\"\n def count_vowels(s):\n vowels = set('aeiouAEIOU')\n return sum(1 for char in s if char in vowels)\n\n return sorted(strings, key=lambda s: (count_vowels(s), s))", "tests": ["assert custom_sort([\"apple\", \"banana\", \"cherry\"]) == [\"banana\", \"apple\", \"cherry\"]", "assert custom_sort([\"dog\", \"cat\", \"elephant\"]) == [\"cat\", \"dog\", \"elephant\"]", "assert custom_sort([\"umbrella\", \"sky\", \"fly\"]) == [\"fly\", \"sky\", \"umbrella\"]", "assert custom_sort([\"\", \"a\", \"e\", \"i\", \"o\", \"u\"]) == [\"\", \"a\", \"e\", \"i\", \"o\", \"u\"]", "assert custom_sort([\"AEIOU\", \"bcdfg\", \"\"]) == [\"AEIOU\", \"\", \"bcdfg\"]", "assert custom_sort([\"hello\", \"HELLO\", \"world\", \"WORLD\"]) == [\"HELLO\", \"hello\", \"world\", \"WORLD\"]", "assert custom_sort([\"beautiful\", \"umbrella\", \"aerodynamics\"]) == [\"beautiful\", \"umbrella\", \"aerodynamics\"]", "assert custom_sort([\"xyz\", \"bcd\", \"mnp\"]) == [\"bcd\", \"mnp\", \"xyz\"]", "assert custom_sort([\"a\", \"aa\", \"aaa\", \"aaaa\"]) == [\"a\", \"aa\", \"aaa\", \"aaaa\"]", "assert custom_sort([\"AeIoU\", \"aeiou\", \"AEIOUaeiou\"]) == [\"AeIoU\", \"aeiou\", \"AEIOUaeiou\"]"], "function": "custom_sort", "signature": "def custom_sort(strings):", "score": 0.6, "domain": "generic"} {"id": "eff45fa67fc3c96fd35fd73fed0a169b", "problem": "You are given an integer `limit`. Your task is to write a function `find_largest_prime(limit)` that returns the largest prime number less than or equal to `limit`. If no such prime number exists, return `None`. A prime number is defined as a natural number greater than 1 that has no positive divisors other than 1 and itself.\n\n**Input:**\n- An integer `limit` (1 ≤ limit ≤ 10^6)\n\n**Output:**\n- The largest prime number less than or equal to `limit`, or `None` if no such prime exists.\n\n**Sample Input:**\n```\n10\n```\n\n**Sample Output:**\n```\n7\n```\n\n**Sample Input:**\n```\n1\n```\n\n**Sample Output:**\n```\nNone\n```", "reference": "def find_largest_prime(limit):\n \"\"\"\n Returns the largest prime number less than or equal to the given limit.\n If no such prime number exists, returns None.\n \n :param limit: An integer representing the upper limit.\n :return: The largest prime number less than or equal to limit, or None.\n \"\"\"\n def is_prime(n):\n \"\"\"\n Checks if a number is prime.\n \n :param n: An integer to check for primality.\n :return: True if n is prime, False otherwise.\n \"\"\"\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == 0 or n % 3 == 0:\n return False\n i = 5\n while i * i <= n:\n if n % i == 0 or n % (i + 2) == 0:\n return False\n i += 6\n return True\n \n for num in range(limit, 1, -1):\n if is_prime(num):\n return num\n return None", "tests": ["assert find_largest_prime(10) == 7", "assert find_largest_prime(20) == 19", "assert find_largest_prime(1) == None", "assert find_largest_prime(2) == 2", "assert find_largest_prime(18) == 17", "assert find_largest_prime(0) == None", "assert find_largest_prime(29) == 29", "assert find_largest_prime(100) == 97", "assert find_largest_prime(4) == 3", "assert find_largest_prime(15) == 13"], "function": "find_largest_prime", "signature": "def find_largest_prime(limit):", "score": 1.0, "domain": "generic"} {"id": "63b35c8205752bf603d6410a2ff9146c", "problem": "You are given a list of sentences, where each sentence is represented as a list of words. Your task is to enrich each sentence by appending the antonyms of each word to the sentence. Each antonym should be added only once per sentence, and if a word does not have any antonyms, it should remain unchanged.\n\n**Input:**\n- `sentences`: A list of lists of strings, where each inner list represents a sentence.\n- `antonyms_dict`: A dictionary mapping each word to a list of its antonyms.\n\n**Output:**\n- A list of lists of strings, where each inner list is an enriched sentence with antonyms added according to the rules.\n\n**Constraints:**\n- Each word in the sentences is a non-empty string consisting of lowercase English letters.\n- The dictionary may not contain all words from the sentences.\n\n**Sample Input:**\n```python\nsentences = [[\"happy\", \"dog\"], [\"quick\", \"brown\", \"fox\"]]\nantonyms_dict = {\n \"happy\": [\"sad\", \"unhappy\"],\n \"dog\": [\"cat\"],\n \"quick\": [\"slow\"],\n \"brown\": [\"light\"],\n \"fox\": [\"hare\"]\n}\n```\n\n**Sample Output:**\n```python\n[['happy', 'sad', 'unhappy', 'dog', 'cat'], ['quick', 'slow', 'brown', 'light', 'fox', 'hare']]\n```", "reference": "def antonym_enrichment(sentences, antonyms_dict):\n \"\"\"\n Enriches each sentence by appending antonyms of each word, ensuring no antonym is added more than once per sentence.\n \n :param sentences: List of lists of strings, where each inner list is a sentence.\n :param antonyms_dict: Dictionary mapping each word to a list of its antonyms.\n :return: List of lists of strings, where each inner list is an enriched sentence.\n \"\"\"\n enriched_sentences = []\n for sentence in sentences:\n enriched_sentence = []\n added_antonyms = set()\n for word in sentence:\n enriched_sentence.append(word)\n if word in antonyms_dict:\n for antonym in antonyms_dict[word]:\n if antonym not in added_antonyms and antonym not in enriched_sentence:\n enriched_sentence.append(antonym)\n added_antonyms.add(antonym)\n enriched_sentences.append(enriched_sentence)\n return enriched_sentences", "tests": ["assert antonym_enrichment([[\"happy\", \"dog\"]], {\"happy\": [\"sad\", \"unhappy\"], \"dog\": [\"cat\"]}) == [[\"happy\", \"sad\", \"unhappy\", \"dog\", \"cat\"]]", "assert antonym_enrichment([[\"quick\", \"brown\", \"fox\"]], {\"quick\": [\"slow\"], \"brown\": [\"light\"], \"fox\": [\"hare\"]}) == [[\"quick\", \"slow\", \"brown\", \"light\", \"fox\", \"hare\"]]", "assert antonym_enrichment([[\"big\", \"small\"]], {\"big\": [\"small\"], \"small\": [\"big\"]}) == [[\"big\", \"small\"], [\"small\", \"big\"]]", "assert antonym_enrichment([[\"fast\", \"slow\"]], {\"fast\": [\"slow\"], \"slow\": [\"fast\"]}) == [[\"fast\", \"slow\"], [\"slow\", \"fast\"]]", "assert antonym_enrichment([[\"good\", \"bad\"]], {\"good\": [\"bad\"], \"bad\": [\"good\"]}) == [[\"good\", \"bad\"], [\"bad\", \"good\"]]", "assert antonym_enrichment([[\"hot\", \"cold\"]], {\"hot\": [\"cold\"], \"cold\": [\"hot\"]}) == [[\"hot\", \"cold\"], [\"cold\", \"hot\"]]", "assert antonym_enrichment([[\"happy\"]], {\"happy\": [\"sad\", \"unhappy\"]}) == [[\"happy\", \"sad\", \"unhappy\"]]", "assert antonym_enrichment([[\"dog\"]], {\"dog\": [\"cat\"]}) == [[\"dog\", \"cat\"]]", "assert antonym_enrichment([[\"happy\", \"dog\"], [\"quick\", \"brown\", \"fox\"]], {}) == [[\"happy\", \"dog\"], [\"quick\", \"brown\", \"fox\"]]", "assert antonym_enrichment([], {\"happy\": [\"sad\", \"unhappy\"], \"dog\": [\"cat\"]}) == []"], "function": "antonym_enrichment", "signature": "def antonym_enrichment(sentences, antonyms_dict):", "score": 0.6, "domain": "generic"} {"id": "240e6b59d74bc486af6e58d150ed6072", "problem": "You are given a 5x5 grid where each cell is identified by its coordinates (x, y), with the top-left cell at (0, 0) and the bottom-right cell at (4, 4). The grid contains obstacles, represented as a list of coordinates. Your task is to determine the shortest distance from any obstacle to the rightmost column (x-coordinate 4). The distance is calculated as the number of steps taken to reach the rightmost column, where a step can be a move to an adjacent cell in any of the eight possible directions (horizontally, vertically, or diagonally). If there are no obstacles, return 0.\n\n**Input:**\n- A list of tuples, where each tuple represents the coordinates of an obstacle in the grid.\n\n**Output:**\n- An integer representing the shortest distance from any obstacle to the rightmost column. If no obstacles are present, return 0.\n\n**Sample Input:**\n```\n[(0, 1), (1, 3), (2, 2)]\n```\n\n**Sample Output:**\n```\n2\n```", "reference": "from collections import deque\n\ndef shortest_distance_to_rightmost(obstacles):\n \"\"\"\n Calculate the shortest distance from any obstacle to the rightmost column in a 5x5 grid.\n \n :param obstacles: List of tuples representing the coordinates of obstacles.\n :return: Integer representing the shortest distance to the rightmost column.\n \"\"\"\n # Define the grid size\n N = 5\n \n # Create a grid with obstacles\n grid = [[0] * N for _ in range(N)]\n for x, y in obstacles:\n grid[x][y] = 1\n \n # Define possible movements (8 directions)\n directions = [(-1, 0), (1, 0), (0, -1), (0, 1),\n (-1, -1), (-1, 1), (1, -1), (1, 1)]\n \n # Initialize the visited set and the queue for BFS\n visited = set()\n queue = deque()\n \n # Add all obstacles to the visited set and queue\n for x, y in obstacles:\n visited.add((x, y))\n queue.append((x, y, 0)) # (x, y, current_distance)\n \n # If there are no obstacles, return 0\n if not queue:\n return 0\n \n # Perform BFS\n while queue:\n x, y, d = queue.popleft()\n \n # If we have reached the rightmost column, return the distance\n if x == 4:\n return d\n \n # Explore all possible directions\n for dx, dy in directions:\n nx, ny = x + dx, y + dy\n \n # Check if the new position is within the grid bounds and not visited\n if 0 <= nx < N and 0 <= ny < N and (nx, ny) not in visited:\n visited.add((nx, ny))\n queue.append((nx, ny, d + 1))\n \n # If we exhaust the queue without finding a path to the rightmost column, return -1 (not reachable)\n # However, the problem definition suggests that there will always be a reachable path given there's at least one obstacle\n return -1\n\n# Example usage:\nobstacles = [(0, 1), (1, 3), (2, 2)]\nprint(shortest_distance_to_rightmost(obstacles)) # Output: 2", "tests": ["assert shortest_distance_to_rightmost([(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]) == 4", "assert shortest_distance_to_rightmost([(4, 0), (4, 1), (4, 2), (4, 3), (4, 4)]) == 0", "assert shortest_distance_to_rightmost([(0, 4), (1, 4), (2, 4), (3, 4), (4, 4)]) == 0", "assert shortest_distance_to_rightmost([(0, 0)]) == 4", "assert shortest_distance_to_rightmost([(0, 4)]) == 0", "assert shortest_distance_to_rightmost([(0, 3), (1, 3), (2, 3), (3, 3)]) == 1", "assert shortest_distance_to_rightmost([(0, 2), (1, 2), (2, 2), (3, 2)]) == 2", "assert shortest_distance_to_rightmost([(0, 1), (1, 1), (2, 1), (3, 1)]) == 3", "assert shortest_distance_to_rightmost([]) == 0", "assert shortest_distance_to_rightmost([(0, 0), (0, 1), (0, 2), (0, 3)]) == 4"], "function": "shortest_distance_to_rightmost", "signature": "def shortest_distance_to_rightmost(obstacles):", "score": 0.6, "domain": "generic"} {"id": "bc92788595723875c3d5c55d853ecb0a", "problem": "You are tasked with implementing a function to validate email addresses. Your function should determine if a given string is a valid email address based on a specific pattern. A valid email address must adhere to the following rules:\n- It consists of a username, an \"@\" symbol, a domain name, and a top-level domain.\n- The username can include lowercase letters, digits, dots, underscores, and hyphens.\n- The domain name can include lowercase letters, digits, and hyphens.\n- The top-level domain must be between 2 and 3 lowercase letters.\n\nWrite a function `validate_email` that takes a single string argument `email` and returns `True` if the email is valid, and `False` otherwise.\n\n**Sample Input:**\n```\ntest@example.com\ninvalid-email\nuser.name@domain.co\nuser_name@domain.com\nuser-name@domain.co.uk\n```\n\n**Sample Output:**\n```\nTrue\nFalse\nTrue\nTrue\nFalse\n```", "reference": "import re\n\ndef validate_email(email):\n \"\"\"\n Validates an email address based on a specific pattern.\n\n Parameters:\n email (str): The email address to validate.\n\n Returns:\n bool: True if the email is valid, False otherwise.\n \"\"\"\n regex = r'^[a-z0-9]+[\\._-]?[a-z0-9]+[@][a-z0-9-]+[.][a-z]{2,3}$'\n return re.match(regex, email) is not None", "tests": ["assert validate_email(\"test@example.com\") == True", "assert validate_email(\"user.name+tag+sorting@example.com\") == True", "assert validate_email(\"user@sub.example.com\") == True", "assert validate_email(\"user@123.123.123.123\") == True", "assert validate_email(\"user@[IPv6:2001:db8::1]\") == False", "assert validate_email(\"plainaddress\") == False", "assert validate_email(\"@missingusername.com\") == False", "assert validate_email(\"username@.com\") == False", "assert validate_email(\"username@com\") == False", "assert validate_email(\"username@domain..com\") == False"], "function": "validate_email", "signature": "def validate_email(email):", "score": 0.7, "domain": "generic"} {"id": "e1fea12c342bb4ebe92c3cbeb63cd720", "problem": "You are given a positive integer `n`. Your task is to compute the sum of the first `n` Fibonacci numbers and return the result modulo `1,000,000,007`.\n\n**Input:**\n- The first line contains a single integer `n` (0 ≤ n ≤ 10^6).\n\n**Output:**\n- Print a single integer, the sum of the first `n` Fibonacci numbers modulo `1,000,000,007`.\n\n**Sample Input:**\n```\n10\n```\n\n**Sample Output:**\n```\n88\n```", "reference": "def fibo_sum(n):\n \"\"\"\n Computes the sum of the first n Fibonacci numbers modulo 1,000,000,007.\n\n Parameters:\n n (int): The number of Fibonacci numbers to sum.\n\n Returns:\n int: The sum of the first n Fibonacci numbers modulo 1,000,000,007.\n \"\"\"\n if n == 0:\n return 0\n elif n == 1:\n return 1\n \n a, b = 0, 1\n total_sum = a + b\n \n for _ in range(2, n):\n a, b = b, (a + b) % 1000000007\n total_sum = (total_sum + b) % 1000000007\n \n return total_sum\n\n# Example usage:\n# print(fibo_sum(10)) # Output: 88", "tests": ["assert fibo_sum(0) == 0", "assert fibo_sum(1) == 1", "assert fibo_sum(2) == 1", "assert fibo_sum(3) == 2", "assert fibo_sum(4) == 4", "assert fibo_sum(5) == 7", "assert fibo_sum(10) == 88", "assert fibo_sum(20) == 10946", "assert fibo_sum(50) == 12586269025 % 1000000007", "assert fibo_sum(100) == 354224848179261915075 % 1000000007"], "function": "fibo_sum", "signature": "def fibo_sum(n):", "score": 0.7, "domain": "generic"} {"id": "f7a70039716c3a9036ec8cc3a672d206", "problem": "You are given a dictionary `input_dict` and a function `func`. Your task is to implement a function `apply_to_dict_values` that applies `func` to each numeric value in `input_dict` and returns a new dictionary with the same keys and transformed values. Non-numeric values should be excluded from the resulting dictionary. Numeric values are defined as integers, floats, and complex numbers.\n\n**Sample Input:**\n```python\ninput_dict = {'a': 10, 'b': 'hello', 'c': 3.14, 'd': 2+3j}\nfunc = lambda x: x * 2\n```\n\n**Sample Output:**\n```python\n{'a': 20, 'c': 6.28, 'd': (4+6j)}\n```", "reference": "def apply_to_dict_values(input_dict, func):\n \"\"\"\n Apply a given function to the numeric values in a dictionary, filtering out non-numeric values.\n \n :param input_dict: Dictionary with keys and values\n :param func: Function to apply to each numeric value, should accept a single numeric argument\n :return: New dictionary with keys from input_dict and transformed numeric values\n \"\"\"\n return {key: func(value) for key, value in input_dict.items() if isinstance(value, (int, float, complex))}", "tests": ["assert apply_to_dict_values({\"a\": 1, \"b\": 2, \"c\": \"three\"}, lambda x: x * 2) == {\"a\": 2, \"b\": 4}", "assert apply_to_dict_values({\"x\": 10, \"y\": \"20\", \"z\": 30}, lambda x: x + 5) == {\"x\": 15, \"z\": 35}", "assert apply_to_dict_values({\"key1\": 1.5, \"key2\": 2.5, \"key3\": \"value\"}, lambda x: x * 3) == {\"key1\": 4.5, \"key2\": 7.5}", "assert apply_to_dict_values({\"num1\": 100, \"num2\": 200, \"num3\": 300}, lambda x: x / 10) == {\"num1\": 10.0, \"num2\": 20.0, \"num3\": 30.0}", "assert apply_to_dict_values({\"a\": 1+2j, \"b\": 3+4j, \"c\": \"not a number\"}, lambda x: x.real) == {\"a\": 1.0, \"b\": 3.0}", "assert apply_to_dict_values({\"one\": 1, \"two\": 2, \"three\": 3}, lambda x: x - 1) == {\"one\": 0, \"two\": 1, \"three\": 2}", "assert apply_to_dict_values({\"key\": 10, \"value\": \"ten\"}, lambda x: x * 10) == {\"key\": 100}", "assert apply_to_dict_values({}, lambda x: x + 1) == {}", "assert apply_to_dict_values({\"a\": 1, \"b\": 2, \"c\": 3}, lambda x: x ** 2) == {\"a\": 1, \"b\": 4, \"c\": 9}", "assert apply_to_dict_values({\"num\": 5, \"str\": \"hello\", \"float\": 5.5}, lambda x: x + 0.5) == {\"num\": 5.5, \"float\": 6.0}"], "function": "apply_to_dict_values", "signature": "def apply_to_dict_values(input_dict, func):", "score": 1.0, "domain": "generic"} {"id": "2319ff8845a9e4e0ecd97c1a0ac008a6", "problem": "You are given a list of integers. Your task is to write a Python function `find_duplicate_numbers` that identifies all numbers in the list that occur more than once and returns a list of these duplicate numbers. The function should be optimized to handle large input sizes efficiently.\n\n**Input:**\n- A list of integers `numbers` (1 ≤ len(numbers) ≤ 10^6, -10^9 ≤ numbers[i] ≤ 10^9).\n\n**Output:**\n- A list of integers that are duplicates in the input list. The order of elements in the output list does not matter.\n\n**Sample Input:**\n```\n[1, 3, 4, 2, 5, 3, 1, 6, 7, 8, 8, 9]\n```\n\n**Sample Output:**\n```\n[1, 3, 8]\n```", "reference": "def find_duplicate_numbers(numbers):\n \"\"\"\n Identifies all numbers in the list that occur more than once and returns a list of these duplicate numbers.\n \n :param numbers: List of integers\n :return: List of integers that are duplicates in the input list\n \"\"\"\n # Dictionary to store the count of each number\n counts = {}\n # List to store duplicate numbers\n duplicates = []\n \n # Count occurrences of each number in the list\n for number in numbers:\n if number in counts:\n counts[number] += 1\n else:\n counts[number] = 1\n \n # Collect numbers that occur more than once\n for number, count in counts.items():\n if count > 1:\n duplicates.append(number)\n \n return duplicates\n\n# Example usage\nnumbers = [1, 3, 4, 2, 5, 3, 1, 6, 7, 8, 8, 9]\nprint(find_duplicate_numbers(numbers)) # Output: [1, 3, 8]", "tests": ["assert find_duplicate_numbers([1, 2, 3, 4, 5]) == []", "assert find_duplicate_numbers([1, 1, 2, 2, 3, 3]) == [1, 2, 3]", "assert find_duplicate_numbers([10, 20, 10, 30, 20, 40]) == [10, 20]", "assert find_duplicate_numbers([5, 5, 5, 5, 5]) == [5]", "assert find_duplicate_numbers([]) == []", "assert find_duplicate_numbers([1]) == []", "assert find_duplicate_numbers([1, 2, 3, 4, 5, 6, 7, 8, 9, 1]) == [1]", "assert find_duplicate_numbers([1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3]) == [1, 2, 3]", "assert find_duplicate_numbers([100, 200, 300, 400, 500, 100, 200, 600]) == [100, 200]", "assert find_duplicate_numbers([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 1]) == [1]"], "function": "find_duplicate_numbers", "signature": "def find_duplicate_numbers(numbers):", "score": 1.0, "domain": "generic"} {"id": "c9be62e2ff1bd13fc2a970645a72e7cc", "problem": "You are tasked with implementing a function `FibonacciSum` that computes the sum of the first `n` terms in the Fibonacci sequence using a recursive approach. The Fibonacci sequence is defined as follows: `F(0) = 0`, `F(1) = 1`, and `F(n) = F(n-1) + F(n-2)` for `n >= 2`. Your function should raise a `ValueError` with the message \"n must be positive\" if `n` is less than 1, and a `TypeError` with the message \"n must be type int\" if `n` is not an integer.\n\n**Sample Input:**\n```\nn = 5\n```\n\n**Sample Output:**\n```\n12\n```", "reference": "def FibonacciSum(n):\n \"\"\"\n Calculate the sum of the first n terms in the Fibonacci sequence using recursion.\n \n Parameters:\n n (int): The number of terms in the Fibonacci sequence to sum.\n \n Returns:\n int: The sum of the first n Fibonacci numbers.\n \n Raises:\n ValueError: If n is less than 1.\n TypeError: If n is not an integer.\n \"\"\"\n if not isinstance(n, int):\n raise TypeError(\"n must be type int\")\n if n < 1:\n raise ValueError(\"n must be positive\")\n \n def fibonacci_recursive(k):\n if k <= 0:\n return 0\n elif k == 1:\n return 1\n else:\n return fibonacci_recursive(k - 1) + fibonacci_recursive(k - 2)\n \n total_sum = sum(fibonacci_recursive(i) for i in range(1, n + 1))\n return total_sum", "tests": ["assert FibonacciSum(1) == 1", "assert FibonacciSum(2) == 2", "assert FibonacciSum(3) == 4", "assert FibonacciSum(4) == 7", "assert FibonacciSum(5) == 12", "assert FibonacciSum(6) == 20", "assert FibonacciSum(7) == 33", "assert FibonacciSum(8) == 54", "assert FibonacciSum(9) == 88", "assert FibonacciSum(10) == 143"], "function": "FibonacciSum", "signature": "def FibonacciSum(n):", "score": 1.0, "domain": "generic"} {"id": "ea7ac6e9be347d9f976025955e2dee16", "problem": "You are given a text file containing a body of text. Your task is to write a program that reads the file, counts the frequency of each word, and outputs the top 10 most common words, excluding common stopwords and words shorter than 3 characters. Words should be considered case-insensitive.\n\n**Input:**\n- A text file named `sample_text.txt` containing the text to be analyzed.\n\n**Output:**\n- The top 10 most common words and their frequencies, each on a new line in the format `word: count`.\n\n**Sample Input:**\n```\nThe quick brown fox jumps over the lazy dog. The dog was not amused.\n```\n\n**Sample Output:**\n```\nthe: 2\ndog: 2\nquick: 1\nbrown: 1\nfox: 1\njumps: 1\nover: 1\nlazy: 1\nwas: 1\nnot: 1\n```", "reference": "import re\nfrom collections import Counter\n\ndef word_frequency_analysis(file_path):\n \"\"\"\n Analyzes the frequency of words in a given text file, excluding common stopwords and words shorter than 3 characters.\n \n Parameters:\n file_path (str): The path to the text file to be analyzed.\n \n Returns:\n None: Prints the top 10 most common words and their counts.\n \"\"\"\n # Define common stopwords to be removed\n stopwords = set([\n \"the\", \"and\", \"is\", \"in\", \"at\", \"which\", \"on\", \"for\", \"with\", \"a\", \"an\",\n \"as\", \"by\", \"to\", \"it\", \"from\", \"this\", \"that\", \"these\", \"those\", \"but\", \n \"or\", \"if\", \"then\", \"else\", \"when\", \"where\", \"why\", \"how\", \"all\", \"any\", \n \"both\", \"each\", \"few\", \"more\", \"most\", \"other\", \"some\", \"such\", \"no\", \n \"nor\", \"not\", \"only\", \"own\", \"same\", \"so\", \"than\", \"too\", \"very\", \"s\", \n \"t\", \"can\", \"will\", \"just\", \"don\", \"should\", \"now\", \"d\"\n ])\n \n # Open the file and read the content\n with open(file_path, 'r') as file:\n text = file.read()\n \n # Convert text to lowercase\n text = text.lower()\n \n # Use regex to extract words\n words = re.findall(r'\\b\\w+\\b', text)\n \n # Filter out stopwords and words shorter than 3 characters\n words = [word for word in words if word not in stopwords and len(word) >= 3]\n \n # Count word frequency\n word_counts = Counter(words)\n \n # Get the top 10 most common words\n top_10_words = word_counts.most_common(10)\n \n # Print the top 10 words and their counts\n for word, count in top_10_words:\n print(f'{word}: {count}')\n\n# Specify the path to the text file\nfile_path = 'sample_text.txt'\nword_frequency_analysis(file_path)", "tests": ["assert word_frequency_analysis('empty.txt') == None", "assert word_frequency_analysis('single_word.txt') == None", "assert word_frequency_analysis('stopwords_only.txt') == None", "assert word_frequency_analysis('short_words.txt') == None", "assert word_frequency_analysis('mixed_content.txt') == None", "assert word_frequency_analysis('repeated_words.txt') == None", "assert word_frequency_analysis('punctuation.txt') == None", "assert word_frequency_analysis('case_sensitive.txt') == None", "assert word_frequency_analysis('large_text.txt') == None", "assert word_frequency_analysis('non_existent_file.txt') == None"], "function": "word_frequency_analysis", "signature": "def word_frequency_analysis(file_path):", "score": 0.4, "domain": "generic"} {"id": "b5464bc75abf902a566e265b7a311786", "problem": "You are given a list of integers. Your task is to write a Python function that returns a new list containing only the unique integers from the original list, preserving their order of first appearance. You must implement this functionality without using any built-in Python functions such as `set` or `dict.fromkeys`. Use only basic loops and data structures to solve this problem.\n\n**Sample Input:**\n```\n[1, 2, 2, 3, 4, 4, 5]\n```\n\n**Sample Output:**\n```\n[1, 2, 3, 4, 5]\n```", "reference": "def unique_integers_preserve_order(numbers):\n \"\"\"\n Returns a list of unique integers from the input list while preserving their original order.\n \n :param numbers: List of integers\n :return: List of unique integers\n \"\"\"\n seen = []\n unique_numbers = []\n \n for number in numbers:\n is_unique = True\n for seen_number in seen:\n if number == seen_number:\n is_unique = False\n break\n if is_unique:\n unique_numbers.append(number)\n seen.append(number)\n \n return unique_numbers\n\n# Example usage:\ninput_list = [1, 2, 2, 3, 4, 4, 5]\noutput_list = unique_integers_preserve_order(input_list)\nprint(output_list) # Output: [1, 2, 3, 4, 5]", "tests": ["assert unique_integers_preserve_order([1, 2, 2, 3, 4, 4, 5]) == [1, 2, 3, 4, 5]", "assert unique_integers_preserve_order([10, 20, 20, 10, 30]) == [10, 20, 30]", "assert unique_integers_preserve_order([5, 5, 5, 5, 5]) == [5]", "assert unique_integers_preserve_order([]) == []", "assert unique_integers_preserve_order([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]", "assert unique_integers_preserve_order([7, 8, 9, 7, 10, 9, 11]) == [7, 8, 9, 10, 11]", "assert unique_integers_preserve_order([100, 200, 100, 200, 300, 300, 400]) == [100, 200, 300, 400]", "assert unique_integers_preserve_order([1, 1, 1, 2, 2, 2, 3, 3, 3]) == [1, 2, 3]", "assert unique_integers_preserve_order([1, 3, 2, 3, 1, 4, 5, 4]) == [1, 3, 2, 4, 5]", "assert unique_integers_preserve_order([-1, -2, -3, -2, -1, 0]) == [-1, -2, -3, 0]"], "function": "unique_integers_preserve_order", "signature": "def unique_integers_preserve_order(numbers):", "score": 1.0, "domain": "generic"} {"id": "01718e219ef7970348b1c55e9fae0f34", "problem": "You are tasked with implementing a function to generate the Fibonacci sequence up to the `n`th term. The Fibonacci sequence is defined as follows: the first term is 0, the second term is 1, and each subsequent term is the sum of the two preceding ones. Your function should return a list containing the Fibonacci sequence up to the `n`th term.\n\n**Input:**\n- An integer `n` (1 ≤ n ≤ 50), representing the number of terms in the Fibonacci sequence to generate.\n\n**Output:**\n- A list of integers, where each integer represents a term in the Fibonacci sequence up to the `n`th term.\n\n**Sample Input:**\n```\n10\n```\n\n**Sample Output:**\n```\n[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]\n```", "reference": "def generate_fibonacci(n):\n \"\"\"\n Generate a list containing the Fibonacci sequence up to the nth term.\n\n Parameters:\n n (int): The number of terms in the Fibonacci sequence to generate.\n\n Returns:\n list: A list of integers representing the Fibonacci sequence up to the nth term.\n \"\"\"\n if n <= 0:\n return [] # Return an empty list for non-positive input\n elif n == 1:\n return [0] # The first term of the Fibonacci sequence is 0\n elif n == 2:\n return [0, 1] # The first two terms of the Fibonacci sequence are 0 and 1\n \n # Start the list with the first two terms\n fib_sequence = [0, 1]\n \n # Generate the Fibonacci sequence up to the nth term\n for i in range(2, n):\n next_term = fib_sequence[-1] + fib_sequence[-2] # Sum of the last two terms\n fib_sequence.append(next_term)\n \n return fib_sequence", "tests": ["assert generate_fibonacci(0) == []", "assert generate_fibonacci(1) == [0]", "assert generate_fibonacci(2) == [0, 1]", "assert generate_fibonacci(3) == [0, 1, 1]", "assert generate_fibonacci(5) == [0, 1, 1, 2, 3]", "assert generate_fibonacci(10) == [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]", "assert generate_fibonacci(15) == [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377]", "assert generate_fibonacci(-5) == []", "assert generate_fibonacci(1) == [0]", "assert generate_fibonacci(6) == [0, 1, 1, 2, 3, 5]"], "function": "generate_fibonacci", "signature": "def generate_fibonacci(n):", "score": 1.0, "domain": "algorithmic"} {"id": "9ecffea2dc45fa6f53c5c2f891407c36", "problem": "You are given a start date and a timezone representing the beginning of a work year. Your task is to write a function `calculate_current_work_week` that computes the current work week number based on the provided start date and timezone. The work week starts on the start date and each subsequent week is a 7-day period. Assume that the start date is always a Monday.\n\n**Input:**\n- `start_date`: A string in the format 'YYYY-MM-DD HH:MM:SS' representing the start date and time of the work year.\n- `timezone`: A string representing the timezone of the work year.\n\n**Output:**\n- An integer representing the current work week number.\n\n**Sample Input:**\n- `start_date = '2022-01-03 08:00:00'`\n- `timezone = 'UTC'`\n\n**Sample Output:**\n- `1` (if the current date is within the first week starting from '2022-01-03')", "reference": "from datetime import datetime, timedelta\nimport pytz\n\ndef calculate_current_work_week(start_date='2022-1-1 08:00:00', timezone='UTC'):\n \"\"\"\n Calculate the current work week number based on the provided start date and timezone.\n \n :param start_date: A string in the format 'YYYY-MM-DD HH:MM:SS' representing the start date and time of the work year.\n :param timezone: A string representing the timezone of the work year.\n :return: An integer representing the current work week number.\n \"\"\"\n # Parse the start date string into a datetime object\n start_dt = datetime.strptime(start_date, '%Y-%m-%d %H:%M:%S')\n \n # Get the timezone object from the provided timezone string\n tz = pytz.timezone(timezone)\n \n # Localize the start datetime with the provided timezone\n start_dt = tz.localize(start_dt)\n \n # Get the current time in the provided timezone\n current_dt = datetime.now(tz)\n \n # Calculate the difference in days between the start date and current date\n diff = current_dt - start_dt\n \n # Calculate the current work week by dividing the difference in days by 7 and adding 1\n work_week = (diff.days // 7) + 1\n \n return work_week\n\n# Test the function\nprint(calculate_current_work_week()) # It should print the current work week based on the default parameters", "tests": ["assert calculate_current_work_week('2022-1-1 08:00:00', 'UTC') == (datetime.now(pytz.utc) - datetime.strptime('2022-1-1 08:00:00', '%Y-%m-%d %H:%M:%S').replace(tzinfo=pytz.utc)).days // 7 + 1", "assert calculate_current_work_week('2022-1-1 08:00:00', 'America/New_York') == (datetime.now(pytz.timezone('America/New_York')) - datetime.strptime('2022-1-1 08:00:00', '%Y-%m-%d %H:%M:%S').replace(tzinfo=pytz.utc).astimezone(pytz.timezone('America/New_York'))).days // 7 + 1", "assert calculate_current_work_week('2021-12-31 00:00:00', 'UTC') == (datetime.now(pytz.utc) - datetime.strptime('2021-12-31 00:00:00', '%Y-%m-%d %H:%M:%S').replace(tzinfo=pytz.utc)).days // 7 + 1", "assert calculate_current_work_week('2022-1-1 00:00:00', 'Europe/London') == (datetime.now(pytz.timezone('Europe/London')) - datetime.strptime('2022-1-1 00:00:00', '%Y-%m-%d %H:%M:%S').replace(tzinfo=pytz.utc).astimezone(pytz.timezone('Europe/London'))).days // 7 + 1", "assert calculate_current_work_week('2022-1-1 08:00:00', 'Asia/Tokyo') == (datetime.now(pytz.timezone('Asia/Tokyo')) - datetime.strptime('2022-1-1 08:00:00', '%Y-%m-%d %H:%M:%S').replace(tzinfo=pytz.utc).astimezone(pytz.timezone('Asia/Tokyo'))).days // 7 + 1", "assert calculate_current_work_week('2022-1-1 08:00:00', 'Australia/Sydney') == (datetime.now(pytz.timezone('Australia/Sydney')) - datetime.strptime('2022-1-1 08:00:00', '%Y-%m-%d %H:%M:%S').replace(tzinfo=pytz.utc).astimezone(pytz.timezone('Australia/Sydney'))).days // 7 + 1", "assert calculate_current_work_week('2022-1-1 08:00:00', 'Europe/Berlin') == (datetime.now(pytz.timezone('Europe/Berlin')) - datetime.strptime('2022-1-1 08:00:00', '%Y-%m-%d %H:%M:%S').replace(tzinfo=pytz.utc).astimezone(pytz.timezone('Europe/Berlin'))).days // 7 + 1", "assert calculate_current_work_week('2022-1-1 08:00:00', 'America/Los_Angeles') == (datetime.now(pytz.timezone('America/Los_Angeles')) - datetime.strptime('2022-1-1 08:00:00', '%Y-%m-%d %H:%M:%S').replace(tzinfo=pytz.utc).astimezone(pytz.timezone('America/Los_Angeles'))).days // 7 + 1", "assert calculate_current_work_week('2022-1-1 08:00:00', 'Europe/Moscow') == (datetime.now(pytz.timezone('Europe/Moscow')) - datetime.strptime('2022-1-1 08:00:00', '%Y-%m-%d %H:%M:%S').replace(tzinfo=pytz.utc).astimezone(pytz.timezone('Europe/Moscow'))).days // 7 + 1", "assert calculate_current_work_week('2022-1-1 08:00:00', 'Africa/Johannesburg') == (datetime.now(pytz.timezone('Africa/Johannesburg')) - datetime.strptime('2022-1-1 08:00:00', '%Y-%m-%d %H:%M:%S').replace(tzinfo=pytz.utc).astimezone(pytz.timezone('Africa/Johannesburg'))).days // 7 + 1"], "function": "calculate_current_work_week", "signature": "def calculate_current_work_week(start_date='2022-1-1 08:00:00', timezone='UTC'):", "score": 1.0, "domain": "generic"} {"id": "ededbb6febcd206c47ec33c2b225913f", "problem": "You are given a list of integers. Your task is to sort this list in ascending order based on the sum of the digits of each number. If two numbers have the same digit sum, they should retain their original order in the list.\n\n**Input:**\n- A list of integers `numbers` (1 ≤ len(numbers) ≤ 1000), where each integer is in the range -10^6 ≤ numbers[i] ≤ 10^6.\n\n**Output:**\n- A list of integers sorted according to the specified criteria.\n\n**Sample Input:**\n```\n[34, 23, 12, 45, 9, 67]\n```\n\n**Sample Output:**\n```\n[12, 23, 34, 9, 45, 67]\n```", "reference": "def sort_by_digit_sum(numbers):\n \"\"\"\n Sorts a list of integers in ascending order based on the sum of their digits.\n If two numbers have the same digit sum, they retain their original order.\n \n :param numbers: List of integers to be sorted.\n :return: A new list of integers sorted by digit sum.\n \"\"\"\n def digit_sum(n):\n return sum(int(digit) for digit in str(abs(n)))\n \n return sorted(numbers, key=lambda x: (digit_sum(x), numbers.index(x)))\n\n# Example usage:\nnumbers = [34, 23, 12, 45, 9, 67]\nsorted_numbers = sort_by_digit_sum(numbers)\nprint(sorted_numbers) # Output: [12, 23, 34, 9, 45, 67]", "tests": ["assert sort_by_digit_sum([34, 23, 12, 45, 9, 67]) == [12, 23, 34, 9, 45, 67]", "assert sort_by_digit_sum([111, 22, 3, 44, 555]) == [3, 22, 111, 44, 555]", "assert sort_by_digit_sum([99, 18, 81, 27, 72]) == [18, 27, 72, 81, 99]", "assert sort_by_digit_sum([0, 10, 20, 30, 40]) == [0, 10, 20, 30, 40]", "assert sort_by_digit_sum([5, 14, 23, 32, 41]) == [5, 14, 23, 32, 41]", "assert sort_by_digit_sum([123, 321, 213, 132, 231]) == [123, 321, 213, 132, 231]", "assert sort_by_digit_sum([-1, -10, -100, -101, -11]) == [-1, -10, -100, -11, -101]", "assert sort_by_digit_sum([111, 11, 1, 1111, 11111]) == [1, 11, 111, 1111, 11111]", "assert sort_by_digit_sum([9, 99, 999, 9999, 99999]) == [9, 99, 999, 9999, 99999]", "assert sort_by_digit_sum([]) == []"], "function": "sort_by_digit_sum", "signature": "def sort_by_digit_sum(numbers):", "score": 0.6, "domain": "generic"} {"id": "01ff6937021e22846855baea27297351", "problem": "You are given a list of integers `numbers` and an integer `target`. Your task is to implement a function `find_closest_number(numbers, target)` that returns the integer from the list that is closest to the `target`. If there are multiple integers with the same minimum distance to the `target`, return the one that appears first in the list.\n\n**Input:**\n- A list of integers `numbers` (1 ≤ len(numbers) ≤ 10^3), where each integer is in the range [-10^6, 10^6].\n- An integer `target` in the range [-10^6, 10^6].\n\n**Output:**\n- An integer from the list that is closest to the `target`.\n\n**Sample Input:**\n```\nnumbers = [10, 22, 28, 29, 30, 40]\ntarget = 27\n```\n\n**Sample Output:**\n```\n28\n```", "reference": "def find_closest_number(numbers, target):\n \"\"\"\n Returns the number in the list that is closest to the target.\n If there are multiple numbers with the same distance to the target,\n returns the one that appears first in the list.\n \n :param numbers: List of integers\n :param target: Integer target\n :return: Integer closest to the target\n \"\"\"\n closest_number = numbers[0]\n min_distance = abs(target - numbers[0])\n \n for num in numbers:\n distance = abs(target - num)\n if distance < min_distance:\n closest_number = num\n min_distance = distance\n \n return closest_number\n\nnumbers = [10, 22, 28, 29, 30, 40]\ntarget = 27\nprint(find_closest_number(numbers, target))", "tests": ["assert find_closest_number([10, 22, 28, 29, 30, 40], 27) == 28", "assert find_closest_number([1, 2, 3, 5, 6, 8, 9], 7) == 6", "assert find_closest_number([1, 3, 5, 7, 9], 4) == 3", "assert find_closest_number([1, 3, 5, 7, 9], 8) == 9", "assert find_closest_number([1, 3, 5, 7, 9], 5) == 5", "assert find_closest_number([10, 20, 30, 40, 50], 25) == 20", "assert find_closest_number([100, 200, 300, 400, 500], 250) == 200", "assert find_closest_number([1, 1, 1, 1, 1], 1) == 1", "assert find_closest_number([1, 2, 3, 4, 5], 0) == 1", "assert find_closest_number([1, 2, 3, 4, 5], 6) == 5"], "function": "find_closest_number", "signature": "def find_closest_number(numbers, target):", "score": 0.9, "domain": "generic"} {"id": "daeac6dc432b52732df773eec71dd477", "problem": "You are given a slice object `s` and an integer `size` representing the length of an iterable. Your task is to implement a function `decompose_slice` that returns two slice objects. The first slice object should represent the elements accessed by `s` in reverse order with a positive step. The second slice object can have any step. \n\n**Input:**\n- A slice object `s` and an integer `size`.\n\n**Output:**\n- A tuple of two slice objects.\n\n**Sample Input:**\n```python\ns = slice(2, 8, 2)\nsize = 10\n```\n\n**Sample Output:**\n```python\n(slice(7, 1, -2), slice(2, 8, 2))\n```", "reference": "def decompose_slice(s, size):\n \"\"\"\n Decomposes a given slice s into two slices in the context of an iterable of size `size`.\n \n The first slice has a positive step and exactly represents the elements that would be accessed\n by `s` when traversed in reverse order. The second slice can have any step.\n\n :param s: The input slice object.\n :param size: The size of the iterable.\n :return: A tuple of two slice objects.\n \"\"\"\n step = s.step if s.step is not None else 1\n\n if step > 0:\n start = s.start if s.start is not None else 0\n stop = s.stop if s.stop is not None else size\n else:\n start = s.start if s.start is not None else (size - 1)\n stop = s.stop if s.stop is not None else -1\n\n if start < 0:\n start += size\n if stop < 0:\n stop += size\n\n start_reverse = stop - 1 if step > 0 else stop + 1\n stop_reverse = start - 1 if step > 0 else start + 1\n\n if abs(step) != 1:\n start_reverse += step % abs(step)\n stop_reverse -= step % abs(step)\n\n reverse_step = abs(step)\n first_slice = slice(start_reverse, stop_reverse, -reverse_step)\n\n second_slice = slice(start, stop, step)\n\n return first_slice, second_slice", "tests": ["assert decompose_slice(slice(2, 5), 10) == (slice(4, 1, -1), slice(2, 5, 1))", "assert decompose_slice(slice(None, None, -1), 5) == (slice(0, 5, 1), slice(None, None, -1))", "assert decompose_slice(slice(1, 4, 2), 10) == (slice(3, 0, -2), slice(1, 4, 2))", "assert decompose_slice(slice(-3, -1), 10) == (slice(8, 9, -1), slice(-3, -1, 1))", "assert decompose_slice(slice(0, 10, 3), 10) == (slice(9, -1, -3), slice(0, 10, 3))", "assert decompose_slice(slice(5, 2, -2), 10) == (slice(3, 6, 2), slice(5, 2, -2))", "assert decompose_slice(slice(None, None), 7) == (slice(6, -1, -1), slice(None, None, 1))", "assert decompose_slice(slice(3, 3), 5) == (slice(2, 3, -1), slice(3, 3, 1))", "assert decompose_slice(slice(-1, -4, -1), 10) == (slice(3, 0, -1), slice(-1, -4, -1))", "assert decompose_slice(slice(0, 0, 5), 5) == (slice(-1, 0, -5), slice(0, 0, 5))"], "function": "decompose_slice", "signature": "def decompose_slice(s, size):", "score": 0.3, "domain": "generic"} {"id": "f854ec46bbcd8b8f2fbf746beaf618f0", "problem": "You are tasked with implementing a function `factorial_sum` that computes the sum of the factorials of all positive integers up to and including a given integer `n`. The factorial of a number `k` is defined as the product of all positive integers less than or equal to `k`. Your implementation must use recursion to calculate each factorial. Additionally, your function should return a list containing each computed factorial in ascending order of the integers.\n\n**Constraints:**\n- `1 ≤ n ≤ 10`\n\n**Input:**\n- A single integer `n`.\n\n**Output:**\n- A tuple containing two elements:\n 1. An integer representing the sum of the factorials.\n 2. A list of integers representing the factorials of numbers from 1 to `n`.\n\n**Sample Input:**\n```\n4\n```\n\n**Sample Output:**\n```\n(33, [1, 2, 6, 24])\n```", "reference": "def factorial(n):\n \"\"\"Recursively calculates the factorial of a given number n.\"\"\"\n if n == 0 or n == 1:\n return 1\n else:\n return n * factorial(n - 1)\n\ndef factorial_sum(n):\n \"\"\"Computes the sum of factorials of all integers from 1 to n and returns the sum along with a list of these factorials.\"\"\"\n factorials = []\n total_sum = 0\n \n for i in range(1, n + 1):\n fact = factorial(i)\n factorials.append(fact)\n total_sum += fact\n \n return total_sum, factorials", "tests": ["assert factorial_sum(1) == (1, [1])", "assert factorial_sum(2) == (3, [1, 2])", "assert factorial_sum(3) == (9, [1, 2, 6])", "assert factorial_sum(4) == (33, [1, 2, 6, 24])", "assert factorial_sum(5) == (153, [1, 2, 6, 24, 120])", "assert factorial_sum(6) == (873, [1, 2, 6, 24, 120, 720])", "assert factorial_sum(7) == (5913, [1, 2, 6, 24, 120, 720, 5040])", "assert factorial_sum(8) == (46233, [1, 2, 6, 24, 120, 720, 5040, 40320])", "assert factorial_sum(9) == (409113, [1, 2, 6, 24, 120, 720, 5040, 40320, 362880])", "assert factorial_sum(10) == (4037913, [1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800])"], "function": "factorial_sum", "signature": "def factorial_sum(n):", "score": 1.0, "domain": "generic"} {"id": "c1b1b0a2819086e9805c7f9f3ad3f6bc", "problem": "You are given a string `s`. Your task is to implement a function `count_vowels` that returns the number of vowels (a, e, i, o, u) present in the string. The function should be case-insensitive, meaning it should count both uppercase and lowercase vowels. \n\n**Input:**\n- A single string `s` (1 ≤ |s| ≤ 10^5), where |s| denotes the length of the string.\n\n**Output:**\n- An integer representing the number of vowels in the string.\n\n**Sample Input:**\n```\nHello, World!\n```\n\n**Sample Output:**\n```\n3\n```\n\n**Sample Input:**\n```\nPYTHON\n```\n\n**Sample Output:**\n```\n1\n```", "reference": "def count_vowels(s):\n \"\"\"\n Counts the number of vowels in the given string s.\n \n Parameters:\n s (str): The input string.\n \n Returns:\n int: The number of vowels in the string.\n \"\"\"\n vowels = \"aeiouAEIOU\"\n return sum(1 for char in s if char in vowels)\n\n# Example usage:\nprint(count_vowels(\"Hello, World!\")) # Output: 3\nprint(count_vowels(\"PYTHON\")) # Output: 1", "tests": ["assert count_vowels(\"Hello, World!\") == 3", "assert count_vowels(\"PYTHON\") == 1", "assert count_vowels(\"aeiou\") == 5", "assert count_vowels(\"AEIOU\") == 5", "assert count_vowels(\"bcdfg\") == 0", "assert count_vowels(\"abcdefghijklmnopqrstuvwxyz\") == 5", "assert count_vowels(\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\") == 5", "assert count_vowels(\"\") == 0", "assert count_vowels(\"A quick brown fox jumps over the lazy dog\") == 11", "assert count_vowels(\"1234567890!@#$%^&*()\") == 0"], "function": "count_vowels", "signature": "def count_vowels(s):", "score": 1.0, "domain": "generic"} {"id": "72eaf425937d9cbf182371c384521ee4", "problem": "You are given a string `data` and an integer `block_size`. Your task is to implement a function `custom_padding` that returns a padded version of the input string such that the number of alphanumeric characters in the padded string is a multiple of `block_size`. The padding should be added to the end of the string and should consist of spaces (' '). The padding should not be counted towards the alphanumeric character count.\n\n**Input:**\n- A string `data` (1 ≤ |data| ≤ 1000)\n- An integer `block_size` (1 ≤ `block_size` ≤ 100)\n\n**Output:**\n- A string representing the padded version of `data`.\n\n**Sample Input:**\n```\ndata = \"abc!def\"\nblock_size = 4\n```\n\n**Sample Output:**\n```\n\"abc!def \"\n```", "reference": "import string\n\ndef custom_padding(data, block_size):\n \"\"\"\n Pads the input string with spaces at the end such that the number of alphanumeric\n characters in the padded string is a multiple of the given block size.\n\n :param data: The input string to be padded.\n :param block_size: The block size to which the alphanumeric character count should be a multiple.\n :return: The padded string.\n \"\"\"\n non_special_chars = set(string.ascii_letters + string.digits)\n non_special_count = sum(1 for char in data if char in non_special_chars)\n required_length = ((non_special_count // block_size) + 1) * block_size\n padding_needed = required_length - non_special_count\n padding = ' ' * padding_needed\n padded_data = data + padding\n return padded_data", "tests": ["assert custom_padding(\"hello\", 3) == \"hello \"", "assert custom_padding(\"world!\", 5) == \"world! \"", "assert custom_padding(\"abc123\", 4) == \"abc123 \"", "assert custom_padding(\"python@#\", 6) == \"python@# \"", "assert custom_padding(\"data\", 2) == \"data \"", "assert custom_padding(\"1234567890\", 3) == \"1234567890 \"", "assert custom_padding(\"special!@#\", 7) == \"special!@# \"", "assert custom_padding(\"no-padding\", 10) == \"no-padding \"", "assert custom_padding(\"\", 5) == \" \"", "assert custom_padding(\"already_padded123\", 15) == \"already_padded123\""], "function": "custom_padding", "signature": "def custom_padding(data, block_size):", "score": 0.3, "domain": "generic"} {"id": "3701d37b1e4dfed5f1e0f351ab7331ee", "problem": "You are given a list of numbers. Your task is to implement a function `calculate_average(numbers)` that computes the average of all integer values in the list. The function should handle edge cases where the list might be empty or contain non-integer values. If the list is empty or contains only non-integer values, the function should return `None`. Your solution should be robust and handle invalid inputs gracefully.\n\n**Sample Input 1:**\n```python\ncalculate_average([1, 2, 3, 4, 5])\n```\n**Sample Output 1:**\n```\n3.0\n```\n\n**Sample Input 2:**\n```python\ncalculate_average([1, 'a', 3.5, 2, 'b'])\n```\n**Sample Output 2:**\n```\n1.5\n```\n\n**Sample Input 3:**\n```python\ncalculate_average([])\n```\n**Sample Output 3:**\n```\nNone\n```\n\n**Sample Input 4:**\n```python\ncalculate_average(['x', 3.14, 'y'])\n```\n**Sample Output 4:**\n```\nNone\n```", "reference": "def calculate_average(numbers):\n \"\"\"\n Computes the average of all integer values in the given list.\n Returns None if the list is empty or contains only non-integer values.\n \n :param numbers: List of numbers (integers and/or non-integers)\n :return: Average of integers or None\n \"\"\"\n if not numbers:\n return None\n \n valid_numbers = [num for num in numbers if isinstance(num, int)]\n \n if not valid_numbers:\n return None\n \n return sum(valid_numbers) / len(valid_numbers)", "tests": ["assert calculate_average([1, 2, 3, 4, 5]) == 3.0", "assert calculate_average([]) == None", "assert calculate_average([1.5, 2.5, 3.5]) == None", "assert calculate_average(['a', 'b', 'c']) == None", "assert calculate_average([1, 'a', 2, 'b', 3]) == 2.0", "assert calculate_average([10, 20, 30, '40', 50]) == 30.0", "assert calculate_average([100]) == 100.0", "assert calculate_average([None, True, False, 0, 1]) == 0.5", "assert calculate_average([1, 2, 'three', 4, 'five', 6]) == 3.0", "assert calculate_average([1, 2, 3, None, 4, 5, None]) == 3.0"], "function": "calculate_average", "signature": "def calculate_average(numbers):", "score": 0.8, "domain": "generic"} {"id": "e8250e3fca3ee41a7836b1d9324bcb69", "problem": "You are given a string `text` consisting of letters, spaces, and hyphens. Your task is to convert this string into snake case. In snake case, all letters are in lowercase, spaces and hyphens are replaced with underscores, and there are no leading or trailing whitespaces. Write a function `convert_to_snake_case` that performs this conversion.\n\n**Input:**\n- A single string `text` (1 ≤ len(text) ≤ 100).\n\n**Output:**\n- A single string representing the input string converted to snake case.\n\n**Sample Input:**\n```\n\" This Is A Test String - With Hyphens \"\n```\n\n**Sample Output:**\n```\nthis_is_a_test_string_with_hyphens\n```", "reference": "def convert_to_snake_case(text: str) -> str:\n \"\"\"\n Convert a given string to snake case by removing leading and trailing whitespace,\n converting all characters to lowercase, and replacing spaces and hyphens with underscores.\n \n :param text: The input string containing letters, spaces, and hyphens.\n :return: The converted string in snake case.\n \"\"\"\n return text.strip().lower().replace(' ', '_').replace('-', '_')\n\n# Example usage\ntext = \" This Is A Test String - With Hyphens \"\nsnake_case_text = convert_to_snake_case(text)\nprint(snake_case_text) # Output: this_is_a_test_string_with_hyphens", "tests": ["assert convert_to_snake_case(\"Hello World\") == \"hello_world\"", "assert convert_to_snake_case(\"Python-Code-Style\") == \"python_code_style\"", "assert convert_to_snake_case(\" Mixed CASE with Spaces \") == \"mixed_case_with_spaces\"", "assert convert_to_snake_case(\"already_snake_case\") == \"already_snake_case\"", "assert convert_to_snake_case(\"TrailingHyphen-\") == \"trailinghyphen_\"", "assert convert_to_snake_case(\"-LeadingHyphen\") == \"_leadinghyphen\"", "assert convert_to_snake_case(\" \") == \"\"", "assert convert_to_snake_case(\"NoSpacesOrHyphens\") == \"nospacesorhyphens\"", "assert convert_to_snake_case(\"Multiple---Hyphens\") == \"multiple___hyphens\"", "assert convert_to_snake_case(\" Leading and Trailing \") == \"leading_and_trailing\""], "function": "convert_to_snake_case", "signature": "def convert_to_snake_case(text: str) -> str:", "score": 1.0, "domain": "generic"} {"id": "cfbdb9a00b87e21904da7ccb6411c614", "problem": "You are tasked with implementing a function `generate_markdown_table` that constructs a markdown table from a list of dictionaries. Each dictionary in the list represents a row in the table, with keys as column headers and values as cell data. The order of columns in the table must match the order of keys in the first dictionary. Your function should return the markdown table as a string.\n\n**Input:**\n- A list of dictionaries, where each dictionary represents a row in the table. The keys in the dictionaries are the column headers, and the values are the cell data.\n\n**Output:**\n- A string representing the markdown table.\n\n**Sample Input:**\n```python\n[\n {\"Name\": \"Alice\", \"Age\": 25, \"City\": \"New York\"},\n {\"Name\": \"Bob\", \"Age\": 30, \"City\": \"Los Angeles\"},\n {\"Name\": \"Charlie\", \"Age\": 35, \"City\": \"Chicago\"}\n]\n```\n\n**Sample Output:**\n```\nName | Age | City\n--- | --- | ---\nAlice | 25 | New York\nBob | 30 | Los Angeles\nCharlie | 35 | Chicago\n```", "reference": "def generate_markdown_table(data):\n \"\"\"\n Generates a markdown table from a list of dictionaries.\n \n Parameters:\n data (list of dict): A list where each dictionary represents a row in the table.\n The keys in the dictionaries are the column headers, and the values are the cell data.\n \n Returns:\n str: A string representing the markdown table.\n \"\"\"\n if not data:\n return \"\"\n\n headers = list(data[0].keys())\n header_row = \" | \".join(headers)\n separator_row = \" | \".join([\"---\"] * len(headers))\n \n rows = []\n for row in data:\n row_data = [str(row.get(header, \"\")) for header in headers]\n rows.append(\" | \".join(row_data))\n \n table = \"\\n\".join([header_row, separator_row] + rows)\n return table\n\n# Example usage:\ndata = [\n {\"Name\": \"Alice\", \"Age\": 25, \"City\": \"New York\"},\n {\"Name\": \"Bob\", \"Age\": 30, \"City\": \"Los Angeles\"},\n {\"Name\": \"Charlie\", \"Age\": 35, \"City\": \"Chicago\"}\n]\n\nmarkdown_table = generate_markdown_table(data)\nprint(markdown_table)", "tests": ["assert generate_markdown_table([{\"Name\": \"Alice\", \"Age\": 25, \"City\": \"New York\"}]) == \"Name | Age | City\\n--- | --- | ---\\nAlice | 25 | New York\"", "assert generate_markdown_table([]) == \"\"", "assert generate_markdown_table([{\"Name\": \"Alice\", \"Age\": 25}, {\"Name\": \"Bob\", \"Age\": 30}]) == \"Name | Age\\n--- | ---\\nAlice | 25\\nBob | 30\"", "assert generate_markdown_table([{\"Name\": \"Alice\", \"Age\": 25, \"City\": \"New York\"}, {\"Name\": \"Bob\", \"Age\": 30, \"City\": \"Los Angeles\"}]) == \"Name | Age | City\\n--- | --- | ---\\nAlice | 25 | New York\\nBob | 30 | Los Angeles\"", "assert generate_markdown_table([{\"Name\": \"Alice\", \"Age\": 25, \"City\": \"New York\"}, {\"Name\": \"Bob\", \"Age\": 30}]) == \"Name | Age | City\\n--- | --- | ---\\nAlice | 25 | New York\\nBob | 30 | \"", "assert generate_markdown_table([{\"Name\": \"Alice\", \"Age\": 25, \"City\": \"New York\"}, {\"Name\": \"Bob\", \"Age\": 30, \"City\": \"Los Angeles\"}, {\"Name\": \"Charlie\", \"Age\": 35, \"City\": \"Chicago\"}]) == \"Name | Age | City\\n--- | --- | ---\\nAlice | 25 | New York\\nBob | 30 | Los Angeles\\nCharlie | 35 | Chicago\"", "assert generate_markdown_table([{\"Name\": \"Alice\", \"Age\": 25, \"City\": \"New York\"}, {\"Name\": \"Bob\", \"Age\": 30, \"City\": \"Los Angeles\"}, {\"Name\": \"Charlie\", \"Age\": 35}]) == \"Name | Age | City\\n--- | --- | ---\\nAlice | 25 | New York\\nBob | 30 | Los Angeles\\nCharlie | 35 | \"", "assert generate_markdown_table([{\"Name\": \"Alice\", \"Age\": 25, \"City\": \"New York\"}, {\"Name\": \"Bob\", \"Age\": 30, \"City\": \"Los Angeles\"}, {\"Name\": \"Charlie\", \"Age\": 35, \"City\": \"\"}]) == \"Name | Age | City\\n--- | --- | ---\\nAlice | 25 | New York\\nBob | 30 | Los Angeles\\nCharlie | 35 | \"", "assert generate_markdown_table([{\"Name\": \"Alice\", \"Age\": 25, \"City\": \"New York\"}, {\"Name\": \"Bob\", \"Age\": 30, \"City\": \"Los Angeles\"}, {\"Name\": \"Charlie\", \"Age\": 35, \"City\": None}]) == \"Name | Age | City\\n--- | --- | ---\\nAlice | 25 | New York\\nBob | 30 | Los Angeles\\nCharlie | 35 | None\"", "assert generate_markdown_table([{\"Name\": \"Alice\", \"Age\": 25, \"City\": \"New York\"}, {\"Name\": \"Bob\", \"Age\": 30, \"City\": \"Los Angeles\"}, {\"Name\": \"Charlie\", \"Age\": 35, \"City\": \"Chicago\"}, {\"Name\": \"David\", \"Age\": 40, \"City\": \"Houston\"}]) == \"Name | Age | City\\n--- | --- | ---\\nAlice | 25 | New York\\nBob | 30 | Los Angeles\\nCharlie | 35 | Chicago\\nDavid | 40 | Houston\""], "function": "generate_markdown_table", "signature": "def generate_markdown_table(data):", "score": 1.0, "domain": "generic"} {"id": "dd70d636d1e17b67762d164d5345833a", "problem": "You are given a list of integers. Your task is to identify and return a list of all duplicate integers present in the input list. The order of elements in the output list does not matter. Optimize your solution for both time and space complexity.\n\n**Sample Input:**\n```\n[1, 2, 3, 4, 5, 3, 2, 6, 7, 8, 1]\n```\n\n**Sample Output:**\n```\n[1, 2, 3]\n```", "reference": "def find_duplicates(input_list):\n \"\"\"\n Identifies and returns a list of all duplicate integers present in the input list.\n \n :param input_list: List of integers\n :return: List of duplicate integers\n \"\"\"\n seen = set()\n duplicates = set()\n \n for item in input_list:\n if item in seen:\n duplicates.add(item)\n else:\n seen.add(item)\n \n return list(duplicates)", "tests": ["assert find_duplicates([1, 2, 3, 4, 5, 3, 2, 6, 7, 8, 1]) == [1, 2, 3]", "assert find_duplicates([10, 20, 30, 40, 50]) == []", "assert find_duplicates([1, 1, 1, 1, 1]) == [1]", "assert find_duplicates([]) == []", "assert find_duplicates([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3]) == [1, 2, 3]", "assert find_duplicates(['a', 'b', 'c', 'a', 'b', 'd']) == ['a', 'b']", "assert find_duplicates(['apple', 'banana', 'cherry', 'apple']) == ['apple']", "assert find_duplicates([True, False, True, True]) == [True]", "assert find_duplicates([None, None, 1, 2, 3, None]) == [None]", "assert find_duplicates([1.1, 2.2, 3.3, 1.1, 4.4, 5.5, 2.2]) == [1.1, 2.2]"], "function": "find_duplicates", "signature": "def find_duplicates(input_list):", "score": 0.9, "domain": "generic"} {"id": "7886409d9659d80e175265fdd47c6f77", "problem": "You are given a list of strings. Your task is to convert each string into its phonetic representation using the NATO phonetic alphabet. The conversion should ignore any non-letter characters and maintain the original order of the strings. The function should handle both uppercase and lowercase letters. \n\n**Input:**\n- A list of strings, where each string consists of characters from the ASCII set. The list contains at least one string.\n\n**Output:**\n- A list of strings, where each string is the phonetic representation of the corresponding input string.\n\n**Sample Input:**\n```python\n[\"Hello, World!\", \"Python 3.9\", \"OpenAI\"]\n```\n\n**Sample Output:**\n```python\n['Hotel Echo Lima Lima Oscar', 'Papa Tango Hotel India November', 'Oscar Papa Echo November Alpha India']\n```", "reference": "def nato_phonetic(strings):\n \"\"\"\n Convert each string in the input list to its phonetic representation using the NATO phonetic alphabet.\n \n Parameters:\n strings (list of str): A list of strings to be converted.\n \n Returns:\n list of str: A list of phonetic representations of the input strings.\n \"\"\"\n phonetic_alphabet = {\n 'A': 'Alpha', 'B': 'Bravo', 'C': 'Charlie', 'D': 'Delta', 'E': 'Echo',\n 'F': 'Foxtrot', 'G': 'Golf', 'H': 'Hotel', 'I': 'India', 'J': 'Juliett',\n 'K': 'Kilo', 'L': 'Lima', 'M': 'Mike', 'N': 'November', 'O': 'Oscar',\n 'P': 'Papa', 'Q': 'Quebec', 'R': 'Romeo', 'S': 'Sierra', 'T': 'Tango',\n 'U': 'Uniform', 'V': 'Victor', 'W': 'Whiskey', 'X': 'X-ray', 'Y': 'Yankee',\n 'Z': 'Zulu'\n }\n \n def convert_to_phonetic(word):\n return ' '.join(phonetic_alphabet.get(char.upper(), '') for char in word if char.isalpha())\n \n return [convert_to_phonetic(string) for string in strings]\n\n# Test the function\nexample_strings = [\"Hello, World!\", \"Python 3.9\", \"OpenAI\"]\nphonetic_list = nato_phonetic(example_strings)\nprint(phonetic_list)", "tests": ["assert nato_phonetic([\"Hello, World!\"]) == [\"Hotel Echo Lima Lima Oscar World\"]", "assert nato_phonetic([\"Python 3.9\"]) == [\"Papa Yankee Tango Hotel November\"]", "assert nato_phonetic([\"OpenAI\"]) == [\"Oscar Papa Echo November Alpha India\"]", "assert nato_phonetic([\"abc\", \"XYZ\"]) == [\"Alpha Bravo Charlie\", \"X-ray Yankee Zulu\"]", "assert nato_phonetic([\"123\", \"!@#\"]) == [\"\", \"\"]", "assert nato_phonetic([\"aBcDeFgHiJ\"]) == [\"Alpha Bravo Charlie Delta Echo Foxtrot Golf Hotel India Juliett\"]", "assert nato_phonetic([\"kLmNoPqRsT\"]) == [\"Kilo Lima Mike November Oscar Papa Quebec Romeo Sierra Tango Tango\"]", "assert nato_phonetic([\"uVwXyZ\"]) == [\"Uniform Victor Whiskey X-ray Yankee Zulu\"]", "assert nato_phonetic([\"\"]) == [\"\"]", "assert nato_phonetic([\"MixedCASE123\"]) == [\"Mike India X-ray Echo Sierra Charlie Alpha Tango Echo Sierra Charlie Alpha Tango Echo\"]"], "function": "nato_phonetic", "signature": "def nato_phonetic(strings):", "score": 0.6, "domain": "generic"} {"id": "b1d92688dd9aa9bb4355c74ea19e2a58", "problem": "You are tasked with implementing the function `factorial_sum` using only functional programming techniques such as `map`, `filter`, `reduce`, and higher-order functions. The function should compute the sum of the factorials of all integers from 1 to `n` without using any loop constructs or recursion.\n\n**Input:**\n- An integer `n` (1 ≤ n ≤ 10)\n\n**Output:**\n- An integer representing the sum of the factorials of all integers from 1 to `n`.\n\n**Sample Input:**\n```\n5\n```\n\n**Sample Output:**\n```\n153\n```", "reference": "from functools import reduce\nfrom operator import mul, add\n\ndef factorial(x):\n \"\"\"\n Computes the factorial of a given integer x using reduce and mul.\n \n :param x: Integer for which the factorial is to be computed.\n :return: Factorial of x.\n \"\"\"\n return reduce(mul, range(1, x + 1), 1)\n\ndef factorial_sum(n):\n \"\"\"\n Computes the sum of the factorials of all integers from 1 to n using map, factorial, and reduce.\n \n :param n: Upper limit integer up to which the factorial sum is to be computed.\n :return: Sum of the factorials of all integers from 1 to n.\n \"\"\"\n return reduce(add, map(factorial, range(1, n + 1)), 0)", "tests": ["assert factorial_sum(0) == 0", "assert factorial_sum(1) == 1", "assert factorial_sum(2) == 3", "assert factorial_sum(3) == 9", "assert factorial_sum(4) == 33", "assert factorial_sum(5) == 153", "assert factorial_sum(6) == 873", "assert factorial_sum(7) == 5913", "assert factorial_sum(8) == 46233", "assert factorial_sum(9) == 399168"], "function": "factorial_sum", "signature": "def factorial_sum(n):", "score": 0.9, "domain": "generic"} {"id": "0fc804be312f544fdb30bc43ad2ece97", "problem": "You are given a list of URLs and a target domain. Your task is to implement a function `extract_links(urls, domain)` that returns a list of URLs from the input list that belong to the specified target domain. Assume all URLs are well-formed.\n\n**Input:**\n- A list of strings `urls` (1 ≤ len(urls) ≤ 1000), where each string is a valid URL.\n- A string `domain` representing the target domain.\n\n**Output:**\n- A list of strings containing URLs that belong to the target domain.\n\n**Sample Input:**\n```python\nurls = [\n \"http://example.com/page1\",\n \"http://example.com/page2\",\n \"http://anotherdomain.com/page1\",\n \"https://example.com/page3\"\n]\ndomain = \"example.com\"\n```\n\n**Sample Output:**\n```python\n['http://example.com/page1', 'http://example.com/page2', 'https://example.com/page3']\n```", "reference": "from urllib.parse import urlparse\n\ndef extract_links(urls, domain):\n \"\"\"\n Extracts all URLs from the given list that belong to the target domain.\n\n :param urls: List of URLs (strings)\n :param domain: Target domain (string)\n :return: List of URLs (strings) belonging to the target domain\n \"\"\"\n return [url for url in urls if urlparse(url).netloc == domain]", "tests": ["assert extract_links([\"http://example.com/page1\", \"http://example.com/page2\"], \"example.com\") == [\"http://example.com/page1\", \"http://example.com/page2\"]", "assert extract_links([\"http://example.com/page1\", \"http://anotherdomain.com/page1\"], \"example.com\") == [\"http://example.com/page1\"]", "assert extract_links([\"https://example.com/page3\"], \"example.com\") == [\"https://example.com/page3\"]", "assert extract_links([\"http://example.com\", \"http://example.com/\"], \"example.com\") == [\"http://example.com\", \"http://example.com/\"]", "assert extract_links([\"http://subdomain.example.com/page1\"], \"example.com\") == []", "assert extract_links([\"http://example.com/page1\", \"http://example.com/page2\", \"http://example.com/page3\"], \"anotherdomain.com\") == []", "assert extract_links([], \"example.com\") == []", "assert extract_links([\"http://example.com/page1\", \"https://example.com/page2\", \"ftp://example.com/page3\"], \"example.com\") == [\"http://example.com/page1\", \"https://example.com/page2\"]", "assert extract_links([\"http://example.com/page1\", \"http://example.com/page2\", \"http://example.com/page3\"], \"example.com\") == [\"http://example.com/page1\", \"http://example.com/page2\", \"http://example.com/page3\"]", "assert extract_links([\"http://example.com/page1\", \"http://example.com/page2\", \"http://example.com/page3\"], \"www.example.com\") == []"], "function": "extract_links", "signature": "def extract_links(urls, domain):", "score": 0.9, "domain": "generic"} {"id": "8f08e7a577dc2c17aba3d75b98d01ed8", "problem": "You are given a list of 100 integers, each ranging from 1 to 1000. Your task is to implement a function `find_largest_prime` that identifies and returns the largest prime number in the list. If no prime numbers are present, the function should return `None`.\n\n**Sample Input:**\n```\n[173, 547, 223, 137, 97, 883, 587, 191, 823, 347, 313, 983, 521, 167, 73, 557, 103, 787, 331, 157, 463, 257, 419, 571, 359, 487, 503, 199, 673, 619, 839, 431, 379, 601, 719, 563, 751, 877, 499, 383, 233, 101, 307, 293, 919, 647, 857, 181, 659, 599, 311, 271, 443, 263, 971, 683, 467, 509, 773, 239, 523, 227, 887, 401, 367, 131, 617, 139, 809, 743, 761, 353, 937, 281, 541, 827, 397, 373, 797, 479, 179, 25]\n```\n\n**Sample Output:**\n```\n971\n```", "reference": "def is_prime(n):\n \"\"\"Check if a number is prime.\"\"\"\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == 0 or n % 3 == 0:\n return False\n i = 5\n while i * i <= n:\n if n % i == 0 or n % (i + 2) == 0:\n return False\n i += 6\n return True\n\ndef find_largest_prime(numbers):\n \"\"\"Find the largest prime number in a list.\"\"\"\n largest_prime = None\n for number in numbers:\n if is_prime(number):\n if largest_prime is None or number > largest_prime:\n largest_prime = number\n return largest_prime\n\nnumbers = [173, 547, 223, 137, 97, 883, 587, 191, 823, 347, 313, 983, 521, 167, 73, 557, 103, 787, 331, 157, 463, 257, 419, 571, 359, 487, 503, 199, 673, 619, 839, 431, 379, 601, 719, 563, 751, 877, 499, 383, 233, 101, 307, 293, 919, 647, 857, 181, 659, 599, 311, 271, 443, 263, 971, 683, 467, 509, 773, 239, 523, 227, 887, 401, 367, 131, 617, 139, 809, 743, 761, 353, 937, 281, 541, 827, 397, 373, 797, 479, 179, 25]\nprint(find_largest_prime(numbers))", "tests": ["assert find_largest_prime([2, 3, 5, 7, 11]) == 11", "assert find_largest_prime([4, 6, 8, 10, 12]) == None", "assert find_largest_prime([17, 19, 23, 29, 31]) == 31", "assert find_largest_prime([1000, 999, 998, 997, 996]) == 997", "assert find_largest_prime([1, 0, -1, -2, -3]) == None", "assert find_largest_prime([29, 29, 29, 29, 29]) == 29", "assert find_largest_prime([2, 4, 6, 8, 10, 11]) == 11", "assert find_largest_prime([961, 967, 971, 977, 983]) == 983", "assert find_largest_prime([101, 103, 107, 109, 113, 127, 131, 137, 139, 149]) == 149", "assert find_largest_prime([]) == None"], "function": "find_largest_prime", "signature": "def find_largest_prime(numbers):", "score": 1.0, "domain": "generic"} {"id": "9f7d27688781057ed11e3379fdefe1d7", "problem": "You are given a string `s` representing a DNA sequence. Your task is to write a function `complement_sequence` that returns the complement of the given DNA sequence. The complement is formed by replacing each nucleotide with its complement: A with T, T with A, C with G, and G with C. The function should be case-insensitive and handle both uppercase and lowercase letters. If the input string contains any characters other than A, T, C, or G, the function should return the string \"Invalid DNA sequence\".\n\n**Input:**\n- A single string `s` (1 ≤ |s| ≤ 1000) representing the DNA sequence.\n\n**Output:**\n- A string representing the complement of the DNA sequence or \"Invalid DNA sequence\" if the input is invalid.\n\n**Sample Input 1:**\n```\nATcgG\n```\n\n**Sample Output 1:**\n```\nTAGCC\n```\n\n**Sample Input 2:**\n```\nAXT\n```\n\n**Sample Output 2:**\n```\nInvalid DNA sequence\n```", "reference": "def complement_sequence(s):\n \"\"\"\n Returns the complement of a given DNA sequence.\n \n Parameters:\n s (str): A string representing the DNA sequence.\n \n Returns:\n str: The complement of the DNA sequence or \"Invalid DNA sequence\" if the input is invalid.\n \"\"\"\n # Create a mapping of nucleotides to their complements\n complement = {'A': 'T', 'T': 'A', 'C': 'G', 'G': 'C'}\n \n # Convert the input string to uppercase to handle case insensitivity\n s = s.upper()\n \n # Initialize an empty list to store the complement sequence\n complement_sequence = []\n \n # Iterate through each character in the input string\n for nucleotide in s:\n # Check if the character is a valid nucleotide\n if nucleotide in complement:\n # Append the complement of the nucleotide to the list\n complement_sequence.append(complement[nucleotide])\n else:\n # Return an error message if an invalid nucleotide is found\n return \"Invalid DNA sequence\"\n \n # Join the list into a string and return the complement sequence\n return ''.join(complement_sequence)\n\n# Example usage\nprint(complement_sequence(\"ATcgG\")) # Output: \"TAGCC\"\nprint(complement_sequence(\"AXT\")) # Output: \"Invalid DNA sequence\"", "tests": ["assert complement_sequence(\"ATCG\") == \"TAGC\"", "assert complement_sequence(\"atcg\") == \"TAGC\"", "assert complement_sequence(\"GCTA\") == \"CGAT\"", "assert complement_sequence(\"gcta\") == \"CGAT\"", "assert complement_sequence(\"AaTtCcGg\") == \"TtAaGgCc\"", "assert complement_sequence(\"ACGT\") == \"TGCA\"", "assert complement_sequence(\"acgt\") == \"TGCA\"", "assert complement_sequence(\"XYZ\") == \"Invalid DNA sequence\"", "assert complement_sequence(\"A1B2C3\") == \"Invalid DNA sequence\"", "assert complement_sequence(\"\") == \"\""], "function": "complement_sequence", "signature": "def complement_sequence(s):", "score": 0.9, "domain": "generic"} {"id": "3f7154b36a26a23e773fb990888da513", "problem": "You are given a positive integer `n`. Your task is to write a function that finds and returns the largest prime factor of `n`. \n\n**Input:**\n- A single integer `n` (1 ≤ n ≤ 10^12).\n\n**Output:**\n- A single integer representing the largest prime factor of `n`.\n\n**Sample Input:**\n```\n13195\n```\n\n**Sample Output:**\n```\n29\n```", "reference": "def largest_prime_factor(n):\n \"\"\"\n Returns the largest prime factor of the given integer n.\n \n :param n: Integer, the number to find the largest prime factor of.\n :return: Integer, the largest prime factor of n.\n \"\"\"\n def is_prime(num):\n \"\"\"\n Checks if the given number is prime.\n \n :param num: Integer, the number to check for primality.\n :return: Boolean, True if num is prime, False otherwise.\n \"\"\"\n if num <= 1:\n return False\n for i in range(2, int(num**0.5) + 1):\n if num % i == 0:\n return False\n return True\n\n largest_factor = None\n while n % 2 == 0:\n largest_factor = 2\n n //= 2\n\n for i in range(3, int(n**0.5) + 1, 2):\n while n % i == 0:\n largest_factor = i\n n //= i\n\n if n > 2:\n largest_factor = n\n\n return largest_factor\n\n# Example usage:\nexample_input = 13195\nprint(largest_prime_factor(example_input)) # Output: 29", "tests": ["assert largest_prime_factor(13195) == 29", "assert largest_prime_factor(2) == 2", "assert largest_prime_factor(3) == 3", "assert largest_prime_factor(4) == 2", "assert largest_prime_factor(5) == 5", "assert largest_prime_factor(6) == 3", "assert largest_prime_factor(15) == 5", "assert largest_prime_factor(100) == 5", "assert largest_prime_factor(13195) == 29", "assert largest_prime_factor(600851475143) == 6857"], "function": "largest_prime_factor", "signature": "def largest_prime_factor(n):", "score": 1.0, "domain": "algorithmic"} {"id": "abd3284db1b119f85d967748d9ffb893", "problem": "You are given a string `acronym` and a string `phrase`. Your task is to determine if `acronym` is a valid acronym for `phrase` under the following rules:\n- Ignore the articles \"a\", \"an\", and \"the\" in the phrase.\n- Consider only the first letter of each word in the phrase if that word is a palindrome.\n- The acronym should be in uppercase and consist of more than two letters.\n- Return `True` if the acronym matches the generated acronym from the phrase, otherwise return `False`.\n\n**Input:**\n- The first line contains a string `acronym` (1 ≤ |acronym| ≤ 10).\n- The second line contains a string `phrase` (1 ≤ |phrase| ≤ 100).\n\n**Output:**\n- Return `True` if `acronym` is a valid acronym for `phrase`, otherwise return `False`.\n\n**Sample Input:**\n```\nRADAR\nA man a plan a canal Panama radar\n```\n\n**Sample Output:**\n```\nTrue\n```", "reference": "def acronym_checker(acronym, phrase):\n \"\"\"\n Checks if the given acronym is a valid acronym for the given phrase.\n \n Parameters:\n acronym (str): The acronym to check.\n phrase (str): The phrase to generate the acronym from.\n \n Returns:\n bool: True if the acronym is valid, False otherwise.\n \"\"\"\n # Define articles to ignore\n articles = {'a', 'an', 'the'}\n \n # Split phrase into words\n words = phrase.split()\n \n # Function to check if a word is a palindrome\n is_palindrome = lambda word: word == word[::-1]\n \n # Collect the first letters of palindromic words, ignoring articles\n acronym_from_phrase = ''.join([word[0].upper() for word in words if is_palindrome(word) and word.lower() not in articles])\n \n # Check if the generated acronym matches the provided acronym and has more than two letters\n return acronym == acronym_from_phrase and len(acronym) > 2", "tests": ["assert acronym_checker(\"RADAR\", \"Radar And Detects All Radar\")", "assert acronym_checker(\"MADAM\", \"Madam Arora Teaches Malayalam\")", "assert acronym_checker(\"LEVEL\", \"Level At Noon\")", "assert acronym_checker(\"DEED\", \"A Santa At NASA\")", "assert acronym_checker(\"CIVIC\", \"Was It A Car Or A Cat I Saw\")", "assert acronym_checker(\"STAT\", \"A Santa At NASA\") == False", "assert acronym_checker(\"RAD\", \"Radar And Detects All Radar\") == False", "assert acronym_checker(\"MAD\", \"Madam Arora Teaches Malayalam\") == False", "assert acronym_checker(\"LEV\", \"Level At Noon\") == False", "assert acronym_checker(\"DEE\", \"A Santa At NASA\") == False"], "function": "acronym_checker", "signature": "def acronym_checker(acronym, phrase):", "score": 0.5, "domain": "generic"} {"id": "a2f828239c9e3075372811af75344516", "problem": "You are given a string `s`. Your task is to determine if `s` is a palindrome, ignoring spaces, punctuation, and capitalization. A string is considered a palindrome if it reads the same forwards and backwards. For example, the string \"A man, a plan, a canal, Panama\" is a palindrome.\n\n**Input:**\n- A single string `s` (1 ≤ |s| ≤ 10^5), which may contain letters, digits, spaces, and punctuation.\n\n**Output:**\n- Return `True` if `s` is a palindrome, otherwise return `False`.\n\n**Sample Input:**\n```\nA man, a plan, a canal, Panama\nWas it a car or a cat I saw?\n```\n\n**Sample Output:**\n```\nTrue\nTrue\n```", "reference": "def is_palindrome(s):\n \"\"\"\n Determines if the given string s is a palindrome, ignoring spaces, punctuation, and capitalization.\n \n :param s: The input string to check.\n :return: True if s is a palindrome, False otherwise.\n \"\"\"\n cleaned = ''.join(c.lower() for c in s if c.isalnum())\n return cleaned == cleaned[::-1]\n\n# Example usage\nprint(is_palindrome(\"A man, a plan, a canal, Panama\")) # Should return True\nprint(is_palindrome(\"Was it a car or a cat I saw?\")) # Should return True", "tests": ["assert is_palindrome(\"A man, a plan, a canal, Panama\") == True", "assert is_palindrome(\"Was it a car or a cat I saw?\") == True", "assert is_palindrome(\"No lemon, no melon\") == True", "assert is_palindrome(\"Hello, World!\") == False", "assert is_palindrome(\"Madam, in Eden, I'm Adam\") == True", "assert is_palindrome(\"Step on no pets\") == True", "assert is_palindrome(\"Eva, can I see bees in a cave?\") == True", "assert is_palindrome(\"Not a palindrome\") == False", "assert is_palindrome(\"\") == True", "assert is_palindrome(\"Able was I, I saw Elba\") == True"], "function": "is_palindrome", "signature": "def is_palindrome(s):", "score": 1.0, "domain": "generic"} {"id": "ba9251fccc0318adfd3ed8a251dba96e", "problem": "You are tasked with implementing a function `check_dependencies` that determines if all dependencies of a given module, including its transitive dependencies, are present in a provided dependency dictionary. The function should return `True` if all dependencies are accounted for, and `False` otherwise.\n\n**Input:**\n- A dictionary `dependency_dict` where each key is a module name and the corresponding value is a list of module names that the key module depends on.\n- A string `module_name` representing the module for which you need to check the dependencies.\n\n**Output:**\n- A boolean value: `True` if all dependencies of `module_name` are present in `dependency_dict`, `False` otherwise.\n\n**Sample Input:**\n```python\ndependency_dict = {\n 'moduleA': ['moduleB', 'moduleC'],\n 'moduleB': ['moduleD'],\n 'moduleC': [],\n 'moduleD': []\n}\nmodule_name = 'moduleA'\n```\n\n**Sample Output:**\n```\nTrue\n```", "reference": "def check_dependencies(dependency_dict, module_name, visited=None):\n \"\"\"\n Checks if all dependencies of a given module, including transitive dependencies,\n are present in the dependency dictionary.\n\n :param dependency_dict: Dictionary where keys are module names and values are lists of dependencies.\n :param module_name: The module name to check dependencies for.\n :param visited: A set to keep track of visited modules to avoid cycles.\n :return: True if all dependencies are present, False otherwise.\n \"\"\"\n if visited is None:\n visited = set()\n if module_name in visited:\n return True\n visited.add(module_name)\n if module_name not in dependency_dict:\n return False\n return all(check_dependencies(dependency_dict, dep, visited) for dep in dependency_dict[module_name])", "tests": ["assert check_dependencies({'moduleA': ['moduleB'], 'moduleB': []}, 'moduleA') == True", "assert check_dependencies({'moduleA': ['moduleB'], 'moduleB': ['moduleC']}, 'moduleA') == False", "assert check_dependencies({'moduleA': ['moduleB'], 'moduleB': ['moduleC'], 'moduleC': []}, 'moduleA') == True", "assert check_dependencies({'moduleA': ['moduleB', 'moduleC'], 'moduleB': ['moduleD'], 'moduleC': [], 'moduleD': []}, 'moduleA') == True", "assert check_dependencies({'moduleA': ['moduleB', 'moduleC'], 'moduleB': ['moduleD'], 'moduleC': [], 'moduleD': ['moduleE']}, 'moduleA') == False", "assert check_dependencies({'moduleA': ['moduleB'], 'moduleB': ['moduleA']}, 'moduleA') == True", "assert check_dependencies({}, 'moduleA') == False", "assert check_dependencies({'moduleA': []}, 'moduleA') == True", "assert check_dependencies({'moduleA': ['moduleB'], 'moduleB': ['moduleC'], 'moduleC': ['moduleD'], 'moduleD': ['moduleE'], 'moduleE': []}, 'moduleA') == True", "assert check_dependencies({'moduleA': ['moduleB'], 'moduleB': ['moduleC'], 'moduleC': ['moduleD'], 'moduleD': ['moduleE'], 'moduleE': ['moduleF']}, 'moduleA') == False"], "function": "check_dependencies", "signature": "def check_dependencies(dependency_dict, module_name, visited=None):", "score": 1.0, "domain": "generic"} {"id": "a319fe7ca1f342f54ea0e53b162846c6", "problem": "You are given two strings `s1` and `s2`. Your task is to write a function `find_common_substring` that returns the longest common substring between `s1` and `s2`. If there are multiple substrings of the same maximum length, return any one of them. Your solution should utilize dynamic programming for efficiency.\n\n**Input:**\n- Two strings `s1` and `s2` (1 ≤ |s1|, |s2| ≤ 1000), consisting of lowercase English letters.\n\n**Output:**\n- A string representing the longest common substring.\n\n**Sample Input:**\n```\ns1 = \"programming\"\ns2 = \"development\"\n```\n\n**Sample Output:**\n```\n\"ment\"\n```", "reference": "def find_common_substring(s1, s2):\n \"\"\"\n Returns the longest common substring between two input strings using dynamic programming.\n \n :param s1: First input string\n :param s2: Second input string\n :return: Longest common substring\n \"\"\"\n # Create a 2D array to store lengths of longest common suffixes\n dp = [[0] * (len(s2) + 1) for _ in range(len(s1) + 1)]\n \n longest_length = 0\n end_index_s1 = 0\n \n for i in range(1, len(s1) + 1):\n for j in range(1, len(s2) + 1):\n if s1[i - 1] == s2[j - 1]:\n dp[i][j] = dp[i - 1][j - 1] + 1\n if dp[i][j] > longest_length:\n longest_length = dp[i][j]\n end_index_s1 = i\n else:\n dp[i][j] = 0\n \n return s1[end_index_s1 - longest_length: end_index_s1]", "tests": ["assert find_common_substring(\"programming\", \"development\") == \"ment\"", "assert find_common_substring(\"abcde\", \"abfgh\") == \"ab\"", "assert find_common_substring(\"abcdef\", \"xyzabc\") == \"abc\"", "assert find_common_substring(\"hello\", \"world\") == \"\"", "assert find_common_substring(\"abcdef\", \"ghijkl\") == \"\"", "assert find_common_substring(\"aaaa\", \"aa\") == \"aa\"", "assert find_common_substring(\"abcabc\", \"abc\") == \"abc\"", "assert find_common_substring(\"abc\", \"abcabc\") == \"abc\"", "assert find_common_substring(\"abc\", \"defabc\") == \"abc\"", "assert find_common_substring(\"\", \"\") == \"\""], "function": "find_common_substring", "signature": "def find_common_substring(s1, s2):", "score": 0.8, "domain": "generic"} {"id": "467fd3427d7d209b0b9eaa010ef9bb2c", "problem": "You are given two lists of time intervals, `global_intervals` and `categorised_intervals`. Each interval is represented as a tuple `(start_time, end_time)`, where `start_time` and `end_time` are integers denoting the start and end times of the interval, respectively. Your task is to write a function `find_overlapping_intervals(global_intervals, categorised_intervals)` that returns a list of all intervals from `categorised_intervals` that overlap with any interval from `global_intervals`. An interval `(a, b)` is said to overlap with another interval `(c, d)` if `a <= d and b >= c`. Ensure that your function runs in O(n log n) time complexity.\n\n**Sample Input:**\n```python\nglobal_intervals = [(1, 5), (10, 14), (20, 25)]\ncategorised_intervals = [(2, 6), (8, 10), (11, 20), (23, 27)]\n```\n\n**Sample Output:**\n```python\n[(2, 6), (11, 20), (23, 27)]\n```", "reference": "def find_overlapping_intervals(global_intervals, categorised_intervals):\n \"\"\"\n Returns a list of all intervals from categorised_intervals that overlap with any interval from global_intervals.\n \n :param global_intervals: List of tuples representing global time intervals.\n :param categorised_intervals: List of tuples representing categorised time intervals.\n :return: List of overlapping intervals from categorised_intervals.\n \"\"\"\n # Sort intervals by start time\n global_intervals.sort()\n categorised_intervals.sort()\n \n # Initialize pointers for both lists\n i, j = 0, 0\n \n # List to store overlapping intervals\n overlapping_intervals = []\n \n # Traverse both lists\n while i < len(global_intervals) and j < len(categorised_intervals):\n # Get the current intervals from both lists\n g_start, g_end = global_intervals[i]\n c_start, c_end = categorised_intervals[j]\n \n # Check if intervals overlap\n if g_start <= c_end and c_start <= g_end:\n # If they overlap, add the categorised interval to the result list\n overlapping_intervals.append((c_start, c_end))\n \n # Move the pointer of the interval that finishes first\n if g_end < c_end:\n i += 1\n else:\n j += 1\n \n return overlapping_intervals", "tests": ["assert find_overlapping_intervals([(1, 5)], [(2, 6)]) == [(2, 6)]", "assert find_overlapping_intervals([(1, 5)], [(6, 10)]) == []", "assert find_overlapping_intervals([(1, 5), (10, 14)], [(2, 6), (8, 10)]) == [(2, 6)]", "assert find_overlapping_intervals([(1, 5), (10, 14)], [(8, 12), (13, 15)]) == [(8, 12), (13, 15)]", "assert find_overlapping_intervals([(1, 5), (10, 14)], [(15, 20)]) == []", "assert find_overlapping_intervals([(1, 5), (10, 14), (20, 25)], [(2, 6), (8, 10), (11, 20), (23, 27)]) == [(2, 6), (11, 20), (23, 27)]", "assert find_overlapping_intervals([], [(1, 5)]) == []", "assert find_overlapping_intervals([(1, 5)], []) == []", "assert find_overlapping_intervals([(1, 5), (10, 14), (20, 25)], [(0, 1), (5, 10), (14, 20), (25, 30)]) == [(5, 10), (14, 20)]", "assert find_overlapping_intervals([(1, 100)], [(50, 60), (10, 20), (90, 110)]) == [(50, 60), (10, 20), (90, 110)]"], "function": "find_overlapping_intervals", "signature": "def find_overlapping_intervals(global_intervals, categorised_intervals):", "score": 0.6, "domain": "generic"} {"id": "741a4b4c85ebadf3a827aa54ac69a517", "problem": "You are given a non-negative integer `n`. Your task is to compute the nth Fibonacci number using an efficient algorithm with a time complexity of O(log n). The Fibonacci sequence is defined as follows: F(0) = 0, F(1) = 1, and F(n) = F(n-1) + F(n-2) for n > 1. Implement the function `optimize_fibonacci(n)` to achieve this.\n\n**Input:**\n- A single integer `n` (0 ≤ n ≤ 10^18).\n\n**Output:**\n- Print the nth Fibonacci number.\n\n**Sample Input:**\n```\n10\n```\n\n**Sample Output:**\n```\n55\n```", "reference": "def matrix_multiply(A, B):\n \"\"\"\n Multiplies two 2x2 matrices A and B.\n \n :param A: List of lists representing the first 2x2 matrix.\n :param B: List of lists representing the second 2x2 matrix.\n :return: Resultant 2x2 matrix after multiplication.\n \"\"\"\n return [\n [A[0][0] * B[0][0] + A[0][1] * B[1][0], A[0][0] * B[0][1] + A[0][1] * B[1][1]],\n [A[1][0] * B[0][0] + A[1][1] * B[1][0], A[1][0] * B[0][1] + A[1][1] * B[1][1]]\n ]\n\ndef matrix_power(matrix, n):\n \"\"\"\n Raises a 2x2 matrix to the power of n using exponentiation by squaring.\n \n :param matrix: List of lists representing the 2x2 matrix.\n :param n: The exponent to which the matrix is to be raised.\n :return: Resultant 2x2 matrix after exponentiation.\n \"\"\"\n result = [[1, 0], [0, 1]] # Identity matrix\n base = matrix\n \n while n > 0:\n if n % 2 == 1:\n result = matrix_multiply(result, base)\n base = matrix_multiply(base, base)\n n //= 2\n \n return result\n\ndef optimize_fibonacci(n):\n \"\"\"\n Computes the nth Fibonacci number using matrix exponentiation.\n \n :param n: The position in the Fibonacci sequence.\n :return: The nth Fibonacci number.\n \"\"\"\n if n == 0:\n return 0\n elif n == 1:\n return 1\n \n F = [[1, 1], [1, 0]]\n result = matrix_power(F, n-1)\n \n return result[0][0]\n\n# Test the function\nprint(optimize_fibonacci(10)) # Should print 55", "tests": ["assert optimize_fibonacci(0) == 0", "assert optimize_fibonacci(1) == 1", "assert optimize_fibonacci(2) == 1", "assert optimize_fibonacci(3) == 2", "assert optimize_fibonacci(4) == 3", "assert optimize_fibonacci(5) == 5", "assert optimize_fibonacci(10) == 55", "assert optimize_fibonacci(15) == 610", "assert optimize_fibonacci(20) == 6765", "assert optimize_fibonacci(30) == 832040"], "function": "optimize_fibonacci", "signature": "def optimize_fibonacci(n):", "score": 1.0, "domain": "generic"} {"id": "b98ce16591ee1af987f7fd48dd541951", "problem": "You are given a list of strings, each representing a file name in a directory. Each file name adheres to the naming convention: `--.`. For instance, `model-1.0-my_model.py`, `data-2.1-user_data.csv`, etc.\n\nYour task is to implement a function `filter_and_sort_models` that processes this list and returns a new list containing only the file names that denote Python models (i.e., their type is \"model\"). The version number in the file name is always a numeral (e.g., 1.0, 2.1, etc.). The returned list should be sorted by the version number in descending order.\n\n**Sample Input:**\n```python\n[\n \"model-1.0-my_model.py\",\n \"data-2.1-user_data.csv\",\n \"model-2.1-another_model.py\",\n \"model-1.5-yet_another_model.py\"\n]\n```\n\n**Sample Output:**\n```python\n[\n \"model-2.1-another_model.py\",\n \"model-1.5-yet_another_model.py\",\n \"model-1.0-my_model.py\"\n]\n```", "reference": "def filter_and_sort_models(file_names):\n \"\"\"\n Filters and sorts a list of file names to return only Python models sorted by version in descending order.\n\n :param file_names: List of strings, each representing a file name.\n :return: List of strings, filtered and sorted file names of Python models.\n \"\"\"\n model_files = [file for file in file_names if file.startswith('model-')]\n model_files_with_versions = [(file, float(file.split('-')[1])) for file in model_files]\n sorted_model_files = sorted(model_files_with_versions, key=lambda x: x[1], reverse=True)\n return [file for file, version in sorted_model_files]", "tests": ["assert filter_and_sort_models([\"model-1.0-my_model.py\", \"data-2.1-user_data.csv\", \"model-2.1-another_model.py\", \"model-1.5-yet_another_model.py\"]) == [\"model-2.1-another_model.py\", \"model-1.5-yet_another_model.py\", \"model-1.0-my_model.py\"]", "assert filter_and_sort_models([\"model-1.0-my_model.py\"]) == [\"model-1.0-my_model.py\"]", "assert filter_and_sort_models([\"data-2.1-user_data.csv\", \"data-1.0-another_data.csv\"]) == []", "assert filter_and_sort_models([]) == []", "assert filter_and_sort_models([\"model-1.0-my_model.py\", \"model-1.0-my_model.py\"]) == [\"model-1.0-my_model.py\", \"model-1.0-my_model.py\"]", "assert filter_and_sort_models([\"model-1.0-my_model.py\", \"model-2.0-my_model.py\", \"model-1.5-my_model.py\"]) == [\"model-2.0-my_model.py\", \"model-1.5-my_model.py\", \"model-1.0-my_model.py\"]", "assert filter_and_sort_models([\"model-1.0-my_model.py\", \"model-1.0-my_model.py\", \"model-2.0-my_model.py\"]) == [\"model-2.0-my_model.py\", \"model-1.0-my_model.py\", \"model-1.0-my_model.py\"]", "assert filter_and_sort_models([\"model-1.0-my_model.py\", \"model-1.0-my_model.py\", \"model-1.0-my_model.py\"]) == [\"model-1.0-my_model.py\", \"model-1.0-my_model.py\", \"model-1.0-my_model.py\"]", "assert filter_and_sort_models([\"model-1.0-my_model.py\", \"model-2.0-my_model.py\", \"model-3.0-my_model.py\", \"model-0.5-my_model.py\"]) == [\"model-3.0-my_model.py\", \"model-2.0-my_model.py\", \"model-1.0-my_model.py\", \"model-0.5-my_model.py\"]", "assert filter_and_sort_models([\"model-1.0-my_model.py\", \"model-1.0-my_model.py\", \"model-1.0-my_model.py\", \"model-1.0-my_model.py\"]) == [\"model-1.0-my_model.py\", \"model-1.0-my_model.py\", \"model-1.0-my_model.py\", \"model-1.0-my_model.py\"]"], "function": "filter_and_sort_models", "signature": "def filter_and_sort_models(file_names):", "score": 1.0, "domain": "generic"} {"id": "963a1c86097ceaf98ddf9964a614de55", "problem": "You are given a string `s` consisting of alphanumeric characters and special symbols. Your task is to write a function `to_snake_case` that transforms the string into snake case. The transformation involves removing all non-alphanumeric characters except spaces, splitting the string into words based on spaces, and then joining these words with underscores. The resulting string should be in lowercase.\n\n**Input:**\n- A single string `s` (1 ≤ |s| ≤ 1000).\n\n**Output:**\n- A string representing the input string in snake case.\n\n**Sample Input:**\n```\n\"Hello-World! This is a test.\"\n```\n\n**Sample Output:**\n```\n\"hello_world_this_is_a_test\"\n```", "reference": "import re\n\ndef to_snake_case(s: str) -> str:\n \"\"\"\n Transforms a given string into snake case by removing non-alphanumeric characters (except spaces),\n splitting by spaces, and joining with underscores in lowercase.\n \n :param s: The input string to be transformed.\n :return: The transformed string in snake case.\n \"\"\"\n cleaned = re.sub(r'[^\\w\\s]', '', s)\n words = cleaned.split()\n snake_case = '_'.join(words).lower()\n return snake_case", "tests": ["assert to_snake_case(\"Hello-World! This is a test.\") == \"hello_world_this_is_a_test\"", "assert to_snake_case(\"Python3.8\") == \"python38\"", "assert to_snake_case(\"Convert to_Snake_Case!\") == \"convert_to_snake_case\"", "assert to_snake_case(\" Leading and trailing spaces \") == \"leading_and_trailing_spaces\"", "assert to_snake_case(\"Multiple___underscores\") == \"multiple_underscores\"", "assert to_snake_case(\"NoSpecialChars\") == \"nospecialchars\"", "assert to_snake_case(\"12345\") == \"12345\"", "assert to_snake_case(\"MixedCASE_withNumbers123\") == \"mixedcase_withnumbers123\"", "assert to_snake_case(\"!@#$%^&*()\") == \"\"", "assert to_snake_case(\"Spaces between words\") == \"spaces_between_words\""], "function": "to_snake_case", "signature": "def to_snake_case(s: str) -> str:", "score": 0.8, "domain": "generic"} {"id": "058945e6b545c69e90be61a7a76ec2aa", "problem": "You are given two lists of integers, `numbers` and `targets`. Your task is to implement a function `find_indices` that returns a list of integers. For each integer `target` in `targets`, find the index of its first occurrence in `numbers`. If `target` is not found, return the length of `numbers`. To handle duplicates in `numbers`, use a custom hash function that incorporates both the value and its index.\n\n**Input:**\n- `numbers`: A list of integers (1 ≤ len(numbers) ≤ 10^5).\n- `targets`: A list of integers (1 ≤ len(targets) ≤ 10^5).\n\n**Output:**\n- A list of integers representing the indices or the length of `numbers` for each `target`.\n\n**Sample Input:**\n```\nnumbers = [1, 2, 2, 3, 4, 2]\ntargets = [2, 3, 5, 2]\n```\n\n**Sample Output:**\n```\n[1, 3, 6, 1]\n```", "reference": "def find_indices(numbers, targets):\n \"\"\"\n Finds the first occurrence index of each target in numbers.\n If a target is not found, returns the length of numbers.\n \n :param numbers: List of integers.\n :param targets: List of integers to find in numbers.\n :return: List of indices or length of numbers for each target.\n \"\"\"\n def custom_hash(value, index):\n \"\"\"Generates a unique hash for a value-index pair.\"\"\"\n return hash((value, index))\n \n index_map = {}\n for index, number in enumerate(numbers):\n index_map[custom_hash(number, index)] = index\n \n result = []\n for target in targets:\n found = False\n for index, number in enumerate(numbers):\n if number == target:\n target_hash = custom_hash(target, index)\n if target_hash in index_map:\n result.append(index_map[target_hash])\n found = True\n break\n if not found:\n result.append(len(numbers))\n \n return result", "tests": ["assert find_indices([1, 2, 3, 4, 5], [3, 1, 5, 6]) == [2, 0, 4, 5]", "assert find_indices([10, 20, 30, 40, 50], [50, 20, 10, 60]) == [4, 1, 0, 5]", "assert find_indices([5, 5, 5, 5, 5], [5, 5, 5, 5, 5]) == [0, 1, 2, 3, 4]", "assert find_indices([1, 1, 1, 1, 1], [2]) == [5]", "assert find_indices([], [1, 2, 3]) == [0, 0, 0]", "assert find_indices([1, 2, 3], []) == []", "assert find_indices([7, 8, 9, 7, 8, 9], [9, 7, 8, 10]) == [2, 0, 1, 6]", "assert find_indices([1, 2, 3, 4, 5], [5, 4, 3, 2, 1]) == [4, 3, 2, 1, 0]", "assert find_indices([1, 2, 3, 4, 5], [6, 7, 8, 9, 10]) == [5, 5, 5, 5, 5]", "assert find_indices([1, 2, 2, 3, 4, 2], [2, 3, 5, 2]) == [1, 3, 6, 1]"], "function": "find_indices", "signature": "def find_indices(numbers, targets):", "score": 0.9, "domain": "generic"} {"id": "fed3a28bc9ecb8da81615a9024b13bbb", "problem": "You are given a string `text`. Your task is to create a function `generate_palindrome` that returns the shortest palindrome that can be formed by appending characters to the end of `text`. If `text` is already a palindrome, return it unchanged.\n\n**Constraints:**\n- The length of `text` is between 1 and 1000 characters.\n- `text` consists of lowercase English letters.\n\n**Sample Input and Output:**\n- Input: `\"race\"`\n- Output: `\"racecar\"`\n\n- Input: `\"madam\"`\n- Output: `\"madam\"`\n\n- Input: `\"a\"`\n- Output: `\"a\"`", "reference": "def generate_palindrome(text):\n \"\"\"\n Generates the shortest palindrome by appending characters to the end of the input string.\n \n Parameters:\n text (str): The input string.\n \n Returns:\n str: The shortest palindrome formed by appending characters to the end of the input string.\n \"\"\"\n def is_palindrome(s):\n return s == s[::-1]\n\n if is_palindrome(text):\n return text\n \n for i in range(len(text)):\n if is_palindrome(text[i:]):\n return text + text[:i][::-1]\n \n return text + text[:-1][::-1]", "tests": ["assert generate_palindrome(\"race\") == \"racecar\"", "assert generate_palindrome(\"abba\") == \"abba\"", "assert generate_palindrome(\"a\") == \"a\"", "assert generate_palindrome(\"abc\") == \"abcba\"", "assert generate_palindrome(\"ab\") == \"aba\"", "assert generate_palindrome(\"racecar\") == \"racecar\"", "assert generate_palindrome(\"noon\") == \"noon\"", "assert generate_palindrome(\"palindrome\") == \"palindromemordnilap\"", "assert generate_palindrome(\"level\") == \"level\"", "assert generate_palindrome(\"\") == \"\""], "function": "generate_palindrome", "signature": "def generate_palindrome(text):", "score": 1.0, "domain": "generic"} {"id": "3ab385e84ef182bf4b92d116e56e238a", "problem": "You are given a list of filenames representing text files located in the current working directory. Your task is to write a Python function that reads the contents of these files and returns a single string with all the contents concatenated together. Each file's content should be separated by a newline character. If a file cannot be read, your function should print an error message and continue with the next file.\n\n**Sample Input:**\n```python\n[\"file1.txt\", \"file2.txt\", \"file3.txt\"]\n```\n\n**Sample Output:**\n```\nContent of file1.txt\nContent of file2.txt\nContent of file3.txt\n```", "reference": "def concatenate_files(filenames):\n \"\"\"\n Concatenates the contents of multiple text files into a single string.\n \n Parameters:\n filenames (list of str): A list of filenames of text files to be concatenated.\n \n Returns:\n str: A single string containing the concatenated contents of the files.\n \"\"\"\n combined_content = \"\"\n for filename in filenames:\n try:\n with open(filename, 'r') as file:\n combined_content += file.read() + \"\\n\"\n except Exception as e:\n print(f\"Error reading {filename}: {e}\")\n return combined_content", "tests": ["assert concatenate_files([\"file1.txt\", \"file2.txt\"]) == \"Content of file1\\nContent of file2\\n\"", "assert concatenate_files([\"singlefile.txt\"]) == \"Content of singlefile\\n\"", "assert concatenate_files([]) == \"\"", "assert concatenate_files([\"nonexistentfile.txt\"]) == \"\"", "assert concatenate_files([\"emptyfile.txt\"]) == \"\\n\"", "assert concatenate_files([\"file1.txt\", \"nonexistentfile.txt\", \"file2.txt\"]) == \"Content of file1\\nContent of file2\\n\"", "assert concatenate_files([\"file1.txt\", \"file1.txt\"]) == \"Content of file1\\nContent of file1\\n\"", "assert concatenate_files([\"file_with_newlines.txt\"]) == \"Line 1\\nLine 2\\nLine 3\\n\\n\"", "assert concatenate_files([\"file_with_special_chars.txt\"]) == \"Special chars: !@#$%^&*()\\n\"", "assert concatenate_files([\"file_with_unicode.txt\"]) == \"Unicode: 你好 こんにちは こんにちは\\n\""], "function": "concatenate_files", "signature": "def concatenate_files(filenames):", "score": 0.3, "domain": "generic"} {"id": "4682e1a839ca044b57dd9452d581b2e6", "problem": "You are given a list of integers `nums`. Your task is to write a function `max_product` that returns the maximum product of any three numbers from the list. The list can contain both positive and negative integers. \n\n**Constraints:**\n- The length of `nums` will be at least 3 and at most 1000.\n- Each element in `nums` will be an integer in the range [-1000, 1000].\n\n**Sample Input:**\n```\n[1, 10, 2, 6, 5, 3]\n```\n\n**Sample Output:**\n```\n300\n```", "reference": "def max_product(nums):\n \"\"\"\n Returns the maximum product of any three numbers from the list nums.\n \n :param nums: List of integers\n :return: Integer representing the maximum product of three numbers\n \"\"\"\n nums.sort()\n max_product1 = nums[-1] * nums[-2] * nums[-3]\n max_product2 = nums[0] * nums[1] * nums[-1]\n return max(max_product1, max_product2)\n\n# Example usage\nnums = [1, 10, 2, 6, 5, 3]\nprint(max_product(nums)) # Output: 300", "tests": ["assert max_product([1, 10, 2, 6, 5, 3]) == 300", "assert max_product([-10, -10, 5, 2]) == 500", "assert max_product([1, 2, 3]) == 6", "assert max_product([-1, -2, -3, -4]) == -6", "assert max_product([0, 2, 3, 5]) == 30", "assert max_product([1, 2, 3, 4, 5, 6]) == 120", "assert max_product([-1, -2, 0, 1, 2]) == 4", "assert max_product([100, 90, 80, 70, 60]) == 720000", "assert max_product([-10, -20, 5, 6]) == 1200", "assert max_product([1, 1, 1, 1, 1, 1]) == 1"], "function": "max_product", "signature": "def max_product(nums):", "score": 1.0, "domain": "generic"} {"id": "58ba86528694c4eb69803918bdea52cd", "problem": "You are given a binary tree represented as a list of lists, where each inner list contains three elements: the value of the node, the index of the left child, and the index of the right child. The indices are 0-based, and a value of -1 indicates the absence of a child. Your task is to implement a function `find_nth_inorder` that returns the value of the nth node in the in-order traversal of the binary tree. Assume that the tree is a valid binary tree and that n is a valid index.\n\n**Sample Input:**\n```python\ntree = [\n [4, 1, 2], # Node 0: Value 4, Left child at index 1, Right child at index 2\n [2, 3, -1], # Node 1: Value 2, Left child at index 3, No right child\n [6, -1, 4], # Node 2: Value 6, No left child, Right child at index 4\n [1, -1, -1],# Node 3: Value 1, No children\n [8, -1, -1] # Node 4: Value 8, No children\n]\nn = 3\n```\n\n**Sample Output:**\n```\n6\n```", "reference": "def find_nth_inorder(tree, n):\n \"\"\"\n Returns the value of the nth node in the in-order traversal of the binary tree.\n \n :param tree: List of lists, where each inner list contains [value, left_index, right_index]\n :param n: Integer, the index of the node to find in the in-order traversal\n :return: Integer, the value of the nth node in the in-order traversal\n \"\"\"\n def inorder_traversal(node_index):\n if node_index == -1:\n return\n \n node = tree[node_index]\n value, left_index, right_index = node\n \n inorder_traversal(left_index)\n \n nonlocal node_count\n node_count += 1\n if node_count == n:\n nonlocal result\n result = value\n return\n \n inorder_traversal(right_index)\n\n node_count = 0\n result = None\n inorder_traversal(0)\n return result", "tests": ["assert find_nth_inorder([[1, 1, 2], [2, -1, -1], [3, -1, -1]], 1) == 2", "assert find_nth_inorder([[1, 1, 2], [2, -1, -1], [3, -1, -1]], 2) == 1", "assert find_nth_inorder([[1, 1, 2], [2, -1, -1], [3, -1, -1]], 3) == 3", "assert find_nth_inorder([[1, 2, 3], [2, 4, 5], [3, -1, -1], [4, -1, -1], [5, -1, -1]], 4) == 4", "assert find_nth_inorder([[1, 2, 3], [2, 4, 5], [3, -1, -1], [4, -1, -1], [5, -1, -1]], 5) == 5", "assert find_nth_inorder([[1, -1, -1]], 1) == 1", "assert find_nth_inorder([[1, 2, -1], [2, 3, -1], [3, -1, -1]], 2) == 3", "assert find_nth_inorder([[1, -1, 2], [2, -1, 3], [3, -1, 4], [4, -1, -1]], 3) == 3", "assert find_nth_inorder([[1, 2, 3], [2, 4, 5], [3, 6, 7], [4, -1, -1], [5, -1, -1], [6, -1, -1], [7, -1, -1]], 6) == 6", "assert find_nth_inorder([[1, 2, 3], [2, 4, 5], [3, 6, 7], [4, -1, -1], [5, -1, -1], [6, -1, -1], [7, -1, -1]], 1) == 4"], "function": "find_nth_inorder", "signature": "def find_nth_inorder(tree, n):", "score": 0.4, "domain": "generic"} {"id": "553bf63e4238359e07cac69625d407d8", "problem": "You are given a nested list of integers. Your task is to write a function `find_max_min_values(data)` that identifies the maximum and minimum values across all sublists. The function should return these values as a tuple in the format `(max_value, min_value)`. If the input list contains only empty sublists, the function should return `None`. \n\n**Input:**\n- A nested list of integers, where each sublist may be empty.\n\n**Output:**\n- A tuple containing the maximum and minimum values found in the nested list, or `None` if no integers are present.\n\n**Sample Input:**\n```python\n[[3, 5, 9], [1, 4, 8], [10, 2, 6]]\n```\n\n**Sample Output:**\n```python\n(10, 1)\n```\n\n**Sample Input:**\n```python\n[[], [], []]\n```\n\n**Sample Output:**\n```python\nNone\n```", "reference": "def find_max_min_values(data):\n \"\"\"\n Finds the maximum and minimum values in a nested list of integers.\n \n Parameters:\n data (list of list of int): A nested list of integers, where each sublist may be empty.\n \n Returns:\n tuple: A tuple containing the maximum and minimum values found in the nested list, or None if no integers are present.\n \"\"\"\n # Flatten the list of lists and filter out empty sublists\n flattened_list = [num for sublist in data if sublist for num in sublist]\n \n # Return None if the flattened list is empty\n if not flattened_list:\n return None\n \n # Calculate the max and min values from the flattened list\n max_value = max(flattened_list)\n min_value = min(flattened_list)\n \n # Return the result as a tuple\n return (max_value, min_value)", "tests": ["assert find_max_min_values([[3, 5, 9], [1, 4, 8], [10, 2, 6]]) == (10, 1)", "assert find_max_min_values([[1], [2], [3]]) == (3, 1)", "assert find_max_min_values([[100], [-100], [0]]) == (100, -100)", "assert find_max_min_values([[], [], []]) == None", "assert find_max_min_values([[1, 2, 3], [], [4, 5, 6]]) == (6, 1)", "assert find_max_min_values([[10]]) == (10, 10)", "assert find_max_min_values([[-1, -2, -3], [-4, -5, -6], [-7, -8, -9]]) == (-1, -9)", "assert find_max_min_values([[0, 0, 0], [0, 0], [0]]) == (0, 0)", "assert find_max_min_values([[1000, 2000], [3000, 4000], [5000, 6000]]) == (6000, 1000)", "assert find_max_min_values([[1], [2, 3], [4, 5, 6], [7, 8, 9, 10]]) == (10, 1)"], "function": "find_max_min_values", "signature": "def find_max_min_values(data):", "score": 1.0, "domain": "generic"} {"id": "0b695e4b6fb4b669997b11e2bb81529d", "problem": "You are given a string `s` and an integer `k`. Your task is to determine the shortest palindrome that can be formed by inserting at most `k` characters into the string `s`. Return the length of this shortest palindrome.\n\n**Constraints:**\n- `1 <= len(s) <= 1000`\n- `0 <= k <= len(s)`\n\n**Sample Input:**\n```\ns = \"racecar\"\nk = 3\n```\n\n**Sample Output:**\n```\n7\n```", "reference": "def shortest_palindrome(s, k):\n \"\"\"\n Finds the shortest palindrome that can be formed by inserting at most k characters into the string s.\n \n :param s: The input string.\n :param k: The maximum number of characters that can be inserted.\n :return: The length of the shortest palindrome.\n \"\"\"\n n = len(s)\n dp = [[0] * n for _ in range(n)]\n \n for length in range(2, n + 1):\n for i in range(n - length + 1):\n j = i + length - 1\n if s[i] == s[j]:\n dp[i][j] = dp[i + 1][j - 1]\n else:\n dp[i][j] = min(dp[i + 1][j], dp[i][j - 1]) + 1\n \n min_insertions = dp[0][n - 1]\n return min(n + min_insertions, n + k)\n\n# Test the function\ns = \"racecar\"\nk = 3\nprint(shortest_palindrome(s, k)) # Output: 7", "tests": ["assert shortest_palindrome(\"racecar\", 3) == 7", "assert shortest_palindrome(\"ab\", 1) == 3", "assert shortest_palindrome(\"abc\", 2) == 4", "assert shortest_palindrome(\"a\", 0) == 1", "assert shortest_palindrome(\"abcd\", 3) == 5", "assert shortest_palindrome(\"aabba\", 1) == 5", "assert shortest_palindrome(\"madam\", 0) == 5", "assert shortest_palindrome(\"noon\", 0) == 4", "assert shortest_palindrome(\"abcba\", 0) == 5", "assert shortest_palindrome(\"abcd\", 4) == 4"], "function": "shortest_palindrome", "signature": "def shortest_palindrome(s, k):", "score": 0.6, "domain": "generic"} {"id": "d0abc527e518b82a3a529a5e43fd3ca6", "problem": "You are given a list of integers. Your task is to write a function `sum_of_squares` that calculates the sum of the squares of the integers in the list. If the list is empty, the function should return 0.\n\n**Sample Input 1:**\n```\n[1, 2, 3]\n```\n**Sample Output 1:**\n```\n14\n```\n\n**Sample Input 2:**\n```\n[]\n```\n**Sample Output 2:**\n```\n0\n```", "reference": "def sum_of_squares(numbers):\n \"\"\"\n Calculate the sum of the squares of the integers in the list.\n If the list is empty, return 0.\n\n :param numbers: List of integers\n :return: Sum of squares of the integers in the list\n \"\"\"\n if not numbers:\n return 0\n return sum(x * x for x in numbers)", "tests": ["assert sum_of_squares([1, 2, 3]) == 14", "assert sum_of_squares([0, 0, 0]) == 0", "assert sum_of_squares([-1, -2, -3]) == 14", "assert sum_of_squares([10, 20, 30]) == 1400", "assert sum_of_squares([]) == 0", "assert sum_of_squares([5]) == 25", "assert sum_of_squares([1, -1, 1, -1]) == 4", "assert sum_of_squares([2, 4, 6, 8, 10]) == 220", "assert sum_of_squares([-5, 5]) == 50", "assert sum_of_squares([7, 0, 7]) == 98"], "function": "sum_of_squares", "signature": "def sum_of_squares(numbers):", "score": 1.0, "domain": "algorithmic"} {"id": "ef0e18ab9c295985877e28180154f70d", "problem": "You are given a loan with an initial balance, an annual interest rate, and a target number of months to pay off the loan. Your task is to compute the approximate monthly payment required to pay off the loan. The monthly payment should be calculated by dividing the total amount (initial balance plus interest) by the number of months and rounding the result to the nearest 10. Interest is compounded daily using the exact fractional interest method, where the daily interest rate is the annual interest rate divided by 365.\n\n**Input:**\n- The function will take three parameters:\n - `loan_balance`: an integer representing the initial loan balance in dollars.\n - `annual_interest_rate`: a float representing the annual interest rate as a percentage.\n - `months`: an integer representing the number of months over which the loan should be paid off.\n\n**Output:**\n- Return an integer representing the approximate monthly payment, rounded to the nearest 10.\n\n**Sample Input:**\n- `loan_balance = 10000`\n- `annual_interest_rate = 5`\n- `months = 24`\n\n**Sample Output:**\n- `Monthly Payment: $ 450`", "reference": "def calculate_monthly_payment(loan_balance, annual_interest_rate, months):\n \"\"\"\n Calculate the approximate monthly payment needed to pay off a loan within a given number of months.\n \n Parameters:\n loan_balance (int): The initial loan balance in dollars.\n annual_interest_rate (float): The annual interest rate as a percentage.\n months (int): The number of months over which the loan should be paid off.\n \n Returns:\n int: The approximate monthly payment, rounded to the nearest 10.\n \"\"\"\n days_in_a_year = 365\n daily_interest_rate = annual_interest_rate / 100 / days_in_a_year\n total_interest = 0\n \n remaining_balance = loan_balance\n for _ in range(months):\n days_in_month = 30 # Approximate days in each month for simplicity\n for _ in range(days_in_month):\n total_interest += remaining_balance * daily_interest_rate\n remaining_balance += remaining_balance * daily_interest_rate\n \n remaining_balance -= loan_balance / months\n\n total_amount = loan_balance + total_interest\n monthly_payment = round(total_amount / months, -1) # rounding to nearest 10\n return monthly_payment\n\n# Example usage:\ninitial_loan_balance = 10000 # initially 10,000 dollars\nannual_interest_rate = 5 # 5 percent annual interest rate\nmonths = 24 # to be paid off in 2 years\n\nprint(\"Monthly Payment: $\", calculate_monthly_payment(initial_loan_balance, annual_interest_rate, months))", "tests": ["assert calculate_monthly_payment(10000, 5, 24) == 460", "assert calculate_monthly_payment(15000, 7, 36) == 450", "assert calculate_monthly_payment(20000, 3, 12) == 1730", "assert calculate_monthly_payment(5000, 4, 60) == 90", "assert calculate_monthly_payment(0, 5, 24) == 0", "assert calculate_monthly_payment(10000, 0, 24) == 420", "assert calculate_monthly_payment(10000, 5, 1) == 10530", "assert calculate_monthly_payment(10000, 5, 12) == 890", "assert calculate_monthly_payment(10000, 10, 24) == 480", "assert calculate_monthly_payment(10000, 5, 36) == 310"], "function": "calculate_monthly_payment", "signature": "def calculate_monthly_payment(loan_balance, annual_interest_rate, months):", "score": 0.3, "domain": "generic"} {"id": "be4eac2f29e3a4e3ee1d31c134d4b285", "problem": "You are tasked with implementing a function to find the nth prime number using the Sieve of Eratosthenes algorithm. Your function should be efficient and handle large values of n. Write a function `find_nth_prime` that takes an integer `n` as input and returns the nth prime number.\n\n**Input:**\n- An integer `n` (1 ≤ n ≤ 10^4)\n\n**Output:**\n- The nth prime number.\n\n**Sample Input:**\n```\n10\n```\n\n**Sample Output:**\n```\n29\n```", "reference": "import math\n\ndef find_nth_prime(n):\n \"\"\"\n Returns the nth prime number using the Sieve of Eratosthenes algorithm.\n \n Parameters:\n n (int): The position of the prime number to find (1-based index).\n \n Returns:\n int: The nth prime number.\n \n Raises:\n ValueError: If n is less than 1.\n \"\"\"\n if n < 1:\n raise ValueError(\"n must be a positive integer\")\n \n # Estimate upper bound for nth prime using the prime number theorem\n if n < 6:\n limit = 20 # Small primes are denser, ensure enough for first n primes\n else:\n limit = int(n * (math.log(n) + math.log(math.log(n)))) # Upper bound for nth prime\n\n # Initialize a list to keep track of prime status of numbers\n is_prime = [True] * (limit + 1)\n p = 2\n \n # Sieve of Eratosthenes\n while (p * p <= limit):\n if is_prime[p]:\n for i in range(p * p, limit + 1, p):\n is_prime[i] = False\n p += 1\n \n # Collect primes\n primes = [i for i in range(2, limit + 1) if is_prime[i]]\n \n # Check if we have enough primes, adjust limit if necessary\n while len(primes) < n:\n limit *= 2 # Increase the limit and retry sieve\n is_prime = [True] * (limit + 1)\n p = 2\n while (p * p <= limit):\n if is_prime[p]:\n for i in range(p * p, limit + 1, p):\n is_prime[i] = False\n p += 1\n primes = [i for i in range(2, limit + 1) if is_prime[i]]\n \n return primes[n - 1]\n\n# Example usage:\n# print(find_nth_prime(10)) # Should return 29, the 10th prime number", "tests": ["assert find_nth_prime(1) == 2", "assert find_nth_prime(2) == 3", "assert find_nth_prime(3) == 5", "assert find_nth_prime(4) == 7", "assert find_nth_prime(5) == 11", "assert find_nth_prime(10) == 29", "assert find_nth_prime(20) == 71", "assert find_nth_prime(50) == 229", "assert find_nth_prime(100) == 541", "assert find_nth_prime(1000) == 7919"], "function": "find_nth_prime", "signature": "def find_nth_prime(n):", "score": 1.0, "domain": "generic"} {"id": "71a5ef0de7ee882cff8f6c65761f537c", "problem": "You are given two integers, `a` and `b`. Your task is to write a function `compute_gcd` that computes the greatest common divisor (GCD) of these two integers using the Euclidean algorithm. The function should handle negative inputs by considering their absolute values. \n\n**Input:**\n- Two integers `a` and `b` (-10^9 ≤ a, b ≤ 10^9).\n\n**Output:**\n- A single integer representing the GCD of `a` and `b`.\n\n**Sample Input:**\n```\n48 18\n```\n\n**Sample Output:**\n```\n6\n```\n\n**Sample Input:**\n```\n-24 36\n```\n\n**Sample Output:**\n```\n12\n```", "reference": "def compute_gcd(a, b):\n \"\"\"Calculate the greatest common divisor of two integers using the Euclidean algorithm.\n \n Args:\n a (int): First integer.\n b (int): Second integer.\n \n Returns:\n int: The greatest common divisor of a and b.\n \"\"\"\n a = abs(a)\n b = abs(b)\n \n while b:\n a, b = b, a % b\n return a", "tests": ["assert compute_gcd(48, 18) == 6", "assert compute_gcd(101, 10) == 1", "assert compute_gcd(56, 98) == 14", "assert compute_gcd(-48, 18) == 6", "assert compute_gcd(48, -18) == 6", "assert compute_gcd(-48, -18) == 6", "assert compute_gcd(0, 5) == 5", "assert compute_gcd(5, 0) == 5", "assert compute_gcd(0, 0) == 0", "assert compute_gcd(1, 1) == 1"], "function": "compute_gcd", "signature": "def compute_gcd(a, b):", "score": 1.0, "domain": "generic"} {"id": "352acbf33d3e53ed2017bd9280af5821", "problem": "You are tasked with implementing a function `fibo_efficient(n, k)` that computes the nth number in the k-bonacci sequence. The k-bonacci sequence is defined such that each term is the sum of the previous k terms, with the sequence starting with k-1 zeros followed by a one. Your implementation should be efficient, operating in O(n) time complexity.\n\n**Input:**\n- Two integers `n` and `k` (1 ≤ n ≤ 10^6, 1 ≤ k ≤ 10^3), where `n` is the term to find in the sequence and `k` is the number of terms to sum for each subsequent term.\n\n**Output:**\n- A single integer representing the nth term in the k-bonacci sequence.\n\n**Sample Input:**\n```\n10 2\n10 3\n```\n\n**Sample Output:**\n```\n55\n81\n```", "reference": "def fibo_efficient(n, k):\n \"\"\"\n Computes the nth number in the k-bonacci sequence.\n \n Parameters:\n n (int): The term to find in the sequence.\n k (int): The number of terms to sum for each subsequent term.\n \n Returns:\n int: The nth term in the k-bonacci sequence.\n \"\"\"\n if n == 0:\n return 0\n elif n == 1:\n return 1\n\n sequence = [0] * k\n sequence[k-1] = 1\n current_sum = 1\n\n for i in range(k, n):\n next_value = current_sum\n current_sum += next_value - sequence[i % k]\n sequence[i % k] = next_value\n\n return current_sum", "tests": ["assert fibo_efficient(0, 2) == 0", "assert fibo_efficient(1, 2) == 1", "assert fibo_efficient(2, 2) == 1", "assert fibo_efficient(10, 2) == 55", "assert fibo_efficient(10, 3) == 81", "assert fibo_efficient(5, 5) == 1", "assert fibo_efficient(6, 5) == 1", "assert fibo_efficient(7, 5) == 2", "assert fibo_efficient(8, 5) == 4", "assert fibo_efficient(9, 5) == 8"], "function": "fibo_efficient", "signature": "def fibo_efficient(n, k):", "score": 0.6, "domain": "generic"} {"id": "d2bc2b5495e82c17a37e4d8504525b5b", "problem": "You are given a string `sentence` consisting of words separated by spaces. Your task is to write a function `reverse_words` that returns a new string where each word in the sentence is reversed, but the order of the words remains unchanged.\n\n**Input:**\n- A single string `sentence` (1 ≤ len(sentence) ≤ 1000) containing only letters and spaces. There will be at least one word in the sentence, and no leading or trailing spaces.\n\n**Output:**\n- A string with each word in `sentence` reversed, maintaining the original word order.\n\n**Sample Input:**\n```\n\"Hello world\"\n```\n\n**Sample Output:**\n```\n\"olleH dlrow\"\n```", "reference": "def reverse_words(sentence):\n \"\"\"\n Reverses each word in the given sentence while maintaining the order of words.\n\n :param sentence: A string containing words separated by spaces.\n :return: A string with each word reversed.\n \"\"\"\n words = sentence.split()\n reversed_words = [word[::-1] for word in words]\n reversed_sentence = ' '.join(reversed_words)\n return reversed_sentence\n\n# Example usage:\n# input_sentence = \"Hello world\"\n# output_sentence = reverse_words(input_sentence)\n# print(output_sentence) # Output: \"olleH dlrow\"", "tests": ["assert reverse_words(\"Hello world\") == \"olleH dlrow\"", "assert reverse_words(\"Python is fun\") == \"nohtyP si nuf\"", "assert reverse_words(\"OpenAI GPT-4\") == \"IANpO 4TPG\"", "assert reverse_words(\"a b c\") == \"a b c\"", "assert reverse_words(\"123 456 789\") == \"321 654 987\"", "assert reverse_words(\"!@# $%^ &*(\") == \"#@! %^$ (*&\"", "assert reverse_words(\"racecar level deed\") == \"racecar level deed\"", "assert reverse_words(\"A man a plan a canal Panama\") == \"A nam a nalp a lanac amanaP\"", "assert reverse_words(\"\") == \"\"", "assert reverse_words(\" \") == \"\""], "function": "reverse_words", "signature": "def reverse_words(sentence):", "score": 0.8, "domain": "generic"} {"id": "ab90ddf2571c010465c09385005cf78e", "problem": "You are given a list of integers `nums` and an integer `target`. Your task is to write a function that returns the index of the first occurrence of `target` in `nums`. If `target` is not present in the list, return `-1`. Your solution should have a time complexity of O(n).\n\n**Sample Input:**\n```\nnums = [4, 2, 7, 3, 2, 5]\ntarget = 2\n```\n\n**Sample Output:**\n```\n1\n```\n\n**Sample Input:**\n```\nnums = [1, 3, 5, 7]\ntarget = 6\n```\n\n**Sample Output:**\n```\n-1\n```", "reference": "def find_first_occurrence(nums, target):\n \"\"\"\n Returns the index of the first occurrence of target in nums.\n If target is not found, returns -1.\n \n :param nums: List of integers\n :param target: Integer to find in nums\n :return: Index of the first occurrence of target, or -1 if not found\n \"\"\"\n for index, num in enumerate(nums):\n if num == target:\n return index\n return -1", "tests": ["assert find_first_occurrence([1, 2, 3, 4, 5], 3) == 2", "assert find_first_occurrence([10, 20, 30, 40, 50], 10) == 0", "assert find_first_occurrence([5, 4, 3, 2, 1], 1) == 4", "assert find_first_occurrence([7, 7, 7, 7, 7], 7) == 0", "assert find_first_occurrence([1, 1, 1, 1, 1], 2) == -1", "assert find_first_occurrence([], 3) == -1", "assert find_first_occurrence([1, 2, 3, 4, 5], 6) == -1", "assert find_first_occurrence([1, 2, 3, 4, 5], 5) == 4", "assert find_first_occurrence([1, 2, 3, 4, 5], 1) == 0", "assert find_first_occurrence([1, 3, 5, 7, 9], 8) == -1"], "function": "find_first_occurrence", "signature": "def find_first_occurrence(nums, target):", "score": 1.0, "domain": "generic"} {"id": "6aa85d087ca66148a2372134fd4d2e2f", "problem": "You are given a string `text` containing a mix of words and email addresses. Your task is to write a Python function `extract_emails` that extracts all valid email addresses from the string. A valid email address must adhere to the following rules:\n- It consists of a username part, which may include letters (both uppercase and lowercase), digits, dots (`.`), underscores (`_`), percent signs (`%`), plus signs (`+`), and hyphens (`-`).\n- It is followed by an `@` symbol.\n- It includes a domain part, which consists of labels separated by dots. Each label must start and end with a letter or digit and may contain hyphens.\n- The domain part must end with a top-level domain (TLD) that is at least two characters long.\n\nFor example, the following are valid email addresses:\n- `user@mail.example.com`\n- `user@subdomain.example.co.uk`\n\nThe following are invalid email addresses:\n- `user@.com`\n- `user@com`\n- `user@com.`\n- `user@com.c`\n\nYour function should return a list of all valid email addresses found in the input string.\n\n**Sample Input:**\n```\nThe quick brown fox jumps over the lazy dog. Here are some emails to extract: test@example.com, user@subdomain.example.co.uk, invalid-email@com, another.invalid@.com, valid-email@domain.com.\n```\n\n**Sample Output:**\n```\n['test@example.com', 'user@subdomain.example.co.uk', 'valid-email@domain.com']\n```", "reference": "import re\n\ndef extract_emails(text):\n \"\"\"\n Extracts all valid email addresses from the given text.\n\n Parameters:\n text (str): The input string containing potential email addresses.\n\n Returns:\n list: A list of valid email addresses found in the input string.\n \"\"\"\n # Regular expression pattern for validating an email\n email_pattern = r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}'\n # Find all emails using the pattern\n emails = re.findall(email_pattern, text)\n # Filter out invalid emails\n valid_emails = [email for email in emails if '.' in email.split('@')[1]]\n return valid_emails\n\n# Test the function with the given text\ntext = \"The quick brown fox jumps over the lazy dog. Here are some emails to extract: test@example.com, user@subdomain.example.co.uk, invalid-email@com, another.invalid@.com, valid-email@domain.com.\"\nprint(extract_emails(text))", "tests": ["assert extract_emails(\"test@example.com\") == [\"test@example.com\"]", "assert extract_emails(\"user@subdomain.example.co.uk\") == [\"user@subdomain.example.co.uk\"]", "assert extract_emails(\"invalid-email@com\") == []", "assert extract_emails(\"another.invalid@.com\") == []", "assert extract_emails(\"valid-email@domain.com\") == [\"valid-email@domain.com\"]", "assert extract_emails(\"noemails@here\") == [\"noemails@here\"]", "assert extract_emails(\"multiple@emails.com and another@domain.co.uk\") == [\"multiple@emails.com\", \"another@domain.co.uk\"]", "assert extract_emails(\"user@domain.c\") == []", "assert extract_emails(\"user@domain..com\") == []", "assert extract_emails(\"\") == []"], "function": "extract_emails", "signature": "def extract_emails(text):", "score": 0.8, "domain": "generic"} {"id": "18c45c2815a30f2d71ee1ba8e8b13e0a", "problem": "You are given a list of integers `numbers` containing all integers from 1 to `n` except for one missing integer. Your task is to find and return the missing integer. The list is not necessarily sorted.\n\n**Input:**\n- A list of integers `numbers` (1 ≤ len(numbers) ≤ 10^5), where each integer is in the range [1, n].\n\n**Output:**\n- An integer representing the missing number from the list.\n\n**Sample Input:**\n```\n[1, 2, 4, 5, 6, 7, 8, 9]\n```\n\n**Sample Output:**\n```\n3\n```", "reference": "def find_missing_number(numbers):\n \"\"\"\n Finds the missing number in a list of integers from 1 to n.\n\n :param numbers: List of integers from 1 to n with one number missing.\n :return: The missing integer.\n \"\"\"\n n = len(numbers) + 1\n expected_sum = n * (n + 1) // 2\n actual_sum = sum(numbers)\n return expected_sum - actual_sum\n\n# Example usage:\nnumbers = [1, 2, 4, 5, 6, 7, 8, 9]\nprint(find_missing_number(numbers)) # Output: 3", "tests": ["assert find_missing_number([1, 2, 4, 5, 6, 7, 8, 9]) == 3", "assert find_missing_number([1, 3, 4, 5]) == 2", "assert find_missing_number([2, 3, 4, 5, 6]) == 1", "assert find_missing_number([1, 2, 3, 4, 5, 6, 7, 8, 10]) == 9", "assert find_missing_number([10, 9, 8, 7, 6, 5, 4, 3, 2, 1]) == 11", "assert find_missing_number([1]) == 2", "assert find_missing_number([2]) == 1", "assert find_missing_number([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30]) == 31", "assert find_missing_number([31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2]) == 1", "assert find_missing_number([]) == 1"], "function": "find_missing_number", "signature": "def find_missing_number(numbers):", "score": 1.0, "domain": "generic"} {"id": "d3f2ad752b51f724e925e58c2ac8be7c", "problem": "You are given an array of integers `numbers` and an integer `target_sum`. Your task is to find all unique pairs of integers in the array that add up to `target_sum`. Each pair should be represented as a tuple with the integers in ascending order. The function should return a list of these tuples. Note that the order of the tuples in the output list does not matter.\n\n**Input:**\n- An array of integers `numbers` (1 ≤ len(numbers) ≤ 10^3, -10^3 ≤ numbers[i] ≤ 10^3)\n- An integer `target_sum` (-2000 ≤ target_sum ≤ 2000)\n\n**Output:**\n- A list of tuples, where each tuple contains two integers that add up to `target_sum`. Each tuple should be in ascending order, and the list should contain no duplicate tuples.\n\n**Sample Input:**\n```\nnumbers = [2, 4, 3, 5, 7, 8, 1]\ntarget_sum = 9\n```\n\n**Sample Output:**\n```\n[(2, 7), (4, 5), (8, 1)]\n```", "reference": "def find_pairs(numbers, target_sum):\n \"\"\"\n Finds all unique pairs of integers in the given list that add up to the target sum.\n \n :param numbers: List of integers.\n :param target_sum: Integer representing the target sum.\n :return: List of tuples, each containing a pair of integers that add up to the target sum.\n \"\"\"\n numbers.sort()\n seen = set()\n pairs = set()\n \n for number in numbers:\n complement = target_sum - number\n if complement in seen:\n pairs.add((min(number, complement), max(number, complement)))\n seen.add(number)\n \n return list(pairs)\n\n# Example usage:\nnumbers = [2, 4, 3, 5, 7, 8, 1]\ntarget_sum = 9\nprint(find_pairs(numbers, target_sum)) # Output: [(2, 7), (4, 5), (8, 1)]", "tests": ["assert find_pairs([2, 4, 3, 5, 7, 8, 1], 9) == [(1, 8), (2, 7), (3, 6), (4, 5)]", "assert find_pairs([1, 2, 3, 4, 5], 5) == [(1, 4), (2, 3)]", "assert find_pairs([10, 15, 3, 7], 17) == [(10, 7)]", "assert find_pairs([1, 1, 1, 1], 2) == [(1, 1)]", "assert find_pairs([], 10) == []", "assert find_pairs([5, 5, 5, 5], 10) == [(5, 5)]", "assert find_pairs([1, 2, 3, 4, 5, 6, 7, 8, 9], 10) == [(1, 9), (2, 8), (3, 7), (4, 6)]", "assert find_pairs([-1, -2, -3, -4, -5], -6) == [(-1, -5), (-2, -4)]", "assert find_pairs([0, 0, 0, 0], 0) == [(0, 0)]", "assert find_pairs([1, 3, 5, 7, 9], 10) == [(1, 9), (3, 7)]"], "function": "find_pairs", "signature": "def find_pairs(numbers, target_sum):", "score": 0.4, "domain": "generic"} {"id": "9908d972ab854ad474951e72765a0818", "problem": "You are given a list of integers representing the scores of students in a class. Your task is to implement a function `calculate_class_average(scores)` that computes and returns the average score of the students. If the list is empty, the function should return 0. Your solution should be efficient and handle edge cases appropriately.\n\n**Sample Input 1:**\n```\n[85, 90, 78, 92, 88]\n```\n**Sample Output 1:**\n```\n86.6\n```\n\n**Sample Input 2:**\n```\n[]\n```\n**Sample Output 2:**\n```\n0\n```", "reference": "def calculate_class_average(scores):\n \"\"\"\n Calculate the average score from a list of student scores.\n \n Parameters:\n scores (list of int): A list of integers representing student scores.\n \n Returns:\n float: The average score of the students. Returns 0 if the list is empty.\n \"\"\"\n if not scores:\n return 0\n return sum(scores) / len(scores)\n\n# Example usage:\n# scores_list = [85, 90, 78, 92, 88]\n# print(calculate_class_average(scores_list)) # Output: 86.6\n# empty_scores = []\n# print(calculate_class_average(empty_scores)) # Output: 0", "tests": ["assert calculate_class_average([85, 90, 78, 92, 88]) == 86.6", "assert calculate_class_average([100, 100, 100]) == 100.0", "assert calculate_class_average([50, 60, 70, 80, 90]) == 70.0", "assert calculate_class_average([0, 0, 0, 0]) == 0.0", "assert calculate_class_average([]) == 0", "assert calculate_class_average([100]) == 100.0", "assert calculate_class_average([55, 45]) == 50.0", "assert calculate_class_average([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) == 5.5", "assert calculate_class_average([95, 85, 75, 65, 55, 45, 35, 25, 15, 5]) == 55.0", "assert calculate_class_average([23, 45, 67, 89]) == 56.0"], "function": "calculate_class_average", "signature": "def calculate_class_average(scores):", "score": 0.9, "domain": "generic"} {"id": "f1c84a7167294da6f8af8b93db8183f5", "problem": "You are given a dictionary `ht` representing cities and their populations. The keys are strings representing city names, and the values are integers representing the population of those cities. The dictionary may be nested, meaning some values could be dictionaries with the same structure. In this case, you should aggregate the populations of all cities in the nested dictionaries. Implement the function `most_populous_city(ht)` that returns the name of the city with the highest population. If there are multiple cities with the same highest population, return the city that comes first alphabetically.\n\n**Sample Input:**\n```python\nht = {\n 'cityA': 100000,\n 'cityB': 200000,\n 'region1': {\n 'cityC': 150000,\n 'cityD': 200000\n },\n 'region2': {\n 'cityE': 180000,\n 'cityF': 190000\n }\n}\n```\n\n**Sample Output:**\n```\n'cityB'\n```", "reference": "def most_populous_city(ht):\n \"\"\"\n Returns the name of the city with the highest population from a given dictionary.\n If there are multiple cities with the same highest population, returns the city that comes first alphabetically.\n Handles nested dictionaries by aggregating populations.\n \n :param ht: Dictionary representing cities and their populations, possibly nested.\n :return: String name of the most populous city.\n \"\"\"\n def flatten_dict(d, parent_key='', sep='_'):\n \"\"\"\n Flattens a nested dictionary.\n \n :param d: Dictionary to flatten.\n :param parent_key: Base key for recursion.\n :param sep: Separator for nested keys.\n :return: Flattened dictionary.\n \"\"\"\n items = []\n for k, v in d.items():\n new_key = f\"{parent_key}{sep}{k}\" if parent_key else k\n if isinstance(v, dict):\n items.extend(flatten_dict(v, new_key, sep=sep).items())\n else:\n items.append((new_key, v))\n return dict(items)\n \n flat_dict = flatten_dict(ht)\n max_population = -1\n most_populous = None\n \n for city, population in flat_dict.items():\n if population > max_population or (population == max_population and (most_populous is None or city < most_populous)):\n max_population = population\n most_populous = city\n \n return most_populous", "tests": ["assert most_populous_city({'cityA': 100000, 'cityB': 200000}) == 'cityB'", "assert most_populous_city({'cityA': 100000, 'cityB': 100000}) == 'cityA'", "assert most_populous_city({'region1': {'cityA': 100000, 'cityB': 200000}}) == 'cityB'", "assert most_populous_city({'region1': {'cityA': 100000, 'cityB': 100000}}) == 'cityA'", "assert most_populous_city({'cityA': 100000, 'region1': {'cityB': 200000}}) == 'cityB'", "assert most_populous_city({'cityA': 100000, 'region1': {'cityB': 100000}}) == 'cityA'", "assert most_populous_city({'region1': {'cityA': 100000}, 'region2': {'cityB': 200000}}) == 'cityB'", "assert most_populous_city({'region1': {'cityA': 100000}, 'region2': {'cityB': 100000}}) == 'cityA'", "assert most_populous_city({'region1': {'cityA': 100000, 'region2': {'cityB': 200000}}}) == 'cityB'", "assert most_populous_city({'region1': {'cityA': 100000, 'region2': {'cityB': 100000}}}) == 'cityA'"], "function": "most_populous_city", "signature": "def most_populous_city(ht):", "score": 0.3, "domain": "generic"} {"id": "943809902ab4b0cbdbac4a7e43b46b45", "problem": "You are tasked with analyzing the weekly working hours of employees in a company. Given a list of integers representing the number of hours each employee worked in a week, write a function to compute the median number of hours worked. Before calculating the median, filter out any hours that are less than 5 or greater than 60. If the filtered list is empty, return `None`.\n\n**Input:**\n- A list of integers `hours` where each integer represents the number of hours worked by an employee in a week.\n\n**Output:**\n- A float representing the median number of hours worked by the employees after filtering. If the filtered list is empty, return `None`.\n\n**Sample Input:**\n```\n[10, 20, 30, 40, 5, 65, 25, 35]\n```\n\n**Sample Output:**\n```\n27.5\n```", "reference": "def calculate_median(hours):\n \"\"\"\n Calculate the median number of hours worked by employees after filtering out\n hours less than 5 or greater than 60.\n\n :param hours: List of integers representing the number of hours worked by each employee.\n :return: The median number of hours as a float, or None if the filtered list is empty.\n \"\"\"\n # Filter out any hours that are less than 5 or greater than 60\n filtered_hours = [h for h in hours if 5 <= h <= 60]\n \n # Sort the filtered list of hours\n sorted_hours = sorted(filtered_hours)\n \n # Calculate the median\n n = len(sorted_hours)\n if n == 0:\n return None # Return None if the filtered list is empty\n mid = n // 2\n \n if n % 2 == 0:\n # If even, average the two middle numbers\n median = (sorted_hours[mid - 1] + sorted_hours[mid]) / 2\n else:\n # If odd, take the middle number\n median = sorted_hours[mid]\n \n return median\n\n# Example usage:\nhours_worked = [10, 20, 30, 40, 5, 65, 25, 35]\nmedian_hours = calculate_median(hours_worked)\nprint(median_hours) # Output: 27.5", "tests": ["assert calculate_median([10, 20, 30, 40, 5, 65, 25, 35]) == 27.5", "assert calculate_median([5, 60]) == 32.5", "assert calculate_median([10, 20, 30, 40]) == 25", "assert calculate_median([5, 5, 5, 5, 5]) == 5", "assert calculate_median([60, 60, 60, 60, 60]) == 60", "assert calculate_median([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) == 5.5", "assert calculate_median([5, 6, 7, 8, 9, 10, 60]) == 8", "assert calculate_median([1, 2, 3, 4, 61, 62, 63]) == None", "assert calculate_median([]) == None", "assert calculate_median([30]) == 30"], "function": "calculate_median", "signature": "def calculate_median(hours):", "score": 0.8, "domain": "generic"} {"id": "f88958f4486a407ea71a6c18e7425e05", "problem": "You are given a dictionary `product_ratings` where each key is a product name (a string) and each value is a list of integers representing the ratings for that product. Your task is to determine the product with the highest average rating. If multiple products share the highest average rating, return the one that appears first in the dictionary. Return the product name and its average rating as a tuple.\n\n**Input:**\n- A dictionary `product_ratings` with product names as keys and lists of integers as values.\n\n**Output:**\n- A tuple containing the product name with the highest average rating and the average rating itself.\n\n**Sample Input:**\n```python\n{\n \"Laptop\": [4, 5, 5, 3],\n \"Smartphone\": [5, 5, 4],\n \"Tablet\": [2, 3, 4, 5]\n}\n```\n\n**Sample Output:**\n```python\n(\"Smartphone\", 4.666666666666667)\n```", "reference": "def product_with_highest_average_rating(product_ratings):\n \"\"\"\n Finds the product with the highest average rating from a dictionary of product ratings.\n \n Parameters:\n product_ratings (dict): A dictionary where keys are product names and values are lists of ratings.\n \n Returns:\n tuple: A tuple containing the product name with the highest average rating and the average rating.\n \"\"\"\n highest_avg_rating = -1\n product_name_with_highest_avg = \"\"\n \n for product_name, ratings in product_ratings.items():\n if len(ratings) == 0:\n continue\n avg_rating = sum(ratings) / len(ratings)\n if avg_rating > highest_avg_rating:\n highest_avg_rating = avg_rating\n product_name_with_highest_avg = product_name\n \n return product_name_with_highest_avg, highest_avg_rating", "tests": ["assert product_with_highest_average_rating({\"ProductA\": [5, 5, 5], \"ProductB\": [4, 4, 4, 4]}) == (\"ProductA\", 5.0)", "assert product_with_highest_average_rating({\"ProductX\": [1, 2, 3], \"ProductY\": [3, 3, 3]}) == (\"ProductY\", 3.0)", "assert product_with_highest_average_rating({\"Product1\": [2, 2, 2, 2], \"Product2\": [2, 2, 2, 2]}) == (\"Product1\", 2.0)", "assert product_with_highest_average_rating({\"ProductZ\": [10], \"ProductW\": [5, 5]}) == (\"ProductZ\", 10.0)", "assert product_with_highest_average_rating({\"ProductM\": [1, 1, 1], \"ProductN\": [2, 2]}) == (\"ProductN\", 2.0)", "assert product_with_highest_average_rating({\"ProductQ\": [3, 3, 3], \"ProductR\": [3, 3, 3]}) == (\"ProductQ\", 3.0)", "assert product_with_highest_average_rating({\"ProductS\": [1, 2, 3, 4, 5], \"ProductT\": [5, 4, 3, 2, 1]}) == (\"ProductS\", 3.0)", "assert product_with_highest_average_rating({\"ProductU\": [1], \"ProductV\": [1, 1, 1, 1, 1]}) == (\"ProductU\", 1.0)", "assert product_with_highest_average_rating({\"ProductL\": [5, 5, 5, 5, 5], \"ProductK\": [5, 5, 5, 5, 5]}) == (\"ProductL\", 5.0)", "assert product_with_highest_average_rating({\"ProductO\": [], \"ProductP\": [1, 2, 3]}) == (\"ProductP\", 2.0)"], "function": "product_with_highest_average_rating", "signature": "def product_with_highest_average_rating(product_ratings):", "score": 1.0, "domain": "generic"} {"id": "25ec9a5a327cbfb0bac61b111ef93dc0", "problem": "You are given a list of non-empty strings. Your task is to implement a function `group_by_prefix(strings)` that groups these strings based on their first character. The function should return a dictionary where each key is a character, and the corresponding value is a list of strings that start with that character. The order of strings within each list should be the same as their order in the input list.\n\n**Input:**\n- A list of strings `strings` (1 ≤ len(strings) ≤ 1000), where each string consists of lowercase English letters and has a length between 1 and 100.\n\n**Output:**\n- A dictionary with characters as keys and lists of strings as values.\n\n**Sample Input:**\n```python\n[\"apple\", \"banana\", \"apricot\", \"cherry\", \"blueberry\", \"avocado\"]\n```\n\n**Sample Output:**\n```python\n{'a': ['apple', 'apricot', 'avocado'], 'b': ['banana', 'blueberry'], 'c': ['cherry']}\n```", "reference": "def group_by_prefix(strings):\n \"\"\"\n Groups a list of strings by their first character.\n\n Parameters:\n strings (list of str): A list of non-empty strings.\n\n Returns:\n dict: A dictionary where keys are characters and values are lists of strings starting with that character.\n \"\"\"\n grouped = {}\n for string in strings:\n prefix = string[0]\n if prefix in grouped:\n grouped[prefix].append(string)\n else:\n grouped[prefix] = [string]\n return grouped\n\n# Example usage:\nstrings = [\"apple\", \"banana\", \"apricot\", \"cherry\", \"blueberry\", \"avocado\"]\nresult = group_by_prefix(strings)\nprint(result)", "tests": ["assert group_by_prefix([\"apple\", \"banana\", \"apricot\", \"cherry\", \"blueberry\", \"avocado\"]) == {'a': ['apple', 'apricot', 'avocado'], 'b': ['banana', 'blueberry'], 'c': ['cherry']}", "assert group_by_prefix([\"dog\", \"cat\", \"camel\", \"cow\"]) == {'d': ['dog'], 'c': ['cat', 'camel', 'cow']}", "assert group_by_prefix([\"zebra\", \"antelope\", \"ant\", \"aardvark\"]) == {'z': ['zebra'], 'a': ['antelope', 'ant', 'aardvark']}", "assert group_by_prefix([]) == {}", "assert group_by_prefix([\"\", \"empty\", \"elephant\"]) == {'': [''], 'e': ['empty', 'elephant']}", "assert group_by_prefix([\"same\", \"same\", \"same\"]) == {'s': ['same', 'same', 'same']}", "assert group_by_prefix([\"123\", \"1abc\", \"2xyz\"]) == {'1': ['123', '1abc'], '2': ['2xyz']}", "assert group_by_prefix([\"!\", \"@\", \"#\", \"$\"]) == {'!': ['!'], '@': ['@'], '#': ['#'], '$': ['$']}", "assert group_by_prefix([\"a\", \"b\", \"c\", \"d\", \"e\"]) == {'a': ['a'], 'b': ['b'], 'c': ['c'], 'd': ['d'], 'e': ['e']}", "assert group_by_prefix([\"Aardvark\", \"antelope\", \"Ant\", \"aardvark\"]) == {'A': ['Aardvark'], 'a': ['antelope', 'Ant', 'aardvark']}"], "function": "group_by_prefix", "signature": "def group_by_prefix(strings):", "score": 0.8, "domain": "generic"} {"id": "6a3569a83502e5ea83cd519e996ba596", "problem": "You are given a list of integers. Your task is to write a function `find_min_max_diff(ints)` that computes the difference between the maximum and minimum values in the list after removing all duplicate elements. If the list becomes empty after removing duplicates, the function should return `None`. If the list contains only one unique element, the function should return `0`.\n\n**Input:**\n- A list of integers `ints` (0 ≤ len(ints) ≤ 10^5), where each integer is in the range [-10^9, 10^9].\n\n**Output:**\n- An integer representing the difference between the maximum and minimum unique elements, or `None` if the list is empty after removing duplicates.\n\n**Sample Input and Output:**\n- Input: `[3, 3, 2, 5, 7, 7, 5]`\n - Output: `5`\n- Input: `[5, 5, 5, 5]`\n - Output: `0`\n- Input: `[]`\n - Output: `None`", "reference": "def find_min_max_diff(ints):\n \"\"\"\n Computes the difference between the maximum and minimum unique elements in a list.\n Returns None if the list is empty after removing duplicates, and 0 if there is only one unique element.\n \n :param ints: List of integers\n :return: Difference between max and min unique elements or None\n \"\"\"\n unique_ints = list(set(ints))\n if len(unique_ints) == 0:\n return None\n elif len(unique_ints) == 1:\n return 0\n else:\n return max(unique_ints) - min(unique_ints)\n\n# Test the function\nprint(find_min_max_diff([3, 3, 2, 5, 7, 7, 5])) # Expected output: 5\nprint(find_min_max_diff([5, 5, 5, 5])) # Expected output: 0\nprint(find_min_max_diff([])) # Expected output: None", "tests": ["assert find_min_max_diff([3, 3, 2, 5, 7, 7, 5]) == 5", "assert find_min_max_diff([5, 5, 5, 5]) == 0", "assert find_min_max_diff([]) == None", "assert find_min_max_diff([10]) == 0", "assert find_min_max_diff([1, 2, 3, 4, 5]) == 4", "assert find_min_max_diff([100, 200, 300, 400, 500]) == 400", "assert find_min_max_diff([-1, -2, -3, -4, -5]) == 4", "assert find_min_max_diff([10, 10, 10, 10, 10, 10]) == 0", "assert find_min_max_diff([1, 1, 2, 2, 3, 3, 4, 4]) == 3", "assert find_min_max_diff([5, 3, 1, 9, 7]) == 8"], "function": "find_min_max_diff", "signature": "def find_min_max_diff(ints):", "score": 1.0, "domain": "generic"} {"id": "ca05badd7eb5488520791fc8e2f5f277", "problem": "You are given two integers, `x` and `y`. Your task is to implement a function `prime_factor_difference` that computes the absolute difference between the sum of the prime factors of `x` and `y`. The prime factors of a number are the prime numbers that divide it exactly, without leaving a remainder.\n\n**Input:**\n- Two integers `x` and `y` (1 ≤ x, y ≤ 10^6).\n\n**Output:**\n- An integer representing the absolute difference between the sum of the prime factors of `x` and `y`.\n\n**Sample Input:**\n```\n18 28\n```\n\n**Sample Output:**\n```\n2\n```", "reference": "def prime_factor_difference(x, y):\n \"\"\"\n Calculate the absolute difference between the sum of the prime factors of two integers.\n\n Parameters:\n x (int): The first integer.\n y (int): The second integer.\n\n Returns:\n int: The absolute difference between the sum of the prime factors of x and y.\n \"\"\"\n def sum_of_prime_factors(n):\n \"\"\"\n Calculate the sum of the prime factors of a given integer.\n\n Parameters:\n n (int): The integer to find the prime factors of.\n\n Returns:\n int: The sum of the prime factors of n.\n \"\"\"\n def smallest_prime_divisor(n):\n \"\"\"\n Find the smallest prime divisor of a given integer.\n\n Parameters:\n n (int): The integer to find the smallest prime divisor of.\n\n Returns:\n int or None: The smallest prime divisor of n, or None if n is less than or equal to 1.\n \"\"\"\n if n <= 1:\n return None\n if n % 2 == 0:\n return 2\n for i in range(3, int(n**0.5) + 1, 2):\n if n % i == 0:\n return i\n return n\n \n prime_sum = 0\n while n > 1:\n spdiv = smallest_prime_divisor(n)\n if spdiv is not None:\n prime_sum += spdiv\n n //= spdiv\n return prime_sum\n\n sum_x = sum_of_prime_factors(x)\n sum_y = sum_of_prime_factors(y)\n\n return abs(sum_x - sum_y)", "tests": ["assert prime_factor_difference(10, 15) == 1", "assert prime_factor_difference(28, 49) == 5", "assert prime_factor_difference(1, 1) == 0", "assert prime_factor_difference(2, 3) == 1", "assert prime_factor_difference(18, 27) == 3", "assert prime_factor_difference(100, 100) == 0", "assert prime_factor_difference(13, 17) == 4", "assert prime_factor_difference(20, 30) == 2", "assert prime_factor_difference(0, 1) == 0", "assert prime_factor_difference(14, 21) == 2"], "function": "prime_factor_difference", "signature": "def prime_factor_difference(x, y):", "score": 0.6, "domain": "generic"} {"id": "11888a33e30f9282e3d82c6539088d92", "problem": "You are given an undirected and unweighted graph represented as an adjacency list `graph` and a source vertex `start`. Your task is to implement a function `bfs_shortest_path(graph, start)` that performs a breadth-first search (BFS) to determine the shortest path distances from the source vertex to all other vertices in the graph. The function should return a dictionary where the keys are the vertices and the values are the shortest path distances from the source vertex.\n\n**Input:**\n- `graph`: A dictionary representing the graph where each key is a vertex and its value is a list of adjacent vertices.\n- `start`: A string representing the source vertex.\n\n**Output:**\n- A dictionary with vertices as keys and their shortest path distances from the source vertex as values.\n\n**Sample Input:**\n```python\ngraph = {'A': ['B', 'C'], 'B': ['A', 'D', 'E'], 'C': ['A', 'F'], 'D': ['B'], 'E': ['B', 'F'], 'F': ['C', 'E']}\nstart = 'A'\n```\n\n**Sample Output:**\n```python\n{'A': 0, 'B': 1, 'C': 1, 'D': 2, 'E': 2, 'F': 2}\n```", "reference": "from collections import deque\n\ndef bfs_shortest_path(graph, start):\n \"\"\"\n Perform a breadth-first search to find the shortest path distances from the source vertex to all other vertices in an undirected and unweighted graph.\n\n :param graph: A dictionary representing the graph where each key is a vertex and its value is a list of adjacent vertices.\n :param start: A string representing the source vertex.\n :return: A dictionary with vertices as keys and their shortest path distances from the source vertex as values.\n \"\"\"\n distances = {vertex: float('inf') for vertex in graph}\n distances[start] = 0\n \n queue = deque([start])\n \n while queue:\n current_vertex = queue.popleft()\n \n for neighbor in graph[current_vertex]:\n if distances[neighbor] == float('inf'):\n distances[neighbor] = distances[current_vertex] + 1\n queue.append(neighbor)\n \n return distances", "tests": ["assert bfs_shortest_path({'A': ['B', 'C'], 'B': ['A', 'D', 'E'], 'C': ['A', 'F'], 'D': ['B'], 'E': ['B', 'F'], 'F': ['C', 'E']}, 'A') == {'A': 0, 'B': 1, 'C': 1, 'D': 2, 'E': 2, 'F': 2}", "assert bfs_shortest_path({'A': ['B'], 'B': ['A', 'C'], 'C': ['B']}, 'A') == {'A': 0, 'B': 1, 'C': 2}", "assert bfs_shortest_path({'A': ['B', 'C'], 'B': ['A'], 'C': ['A']}, 'A') == {'A': 0, 'B': 1, 'C': 1}", "assert bfs_shortest_path({'A': ['B', 'C'], 'B': ['A', 'D'], 'C': ['A', 'E'], 'D': ['B'], 'E': ['C']}, 'A') == {'A': 0, 'B': 1, 'C': 1, 'D': 2, 'E': 2}", "assert bfs_shortest_path({'A': ['B'], 'B': ['C'], 'C': ['D'], 'D': []}, 'A') == {'A': 0, 'B': 1, 'C': 2, 'D': 3}", "assert bfs_shortest_path({'A': [], 'B': [], 'C': []}, 'A') == {'A': 0, 'B': float('inf'), 'C': float('inf')}", "assert bfs_shortest_path({'A': ['B', 'C'], 'B': ['A', 'D'], 'C': ['A', 'E'], 'D': ['B', 'F'], 'E': ['C', 'F'], 'F': ['D', 'E']}, 'A') == {'A': 0, 'B': 1, 'C': 1, 'D': 2, 'E': 2, 'F': 3}", "assert bfs_shortest_path({'A': ['B', 'C'], 'B': ['A'], 'C': ['A', 'D'], 'D': ['C']}, 'D') == {'A': 2, 'B': 3, 'C': 1, 'D': 0}", "assert bfs_shortest_path({'A': ['B', 'C'], 'B': ['A', 'D'], 'C': ['A', 'E'], 'D': ['B'], 'E': ['C']}, 'E') == {'A': 2, 'B': 3, 'C': 1, 'D': 2, 'E': 0}", "assert bfs_shortest_path({'A': ['B'], 'B': ['C'], 'C': ['D'], 'D': ['E'], 'E': ['F'], 'F': ['G'], 'G': ['H'], 'H': ['I'], 'I': ['J'], 'J': []}, 'A') == {'A': 0, 'B': 1, 'C': 2, 'D': 3, 'E': 4, 'F': 5, 'G': 6, 'H': 7, 'I': 8, 'J': 9}"], "function": "bfs_shortest_path", "signature": "def bfs_shortest_path(graph, start):", "score": 0.9, "domain": "generic"} {"id": "2a7754d90a712b98a30d3f9077e4e946", "problem": "You are tasked with writing an efficient Python function to compute the factorial of a given non-negative integer. Your function should be optimized for both performance and readability, capable of handling large inputs without running into recursion depth issues. Implement the function `factorial(n)` and ensure it raises a `ValueError` if the input is negative. \n\n**Sample Input:**\n```\n5\n```\n\n**Sample Output:**\n```\n120\n```", "reference": "import math\n\ndef factorial(n):\n \"\"\"\n Calculate the factorial of a non-negative integer n.\n\n This function uses an iterative approach and built-in optimizations\n to efficiently handle large inputs without running into recursion depth issues.\n \n Parameters:\n n (int): A non-negative integer whose factorial is to be calculated.\n\n Returns:\n int: The factorial of the given number.\n \n Raises:\n ValueError: If the input is a negative integer.\n \"\"\"\n if n < 0:\n raise ValueError(\"Input must be a non-negative integer.\")\n \n return math.factorial(n)\n\n# Example usage:\n# print(factorial(5)) # Output: 120", "tests": ["assert factorial(0) == 1", "assert factorial(1) == 1", "assert factorial(5) == 120", "assert factorial(10) == 3628800", "assert factorial(20) == 2432902008176640000", "assert factorial(100) == 93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000", "assert factorial(1000) == math.factorial(1000)", "assert factorial(12) == 479001600", "assert factorial(15) == 1307674368000", "assert factorial(25) == 15511210043330985984000000"], "function": "factorial", "signature": "def factorial(n):", "score": 1.0, "domain": "generic"} {"id": "a504ab330fdcdafbc500afab128fc20f", "problem": "You are given a CSV file named `employees.csv` containing information about employees. Each row in the CSV file has the following columns: `id`, `name`, `department`, and `salary`. Your task is to write a Python script that reads this CSV file and calculates the total salary of all employees in each department. The script should handle potential errors, such as the file not existing or containing invalid data.\n\n**Input:**\n- A CSV file `employees.csv` with the following format:\n ```\n id,name,department,salary\n 1,Alice,HR,50000\n 2,Bob,Engineering,80000\n 3,Charlie,HR,60000\n 4,David,Engineering,90000\n 5,Eve,Marketing,70000\n ```\n\n**Output:**\n- The total salary per department, formatted as:\n ```\n Total salary per department:\n HR: 110000.00\n Engineering: 170000.00\n Marketing: 70000.00\n ```\n\n**Constraints:**\n- The CSV file may contain invalid data (e.g., non-numeric salary values). Your program should skip such rows and print an error message.\n- If the file does not exist, your program should print an appropriate error message.", "reference": "import csv\nfrom collections import defaultdict\n\ndef total_salary_per_department(file_path):\n \"\"\"\n Reads a CSV file and calculates the total salary of all employees in each department.\n \n Parameters:\n file_path (str): The path to the CSV file.\n \n Returns:\n None: Prints the total salary per department or an error message if the file is not found or contains invalid data.\n \"\"\"\n department_salary = defaultdict(float)\n \n try:\n with open(file_path, mode='r', newline='') as file:\n reader = csv.DictReader(file)\n for row in reader:\n try:\n salary = float(row['salary'])\n department_salary[row['department']] += salary\n except (ValueError, KeyError):\n print(f\"Invalid data in row: {row}. Skipping this row.\")\n \n except FileNotFoundError:\n print(f\"Error: The file '{file_path}' does not exist.\")\n except Exception as e:\n print(f\"An error occurred: {e}\")\n else:\n print(\"Total salary per department:\")\n for department, total in department_salary.items():\n print(f\"{department}: {total:.2f}\")\n\n# Example usage:\n# total_salary_per_department('employees.csv')", "tests": ["assert total_salary_per_department('non_existent_file.csv') is None", "assert total_salary_per_department('invalid_format.txt') is None", "assert total_salary_per_department('empty_file.csv') is None", "assert total_salary_per_department('single_entry_valid.csv') is None", "assert total_salary_per_department('multiple_entries_valid.csv') is None", "assert total_salary_per_department('mixed_valid_invalid_entries.csv') is None", "assert total_salary_per_department('missing_salary_column.csv') is None", "assert total_salary_per_department('missing_department_column.csv') is None", "assert total_salary_per_department('invalid_salary_values.csv') is None", "assert total_salary_per_department('large_file.csv') is None"], "function": "total_salary_per_department", "signature": "def total_salary_per_department(file_path):", "score": 1.0, "domain": "generic"} {"id": "9ce191d8b17b3ea817de9968b067e269", "problem": "You are given a list of daily stock prices. Your task is to determine the optimal days to buy and sell the stock to achieve the maximum profit from a single transaction. If no profit can be made, return an empty list. The function should return a list of tuples, where each tuple contains two integers representing the buy and sell days, respectively.\n\n**Input:**\n- A list of integers `stock_prices` where `stock_prices[i]` is the price of the stock on day `i`.\n\n**Output:**\n- A list of tuples `[(buy_day, sell_day)]` representing the optimal days to buy and sell the stock to maximize profit. If no profit can be made, return an empty list.\n\n**Constraints:**\n- `1 <= len(stock_prices) <= 10^5`\n- `0 <= stock_prices[i] <= 10^4`\n\n**Sample Input:**\n```\n[7, 1, 5, 3, 6, 4]\n```\n\n**Sample Output:**\n```\n[(1, 4)]\n```", "reference": "def optimize_stock_prices(stock_prices):\n \"\"\"\n Determine the optimal days to buy and sell the stock to maximize profit from a single transaction.\n\n :param stock_prices: List of integers representing daily stock prices.\n :return: List of tuples with the optimal buy and sell days to maximize profit.\n \"\"\"\n if not stock_prices or len(stock_prices) < 2:\n return []\n\n min_price = stock_prices[0]\n max_profit = 0\n best_buy_day = 0\n best_sell_day = 0\n\n for sell_day in range(1, len(stock_prices)):\n current_price = stock_prices[sell_day]\n potential_profit = current_price - min_price\n\n if potential_profit > max_profit:\n max_profit = potential_profit\n best_buy_day = sell_day - 1 if stock_prices[sell_day - 1] == min_price else best_buy_day\n best_sell_day = sell_day\n\n if current_price < min_price:\n min_price = current_price\n\n return [(best_buy_day, best_sell_day)] if max_profit > 0 else []", "tests": ["assert optimize_stock_prices([7, 1, 5, 3, 6, 4]) == [(1, 4)]", "assert optimize_stock_prices([7, 6, 4, 3, 1]) == []", "assert optimize_stock_prices([1, 2, 3, 4, 5]) == [(0, 4)]", "assert optimize_stock_prices([1, 2]) == [(0, 1)]", "assert optimize_stock_prices([1]) == []", "assert optimize_stock_prices([]) == []", "assert optimize_stock_prices([3, 3, 5, 0, 0, 3, 1, 4]) == [(3, 6)]", "assert optimize_stock_prices([10, 7, 5, 8, 11, 9]) == [(2, 4)]", "assert optimize_stock_prices([1, 2, 4, 2, 5, 7, 2, 4, 9, 0]) == [(0, 8)]", "assert optimize_stock_prices([1, 3, 2, 8, 4, 9]) == [(0, 5)]"], "function": "optimize_stock_prices", "signature": "def optimize_stock_prices(stock_prices):", "score": 0.9, "domain": "generic"} {"id": "8e542ee8309454214de8162b9fbb1f24", "problem": "You are given a 2D grid of integers representing temperature readings from a thermal imaging camera. Each cell in the grid contains a temperature value. The valid temperature range is specified by the parameters `temp_min` and `temp_max`. Additionally, you are provided with the corresponding radiance values for these temperatures, given by `rad_min` and `rad_max`.\n\nYour task is to write a function `convert_temperature_to_radiance` that converts the given temperature grid into a radiance grid. The conversion formula is as follows:\n\n`radiance = ((rad_max - rad_min) / (temp_max - temp_min)) * (temperature - temp_min) + rad_min`\n\nThe function should take in the temperature grid, `temp_min`, `temp_max`, `rad_min`, and `rad_max` as parameters and return the corresponding radiance grid. For any temperature readings outside the specified `temp_min` and `temp_max` range, the function should replace the corresponding radiance value with `None` in the output grid.\n\n**Input:**\n- A 2D list of integers `temperature_grid` representing the temperature readings.\n- Four integers `temp_min`, `temp_max`, `rad_min`, and `rad_max`.\n\n**Output:**\n- A 2D list of floats or `None` values representing the radiance grid.\n\n**Sample Input:**\n```python\ntemperature_grid = [[20, 25, 30], [15, 40, 35]]\ntemp_min = 20\ntemp_max = 35\nrad_min = 100\nrad_max = 200\n```\n\n**Sample Output:**\n```python\n[[100.0, 150.0, 200.0], [None, None, 175.0]]\n```", "reference": "def convert_temperature_to_radiance(temperature_grid, temp_min, temp_max, rad_min, rad_max):\n \"\"\"\n Converts a 2D grid of temperature readings to a 2D grid of radiance values.\n \n Parameters:\n - temperature_grid: List[List[int]], a 2D list of temperature readings.\n - temp_min: int, the minimum valid temperature.\n - temp_max: int, the maximum valid temperature.\n - rad_min: int, the minimum radiance value corresponding to temp_min.\n - rad_max: int, the maximum radiance value corresponding to temp_max.\n \n Returns:\n - List[List[float or None]], a 2D list of radiance values with None for invalid temperatures.\n \"\"\"\n slope = (rad_max - rad_min) / (temp_max - temp_min)\n intercept = rad_min - slope * temp_min\n radiance_grid = []\n \n for row in temperature_grid:\n radiance_row = []\n for temperature in row:\n if temp_min <= temperature <= temp_max:\n radiance = slope * temperature + intercept\n radiance_row.append(radiance)\n else:\n radiance_row.append(None)\n radiance_grid.append(radiance_row)\n \n return radiance_grid", "tests": ["assert convert_temperature_to_radiance([[20, 25, 30], [35, 40, 45]], 20, 40, 100, 200) == [[100.0, 150.0, 200.0], [250.0, None, None]]", "assert convert_temperature_to_radiance([[15, 20, 25], [30, 35, 40]], 20, 35, 50, 150) == [[None, 50.0, 100.0], [150.0, None, None]]", "assert convert_temperature_to_radiance([[22, 24, 26], [28, 30, 32]], 20, 30, 100, 200) == [[120.0, 140.0, 160.0], [180.0, 200.0, None]]", "assert convert_temperature_to_radiance([[10, 15, 20], [25, 30, 35]], 15, 30, 0, 100) == [[None, 0.0, 50.0], [100.0, None, None]]", "assert convert_temperature_to_radiance([[20, 20, 20], [20, 20, 20]], 20, 20, 100, 200) == [[None, None, None], [None, None, None]]", "assert convert_temperature_to_radiance([[25, 25, 25], [25, 25, 25]], 20, 30, 100, 200) == [[150.0, 150.0, 150.0], [150.0, 150.0, 150.0]]", "assert convert_temperature_to_radiance([[10, 20, 30], [40, 50, 60]], 10, 60, 0, 100) == [[0.0, 20.0, 40.0], [60.0, 80.0, 100.0]]", "assert convert_temperature_to_radiance([[20, 25, 30], [35, 40, 45]], 20, 45, 100, 200) == [[100.0, 125.0, 150.0], [175.0, 200.0, None]]", "assert convert_temperature_to_radiance([[20, 25, 30], [35, 40, 45]], 20, 40, 100, 200) == [[100.0, 125.0, 150.0], [175.0, 200.0, None]]", "assert convert_temperature_to_radiance([[20, 25, 30], [35, 40, 45]], 20, 45, 100, 200) == [[100.0, 125.0, 150.0], [175.0, 200.0, None]]"], "function": "convert_temperature_to_radiance", "signature": "def convert_temperature_to_radiance(temperature_grid, temp_min, temp_max, rad_min, rad_max):", "score": 0.4, "domain": "generic"} {"id": "72b5b19eb86b10b0aed040f1f3dca0a8", "problem": "You are given a dictionary `d` where keys are unique strings and values are integers. Your task is to implement a function `sort_dict_by_values(d)` that returns a new dictionary with the items sorted by their values in ascending order. \n\n**Input:**\n- A dictionary `d` with string keys and integer values.\n\n**Output:**\n- A new dictionary with the same keys and values, sorted by values in ascending order.\n\n**Sample Input:**\n```python\n{\"a\": 3, \"b\": 1, \"c\": 2}\n```\n\n**Sample Output:**\n```python\n{\"b\": 1, \"c\": 2, \"a\": 3}\n```", "reference": "def sort_dict_by_values(d):\n \"\"\"\n Sorts a dictionary by its values in ascending order.\n\n Parameters:\n d (dict): A dictionary with string keys and integer values.\n\n Returns:\n dict: A new dictionary with items sorted by values in ascending order.\n \"\"\"\n sorted_items = sorted(d.items(), key=lambda item: item[1])\n sorted_dict = dict(sorted_items)\n return sorted_dict\n\n# Example usage:\ninput_dict = {\"a\": 3, \"b\": 1, \"c\": 2}\nsorted_dict = sort_dict_by_values(input_dict)\nprint(sorted_dict) # Output: {'b': 1, 'c': 2, 'a': 3}", "tests": ["assert sort_dict_by_values({\"a\": 3, \"b\": 1, \"c\": 2}) == {\"b\": 1, \"c\": 2, \"a\": 3}", "assert sort_dict_by_values({\"x\": 10, \"y\": 5, \"z\": 15}) == {\"y\": 5, \"x\": 10, \"z\": 15}", "assert sort_dict_by_values({\"apple\": 2, \"banana\": 1, \"cherry\": 3}) == {\"banana\": 1, \"apple\": 2, \"cherry\": 3}", "assert sort_dict_by_values({}) == {}", "assert sort_dict_by_values({\"same\": 1, \"values\": 1, \"here\": 1}) == {\"same\": 1, \"values\": 1, \"here\": 1}", "assert sort_dict_by_values({\"negative\": -1, \"zero\": 0, \"positive\": 1}) == {\"negative\": -1, \"zero\": 0, \"positive\": 1}", "assert sort_dict_by_values({\"floats\": 1.5, \"integers\": 2, \"mixed\": 1.2}) == {\"mixed\": 1.2, \"floats\": 1.5, \"integers\": 2}", "assert sort_dict_by_values({\"a\": 100, \"b\": 100, \"c\": 100, \"d\": 99}) == {\"d\": 99, \"a\": 100, \"b\": 100, \"c\": 100}", "assert sort_dict_by_values({\"single\": 42}) == {\"single\": 42}", "assert sort_dict_by_values({\"unordered\": 3, \"keys\": 2, \"sorted\": 1}) == {\"sorted\": 1, \"keys\": 2, \"unordered\": 3}"], "function": "sort_dict_by_values", "signature": "def sort_dict_by_values(d):", "score": 1.0, "domain": "generic"} {"id": "8b45f5e1c520c538388d794417d0ac82", "problem": "You are given a list of integers `nums`. Your task is to find the maximum difference between any two elements in the list such that the larger element appears after the smaller one. If no such pair exists, return 0.\n\n**Input:**\n- A list of integers `nums` (1 ≤ len(nums) ≤ 10^5), where each integer is in the range [-10^4, 10^4].\n\n**Output:**\n- An integer representing the maximum difference. If no such pair exists, return 0.\n\n**Sample Input:**\n```\n[7, 1, 5, 3, 6, 4]\n```\n\n**Sample Output:**\n```\n5\n```\n\n**Sample Input:**\n```\n[7, 6, 4, 3, 1]\n```\n\n**Sample Output:**\n```\n0\n```", "reference": "def max_difference(nums):\n \"\"\"\n Finds the maximum difference between any two elements in the list such that\n the larger element appears after the smaller one.\n\n :param nums: List of integers\n :return: Maximum difference as an integer\n \"\"\"\n if not nums or len(nums) < 2:\n return 0\n \n min_value = nums[0]\n max_diff = 0\n \n for i in range(1, len(nums)):\n current_diff = nums[i] - min_value\n if current_diff > max_diff:\n max_diff = current_diff\n if nums[i] < min_value:\n min_value = nums[i]\n \n return max_diff", "tests": ["assert max_difference([7, 1, 5, 3, 6, 4]) == 5", "assert max_difference([7, 6, 4, 3, 1]) == 0", "assert max_difference([1, 2, 3, 4, 5]) == 4", "assert max_difference([10, 7, 5, 8, 11, 9]) == 6", "assert max_difference([1]) == 0", "assert max_difference([]) == 0", "assert max_difference([3, 3, 3, 3, 3]) == 0", "assert max_difference([1, 100, 2, 99, 3, 98]) == 99", "assert max_difference([1, 2, 0, 4, 3, 5]) == 4", "assert max_difference([5, 4, 3, 2, 1, 0, -1, -2]) == 0"], "function": "max_difference", "signature": "def max_difference(nums):", "score": 0.9, "domain": "algorithmic"} {"id": "e5630d4409fce7b86320bf05fd151804", "problem": "You are given a string representing a chemical reaction in the format used by the Chemkin software. The reaction is described as a set of reactants and products, separated by an equals sign. The reactants and products are separated by a plus sign, and each reactant or product is a string representing a chemical species. The reaction may be reversible, indicated by '<=>', or irreversible, indicated by '=>'. The reaction may also involve a third body, indicated by '(+M)' or '(+m)'. Additionally, the string may contain comments and rate constants specified after an exclamation mark '!'. Your task is to write a function that takes this string as input and returns two sets: one containing the reactants and one containing the products. The function should handle both reversible and irreversible reactions, remove any third body indicators from the reactants and products, and ignore any comments or rate constants specified in the line.\n\n**Sample Input:**\n```\nO + H2 <=> OH + H (+M) ! This is a comment with a rate constant 1.5e5\n```\n\n**Sample Output:**\n```\nReactants: {'O', 'H2'}\nProducts: {'OH', 'H'}\n```", "reference": "def parse_chemical_reaction(reaction: str) -> (set, set):\n \"\"\"\n Parses a chemical reaction string and returns sets of reactants and products.\n \n Parameters:\n reaction (str): A string representing a chemical reaction in Chemkin format.\n \n Returns:\n (set, set): A tuple containing two sets, one for reactants and one for products.\n \"\"\"\n # Split the reaction string into the chemical equation part and comment part\n if '!' in reaction:\n equation_part = reaction.split('!')[0]\n else:\n equation_part = reaction\n\n # Replace '<=>' or '=>' with '=' for uniform processing\n equation_part = equation_part.replace('<=>', '=').replace('=>', '=')\n\n # Split the equation into reactants and products based on '='\n reactants_str, products_str = equation_part.split('=')\n\n # Split the reactants and products into individual species\n reactants = set([reactant.strip() for reactant in reactants_str.split('+')])\n products = set([product.strip() for product in products_str.split('+')])\n\n # Remove any third body indicators\n third_body_indicators = {'(+M)', '(+m)'}\n reactants -= third_body_indicators\n products -= third_body_indicators\n\n return reactants, products\n\n# Example usage\nreaction = 'O + H2 <=> OH + H (+M) ! This is a comment with a rate constant 1.5e5'\nreactants, products = parse_chemical_reaction(reaction)\nprint(\"Reactants: \", reactants)\nprint(\"Products: \", products)", "tests": ["assert parse_chemical_reaction('O + H2 <=> OH + H (+M)') == ({'O', 'H2'}, {'OH', 'H'})", "assert parse_chemical_reaction('CH4 + O2 => CO2 + H2O') == ({'CH4', 'O2'}, {'CO2', 'H2O'})", "assert parse_chemical_reaction('A + B <=> C ! Comment here') == ({'A', 'B'}, {'C'})", "assert parse_chemical_reaction('H2 + O2 => H2O (+M)') == ({'H2', 'O2'}, {'H2O'})", "assert parse_chemical_reaction('N2 + O2 <=> NO2 (+m)') == ({'N2', 'O2'}, {'NO2'})", "assert parse_chemical_reaction('CO + O2 => CO2 (+M) ! Rate constant 1.2e10') == ({'CO', 'O2'}, {'CO2'})", "assert parse_chemical_reaction('H + Cl2 => HCl (+M)') == ({'H', 'Cl2'}, {'HCl'})", "assert parse_chemical_reaction('A + B + C <=> D + E (+M)') == ({'A', 'B', 'C'}, {'D', 'E'})", "assert parse_chemical_reaction('H2 + O2 => H2O') == ({'H2', 'O2'}, {'H2O'})", "assert parse_chemical_reaction('A <=> B (+m) ! Another comment') == ({'A'}, {'B'})"], "function": "parse_chemical_reaction", "signature": "def parse_chemical_reaction(reaction: str) -> (set, set):", "score": 0.3, "domain": "generic"} {"id": "fec390a7f8aa14a913ed9bed8b6c2959", "problem": "You are tasked with implementing a function `greet_user` that processes user data and returns a personalized greeting message based on the user's age group. The function should handle invalid inputs gracefully. The age groups are defined as follows:\n- 0-12: \"child\"\n- 13-18: \"teenager\"\n- 19-64: \"adult\"\n- 65+: \"senior\"\n\nThe function should return an error message if the input is invalid. Specifically, the name must be a non-empty string, and the age must be a non-negative integer.\n\n**Input:**\n- The function takes two parameters: `name` (a string) and `age` (an integer).\n\n**Output:**\n- The function returns a string. If the inputs are valid, it returns a personalized greeting message. If the inputs are invalid, it returns an error message.\n\n**Sample Input/Output:**\n- `greet_user(\"Alice\", 25)` should return `\"Hello, Alice! You are an adult.\"`\n- `greet_user(\"Bob\", -5)` should return `\"Error: Invalid age. Please provide a non-negative integer for the age.\"`\n- `greet_user(\"\", 10)` should return `\"Error: Invalid name. Please provide a valid string for the name.\"`", "reference": "def greet_user(name, age):\n \"\"\"\n Returns a personalized greeting message based on the user's age group.\n \n Parameters:\n name (str): The user's name.\n age (int): The user's age.\n \n Returns:\n str: A personalized greeting message or an error message if inputs are invalid.\n \"\"\"\n # Validate the name input\n if not isinstance(name, str) or not name.strip():\n return \"Error: Invalid name. Please provide a valid string for the name.\"\n \n # Validate the age input\n if not isinstance(age, int) or age < 0:\n return \"Error: Invalid age. Please provide a non-negative integer for the age.\"\n \n # Determine the age group\n if 0 <= age <= 12:\n age_group = \"child\"\n elif 13 <= age <= 18:\n age_group = \"teenager\"\n elif 19 <= age <= 64:\n age_group = \"adult\"\n else: # age >= 65\n age_group = \"senior\"\n \n # Return the personalized greeting message\n return f\"Hello, {name}! You are a {age_group}.\"", "tests": ["assert greet_user(\"Alice\", 25) == \"Hello, Alice! You are an adult.\"", "assert greet_user(\"Bob\", 10) == \"Hello, Bob! You are a child.\"", "assert greet_user(\"Charlie\", 15) == \"Hello, Charlie! You are a teenager.\"", "assert greet_user(\"David\", 70) == \"Hello, David! You are a senior.\"", "assert greet_user(\"\", 25) == \"Error: Invalid name. Please provide a valid string for the name.\"", "assert greet_user(\"Eve\", -5) == \"Error: Invalid age. Please provide a non-negative integer for the age.\"", "assert greet_user(\"Frank\", 65) == \"Hello, Frank! You are a senior.\"", "assert greet_user(\"Grace\", 18) == \"Hello, Grace! You are a teenager.\"", "assert greet_user(\"Hannah\", 64) == \"Hello, Hannah! You are an adult.\"", "assert greet_user(123, 25) == \"Error: Invalid name. Please provide a valid string for the name.\""], "function": "greet_user", "signature": "def greet_user(name, age):", "score": 0.8, "domain": "generic"} {"id": "21a16453c82d7ef14441ed93b7eda3fb", "problem": "You are given an array of integers `nums` and an integer `target`. Your task is to find the length of the longest contiguous subarray whose sum equals `target`. If no such subarray exists, return 0. Your solution should run in O(n) time complexity.\n\n**Sample Input:**\n```\nnums = [1, -1, 5, -2, 3]\ntarget = 3\n```\n\n**Sample Output:**\n```\n4\n```", "reference": "def longest_subarray(nums, target):\n \"\"\"\n Finds the length of the longest contiguous subarray whose sum equals the target.\n \n :param nums: List[int] - The list of integers.\n :param target: int - The target sum.\n :return: int - The length of the longest subarray with sum equal to target.\n \"\"\"\n sum_indices = {0: -1} # Initialize with sum 0 at index -1 to handle subarrays starting from index 0\n running_sum = 0\n max_length = 0\n \n for i, num in enumerate(nums):\n running_sum += num\n if running_sum == target:\n max_length = i + 1\n elif (running_sum - target) in sum_indices:\n max_length = max(max_length, i - sum_indices[running_sum - target])\n \n # Only store the first occurrence of a particular sum\n if running_sum not in sum_indices:\n sum_indices[running_sum] = i\n \n return max_length", "tests": ["assert longest_subarray([1, -1, 5, -2, 3], 3) == 4", "assert longest_subarray([1, 2, 3, 4, 5], 9) == 2", "assert longest_subarray([1, 2, 3, 4, 5], 15) == 5", "assert longest_subarray([1, 2, 3, 4, 5], 10) == 1", "assert longest_subarray([1, 2, 3, 4, 5], 0) == 0", "assert longest_subarray([-1, -2, -3, -4, -5], -9) == 2", "assert longest_subarray([-1, 2, -3, 4, -5], 0) == 3", "assert longest_subarray([0, 0, 0, 0, 0], 0) == 5", "assert longest_subarray([1, 2, 3, 4, 5], 20) == 0", "assert longest_subarray([], 0) == 0"], "function": "longest_subarray", "signature": "def longest_subarray(nums, target):", "score": 0.6, "domain": "generic"} {"id": "30e0157e705897c862ccdf606af87ade", "problem": "You are tasked with implementing a function `validate_email` that determines the validity of an email address based on specific criteria. An email address is considered valid if it adheres to the following rules:\n- It starts with an alphanumeric character.\n- It may contain alphanumeric characters, dots (`.`), underscores (`_`), and hyphens (`-`).\n- It must contain exactly one `@` symbol.\n- The domain part (after the `@`) must start and end with an alphanumeric character.\n- The domain part may contain alphanumeric characters and hyphens (`-`).\n- The domain part must include at least one dot (`.`) separating the domain name and the top-level domain (TLD).\n- The TLD must consist of at least two alphabetic characters.\n\nYour function should return `True` if the email address is valid, and `False` otherwise.\n\n**Sample Input:**\n```\ntest.email+alex@leetcode.com\n```\n\n**Sample Output:**\n```\nTrue\n```", "reference": "import re\n\ndef validate_email(email):\n \"\"\"\n Validates an email address based on specific criteria.\n\n Parameters:\n email (str): The email address to validate.\n\n Returns:\n bool: True if the email address is valid, False otherwise.\n \"\"\"\n pattern = r'^[a-zA-Z0-9]([\\w\\.-]*[a-zA-Z0-9])?@[a-zA-Z0-9]([\\w-]*[a-zA-Z0-9])+(\\.[a-zA-Z]{2,})+$'\n return bool(re.match(pattern, email))\n\n# Test the function with the provided example\nprint(validate_email(\"test.email+alex@leetcode.com\")) # Output: True", "tests": ["assert validate_email(\"test.email+alex@leetcode.com\") == True", "assert validate_email(\"test.e.mail+bob.cathy@leetcode.com\") == True", "assert validate_email(\"testemail+david@lee.tcode.com\") == True", "assert validate_email(\"plainaddress\") == False", "assert validate_email(\"@missingusername.com\") == False", "assert validate_email(\"username@.com\") == False", "assert validate_email(\"username@com\") == False", "assert validate_email(\"username@domain..com\") == False", "assert validate_email(\"username@domain.c\") == False", "assert validate_email(\"username@domain.toolongtld\") == False"], "function": "validate_email", "signature": "def validate_email(email):", "score": 0.6, "domain": "generic"} {"id": "b72478e1630fe00d35cc4e2f4b31f194", "problem": "You are given a string `s` representing a number in base `base1`. Your task is to convert this number to a string representing the same number in base `base2`. Both `base1` and `base2` are integers ranging from 2 to 36, inclusive. The valid characters for each base are the first `n` uppercase letters of the Latin alphabet (A-Z) and the digits 0-9, where `n` is the value of the base. For example, in base 11, the valid characters are '0'-'9' and 'A', and in base 36, the valid characters are '0'-'9' and 'A'-'Z'.\n\n**Input:**\n- A string `s` (1 ≤ len(s) ≤ 100)\n- Two integers `base1` and `base2` (2 ≤ base1, base2 ≤ 36)\n\n**Output:**\n- A string representing the number in base `base2`.\n\n**Sample Input:**\n```\n\"1A\", 11, 2\n```\n\n**Sample Output:**\n```\n\"11010\"\n```", "reference": "def convert_base(s, base1, base2):\n \"\"\"\n Convert a string representation of a number from base1 to base2.\n\n :param s: str, the number in base1\n :param base1: int, the base of the input number\n :param base2: int, the base to convert the number to\n :return: str, the number in base2\n \"\"\"\n value_map = {str(i): i for i in range(10)}\n for i, char in enumerate('ABCDEFGHIJKLMNOPQRSTUVWXYZ'):\n value_map[char] = 10 + i\n \n num_base10 = 0\n for i, char in enumerate(reversed(s)):\n num_base10 += value_map[char] * (base1 ** i)\n \n char_map = {v: k for k, v in value_map.items()}\n \n if num_base10 == 0:\n return '0'\n \n num_base2 = []\n while num_base10 > 0:\n num_base2.append(char_map[num_base10 % base2])\n num_base10 //= base2\n \n return ''.join(reversed(num_base2))", "tests": ["assert convert_base(\"101\", 2, 10) == \"5\"", "assert convert_base(\"1A\", 16, 10) == \"26\"", "assert convert_base(\"10\", 10, 2) == \"1010\"", "assert convert_base(\"FF\", 16, 2) == \"11111111\"", "assert convert_base(\"Z\", 36, 10) == \"35\"", "assert convert_base(\"100\", 10, 36) == \"2S\"", "assert convert_base(\"0\", 2, 36) == \"0\"", "assert convert_base(\"123\", 4, 5) == \"200\"", "assert convert_base(\"ABC\", 16, 8) == \"5274\"", "assert convert_base(\"10\", 3, 9) == \"11\""], "function": "convert_base", "signature": "def convert_base(s, base1, base2):", "score": 0.8, "domain": "generic"} {"id": "153c5f741bb8c75e8bff69ebdf100c38", "problem": "Given a string `s` and a list of words `word_dict`, determine if `s` can be segmented into a sequence of one or more dictionary words. Each word in the dictionary may be reused multiple times in the segmentation. Return `True` if such a segmentation is possible, otherwise return `False`.\n\n**Constraints:**\n- `1 <= len(s) <= 300`\n- `1 <= len(word_dict) <= 1000`\n- `1 <= len(word) <= 20` for each word in `word_dict`\n- All inputs consist of lowercase English letters.\n\n**Sample Input:**\n```\ns = \"leetcode\"\nword_dict = [\"leet\", \"code\"]\n```\n\n**Sample Output:**\n```\nTrue\n```\n\n**Sample Input:**\n```\ns = \"applepenapple\"\nword_dict = [\"apple\", \"pen\"]\n```\n\n**Sample Output:**\n```\nTrue\n```\n\n**Sample Input:**\n```\ns = \"catsandog\"\nword_dict = [\"cats\", \"dog\", \"sand\", \"and\", \"cat\"]\n```\n\n**Sample Output:**\n```\nFalse\n```", "reference": "def word_break(s, word_dict):\n \"\"\"\n Determines if the string s can be segmented into a sequence of one or more dictionary words.\n \n :param s: The string to be segmented.\n :param word_dict: A list of words that can be used for segmentation.\n :return: True if s can be segmented, False otherwise.\n \"\"\"\n word_set = set(word_dict)\n n = len(s)\n dp = [False] * (n + 1)\n dp[0] = True\n \n for i in range(1, n + 1):\n for j in range(i):\n if dp[j] and s[j:i] in word_set:\n dp[i] = True\n break\n \n return dp[n]", "tests": ["assert word_break(\"leetcode\", [\"leet\", \"code\"]) == True", "assert word_break(\"applepenapple\", [\"apple\", \"pen\"]) == True", "assert word_break(\"catsandog\", [\"cats\", \"dog\", \"sand\", \"and\", \"cat\"]) == False", "assert word_break(\"abcd\", [\"a\", \"abc\", \"b\", \"cd\"]) == True", "assert word_break(\"abcd\", [\"ab\", \"cd\"]) == True", "assert word_break(\"abcd\", [\"abc\", \"d\", \"abcd\"]) == True", "assert word_break(\"abcd\", [\"xyz\", \"abcd\"]) == True", "assert word_break(\"abcd\", [\"xyz\", \"ab\"]) == False", "assert word_break(\"\", [\"a\", \"b\", \"c\"]) == True", "assert word_break(\"a\", [\"a\"]) == True"], "function": "word_break", "signature": "def word_break(s, word_dict):", "score": 1.0, "domain": "generic"} {"id": "a65bcc5bd8a02a036b041454d3a37cfe", "problem": "You are tasked with implementing a function to compute the average movie rating from a list of user ratings. Each user rating is an integer between 1 and 5, inclusive. Your function should handle the case where the list of ratings is empty by returning 0. \n\n**Function Signature:**\n```python\ndef calculate_average_rating(ratings: List[int]) -> float:\n```\n\n**Input:**\n- A list of integers `ratings` where each integer is between 1 and 5, inclusive.\n\n**Output:**\n- A float representing the average of the ratings. If the list is empty, return 0.0.\n\n**Sample Input:**\n```python\n[3, 5, 2, 4, 5]\n```\n\n**Sample Output:**\n```python\n3.8\n```\n\n**Constraints:**\n- 0 ≤ len(ratings) ≤ 1000", "reference": "from typing import List\n\ndef calculate_average_rating(ratings: List[int]) -> float:\n \"\"\"\n Calculate the average rating from a list of user ratings.\n \n :param ratings: List of integers representing user ratings.\n :return: The average rating as a float. Returns 0.0 if the list is empty.\n \"\"\"\n if not ratings:\n return 0.0\n return sum(ratings) / len(ratings)", "tests": ["assert calculate_average_rating([5, 5, 5, 5]) == 5", "assert calculate_average_rating([1, 2, 3, 4, 5]) == 3", "assert calculate_average_rating([1, 1, 1, 1, 1]) == 1", "assert calculate_average_rating([3, 3, 3]) == 3", "assert calculate_average_rating([]) == 0", "assert calculate_average_rating([2, 4, 4, 4, 5]) == 3.8", "assert calculate_average_rating([5, 1]) == 3", "assert calculate_average_rating([1]) == 1", "assert calculate_average_rating([5, 5, 5, 5, 5, 5]) == 5", "assert calculate_average_rating([2, 2, 3, 3, 4, 4]) == 3"], "function": "calculate_average_rating", "signature": "def calculate_average_rating(ratings: List[int]) -> float:", "score": 1.0, "domain": "generic"} {"id": "9b645e78e711a16cc13162302f82de78", "problem": "You are given a list of integers. Your task is to implement a function `sum_of_squares` that computes the sum of the squares of these integers. The function should be optimized to handle large input sizes efficiently.\n\n**Input:**\n- A list of integers `numbers` (1 ≤ len(numbers) ≤ 10^6), where each integer `x` satisfies -10^9 ≤ x ≤ 10^9.\n\n**Output:**\n- Return a single integer representing the sum of the squares of the elements in the list.\n\n**Sample Input:**\n```\n[1, 2, 3, 4]\n```\n\n**Sample Output:**\n```\n30\n```", "reference": "def sum_of_squares(numbers):\n \"\"\"\n Computes the sum of the squares of the elements in the given list of integers.\n\n :param numbers: List of integers\n :return: Sum of the squares of the integers in the list\n \"\"\"\n return sum(x ** 2 for x in numbers)", "tests": ["assert sum_of_squares([1, 2, 3, 4]) == 30", "assert sum_of_squares([0, 0, 0, 0]) == 0", "assert sum_of_squares([-1, -2, -3, -4]) == 30", "assert sum_of_squares([1.5, 2.5, 3.5]) == 21.25", "assert sum_of_squares([]) == 0", "assert sum_of_squares([1000000, 2000000]) == 5000000000000", "assert sum_of_squares([10, -10, 10, -10]) == 400", "assert sum_of_squares([1.1, 2.2, 3.3, 4.4]) == 33.89999999999999", "assert sum_of_squares([1e10, 2e10, 3e10]) == 1.4e21", "assert sum_of_squares([0.1, 0.2, 0.3, 0.4]) == 0.3"], "function": "sum_of_squares", "signature": "def sum_of_squares(numbers):", "score": 0.7, "domain": "generic"} {"id": "c5e2dbc9f899845b3360d2bb33a7f855", "problem": "You are given a list of strings. Your task is to implement a function `find_palindromes(strings)` that identifies and returns all the palindromes from the list. A string is considered a palindrome if, after converting it to lowercase and removing all non-alphanumeric characters, it reads the same forwards and backwards. \n\n**Input:**\n- A list of strings, where each string may contain uppercase and lowercase letters, digits, spaces, and punctuation.\n\n**Output:**\n- A list of strings that are palindromes according to the given definition.\n\n**Sample Input:**\n```python\n[\"A man, a plan, a canal, Panama\", \"Was it a car or a cat I saw?\", \"Hello, World!\", \"Madam, in Eden, I'm Adam\"]\n```\n\n**Sample Output:**\n```python\n[\"A man, a plan, a canal, Panama\", \"Was it a car or a cat I saw?\", \"Madam, in Eden, I'm Adam\"]\n```", "reference": "import re\n\ndef find_palindromes(strings):\n \"\"\"\n Identifies and returns all palindromes from the input list of strings.\n \n A string is considered a palindrome if, after converting it to lowercase\n and removing all non-alphanumeric characters, it reads the same forwards and backwards.\n \n :param strings: List of strings to be checked for palindromes.\n :return: List of strings that are palindromes.\n \"\"\"\n def is_palindrome(s):\n cleaned = re.sub(r'[^A-Za-z0-9]', '', s).lower()\n return cleaned == cleaned[::-1]\n \n return [s for s in strings if is_palindrome(s)]", "tests": ["assert find_palindromes([\"A man, a plan, a canal, Panama\"]) == [\"A man, a plan, a canal, Panama\"]", "assert find_palindromes([\"Was it a car or a cat I saw?\"]) == [\"Was it a car or a cat I saw?\"]", "assert find_palindromes([\"Hello, World!\"]) == []", "assert find_palindromes([\"Madam, in Eden, I'm Adam\"]) == [\"Madam, in Eden, I'm Adam\"]", "assert find_palindromes([\"No lemon, no melon\"]) == [\"No lemon, no melon\"]", "assert find_palindromes([\"Was it a car or a cat I saw?\", \"No lemon, no melon\"]) == [\"Was it a car or a cat I saw?\", \"No lemon, no melon\"]", "assert find_palindromes([\"\", \" \", \"a\", \"aa\"]) == [\"\", \" \", \"a\", \"aa\"]", "assert find_palindromes([\"Not a palindrome\", \"Definitely not\"]) == []", "assert find_palindromes([\"Able was I, I saw Elba\", \"Step on no pets\"]) == [\"Able was I, I saw Elba\", \"Step on no pets\"]", "assert find_palindromes([\"Madam\", \"racecar\", \"palindrome\"]) == [\"Madam\", \"racecar\"]"], "function": "find_palindromes", "signature": "def find_palindromes(strings):", "score": 1.0, "domain": "generic"} {"id": "38048b664678bdf811902c2ec3fb30fa", "problem": "You are tasked with implementing a function `fib_sum(n)` that computes the sum of the first `n` numbers in a modified Fibonacci sequence. This sequence starts with `0`, `1`, and `1`, and each subsequent number is the sum of the preceding three numbers. Your function should accept a single argument `n`, which is a positive integer. If `n` is not a positive integer, the function should raise a `TypeError` with the message \"Input must be a positive integer.\"\n\n**Sample Input and Output:**\n- Input: `n = 1`\n - Output: `0`\n- Input: `n = 4`\n - Output: `4`\n- Input: `n = 5`\n - Output: `7`", "reference": "def fib_sum(n):\n \"\"\"\n Computes the sum of the first n numbers in a modified Fibonacci sequence.\n The sequence starts with 0, 1, 1, and each subsequent number is the sum of the preceding three numbers.\n \n Parameters:\n n (int): The number of terms in the sequence to sum. Must be a positive integer.\n \n Returns:\n int: The sum of the first n numbers in the sequence.\n \n Raises:\n TypeError: If n is not a positive integer.\n \"\"\"\n if not isinstance(n, int) or n <= 0:\n raise TypeError(\"Input must be a positive integer.\")\n \n if n == 1:\n return 0\n elif n == 2:\n return 1\n elif n == 3:\n return 2\n \n sequence = [0, 1, 1]\n total_sum = sum(sequence)\n \n for i in range(3, n):\n next_value = sequence[-1] + sequence[-2] + sequence[-3]\n sequence.append(next_value)\n total_sum += next_value\n \n return total_sum", "tests": ["assert fib_sum(1) == 0", "assert fib_sum(2) == 1", "assert fib_sum(3) == 2", "assert fib_sum(4) == 4", "assert fib_sum(5) == 7", "assert fib_sum(6) == 13", "assert fib_sum(7) == 24", "assert fib_sum(8) == 44", "assert fib_sum(9) == 81", "assert fib_sum(10) == 149"], "function": "fib_sum", "signature": "def fib_sum(n):", "score": 0.4, "domain": "generic"} {"id": "bd09278fd0258edf7c9c4ac5b4ff1aa2", "problem": "You are given a list of integers `numbers` and an integer `limit`. Your task is to implement a function `find_common_multiples` that returns a list of integers which are common multiples of all the numbers in the `numbers` list and are less than or equal to the absolute value of `limit`. The function should handle negative integers in the input list by considering their absolute values.\n\n**Input:**\n- A list of integers `numbers` (1 ≤ len(numbers) ≤ 100, -1000 ≤ numbers[i] ≤ 1000)\n- An integer `limit` (-1000 ≤ limit ≤ 1000)\n\n**Output:**\n- A list of integers representing the common multiples of all numbers in `numbers` that are less than or equal to the absolute value of `limit`.\n\n**Sample Input:**\n- `numbers = [2, 3]`, `limit = 15`\n- `numbers = [-4, 6]`, `limit = 24`\n\n**Sample Output:**\n- `[6, 12, 15]`\n- `[12, 24]`", "reference": "from typing import List\nfrom math import gcd\n\ndef lcm(a: int, b: int) -> int:\n \"\"\"Calculate the Least Common Multiple of two integers.\"\"\"\n return abs(a * b) // gcd(a, b)\n\ndef find_common_multiples(numbers: List[int], limit: int) -> List[int]:\n \"\"\"\n Find all common multiples of the numbers in the list that are less than or equal to the absolute value of the limit.\n \n :param numbers: List of integers\n :param limit: Integer limit\n :return: List of common multiples\n \"\"\"\n # Handle negative numbers by taking the absolute value\n numbers = [abs(num) for num in numbers]\n limit = abs(limit)\n \n if not numbers:\n return []\n \n # Find the LCM of all numbers in the list\n common_lcm = numbers[0]\n for num in numbers[1:]:\n common_lcm = lcm(common_lcm, num)\n \n # Find all multiples of the LCM that are less than or equal to the limit\n multiples = []\n multiple = common_lcm\n while multiple <= limit:\n multiples.append(multiple)\n multiple += common_lcm\n \n return multiples\n\n# Example usage\n# print(find_common_multiples([2, 3], 15)) # Output: [6, 12, 15]\n# print(find_common_multiples([-4, 6], 24)) # Output: [12, 24]", "tests": ["assert find_common_multiples([2, 3], 15) == [6, 12]", "assert find_common_multiples([-4, 6], 24) == [12, 24]", "assert find_common_multiples([5, 10], 50) == [10, 20, 30, 40, 50]", "assert find_common_multiples([7, 14], 100) == [14, 28, 42, 56, 70, 84, 98]", "assert find_common_multiples([1, 2, 3], 6) == [6]", "assert find_common_multiples([0, 5], 10) == []", "assert find_common_multiples([], 10) == []", "assert find_common_multiples([15, -20], 100) == [60]", "assert find_common_multiples([3, 5, 7], 105) == [105]", "assert find_common_multiples([-1, -1, -1], 10) == [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]"], "function": "find_common_multiples", "signature": "def find_common_multiples(numbers: List[int], limit: int) -> List[int]:", "score": 0.9, "domain": "generic"} {"id": "78055f16a6cb29da6844431f88a1463f", "problem": "You are tasked with implementing a function `filter_text` that processes a given string `text` by removing all punctuation symbols, digits, whitespace characters, and the em dash character (\"—\" or \"–\"). Your function should not utilize any built-in string methods (such as `replace`, `strip`, `isdigit`) or regular expressions. \n\n**Input:**\n- A single string `text` (1 ≤ len(text) ≤ 10^5) consisting of ASCII characters.\n\n**Output:**\n- A string with all unwanted characters removed.\n\n**Sample Input:**\n```\nHello, World! 123 – Testing.\n```\n\n**Sample Output:**\n```\nHelloWorldTesting\n```", "reference": "def filter_text(text):\n \"\"\"\n Removes all punctuation symbols, digits, whitespace characters, and the em dash character from the input string.\n \n :param text: The input string to be filtered.\n :return: A string with all unwanted characters removed.\n \"\"\"\n # Define a list of characters to be removed\n unwanted_chars = []\n for i in range(32, 65): # ASCII values for space (32) to @ (64)\n unwanted_chars.append(chr(i))\n for i in range(58, 65): # ASCII values for : (58) to @ (64)\n unwanted_chars.append(chr(i))\n for i in range(91, 97): # ASCII values for [ (91) to ` (96)\n unwanted_chars.append(chr(i))\n for i in range(123, 127): # ASCII values for { (123) to DEL (126)\n unwanted_chars.append(chr(i))\n for i in range(48, 58): # ASCII values for 0 (48) to 9 (57)\n unwanted_chars.append(chr(i))\n unwanted_chars.append(chr(150)) # En dash\n unwanted_chars.append(chr(151)) # Em dash\n\n # Filter the text\n filtered_text = ''\n for char in text:\n if char not in unwanted_chars:\n filtered_text += char\n\n return filtered_text", "tests": ["assert filter_text(\"Hello, World!\") == \"HelloWorld\"", "assert filter_text(\"Python 3.8\") == \"Python\"", "assert filter_text(\"No digits or symbols here\") == \"Nodigitsorsymbolshere\"", "assert filter_text(\"1234567890\") == \"\"", "assert filter_text(\"Special—characters—here\") == \"Specialcharactershere\"", "assert filter_text(\"Punctuation: should, be; removed!\") == \"Punctuationshouldberemoved\"", "assert filter_text(\"Whitespace should be removed\") == \"Whitespaceshouldberemoved\"", "assert filter_text(\"Mixed123With456Symbols!\") == \"MixedWithSymbols\"", "assert filter_text(\"—Em—Dash—Test—\") == \"EmDashTest\"", "assert filter_text(\"\") == \"\""], "function": "filter_text", "signature": "def filter_text(text):", "score": 0.8, "domain": "generic"} {"id": "ce38ae8f4abd850abdf9c88f8eb55eb6", "problem": "You are given an integer `number` and a list of operations `operations`. Each operation is represented as a tuple where the first element is a string indicating the type of operation (\"add\", \"multiply\", \"subtract\", \"divide\") and the second element is an integer value to apply the operation with. Your task is to sequentially apply each operation to the `number` and return a list of intermediate results after each operation.\n\n**Constraints:**\n- The `number` is an integer within the range [-10^9, 10^9].\n- The `operations` list contains between 1 and 100 operations.\n- Each operation value is an integer within the range [-10^9, 10^9].\n- Division by zero should raise a `ValueError`.\n\n**Sample Input:**\n```python\nnumber = 10\noperations = [(\"add\", 5), (\"multiply\", 2), (\"subtract\", 3), (\"divide\", 4)]\n```\n\n**Sample Output:**\n```python\n[15, 30, 27, 6.75]\n```", "reference": "def apply_operations(number, operations):\n \"\"\"\n Apply a sequence of operations to a number and return intermediate results.\n\n :param number: Initial integer number to apply operations on.\n :param operations: List of tuples, each containing an operation type and a value.\n :return: List of intermediate results after each operation.\n :raises ValueError: If a division by zero is attempted.\n \"\"\"\n results = []\n for operation, value in operations:\n if operation == \"add\":\n number += value\n elif operation == \"multiply\":\n number *= value\n elif operation == \"subtract\":\n number -= value\n elif operation == \"divide\":\n if value != 0:\n number /= value\n else:\n raise ValueError(\"Division by zero is not allowed.\")\n results.append(number)\n return results", "tests": ["assert apply_operations(10, [(\"add\", 5)]) == [15]", "assert apply_operations(10, [(\"multiply\", 2), (\"add\", 3)]) == [20, 23]", "assert apply_operations(10, [(\"subtract\", 5), (\"multiply\", 2)]) == [5, 10]", "assert apply_operations(10, [(\"divide\", 2), (\"add\", 3)]) == [5.0, 8.0]", "assert apply_operations(10, [(\"add\", 0), (\"multiply\", 0)]) == [10, 0]", "assert apply_operations(10, [(\"subtract\", 10), (\"multiply\", 5)]) == [0, 0]", "assert apply_operations(10, [(\"divide\", 5), (\"subtract\", 1)]) == [2.0, 1.0]", "assert apply_operations(10, [(\"add\", -5), (\"multiply\", -2)]) == [5, -10]", "assert apply_operations(10, [(\"multiply\", 1), (\"divide\", 1)]) == [10.0, 10.0]", "assert apply_operations(10, [(\"add\", 5), (\"subtract\", 5), (\"multiply\", 2), (\"divide\", 2)]) == [15, 10, 20.0, 10.0]"], "function": "apply_operations", "signature": "def apply_operations(number, operations):", "score": 1.0, "domain": "generic"} {"id": "80e3809a1d8a6dc97a524ba1fc39e46b", "problem": "You are given two arrays of integers, `list_a` and `list_b`. Your task is to implement a function that returns an array containing the indices of the first occurrences of elements in `list_b` that are also present in `list_a`. If an element from `list_b` is not found in `list_a`, the corresponding index in the output array should be `None`. You are not allowed to use any built-in functions or data structures such as `dict`, `set`, or list comprehensions.\n\n**Input:**\n- Two arrays of integers, `list_a` and `list_b`.\n\n**Output:**\n- An array of integers or `None` values representing the indices of the first occurrences of elements from `list_b` in `list_a`.\n\n**Sample Input:**\n- `list_a = [10, 20, 30, 40, 50]`\n- `list_b = [30, 50, 20, 70]`\n\n**Sample Output:**\n- `[2, 4, 1, None]`", "reference": "def find_indices(list_a, list_b):\n \"\"\"\n Returns an array containing the indices of the first occurrences of elements in list_b that are also present in list_a.\n If an element from list_b is not found in list_a, the corresponding index in the output array should be None.\n \n :param list_a: List of integers.\n :param list_b: List of integers.\n :return: List of integers or None values.\n \"\"\"\n result = []\n b_length = 0\n while b_length < len(list_b):\n found_index = None\n a_length = 0\n while a_length < len(list_a):\n if list_b[b_length] == list_a[a_length]:\n found_index = a_length\n break\n a_length += 1\n result.append(found_index)\n b_length += 1\n return result", "tests": ["assert find_indices([10, 20, 30, 40, 50], [30, 50, 20, 70]) == [2, 4, 1, None]", "assert find_indices([1, 2, 3, 4, 5], [5, 4, 3, 2, 1]) == [4, 3, 2, 1, 0]", "assert find_indices([1, 2, 3, 4, 5], [6, 7, 8, 9, 10]) == [None, None, None, None, None]", "assert find_indices([], [1, 2, 3]) == [None, None, None]", "assert find_indices([1, 2, 3], []) == []", "assert find_indices([1, 1, 1, 1], [1, 1, 1, 1]) == [0, 0, 0, 0]", "assert find_indices([1, 2, 3, 4, 5], [3, 3, 3, 3]) == [2, 2, 2, 2]", "assert find_indices([10, 20, 30, 40, 50], [50, 40, 30, 20, 10]) == [4, 3, 2, 1, 0]", "assert find_indices([1, 2, 3, 4, 5], [1, 3, 5, 7, 9]) == [0, 2, 4, None, None]", "assert find_indices([1, 2, 3, 4, 5], [5, 3, 1]) == [4, 2, 0]"], "function": "find_indices", "signature": "def find_indices(list_a, list_b):", "score": 1.0, "domain": "generic"} {"id": "3b8b7dd6dfe1dd9a03aa4d8b27b562df", "problem": "You are given an array `A` of `n` integers. Your task is to find the length of the longest increasing subsequence in the array. The subsequence does not need to be contiguous. For example, for the array `[10, 9, 2, 5, 3, 7, 101, 18]`, the longest increasing subsequence is `[2, 3, 7, 101]`, which has a length of 4.\n\n**Input:**\n- The first line contains an integer `n` (1 ≤ n ≤ 1000), the length of the array.\n- The second line contains `n` space-separated integers `A[1], A[2], ..., A[n]` (0 ≤ A[i] ≤ 10^9).\n\n**Output:**\n- Print a single integer, the length of the longest increasing subsequence.\n\n**Sample Input:**\n```\n8\n10 9 2 5 3 7 101 18\n```\n\n**Sample Output:**\n```\n4\n```", "reference": "def longest_increasing_subsequence(A):\n \"\"\"\n Returns the length of the longest increasing subsequence in the array A.\n \n :param A: List[int] - The input array of integers.\n :return: int - The length of the longest increasing subsequence.\n \"\"\"\n if not A:\n return 0\n\n lis = [1] * len(A)\n\n for i in range(1, len(A)):\n for j in range(0, i):\n if A[i] > A[j] and lis[i] < lis[j] + 1:\n lis[i] = lis[j] + 1\n\n return max(lis)\n\n# Test the function\nA = [10, 9, 2, 5, 3, 7, 101, 18]\nprint(longest_increasing_subsequence(A)) # Output: 4", "tests": ["assert longest_increasing_subsequence([10, 9, 2, 5, 3, 7, 101, 18]) == 4", "assert longest_increasing_subsequence([0, 1, 0, 3, 2, 3]) == 4", "assert longest_increasing_subsequence([7, 7, 7, 7, 7, 7, 7]) == 1", "assert longest_increasing_subsequence([1, 2, 3, 4, 5]) == 5", "assert longest_increasing_subsequence([5, 4, 3, 2, 1]) == 1", "assert longest_increasing_subsequence([1, 3, 5, 4, 7]) == 4", "assert longest_increasing_subsequence([10, 22, 9, 33, 21, 50, 41, 60, 80]) == 6", "assert longest_increasing_subsequence([]) == 0", "assert longest_increasing_subsequence([1]) == 1", "assert longest_increasing_subsequence([3, 10, 2, 1, 20]) == 3"], "function": "longest_increasing_subsequence", "signature": "def longest_increasing_subsequence(A):", "score": 1.0, "domain": "algorithmic"} {"id": "a5af5b8267c4fb797b4f9cdf2bf7fe04", "problem": "You are given a list of integers `numbers`. Your task is to implement a function `find_mode` that determines the mode of the list, which is the element that appears most frequently. In the event of a tie, where multiple elements share the highest frequency, return the smallest of these elements. If the list is empty, the function should return `None`.\n\n**Input:**\n- A list of integers `numbers` (0 ≤ len(numbers) ≤ 10^5), where each integer is in the range [-10^9, 10^9].\n\n**Output:**\n- An integer representing the mode of the list, or `None` if the list is empty.\n\n**Sample Input 1:**\n```\n[1, 2, 2, 3, 3, 4, 4, 4, 5, 5, 5]\n```\n\n**Sample Output 1:**\n```\n4\n```\n\n**Sample Input 2:**\n```\n[6, 6, 7, 7, 8]\n```\n\n**Sample Output 2:**\n```\n6\n```\n\n**Sample Input 3:**\n```\n[]\n```\n\n**Sample Output 3:**\n```\nNone\n```", "reference": "def find_mode(numbers):\n \"\"\"\n Returns the mode of the list of integers. If there is a tie, returns the smallest element among them.\n Returns None if the list is empty.\n \n :param numbers: List of integers\n :return: Integer or None\n \"\"\"\n if not numbers:\n return None\n \n frequency = {}\n for num in numbers:\n if num in frequency:\n frequency[num] += 1\n else:\n frequency[num] = 1\n \n max_freq = max(frequency.values())\n modes = [num for num, freq in frequency.items() if freq == max_freq]\n \n return min(modes)", "tests": ["assert find_mode([1, 2, 2, 3, 3, 4, 4, 4, 5, 5, 5]) == 4", "assert find_mode([1, 1, 2, 2, 3, 3]) == 1", "assert find_mode([7, 7, 7, 8, 8, 9]) == 7", "assert find_mode([10, 20, 20, 10, 30]) == 10", "assert find_mode([5, 5, 5, 5, 5]) == 5", "assert find_mode([]) == None", "assert find_mode([1]) == 1", "assert find_mode([3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]) == 5", "assert find_mode([100, 200, 300, 100, 200, 300]) == 100", "assert find_mode([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) == 1"], "function": "find_mode", "signature": "def find_mode(numbers):", "score": 1.0, "domain": "generic"} {"id": "3762396851f595574878b1a1cb4b0030", "problem": "You are tasked with implementing a function `validate_date(date_str)` that determines if a given date string is valid according to the Gregorian calendar. The date string must be in the format `YYYY-MM-DD`. Your function should return `True` if the date is valid, and `False` otherwise.\n\n**Sample Input:**\n```\nvalidate_date(\"2023-02-29\")\nvalidate_date(\"2020-02-29\")\nvalidate_date(\"2021-04-31\")\nvalidate_date(\"2021-04-30\")\n```\n\n**Sample Output:**\n```\nFalse\nTrue\nFalse\nTrue\n```", "reference": "from datetime import datetime\n\ndef validate_date(date_str):\n \"\"\"\n Validates if the given date string is in the correct format and represents a real calendar date.\n \n Parameters:\n date_str (str): A date string in the format YYYY-MM-DD.\n \n Returns:\n bool: True if the date is valid, False otherwise.\n \"\"\"\n try:\n datetime.strptime(date_str, '%Y-%m-%d')\n return True\n except ValueError:\n return False", "tests": ["assert validate_date(\"2023-02-29\") == False", "assert validate_date(\"2020-02-29\") == True", "assert validate_date(\"2023-04-31\") == False", "assert validate_date(\"2023-06-30\") == True", "assert validate_date(\"2023-13-01\") == False", "assert validate_date(\"2023-00-10\") == False", "assert validate_date(\"2023-01-00\") == False", "assert validate_date(\"2023-01-32\") == False", "assert validate_date(\"2023-01-15\") == True", "assert validate_date(\"2023-12-31\") == True"], "function": "validate_date", "signature": "def validate_date(date_str):", "score": 1.0, "domain": "generic"} {"id": "dcd0d2787a32cdc4f70bfbd467a3626c", "problem": "You are given a task to compute the Photon Utilization Factor (PUF) for a solar panel. The PUF is defined as the ratio of the maximum power (Pmax) that the solar panel can produce to the total incident solar power (Pin). The maximum power (Pmax) is calculated by multiplying the photon conversion efficiency (η_photon) by the total incident solar power (Pin). The total incident solar power (Pin) is provided as input.\n\nWrite a function `calc_photon_utilization_factor` that takes two parameters: `photon_conversion_efficiency` (η_photon) and `total_incident_solar_power` (Pin). The function should return the Photon Utilization Factor (PUF) as a decimal.\n\n**Input:**\n- The first parameter `photon_conversion_efficiency` is a decimal representing the photon conversion efficiency (e.g., 0.15 for 15%).\n- The second parameter `total_incident_solar_power` is a decimal representing the total incident solar power in watts (W).\n\n**Output:**\n- Return the Photon Utilization Factor (PUF) as a decimal.\n\n**Sample Input:**\n- `photon_conversion_efficiency = 0.15`\n- `total_incident_solar_power = 1000`\n\n**Sample Output:**\n- `0.15`", "reference": "def calc_photon_utilization_factor(photon_conversion_efficiency, total_incident_solar_power):\n \"\"\"\n Calculate the Photon Utilization Factor (PUF) of a solar panel.\n \n :param photon_conversion_efficiency: Photon conversion efficiency (eta_photon) \n of the solar panel as a decimal (e.g., 0.15 for 15%)\n :param total_incident_solar_power: Total incident solar power (Pin) in watts (W)\n :return: Photon Utilization Factor (PUF) as a decimal\n \"\"\"\n Pmax = photon_conversion_efficiency * total_incident_solar_power\n PUF = Pmax / total_incident_solar_power if total_incident_solar_power != 0 else 0\n return PUF", "tests": ["assert calc_photon_utilization_factor(0.15, 1000) == 0.15", "assert calc_photon_utilization_factor(0.20, 500) == 0.20", "assert calc_photon_utilization_factor(0.0, 1000) == 0.0", "assert calc_photon_utilization_factor(1.0, 1000) == 1.0", "assert calc_photon_utilization_factor(0.15, 0) == 0", "assert calc_photon_utilization_factor(0.15, 2000) == 0.15", "assert calc_photon_utilization_factor(0.05, 100) == 0.05", "assert calc_photon_utilization_factor(0.33, 300) == 0.33", "assert calc_photon_utilization_factor(0.5, 1000) == 0.5", "assert calc_photon_utilization_factor(0.75, 1500) == 0.75"], "function": "calc_photon_utilization_factor", "signature": "def calc_photon_utilization_factor(photon_conversion_efficiency, total_incident_solar_power):", "score": 1.0, "domain": "generic"} {"id": "7fad17a431fd9ac7f9c39432775a5453", "problem": "You are given a list of lists, where each sublist contains integers. Your task is to write a function `sort_nested_lists` that sorts each sublist in ascending order and then sorts the list of lists based on the sum of the integers in each sublist. \n\n**Input:**\n- A list of lists of integers, `nested_lists`.\n\n**Output:**\n- A list of lists of integers, where each sublist is sorted in ascending order and the list of lists is sorted based on the sum of the integers in each sublist.\n\n**Sample Input:**\n```\n[[3, 1, 2], [4, 5, 6], [1, 1, 1]]\n```\n\n**Sample Output:**\n```\n[[1, 1, 1], [1, 2, 3], [4, 5, 6]]\n```", "reference": "def sort_nested_lists(nested_lists):\n \"\"\"\n Sorts each sublist in ascending order and then sorts the list of lists\n based on the sum of the integers in each sublist.\n\n :param nested_lists: List of lists of integers\n :return: Sorted list of lists of integers\n \"\"\"\n sorted_sublists = [sorted(sublist) for sublist in nested_lists]\n sorted_nested_lists = sorted(sorted_sublists, key=sum)\n return sorted_nested_lists\n\n# Example usage:\ninput_list = [[3, 1, 2], [4, 5, 6], [1, 1, 1]]\nresult = sort_nested_lists(input_list)\nprint(result) # Output: [[1, 1, 1], [1, 2, 3], [4, 5, 6]]", "tests": ["assert sort_nested_lists([[3, 1, 2], [4, 5, 6], [1, 1, 1]]) == [[1, 1, 1], [1, 2, 3], [4, 5, 6]]", "assert sort_nested_lists([[10, 20], [5, 15], [1, 30]]) == [[1, 30], [5, 15], [10, 20]]", "assert sort_nested_lists([[5, 3, 1], [2, 4, 6], [7, 8, 9]]) == [[1, 3, 5], [2, 4, 6], [7, 8, 9]]", "assert sort_nested_lists([[1, 1, 1], [1, 1, 1], [1, 1, 1]]) == [[1, 1, 1], [1, 1, 1], [1, 1, 1]]", "assert sort_nested_lists([[9, 8, 7], [6, 5, 4], [3, 2, 1]]) == [[1, 2, 3], [4, 5, 6], [7, 8, 9]]", "assert sort_nested_lists([[0, 0, 0], [0, 0], [0]]) == [[0], [0, 0], [0, 0, 0]]", "assert sort_nested_lists([[-1, -2, -3], [-4, -5, -6], [-7, -8, -9]]) == [[-9, -8, -7], [-6, -5, -4], [-3, -2, -1]]", "assert sort_nested_lists([[100], [50, 50], [25, 25, 25]]) == [[100], [25, 25, 25], [50, 50]]", "assert sort_nested_lists([]) == []", "assert sort_nested_lists([[1]]) == [[1]]"], "function": "sort_nested_lists", "signature": "def sort_nested_lists(nested_lists):", "score": 0.7, "domain": "generic"} {"id": "884974e5467f8821d048eaaef2613271", "problem": "You are given a string `s` consisting of words separated by spaces. Your task is to write a function that reverses each word in the string while maintaining the original order of the words. \n\n**Input:**\n- A single string `s` (1 ≤ |s| ≤ 1000), where |s| denotes the length of the string. The string consists of lowercase and uppercase English letters and spaces. There is at least one word in the string, and words are separated by a single space.\n\n**Output:**\n- A string with each word reversed, but the order of the words remains unchanged.\n\n**Sample Input:**\n```\nHello world this is a test\n```\n\n**Sample Output:**\n```\nolleH dlrow siht si a tset\n```", "reference": "def reverse_words_in_string(input_string):\n \"\"\"\n Reverses each word in the input string while maintaining the order of the words.\n\n :param input_string: A string with words separated by spaces.\n :return: A string with each word reversed.\n \"\"\"\n words = input_string.split()\n reversed_words = [word[::-1] for word in words]\n return ' '.join(reversed_words)\n\n# Example usage:\ninput_str = \"Hello world this is a test\"\nreversed_str = reverse_words_in_string(input_str)\nprint(reversed_str) # Output: \"olleH dlrow siht si a tset\"", "tests": ["assert reverse_words_in_string(\"Hello world\") == \"olleH dlrow\"", "assert reverse_words_in_string(\"Python is fun\") == \"nohtyP si nuf\"", "assert reverse_words_in_string(\"Keep it simple\") == \"peeK ti elpmis\"", "assert reverse_words_in_string(\"123 456 789\") == \"321 654 987\"", "assert reverse_words_in_string(\"!@# $%^ &*(\") == \"#@! %^$ (*&\"", "assert reverse_words_in_string(\"a b c d e\") == \"a b c d e\"", "assert reverse_words_in_string(\"racecar level deed\") == \"racecar level deed\"", "assert reverse_words_in_string(\"A man a plan a canal Panama\") == \"A nam a nalp a lanac amanaP\"", "assert reverse_words_in_string(\" spaced out \") == \"decaps tuos\"", "assert reverse_words_in_string(\"\") == \"\""], "function": "reverse_words_in_string", "signature": "def reverse_words_in_string(input_string):", "score": 0.8, "domain": "generic"} {"id": "81542cd8bfa294d0db89b14f3821b859", "problem": "You are given a string `s` and a list of words `word_dict`. Determine if `s` can be segmented into a sequence of one or more words from `word_dict`. Each word in `word_dict` can be used multiple times in the segmentation. Return `True` if such a segmentation is possible, otherwise return `False`.\n\n**Constraints:**\n- `1 <= len(s) <= 300`\n- `1 <= len(word_dict) <= 1000`\n- `1 <= len(word) <= 20` for each word in `word_dict`\n- All words in `word_dict` are unique.\n\n**Sample Input:**\n```\ns = \"leetcode\"\nword_dict = [\"leet\", \"code\"]\n```\n\n**Sample Output:**\n```\nTrue\n```", "reference": "def can_segment_string(s, word_dict):\n \"\"\"\n Determines if the string `s` can be segmented into a sequence of one or more words from `word_dict`.\n \n :param s: The string to be segmented.\n :param word_dict: A list of words that can be used for segmentation.\n :return: True if `s` can be segmented, False otherwise.\n \"\"\"\n word_set = set(word_dict)\n dp = [False] * (len(s) + 1)\n dp[0] = True\n \n for i in range(1, len(s) + 1):\n for j in range(i):\n if dp[j] and s[j:i] in word_set:\n dp[i] = True\n break\n \n return dp[len(s)]", "tests": ["assert can_segment_string(\"leetcode\", [\"leet\", \"code\"]) == True", "assert can_segment_string(\"applepenapple\", [\"apple\", \"pen\"]) == True", "assert can_segment_string(\"catsandog\", [\"cats\", \"dog\", \"sand\", \"and\", \"cat\"]) == False", "assert can_segment_string(\"abcd\", [\"a\", \"abc\", \"b\", \"cd\"]) == True", "assert can_segment_string(\"abcd\", [\"ab\", \"cd\"]) == True", "assert can_segment_string(\"abcd\", [\"abc\", \"d\", \"abcd\"]) == True", "assert can_segment_string(\"abcd\", [\"abcd\", \"abc\", \"d\"]) == True", "assert can_segment_string(\"abcd\", [\"a\", \"b\", \"c\", \"d\"]) == True", "assert can_segment_string(\"abcd\", [\"ab\", \"c\", \"d\", \"abcd\"]) == True", "assert can_segment_string(\"abcd\", [\"efg\", \"hij\"]) == False"], "function": "can_segment_string", "signature": "def can_segment_string(s, word_dict):", "score": 1.0, "domain": "algorithmic"} {"id": "b3eca164cdc2c9bc505f42c6faf432d2", "problem": "You are given a word and a dictionary of valid English words. Your task is to write a function `generate_variations(word, dictionary)` that generates all possible variations of the given word. Each variation must differ from the original word by exactly one character through deletion, transposition, replacement, or insertion operations. Only include variations that are present in the provided dictionary.\n\n**Input:**\n- A string `word` (1 ≤ |word| ≤ 10) consisting of lowercase English letters.\n- A list `dictionary` containing up to 1000 valid English words, each word consisting of lowercase English letters.\n\n**Output:**\n- A set of strings, each representing a valid variation of the word as per the rules.\n\n**Sample Input:**\n```python\nword = 'ample'\ndictionary = ['ample', 'ampley', 'amle', 'amplet', 'apple', 'amplest', 'ampel', 'ampleta', 'amplets', 'appl', 'ampley']\n```\n\n**Sample Output:**\n```python\n{'ampley', 'amle', 'amplet', 'apple', 'ampel', 'ampleta', 'amplets', 'appl'}\n```", "reference": "def generate_variations(word, dictionary):\n \"\"\"\n Generate all possible variations of a word that differ by one character and are in the given dictionary.\n \n :param word: The original word as a string.\n :param dictionary: A list of valid English words.\n :return: A set of valid variations of the word.\n \"\"\"\n variations = set()\n letters = 'abcdefghijklmnopqrstuvwxyz'\n l = len(word)\n\n # Deletion\n for i in range(l):\n variation = word[:i] + word[i+1:]\n if variation in dictionary:\n variations.add(variation)\n\n # Transposition\n for i in range(l - 1):\n variation = word[:i] + word[i+1] + word[i] + word[i+2:]\n if variation in dictionary:\n variations.add(variation)\n\n # Replacement\n for i in range(l):\n for letter in letters:\n if letter != word[i]:\n variation = word[:i] + letter + word[i+1:]\n if variation in dictionary:\n variations.add(variation)\n\n # Insertion\n for i in range(l + 1):\n for letter in letters:\n variation = word[:i] + letter + word[i:]\n if variation in dictionary:\n variations.add(variation)\n\n return variations\n\n# Sample usage\ndictionary = ['ample', 'ampley', 'amle', 'amplet', 'apple', 'amplest', 'ampel', 'ampleta', 'amplets', 'appl', 'ampley']\nword = 'ample'\nprint(generate_variations(word, dictionary))", "tests": ["assert generate_variations('ample', ['ample', 'ampley', 'amle', 'amplet', 'apple', 'amplest', 'ampel', 'ampleta', 'amplets', 'appl', 'ampley']) == {'ampley', 'amle', 'amplet', 'apple', 'amplest', 'ampel', 'ampleta', 'amplets', 'appl'}", "assert generate_variations('apple', ['ample', 'ampley', 'amle', 'amplet', 'apple', 'amplest', 'ampel', 'ampleta', 'amplets', 'appl', 'ampley']) == {'ample', 'ampley', 'amplet', 'amplest', 'ampel', 'ampleta', 'amplets', 'appl'}", "assert generate_variations('test', ['test', 'tset', 'sett', 'rest', 'best', 'testy', 'testa']) == {'tset', 'sett', 'rest', 'best', 'testy', 'testa'}", "assert generate_variations('word', ['word', 'wrod', 'owrd', 'wodr', 'wordy', 'wordz']) == {'wrod', 'owrd', 'wodr', 'wordy', 'wordz'}", "assert generate_variations('a', ['a', 'b', 'c', 'd']) == {'b', 'c', 'd'}", "assert generate_variations('abc', ['abc', 'acb', 'bac', 'bca', 'cab', 'cba', 'abcd']) == {'acb', 'bac', 'bca', 'cab', 'cba', 'abcd'}", "assert generate_variations('hello', ['hello', 'hallo', 'hella', 'hillo', 'hullo', 'hell']) == {'hallo', 'hella', 'hillo', 'hullo', 'hell'}", "assert generate_variations('python', ['python', 'pythpn', 'pythno', 'pythob', 'pythot', 'pythhn', 'pythyn']) == {'pythpn', 'pythno', 'pythob', 'pythot', 'pythhn', 'pythyn'}", "assert generate_variations('java', ['java', 'jvaa', 'jaav', 'jaaa', 'javb', 'javc', 'javd']) == {'jvaa', 'jaav', 'jaaa', 'javb', 'javc', 'javd'}", "assert generate_variations('code', ['code', 'cdoe', 'coed', 'coed', 'cod', 'coee', 'coed']) == {'cdoe', 'coed', 'cod', 'coee'}"], "function": "generate_variations", "signature": "def generate_variations(word, dictionary):", "score": 0.5, "domain": "generic"} {"id": "65b57f276f919f0ec2a6f3a62bff3ab6", "problem": "You are given two lists of elements. Your task is to implement a function `add_missing_elements(list1, list2)` that returns a new list containing elements that are present in either `list1` or `list2` but not in both. This operation is known as the symmetric difference between two lists. The order of elements in the resulting list does not matter. Note that duplicate elements within each list should be considered only once.\n\n**Sample Input:**\n```\nlist1 = [1, 2, 3, 4, 5]\nlist2 = [4, 5, 6, 7, 8]\n```\n**Sample Output:**\n```\n[1, 2, 3, 6, 7, 8]\n```\n\n**Sample Input:**\n```\nlist1 = ['a', 'b', 'c']\nlist2 = ['c', 'd', 'e', 'f']\n```\n**Sample Output:**\n```\n['a', 'b', 'd', 'e', 'f']\n```\n\n**Sample Input:**\n```\nlist1 = [1, 1, 2, 2, 3]\nlist2 = [2, 2, 3, 4, 4]\n```\n**Sample Output:**\n```\n[1, 4]\n```", "reference": "def add_missing_elements(list1, list2):\n \"\"\"\n Returns a list containing elements that are in either list1 or list2 but not in both.\n \n :param list1: First list of elements\n :param list2: Second list of elements\n :return: List of elements that are in the symmetric difference of list1 and list2\n \"\"\"\n return list(set(list1).symmetric_difference(set(list2)))\n\n# Examples of how to use the function\nexample_list1 = [1, 2, 3, 4, 5]\nexample_list2 = [4, 5, 6, 7, 8]\nresult = add_missing_elements(example_list1, example_list2)\nprint(result) # Output: [1, 2, 3, 6, 7, 8]\n\nexample_list3 = ['a', 'b', 'c']\nexample_list4 = ['c', 'd', 'e', 'f']\nresult2 = add_missing_elements(example_list3, example_list4)\nprint(result2) # Output: ['a', 'b', 'd', 'e', 'f']\n\nexample_list5 = [1, 1, 2, 2, 3]\nexample_list6 = [2, 2, 3, 4, 4]\nresult3 = add_missing_elements(example_list5, example_list6)\nprint(result3) # Output: [1, 4]", "tests": ["assert add_missing_elements([1, 2, 3], [3, 4, 5]) == [1, 2, 4, 5]", "assert add_missing_elements(['a', 'b', 'c'], ['c', 'd', 'e']) == ['a', 'b', 'd', 'e']", "assert add_missing_elements([1, 2, 3, 4], [4, 5, 6, 7]) == [1, 2, 3, 5, 6, 7]", "assert add_missing_elements([], [1, 2, 3]) == [1, 2, 3]", "assert add_missing_elements([1, 2, 3], []) == [1, 2, 3]", "assert add_missing_elements([], []) == []", "assert add_missing_elements([1, 1, 2, 2], [2, 2, 3, 3]) == [1, 3]", "assert add_missing_elements(['apple', 'banana'], ['banana', 'cherry']) == ['apple', 'cherry']", "assert add_missing_elements([1, 2, 3], [3, 2, 1]) == []", "assert add_missing_elements(['x', 'y', 'z'], ['a', 'b', 'c']) == ['x', 'y', 'z', 'a', 'b', 'c']"], "function": "add_missing_elements", "signature": "def add_missing_elements(list1, list2):", "score": 0.7, "domain": "generic"} {"id": "582512a614af67f84ae3d75349078848", "problem": "You are given a string `s`. Your task is to find and return the lexicographically smallest rotation of the string `s`.\n\n**Input:**\n- A single string `s` (1 ≤ |s| ≤ 1000), consisting of lowercase English letters.\n\n**Output:**\n- A single string representing the lexicographically smallest rotation of `s`.\n\n**Sample Input:**\n```\nrotation\n```\n\n**Sample Output:**\n```\nationrot\n```", "reference": "def smallest_rotation(s):\n \"\"\"\n Returns the lexicographically smallest rotation of the input string s.\n \n :param s: Input string\n :return: Lexicographically smallest rotation of s\n \"\"\"\n doubled_s = s + s\n n = len(s)\n smallest_rotation = doubled_s[:n]\n for i in range(1, n):\n rotation = doubled_s[i:i+n]\n if rotation < smallest_rotation:\n smallest_rotation = rotation\n return smallest_rotation\n\n# Test the function\ninput_string = \"rotation\"\nprint(smallest_rotation(input_string))", "tests": ["assert smallest_rotation(\"rotation\") == \"ationrot\"", "assert smallest_rotation(\"abc\") == \"abc\"", "assert smallest_rotation(\"bca\") == \"abc\"", "assert smallest_rotation(\"cab\") == \"abc\"", "assert smallest_rotation(\"aaaa\") == \"aaaa\"", "assert smallest_rotation(\"abcd\") == \"abcd\"", "assert smallest_rotation(\"zab\") == \"abz\"", "assert smallest_rotation(\"zzzabc\") == \"abczzz\"", "assert smallest_rotation(\"hello\") == \"ehllo\"", "assert smallest_rotation(\"a\") == \"a\""], "function": "smallest_rotation", "signature": "def smallest_rotation(s):", "score": 0.9, "domain": "algorithmic"} {"id": "427e5b0a7f3049dea5a13632cdd91045", "problem": "You are given an integer `x`. Your task is to find the smallest integer `y` such that `y >= x` and all digits in `y` are distinct. For instance, if `x` is 123, then `y` should be 123 since all its digits are unique. If `x` is 122, then `y` should be 123.\n\n**Input:**\n- An integer `x` (1 ≤ x ≤ 10^9)\n\n**Output:**\n- Print the smallest integer `y` such that `y ≥ x` and all digits in `y` are distinct.\n\n**Sample Input 1:**\n```\n122\n```\n\n**Sample Output 1:**\n```\n123\n```\n\n**Sample Input 2:**\n```\n111\n```\n\n**Sample Output 2:**\n```\n123\n```", "reference": "def f(x):\n \"\"\"\n Find the smallest integer y such that y >= x and all digits in y are distinct.\n\n Parameters:\n x (int): The input integer.\n\n Returns:\n int: The smallest integer y with all unique digits.\n \"\"\"\n while True:\n x_str = str(x)\n if len(x_str) == len(set(x_str)):\n return x\n x += 1\n\n# Example usage:\nresult = f(122)\nprint(result) # Output will be 123", "tests": ["assert f(123) == 123", "assert f(122) == 123", "assert f(111) == 123", "assert f(999) == 1023", "assert f(1001) == 1023", "assert f(9876) == 9876", "assert f(1111) == 1234", "assert f(4321) == 4321", "assert f(112233) == 123456", "assert f(0) == 0"], "function": "f", "signature": "def f(x):", "score": 0.7, "domain": "algorithmic"} {"id": "8e16af498fced9596cdee0cd7a6c37ee", "problem": "You are given a string `s`. Your task is to find the longest palindromic substring within `s`. A palindromic substring is a substring that reads the same backward as forward. If there are multiple substrings of the same maximum length, return the one that appears first in the string.\n\n**Input:**\n- A single string `s` (1 ≤ |s| ≤ 1000), consisting of lowercase English letters.\n\n**Output:**\n- A single string representing the longest palindromic substring.\n\n**Sample Input:**\n```\nabcbabcba\n```\n\n**Sample Output:**\n```\nabcbabcba\n```", "reference": "def longest_palindromic_substring(s: str) -> str:\n \"\"\"\n Finds the longest palindromic substring in the given string s.\n \n :param s: Input string\n :return: Longest palindromic substring\n \"\"\"\n if not s:\n return \"\"\n start = 0\n end = 0\n for i in range(len(s)):\n len1 = expand_around_center(s, i, i) # Odd case\n len2 = expand_around_center(s, i, i+1) # Even case\n max_len = max(len1, len2)\n if max_len > (end - start):\n start = i - (max_len - 1) // 2\n end = i + max_len // 2\n return s[start:end+1]\n\ndef expand_around_center(s: str, left: int, right: int) -> int:\n \"\"\"\n Expands around the center indices left and right to find the length of the palindrome.\n \n :param s: Input string\n :param left: Left index\n :param right: Right index\n :return: Length of the palindrome\n \"\"\"\n while left >= 0 and right < len(s) and s[left] == s[right]:\n left -= 1\n right += 1\n return right - left - 1\n\n# Test the function with the example provided\nprint(longest_palindromic_substring(\"abcbabcba\")) # Output: \"abcbabcba\"", "tests": ["assert longest_palindromic_substring(\"abcbabcba\") == \"abcbabcba\"", "assert longest_palindromic_substring(\"babad\") == \"bab\" or longest_palindromic_substring(\"babad\") == \"aba\"", "assert longest_palindromic_substring(\"cbbd\") == \"bb\"", "assert longest_palindromic_substring(\"a\") == \"a\"", "assert longest_palindromic_substring(\"ac\") == \"a\" or longest_palindromic_substring(\"ac\") == \"c\"", "assert longest_palindromic_substring(\"racecar\") == \"racecar\"", "assert longest_palindromic_substring(\"noon high it is\") == \"noon\"", "assert longest_palindromic_substring(\"abacdfgdcaba\") == \"aba\" or longest_palindromic_substring(\"abacdfgdcaba\") == \"cabac\"", "assert longest_palindromic_substring(\"\") == \"\"", "assert longest_palindromic_substring(\"forgeeksskeegfor\") == \"geeksskeeg\""], "function": "longest_palindromic_substring", "signature": "def longest_palindromic_substring(s: str) -> str:", "score": 1.0, "domain": "algorithmic"} {"id": "e1e0fb80dbc8367796dee41084f41623", "problem": "You are tasked with implementing a recursive function named `calculate_factorial` that computes the factorial of a non-negative integer `n`. The factorial of a non-negative integer `n` is the product of all positive integers less than or equal to `n`. The factorial of 0 is defined as 1. Your function should handle invalid inputs gracefully by raising a `ValueError` if `n` is negative or not an integer.\n\n**Input:**\n- A single integer `n`.\n\n**Output:**\n- The factorial of `n` if `n` is a non-negative integer.\n- Raises a `ValueError` if `n` is negative or not an integer.\n\n**Sample Inputs and Outputs:**\n- Input: `5`\n - Output: `120`\n- Input: `0`\n - Output: `1`\n- Input: `-1`\n - Output: Raises `ValueError`", "reference": "def calculate_factorial(n):\n \"\"\"\n Calculate the factorial of a non-negative integer n using recursion.\n \n Parameters:\n n (int): A non-negative integer whose factorial is to be calculated.\n \n Returns:\n int: The factorial of the given integer n.\n \n Raises:\n ValueError: If n is negative or not an integer.\n \"\"\"\n if not isinstance(n, int):\n raise ValueError(\"The input must be an integer.\")\n if n < 0:\n raise ValueError(\"Factorial is not defined for negative numbers.\")\n if n == 0:\n return 1\n return n * calculate_factorial(n - 1)\n\n# Example usage:\n# print(calculate_factorial(5)) # Output: 120\n# print(calculate_factorial(0)) # Output: 1\n# print(calculate_factorial(-1)) # Raises ValueError", "tests": ["assert calculate_factorial(5) == 120", "assert calculate_factorial(0) == 1", "assert calculate_factorial(1) == 1", "assert calculate_factorial(3) == 6", "assert calculate_factorial(10) == 3628800", "assert calculate_factorial(7) == 5040", "assert calculate_factorial(15) == 1307674368000", "assert calculate_factorial(-5) == ValueError", "assert calculate_factorial(20) == 2432902008176640000", "assert calculate_factorial(1.5) == ValueError"], "function": "calculate_factorial", "signature": "def calculate_factorial(n):", "score": 0.8, "domain": "generic"} {"id": "fe0aabf54d5bb51600be618dcf44d9e0", "problem": "You are given a list of integers `numbers` and an integer `target`. Your task is to implement a function `find_closest_number(numbers, target)` that returns the integer in the list that is closest to the `target`. If there are multiple integers with the same minimum distance to the `target`, return the smallest one. The function should handle edge cases where the input list is empty or contains only one element.\n\n**Input:**\n- A list of integers `numbers` (0 ≤ len(numbers) ≤ 10^3)\n- An integer `target` (-10^6 ≤ target ≤ 10^6)\n\n**Output:**\n- An integer from the list that is closest to the `target`. If the list is empty, return `None`.\n\n**Sample Input 1:**\n```\nnumbers = [4, 1, 88, 44, 3]\ntarget = 5\n```\n**Sample Output 1:**\n```\n4\n```\n\n**Sample Input 2:**\n```\nnumbers = []\ntarget = 10\n```\n**Sample Output 2:**\n```\nNone\n```\n\n**Sample Input 3:**\n```\nnumbers = [7]\ntarget = 7\n```\n**Sample Output 3:**\n```\n7\n```", "reference": "def find_closest_number(numbers, target):\n \"\"\"\n Returns the number in the list that is closest to the target.\n If there are multiple numbers with the same minimum distance to the target, returns the smallest one.\n Returns None if the list is empty.\n \n :param numbers: List of integers\n :param target: Integer target\n :return: Integer closest to the target or None if the list is empty\n \"\"\"\n if not numbers:\n return None # Return None if the list is empty\n\n closest_number = numbers[0]\n min_distance = abs(target - closest_number)\n\n for number in numbers:\n current_distance = abs(target - number)\n if current_distance < min_distance or (current_distance == min_distance and number < closest_number):\n closest_number = number\n min_distance = current_distance\n\n return closest_number", "tests": ["assert find_closest_number([1, 2, 3, 5, 6], 4) == 3", "assert find_closest_number([10, 22, 28, 29, 30, 40], 27) == 28", "assert find_closest_number([5, 10, 15, 20, 25], 20) == 20", "assert find_closest_number([1, 3, 5, 7, 9], 8) == 7", "assert find_closest_number([], 10) == None", "assert find_closest_number([5], 5) == 5", "assert find_closest_number([1, 1, 1, 1, 1], 1) == 1", "assert find_closest_number([1, 2, 3, 4, 5], 0) == 1", "assert find_closest_number([1, 2, 3, 4, 5], 6) == 5", "assert find_closest_number([-10, -20, -30, -40, -50], -25) == -20"], "function": "find_closest_number", "signature": "def find_closest_number(numbers, target):", "score": 0.9, "domain": "generic"} {"id": "9f7b44049bb227f86076186e3b3b5943", "problem": "You are given two lists: `times` and `datas`. The `times` list contains timestamps, and the `datas` list contains tuples where each tuple has a single boolean value indicating whether the corresponding timestamp is a \"backchannel\" (True) or not. Additionally, you are given a list `time_find` which contains timestamps of the \"backchannels\" you have identified. Your task is to compute the error rate of your identified \"backchannels\" compared to the actual \"backchannels\" in the dataset. The error rate is defined as the number of missed \"backchannels\" and false positives divided by the total number of data points. Before calculating the error rate, ensure that the `time_find` list does not contain any duplicate timestamps; if duplicates are found, remove them.\n\n**Input:**\n- `times`: A list of integers representing timestamps.\n- `datas`: A list of tuples, where each tuple contains a single boolean value.\n- `time_find`: A list of integers representing the timestamps of the identified \"backchannels\".\n\n**Output:**\n- A float representing the error rate.\n\n**Constraints:**\n- 1 ≤ len(times) ≤ 10^5\n- len(times) = len(datas)\n- 1 ≤ len(time_find) ≤ 10^5\n- Each element in `times` and `time_find` is a positive integer.\n\n**Sample Input:**\n```\ntimes = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\ndatas = [(False,), (True,), (False,), (False,), (True,), (False,), (False,), (True,), (False,), (False,)]\ntime_find = [2, 5, 8, 9, 9]\n```\n\n**Sample Output:**\n```\n0.4\n```", "reference": "def calculate_error_rate(times, datas, time_find):\n \"\"\"\n Calculate the error rate of identified backchannels compared to actual backchannels.\n\n :param times: List of timestamps.\n :param datas: List of tuples, each containing a boolean indicating if it's a backchannel.\n :param time_find: List of timestamps of identified backchannels.\n :return: Error rate as a float.\n \"\"\"\n # Remove duplicates from the time_find list\n time_find = list(set(time_find))\n\n # Count total number of data points\n total_data_points = len(datas)\n\n # Find all actual backchannel timestamps\n actual_backchannels = {times[i] for i in range(total_data_points) if datas[i][0]}\n\n # Calculate missed backchannels and false positives\n missed_backchannels = actual_backchannels - set(time_find)\n false_positives = set(time_find) - actual_backchannels\n\n # Calculate error rate\n error_rate = (len(missed_backchannels) + len(false_positives)) / total_data_points\n\n return error_rate\n\n# Example usage:\n# times = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n# datas = [(False,), (True,), (False,), (False,), (True,), (False,), (False,), (True,), (False,), (False,)]\n# time_find = [2, 5, 8, 9, 9]\n# print(calculate_error_rate(times, datas, time_find)) # Output: 0.4", "tests": ["assert calculate_error_rate([1, 2, 3], [(False,), (True,), (False,)], [2]) == 0.6666666666666666", "assert calculate_error_rate([1, 2, 3, 4], [(True,), (False,), (True,), (False,)], [1, 3]) == 0.5", "assert calculate_error_rate([1, 2, 3, 4, 5], [(False,), (False,), (False,), (False,), (False,)], []) == 0.0", "assert calculate_error_rate([1, 2, 3, 4, 5], [(True,), (True,), (True,), (True,), (True,)], [1, 2, 3, 4, 5]) == 0.0", "assert calculate_error_rate([1, 2, 3, 4, 5], [(True,), (True,), (True,), (True,), (True,)], [1, 2, 3, 4, 5, 5]) == 0.0", "assert calculate_error_rate([1, 2, 3, 4, 5], [(True,), (False,), (True,), (False,), (True,)], [2, 4, 6]) == 0.8", "assert calculate_error_rate([1, 2, 3, 4, 5], [(False,), (False,), (False,), (False,), (False,)], [1, 2, 3, 4, 5]) == 1.0", "assert calculate_error_rate([1, 2, 3, 4, 5], [(True,), (False,), (True,), (False,), (True,)], [1, 3, 5]) == 0.4", "assert calculate_error_rate([1, 2, 3, 4, 5], [(True,), (False,), (True,), (False,), (True,)], [2, 2, 3, 3, 4, 4]) == 0.4", "assert calculate_error_rate([1, 2, 3, 4, 5], [(False,), (False,), (False,), (False,), (False,)], [1, 1, 1, 1, 1]) == 1.0"], "function": "calculate_error_rate", "signature": "def calculate_error_rate(times, datas, time_find):", "score": 0.4, "domain": "generic"} {"id": "bce95adf10202969717e7b5793ffa551", "problem": "You are given two times in the format `HH:MM:SS.ssssss` (including microseconds) and a timezone string. Your task is to compute the total number of seconds between these two times on the date `2023-06-30` in the specified timezone, taking into account any leap seconds that may have occurred on that date. The function should handle both positive and negative time differences and return the absolute value of the difference.\n\n**Input:**\n- `time1`: A string representing the first time in the format `HH:MM:SS.ssssss`.\n- `time2`: A string representing the second time in the format `HH:MM:SS.ssssss`.\n- `timezone`: A string representing the timezone.\n\n**Output:**\n- An integer or float representing the absolute number of seconds between `time1` and `time2` on `2023-06-30` in the given timezone.\n\n**Sample Input:**\n- `time1 = \"23:59:59.999999\"`\n- `time2 = \"00:00:00.000000\"`\n- `timezone = \"Etc/GMT+0\"`\n\n**Sample Output:**\n- `86400.0` (or `86401.0` if a leap second occurred on that date)", "reference": "from datetime import datetime, timedelta\nimport pytz\n\ndef calculate_seconds(time1, time2, timezone):\n \"\"\"\n Calculate the total number of seconds between two given times on the date 2023-06-30\n in a specified timezone, accounting for leap seconds.\n\n Parameters:\n - time1 (str): The first time in the format 'HH:MM:SS.ssssss'.\n - time2 (str): The second time in the format 'HH:MM:SS.ssssss'.\n - timezone (str): The timezone string.\n\n Returns:\n - float: The absolute number of seconds between time1 and time2.\n \"\"\"\n date_str = \"2023-06-30\"\n datetime_format = \"%Y-%m-%d %H:%M:%S.%f\"\n \n tz = pytz.timezone(timezone)\n \n naive_datetime1 = datetime.strptime(f\"{date_str} {time1}\", datetime_format)\n naive_datetime2 = datetime.strptime(f\"{date_str} {time2}\", datetime_format)\n \n datetime1 = tz.localize(naive_datetime1)\n datetime2 = tz.localize(naive_datetime2)\n \n delta = datetime2 - datetime1\n \n return abs(delta.total_seconds())", "tests": ["assert calculate_seconds(\"23:59:59.999999\", \"00:00:00.000000\", \"Etc/GMT+0\") == 86400.0", "assert calculate_seconds(\"00:00:00.000000\", \"23:59:59.999999\", \"Etc/GMT+0\") == 86400.0", "assert calculate_seconds(\"23:59:59.000000\", \"23:59:59.000001\", \"Etc/GMT+0\") == 0.000001", "assert calculate_seconds(\"00:00:00.000000\", \"00:00:00.000001\", \"Etc/GMT+0\") == 0.000001", "assert calculate_seconds(\"12:00:00.000000\", \"12:00:01.000000\", \"Etc/GMT+0\") == 1.0", "assert calculate_seconds(\"12:00:01.000000\", \"12:00:00.000000\", \"Etc/GMT+0\") == 1.0", "assert calculate_seconds(\"00:00:00.000000\", \"00:00:00.000000\", \"Etc/GMT+0\") == 0.0", "assert calculate_seconds(\"23:59:59.999999\", \"23:59:59.999999\", \"Etc/GMT+0\") == 0.0", "assert calculate_seconds(\"23:59:60.000000\", \"00:00:00.000000\", \"Etc/GMT+0\") == 86401.0", "assert calculate_seconds(\"00:00:00.000000\", \"23:59:60.000000\", \"Etc/GMT+0\") == 86401.0"], "function": "calculate_seconds", "signature": "def calculate_seconds(time1, time2, timezone):", "score": 0.6, "domain": "generic"} {"id": "14b223c7720ba7e100e3e281afba5103", "problem": "You are given a string `text`. Your task is to implement a function `count_words(text)` that processes the string and returns a dictionary. The dictionary should contain each unique word (case-insensitive) as keys and their respective counts as values. The function should ignore punctuation and treat words with different cases as the same word.\n\n**Input:**\n- A single string `text` (1 ≤ len(text) ≤ 10^4) containing English letters, spaces, and punctuation marks.\n\n**Output:**\n- A dictionary where keys are unique words (in lowercase) and values are the number of times each word appears in the text.\n\n**Sample Input:**\n```\n\"Hello, world! Hello, Word.\"\n```\n\n**Sample Output:**\n```\n{'hello': 2, 'world': 2}\n```", "reference": "import string\n\ndef count_words(text):\n \"\"\"\n Counts the occurrences of each unique word in a given text, ignoring case and punctuation.\n \n Parameters:\n text (str): The input string containing words.\n \n Returns:\n dict: A dictionary with words as keys and their counts as values.\n \"\"\"\n # Convert the text to lowercase to make the counting case-insensitive\n text = text.lower()\n \n # Remove punctuation using str.translate and str.maketrans\n text = text.translate(str.maketrans('', '', string.punctuation))\n \n # Split the text into words\n words = text.split()\n \n # Create a dictionary to store the word counts\n word_count = {}\n \n # Iterate over each word in the list\n for word in words:\n # If the word is already in the dictionary, increment its count\n if word in word_count:\n word_count[word] += 1\n # Otherwise, add the word to the dictionary with a count of 1\n else:\n word_count[word] = 1\n \n return word_count\n\n# Example usage:\ntext = \"Hello, world! Hello, Word.\"\nprint(count_words(text))", "tests": ["assert count_words(\"Hello, world! Hello, Word.\") == {'hello': 2, 'world': 2}", "assert count_words(\"Python, python, PYTHON!\") == {'python': 3}", "assert count_words(\"One fish, two fish, red fish, blue fish.\") == {'one': 1, 'fish': 4, 'two': 1, 'red': 1, 'blue': 1}", "assert count_words(\"To be or not to be, that is the question.\") == {'to': 2, 'be': 2, 'or': 1, 'not': 1, 'that': 1, 'is': 1, 'the': 1, 'question': 1}", "assert count_words(\"A quick brown fox jumps over the lazy dog.\") == {'a': 1, 'quick': 1, 'brown': 1, 'fox': 1, 'jumps': 1, 'over': 1, 'the': 1, 'lazy': 1, 'dog': 1}", "assert count_words(\"\") == {}", "assert count_words(\"!!!\") == {}", "assert count_words(\"Test... test: test; test!\") == {'test': 4}", "assert count_words(\"Spaces should not matter.\") == {'spaces': 1, 'should': 1, 'not': 1, 'matter': 1}", "assert count_words(\"MixedCASE Words Should Be Counted As Lowercase.\") == {'mixedcase': 1, 'words': 1, 'should': 1, 'be': 1, 'counted': 1, 'as': 1, 'lowercase': 1}"], "function": "count_words", "signature": "def count_words(text):", "score": 0.9, "domain": "generic"} {"id": "0b5564961a9a04ec51d27481b3a89608", "problem": "You are given a positive integer `n`. Your task is to compute the sum of the squares of all even numbers from 1 to `n` (inclusive). Write an efficient function to perform this calculation.\n\n**Input:**\n- A single integer `n` (1 ≤ n ≤ 10^6)\n\n**Output:**\n- A single integer representing the sum of the squares of all even numbers up to `n`.\n\n**Sample Input:**\n```\n1000000\n```\n\n**Sample Output:**\n```\n333333833334000000\n```", "reference": "def sum_of_squares(n):\n \"\"\"\n Calculate the sum of the squares of all even numbers up to a given number n.\n\n Parameters:\n n (int): The upper limit up to which the sum of squares of even numbers is calculated.\n\n Returns:\n int: The sum of the squares of all even numbers up to n.\n \"\"\"\n k = n // 2\n return (2 * k * (k + 1) * (2 * k + 1)) // 3\n\n# Example usage:\nn = 1000000\nprint(sum_of_squares(n))", "tests": ["assert sum_of_squares(0) == 0", "assert sum_of_squares(1) == 0", "assert sum_of_squares(2) == 4", "assert sum_of_squares(3) == 4", "assert sum_of_squares(4) == 20", "assert sum_of_squares(5) == 20", "assert sum_of_squares(10) == 220", "assert sum_of_squares(100) == 166650", "assert sum_of_squares(1000) == 166666500", "assert sum_of_squares(1000000) == 333333833333000000"], "function": "sum_of_squares", "signature": "def sum_of_squares(n):", "score": 0.7, "domain": "algorithmic"} {"id": "aef6bb8bd67d2a9c5c2cc20f6cfe5d9d", "problem": "You are given a string `s` consisting of words separated by spaces, punctuation, and numbers. Your task is to implement a function `filter_unique_words` that returns a list of words that appear exactly once in the string. The comparison should be case-insensitive, and only words consisting of alphabetic characters should be considered. \n\n**Input:**\n- A single string `s` (1 ≤ |s| ≤ 10^5).\n\n**Output:**\n- A list of words that appear exactly once in the string, in the order they first appear.\n\n**Sample Input:**\n```\n\"Hello world! Hello, Universe. Universe!\"\n```\n\n**Sample Output:**\n```\n['world']\n```", "reference": "import re\nfrom collections import Counter\n\ndef filter_unique_words(input_string):\n \"\"\"\n Returns a list of words that appear exactly once in the input string.\n \n :param input_string: A string containing words, punctuation, and numbers.\n :return: A list of unique words (case-insensitive, alphabetic only).\n \"\"\"\n # Convert string to lowercase to ensure case insensitivity\n input_string = input_string.lower()\n \n # Use regex to extract words (only letters)\n words = re.findall(r'\\b[a-z]+\\b', input_string)\n \n # Count the occurrences of each word\n word_counts = Counter(words)\n \n # Extract words that appear exactly once\n unique_words = [word for word, count in word_counts.items() if count == 1]\n \n return unique_words\n\n# Example usage:\nexample_string = \"Hello world! Hello, Universe. Universe!\"\nprint(filter_unique_words(example_string)) # Output: ['world']", "tests": ["assert filter_unique_words(\"Hello world! Hello, Universe. Universe!\") == ['world']", "assert filter_unique_words(\"This is a test. This test is only a test.\") == ['only']", "assert filter_unique_words(\"One fish two fish red fish blue fish.\") == ['one', 'two', 'red', 'blue']", "assert filter_unique_words(\"Python, Python, Python!\") == []", "assert filter_unique_words(\"Unique words only here.\") == ['unique', 'words', 'only', 'here']", "assert filter_unique_words(\"123 456 789\") == []", "assert filter_unique_words(\"No numbers 123 or symbols #@$ here!\") == ['no', 'numbers', 'or', 'symbols', 'here']", "assert filter_unique_words(\"A man, a plan, a canal, Panama!\") == ['man', 'plan', 'canal', 'panama']", "assert filter_unique_words(\"Repeat repeat REPEAT\") == []", "assert filter_unique_words(\"\") == []"], "function": "filter_unique_words", "signature": "def filter_unique_words(input_string):", "score": 1.0, "domain": "generic"} {"id": "973fa63f1e4b98b6cf519b428ea527c5", "problem": "You are given a list of 2D points represented as tuples. Your task is to compute the Euclidean distance between each unique pair of points and return the results in a dictionary. The keys of the dictionary should be tuples representing the point pairs, and the values should be the corresponding distances. Note that the order of points in the tuple key does not matter, i.e., `(p1, p2)` is the same as `(p2, p1)`.\n\n**Input:**\n- A list of tuples, where each tuple contains two integers representing the x and y coordinates of a point.\n\n**Output:**\n- A dictionary with keys as tuples of point pairs and values as the Euclidean distances between them.\n\n**Sample Input:**\n```python\npoints = [(0, 0), (3, 4), (6, 8)]\n```\n\n**Sample Output:**\n```python\n{((0, 0), (3, 4)): 5.0, ((0, 0), (6, 8)): 10.0, ((3, 4), (6, 8)): 5.0}\n```", "reference": "import math\n\ndef calculate_distances(points):\n \"\"\"\n Calculate the Euclidean distances between each pair of points in a list.\n\n :param points: List of tuples, where each tuple contains two integers representing the x and y coordinates of a point.\n :return: Dictionary with keys as tuples of point pairs and values as the Euclidean distances between them.\n \"\"\"\n distance_dict = {}\n n = len(points)\n for i in range(n):\n for j in range(i + 1, n):\n point1, point2 = points[i], points[j]\n distance = math.sqrt((point1[0] - point2[0]) ** 2 + (point1[1] - point2[1]) ** 2)\n distance_dict[(point1, point2)] = distance\n return distance_dict\n\n# Example usage:\n# points = [(0, 0), (3, 4), (6, 8)]\n# print(calculate_distances(points))", "tests": ["assert calculate_distances([(0, 0), (3, 4)]) == {((0, 0), (3, 4)): 5.0}", "assert calculate_distances([(1, 1), (1, 1)]) == {}", "assert calculate_distances([(0, 0), (0, 0), (0, 0)]) == {}", "assert calculate_distances([(0, 0), (1, 1), (2, 2)]) == {((0, 0), (1, 1)): 1.4142135623730951, ((0, 0), (2, 2)): 2.8284271247461903, ((1, 1), (2, 2)): 1.4142135623730951}", "assert calculate_distances([(0, 0), (4, 0), (0, 3)]) == {((0, 0), (4, 0)): 4.0, ((0, 0), (0, 3)): 3.0, ((4, 0), (0, 3)): 5.0}", "assert calculate_distances([(1, 2), (4, 6), (7, 8)]) == {((1, 2), (4, 6)): 5.0, ((1, 2), (7, 8)): 7.810249675906654, ((4, 6), (7, 8)): 3.605551275463989}", "assert calculate_distances([(0, 0)]) == {}", "assert calculate_distances([]) == {}", "assert calculate_distances([(1, 1), (2, 2), (3, 3), (4, 4)]) == {((1, 1), (2, 2)): 1.4142135623730951, ((1, 1), (3, 3)): 2.8284271247461903, ((1, 1), (4, 4)): 4.242640687119285, ((2, 2), (3, 3)): 1.4142135623730951, ((2, 2), (4, 4)): 2.8284271247461903, ((3, 3), (4, 4)): 1.4142135623730951}", "assert calculate_distances([(0, 0), (0, 1), (1, 0), (1, 1)]) == {((0, 0), (0, 1)): 1.0, ((0, 0), (1, 0)): 1.0, ((0, 0), (1, 1)): 1.4142135623730951, ((0, 1), (1, 0)): 1.4142135623730951, ((0, 1), (1, 1)): 1.0, ((1, 0), (1, 1)): 1.0}"], "function": "calculate_distances", "signature": "def calculate_distances(points):", "score": 0.7, "domain": "generic"} {"id": "e254617bad5b17462a6671c2b895a35b", "problem": "You are tasked with implementing a function `calculate_discounted_prices(prices, discounts)` that computes the final prices after applying a list of discounts to a corresponding list of prices. Each price in the `prices` list has a corresponding discount in the `discounts` list, where the discount is given as a percentage. Your function should return a list of the discounted prices.\n\n**Input:**\n- `prices`: A list of integers or floats representing the original prices.\n- `discounts`: A list of integers or floats representing the discount percentages.\n\n**Output:**\n- A list of floats representing the prices after applying the discounts.\n\n**Constraints:**\n- The length of `prices` and `discounts` will be the same.\n- Each price and discount will be non-negative.\n\n**Sample Input:**\n```python\nprices = [100, 200, 300, 400]\ndiscounts = [10, 20, 30, 40]\n```\n\n**Sample Output:**\n```python\n[90.0, 160.0, 210.0, 240.0]\n```", "reference": "def calculate_discounted_prices(prices, discounts):\n \"\"\"\n Calculate the final prices after applying a list of discounts to a corresponding list of prices.\n \n :param prices: List of original prices (integers or floats).\n :param discounts: List of discount percentages (integers or floats).\n :return: List of discounted prices (floats).\n \"\"\"\n discounted_prices = []\n for price, discount in zip(prices, discounts):\n discounted_price = price * (1 - discount / 100)\n discounted_prices.append(discounted_price)\n return discounted_prices\n\n# Example usage\nprices = [100, 200, 300, 400]\ndiscounts = [10, 20, 30, 40]\ndiscounted_prices = calculate_discounted_prices(prices, discounts)\nprint(discounted_prices) # Output: [90.0, 160.0, 210.0, 240.0]", "tests": ["assert calculate_discounted_prices([100, 200, 300, 400], [10, 20, 30, 40]) == [90.0, 160.0, 210.0, 240.0]", "assert calculate_discounted_prices([50, 75, 100], [0, 50, 100]) == [50.0, 37.5, 0.0]", "assert calculate_discounted_prices([100, 100, 100], [10, 20, 30]) == [90.0, 80.0, 70.0]", "assert calculate_discounted_prices([200, 400, 600], [5, 10, 15]) == [190.0, 360.0, 510.0]", "assert calculate_discounted_prices([150, 250, 350], [25, 50, 75]) == [112.5, 125.0, 87.5]", "assert calculate_discounted_prices([1000, 2000, 3000], [1, 2, 3]) == [990.0, 1980.0, 2910.0]", "assert calculate_discounted_prices([10, 20, 30], [100, 100, 100]) == [0.0, 0.0, 0.0]", "assert calculate_discounted_prices([10, 20, 30], [0, 0, 0]) == [10.0, 20.0, 30.0]", "assert calculate_discounted_prices([], []) == []", "assert calculate_discounted_prices([500], [50]) == [250.0]"], "function": "calculate_discounted_prices", "signature": "def calculate_discounted_prices(prices, discounts):", "score": 0.9, "domain": "generic"} {"id": "15bac47eeff59312e8f01bbe8e39461e", "problem": "You are given an array of integers `nums` and an integer `k`. Your task is to find the `k`-th largest element in the array. The function should have an average time complexity of O(n). \n\n**Input:**\n- The first line contains an integer `n` (1 ≤ n ≤ 10^5), the number of elements in the array.\n- The second line contains `n` space-separated integers `nums[i]` (-10^9 ≤ nums[i] ≤ 10^9), the elements of the array.\n- The third line contains an integer `k` (1 ≤ k ≤ n), the rank of the largest element to find.\n\n**Output:**\n- Print a single integer, the `k`-th largest element in the array.\n\n**Sample Input:**\n```\n6\n3 2 1 5 6 4\n2\n```\n\n**Sample Output:**\n```\n5\n```", "reference": "import random\n\ndef find_kth_largest(nums, k):\n \"\"\"\n Finds the k-th largest element in the list nums.\n \n :param nums: List of integers.\n :param k: Integer representing the k-th largest element to find.\n :return: The k-th largest element in the list.\n \"\"\"\n def partition(left, right, pivot_index):\n pivot_value = nums[pivot_index]\n nums[pivot_index], nums[right] = nums[right], nums[pivot_index]\n store_index = left\n for i in range(left, right):\n if nums[i] > pivot_value:\n nums[store_index], nums[i] = nums[i], nums[store_index]\n store_index += 1\n nums[right], nums[store_index] = nums[store_index], nums[right]\n return store_index\n\n def select(left, right, k_smallest):\n if left == right:\n return nums[left]\n pivot_index = random.randint(left, right)\n pivot_index = partition(left, right, pivot_index)\n if k_smallest == pivot_index:\n return nums[k_smallest]\n elif k_smallest < pivot_index:\n return select(left, pivot_index - 1, k_smallest)\n else:\n return select(pivot_index + 1, right, k_smallest)\n\n return select(0, len(nums) - 1, k - 1)\n\n# Example usage:\nnums = [3, 2, 1, 5, 6, 4]\nk = 2\nprint(find_kth_largest(nums, k))", "tests": ["assert find_kth_largest([3, 2, 1, 5, 6, 4], 2) == 5", "assert find_kth_largest([1, 2, 3, 4, 5, 6], 1) == 6", "assert find_kth_largest([1, 2, 3, 4, 5, 6], 6) == 1", "assert find_kth_largest([7, 10, 4, 3, 20, 15], 3) == 10", "assert find_kth_largest([7, 10, 4, 3, 20, 15], 4) == 7", "assert find_kth_largest([10, 20, 30, 40, 50], 5) == 10", "assert find_kth_largest([50, 40, 30, 20, 10], 1) == 50", "assert find_kth_largest([1, 1, 1, 1, 1, 1], 1) == 1", "assert find_kth_largest([1, 2, 3, 4, 5], 3) == 3", "assert find_kth_largest([9, 8, 7, 6, 5, 4, 3, 2, 1], 9) == 1"], "function": "find_kth_largest", "signature": "def find_kth_largest(nums, k):", "score": 1.0, "domain": "generic"} {"id": "f521590c3a7f0c9e6558b918be24ae41", "problem": "You are given a list of integers and a separator. Your task is to implement a function `convert_list_to_string` that processes the list to include only integers within the range of -19 to 19 (inclusive of -19 and 19, but exclusive of -20 and 20). The function should convert these integers to strings and join them using the provided separator. \n\n**Input:**\n- A list of integers `int_list` and a string `separator`.\n\n**Output:**\n- A string that is the result of joining the filtered and converted integers using the separator.\n\n**Constraints:**\n- The list can contain any integers, but only those within the specified range should be included in the final output.\n- The separator is a non-empty string.\n\n**Sample Input:**\n- `int_list = [1, 2, 19, 20, -1, -19, -20]`\n- `separator = \", \"`\n\n**Sample Output:**\n- `\"1, 2, 19, -1, -19\"`", "reference": "def convert_list_to_string(int_list, separator):\n \"\"\"\n Converts a list of integers to a string, including only those integers within the range -19 to 19,\n and joins them using the provided separator.\n\n :param int_list: List of integers to be processed.\n :param separator: String used to separate the integers in the final output.\n :return: A string with the filtered and joined integers.\n \"\"\"\n filtered_list = [num for num in int_list if -20 < num < 20]\n string_list = [str(num) for num in filtered_list]\n result_string = separator.join(string_list)\n return result_string\n\n# Example usage:\n# print(convert_list_to_string([1, 2, 19, 20, -1, -19, -20], \", \")) # Output: \"1, 2, 19, -1, -19\"", "tests": ["assert convert_list_to_string([1, 2, 19, 20, -1, -19, -20], \", \") == \"1, 2, 19, -1, -19\"", "assert convert_list_to_string([5, 10, 15], \"-\") == \"5-10-15\"", "assert convert_list_to_string([-5, -10, -15], \" \") == \"-5 -10 -15\"", "assert convert_list_to_string([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19], \"|\") == \"0|1|2|3|4|5|6|7|8|9|10|11|12|13|14|15|16|17|18|19\"", "assert convert_list_to_string([-1, -2, -3, -4, -5, -6, -7, -8, -9, -10, -11, -12, -13, -14, -15, -16, -17, -18, -19], \":\") == \"-1:-2:-3:-4:-5:-6:-7:-8:-9:-10:-11:-12:-13:-14:-15:-16:-17:-18:-19\"", "assert convert_list_to_string([20, -20, 0], \",\") == \"0\"", "assert convert_list_to_string([], \",\") == \"\"", "assert convert_list_to_string([10, 20, 30, -10, -20, -30], \",\") == \"10,-10\"", "assert convert_list_to_string([19, -19, 20, -20], \" and \") == \"19 and -19\"", "assert convert_list_to_string([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, -1, -2, -3, -4, -5, -6, -7, -8, -9, -10, -11, -12, -13, -14, -15, -16, -17, -18, -19], \",\") == \"1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,-1,-2,-3,-4,-5,-6,-7,-8,-9,-10,-11,-12,-13,-14,-15,-16,-17,-18,-19\""], "function": "convert_list_to_string", "signature": "def convert_list_to_string(int_list, separator):", "score": 1.0, "domain": "generic"} {"id": "d24ce4ab3c48fea2e29a0da02b7afcaf", "problem": "You are given a list of strings and a positive integer threshold. Your task is to implement a function `filter_strings_by_length(strings, threshold)` that returns a new list containing only the strings from the input list whose lengths exceed the given threshold. \n\n**Input:**\n- A list of strings `strings` (1 ≤ len(strings) ≤ 1000), where each string consists of lowercase English letters and has a length between 1 and 100.\n- A positive integer `threshold` (1 ≤ threshold ≤ 100).\n\n**Output:**\n- A list of strings from `strings` that have a length greater than `threshold`.\n\n**Sample Input:**\n```\nstrings = [\"short\", \"medium\", \"longer_string\", \"tiny\", \"example_string\"]\nthreshold = 5\n```\n\n**Sample Output:**\n```\n['medium', 'longer_string', 'example_string']\n```", "reference": "def filter_strings_by_length(strings, threshold):\n \"\"\"\n Filters a list of strings, returning only those with a length greater than the specified threshold.\n\n :param strings: List of strings to be filtered.\n :param threshold: Positive integer threshold for string length.\n :return: List of strings with length greater than the threshold.\n \"\"\"\n return [s for s in strings if len(s) > threshold]", "tests": ["assert filter_strings_by_length([\"hello\", \"world\", \"hi\", \"python\"], 2) == [\"hello\", \"world\", \"python\"]", "assert filter_strings_by_length([\"a\", \"ab\", \"abc\", \"abcd\"], 3) == [\"abcd\"]", "assert filter_strings_by_length([\"short\", \"longer\", \"tiny\"], 5) == [\"longer\"]", "assert filter_strings_by_length([\"one\", \"two\", \"three\", \"four\"], 4) == [\"three\"]", "assert filter_strings_by_length([], 1) == []", "assert filter_strings_by_length([\"same\", \"size\", \"test\"], 3) == [\"same\", \"size\", \"test\"]", "assert filter_strings_by_length([\"threshold\", \"boundary\", \"case\"], 8) == [\"threshold\", \"boundary\"]", "assert filter_strings_by_length([\"\", \"a\", \"ab\", \"abc\"], 0) == [\"\", \"a\", \"ab\", \"abc\"]", "assert filter_strings_by_length([\"equal\", \"equal\", \"equal\"], 5) == []", "assert filter_strings_by_length([\"unique\", \"words\", \"only\"], 10) == []"], "function": "filter_strings_by_length", "signature": "def filter_strings_by_length(strings, threshold):", "score": 0.8, "domain": "generic"} {"id": "6e4e4e9858446d159433a5387e1fa9a8", "problem": "You are given a list of strings. Your task is to write a Python function that processes these strings and returns a dictionary. The dictionary should map each unique word (ignoring punctuation and case) to the number of times it appears across all strings. Assume words are separated by spaces.\n\n**Input:**\n- A list of strings, where each string may contain punctuation and words of varying cases.\n\n**Output:**\n- A dictionary with words as keys and their counts as values.\n\n**Sample Input:**\n```python\n[\"Apple is delicious!\", \"An apple a day keeps the doctor away.\", \"APPLE, apple, apple!\"]\n```\n\n**Sample Output:**\n```python\n{'apple': 6, 'is': 1, 'delicious': 1, 'an': 1, 'a': 1, 'day': 1, 'keeps': 1, 'the': 1, 'doctor': 1, 'away': 1}\n```", "reference": "import string\n\ndef count_words(strings):\n \"\"\"\n Counts the occurrences of each unique word in a list of strings, ignoring punctuation and case.\n \n :param strings: List of strings to process.\n :return: Dictionary mapping each unique word to its count.\n \"\"\"\n words_count = {}\n translator = str.maketrans('', '', string.punctuation)\n\n for s in strings:\n s = s.translate(translator).lower()\n words = s.split()\n for word in words:\n words_count[word] = words_count.get(word, 0) + 1\n\n return words_count\n\n# Example usage:\ninput_strings = [\"Apple is delicious!\", \"An apple a day keeps the doctor away.\", \"APPLE, apple, apple!\"]\nprint(count_words(input_strings))", "tests": ["assert count_words([\"Hello, world!\", \"Hello again.\"]) == {'hello': 2, 'world': 1, 'again': 1}", "assert count_words([\"Python, python, PYTHON!\"]) == {'python': 3}", "assert count_words([\"One fish, two fish, red fish, blue fish.\"]) == {'one': 1, 'fish': 4, 'two': 1, 'red': 1, 'blue': 1}", "assert count_words([\"\"]) == {}", "assert count_words([\"A quick brown fox jumps over the lazy dog.\"]) == {'a': 1, 'quick': 1, 'brown': 1, 'fox': 1, 'jumps': 1, 'over': 1, 'the': 1, 'lazy': 1, 'dog': 1}", "assert count_words([\"Punctuation: should, not; affect: the? count!\"]) == {'punctuation': 1, 'should': 1, 'not': 1, 'affect': 1, 'the': 1, 'count': 1}", "assert count_words([\"Multiple spaces should be handled.\"]) == {'multiple': 1, 'spaces': 1, 'should': 1, 'be': 1, 'handled': 1}", "assert count_words([\"Case Insensitivity\", \"CASE INSENSITIVITY\", \"case insensitivity\"]) == {'case': 3, 'insensitivity': 3}", "assert count_words([\"Mixed CASE words, mixed Case Words.\"]) == {'mixed': 2, 'case': 2, 'words': 2}", "assert count_words([\"SingleWord\"]) == {'singleword': 1}"], "function": "count_words", "signature": "def count_words(strings):", "score": 1.0, "domain": "generic"} {"id": "dfe987bd87801a2687647d762586e24a", "problem": "You are tasked with implementing a Python class named `Employee` to manage employee details. The class should have a constructor that accepts three parameters: `name` (a string), `id` (an integer), and `salary` (a float). Implement the following methods within the `Employee` class:\n\n1. `increase_salary(percentage)`: A method that increases the employee's salary by a given percentage.\n2. `display_details()`: A method that returns a formatted string containing the employee's ID, name, and salary.\n\nAdditionally, implement a function `create_employee(name, id, salary)` that creates and returns an instance of the `Employee` class with the provided parameters.\n\n**Sample Input:**\n```python\nemployee = create_employee(\"John Doe\", 123, 50000.0)\nemployee.increase_salary(10)\nprint(employee.display_details())\n```\n\n**Sample Output:**\n```\nEmployee ID: 123, Name: John Doe, Salary: $55000.00\n```", "reference": "class Employee:\n def __init__(self, name, id, salary):\n \"\"\"Initialize an Employee object with name, id, and salary.\"\"\"\n self.name = name\n self.id = id\n self.salary = salary\n\n def increase_salary(self, percentage):\n \"\"\"Increase the employee's salary by a given percentage.\"\"\"\n self.salary += self.salary * (percentage / 100)\n\n def display_details(self):\n \"\"\"Return a formatted string of the employee's details.\"\"\"\n return f\"Employee ID: {self.id}, Name: {self.name}, Salary: ${self.salary:.2f}\"\n\ndef create_employee(name, id, salary):\n \"\"\"Create and return an Employee object with the provided parameters.\"\"\"\n return Employee(name, id, salary)", "tests": ["assert create_employee(\"John Doe\", 123, 50000).display_details() == \"Employee ID: 123, Name: John Doe, Salary: $50000.00\"", "assert create_employee(\"Jane Smith\", 456, 60000).display_details() == \"Employee ID: 456, Name: Jane Smith, Salary: $60000.00\"", "assert create_employee(\"Alice Johnson\", 789, 75000).increase_salary(10) is None", "assert create_employee(\"Alice Johnson\", 789, 75000).display_details() == \"Employee ID: 789, Name: Alice Johnson, Salary: $75000.00\"", "assert create_employee(\"Alice Johnson\", 789, 75000).increase_salary(10) or True\nassert create_employee(\"Alice Johnson\", 789, 75000).display_details() == \"Employee ID: 789, Name: Alice Johnson, Salary: $82500.00\"", "assert create_employee(\"Bob Brown\", 101, 55000).increase_salary(5) is None", "assert create_employee(\"Bob Brown\", 101, 55000).display_details() == \"Employee ID: 101, Name: Bob Brown, Salary: $55000.00\"", "assert create_employee(\"Bob Brown\", 101, 55000).increase_salary(5) or True\nassert create_employee(\"Bob Brown\", 101, 55000).display_details() == \"Employee ID: 101, Name: Bob Brown, Salary: $57750.00\"", "assert create_employee(\"Charlie Davis\", 202, 48000).increase_salary(20) is None", "assert create_employee(\"Charlie Davis\", 202, 48000).display_details() == \"Employee ID: 202, Name: Charlie Davis, Salary: $57600.00\""], "function": "create_employee", "signature": "def create_employee(name, id, salary):", "score": 0.7, "domain": "generic"} {"id": "4cad42cb38a0acb6f058a54a9315d491", "problem": "You are tasked with implementing a function `is_palindrome(s)` that determines whether a given string `s` is a palindrome. A string is considered a palindrome if it reads the same backward as forward, ignoring case, spaces, and punctuation. Your function should return `True` if the string is a palindrome and `False` otherwise.\n\n**Input:**\n- A single string `s` (1 ≤ len(s) ≤ 1000).\n\n**Output:**\n- Return `True` if `s` is a palindrome, otherwise return `False`.\n\n**Sample Input:**\n```\n\"A man, a plan, a canal, Panama\"\n```\n\n**Sample Output:**\n```\nTrue\n```\n\n**Sample Input:**\n```\n\"hello\"\n```\n\n**Sample Output:**\n```\nFalse\n```\n\nWrite a test suite for this function using the `unittest` framework to ensure its correctness.", "reference": "import unittest\nimport string\n\ndef is_palindrome(s):\n \"\"\"\n Determines if the given string s is a palindrome, ignoring case, spaces, and punctuation.\n \n :param s: The input string.\n :return: True if s is a palindrome, False otherwise.\n \"\"\"\n translator = str.maketrans('', '', string.punctuation + string.whitespace)\n normalized_s = s.translate(translator).lower()\n return normalized_s == normalized_s[::-1]\n\nclass TestIsPalindrome(unittest.TestCase):\n def test_empty_string(self):\n self.assertTrue(is_palindrome(\"\"))\n\n def test_single_character(self):\n self.assertTrue(is_palindrome(\"a\"))\n\n def test_palindrome_no_punctuation_no_spaces(self):\n self.assertTrue(is_palindrome(\"racecar\"))\n self.assertTrue(is_palindrome(\"madam\"))\n self.assertTrue(is_palindrome(\"refer\"))\n\n def test_palindrome_with_punctuation(self):\n self.assertTrue(is_palindrome(\"A man, a plan, a canal, Panama\"))\n self.assertTrue(is_palindrome(\"No 'x' in Nixon\"))\n self.assertTrue(is_palindrome(\"Madam, in Eden, I'm Adam\"))\n\n def test_palindrome_with_spaces(self):\n self.assertTrue(is_palindrome(\"level\"))\n self.assertTrue(is_palindrome(\"Was it a car or a cat I saw\"))\n self.assertTrue(is_palindrome(\"A Toyota. Race fast, safe car. A Toyota.\"))\n\n def test_non_palindrome(self):\n self.assertFalse(is_palindrome(\"hello\"))\n self.assertFalse(is_palindrome(\"world\"))\n self.assertFalse(is_palindrome(\"palindrome\"))\n\n def test_mixed_case(self):\n self.assertTrue(is_palindrome(\"Malayalam\"))\n self.assertTrue(is_palindrome(\"Step on no pets\"))\n self.assertTrue(is_palindrome(\"Madam\"))\n\n def test_long_palindrome(self):\n self.assertTrue(is_palindrome(\"A Santa at NASA\"))\n self.assertTrue(is_palindrome(\"Was it a car or a cat I saw住Madam, in Eden, I'm AdamSit a cat or a car, as it was\"))\n self.assertTrue(is_palindrome(\"A Toyota. Race fast, safe car. A Toyota. A Toyota. Race fast, safe car. A Toyota.\"))\n\n def test_long_non_palindrome(self):\n self.assertFalse(is_palindrome(\"This is not a palindrome\"))\n\nif __name__ == '__main__':\n unittest.main()", "tests": ["assert is_palindrome(\"\") == True", "assert is_palindrome(\"a\") == True", "assert is_palindrome(\"racecar\") == True", "assert is_palindrome(\"madam\") == True", "assert is_palindrome(\"refer\") == True", "assert is_palindrome(\"A man, a plan, a canal, Panama\") == True", "assert is_palindrome(\"No 'x' in Nixon\") == True", "assert is_palindrome(\"Madam, in Eden, I'm Adam\") == True", "assert is_palindrome(\"hello\") == False", "assert is_palindrome(\"world\") == False"], "function": "is_palindrome", "signature": "def is_palindrome(s):", "score": 1.0, "domain": "generic"} {"id": "43799c1936d880fbbf9456418bc4e7f4", "problem": "You are given a string `s` representing a Roman numeral. Your task is to write a function `roman_to_int` that converts this Roman numeral to its corresponding integer value. The input string `s` can contain both uppercase and lowercase Roman numerals. Your function should handle these cases and return the correct integer.\n\n**Constraints:**\n- The length of the string `s` is between 1 and 15.\n- The string `s` is guaranteed to be a valid Roman numeral.\n\n**Sample Input:**\n```\n\"MCMXCIV\"\n\"mmxxiii\"\n```\n\n**Sample Output:**\n```\n1994\n2023\n```", "reference": "def roman_to_int(s: str) -> int:\n \"\"\"\n Convert a Roman numeral string to an integer.\n \n :param s: A string representing a Roman numeral (both uppercase and lowercase are allowed).\n :return: The integer value corresponding to the Roman numeral.\n \"\"\"\n roman_to_value = {\n 'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000,\n 'i': 1, 'v': 5, 'x': 10, 'l': 50, 'c': 100, 'd': 500, 'm': 1000\n }\n \n result = 0\n \n for i in range(len(s)):\n if i + 1 < len(s) and roman_to_value[s[i]] < roman_to_value[s[i + 1]]:\n result -= roman_to_value[s[i]]\n else:\n result += roman_to_value[s[i]]\n \n return result", "tests": ["assert roman_to_int(\"III\") == 3", "assert roman_to_int(\"IV\") == 4", "assert roman_to_int(\"IX\") == 9", "assert roman_to_int(\"LVIII\") == 58", "assert roman_to_int(\"MCMXCIV\") == 1994", "assert roman_to_int(\"mmxxiii\") == 2023", "assert roman_to_int(\"XLIV\") == 44", "assert roman_to_int(\"CDXLIV\") == 444", "assert roman_to_int(\"MCMLXXXIV\") == 1984", "assert roman_to_int(\"D\") == 500"], "function": "roman_to_int", "signature": "def roman_to_int(s: str) -> int:", "score": 1.0, "domain": "generic"} {"id": "fdb2aa80b0afe01660ff1fe3185ce8cd", "problem": "You are given a string `s`. Your task is to determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. A string is a palindrome if it reads the same forwards and backwards.\n\n**Input:**\n- A single string `s` (1 ≤ |s| ≤ 10^5), which may contain uppercase and lowercase letters, digits, and spaces.\n\n**Output:**\n- Return `True` if the string is a palindrome, otherwise return `False`.\n\n**Sample Input:**\n```\nA man a plan a canal Panama\nWas it a car or a cat I saw\n```\n\n**Sample Output:**\n```\nTrue\nTrue\n```", "reference": "def is_palindrome(s: str) -> bool:\n \"\"\"\n Determines if the given string is a palindrome, considering only alphanumeric characters and ignoring cases.\n \n :param s: The input string.\n :return: True if the string is a palindrome, False otherwise.\n \"\"\"\n cleaned_string = ''.join(char.lower() for char in s if char.isalnum())\n return cleaned_string == cleaned_string[::-1]\n\n# Example usage:\nprint(is_palindrome(\"A man a plan a canal Panama\")) # Output: True\nprint(is_palindrome(\"Was it a car or a cat I saw\")) # Output: True", "tests": ["assert is_palindrome(\"A man a plan a canal Panama\") == True", "assert is_palindrome(\"Was it a car or a cat I saw\") == True", "assert is_palindrome(\"No lemon no melon\") == True", "assert is_palindrome(\"Hello World\") == False", "assert is_palindrome(\"racecar\") == True", "assert is_palindrome(\"Madam In Eden Im Adam\") == True", "assert is_palindrome(\"Step on no pets\") == True", "assert is_palindrome(\"Eva, can I see bees in a cave?\") == True", "assert is_palindrome(\"Not a palindrome\") == False", "assert is_palindrome(\"\") == True"], "function": "is_palindrome", "signature": "def is_palindrome(s: str) -> bool:", "score": 1.0, "domain": "generic"} {"id": "a89a052d9bcdfc97a9b3718aba8072d3", "problem": "You are given two strings `str1` and `str2`. Your task is to find the longest common substring between these two strings. A substring is a contiguous sequence of characters within a string.\n\n**Input:**\n- Two strings `str1` and `str2` (1 ≤ |str1|, |str2| ≤ 1000).\n\n**Output:**\n- A single string representing the longest common substring. If there are multiple substrings of the same maximum length, return any one of them.\n\n**Sample Input:**\n```\nstr1 = \"the quick brown fox jumps over the lazy dog\"\nstr2 = \"the quick red fox jumps over the lazy cat\"\n```\n\n**Sample Output:**\n```\n\"the quick fox jumps over the lazy \"\n```", "reference": "def longest_common_substring(str1, str2):\n \"\"\"\n Finds the longest common substring between two given strings.\n\n :param str1: First input string.\n :param str2: Second input string.\n :return: The longest common substring.\n \"\"\"\n m = len(str1)\n n = len(str2)\n L = [[0] * (n + 1) for _ in range(m + 1)]\n length_of_lcs = 0\n end_index_lcs = 0\n\n for i in range(1, m + 1):\n for j in range(1, n + 1):\n if str1[i - 1] == str2[j - 1]:\n L[i][j] = L[i - 1][j - 1] + 1\n if L[i][j] > length_of_lcs:\n length_of_lcs = L[i][j]\n end_index_lcs = i\n else:\n L[i][j] = 0\n\n longest_common_substr = str1[end_index_lcs - length_of_lcs:end_index_lcs]\n return longest_common_substr\n\n# Define the strings\nstring1 = \"the quick brown fox jumps over the lazy dog\"\nstring2 = \"the quick red fox jumps over the lazy cat\"\n\n# Call the function and print the solution\nresult = longest_common_substring(string1, string2)\nprint(\"The longest common substring is:\", result)", "tests": ["assert longest_common_substring(\"abcde\", \"abfde\") == \"ab\"", "assert longest_common_substring(\"abcdef\", \"zabcf\") == \"abc\"", "assert longest_common_substring(\"hello\", \"yellow\") == \"ello\"", "assert longest_common_substring(\"abcdef\", \"ghijkl\") == \"\"", "assert longest_common_substring(\"aaaa\", \"aa\") == \"aa\"", "assert longest_common_substring(\"abc\", \"def\") == \"\"", "assert longest_common_substring(\"abcabc\", \"abc\") == \"abc\"", "assert longest_common_substring(\"abc\", \"abcabc\") == \"abc\"", "assert longest_common_substring(\"\", \"abc\") == \"\"", "assert longest_common_substring(\"abc\", \"\") == \"\""], "function": "longest_common_substring", "signature": "def longest_common_substring(str1, str2):", "score": 1.0, "domain": "algorithmic"} {"id": "5898153774f4e58a0db23c51b06e8464", "problem": "You are given an array `arr` of integers. Your task is to implement a function `find_min_max` that returns a tuple `(min, max)` where `min` is the smallest element in the array and `max` is the largest element in the array. The function should handle edge cases such as an empty array or an array with a single element. You are not allowed to use built-in functions like `min` and `max`.\n\n**Input:**\n- An array `arr` of integers.\n\n**Output:**\n- A tuple `(min, max)` where `min` is the smallest element and `max` is the largest element in the array. If the array is empty, return `(None, None)`.\n\n**Sample Input:**\n- `arr = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]`\n\n**Sample Output:**\n- `(1, 9)`\n\n**Constraints:**\n- The array can contain between 0 and 10^5 elements.\n- Each element in the array can range from -10^9 to 10^9.", "reference": "def find_min_max(arr):\n \"\"\"\n Finds the minimum and maximum elements in an array of integers.\n \n Parameters:\n arr (list of int): The array of integers.\n \n Returns:\n tuple: A tuple containing the minimum and maximum elements of the array.\n Returns (None, None) if the array is empty.\n \"\"\"\n # Handle edge case for empty array\n if len(arr) == 0:\n return None, None\n \n # Initialize min and max with the first element of the array\n min_val = arr[0]\n max_val = arr[0]\n \n # Iterate through the array starting from the second element\n for num in arr[1:]:\n if num < min_val:\n min_val = num\n if num > max_val:\n max_val = num\n \n return min_val, max_val", "tests": ["assert find_min_max([3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]) == (1, 9)", "assert find_min_max([10]) == (10, 10)", "assert find_min_max([-10, -20, -30, -40]) == (-40, -10)", "assert find_min_max([0, 0, 0, 0]) == (0, 0)", "assert find_min_max([]) == (None, None)", "assert find_min_max([100, 200, 300, 400, 500]) == (100, 500)", "assert find_min_max([5, 4, 3, 2, 1]) == (1, 5)", "assert find_min_max([1, 2, 3, 4, 5, -1, -2, -3, -4, -5]) == (-5, 5)", "assert find_min_max([7]) == (7, 7)", "assert find_min_max([1, 1, 1, 1, 1, 1, 1]) == (1, 1)"], "function": "find_min_max", "signature": "def find_min_max(arr):", "score": 1.0, "domain": "generic"} {"id": "cdf839972c27a8356812adb514046bca", "problem": "You are given a list of integers. Your task is to determine the number of unique pairs `(i, j)` such that `i < j` and the sum of `arr[i]` and `arr[j]` is even. \n\n**Input:**\n- The first line contains an integer `n` (1 ≤ n ≤ 10^5), the number of elements in the list.\n- The second line contains `n` space-separated integers `arr[i]` (1 ≤ arr[i] ≤ 10^9).\n\n**Output:**\n- Print a single integer, the number of unique pairs `(i, j)` such that `i < j` and `arr[i] + arr[j]` is even.\n\n**Sample Input:**\n```\n5\n1 2 3 4 5\n```\n\n**Sample Output:**\n```\n4\n```", "reference": "def count_even_sum_pairs(arr):\n \"\"\"\n Counts the number of unique pairs (i, j) such that i < j and arr[i] + arr[j] is even.\n\n :param arr: List of integers\n :return: Integer count of valid pairs\n \"\"\"\n even_count = 0\n odd_count = 0\n \n for num in arr:\n if num % 2 == 0:\n even_count += 1\n else:\n odd_count += 1\n \n even_pairs = (even_count * (even_count - 1)) // 2\n odd_pairs = (odd_count * (odd_count - 1)) // 2\n \n return even_pairs + odd_pairs\n\n# Example usage:\narr = [1, 2, 3, 4, 5]\nprint(count_even_sum_pairs(arr)) # Output: 4", "tests": ["assert count_even_sum_pairs([1, 2, 3, 4, 5]) == 4", "assert count_even_sum_pairs([2, 4, 6, 8]) == 6", "assert count_even_sum_pairs([1, 3, 5, 7]) == 6", "assert count_even_sum_pairs([1, 2]) == 0", "assert count_even_sum_pairs([2, 3]) == 0", "assert count_even_sum_pairs([1]) == 0", "assert count_even_sum_pairs([]) == 0", "assert count_even_sum_pairs([1, 1, 1, 1]) == 6", "assert count_even_sum_pairs([2, 2, 2, 2]) == 6", "assert count_even_sum_pairs([1, 2, 3, 4, 5, 6]) == 9"], "function": "count_even_sum_pairs", "signature": "def count_even_sum_pairs(arr):", "score": 0.9, "domain": "algorithmic"} {"id": "7016af49080f9c6a70b31a987cf1c745", "problem": "You are tasked with implementing a function `geometric_mean(series: list) -> float` that computes the geometric mean of a given list of positive floating-point numbers. The geometric mean is defined as the nth root of the product of n numbers, where n is the number of elements in the list. Your function must handle lists containing up to 15 decimal places of precision and return the result rounded to 14 decimal places.\n\nYour function should raise a `ValueError` with a descriptive message if the input is not a non-empty list or if any element in the list is not a positive floating-point number.\n\n**Constraints:**\n- The list `series` will contain between 1 and 100 elements.\n- Each element in `series` will be a positive floating-point number.\n\n**Sample Input:**\n```python\n[1.0, 2.0, 3.0, 4.0]\n```\n\n**Sample Output:**\n```python\n2.21336383940064\n```", "reference": "import math\n\ndef geometric_mean(series: list) -> float:\n \"\"\"\n Calculate the geometric mean of a non-empty list of positive floating-point numbers.\n \n Parameters:\n series (list): A list of positive floating-point numbers.\n \n Returns:\n float: The geometric mean rounded to 14 decimal places.\n \n Raises:\n ValueError: If the input is not a non-empty list or contains non-positive floating-point numbers.\n \"\"\"\n if not isinstance(series, list) or not series:\n raise ValueError(\"Input must be a non-empty list.\")\n if not all(isinstance(num, float) and num > 0 for num in series):\n raise ValueError(\"All elements must be positive floating-point numbers.\")\n \n product = 1.0\n for num in series:\n product *= num\n \n geo_mean = product ** (1 / len(series))\n return round(geo_mean, 14)", "tests": ["assert geometric_mean([1.0, 2.0, 3.0, 4.0]) == 2.21336383940064", "assert geometric_mean([1.5, 2.5, 3.5]) == 2.28942848510666", "assert geometric_mean([1.0]) == 1.0", "assert geometric_mean([2.0, 8.0]) == 4.0", "assert geometric_mean([1.23456789, 9.87654321]) == 3.74165738677394", "assert geometric_mean([10.0, 10.0, 10.0, 10.0]) == 10.0", "assert geometric_mean([0.1, 0.2, 0.3, 0.4]) == 0.18171205928321", "assert geometric_mean([1.1, 2.2, 3.3, 4.4, 5.5]) == 2.60517108469735", "assert geometric_mean([100.0, 100.0, 100.0]) == 100.0", "assert geometric_mean([1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]) == 1.0"], "function": "geometric_mean", "signature": "def geometric_mean(series: list) -> float:", "score": 0.5, "domain": "generic"} {"id": "1dd96ed337b82b9413ca403b5fac089b", "problem": "You are tasked with implementing a function `convert_ids` that processes a list of identifiers for entities in a hypothetical database. Each identifier can be either a single string or a list of strings. If an identifier is a list of strings, you must sort the strings in lexicographical order before generating URLs for them. \n\nYour function should return a list of URLs, where each URL is constructed as `http://www.hypothetical-database.com/entity/{id}`, with `{id}` being the unique identifier.\n\n**Input:**\n- A list of identifiers, where each identifier is either a string or a list of strings.\n\n**Output:**\n- A list of URLs corresponding to the identifiers.\n\n**Sample Input:**\n```python\n[\"abc\", [\"def\", \"abc\"], \"ghi\"]\n```\n\n**Sample Output:**\n```python\n[\n \"http://www.hypothetical-database.com/entity/abc\",\n \"http://www.hypothetical-database.com/entity/abc\",\n \"http://www.hypothetical-database.com/entity/def\",\n \"http://www.hypothetical-database.com/entity/ghi\"\n]\n```", "reference": "def convert_ids(ids):\n \"\"\"\n Converts a list of identifiers into a list of URLs.\n \n Parameters:\n ids (list): A list of identifiers, where each identifier is either a string or a list of strings.\n \n Returns:\n list: A list of URLs corresponding to the identifiers.\n \"\"\"\n urls = []\n for id in ids:\n if isinstance(id, list):\n id = sorted(id)\n urls.extend([f\"http://www.hypothetical-database.com/entity/{single_id}\" for single_id in id])\n else:\n urls.append(f\"http://www.hypothetical-database.com/entity/{id}\")\n return urls", "tests": ["assert convert_ids([\"abc\", \"def\"]) == [\"http://www.hypothetical-database.com/entity/abc\", \"http://www.hypothetical-database.com/entity/def\"]", "assert convert_ids([[\"banana\", \"apple\"], \"cherry\"]) == [\"http://www.hypothetical-database.com/entity/apple\", \"http://www.hypothetical-database.com/entity/banana\", \"http://www.hypothetical-database.com/entity/cherry\"]", "assert convert_ids([[\"zebra\", \"yak\", \"antelope\"], \"giraffe\"]) == [\"http://www.hypothetical-database.com/entity/antelope\", \"http://www.hypothetical-database.com/entity/yak\", \"http://www.hypothetical-database.com/entity/zebra\", \"http://www.hypothetical-database.com/entity/giraffe\"]", "assert convert_ids([\"123\", [\"456\", \"789\"]]) == [\"http://www.hypothetical-database.com/entity/123\", \"http://www.hypothetical-database.com/entity/456\", \"http://www.hypothetical-database.com/entity/789\"]", "assert convert_ids([]) == []", "assert convert_ids([[\"single\"]]) == [\"http://www.hypothetical-database.com/entity/single\"]", "assert convert_ids([\"a\", [\"b\", \"a\"], \"c\"]) == [\"http://www.hypothetical-database.com/entity/a\", \"http://www.hypothetical-database.com/entity/a\", \"http://www.hypothetical-database.com/entity/b\", \"http://www.hypothetical-database.com/entity/c\"]", "assert convert_ids([[\"x\", \"y\", \"z\"], [\"m\", \"n\", \"o\"], \"p\"]) == [\"http://www.hypothetical-database.com/entity/x\", \"http://www.hypothetical-database.com/entity/y\", \"http://www.hypothetical-database.com/entity/z\", \"http://www.hypothetical-database.com/entity/m\", \"http://www.hypothetical-database.com/entity/n\", \"http://www.hypothetical-database.com/entity/o\", \"http://www.hypothetical-database.com/entity/p\"]", "assert convert_ids([\"single\"]) == [\"http://www.hypothetical-database.com/entity/single\"]", "assert convert_ids([[\"apple\", \"banana\", \"cherry\"], [\"dog\", \"cat\"], \"elephant\"]) == [\"http://www.hypothetical-database.com/entity/apple\", \"http://www.hypothetical-database.com/entity/banana\", \"http://www.hypothetical-database.com/entity/cherry\", \"http://www.hypothetical-database.com/entity/cat\", \"http://www.hypothetical-database.com/entity/dog\", \"http://www.hypothetical-database.com/entity/elephant\"]"], "function": "convert_ids", "signature": "def convert_ids(ids):", "score": 1.0, "domain": "generic"} {"id": "82422d476254f03d7ed200f7647fd36d", "problem": "You are given a list of integers `numbers` and a list of operations `operations`. The `operations` list consists of the strings \"add\" and \"subtract\" in alternating order. Your task is to sequentially apply these operations to the `numbers` list and return the final result. If at any point the result of an operation becomes negative, round it up to the nearest multiple of 5 before proceeding with the next operation. Implement the function `alternating_operations(numbers: List[int], operations: List[str]) -> int` to achieve this.\n\n**Constraints:**\n- 1 ≤ len(numbers) ≤ 100\n- 1 ≤ len(operations) ≤ 99\n- -1000 ≤ numbers[i] ≤ 1000\n- operations[i] is either \"add\" or \"subtract\"\n\n**Sample Input:**\n```\nnumbers = [10, -5, 3, 8]\noperations = [\"subtract\", \"add\", \"subtract\"]\n```\n\n**Sample Output:**\n```\n5\n```", "reference": "from typing import List\nimport math\n\ndef alternating_operations(numbers: List[int], operations: List[str]) -> int:\n \"\"\"\n Apply alternating operations on a list of numbers and return the final result.\n If the result of an operation is negative, round it up to the nearest multiple of 5.\n \n :param numbers: List of integers to perform operations on.\n :param operations: List of operations (\"add\" or \"subtract\") to apply in sequence.\n :return: Final result after applying all operations.\n \"\"\"\n result = numbers[0]\n for i, operation in enumerate(operations):\n if operation == \"add\":\n result += numbers[i + 1]\n elif operation == \"subtract\":\n result -= numbers[i + 1]\n \n if result < 0:\n result = math.ceil(result / 5) * 5\n \n return result", "tests": ["assert alternating_operations([10, 5, 3], [\"subtract\", \"add\"]) == 8", "assert alternating_operations([10, 15, 5], [\"subtract\", \"subtract\"]) == 0", "assert alternating_operations([10, 20, 5], [\"add\", \"subtract\"]) == 15", "assert alternating_operations([5, 10, 15], [\"subtract\", \"subtract\"]) == -10", "assert alternating_operations([5, 10, 15], [\"subtract\", \"add\"]) == 10", "assert alternating_operations([1, 2, 3, 4], [\"add\", \"subtract\", \"add\"]) == 3", "assert alternating_operations([10, 20, 30, 40], [\"subtract\", \"subtract\", \"subtract\"]) == -70", "assert alternating_operations([10, 5, 3, 2], [\"subtract\", \"subtract\", \"subtract\"]) == -1", "assert alternating_operations([0, 0, 0, 0], [\"add\", \"add\", \"add\"]) == 0", "assert alternating_operations([5, 5, 5, 5], [\"subtract\", \"subtract\", \"subtract\"]) == -15"], "function": "alternating_operations", "signature": "def alternating_operations(numbers: List[int], operations: List[str]) -> int:", "score": 0.3, "domain": "generic"} {"id": "7a612e4415986a56b84de72c80e17739", "problem": "You are given a 2D list `matrix` representing a matrix of integers. Your task is to write a function `find_max_in_each_row` that returns a list of integers where each integer is the maximum value found in the corresponding row of the matrix. If a row is empty, append `None` to the result list. The function should efficiently handle edge cases, such as an empty matrix or rows with a single element.\n\n**Sample Input:**\n```python\nmatrix = [\n [3, 1, 4],\n [1, 5, 9],\n [2, 6, 5, 3, 5],\n [7],\n []\n]\n```\n\n**Sample Output:**\n```python\n[4, 9, 6, 7, None]\n```", "reference": "def find_max_in_each_row(matrix):\n \"\"\"\n Returns a list of integers representing the maximum value in each row of the matrix.\n If a row is empty, appends None to the result list.\n \n :param matrix: List[List[int]] - A 2D list of integers.\n :return: List[Optional[int]] - A list of maximum values from each row.\n \"\"\"\n max_values = []\n for row in matrix:\n if row:\n max_values.append(max(row))\n else:\n max_values.append(None)\n return max_values\n\n# Example usage:\nmatrix = [\n [3, 1, 4],\n [1, 5, 9],\n [2, 6, 5, 3, 5],\n [7],\n []\n]\n\nprint(find_max_in_each_row(matrix)) # Output: [4, 9, 6, 7, None]", "tests": ["assert find_max_in_each_row([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) == [3, 6, 9]", "assert find_max_in_each_row([[10], [20], [30]]) == [10, 20, 30]", "assert find_max_in_each_row([[-1, -2, -3], [-4, -5, -6], [-7, -8, -9]]) == [-1, -4, -7]", "assert find_max_in_each_row([[100]]) == [100]", "assert find_max_in_each_row([[]]) == [None]", "assert find_max_in_each_row([]) == []", "assert find_max_in_each_row([[1, 1, 1], [2, 2, 2], [3, 3, 3]]) == [1, 2, 3]", "assert find_max_in_each_row([[1, 2], [3, 4, 5], [6], [7, 8, 9, 10], []]) == [2, 5, 6, 10, None]", "assert find_max_in_each_row([[0, -1, -2], [-3, -4, -5], [-6, -7, -8], [-9]]) == [0, -3, -6, -9]", "assert find_max_in_each_row([[1000, 2000, 3000], [4000, 5000], [6000], [], [7000, 8000, 9000]]) == [3000, 5000, 6000, None, 9000]"], "function": "find_max_in_each_row", "signature": "def find_max_in_each_row(matrix):", "score": 1.0, "domain": "generic"} {"id": "b90624dab46f38fb893a18c430c078f5", "problem": "You are given two strings, `str1` and `str2`. Your task is to write a function that computes the minimum edit distance (Levenshtein distance) between these two strings. The minimum edit distance is defined as the minimum number of single-character edits (insertions, deletions, or substitutions) required to transform `str1` into `str2`. Your function should return an integer representing this distance.\n\n**Input:**\n- Two strings `str1` and `str2` (1 ≤ |str1|, |str2| ≤ 1000).\n\n**Output:**\n- An integer representing the minimum edit distance between `str1` and `str2`.\n\n**Sample Input:**\n```\nkitten\nsitting\n```\n\n**Sample Output:**\n```\n3\n```", "reference": "def min_edit_distance(str1, str2):\n \"\"\"\n Calculate the minimum edit distance (Levenshtein distance) between two strings.\n \n Parameters:\n str1 (str): The first string.\n str2 (str): The second string.\n \n Returns:\n int: The minimum number of single-character edits required to change str1 into str2.\n \"\"\"\n m = len(str1)\n n = len(str2)\n \n dp = [[0] * (n + 1) for _ in range(m + 1)]\n \n for i in range(m + 1):\n for j in range(n + 1):\n if i == 0:\n dp[i][j] = j\n elif j == 0:\n dp[i][j] = i\n elif str1[i - 1] == str2[j - 1]:\n dp[i][j] = dp[i - 1][j - 1]\n else:\n dp[i][j] = 1 + min(dp[i][j - 1], dp[i - 1][j], dp[i - 1][j - 1])\n \n return dp[m][n]", "tests": ["assert min_edit_distance(\"kitten\", \"sitting\") == 3", "assert min_edit_distance(\"flaw\", \"lawn\") == 2", "assert min_edit_distance(\"intention\", \"execution\") == 5", "assert min_edit_distance(\"abc\", \"abc\") == 0", "assert min_edit_distance(\"abc\", \"def\") == 3", "assert min_edit_distance(\"\", \"abc\") == 3", "assert min_edit_distance(\"abc\", \"\") == 3", "assert min_edit_distance(\"\", \"\") == 0", "assert min_edit_distance(\"a\", \"b\") == 1", "assert min_edit_distance(\"abcde\", \"bcde\") == 1"], "function": "min_edit_distance", "signature": "def min_edit_distance(str1, str2):", "score": 1.0, "domain": "generic"} {"id": "e8c16d65b1a2f7521dac547e6fa6dab2", "problem": "You are given a JSON file containing an array of user objects. Each user object has the following fields:\n- `id`: A unique identifier for the user.\n- `name`: The user's name.\n- `email`: The user's email address.\n- `age`: The user's age.\n- `address`: The user's address.\n- `phone`: The user's phone number.\n\nYour task is to write a Python function `process_users(json_file_path)` that reads this JSON file, processes the data, and returns a dictionary. The dictionary should map each user's `id` to another dictionary containing the user's `name` and `email`. You should ignore any user who is under 18 years old and any user who does not have a valid email address (i.e., an email address that contains both '@' and '.'). Your function should handle any errors that may occur when reading or processing the file.\n\n**Sample Input (users.json):**\n```json\n[\n {\"id\": 1, \"name\": \"Alice\", \"email\": \"alice@example.com\", \"age\": 20, \"address\": \"123 Main St\", \"phone\": \"555-1234\"},\n {\"id\": 2, \"name\": \"Bob\", \"email\": \"bobexample.com\", \"age\": 22, \"address\": \"456 Elm St\", \"phone\": \"555-5678\"},\n {\"id\": 3, \"name\": \"Charlie\", \"email\": \"charlie@example.com\", \"age\": 17, \"address\": \"789 Oak St\", \"phone\": \"555-8765\"}\n]\n```\n\n**Sample Output:**\n```python\n{1: {'name': 'Alice', 'email': 'alice@example.com'}, 2: {'name': 'Charlie', 'email': 'charlie@example.com'}}\n```", "reference": "import json\n\ndef process_users(json_file_path):\n \"\"\"\n Reads a JSON file containing user data and returns a dictionary mapping each user's id to their name and email.\n Only includes users who are 18 or older and have a valid email address.\n \n :param json_file_path: Path to the JSON file.\n :return: Dictionary with user ids as keys and dictionaries of name and email as values.\n \"\"\"\n users_info = {}\n try:\n with open(json_file_path, 'r') as file:\n users = json.load(file)\n\n for user in users:\n try:\n if user['age'] >= 18 and '@' in user['email'] and '.' in user['email']:\n users_info[user['id']] = {'name': user['name'], 'email': user['email']}\n except KeyError:\n continue\n except (FileNotFoundError, json.JSONDecodeError):\n pass\n \n return users_info", "tests": ["assert process_users('empty.json') == {}", "assert process_users('no_users.json') == {}", "assert process_users('underage_users.json') == {}", "assert process_users('invalid_emails.json') == {}", "assert process_users('valid_users.json') == {'1': {'name': 'John Doe', 'email': 'john.doe@example.com'}, '2': {'name': 'Jane Smith', 'email': 'jane.smith@example.com'}}", "assert process_users('mixed_users.json') == {'3': {'name': 'Alice Johnson', 'email': 'alice.johnson@example.com'}}", "assert process_users('missing_keys.json') == {'5': {'name': 'Bob Brown', 'email': 'bob.brown@example.com'}}", "assert process_users('malformed_json.json') == {}", "assert process_users('nonexistent_file.json') == {}", "assert process_users('users_with_extra_fields.json') == {'6': {'name': 'Charlie Davis', 'email': 'charlie.davis@example.com'}}"], "function": "process_users", "signature": "def process_users(json_file_path):", "score": 0.6, "domain": "generic"} {"id": "be44fd7f965b70e37b6fd66847db1154", "problem": "You are given a function `shape_properties` that accepts a list of integers representing the dimensions of a geometric shape. The function must return a string detailing the perimeter and area of the shape. The input list can contain one, two, or three integers:\n\n- **One integer**: Represents the side length of a square.\n- **Two integers**: Represent the length and width of a rectangle.\n- **Three integers**: Represent the side lengths of a triangle. If the dimensions do not form a valid triangle, return \"Invalid triangle dimensions\".\n\nFor a triangle, determine its type (Equilateral, Isosceles, or Scalene) and include this information in the output string. The perimeter and area values should be rounded to one decimal place.\n\n**Sample Input and Output:**\n- Input: `[5]`\n - Output: `\"Perimeter = 20.0 Area = 25.0\"`\n- Input: `[4, 6]`\n - Output: `\"Perimeter = 20.0 Area = 24.0\"`\n- Input: `[3, 4, 5]`\n - Output: `\"Scalene Triangle: Perimeter = 12.0 Area = 6.0\"`\n- Input: `[1, 1, 2]`\n - Output: `\"Invalid triangle dimensions\"`", "reference": "import math\n\ndef shape_properties(dimensions):\n \"\"\"\n Calculate and return the perimeter and area of a shape based on its dimensions.\n \n Parameters:\n dimensions (list of int): A list containing 1, 2, or 3 integers representing the dimensions of a shape.\n \n Returns:\n str: A string detailing the perimeter and area of the shape, rounded to one decimal place.\n If the dimensions do not form a valid triangle, returns \"Invalid triangle dimensions\".\n \"\"\"\n if len(dimensions) == 1:\n side = dimensions[0]\n perimeter = 4 * side\n area = side * side\n return f\"Perimeter = {perimeter:.1f} Area = {area:.1f}\"\n elif len(dimensions) == 2:\n length, width = dimensions\n perimeter = 2 * (length + width)\n area = length * width\n return f\"Perimeter = {perimeter:.1f} Area = {area:.1f}\"\n elif len(dimensions) == 3:\n a, b, c = dimensions\n if a + b <= c or a + c <= b or b + c <= a:\n return \"Invalid triangle dimensions\"\n perimeter = a + b + c\n s = perimeter / 2\n area = math.sqrt(s * (s - a) * (s - b) * (s - c))\n if a == b == c:\n triangle_type = \"Equilateral\"\n elif a == b or b == c or a == c:\n triangle_type = \"Isosceles\"\n else:\n triangle_type = \"Scalene\"\n return f\"{triangle_type} Triangle: Perimeter = {perimeter:.1f} Area = {area:.1f}\"\n else:\n return \"Invalid input dimensions\"", "tests": ["assert shape_properties([5]) == \"Perimeter = 20.0 Area = 25.0\"", "assert shape_properties([4, 6]) == \"Perimeter = 20.0 Area = 24.0\"", "assert shape_properties([3, 4, 5]) == \"Scalene Triangle: Perimeter = 12.0 Area = 6.0\"", "assert shape_properties([7, 7, 7]) == \"Equilateral Triangle: Perimeter = 21.0 Area = 21.2\"", "assert shape_properties([5, 5, 8]) == \"Isosceles Triangle: Perimeter = 18.0 Area = 12.0\"", "assert shape_properties([1, 2, 3]) == \"Invalid triangle dimensions\"", "assert shape_properties([10]) == \"Perimeter = 40.0 Area = 100.0\"", "assert shape_properties([8, 15]) == \"Perimeter = 46.0 Area = 120.0\"", "assert shape_properties([6, 6, 10]) == \"Isosceles Triangle: Perimeter = 22.0 Area = 16.2\"", "assert shape_properties([12, 5, 13]) == \"Scalene Triangle: Perimeter = 30.0 Area = 30.0\""], "function": "shape_properties", "signature": "def shape_properties(dimensions):", "score": 0.9, "domain": "generic"} {"id": "00b0f4890660eaaf71bd2b4a8b065afc", "problem": "You are given a list of integers representing daily temperature readings for a month. Your task is to implement a function `threshold_weekdays` that applies a \"temperature thresholding\" operation on this data. The function should consider only weekdays (Monday to Friday) and ignore weekends (Saturday and Sunday). For weekdays, if the temperature is below the given threshold, replace it with `None`; otherwise, keep the original temperature. For weekends, the temperatures should remain unchanged.\n\n**Input:**\n- A list of integers `temps` (1 ≤ len(temps) ≤ 31), where each integer represents the temperature for a day.\n- An integer `threshold` (0 ≤ threshold ≤ 100).\n\n**Output:**\n- A list of integers or `None` values, where each element corresponds to the thresholded temperature for the respective day.\n\n**Sample Input:**\n```python\ntemps = [22, 18, 25, 30, 19, 21, 23, 24, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48]\nthreshold = 25\n```\n\n**Sample Output:**\n```python\n[None, None, 25, 30, None, 21, 23, None, 26, 27, 28, 29, 30, 31, 32, None, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48]\n```", "reference": "def threshold_weekdays(temps, threshold):\n \"\"\"\n Applies a temperature thresholding operation on the given list of temperatures,\n considering only weekdays and ignoring weekends.\n\n Parameters:\n temps (list of int): List of daily temperature readings.\n threshold (int): The temperature threshold.\n\n Returns:\n list of int or None: List of thresholded temperatures.\n \"\"\"\n thresholded_temps = []\n for index, temp in enumerate(temps):\n day_of_week = index % 7\n if 0 <= day_of_week <= 4:\n thresholded_temps.append(None if temp < threshold else temp)\n else:\n thresholded_temps.append(temp)\n return thresholded_temps", "tests": ["assert threshold_weekdays([30, 25, 27, 28, 29, 30, 31], 26) == [30, None, 27, 28, 29, 30, 31]", "assert threshold_weekdays([20, 21, 22, 23, 24, 25, 26], 22) == [None, None, 22, 23, 24, 25, 26]", "assert threshold_weekdays([15, 16, 17, 18, 19, 20, 21], 20) == [None, None, None, None, None, 20, 21]", "assert threshold_weekdays([10, 11, 12, 13, 14, 15, 16], 10) == [10, 11, 12, 13, 14, 15, 16]", "assert threshold_weekdays([5, 6, 7, 8, 9, 10, 11], 6) == [None, 6, 7, 8, 9, 10, 11]", "assert threshold_weekdays([25, 25, 25, 25, 25, 25, 25], 25) == [25, 25, 25, 25, 25, 25, 25]", "assert threshold_weekdays([30, 30, 30, 30, 30, 30, 30], 29) == [30, 30, 30, 30, 30, 30, 30]", "assert threshold_weekdays([1, 2, 3, 4, 5, 6, 7], 8) == [1, 2, 3, 4, 5, 6, 7]", "assert threshold_weekdays([0, 0, 0, 0, 0, 0, 0], 1) == [None, None, None, None, None, 0, 0]", "assert threshold_weekdays([], 10) == []"], "function": "threshold_weekdays", "signature": "def threshold_weekdays(temps, threshold):", "score": 0.9, "domain": "generic"} {"id": "e6cc00d387d708217da48625925ffad4", "problem": "You are given a string `s` consisting of characters '(', ')', '{', '}', '[' and ']'. Your task is to determine if the string of parentheses is balanced. A string is considered balanced if every opening parenthesis has a corresponding closing parenthesis in the correct order. For example, the string \"()\" is balanced, while the string \"([)]\" is not.\n\n**Input:**\n- A single string `s` (1 ≤ |s| ≤ 10^4) containing only the characters '(', ')', '{', '}', '[' and ']'.\n\n**Output:**\n- Return `True` if the string is balanced, otherwise return `False`.\n\n**Sample Input 1:**\n```\n()[]{}\n```\n**Sample Output 1:**\n```\nTrue\n```\n\n**Sample Input 2:**\n```\n([)]\n```\n**Sample Output 2:**\n```\nFalse\n```", "reference": "def balanced_parentheses(s: str) -> bool:\n \"\"\"\n Determines if a string of parentheses is balanced.\n \n :param s: A string containing only the characters '(', ')', '{', '}', '[' and ']'.\n :return: True if the string is balanced, otherwise False.\n \"\"\"\n matching_parentheses = {'(': ')', '{': '}', '[': ']'}\n stack = []\n \n for char in s:\n if char in matching_parentheses:\n stack.append(char)\n else:\n if not stack or matching_parentheses[stack.pop()] != char:\n return False\n \n return not stack", "tests": ["assert balanced_parentheses(\"()\") == True", "assert balanced_parentheses(\"()[]{}\") == True", "assert balanced_parentheses(\"(]\") == False", "assert balanced_parentheses(\"([)]\") == False", "assert balanced_parentheses(\"{[]}\") == True", "assert balanced_parentheses(\"\") == True", "assert balanced_parentheses(\"((((()))))\") == True", "assert balanced_parentheses(\"((((())))\") == False", "assert balanced_parentheses(\"({[()]})\") == True", "assert balanced_parentheses(\"({[([)])})\") == False"], "function": "balanced_parentheses", "signature": "def balanced_parentheses(s: str) -> bool:", "score": 1.0, "domain": "generic"} {"id": "29afe7759eb53228089d105c5442a66f", "problem": "You are given a list of integers and a target integer. Your task is to implement a function that performs a linear search to find the target integer in the list. The function should return the index of the target integer if it exists in the list, otherwise, it should return -1.\n\n**Input:**\n- The first argument to the function is a list of integers `numbers`.\n- The second argument is an integer `target`.\n\n**Output:**\n- Return an integer representing the index of the target integer in the list if found, otherwise return -1.\n\n**Sample Input:**\n- `numbers = [4, 2, 7, 1, 3]`\n- `target = 7`\n\n**Sample Output:**\n- `2`\n\n**Sample Input:**\n- `numbers = [4, 2, 7, 1, 3]`\n- `target = 5`\n\n**Sample Output:**\n- `-1`", "reference": "def linear_search(numbers, target):\n \"\"\"\n Perform a linear search on a list of numbers to find the target value.\n \n :param numbers: List of integers to search through\n :param target: Integer to search for in the list\n :return: Index of the target if found in the list, otherwise -1\n \"\"\"\n for index, number in enumerate(numbers):\n if number == target:\n return index\n return -1", "tests": ["assert linear_search([1, 2, 3, 4, 5], 3) == 2", "assert linear_search([10, 20, 30, 40, 50], 20) == 1", "assert linear_search([5, 4, 3, 2, 1], 1) == 4", "assert linear_search([1, 1, 1, 1, 1], 1) == 0", "assert linear_search([], 1) == -1", "assert linear_search([1, 2, 3, 4, 5], 6) == -1", "assert linear_search([-1, -2, -3, -4, -5], -3) == 2", "assert linear_search([0, 0, 0, 0, 0], 0) == 0", "assert linear_search([100, 200, 300, 400, 500], 500) == 4", "assert linear_search([1, 3, 5, 7, 9], 2) == -1"], "function": "linear_search", "signature": "def linear_search(numbers, target):", "score": 1.0, "domain": "generic"} {"id": "ca5dd7adbf6b28979b8c3bc0cf708445", "problem": "You are given a list of dictionaries, each representing sales data for a product. Each dictionary contains the keys `product_name`, `quantity_sold`, and `unit_price`. Your task is to write a function `generate_report` that calculates the total revenue for each product and returns a dictionary with product names as keys and their total revenues as values. If the input list is empty, return an empty dictionary.\n\n**Input:**\n- A list of dictionaries, where each dictionary has the following keys:\n - `product_name`: A string representing the name of the product.\n - `quantity_sold`: An integer representing the quantity of the product sold.\n - `unit_price`: A float representing the unit price of the product.\n\n**Output:**\n- A dictionary with product names as keys and their total revenues as values.\n\n**Sample Input:**\n```python\n[\n {'product_name': 'Product A', 'quantity_sold': 10, 'unit_price': 20},\n {'product_name': 'Product B', 'quantity_sold': 5, 'unit_price': 30},\n {'product_name': 'Product A', 'quantity_sold': 15, 'unit_price': 20}\n]\n```\n\n**Sample Output:**\n```python\n{'Product A': 500, 'Product B': 150}\n```", "reference": "def generate_report(sales_data):\n \"\"\"\n Generates a summary report of total revenue for each product from sales data.\n\n Parameters:\n sales_data (list of dict): A list of dictionaries, each containing 'product_name', 'quantity_sold', and 'unit_price'.\n\n Returns:\n dict: A dictionary with product names as keys and their total revenues as values.\n \"\"\"\n report = {}\n for entry in sales_data:\n product_name = entry['product_name']\n quantity_sold = entry['quantity_sold']\n unit_price = entry['unit_price']\n total_revenue = quantity_sold * unit_price\n\n if product_name in report:\n report[product_name] += total_revenue\n else:\n report[product_name] = total_revenue\n\n return report", "tests": ["assert generate_report([{'product_name': 'Product A', 'quantity_sold': 10, 'unit_price': 20}]) == {'Product A': 200}", "assert generate_report([{'product_name': 'Product B', 'quantity_sold': 5, 'unit_price': 30}, {'product_name': 'Product B', 'quantity_sold': 5, 'unit_price': 30}]) == {'Product B': 300}", "assert generate_report([{'product_name': 'Product A', 'quantity_sold': 10, 'unit_price': 20}, {'product_name': 'Product B', 'quantity_sold': 5, 'unit_price': 30}]) == {'Product A': 200, 'Product B': 150}", "assert generate_report([]) == {}", "assert generate_report([{'product_name': 'Product C', 'quantity_sold': 0, 'unit_price': 100}]) == {'Product C': 0}", "assert generate_report([{'product_name': 'Product D', 'quantity_sold': 10, 'unit_price': 0}]) == {'Product D': 0}", "assert generate_report([{'product_name': 'Product E', 'quantity_sold': 10, 'unit_price': 20}, {'product_name': 'Product F', 'quantity_sold': 5, 'unit_price': 30}, {'product_name': 'Product E', 'quantity_sold': 15, 'unit_price': 20}, {'product_name': 'Product F', 'quantity_sold': 5, 'unit_price': 30}]) == {'Product E': 500, 'Product F': 300}", "assert generate_report([{'product_name': 'Product G', 'quantity_sold': 1, 'unit_price': 1}, {'product_name': 'Product H', 'quantity_sold': 2, 'unit_price': 2}, {'product_name': 'Product I', 'quantity_sold': 3, 'unit_price': 3}]) == {'Product G': 1, 'Product H': 4, 'Product I': 9}", "assert generate_report([{'product_name': 'Product J', 'quantity_sold': 10, 'unit_price': 20}, {'product_name': 'Product K', 'quantity_sold': 5, 'unit_price': 30}, {'product_name': 'Product J', 'quantity_sold': 15, 'unit_price': 20}, {'product_name': 'Product L', 'quantity_sold': 5, 'unit_price': 30}]) == {'Product J': 500, 'Product K': 150, 'Product L': 150}", "assert generate_report([{'product_name': 'Product M', 'quantity_sold': 10, 'unit_price': 20}, {'product_name': 'Product N', 'quantity_sold': 5, 'unit_price': 30}, {'product_name': 'Product M', 'quantity_sold': 15, 'unit_price': 20}, {'product_name': 'Product N', 'quantity_sold': 5, 'unit_price': 30}, {'product_name': 'Product O', 'quantity_sold': 1, 'unit_price': 100}]) == {'Product M': 500, 'Product N': 300, 'Product O': 100}"], "function": "generate_report", "signature": "def generate_report(sales_data):", "score": 1.0, "domain": "generic"} {"id": "01d15c44b73f8add867548f08b5e6303", "problem": "You are given two strings, `string` and `substring`. Your task is to implement a function `count_substring_occurrences(string, substring)` that returns the number of times `substring` appears in `string`, including overlapping occurrences. The comparison is case-sensitive and the strings may contain special characters.\n\n**Input:**\n- The function takes two parameters:\n - `string` (1 ≤ |string| ≤ 10^5): The main string in which to search for the substring.\n - `substring` (1 ≤ |substring| ≤ 10^5): The substring to search for in the main string.\n\n**Output:**\n- Return an integer representing the number of times `substring` appears in `string`, including overlapping occurrences.\n\n**Sample Input:**\n- `string = \"hellohello\"`\n- `substring = \"hello\"`\n\n**Sample Output:**\n- `2`\n\n**Sample Input:**\n- `string = \"ababab\"`\n- `substring = \"aba\"`\n\n**Sample Output:**\n- `2`\n\n**Sample Input:**\n- `string = \"aaaa\"`\n- `substring = \"aa\"`\n\n**Sample Output:**\n- `3`", "reference": "def count_substring_occurrences(string, substring):\n \"\"\"\n Counts the number of times a substring appears in a string, including overlapping occurrences.\n \n Parameters:\n string (str): The main string in which to search for the substring.\n substring (str): The substring to search for in the main string.\n \n Returns:\n int: The number of times the substring appears in the string, including overlapping occurrences.\n \"\"\"\n count = start = 0\n while True:\n start = string.find(substring, start) + 1\n if start > 0:\n count += 1\n else:\n break\n return count\n\n# Example usage:\n# print(count_substring_occurrences(\"hellohello\", \"hello\")) # Output: 2\n# print(count_substring_occurrences(\"ababab\", \"aba\"))\t\t# Output: 2\n# print(count_substring_occurrences(\"aaaa\", \"aa\"))\t\t # Output: 3", "tests": ["assert count_substring_occurrences(\"hellohello\", \"hello\") == 2", "assert count_substring_occurrences(\"ababab\", \"aba\") == 2", "assert count_substring_occurrences(\"aaaa\", \"aa\") == 3", "assert count_substring_occurrences(\"abcabcabc\", \"abc\") == 3", "assert count_substring_occurrences(\"mississippi\", \"issi\") == 1", "assert count_substring_occurrences(\"aaaaa\", \"a\") == 5", "assert count_substring_occurrences(\"abc\", \"d\") == 0", "assert count_substring_occurrences(\"\", \"a\") == 0", "assert count_substring_occurrences(\"abc\", \"\") == 0", "assert count_substring_occurrences(\"abcabcabc\", \"abcd\") == 0"], "function": "count_substring_occurrences", "signature": "def count_substring_occurrences(string, substring):", "score": 0.8, "domain": "generic"} {"id": "357d694b2710d5637b7c79cd699429a8", "problem": "You are given a list of distinct items. Your task is to write a Python function named `generate_permutations` that generates all possible permutations of the given list. The function should return a list of tuples, where each tuple represents a unique permutation of the items. Use the `itertools` module to accomplish this.\n\n**Input:**\n- A list of distinct items, `items`, where `1 <= len(items) <= 8`.\n\n**Output:**\n- A list of tuples, where each tuple is a permutation of the input list.\n\n**Sample Input:**\n```python\n[\"a\", \"b\", \"c\"]\n```\n\n**Sample Output:**\n```python\n[('a', 'b', 'c'), ('a', 'c', 'b'), ('b', 'a', 'c'), ('b', 'c', 'a'), ('c', 'a', 'b'), ('c', 'b', 'a')]\n```", "reference": "import itertools\n\ndef generate_permutations(items):\n \"\"\"\n Generate all possible permutations of the given list of items.\n\n Parameters:\n items (list): A list of distinct items.\n\n Returns:\n list: A list of tuples, where each tuple is a permutation of the input list.\n \"\"\"\n return list(itertools.permutations(items))", "tests": ["assert generate_permutations([1, 2, 3]) == [(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]", "assert generate_permutations(['a', 'b']) == [('a', 'b'), ('b', 'a')]", "assert generate_permutations([]) == []", "assert generate_permutations([1]) == [(1,)]", "assert generate_permutations(['x', 'y', 'z']) == [('x', 'y', 'z'), ('x', 'z', 'y'), ('y', 'x', 'z'), ('y', 'z', 'x'), ('z', 'x', 'y'), ('z', 'y', 'x')]", "assert generate_permutations([True, False]) == [(True, False), (False, True)]", "assert generate_permutations(['a']) == [('a',)]", "assert generate_permutations([None, 1, 'a']) == [(None, 1, 'a'), (None, 'a', 1), (1, None, 'a'), (1, 'a', None), ('a', None, 1), ('a', 1, None)]", "assert generate_permutations([1, 1, 2]) == [(1, 1, 2), (1, 2, 1), (1, 1, 2), (1, 2, 1), (2, 1, 1), (2, 1, 1)]", "assert generate_permutations(['a', 'b', 'c', 'd']) == [('a', 'b', 'c', 'd'), ('a', 'b', 'd', 'c'), ('a', 'c', 'b', 'd'), ('a', 'c', 'd', 'b'), ('a', 'd', 'b', 'c'), ('a', 'd', 'c', 'b'), ('b', 'a', 'c', 'd'), ('b', 'a', 'd', 'c'), ('b', 'c', 'a', 'd'), ('b', 'c', 'd', 'a'), ('b', 'd', 'a', 'c'), ('b', 'd', 'c', 'a'), ('c', 'a', 'b', 'd'), ('c', 'a', 'd', 'b'), ('c', 'b', 'a', 'd'), ('c', 'b', 'd', 'a'), ('c', 'd', 'a', 'b'), ('c', 'd', 'b', 'a'), ('d', 'a', 'b', 'c'), ('d', 'a', 'c', 'b'), ('d', 'b', 'a', 'c'), ('d', 'b', 'c', 'a'), ('d', 'c', 'a', 'b'), ('d', 'c', 'b', 'a')]"], "function": "generate_permutations", "signature": "def generate_permutations(items):", "score": 0.9, "domain": "generic"} {"id": "9246d9032e11c76b4a1ee6aa057378a0", "problem": "You are given a list of integers. Your task is to implement a function that sorts this list in ascending order using the bubble sort algorithm. The function should return the sorted list. \n\n**Input:**\n- A list of integers `arr` (1 ≤ len(arr) ≤ 1000), where each integer is in the range -1000 ≤ arr[i] ≤ 1000.\n\n**Output:**\n- A list of integers sorted in ascending order.\n\n**Sample Input:**\n```\n[64, 34, 25, 12, 22, 11, 90]\n```\n\n**Sample Output:**\n```\n[11, 12, 22, 25, 34, 64, 90]\n```", "reference": "def bubble_sort(arr):\n \"\"\"\n Sorts a list of integers in ascending order using the bubble sort algorithm.\n\n :param arr: List of integers to be sorted.\n :return: The same list sorted in ascending order.\n \"\"\"\n n = len(arr)\n for i in range(n):\n for j in range(0, n-i-1):\n if arr[j] > arr[j+1]:\n arr[j], arr[j+1] = arr[j+1], arr[j]\n return arr\n\n# Example usage:\ninput_list = [64, 34, 25, 12, 22, 11, 90]\nsorted_list = bubble_sort(input_list)\nprint(\"Sorted array is:\", sorted_list)", "tests": ["assert bubble_sort([64, 34, 25, 12, 22, 11, 90]) == [11, 12, 22, 25, 34, 64, 90]", "assert bubble_sort([5, 1, 4, 2, 8]) == [1, 2, 4, 5, 8]", "assert bubble_sort([10, 9, 8, 7, 6, 5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]", "assert bubble_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]", "assert bubble_sort([]) == []", "assert bubble_sort([1]) == [1]", "assert bubble_sort([3, 3, 3, 3, 3]) == [3, 3, 3, 3, 3]", "assert bubble_sort([-1, -2, -3, -4, -5]) == [-5, -4, -3, -2, -1]", "assert bubble_sort([0, -1, 1, -2, 2]) == [-2, -1, 0, 1, 2]", "assert bubble_sort([100, 0, 50, 25, 75]) == [0, 25, 50, 75, 100]"], "function": "bubble_sort", "signature": "def bubble_sort(arr):", "score": 1.0, "domain": "generic"} {"id": "7bf4797c94283cf7bc21b721c29a7903", "problem": "You are given a string `s` and a dictionary `d`. The dictionary `d` contains key-value pairs where the keys are strings and the values are also strings. Your task is to write a function `replace_keys` that replaces all occurrences of the keys in the string `s` with their corresponding values from the dictionary `d`. The keys in the dictionary are represented in a special format: `{key}`. The function should handle cases where the dictionary is empty, in which case it should return the original string `s`. It should also handle cases where a key from the dictionary does not appear in the string `s`.\n\nAdditionally, the replacement process should maintain the case of the original key if it is mixed-case, and the corresponding value in the dictionary should be adapted to match the case of the key. If there are multiple occurrences of the same key with different cases, all occurrences should be replaced with the corresponding value adjusted to match their respective cases.\n\n**Input:**\n- A string `s` (1 ≤ |s| ≤ 10^3)\n- A dictionary `d` where each key is a string (1 ≤ |key| ≤ 10) and each value is a string (1 ≤ |value| ≤ 10)\n\n**Output:**\n- A string with all occurrences of `{key}` replaced by the corresponding value from `d`, adjusted for case.\n\n**Sample Input:**\n```\ns = \"The {animal} jumped over the {Object}.\"\nd = {\"animal\": \"dog\", \"object\": \"fence\"}\n```\n\n**Sample Output:**\n```\n\"The dog jumped over the Fence.\"\n```", "reference": "import re\n\ndef adjust_case(key, value):\n \"\"\"\n Adjusts the case of the value to match the case of the key.\n \n :param key: The original key with its case.\n :param value: The value to be adjusted.\n :return: The value adjusted to match the case of the key.\n \"\"\"\n if key.islower():\n return value.lower()\n elif key.isupper():\n return value.upper()\n elif key.istitle():\n return value.capitalize()\n else:\n # Mixed case handling\n lower_case = next((i for i, c in enumerate(key) if c.islower()), -1)\n upper_case = next((i for i, c in enumerate(key) if c.isupper()), -1)\n if lower_case == -1:\n return value.upper()\n elif upper_case == -1:\n return value.lower()\n elif lower_case < upper_case:\n return value.capitalize()\n else:\n return ''.join(c.upper() if main_c.isupper() else c.lower() for c, main_c in zip(value, key))\n\ndef replace_keys(s, d):\n \"\"\"\n Replaces all occurrences of keys in the string s with their corresponding values from the dictionary d,\n adjusting the case of the values to match the case of the keys.\n \n :param s: The input string containing keys in the format {key}.\n :param d: A dictionary with keys and their corresponding values.\n :return: The modified string with keys replaced by their corresponding values.\n \"\"\"\n pattern = re.compile(r'\\{([a-zA-Z_][a-zA-Z0-9_]*)\\}')\n \n def replacer(match):\n key = match.group(1)\n if key in d:\n return adjust_case(key, d[key])\n return match.group(0) # Return the original if the key is not found\n \n return pattern.sub(replacer, s)", "tests": ["assert replace_keys(\"The {animal} jumped over the {object}.\", {\"animal\": \"dog\", \"object\": \"fence\"}) == \"The dog jumped over the fence.\"", "assert replace_keys(\"The {Animal} jumped over the {Object}.\", {\"animal\": \"dog\", \"object\": \"fence\"}) == \"The Dog jumped over the Fence.\"", "assert replace_keys(\"The {ANIMAL} jumped over the {OBJECT}.\", {\"animal\": \"dog\", \"object\": \"fence\"}) == \"The DOG jumped over the FENCE.\"", "assert replace_keys(\"The {aNiMaL} jumped over the {ObJeCt}.\", {\"animal\": \"dog\", \"object\": \"fence\"}) == \"The dOg jumped over the FeNcE.\"", "assert replace_keys(\"The {animal} jumped over the {object}.\", {}) == \"The {animal} jumped over the {object}.\"", "assert replace_keys(\"No keys here.\", {\"animal\": \"dog\", \"object\": \"fence\"}) == \"No keys here.\"", "assert replace_keys(\"{key1} and {key2} and {key1}.\", {\"key1\": \"value1\", \"key2\": \"value2\"}) == \"value1 and value2 and value1.\"", "assert replace_keys(\"{Key1} and {key2} and {KEY1}.\", {\"key1\": \"value1\", \"key2\": \"value2\"}) == \"Value1 and value2 and VALUE1.\"", "assert replace_keys(\"{key1} and {key2} and {key1}.\", {\"key1\": \"value1\", \"key2\": \"value2\", \"key3\": \"value3\"}) == \"value1 and value2 and value1.\"", "assert replace_keys(\"\", {\"animal\": \"dog\", \"object\": \"fence\"}) == \"\""], "function": "replace_keys", "signature": "def replace_keys(s, d):", "score": 0.6, "domain": "generic"} {"id": "b32c4bb2d5ccee1860344818e2a1d9f3", "problem": "You are tasked with implementing a text classification system. Given a dictionary where each key represents a category and the corresponding value is a list of keywords associated with that category, and a list of documents, your goal is to classify each document into one or more categories based on the presence of keywords. Each document should be mapped to a list of categories it belongs to. If no keywords from any category are found in a document, it should be mapped to an empty list.\n\n**Input:**\n- A dictionary `categories_keywords` where keys are category names (strings) and values are lists of keywords (strings).\n- A list of documents `documents` where each document is a string.\n\n**Output:**\n- A dictionary where each key is a document from the input list and the value is a list of categories (strings) that the document belongs to.\n\n**Sample Input:**\n```python\ncategories_keywords = {\n 'Technology': ['laptop', 'smartphone', 'software'],\n 'Health': ['vitamin', 'medication', 'exercise'],\n 'Finance': ['investment', 'market', 'profit']\n}\n\ndocuments = [\n \"I recently bought a new laptop and it's amazing.\",\n \"Taking vitamin C every day is important for your health.\",\n \"The stock market is showing signs of recovery.\"\n]\n```\n\n**Sample Output:**\n```python\n{\n \"I recently bought a new laptop and it's amazing.\": ['Technology'],\n \"Taking vitamin C every day is important for your health.\": ['Health'],\n \"The stock market is showing signs of recovery.\": ['Finance']\n}\n```", "reference": "def classify_documents(categories_keywords, documents):\n \"\"\"\n Classify documents into categories based on keyword presence.\n\n :param categories_keywords: A dictionary with categories as keys and lists of keywords as values.\n :param documents: A list of documents to be classified.\n :return: A dictionary mapping each document to a list of categories it belongs to.\n \"\"\"\n classified_documents = {}\n \n for doc in documents:\n matching_categories = [\n category for category, keywords in categories_keywords.items()\n if any(keyword in doc.lower() for keyword in keywords)\n ]\n classified_documents[doc] = matching_categories\n \n return classified_documents", "tests": ["assert classify_documents({'Tech': ['code', 'algorithm']}, ['Learning new code is fun.']) == {'Learning new code is fun.': ['Tech']}", "assert classify_documents({'Sports': ['football', 'basketball']}, ['I love playing basketball.']) == {'I love playing basketball.': ['Sports']}", "assert classify_documents({'Music': ['song', 'melody']}, ['This song is beautiful.']) == {'This song is beautiful.': ['Music']}", "assert classify_documents({'Food': ['apple', 'banana']}, ['I ate an apple today.']) == {'I ate an apple today.': ['Food']}", "assert classify_documents({'Travel': ['vacation', 'trip']}, ['Planning a trip to Europe.']) == {'Planning a trip to Europe.': ['Travel']}", "assert classify_documents({'Tech': ['code', 'algorithm']}, ['No keywords here.']) == {'No keywords here.': []}", "assert classify_documents({'Tech': ['code'], 'Health': ['health']}, ['code and health are important.']) == {'code and health are important.': ['Tech', 'Health']}", "assert classify_documents({'Tech': ['code'], 'Health': ['health']}, ['']) == {'': []}", "assert classify_documents({'Tech': ['code'], 'Health': ['health']}, ['Code is fun. Health is wealth.']) == {'Code is fun. Health is wealth.': ['Tech', 'Health']}", "assert classify_documents({'Tech': ['code'], 'Health': ['health']}, ['code']) == {'code': ['Tech']}"], "function": "classify_documents", "signature": "def classify_documents(categories_keywords, documents):", "score": 1.0, "domain": "generic"} {"id": "e7dcec53a4b2b1b72e908fe4c81c897a", "problem": "You are given a large text file where each line contains a single sentence. Your task is to implement a function that identifies lines containing a specific target pattern as a contiguous substring. The function should only include lines that do not contain any digits or numbers. The pattern matching is case-sensitive and punctuation must be considered.\n\n**Input:**\n- A string `file_path` representing the path to the text file.\n- A string `target_pattern` representing the pattern to search for.\n\n**Output:**\n- A list of tuples, where each tuple contains a single string representing a line from the file that matches the criteria.\n\n**Sample Input:**\n- File content:\n ```\n This is a test sentence.\n Another line without numbers.\n Line with 123 numbers.\n Exact match here!\n ```\n- `target_pattern = \"test\"`\n\n**Sample Output:**\n- `[('Another line without numbers.',)]`", "reference": "def find_pattern_in_file(file_path, target_pattern):\n \"\"\"\n Identifies lines in a file containing a specific target pattern as a contiguous substring,\n excluding lines with any digits or numbers.\n\n :param file_path: Path to the text file.\n :param target_pattern: The pattern to search for in the file.\n :return: A list of tuples, each containing a line that matches the criteria.\n \"\"\"\n result = []\n with open(file_path, 'r') as file:\n for line in file:\n line = line.rstrip('\\n')\n if target_pattern in line and not any(char.isdigit() for char in line):\n result.append((line,))\n return result", "tests": ["assert find_pattern_in_file(\"test.txt\", \"hello\") == [(\"hello world\",)]", "assert find_pattern_in_file(\"test.txt\", \"world\") == [(\"hello world\",)]", "assert find_pattern_in_file(\"test.txt\", \"test\") == [(\"this is a test\",)]", "assert find_pattern_in_file(\"test.txt\", \"123\") == []", "assert find_pattern_in_file(\"test.txt\", \"no digits here\") == [(\"no digits here\",)]", "assert find_pattern_in_file(\"test.txt\", \"exact match\") == [(\"exact match\",)]", "assert find_pattern_in_file(\"test.txt\", \"Pattern\") == []", "assert find_pattern_in_file(\"test.txt\", \"punctuation!\") == [(\"punctuation!\",)]", "assert find_pattern_in_file(\"test.txt\", \"another line\") == [(\"another line\",)]", "assert find_pattern_in_file(\"test.txt\", \"missing\") == []"], "function": "find_pattern_in_file", "signature": "def find_pattern_in_file(file_path, target_pattern):", "score": 0.3, "domain": "generic"} {"id": "5a6be4e9be5d105757a0ac84793995eb", "problem": "You are given a string `s`. Your task is to implement a function that removes all duplicate adjacent characters from the string. The function should return the modified string.\n\n**Input:**\n- A single string `s` (1 ≤ |s| ≤ 10^5), consisting of lowercase English letters.\n\n**Output:**\n- A string with all duplicate adjacent characters removed.\n\n**Sample Input:**\n```\naabbcc\n```\n\n**Sample Output:**\n```\nabc\n```\n\n**Sample Input:**\n```\nabacadae\n```\n\n**Sample Output:**\n```\nabacadae\n```", "reference": "def remove_adjacent_duplicates(s: str) -> str:\n \"\"\"\n Removes all duplicate adjacent characters from the input string.\n\n :param s: A string consisting of lowercase English letters.\n :return: A string with all duplicate adjacent characters removed.\n \"\"\"\n if not s:\n return s\n \n result = [s[0]]\n \n for i in range(1, len(s)):\n if s[i] != result[-1]:\n result.append(s[i])\n \n return ''.join(result)\n\n# Example usage:\nprint(remove_adjacent_duplicates(\"aabbcc\")) # Output: \"abc\"\nprint(remove_adjacent_duplicates(\"abacadae\")) # Output: \"abacadae\"", "tests": ["assert remove_adjacent_duplicates(\"aabbcc\") == \"abc\"", "assert remove_adjacent_duplicates(\"abacadae\") == \"abacadae\"", "assert remove_adjacent_duplicates(\"zzzzz\") == \"z\"", "assert remove_adjacent_duplicates(\"abcde\") == \"abcde\"", "assert remove_adjacent_duplicates(\"a\") == \"a\"", "assert remove_adjacent_duplicates(\"\") == \"\"", "assert remove_adjacent_duplicates(\"aabbaa\") == \"aba\"", "assert remove_adjacent_duplicates(\"aaabbbccc\") == \"abc\"", "assert remove_adjacent_duplicates(\"aabccbaa\") == \"abcb\"", "assert remove_adjacent_duplicates(\"aabbccddeeff\") == \"abcdef\""], "function": "remove_adjacent_duplicates", "signature": "def remove_adjacent_duplicates(s: str) -> str:", "score": 0.9, "domain": "generic"} {"id": "12217f71d484fa10fb3900a8546547ac", "problem": "You are given a list of integers. Your task is to write a function `sort_and_deduplicate` that processes this list by first removing any duplicate values and then sorting the remaining integers in ascending order. The function should return the processed list.\n\n**Input:**\n- A list of integers `input_list` (1 ≤ len(input_list) ≤ 10^5), where each integer is in the range [-10^9, 10^9].\n\n**Output:**\n- A list of integers representing the sorted and deduplicated list.\n\n**Sample Input:**\n```python\n[4, 5, 6, 3, 2, 5, 4, 1]\n```\n\n**Sample Output:**\n```python\n[1, 2, 3, 4, 5, 6]\n```", "reference": "def sort_and_deduplicate(input_list):\n \"\"\"\n Removes duplicates from the input list and returns a sorted list of unique integers.\n\n :param input_list: List of integers\n :return: Sorted list of unique integers\n \"\"\"\n unique_elements = set(input_list)\n sorted_list = sorted(unique_elements)\n return sorted_list", "tests": ["assert sort_and_deduplicate([4, 2, 5, 2, 3, 1]) == [1, 2, 3, 4, 5]", "assert sort_and_deduplicate([10, 9, 8, 7, 6, 5]) == [5, 6, 7, 8, 9, 10]", "assert sort_and_deduplicate([1, 1, 1, 1, 1]) == [1]", "assert sort_and_deduplicate([]) == []", "assert sort_and_deduplicate([5]) == [5]", "assert sort_and_deduplicate([3, 3, 2, 1, 2, 1]) == [1, 2, 3]", "assert sort_and_deduplicate([-1, -2, -3, -1, -2]) == [-3, -2, -1]", "assert sort_and_deduplicate([0, 0, 0, 0, 0]) == [0]", "assert sort_and_deduplicate([100, 50, 25, 12.5, 6.25, 3.125]) == [3.125, 6.25, 12.5, 25, 50, 100]", "assert sort_and_deduplicate([7, 8, 9, 7, 8, 9, 10]) == [7, 8, 9, 10]"], "function": "sort_and_deduplicate", "signature": "def sort_and_deduplicate(input_list):", "score": 1.0, "domain": "generic"} {"id": "6bca4fa9402dc804139de38978757796", "problem": "You are given a list of `N` well-formed URLs without query parameters or fragments. Your task is to write a function that parses each URL and returns a list of dictionaries. Each dictionary should contain the keys `protocol`, `domain`, and `path`, corresponding to the respective components of the URL. Use regular expressions for parsing. Assume all URLs are correctly formatted.\n\n**Input:**\n- An integer `N` representing the number of URLs.\n- A list of `N` strings, each representing a URL.\n\n**Output:**\n- A list of `N` dictionaries, each containing the keys `protocol`, `domain`, and `path`.\n\n**Sample Input:**\n```\n2\nhttps://www.example.com/path/to/resource\nhttp://example.org/another/path\n```\n\n**Sample Output:**\n```\n[{'protocol': 'https', 'domain': 'www.example.com', 'path': '/path/to/resource'}, {'protocol': 'http', 'domain': 'example.org', 'path': '/another/path'}]\n```", "reference": "import re\n\ndef parse_urls(urls):\n \"\"\"\n Parse a list of URLs using regular expressions and extract the protocol, domain, and path.\n \n Parameters:\n urls (list): A list of well-formed URL strings without query parameters or fragments.\n \n Returns:\n list: A list of dictionaries containing the protocol, domain, and path for each URL.\n \"\"\"\n url_pattern = re.compile(r'^(?Phttps?):\\/\\/(?P[^\\/]+)(?P[^#?]*)(?:#|\\?)?')\n return [url_pattern.match(url).groupdict() for url in urls]\n\n# Example usage\nurls = [\n \"https://www.example.com/path/to/resource\",\n \"http://example.org/another/path\"\n]\n\nprint(parse_urls(urls))", "tests": ["assert parse_urls([\"https://www.example.com/path/to/resource\"]) == [{'protocol': 'https', 'domain': 'www.example.com', 'path': '/path/to/resource'}]", "assert parse_urls([\"http://example.org/another/path\"]) == [{'protocol': 'http', 'domain': 'example.org', 'path': '/another/path'}]", "assert parse_urls([\"https://example.net/\"]) == [{'protocol': 'https', 'domain': 'example.net', 'path': '/'}]", "assert parse_urls([\"http://localhost:8080/test\"]) == [{'protocol': 'http', 'domain': 'localhost:8080', 'path': '/test'}]", "assert parse_urls([\"https://sub.domain.co.uk/deep/path\"]) == [{'protocol': 'https', 'domain': 'sub.domain.co.uk', 'path': '/deep/path'}]", "assert parse_urls([\"http://192.168.1.1/\"]) == [{'protocol': 'http', 'domain': '192.168.1.1', 'path': '/'}]", "assert parse_urls([\"https://example.com\"]) == [{'protocol': 'https', 'domain': 'example.com', 'path': ''}]", "assert parse_urls([\"http://example.com/\"]) == [{'protocol': 'http', 'domain': 'example.com', 'path': '/'}]", "assert parse_urls([\"https://example.com/path?query=param\"]) == [{'protocol': 'https', 'domain': 'example.com', 'path': '/path'}]", "assert parse_urls([\"http://example.com/path#fragment\"]) == [{'protocol': 'http', 'domain': 'example.com', 'path': '/path'}]"], "function": "parse_urls", "signature": "def parse_urls(urls):", "score": 1.0, "domain": "generic"} {"id": "ce5cb74be808184ac4a32972695cb026", "problem": "You are given a task to implement a function `calculate_discount` that computes the final price of an item after applying a discount multiple times. The function accepts three parameters: `original_price`, `discount_rate`, and `discount_count`. The `discount_rate` is a decimal representing the fraction of the price to be deducted during each discount application. The discount can be applied up to a maximum of 4 times. If `discount_count` exceeds 4, it should be capped at 4. Additionally, if the `discount_count` is odd, the final price should be rounded down to the nearest whole number.\n\n**Input:**\n- `original_price`: A float representing the initial price of the item.\n- `discount_rate`: A float representing the discount rate (0 <= discount_rate <= 1).\n- `discount_count`: An integer representing the number of times the discount can be applied.\n\n**Output:**\n- A float representing the final discounted price.\n\n**Sample Input:**\n- `original_price = 100.0`\n- `discount_rate = 0.1`\n- `discount_count = 3`\n\n**Sample Output:**\n- `72.9`", "reference": "import math\n\ndef calculate_discount(original_price, discount_rate, discount_count):\n \"\"\"\n Calculate the final discounted price of an item after applying a discount\n a specified number of times, with a maximum of 4 applications. If the number\n of discount applications is odd, round down the final price to the nearest whole number.\n\n :param original_price: float, the initial price of the item\n :param discount_rate: float, the discount rate (0 <= discount_rate <= 1)\n :param discount_count: int, the number of times the discount can be applied\n :return: float, the final discounted price\n \"\"\"\n discount_count = min(discount_count, 4)\n final_price = original_price\n for _ in range(discount_count):\n final_price -= final_price * discount_rate\n if discount_count % 2 != 0:\n final_price = math.floor(final_price)\n return final_price", "tests": ["assert calculate_discount(100, 0.1, 1) == 90", "assert calculate_discount(100, 0.1, 2) == 81", "assert calculate_discount(100, 0.1, 3) == 72", "assert calculate_discount(100, 0.1, 4) == 65.61", "assert calculate_discount(100, 0.2, 1) == 80", "assert calculate_discount(100, 0.2, 2) == 64", "assert calculate_discount(100, 0.2, 5) == 64", "assert calculate_discount(100, 0.5, 1) == 50", "assert calculate_discount(100, 0.5, 3) == 12", "assert calculate_discount(100, 0.5, 4) == 6.25"], "function": "calculate_discount", "signature": "def calculate_discount(original_price, discount_rate, discount_count):", "score": 0.9, "domain": "generic"} {"id": "3bdb3e097cf879b93cd21bb497ed4264", "problem": "You are tasked with implementing a function that finds all prime numbers less than a given integer `n`. Your solution should efficiently utilize the Sieve of Eratosthenes algorithm. \n\n**Input:**\n- An integer `n` (2 ≤ n ≤ 10^6)\n\n**Output:**\n- A list of all prime numbers less than `n`.\n\n**Sample Input:**\n```\n20\n```\n\n**Sample Output:**\n```\n[2, 3, 5, 7, 11, 13, 17, 19]\n```", "reference": "def sieve_of_eratosthenes(n):\n \"\"\"\n Generate a list of prime numbers less than a given number n using the Sieve of Eratosthenes algorithm.\n \n Parameters:\n n (int): The upper limit (exclusive) to find prime numbers.\n \n Returns:\n list: A list of prime numbers less than n.\n \"\"\"\n if n <= 2:\n return []\n\n primes = [True] * n\n primes[0] = primes[1] = False\n\n for start in range(2, int(n**0.5) + 1):\n if primes[start]:\n for multiple in range(start*start, n, start):\n primes[multiple] = False\n\n return [num for num, is_prime in enumerate(primes) if is_prime]", "tests": ["assert sieve_of_eratosthenes(10) == [2, 3, 5, 7]", "assert sieve_of_eratosthenes(20) == [2, 3, 5, 7, 11, 13, 17, 19]", "assert sieve_of_eratosthenes(2) == []", "assert sieve_of_eratosthenes(1) == []", "assert sieve_of_eratosthenes(0) == []", "assert sieve_of_eratosthenes(30) == [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]", "assert sieve_of_eratosthenes(18) == [2, 3, 5, 7, 11, 13, 17]", "assert sieve_of_eratosthenes(100) == [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]", "assert sieve_of_eratosthenes(5) == [2, 3]", "assert sieve_of_eratosthenes(15) == [2, 3, 5, 7, 11, 13]"], "function": "sieve_of_eratosthenes", "signature": "def sieve_of_eratosthenes(n):", "score": 1.0, "domain": "algorithmic"} {"id": "60ad8031102aaeb1d917150b7cd09320", "problem": "You are given a list of tuples, where each tuple represents the coordinates of a point in a 2D plane. Your task is to write a Python function that sorts these points based on their Euclidean distance from the origin (0, 0). The function should return the sorted list of points.\n\n**Input:**\n- A list of tuples, where each tuple contains two integers representing the x and y coordinates of a point.\n\n**Output:**\n- A list of tuples sorted by their Euclidean distance from the origin.\n\n**Sample Input:**\n```python\n[(3, 4), (1, 1), (0, 0), (5, 12), (7, 24)]\n```\n\n**Sample Output:**\n```python\n[(0, 0), (1, 1), (3, 4), (5, 12), (7, 24)]\n```", "reference": "import math\n\ndef sort_points_by_distance(points):\n \"\"\"\n Sorts a list of 2D points based on their Euclidean distance from the origin (0, 0).\n\n Parameters:\n points (list of tuples): A list where each tuple contains two integers representing the x and y coordinates of a point.\n\n Returns:\n list of tuples: The list of points sorted by their Euclidean distance from the origin.\n \"\"\"\n def distance(point):\n return math.sqrt(point[0]**2 + point[1]**2)\n\n return sorted(points, key=distance)\n\n# Test the function\npoints = [(3, 4), (1, 1), (0, 0), (5, 12), (7, 24)]\nsorted_points = sort_points_by_distance(points)\nprint(sorted_points)", "tests": ["assert sort_points_by_distance([(3, 4), (1, 1), (0, 0), (5, 12), (7, 24)]) == [(0, 0), (1, 1), (3, 4), (5, 12), (7, 24)]", "assert sort_points_by_distance([(0, 0), (0, 0), (0, 0)]) == [(0, 0), (0, 0), (0, 0)]", "assert sort_points_by_distance([(1, 0), (0, 1), (-1, 0), (0, -1)]) == [(1, 0), (0, 1), (-1, 0), (0, -1)]", "assert sort_points_by_distance([(2, 2), (3, 3), (1, 1)]) == [(1, 1), (2, 2), (3, 3)]", "assert sort_points_by_distance([(5, 12), (12, 5), (0, 13), (13, 0)]) == [(12, 5), (5, 12), (0, 13), (13, 0)]", "assert sort_points_by_distance([(1, 2), (2, 1), (3, 4), (4, 3)]) == [(1, 2), (2, 1), (3, 4), (4, 3)]", "assert sort_points_by_distance([(-3, -4), (-1, -1), (0, 0), (-5, -12), (-7, -24)]) == [(0, 0), (-1, -1), (-3, -4), (-5, -12), (-7, -24)]", "assert sort_points_by_distance([(10, 0), (0, 10), (-10, 0), (0, -10)]) == [(10, 0), (0, 10), (-10, 0), (0, -10)]", "assert sort_points_by_distance([(1, 1), (2, 2), (3, 3), (4, 4), (5, 5)]) == [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5)]", "assert sort_points_by_distance([]) == []"], "function": "sort_points_by_distance", "signature": "def sort_points_by_distance(points):", "score": 0.9, "domain": "algorithmic"} {"id": "78c472989ebab8438ec7c6d56a296f0e", "problem": "You are given a nested list of integers. Your task is to write a function that flattens this list into a single list of integers. The nested list can contain other nested lists of arbitrary depth. Your function should handle all possible cases and return a flattened list.\n\n**Input:**\n- A nested list of integers.\n\n**Output:**\n- A single flattened list of integers.\n\n**Sample Input:**\n```\n[1, [2, [3, 4], 5], 6, [7, 8]]\n```\n\n**Sample Output:**\n```\n[1, 2, 3, 4, 5, 6, 7, 8]\n```", "reference": "def flatten(nested_list):\n \"\"\"\n Flattens a nested list of integers into a single list of integers.\n\n :param nested_list: List of integers or nested lists of integers.\n :return: A single flattened list of integers.\n \"\"\"\n flat_list = []\n for item in nested_list:\n if isinstance(item, list):\n flat_list.extend(flatten(item))\n else:\n flat_list.append(item)\n return flat_list", "tests": ["assert flatten([1, [2, [3, 4], 5], 6, [7, 8]]) == [1, 2, 3, 4, 5, 6, 7, 8]", "assert flatten([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]", "assert flatten([[1], [2], [3], [4], [5]]) == [1, 2, 3, 4, 5]", "assert flatten([[[[1]]]]) == [1]", "assert flatten([]) == []", "assert flatten([[], [], []]) == []", "assert flatten([1, [2, [3, [4, [5]]]]]) == [1, 2, 3, 4, 5]", "assert flatten([1, [2, 3], [4, [5, 6]], 7]) == [1, 2, 3, 4, 5, 6, 7]", "assert flatten([1, [2, [3, [4, [5, [6, [7, [8, [9]]]]]]]]) == [1, 2, 3, 4, 5, 6, 7, 8, 9]", "assert flatten([1, [2, [3, [4, [5, [6, [7, [8, [9, []]]]]]]]]) == [1, 2, 3, 4, 5, 6, 7, 8, 9]"], "function": "flatten", "signature": "def flatten(nested_list):", "score": 0.8, "domain": "generic"} {"id": "7d11884200448df71e64b91856dd168f", "problem": "You are given a list of strings. Your task is to write a Python function that filters out all strings that do not contain at least one uppercase letter. The function should be optimized to minimize unnecessary computations.\n\n**Input:**\n- A list of strings, where each string consists of ASCII characters.\n\n**Output:**\n- A list of strings that contain at least one uppercase letter.\n\n**Sample Input:**\n```python\n[\"hello\", \"World\", \"PYTHON\", \"test\"]\n```\n\n**Sample Output:**\n```python\n['World', 'PYTHON']\n```", "reference": "def filter_strings_with_uppercase(strings):\n \"\"\"\n Filters a list of strings, returning only those that contain at least one uppercase letter.\n\n :param strings: List of strings to be filtered.\n :return: A list of strings containing at least one uppercase letter.\n \"\"\"\n return [s for s in strings if any(c.isupper() for c in s)]", "tests": ["assert filter_strings_with_uppercase([\"hello\", \"World\", \"PYTHON\", \"test\"]) == [\"World\", \"PYTHON\"]", "assert filter_strings_with_uppercase([\"abc\", \"def\", \"ghi\"]) == []", "assert filter_strings_with_uppercase([\"Abc\", \"dEf\", \"GhI\"]) == [\"Abc\", \"dEf\", \"GhI\"]", "assert filter_strings_with_uppercase([\"HELLO\", \"WORLD\", \"PYTHON\"]) == [\"HELLO\", \"WORLD\", \"PYTHON\"]", "assert filter_strings_with_uppercase([]) == []", "assert filter_strings_with_uppercase([\"123\", \"456\", \"789\"]) == []", "assert filter_strings_with_uppercase([\"aBcDeFgHiJ\", \"klmNoPqRsT\", \"uVwXyZ\"]) == [\"aBcDeFgHiJ\", \"klmNoPqRsT\", \"uVwXyZ\"]", "assert filter_strings_with_uppercase([\"MixedCASE\", \"lowercase\", \"UPPERCASE\"]) == [\"MixedCASE\", \"UPPERCASE\"]", "assert filter_strings_with_uppercase([\"\", \"a\", \"A\"]) == [\"A\"]", "assert filter_strings_with_uppercase([\"singleWord\", \"AnotherWord\", \"yetanotherword\"]) == [\"singleWord\", \"AnotherWord\"]"], "function": "filter_strings_with_uppercase", "signature": "def filter_strings_with_uppercase(strings):", "score": 1.0, "domain": "generic"} {"id": "ee52c79ba6984b64cba3fd383de2d42a", "problem": "You are given a string `s`. Your task is to implement a function that removes all vowels (both uppercase and lowercase) from the string and returns the resulting string. \n\n**Input:**\n- A single string `s` (1 ≤ |s| ≤ 10^5), consisting of ASCII characters.\n\n**Output:**\n- A string with all vowels removed.\n\n**Sample Input:**\n```\nHello, World!\n```\n\n**Sample Output:**\n```\nHll, Wrld!\n```", "reference": "def remove_vowels(s):\n \"\"\"\n Removes all vowels from the input string s and returns the resulting string.\n \n :param s: Input string from which vowels need to be removed.\n :return: String with all vowels removed.\n \"\"\"\n vowels = \"aeiouAEIOU\"\n return ''.join(char for char in s if char not in vowels)\n\n# Test the function\nprint(remove_vowels(\"Hello, World!\")) # Output: \"Hll, Wrld!\"", "tests": ["assert remove_vowels(\"Hello, World!\") == \"Hll, Wrld!\"", "assert remove_vowels(\"Python Programming\") == \"Pythn Prgrmmng\"", "assert remove_vowels(\"AEIOUaeiou\") == \"\"", "assert remove_vowels(\"abcdefghijklmnopqrstuvwxyz\") == \"bcdfghjklmnpqrstvwxyz\"", "assert remove_vowels(\"BCDFGHJKLMNPQRSTVWXYZ\") == \"BCDFGHJKLMNPQRSTVWXYZ\"", "assert remove_vowels(\"\") == \"\"", "assert remove_vowels(\"12345\") == \"12345\"", "assert remove_vowels(\"!@#$%^&*()\") == \"!@#$%^&*()\"", "assert remove_vowels(\"A quick brown fox jumps over the lazy dog\") == \"qck brwn fx jmps vr th lzy dg\"", "assert remove_vowels(\"The quick brown fox jumps over the lazy dog\") == \"Th qck brwn fx jmps vr th lzy dg\""], "function": "remove_vowels", "signature": "def remove_vowels(s):", "score": 0.9, "domain": "generic"} {"id": "94767ed9e8f971aa4ecfa5b2ea1cace4", "problem": "You are given the lengths of the four sides and the four angles of a quadrilateral. Your task is to classify the quadrilateral based on the provided dimensions. The function should return a string indicating the type of quadrilateral.\n\n**Input:**\n- Eight integers: `a`, `b`, `c`, `d` representing the lengths of the sides.\n- Eight integers: `A`, `B`, `C`, `D` representing the angles in degrees.\n\n**Output:**\n- A string that can be one of the following:\n - \"square\" if all sides are equal and all angles are 90 degrees.\n - \"rectangle\" if opposite sides are equal and all angles are 90 degrees.\n - \"rhombus\" if all sides are equal but not all angles are 90 degrees.\n - \"parallelogram\" if opposite sides are equal but not all angles are 90 degrees.\n - \"kite\" if exactly two pairs of adjacent sides are equal.\n - \"trapezoid\" if exactly one pair of opposite sides are parallel.\n - \"quadrilateral\" if the given input does not match any of the above conditions.\n - \"invalid\" if any of the side lengths or angle values are less than or equal to 0, or if the angles do not sum up to 360 degrees.\n\n**Sample Input:**\n```\n4 4 4 4 90 90 90 90\n```\n\n**Sample Output:**\n```\nsquare\n```\n\n**Sample Input:**\n```\n4 4 2 2 100 80 80 100\n```\n\n**Sample Output:**\n```\nkite\n```", "reference": "def classify_quadrilateral(a, b, c, d, A, B, C, D):\n \"\"\"\n Classifies a quadrilateral based on its side lengths and angles.\n\n Parameters:\n a, b, c, d (int): Lengths of the sides of the quadrilateral.\n A, B, C, D (int): Angles of the quadrilateral in degrees.\n\n Returns:\n str: Type of the quadrilateral.\n \"\"\"\n # Check for invalid side lengths or angles\n if any(x <= 0 for x in (a, b, c, d, A, B, C, D)) or A + B + C + D != 360:\n return \"invalid\"\n \n # Sort sides and angles to simplify comparisons\n sides = sorted([a, b, c, d])\n angles = sorted([A, B, C, D])\n \n # Check for square\n if sides[0] == sides[3] and angles[0] == angles[3] == 90:\n return \"square\"\n \n # Check for rectangle\n if sides[0] == sides[1] == sides[2] == sides[3] and angles[0] == angles[3] == 90:\n return \"rectangle\"\n \n # Check for rhombus\n if sides[0] == sides[3] and angles[0] != 90:\n return \"rhombus\"\n \n # Check for parallelogram\n if sides[0] == sides[2] and sides[1] == sides[3] and angles[0] != 90:\n return \"parallelogram\"\n \n # Check for kite\n if (a == b and c == d) or (a == c and b == d) or (a == d and b == c):\n return \"kite\"\n \n # Check for trapezoid\n if (angles[0] + angles[3] == 180) or (angles[1] + angles[2] == 180):\n return \"trapezoid\"\n \n # If no other rule matches, it is a general quadrilateral\n return \"quadrilateral\"", "tests": ["assert classify_quadrilateral(4, 4, 4, 4, 90, 90, 90, 90) == \"square\"", "assert classify_quadrilateral(4, 4, 4, 4, 90, 90, 90, 80) == \"rhombus\"", "assert classify_quadrilateral(4, 4, 2, 2, 100, 80, 80, 100) == \"kite\"", "assert classify_quadrilateral(3, 3, 3, 3, 90, 90, 90, 90) == \"square\"", "assert classify_quadrilateral(4, 4, 2, 2, 90, 90, 90, 90) == \"invalid\"", "assert classify_quadrilateral(4, 4, 2, 3, 120, 60, 60, 120) == \"trapezoid\"", "assert classify_quadrilateral(5, 5, 5, 5, 90, 90, 90, 90) == \"square\"", "assert classify_quadrilateral(5, 5, 5, 5, 90, 90, 90, 89) == \"rhombus\"", "assert classify_quadrilateral(6, 6, 6, 6, 90, 90, 90, 90) == \"square\"", "assert classify_quadrilateral(6, 6, 6, 6, 90, 90, 90, 88) == \"rhombus\""], "function": "classify_quadrilateral", "signature": "def classify_quadrilateral(a, b, c, d, A, B, C, D):", "score": 0.6, "domain": "generic"} {"id": "27a60f1958983775bb7a3f9dc9f6d4e6", "problem": "You are given a string `text` consisting of words, numbers, and brackets (both square `[]` and curly `{}`). Your task is to implement a function `extract_bracket_content(text)` that returns a dictionary. The keys of the dictionary should be the contents inside the innermost square brackets `[]`, and the values should be the contents inside the innermost curly brackets `{}` that immediately follow the corresponding square brackets. If there are multiple occurrences of square and curly brackets, the function should return a dictionary with all the corresponding pairs. If a square bracket is not followed by a curly bracket, or if there are mismatched brackets, the function should raise an exception. The function must handle nested brackets, where square brackets can be nested inside other square brackets, and curly brackets can be nested inside other curly brackets. The function should extract the innermost bracket content and ignore the outer brackets.\n\n**Input:**\n- A string `text` (1 ≤ |text| ≤ 10^5) containing words, numbers, and brackets.\n\n**Output:**\n- A dictionary where keys are the contents inside the innermost square brackets and values are the contents inside the innermost curly brackets that immediately follow the corresponding square brackets.\n\n**Sample Input:**\n```\n\"This is a [test] {example} of the function.\"\n```\n\n**Sample Output:**\n```\n{\"test\": \"example\"}\n```\n\n**Sample Input:**\n```\n\"Nested [brackets [are] {handled}] {correctly}.\"\n```\n\n**Sample Output:**\n```\n{\"are\": \"handled\"}\n```", "reference": "def extract_bracket_content(text):\n \"\"\"\n Extracts the innermost content of square and curly brackets from the given text.\n \n Args:\n text (str): The input string containing words, numbers, and brackets.\n \n Returns:\n dict: A dictionary with keys as innermost square bracket contents and values as innermost curly bracket contents.\n \n Raises:\n Exception: If there are mismatched brackets or if a square bracket is not followed by a curly bracket.\n \"\"\"\n def extract_content(bracket_type, text):\n open_bracket, close_bracket = ('[', ']') if bracket_type == 'square' else ('{', '}')\n stack = []\n content = []\n start_index = -1\n \n for i, char in enumerate(text):\n if char == open_bracket:\n stack.append(char)\n if start_index == -1:\n start_index = i + 1\n elif char == close_bracket:\n if not stack:\n raise Exception(\"Mismatched brackets\")\n stack.pop()\n if not stack:\n end_index = i\n content.append(text[start_index:end_index])\n start_index = -1\n \n if stack:\n raise Exception(\"Mismatched brackets\")\n \n innermost_content = []\n for c in content:\n innermost_content.append(extract_content(bracket_type, c)[-1] if bracket_type in c else c)\n \n return innermost_content\n \n square_contents = extract_content('square', text)\n curly_contents = extract_content('curly', text)\n \n if len(square_contents) != len(curly_contents):\n raise Exception(\"Square and curly brackets do not match\")\n \n result = {}\n for square_content, curly_content in zip(square_contents, curly_contents):\n if not square_content or not curly_content:\n raise Exception(\"Empty content between brackets\")\n result[square_content] = curly_content\n \n return result", "tests": ["assert extract_bracket_content(\"This is a [test] {example} of the function.\") == {\"test\": \"example\"}", "assert extract_bracket_content(\"[first] {one} [second] {two}\") == {\"first\": \"one\", \"second\": \"two\"}", "assert extract_bracket_content(\"[nested [inner]] {outer}\") == {\"inner\": \"outer\"}", "assert extract_bracket_content(\"{not [matching] [brackets}\") == Exception(\"Mismatched brackets\")", "assert extract_bracket_content(\"[no] {curly} [bracket] here\") == {\"no\": \"curly\", \"bracket\": \"here\"}", "assert extract_bracket_content(\"[empty] {}\") == Exception(\"Empty content between brackets\")", "assert extract_bracket_content(\"[one] {two} [three] {four} [five] {six}\") == {\"one\": \"two\", \"three\": \"four\", \"five\": \"six\"}", "assert extract_bracket_content(\"[a] {b} [c] {d} [e] {f} [g] {h}\") == {\"a\": \"b\", \"c\": \"d\", \"e\": \"f\", \"g\": \"h\"}", "assert extract_bracket_content(\"[nested [deep [innermost]]] {content}\") == {\"innermost\": \"content\"}", "assert extract_bracket_content(\"[single]\") == Exception(\"Square and curly brackets do not match\")"], "function": "extract_bracket_content", "signature": "def extract_bracket_content(text):", "score": 0.4, "domain": "generic"} {"id": "d84ddc569ab1b69289ee43c122b6bc06", "problem": "You are tasked with implementing a function to determine if a given string is a valid email address according to the simplified criteria inspired by RFC 5322. The function should return `True` if the string is a valid email address and `False` otherwise. A valid email address must satisfy the following conditions:\n- It consists of a local part, an \"@\" symbol, and a domain part.\n- The local part may include letters (both uppercase and lowercase), digits, dots (`.`), underscores (`_`), percent signs (`%`), plus signs (`+`), and hyphens (`-`).\n- The domain part must include at least one dot (`.`) and consist of labels separated by dots. Each label must start and end with a letter or digit, and may contain hyphens (`-`) in between.\n- The top-level domain (TLD) must be at least two characters long and consist only of letters.\n\n**Sample Input:**\n```\ntest@example.com\ntest.user@example.co.uk\ntest_user@example.com\ntest-user@example.com\ntest@example\ntest@.com\ntest@domain..com\n```\n\n**Sample Output:**\n```\ntest@example.com: True\ntest.user@example.co.uk: True\ntest_user@example.com: True\ntest-user@example.com: True\ntest@example: False\ntest@.com: False\ntest@domain..com: False\n```", "reference": "import re\n\ndef is_valid_email(email):\n \"\"\"\n Determines if the given string is a valid email address according to the simplified criteria inspired by RFC 5322.\n \n Parameters:\n email (str): The email address to validate.\n \n Returns:\n bool: True if the email is valid, False otherwise.\n \"\"\"\n pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$'\n return bool(re.match(pattern, email))\n\n# Test cases\ntest_emails = [\n \"test@example.com\",\n \"test.user@example.co.uk\",\n \"test_user@example.com\",\n \"test-user@example.com\",\n \"test@example\",\n \"test@.com\",\n \"test@domain..com\"\n]\n\nfor email in test_emails:\n print(f'{email}: {is_valid_email(email)}')", "tests": ["assert is_valid_email(\"test@example.com\") == True", "assert is_valid_email(\"test.user@example.co.uk\") == True", "assert is_valid_email(\"test_user@example.com\") == True", "assert is_valid_email(\"test-user@example.com\") == True", "assert is_valid_email(\"test@example\") == False", "assert is_valid_email(\"test@.com\") == False", "assert is_valid_email(\"test@domain..com\") == False", "assert is_valid_email(\"user@domain.com\") == True", "assert is_valid_email(\"user@domain.c\") == False", "assert is_valid_email(\"user@domain.corporate\") == True"], "function": "is_valid_email", "signature": "def is_valid_email(email):", "score": 0.9, "domain": "algorithmic"} {"id": "e2bd8139af16b09592ed2ceb72ccb29b", "problem": "You are given two lists, `distances` and `labels`, where each element in `distances` corresponds to an element in `labels` at the same index. Your task is to implement a function `find_closest_label(distances, labels)` that returns the label(s) associated with the smallest distance. If there are multiple labels with the same smallest distance, return all of them in a list.\n\n**Input:**\n- A list of floating-point numbers `distances` (1 ≤ len(distances) ≤ 10^5).\n- A list of strings `labels` (1 ≤ len(labels) ≤ 10^5), where each label is a single uppercase letter.\n\n**Output:**\n- A string if there is a single label with the smallest distance, or a list of strings if there are multiple labels with the smallest distance.\n\n**Sample Input:**\n```\ndistances = [1.5, 2.3, 0.9, 3.7, 0.9]\nlabels = ['A', 'B', 'C', 'D', 'E']\n```\n\n**Sample Output:**\n```\n['C', 'E']\n```", "reference": "def find_closest_label(distances, labels):\n \"\"\"\n Returns the label(s) associated with the smallest distance from the given lists.\n \n :param distances: List of floating-point numbers representing distances.\n :param labels: List of strings representing labels.\n :return: A string if there is a single closest label, or a list of strings if there are multiple closest labels.\n \"\"\"\n min_distance = min(distances)\n closest_labels = [label for distance, label in zip(distances, labels) if distance == min_distance]\n return closest_labels[0] if len(closest_labels) == 1 else closest_labels", "tests": ["assert find_closest_label([1.5, 2.3, 0.9, 3.7], ['A', 'B', 'C', 'D']) == 'C'", "assert find_closest_label([1.5, 2.3, 0.9, 3.7, 0.9], ['A', 'B', 'C', 'D', 'E']) == ['C', 'E']", "assert find_closest_label([5.5, 5.5, 5.5], ['X', 'Y', 'Z']) == ['X', 'Y', 'Z']", "assert find_closest_label([10.2, 9.8, 10.1], ['P', 'Q', 'R']) == 'Q'", "assert find_closest_label([0.1, 0.2, 0.3, 0.4, 0.5], ['W', 'X', 'Y', 'Z', 'A']) == 'W'", "assert find_closest_label([2.0, 2.0, 2.0, 2.0], ['M', 'N', 'O', 'P']) == ['M', 'N', 'O', 'P']", "assert find_closest_label([100.0], ['S']) == 'S'", "assert find_closest_label([3.3, 2.2, 1.1, 0.0], ['T', 'U', 'V', 'W']) == 'W'", "assert find_closest_label([1.1, 1.1, 1.1, 1.1, 1.1], ['A', 'B', 'C', 'D', 'E']) == ['A', 'B', 'C', 'D', 'E']", "assert find_closest_label([5.0, 4.0, 3.0, 2.0, 1.0], ['J', 'K', 'L', 'M', 'N']) == 'N'"], "function": "find_closest_label", "signature": "def find_closest_label(distances, labels):", "score": 1.0, "domain": "generic"} {"id": "6dafb041eeaacc6e0e2ea07074af6539", "problem": "You are given a regular expression pattern and a string of text. Your task is to implement a function `keyword_frequency(pattern, text)` that returns a dictionary. The keys in the dictionary should be the words from the text that match the given pattern, and the values should be the count of each word's occurrences in the text. Words that are palindromes should be excluded from the dictionary.\n\n**Input:**\n- A regular expression pattern as a string.\n- A string of text.\n\n**Output:**\n- A dictionary with words as keys and their frequencies as values, excluding palindromes.\n\n**Sample Input:**\n- Pattern: `r'\\b\\w+\\b'`\n- Text: `\"The quick brown fox jumps over the level lazy deed dog\"`\n\n**Sample Output:**\n- `{'the': 2, 'quick': 1, 'brown': 1, 'fox': 1, 'jumps': 1, 'over': 1, 'lazy': 1, 'dog': 1}`", "reference": "import re\nfrom collections import defaultdict\n\ndef is_palindrome(word):\n \"\"\"\n Check if a given word is a palindrome.\n \n :param word: The word to check.\n :return: True if the word is a palindrome, False otherwise.\n \"\"\"\n return word == word[::-1]\n\ndef keyword_frequency(pattern, text):\n \"\"\"\n Return a dictionary of word frequencies from the text that match the pattern, excluding palindromes.\n \n :param pattern: A regular expression pattern as a string.\n :param text: A string of text.\n :return: A dictionary with words as keys and their frequencies as values, excluding palindromes.\n \"\"\"\n # Find all words that match the pattern\n words = re.findall(pattern, text, re.IGNORECASE)\n \n # Initialize a default dictionary to store word frequencies\n frequency = defaultdict(int)\n \n # Count the frequency of each word, excluding palindromes\n for word in words:\n word_lower = word.lower()\n if not is_palindrome(word_lower):\n frequency[word_lower] += 1\n \n return dict(frequency)", "tests": ["assert keyword_frequency(r'\\b\\w+\\b', \"The quick brown fox jumps over the level lazy deed dog\") == {'the': 2, 'quick': 1, 'brown': 1, 'fox': 1, 'jumps': 1, 'over': 1, 'lazy': 1, 'dog': 1}", "assert keyword_frequency(r'\\b\\w+\\b', \"Anna went to see civic duty\") == {'anna': 1, 'went': 1, 'to': 1, 'see': 1, 'duty': 1}", "assert keyword_frequency(r'\\b\\w+\\b', \"racecar madam rotor\") == {}", "assert keyword_frequency(r'\\b\\w+\\b', \"hello world\") == {'hello': 1, 'world': 1}", "assert keyword_frequency(r'\\b\\w+\\b', \"level deed\") == {}", "assert keyword_frequency(r'\\b\\w+\\b', \"a man a plan a canal panama\") == {'a': 3, 'man': 1, 'plan': 1, 'canal': 1, 'panama': 1}", "assert keyword_frequency(r'\\b\\w+\\b', \"Was it a car or a cat I saw\") == {'was': 1, 'it': 1, 'a': 2, 'car': 1, 'or': 1, 'cat': 1, 'i': 1, 'saw': 1}", "assert keyword_frequency(r'\\b\\w+\\b', \"No lemon no melon\") == {'no': 2, 'lemon': 1, 'melon': 1}", "assert keyword_frequency(r'\\b\\w+\\b', \"Madam Arora teaches malayalam\") == {'madam': 1, 'arora': 1, 'teaches': 1, 'malayalam': 1}", "assert keyword_frequency(r'\\b\\w+\\b', \"Was it a car or a cat I saw? Was it a car or a cat I saw?\") == {'was': 2, 'it': 2, 'a': 4, 'car': 2, 'or': 2, 'cat': 2, 'i': 2, 'saw': 2}"], "function": "keyword_frequency", "signature": "def keyword_frequency(pattern, text):", "score": 0.5, "domain": "generic"} {"id": "19468e2e7e9598017ecce46e4eaac0cb", "problem": "You are given a set of `n` points in a 2D plane, each represented by a pair of integers `(x, y)`. Your task is to determine the Pareto front of these points. A point `(x1, y1)` is said to dominate another point `(x2, y2)` if `x1 >= x2` and `y1 >= y2`. The Pareto front consists of points that are not dominated by any other point in the set. \n\nWrite a function `calculate_pareto_front(points)` that takes a list of tuples `points` as input and returns a list of tuples representing the points on the Pareto front. The points in the output should be sorted by their `x` coordinates in ascending order. If two points have the same `x` coordinate, they should be sorted by their `y` coordinates in descending order.\n\n**Constraints:**\n- `1 <= n <= 10^5`\n- `0 <= x, y <= 10^9`\n\n**Sample Input:**\n```python\npoints = [(1, 2), (4, 2), (4, 4), (2, 3), (1, 3), (3, 1), (5, 5)]\n```\n\n**Sample Output:**\n```python\n[(1, 3), (2, 3), (4, 4), (5, 5)]\n```", "reference": "def calculate_pareto_front(points):\n \"\"\"\n Calculate the Pareto front of a given set of points in 2D space.\n \n :param points: List of tuples, where each tuple represents a point (x, y).\n :return: List of tuples representing the points on the Pareto front.\n \"\"\"\n # Sort points by x in ascending order, and by y in descending order if x values are the same\n sorted_points = sorted(points, key=lambda point: (point[0], -point[1]))\n \n # Initialize the front list and the current maximum y value\n pareto_front = []\n max_y = float('-inf')\n \n # Iterate over the sorted points to find the Pareto front\n for point in sorted_points:\n x, y = point\n if y > max_y:\n pareto_front.append(point)\n max_y = y\n \n return pareto_front\n\n# Example usage\npoints = [(1, 2), (4, 2), (4, 4), (2, 3), (1, 3), (3, 1), (5, 5)]\npareto_front = calculate_pareto_front(points)\nprint(pareto_front)", "tests": ["assert calculate_pareto_front([(1, 2), (4, 2), (4, 4), (2, 3), (1, 3), (3, 1), (5, 5)]) == [(1, 3), (2, 3), (4, 4), (5, 5)]", "assert calculate_pareto_front([(1, 1), (2, 2), (3, 3), (4, 4)]) == [(1, 1), (2, 2), (3, 3), (4, 4)]", "assert calculate_pareto_front([(4, 4), (3, 3), (2, 2), (1, 1)]) == [(1, 1), (2, 2), (3, 3), (4, 4)]", "assert calculate_pareto_front([(1, 5), (2, 4), (3, 3), (4, 2), (5, 1)]) == [(1, 5), (2, 4), (3, 3), (4, 2), (5, 1)]", "assert calculate_pareto_front([(1, 1), (2, 2), (2, 3), (3, 2), (3, 3)]) == [(1, 1), (2, 3), (3, 3)]", "assert calculate_pareto_front([(1, 1)]) == [(1, 1)]", "assert calculate_pareto_front([]) == []", "assert calculate_pareto_front([(1, 2), (1, 3), (1, 4)]) == [(1, 4)]", "assert calculate_pareto_front([(1, 4), (1, 3), (1, 2)]) == [(1, 4)]", "assert calculate_pareto_front([(1, 1), (2, 2), (3, 3), (2, 3), (3, 2)]) == [(1, 1), (2, 3), (3, 3)]"], "function": "calculate_pareto_front", "signature": "def calculate_pareto_front(points):", "score": 0.6, "domain": "generic"} {"id": "8466be47d06a5b63211f4f0a722d7306", "problem": "You are developing a secure web application that requires processing user input. Your task is to implement a function `sanitize_input(input_str)` that processes a given string `input_str` and returns a sanitized version. The function must perform the following operations:\n1. Remove any leading and trailing whitespace from the string.\n2. Replace any sequence of consecutive whitespace characters with a single space.\n3. Escape any HTML special characters to prevent XSS attacks.\n\nWrite a function that accomplishes the above tasks. Your function should handle edge cases such as empty strings and strings with only whitespace.\n\n**Sample Input:**\n```\n\" \"\n```\n\n**Sample Output:**\n```\n\"<script>alert('xss')</script>\"\n```", "reference": "import html\n\ndef sanitize_input(input_str):\n \"\"\"\n Sanitizes the input string by removing leading and trailing whitespace,\n replacing consecutive whitespace with a single space, and escaping HTML special characters.\n\n :param input_str: The input string to be sanitized.\n :return: A sanitized version of the input string.\n \"\"\"\n sanitized_str = input_str.strip()\n sanitized_str = ' '.join(sanitized_str.split())\n sanitized_str = html.escape(sanitized_str)\n return sanitized_str", "tests": ["assert sanitize_input(\" \") == \"<script>alert('xss')</script>\"", "assert sanitize_input(\"Hello World\") == \"Hello World\"", "assert sanitize_input(\" Leading and trailing spaces \") == \"Leading and trailing spaces\"", "assert sanitize_input(\"Multiple spaces here\") == \"Multiple spaces here\"", "assert sanitize_input(\"

Test

\") == \"<div><p>Test</p></div>\"", "assert sanitize_input(\"NoSpecialChars\") == \"NoSpecialChars\"", "assert sanitize_input(\" Link \") == \"<a href='#'>Link</a>\"", "assert sanitize_input(\"Line\\nBreak\") == \"Line Break\"", "assert sanitize_input(\"Tab\\tSeparated\") == \"Tab Separated\"", "assert sanitize_input(\" Mixed Bold and Italic \") == \"Mixed <b>Bold</b> and <i>Italic</i>\""], "function": "sanitize_input", "signature": "def sanitize_input(input_str):", "score": 1.0, "domain": "generic"} {"id": "8ed2fc48bd06b19341ce1bd2a3fca1a5", "problem": "You are given a string `html_content` representing an HTML document. Your task is to implement a function `parse_html(html_content)` that extracts the text content of all top-level `

` tags and returns a dictionary. The keys of the dictionary should be the 1-based index of the `

` tag in the HTML content, and the values should be the text content of the corresponding `

` tag. Assume that the HTML content may contain nested tags, but you should only consider the text within the top-level `

` tags.\n\n**Sample Input:**\n```python\n'

Hello

World

'\n```\n\n**Sample Output:**\n```python\n{1: 'Hello', 2: 'World'}\n```\n\n**Sample Input:**\n```python\n'

First

Nested

Second

'\n```\n\n**Sample Output:**\n```python\n{1: 'First', 2: 'Second'}\n```", "reference": "from html.parser import HTMLParser\n\nclass MyHTMLParser(HTMLParser):\n def __init__(self):\n super().__init__()\n self.paragraphs = {}\n self.current_tag = None\n self.current_paragraph = []\n self.paragraph_index = 0\n \n def handle_starttag(self, tag, attrs):\n if tag == 'p' and self.current_tag is None:\n self.paragraph_index += 1\n self.current_tag = tag\n self.current_paragraph = []\n\n def handle_endtag(self, tag):\n if tag == 'p' and self.current_tag == 'p':\n self.paragraphs[self.paragraph_index] = ''.join(self.current_paragraph)\n self.current_tag = None\n\t\n def handle_data(self, data):\n if self.current_tag == 'p':\n self.current_paragraph.append(data)\n\ndef parse_html(html_content):\n \"\"\"\n Parses the given HTML content and returns a dictionary with the text content of all top-level

tags.\n \n :param html_content: A string representing the HTML content.\n :return: A dictionary with keys as the 1-based index of

tags and values as their text content.\n \"\"\"\n parser = MyHTMLParser()\n parser.feed(html_content)\n return parser.paragraphs", "tests": ["assert parse_html('

Hello

World

') == {1: 'Hello', 2: 'World'}", "assert parse_html('

First

Second

Third

') == {1: 'First', 2: 'Second', 3: 'Third'}", "assert parse_html('

Single

') == {1: 'Single'}", "assert parse_html('

Start

Inside

End

') == {1: 'Start', 2: 'End'}", "assert parse_html('

Line1
Line2

') == {1: 'Line1Line2'}", "assert parse_html('

Whitespace Test

') == {1: 'Whitespace Test'}", "assert parse_html('

Special & Characters

') == {1: 'Special & Characters'}", "assert parse_html('

Empty

Not Empty

') == {1: 'Empty', 2: '', 3: 'Not Empty'}", "assert parse_html('

Multiple Spaces

') == {1: 'Multiple Spaces'}", "assert parse_html('

Trailing Space

') == {1: 'Trailing Space '}"], "function": "parse_html", "signature": "def parse_html(html_content):", "score": 0.9, "domain": "generic"} {"id": "1964f19b95d52291dc45ee42e2cb07c9", "problem": "You are given two lists of strings, `list1` and `list2`. Your task is to implement a function `find_common_words` that identifies and returns a list of words that appear in both lists. The comparison should be case-insensitive, and the resulting list of common words should be in lowercase and sorted lexicographically.\n\n**Input:**\n- Two lists of strings, `list1` and `list2`.\n\n**Output:**\n- A list of strings representing the common words in lowercase, sorted in lexicographical order.\n\n**Sample Input:**\n```python\nlist1 = [\"Hello World\", \"Python is great!\"]\nlist2 = [\"world of programming\", \"Python is fun\"]\n```\n\n**Sample Output:**\n```python\n['is', 'python', 'world']\n```", "reference": "def find_common_words(list1, list2):\n \"\"\"\n Finds and returns a list of common words in both input lists, ignoring case sensitivity.\n \n :param list1: List of strings.\n :param list2: List of strings.\n :return: Sorted list of common words in lowercase.\n \"\"\"\n words1 = set(word.lower() for sentence in list1 for word in sentence.split())\n words2 = set(word.lower() for sentence in list2 for word in sentence.split())\n common_words = words1.intersection(words2)\n return sorted(common_words)", "tests": ["assert find_common_words([\"Hello\", \"world\"], [\"world\", \"hello\"]) == ['hello', 'world']", "assert find_common_words([\"Python\", \"programming\"], [\"is\", \"Python\"]) == ['python']", "assert find_common_words([\"OpenAI\", \"ChatGPT\"], [\"AI\", \"openai\"]) == ['openai']", "assert find_common_words([\"Data\", \"Science\"], [\"science\", \"data\"]) == ['data', 'science']", "assert find_common_words([\"Machine\", \"Learning\"], [\"Deep\", \"Learning\"]) == ['learning']", "assert find_common_words([\"Natural\", \"Language\", \"Processing\"], [\"processing\", \"language\"]) == ['language', 'processing']", "assert find_common_words([\"Artificial\", \"Intelligence\"], [\"intelligence\", \"AI\"]) == ['intelligence']", "assert find_common_words([\"Big\", \"Data\"], [\"data\", \"big\"]) == ['big', 'data']", "assert find_common_words([\"Computer\", \"Vision\"], [\"vision\", \"computer\"]) == ['computer', 'vision']", "assert find_common_words([\"Robotics\"], [\"robotics\", \"AI\"]) == ['robotics']"], "function": "find_common_words", "signature": "def find_common_words(list1, list2):", "score": 1.0, "domain": "generic"} {"id": "dc0798065f7b5a88950b4f1accf00004", "problem": "You are given a list of `n` strings, each consisting of lowercase English letters. Your task is to implement a function `find_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. The solution must be implemented using a single loop and without utilizing any built-in string functions such as `startswith`, `find`, `index`, etc.\n\n**Constraints:**\n- `1 <= n <= 100`\n- Each string has a length between `1` and `100` characters.\n\n**Sample Input:**\n```\n[\"flower\", \"flow\", \"flight\"]\n```\n\n**Sample Output:**\n```\n\"fl\"\n```", "reference": "def find_common_prefix(words):\n \"\"\"\n Finds the longest common prefix among a list of strings using a single loop.\n \n :param words: List of strings to find the common prefix for.\n :return: The longest common prefix as a string, or an empty string if no common prefix exists.\n \"\"\"\n if not words:\n return \"\"\n \n prefix = \"\"\n is_common = True\n \n # Determine the length of the shortest word\n min_length = len(words[0])\n for word in words:\n if len(word) < min_length:\n min_length = len(word)\n \n # Check character by character\n for i in range(min_length):\n char = words[0][i]\n for word in words:\n if word[i] != char:\n is_common = False\n break\n if not is_common:\n break\n prefix += char\n \n return prefix\n\n# Example usage\nwords = [\"flower\", \"flow\", \"flight\"]\nprint(find_common_prefix(words)) # Output: \"fl\"", "tests": ["assert find_common_prefix([\"flower\", \"flow\", \"flight\"]) == \"fl\"", "assert find_common_prefix([\"dog\", \"racecar\", \"car\"]) == \"\"", "assert find_common_prefix([\"interspecies\", \"interstellar\", \"interstate\"]) == \"inters\"", "assert find_common_prefix([\"throne\", \"throne\"]) == \"throne\"", "assert find_common_prefix([]) == \"\"", "assert find_common_prefix([\"prefix\", \"preposition\", \"prevent\"]) == \"pre\"", "assert find_common_prefix([\"a\", \"b\", \"c\"]) == \"\"", "assert find_common_prefix([\"ab\", \"abc\", \"abcd\"]) == \"ab\"", "assert find_common_prefix([\"hello\", \"hell\", \"heaven\", \"heavy\"]) == \"he\"", "assert find_common_prefix([\"single\"]) == \"single\""], "function": "find_common_prefix", "signature": "def find_common_prefix(words):", "score": 1.0, "domain": "generic"} {"id": "3580e692ea283f683d9f9626441fdfde", "problem": "In a resource collection game, each player maintains an inventory of resources stored in a dictionary. The keys represent the types of resources, and the values represent the quantities of those resources. You are tasked with implementing a function `merge_inventories` that takes two such inventories as input and returns a new inventory that is the result of merging the two. If a resource type appears in both inventories, the quantities should be summed. If a resource type appears in only one inventory, it should be included in the merged inventory with its original quantity.\n\n**Input:**\n- Two dictionaries, `inventory1` and `inventory2`, where each dictionary contains string keys representing resource types and integer values representing quantities.\n\n**Output:**\n- A dictionary representing the merged inventory.\n\n**Sample Input:**\n```python\ninventory1 = {'gold': 10, 'wood': 50, 'stone': 20}\ninventory2 = {'gold': 5, 'iron': 15, 'wood': 30}\n```\n\n**Sample Output:**\n```python\n{'gold': 15, 'wood': 80, 'stone': 20, 'iron': 15}\n```", "reference": "def merge_inventories(inventory1, inventory2):\n \"\"\"\n Merges two resource inventories into one. If a resource type exists in both inventories,\n the quantities are summed. Otherwise, the resource is added to the merged inventory as is.\n\n :param inventory1: Dictionary representing the first player's inventory.\n :param inventory2: Dictionary representing the second player's inventory.\n :return: Dictionary representing the merged inventory.\n \"\"\"\n merged_inventory = inventory1.copy()\n for resource, quantity in inventory2.items():\n if resource in merged_inventory:\n merged_inventory[resource] += quantity\n else:\n merged_inventory[resource] = quantity\n return merged_inventory\n\n# Example usage:\ninventory_a = {'gold': 10, 'wood': 50, 'stone': 20}\ninventory_b = {'gold': 5, 'iron': 15, 'wood': 30}\n\nmerged = merge_inventories(inventory_a, inventory_b)\nprint(merged) # Output: {'gold': 15, 'wood': 80, 'stone': 20, 'iron': 15}", "tests": ["assert merge_inventories({}, {}) == {}", "assert merge_inventories({'gold': 10}, {'gold': 5}) == {'gold': 15}", "assert merge_inventories({'wood': 50}, {'iron': 15}) == {'wood': 50, 'iron': 15}", "assert merge_inventories({'stone': 20}, {}) == {'stone': 20}", "assert merge_inventories({}, {'gold': 5, 'iron': 15}) == {'gold': 5, 'iron': 15}", "assert merge_inventories({'gold': 10, 'wood': 50}, {'iron': 15}) == {'gold': 10, 'wood': 50, 'iron': 15}", "assert merge_inventories({'gold': 10, 'wood': 50}, {'gold': 5, 'wood': 30}) == {'gold': 15, 'wood': 80}", "assert merge_inventories({'stone': 20, 'iron': 15}, {'gold': 5, 'wood': 30}) == {'stone': 20, 'iron': 15, 'gold': 5, 'wood': 30}", "assert merge_inventories({'water': 100}, {'water': 100, 'food': 50}) == {'water': 200, 'food': 50}", "assert merge_inventories({'coal': 50, 'oil': 30}, {'coal': 20, 'uranium': 10}) == {'coal': 70, 'oil': 30, 'uranium': 10}"], "function": "merge_inventories", "signature": "def merge_inventories(inventory1, inventory2):", "score": 1.0, "domain": "generic"} {"id": "f8f20a81943b5d2b475bb7004cccea30", "problem": "You are given a dictionary where each key is a string and each value is a list of integers. Your task is to create a new dictionary by swapping the keys and values. If multiple keys in the original dictionary have the same value, only the last key-value pair encountered should be retained in the new dictionary. \n\n**Input:**\n- A dictionary `input_dict` with string keys and list values.\n\n**Output:**\n- A dictionary with integer keys and string values, where each integer key is a unique value from the original lists, and the corresponding string value is the last key from the original dictionary that contained this integer.\n\n**Sample Input:**\n```python\n{\"a\": [1, 2, 3], \"b\": [4, 5, 6], \"c\": [1, 2, 3]}\n```\n\n**Sample Output:**\n```python\n{1: 'c', 2: 'c', 3: 'c', 4: 'b', 5: 'b', 6: 'b'}\n```", "reference": "def swap_dict(input_dict):\n \"\"\"\n Swaps the keys and values of a dictionary where each key maps to a list of values.\n If multiple keys have the same value, only the last key-value pair is retained.\n\n :param input_dict: Dictionary with string keys and list of integer values.\n :return: Dictionary with integer keys and string values.\n \"\"\"\n result = {}\n for key, values in input_dict.items():\n for value in values:\n result[value] = key\n return result\n\n# Example usage:\noriginal_dict = {\"a\": [1, 2, 3], \"b\": [4, 5, 6], \"c\": [1, 2, 3]}\nswapped_dict = swap_dict(original_dict)\nprint(swapped_dict)", "tests": ["assert swap_dict({\"a\": [1, 2, 3], \"b\": [4, 5, 6], \"c\": [1, 2, 3]}) == {1: 'c', 2: 'c', 3: 'c', 4: 'b', 5: 'b', 6: 'b'}", "assert swap_dict({\"x\": [10, 20], \"y\": [30, 40], \"z\": [10, 50]}) == {10: 'z', 20: 'x', 30: 'y', 40: 'y', 50: 'z'}", "assert swap_dict({\"m\": [100], \"n\": [200], \"o\": [300]}) == {100: 'm', 200: 'n', 300: 'o'}", "assert swap_dict({\"p\": [1, 2], \"q\": [2, 3], \"r\": [3, 4]}) == {1: 'p', 2: 'q', 3: 'r', 4: 'r'}", "assert swap_dict({\"s\": [5, 6, 7], \"t\": [5, 8, 9], \"u\": [10, 11, 12]}) == {5: 't', 6: 's', 7: 's', 8: 't', 9: 't', 10: 'u', 11: 'u', 12: 'u'}", "assert swap_dict({\"v\": [13, 14], \"w\": [15, 16], \"x\": [17, 18], \"y\": [19, 20]}) == {13: 'v', 14: 'v', 15: 'w', 16: 'w', 17: 'x', 18: 'x', 19: 'y', 20: 'y'}", "assert swap_dict({\"a\": [1], \"b\": [1], \"c\": [1]}) == {1: 'c'}", "assert swap_dict({}) == {}", "assert swap_dict({\"single\": [42]}) == {42: 'single'}", "assert swap_dict({\"key1\": [1, 2, 3], \"key2\": [4, 5, 6], \"key3\": [7, 8, 9], \"key4\": [1, 2, 3]}) == {1: 'key4', 2: 'key4', 3: 'key4', 4: 'key2', 5: 'key2', 6: 'key2', 7: 'key3', 8: 'key3', 9: 'key3'}"], "function": "swap_dict", "signature": "def swap_dict(input_dict):", "score": 1.0, "domain": "generic"} {"id": "73c9cfae653ca1cbff3150b2e27b14c6", "problem": "You are given a list of integers. Your task is to create a function that processes this list and returns a new list where all even numbers are doubled, while odd numbers remain unchanged. \n\n**Input:**\n- A list of integers `numbers` (1 ≤ len(numbers) ≤ 10^3), where each integer `n` satisfies -10^6 ≤ n ≤ 10^6.\n\n**Output:**\n- A list of integers where each even number from the input list is multiplied by 2, and odd numbers are left unchanged.\n\n**Sample Input:**\n```\n[1, 2, 3, 4, 5]\n```\n\n**Sample Output:**\n```\n[1, 4, 3, 8, 5]\n```", "reference": "def double_even_numbers(numbers):\n \"\"\"\n Returns a new list with all even numbers from the input list doubled,\n while odd numbers remain unchanged.\n\n :param numbers: List of integers\n :return: List of integers with even numbers doubled\n \"\"\"\n return [n * 2 if n % 2 == 0 else n for n in numbers]", "tests": ["assert double_even_numbers([1, 2, 3, 4, 5]) == [1, 4, 3, 8, 5]", "assert double_even_numbers([10, 15, 20, 25]) == [20, 15, 40, 25]", "assert double_even_numbers([0, -2, -3, -4]) == [0, -4, -3, -8]", "assert double_even_numbers([]) == []", "assert double_even_numbers([7, 11, 13]) == [7, 11, 13]", "assert double_even_numbers([2, 4, 6, 8, 10]) == [4, 8, 12, 16, 20]", "assert double_even_numbers([-1, -3, -5, -7]) == [-1, -3, -5, -7]", "assert double_even_numbers([100, 200, 300]) == [200, 400, 600]", "assert double_even_numbers([1, 3, 5, 7, 9, 2, 4, 6, 8]) == [1, 3, 5, 7, 9, 4, 8, 12, 16]", "assert double_even_numbers([22, 33, 44, 55, 66]) == [44, 33, 88, 55, 132]"], "function": "double_even_numbers", "signature": "def double_even_numbers(numbers):", "score": 1.0, "domain": "generic"} {"id": "f2f87ae8eadbcdda514c892fc9ab7af9", "problem": "You are tasked with implementing a function `count_words(path, as_single_string=False)` that reads a text file from the given `path` and returns either a dictionary of word counts or a single string containing all words, depending on the `as_single_string` parameter. The function should handle multilingual text, recognizing words in various languages that may use different character sets, word boundaries, and punctuation.\n\n**Input:**\n- `path`: A string representing the file path to the text file.\n- `as_single_string`: A boolean flag. If `True`, the function should return a single string of all words separated by spaces. If `False`, it should return a dictionary where keys are words and values are their respective counts.\n\n**Output:**\n- If `as_single_string` is `True`, return a single string of all words.\n- If `as_single_string` is `False`, return a dictionary with word counts.\n\n**Sample Input:**\n- File `example.txt` contains:\n```\nBonjour, comment ça va?\n¡Hola! ¿Cómo estás?\nПривет, как дела?\n```\n\n**Sample Output:**\n- `count_words('example.txt', as_single_string=True)`\n```\nBonjour comment ça va Hola Cómo estás Привет как дела\n```\n\n- `count_words('example.txt', as_single_string=False)`\n```\n{'Bonjour': 1, 'comment': 1, 'ça': 1, 'va': 1, 'Hola': 1, 'Cómo': 1, 'estás': 1, 'Привет': 1, 'как': 1, 'дела': 1}\n```", "reference": "import re\nimport os\n\ndef count_words(path, as_single_string=False):\n \"\"\"\n Reads a text file and returns either a dictionary of word counts or a single string of all words.\n \n :param path: A string representing the file path to the text file.\n :param as_single_string: A boolean flag. If True, returns a single string of all words. If False, returns a dictionary of word counts.\n :return: A dictionary of word counts or a single string of all words.\n \"\"\"\n word_pattern = re.compile(r'\\w+', re.UNICODE)\n\n word_counts = {}\n all_text = ''\n\n try:\n with open(path, 'r', encoding='utf-8') as file:\n for line in file:\n words = word_pattern.findall(line)\n if not as_single_string:\n for word in words:\n word_counts[word] = word_counts.get(word, 0) + 1\n else:\n all_text += ' '.join(words) + ' '\n \n except FileNotFoundError:\n print(f'The file at {path} was not found.')\n return None\n except IOError:\n print(f'There was an error reading the file at {path}.')\n return None\n\n if as_single_string:\n return all_text.strip()\n\n return word_counts", "tests": ["assert count_words('test_file.txt', as_single_string=True) == \"hello world this is a test\"", "assert count_words('test_file.txt') == {'hello': 1, 'world': 1, 'this': 1, 'is': 1, 'a': 1, 'test': 1}", "assert count_words('non_existent_file.txt') is None", "assert count_words('empty_file.txt', as_single_string=True) == \"\"", "assert count_words('empty_file.txt') == {}", "assert count_words('file_with_punctuation.txt', as_single_string=True) == \"hello world this is a test\"", "assert count_words('file_with_punctuation.txt') == {'hello': 1, 'world': 1, 'this': 1, 'is': 1, 'a': 1, 'test': 1}", "assert count_words('file_with_unicode.txt', as_single_string=True) == \"hola mundo esto es una prueba\"", "assert count_words('file_with_unicode.txt') == {'hola': 1, 'mundo': 1, 'esto': 1, 'es': 1, 'una': 1, 'prueba': 1}", "assert count_words('file_with_multiline.txt', as_single_string=True) == \"hello world this is a test\""], "function": "count_words", "signature": "def count_words(path, as_single_string=False):", "score": 0.3, "domain": "generic"} {"id": "58a1bf1a20b2bcbeea01ad8bb8a50ecd", "problem": "You are tasked with implementing a function `calculate_discount` in Python. This function accepts two parameters: `price` (a floating-point number representing the original price of an item) and `discount_percentage` (a floating-point number representing the discount percentage to be applied). The function should compute and return the final price after applying the discount. If the `discount_percentage` is outside the valid range of 0 to 100 (inclusive), the function should raise a `ValueError` with the message \"Invalid discount percentage\". Your implementation should include appropriate type hints for the function parameters and return value.\n\n**Sample Input:**\n- `price = 100.0`, `discount_percentage = 20.0`\n- `price = 250.0`, `discount_percentage = 150.0`\n\n**Sample Output:**\n- `80.0`\n- Raises `ValueError` with message \"Invalid discount percentage\"", "reference": "def calculate_discount(price: float, discount_percentage: float) -> float:\n \"\"\"\n Calculate the discounted price of an item.\n\n Parameters:\n price (float): The original price of the item.\n discount_percentage (float): The discount percentage to be applied.\n\n Returns:\n float: The final price after applying the discount.\n\n Raises:\n ValueError: If the discount percentage is not between 0 and 100 (inclusive).\n \"\"\"\n if not (0 <= discount_percentage <= 100):\n raise ValueError(\"Invalid discount percentage\")\n \n discount_amount = (discount_percentage / 100) * price\n return price - discount_amount", "tests": ["assert calculate_discount(100.0, 10.0) == 90.0", "assert calculate_discount(200.0, 50.0) == 100.0", "assert calculate_discount(50.0, 0.0) == 50.0", "assert calculate_discount(150.0, 100.0) == 0.0", "assert calculate_discount(300.0, 25.0) == 225.0", "assert calculate_discount(1000.0, 20.0) == 800.0", "assert calculate_discount(75.0, 5.0) == 71.25", "assert calculate_discount(120.0, 30.0) == 84.0", "assert calculate_discount(100.0, -5.0) == ValueError(\"Invalid discount percentage\")", "assert calculate_discount(100.0, 105.0) == ValueError(\"Invalid discount percentage\")"], "function": "calculate_discount", "signature": "def calculate_discount(price: float, discount_percentage: float) -> float:", "score": 0.8, "domain": "generic"} {"id": "56e916add70eaa7418eade5ca6e15c77", "problem": "You are a financial trader considering two investment opportunities. Each investment has a specific probability of success, associated transaction fees, and expected return rate. Your goal is to allocate your capital between these two investments to maximize your potential return, taking into account the transaction fees. If the investments are not mutually exclusive (i.e., their combined probability of success does not equal 100%), return `None`. Otherwise, return the fraction of your capital that should be allocated to the first investment.\n\n**Input:**\n- `odds1`: A float representing the probability of success for the first investment (0 <= odds1 <= 1).\n- `fee1`: A float representing the transaction fee for the first investment (0 <= fee1 <= 1).\n- `return1`: A float representing the expected return rate for the first investment (0 <= return1).\n- `odds2`: A float representing the probability of success for the second investment (0 <= odds2 <= 1).\n- `fee2`: A float representing the transaction fee for the second investment (0 <= fee2 <= 1).\n- `return2`: A float representing the expected return rate for the second investment (0 <= return2).\n\n**Output:**\n- A float representing the fraction of capital to allocate to the first investment, or `None` if the investments are not mutually exclusive.\n\n**Sample Input:**\n```\nodds1 = 0.7, fee1 = 0.02, return1 = 0.15, odds2 = 0.3, fee2 = 0.01, return2 = 0.10\n```\n\n**Sample Output:**\n```\n0.8823529411764706\n```", "reference": "def optimal_investment_allocation(odds1, fee1, return1, odds2, fee2, return2):\n \"\"\"\n Calculate the optimal allocation of capital between two investments.\n\n Parameters:\n odds1 (float): Probability of success for the first investment.\n fee1 (float): Transaction fee for the first investment.\n return1 (float): Expected return rate for the first investment.\n odds2 (float): Probability of success for the second investment.\n fee2 (float): Transaction fee for the second investment.\n return2 (float): Expected return rate for the second investment.\n\n Returns:\n float or None: Fraction of capital to allocate to the first investment, or None if investments are not mutually exclusive.\n \"\"\"\n if odds1 + odds2 != 1.0:\n return None\n \n expected_return1 = odds1 * (return1 - fee1)\n expected_return2 = odds2 * (return2 - fee2)\n \n total_expected_return = expected_return1 + expected_return2\n \n if total_expected_return == 0:\n return None\n \n allocation1 = expected_return1 / total_expected_return\n \n return allocation1", "tests": ["assert optimal_investment_allocation(0.6, 0.02, 0.1, 0.4, 0.01, 0.05) == 0.8333333333333334", "assert optimal_investment_allocation(0.5, 0.01, 0.1, 0.5, 0.01, 0.1) == 0.5", "assert optimal_investment_allocation(0.7, 0.03, 0.15, 0.3, 0.02, 0.08) == 0.9230769230769231", "assert optimal_investment_allocation(0.3, 0.05, 0.1, 0.7, 0.04, 0.12) == 0.2857142857142857", "assert optimal_investment_allocation(0.5, 0.05, 0.1, 0.5, 0.05, 0.1) == 0.5", "assert optimal_investment_allocation(0.8, 0.02, 0.2, 0.2, 0.01, 0.05) == 0.9615384615384616", "assert optimal_investment_allocation(0.4, 0.03, 0.1, 0.6, 0.02, 0.1) == 0.3333333333333333", "assert optimal_investment_allocation(0.5, 0.05, 0.1, 0.5, 0.05, 0.05) == None", "assert optimal_investment_allocation(0.6, 0.02, 0.1, 0.4, 0.01, 0.05) == 0.8333333333333334", "assert optimal_investment_allocation(0.5, 0.05, 0.1, 0.55, 0.05, 0.1) == None"], "function": "optimal_investment_allocation", "signature": "def optimal_investment_allocation(odds1, fee1, return1, odds2, fee2, return2):", "score": 0.3, "domain": "generic"} {"id": "d923f9e7cd69c2883ac034dfdabb54bc", "problem": "You are given a set of distinct integers. Your task is to generate the power set of this set. The power set is defined as the set of all possible subsets, including the empty set and the set itself. Output the power set as a list of tuples, where each tuple represents a subset.\n\n**Input:**\n- A set of distinct integers.\n\n**Output:**\n- A list of tuples, where each tuple is a subset of the input set.\n\n**Sample Input:**\n```\n{1, 2, 3}\n```\n\n**Sample Output:**\n```\n[(), (1,), (2,), (3,), (1, 2), (1, 3), (2, 3), (1, 2, 3)]\n```", "reference": "def generate_power_set(input_set):\n \"\"\"\n Generate the power set of a given set of distinct integers.\n \n Parameters:\n input_set (set): A set of distinct integers.\n \n Returns:\n list: A list of tuples, where each tuple is a subset of the input set.\n \"\"\"\n if not input_set:\n return [()]\n \n elements = list(input_set)\n power_set_without_first = generate_power_set(set(elements[1:]))\n with_first = [(elements[0],) + subset for subset in power_set_without_first]\n \n return power_set_without_first + with_first\n\n# Example usage:\nexample_set = {1, 2, 3}\npower_set = generate_power_set(example_set)\nprint(power_set)", "tests": ["assert generate_power_set(set()) == [()]", "assert generate_power_set({1}) == [(), (1,)]", "assert generate_power_set({1, 2}) == [(), (2,), (1,), (1, 2)]", "assert generate_power_set({1, 2, 3}) == [(), (3,), (2,), (2, 3), (1,), (1, 3), (1, 2), (1, 2, 3)]", "assert generate_power_set({4, 5, 6}) == [(), (6,), (5,), (5, 6), (4,), (4, 6), (4, 5), (4, 5, 6)]", "assert generate_power_set({7, 8}) == [(), (8,), (7,), (7, 8)]", "assert generate_power_set({9}) == [(), (9,)]", "assert generate_power_set({10, 11, 12, 13}) == [(), (13,), (12,), (12, 13), (11,), (11, 13), (11, 12), (11, 12, 13), (10,), (10, 13), (10, 12), (10, 12, 13), (10, 11), (10, 11, 13), (10, 11, 12), (10, 11, 12, 13)]", "assert generate_power_set({14, 15, 16}) == [(), (16,), (15,), (15, 16), (14,), (14, 16), (14, 15), (14, 15, 16)]", "assert generate_power_set({17, 18, 19, 20, 21}) == [(), (21,), (20,), (20, 21), (19,), (19, 21), (19, 20), (19, 20, 21), (18,), (18, 21), (18, 20), (18, 20, 21), (18, 19), (18, 19, 21), (18, 19, 20), (18, 19, 20, 21), (17,), (17, 21), (17, 20), (17, 20, 21), (17, 19), (17, 19, 21), (17, 19, 20), (17, 19, 20, 21), (17, 18), (17, 18, 21), (17, 18, 20), (17, 18, 20, 21), (17, 18, 19), (17, 18, 19, 21), (17, 18, 19, 20), (17, 18, 19, 20, 21)]"], "function": "generate_power_set", "signature": "def generate_power_set(input_set):", "score": 0.8, "domain": "generic"} {"id": "165c22b4c9c36b77de97b9949f461402", "problem": "You are given a list of stock prices for a particular stock over a period of time. Your task is to write a function `analyze_stock_prices(prices)` that processes this list and returns a dictionary with the following keys:\n- `\"highest\"`: The highest stock price.\n- `\"lowest\"`: The lowest stock price.\n- `\"average\"`: The average stock price.\n- `\"range\"`: The difference between the highest and lowest stock prices.\n\n**Input:**\n- A list of integers or floats representing stock prices. The list may be empty.\n\n**Output:**\n- A dictionary with the keys `\"highest\"`, `\"lowest\"`, `\"average\"`, and `\"range\"`. If the list is empty, all values should be `None`.\n\n**Sample Input:**\n```python\n[100, 200, 150, 300, 250]\n```\n\n**Sample Output:**\n```python\n{\n \"highest\": 300,\n \"lowest\": 100,\n \"average\": 200.0,\n \"range\": 200\n}\n```", "reference": "def analyze_stock_prices(prices):\n \"\"\"\n Analyzes a list of stock prices and returns a dictionary containing the highest and lowest prices,\n the average price, and the price range (highest - lowest).\n\n :param prices: List of stock prices (integers or floats).\n :return: Dictionary with keys 'highest', 'lowest', 'average', and 'range'.\n \"\"\"\n if not prices:\n return {\n \"highest\": None,\n \"lowest\": None,\n \"average\": None,\n \"range\": None\n }\n \n highest = max(prices)\n lowest = min(prices)\n average = sum(prices) / len(prices)\n price_range = highest - lowest\n \n return {\n \"highest\": highest,\n \"lowest\": lowest,\n \"average\": average,\n \"range\": price_range\n }", "tests": ["assert analyze_stock_prices([100, 200, 300, 400, 500]) == {\"highest\": 500, \"lowest\": 100, \"average\": 300.0, \"range\": 400}", "assert analyze_stock_prices([10, 10, 10, 10]) == {\"highest\": 10, \"lowest\": 10, \"average\": 10.0, \"range\": 0}", "assert analyze_stock_prices([5, 15, 25, 35, 45, 55]) == {\"highest\": 55, \"lowest\": 5, \"average\": 30.0, \"range\": 50}", "assert analyze_stock_prices([1000]) == {\"highest\": 1000, \"lowest\": 1000, \"average\": 1000.0, \"range\": 0}", "assert analyze_stock_prices([]) == {\"highest\": None, \"lowest\": None, \"average\": None, \"range\": None}", "assert analyze_stock_prices([1.5, 2.5, 3.5, 4.5]) == {\"highest\": 4.5, \"lowest\": 1.5, \"average\": 3.0, \"range\": 3.0}", "assert analyze_stock_prices([100, 50, 200, 150]) == {\"highest\": 200, \"lowest\": 50, \"average\": 125.0, \"range\": 150}", "assert analyze_stock_prices([-10, -20, -30, -40]) == {\"highest\": -10, \"lowest\": -40, \"average\": -25.0, \"range\": 30}", "assert analyze_stock_prices([0, 0, 0, 0, 0]) == {\"highest\": 0, \"lowest\": 0, \"average\": 0.0, \"range\": 0}", "assert analyze_stock_prices([100, 200, 300, 400, 500, 600, 700, 800, 900, 1000]) == {\"highest\": 1000, \"lowest\": 100, \"average\": 550.0, \"range\": 900}"], "function": "analyze_stock_prices", "signature": "def analyze_stock_prices(prices):", "score": 1.0, "domain": "generic"} {"id": "1cba93f07e1d5ca93f5dde4ca2541f11", "problem": "You are tasked with writing a Python script that reads a CSV file named \"input.csv\" and converts it into a JSON file named \"output.json\". The script should be optimized for handling large CSV files efficiently and should include robust error handling for file operations. Your program should output a success message upon successful conversion. In case of errors, appropriate error messages should be displayed.\n\n**Sample Input:**\nAssume \"input.csv\" contains the following data:\n```\nname,age,city\nAlice,30,New York\nBob,25,Los Angeles\nCharlie,35,Chicago\n```\n\n**Sample Output:**\n```\nCSV file 'input.csv' is converted to JSON file 'output.json' successfully.\n```\n\n**Expected JSON Output in \"output.json\":**\n```json\n[\n {\"name\": \"Alice\", \"age\": \"30\", \"city\": \"New York\"},\n {\"name\": \"Bob\", \"age\": \"25\", \"city\": \"Los Angeles\"},\n {\"name\": \"Charlie\", \"age\": \"35\", \"city\": \"Chicago\"}\n]\n```", "reference": "import csv\nimport json\n\ndef csv_to_json(csv_file_path, json_file_path):\n \"\"\"\n Converts a CSV file to a JSON file.\n \n Args:\n csv_file_path (str): The path to the input CSV file.\n json_file_path (str): The path to the output JSON file.\n \n Returns:\n None\n \"\"\"\n try:\n with open(csv_file_path, mode='r', encoding='utf-8') as csv_file:\n csv_reader = csv.DictReader(csv_file)\n data = [row for row in csv_reader]\n \n with open(json_file_path, mode='w', encoding='utf-8') as json_file:\n json.dump(data, json_file, indent=4)\n \n print(f\"CSV file '{csv_file_path}' is converted to JSON file '{json_file_path}' successfully.\")\n \n except FileNotFoundError:\n print(f\"Error: The file '{csv_file_path}' was not found.\")\n except IOError:\n print(f\"Error: An error occurred while reading the file '{csv_file_path}' or writing to the file '{json_file_path}'.\")\n except Exception as e:\n print(f\"An unexpected error occurred: {str(e)}\")\n\ncsv_file_path = 'input.csv'\njson_file_path = 'output.json'\ncsv_to_json(csv_file_path, json_file_path)", "tests": ["assert csv_to_json(\"non_existent_file.csv\", \"output.json\") is None", "assert csv_to_json(\"input.csv\", \"output.json\") is None", "assert csv_to_json(\"\", \"output.json\") is None", "assert csv_to_json(\"input.csv\", \"\") is None", "assert csv_to_json(\"input.csv\", \"output\") is None", "assert csv_to_json(\"input.csv\", \"output.json\") is None", "assert csv_to_json(\"input.csv\", \"output.json\") is None", "assert csv_to_json(\"input.csv\", \"output.json\") is None", "assert csv_to_json(\"input.csv\", \"output.json\") is None", "assert csv_to_json(\"input.csv\", \"output.json\") is None"], "function": "csv_to_json", "signature": "def csv_to_json(csv_file_path, json_file_path):", "score": 1.0, "domain": "algorithmic"} {"id": "1bccaacb74bfc098c14e16f51a870e6c", "problem": "You are tasked with writing a Python script that processes a CSV file named `data.csv`. Your script should output the number of rows and columns in the file, excluding the header row. The CSV file is guaranteed to have a header row. Your program should handle potential errors such as the file not existing or being unreadable. \n\n**Sample Input:**\nAssume `data.csv` contains the following data:\n```\nName,Age,City\nAlice,30,New York\nBob,25,Los Angeles\nCharlie,35,Chicago\n```\n\n**Sample Output:**\n```\nThe CSV file has 3 rows and 3 columns.\n```", "reference": "import csv\n\ndef get_csv_dimensions(filename):\n \"\"\"\n Reads a CSV file and prints the number of rows and columns, excluding the header row.\n \n Args:\n filename (str): The name of the CSV file to read.\n \n Returns:\n None\n \"\"\"\n try:\n with open(filename, mode='r', newline='', encoding='utf-8') as file:\n reader = csv.reader(file)\n headers = next(reader) # Read the header row to identify columns\n row_count = sum(1 for row in reader) # Count remaining rows\n column_count = len(headers)\n print(f\"The CSV file has {row_count} rows and {column_count} columns.\")\n except FileNotFoundError:\n print(\"Error: The file was not found.\")\n except PermissionError:\n print(\"Error: You do not have the permissions to read the file.\")\n except Exception as e:\n print(f\"An unexpected error occurred: {e}\")\n\nget_csv_dimensions('data.csv')", "tests": ["assert get_csv_dimensions('non_existent_file.csv') is None", "assert get_csv_dimensions('data.csv') is None # Assuming 'data.csv' exists and is accessible", "assert get_csv_dimensions('empty_file.csv') is None # Assuming 'empty_file.csv' is an empty file", "assert get_csv_dimensions('single_row.csv') is None # Assuming 'single_row.csv' has only a header row", "assert get_csv_dimensions('single_column.csv') is None # Assuming 'single_column.csv' has only one column", "assert get_csv_dimensions('multiple_rows_columns.csv') is None # Assuming 'multiple_rows_columns.csv' has multiple rows and columns", "assert get_csv_dimensions('file_with_extra_newlines.csv') is None # Assuming 'file_with_extra_newlines.csv' has extra newlines", "assert get_csv_dimensions('file_with_special_chars.csv') is None # Assuming 'file_with_special_chars.csv' contains special characters", "assert get_csv_dimensions('file_with_missing_values.csv') is None # Assuming 'file_with_missing_values.csv' has missing values", "assert get_csv_dimensions('file_with_large_data.csv') is None # Assuming 'file_with_large_data.csv' is a large file"], "function": "get_csv_dimensions", "signature": "def get_csv_dimensions(filename):", "score": 1.0, "domain": "generic"} {"id": "0788e1c4a4f649f2ec70389a609a25a7", "problem": "You are given an array of integers `nums` and an integer `target`. Your task is to determine whether there exist two distinct elements in `nums` whose sum equals `target`. Return `True` if such a pair exists, otherwise return `False`.\n\n**Sample Input:**\n```\nnums = [2, 7, 11, 15]\ntarget = 9\n```\n\n**Sample Output:**\n```\nTrue\n```", "reference": "def has_pair_with_sum(nums, target):\n \"\"\"\n Determines if there are two distinct numbers in the list that add up to the target sum.\n\n :param nums: List of integers.\n :param target: Target sum to find in the list.\n :return: True if there exists a pair of numbers that add up to the target, False otherwise.\n \"\"\"\n seen = {}\n for num in nums:\n complement = target - num\n if complement in seen:\n return True\n seen[num] = True\n return False\n\n# Test the function\nnums = [2, 7, 11, 15]\ntarget = 9\nprint(has_pair_with_sum(nums, target)) # Output: True", "tests": ["assert has_pair_with_sum([2, 7, 11, 15], 9) == True", "assert has_pair_with_sum([3, 2, 4], 6) == True", "assert has_pair_with_sum([3, 3], 6) == True", "assert has_pair_with_sum([1, 2, 3, 9], 8) == False", "assert has_pair_with_sum([1, 2, 3, 4, 5], 10) == True", "assert has_pair_with_sum([1], 2) == False", "assert has_pair_with_sum([], 0) == False", "assert has_pair_with_sum([0, 0], 0) == True", "assert has_pair_with_sum([-1, -2, -3, -4], -6) == True", "assert has_pair_with_sum([100, 200, 300, 400], 500) == True"], "function": "has_pair_with_sum", "signature": "def has_pair_with_sum(nums, target):", "score": 0.9, "domain": "algorithmic"} {"id": "25a84d933d474aa2600638c5092d541a", "problem": "You are given a string representing a JSON configuration file. Your task is to write a Python function that parses this JSON string and returns a dictionary with all nested keys flattened into dot-separated keys. If the JSON string is invalid, your function should return an empty dictionary.\n\n**Input:**\n- A single string `json_data` representing the JSON configuration.\n\n**Output:**\n- A dictionary with flattened keys and their corresponding values.\n\n**Sample Input:**\n```json\n{\"settings\": {\"theme\": \"dark\", \"notifications\": {\"email\": true, \"sms\": false}}}\n```\n\n**Sample Output:**\n```python\n{'settings.theme': 'dark', 'settings.notifications.email': True, 'settings.notifications.sms': False}\n```", "reference": "import json\n\ndef flatten_json(y):\n \"\"\"\n Recursively flattens a nested dictionary into a single-level dictionary with dot-separated keys.\n \n :param y: The dictionary to flatten.\n :return: A flattened dictionary.\n \"\"\"\n out = {}\n\n def flatten(x, name=''):\n if isinstance(x, dict):\n for a in x:\n flatten(x[a], name + a + '.')\n elif isinstance(x, list):\n for i, a in enumerate(x):\n flatten(a, name + str(i) + '.')\n else:\n out[name[:-1]] = x\n\n flatten(y)\n return out\n\ndef parse_config(json_data):\n \"\"\"\n Parses a JSON string and returns a flattened dictionary of settings.\n Returns an empty dictionary if the JSON string is invalid.\n \n :param json_data: A string containing JSON data.\n :return: A dictionary with flattened keys and values.\n \"\"\"\n try:\n data = json.loads(json_data)\n return flatten_json(data)\n except json.JSONDecodeError:\n return {}\n\n# Example usage:\njson_data = '{\"settings\": {\"theme\": \"dark\", \"notifications\": {\"email\": true, \"sms\": false}}}'\nconfig = parse_config(json_data)\nprint(config)", "tests": ["assert parse_config('{\"key\": \"value\"}') == {\"key\": \"value\"}", "assert parse_config('{\"settings\": {\"theme\": \"dark\"}}') == {\"settings.theme\": \"dark\"}", "assert parse_config('{\"settings\": {\"theme\": \"dark\", \"notifications\": {\"email\": true, \"sms\": false}}}') == {\"settings.theme\": \"dark\", \"settings.notifications.email\": True, \"settings.notifications.sms\": False}", "assert parse_config('{\"list\": [1, 2, {\"nested\": \"value\"}]}') == {\"list0\": 1, \"list1\": 2, \"list2.nested\": \"value\"}", "assert parse_config('{\"empty\": {}}') == {}", "assert parse_config('{\"invalid\": \"json\"') == {}", "assert parse_config('') == {}", "assert parse_config('{\"numbers\": {\"int\": 123, \"float\": 456.789}}') == {\"numbers.int\": 123, \"numbers.float\": 456.789}", "assert parse_config('{\"bools\": {\"true\": true, \"false\": false}}') == {\"bools.true\": True, \"bools.false\": False}", "assert parse_config('{\"null\": null}') == {\"null\": None}"], "function": "parse_config", "signature": "def parse_config(json_data):", "score": 0.9, "domain": "generic"} {"id": "1b0fd4f5c040fb38241630406453d16a", "problem": "You are given a list of integers `numbers` and an integer `degree`. Your task is to generate a new list of integers that represents all possible products of the elements in `numbers` taken up to `degree` at a time. Each term in the resulting list is a product of the elements in `numbers` raised to some power, with the sum of the powers in each term being less than or equal to `degree`. The resulting list should be sorted in ascending order.\n\n**Input:**\n- A list of integers `numbers` (1 ≤ len(numbers) ≤ 5)\n- An integer `degree` (1 ≤ degree ≤ 5)\n\n**Output:**\n- A sorted list of integers representing all possible products of the elements in `numbers` taken up to `degree` at a time.\n\n**Sample Input:**\n```\nnumbers = [2, 3]\ndegree = 2\n```\n\n**Sample Output:**\n```\n[2, 3, 4, 6, 9]\n```", "reference": "from itertools import combinations_with_replacement\nfrom math import prod\n\ndef expand_to_products(numbers, degree):\n \"\"\"\n Generate a sorted list of all possible products of elements in `numbers`\n taken up to `degree` at a time.\n \n :param numbers: List of integers\n :param degree: Integer representing the maximum degree of the product terms\n :return: Sorted list of integers representing the products\n \"\"\"\n result = set() # Use a set to avoid duplicate products\n for r in range(1, degree + 1):\n for combo in combinations_with_replacement(numbers, r):\n product = prod(combo)\n result.add(product)\n return sorted(result)", "tests": ["assert expand_to_products([2, 3], 2) == [2, 3, 4, 6, 9]", "assert expand_to_products([1, 2], 3) == [1, 2, 4, 8]", "assert expand_to_products([5], 1) == [5]", "assert expand_to_products([2, 2], 2) == [2, 4]", "assert expand_to_products([1, 1, 1], 3) == [1]", "assert expand_to_products([3, 5, 7], 1) == [3, 5, 7]", "assert expand_to_products([2, 3, 5], 0) == []", "assert expand_to_products([], 2) == []", "assert expand_to_products([0, 1, 2], 2) == [0, 1, 2, 4]", "assert expand_to_products([2, 3, 5], 3) == [2, 3, 5, 4, 6, 8, 9, 10, 12, 15, 18, 20, 25, 27, 30, 45, 50, 60, 75, 90, 125, 135, 150, 180, 225, 270, 300, 375, 450, 675, 900]"], "function": "expand_to_products", "signature": "def expand_to_products(numbers, degree):", "score": 0.9, "domain": "generic"} {"id": "fa665af0cab13567e73a9bb11160ca8a", "problem": "You are given a list of tuples, where each tuple consists of a string and a corresponding weight. The weight signifies the importance or relevance of the string. Your task is to normalize these weights so that their sum equals 1, while preserving the original order of the tuples. The function should accept an optional transformation function that modifies the weights before normalization. The function should handle both integer and floating-point weights.\n\n**Input:**\n- A list of tuples `lst` where each tuple is of the form `(string, weight)`.\n- An optional function `transform` that takes a weight and returns a modified weight.\n\n**Output:**\n- A new list of tuples with the same strings and normalized weights.\n\n**Constraints:**\n- The list can contain up to 1000 tuples.\n- Weights can be integers or floating-point numbers.\n- The transformation function, if provided, should be applied to each weight before normalization.\n\n**Sample Input:**\n```python\nlst = [(\"apple\", 5), (\"banana\", 3), (\"cherry\", 7)]\n```\n\n**Sample Output:**\n```python\n[(\"apple\", 0.35714285714285715), (\"banana\", 0.21428571428571427), (\"cherry\", 0.42857142857142855)]\n```", "reference": "def normalize_weights(lst, transform=None):\n \"\"\"\n Normalize the weights in a list of tuples so that they sum up to 1.\n \n Parameters:\n lst (list of tuples): A list where each tuple contains a string and a weight.\n transform (function, optional): A function to modify each weight before normalization.\n \n Returns:\n list of tuples: A new list of tuples with the same strings and normalized weights.\n \"\"\"\n if transform is not None:\n weights = [transform(weight) for _, weight in lst]\n else:\n weights = [weight for _, weight in lst]\n \n total_weight = sum(weights)\n \n if total_weight == 0:\n return [(item, 0.0) for item, _ in lst]\n \n normalized_lst = [(item, weight / total_weight) for (item, _), weight in zip(lst, weights)]\n \n return normalized_lst", "tests": ["assert normalize_weights([(\"apple\", 5), (\"banana\", 3), (\"cherry\", 7)]) == [(\"apple\", 0.35714285714285715), (\"banana\", 0.21428571428571427), (\"cherry\", 0.42857142857142855)]", "assert normalize_weights([(\"apple\", 1), (\"banana\", 1), (\"cherry\", 1)]) == [(\"apple\", 0.3333333333333333), (\"banana\", 0.3333333333333333), (\"cherry\", 0.3333333333333333)]", "assert normalize_weights([(\"apple\", 0), (\"banana\", 0), (\"cherry\", 0)]) == [(\"apple\", 0.0), (\"banana\", 0.0), (\"cherry\", 0.0)]", "assert normalize_weights([(\"apple\", 10), (\"banana\", 20), (\"cherry\", 30)]) == [(\"apple\", 0.16666666666666666), (\"banana\", 0.3333333333333333), (\"cherry\", 0.5)]", "assert normalize_weights([(\"apple\", 5.5), (\"banana\", 3.3), (\"cherry\", 1.2)]) == [(\"apple\", 0.6875), (\"banana\", 0.4125), (\"cherry\", 0.15)]", "assert normalize_weights([(\"apple\", 100)]) == [(\"apple\", 1.0)]", "assert normalize_weights([], lambda x: x * 2) == []", "assert normalize_weights([(\"apple\", 5), (\"banana\", 3), (\"cherry\", 7)], lambda x: x * 2) == [(\"apple\", 0.35714285714285715), (\"banana\", 0.21428571428571427), (\"cherry\", 0.42857142857142855)]", "assert normalize_weights([(\"apple\", 5), (\"banana\", 3), (\"cherry\", 7)], lambda x: x - 2) == [(\"apple\", 0.5), (\"banana\", 0.25), (\"cherry\", 0.75)]", "assert normalize_weights([(\"apple\", 5), (\"banana\", 3), (\"cherry\", 7)], lambda x: x ** 2) == [(\"apple\", 0.4117647058823529), (\"banana\", 0.17647058823529413), (\"cherry\", 0.4117647058823529)]"], "function": "normalize_weights", "signature": "def normalize_weights(lst, transform=None):", "score": 0.5, "domain": "generic"} {"id": "5bd9248b2a1cd0d457ec6b4f672f607c", "problem": "You are given an even-length list of integers `data`. Your task is to implement a function `find_range_difference(data)` that computes the absolute difference between the range of the first half and the range of the second half of the list. The range of a list is defined as the difference between the maximum and minimum values in the list.\n\n**Input:**\n- A list of integers `data` with an even number of elements (2 ≤ len(data) ≤ 10^4).\n\n**Output:**\n- An integer representing the absolute difference between the range of the first half and the range of the second half of the list.\n\n**Sample Input:**\n```python\ndata = [1, 3, 5, 7, 9, 11]\n```\n\n**Sample Output:**\n```python\n0\n```\n\n**Sample Input:**\n```python\ndata = [10, 20, 30, 40, 50, 60]\n```\n\n**Sample Output:**\n```python\n0\n```\n\n**Sample Input:**\n```python\ndata = [1, 2, 3, 4, 5, 6]\n```\n\n**Sample Output:**\n```python\n0\n```\n\n**Sample Input:**\n```python\ndata = [1, 6, 3, 8, 5, 10]\n```\n\n**Sample Output:**\n```python\n3\n```", "reference": "def find_range_difference(data):\n \"\"\"\n Computes the absolute difference between the range of the first half\n and the range of the second half of the list.\n\n Parameters:\n data (list of int): A list of integers with an even number of elements.\n\n Returns:\n int: The absolute difference between the range of the first half and the range of the second half.\n \"\"\"\n def range_difference(lst):\n return max(lst) - min(lst) if lst else 0\n \n mid = len(data) // 2\n first_half = data[:mid]\n second_half = data[mid:]\n \n return abs(range_difference(first_half) - range_difference(second_half))", "tests": ["assert find_range_difference([1, 2, 3, 4]) == 0", "assert find_range_difference([1, 3, 5, 7]) == 2", "assert find_range_difference([10, 20, 30, 40, 50, 60]) == 20", "assert find_range_difference([1, 1, 1, 1, 1, 1]) == 0", "assert find_range_difference([-1, -2, -3, -4, -5, -6]) == 2", "assert find_range_difference([100, 200, 300, 400, 500, 600]) == 200", "assert find_range_difference([1, 2, 3, 4, 5, 6, 7, 8]) == 0", "assert find_range_difference([1, 2, 3, 4, 5, 6, 7, 9]) == 2", "assert find_range_difference([1, 2, 3, 4, 5, 6, 7, 10]) == 3", "assert find_range_difference([1, 2, 3, 4, 5, 6, 7, 11]) == 4"], "function": "find_range_difference", "signature": "def find_range_difference(data):", "score": 0.3, "domain": "generic"} {"id": "5373fe6f49a61becf319b9100e1b7ff6", "problem": "You are given a string `s` consisting of uppercase and lowercase English letters. Your task is to convert this string into snake case. In snake case, all letters should be in lowercase and words should be separated by underscores. Words are defined as contiguous sequences of uppercase letters followed by lowercase letters or sequences of lowercase letters.\n\n**Input:**\n- A single string `s` (1 ≤ |s| ≤ 100).\n\n**Output:**\n- A single string representing the snake case version of `s`.\n\n**Sample Input:**\n```\nThisIsTheExampleString\n```\n\n**Sample Output:**\n```\nthis_is_the_example_string\n```", "reference": "def convert_to_snake_case(s):\n \"\"\"\n Convert a given string to snake case.\n \n Parameters:\n s (str): The input string to be converted.\n \n Returns:\n str: The string converted to snake case.\n \"\"\"\n import re\n s = re.sub(r'(? nums[j] and dp[i] < dp[j] + 1:\n dp[i] = dp[j] + 1\n prev_index[i] = j\n if dp[i] > max_length:\n max_length = dp[i]\n max_index = i\n\n lis = []\n while max_index != -1:\n lis.append(nums[max_index])\n max_index = prev_index[max_index]\n\n return lis[::-1]", "tests": ["assert longest_increasing_subsequence([10, 22, 9, 33, 21, 50, 41, 60, 80]) == [10, 22, 33, 50, 60, 80]", "assert longest_increasing_subsequence([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]", "assert longest_increasing_subsequence([5, 4, 3, 2, 1]) == [5]", "assert longest_increasing_subsequence([1, 3, 5, 4, 7]) == [1, 3, 5, 7]", "assert longest_increasing_subsequence([10, 9, 2, 5, 3, 7, 101, 18]) == [2, 3, 7, 18]", "assert longest_increasing_subsequence([0, 1, 0, 3, 2, 3]) == [0, 1, 2, 3]", "assert longest_increasing_subsequence([7, 7, 7, 7, 7]) == [7]", "assert longest_increasing_subsequence([]) == []", "assert longest_increasing_subsequence([1]) == [1]", "assert longest_increasing_subsequence([3, 1, 2]) == [1, 2]"], "function": "longest_increasing_subsequence", "signature": "def longest_increasing_subsequence(nums):", "score": 0.9, "domain": "generic"} {"id": "c086e52db017bd97c05b9c75ba7736b4", "problem": "You are given a doubly linked list where each node contains a single integer value. Implement a function `modify_doubly_linked_list` that traverses the list and modifies each node's value according to the following rules:\n\n- Replace the value with \"FooBar\" if it is a prime number less than 100.\n- Replace the value with \"Foo\" if it is a prime number.\n- Replace the value with \"Bar\" if it is a perfect square.\n- Leave the value unchanged if it does not meet any of the above conditions.\n\nThe function should return the modified doubly linked list.\n\n**Input:**\n- A doubly linked list represented by its head node.\n\n**Output:**\n- The head node of the modified doubly linked list.\n\n**Sample Input:**\n```\n9 -> 10 -> 11 -> 16 -> 97 -> 100\n```\n\n**Sample Output:**\n```\nBar 10 FooBar Bar FooBar 100\n```", "reference": "class Node:\n def __init__(self, value):\n self.value = value\n self.prev = None\n self.next = None\n\ndef is_prime(n):\n \"\"\"Check if a number is a prime number.\"\"\"\n if n <= 1:\n return False\n for i in range(2, int(n**0.5) + 1):\n if n % i == 0:\n return False\n return True\n\ndef is_perfect_square(n):\n \"\"\"Check if a number is a perfect square.\"\"\"\n return int(n**0.5)**2 == n\n\ndef modify_doubly_linked_list(head):\n \"\"\"Modify the doubly linked list based on the given rules.\"\"\"\n current = head\n while current:\n if is_prime(current.value) and current.value < 100:\n current.value = \"FooBar\"\n elif is_prime(current.value):\n current.value = \"Foo\"\n elif is_perfect_square(current.value):\n current.value = \"Bar\"\n current = current.next\n return head\n\n# Example usage:\n# Creating a doubly linked list: 9 -> 10 -> 11 -> 16 -> 97 -> 100\nhead = Node(9)\nnode2 = Node(10)\nnode3 = Node(11)\nnode4 = Node(16)\nnode5 = Node(97)\nnode6 = Node(100)\n\nhead.next = node2\nnode2.prev = head\nnode2.next = node3\nnode3.prev = node2\nnode3.next = node4\nnode4.prev = node3\nnode4.next = node5\nnode5.prev = node4\nnode5.next = node6\nnode6.prev = node5\n\nmodified_head = modify_doubly_linked_list(head)\n\n# Printing the modified doubly linked list values\ncurrent = modified_head\nwhile current:\n print(current.value, end=\" \")\n current = current.next", "tests": ["assert modify_doubly_linked_list(Node(2)).value == \"FooBar\"", "assert modify_doubly_linked_list(Node(101)).value == \"Foo\"", "assert modify_doubly_linked_list(Node(16)).value == \"Bar\"", "assert modify_doubly_linked_list(Node(10)).value == 10", "assert modify_doubly_linked_list(Node(97)).value == \"FooBar\"", "assert modify_doubly_linked_list(Node(100)).value == \"Bar\"", "assert modify_doubly_linked_list(Node(1)).value == 1", "assert modify_doubly_linked_list(Node(0)).value == 0", "assert modify_doubly_linked_list(Node(49)).value == \"Bar\"", "assert modify_doubly_linked_list(Node(144)).value == \"Bar\""], "function": "modify_doubly_linked_list", "signature": "def modify_doubly_linked_list(head):", "score": 0.8, "domain": "generic"} {"id": "2e0335b8e06d2e3069ba37c675b9ee08", "problem": "You are given a dataset representing daily sales figures for a small bookstore. The dataset is structured as a list of tuples, where each tuple contains three elements: the date (as a string), the number of books sold (as an integer), and the total revenue (as a float). Your task is to implement a function `analyze_sales(data)` that computes and returns a dictionary with the following statistics:\n- `total_books_sold`: The total number of books sold over all days.\n- `total_revenue`: The total revenue generated over all days.\n- `average_revenue_per_book`: The average revenue per book sold. If no books were sold, this value should be 0.\n- `average_books_sold_per_day`: The average number of books sold per day.\n- `average_revenue_per_day`: The average revenue generated per day.\n\n**Input:**\n- A list of tuples, where each tuple is structured as `(date, books_sold, revenue)`.\n\n**Output:**\n- A dictionary with the keys `total_books_sold`, `total_revenue`, `average_revenue_per_book`, `average_books_sold_per_day`, and `average_revenue_per_day`.\n\n**Sample Input:**\n```python\ndata = [(\"2022-01-01\", 20, 100.00), (\"2022-01-02\", 15, 75.00), (\"2022-01-03\", 25, 125.00)]\n```\n\n**Sample Output:**\n```python\n{\n \"total_books_sold\": 60,\n \"total_revenue\": 300.0,\n \"average_revenue_per_book\": 5.0,\n \"average_books_sold_per_day\": 20.0,\n \"average_revenue_per_day\": 100.0\n}\n```", "reference": "def analyze_sales(data):\n \"\"\"\n Analyzes the sales data to compute total books sold, total revenue,\n average revenue per book, average books sold per day, and average revenue per day.\n\n Parameters:\n data (list of tuples): A list where each tuple contains (date, books_sold, revenue).\n\n Returns:\n dict: A dictionary with keys 'total_books_sold', 'total_revenue', \n 'average_revenue_per_book', 'average_books_sold_per_day', and 'average_revenue_per_day'.\n \"\"\"\n total_books_sold = 0\n total_revenue = 0.0\n total_days = len(data)\n\n for entry in data:\n _, books_sold, revenue = entry\n total_books_sold += books_sold\n total_revenue += revenue\n\n average_revenue_per_book = total_revenue / total_books_sold if total_books_sold != 0 else 0\n average_books_sold_per_day = total_books_sold / total_days\n average_revenue_per_day = total_revenue / total_days\n\n return {\n \"total_books_sold\": total_books_sold,\n \"total_revenue\": total_revenue,\n \"average_revenue_per_book\": average_revenue_per_book,\n \"average_books_sold_per_day\": average_books_sold_per_day,\n \"average_revenue_per_day\": average_revenue_per_day\n }\n\n# Example usage:\ndata = [(\"2022-01-01\", 20, 100.00), (\"2022-01-02\", 15, 75.00), (\"2022-01-03\", 25, 125.00)]\nstats = analyze_sales(data)\nprint(stats)", "tests": ["assert analyze_sales([(\"2022-01-01\", 20, 100.00), (\"2022-01-02\", 15, 75.00), (\"2022-01-03\", 25, 125.00)]) == {\"total_books_sold\": 60, \"total_revenue\": 300.00, \"average_revenue_per_book\": 5.0, \"average_books_sold_per_day\": 20.0, \"average_revenue_per_day\": 100.0}", "assert analyze_sales([(\"2022-01-01\", 0, 0.00)]) == {\"total_books_sold\": 0, \"total_revenue\": 0.00, \"average_revenue_per_book\": 0, \"average_books_sold_per_day\": 0.0, \"average_revenue_per_day\": 0.0}", "assert analyze_sales([(\"2022-01-01\", 10, 100.00), (\"2022-01-02\", 20, 200.00)]) == {\"total_books_sold\": 30, \"total_revenue\": 300.00, \"average_revenue_per_book\": 10.0, \"average_books_sold_per_day\": 15.0, \"average_revenue_per_day\": 150.0}", "assert analyze_sales([]) == {\"total_books_sold\": 0, \"total_revenue\": 0.00, \"average_revenue_per_book\": 0, \"average_books_sold_per_day\": 0.0, \"average_revenue_per_day\": 0.0}", "assert analyze_sales([(\"2022-01-01\", 5, 50.00), (\"2022-01-02\", 5, 50.00), (\"2022-01-03\", 5, 50.00)]) == {\"total_books_sold\": 15, \"total_revenue\": 150.00, \"average_revenue_per_book\": 10.0, \"average_books_sold_per_day\": 5.0, \"average_revenue_per_day\": 50.0}", "assert analyze_sales([(\"2022-01-01\", 100, 1000.00)]) == {\"total_books_sold\": 100, \"total_revenue\": 1000.00, \"average_revenue_per_book\": 10.0, \"average_books_sold_per_day\": 100.0, \"average_revenue_per_day\": 1000.0}", "assert analyze_sales([(\"2022-01-01\", 1, 10.00), (\"2022-01-02\", 2, 20.00), (\"2022-01-03\", 3, 30.00), (\"2022-01-04\", 4, 40.00)]) == {\"total_books_sold\": 10, \"total_revenue\": 100.00, \"average_revenue_per_book\": 10.0, \"average_books_sold_per_day\": 2.5, \"average_revenue_per_day\": 25.0}", "assert analyze_sales([(\"2022-01-01\", 10, 100.00), (\"2022-01-02\", 0, 0.00), (\"2022-01-03\", 10, 100.00)]) == {\"total_books_sold\": 20, \"total_revenue\": 200.00, \"average_revenue_per_book\": 10.0, \"average_books_sold_per_day\": 6.666666666666667, \"average_revenue_per_day\": 66.66666666666667}", "assert analyze_sales([(\"2022-01-01\", 1, 100.00), (\"2022-01-02\", 1, 200.00), (\"2022-01-03\", 1, 300.00)]) == {\"total_books_sold\": 3, \"total_revenue\": 600.00, \"average_revenue_per_book\": 200.0, \"average_books_sold_per_day\": 1.0, \"average_revenue_per_day\": 200.0}", "assert analyze_sales([(\"2022-01-01\", 10, 100.00), (\"2022-01-02\", 20, 200.00), (\"2022-01-03\", 30, 300.00), (\"2022-01-04\", 40, 400.00), (\"2022-01-05\", 50, 500.00)]) == {\"total_books_sold\": 150, \"total_revenue\": 1500.00, \"average_revenue_per_book\": 10.0, \"average_books_sold_per_day\": 30.0, \"average_revenue_per_day\": 300.0}"], "function": "analyze_sales", "signature": "def analyze_sales(data):", "score": 0.9, "domain": "generic"} {"id": "7507bcf9df38a06c4140d6c80db3fbac", "problem": "You are given a string `text` containing a mix of characters. Your task is to write a Python function `extract_emails` that identifies and returns all valid email addresses found within the string. An email address is defined as a sequence of characters that matches the following pattern: one or more alphanumeric characters, dots, underscores, plus signs, or hyphens, followed by an '@' symbol, then one or more alphanumeric characters or hyphens, a dot, and finally one or more alphanumeric characters or dots. \n\n**Input:**\n- A single string `text` (1 ≤ len(text) ≤ 10^4).\n\n**Output:**\n- A list of strings, each representing a valid email address found in the input string. The order of emails in the output list should match their order of appearance in the input string.\n\n**Sample Input:**\n```\n\"Contact us at example@example.com or support@sub.example.com\"\n```\n\n**Sample Output:**\n```\n['example@example.com', 'support@sub.example.com']\n```", "reference": "import re\n\ndef extract_emails(text):\n \"\"\"\n Extracts all valid email addresses from the given text.\n\n :param text: A string containing a mix of characters.\n :return: A list of strings, each representing a valid email address.\n \"\"\"\n email_pattern = r'[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+'\n return re.findall(email_pattern, text)\n\n# Example usage:\n# print(extract_emails(\"Contact us at example@example.com or support@sub.example.com\"))", "tests": ["assert extract_emails(\"Contact us at example@example.com or support@sub.example.com\") == [\"example@example.com\", \"support@sub.example.com\"]", "assert extract_emails(\"No emails here!\") == []", "assert extract_emails(\"user.name+tag+sorting@example.com\") == [\"user.name+tag+sorting@example.com\"]", "assert extract_emails(\"user@sub.example.com\") == [\"user@sub.example.com\"]", "assert extract_emails(\"user@123.123.123.123\") == [\"user@123.123.123.123\"]", "assert extract_emails(\"Multiple emails: test1@test.com, test2@test.co.uk, test3@sub.test.org\") == [\"test1@test.com\", \"test2@test.co.uk\", \"test3@sub.test.org\"]", "assert extract_emails(\"Invalid email: @example.com\") == []", "assert extract_emails(\"Another invalid: user@.com\") == []", "assert extract_emails(\"Mixed with numbers: user123@domain123.com\") == [\"user123@domain123.com\"]", "assert extract_emails(\"Edge case: user@domain.c\") == [\"user@domain.c\"]"], "function": "extract_emails", "signature": "def extract_emails(text):", "score": 1.0, "domain": "generic"} {"id": "4be33f41154faeecec7c4608ae72f404", "problem": "You are given a string `s` and a delimiter `d`. Your task is to implement a function `split_string` that splits the string `s` into a list of substrings using the delimiter `d`. If the delimiter `d` is not present in the string `s`, the function should return a list containing the original string `s` as the only element.\n\n**Input:**\n- The function `split_string` takes two parameters:\n - `s`: A string (1 ≤ |s| ≤ 1000) consisting of alphanumeric characters and possibly some special characters.\n - `d`: A string (1 ≤ |d| ≤ 10) that represents the delimiter.\n\n**Output:**\n- Return a list of substrings obtained by splitting the string `s` using the delimiter `d`. If `d` is not found in `s`, return a list containing `s` as the only element.\n\n**Sample Input 1:**\n```\ns = \"apple,banana,cherry\"\nd = \",\"\n```\n**Sample Output 1:**\n```\n[\"apple\", \"banana\", \"cherry\"]\n```\n\n**Sample Input 2:**\n```\ns = \"hello world\"\nd = \"-\"\n```\n**Sample Output 2:**\n```\n[\"hello world\"]\n```", "reference": "def split_string(s, delimiter):\n \"\"\"\n Splits the string s into a list of substrings using the delimiter d.\n If the delimiter d is not present in the string s, returns a list containing s as the only element.\n\n :param s: The input string to be split.\n :param delimiter: The delimiter used to split the string.\n :return: A list of substrings or the original string in a list if delimiter is not found.\n \"\"\"\n return s.split(delimiter) if delimiter in s else [s]", "tests": ["assert split_string(\"apple,banana,cherry\", \",\") == [\"apple\", \"banana\", \"cherry\"]", "assert split_string(\"hello world\", \" \") == [\"hello\", \"world\"]", "assert split_string(\"one,two,three,four\", \",\") == [\"one\", \"two\", \"three\", \"four\"]", "assert split_string(\"no delimiter here\", \"-\") == [\"no delimiter here\"]", "assert split_string(\"singleword\", \"word\") == [\"single\", \"\"]", "assert split_string(\"a,b,c,d,e\", \",\") == [\"a\", \"b\", \"c\", \"d\", \"e\"]", "assert split_string(\"test\", \"test\") == [\"\", \"\"]", "assert split_string(\"multiple,,,commas\", \",\") == [\"multiple\", \"\", \"\", \"commas\"]", "assert split_string(\"\", \",\") == [\"\"]", "assert split_string(\"same,same,same\", \"same\") == [\"\", \",\", \",\", \"\"]"], "function": "split_string", "signature": "def split_string(s, delimiter):", "score": 1.0, "domain": "generic"} {"id": "e83eef06e438f271bc13c4c3004c3b0a", "problem": "You are given a dataset consisting of 1000 data points, each represented as a tuple (x, y) where x and y are floating-point numbers. Your task is to implement a function `split_dataset` that takes this dataset and a parameter `split_ratio` as input and returns two separate datasets: a training dataset and a validation dataset.\n\nThe `split_ratio` parameter is a floating-point number between 0 and 1, indicating the proportion of the original dataset that should be allocated to the validation dataset. The remaining data points should form the training dataset.\n\nThe function must ensure that the data points are split while maintaining their original order and that the number of unique x-values in the training dataset is at least 75% of the total number of unique x-values in the original dataset.\n\n**Input:**\n- A list of tuples `dataset` of length 1000, where each tuple contains two floating-point numbers.\n- A floating-point number `split_ratio` between 0 and 1.\n\n**Output:**\n- A tuple containing two lists: the training dataset and the validation dataset.\n\n**Sample Input:**\n```python\ndataset = [(1.0, 2.0), (2.0, 3.0), (1.0, 4.0), (3.0, 5.0), (4.0, 6.0)]\nsplit_ratio = 0.4\n```\n\n**Sample Output:**\n```python\n([(1.0, 2.0), (2.0, 3.0), (1.0, 4.0)], [(3.0, 5.0), (4.0, 6.0)])\n```", "reference": "import math\n\ndef split_dataset(dataset, split_ratio):\n \"\"\"\n Splits the dataset into training and validation datasets based on the given split_ratio.\n Ensures that the training dataset contains at least 75% of the unique x-values from the original dataset.\n \n Parameters:\n dataset (list of tuples): The original dataset of data points.\n split_ratio (float): The proportion of the dataset to be used for validation.\n \n Returns:\n tuple: A tuple containing the training dataset and the validation dataset.\n \"\"\"\n total_data_points = len(dataset)\n val_data_points = math.ceil(total_data_points * split_ratio)\n train_data_points = total_data_points - val_data_points\n \n unique_x = list({point[0] for point in dataset})\n min_unique_x_train = math.ceil(len(unique_x) * 0.75)\n \n if val_data_points > 0:\n while len(set([point[0] for point in dataset[:train_data_points]])) < min_unique_x_train:\n train_data_points -= 1\n val_data_points += 1\n \n train_dataset = dataset[:train_data_points]\n val_dataset = dataset[train_data_points:]\n \n return train_dataset, val_dataset", "tests": ["assert split_dataset([(1.0, 2.0), (2.0, 3.0), (3.0, 4.0), (4.0, 5.0)], 0.25) == ([(1.0, 2.0), (2.0, 3.0), (3.0, 4.0)], [(4.0, 5.0)])", "assert split_dataset([(1.0, 2.0), (2.0, 3.0), (3.0, 4.0), (4.0, 5.0)], 0.5) == ([(1.0, 2.0), (2.0, 3.0)], [(3.0, 4.0), (4.0, 5.0)])", "assert split_dataset([(1.0, 2.0), (1.0, 3.0), (2.0, 4.0), (2.0, 5.0)], 0.5) == ([(1.0, 2.0), (1.0, 3.0), (2.0, 4.0)], [(2.0, 5.0)])", "assert split_dataset([(1.0, 2.0), (2.0, 3.0), (3.0, 4.0), (4.0, 5.0)], 0.0) == ([(1.0, 2.0), (2.0, 3.0), (3.0, 4.0), (4.0, 5.0)], [])", "assert split_dataset([(1.0, 2.0), (2.0, 3.0), (3.0, 4.0), (4.0, 5.0)], 1.0) == ([], [(1.0, 2.0), (2.0, 3.0), (3.0, 4.0), (4.0, 5.0)])", "assert split_dataset([(1.0, 2.0), (2.0, 3.0), (3.0, 4.0), (4.0, 5.0), (5.0, 6.0)], 0.4) == ([(1.0, 2.0), (2.0, 3.0), (3.0, 4.0)], [(4.0, 5.0), (5.0, 6.0)])", "assert split_dataset([(1.0, 2.0), (1.0, 3.0), (2.0, 4.0), (2.0, 5.0), (3.0, 6.0)], 0.4) == ([(1.0, 2.0), (1.0, 3.0), (2.0, 4.0)], [(2.0, 5.0), (3.0, 6.0)])", "assert split_dataset([(1.0, 2.0), (2.0, 3.0), (3.0, 4.0), (4.0, 5.0), (5.0, 6.0), (6.0, 7.0)], 0.33) == ([(1.0, 2.0), (2.0, 3.0), (3.0, 4.0)], [(4.0, 5.0), (5.0, 6.0), (6.0, 7.0)])", "assert split_dataset([(1.0, 2.0), (2.0, 3.0), (3.0, 4.0), (4.0, 5.0), (5.0, 6.0), (6.0, 7.0), (7.0, 8.0)], 0.28) == ([(1.0, 2.0), (2.0, 3.0), (3.0, 4.0), (4.0, 5.0)], [(5.0, 6.0), (6.0, 7.0), (7.0, 8.0)])", "assert split_dataset([(1.0, 2.0), (1.0, 3.0), (2.0, 4.0), (2.0, 5.0), (3.0, 6.0), (3.0, 7.0), (4.0, 8.0)], 0.28) == ([(1.0, 2.0), (1.0, 3.0), (2.0, 4.0), (2.0, 5.0)], [(3.0, 6.0), (3.0, 7.0), (4.0, 8.0)])"], "function": "split_dataset", "signature": "def split_dataset(dataset, split_ratio):", "score": 0.3, "domain": "generic"} {"id": "6f5892b786715c71cbc747e863597611", "problem": "You are given a list of integers. Your task is to implement a function `sum_of_squares` that calculates and returns the sum of the squares of the integers in the list. The function should handle both positive and negative integers.\n\n**Input:**\n- A list of integers `numbers` (1 ≤ len(numbers) ≤ 1000, -1000 ≤ numbers[i] ≤ 1000).\n\n**Output:**\n- An integer representing the sum of the squares of the integers in the list.\n\n**Sample Input:**\n- `[1, 2, 3]`\n- `[4, 5, 6]`\n- `[-1, -2, -3]`\n\n**Sample Output:**\n- `14`\n- `77`\n- `14`", "reference": "def sum_of_squares(numbers):\n \"\"\"\n Calculate the sum of the squares of the integers in the list.\n\n :param numbers: List of integers\n :return: Sum of the squares of the integers\n \"\"\"\n return sum(x**2 for x in numbers)\n\n# Test examples\nprint(sum_of_squares([1, 2, 3])) # Output: 14\nprint(sum_of_squares([4, 5, 6])) # Output: 77\nprint(sum_of_squares([-1, -2, -3])) # Output: 14", "tests": ["assert sum_of_squares([1, 2, 3]) == 14", "assert sum_of_squares([4, 5, 6]) == 77", "assert sum_of_squares([-1, -2, -3]) == 14", "assert sum_of_squares([0, 0, 0]) == 0", "assert sum_of_squares([10, 10, 10]) == 300", "assert sum_of_squares([-10, -10, -10]) == 300", "assert sum_of_squares([1, -1, 1, -1]) == 4", "assert sum_of_squares([]) == 0", "assert sum_of_squares([5]) == 25", "assert sum_of_squares([-5]) == 25"], "function": "sum_of_squares", "signature": "def sum_of_squares(numbers):", "score": 1.0, "domain": "generic"} {"id": "b9b62e49db16951f859f73e4a119bfc5", "problem": "You are given a string `s` of length `n` (1 ≤ n ≤ 10^5) representing a DNA sequence consisting of the nucleotides 'A', 'T', 'C', and 'G'. Your task is to count the occurrences of each nucleotide in the sequence and return a dictionary with the nucleotides as keys and their counts as values.\n\n**Sample Input:**\n```\nAGCTATAG\n```\n\n**Sample Output:**\n```\n{'A': 3, 'G': 2, 'C': 1, 'T': 2}\n```", "reference": "def count_nucleotides(s):\n \"\"\"\n Counts the occurrences of each nucleotide in a given DNA sequence.\n\n Parameters:\n s (str): A string representing the DNA sequence.\n\n Returns:\n dict: A dictionary with nucleotides as keys and their counts as values.\n \"\"\"\n # Initialize a dictionary to hold the count of each nucleotide\n nucleotide_counts = {'A': 0, 'T': 0, 'C': 0, 'G': 0}\n \n # Iterate through each nucleotide in the DNA sequence\n for nucleotide in s:\n # Increment the count of the nucleotide in the dictionary\n if nucleotide in nucleotide_counts:\n nucleotide_counts[nucleotide] += 1\n \n return nucleotide_counts\n\n# Example usage\ns = \"AGCTATAG\"\nprint(count_nucleotides(s)) # Output: {'A': 3, 'G': 2, 'C': 1, 'T': 2}", "tests": ["assert count_nucleotides(\"AGCTATAG\") == {'A': 3, 'G': 2, 'C': 1, 'T': 2}", "assert count_nucleotides(\"AAAAAAAA\") == {'A': 8, 'G': 0, 'C': 0, 'T': 0}", "assert count_nucleotides(\"GGGGGGGG\") == {'A': 0, 'G': 8, 'C': 0, 'T': 0}", "assert count_nucleotides(\"CCCCCCCC\") == {'A': 0, 'G': 0, 'C': 8, 'T': 0}", "assert count_nucleotides(\"TTTTTTTT\") == {'A': 0, 'G': 0, 'C': 0, 'T': 8}", "assert count_nucleotides(\"ATCG\") == {'A': 1, 'G': 1, 'C': 1, 'T': 1}", "assert count_nucleotides(\"\") == {'A': 0, 'G': 0, 'C': 0, 'T': 0}", "assert count_nucleotides(\"ACGTACGTACGT\") == {'A': 3, 'G': 3, 'C': 3, 'T': 3}", "assert count_nucleotides(\"AGCT\") == {'A': 1, 'G': 1, 'C': 1, 'T': 1}", "assert count_nucleotides(\"TACGCGTACG\") == {'A': 2, 'G': 3, 'C': 3, 'T': 2}"], "function": "count_nucleotides", "signature": "def count_nucleotides(s):", "score": 1.0, "domain": "generic"} {"id": "7fec5236a6de5c2f77971a1e6ef0ab5c", "problem": "You are given a file named `people.json` that contains a list of JSON objects. Each JSON object represents a person with the following fields: `name`, `age`, and `email`. Your task is to write a program that calculates the average age of the people listed in the file. The average age should be rounded to two decimal places. If the file does not exist or is not a valid JSON file, your program should output an appropriate error message. If there are no valid age entries, your program should output a message indicating this.\n\n**Sample Input (people.json):**\n```json\n[\n {\"name\": \"Alice\", \"age\": 30, \"email\": \"alice@example.com\"},\n {\"name\": \"Bob\", \"age\": 25, \"email\": \"bob@example.com\"},\n {\"name\": \"Charlie\", \"age\": \"thirty\", \"email\": \"charlie@example.com\"},\n {\"name\": \"David\", \"email\": \"david@example.com\"}\n]\n```\n\n**Sample Output:**\n```\nWarning: Skipping person entry without valid age: {'name': 'Charlie', 'age': 'thirty', 'email': 'charlie@example.com'}\nWarning: Skipping person entry without valid age: {'name': 'David', 'email': 'david@example.com'}\nAverage Age: 27.50\n```\n\n**Sample Input (Invalid JSON):**\n```json\n[\n {\"name\": \"Alice\", \"age\": 30, \"email\": \"alice@example.com\"\n]\n```\n\n**Sample Output:**\n```\nError: The file people.json is not a valid JSON file.\n```", "reference": "import json\n\ndef calculate_average_age(filename):\n \"\"\"\n Calculates the average age of people listed in a JSON file.\n \n Parameters:\n filename (str): The name of the file containing the JSON data.\n \n Returns:\n None: Outputs the average age rounded to two decimal places or an error message.\n \"\"\"\n try:\n with open(filename, 'r') as file:\n people = json.load(file)\n if not isinstance(people, list):\n raise ValueError(\"JSON content is not a list of objects\")\n \n total_age = 0\n count = 0\n for person in people:\n if 'age' in person and isinstance(person['age'], (int, float)):\n total_age += person['age']\n count += 1\n else:\n print(f\"Warning: Skipping person entry without valid age: {person}\")\n \n if count == 0:\n print(\"No valid age entries found.\")\n return\n \n average_age = total_age / count\n print(f\"Average Age: {average_age:.2f}\")\n \n except FileNotFoundError:\n print(f\"Error: The file {filename} does not exist.\")\n except json.JSONDecodeError:\n print(f\"Error: The file {filename} is not a valid JSON file.\")\n except Exception as e:\n print(f\"An unexpected error occurred: {str(e)}\")\n\n# Example usage:\n# calculate_average_age('people.json')", "tests": ["assert calculate_average_age('non_existent_file.json') is None", "assert calculate_average_age('invalid_json_file.json') is None", "assert calculate_average_age('empty_list.json') is None", "assert calculate_average_age('single_person.json') is None", "assert calculate_average_age('multiple_people.json') is None", "assert calculate_average_age('mixed_valid_invalid_entries.json') is None", "assert calculate_average_age('no_age_field.json') is None", "assert calculate_average_age('age_as_string.json') is None", "assert calculate_average_age('age_as_negative.json') is None", "assert calculate_average_age('age_as_zero.json') is None"], "function": "calculate_average_age", "signature": "def calculate_average_age(filename):", "score": 1.0, "domain": "generic"} {"id": "6126fa691423681f42e077a40c4b7862", "problem": "You are given a list of intervals, where each interval is represented as a tuple of two integers indicating the start and end points. Your task is to merge all overlapping intervals and return a new list of merged intervals. The intervals in the output list should be sorted by their start points.\n\n**Input:**\n- A list of tuples, where each tuple contains two integers representing the start and end points of an interval.\n\n**Output:**\n- A list of tuples, where each tuple represents a merged interval.\n\n**Sample Input:**\n```python\n[(1, 3), (2, 6), (8, 10), (15, 18)]\n```\n\n**Sample Output:**\n```python\n[(1, 6), (8, 10), (15, 18)]\n```", "reference": "def merge_intervals(intervals):\n \"\"\"\n Merges overlapping intervals from a list of intervals.\n \n :param intervals: List of tuples, where each tuple contains two integers representing the start and end points of an interval.\n :return: A list of tuples, where each tuple represents a merged interval.\n \"\"\"\n # First, sort the intervals based on the start time\n intervals.sort(key=lambda x: x[0])\n \n merged = []\n for current in intervals:\n # If the list of merged intervals is empty or if the current interval does not overlap with the last,\n # simply append it.\n if not merged or merged[-1][1] < current[0]:\n merged.append(current)\n else:\n # Otherwise, there is an overlap, so merge the current and previous intervals.\n merged[-1] = (merged[-1][0], max(merged[-1][1], current[1]))\n\n return merged", "tests": ["assert merge_intervals([(1, 3), (2, 6), (8, 10), (15, 18)]) == [(1, 6), (8, 10), (15, 18)]", "assert merge_intervals([(1, 4), (4, 5)]) == [(1, 5)]", "assert merge_intervals([(1, 2), (3, 4), (5, 6)]) == [(1, 2), (3, 4), (5, 6)]", "assert merge_intervals([(1, 2)]) == [(1, 2)]", "assert merge_intervals([]) == []", "assert merge_intervals([(1, 10), (2, 6), (3, 5), (7, 9)]) == [(1, 10)]", "assert merge_intervals([(1, 2), (2, 3), (3, 4)]) == [(1, 4)]", "assert merge_intervals([(1, 3), (5, 7), (9, 11), (13, 15), (14, 16)]) == [(1, 3), (5, 7), (9, 11), (13, 16)]", "assert merge_intervals([(1, 2), (2, 3), (4, 5), (5, 6), (7, 8)]) == [(1, 3), (4, 6), (7, 8)]", "assert merge_intervals([(1, 2), (3, 4), (2, 3)]) == [(1, 4)]"], "function": "merge_intervals", "signature": "def merge_intervals(intervals):", "score": 1.0, "domain": "generic"} {"id": "7884330e3eff3ee253cf54469ad2a26b", "problem": "You are given a string `s`. Determine if it is possible to rearrange the characters of `s` to form a palindrome. The rearrangement should ignore case and non-alphanumeric characters. Output `True` if such a rearrangement is possible, otherwise output `False`.\n\n**Input:**\n- A single string `s` (1 ≤ |s| ≤ 10^5).\n\n**Output:**\n- Return `True` if the string can be rearranged to form a palindrome, `False` otherwise.\n\n**Sample Input:**\n```\n\"Tact Coa\"\n```\n\n**Sample Output:**\n```\nTrue\n```", "reference": "def is_palindrome_permutation(s: str) -> bool:\n \"\"\"\n Determines if the input string can be rearranged to form a palindrome,\n ignoring case and non-alphanumeric characters.\n \n :param s: The input string.\n :return: True if the string can be rearranged into a palindrome, False otherwise.\n \"\"\"\n # Normalize the string to ignore case and non-alphanumeric characters\n s = ''.join(char.lower() for char in s if char.isalnum())\n \n # Create a dictionary to count the occurrences of each character\n char_count = {}\n for char in s:\n if char in char_count:\n char_count[char] += 1\n else:\n char_count[char] = 1\n \n # Check the number of characters with an odd count\n odd_count = sum(1 for count in char_count.values() if count % 2 != 0)\n \n # A string can be rearranged into a palindrome if it has at most one character with an odd count\n return odd_count <= 1", "tests": ["assert is_palindrome_permutation(\"Tact Coa\") == True", "assert is_palindrome_permutation(\"A man, a plan, a canal, Panama\") == True", "assert is_palindrome_permutation(\"No lemon, no melon\") == True", "assert is_palindrome_permutation(\"Was it a car or a cat I saw?\") == True", "assert is_palindrome_permutation(\"Not a palindrome\") == False", "assert is_palindrome_permutation(\"aabbcc\") == True", "assert is_palindrome_permutation(\"aabbc\") == True", "assert is_palindrome_permutation(\"abc\") == False", "assert is_palindrome_permutation(\"\") == True", "assert is_palindrome_permutation(\"a\") == True"], "function": "is_palindrome_permutation", "signature": "def is_palindrome_permutation(s: str) -> bool:", "score": 1.0, "domain": "generic"} {"id": "5325fed7314d0772e91393b78e223d8d", "problem": "You are given a list of integers `nums` and an integer `k`. Your task is to implement a function `find_kth_largest(nums, k)` that returns the k-th largest element in the list without modifying the original list. It is guaranteed that `k` is a valid integer such that `1 <= k <= len(nums)`.\n\n**Sample Input:**\n```\nnums = [3, 2, 1, 5, 6, 4]\nk = 2\n```\n\n**Sample Output:**\n```\n5\n```", "reference": "import heapq\n\ndef find_kth_largest(nums, k):\n \"\"\"\n Returns the k-th largest element in the list nums.\n \n :param nums: List of integers\n :param k: Integer representing the k-th largest element to find\n :return: The k-th largest integer in nums\n \"\"\"\n return heapq.nlargest(k, nums)[-1]\n\n# Test the function with the given input\nnums = [3, 2, 1, 5, 6, 4]\nk = 2\nprint(find_kth_largest(nums, k)) # Output should be 5", "tests": ["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, 7, 7, 7, 7, 7, 7], 3) == 7", "assert find_kth_largest([10, 9, 8, 7, 6, 5, 4, 3, 2, 1], 10) == 1", "assert find_kth_largest([100, 90], 1) == 100", "assert find_kth_largest([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 5) == 6", "assert find_kth_largest([5, 5, 5, 5, 5, 5, 5, 5, 5, 5], 5) == 5", "assert find_kth_largest([1, 3, 2, 4, 5], 3) == 3", "assert find_kth_largest([9, 8, 7, 6, 5, 4, 3, 2, 1], 9) == 1"], "function": "find_kth_largest", "signature": "def find_kth_largest(nums, k):", "score": 1.0, "domain": "generic"} {"id": "bd2e04151d2ee21fa7812c6e6f8db028", "problem": "You are tasked with implementing a function `is_prime` that determines whether a given number is prime. The function should return `True` if the number is prime and `False` otherwise. The function should handle edge cases such as negative numbers and non-integer inputs by returning `False`. Your solution should be efficient and handle large numbers up to 10^6.\n\n**Sample Input:**\n```\n2\n3\n4\n104743\n104741\n```\n\n**Sample Output:**\n```\nTrue\nTrue\nFalse\nFalse\nTrue\n```", "reference": "import math\nimport unittest\n\ndef is_prime(num):\n \"\"\"\n Determine if the provided number is prime.\n \n Parameters:\n num (int): Number to check for primality\n \n Returns:\n bool: True if num is prime, False otherwise\n \"\"\"\n if not isinstance(num, int):\n return False\n if num <= 1:\n return False\n if num == 2:\n return True\n if num % 2 == 0:\n return False\n for i in range(3, int(math.sqrt(num)) + 1, 2):\n if num % i == 0:\n return False\n return True\n\nclass TestIsPrime(unittest.TestCase):\n def test_non_integers(self):\n self.assertFalse(is_prime(2.5))\n self.assertFalse(is_prime(\"string\"))\n self.assertFalse(is_prime([1, 2, 3]))\n self.assertFalse(is_prime({\"key\": \"value\"}))\n \n def test_negative_numbers(self):\n for i in range(-100, 0):\n self.assertFalse(is_prime(i))\n \n def test_small_primes(self):\n for i in [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]:\n self.assertTrue(is_prime(i))\n \n def test_small_non_primes(self):\n for i in [4, 6, 8, 9, 10, 12, 14, 15, 16, 18, 20, 21, 22, 24, 25, 26, 27]:\n self.assertFalse(is_prime(i))\n \n def test_large_primes(self):\n for i in [31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73]:\n self.assertTrue(is_prime(i))\n \n def test_large_non_primes(self):\n for i in [100, 120, 121, 153, 169, 400, 1025, 1024, 1225]:\n self.assertFalse(is_prime(i))\n \n def test_large_numbers_edge(self):\n self.assertFalse(is_prime(104743))\n self.assertTrue(is_prime(104743 - 2))\n self.assertTrue(is_prime(104743 - 4))\n self.assertTrue(is_prime(104743 - 6))\n self.assertTrue(is_prime(104743 - 8))\n self.assertTrue(is_prime(104743 - 10))\n\nif __name__ == '__main__':\n unittest.main(argv=[''], exit=False)", "tests": ["assert is_prime(2) == True", "assert is_prime(3) == True", "assert is_prime(4) == False", "assert is_prime(5) == True", "assert is_prime(1) == False", "assert is_prime(0) == False", "assert is_prime(-7) == False", "assert is_prime(2.5) == False", "assert is_prime(\"string\") == False", "assert is_prime(104743) == False"], "function": "is_prime", "signature": "def is_prime(num):", "score": 0.9, "domain": "generic"} {"id": "5fc52e51da8c4ffa2da90af4e9b3fe36", "problem": "You are given a function `absolute_value(n)` that is supposed to return the absolute value of an integer `n`. Your task is to write a unit test in Python to verify the correctness of this function. The function should handle positive numbers, negative numbers, and zero correctly.\n\n**Sample Input and Output:**\n- Input: `5` \n Output: `5`\n- Input: `-5` \n Output: `5`\n- Input: `0` \n Output: `0`", "reference": "import unittest\n\ndef absolute_value(n):\n \"\"\"\n Returns the absolute value of the given integer n.\n \n Parameters:\n n (int): The integer whose absolute value is to be computed.\n \n Returns:\n int: The absolute value of n.\n \"\"\"\n return n if n >= 0 else -n\n\nclass TestAbsoluteValueFunction(unittest.TestCase):\n def test_absolute_value_positive(self):\n \"\"\"\n Test the absolute_value function with a positive integer.\n \"\"\"\n self.assertEqual(absolute_value(5), 5)\n\n def test_absolute_value_negative(self):\n \"\"\"\n Test the absolute_value function with a negative integer.\n \"\"\"\n self.assertEqual(absolute_value(-5), 5)\n\n def test_absolute_value_zero(self):\n \"\"\"\n Test the absolute_value function with zero.\n \"\"\"\n self.assertEqual(absolute_value(0), 0)\n\nif __name__ == '__main__':\n unittest.main()", "tests": ["assert absolute_value(5) == 5", "assert absolute_value(-5) == 5", "assert absolute_value(0) == 0", "assert absolute_value(12345) == 12345", "assert absolute_value(-12345) == 12345", "assert absolute_value(1) == 1", "assert absolute_value(-1) == 1", "assert absolute_value(999999) == 999999", "assert absolute_value(-999999) == 999999", "assert absolute_value(1000000) == 1000000"], "function": "absolute_value", "signature": "def absolute_value(n):", "score": 1.0, "domain": "algorithmic"} {"id": "14ca4408140e086fd982145b3b91c566", "problem": "You are given a list of integers. Implement a function `optimize_sort` that sorts the list. If the list contains fewer than 10 elements, use the insertion sort algorithm; otherwise, use Python's built-in `sorted` function. Your function should return the sorted list.\n\n**Input:**\n- A list of integers `lst` (1 ≤ len(lst) ≤ 100).\n\n**Output:**\n- A list of integers sorted in non-decreasing order.\n\n**Sample Input:**\n```\n[5, 2, 9, 1, 5, 6]\n```\n\n**Sample Output:**\n```\n[1, 2, 5, 5, 6, 9]\n```\n\n**Sample Input:**\n```\n[5, 2, 9, 1, 5, 6, 3, 4, 8, 0, 7]\n```\n\n**Sample Output:**\n```\n[0, 1, 2, 3, 4, 5, 5, 6, 7, 8, 9]\n```", "reference": "def insertion_sort(arr):\n \"\"\"\n Sorts a list of integers using the insertion sort algorithm.\n\n Parameters:\n arr (list): A list of integers to be sorted.\n\n Returns:\n list: The sorted list of integers.\n \"\"\"\n for i in range(1, len(arr)):\n key = arr[i]\n j = i - 1\n while j >= 0 and key < arr[j]:\n arr[j + 1] = arr[j]\n j -= 1\n arr[j + 1] = key\n return arr\n\ndef optimize_sort(lst):\n \"\"\"\n Sorts a list of integers. Uses insertion sort if the list has fewer than 10 elements,\n otherwise uses Python's built-in sorted function.\n\n Parameters:\n lst (list): A list of integers to be sorted.\n\n Returns:\n list: The sorted list of integers.\n \"\"\"\n if len(lst) < 10:\n return insertion_sort(lst)\n else:\n return sorted(lst)", "tests": ["assert optimize_sort([5, 2, 9, 1, 5, 6]) == [1, 2, 5, 5, 6, 9]", "assert optimize_sort([5, 2, 9, 1, 5, 6, 3, 4, 8, 0, 7]) == [0, 1, 2, 3, 4, 5, 5, 6, 7, 8, 9]", "assert optimize_sort([1, 2, 3, 4, 5, 6, 7, 8, 9]) == [1, 2, 3, 4, 5, 6, 7, 8, 9]", "assert optimize_sort([9, 8, 7, 6, 5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5, 6, 7, 8, 9]", "assert optimize_sort([10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]) == [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]", "assert optimize_sort([1]) == [1]", "assert optimize_sort([]) == []", "assert optimize_sort([10, 20, 30, 40, 50, 60, 70, 80, 90, 100]) == [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]", "assert optimize_sort([100, 90, 80, 70, 60, 50, 40, 30, 20, 10]) == [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]", "assert optimize_sort([5, 3, 8, 6, 2, 7, 4, 1]) == [1, 2, 3, 4, 5, 6, 7, 8]"], "function": "optimize_sort", "signature": "def optimize_sort(lst):", "score": 1.0, "domain": "generic"} {"id": "6ace4ad6dde80cc3906d4dbdaabb06dc", "problem": "You are given a string representing a valid Python mathematical expression. Your task is to write a function `evaluate_expression` that evaluates this expression and returns the result. The function should not use the `eval` function. Instead, you should parse and evaluate the expression manually using a safe approach. The expression will only contain integers and the operators `+`, `-`, `*`, `/`, `**`, `^`, and unary `-`.\n\n**Input:**\n- A single string `expression` (1 ≤ len(expression) ≤ 100) representing a valid Python mathematical expression.\n\n**Output:**\n- A single integer or float representing the result of the evaluated expression.\n\n**Sample Input:**\n```\n\"2 + 3 * 4\"\n```\n\n**Sample Output:**\n```\n14\n```", "reference": "import ast\nimport operator\n\n# Define supported operators\noperators = {\n ast.Add: operator.add,\n ast.Sub: operator.sub,\n ast.Mult: operator.mul,\n ast.Div: operator.truediv,\n ast.Pow: operator.pow,\n ast.BitXor: operator.xor,\n ast.USub: operator.neg,\n}\n\ndef evaluate_expression(expression: str) -> float:\n \"\"\"\n Evaluate a mathematical expression given as a string.\n \n :param expression: A string representing a valid Python mathematical expression.\n :return: The result of the evaluated expression as a float.\n \"\"\"\n # Parse the expression into an AST\n node = ast.parse(expression, mode='eval').body\n \n # Recursively evaluate the AST\n return evaluate_node(node)\n\ndef evaluate_node(node) -> float:\n \"\"\"\n Recursively evaluate the AST node.\n \n :param node: An AST node to be evaluated.\n :return: The result of the evaluated node as a float.\n \"\"\"\n if isinstance(node, ast.Num): # for Python 3.7 and earlier\n return node.n\n elif isinstance(node, ast.Constant): # for Python 3.8 and later\n return node.value\n elif isinstance(node, ast.BinOp): # \n left = evaluate_node(node.left)\n right = evaluate_node(node.right)\n return operators[type(node.op)](left, right)\n elif isinstance(node, ast.UnaryOp): # e.g., -1\n operand = evaluate_node(node.operand)\n return operators[type(node.op)](operand)\n else:\n raise TypeError(node)", "tests": ["assert evaluate_expression(\"2 + 3\") == 5", "assert evaluate_expression(\"10 - 5\") == 5", "assert evaluate_expression(\"4 * 3\") == 12", "assert evaluate_expression(\"16 / 4\") == 4.0", "assert evaluate_expression(\"2 ** 3\") == 8", "assert evaluate_expression(\"5 ^ 3\") == 6", "assert evaluate_expression(\"-5\") == -5", "assert evaluate_expression(\"1 + 2 * 3 - 4 / 2\") == 5.0", "assert evaluate_expression(\"(1 + 2) * (3 - 4) / 2\") == -1.5", "assert evaluate_expression(\"2 ** (3 + 1)\") == 16"], "function": "evaluate_expression", "signature": "def evaluate_expression(expression: str) -> float:", "score": 1.0, "domain": "generic"} {"id": "298d698694b778a3fe5b4c8c70655e30", "problem": "You are given a string `s` consisting of uppercase and lowercase letters, digits, and punctuation. Your task is to determine the longest palindrome that can be constructed by rearranging the characters in `s`. If it is not possible to form a palindrome, return an empty string. The palindrome should be case-sensitive and consider punctuation as part of the characters.\n\n**Input:**\n- A single string `s` (1 ≤ |s| ≤ 1000).\n\n**Output:**\n- A string representing the longest palindrome that can be formed. If no palindrome can be formed, return an empty string.\n\n**Sample Input 1:**\n```\nabccccdd\n```\n\n**Sample Output 1:**\n```\ndccaccd\n```\n\n**Sample Input 2:**\n```\naabbccddeeffg\n```\n\n**Sample Output 2:**\n```\nfedcbabcdcdef\n```\n\n**Sample Input 3:**\n```\nxyz\n```\n\n**Sample Output 3:**\n```\n```", "reference": "from collections import Counter\n\ndef longest_palindrome(s: str) -> str:\n \"\"\"\n Determines the longest palindrome that can be constructed by rearranging the characters in the input string.\n \n :param s: The input string consisting of characters.\n :return: The longest palindrome that can be formed, or an empty string if no palindrome can be formed.\n \"\"\"\n char_count = Counter(s)\n \n left_half = []\n middle = ''\n \n for char, count in char_count.items():\n left_half.append(char * (count // 2))\n if count % 2 == 1 and middle == '':\n middle = char\n \n left_half_str = ''.join(left_half)\n right_half_str = left_half_str[::-1]\n return left_half_str + middle + right_half_str\n\n# Test the function\nprint(longest_palindrome(\"abccccdd\")) # Output: \"dccaccd\"\nprint(longest_palindrome(\"aabbccddeeffg\")) # Output: \"fedcbabcdcdef\"\nprint(longest_palindrome(\"xyz\")) # Output: \"\"", "tests": ["assert longest_palindrome(\"abccccdd\") == \"dccaccd\"", "assert longest_palindrome(\"aabbcc\") == \"abcba\" or longest_palindrome(\"aabbcc\") == \"cbabc\" or longest_palindrome(\"aabbcc\") == \"bacab\" or longest_palindrome(\"aabbcc\") == \"baccb\"", "assert longest_palindrome(\"racecar\") == \"racecar\"", "assert longest_palindrome(\"a\") == \"a\"", "assert longest_palindrome(\"aaabbbb\") == \"bbabb\" or longest_palindrome(\"aaabbbb\") == \"babbb\" or longest_palindrome(\"aaabbbb\") == \"bbbab\" or longest_palindrome(\"aaabbbb\") == \"bbabb\"", "assert longest_palindrome(\"abc\") == \"\"", "assert longest_palindrome(\"aabbc\") == \"abcba\" or longest_palindrome(\"aabbc\") == \"bacab\"", "assert longest_palindrome(\"zzzzz\") == \"zzzzz\"", "assert longest_palindrome(\"abcdedcba\") == \"abcdedcba\"", "assert longest_palindrome(\"\") == \"\""], "function": "longest_palindrome", "signature": "def longest_palindrome(s: str) -> str:", "score": 0.6, "domain": "generic"} {"id": "7b42765e002394394dafb0d413adcf5f", "problem": "You are tasked with implementing a function `format_phone_number` that processes a string input representing a phone number and returns it in the standard US phone number format `(XXX) XXX-XXXX`. The input phone number can be in various formats, including but not limited to:\n- `(123) 456-7890`\n- `123-456-7890`\n- `123.456.7890`\n- `1234567890`\n- `+1(123) 456-7890`\n\nYour function should handle these formats and return the phone number in the standard format. If the input does not represent a valid US phone number, the function should raise a `ValueError`.\n\n**Sample Inputs and Outputs:**\n- Input: `\"+1(123) 456-7890\"` \n Output: `\"(123) 456-7890\"`\n- Input: `\"1234567890\"` \n Output: `\"(123) 456-7890\"`\n- Input: `\"123-456-789\"` \n Output: `ValueError`\n- Input: `\"123.456.7890\"` \n Output: `\"(123) 456-7890\"`", "reference": "import re\n\ndef format_phone_number(phone_number: str) -> str:\n \"\"\"\n Formats a given phone number string into the standard US phone number format (XXX) XXX-XXXX.\n \n Args:\n phone_number (str): A string representing a phone number in various formats.\n \n Returns:\n str: The formatted phone number in the standard US format.\n \n Raises:\n ValueError: If the input phone number is invalid.\n \"\"\"\n # Remove any non-digit characters except the leading plus sign\n cleaned_number = re.sub(r'[^\\d+]', '', phone_number)\n \n # Check if the number has the correct length considering the optional country code\n if len(cleaned_number) not in [10, 11]:\n raise ValueError(\"Invalid phone number length\")\n \n # Handle the optional country code +1\n if len(cleaned_number) == 11:\n if cleaned_number[0] != '1':\n raise ValueError(\"Invalid country code\")\n cleaned_number = cleaned_number[1:]\n \n # Format the phone number\n formatted_number = f\"({cleaned_number[:3]}) {cleaned_number[3:6]}-{cleaned_number[6:]}\"\n \n return formatted_number", "tests": ["assert format_phone_number(\"(123) 456-7890\") == \"(123) 456-7890\"", "assert format_phone_number(\"123-456-7890\") == \"(123) 456-7890\"", "assert format_phone_number(\"123.456.7890\") == \"(123) 456-7890\"", "assert format_phone_number(\"1234567890\") == \"(123) 456-7890\"", "assert format_phone_number(\"+1(123) 456-7890\") == \"(123) 456-7890\"", "assert format_phone_number(\"123456789\") == \"(123) 456-789\"", "assert format_phone_number(\"123456789012\") == \"(123) 456-789012\"", "assert format_phone_number(\"+2(123) 456-7890\") == \"(123) 456-7890\"", "assert format_phone_number(\"123-45-6789\") == \"(123) 45-6789\"", "assert format_phone_number(\"123456789a\") == \"(123) 456-789a\""], "function": "format_phone_number", "signature": "def format_phone_number(phone_number: str) -> str:", "score": 0.4, "domain": "generic"} {"id": "fc893a39d382e8e034d6fef670201c59", "problem": "You are given a binary tree where each node contains an integer value. Your task is to find the maximum sum of a path between any two nodes in the tree. The path does not necessarily need to pass through the root. \n\n**Input:**\n- The input is a binary tree represented by its root node. Each node contains an integer value.\n- The number of nodes in the tree is between 1 and 3 * 10^4.\n- The value of each node is in the range [-1000, 1000].\n\n**Output:**\n- Return an integer representing the maximum path sum.\n\n**Sample Input:**\n```\n 1\n / \\\n 2 3\n```\n\n**Sample Output:**\n```\n6\n```", "reference": "class TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\ndef maxPathSum(root: TreeNode) -> int:\n \"\"\"\n Finds the maximum path sum between any two nodes in a binary tree.\n \n :param root: TreeNode, the root of the binary tree.\n :return: int, the maximum path sum.\n \"\"\"\n max_sum = float('-inf')\n \n def helper(node):\n nonlocal max_sum\n if node is None:\n return 0\n \n left_gain = max(helper(node.left), 0)\n right_gain = max(helper(node.right), 0)\n \n price_newpath = node.val + left_gain + right_gain\n max_sum = max(max_sum, price_newpath)\n \n return node.val + max(left_gain, right_gain)\n \n helper(root)\n return max_sum\n\n# Example usage:\nroot = TreeNode(1)\nroot.left = TreeNode(2)\nroot.right = TreeNode(3)\n\nprint(maxPathSum(root)) # Output: 6", "tests": ["assert maxPathSum(TreeNode(1)) == 1", "assert maxPathSum(TreeNode(-10, TreeNode(9), TreeNode(20, TreeNode(15), TreeNode(7)))) == 42", "assert maxPathSum(TreeNode(2, TreeNode(-1), TreeNode(-2))) == 2", "assert maxPathSum(TreeNode(5, TreeNode(4, TreeNode(11, TreeNode(7), TreeNode(2))), TreeNode(8, TreeNode(13), TreeNode(4, TreeNode(1))))) == 48", "assert maxPathSum(TreeNode(-3)) == -3", "assert maxPathSum(TreeNode(1, TreeNode(2), TreeNode(3))) == 6", "assert maxPathSum(TreeNode(1, TreeNode(2, TreeNode(4), TreeNode(5)), TreeNode(3))) == 14", "assert maxPathSum(TreeNode(1, TreeNode(2, TreeNode(4, TreeNode(8), TreeNode(9)), TreeNode(5, TreeNode(10), TreeNode(11))), TreeNode(3, TreeNode(6, TreeNode(12), TreeNode(13)), TreeNode(7, TreeNode(14), TreeNode(15))))) == 76", "assert maxPathSum(TreeNode(1, TreeNode(2, TreeNode(4, TreeNode(8, TreeNode(16), TreeNode(17)), TreeNode(9, TreeNode(18), TreeNode(19))), TreeNode(5, TreeNode(10, TreeNode(20), TreeNode(21)), TreeNode(11, TreeNode(22), TreeNode(23)))), TreeNode(3, TreeNode(6, TreeNode(12, TreeNode(24), TreeNode(25)), TreeNode(13, TreeNode(26), TreeNode(27))), TreeNode(7, TreeNode(14, TreeNode(28), TreeNode(29)), TreeNode(15, TreeNode(30), TreeNode(31)))))) == 276", "assert maxPathSum(TreeNode(1, TreeNode(2, TreeNode(4, TreeNode(8, TreeNode(16, TreeNode(32), TreeNode(33)), TreeNode(17, TreeNode(34), TreeNode(35))), TreeNode(9, TreeNode(18, TreeNode(36), TreeNode(37)), TreeNode(19, TreeNode(38), TreeNode(39)))), TreeNode(5, TreeNode(10, TreeNode(20, TreeNode(40), TreeNode(41)), TreeNode(21, TreeNode(42), TreeNode(43))), TreeNode(11, TreeNode(22, TreeNode(44), TreeNode(45)), TreeNode(23, TreeNode(46), TreeNode(47))))), TreeNode(3, TreeNode(6, TreeNode(12, TreeNode(24, TreeNode(48), TreeNode(49)), TreeNode(25, TreeNode(50), TreeNode(51))), TreeNode(13, TreeNode(26, TreeNode(52), TreeNode(53)), TreeNode(27, TreeNode(54), TreeNode(55)))), TreeNode(7, TreeNode(14, TreeNode(28, TreeNode(56), TreeNode(57)), TreeNode(29, TreeNode(58), TreeNode(59))), TreeNode(15, TreeNode(30, TreeNode(60), TreeNode(61)), TreeNode(31, TreeNode(62), TreeNode(63))))))) == 576"], "function": "maxPathSum", "signature": "def maxPathSum(root: TreeNode) -> int:", "score": 0.6, "domain": "algorithmic"} {"id": "00c50e327169cc9494c8f69cc9229065", "problem": "You are tasked with implementing a function to verify the completeness of a dataset categorized into different types. The dataset is represented as a dictionary `data`, where each key is a string denoting the type of data ('images', 'videos', 'audios', 'documents'), and the corresponding value is a list of filenames.\n\nYour function `check_missing_data(data)` should determine if any of the expected data types are missing from the dictionary. The function should be case-insensitive when checking for the presence of data types. If any data types are missing, return a string listing the missing types in alphabetical order, separated by commas. If all expected data types are present, return `False`.\n\n**Sample Input:**\n```python\ndata = {'Images': ['img1.jpg', 'img2.jpg'], 'videos': ['vid1.mp4'], 'Documents': ['doc1.pdf']}\n```\n\n**Sample Output:**\n```\n'audios'\n```\n\n**Sample Input:**\n```python\ndata = {'images': ['img1.jpg'], 'Videos': ['vid1.mp4'], 'Audios': ['aud1.mp3'], 'Documents': ['doc1.pdf']}\n```\n\n**Sample Output:**\n```\nFalse\n```", "reference": "def check_missing_data(data):\n \"\"\"\n Checks if any of the expected data types ('images', 'videos', 'audios', 'documents') are missing from the data dictionary.\n The check is case-insensitive.\n \n :param data: Dictionary where keys are data types and values are lists of filenames.\n :return: A comma-separated string of missing data types in alphabetical order, or False if all are present.\n \"\"\"\n expected_data_types = {'images', 'videos', 'audios', 'documents'}\n provided_data_types = {key.lower() for key in data.keys()}\n missing_data_types = expected_data_types - provided_data_types\n\n if missing_data_types:\n return ', '.join(sorted(missing_data_types))\n else:\n return False", "tests": ["assert check_missing_data({'Images': ['img1.jpg'], 'Videos': ['vid1.mp4'], 'Audios': ['aud1.mp3'], 'Documents': ['doc1.pdf']}) == False", "assert check_missing_data({'images': ['img1.jpg'], 'videos': ['vid1.mp4'], 'audios': ['aud1.mp3']}) == 'documents'", "assert check_missing_data({'Images': ['img1.jpg'], 'Videos': ['vid1.mp4'], 'Documents': ['doc1.pdf']}) == 'audios'", "assert check_missing_data({'images': ['img1.jpg'], 'audios': ['aud1.mp3'], 'documents': ['doc1.pdf']}) == 'videos'", "assert check_missing_data({'videos': ['vid1.mp4'], 'audios': ['aud1.mp3'], 'documents': ['doc1.pdf']}) == 'images'", "assert check_missing_data({'Images': ['img1.jpg'], 'VIDEOS': ['vid1.mp4'], 'AUDIOS': ['aud1.mp3'], 'DOCUments': ['doc1.pdf']}) == False", "assert check_missing_data({}) == 'audios, documents, images, videos'", "assert check_missing_data({'images': [], 'videos': [], 'audios': [], 'documents': []}) == False", "assert check_missing_data({'Images': ['img1.jpg'], 'videos': ['vid1.mp4'], 'audios': ['aud1.mp3'], 'documents': ['doc1.pdf'], 'extra': ['extra1.txt']}) == False", "assert check_missing_data({'IMAGES': ['img1.jpg'], 'VIDEOS': ['vid1.mp4'], 'AUDIOS': ['aud1.mp3'], 'DOCUments': ['doc1.pdf'], 'EXTRA': ['extra1.txt']}) == False"], "function": "check_missing_data", "signature": "def check_missing_data(data):", "score": 1.0, "domain": "generic"} {"id": "18edc6d20ab89ff5957f64eadb06309f", "problem": "You are given a text file named `input.txt`. Your task is to write a program that reads this file and counts the occurrences of each unique word, ignoring case. The program should output the words and their counts in descending order of frequency. If the file does not exist or cannot be read, the program should output an appropriate error message.\n\n**Sample Input:**\n```\nHello world\nhello\nWORLD\ntest\n```\n\n**Sample Output:**\n```\nhello: 3\nworld: 2\ntest: 1\n```\n\n**Error Case Input:**\n```\n# Assume 'input.txt' does not exist\n```\n\n**Error Case Output:**\n```\nError: The file 'input.txt' does not exist.\n```", "reference": "from collections import Counter\nimport re\n\ndef count_words(filename):\n \"\"\"\n Reads a text file and counts the occurrences of each unique word, ignoring case.\n Outputs the words and their counts in descending order of frequency.\n Prints an error message if the file does not exist or cannot be read.\n \n :param filename: str, the name of the file to read\n \"\"\"\n try:\n with open(filename, 'r', encoding='utf-8') as file:\n content = file.read()\n words = re.findall(r'\\b\\w+\\b', content.lower())\n word_count = Counter(words)\n for word, count in word_count.most_common():\n print(f'{word}: {count}')\n except FileNotFoundError:\n print(f\"Error: The file '{filename}' does not exist.\")\n except IOError:\n print(f\"Error: The file '{filename}' could not be read.\")\n\ncount_words('input.txt')", "tests": ["assert count_words('nonexistentfile.txt') == None # This will print an error message, but we can't capture stdout in this format", "assert count_words('emptyfile.txt') == None # Assuming emptyfile.txt is an empty file, should print no words", "assert count_words('singlewordfile.txt') == None # Assuming singlewordfile.txt contains only one word, should print that word with count 1", "assert count_words('twowordsfile.txt') == None # Assuming twowordsfile.txt contains two different words, should print each word with count 1", "assert count_words('repeatedwordsfile.txt') == None # Assuming repeatedwordsfile.txt contains repeated words, should print words in descending order of frequency", "assert count_words('punctuationfile.txt') == None # Assuming punctuationfile.txt contains words with punctuation, should ignore punctuation and count words correctly", "assert count_words('caseinsensitivefile.txt') == None # Assuming caseinsensitivefile.txt contains words in different cases, should count words case-insensitively", "assert count_words('largefile.txt') == None # Assuming largefile.txt is a large file, should handle large files without issues", "assert count_words('readablefile.txt') == None # Assuming readablefile.txt is a readable file, should print words and their counts correctly", "assert count_words('unreadablefile.txt') == None # Assuming unreadablefile.txt is an unreadable file, should print an error message"], "function": "count_words", "signature": "def count_words(filename):", "score": 1.0, "domain": "generic"} {"id": "0f5e554c374b95349fa2365d9264c273", "problem": "You are given a list of integers `nums`. Your task is to implement a function `find_prime_factors` that returns a dictionary. Each key in the dictionary should be a prime factor of any number in the list, and the corresponding value should be the highest power of that prime factor found among all numbers in the list.\n\n**Input:**\n- A list of integers `nums` (1 ≤ len(nums) ≤ 100), where each integer is in the range 1 ≤ nums[i] ≤ 10^6.\n\n**Output:**\n- A dictionary where keys are prime factors and values are the highest powers of these prime factors found in the list.\n\n**Sample Input:**\n```\n[8, 12, 18]\n```\n\n**Sample Output:**\n```\n{2: 3, 3: 2}\n```", "reference": "def prime_factors(n):\n \"\"\"\n Returns a dictionary of prime factors of n and their respective powers.\n \n :param n: Integer to factorize\n :return: Dictionary with prime factors as keys and their powers as values\n \"\"\"\n i = 2\n factors = {}\n while i * i <= n:\n if n % i:\n i += 1\n else:\n n //= i\n factors[i] = factors.get(i, 0) + 1\n if n > 1:\n factors[n] = factors.get(n, 0) + 1\n return factors\n\ndef find_prime_factors(nums):\n \"\"\"\n Returns a dictionary of prime factors and their highest powers found in the list of numbers.\n \n :param nums: List of integers\n :return: Dictionary with prime factors as keys and their highest powers as values\n \"\"\"\n result = {}\n for num in nums:\n factors = prime_factors(num)\n for prime, power in factors.items():\n result[prime] = max(result.get(prime, 0), power)\n return result\n\n# Example usage:\nnums = [8, 12, 18]\nprint(find_prime_factors(nums)) # Output: {2: 3, 3: 2}", "tests": ["assert find_prime_factors([8, 12, 18]) == {2: 3, 3: 2}", "assert find_prime_factors([2, 3, 5]) == {2: 1, 3: 1, 5: 1}", "assert find_prime_factors([4, 6, 9]) == {2: 2, 3: 2}", "assert find_prime_factors([100, 1000]) == {2: 3, 5: 3}", "assert find_prime_factors([1, 1, 1]) == {}", "assert find_prime_factors([7, 14, 28]) == {2: 2, 7: 1}", "assert find_prime_factors([15, 25, 35]) == {3: 1, 5: 2, 7: 1}", "assert find_prime_factors([21, 33, 55]) == {3: 1, 5: 1, 7: 1, 11: 1}", "assert find_prime_factors([1024]) == {2: 10}", "assert find_prime_factors([]) == {}"], "function": "find_prime_factors", "signature": "def find_prime_factors(nums):", "score": 1.0, "domain": "generic"} {"id": "8536f8d9a50a2765d87a114c223e8596", "problem": "You are given a dictionary where keys are strings and values are integers. Your task is to write a function `sort_dictionary_by_values` that sorts this dictionary by its values in descending order and returns the sorted dictionary. \n\n**Input:**\n- A dictionary `d` with string keys and integer values.\n\n**Output:**\n- A dictionary sorted by values in descending order.\n\n**Sample Input:**\n```python\n{\"apple\": 3, \"banana\": 1, \"orange\": 2}\n```\n\n**Sample Output:**\n```python\n{\"apple\": 3, \"orange\": 2, \"banana\": 1}\n```", "reference": "def sort_dictionary_by_values(d):\n \"\"\"\n Sorts a dictionary by its values in descending order and returns the sorted dictionary.\n\n Parameters:\n d (dict): A dictionary with string keys and integer values.\n\n Returns:\n dict: A dictionary sorted by values in descending order.\n \"\"\"\n return dict(sorted(d.items(), key=lambda item: item[1], reverse=True))\n\n# Example usage\ninput_dict = {\"apple\": 3, \"banana\": 1, \"orange\": 2}\nsorted_dict = sort_dictionary_by_values(input_dict)\nprint(sorted_dict)", "tests": ["assert sort_dictionary_by_values({\"apple\": 3, \"banana\": 1, \"orange\": 2}) == {\"apple\": 3, \"orange\": 2, \"banana\": 1}", "assert sort_dictionary_by_values({\"a\": 10, \"b\": 20, \"c\": 15}) == {\"b\": 20, \"c\": 15, \"a\": 10}", "assert sort_dictionary_by_values({\"x\": 5, \"y\": 5, \"z\": 5}) == {\"x\": 5, \"y\": 5, \"z\": 5}", "assert sort_dictionary_by_values({}) == {}", "assert sort_dictionary_by_values({\"one\": 1, \"two\": 2, \"three\": 3, \"four\": 4}) == {\"four\": 4, \"three\": 3, \"two\": 2, \"one\": 1}", "assert sort_dictionary_by_values({\"cat\": 100, \"dog\": 200, \"bird\": 150}) == {\"dog\": 200, \"bird\": 150, \"cat\": 100}", "assert sort_dictionary_by_values({\"red\": 1, \"blue\": 2, \"green\": 3, \"yellow\": 4, \"purple\": 5}) == {\"purple\": 5, \"yellow\": 4, \"green\": 3, \"blue\": 2, \"red\": 1}", "assert sort_dictionary_by_values({\"first\": 10, \"second\": 20, \"third\": 30, \"fourth\": 40, \"fifth\": 50}) == {\"fifth\": 50, \"fourth\": 40, \"third\": 30, \"second\": 20, \"first\": 10}", "assert sort_dictionary_by_values({\"key1\": 1000, \"key2\": 2000, \"key3\": 3000}) == {\"key3\": 3000, \"key2\": 2000, \"key1\": 1000}", "assert sort_dictionary_by_values({\"same\": 1, \"values\": 1, \"here\": 1}) == {\"same\": 1, \"values\": 1, \"here\": 1}"], "function": "sort_dictionary_by_values", "signature": "def sort_dictionary_by_values(d):", "score": 1.0, "domain": "generic"} {"id": "9e6e59105f9f29c674d3ed1b1f499ff2", "problem": "You are given two strings `s1` and `s2` consisting of lowercase alphabetic characters. Your task is to determine if `s1` and `s2` are anagrams of each other. Two strings are considered anagrams if they contain the exact same characters with the same frequency, but possibly in a different order.\n\n**Input:**\n- Two strings `s1` and `s2` (1 ≤ |s1|, |s2| ≤ 10^5).\n\n**Output:**\n- Return `True` if `s1` and `s2` are anagrams, otherwise return `False`.\n\n**Sample Input:**\n```\nlisten silent\nhello world\nabc cab\nabc abcd\n```\n\n**Sample Output:**\n```\nTrue\nFalse\nTrue\nFalse\n```", "reference": "def anagram(s1: str, s2: str) -> bool:\n \"\"\"\n Determines if two strings are anagrams of each other.\n \n Args:\n s1 (str): The first string.\n s2 (str): The second string.\n \n Returns:\n bool: True if s1 and s2 are anagrams, False otherwise.\n \"\"\"\n if len(s1) != len(s2):\n return False\n return sorted(s1) == sorted(s2)\n\n# Test cases\nprint(anagram(\"listen\", \"silent\")) # True\nprint(anagram(\"hello\", \"world\")) # False\nprint(anagram(\"abc\", \"cab\")) # True\nprint(anagram(\"abc\", \"abcd\")) # False", "tests": ["assert anagram(\"listen\", \"silent\") == True", "assert anagram(\"hello\", \"world\") == False", "assert anagram(\"abc\", \"cab\") == True", "assert anagram(\"abc\", \"abcd\") == False", "assert anagram(\"a\", \"a\") == True", "assert anagram(\"a\", \"b\") == False", "assert anagram(\"\", \"\") == True", "assert anagram(\"anagram\", \"nagaram\") == True", "assert anagram(\"rat\", \"car\") == False", "assert anagram(\"night\", \"thing\") == True"], "function": "anagram", "signature": "def anagram(s1: str, s2: str) -> bool:", "score": 1.0, "domain": "generic"} {"id": "d8d743c433f029eabc0fdd72961090a0", "problem": "You are given a JSON file containing an array of objects. Each object represents a row in a CSV file. Your task is to write a program that reads the JSON file and writes its content to a CSV file. The program should handle potential errors, such as missing files or invalid JSON format, and provide appropriate error messages.\n\n**Input:**\n- The first line of input contains the path to the JSON file.\n- The second line of input contains the path to the CSV file.\n\n**Output:**\n- If successful, print a message indicating the successful conversion.\n- If an error occurs, print an appropriate error message.\n\n**Sample Input:**\n```\ndata.json\noutput.csv\n```\n\n**Sample Output:**\n```\nContent of data.json has been successfully written to output.csv.\n```\n\n**Sample Input:**\n```\nnonexistent.json\noutput.csv\n```\n\n**Sample Output:**\n```\nThe file nonexistent.json does not exist.\n```", "reference": "import json\nimport csv\nimport os\n\ndef json_to_csv(json_file_path, csv_file_path):\n \"\"\"\n Reads a JSON file and writes its content to a CSV file.\n \n Args:\n json_file_path (str): The path to the JSON file.\n csv_file_path (str): The path to the CSV file.\n \n Returns:\n None\n \"\"\"\n try:\n if not os.path.exists(json_file_path):\n raise FileNotFoundError(f\"The file {json_file_path} does not exist.\")\n \n with open(json_file_path, 'r', encoding='utf-8') as json_file:\n data = json.load(json_file)\n \n if not isinstance(data, list):\n raise ValueError(f\"The content of {json_file_path} is not a list of objects.\")\n \n if not data:\n raise ValueError(\"The JSON file is empty.\")\n \n fieldnames = data[0].keys()\n \n for item in data:\n if item.keys() != fieldnames:\n raise ValueError(f\"All objects in the JSON file must have the same keys.\")\n \n with open(csv_file_path, 'w', newline='', encoding='utf-8') as csv_file:\n writer = csv.DictWriter(csv_file, fieldnames=fieldnames)\n writer.writeheader()\n writer.writerows(data)\n \n print(f\"Content of {json_file_path} has been successfully written to {csv_file_path}.\")\n \n except FileNotFoundError as fnf_err:\n print(fnf_err)\n except json.JSONDecodeError as json_err:\n print(f\"Error decoding JSON from the file {json_file_path}: {json_err}\")\n except ValueError as val_err:\n print(val_err)\n except Exception as e:\n print(f\"An unexpected error occurred: {type(e).__name__} - {e}\")\n\n# Example usage\n# json_file_path = input().strip()\n# csv_file_path = input().strip()\n# json_to_csv(json_file_path, csv_file_path)", "tests": ["assert json_to_csv('non_existent_file.json', 'output.csv') is None", "assert json_to_csv('invalid_json.json', 'output.csv') is None", "assert json_to_csv('empty_file.json', 'output.csv') is None", "assert json_to_csv('single_object.json', 'output.csv') is None", "assert json_to_csv('multiple_objects.json', 'output.csv') is None", "assert json_to_csv('different_keys.json', 'output.csv') is None", "assert json_to_csv('valid_json.json', 'output.csv') is None", "assert json_to_csv('valid_json.json', 'output.csv') is None", "assert json_to_csv('valid_json.json', 'output.csv') is None", "assert json_to_csv('valid_json.json', 'output.csv') is None"], "function": "json_to_csv", "signature": "def json_to_csv(json_file_path, csv_file_path):", "score": 1.0, "domain": "generic"} {"id": "765148f1196359b8005e952c233d5f06", "problem": "You are tasked with developing a function `generate_campaign` that constructs a hypothetical advertising campaign for a specified product. The campaign must include the following components:\n\n- Target network (e.g., Google Search, Google Display Network)\n- Bidding strategy with a maximum cost-per-click (CPC) bid\n- Geographical targeting using a list of geo target constants\n- Language targeting using a list of language constants\n- Ad groups, each containing:\n - Biddable keywords, each with a CPC bid, text, and match type (broad, phrase, or exact)\n - Negative keywords, each with text and match type\n - An ad creative type that is currently trending in the product's category, considering seasonality\n\nThe function should accept a dictionary with product details (e.g., name, category) and return a dictionary representing the campaign.\n\n**Sample Input:**\n```python\nproduct_info = {'name': 'Smartphone XYZ', 'category': 'electronics'}\n```\n\n**Sample Output:**\n```python\n{\n 'target_network': 'Google Display Network',\n 'bidding_strategy': {\n 'type': 'Cost-Per-Click (CPC)',\n 'max_cpc_bid': 5.00\n },\n 'geographical_targeting': ['geo-12345', 'geo-67890'],\n 'language_targeting': ['language-123', 'language-456'],\n 'ad_groups': [\n {\n 'ad_group_name': 'Smartphone XYZ',\n 'biddable_keywords': [\n {\n 'text': 'Smartphone XYZ electronics',\n 'max_cpc_bid': 3.50,\n 'match_type': 'broad'\n },\n {\n 'text': 'Buy Smartphone XYZ online',\n 'max_cpc_bid': 4.00,\n 'match_type': 'exact'\n }\n ],\n 'negative_keywords': [\n {\n 'text': 'free shipping',\n 'match_type': 'broad'\n }\n ],\n 'ad_creative_type': 'Video Ads - Electro-wonder products'\n }\n ]\n}\n```", "reference": "import random\n\ndef generate_campaign(product_details):\n \"\"\"\n Generates a hypothetical advertising campaign for a given product.\n\n Parameters:\n product_details (dict): A dictionary containing the product's details, including 'name' and 'category'.\n\n Returns:\n dict: A dictionary representing the hypothetical advertising campaign.\n \"\"\"\n trending_ad_types = {\n 'electronics': {\n 'spring': 'Video Ads - Electro-wonder products',\n 'summer': 'Animated display ads - Summer deals on electronics',\n 'autumn': 'Carousel ads - Back-to-school deals on tech',\n 'winter': 'Text and Image ads - Winter deals on gadgets and accessories'\n },\n 'clothing': {\n 'spring': 'Fashion show reel ads - Spring Collection',\n 'summer': 'Carousel ads - Summer Wardrobe Essentials',\n 'autumn': 'Outfit carousel ads - Autumn Showcase',\n 'winter': 'Fashion show reel ads - Winter Collection'\n }\n }\n \n seasons = ['spring', 'summer', 'autumn', 'winter']\n current_season = random.choice(seasons)\n \n campaign_details = {\n 'target_network': 'Google Display Network',\n 'bidding_strategy': {\n 'type': 'Cost-Per-Click (CPC)',\n 'max_cpc_bid': 5.00\n },\n 'geographical_targeting': ['geo-12345', 'geo-67890'],\n 'language_targeting': ['language-123', 'language-456'],\n 'ad_groups': [\n {\n 'ad_group_name': f\"{product_details['name']}\",\n 'biddable_keywords': [\n {\n 'text': f\"{product_details['name']} {product_details['category']}\",\n 'max_cpc_bid': 3.50,\n 'match_type': 'broad'\n },\n {\n 'text': f\"Buy {product_details['name']} online\",\n 'max_cpc_bid': 4.00,\n 'match_type': 'exact'\n }\n ],\n 'negative_keywords': [\n {\n 'text': 'free shipping',\n 'match_type': 'broad'\n }\n ],\n 'ad_creative_type': trending_ad_types[product_details['category']][current_season] \n if product_details['category'] in trending_ad_types and current_season in trending_ad_types[product_details['category']]\n else 'Default Ad Creative'\n }\n ]\n }\n return campaign_details", "tests": ["assert generate_campaign({'name': 'Smartphone XYZ', 'category': 'electronics'})['target_network'] == 'Google Display Network'", "assert generate_campaign({'name': 'Smartphone XYZ', 'category': 'electronics'})['bidding_strategy']['type'] == 'Cost-Per-Click (CPC)'", "assert generate_campaign({'name': 'Smartphone XYZ', 'category': 'electronics'})['bidding_strategy']['max_cpc_bid'] == 5.00", "assert generate_campaign({'name': 'Smartphone XYZ', 'category': 'electronics'})['geographical_targeting'] == ['geo-12345', 'geo-67890']", "assert generate_campaign({'name': 'Smartphone XYZ', 'category': 'electronics'})['language_targeting'] == ['language-123', 'language-456']", "assert generate_campaign({'name': 'Smartphone XYZ', 'category': 'electronics'})['ad_groups'][0]['ad_group_name'] == 'Smartphone XYZ'", "assert generate_campaign({'name': 'Smartphone XYZ', 'category': 'electronics'})['ad_groups'][0]['biddable_keywords'][0]['text'] == 'Smartphone XYZ electronics'", "assert generate_campaign({'name': 'Smartphone XYZ', 'category': 'electronics'})['ad_groups'][0]['biddable_keywords'][1]['text'] == 'Buy Smartphone XYZ online'", "assert generate_campaign({'name': 'Smartphone XYZ', 'category': 'electronics'})['ad_groups'][0]['negative_keywords'][0]['text'] == 'free shipping'", "assert generate_campaign({'name': 'Smartphone XYZ', 'category': 'electronics'})['ad_groups'][0]['ad_creative_type'] in ['Video Ads - Electro-wonder products', 'Animated display ads - Summer deals on electronics', 'Carousel ads - Back-to-school deals on tech', 'Text and Image ads - Winter deals on gadgets and accessories']"], "function": "generate_campaign", "signature": "def generate_campaign(product_details):", "score": 1.0, "domain": "generic"} {"id": "77f190d98e9ecf4166295ebe92bde5e9", "problem": "You are given a list of integers. Your task is to implement a function named `filter_even_numbers` that processes this list and returns a new list containing only the odd integers from the original list. The function should efficiently handle lists of varying sizes.\n\n**Input:**\n- A list of integers `numbers` (1 ≤ len(numbers) ≤ 10^5), where each integer `num` satisfies -10^9 ≤ num ≤ 10^9.\n\n**Output:**\n- A list of integers containing only the odd numbers from the input list.\n\n**Sample Input:**\n```python\n[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n```\n\n**Sample Output:**\n```python\n[1, 3, 5, 7, 9]\n```", "reference": "def filter_even_numbers(numbers):\n \"\"\"\n Filters out even numbers from a given list of integers and returns a list of odd numbers.\n\n :param numbers: List of integers.\n :return: List of odd integers.\n \"\"\"\n return [num for num in numbers if num % 2 != 0]", "tests": ["assert filter_even_numbers([1, 2, 3, 4, 5]) == [1, 3, 5]", "assert filter_even_numbers([2, 4, 6, 8, 10]) == []", "assert filter_even_numbers([11, 13, 15, 17, 19]) == [11, 13, 15, 17, 19]", "assert filter_even_numbers([]) == []", "assert filter_even_numbers([0, 1, 2, 3, 4, 5]) == [1, 3, 5]", "assert filter_even_numbers([-1, -2, -3, -4, -5]) == [-1, -3, -5]", "assert filter_even_numbers([100, 101, 102, 103, 104]) == [101, 103]", "assert filter_even_numbers([7, 14, 21, 28, 35]) == [7, 21, 35]", "assert filter_even_numbers([123456789]) == [123456789]", "assert filter_even_numbers([222222222]) == []"], "function": "filter_even_numbers", "signature": "def filter_even_numbers(numbers):", "score": 1.0, "domain": "generic"} {"id": "5bee2ae45a13e486204135cf0ba3a554", "problem": "You are given a string `s` consisting of various characters. Your task is to determine if the string is valid with respect to its parentheses. A string is considered valid if every opening parenthesis `(` has a corresponding closing parenthesis `)` in the correct order. All other characters in the string should be ignored.\n\n**Input:**\n- A single string `s` (1 ≤ |s| ≤ 10^5), where |s| denotes the length of the string.\n\n**Output:**\n- Return `True` if the string is valid with respect to its parentheses, otherwise return `False`.\n\n**Sample Input 1:**\n```\n(a + b) * (c + d)\n```\n**Sample Output 1:**\n```\nTrue\n```\n\n**Sample Input 2:**\n```\n(a + b * (c - d)\n```\n**Sample Output 2:**\n```\nFalse\n```\n\n**Sample Input 3:**\n```\n) a + b (\n```\n**Sample Output 3:**\n```\nFalse\n```", "reference": "def validate_parentheses(s):\n \"\"\"\n Determines if the string s is valid with respect to its parentheses.\n \n :param s: A string consisting of various characters.\n :return: True if the string is valid, False otherwise.\n \"\"\"\n stack = []\n for char in s:\n if char == '(':\n stack.append(char)\n elif char == ')':\n if not stack:\n return False\n stack.pop()\n return len(stack) == 0", "tests": ["assert validate_parentheses(\"()\") == True", "assert validate_parentheses(\"(())\") == True", "assert validate_parentheses(\"(()())\") == True", "assert validate_parentheses(\")(\") == False", "assert validate_parentheses(\"(()\") == False", "assert validate_parentheses(\"())\") == False", "assert validate_parentheses(\"a(b)c(d)e\") == True", "assert validate_parentheses(\"a(b(c)d)e\") == True", "assert validate_parentheses(\"a(b(c)d\") == False", "assert validate_parentheses(\"a)bc(\") == False"], "function": "validate_parentheses", "signature": "def validate_parentheses(s):", "score": 1.0, "domain": "generic"} {"id": "57bdf0851e2a4bbacae5a21d62043ed0", "problem": "You are given a binary tree where each node contains an integer value, and pointers to its left and right children. Your task is to implement a function that performs an in-order traversal of the tree and returns a list of the node values in the order they were visited. The binary tree is represented by the `TreeNode` class, which has the following attributes:\n- `value`: An integer representing the value of the node.\n- `left`: A pointer to the left child node, which is either an instance of `TreeNode` or `None`.\n- `right`: A pointer to the right child node, which is either an instance of `TreeNode` or `None`.\n\n**Input:**\n- The root node of the binary tree.\n\n**Output:**\n- A list of integers representing the in-order traversal of the tree.\n\n**Sample Input:**\n```\n 1\n \\\n 2\n /\n 3\n```\n\n**Sample Output:**\n```\n[1, 3, 2]\n```", "reference": "class TreeNode:\n def __init__(self, value=0, left=None, right=None):\n self.value = value\n self.left = left\n self.right = right\n\ndef inorder_traversal(root):\n \"\"\"\n Perform an in-order traversal of a binary tree and return the node values in the order they were visited.\n\n :param root: TreeNode, the root of the binary tree\n :return: List[int], the in-order traversal of the tree\n \"\"\"\n result = []\n def traverse(node):\n if not node:\n return\n traverse(node.left)\n result.append(node.value)\n traverse(node.right)\n traverse(root)\n return result", "tests": ["assert inorder_traversal(None) == []", "assert inorder_traversal(TreeNode(1)) == [1]", "assert inorder_traversal(TreeNode(2, TreeNode(1), TreeNode(3))) == [1, 2, 3]", "assert inorder_traversal(TreeNode(4, TreeNode(2, TreeNode(1), TreeNode(3)), TreeNode(6, TreeNode(5), TreeNode(7)))) == [1, 2, 3, 4, 5, 6, 7]", "assert inorder_traversal(TreeNode(5, None, TreeNode(6, TreeNode(7)))) == [5, 7, 6]", "assert inorder_traversal(TreeNode(8, TreeNode(4, TreeNode(2, TreeNode(1), TreeNode(3)), TreeNode(6, TreeNode(5), TreeNode(7))), TreeNode(12, TreeNode(10, TreeNode(9), TreeNode(11)), TreeNode(14, TreeNode(13), TreeNode(15))))) == [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]", "assert inorder_traversal(TreeNode(10, TreeNode(5), TreeNode(15, TreeNode(12), TreeNode(20)))) == [5, 10, 12, 15, 20]", "assert inorder_traversal(TreeNode(1, None, TreeNode(2, None, TreeNode(3)))) == [1, 2, 3]", "assert inorder_traversal(TreeNode(3, TreeNode(2, TreeNode(1)), None)) == [1, 2, 3]", "assert inorder_traversal(TreeNode(7, TreeNode(3, TreeNode(1, None, TreeNode(2)), TreeNode(5)), TreeNode(9, None, TreeNode(10)))) == [1, 2, 3, 5, 7, 9, 10]"], "function": "inorder_traversal", "signature": "def inorder_traversal(root):", "score": 1.0, "domain": "generic"} {"id": "6f630222602c1001f936ea19e286b5f3", "problem": "You are given a tuple of floating-point numbers and an integer representing the precision. Your task is to implement a function `round_tuple_values_with_precision` that rounds each number in the tuple to the specified precision without converting the numbers to strings or using any built-in rounding functions. The function should return a new tuple with the rounded values.\n\n**Input:**\n- A tuple of floating-point numbers `float_tuple`.\n- An integer `precision` indicating the number of decimal places to round to.\n\n**Output:**\n- A tuple of floating-point numbers where each number is rounded to the specified precision.\n\n**Sample Input:**\n```python\nexample_tuple = (1.234, 2.567, 3.891)\nprecision = 2\n```\n\n**Sample Output:**\n```python\n(1.23, 2.57, 3.89)\n```", "reference": "def round_tuple_values_with_precision(float_tuple, precision):\n \"\"\"\n Rounds each number in the given tuple to the specified precision without using\n string conversion or built-in rounding functions.\n\n :param float_tuple: Tuple of floating-point numbers to be rounded.\n :param precision: Integer representing the number of decimal places to round to.\n :return: A new tuple with the rounded values.\n \"\"\"\n rounded_values = []\n \n for num in float_tuple:\n factor = 10 ** precision\n # Multiply the number by the factor, adjust for rounding, and then truncate using int division\n rounded_num = (int(num * factor + 0.5 if num >= 0 else num * factor - 0.5)) / factor\n rounded_values.append(rounded_num)\n \n return tuple(rounded_values)", "tests": ["assert round_tuple_values_with_precision((1.234, 2.567, 3.891), 2) == (1.23, 2.57, 3.89)", "assert round_tuple_values_with_precision((1.235, 2.565, 3.895), 2) == (1.24, 2.57, 3.90)", "assert round_tuple_values_with_precision((1.2345, 2.5678, 3.8912), 3) == (1.235, 2.568, 3.891)", "assert round_tuple_values_with_precision((-1.234, -2.567, -3.891), 2) == (-1.23, -2.57, -3.89)", "assert round_tuple_values_with_precision((-1.235, -2.565, -3.895), 2) == (-1.24, -2.57, -3.90)", "assert round_tuple_values_with_precision((0.0, 0.0, 0.0), 2) == (0.0, 0.0, 0.0)", "assert round_tuple_values_with_precision((1.0, 2.0, 3.0), 0) == (1.0, 2.0, 3.0)", "assert round_tuple_values_with_precision((1.999, 2.999, 3.999), 2) == (2.0, 3.0, 4.0)", "assert round_tuple_values_with_precision((1.001, 2.001, 3.001), 2) == (1.0, 2.0, 3.0)", "assert round_tuple_values_with_precision((123.456, 789.123, 456.789), 1) == (123.5, 789.1, 456.8)"], "function": "round_tuple_values_with_precision", "signature": "def round_tuple_values_with_precision(float_tuple, precision):", "score": 1.0, "domain": "generic"} {"id": "819d5156812a4a847b77a30a81419b5e", "problem": "You are given a dictionary `input_dict` where each key is unique. Your task is to create a function `swap_keys_values` that returns a new dictionary with keys and values swapped. If a value appears more than once in the original dictionary, the corresponding key in the new dictionary should be a list containing all the keys from the original dictionary that had that value. \n\n**Input:**\n- A dictionary `input_dict` with unique keys.\n\n**Output:**\n- A dictionary with keys and values swapped. If a value appears multiple times in the input dictionary, the corresponding key in the output dictionary should be a list of keys from the input dictionary.\n\n**Sample Input:**\n```python\n{\"a\": 1, \"b\": 2, \"c\": 2, \"d\": 3}\n```\n\n**Sample Output:**\n```python\n{1: \"a\", 2: [\"b\", \"c\"], 3: \"d\"}\n```", "reference": "def swap_keys_values(input_dict):\n \"\"\"\n Swaps the keys and values of the input dictionary. If a value appears more than once,\n the corresponding key in the new dictionary is a list of all keys that had that value.\n\n :param input_dict: Dictionary with unique keys.\n :return: Dictionary with keys and values swapped.\n \"\"\"\n swapped_dict = {}\n for key, value in input_dict.items():\n if value in swapped_dict:\n if not isinstance(swapped_dict[value], list):\n swapped_dict[value] = [swapped_dict[value]]\n swapped_dict[value].append(key)\n else:\n swapped_dict[value] = key\n return swapped_dict", "tests": ["assert swap_keys_values({'a': 1, 'b': 2, 'c': 3}) == {1: 'a', 2: 'b', 3: 'c'}", "assert swap_keys_values({'a': 1, 'b': 1, 'c': 2}) == {1: ['a', 'b'], 2: 'c'}", "assert swap_keys_values({'x': 10, 'y': 20, 'z': 10}) == {10: ['x', 'z'], 20: 'y'}", "assert swap_keys_values({'one': 'first', 'two': 'second', 'three': 'first'}) == {'first': ['one', 'three'], 'second': 'two'}", "assert swap_keys_values({}) == {}", "assert swap_keys_values({'single': 'only'}) == {'only': 'single'}", "assert swap_keys_values({'a': 1, 'b': 2, 'c': 3, 'd': 2}) == {1: 'a', 2: ['b', 'd'], 3: 'c'}", "assert swap_keys_values({'key1': 'value1', 'key2': 'value2', 'key3': 'value1', 'key4': 'value3'}) == {'value1': ['key1', 'key3'], 'value2': 'key2', 'value3': 'key4'}", "assert swap_keys_values({'k1': 'v1', 'k2': 'v2', 'k3': 'v3', 'k4': 'v2', 'k5': 'v1'}) == {'v1': ['k1', 'k5'], 'v2': ['k2', 'k4'], 'v3': 'k3'}", "assert swap_keys_values({'unique': 'unique'}) == {'unique': 'unique'}"], "function": "swap_keys_values", "signature": "def swap_keys_values(input_dict):", "score": 1.0, "domain": "generic"} {"id": "3d4d4255cabd21971ef2d7a96bf4ca56", "problem": "You are given an array of integers `nums`. Your task is to write a function `find_max_min(nums: List[int]) -> Tuple[int, int]` that efficiently computes and returns a tuple containing the maximum and minimum values in the array. The function must operate in O(n) time complexity.\n\n**Constraints:**\n- The array `nums` will contain at least one integer.\n- The integers in the array can range from -10^9 to 10^9.\n\n**Sample Input:**\n```python\nnums = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]\n```\n\n**Sample Output:**\n```python\n(9, 1)\n```", "reference": "from typing import List, Tuple\n\ndef find_max_min(nums: List[int]) -> Tuple[int, int]:\n \"\"\"\n Finds the maximum and minimum values in a list of integers.\n\n Args:\n nums (List[int]): A list of integers.\n\n Returns:\n Tuple[int, int]: A tuple containing the maximum and minimum values in the list.\n \"\"\"\n max_val = float('-inf')\n min_val = float('inf')\n \n for num in nums:\n if num > max_val:\n max_val = num\n if num < min_val:\n min_val = num\n \n return max_val, min_val", "tests": ["assert find_max_min([3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]) == (9, 1)", "assert find_max_min([10]) == (10, 10)", "assert find_max_min([-10, -20, -30, -40]) == (-10, -40)", "assert find_max_min([0, 0, 0, 0]) == (0, 0)", "assert find_max_min([100, 200, 300, 400, 500]) == (500, 100)", "assert find_max_min([-1, 0, 1]) == (1, -1)", "assert find_max_min([1000, -1000, 500, -500]) == (1000, -1000)", "assert find_max_min([7, 7, 7, 7, 7, 7]) == (7, 7)", "assert find_max_min([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) == (10, 1)", "assert find_max_min([10, 9, 8, 7, 6, 5, 4, 3, 2, 1]) == (10, 1)"], "function": "find_max_min", "signature": "def find_max_min(nums: List[int]) -> Tuple[int, int]:", "score": 1.0, "domain": "generic"} {"id": "8c94ba2009481c5d9fce84879db48fed", "problem": "You are given a list of distinct integers. Your task is to write a recursive function `generate_permutations` that generates all possible permutations of the given list. Return the permutations as a list of lists.\n\n**Input:**\n- A list of distinct integers `nums` (1 ≤ len(nums) ≤ 6).\n\n**Output:**\n- A list of lists, where each inner list is a unique permutation of the input list.\n\n**Sample Input:**\n```\n[1, 2, 3]\n```\n\n**Sample Output:**\n```\n[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]\n```", "reference": "def generate_permutations(nums):\n \"\"\"\n Generate all permutations of a given list of distinct integers.\n\n :param nums: List of distinct integers.\n :return: List of lists, where each inner list is a unique permutation of the input list.\n \"\"\"\n def backtrack(path, used, res):\n if len(path) == len(nums):\n res.append(path[:])\n return\n for i in range(len(nums)):\n if used[i]:\n continue\n used[i] = True\n path.append(nums[i])\n backtrack(path, used, res)\n path.pop()\n used[i] = False\n\n result = []\n if not nums:\n return result\n used = [False] * len(nums)\n backtrack([], used, result)\n return result", "tests": ["assert generate_permutations([1, 2, 3]) == [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]", "assert generate_permutations([1]) == [[1]]", "assert generate_permutations([]) == []", "assert generate_permutations([1, 2]) == [[1, 2], [2, 1]]", "assert generate_permutations([1, 1, 2]) == [[1, 1, 2], [1, 2, 1], [2, 1, 1]]", "assert generate_permutations([1, 2, 3, 4]) == [[1, 2, 3, 4], [1, 2, 4, 3], [1, 3, 2, 4], [1, 3, 4, 2], [1, 4, 2, 3], [1, 4, 3, 2], [2, 1, 3, 4], [2, 1, 4, 3], [2, 3, 1, 4], [2, 3, 4, 1], [2, 4, 1, 3], [2, 4, 3, 1], [3, 1, 2, 4], [3, 1, 4, 2], [3, 2, 1, 4], [3, 2, 4, 1], [3, 4, 1, 2], [3, 4, 2, 1], [4, 1, 2, 3], [4, 1, 3, 2], [4, 2, 1, 3], [4, 2, 3, 1], [4, 3, 1, 2], [4, 3, 2, 1]]", "assert generate_permutations([5]) == [[5]]", "assert generate_permutations([0, 1]) == [[0, 1], [1, 0]]", "assert generate_permutations([1, 1]) == [[1, 1]]", "assert generate_permutations([1, 2, 2]) == [[1, 2, 2], [2, 1, 2], [2, 2, 1]]"], "function": "generate_permutations", "signature": "def generate_permutations(nums):", "score": 0.7, "domain": "generic"} {"id": "ca5b73715252ddcfa5f242e4314d68d5", "problem": "You are given a list of integers `nums`. Your task is to determine if there exists at least one number in the list that has a prime factor greater than 10. Implement the function `has_prime_factor(nums)` without using any built-in functions for prime factorization or checking for prime numbers. You must write your own logic for these operations.\n\n**Input:**\n- A list of integers `nums` (1 ≤ len(nums) ≤ 100), where each integer is in the range 1 ≤ nums[i] ≤ 1000.\n\n**Output:**\n- Return `True` if there is at least one number in the list that has a prime factor greater than 10. Otherwise, return `False`.\n\n**Sample Input:**\n```\n[14, 15, 21, 22]\n```\n\n**Sample Output:**\n```\nFalse\n```\n\n**Sample Input:**\n```\n[14, 15, 21, 22, 29]\n```\n\n**Sample Output:**\n```\nTrue\n```", "reference": "def is_prime(n):\n \"\"\"\n Check if a number is prime.\n \n :param n: Integer to check for primality.\n :return: True if n is prime, False otherwise.\n \"\"\"\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == 0 or n % 3 == 0:\n return False\n i = 5\n while i * i <= n:\n if n % i == 0 or n % (i + 2) == 0:\n return False\n i += 6\n return True\n\ndef has_prime_factor(nums):\n \"\"\"\n Determine if there is at least one number in the list that has a prime factor greater than 10.\n \n :param nums: List of integers.\n :return: True if there is at least one number with a prime factor greater than 10, False otherwise.\n \"\"\"\n def has_large_prime_factor(num):\n \"\"\"\n Check if a number has a prime factor greater than 10.\n \n :param num: Integer to check for large prime factors.\n :return: True if num has a prime factor greater than 10, False otherwise.\n \"\"\"\n if num < 2:\n return False\n for i in range(2, num + 1):\n if num % i == 0:\n if is_prime(i) and i > 10:\n return True\n num //= i\n return False\n\n for num in nums:\n if has_large_prime_factor(num):\n return True\n return False", "tests": ["assert has_prime_factor([14, 15, 21, 22]) == False", "assert has_prime_factor([14, 15, 21, 22, 29]) == True", "assert has_prime_factor([4, 6, 8, 9, 10]) == False", "assert has_prime_factor([11, 13, 17, 19]) == True", "assert has_prime_factor([1, 2, 3, 5, 7]) == False", "assert has_prime_factor([100, 101, 102, 103]) == True", "assert has_prime_factor([30, 42, 55, 77]) == True", "assert has_prime_factor([121, 143, 169, 187]) == True", "assert has_prime_factor([25, 49, 81, 121]) == False", "assert has_prime_factor([]) == False"], "function": "has_prime_factor", "signature": "def has_prime_factor(nums):", "score": 0.8, "domain": "generic"} {"id": "d057c9711d63c3b97dc95907ce85b528", "problem": "You are given two strings `str1` and `str2`. Your task is to implement a function `find_longest_common_subsequence(str1, str2)` that computes the longest common subsequence (LCS) between the two strings using dynamic programming. The function should return a tuple containing the length of the LCS and the LCS itself as a string.\n\n**Input:**\n- Two strings `str1` and `str2` (1 ≤ |str1|, |str2| ≤ 1000).\n\n**Output:**\n- A tuple `(length, lcs)` where `length` is the length of the LCS and `lcs` is the LCS itself.\n\n**Sample Input:**\n```\nstr1 = \"AGGTAB\"\nstr2 = \"GXTXAYB\"\n```\n\n**Sample Output:**\n```\n(4, \"GTAB\")\n```", "reference": "def find_longest_common_subsequence(str1, str2):\n \"\"\"\n Computes the longest common subsequence (LCS) between two strings using dynamic programming.\n \n Parameters:\n str1 (str): The first input string.\n str2 (str): The second input string.\n \n Returns:\n tuple: A tuple containing the length of the LCS and the LCS itself as a string.\n \"\"\"\n m, n = len(str1), len(str2)\n \n # Create a 2D array to store lengths of longest common suffixes of substrings\n dp = [[0] * (n + 1) for _ in range(m + 1)]\n \n # Build the dp array from bottom up\n for i in range(1, m + 1):\n for j in range(1, n + 1):\n if str1[i - 1] == str2[j - 1]:\n dp[i][j] = dp[i - 1][j - 1] + 1\n else:\n dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])\n \n # Reconstruct the longest common subsequence from the dp array\n lcs = []\n i, j = m, n\n while i > 0 and j > 0:\n if str1[i - 1] == str2[j - 1]:\n lcs.append(str1[i - 1])\n i -= 1\n j -= 1\n elif dp[i - 1][j] > dp[i][j - 1]:\n i -= 1\n else:\n j -= 1\n \n # The lcs list contains the LCS in reverse order\n lcs.reverse()\n \n # Convert list to string\n lcs_string = ''.join(lcs)\n \n # Return the length of the LCS and the LCS itself\n return dp[m][n], lcs_string", "tests": ["assert find_longest_common_subsequence(\"AGGTAB\", \"GXTXAYB\") == (4, \"GTAB\")", "assert find_longest_common_subsequence(\"ABC\", \"AC\") == (2, \"AC\")", "assert find_longest_common_subsequence(\"ABC\", \"DEF\") == (0, \"\")", "assert find_longest_common_subsequence(\"aaaa\", \"aa\") == (2, \"aa\")", "assert find_longest_common_subsequence(\"abcde\", \"ace\") == (3, \"ace\")", "assert find_longest_common_subsequence(\"abcdef\", \"zabcf\") == (4, \"abcf\")", "assert find_longest_common_subsequence(\"\", \"abc\") == (0, \"\")", "assert find_longest_common_subsequence(\"abc\", \"\") == (0, \"\")", "assert find_longest_common_subsequence(\"\", \"\") == (0, \"\")", "assert find_longest_common_subsequence(\"12345\", \"54321\") == (1, \"1\")"], "function": "find_longest_common_subsequence", "signature": "def find_longest_common_subsequence(str1, str2):", "score": 0.9, "domain": "generic"} {"id": "4c71605c923732b3e7d3cb1da0f4ca6c", "problem": "You are given a list of tuples, where each tuple consists of a person's name and their age. Your task is to implement a function that sorts this list in descending order based on the age of the individuals. The function should return the sorted list.\n\n**Input:**\n- A list of tuples, where each tuple contains a string (name) and an integer (age).\n\n**Output:**\n- A list of tuples sorted by age in descending order.\n\n**Sample Input:**\n```python\n[(\"Alice\", 30), (\"Bob\", 25), (\"Charlie\", 35)]\n```\n\n**Sample Output:**\n```python\n[(\"Charlie\", 35), (\"Alice\", 30), (\"Bob\", 25)]\n```", "reference": "def sort_people_by_age(people_list):\n \"\"\"\n Sorts a list of tuples containing names and ages in descending order based on age.\n\n :param people_list: List of tuples, where each tuple contains a name and an age.\n :return: A list of tuples sorted by age in descending order.\n \"\"\"\n return sorted(people_list, key=lambda person: person[1], reverse=True)\n\n# Example usage\npeople = [(\"Alice\", 30), (\"Bob\", 25), (\"Charlie\", 35)]\nsorted_people = sort_people_by_age(people)\nprint(sorted_people) # Output: [(\"Charlie\", 35), (\"Alice\", 30), (\"Bob\", 25)]", "tests": ["assert sort_people_by_age([(\"Alice\", 30), (\"Bob\", 25), (\"Charlie\", 35)]) == [(\"Charlie\", 35), (\"Alice\", 30), (\"Bob\", 25)]", "assert sort_people_by_age([(\"Anna\", 22), (\"Tom\", 45), (\"John\", 30)]) == [(\"Tom\", 45), (\"John\", 30), (\"Anna\", 22)]", "assert sort_people_by_age([(\"Eve\", 29), (\"Eve\", 29), (\"Eve\", 29)]) == [(\"Eve\", 29), (\"Eve\", 29), (\"Eve\", 29)]", "assert sort_people_by_age([(\"Zoe\", 18)]) == [(\"Zoe\", 18)]", "assert sort_people_by_age([]) == []", "assert sort_people_by_age([(\"Sam\", 50), (\"Dean\", 50), (\"Castiel\", 50)]) == [(\"Sam\", 50), (\"Dean\", 50), (\"Castiel\", 50)]", "assert sort_people_by_age([(\"Sarah\", 23), (\"Mike\", 23), (\"Chris\", 22)]) == [(\"Sarah\", 23), (\"Mike\", 23), (\"Chris\", 22)]", "assert sort_people_by_age([(\"Ava\", 33), (\"Sophia\", 32), (\"Isabella\", 34)]) == [(\"Isabella\", 34), (\"Ava\", 33), (\"Sophia\", 32)]", "assert sort_people_by_age([(\"Olivia\", 28), (\"Emma\", 27), (\"Ava\", 29)]) == [(\"Ava\", 29), (\"Olivia\", 28), (\"Emma\", 27)]", "assert sort_people_by_age([(\"Noah\", 21), (\"Liam\", 20), (\"Mason\", 22)]) == [(\"Mason\", 22), (\"Noah\", 21), (\"Liam\", 20)]"], "function": "sort_people_by_age", "signature": "def sort_people_by_age(people_list):", "score": 1.0, "domain": "generic"} {"id": "4563d587628d2b215bd6d1a2c7f69dbf", "problem": "You are tasked with implementing a function `generate_fibonacci_sequence` that generates the Fibonacci sequence up to a specified number of terms. The Fibonacci sequence is defined such that the first term is 1, the second term is 1, and each subsequent term is the sum of the two preceding terms. Your function should take a single integer `n` as input, representing the number of terms to generate, and return a list containing the first `n` terms of the Fibonacci sequence. It is guaranteed that `n` is a positive integer.\n\n**Sample Input:**\n```\n5\n```\n\n**Sample Output:**\n```\n[1, 1, 2, 3, 5]\n```", "reference": "def generate_fibonacci_sequence(n):\n \"\"\"\n Generates a Fibonacci sequence up to a specified number of terms.\n\n Parameters:\n n (int): The number of terms in the Fibonacci sequence to generate.\n\n Returns:\n list: A list containing the first n terms of the Fibonacci sequence.\n \"\"\"\n if n == 1:\n return [1]\n elif n == 2:\n return [1, 1]\n \n fib_sequence = [1, 1]\n for i in range(2, n):\n fib_sequence.append(fib_sequence[-1] + fib_sequence[-2])\n \n return fib_sequence\n\n# Example usage:\n# print(generate_fibonacci_sequence(5)) # Output: [1, 1, 2, 3, 5]", "tests": ["assert generate_fibonacci_sequence(1) == [1]", "assert generate_fibonacci_sequence(2) == [1, 1]", "assert generate_fibonacci_sequence(3) == [1, 1, 2]", "assert generate_fibonacci_sequence(4) == [1, 1, 2, 3]", "assert generate_fibonacci_sequence(5) == [1, 1, 2, 3, 5]", "assert generate_fibonacci_sequence(6) == [1, 1, 2, 3, 5, 8]", "assert generate_fibonacci_sequence(7) == [1, 1, 2, 3, 5, 8, 13]", "assert generate_fibonacci_sequence(10) == [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]", "assert generate_fibonacci_sequence(15) == [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610]", "assert generate_fibonacci_sequence(20) == [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765]"], "function": "generate_fibonacci_sequence", "signature": "def generate_fibonacci_sequence(n):", "score": 1.0, "domain": "generic"} {"id": "b0e54b8dca7a93a31ea541967a5fa123", "problem": "Given a list of integers, your task is to implement a function that identifies the two largest distinct numbers and returns them as a tuple. If the list contains fewer than two distinct numbers, the function should return `None`. \n\n**Input:**\n- A list of integers, `numbers` (1 ≤ len(numbers) ≤ 10^5), where each integer is in the range [-10^9, 10^9].\n\n**Output:**\n- A tuple containing the two largest distinct integers in descending order, or `None` if there are fewer than two distinct integers.\n\n**Sample Input:**\n```\n[5, 3, 9, 1, 9, 5]\n```\n\n**Sample Output:**\n```\n(9, 5)\n```", "reference": "def find_two_largest_distinct(numbers):\n \"\"\"\n Finds the two largest distinct numbers in a list and returns them as a tuple.\n If there are fewer than two distinct numbers, returns None.\n \n :param numbers: List of integers\n :return: Tuple of two largest distinct integers or None\n \"\"\"\n distinct_numbers = sorted(set(numbers), reverse=True)\n if len(distinct_numbers) < 2:\n return None\n return (distinct_numbers[0], distinct_numbers[1])\n\n# Example usage\nexample_input = [5, 3, 9, 1, 9, 5]\nresult = find_two_largest_distinct(example_input)\nprint(result) # Output should be (9, 5)", "tests": ["assert find_two_largest_distinct([5, 3, 9, 1, 9, 5]) == (9, 5)", "assert find_two_largest_distinct([1, 2, 3, 4, 5]) == (5, 4)", "assert find_two_largest_distinct([10, 10, 10]) == None", "assert find_two_largest_distinct([1]) == None", "assert find_two_largest_distinct([]) == None", "assert find_two_largest_distinct([7, 7, 8, 8, 9, 9]) == (9, 8)", "assert find_two_largest_distinct([-1, -2, -3, -4]) == (-1, -2)", "assert find_two_largest_distinct([0, 0, 0, 1]) == (1, 0)", "assert find_two_largest_distinct([100, 90]) == (100, 90)", "assert find_two_largest_distinct([5, 5, 5, 5, 5, 5, 5, 5, 5, 5]) == None"], "function": "find_two_largest_distinct", "signature": "def find_two_largest_distinct(numbers):", "score": 1.0, "domain": "generic"} {"id": "27e281fc829b80bcb4d5312de18f0dbc", "problem": "Implement the bubble sort algorithm in Python. Your function should take a list of integers as input and return the sorted list. The input list will contain between 1 and 1000 elements, each ranging from -1000 to 1000.\n\n**Sample Input:**\n```\n[64, 34, 25, 12, 22, 11, 90]\n```\n\n**Sample Output:**\n```\n[11, 12, 22, 25, 34, 64, 90]\n```", "reference": "def bubble_sort(arr):\n \"\"\"\n Sorts a list of integers using the bubble sort algorithm.\n\n Parameters:\n arr (list): A list of integers to be sorted.\n\n Returns:\n list: The sorted list of integers.\n \"\"\"\n n = len(arr)\n for i in range(n):\n for j in range(0, n-i-1):\n if arr[j] > arr[j+1]:\n arr[j], arr[j+1] = arr[j+1], arr[j]\n return arr\n\n# Example usage:\narray = [64, 34, 25, 12, 22, 11, 90]\nsorted_array = bubble_sort(array)\nprint(\"Sorted array:\", sorted_array)", "tests": ["assert bubble_sort([64, 34, 25, 12, 22, 11, 90]) == [11, 12, 22, 25, 34, 64, 90]", "assert bubble_sort([5, 1, 4, 2, 8]) == [1, 2, 4, 5, 8]", "assert bubble_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]", "assert bubble_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5]", "assert bubble_sort([]) == []", "assert bubble_sort([1]) == [1]", "assert bubble_sort([3, 3, 3, 3, 3]) == [3, 3, 3, 3, 3]", "assert bubble_sort([10, -1, 2, 5, 0]) == [-1, 0, 2, 5, 10]", "assert bubble_sort([100, 200, 300, 400, 500]) == [100, 200, 300, 400, 500]", "assert bubble_sort([-10, -20, -30, -40, -50]) == [-50, -40, -30, -20, -10]"], "function": "bubble_sort", "signature": "def bubble_sort(arr):", "score": 1.0, "domain": "generic"} {"id": "cd2823005c7f0d82e13165a55bb0bcad", "problem": "You are given a positive integer `n`. Your task is to compute the sum of the first `n` numbers in a modified Fibonacci sequence. This sequence starts with 2 and 3, and each subsequent number is the sum of the previous two numbers. \n\n**Constraints:**\n- `1 ≤ n ≤ 10^6`\n\n**Input:**\n- An integer `n`.\n\n**Output:**\n- The sum of the first `n` numbers in the modified Fibonacci sequence.\n\n**Sample Input:**\n```\n5\n```\n\n**Sample Output:**\n```\n19\n```", "reference": "def fibonacci_sum(n):\n \"\"\"\n Computes the sum of the first n numbers in a modified Fibonacci sequence\n starting with 2 and 3, where each subsequent number is the sum of the\n previous two numbers.\n\n Parameters:\n n (int): The number of terms in the sequence to sum.\n\n Returns:\n int: The sum of the first n numbers in the sequence.\n\n Raises:\n TypeError: If the input is not an integer.\n ValueError: If the input is less than 1.\n \"\"\"\n if not isinstance(n, int):\n raise TypeError(\"Input must be an integer.\")\n if n < 1:\n raise ValueError(\"Input must be greater than or equal to 1.\")\n \n if n == 1:\n return 2\n elif n == 2:\n return 5\n \n a, b = 2, 3\n total_sum = a + b\n \n for _ in range(2, n):\n a, b = b, a + b\n total_sum += b\n \n return total_sum", "tests": ["assert fibonacci_sum(1) == 2", "assert fibonacci_sum(2) == 5", "assert fibonacci_sum(3) == 10", "assert fibonacci_sum(4) == 17", "assert fibonacci_sum(5) == 27", "assert fibonacci_sum(6) == 44", "assert fibonacci_sum(7) == 71", "assert fibonacci_sum(8) == 115", "assert fibonacci_sum(9) == 186", "assert fibonacci_sum(10) == 301"], "function": "fibonacci_sum", "signature": "def fibonacci_sum(n):", "score": 0.3, "domain": "generic"} {"id": "f1ad044c33bd7ce95f15891f352d42cf", "problem": "You are given a string representing a mathematical expression consisting of integers, the operators `+`, `-`, `*`, `/`, and parentheses `()`. Your task is to write a Python function that evaluates the expression and returns the result. Assume that the input string is well-formed and does not contain any invalid characters or operators.\n\n**Input:**\n- A single string representing the mathematical expression.\n\n**Output:**\n- An integer or float representing the result of the evaluated expression.\n\n**Sample Input:**\n```\n\"3 + 5 * (2 - 8)\"\n```\n\n**Sample Output:**\n```\n-17\n```", "reference": "import ast\nimport operator\n\n# Supported operators\noperators = {\n ast.Add: operator.add,\n ast.Sub: operator.sub,\n ast.Mult: operator.mul,\n ast.Div: operator.truediv,\n}\n\nclass Evaluator(ast.NodeVisitor):\n def visit_BinOp(self, node):\n \"\"\"Recursively evaluate binary operations.\"\"\"\n left = self.visit(node.left)\n right = self.visit(node.right)\n return operators[type(node.op)](left, right)\n\n def visit_Num(self, node):\n \"\"\"Return the numeric value of a node.\"\"\"\n return node.n\n\n def visit_Expr(self, node):\n \"\"\"Handle the root expression node.\"\"\"\n return self.visit(node.value)\n\n def visit_UnaryOp(self, node):\n \"\"\"Evaluate unary operations.\"\"\"\n operand = self.visit(node.operand)\n if isinstance(node.op, ast.USub):\n return -operand\n elif isinstance(node.op, ast.UAdd):\n return operand\n else:\n raise ValueError(\"Unsupported unary operator\")\n\n def visit_Paren(self, node):\n \"\"\"Evaluate expressions within parentheses.\"\"\"\n return self.visit(node.value)\n\n def visit_Call(self, node):\n \"\"\"Handle function calls (future extension).\"\"\"\n func = self.visit(node.func)\n args = [self.visit(arg) for arg in node.args]\n return func(*args)\n\n def visit_List(self, node):\n \"\"\"Handle lists (future extension).\"\"\"\n return [self.visit(item) for item in node.elts]\n\n def visit_Tuple(self, node):\n \"\"\"Handle tuples (future extension).\"\"\"\n return tuple(self.visit(item) for item in node.elts)\n\n def eval(self, expression):\n \"\"\"Parse and evaluate the given expression.\"\"\"\n tree = ast.parse(expression, mode='eval')\n return self.visit(tree.body)\n\ndef evaluate_math_expression(expression):\n \"\"\"\n Evaluate a mathematical expression given as a string.\n\n :param expression: A string representing the mathematical expression.\n :return: The result of the evaluated expression.\n \"\"\"\n evaluator = Evaluator()\n return evaluator.eval(expression)\n\n# Example usage:\nexpression = \"3 + 5 * (2 - 8)\"\nresult = evaluate_math_expression(expression)\nprint(result) # Output: -17", "tests": ["assert evaluate_math_expression(\"3 + 5 * (2 - 8)\") == -17", "assert evaluate_math_expression(\"10 + 2 * 6\") == 22", "assert evaluate_math_expression(\"100 * 2 + 12\") == 212", "assert evaluate_math_expression(\"100 * ( 2 + 12 )\") == 1400", "assert evaluate_math_expression(\"100 * ( 2 + 12 ) / 14\") == 100", "assert evaluate_math_expression(\"2 + 3 * 4 / 3 - 6 / 3 * 3 + 8\") == 8", "assert evaluate_math_expression(\"1 + 1\") == 2", "assert evaluate_math_expression(\"1 - 1\") == 0", "assert evaluate_math_expression(\"1 * 1\") == 1", "assert evaluate_math_expression(\"1 / 1\") == 1.0"], "function": "evaluate_math_expression", "signature": "def evaluate_math_expression(expression):", "score": 0.9, "domain": "generic"} {"id": "d9687a8da3f50c758ecb884454b5237e", "problem": "You are given a task to implement a function `calculate_discounted_price(price, discount)` in Python. This function should compute the final price of an item after applying a given discount percentage. The discount is calculated as a percentage of the original price. The result should be rounded to two decimal places.\n\n**Input:**\n- The function takes two arguments:\n - `price` (float): The original price of the item.\n - `discount` (float): The discount percentage to be applied.\n\n**Output:**\n- The function should return a float representing the discounted price, rounded to two decimal places.\n\n**Sample Input/Output:**\n- Input: `calculate_discounted_price(100.00, 20.00)`\n- Output: `80.00`\n- Input: `calculate_discounted_price(250.75, 15.00)`\n- Output: `212.64`", "reference": "def calculate_discounted_price(price, discount):\n \"\"\"\n Calculate the discounted price given the original price and discount percentage.\n\n Args:\n price (float): The original price of the item.\n discount (float): The discount percentage to be applied.\n\n Returns:\n float: The discounted price rounded to two decimal places.\n \"\"\"\n discounted_price = price * (1 - discount / 100)\n return round(discounted_price, 2)", "tests": ["assert calculate_discounted_price(100, 10) == 90.00", "assert calculate_discounted_price(200, 25) == 150.00", "assert calculate_discounted_price(50, 50) == 25.00", "assert calculate_discounted_price(0, 20) == 0.00", "assert calculate_discounted_price(123.45, 10) == 111.11", "assert calculate_discounted_price(99.99, 0) == 99.99", "assert calculate_discounted_price(100, 100) == 0.00", "assert calculate_discounted_price(150.75, 20.5) == 119.56", "assert calculate_discounted_price(300, 75) == 75.00", "assert calculate_discounted_price(1000, 5) == 950.00"], "function": "calculate_discounted_price", "signature": "def calculate_discounted_price(price, discount):", "score": 0.9, "domain": "generic"} {"id": "26d2a69236ae67ecf52663640130ec5b", "problem": "You are developing a simple text-based game where a player can execute two types of commands: \"move\" and \"attack\". Each command consists of an action followed by a target. The action \"move\" can be directed towards one of the four cardinal directions: \"north\", \"south\", \"east\", or \"west\". The action \"attack\" can only target \"enemy\". Your task is to implement a function `interpret_command(command)` that parses a command string and returns a dictionary with the keys \"action\" and \"target\". If the command does not conform to the expected format or contains invalid actions or targets, the function should raise a `ValueError` with the appropriate message.\n\n**Input:**\n- A single string `command` representing the player's action.\n\n**Output:**\n- A dictionary with keys \"action\" and \"target\" if the command is valid.\n- Raises a `ValueError` with the message \"Invalid command format\" if the command does not have exactly two parts.\n- Raises a `ValueError` with the message \"Invalid action or target\" if the action or target is not recognized.\n\n**Sample Input/Output:**\n- Input: `\"move north\"`\n - Output: `{\"action\": \"move\", \"target\": \"north\"}`\n- Input: `\"attack enemy\"`\n - Output: `{\"action\": \"attack\", \"target\": \"enemy\"}`\n- Input: `\"move up\"`\n - Output: Raises `ValueError(\"Invalid action or target\")`\n- Input: `\"jump high\"`\n - Output: Raises `ValueError(\"Invalid action or target\")`\n- Input: `\"move north south\"`\n - Output: Raises `ValueError(\"Invalid command format\")`", "reference": "def interpret_command(command):\n \"\"\"\n Parses a command string and returns a dictionary with the action and target.\n \n Args:\n command (str): A string representing the player's action.\n \n Returns:\n dict: A dictionary with keys \"action\" and \"target\" if the command is valid.\n \n Raises:\n ValueError: If the command format is invalid or contains invalid actions or targets.\n \"\"\"\n valid_actions = [\"move\", \"attack\"]\n valid_targets_move = [\"north\", \"south\", \"east\", \"west\"]\n valid_target_attack = [\"enemy\"]\n \n parts = command.split()\n \n if len(parts) != 2:\n raise ValueError(\"Invalid command format\")\n \n action, target = parts\n \n if action not in valid_actions:\n raise ValueError(\"Invalid action or target\")\n \n if action == \"move\" and target not in valid_targets_move:\n raise ValueError(\"Invalid action or target\")\n \n if action == \"attack\" and target not in valid_target_attack:\n raise ValueError(\"Invalid action or target\")\n \n return {\"action\": action, \"target\": target}", "tests": ["assert interpret_command(\"move north\") == {\"action\": \"move\", \"target\": \"north\"}", "assert interpret_command(\"attack enemy\") == {\"action\": \"attack\", \"target\": \"enemy\"}", "assert interpret_command(\"move south\") == {\"action\": \"move\", \"target\": \"south\"}", "assert interpret_command(\"move east\") == {\"action\": \"move\", \"target\": \"east\"}", "assert interpret_command(\"move west\") == {\"action\": \"move\", \"target\": \"west\"}", "assert interpret_command(\"attack enemy\") == {\"action\": \"attack\", \"target\": \"enemy\"}", "assert interpret_command(\"move north\") == {\"action\": \"move\", \"target\": \"north\"}", "assert interpret_command(\"move nowhere\") == {\"action\": \"move\", \"target\": \"nowhere\"}", "assert interpret_command(\"jump north\") == {\"action\": \"jump\", \"target\": \"north\"}", "assert interpret_command(\"attack friend\") == {\"action\": \"attack\", \"target\": \"friend\"}"], "function": "interpret_command", "signature": "def interpret_command(command):", "score": 0.7, "domain": "generic"} {"id": "68d4d07c1c92acaf10c1e5035a2acd2c", "problem": "You are given a JSON string that may contain nested objects and arrays. Your task is to write a function `parse_json_data` that parses this JSON string and returns a Python dictionary. If the JSON string is invalid, the function should return `None`. Your function should handle any parsing errors gracefully.\n\n**Sample Input 1:**\n```\n{\"name\": \"John\", \"age\": 30, \"city\": \"New York\"}\n```\n\n**Sample Output 1:**\n```\n{'name': 'John', 'age': 30, 'city': 'New York'}\n```\n\n**Sample Input 2:**\n```\n{\"name\": \"John\", \"age\": 30, \"city\": \"New York\"\n```\n\n**Sample Output 2:**\n```\nNone\n```", "reference": "import json\n\ndef parse_json_data(json_string):\n \"\"\"\n Parses a JSON string and returns a Python dictionary.\n \n Parameters:\n json_string (str): A string containing JSON data.\n \n Returns:\n dict: A Python dictionary representing the parsed JSON data.\n Returns None if the JSON string is invalid.\n \"\"\"\n try:\n return json.loads(json_string)\n except json.JSONDecodeError:\n return None", "tests": ["assert parse_json_data('{\"name\": \"John\", \"age\": 30, \"city\": \"New York\"}') == {\"name\": \"John\", \"age\": 30, \"city\": \"New York\"}", "assert parse_json_data('{\"name\": \"Alice\", \"age\": 25, \"city\": \"Los Angeles\", \"hobbies\": [\"reading\", \"hiking\"]}') == {\"name\": \"Alice\", \"age\": 25, \"city\": \"Los Angeles\", \"hobbies\": [\"reading\", \"hiking\"]}", "assert parse_json_data('{\"employees\": [{\"name\": \"John\", \"age\": 30}, {\"name\": \"Jane\", \"age\": 25}]}') == {\"employees\": [{\"name\": \"John\", \"age\": 30}, {\"name\": \"Jane\", \"age\": 25}]}", "assert parse_json_data('{\"name\": \"Bob\", \"details\": {\"age\": 40, \"city\": \"Chicago\"}}') == {\"name\": \"Bob\", \"details\": {\"age\": 40, \"city\": \"Chicago\"}}", "assert parse_json_data('{\"numbers\": [1, 2, 3, 4, 5]}') == {\"numbers\": [1, 2, 3, 4, 5]}", "assert parse_json_data('{\"empty\": {}}') == {\"empty\": {}}", "assert parse_json_data('{\"empty_array\": []}') == {\"empty_array\": []}", "assert parse_json_data('{\"name\": \"Charlie\", \"age\": null}') == {\"name\": \"Charlie\", \"age\": None}", "assert parse_json_data('{\"name\": \"David\", \"age\": 35, \"city\": \"San Francisco\", \"is_student\": false}') == {\"name\": \"David\", \"age\": 35, \"city\": \"San Francisco\", \"is_student\": False}", "assert parse_json_data('{\"invalid_json\": \"missing closing brace}') == None"], "function": "parse_json_data", "signature": "def parse_json_data(json_string):", "score": 1.0, "domain": "generic"} {"id": "feee4337d31102fcfe899f7310d18063", "problem": "You are given a sequence of numbers where the first number is 1, and each subsequent number is obtained by adding a fixed positive integer difference `d` to the previous number. This sequence is defined as follows: 1, 1+d, 1+2d, 1+3d, ... Your task is to determine if a given positive integer `n` is part of this sequence.\n\n**Input:**\n- Two integers `n` (1 ≤ n ≤ 10^9) and `d` (1 ≤ d ≤ 10^9), where `n` is the number to check and `d` is the difference between consecutive numbers in the sequence.\n\n**Output:**\n- Return `True` if `n` is a special number in the sequence with difference `d`, otherwise return `False`.\n\n**Sample Input:**\n```\n13 3\n```\n\n**Sample Output:**\n```\nTrue\n```", "reference": "def is_special_number(n, d):\n \"\"\"\n Determines if a given number n is a special number in the sequence\n starting with 1 and having a fixed difference d between consecutive numbers.\n \n :param n: The number to check.\n :param d: The difference between consecutive numbers in the sequence.\n :return: True if n is a special number, False otherwise.\n \"\"\"\n return (n - 1) % d == 0\n\n# Test with given n and d\nn = 13\nd = 3\nprint(is_special_number(n, d)) # Output should be True if 13 is a special number with difference 3", "tests": ["assert is_special_number(1, 3) == True", "assert is_special_number(4, 3) == True", "assert is_special_number(7, 3) == True", "assert is_special_number(10, 3) == True", "assert is_special_number(13, 3) == True", "assert is_special_number(2, 3) == False", "assert is_special_number(5, 3) == False", "assert is_special_number(8, 3) == False", "assert is_special_number(11, 3) == False", "assert is_special_number(14, 3) == False"], "function": "is_special_number", "signature": "def is_special_number(n, d):", "score": 1.0, "domain": "algorithmic"} {"id": "8ad0c70901763b70a8ba6d4a4e9d5562", "problem": "You are given a string representing a simple mathematical expression consisting of non-negative integers and the operators `+`, `-`, `*`, and `/`. The expression does not contain any parentheses or spaces. Your task is to evaluate the expression and return the result as an integer. Assume that the division operator `/` performs integer division.\n\n**Input:**\n- A string `expression` (1 ≤ len(expression) ≤ 100) representing the mathematical expression.\n\n**Output:**\n- An integer representing the result of the evaluated expression.\n\n**Sample Input:**\n```\n3+3*2-1\n```\n\n**Sample Output:**\n```\n8\n```", "reference": "def evaluate_expression(expression: str) -> int:\n \"\"\"\n Evaluates a simple mathematical expression consisting of non-negative integers and the operators\n '+', '-', '*', and '/'. The expression does not contain any parentheses or spaces.\n \n :param expression: A string representing the mathematical expression.\n :return: An integer representing the result of the evaluated expression.\n \"\"\"\n def apply_operation(operators, values):\n operator = operators.pop()\n right = values.pop()\n left = values.pop()\n if operator == '+':\n values.append(left + right)\n elif operator == '-':\n values.append(left - right)\n elif operator == '*':\n values.append(left * right)\n elif operator == '/':\n values.append(left // right)\n\n precedence = {'+': 1, '-': 1, '*': 2, '/': 2}\n operators = []\n values = []\n i = 0\n\n while i < len(expression):\n token = expression[i]\n if token.isdigit():\n j = i\n while j < len(expression) and expression[j].isdigit():\n j += 1\n values.append(int(expression[i:j]))\n i = j - 1\n elif token in precedence:\n while (operators and operators[-1] in precedence and\n precedence[operators[-1]] >= precedence[token]):\n apply_operation(operators, values)\n operators.append(token)\n i += 1\n\n while operators:\n apply_operation(operators, values)\n\n return values[0]", "tests": ["assert evaluate_expression(\"3 + 3 * 2 - 1\") == 8", "assert evaluate_expression(\"10 - 2 * 3\") == 4", "assert evaluate_expression(\"100 / 10 + 5\") == 15", "assert evaluate_expression(\"5 + 5 + 5 + 5\") == 20", "assert evaluate_expression(\"10 * 10 - 100\") == 0", "assert evaluate_expression(\"100 / 10 / 2\") == 5", "assert evaluate_expression(\"1 + 2 * 3 + 4 * 5\") == 23", "assert evaluate_expression(\"7 * 8 - 5 * 4\") == 36", "assert evaluate_expression(\"100 - 50 + 25 * 2\") == 100", "assert evaluate_expression(\"1 * 2 * 3 * 4 * 5\") == 120"], "function": "evaluate_expression", "signature": "def evaluate_expression(expression: str) -> int:", "score": 0.9, "domain": "generic"} {"id": "a1a671486f01d8c47921e9ee2d5ffe23", "problem": "You are tasked with implementing an efficient function to determine if a given integer is a prime number. Your function should return `True` if the number is prime and `False` otherwise. The algorithm should be more efficient than basic trial division, specifically avoiding unnecessary checks beyond the square root of the number.\n\n**Input:**\n- An integer `n` (1 ≤ n ≤ 10^9)\n\n**Output:**\n- A boolean value: `True` if `n` is a prime number, `False` otherwise.\n\n**Sample Input:**\n```\n29\n```\n\n**Sample Output:**\n```\nTrue\n```\n\n**Sample Input:**\n```\n15\n```\n\n**Sample Output:**\n```\nFalse\n```", "reference": "def is_prime(n):\n \"\"\"\n Determines if the given integer n is a prime number.\n \n Args:\n n (int): The integer to check for primality.\n \n Returns:\n bool: True if n is a prime number, False otherwise.\n \"\"\"\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == 0 or n % 3 == 0:\n return False\n i = 5\n while i * i <= n:\n if n % i == 0 or n % (i + 2) == 0:\n return False\n i += 6\n return True", "tests": ["assert is_prime(2) == True", "assert is_prime(3) == True", "assert is_prime(4) == False", "assert is_prime(5) == True", "assert is_prime(9) == False", "assert is_prime(11) == True", "assert is_prime(15) == False", "assert is_prime(17) == True", "assert is_prime(19) == True", "assert is_prime(20) == False"], "function": "is_prime", "signature": "def is_prime(n):", "score": 1.0, "domain": "generic"} {"id": "6a3a606df14304278e3c0cf5e39f5928", "problem": "You are given a list of strings. Your task is to implement a function named `string_length_map` that constructs and returns a dictionary. The keys of this dictionary should be the strings from the input list, and the corresponding values should be the lengths of these strings. \n\n**Input:**\n- A list of strings, where each string consists of lowercase English letters and has a length between 1 and 20 characters.\n- The list can contain up to 100 strings.\n\n**Output:**\n- A dictionary with strings as keys and their respective lengths as values.\n\n**Sample Input:**\n```python\n[\"apple\", \"banana\", \"cherry\"]\n```\n\n**Sample Output:**\n```python\n{'apple': 5, 'banana': 6, 'cherry': 6}\n```", "reference": "def string_length_map(strings):\n \"\"\"\n Constructs a dictionary where keys are strings from the input list\n and values are the lengths of these strings.\n\n :param strings: List of strings\n :return: Dictionary with strings as keys and their lengths as values\n \"\"\"\n return {s: len(s) for s in strings}\n\n# Sample usage\nsample_list = [\"apple\", \"banana\", \"cherry\"]\nresult = string_length_map(sample_list)\nprint(result) # Output: {'apple': 5, 'banana': 6, 'cherry': 6}", "tests": ["assert string_length_map([\"hello\", \"world\"]) == {\"hello\": 5, \"world\": 5}", "assert string_length_map([\"a\", \"ab\", \"abc\"]) == {\"a\": 1, \"ab\": 2, \"abc\": 3}", "assert string_length_map([]) == {}", "assert string_length_map([\"\"]) == {\"\" : 0}", "assert string_length_map([\"Python\", \"is\", \"fun!\"]) == {\"Python\": 6, \"is\": 2, \"fun!\": 4}", "assert string_length_map([\"123\", \"4567\", \"89\"]) == {\"123\": 3, \"4567\": 4, \"89\": 2}", "assert string_length_map([\"!@#\", \"$%^\", \"&*()\"]) == {\"!@#\": 3, \"$%^\": 3, \"&*()\": 4}", "assert string_length_map([\"repeat\", \"repeat\", \"repeat\"]) == {\"repeat\": 6}", "assert string_length_map([\"singleword\"]) == {\"singleword\": 10}", "assert string_length_map([\"Mixed\", \"CASE\", \"test\"]) == {\"Mixed\": 5, \"CASE\": 4, \"test\": 4}"], "function": "string_length_map", "signature": "def string_length_map(strings):", "score": 1.0, "domain": "generic"} {"id": "e603dc3c47d9cbaa4d811b69720c14d4", "problem": "You are given a list of lists `nested_list`. Your task is to write a Python function `flatten_list(nested_list)` that takes this nested list as input and returns a single flattened list containing all the elements from the inner lists in the same order. \n\n**Input:**\n- A list of lists `nested_list` where each sublist contains integers.\n\n**Output:**\n- A single list containing all the integers from the sublists in the order they appear.\n\n**Sample Input:**\n```python\n[[1, 2, 3], [4, 5, 6], [7, 8, 9]]\n```\n\n**Sample Output:**\n```python\n[1, 2, 3, 4, 5, 6, 7, 8, 9]\n```", "reference": "def flatten_list(nested_list):\n \"\"\"\n Flattens a list of lists into a single list with all elements from the inner lists.\n \n :param nested_list: List of lists containing integers.\n :return: A single list with all integers from the sublists.\n \"\"\"\n return [item for sublist in nested_list for item in sublist]\n\n# Example usage\nprint(flatten_list([[1, 2, 3], [4, 5, 6], [7, 8, 9]])) # Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]", "tests": ["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]]) == [1, 2, 3]", "assert flatten_list([[1, 2], [3, 4], [5, 6]]) == [1, 2, 3, 4, 5, 6]", "assert flatten_list([]) == []", "assert flatten_list([[], [], []]) == []", "assert flatten_list([[1, 2, 3]]) == [1, 2, 3]", "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]]) == [1, 2, 3, 4, 5, 6]", "assert flatten_list([['a', 'b'], ['c', 'd'], ['e', 'f']]) == ['a', 'b', 'c', 'd', 'e', 'f']"], "function": "flatten_list", "signature": "def flatten_list(nested_list):", "score": 1.0, "domain": "generic"} {"id": "d745e2779a052be9ae47d6553108b711", "problem": "You are given a string `text` consisting of words separated by spaces and possibly containing punctuation. Your task is to implement a function `find_longest_word` that returns the longest word in the text. If there are multiple words with the same maximum length, return the first one encountered. Words are defined as sequences of alphanumeric characters, ignoring punctuation.\n\n**Input:**\n- A single string `text` (1 ≤ |text| ≤ 10^4).\n\n**Output:**\n- A single string representing the longest word in the text.\n\n**Sample Input:**\n```\nThe quick brown fox jumps over the lazy dog. However, the quick brown fox was very fast and clever.\n```\n\n**Sample Output:**\n```\nHowever\n```", "reference": "import re\n\ndef find_longest_word(text):\n \"\"\"\n Returns the longest word in the given text, ignoring punctuation.\n If multiple words have the same length, the first one encountered is returned.\n \n :param text: A string containing words separated by spaces and possibly punctuation.\n :return: The longest word in the text.\n \"\"\"\n # Use regex to find words, ignoring punctuation\n words = re.findall(r'\\b\\w+\\b', text)\n # Find the longest word\n longest_word = max(words, key=len)\n return longest_word\n\n# Example usage:\ntext = \"The quick brown fox jumps over the lazy dog. However, the quick brown fox was very fast and clever.\"\nprint(find_longest_word(text))", "tests": ["assert find_longest_word(\"The quick brown fox jumps over the lazy dog.\") == \"jumps\"", "assert find_longest_word(\"Hello, world!\") == \"Hello\"", "assert find_longest_word(\"A quick movement of the enemy will jeopardize five gunboats.\") == \"jeopardize\"", "assert find_longest_word(\"To be or not to be, that is the question.\") == \"question\"", "assert find_longest_word(\"One fish, two fish, red fish, blue fish.\") == \"fish\"", "assert find_longest_word(\"All animals are equal, but some animals are more equal than others.\") == \"animals\"", "assert find_longest_word(\"Short words.\") == \"Short\"", "assert find_longest_word(\"Equal words: test test test.\") == \"Equal\"", "assert find_longest_word(\"Punctuation, should! not? affect: the; words.\") == \"Punctuation\"", "assert find_longest_word(\"\") == \"\""], "function": "find_longest_word", "signature": "def find_longest_word(text):", "score": 0.8, "domain": "generic"} {"id": "b204760a42f5c148243b6b6152734ba7", "problem": "You are tasked with implementing a function `convert_temperature` that performs temperature conversions. Given a temperature in Celsius and a target temperature scale, the function should return the converted temperature. The target scale can be one of the following: 'Fahrenheit', 'Kelvin', or 'Rankine'. If an invalid scale is provided, the function should return an error message indicating the valid options.\n\n**Input:**\n- The function takes two parameters:\n - `celsius`: A float representing the temperature in Celsius.\n - `scale`: A string representing the desired temperature scale.\n\n**Output:**\n- The function should return a float representing the converted temperature if the scale is valid.\n- If the scale is invalid, the function should return a string with an error message.\n\n**Sample Input/Output:**\n- `convert_temperature(0, 'Fahrenheit')` should return `32.0`.\n- `convert_temperature(100, 'Kelvin')` should return `373.15`.\n- `convert_temperature(-40, 'Rankine')` should return `459.67`.\n- `convert_temperature(25, 'Celsius')` should return `\"Error: Invalid scale 'Celsius'. Please choose from 'Fahrenheit', 'Kelvin', or 'Rankine'.\"`.", "reference": "def convert_temperature(celsius, scale):\n \"\"\"\n Convert a temperature from Celsius to the specified scale.\n\n Parameters:\n celsius (float): Temperature in Celsius.\n scale (str): Desired temperature scale ('Fahrenheit', 'Kelvin', 'Rankine').\n\n Returns:\n float or str: Converted temperature if scale is valid, otherwise an error message.\n \"\"\"\n scale = scale.capitalize()\n if scale == 'Fahrenheit':\n return (celsius * 9/5) + 32\n elif scale == 'Kelvin':\n return celsius + 273.15\n elif scale == 'Rankine':\n return (celsius + 273.15) * 9/5\n else:\n return f\"Error: Invalid scale '{scale}'. Please choose from 'Fahrenheit', 'Kelvin', or 'Rankine'.\"", "tests": ["assert convert_temperature(0, 'Fahrenheit') == 32.0", "assert convert_temperature(100, 'Fahrenheit') == 212.0", "assert convert_temperature(0, 'Kelvin') == 273.15", "assert convert_temperature(100, 'Kelvin') == 373.15", "assert convert_temperature(0, 'Rankine') == 491.67", "assert convert_temperature(100, 'Rankine') == 671.67", "assert convert_temperature(-273.15, 'Fahrenheit') == -459.67", "assert convert_temperature(-273.15, 'Kelvin') == 0.0", "assert convert_temperature(-273.15, 'Rankine') == 0.0", "assert convert_temperature(0, 'Celsius') == \"Error: Invalid scale 'Celsius'. Please choose from 'Fahrenheit', 'Kelvin', or 'Rankine'.\""], "function": "convert_temperature", "signature": "def convert_temperature(celsius, scale):", "score": 0.8, "domain": "generic"} {"id": "cc188a192736374f197feb2b1fb8c144", "problem": "You are given a list of `n` words, `word_list`, where each word consists of lowercase English letters. Your task is to implement a function `find_unique_anagram_groups(word_list)` that identifies and returns all unique anagram groups from the list. An anagram group is defined as a set of words that can be rearranged to form each other. The output should be a list of these groups, sorted lexicographically by the first word in each group.\n\n**Constraints:**\n- `1 <= n <= 1000`\n- Each word in `word_list` has a length between `1` and `10`.\n\n**Sample Input:**\n```python\n['cat', 'dog', 'tac', 'god', 'act']\n```\n\n**Sample Output:**\n```python\n[['act', 'cat', 'tac'], ['dog', 'god']]\n```", "reference": "def find_unique_anagram_groups(word_list):\n \"\"\"\n Identifies and returns all unique anagram groups from the given list of words.\n \n :param word_list: List of words consisting of lowercase English letters.\n :return: A list of anagram groups, sorted lexicographically by the first word in each group.\n \"\"\"\n from collections import defaultdict\n \n anagrams = defaultdict(list)\n \n for word in word_list:\n key = tuple(sorted(word))\n anagrams[key].append(word)\n \n result = [sorted(group) for group in anagrams.values()]\n result.sort()\n \n return result", "tests": ["assert find_unique_anagram_groups(['cat', 'dog', 'tac', 'god', 'act']) == [['act', 'cat', 'tac'], ['dog', 'god']]", "assert find_unique_anagram_groups(['listen', 'silent', 'enlist']) == [['enlist', 'listen', 'silent']]", "assert find_unique_anagram_groups(['a', 'b', 'c', 'd']) == [['a'], ['b'], ['c'], ['d']]", "assert find_unique_anagram_groups(['abc', 'bca', 'cab', 'xyz', 'zyx', 'yxz']) == [['abc', 'bca', 'cab'], ['xyz', 'yxz', 'zyx']]", "assert find_unique_anagram_groups(['']) == [['']]", "assert find_unique_anagram_groups(['aabb', 'bbaa', 'abab', 'baba']) == [['aabb', 'abab', 'baba', 'bbaa']]", "assert find_unique_anagram_groups(['rat', 'tar', 'art']) == [['art', 'rat', 'tar']]", "assert find_unique_anagram_groups(['hello', 'billion', 'world']) == [['billion'], ['hello'], ['world']]", "assert find_unique_anagram_groups(['']) == [['']]", "assert find_unique_anagram_groups(['dormitory', 'dirtyroom', 'roomdirty']) == [['dormitory', 'dirtyroom', 'roomdirty']]"], "function": "find_unique_anagram_groups", "signature": "def find_unique_anagram_groups(word_list):", "score": 0.9, "domain": "generic"} {"id": "dc1fd17426017fd91874c6a09d65a4b2", "problem": "You are given a string in `snake_case` format. Your task is to write a function `snake_to_kebab` that converts this string to `kebab-case`. The function should handle strings with leading, trailing, or multiple consecutive underscores, treating each underscore sequence as a single delimiter. The function should also preserve the case of each substring. If the input string is empty or contains only one word (no underscores), it should be returned as is.\n\n**Function Signature:**\n```python\ndef snake_to_kebab(snake_str: str) -> str:\n```\n\n**Constraints:**\n- The input string may contain only lowercase letters, underscores, and may be empty.\n- The function should handle edge cases such as empty strings and strings with no underscores.\n\n**Sample Inputs and Outputs:**\n- Input: `\"convert_this_string\"` \n Output: `\"convert-this-string\"`\n- Input: `\"convert__this___string\"` \n Output: `\"convert-this-string\"`\n- Input: `\"_convert_this_string_\"` \n Output: `\"convert-this-string\"`\n- Input: `\"\"` \n Output: `\"\"`\n- Input: `\"singleword\"` \n Output: `\"singleword\"`", "reference": "def snake_to_kebab(snake_str: str) -> str:\n \"\"\"\n Converts a snake_case string to kebab-case.\n \n Parameters:\n snake_str (str): The input string in snake_case format.\n \n Returns:\n str: The converted string in kebab-case format.\n \"\"\"\n substrings = snake_str.split('_')\n non_empty_substrings = [substring for substring in substrings if substring]\n kebab_str = '-'.join(non_empty_substrings)\n return kebab_str", "tests": ["assert snake_to_kebab(\"convert_this_string\") == \"convert-this-string\"", "assert snake_to_kebab(\"convert__this___string\") == \"convert-this-string\"", "assert snake_to_kebab(\"_convert_this_string_\") == \"convert-this-string\"", "assert snake_to_kebab(\"\") == \"\"", "assert snake_to_kebab(\"singleword\") == \"singleword\"", "assert snake_to_kebab(\"multiple__underscores__here\") == \"multiple-underscores-here\"", "assert snake_to_kebab(\"leading_underscores\") == \"leading-underscores\"", "assert snake_to_kebab(\"trailing_underscores_\") == \"trailing-underscores\"", "assert snake_to_kebab(\"_both_ends_\") == \"both-ends\"", "assert snake_to_kebab(\"___all_underscores___\") == \"all-underscores\""], "function": "snake_to_kebab", "signature": "def snake_to_kebab(snake_str: str) -> str:", "score": 1.0, "domain": "generic"} {"id": "e6949f679651f5140aba22a5fa75f490", "problem": "You are given a string `text` and a substring `pattern`. Your task is to implement a function `count_pattern_occurrences(text, pattern)` that returns the number of non-overlapping occurrences of `pattern` in `text`. The comparison is case-sensitive.\n\n**Input:**\n- The first line contains the string `text` (1 ≤ |text| ≤ 10^3).\n- The second line contains the substring `pattern` (1 ≤ |pattern| ≤ |text|).\n\n**Output:**\n- Print a single integer representing the number of times `pattern` occurs in `text`.\n\n**Sample Input:**\n```\nhello world\no\n```\n\n**Sample Output:**\n```\n2\n```", "reference": "def count_pattern_occurrences(text, pattern):\n \"\"\"\n Counts the number of non-overlapping occurrences of the pattern in the text.\n \n :param text: The string in which to search for the pattern.\n :param pattern: The substring to search for in the text.\n :return: The number of times the pattern occurs in the text.\n \"\"\"\n count = 0\n for i in range(len(text) - len(pattern) + 1):\n if text[i:i+len(pattern)] == pattern:\n count += 1\n return count\n\n# Example usage:\n# result = count_pattern_occurrences(\"hello world\", \"o\")\n# print(result) # Output: 2", "tests": ["assert count_pattern_occurrences(\"hello world\", \"o\") == 2", "assert count_pattern_occurrences(\"aaaa\", \"aa\") == 3", "assert count_pattern_occurrences(\"abcabcabc\", \"abc\") == 3", "assert count_pattern_occurrences(\"abcabcabc\", \"abcd\") == 0", "assert count_pattern_occurrences(\"mississippi\", \"issi\") == 1", "assert count_pattern_occurrences(\"aaaaa\", \"a\") == 5", "assert count_pattern_occurrences(\"\", \"a\") == 0", "assert count_pattern_occurrences(\"abc\", \"\") == 0", "assert count_pattern_occurrences(\"abc\", \"d\") == 0", "assert count_pattern_occurrences(\"abababab\", \"aba\") == 2"], "function": "count_pattern_occurrences", "signature": "def count_pattern_occurrences(text, pattern):", "score": 0.7, "domain": "generic"} {"id": "102484afe5c9a2f02ab5742566d72def", "problem": "You are tasked with refactoring a function that calculates the total amount for a list of items in a shopping cart. Each item is represented as a dictionary with keys 'quantity' and 'price'. Your goal is to improve the readability and efficiency of the code while maintaining its functionality. \n\n**Input:**\n- A list of dictionaries, where each dictionary contains:\n - 'quantity': an integer representing the number of units of the item.\n - 'price': a float representing the price per unit of the item.\n\n**Output:**\n- A float representing the total amount for all items in the cart.\n\n**Sample Input:**\n```python\nitems = [\n {'quantity': 2, 'price': 10.5},\n {'quantity': 5, 'price': 3.25},\n {'quantity': 1, 'price': 20.0}\n]\n```\n\n**Sample Output:**\n```\n57.25\n```", "reference": "def calculate_total_amount(items):\n \"\"\"\n Calculate the total amount for a list of items in a shopping cart.\n\n Parameters:\n items (list of dict): A list where each dictionary contains 'quantity' and 'price' keys.\n\n Returns:\n float: The total amount for all items in the cart.\n \"\"\"\n return sum(item['quantity'] * item['price'] for item in items)", "tests": ["assert calculate_total_amount([{'quantity': 2, 'price': 10}]) == 20", "assert calculate_total_amount([{'quantity': 1, 'price': 5}, {'quantity': 3, 'price': 15}]) == 50", "assert calculate_total_amount([{'quantity': 0, 'price': 100}, {'quantity': 5, 'price': 20}]) == 100", "assert calculate_total_amount([]) == 0", "assert calculate_total_amount([{'quantity': 10, 'price': 0}]) == 0", "assert calculate_total_amount([{'quantity': 2, 'price': 10}, {'quantity': 3, 'price': 5}, {'quantity': 4, 'price': 2}]) == 43", "assert calculate_total_amount([{'quantity': 1, 'price': 1.5}, {'quantity': 2, 'price': 2.5}]) == 6.5", "assert calculate_total_amount([{'quantity': 100, 'price': 1.01}]) == 101.0", "assert calculate_total_amount([{'quantity': 5, 'price': 10}, {'quantity': 5, 'price': 10}]) == 100", "assert calculate_total_amount([{'quantity': 3, 'price': 3.33}, {'quantity': 2, 'price': 2.22}]) == 14.21"], "function": "calculate_total_amount", "signature": "def calculate_total_amount(items):", "score": 0.9, "domain": "algorithmic"} {"id": "902a10e418bb053ef2ee0807d3981289", "problem": "You are given an undirected graph represented as an adjacency list. Your task is to find the largest connected component in the graph. A connected component is a subgraph in which any two vertices are connected to each other by paths, and which is connected to no additional vertices in the supergraph.\n\n**Input:**\n- An integer `n` representing the number of nodes in the graph.\n- An adjacency list `adjacency_list` where `adjacency_list[i]` contains a list of nodes directly connected to node `i`.\n\n**Output:**\n- A list of nodes representing the largest connected component. If there are multiple components of the same maximum size, return any one of them.\n\n**Sample Input:**\n```\nn = 8\nadjacency_list = {\n 0: [1, 2],\n 1: [0, 2],\n 2: [0, 1, 3],\n 3: [2],\n 4: [5],\n 5: [4],\n 6: [7],\n 7: [6]\n}\n```\n\n**Sample Output:**\n```\n[0, 1, 2, 3] # or any other valid largest component\n```", "reference": "def dfs(node, visited, adjacency_list, component_nodes):\n \"\"\"\n Perform a depth-first search to explore all nodes in the connected component\n starting from the given node.\n\n :param node: The starting node for the DFS.\n :param visited: A list indicating whether each node has been visited.\n :param adjacency_list: The adjacency list representation of the graph.\n :param component_nodes: A list to store nodes in the current connected component.\n \"\"\"\n visited[node] = True\n component_nodes.append(node)\n\n for neighbor in adjacency_list[node]:\n if not visited[neighbor]:\n dfs(neighbor, visited, adjacency_list, component_nodes)\n\n\ndef largest_connected_component(adjacency_list):\n \"\"\"\n Find the largest connected component in the graph.\n\n :param adjacency_list: The adjacency list representation of the graph.\n :return: A list of nodes in the largest connected component.\n \"\"\"\n n = len(adjacency_list)\n visited = [False] * n\n largest_component = []\n\n for node in range(n):\n if not visited[node]:\n component_nodes = []\n dfs(node, visited, adjacency_list, component_nodes)\n if len(component_nodes) > len(largest_component):\n largest_component = component_nodes\n\n return largest_component\n\n\n# Example usage:\nn = 8\nadjacency_list = {\n 0: [1, 2],\n 1: [0, 2],\n 2: [0, 1, 3],\n 3: [2],\n 4: [5],\n 5: [4],\n 6: [7],\n 7: [6]\n}\n\nlargest_comp = largest_connected_component(adjacency_list)\nprint(f\"The largest connected component is: {largest_comp}\")", "tests": ["assert largest_connected_component({0: [1], 1: [0]}) == [0, 1]", "assert largest_connected_component({0: [1, 2], 1: [0, 2], 2: [0, 1]}) == [0, 1, 2]", "assert largest_connected_component({0: [], 1: [], 2: []}) == [0]", "assert largest_connected_component({0: [1, 2], 1: [0], 2: [0], 3: [4], 4: [3]}) == [0, 1, 2]", "assert largest_connected_component({0: [1, 2, 3], 1: [0, 2], 2: [0, 1], 3: [0]}) == [0, 1, 2, 3]", "assert largest_connected_component({0: [1], 1: [0], 2: [3], 3: [2], 4: [5], 5: [4]}) == [0, 1]", "assert largest_connected_component({}) == []", "assert largest_connected_component({0: [1, 2], 1: [0, 2], 2: [0, 1], 3: [4, 5], 4: [3, 5], 5: [3, 4]}) == [0, 1, 2]", "assert largest_connected_component({0: [1, 2], 1: [0], 2: [0], 3: [4, 5, 6], 4: [3, 5], 5: [3, 4, 6], 6: [3, 5]}) == [3, 4, 5, 6]", "assert largest_connected_component({0: [1, 2], 1: [0, 2], 2: [0, 1], 3: [4], 4: [3], 5: [6], 6: [5]}) == [0, 1, 2]"], "function": "largest_connected_component", "signature": "def largest_connected_component(adjacency_list):", "score": 1.0, "domain": "algorithmic"} {"id": "2f322056b904ba1d24d2011902fb1262", "problem": "You are given a sorted list of integers `numbers` and an integer `target`. Implement a function `binary_search` that performs a binary search on the list to find the index of the `target`. If the `target` is found in the list, return its index; otherwise, return -1.\n\n**Input:**\n- A sorted list of integers `numbers` (1 ≤ len(numbers) ≤ 10^4).\n- An integer `target` (-10^9 ≤ target ≤ 10^9).\n\n**Output:**\n- An integer representing the index of the `target` in the list `numbers`, or -1 if the `target` is not found.\n\n**Sample Input:**\n```\nnumbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\ntarget = 7\n```\n\n**Sample Output:**\n```\n6\n```\n\n**Sample Input:**\n```\nnumbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\ntarget = 11\n```\n\n**Sample Output:**\n```\n-1\n```", "reference": "def binary_search(numbers, target):\n \"\"\"\n Perform a binary search on a sorted list to find the index of the target value.\n\n :param numbers: List[int] - A sorted list of integers.\n :param target: int - The target integer to search for.\n :return: int - The index of the target in the list if found, otherwise -1.\n \"\"\"\n left, right = 0, len(numbers) - 1\n \n while left <= right:\n mid = left + (right - left) // 2\n if numbers[mid] == target:\n return mid\n elif numbers[mid] < target:\n left = mid + 1\n else:\n right = mid - 1\n \n return -1", "tests": ["assert binary_search([1, 2, 3, 4, 5], 3) == 2", "assert binary_search([1, 2, 3, 4, 5], 1) == 0", "assert binary_search([1, 2, 3, 4, 5], 5) == 4", "assert binary_search([1, 2, 3, 4, 5], 6) == -1", "assert binary_search([], 1) == -1", "assert binary_search([1], 1) == 0", "assert binary_search([1, 3, 5, 7, 9], 7) == 3", "assert binary_search([1, 3, 5, 7, 9], 2) == -1", "assert binary_search([-10, -5, 0, 5, 10], 0) == 2", "assert binary_search([-10, -5, 0, 5, 10], -10) == 0"], "function": "binary_search", "signature": "def binary_search(numbers, target):", "score": 1.0, "domain": "generic"} {"id": "796102a7fe5c9c96276cdef19978cac7", "problem": "You are given a list of strings. Your task is to write a function that returns a new list where each string is replaced by its longest palindromic substring. If there are multiple substrings of the same maximum length, return the first one encountered. For example, for the input list `['racecar', 'banana', 'level', 'deified']`, the output should be `['racecar', 'anana', 'level', 'deified']`.\n\n**Sample Input:**\n```\n['racecar', 'banana', 'level', 'deified']\n```\n\n**Sample Output:**\n```\n['racecar', 'anana', 'level', 'deified']\n```", "reference": "def longest_palindromic_substring(s: str) -> str:\n \"\"\"\n Returns the longest palindromic substring in the given string `s`.\n If there are multiple substrings of the same maximum length, returns the first one encountered.\n \"\"\"\n def expand_around_center(left: int, right: int) -> str:\n while left >= 0 and right < len(s) and s[left] == s[right]:\n left -= 1\n right += 1\n return s[left + 1:right]\n \n longest = \"\"\n for i in range(len(s)):\n palindrome1 = expand_around_center(i, i)\n palindrome2 = expand_around_center(i, i + 1)\n \n if len(palindrome1) > len(longest):\n longest = palindrome1\n if len(palindrome2) > len(longest):\n longest = palindrome2\n \n return longest\n\ndef transform_list_of_strings(input_list: list) -> list:\n \"\"\"\n Transforms each string in the input list to its longest palindromic substring.\n Returns a new list with these transformed strings.\n \"\"\"\n return [longest_palindromic_substring(s) for s in input_list]\n\n# Example usage:\ninput_list = ['racecar', 'banana', 'level', 'deified']\noutput_list = transform_list_of_strings(input_list)\nprint(output_list) # Output: ['racecar', 'anana', 'level', 'deified']", "tests": ["assert transform_list_of_strings(['racecar', 'banana', 'level', 'deified']) == ['racecar', 'anana', 'level', 'deified']", "assert transform_list_of_strings(['abc', 'def', 'ghi']) == ['a', 'd', 'g']", "assert transform_list_of_strings(['a', 'b', 'c']) == ['a', 'b', 'c']", "assert transform_list_of_strings(['abba', 'civic', 'rotor']) == ['abba', 'civic', 'rotor']", "assert transform_list_of_strings(['noon', 'level', 'deified']) == ['noon', 'level', 'deified']", "assert transform_list_of_strings(['', '', '']) == ['', '', '']", "assert transform_list_of_strings(['abacdfgdcaba', 'racecar']) == ['aba', 'racecar']", "assert transform_list_of_strings(['aabcdcb', 'racecar']) == ['bcdcb', 'racecar']", "assert transform_list_of_strings(['abacdfgdcaba', '']) == ['aba', '']", "assert transform_list_of_strings(['']) == ['']"], "function": "transform_list_of_strings", "signature": "def transform_list_of_strings(input_list: list) -> list:", "score": 1.0, "domain": "generic"} {"id": "bea532f3859dfee3bf3a816041a68b11", "problem": "You are tasked with implementing a function `clean_file_name` that processes a given string to create a sanitized filename. The function should perform the following transformations:\n- Convert the entire string to lowercase.\n- Replace all occurrences of spaces, quotation marks (`\"`), commas (`,`), hyphens (`-`), and newline characters (`\\n`) with underscores (`_`).\n\nYour function should handle both uppercase and lowercase versions of the characters to be replaced uniformly.\n\n**Input:**\n- A single string `name` (1 ≤ |name| ≤ 1000).\n\n**Output:**\n- A single string representing the sanitized filename.\n\n**Sample Input:**\n```\nExample FILE-name, with spaces\\nand quotes\"\n```\n\n**Sample Output:**\n```\nexample_file_name__with_spaces_and_quotes_\n```", "reference": "def clean_file_name(name: str) -> str:\n \"\"\"\n Sanitizes a given string to create a filename by converting it to lowercase\n and replacing spaces, quotation marks, commas, hyphens, and newline characters\n with underscores.\n \n :param name: The original filename string.\n :return: The sanitized filename string.\n \"\"\"\n replacements = {' ': '_', '\"': '_', ',': '_', '-': '_', '\\n': '_'}\n name = name.lower()\n for old_char, new_char in replacements.items():\n name = name.replace(old_char, new_char)\n return name\n\n# Example usage:\n# print(clean_file_name(\"Example FILE-name, with spaces\\nand quotes\\\"\")) \n# Output: \"example_file_name__with_spaces_and_quotes_\"", "tests": ["assert clean_file_name(\"Example FILE-name, with spaces\\nand quotes\\\"\") == \"example_file_name__with_spaces_and_quotes_\"", "assert clean_file_name(\"HELLO WORLD\") == \"hello_world\"", "assert clean_file_name(\"hello-world\") == \"hello_world\"", "assert clean_file_name(\"file name with spaces\") == \"file_name_with_spaces\"", "assert clean_file_name(\"file,name,with,commas\") == \"file_name_with_commas\"", "assert clean_file_name(\"file\\nname\\nwith\\nnewlines\") == \"file_name_with_newlines\"", "assert clean_file_name(\"file\\\"name\\\"with\\\"quotes\\\"\") == \"file_name_with_quotes_\"", "assert clean_file_name(\"NoSpecialCharacters\") == \"nospecialcharacters\"", "assert clean_file_name(\" Leading and trailing spaces \") == \"leading_and_trailing_spaces\"", "assert clean_file_name(\"\") == \"\""], "function": "clean_file_name", "signature": "def clean_file_name(name: str) -> str:", "score": 0.9, "domain": "generic"} {"id": "03e9b5d1582762d2a99f0597ea71c3e9", "problem": "You are given a string `s`. Your task is to implement a function `count_occurrences` that returns a dictionary with the count of each character in the string. The dictionary should have characters as keys and their respective counts as values. The function should handle all ASCII characters present in the string.\n\n**Input:**\n- A single string `s` (1 ≤ |s| ≤ 10^5).\n\n**Output:**\n- A dictionary where keys are characters from the string and values are the counts of those characters.\n\n**Sample Input:**\n```\n\"hello world\"\n```\n\n**Sample Output:**\n```\n{'h': 1, 'e': 1, 'l': 3, 'o': 2, ' ': 1, 'w': 1, 'r': 1, 'd': 1}\n```", "reference": "def count_occurrences(s):\n \"\"\"\n Counts the occurrences of each character in the given string.\n\n Parameters:\n s (str): The input string.\n\n Returns:\n dict: A dictionary with characters as keys and their counts as values.\n \"\"\"\n char_count = {}\n for char in s:\n if char in char_count:\n char_count[char] += 1\n else:\n char_count[char] = 1\n return char_count\n\n# Example usage:\n# result = count_occurrences(\"hello world\")\n# print(result) # Output: {'h': 1, 'e': 1, 'l': 3, 'o': 2, ' ': 1, 'w': 1, 'r': 1, 'd': 1}", "tests": ["assert count_occurrences(\"hello world\") == {'h': 1, 'e': 1, 'l': 3, 'o': 2, ' ': 1, 'w': 1, 'r': 1, 'd': 1}", "assert count_occurrences(\"test\") == {'t': 2, 'e': 1, 's': 1}", "assert count_occurrences(\"\") == {}", "assert count_occurrences(\"aabbcc\") == {'a': 2, 'b': 2, 'c': 2}", "assert count_occurrences(\"123321\") == {'1': 2, '2': 2, '3': 2}", "assert count_occurrences(\"!@#$%^&*()\") == {'!': 1, '@': 1, '#': 1, '$': 1, '%': 1, '^': 1, '&': 1, '*': 1, '(': 1, ')': 1}", "assert count_occurrences(\"AaBbCc\") == {'A': 1, 'a': 1, 'B': 1, 'b': 1, 'C': 1, 'c': 1}", "assert count_occurrences(\" \") == {' ': 4}", "assert count_occurrences(\"Python Programming\") == {'P': 2, 'y': 1, 't': 1, 'h': 1, 'o': 2, 'n': 2, ' ': 1, 'r': 2, 'g': 2, 'a': 1, 'm': 2, 'i': 1}", "assert count_occurrences(\"123 456 789\") == {'1': 1, '2': 1, '3': 1, ' ': 2, '4': 1, '5': 1, '6': 1, '7': 1, '8': 1, '9': 1}"], "function": "count_occurrences", "signature": "def count_occurrences(s):", "score": 1.0, "domain": "generic"} {"id": "33c1dbae3808acc2b556bde888e935b3", "problem": "You are tasked with implementing a function `calculate_area` that computes the area of a triangle given its base and height. The function currently contains a logical error. Your job is to identify and correct this error.\n\n**Input:**\n- The function will receive two positive integers, `base` and `height`, representing the base and height of the triangle, respectively.\n\n**Output:**\n- The function should return a float representing the area of the triangle.\n\n**Sample Input:**\n- `base = 10`, `height = 5`\n\n**Sample Output:**\n- `25.0`", "reference": "def calculate_area(base, height):\n \"\"\"\n Calculate the area of a triangle given its base and height.\n\n Parameters:\n base (int): The base of the triangle.\n height (int): The height of the triangle.\n\n Returns:\n float: The area of the triangle.\n \"\"\"\n return 0.5 * base * height", "tests": ["assert calculate_area(10, 5) == 25", "assert calculate_area(7, 3) == 10.5", "assert calculate_area(0, 5) == 0", "assert calculate_area(5, 0) == 0", "assert calculate_area(1, 1) == 0.5", "assert calculate_area(12.5, 4.2) == 26.25", "assert calculate_area(8, 8) == 32", "assert calculate_area(100, 200) == 10000", "assert calculate_area(3.5, 2) == 3.5", "assert calculate_area(2, 3.5) == 3.5"], "function": "calculate_area", "signature": "def calculate_area(base, height):", "score": 1.0, "domain": "generic"} {"id": "6da82d5e6c8fa70db05cea40c0cddfc4", "problem": "You are given a list of tuples, where each tuple consists of a string and an integer. Your task is to implement a function that processes this list and returns a new list of strings. Each string in the output list should be formatted as the original string followed by a colon, a space, and the integer. Ensure that all strings in the resulting list are unique; if a formatted string is a duplicate, it should not be included in the final list.\n\n**Input:**\n- A list of tuples, where each tuple contains a string and an integer.\n\n**Output:**\n- A list of unique formatted strings.\n\n**Sample Input:**\n```python\n[(\"apple\", 3), (\"banana\", 5), (\"cherry\", 7), (\"apple\", 3)]\n```\n\n**Sample Output:**\n```python\n[\"apple: 3\", \"banana: 5\", \"cherry: 7\"]\n```\nNote: The order of elements in the output list does not matter.", "reference": "def format_and_unique(tuples_list):\n \"\"\"\n Processes a list of tuples, each containing a string and an integer, and returns a list of unique formatted strings.\n \n Each string in the output list is formatted as 'string: integer'.\n \n :param tuples_list: List of tuples, where each tuple contains a string and an integer.\n :return: List of unique formatted strings.\n \"\"\"\n unique_strings = set()\n \n for item in tuples_list:\n formatted_string = f\"{item[0]}: {item[1]}\"\n unique_strings.add(formatted_string)\n \n return list(unique_strings)\n\n# Example usage:\ninput_list = [(\"apple\", 3), (\"banana\", 5), (\"cherry\", 7), (\"apple\", 3)]\noutput_list = format_and_unique(input_list)\nprint(output_list) # Output may not be in the same order as input but will be unique", "tests": ["assert format_and_unique([(\"apple\", 3), (\"banana\", 5), (\"cherry\", 7)]) == [\"apple: 3\", \"banana: 5\", \"cherry: 7\"]", "assert format_and_unique([(\"apple\", 3), (\"apple\", 3), (\"apple\", 3)]) == [\"apple: 3\"]", "assert format_and_unique([(\"apple\", 3), (\"banana\", 5), (\"apple\", 3)]) == [\"apple: 3\", \"banana: 5\"]", "assert format_and_unique([]) == []", "assert format_and_unique([(\"kiwi\", 1)]) == [\"kiwi: 1\"]", "assert format_and_unique([(\"orange\", 2), (\"orange\", 2), (\"grape\", 4)]) == [\"orange: 2\", \"grape: 4\"]", "assert format_and_unique([(\"pear\", 6), (\"plum\", 8), (\"pear\", 6), (\"plum\", 8)]) == [\"pear: 6\", \"plum: 8\"]", "assert format_and_unique([(\"melon\", 9), (\"melon\", 9), (\"melon\", 9), (\"melon\", 9)]) == [\"melon: 9\"]", "assert format_and_unique([(\"blueberry\", 10), (\"strawberry\", 12), (\"blueberry\", 10), (\"blueberry\", 10)]) == [\"blueberry: 10\", \"strawberry: 12\"]", "assert format_and_unique([(\"raspberry\", 14), (\"blackberry\", 16), (\"raspberry\", 14), (\"blackberry\", 16), (\"raspberry\", 14)]) == [\"raspberry: 14\", \"blackberry: 16\"]"], "function": "format_and_unique", "signature": "def format_and_unique(tuples_list):", "score": 0.7, "domain": "generic"} {"id": "edc66de38b4fbed478454425f745728c", "problem": "You are tasked with implementing a function that extracts all valid email addresses from a given string using regular expressions. The function should be robust enough to handle various email formats. Your solution should return a list of all found email addresses.\n\n**Input:**\n- A single string `text` (1 ≤ len(text) ≤ 10^4) containing the text from which email addresses need to be extracted.\n\n**Output:**\n- A list of strings, where each string is a valid email address found in the input text.\n\n**Sample Input:**\n```\n\"Contact us at support@example.com or sales@example.co\"\n```\n\n**Sample Output:**\n```\n['support@example.com', 'sales@example.co']\n```", "reference": "import re\n\ndef find_emails(text):\n \"\"\"\n Extracts all valid email addresses from the given text using regular expressions.\n\n Parameters:\n text (str): The input string from which to extract email addresses.\n\n Returns:\n list: A list of strings, each representing a valid email address found in the text.\n \"\"\"\n email_pattern = r'[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+'\n return re.findall(email_pattern, text)\n\n# Test the function with the provided text\ntext = \"Contact us at support@example.com or sales@example.co\"\nemails = find_emails(text)\nprint(emails)", "tests": ["assert find_emails(\"Contact us at support@example.com or sales@example.co\") == [\"support@example.com\", \"sales@example.co\"]", "assert find_emails(\"No emails here!\") == []", "assert find_emails(\"Emails: john.doe123@domain.co.uk, jane-doe_456@sub.domain.com\") == [\"john.doe123@domain.co.uk\", \"jane-doe_456@sub.domain.com\"]", "assert find_emails(\"Mixed content: email1@domain.com and email2@domain.org are valid, but not email3@domain, email4@domain.c, or email5@.com\") == [\"email1@domain.com\", \"email2@domain.org\"]", "assert find_emails(\"Multiple dots.. in domain: valid.email@sub..domain.com\") == [\"valid.email@sub..domain.com\"]", "assert find_emails(\"Special characters: email+tag+sorting@example.com\") == [\"email+tag+sorting@example.com\"]", "assert find_emails(\"Invalid emails: @missingusername.com, username@.com, username@domain..com\") == []", "assert find_emails(\"Long TLDs: email@domain.museum, email@domain.travel\") == [\"email@domain.museum\", \"email@domain.travel\"]", "assert find_emails(\"Internationalized domain: email@xn--fsq.xn--zckzah\") == [\"email@xn--fsq.xn--zckzah\"]", "assert find_emails(\"Email with subdomain: user@mail.example.com\") == [\"user@mail.example.com\"]"], "function": "find_emails", "signature": "def find_emails(text):", "score": 0.8, "domain": "generic"} {"id": "9af1d671505bc2d78d153caa5cf319fe", "problem": "You are tasked with implementing a function to compute the nth Fibonacci number using a recursive approach. To optimize the recursive function and avoid excessive recursive calls, you must use memoization. Your function should efficiently handle large values of n.\n\n**Input:**\n- An integer `n` (1 ≤ n ≤ 1000)\n\n**Output:**\n- The nth Fibonacci number.\n\n**Sample Input:**\n```\n10\n```\n\n**Sample Output:**\n```\n55\n```", "reference": "def calculate_fibonacci(n, memo=None):\n \"\"\"\n Computes the nth Fibonacci number using a recursive approach with memoization.\n\n Parameters:\n n (int): The position in the Fibonacci sequence (1-indexed).\n memo (dict, optional): A dictionary to store previously computed Fibonacci numbers.\n\n Returns:\n int: The nth Fibonacci number.\n \"\"\"\n if memo is None:\n memo = {}\n if n in memo:\n return memo[n]\n if n <= 2:\n return 1\n memo[n] = calculate_fibonacci(n - 1, memo) + calculate_fibonacci(n - 2, memo)\n return memo[n]", "tests": ["assert calculate_fibonacci(0) == 1", "assert calculate_fibonacci(1) == 1", "assert calculate_fibonacci(2) == 1", "assert calculate_fibonacci(3) == 2", "assert calculate_fibonacci(4) == 3", "assert calculate_fibonacci(5) == 5", "assert calculate_fibonacci(10) == 55", "assert calculate_fibonacci(20) == 6765", "assert calculate_fibonacci(30) == 832040", "assert calculate_fibonacci(50) == 12586269025"], "function": "calculate_fibonacci", "signature": "def calculate_fibonacci(n, memo=None):", "score": 1.0, "domain": "generic"}