{"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```", "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# 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\"}) == \"\"", "assert format_user_profile({\"name\": \"Bob\", \"age\": 25, \"location\": \"Los Angeles\"}) == \"\"", "assert format_user_profile({\"name\": \"Charlie\", \"age\": 35, \"location\": \"Chicago\"}) == \"\"", "assert format_user_profile({\"name\": \"David\", \"age\": 40, \"location\": \"Houston\"}) == \"\"", "assert format_user_profile({\"name\": \"Eve\", \"age\": 28, \"location\": \"Phoenix\"}) == \"\"", "assert format_user_profile({\"name\": \"Frank\", \"age\": 50, \"location\": \"Philadelphia\"}) == \"\"", "assert format_user_profile({\"name\": \"Grace\", \"age\": 22, \"location\": \"San Antonio\"}) == \"\"", "assert format_user_profile({\"name\": \"Hannah\", \"age\": 33, \"location\": \"San Diego\"}) == \"\"", "assert format_user_profile({\"name\": \"Ivy\", \"age\": 45, \"location\": \"Dallas\"}) == \"\"", "assert format_user_profile({\"name\": \"Jack\", \"age\": 29, \"location\": \"San Jose\"}) == \"\""], "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| Name | Age | City |
|---|---|---|
| Alice | 30 | New York |
| Bob | 24 | Los Angeles |
| Charlie | 29 | Chicago |
| {header} | \")\n \n html.append(\"
|---|
| {row.get(header, '')} | \")\n html.append(\"
| Name | Age |
|---|---|
| Alice | 30 |
| Name | Age |
|---|---|
| Alice | 30 |
| Bob | 24 |
| Name | Age | City |
|---|---|---|
| Alice | 30 | |
| Bob | 24 | Los Angeles |
| Name | Age |
|---|---|
| Alice | 30 |
| Bob | 24 |
| Charlie | 29 |
| Name | Age | City |
|---|---|---|
| Alice | 30 | |
| Bob | 24 | |
| Charlie | 29 | Chicago |
| Name | Age | City | Country |
|---|---|---|---|
| Alice | 30 | ||
| Bob | 24 | ||
| Charlie | 29 | Chicago | USA |
| Name | Age | City | Country |
|---|---|---|---|
| Alice | 30 | ||
| Bob | 24 | ||
| Charlie | 29 | Chicago | USA |
| David | 22 | San Francisco | USA |
| Name | Age | City | Country |
|---|---|---|---|
| Alice | 30 | ||
| Bob | 24 | ||
| Charlie | 29 | Chicago | USA |
| David | 22 | San Francisco | USA |
| Eve | 27 |
| Name | Age | City | Country |
|---|---|---|---|
| Alice | 30 | ||
| Bob | 24 | ||
| Charlie | 29 | Chicago | USA |
| David | 22 | San Francisco | USA |
| Eve | 27 | Seattle |
Test
` 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-leveltags.\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
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): #