Skip to content

Instantly share code, notes, and snippets.

@eruo005-dev
Created July 20, 2026 23:21
Show Gist options
  • Select an option

  • Save eruo005-dev/c2c663f9557ddff5dd1dd588b6c6d843 to your computer and use it in GitHub Desktop.

Select an option

Save eruo005-dev/c2c663f9557ddff5dd1dd588b6c6d843 to your computer and use it in GitHub Desktop.
runlocalai_vast5090_gemma-4-31b-humaneval
model: gemma-4-31b quant: Q4_K_M runtime: ollama-0.32.1-vast5090 hardware: rtx-5090
dataset: humaneval+ (164 problems)
rig: rented Vast.ai RTX 5090 32GB instance (transient — no persistent storage; benchmarked, then torn down)
=== gen + score log (tail) ===
[140/164] generate HumanEval/139
wrote 746 chars in 13.9s | ETA 9.4 min
[141/164] generate HumanEval/140
wrote 923 chars in 39.4s | ETA 9.0 min
[142/164] generate HumanEval/141
wrote 1485 chars in 29.0s | ETA 8.6 min
[143/164] generate HumanEval/142
wrote 1034 chars in 19.8s | ETA 8.2 min
[144/164] generate HumanEval/143
wrote 1220 chars in 25.6s | ETA 7.9 min
[145/164] generate HumanEval/144
wrote 1039 chars in 20.0s | ETA 7.5 min
[146/164] generate HumanEval/145
wrote 1552 chars in 105.0s | ETA 7.2 min
[147/164] generate HumanEval/146
wrote 947 chars in 25.3s | ETA 6.8 min
[148/164] generate HumanEval/147
wrote 1776 chars in 70.0s | ETA 6.5 min
[149/164] generate HumanEval/148
wrote 1511 chars in 22.4s | ETA 6.1 min
[150/164] generate HumanEval/149
wrote 1026 chars in 20.6s | ETA 5.7 min
[151/164] generate HumanEval/150
wrote 564 chars in 15.2s | ETA 5.3 min
[152/164] generate HumanEval/151
wrote 807 chars in 33.3s | ETA 4.9 min
[153/164] generate HumanEval/152
wrote 1009 chars in 18.9s | ETA 4.5 min
[154/164] generate HumanEval/153
wrote 1626 chars in 32.3s | ETA 4.1 min
[155/164] generate HumanEval/154
wrote 1187 chars in 25.1s | ETA 3.7 min
[156/164] generate HumanEval/155
wrote 524 chars in 14.9s | ETA 3.2 min
[157/164] generate HumanEval/156
wrote 1072 chars in 25.4s | ETA 2.8 min
[158/164] generate HumanEval/157
wrote 752 chars in 20.2s | ETA 2.4 min
[159/164] generate HumanEval/158
wrote 1213 chars in 32.5s | ETA 2.0 min
[160/164] generate HumanEval/159
wrote 1406 chars in 22.4s | ETA 1.6 min
[161/164] generate HumanEval/160
wrote 1053 chars in 24.0s | ETA 1.2 min
[162/164] generate HumanEval/161
wrote 688 chars in 14.9s | ETA 0.8 min
[163/164] generate HumanEval/162
wrote 580 chars in 17.5s | ETA 0.4 min
[164/164] generate HumanEval/163
wrote 732 chars in 23.8s | ETA 0.0 min
Done: results/gemma-4-31b-humaneval.jsonl
Load from ground-truth from /root/.cache/evalplus/fe585eb4df8c88d844eeb463ea4d0302.pkl
Reading samples...
0it [00:00, ?it/s] 1it [00:03, 3.22s/it] 164it [00:03, 50.70it/s]
0%| | 0/164 [00:00<?, ?it/s] 1%| | 1/164 [00:00<00:34, 4.69it/s] 9%|▉ | 15/164 [00:00<00:02, 54.61it/s] 14%|█▍ | 23/164 [00:00<00:05, 26.94it/s] 20%|██ | 33/164 [00:01<00:06, 20.68it/s] 76%|███████▌ | 125/164 [00:01<00:00, 97.80it/s] 84%|████████▍ | 138/164 [00:01<00:00, 99.77it/s] 96%|█████████▋| 158/164 [00:02<00:00, 110.01it/s] 100%|██████████| 164/164 [00:06<00:00, 25.49it/s]
humaneval (base tests)
pass@1: 0.988
humaneval+ (base + extra tests)
pass@1: 0.933
=== sanitized samples jsonl ===
{"task_id": "HumanEval/0", "solution": "from typing import List\ndef has_close_elements(numbers: List[float], threshold: float) -> bool:\n \"\"\" Check if in given list of numbers, are any two numbers closer to each other than\n given threshold.\n >>> has_close_elements([1.0, 2.0, 3.0], 0.5)\n False\n >>> has_close_elements([1.0, 2.8, 3.0, 4.0, 5.0, 2.0], 0.3)\n True\n \"\"\"\n # Sort the numbers to ensure that the closest elements are adjacent\n sorted_numbers = sorted(numbers)\n \n # Iterate through the sorted list and check the difference between neighbors\n for i in range(len(sorted_numbers) - 1):\n if sorted_numbers[i + 1] - sorted_numbers[i] < threshold:\n return True\n \n return False"}
{"task_id": "HumanEval/1", "solution": "from typing import List\ndef separate_paren_groups(paren_string: str) -> List[str]:\n \"\"\" Input to this function is a string containing multiple groups of nested parentheses. Your goal is to\n separate those group into separate strings and return the list of those.\n Separate groups are balanced (each open brace is properly closed) and not nested within each other\n Ignore any spaces in the input string.\n >>> separate_paren_groups('( ) (( )) (( )( ))')\n ['()', '(())', '(()())']\n \"\"\"\n # Remove all whitespace from the input string as per requirements\n cleaned_string = \"\".join(paren_string.split())\n \n result = []\n current_group = []\n balance = 0\n \n for char in cleaned_string:\n if char == '(':\n balance += 1\n current_group.append(char)\n elif char == ')':\n balance -= 1\n current_group.append(char)\n \n # When balance returns to 0, we have completed a top-level group\n if balance == 0:\n result.append(\"\".join(current_group))\n current_group = []\n \n return result"}
{"task_id": "HumanEval/2", "solution": "def truncate_number(number: float) -> float:\n \"\"\" Given a positive floating point number, it can be decomposed into\n and integer part (largest integer smaller than given number) and decimals\n (leftover part always smaller than 1).\n\n Return the decimal part of the number.\n >>> truncate_number(3.5)\n 0.5\n \"\"\"\n return number - int(number)"}
{"task_id": "HumanEval/3", "solution": "from typing import List\ndef below_zero(operations: List[int]) -> bool:\n \"\"\" You're given a list of deposit and withdrawal operations on a bank account that starts with\n zero balance. Your task is to detect if at any point the balance of account fallls below zero, and\n at that point function should return True. Otherwise it should return False.\n >>> below_zero([1, 2, 3])\n False\n >>> below_zero([1, 2, -4, 5])\n True\n \"\"\"\n balance = 0\n for op in operations:\n balance += op\n if balance < 0:\n return True\n return False"}
{"task_id": "HumanEval/4", "solution": "from typing import List\ndef mean_absolute_deviation(numbers: List[float]) -> float:\n \"\"\" For a given list of input numbers, calculate Mean Absolute Deviation\n around the mean of this dataset.\n Mean Absolute Deviation is the average absolute difference between each\n element and a centerpoint (mean in this case):\n MAD = average | x - x_mean |\n >>> mean_absolute_deviation([1.0, 2.0, 3.0, 4.0])\n 1.0\n \"\"\"\n if not numbers:\n return 0.0\n\n # Calculate the arithmetic mean of the dataset\n mean = sum(numbers) / len(numbers)\n \n # Calculate the sum of absolute differences between each element and the mean\n total_absolute_deviation = sum(abs(x - mean) for x in numbers)\n \n # Return the average of these absolute differences\n return total_absolute_deviation / len(numbers)"}
{"task_id": "HumanEval/5", "solution": "from typing import List\ndef intersperse(numbers: List[int], delimeter: int) -> List[int]:\n \"\"\" Insert a number 'delimeter' between every two consecutive elements of input list `numbers'\n >>> intersperse([], 4)\n []\n >>> intersperse([1, 2, 3], 4)\n [1, 4, 2, 4, 3]\n \"\"\"\n if not numbers:\n return []\n\n result = []\n for i in range(len(numbers)):\n result.append(numbers[i])\n # Append the delimiter only if we are not at the last element\n if i < len(numbers) - 1:\n result.append(delimeter)\n \n return result"}
{"task_id": "HumanEval/6", "solution": "from typing import List\ndef parse_nested_parens(paren_string: str) -> List[int]:\n \"\"\" Input to this function is a string represented multiple groups for nested parentheses separated by spaces.\n For each of the group, output the deepest level of nesting of parentheses.\n E.g. (()()) has maximum two levels of nesting while ((())) has three.\n\n >>> parse_nested_parens('(()()) ((())) () ((())()())')\n [2, 3, 1, 3]\n \"\"\"\n # Split the input string into individual groups based on spaces\n groups = paren_string.split()\n results = []\n\n for group in groups:\n current_depth = 0\n max_depth = 0\n \n # Iterate through each character in the current parenthesis group\n for char in group:\n if char == '(':\n current_depth += 1\n # Update max_depth if the current nesting level is the deepest seen so far\n if current_depth > max_depth:\n max_depth = current_depth\n elif char == ')':\n current_depth -= 1\n \n results.append(max_depth)\n\n return results"}
{"task_id": "HumanEval/7", "solution": "from typing import List\ndef filter_by_substring(strings: List[str], substring: str) -> List[str]:\n \"\"\" Filter an input list of strings only for ones that contain given substring\n >>> filter_by_substring([], 'a')\n []\n >>> filter_by_substring(['abc', 'bacd', 'cde', 'array'], 'a')\n ['abc', 'bacd', 'array']\n \"\"\"\n return [s for s in strings if substring in s]"}
{"task_id": "HumanEval/8", "solution": "from typing import List, Tuple\ndef sum_product(numbers: List[int]) -> Tuple[int, int]:\n \"\"\" For a given list of integers, return a tuple consisting of a sum and a product of all the integers in a list.\n Empty sum should be equal to 0 and empty product should be equal to 1.\n >>> sum_product([])\n (0, 1)\n >>> sum_product([1, 2, 3, 4])\n (10, 24)\n \"\"\"\n total_sum = 0\n total_product = 1\n \n for num in numbers:\n total_sum += num\n total_product *= num\n \n return (total_sum, total_product)"}
{"task_id": "HumanEval/9", "solution": "from typing import List\ndef rolling_max(numbers: List[int]) -> List[int]:\n \"\"\" From a given list of integers, generate a list of rolling maximum element found until given moment\n in the sequence.\n >>> rolling_max([1, 2, 3, 2, 3, 4, 2])\n [1, 2, 3, 3, 3, 4, 4]\n \"\"\"\n if not numbers:\n return []\n\n result = []\n # Initialize current_max with the first element of the list\n current_max = numbers[0]\n \n for num in numbers:\n # Update current_max if the current number is larger\n if num > current_max:\n current_max = num\n result.append(current_max)\n \n return result"}
{"task_id": "HumanEval/10", "solution": "def is_palindrome(string: str) -> bool:\n \"\"\" Test if given string is a palindrome \"\"\"\n return string == string[::-1]\ndef make_palindrome(string: str) -> str:\n \"\"\" Find the shortest palindrome that begins with a supplied string.\n Algorithm idea is simple:\n - Find the longest postfix of supplied string that is a palindrome.\n - Append to the end of the string reverse of a string prefix that comes before the palindromic suffix.\n >>> make_palindrome('')\n ''\n >>> make_palindrome('cat')\n 'catac'\n >>> make_palindrome('cata')\n 'catac'\n \"\"\"\n if not string:\n return \"\"\n\n # We look for the longest palindromic suffix.\n # By iterating from the start of the string (index 0), \n # the first index 'i' that makes string[i:] a palindrome \n # will give us the longest possible palindromic suffix.\n for i in range(len(string)):\n suffix = string[i:]\n if is_palindrome(suffix):\n # The part of the string before the palindromic suffix\n prefix = string[:i]\n # Append the reverse of that prefix to the original string\n return string + prefix[::-1]\n \n return string # Fallback, though logic above covers all cases"}
{"task_id": "HumanEval/11", "solution": "from typing import List\ndef string_xor(a: str, b: str) -> str:\n \"\"\" Input are two strings a and b consisting only of 1s and 0s.\n Perform binary XOR on these inputs and return result also as a string.\n >>> string_xor('010', '110')\n '100'\n \"\"\"\n # Use zip to iterate through both strings simultaneously.\n # In binary, XOR is 1 if the bits are different and 0 if they are the same.\n return \"\".join('1' if x != y else '0' for x, y in zip(a, b))"}
{"task_id": "HumanEval/12", "solution": "from typing import List, Optional\ndef longest(strings: List[str]) -> Optional[str]:\n \"\"\" Out of list of strings, return the longest one. Return the first one in case of multiple\n strings of the same length. Return None in case the input list is empty.\n >>> longest([])\n None\n >>> longest(['a', 'b', 'c'])\n 'a'\n >>> longest(['a', 'bb', 'ccc'])\n 'ccc'\n \"\"\"\n if not strings:\n return None\n \n # Python's max() function is stable, meaning if multiple elements have the \n # same key value (length in this case), it returns the first one encountered.\n return max(strings, key=len)"}
{"task_id": "HumanEval/13", "solution": "def greatest_common_divisor(a: int, b: int) -> int:\n \"\"\" Return a greatest common divisor of two integers a and b\n >>> greatest_common_divisor(3, 5)\n 1\n >>> greatest_common_divisor(25, 15)\n 5\n \"\"\"\n while b:\n a, b = b, a % b\n return a"}
{"task_id": "HumanEval/14", "solution": "from typing import List\ndef all_prefixes(string: str) -> List[str]:\n \"\"\" Return list of all prefixes from shortest to longest of the input string\n >>> all_prefixes('abc')\n ['a', 'ab', 'abc']\n \"\"\"\n return [string[:i] for i in range(1, len(string) + 1)]"}
{"task_id": "HumanEval/15", "solution": "def string_sequence(n: int) -> str:\n \"\"\" Return a string containing space-delimited numbers starting from 0 upto n inclusive.\n >>> string_sequence(0)\n '0'\n >>> string_sequence(5)\n '0 1 2 3 4 5'\n \"\"\"\n # range(n + 1) generates integers from 0 up to and including n.\n # map(str, ...) converts each integer in that range into a string.\n # ' '.join(...) concatenates those strings with a space between them.\n return ' '.join(map(str, range(n + 1)))"}
{"task_id": "HumanEval/16", "solution": "def count_distinct_characters(string: str) -> int:\n \"\"\" Given a string, find out how many distinct characters (regardless of case) does it consist of\n >>> count_distinct_characters('xyzXYZ')\n 3\n >>> count_distinct_characters('Jerry')\n 4\n \"\"\"\n # Convert the string to lowercase to ensure case-insensitivity\n lowered_string = string.lower()\n \n # Use a set to store unique characters and return its length\n return len(set(lowered_string))"}
{"task_id": "HumanEval/17", "solution": "from typing import List\ndef parse_music(music_string: str) -> List[int]:\n \"\"\" Input to this function is a string representing musical notes in a special ASCII format.\n Your task is to parse this string and return list of integers corresponding to how many beats does each\n not last.\n\n Here is a legend:\n 'o' - whole note, lasts four beats\n 'o|' - half note, lasts two beats\n '.|' - quater note, lasts one beat\n\n >>> parse_music('o o| .| o| o| .| .| .| .| o o')\n [4, 2, 1, 2, 2, 1, 1, 1, 1, 4, 4]\n \"\"\"\n # Define the mapping of note symbols to their beat values\n note_map = {\n 'o': 4,\n 'o|': 2,\n '.|': 1\n }\n \n # Split the input string by whitespace to isolate each note token\n tokens = music_string.split()\n \n # Map each token to its corresponding beat value using the dictionary\n beats = [note_map[token] for token in tokens]\n \n return beats"}
{"task_id": "HumanEval/18", "solution": "def how_many_times(string: str, substring: str) -> int:\n \"\"\" Find how many times a given substring can be found in the original string. Count overlaping cases.\n >>> how_many_times('', 'a')\n 0\n >>> how_many_times('aaa', 'a')\n 3\n >>> how_many_times('aaaa', 'aa')\n 3\n \"\"\"\n if not substring:\n return 0\n \n count = 0\n # Iterate through the string and check slices of the same length as the substring\n for i in range(len(string) - len(substring) + 1):\n if string[i : i + len(substring)] == substring:\n count += 1\n \n return count"}
{"task_id": "HumanEval/19", "solution": "from typing import List\ndef sort_numbers(numbers: str) -> str:\n \"\"\" Input is a space-delimited string of numberals from 'zero' to 'nine'.\n Valid choices are 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight' and 'nine'.\n Return the string with numbers sorted from smallest to largest\n >>> sort_numbers('three one five')\n 'one three five'\n \"\"\"\n # Mapping of number words to their integer values for sorting purposes\n num_map = {\n 'zero': 0,\n 'one': 1,\n 'two': 2,\n 'three': 3,\n 'four': 4,\n 'five': 5,\n 'six': 6,\n 'seven': 7,\n 'eight': 8,\n 'nine': 9\n }\n \n # Split the input string into a list of words\n words = numbers.split()\n \n # Sort the words using the integer value from the map as the sort key\n sorted_words = sorted(words, key=lambda x: num_map[x])\n \n # Join the sorted list back into a space-delimited string\n return ' '.join(sorted_words)"}
{"task_id": "HumanEval/20", "solution": "from typing import List, Tuple\ndef find_closest_elements(numbers: List[float]) -> Tuple[float, float]:\n \"\"\" From a supplied list of numbers (of length at least two) select and return two that are the closest to each\n other and return them in order (smaller number, larger number).\n >>> find_closest_elements([1.0, 2.0, 3.0, 4.0, 5.0, 2.2])\n (2.0, 2.2)\n >>> find_closest_elements([1.0, 2.0, 3.0, 4.0, 5.0, 2.0])\n (2.0, 2.0)\n \"\"\"\n # First, sort the numbers to ensure that the closest elements are adjacent\n sorted_nums = sorted(numbers)\n \n # Initialize variables to track the minimum difference and the resulting pair\n # We start with the first two elements as the initial baseline\n min_diff = float('inf')\n closest_pair = (sorted_nums[0], sorted_nums[1])\n \n # Iterate through the sorted list and compare adjacent pairs\n for i in range(len(sorted_nums) - 1):\n current_num = sorted_nums[i]\n next_num = sorted_nums[i + 1]\n diff = next_num - current_num\n \n if diff < min_diff:\n min_diff = diff\n closest_pair = (current_num, next_num)\n \n return closest_pair"}
{"task_id": "HumanEval/21", "solution": "from typing import List\ndef rescale_to_unit(numbers: List[float]) -> List[float]:\n \"\"\" Given list of numbers (of at least two elements), apply a linear transform to that list,\n such that the smallest number will become 0 and the largest will become 1\n >>> rescale_to_unit([1.0, 2.0, 3.0, 4.0, 5.0])\n [0.0, 0.25, 0.5, 0.75, 1.0]\n \"\"\"\n min_val = min(numbers)\n max_val = max(numbers)\n diff = max_val - min_val\n\n # Handle the case where all elements in the list are the same to avoid division by zero\n if diff == 0:\n return [0.0] * len(numbers)\n\n return [(x - min_val) / diff for x in numbers]"}
{"task_id": "HumanEval/22", "solution": "from typing import List, Any\ndef filter_integers(values: List[Any]) -> List[int]:\n \"\"\" Filter given list of any python values only for integers\n >>> filter_integers(['a', 3.14, 5])\n [5]\n >>> filter_integers([1, 2, 3, 'abc', {}, []])\n [1, 2, 3]\n \"\"\"\n # We use type(x) is int instead of isinstance(x, int) because \n # in Python, bools are a subclass of ints (isinstance(True, int) is True).\n return [x for x in values if type(x) is int]"}
{"task_id": "HumanEval/23", "solution": "def strlen(string: str) -> int:\n \"\"\" Return length of given string\n >>> strlen('')\n 0\n >>> strlen('abc')\n 3\n \"\"\"\n return len(string)"}
{"task_id": "HumanEval/24", "solution": "def largest_divisor(n: int) -> int:\n \"\"\" For a given number n, find the largest number that divides n evenly, smaller than n\n >>> largest_divisor(15)\n 5\n \"\"\"\n # The largest divisor of n (smaller than n) is equal to n divided by \n # the smallest prime factor of n.\n # We iterate from 2 up to the square root of n to find the smallest factor.\n for i in range(2, int(n**0.5) + 1):\n if n % i == 0:\n return n // i\n \n # If no divisor is found between 2 and sqrt(n), then n is prime (or n=1).\n # In the case of a prime number, the only divisor smaller than itself is 1.\n return 1"}
{"task_id": "HumanEval/25", "solution": "from typing import List\ndef factorize(n: int) -> List[int]:\n \"\"\" Return list of prime factors of given integer in the order from smallest to largest.\n Each of the factors should be listed number of times corresponding to how many times it appeares in factorization.\n Input number should be equal to the product of all factors\n >>> factorize(8)\n [2, 2, 2]\n >>> factorize(25)\n [5, 5]\n >>> factorize(70)\n [2, 5, 7]\n \"\"\"\n factors = []\n # Handle the smallest prime factor 2 separately to allow stepping by 2 in the loop\n while n % 2 == 0:\n factors.append(2)\n n //= 2\n \n # Check odd numbers starting from 3 up to the square root of n\n d = 3\n while d * d <= n:\n while n % d == 0:\n factors.append(d)\n n //= d\n d += 2\n \n # If n is still greater than 1, then the remaining n must be prime\n if n > 1:\n factors.append(n)\n \n return factors"}
{"task_id": "HumanEval/26", "solution": "from typing import List\nfrom collections import Counter\ndef remove_duplicates(numbers: List[int]) -> List[int]:\n \"\"\" From a list of integers, remove all elements that occur more than once.\n Keep order of elements left the same as in the input.\n >>> remove_duplicates([1, 2, 3, 2, 4])\n [1, 3, 4]\n \"\"\"\n # Count occurrences of each number in the list\n counts = Counter(numbers)\n \n # Return a new list containing only elements that appeared exactly once,\n # preserving the original order.\n return [x for x in numbers if counts[x] == 1]"}
{"task_id": "HumanEval/27", "solution": "def flip_case(string: str) -> str:\n \"\"\" For a given string, flip lowercase characters to uppercase and uppercase to lowercase.\n >>> flip_case('Hello')\n 'hELLO'\n \"\"\"\n return string.swapcase()"}
{"task_id": "HumanEval/28", "solution": "from typing import List\ndef concatenate(strings: List[str]) -> str:\n \"\"\" Concatenate list of strings into a single string\n >>> concatenate([])\n ''\n >>> concatenate(['a', 'b', 'c'])\n 'abc'\n \"\"\"\n return \"\".join(strings)"}
{"task_id": "HumanEval/29", "solution": "from typing import List\ndef filter_by_prefix(strings: List[str], prefix: str) -> List[str]:\n \"\"\" Filter an input list of strings only for ones that start with a given prefix.\n >>> filter_by_prefix([], 'a')\n []\n >>> filter_by_prefix(['abc', 'bcd', 'cde', 'array'], 'a')\n ['abc', 'array']\n \"\"\"\n return [s for s in strings if s.startswith(prefix)]"}
{"task_id": "HumanEval/30", "solution": "def get_positive(l: list):\n \"\"\"Return only positive numbers in the list.\n >>> get_positive([-1, 2, -4, 5, 6])\n [2, 5, 6]\n >>> get_positive([5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10])\n [5, 3, 2, 3, 9, 123, 1]\n \"\"\"\n return [x for x in l if x > 0]"}
{"task_id": "HumanEval/31", "solution": "import math\ndef is_prime(n):\n \"\"\"Return true if a given number is prime, and false otherwise.\n >>> is_prime(6)\n False\n >>> is_prime(101)\n True\n >>> is_prime(11)\n True\n >>> is_prime(13441)\n True\n >>> is_prime(61)\n True\n >>> is_prime(4)\n False\n >>> is_prime(1)\n False\n \"\"\"\n # Prime numbers must be greater than 1\n if n <= 1:\n return False\n \n # 2 is the only even prime number\n if n == 2:\n return True\n \n # Eliminate all other even numbers immediately\n if n % 2 == 0:\n return False\n \n # Check for factors from 3 up to the square root of n.\n # We only need to check odd numbers because we've already handled evens.\n limit = int(math.sqrt(n)) + 1\n for i in range(3, limit, 2):\n if n % i == 0:\n return False\n \n return True"}
{"task_id": "HumanEval/32", "solution": "import math\ndef poly(xs: list, x: float):\n \"\"\"\n Evaluates polynomial with coefficients xs at point x.\n return xs[0] + xs[1] * x + xs[2] * x^2 + .... xs[n] * x^n\n \"\"\"\n return sum([coeff * math.pow(x, i) for i, coeff in enumerate(xs)])\ndef find_zero(xs: list):\n \"\"\" \n xs are coefficients of a polynomial.\n find_zero finds x such that poly(x) = 0.\n find_zero returns only one zero point, even if there are many.\n Moreover, find_zero only takes list xs having even number of coefficients\n and largest non zero coefficient as it guarantees a solution.\n \n >>> round(find_zero([1, 2]), 2) # f(x) = 1 + 2x\n -0.5\n >>> round(find_zero([-6, 11, -6, 1]), 2) # (x - 1) * (x - 2) * (x - 3) = -6 + 11x - 6x^2 + x^3\n 1.0\n \"\"\"\n # The problem states the list has an even number of coefficients, meaning the degree n is odd.\n # A real polynomial of odd degree always has at least one real root.\n \n # We use Cauchy's bound to find an interval [-M, M] that contains all roots.\n # For f(x) = a_n*x^n + ... + a_0, any root z satisfies |z| <= 1 + max(|a_0|, ..., |a_{n-1}|) / |a_n|\n n = len(xs) - 1\n an = abs(xs[n])\n \n # Handle the case where leading coefficient might be zero (though constraints suggest otherwise)\n if an == 0:\n # Find the actual degree by looking for the last non-zero coefficient\n while n > 0 and xs[n] == 0:\n n -= 1\n an = abs(xs[n])\n\n max_coeff = max(abs(c) for c in xs[:n])\n M = 1 + (max_coeff / an if an != 0 else 1.0)\n\n # Bisection Method\n low = -M\n high = M\n f_low = poly(xs, low)\n f_high = poly(xs, high)\n\n # If the boundaries don't have opposite signs (which shouldn't happen for odd degree), \n # we expand slightly or shift. But for odd degrees, f(-inf) and f(+inf) always differ in sign.\n if f_low * f_high > 0:\n # This is a fallback; theoretically not reached for odd-degree polynomials with an != 0\n return None\n\n # Iterate to narrow down the root (100 iterations provide high precision)\n for _ in range(100):\n mid = (low + high) / 2\n f_mid = poly(xs, mid)\n \n if f_mid == 0:\n return mid\n \n # Check which sub-interval contains the root\n if f_low * f_mid < 0:\n high = mid\n f_high = f_mid\n else:\n low = mid\n f_low = f_mid\n\n return (low + high) / 2"}
{"task_id": "HumanEval/33", "solution": "def sort_third(l: list):\n \"\"\"This function takes a list l and returns a list l' such that\n l' is identical to l in the indices that are not divisible by three, while its values at the indices that are divisible by three are equal\n to the values of the corresponding indices of l, but sorted.\n >>> sort_third([1, 2, 3])\n [1, 2, 3]\n >>> sort_third([5, 6, 3, 4, 8, 9, 2])\n [2, 6, 3, 4, 8, 9, 5]\n \"\"\"\n # Extract elements at indices divisible by 3 (0, 3, 6, ...)\n thirds = [l[i] for i in range(len(l)) if i % 3 == 0]\n \n # Sort the extracted elements\n thirds.sort()\n \n # Create a new list to store the result\n result = []\n third_ptr = 0\n \n for i in range(len(l)):\n if i % 3 == 0:\n # If index is divisible by 3, insert the next sorted element\n result.append(thirds[third_ptr])\n third_ptr += 1\n else:\n # Otherwise, keep the original element\n result.append(l[i])\n \n return result"}
{"task_id": "HumanEval/34", "solution": "def unique(l: list):\n \"\"\"Return sorted unique elements in a list\n >>> unique([5, 3, 5, 2, 3, 3, 9, 0, 123])\n [0, 2, 3, 5, 9, 123]\n \"\"\"\n # set(l) removes all duplicate elements\n # sorted() returns a new list containing all elements from the iterable in ascending order\n return sorted(set(l))"}
{"task_id": "HumanEval/35", "solution": "def max_element(l: list):\n \"\"\"Return maximum element in the list.\n >>> max_element([1, 2, 3])\n 3\n >>> max_element([5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10])\n 123\n \"\"\"\n return max(l)"}
{"task_id": "HumanEval/36", "solution": "def fizz_buzz(n: int):\n \"\"\"Return the number of times the digit 7 appears in integers less than n which are divisible by 11 or 13.\n >>> fizz_buzz(50)\n 0\n >>> fizz_buzz(78)\n 2\n >>> fizz_buzz(79)\n 3\n \"\"\"\n count = 0\n for i in range(n):\n # Check if the number is divisible by 11 or 13\n if i % 11 == 0 or i % 13 == 0:\n # Convert the number to a string and count occurrences of '7'\n count += str(i).count('7')\n return count"}
{"task_id": "HumanEval/37", "solution": "def sort_even(l: list):\n \"\"\"This function takes a list l and returns a list l' such that\n l' is identical to l in the odd indicies, while its values at the even indicies are equal\n to the values of the even indicies of l, but sorted.\n >>> sort_even([1, 2, 3])\n [1, 2, 3]\n >>> sort_even([5, 6, 3, 4])\n [3, 6, 5, 4]\n \"\"\"\n # Create a copy of the original list to avoid mutating the input\n result = l[:]\n \n # Extract elements at even indices (0, 2, 4...) using slicing [start:stop:step]\n even_elements = l[0::2]\n \n # Sort the extracted even-indexed elements\n sorted_evens = sorted(even_elements)\n \n # Assign the sorted values back into the even indices of the result list\n result[0::2] = sorted_evens\n \n return result"}
{"task_id": "HumanEval/38", "solution": "def decode_cyclic(s: str):\n \"\"\"\n takes as input string encoded with encode_cyclic function. Returns decoded string.\n \"\"\"\n # Split the encoded string into groups of three characters, just like in encode_cyclic.\n groups = [s[(3 * i):min((3 * i + 3), len(s))] for i in range((len(s) + 2) // 3)]\n \n # In encode_cyclic, a group (0, 1, 2) became (1, 2, 0).\n # To reverse this, the encoded group (E0, E1, E2) must become (E2, E0, E1).\n decoded_groups = []\n for group in groups:\n if len(group) == 3:\n # Shift the last character to the front\n decoded_group = group[2] + group[0:2]\n decoded_groups.append(decoded_group)\n else:\n # Groups with fewer than 3 characters were not changed during encoding\n decoded_groups.append(group)\n \n return \"\".join(decoded_groups)"}
{"task_id": "HumanEval/39", "solution": "def prime_fib(n: int):\n \"\"\"\n prime_fib returns n-th number that is a Fibonacci number and it's also prime.\n >>> prime_fib(1)\n 2\n >>> prime_fib(2)\n 3\n >>> prime_fib(3)\n 5\n >>> prime_fib(4)\n 13\n >>> prime_fib(5)\n 89\n \"\"\"\n def is_prime(num):\n \"\"\"Helper function to check if a number is prime.\"\"\"\n if num < 2:\n return False\n if num == 2:\n return True\n if num % 2 == 0:\n return False\n # Check odd divisors up to the square root of the number\n for i in range(3, int(num**0.5) + 1, 2):\n if num % i == 0:\n return False\n return True\n\n count = 0\n a, b = 0, 1\n \n # Generate Fibonacci numbers and check for primality until the n-th prime is found\n while count < n:\n # Calculate next Fibonacci number\n a, b = b, a + b\n if is_prime(b):\n count += 1\n \n return b"}
{"task_id": "HumanEval/40", "solution": "def triples_sum_to_zero(l: list):\n \"\"\"\n triples_sum_to_zero takes a list of integers as an input.\n it returns True if there are three distinct elements in the list that\n sum to zero, and False otherwise.\n\n >>> triples_sum_to_zero([1, 3, 5, 0])\n False\n >>> triples_sum_to_zero([1, 3, -2, 1])\n True\n >>> triples_sum_to_zero([1, 2, 3, 7])\n False\n >>> triples_sum_to_zero([2, 4, -5, 3, 9, 7])\n True\n >>> triples_sum_to_zero([1])\n False\n \"\"\"\n n = len(l)\n if n < 3:\n return False\n\n # Sort the list to enable the two-pointer approach\n # Time Complexity: O(n log n) for sorting, O(n^2) for searching. Total: O(n^2).\n # Space Complexity: O(1) or O(n) depending on sort implementation.\n nums = sorted(l)\n\n for i in range(n - 2):\n # Use two pointers to find if any pair sums to the negative of nums[i]\n left = i + 1\n right = n - 1\n \n while left < right:\n current_sum = nums[i] + nums[left] + nums[right]\n if current_sum == 0:\n return True\n elif current_sum < 0:\n left += 1\n else:\n right -= 1\n \n return False"}
{"task_id": "HumanEval/41", "solution": "def car_race_collision(n: int):\n \"\"\"\n Imagine a road that's a perfectly straight infinitely long line.\n n cars are driving left to right; simultaneously, a different set of n cars\n are driving right to left. The two sets of cars start out being very far from\n each other. All cars move in the same speed. Two cars are said to collide\n when a car that's moving left to right hits a car that's moving right to left.\n However, the cars are infinitely sturdy and strong; as a result, they continue moving\n in their trajectory as if they did not collide.\n\n This function outputs the number of such collisions.\n \"\"\"\n # Analysis:\n # 1. There are n cars moving Left -> Right (L2R).\n # 2. There are n cars moving Right -> Left (R2L).\n # 3. The problem states they start \"very far from each other,\" implying that all \n # L2R cars begin to the left of all R2L cars.\n # 4. Since every L2R car is moving towards every R2L car and they pass through \n # each other without changing direction or speed, every single L2R car will \n # eventually collide with every single R2L car exactly once.\n # 5. Therefore, the total number of collisions is the product of the sizes of \n # the two sets: n * n.\n \n return n * n"}
{"task_id": "HumanEval/42", "solution": "def incr_list(l: list):\n \"\"\"Return list with elements incremented by 1.\n >>> incr_list([1, 2, 3])\n [2, 3, 4]\n >>> incr_list([5, 3, 5, 2, 3, 3, 9, 0, 123])\n [6, 4, 6, 3, 4, 4, 10, 1, 124]\n \"\"\"\n return [x + 1 for x in l]"}
{"task_id": "HumanEval/43", "solution": "def pairs_sum_to_zero(l):\n \"\"\"\n pairs_sum_to_zero takes a list of integers as an input.\n it returns True if there are two distinct elements in the list that\n sum to zero, and False otherwise.\n >>> pairs_sum_to_zero([1, 3, 5, 0])\n False\n >>> pairs_sum_to_zero([1, 3, -2, 1])\n False\n >>> pairs_sum_to_zero([1, 2, 3, 7])\n False\n >>> pairs_sum_to_zero([2, 4, -5, 3, 5, 7])\n True\n >>> pairs_sum_to_zero([1])\n False\n \"\"\"\n # We use a set to keep track of the numbers we have encountered so far.\n # This allows us to check if the additive inverse (negative) of the current \n # number exists in the list in O(1) average time complexity.\n seen = set()\n \n for num in l:\n # If -num is already in our set, we have found two distinct elements that sum to zero.\n if -num in seen:\n return True\n # Otherwise, add the current number to the set and continue.\n seen.add(num)\n \n return False"}
{"task_id": "HumanEval/44", "solution": "def change_base(x: int, base: int):\n \"\"\"Change numerical base of input number x to base.\n return string representation after the conversion.\n base numbers are less than 10.\n >>> change_base(8, 3)\n '22'\n >>> change_base(8, 2)\n '1000'\n >>> change_base(7, 2)\n '111'\n \"\"\"\n if x == 0:\n return '0'\n \n digits = []\n while x > 0:\n # Get the remainder of division by base (the current digit)\n digits.append(str(x % base))\n # Update x to be the quotient\n x //= base\n \n # The digits were collected from least significant to most significant,\n # so we reverse them and join into a single string.\n return \"\".join(reversed(digits))"}
{"task_id": "HumanEval/45", "solution": "def triangle_area(a, h):\n \"\"\"Given length of a side and high return area for a triangle.\n >>> triangle_area(5, 3)\n 7.5\n \"\"\"\n return 0.5 * a * h"}
{"task_id": "HumanEval/46", "solution": "def fib4(n: int):\n \"\"\"The Fib4 number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:\n fib4(0) -> 0\n fib4(1) -> 0\n fib4(2) -> 2\n fib4(3) -> 0\n fib4(n) -> fib4(n-1) + fib4(n-2) + fib4(n-3) + fib4(n-4).\n Please write a function to efficiently compute the n-th element of the fib4 number sequence. Do not use recursion.\n >>> fib4(5)\n 4\n >>> fib4(6)\n 8\n >>> fib4(7)\n 14\n \"\"\"\n # Base cases for n < 4\n if n == 0:\n return 0\n if n == 1:\n return 0\n if n == 2:\n return 2\n if n == 3:\n return 0\n\n # We use a sliding window of the last four values to compute the next value.\n # Initial state for fib4(0), fib4(1), fib4(2), fib4(3)\n a, b, c, d = 0, 0, 2, 0\n\n # Iterate from index 4 up to n\n for _ in range(4, n + 1):\n # The next element is the sum of the previous four elements\n current = a + b + c + d\n # Shift the window forward:\n # a becomes fib4(i-3), b becomes fib4(i-2), etc.\n a, b, c, d = b, c, d, current\n\n return d"}
{"task_id": "HumanEval/47", "solution": "def median(l: list):\n \"\"\"Return median of elements in the list l.\n >>> median([3, 1, 2, 4, 5])\n 3\n >>> median([-10, 4, 6, 1000, 10, 20])\n 8.0\n \"\"\"\n # First, sort the list in ascending order\n sorted_l = sorted(l)\n n = len(sorted_l)\n \n # If the list is empty, we cannot calculate a median\n if n == 0:\n return None\n \n mid = n // 2\n \n # If the number of elements is odd, return the middle element\n if n % 2 == 1:\n return sorted_l[mid]\n # If the number of elements is even, return the average of the two middle elements\n else:\n return (sorted_l[mid - 1] + sorted_l[mid]) / 2.0"}
{"task_id": "HumanEval/48", "solution": "def is_palindrome(text: str):\n \"\"\"\n Checks if given string is a palindrome\n >>> is_palindrome('')\n True\n >>> is_palindrome('aba')\n True\n >>> is_palindrome('aaaaa')\n True\n >>> is_palindrome('zbcd')\n False\n \"\"\"\n return text == text[::-1]"}
{"task_id": "HumanEval/49", "solution": "def modp(n: int, p: int):\n \"\"\"Return 2^n modulo p (be aware of numerics).\n >>> modp(3, 5)\n 3\n >>> modp(1101, 101)\n 2\n >>> modp(0, 101)\n 1\n >>> modp(3, 11)\n 8\n >>> modp(100, 101)\n 1\n \"\"\"\n # Python's built-in pow(base, exp, mod) function implements \n # modular exponentiation efficiently using the square-and-multiply algorithm.\n return pow(2, n, p)"}
{"task_id": "HumanEval/50", "solution": "def decode_shift(s: str):\n \"\"\"\n takes as input string encoded with encode_shift function. Returns decoded string.\n \"\"\"\n # To reverse a shift of +5, we shift by -5.\n return \"\".join([chr(((ord(ch) - 5 - ord(\"a\")) % 26) + ord(\"a\")) for ch in s])"}
{"task_id": "HumanEval/51", "solution": "def remove_vowels(text):\n \"\"\"\n remove_vowels is a function that takes string and returns string without vowels.\n >>> remove_vowels('')\n ''\n >>> remove_vowels(\"abcdef\\nghijklm\")\n 'bcdf\\nghjklm'\n >>> remove_vowels('abcdef')\n 'bcdf'\n >>> remove_vowels('aaaaa')\n ''\n >>> remove_vowels('aaBAA')\n 'B'\n >>> remove_vowels('zbcd')\n 'zbcd'\n \"\"\"\n vowels = \"aeiouAEIOU\"\n return \"\".join([char for char in text if char not in vowels])"}
{"task_id": "HumanEval/52", "solution": "def below_threshold(l: list, t: int):\n \"\"\"Return True if all numbers in the list l are below threshold t.\n >>> below_threshold([1, 2, 4, 10], 100)\n True\n >>> below_threshold([1, 20, 4, 10], 5)\n False\n \"\"\"\n return all(x < t for x in l)"}
{"task_id": "HumanEval/53", "solution": "def add(x: int, y: int) -> int:\n \"\"\"Add two numbers x and y\n >>> add(2, 3)\n 5\n >>> add(5, 7)\n 12\n \"\"\"\n return x + y"}
{"task_id": "HumanEval/54", "solution": "def same_chars(s0: str, s1: str):\n \"\"\"\n Check if two words have the same characters.\n >>> same_chars('eabcdzzzz', 'dddzzzzzzzddeddabc')\n True\n >>> same_chars('abcd', 'dddddddabc')\n True\n >>> same_chars('dddddddabc', 'abcd')\n True\n >>> same_chars('eabcd', 'dddddddabc')\n False\n >>> same_chars('abcd', 'dddddddabce')\n False\n >>> same_chars('eabcdzzzz', 'dddzzzzzzzddddabc')\n False\n \"\"\"\n # Convert both strings to sets of characters and compare them.\n # A set contains only unique elements, so this effectively checks \n # if the collection of distinct characters in s0 is identical to that in s1.\n return set(s0) == set(s1)"}
{"task_id": "HumanEval/55", "solution": "def fib(n: int):\n \"\"\"Return n-th Fibonacci number.\n >>> fib(10)\n 55\n >>> fib(1)\n 1\n >>> fib(8)\n 21\n \"\"\"\n if n <= 0:\n return 0\n elif n == 1:\n return 1\n \n a, b = 0, 1\n for _ in range(2, n + 1):\n a, b = b, a + b\n return b"}
{"task_id": "HumanEval/56", "solution": "def correct_bracketing(brackets: str):\n \"\"\" brackets is a string of \"<\" and \">\".\n return True if every opening bracket has a corresponding closing bracket.\n\n >>> correct_bracketing(\"<\")\n False\n >>> correct_bracketing(\"<>\")\n True\n >>> correct_bracketing(\"<<><>>\")\n True\n >>> correct_bracketing(\"><<>\")\n False\n \"\"\"\n balance = 0\n for char in brackets:\n if char == '<':\n balance += 1\n elif char == '>':\n balance -= 1\n \n # If balance is negative, a closing bracket appeared without an opening one\n if balance < 0:\n return False\n \n # The string is correct if all opened brackets were closed (balance returns to 0)\n return balance == 0"}
{"task_id": "HumanEval/57", "solution": "def monotonic(l: list):\n \"\"\"Return True is list elements are monotonically increasing or decreasing.\n >>> monotonic([1, 2, 4, 20])\n True\n >>> monotonic([1, 20, 4, 10])\n False\n >>> monotonic([4, 1, 0, -10])\n True\n \"\"\"\n # An empty list or a list with one element is monotonically both increasing and decreasing.\n if len(l) <= 1:\n return True\n\n is_increasing = True\n is_decreasing = True\n\n for i in range(len(l) - 1):\n if l[i] > l[i+1]:\n is_increasing = False\n if l[i] < l[i+1]:\n is_decreasing = False\n \n return is_increasing or is_decreasing"}
{"task_id": "HumanEval/58", "solution": "def common(l1: list, l2: list):\n \"\"\"Return sorted unique common elements for two lists.\n >>> common([1, 4, 3, 34, 653, 2, 5], [5, 7, 1, 5, 9, 653, 121])\n [1, 5, 653]\n >>> common([5, 3, 2, 8], [3, 2])\n [2, 3]\n \"\"\"\n # Convert lists to sets to find the intersection (common elements)\n # and automatically handle uniqueness.\n set1 = set(l1)\n set2 = set(l2)\n \n # Find common elements using the intersection operator '&'\n intersect = set1 & set2\n \n # Return the result as a sorted list\n return sorted(list(intersect))"}
{"task_id": "HumanEval/59", "solution": "def largest_prime_factor(n: int):\n \"\"\"Return the largest prime factor of n. Assume n > 1 and is not a prime.\n >>> largest_prime_factor(13195)\n 29\n >>> largest_prime_factor(2048)\n 2\n \"\"\"\n i = 2\n max_f = 0\n # Iterate from the smallest possible prime factor (2) up to sqrt(n)\n while i * i <= n:\n if n % i == 0:\n # If i divides n, it is a prime factor because we are iterating upwards\n # and have already removed all smaller factors.\n max_f = i\n # Divide out all occurrences of this factor\n while n % i == 0:\n n //= i\n i += 1\n \n # If after the loop n is still greater than 1, then the remaining n \n # must be a prime number and it will be the largest prime factor.\n if n > 1:\n max_f = n\n \n return max_f"}
{"task_id": "HumanEval/60", "solution": "def sum_to_n(n: int):\n \"\"\"sum_to_n is a function that sums numbers from 1 to n.\n >>> sum_to_n(30)\n 465\n >>> sum_to_n(100)\n 5050\n >>> sum_to_n(5)\n 15\n >>> sum_to_n(10)\n 55\n >>> sum_to_n(1)\n 1\n \"\"\"\n # Using the arithmetic series formula: Sum = n * (n + 1) / 2\n return n * (n + 1) // 2"}
{"task_id": "HumanEval/61", "solution": "def correct_bracketing(brackets: str):\n \"\"\" brackets is a string of \"(\" and \")\".\n return True if every opening bracket has a corresponding closing bracket.\n\n >>> correct_bracketing(\"(\")\n False\n >>> correct_bracketing(\"()\")\n True\n >>> correct_bracketing(\"(()())\")\n True\n >>> correct_bracketing(\")(()\")\n False\n \"\"\"\n balance = 0\n for char in brackets:\n if char == '(':\n balance += 1\n elif char == ')':\n balance -= 1\n \n # If balance is negative, a closing bracket appeared without a matching opening one\n if balance < 0:\n return False\n \n # The string is correct if all opened brackets were closed (balance returns to 0)\n return balance == 0"}
{"task_id": "HumanEval/62", "solution": "def derivative(xs: list):\n \"\"\" xs represent coefficients of a polynomial.\n xs[0] + xs[1] * x + xs[2] * x^2 + ....\n Return derivative of this polynomial in the same form.\n >>> derivative([3, 1, 2, 4, 5])\n [1, 4, 12, 20]\n >>> derivative([1, 2, 3])\n [2, 6]\n \"\"\"\n # The derivative of a constant (xs[0]) is 0.\n # For terms xs[i] * x^i where i > 0, the derivative is (i * xs[i]) * x^(i-1).\n # Therefore, we start iterating from index 1 and multiply each coefficient by its power.\n return [i * xs[i] for i in range(1, len(xs))]"}
{"task_id": "HumanEval/63", "solution": "def fibfib(n: int):\n \"\"\"The FibFib number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:\n fibfib(0) == 0\n fibfib(1) == 0\n fibfib(2) == 1\n fibfib(n) == fibfib(n-1) + fibfib(n-2) + fibfib(n-3).\n Please write a function to efficiently compute the n-th element of the fibfib number sequence.\n >>> fibfib(1)\n 0\n >>> fibfib(5)\n 4\n >>> fibfib(8)\n 24\n \"\"\"\n # Base cases for n = 0, 1, 2\n if n == 0:\n return 0\n if n == 1:\n return 0\n if n == 2:\n return 1\n\n # We use an iterative approach to achieve O(n) time complexity and O(1) space complexity.\n # a, b, c represent fibfib(i-3), fibfib(i-2), and fibfib(i-1) respectively.\n a, b, c = 0, 0, 1\n \n for _ in range(3, n + 1):\n # The next element is the sum of the previous three elements\n next_val = a + b + c\n # Shift values forward for the next iteration\n a, b, c = b, c, next_val\n \n return c"}
{"task_id": "HumanEval/64", "solution": "def vowels_count(s):\n \"\"\"Write a function vowels_count which takes a string representing\n a word as input and returns the number of vowels in the string.\n Vowels in this case are 'a', 'e', 'i', 'o', 'u'. Here, 'y' is also a\n vowel, but only when it is at the end of the given word.\n\n Example:\n >>> vowels_count(\"abcde\")\n 2\n >>> vowels_count(\"ACEDY\")\n 3\n \"\"\"\n # Convert string to lowercase to handle case-insensitivity\n s_lower = s.lower()\n vowels = \"aeiou\"\n count = 0\n \n # Count standard vowels\n for char in s_lower:\n if char in vowels:\n count += 1\n \n # Check if 'y' is at the end of the word\n if s_lower and s_lower[-1] == 'y':\n count += 1\n \n return count"}
{"task_id": "HumanEval/65", "solution": "def circular_shift(x, shift):\n \"\"\"Circular shift the digits of the integer x, shift the digits right by shift\n and return the result as a string.\n If shift > number of digits, return digits reversed.\n >>> circular_shift(12, 1)\n \"21\"\n >>> circular_shift(12, 2)\n \"12\"\n \"\"\"\n # Convert integer to string to manipulate digits\n s = str(x)\n n = len(s)\n \n if shift > n:\n # If shift is greater than the number of digits, return reversed string\n return s[::-1]\n elif shift == 0:\n # A shift of 0 returns the original string\n return s\n else:\n # Perform circular right shift:\n # Take the last 'shift' characters and move them to the front\n # The slice s[n-shift:] gets the tail, s[:n-shift] gets the head\n return s[n - shift:] + s[:n - shift]"}
{"task_id": "HumanEval/66", "solution": "def digitSum(s):\n \"\"\"Task\n Write a function that takes a string as input and returns the sum of the upper characters only'\n ASCII codes.\n\n Examples:\n digitSum(\"\") => 0\n digitSum(\"abAB\") => 131\n digitSum(\"abcCd\") => 67\n digitSum(\"helloE\") => 69\n digitSum(\"woArBld\") => 131\n digitSum(\"aAaaaXa\") => 153\n \"\"\"\n # Use a generator expression to iterate through the string, \n # filter for uppercase characters using .isupper(), \n # get their ASCII values with ord(), and sum them up.\n return sum(ord(char) for char in s if char.isupper())"}
{"task_id": "HumanEval/67", "solution": "import re\ndef fruit_distribution(s, n):\n \"\"\"\n In this task, you will be given a string that represents a number of apples and oranges \n that are distributed in a basket of fruit this basket contains \n apples, oranges, and mango fruits. Given the string that represents the total number of \n the oranges and apples and an integer that represent the total number of the fruits \n in the basket return the number of the mango fruits in the basket.\n \n Example:\n fruit_distribution(\"5 apples and 6 oranges\", 19) -> 19 - 5 - 6 = 8\n \"\"\"\n # Use regular expressions to find all sequences of digits in the string\n numbers = re.findall(r'\\d+', s)\n \n # Convert the extracted strings to integers\n fruit_counts = [int(num) for num in numbers]\n \n # Calculate the sum of apples and oranges\n total_apples_and_oranges = sum(fruit_counts)\n \n # The number of mangoes is the total fruits minus (apples + oranges)\n return n - total_apples_and_oranges"}
{"task_id": "HumanEval/68", "solution": "def pluck(arr):\n \"\"\"\n Given an array representing a branch of a tree that has non-negative integer nodes,\n your task is to pluck one of the nodes and return it.\n The plucked node should be the node with the smallest even value.\n If multiple nodes with the same smallest even value are found, return the node \n that has the smallest index.\n\n The plucked node should be returned in a list: [smallest_value, its_index].\n If there are no even values or the given array is empty, return [].\n \"\"\"\n # Initialize variables to track the minimum even value and its corresponding index\n min_val = float('inf')\n min_idx = -1\n\n for idx, val in enumerate(arr):\n # Check if the current node value is even\n if val % 2 == 0:\n # We only update if we find a value strictly smaller than our current minimum.\n # This naturally handles the requirement to return the smallest index \n # because we iterate from left to right and ignore equal values.\n if val < min_val:\n min_val = val\n min_idx = idx\n\n # If min_idx remains -1, it means no even number was found or array was empty\n if min_idx == -1:\n return []\n \n return [min_val, min_idx]"}
{"task_id": "HumanEval/69", "solution": "def search(lst):\n '''\n You are given a non-empty list of positive integers. Return the greatest integer that is greater than \n zero, and has a frequency greater than or equal to the value of the integer itself. \n The frequency of an integer is the number of times it appears in the list.\n If no such a value exist, return -1.\n Examples:\n search([4, 1, 2, 2, 3, 1]) == 2\n search([1, 2, 2, 3, 3, 3, 4, 4, 4]) == 3\n search([5, 5, 4, 4, 4]) == -1\n '''\n # Create a dictionary to store the frequency of each number in the list\n counts = {}\n for num in lst:\n counts[num] = counts.get(num, 0) + 1\n \n max_val = -1\n \n # Iterate through the unique numbers and their frequencies\n for val, freq in counts.items():\n # Check if the frequency is greater than or equal to the value itself\n if freq >= val:\n # We are looking for the greatest such integer\n if val > max_val:\n max_val = val\n \n return max_val"}
{"task_id": "HumanEval/70", "solution": "def strange_sort_list(lst):\n '''\n Given list of integers, return list in strange order.\n Strange sorting, is when you start with the minimum value,\n then maximum of the remaining integers, then minimum and so on.\n\n Examples:\n strange_sort_list([1, 2, 3, 4]) == [1, 4, 2, 3]\n strange_sort_list([5, 5, 5, 5]) == [5, 5, 5, 5]\n strange_sort_list([]) == []\n '''\n # First, sort the list to easily access minimums and maximums\n sorted_lst = sorted(lst)\n result = []\n \n # Use two pointers: one at the start (min) and one at the end (max)\n left = 0\n right = len(sorted_lst) - 1\n \n while left <= right:\n # Append the current minimum\n result.append(sorted_lst[left])\n left += 1\n \n # Check if there are still elements remaining to avoid duplicating the middle element\n if left <= right:\n # Append the current maximum\n result.append(sorted_lst[right])\n right -= 1\n \n return result"}
{"task_id": "HumanEval/71", "solution": "import math\ndef triangle_area(a, b, c):\n '''\n Given the lengths of the three sides of a triangle. Return the area of\n the triangle rounded to 2 decimal points if the three sides form a valid triangle. \n Otherwise return -1\n Three sides make a valid triangle when the sum of any two sides is greater \n than the third side.\n Example:\n triangle_area(3, 4, 5) == 6.00\n triangle_area(1, 2, 10) == -1\n '''\n # Check if the three sides form a valid triangle\n if (a + b > c) and (a + c > b) and (b + c > a):\n # Calculate the semi-perimeter\n s = (a + b + c) / 2\n # Use Heron's formula to calculate the area\n area = math.sqrt(s * (s - a) * (s - b) * (s - c))\n return round(area, 2)\n else:\n # Return -1 if it is not a valid triangle\n return -1"}
{"task_id": "HumanEval/72", "solution": "def will_it_fly(q, w):\n '''\n Write a function that returns True if the object q will fly, and False otherwise.\n The object q will fly if it's balanced (it is a palindromic list) and the sum of its elements is less than or equal the maximum possible weight w.\n\n Example:\n will_it_fly([1, 2], 5) \u279e False \n # 1+2 is less than the maximum possible weight, but it's unbalanced.\n\n will_it_fly([3, 2, 3], 1) \u279e False\n # it's balanced, but 3+2+3 is more than the maximum possible weight.\n\n will_it_fly([3, 2, 3], 9) \u279e True\n # 3+2+3 is less than the maximum possible weight, and it's balanced.\n\n will_it_fly([3], 5) \u279e True\n # 3 is less than the maximum possible weight, and it's balanced.\n '''\n # Check if the list is a palindrome (reads the same forwards and backwards)\n is_balanced = q == q[::-1]\n \n # Check if the sum of elements is less than or equal to the max weight w\n is_light_enough = sum(q) <= w\n \n return is_balanced and is_light_enough"}
{"task_id": "HumanEval/73", "solution": "def smallest_change(arr):\n \"\"\"\n Given an array arr of integers, find the minimum number of elements that\n need to be changed to make the array palindromic. A palindromic array is an array that\n is read the same backwards and forwards. In one change, you can change one element to any other element.\n\n For example:\n smallest_change([1,2,3,5,4,7,9,6]) == 4\n smallest_change([1, 2, 3, 4, 3, 2, 2]) == 1\n smallest_change([1, 2, 3, 2, 1]) == 0\n \"\"\"\n n = len(arr)\n changes = 0\n \n # We only need to iterate through the first half of the array.\n # For each element at index i, its corresponding mirror element is at index n - 1 - i.\n for i in range(n // 2):\n if arr[i] != arr[n - 1 - i]:\n changes += 1\n \n return changes"}
{"task_id": "HumanEval/74", "solution": "def total_match(lst1, lst2):\n '''\n Write a function that accepts two lists of strings and returns the list that has \n total number of chars in the all strings of the list less than the other list.\n\n if the two lists have the same number of chars, return the first list.\n\n Examples\n total_match([], []) \u279e []\n total_match(['hi', 'admin'], ['hI', 'Hi']) \u279e ['hI', 'Hi']\n total_match(['hi', 'admin'], ['hi', 'hi', 'admin', 'project']) \u279e ['hi', 'admin']\n total_match(['hi', 'admin'], ['hI', 'hi', 'hi']) \u279e ['hI', 'hi', 'hi']\n total_match(['4'], ['1', '2', '3', '4', '5']) \u279e ['4']\n '''\n # Calculate the total number of characters in the first list\n sum1 = sum(len(s) for s in lst1)\n # Calculate the total number of characters in the second list\n sum2 = sum(len(s) for s in lst2)\n \n # Return the second list only if its total length is strictly less than the first.\n # Otherwise (if lst1 is shorter or they are equal), return the first list.\n if sum2 < sum1:\n return lst2\n else:\n return lst1"}
{"task_id": "HumanEval/75", "solution": "def is_multiply_prime(a):\n \"\"\"\n Returns True if the given number 'a' is the product of exactly 3 prime numbers,\n and False otherwise.\n \n Example:\n is_multiply_prime(30) == True # 2 * 3 * 5\n is_multiply_prime(8) == True # 2 * 2 * 2\n is_multiply_prime(12) == True # 2 * 2 * 3\n is_multiply_prime(7) == False # Only 1 prime factor\n \"\"\"\n if a < 2:\n return False\n \n count = 0\n temp = a\n d = 2\n \n # Perform prime factorization\n while d * d <= temp:\n while temp % d == 0:\n count += 1\n temp //= d\n d += 1\n \n # If there is a remaining factor greater than 1, it must be prime\n if temp > 1:\n count += 1\n \n # Return True if the total number of prime factors (with multiplicity) is exactly 3\n return count == 3"}
{"task_id": "HumanEval/76", "solution": "def is_simple_power(x, n):\n \"\"\"Your task is to write a function that returns true if a number x is a simple\n power of n and false in other cases.\n x is a simple power of n if n**int=x\n For example:\n is_simple_power(1, 4) => true\n is_simple_power(2, 2) => true\n is_simple_power(8, 2) => true\n is_simple_power(3, 2) => false\n is_simple_power(3, 1) => false\n is_simple_power(5, 3) => false\n \"\"\"\n # Any number n raised to the power of 0 is 1 (n**0 = 1).\n if x == 1:\n return True\n \n # If n is 1, it can only result in 1 (handled above).\n # If n is 0, it can result in 0 (for int > 0) or 1 (for int = 0).\n if n <= 1:\n if n == 0 and x == 0:\n return True\n return False\n\n # For n > 1, we repeatedly divide x by n as long as it is divisible.\n # If we eventually reach 1, then x was a power of n.\n while x > 1 and x % n == 0:\n x //= n\n \n return x == 1"}
{"task_id": "HumanEval/77", "solution": "def iscube(a):\n '''\n Write a function that takes an integer a and returns True \n if this integer is a cube of some integer number.\n Note: you may assume the input is always valid.\n Examples:\n iscube(1) ==> True\n iscube(2) ==> False\n iscube(-1) ==> True\n iscube(64) ==> True\n iscube(0) ==> True\n iscube(180) ==> False\n '''\n # We take the absolute value of 'a' because Python's power operator (**) \n # with a fractional exponent on a negative number returns a complex number.\n # Since (-n)^3 = -(n^3), we only need to check if the magnitude is a perfect cube.\n root = round(abs(a)**(1/3))\n return root**3 == abs(a)"}
{"task_id": "HumanEval/78", "solution": "def hex_key(num):\n \"\"\"You have been tasked to write a function that receives \n a hexadecimal number as a string and counts the number of hexadecimal \n digits that are primes (prime number, or a prime, is a natural number \n greater than 1 that is not a product of two smaller natural numbers).\n Hexadecimal digits are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F.\n Prime numbers are 2, 3, 5, 7, 11, 13, 17,...\n So you have to determine a number of the following digits: 2, 3, 5, 7, \n B (=decimal 11), D (=decimal 13).\n Note: you may assume the input is always correct or empty string, \n and symbols A,B,C,D,E,F are always uppercase.\n Examples:\n For num = \"AB\" the output should be 1.\n For num = \"1077E\" the output should be 2.\n For num = \"ABED1A33\" the output should be 4.\n For num = \"123456789ABCDEF0\" the output should be 6.\n For num = \"2020\" the output should be 2.\n \"\"\"\n # Define the set of hexadecimal digits that correspond to prime numbers:\n # 2 -> 2 (prime)\n # 3 -> 3 (prime)\n # 5 -> 5 (prime)\n # 7 -> 7 (prime)\n # B -> 11 (prime)\n # D -> 13 (prime)\n primes = {'2', '3', '5', '7', 'B', 'D'}\n \n count = 0\n for char in num:\n if char in primes:\n count += 1\n \n return count"}
{"task_id": "HumanEval/79", "solution": "def decimal_to_binary(decimal):\n \"\"\"You will be given a number in decimal form and your task is to convert it to\n binary format. The function should return a string, with each character representing a binary\n number. Each character in the string will be '0' or '1'.\n\n There will be an extra couple of characters 'db' at the beginning and at the end of the string.\n The extra characters are there to help with the format.\n\n Examples:\n decimal_to_binary(15) # returns \"db1111db\"\n decimal_to_binary(32) # returns \"db100000db\"\n \"\"\"\n # bin() converts an integer to a binary string prefixed with '0b'\n # We slice from index 2 onwards to remove the '0b' prefix\n binary_string = bin(decimal)[2:]\n \n # Wrap the result in 'db' at the start and end\n return f\"db{binary_string}db\""}
{"task_id": "HumanEval/80", "solution": "def is_happy(s):\n \"\"\"You are given a string s.\n Your task is to check if the string is happy or not.\n A string is happy if its length is at least 3 and every 3 consecutive letters are distinct\n For example:\n is_happy(\"a\") => False\n is_happy(\"aa\") => False\n is_happy(\"abcd\") => True\n is_happy(\"aabb\") => False\n is_happy(\"adb\") => True\n is_happy(\"xyy\") => False\n \"\"\"\n # A string is happy if its length is at least 3\n if len(s) < 3:\n return False\n \n # Check every sequence of 3 consecutive letters\n for i in range(len(s) - 2):\n # Extract the triplet starting at index i\n triplet = s[i : i + 3]\n # A set removes duplicates; if length is not 3, characters were not distinct\n if len(set(triplet)) != 3:\n return False\n \n return True"}
{"task_id": "HumanEval/81", "solution": "def numerical_letter_grade(grades):\n \"\"\"It is the last week of the semester and the teacher has to give the grades\n to students. The teacher has been making her own algorithm for grading.\n The only problem is, she has lost the code she used for grading.\n She has given you a list of GPAs for some students and you have to write \n a function that can output a list of letter grades using the following table:\n GPA | Letter grade\n 4.0 A+\n > 3.7 A \n > 3.3 A- \n > 3.0 B+\n > 2.7 B \n > 2.3 B-\n > 2.0 C+\n > 1.7 C\n > 1.3 C-\n > 1.0 D+ \n > 0.7 D \n > 0.0 D-\n 0.0 E\n\n Example:\n numerical_letter_grade([4.0, 3, 1.7, 2, 3.5]) ==> ['A+', 'B', 'C-', 'C', 'A-']\n \"\"\"\n letter_grades = []\n for gpa in grades:\n if gpa == 4.0:\n letter_grades.append('A+')\n elif gpa > 3.7:\n letter_grades.append('A')\n elif gpa > 3.3:\n letter_grades.append('A-')\n elif gpa > 3.0:\n letter_grades.append('B+')\n elif gpa > 2.7:\n letter_grades.append('B')\n elif gpa > 2.3:\n letter_grades.append('B-')\n elif gpa > 2.0:\n letter_grades.append('C+')\n elif gpa > 1.7:\n letter_grades.append('C')\n elif gpa > 1.3:\n letter_grades.append('C-')\n elif gpa > 1.0:\n letter_grades.append('D+')\n elif gpa > 0.7:\n letter_grades.append('D')\n elif gpa > 0.0:\n letter_grades.append('D-')\n else:\n letter_grades.append('E')\n return letter_grades"}
{"task_id": "HumanEval/82", "solution": "def prime_length(string):\n \"\"\"Write a function that takes a string and returns True if the string\n length is a prime number or False otherwise\n Examples\n prime_length('Hello') == True\n prime_length('abcdcba') == True\n prime_length('kittens') == True\n prime_length('orange') == False\n \"\"\"\n n = len(string)\n \n # Prime numbers must be greater than 1\n if n < 2:\n return False\n \n # Check for factors from 2 up to the square root of n\n for i in range(2, int(n**0.5) + 1):\n if n % i == 0:\n return False\n \n return True"}
{"task_id": "HumanEval/83", "solution": "def starts_one_ends(n):\n \"\"\"\n Given a positive integer n, return the count of the numbers of n-digit\n positive integers that start or end with 1.\n \"\"\"\n # Case for single digit numbers: only the number '1' satisfies the condition.\n if n == 1:\n return 1\n \n # For n > 1, we use the Principle of Inclusion-Exclusion:\n # Total = |Starts with 1| + |Ends with 1| - |Starts and Ends with 1|\n \n # 1. Numbers that start with 1:\n # The first digit is fixed as '1'. The remaining (n-1) digits can be any of 0-9.\n # Count = 1 * 10**(n-1)\n starts_with_one = 10**(n - 1)\n \n # 2. Numbers that end with 1:\n # The last digit is fixed as '1'. \n # The first digit can be any of 1-9 (cannot be 0).\n # The middle (n-2) digits can be any of 0-9.\n # Count = 9 * 10**(n-2) * 1\n ends_with_one = 9 * 10**(n - 2)\n \n # 3. Numbers that both start and end with 1:\n # The first digit is fixed as '1'.\n # The last digit is fixed as '1'.\n # The middle (n-2) digits can be any of 0-9.\n # Count = 1 * 10**(n-2) * 1\n both_start_end_one = 10**(n - 2)\n \n return starts_with_one + ends_with_one - both_start_end_one"}
{"task_id": "HumanEval/84", "solution": "def solve(N):\n \"\"\"Given a positive integer N, return the total sum of its digits in binary.\n \n Example\n For N = 1000, the sum of digits will be 1 the output should be \"1\".\n For N = 150, the sum of digits will be 6 the output should be \"110\".\n For N = 147, the sum of digits will be 12 the output should be \"1100\".\n \n Variables:\n @N integer\n Constraints: 0 \u2264 N \u2264 10000.\n Output:\n a string of binary number\n \"\"\"\n # Step 1: Calculate the sum of digits of N in base 10\n # We convert N to a string, iterate through each character, \n # convert it back to an integer and sum them up.\n digit_sum = sum(int(digit) for digit in str(N))\n \n # Step 2: Convert the resulting sum into its binary representation\n # bin() returns a string starting with '0b', so we slice from index 2 onwards.\n binary_representation = bin(digit_sum)[2:]\n \n return binary_representation"}
{"task_id": "HumanEval/85", "solution": "def add(lst):\n \"\"\"Given a non-empty list of integers lst, add the even elements that are at odd indices.\n\n Examples:\n add([4, 2, 6, 7]) ==> 2 \n \"\"\"\n # We iterate through the list starting from index 1 (the first odd index),\n # stepping by 2 to only visit odd indices.\n total = 0\n for i in range(1, len(lst), 2):\n if lst[i] % 2 == 0:\n total += lst[i]\n return total"}
{"task_id": "HumanEval/86", "solution": "def anti_shuffle(s):\n \"\"\"\n Write a function that takes a string and returns an ordered version of it.\n Ordered version of string, is a string where all words (separated by space)\n are replaced by a new word where all the characters arranged in\n ascending order based on ascii value.\n Note: You should keep the order of words and blank spaces in the sentence.\n\n For example:\n anti_shuffle('Hi') returns 'Hi'\n anti_shuffle('hello') returns 'ehllo'\n anti_shuffle('Hello World!!!') returns 'Hello !!!Wdlor'\n \"\"\"\n # Split the string by a single space to preserve multiple spaces if they exist.\n words = s.split(' ')\n \n sorted_words = []\n for word in words:\n # sorted() takes an iterable and returns a list of elements \n # sorted in ascending order based on their ASCII values.\n sorted_chars = sorted(word)\n # Join the sorted characters back into a single string.\n sorted_words.append(\"\".join(sorted_chars))\n \n # Join the processed words back together using a single space as the separator.\n return \" \".join(sorted_words)"}
{"task_id": "HumanEval/87", "solution": "def get_row(lst, x):\n \"\"\"\n You are given a 2 dimensional data, as a nested lists,\n which is similar to matrix, however, unlike matrices,\n each row may contain a different number of columns.\n Given lst, and integer x, find integers x in the list,\n and return list of tuples, [(x1, y1), (x2, y2) ...] such that\n each tuple is a coordinate - (row, columns), starting with 0.\n Sort coordinates initially by rows in ascending order.\n Also, sort coordinates of the row by columns in descending order.\n \"\"\"\n result = []\n \n # Iterate through each row and its index\n for r_idx, row in enumerate(lst):\n # Find all column indices where the value equals x\n cols = [c_idx for c_idx, val in enumerate(row) if val == x]\n \n # Sort the column indices for this specific row in descending order\n cols.sort(reverse=True)\n \n # Append the coordinates as tuples to the result list\n for c_idx in cols:\n result.append((r_idx, c_idx))\n \n return result"}
{"task_id": "HumanEval/88", "solution": "def sort_array(array):\n \"\"\"\n Given an array of non-negative integers, return a copy of the given array after sorting,\n you will sort the given array in ascending order if the sum( first index value, last index value) is odd,\n or sort it in descending order if the sum( first index value, last index value) is even.\n\n Note:\n * don't change the given array.\n\n Examples:\n * sort_array([]) => []\n * sort_array([5]) => [5]\n * sort_array([2, 4, 3, 0, 1, 5]) => [0, 1, 2, 3, 4, 5]\n * sort_array([2, 4, 3, 0, 1, 5, 6]) => [6, 5, 4, 3, 2, 1, 0]\n \"\"\"\n # Handle empty array case\n if not array:\n return []\n\n # Calculate the sum of the first and last elements\n first_val = array[0]\n last_val = array[-1]\n total_sum = first_val + last_val\n\n # Determine sorting order based on parity of the sum\n if total_sum % 2 != 0:\n # Sum is odd: sort in ascending order\n return sorted(array)\n else:\n # Sum is even: sort in descending order\n return sorted(array, reverse=True)"}
{"task_id": "HumanEval/89", "solution": "def encrypt(s):\n \"\"\"Create a function encrypt that takes a string as an argument and\n returns a string encrypted with the alphabet being rotated. \n The alphabet should be rotated in a manner such that the letters \n shift down by two multiplied to two places (2 * 2 = 4).\n \n For example:\n encrypt('hi') returns 'lm'\n encrypt('asdfghjkl') returns 'ewhjklnop'\n encrypt('gf') returns 'kj'\n encrypt('et') returns 'ix'\n \"\"\"\n # The shift is defined as \"two multiplied to two places\", which equals 4.\n shift = 4\n result = []\n\n for char in s:\n if 'a' <= char <= 'z':\n # Calculate the new character for lowercase letters\n # ord('a') provides the ASCII value of 'a' (97)\n shifted_char = chr((ord(char) - ord('a') + shift) % 26 + ord('a'))\n result.append(shifted_char)\n elif 'A' <= char <= 'Z':\n # Calculate the new character for uppercase letters\n # ord('A') provides the ASCII value of 'A' (65)\n shifted_char = chr((ord(char) - ord('A') + shift) % 26 + ord('A'))\n result.append(shifted_char)\n else:\n # If the character is not a letter, keep it as is\n result.append(char)\n\n return \"\".join(result)"}
{"task_id": "HumanEval/90", "solution": "def next_smallest(lst):\n \"\"\"\n You are given a list of integers.\n Write a function next_smallest() that returns the 2nd smallest element of the list.\n Return None if there is no such element.\n \n next_smallest([1, 2, 3, 4, 5]) == 2\n next_smallest([5, 1, 4, 3, 2]) == 2\n next_smallest([]) == None\n next_smallest([1, 1]) == None\n \"\"\"\n # Remove duplicates by converting the list to a set\n unique_elements = set(lst)\n \n # Sort the unique elements in ascending order\n sorted_elements = sorted(list(unique_elements))\n \n # If there are fewer than 2 unique elements, return None\n if len(sorted_elements) < 2:\n return None\n \n # Return the second element in the sorted list\n return sorted_elements[1]"}
{"task_id": "HumanEval/91", "solution": "import re\ndef is_bored(S):\n \"\"\"\n You'll be given a string of words, and your task is to count the number\n of boredoms. A boredom is a sentence that starts with the word \"I\".\n Sentences are delimited by '.', '?' or '!'.\n \n For example:\n >>> is_bored(\"Hello world\")\n 0\n >>> is_bored(\"The sky is blue. The sun is shining. I love this weather\")\n 1\n \"\"\"\n # Use regular expressions to split the string by any of the delimiters '.', '?', or '!'\n sentences = re.split(r'[.?!]', S)\n \n count = 0\n for sentence in sentences:\n # Remove leading and trailing whitespace from the sentence\n sentence = sentence.strip()\n \n # Skip empty strings resulting from consecutive delimiters or trailing punctuation\n if not sentence:\n continue\n \n # Split the sentence into words to isolate the first word\n words = sentence.split()\n \n # Check if the list of words is not empty and the first word is exactly \"I\"\n if words and words[0] == \"I\":\n count += 1\n \n return count"}
{"task_id": "HumanEval/92", "solution": "def any_int(x, y, z):\n '''\n Create a function that takes 3 numbers.\n Returns true if one of the numbers is equal to the sum of the other two, and all numbers are integers.\n Returns false in any other cases.\n \n Examples:\n any_int(5, 2, 7) \u279e True\n any_int(3, 2, 2) \u279e False\n any_int(3, -2, 1) \u279e True\n any_int(3.6, -2.2, 2) \u279e False\n '''\n # First, check if all three inputs are of type int\n if not (isinstance(x, int) and isinstance(y, int) and isinstance(z, int)):\n return False\n \n # Check if any one number is the sum of the other two\n return (x + y == z) or (x + z == y) or (y + z == x)"}
{"task_id": "HumanEval/93", "solution": "def encode(message):\n \"\"\"\n Write a function that takes a message, and encodes in such a \n way that it swaps case of all letters, replaces all vowels in \n the message with the letter that appears 2 places ahead of that \n vowel in the english alphabet. \n Assume only letters. \n \n Examples:\n >>> encode('test')\n 'TGST'\n >>> encode('This is a message')\n 'tHKS KS C MGSSCGG'\n \"\"\"\n vowels = \"aeiouAEIOU\"\n result = []\n \n for char in message:\n # First, swap the case of the character\n swapped_char = char.swapcase()\n \n # If the original character was a vowel, shift the swapped version 2 places ahead\n if char in vowels:\n # ord() gets ASCII value, chr() converts it back to a character\n encoded_char = chr(ord(swapped_char) + 2)\n result.append(encoded_char)\n else:\n # If not a vowel, just use the swapped case version\n result.append(swapped_char)\n \n return \"\".join(result)"}
{"task_id": "HumanEval/94", "solution": "def skjkasdkd(lst):\n \"\"\"You are given a list of integers.\n You need to find the largest prime value and return the sum of its digits.\n\n Examples:\n For lst = [0,3,2,1,3,5,7,4,5,5,5,2,181,32,4,32,3,2,32,324,4,3] the output should be 10\n For lst = [1,0,1,8,2,4597,2,1,3,40,1,2,1,2,4,2,5,1] the output should be 25\n For lst = [1,3,1,32,5107,34,83278,109,163,23,2323,32,30,1,9,3] the output should be 13\n For lst = [0,724,32,71,99,32,6,0,5,91,83,0,5,6] the output should be 11\n For lst = [0,81,12,3,1,21] the output should be 3\n For lst = [0,8,1,2,1,7] the output should be 7\n \"\"\"\n\n def is_prime(n):\n \"\"\"Helper function to check if a number is prime.\"\"\"\n if n < 2:\n return False\n if n == 2:\n return True\n if n % 2 == 0:\n return False\n # Check odd divisors up to the square root of n\n for i in range(3, int(n**0.5) + 1, 2):\n if n % i == 0:\n return False\n return True\n\n max_prime = -1\n \n # Iterate through the list to find the largest prime number\n for num in lst:\n if is_prime(num):\n if num > max_prime:\n max_prime = num\n \n # If no prime was found, return 0 or a suitable default value\n if max_prime == -1:\n return 0\n \n # Calculate the sum of digits of the largest prime number\n digit_sum = sum(int(digit) for digit in str(max_prime))\n \n return digit_sum"}
{"task_id": "HumanEval/95", "solution": "def check_dict_case(dictionary):\n \"\"\"\n Given a dictionary, return True if all keys are strings in lower \n case or all keys are strings in upper case, else return False.\n The function should return False is the given dictionary is empty.\n Examples:\n check_dict_case({\"a\":\"apple\", \"b\":\"banana\"}) should return True.\n check_dict_case({\"a\":\"apple\", \"A\":\"banana\", \"B\":\"banana\"}) should return False.\n check_dict_case({\"a\":\"apple\", 8:\"banana\", \"a\":\"apple\"}) should return False.\n check_dict_case({\"Name\":\"John\", \"Age\":\"36\", \"City\":\"Houston\"}) should return False.\n check_dict_case({\"STATE\":\"NC\", \"ZIP\":\"12345\" }) should return True.\n \"\"\"\n # Return False if the dictionary is empty\n if not dictionary:\n return False\n\n keys = list(dictionary.keys())\n\n # Check if all keys are strings; if any key is not a string, return False\n for key in keys:\n if not isinstance(key, str):\n return False\n\n # A key is considered \"lowercase\" if it equals its own lowercase version\n # and \"uppercase\" if it equals its own uppercase version.\n # We check if every single key satisfies the lower condition OR \n # every single key satisfies the upper condition.\n all_lower = all(key == key.lower() for key in keys)\n all_upper = all(key == key.upper() for key in keys)\n\n return all_lower or all_upper"}
{"task_id": "HumanEval/96", "solution": "def count_up_to(n):\n \"\"\"Implement a function that takes an non-negative integer and returns an array of the first n\n integers that are prime numbers and less than n.\n for example:\n count_up_to(5) => [2,3]\n count_up_to(11) => [2,3,5,7]\n count_up_to(0) => []\n count_up_to(20) => [2,3,5,7,11,13,17,19]\n count_up_to(1) => []\n count_up_to(18) => [2,3,5,7,11,13,17]\n \"\"\"\n def is_prime(num):\n if num < 2:\n return False\n for i in range(2, int(num**0.5) + 1):\n if num % i == 0:\n return False\n return True\n\n primes = []\n # We iterate from 2 up to (but not including) n\n for i in range(2, n):\n if is_prime(i):\n primes.append(i)\n return primes"}
{"task_id": "HumanEval/97", "solution": "def multiply(a, b):\n \"\"\"Complete the function that takes two integers and returns \n the product of their unit digits.\n Assume the input is always valid.\n Examples:\n multiply(148, 412) should return 16.\n multiply(19, 28) should return 72.\n multiply(2020, 1851) should return 0.\n multiply(14,-15) should return 20.\n \"\"\"\n # The unit digit is the last digit of a number.\n # We use abs() to ensure that negative numbers are treated by their absolute value,\n # as the \"unit digit\" of -15 is typically considered to be 5.\n digit_a = abs(a) % 10\n digit_b = abs(b) % 10\n return digit_a * digit_b"}
{"task_id": "HumanEval/98", "solution": "def count_upper(s):\n \"\"\"\n Given a string s, count the number of uppercase vowels in even indices.\n \n For example:\n count_upper('aBCdEf') returns 1\n count_upper('abcdefg') returns 0\n count_upper('dBBE') returns 0\n \"\"\"\n # Define the set of uppercase vowels\n vowels = {'A', 'E', 'I', 'O', 'U'}\n count = 0\n \n # Iterate through the string using a step of 2 to only visit even indices (0, 2, 4...)\n for i in range(0, len(s), 2):\n if s[i] in vowels:\n count += 1\n \n return count"}
{"task_id": "HumanEval/99", "solution": "import math\ndef closest_integer(value):\n '''\n Create a function that takes a value (string) representing a number\n and returns the closest integer to it. If the number is equidistant\n from two integers, round it away from zero.\n\n Examples\n >>> closest_integer(\"10\")\n 10\n >>> closest_integer(\"15.3\")\n 15\n >>> closest_integer(\"14.5\")\n 15\n >>> closest_integer(\"-14.5\")\n -15\n '''\n # Convert the input string to a float for calculation\n num = float(value)\n \n if num >= 0:\n # For positive numbers, adding 0.5 and flooring handles \"round half up\"\n # e.g., 14.4 + 0.5 = 14.9 -> floor is 14\n # e.g., 14.5 + 0.5 = 15.0 -> floor is 15\n return int(math.floor(num + 0.5))\n else:\n # For negative numbers, subtracting 0.5 and ceiling handles \"round half down\" (away from zero)\n # e.g., -14.4 - 0.5 = -14.9 -> ceil is -14\n # e.g., -14.5 - 0.5 = -15.0 -> ceil is -15\n return int(math.ceil(num - 0.5))"}
{"task_id": "HumanEval/100", "solution": "def make_a_pile(n):\n \"\"\"\n Given a positive integer n, you have to make a pile of n levels of stones.\n The first level has n stones.\n The number of stones in the next level is:\n - the next odd number if n is odd.\n - the next even number if n is even.\n Return the number of stones in each level in a list, where element at index\n i represents the number of stones in the level (i+1).\n\n Examples:\n >>> make_a_pile(3)\n [3, 5, 7]\n \"\"\"\n # The problem describes an arithmetic progression starting at n with a common difference of 2.\n # Since we need n levels, the sequence will be [n, n+2, n+4, ..., n + 2*(n-1)].\n return [n + 2 * i for i in range(n)]"}
{"task_id": "HumanEval/101", "solution": "def words_string(s):\n \"\"\"\n You will be given a string of words separated by commas or spaces. Your task is\n to split the string into words and return an array of the words.\n \n For example:\n words_string(\"Hi, my name is John\") == [\"Hi\", \"my\", \"name\", \"is\", \"John\"]\n words_string(\"One, two, three, four, five, six\") == [\"One\", \"two\", \"three\", \"four\", \"five\", \"six\"]\n \"\"\"\n # Replace all commas with spaces so that the string only contains space-separated words.\n # Then use .split() without arguments, which splits by any whitespace \n # and automatically discards empty strings resulting from multiple separators.\n return s.replace(',', ' ').split()"}
{"task_id": "HumanEval/102", "solution": "def choose_num(x, y):\n \"\"\"This function takes two positive numbers x and y and returns the\n biggest even integer number that is in the range [x, y] inclusive. If \n there's no such number, then the function should return -1.\n\n For example:\n choose_num(12, 15) = 14\n choose_num(13, 12) = -1\n \"\"\"\n # If x is greater than y, the range [x, y] is empty\n if x > y:\n return -1\n \n # Start checking from the upper bound y downwards\n # If y is even, it's the biggest even number in the range\n if y % 2 == 0:\n return y\n \n # If y is odd, check if the number immediately below it (y-1) \n # is within the lower bound x. Since y is odd, y-1 must be even.\n if y - 1 >= x:\n return y - 1\n \n # If neither y nor y-1 are valid even numbers in [x, y], return -1\n return -1"}
{"task_id": "HumanEval/103", "solution": "def rounded_avg(n, m):\n \"\"\"You are given two positive integers n and m, and your task is to compute the\n average of the integers from n through m (including n and m). \n Round the answer to the nearest integer and convert that to binary.\n If n is greater than m, return -1.\n Example:\n rounded_avg(1, 5) => \"0b11\"\n rounded_avg(7, 5) => -1\n rounded_avg(10, 20) => \"0b1111\"\n rounded_avg(20, 33) => \"0b11010\"\n \"\"\"\n # If n is greater than m, return -1 as per requirements.\n if n > m:\n return -1\n \n # The average of a sequence of consecutive integers from n to m is (n + m) / 2.\n # This is derived from the sum formula: Sum = ((m - n + 1) * (n + m)) / 2\n # Average = Sum / count = (((m - n + 1) * (n + m)) / 2) / (m - n + 1) = (n + m) / 2.\n avg = (n + m) / 2\n \n # Round the average to the nearest integer.\n # Python's round() function rounds half to even, which matches the example:\n # rounded_avg(20, 33) -> avg is 26.5 -> round(26.5) is 26 -> bin(26) is '0b11010'.\n rounded_val = round(avg)\n \n # Convert the integer to its binary representation string.\n return bin(rounded_val)"}
{"task_id": "HumanEval/104", "solution": "def unique_digits(x):\n \"\"\"Given a list of positive integers x, return a sorted list of all \n elements that haven't any even digit.\n\n Note: Returned list should be sorted in increasing order.\n \n For example:\n >>> unique_digits([15, 33, 1422, 1])\n [1, 15, 33]\n >>> unique_digits([152, 323, 1422, 10])\n []\n \"\"\"\n result = []\n for num in x:\n # Convert the number to a string to iterate through each digit\n s_num = str(num)\n # Check if all digits in the string are odd\n # A digit is odd if int(digit) % 2 != 0\n if all(int(digit) % 2 != 0 for digit in s_num):\n result.append(num)\n \n # Return the filtered list sorted in increasing order\n return sorted(result)"}
{"task_id": "HumanEval/105", "solution": "def by_length(arr):\n \"\"\"\n Given an array of integers, sort the integers that are between 1 and 9 inclusive,\n reverse the resulting array, and then replace each digit by its corresponding name from\n \"One\", \"Two\", \"Three\", \"Four\", \"Five\", \"Six\", \"Seven\", \"Eight\", \"Nine\".\n\n For example:\n arr = [2, 1, 1, 4, 5, 8, 2, 3] \n -> sort arr -> [1, 1, 2, 2, 3, 4, 5, 8] \n -> reverse arr -> [8, 5, 4, 3, 2, 2, 1, 1]\n return [\"Eight\", \"Five\", \"Four\", \"Three\", \"Two\", \"Two\", \"One\", \"One\"]\n \n If the array is empty, return an empty array:\n arr = []\n return []\n \n If the array has any strange number ignore it:\n arr = [1, -1 , 55] \n -> sort arr -> [-1, 1, 55]\n -> reverse arr -> [55, 1, -1]\n return = ['One']\n \"\"\"\n # Mapping of integers to their corresponding names\n digit_map = {\n 1: \"One\",\n 2: \"Two\",\n 3: \"Three\",\n 4: \"Four\",\n 5: \"Five\",\n 6: \"Six\",\n 7: \"Seven\",\n 8: \"Eight\",\n 9: \"Nine\"\n }\n\n # 1. Filter the array to keep only integers between 1 and 9 inclusive\n filtered_arr = [x for x in arr if 1 <= x <= 9]\n\n # 2. Sort the filtered integers (ascending)\n filtered_arr.sort()\n\n # 3. Reverse the resulting array (descending)\n filtered_arr.reverse()\n\n # 4. Replace each digit by its corresponding name from the map\n result = [digit_map[x] for x in filtered_arr]\n\n return result"}
{"task_id": "HumanEval/106", "solution": "import math\ndef f(n):\n \"\"\" Implement the function f that takes n as a parameter,\n and returns a list of size n, such that the value of the element at index i is the factorial of i if i is even\n or the sum of numbers from 1 to i otherwise.\n i starts from 1.\n the factorial of i is the multiplication of the numbers from 1 to i (1 * 2 * ... * i).\n Example:\n f(5) == [1, 2, 6, 24, 15]\n \"\"\"\n result = []\n # The problem states i starts from 1 and the list size is n.\n for i in range(1, n + 1):\n if i % 2 == 0:\n # If i is even, calculate factorial of i\n result.append(math.factorial(i))\n else:\n # If i is odd, calculate the sum from 1 to i\n # Formula for sum of first n integers: (n * (n + 1)) // 2\n result.append((i * (i + 1)) // 2)\n return result"}
{"task_id": "HumanEval/107", "solution": "def even_odd_palindrome(n):\n \"\"\"\n Given a positive integer n, return a tuple that has the number of even and odd\n integer palindromes that fall within the range(1, n), inclusive.\n\n Example 1:\n Input: 3\n Output: (1, 2)\n Explanation:\n Integer palindrome are 1, 2, 3. one of them is even, and two of them are odd.\n\n Example 2:\n Input: 12\n Output: (4, 6)\n Explanation:\n Integer palindrome are 1, 2, 3, 4, 5, 6, 7, 8, 9, 11. four of them are even, and 6 of them are odd.\n\n Note:\n 1. 1 <= n <= 10^3\n 2. returned tuple has the number of even and odd integer palindromes respectively.\n \"\"\"\n even_count = 0\n odd_count = 0\n \n # Iterate through all numbers from 1 to n inclusive\n for i in range(1, n + 1):\n # Convert the number to a string to check if it's a palindrome\n s = str(i)\n if s == s[::-1]:\n # If it is a palindrome, check if the integer is even or odd\n if i % 2 == 0:\n even_count += 1\n else:\n odd_count += 1\n \n return (even_count, odd_count)"}
{"task_id": "HumanEval/108", "solution": "def count_nums(arr):\n \"\"\"\n Write a function count_nums which takes an array of integers and returns\n the number of elements which has a sum of digits > 0.\n If a number is negative, then its first signed digit will be negative:\n e.g. -123 has signed digits -1, 2, and 3.\n >>> count_nums([]) == 0\n >>> count_nums([-1, 11, -11]) == 1\n >>> count_nums([1, 1, 2]) == 3\n \"\"\"\n count = 0\n for num in arr:\n # Convert the absolute value of the number to a string to iterate through digits\n s = str(abs(num))\n digits = [int(d) for d in s]\n \n # If the original number was negative, the first digit is treated as negative\n if num < 0:\n digits[0] = -digits[0]\n \n # Calculate the sum of these signed digits\n if sum(digits) > 0:\n count += 1\n \n return count"}
{"task_id": "HumanEval/109", "solution": "def move_one_ball(arr):\n \"\"\"We have an array 'arr' of N integers arr[1], arr[2], ..., arr[N].The\n numbers in the array will be randomly ordered. Your task is to determine if\n it is possible to get an array sorted in non-decreasing order by performing \n the following operation on the given array:\n You are allowed to perform right shift operation any number of times.\n \n One right shift operation means shifting all elements of the array by one\n position in the right direction. The last element of the array will be moved to\n the starting position in the array i.e. 0th index. \n\n If it is possible to obtain the sorted array by performing the above operation\n then return True else return False.\n If the given array is empty then return True.\n\n Note: The given list is guaranteed to have unique elements.\n\n For Example:\n \n move_one_ball([3, 4, 5, 1, 2])==>True\n Explanation: By performin 2 right shift operations, non-decreasing order can\n be achieved for the given array.\n move_one_ball([3, 5, 4, 1, 2])==>False\n Explanation:It is not possible to get non-decreasing order for the given\n array by performing any number of right shift operations.\n \n \"\"\"\n # If the array is empty, return True as per problem description.\n if not arr:\n return True\n \n n = len(arr)\n # A sequence can be rotated to become sorted if and only if there is at most \n # one point in the cyclic order where an element is greater than the next one.\n # For unique elements, a perfectly sorted array will have exactly one such drop \n # when considering the wrap-around from the last element back to the first.\n \n drops = 0\n for i in range(n):\n # Compare current element with the next element (using modulo for cyclic check)\n if arr[i] > arr[(i + 1) % n]:\n drops += 1\n \n # If there is more than one drop, it's impossible to sort by rotation.\n # If there is 0 or 1 drop, it can be sorted (or is already sorted).\n return drops <= 1"}
{"task_id": "HumanEval/110", "solution": "def exchange(lst1, lst2):\n \"\"\"In this problem, you will implement a function that takes two lists of numbers,\n and determines whether it is possible to perform an exchange of elements\n between them to make lst1 a list of only even numbers.\n There is no limit on the number of exchanged elements between lst1 and lst2.\n If it is possible to exchange elements between the lst1 and lst2 to make\n all the elements of lst1 to be even, return \"YES\".\n Otherwise, return \"NO\".\n For example:\n exchange([1, 2, 3, 4], [1, 2, 3, 4]) => \"YES\"\n exchange([1, 2, 3, 4], [1, 5, 3, 4]) => \"NO\"\n It is assumed that the input lists will be non-empty.\n \"\"\"\n # Count how many odd numbers are currently in lst1.\n # These are the elements that MUST be replaced to make lst1 all even.\n odds_in_lst1 = len([x for x in lst1 if x % 2 != 0])\n \n # Count how many even numbers are available in lst2.\n # These are the only candidates that can replace odd numbers in lst1 to maintain/achieve parity.\n evens_in_lst2 = len([x for x in lst2 if x % 2 == 0])\n \n # If we have at least as many even numbers in lst2 as there are odd numbers in lst1,\n # we can swap every odd number in lst1 with an even number from lst2.\n if evens_in_lst2 >= odds_in_lst1:\n return \"YES\"\n else:\n return \"NO\""}
{"task_id": "HumanEval/111", "solution": "def histogram(test):\n \"\"\"Given a string representing a space separated lowercase letters, return a dictionary\n of the letter with the most repetition and containing the corresponding count.\n If several letters have the same occurrence, return all of them.\n \n Example:\n histogram('a b c') == {'a': 1, 'b': 1, 'c': 1}\n histogram('a b b a') == {'a': 2, 'b': 2}\n histogram('a b c a b') == {'a': 2, 'b': 2}\n histogram('b b b b a') == {'b': 4}\n histogram('') == {}\n \"\"\"\n # Handle the empty string case immediately\n if not test.strip():\n return {}\n\n # Split the input string into individual characters based on whitespace\n letters = test.split()\n \n # Create a frequency map of all letters present in the list\n counts = {}\n for char in letters:\n counts[char] = counts.get(char, 0) + 1\n \n # Determine the maximum number of occurrences found\n max_count = max(counts.values())\n \n # Extract all keys that have a value equal to the maximum count\n result = {k: v for k, v in counts.items() if v == max_count}\n \n return result"}
{"task_id": "HumanEval/112", "solution": "def reverse_delete(s, c):\n \"\"\"Task\n We are given two strings s and c, you have to deleted all the characters in s that are equal to any character in c\n then check if the result string is palindrome.\n A string is called palindrome if it reads the same backward as forward.\n You should return a tuple containing the result string and True/False for the check.\n Example\n For s = \"abcde\", c = \"ae\", the result should be ('bcd',False)\n For s = \"abcdef\", c = \"b\" the result should be ('acdef',False)\n For s = \"abcdedcba\", c = \"ab\", the result should be ('cdedc',True)\n \"\"\"\n # Create a set of characters to delete for O(1) lookup time\n chars_to_delete = set(c)\n \n # Filter out characters in s that are present in the deletion set\n result_string = \"\".join([char for char in s if char not in chars_to_delete])\n \n # A string is a palindrome if it equals its reverse\n is_palindrome = result_string == result_string[::-1]\n \n return (result_string, is_palindrome)"}
{"task_id": "HumanEval/113", "solution": "def odd_count(lst):\n \"\"\"Given a list of strings, where each string consists of only digits, return a list.\n Each element i of the output should be \"the number of odd elements in the\n string i of the input.\" where all the i's should be replaced by the number\n of odd digits in the i'th string of the input.\n\n >>> odd_count(['1234567'])\n [\"the number of odd elements 4n the str4ng 4 of the 4nput.\"]\n >>> odd_count(['3',\"11111111\"])\n [\"the number of odd elements 1n the str1ng 1 of the 1nput.\",\n \"the number of odd elements 8n the str8ng 8 of the 8nput.\"]\n \"\"\"\n result = []\n # The template sentence containing 'i' characters to be replaced.\n template = \"the number of odd elements in the string i of the input.\"\n \n for s in lst:\n # Count how many digits in the current string are odd.\n count = 0\n for char in s:\n if int(char) % 2 != 0:\n count += 1\n \n # Replace every occurrence of 'i' with the calculated count.\n modified_sentence = template.replace('i', str(count))\n result.append(modified_sentence)\n \n return result"}
{"task_id": "HumanEval/114", "solution": "def minSubArraySum(nums):\n \"\"\"\n Given an array of integers nums, find the minimum sum of any non-empty sub-array\n of nums.\n Example\n minSubArraySum([2, 3, 4, 1, 2, 4]) == 1\n minSubArraySum([-1, -2, -3]) == -6\n \"\"\"\n if not nums:\n return 0\n\n # We use a variation of Kadane's Algorithm.\n # Instead of tracking the maximum subarray sum, we track the minimum.\n \n # Initialize current_min and min_so_far with the first element to handle non-empty requirement.\n current_min = nums[0]\n min_so_far = nums[0]\n\n for i in range(1, len(nums)):\n # At each index, we decide whether to start a new subarray at the current element\n # or extend the existing minimum subarray ending at the previous index.\n current_min = min(nums[i], current_min + nums[i])\n \n # Update the global minimum found so far.\n min_so_far = min(min_so_far, current_min)\n\n return min_so_far"}
{"task_id": "HumanEval/115", "solution": "import math\ndef max_fill(grid, capacity):\n \"\"\"\n You are given a rectangular grid of wells. Each row represents a single well,\n and each 1 in a row represents a single unit of water.\n Each well has a corresponding bucket that can be used to extract water from it, \n and all buckets have the same capacity.\n Your task is to use the buckets to empty the wells.\n Output the number of times you need to lower the buckets.\n\n Example 1:\n Input: \n grid : [[0,0,1,0], [0,1,0,0], [1,1,1,1]]\n bucket_capacity : 1\n Output: 6\n\n Example 2:\n Input: \n grid : [[0,0,1,1], [0,0,0,0], [1,1,1,1], [0,1,1,1]]\n bucket_capacity : 2\n Output: 5\n \n Example 3:\n Input: \n grid : [[0,0,0], [0,0,0]]\n bucket_capacity : 5\n Output: 0\n \"\"\"\n total_trips = 0\n \n for row in grid:\n # Count the number of units of water (1s) in the current well\n water_count = sum(row)\n \n # Calculate how many times the bucket must be lowered for this specific well.\n # We use ceiling division because any remaining water requires an additional trip.\n trips_for_well = math.ceil(water_count / capacity)\n \n total_trips += trips_for_well\n \n return total_trips"}
{"task_id": "HumanEval/116", "solution": "def sort_array(arr):\n \"\"\"\n Sorts an array of integers according to the number of ones in their \n binary representation in ascending order. For numbers with the same \n number of ones, they are sorted based on their decimal value in ascending order.\n\n Note: In Python, bin() for negative numbers returns a string like '-0b101'.\n The count of '1's is performed on the binary representation of the absolute value.\n \"\"\"\n # The key function returns a tuple (primary_key, secondary_key)\n # Primary key: number of ones in binary representation\n # Secondary key: the decimal value itself\n return sorted(arr, key=lambda x: (bin(x).count('1'), x))"}
{"task_id": "HumanEval/117", "solution": "def select_words(s, n):\n \"\"\"Given a string s and a natural number n, you have been tasked to implement \n a function that returns a list of all words from string s that contain exactly \n n consonants, in order these words appear in the string s.\n If the string s is empty then the function should return an empty list.\n Note: you may assume the input string contains only letters and spaces.\n Examples:\n select_words(\"Mary had a little lamb\", 4) ==> [\"little\"]\n select_words(\"Mary had a little lamb\", 3) ==> [\"Mary\", \"lamb\"]\n select_words(\"simple white space\", 2) ==> []\n select_words(\"Hello world\", 4) ==> [\"world\"]\n select_words(\"Uncle sam\", 3) ==> [\"Uncle\"]\n \"\"\"\n if not s:\n return []\n\n # Define vowels for comparison. \n # Based on the examples provided, 'y' is treated as a consonant.\n vowels = set(\"aeiouAEIOU\")\n \n # Split the string into words based on whitespace\n words = s.split()\n result = []\n\n for word in words:\n # Count characters that are not vowels\n # Since input is guaranteed to be only letters and spaces, \n # any character in a word that isn't a vowel is a consonant.\n consonant_count = sum(1 for char in word if char not in vowels)\n \n if consonant_count == n:\n result.append(word)\n\n return result"}
{"task_id": "HumanEval/118", "solution": "def get_closest_vowel(word):\n \"\"\"You are given a word. Your task is to find the closest vowel that stands between \n two consonants from the right side of the word (case sensitive).\n \n Vowels in the beginning and ending doesn't count. Return empty string if you didn't\n find any vowel met the above condition. \n\n You may assume that the given string contains English letter only.\n\n Example:\n get_closest_vowel(\"yogurt\") ==> \"u\"\n get_closest_vowel(\"FULL\") ==> \"U\"\n get_closest_vowel(\"quick\") ==> \"\"\n get_closest_vowel(\"ab\") ==> \"\"\n \"\"\"\n vowels = set(\"aeiouAEIOU\")\n \n # We iterate from the right side of the word.\n # A vowel must be between two consonants, so it cannot be at index 0 or index len(word)-1.\n # Therefore, we check indices from len(word) - 2 down to 1.\n for i in range(len(word) - 2, 0, -1):\n char = word[i]\n if char in vowels:\n # Check if the character to the left and right are consonants.\n # Since we assume only English letters, a consonant is any letter not in the vowel set.\n left_char = word[i - 1]\n right_char = word[i + 1]\n \n if left_char not in vowels and right_char not in vowels:\n return char\n \n return \"\""}
{"task_id": "HumanEval/119", "solution": "def match_parens(lst):\n '''\n You are given a list of two strings, both strings consist of open\n parentheses '(' or close parentheses ')' only.\n Your job is to check if it is possible to concatenate the two strings in\n some order, that the resulting string will be good.\n A string S is considered to be good if and only if all parentheses in S\n are balanced. For example: the string '(())()' is good, while the string\n '())' is not.\n Return 'Yes' if there's a way to make a good string, and return 'No' otherwise.\n\n Examples:\n match_parens(['()(', ')']) == 'Yes'\n match_parens([')', ')']) == 'No'\n '''\n def is_balanced(s):\n \"\"\"Helper function to check if a parentheses string is balanced.\"\"\"\n balance = 0\n for char in s:\n if char == '(':\n balance += 1\n else:\n balance -= 1\n # If balance drops below zero, there are more closing than opening parens at this point\n if balance < 0:\n return False\n # The string is balanced only if the final count of open and close parens are equal\n return balance == 0\n\n s1 = lst[0]\n s2 = lst[1]\n\n # Check both possible concatenation orders: s1 + s2 and s2 + s1\n if is_balanced(s1 + s2) or is_balanced(s2 + s1):\n return 'Yes'\n else:\n return 'No'"}
{"task_id": "HumanEval/120", "solution": "def maximum(arr, k):\n \"\"\"\n Given an array arr of integers and a positive integer k, return a sorted list \n of length k with the maximum k numbers in arr.\n\n Example 1:\n Input: arr = [-3, -4, 5], k = 3\n Output: [-4, -3, 5]\n\n Example 2:\n Input: arr = [4, -4, 4], k = 2\n Output: [4, 4]\n\n Example 3:\n Input: arr = [-3, 2, 1, 2, -1, -2, 1], k = 1\n Output: [2]\n \"\"\"\n # If k is 0, return an empty list as per the constraints (0 <= k <= len(arr))\n if k == 0:\n return []\n\n # Sort the array in ascending order.\n # Time Complexity: O(N log N) where N is the length of the array.\n sorted_arr = sorted(arr)\n \n # The maximum k numbers will be at the end of the sorted list.\n # Slicing from index -k to the end gives us these elements in ascending order.\n return sorted_arr[-k:]"}
{"task_id": "HumanEval/121", "solution": "def solution(lst):\n \"\"\"Given a non-empty list of integers, return the sum of all of the odd elements that are in even positions.\n \n\n Examples\n solution([5, 8, 7, 1]) ==> 12\n solution([3, 3, 3, 3, 3]) ==> 9\n solution([30, 13, 24, 321]) ==> 0\n \"\"\"\n # lst[::2] slices the list to get elements at indices 0, 2, 4... (even positions)\n # We then filter for elements that are odd (x % 2 != 0) and sum them.\n return sum(x for x in lst[::2] if x % 2 != 0)"}
{"task_id": "HumanEval/122", "solution": "def add_elements(arr, k):\n \"\"\"\n Given a non-empty array of integers arr and an integer k, return\n the sum of the elements with at most two digits from the first k elements of arr.\n\n Example:\n Input: arr = [111, 21, 3, 4000, 5, 6, 7, 8, 9], k = 4\n Output: 24 # sum of 21 + 3\n\n Constraints:\n 1. 1 <= len(arr) <= 100\n 2. 1 <= k <= len(arr)\n \"\"\"\n # Slice the array to get only the first k elements\n first_k = arr[:k]\n \n # Initialize sum variable\n total_sum = 0\n \n for num in first_k:\n # A number has at most two digits if its absolute value is less than 100.\n # This covers numbers from -99 to 99.\n if abs(num) < 100:\n total_sum += num\n \n return total_sum"}
{"task_id": "HumanEval/123", "solution": "def get_odd_collatz(n):\n \"\"\"\n Given a positive integer n, return a sorted list that has the odd numbers in collatz sequence.\n\n The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined\n as follows: start with any positive integer n. Then each term is obtained from the \n previous term as follows: if the previous term is even, the next term is one half of \n the previous term. If the previous term is odd, the next term is 3 times the previous\n term plus 1. The conjecture is that no matter what value of n, the sequence will always reach 1.\n\n Note: \n 1. Collatz(1) is [1].\n 2. returned list sorted in increasing order.\n\n For example:\n get_odd_collatz(5) returns [1, 5] # The collatz sequence for 5 is [5, 16, 8, 4, 2, 1], so the odd numbers are only 1, and 5.\n \"\"\"\n odds = []\n current = n\n \n # Generate the Collatz sequence until it reaches 1\n while current != 1:\n if current % 2 != 0:\n odds.append(current)\n current = 3 * current + 1\n else:\n current = current // 2\n \n # The loop stops when current == 1, and since 1 is odd, we add it to the list\n odds.append(1)\n \n # Return the list sorted in increasing order\n return sorted(odds)"}
{"task_id": "HumanEval/124", "solution": "def valid_date(date):\n \"\"\"You have to write a function which validates a given date string and\n returns True if the date is valid otherwise False.\n The date is valid if all of the following rules are satisfied:\n 1. The date string is not empty.\n 2. The number of days is not less than 1 or higher than 31 days for months 1,3,5,7,8,10,12. \n And the number of days is not less than 1 or higher than 30 days for months 4,6,9,11. \n And, the number of days is not less than 1 or higher than 29 for the month 2.\n 3. The months should not be less than 1 or higher than 12.\n 4. The date should be in the format: mm-dd-yyyy\n \"\"\"\n # Rule 1: Check if the string is empty\n if not date:\n return False\n\n # Rule 4: Check for correct format (mm-dd-yyyy)\n # Split by '-' to isolate month, day, and year\n parts = date.split('-')\n if len(parts) != 3:\n return False\n\n month_str, day_str, year_str = parts\n\n # Ensure the format is strictly mm-dd-yyyy (lengths must be 2, 2, 4)\n # and that all components consist only of digits.\n if len(month_str) != 2 or len(day_str) != 2 or len(year_str) != 4:\n return False\n \n if not (month_str.isdigit() and day_str.isdigit() and year_str.isdigit()):\n return False\n\n # Convert strings to integers for value validation\n try:\n m = int(month_str)\n d = int(day_str)\n y = int(year_str)\n except ValueError:\n return False\n\n # Rule 3: The months should not be less than 1 or higher than 12.\n if m < 1 or m > 12:\n return False\n\n # Rule 2: Validate days based on the month\n if m in [1, 3, 5, 7, 8, 10, 12]:\n if d < 1 or d > 31:\n return False\n elif m in [4, 6, 9, 11]:\n if d < 1 or d > 30:\n return False\n elif m == 2:\n # The prompt specifies a hard limit of 29 for February regardless of leap year logic.\n if d < 1 or d > 29:\n return False\n\n return True"}
{"task_id": "HumanEval/125", "solution": "def split_words(txt):\n '''\n Given a string of words, return a list of words split on whitespace, if no whitespaces exists in the text you\n should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the\n alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25\n Examples\n split_words(\"Hello world!\") \u279e [\"Hello\", \"world!\"]\n split_words(\"Hello,world!\") \u279e [\"Hello\", \"world!\"]\n split_words(\"abcdef\") == 3 \n '''\n # Check if any whitespace characters exist in the string\n if any(char.isspace() for char in txt):\n return txt.split()\n \n # If no whitespaces, check if commas exist\n if ',' in txt:\n return txt.split(',')\n \n # If neither whitespaces nor commas exist, count lowercase letters with odd alphabet indices\n count = 0\n for char in txt:\n if 'a' <= char <= 'z':\n # Calculate index: a=0, b=1, c=2...\n index = ord(char) - ord('a')\n if index % 2 != 0:\n count += 1\n return count"}
{"task_id": "HumanEval/126", "solution": "def is_sorted(lst):\n '''\n Given a list of numbers, return whether or not they are sorted\n in ascending order. If list has more than 1 duplicate of the same\n number (meaning 3 or more occurrences), return False. Assume no negative numbers and only integers.\n\n Examples\n is_sorted([5]) \u279e True\n is_sorted([1, 2, 3, 4, 5]) \u279e True\n is_sorted([1, 3, 2, 4, 5]) \u279e False\n is_sorted([1, 2, 3, 4, 5, 6]) \u279e True\n is_sorted([1, 2, 3, 4, 5, 6, 7]) \u279e True\n is_sorted([1, 3, 2, 4, 5, 6, 7]) \u279e False\n is_sorted([1, 2, 2, 3, 3, 4]) \u279e True\n is_sorted([1, 2, 2, 2, 3, 4]) \u279e False\n '''\n # Check if the list is sorted in ascending order\n for i in range(len(lst) - 1):\n if lst[i] > lst[i + 1]:\n return False\n\n # Check if any number appears more than twice\n # Since we already verified it's sorted, duplicates must be adjacent.\n # However, using a dictionary/count is cleaner and works regardless of order.\n counts = {}\n for num in lst:\n counts[num] = counts.get(num, 0) + 1\n if counts[num] > 2:\n return False\n\n return True"}
{"task_id": "HumanEval/127", "solution": "def intersection(interval1, interval2):\n \"\"\"You are given two intervals,\n where each interval is a pair of integers. For example, interval = (start, end) = (1, 2).\n The given intervals are closed which means that the interval (start, end)\n includes both start and end.\n For each given interval, it is assumed that its start is less or equal its end.\n Your task is to determine whether the length of intersection of these two \n intervals is a prime number.\n Example, the intersection of the intervals (1, 3), (2, 4) is (2, 3)\n which its length is 1, which not a prime number.\n If the length of the intersection is a prime number, return \"YES\",\n otherwise, return \"NO\".\n If the two intervals don't intersect, return \"NO\".\n\n\n [input/output] samples:\n intersection((1, 2), (2, 3)) ==> \"NO\"\n intersection((-1, 1), (0, 4)) ==> \"NO\"\n intersection((-3, -1), (-5, 5)) ==> \"YES\"\n \"\"\"\n\n def is_prime(n):\n \"\"\"Helper function to check if a number is prime.\"\"\"\n if n < 2:\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\n # Extract start and end points of the intervals\n start1, end1 = interval1\n start2, end2 = interval2\n\n # The intersection of two closed intervals [a, b] and [c, d] is [max(a, c), min(b, d)]\n max_start = max(start1, start2)\n min_end = min(end1, end2)\n\n # If the maximum start point is greater than the minimum end point, \n # there is no intersection.\n if max_start > min_end:\n return \"NO\"\n\n # The length of a closed interval [a, b] is defined as (b - a).\n length = min_end - max_start\n\n # Check if the calculated length is a prime number.\n if is_prime(length):\n return \"YES\"\n else:\n return \"NO\""}
{"task_id": "HumanEval/128", "solution": "def prod_signs(arr):\n \"\"\"\n You are given an array arr of integers and you need to return\n sum of magnitudes of integers multiplied by product of all signs\n of each number in the array, represented by 1, -1 or 0.\n Note: return None for empty arr.\n\n Example:\n >>> prod_signs([1, 2, 2, -4]) == -9\n >>> prod_signs([0, 1]) == 0\n >>> prod_signs([]) == None\n \"\"\"\n if not arr:\n return None\n\n # Calculate the sum of magnitudes (absolute values)\n sum_magnitudes = sum(abs(x) for x in arr)\n\n # Calculate the product of signs\n # Sign is 1 if x > 0, -1 if x < 0, and 0 if x == 0\n product_of_signs = 1\n for x in arr:\n if x > 0:\n sign = 1\n elif x < 0:\n sign = -1\n else:\n sign = 0\n \n product_of_signs *= sign\n \n # Optimization: if the product becomes 0, it will stay 0\n if product_of_signs == 0:\n break\n\n return sum_magnitudes * product_of_signs"}
{"task_id": "HumanEval/129", "solution": "def minPath(grid, k):\n \"\"\"\n Given a grid with N rows and N columns (N >= 2) and a positive integer k, \n each cell of the grid contains a value. Every integer in the range [1, N * N]\n inclusive appears exactly once on the cells of the grid.\n\n You have to find the minimum path of length k in the grid. You can start\n from any cell, and in each step you can move to any of the neighbor cells,\n in other words, you can go to cells which share an edge with your current\n cell.\n A path A (of length k) is considered less than a path B (of length k) if \n the sequence of values in A is lexicographically smaller than that in B.\n\n The strategy for the minimum path:\n 1. To minimize the sequence lexicographically, we must start at the cell with value 1.\n 2. If k = 1, the answer is simply [1].\n 3. If k > 1, the second element should be the smallest possible neighbor of the cell containing 1.\n 4. For the third element, since no value in the grid is smaller than 1, moving back to the \n cell with value 1 is always the optimal choice.\n 5. This pattern (1 -> min_neighbor -> 1 -> min_neighbor ...) continues for k elements.\n \"\"\"\n n = len(grid)\n \n # Find the coordinates of the cell containing the value 1\n start_r, start_c = -1, -1\n for r in range(n):\n for c in range(n):\n if grid[r][c] == 1:\n start_r, start_c = r, c\n break\n if start_r != -1:\n break\n \n # If the path length is 1, the smallest possible sequence is just [1]\n if k == 1:\n return [1]\n \n # Find the minimum value among the neighbors of cell (start_r, start_c)\n min_neighbor = float('inf')\n directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]\n for dr, dc in directions:\n nr, nc = start_r + dr, start_c + dc\n if 0 <= nr < n and 0 <= nc < n:\n if grid[nr][nc] < min_neighbor:\n min_neighbor = grid[nr][nc]\n \n # Construct the path by alternating between 1 and its smallest neighbor\n path = []\n for i in range(k):\n if i % 2 == 0:\n path.append(1)\n else:\n path.append(min_neighbor)\n \n return path"}
{"task_id": "HumanEval/130", "solution": "def tri(n):\n \"\"\"Everyone knows Fibonacci sequence, it was studied deeply by mathematicians in \n the last couple centuries. However, what people don't know is Tribonacci sequence.\n Tribonacci sequence is defined by the recurrence:\n tri(1) = 3\n tri(n) = 1 + n / 2, if n is even.\n tri(n) = tri(n - 1) + tri(n - 2) + tri(n + 1), if n is odd.\n For example:\n tri(2) = 1 + (2 / 2) = 2\n tri(4) = 3\n tri(3) = tri(2) + tri(1) + tri(4)\n = 2 + 3 + 3 = 8 \n You are given a non-negative integer number n, you have to return a list of the \n first n + 1 numbers of the Tribonacci sequence.\n Examples:\n tri(3) = [1, 3, 2, 8]\n \"\"\"\n # Initialize an empty list to store the sequence values from index 0 up to n\n sequence = []\n \n for i in range(n + 1):\n if i == 1:\n # Explicit definition for tri(1)\n val = 3\n elif i % 2 == 0:\n # Rule for even indices: tri(n) = 1 + n / 2\n val = 1 + (i // 2)\n else:\n # Rule for odd indices (where i > 1): tri(n) = tri(n-1) + tri(n-2) + tri(n+1)\n # Since we are iterating sequentially, sequence[i-1] and sequence[i-2] are already computed.\n # Because i is odd, (i + 1) is even, so we can calculate tri(i+1) using the even rule.\n tri_prev1 = sequence[i - 1]\n tri_prev2 = sequence[i - 2]\n tri_next = 1 + ((i + 1) // 2)\n val = tri_prev1 + tri_prev2 + tri_next\n \n sequence.append(val)\n \n return sequence"}
{"task_id": "HumanEval/131", "solution": "def digits(n):\n \"\"\"Given a positive integer n, return the product of the odd digits.\n Return 0 if all digits are even.\n For example:\n digits(1) == 1\n digits(4) == 0\n digits(235) == 15\n \"\"\"\n # Convert integer to string to iterate through each digit\n s = str(n)\n product = 1\n found_odd = False\n \n for char in s:\n digit = int(char)\n # Check if the digit is odd\n if digit % 2 != 0:\n product *= digit\n found_odd = True\n \n # If no odd digits were found, return 0 as per requirements\n return product if found_odd else 0"}
{"task_id": "HumanEval/132", "solution": "def is_nested(string):\n \"\"\"\n Create a function that takes a string as input which contains only square brackets.\n The function should return True if and only if there is a valid subsequence of brackets \n where at least one bracket in the subsequence is nested.\n\n A \"valid nested subsequence\" essentially means we can find four indices i < j < k < l \n such that string[i] == '[', string[j] == '[', string[k] == ']', and string[l] == ']'.\n This forms the pattern [[ ]], which is the simplest form of nesting. Any more complex \n nested valid sequence will also contain this subsequence.\n\n is_nested('[[]]') \u279e True\n is_nested('[]]]]]]][[[[[]') \u279e False\n is_nested('[][]') \u279e False\n is_nested('[]') \u279e False\n is_nested('[[][]]') \u279e True\n is_nested('[[]][[') \u279e True\n \"\"\"\n # Collect the indices of all opening brackets\n opens = [i for i, char in enumerate(string) if char == '[']\n # Collect the indices of all closing brackets\n closes = [i for i, char in enumerate(string) if char == ']']\n \n # To have a nested subsequence [[ ]], we need at least two opening \n # and two closing brackets.\n if len(opens) < 2 or len(closes) < 2:\n return False\n \n # The most likely candidates to satisfy the condition i < j < k < l are:\n # - The first two opening brackets (smallest indices)\n # - The last two closing brackets (largest indices)\n # If the second opening bracket appears before the second-to-last \n # closing bracket, then we have found a nested subsequence.\n return opens[1] < closes[-2]"}
{"task_id": "HumanEval/133", "solution": "import math\ndef sum_squares(lst):\n \"\"\"You are given a list of numbers.\n You need to return the sum of squared numbers in the given list,\n round each element in the list to the upper int(Ceiling) first.\n Examples:\n For lst = [1,2,3] the output should be 14\n For lst = [1,4,9] the output should be 98\n For lst = [1,3,5,7] the output should be 84\n For lst = [1.4,4.2,0] the output should be 29\n For lst = [-2.4,1,1] the output should be 6\n \"\"\"\n return sum(math.ceil(x)**2 for x in lst)"}
{"task_id": "HumanEval/134", "solution": "def check_if_last_char_is_a_letter(txt):\n '''\n Create a function that returns True if the last character\n of a given string is an alphabetical character and is not\n a part of a word, and False otherwise.\n Note: \"word\" is a group of characters separated by space.\n\n Examples:\n check_if_last_char_is_a_letter(\"apple pie\") \u279e False\n check_if_last_char_is_a_letter(\"apple pi e\") \u279e True\n check_if_last_char_is_a_letter(\"apple pi e \") \u279e False\n check_if_last_char_is_a_letter(\"\") \u279e False \n '''\n # Check if the string is empty\n if not txt:\n return False\n \n # Get the last character of the string\n last_char = txt[-1]\n \n # The last character must be an alphabetical letter\n if not last_char.isalpha():\n return False\n \n # To \"not be part of a word\", the character must either:\n # 1. Be the only character in the string\n # 2. Be preceded by a space\n if len(txt) == 1 or txt[-2] == ' ':\n return True\n \n return False"}
{"task_id": "HumanEval/135", "solution": "def can_arrange(arr):\n \"\"\"Create a function which returns the largest index of an element which\n is not greater than or equal to the element immediately preceding it. If\n no such element exists then return -1. The given array will not contain\n duplicate values.\n\n Examples:\n can_arrange([1,2,4,3,5]) = 3\n can_arrange([1,2,3]) = -1\n \"\"\"\n last_index = -1\n # Start from the second element (index 1) to compare with the preceding one\n for i in range(1, len(arr)):\n # \"Not greater than or equal to\" is equivalent to \"strictly less than\"\n if arr[i] < arr[i-1]:\n last_index = i\n \n return last_index"}
{"task_id": "HumanEval/136", "solution": "def largest_smallest_integers(lst):\n '''\n Create a function that returns a tuple (a, b), where 'a' is\n the largest of negative integers, and 'b' is the smallest\n of positive integers in a list.\n If there is no negative or positive integers, return them as None.\n\n Examples:\n largest_smallest_integers([2, 4, 1, 3, 5, 7]) == (None, 1)\n largest_smallest_integers([]) == (None, None)\n largest_smallest_integers([0]) == (None, None)\n '''\n # Filter the list to get only negative integers\n negatives = [x for x in lst if x < 0]\n # Filter the list to get only positive integers\n positives = [x for x in lst if x > 0]\n \n # Find the maximum of negatives if they exist, otherwise None\n a = max(negatives) if negatives else None\n # Find the minimum of positives if they exist, otherwise None\n b = min(positives) if positives else None\n \n return (a, b)"}
{"task_id": "HumanEval/137", "solution": "def compare_one(a, b):\n \"\"\"\n Create a function that takes integers, floats, or strings representing\n real numbers, and returns the larger variable in its given variable type.\n Return None if the values are equal.\n Note: If a real number is represented as a string, the floating point might be . or ,\n \"\"\"\n def to_float(val):\n # If the value is a string, handle potential comma decimal separators\n if isinstance(val, str):\n return float(val.replace(',', '.'))\n # Otherwise, cast directly to float (handles int and float)\n return float(val)\n\n # Convert both inputs to floats for comparison\n num_a = to_float(a)\n num_b = to_float(b)\n\n if num_a > num_b:\n return a\n elif num_b > num_a:\n return b\n else:\n return None"}
{"task_id": "HumanEval/138", "solution": "def is_equal_to_sum_even(n):\n \"\"\"Evaluate whether the given number n can be written as the sum of exactly 4 positive even numbers\n Example\n is_equal_to_sum_even(4) == False\n is_equal_to_sum_even(6) == False\n is_equal_to_sum_even(8) == True\n \"\"\"\n # A number n can be written as the sum of 4 positive even numbers if:\n # 1. n is even (since the sum of any number of even integers is always even).\n # 2. n is at least 8 (the smallest positive even number is 2, and 2 * 4 = 8).\n return n >= 8 and n % 2 == 0"}
{"task_id": "HumanEval/139", "solution": "import math\ndef special_factorial(n):\n \"\"\"The Brazilian factorial is defined as:\n brazilian_factorial(n) = n! * (n-1)! * (n-2)! * ... * 1!\n where n > 0\n\n For example:\n >>> special_factorial(4)\n 288\n\n The function will receive an integer as input and should return the special\n factorial of this integer.\n \"\"\"\n if n <= 0:\n return 0 # Or handle based on specific requirements for non-positive integers\n \n result = 1\n current_factorial = 1\n \n # We iterate from 1 to n. In each step, we update the current factorial (i!)\n # and multiply it into our running total product.\n for i in range(1, n + 1):\n current_factorial *= i\n result *= current_factorial\n \n return result"}
{"task_id": "HumanEval/140", "solution": "import re\ndef fix_spaces(text):\n \"\"\"\n Given a string text, replace all spaces in it with underscores, \n and if a string has more than 2 consecutive spaces, \n then replace all consecutive spaces with - \n \n fix_spaces(\"Example\") == \"Example\"\n fix_spaces(\"Example 1\") == \"Example_1\"\n fix_spaces(\" Example 2\") == \"_Example_2\"\n fix_spaces(\" Example 3\") == \"_Example-3\"\n \"\"\"\n # First, handle the case of more than 2 consecutive spaces.\n # We use a regular expression to find sequences of 3 or more spaces (' {3,}')\n # and replace each such sequence with a single hyphen '-'.\n text = re.sub(r' {3,}', '-', text)\n \n # Then, handle the remaining spaces (single or double).\n # According to the rule \"replace all spaces in it with underscores\",\n # every individual space character left should be converted to an underscore.\n text = text.replace(' ', '_')\n \n return text"}
{"task_id": "HumanEval/141", "solution": "def file_name_check(file_name):\n \"\"\"Create a function which takes a string representing a file's name, and returns\n 'Yes' if the the file's name is valid, and returns 'No' otherwise.\n A file's name is considered to be valid if and only if all the following conditions \n are met:\n - There should not be more than three digits ('0'-'9') in the file's name.\n - The file's name contains exactly one dot '.'\n - The substring before the dot should not be empty, and it starts with a letter from \n the latin alphapet ('a'-'z' and 'A'-'Z').\n - The substring after the dot should be one of these: ['txt', 'exe', 'dll']\n \"\"\"\n # Condition 2: Exactly one dot '.'\n if file_name.count('.') != 1:\n return 'No'\n \n # Split the name into prefix and suffix based on the single dot\n prefix, suffix = file_name.split('.')\n \n # Condition 4: The substring after the dot should be one of ['txt', 'exe', 'dll']\n if suffix not in ['txt', 'exe', 'dll']:\n return 'No'\n \n # Condition 3: Substring before the dot should not be empty and starts with a latin letter\n if not prefix:\n return 'No'\n \n first_char = prefix[0]\n if not (('a' <= first_char <= 'z') or ('A' <= first_char <= 'Z')):\n return 'No'\n \n # Condition 1: There should not be more than three digits ('0'-'9') in the file's name\n digit_count = sum(c.isdigit() for c in file_name)\n if digit_count > 3:\n return 'No'\n \n return 'Yes'"}
{"task_id": "HumanEval/142", "solution": "def sum_squares(lst):\n \"\"\"\n This function will take a list of integers. For all entries in the list, the function shall square the integer entry if its index is a \n multiple of 3 and will cube the integer entry if its index is a multiple of 4 and not a multiple of 3. The function will not \n change the entries in the list whose indexes are not a multiple of 3 or 4. The function shall then return the sum of all entries. \n \n Examples:\n For lst = [1,2,3] the output should be 6\n For lst = [] the output should be 0\n For lst = [-1,-5,2,-1,-5] the output should be -126\n \"\"\"\n total_sum = 0\n for i, val in enumerate(lst):\n if i % 3 == 0:\n # Square the entry if index is a multiple of 3\n total_sum += val ** 2\n elif i % 4 == 0:\n # Cube the entry if index is a multiple of 4 and NOT a multiple of 3\n total_sum += val ** 3\n else:\n # Keep the entry as is otherwise\n total_sum += val\n \n return total_sum"}
{"task_id": "HumanEval/143", "solution": "def words_in_sentence(sentence):\n \"\"\"\n You are given a string representing a sentence,\n the sentence contains some words separated by a space,\n and you have to return a string that contains the words from the original sentence,\n whose lengths are prime numbers,\n the order of the words in the new string should be the same as the original one.\n\n Example 1:\n Input: sentence = \"This is a test\"\n Output: \"is\"\n\n Example 2:\n Input: sentence = \"lets go for swimming\"\n Output: \"go for\"\n\n Constraints:\n * 1 <= len(sentence) <= 100\n * sentence contains only letters\n \"\"\"\n def is_prime(n):\n \"\"\"Helper function to check if a number is prime.\"\"\"\n if n < 2:\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\n # Split the sentence into individual words based on spaces\n words = sentence.split()\n \n # Filter words whose length is a prime number\n prime_length_words = [word for word in words if is_prime(len(word))]\n \n # Join the filtered words back into a single string separated by space\n return \" \".join(prime_length_words)"}
{"task_id": "HumanEval/144", "solution": "def simplify(x, n):\n \"\"\"Your task is to implement a function that will simplify the expression\n x * n. The function returns True if x * n evaluates to a whole number and False\n otherwise. Both x and n, are string representation of a fraction, and have the following format,\n <numerator>/<denominator> where both numerator and denominator are positive whole numbers.\n\n You can assume that x, and n are valid fractions, and do not have zero as denominator.\n\n simplify(\"1/5\", \"5/1\") = True\n simplify(\"1/6\", \"2/1\") = False\n simplify(\"7/10\", \"10/2\") = False\n \"\"\"\n # Split the input strings to extract numerators and denominators\n num_x, den_x = map(int, x.split('/'))\n num_n, den_n = map(int, n.split('/'))\n \n # The product of two fractions (a/b) * (c/d) is (a*c) / (b*d)\n numerator_product = num_x * num_n\n denominator_product = den_x * den_n\n \n # A fraction represents a whole number if the numerator is divisible by the denominator\n return numerator_product % denominator_product == 0"}
{"task_id": "HumanEval/145", "solution": "def order_by_points(nums):\n \"\"\"\n Write a function which sorts the given list of integers\n in ascending order according to the sum of their digits.\n Note: if there are several items with similar sum of their digits,\n order them based on their index in original list.\n\n For example:\n >>> order_by_points([1, 11, -1, -11, -12]) == [-1, -11, 1, -12, 11]\n >>> order_by_points([]) == []\n \"\"\"\n def get_digit_sum(n):\n \"\"\"\n Calculates the sum of digits based on the logic derived from the example:\n - For positive numbers, it is the standard sum of digits.\n - For negative numbers, the first digit (most significant) is treated as \n negative, and all subsequent digits are treated as positive.\n Example: -123 -> (-1) + 2 + 3 = 4\n \"\"\"\n s = str(n)\n if s[0] == '-':\n # The first digit includes the minus sign (e.g., \"-1\")\n # and is added to the sum of the remaining digits.\n first_digit_val = int(s[0] + s[1])\n remaining_digits_sum = sum(int(d) for d in s[2:])\n return first_digit_val + remaining_digits_sum\n else:\n # Standard sum of digits for non-negative integers.\n return sum(int(d) for d in s)\n\n # Python's sorted() function is stable, meaning it preserves the original \n # order of elements that have equal sort keys. This satisfies the requirement \n # to order items based on their index in the original list as a tie-breaker.\n return sorted(nums, key=get_digit_sum)"}
{"task_id": "HumanEval/146", "solution": "def specialFilter(nums):\n \"\"\"Write a function that takes an array of numbers as input and returns \n the number of elements in the array that are greater than 10 and both \n first and last digits of a number are odd (1, 3, 5, 7, 9).\n For example:\n specialFilter([15, -73, 14, -15]) => 1 \n specialFilter([33, -2, -3, 45, 21, 109]) => 2\n \"\"\"\n count = 0\n # Set of odd digits as strings for quick lookup\n odd_digits = {'1', '3', '5', '7', '9'}\n \n for num in nums:\n # Condition 1: Number must be greater than 10\n if num > 10:\n # Convert number to string to easily access the first and last digits\n s = str(num)\n first_digit = s[0]\n last_digit = s[-1]\n \n # Condition 2 & 3: First and last digits must be odd\n if first_digit in odd_digits and last_digit in odd_digits:\n count += 1\n \n return count"}
{"task_id": "HumanEval/147", "solution": "def get_max_triples(n):\n \"\"\"\n You are given a positive integer n. You have to create an integer array a of length n.\n For each i (1 \u2264 i \u2264 n), the value of a[i] = i * i - i + 1.\n Return the number of triples (a[i], a[j], a[k]) of a where i < j < k, \n and a[i] + a[j] + a[k] is a multiple of 3.\n\n Analysis:\n The condition for a triple to be a multiple of 3 depends on the remainders of each element modulo 3.\n Let's analyze a[i] = i^2 - i + 1 (mod 3):\n - If i % 3 == 0, then a[i] = 0^2 - 0 + 1 = 1 (mod 3)\n - If i % 3 == 1, then a[i] = 1^2 - 1 + 1 = 1 (mod 3)\n - If i % 3 == 2, then a[i] = 2^2 - 2 + 1 = 4 - 2 + 1 = 3 = 0 (mod 3)\n\n So, the elements of array 'a' only have remainders 0 or 1 modulo 3.\n Let c0 be the count of elements where a[i] % 3 == 0 and c1 be the count where a[i] % 3 == 1.\n - i = 2, 5, 8... result in a[i] % 3 == 0. The number of such indices is floor((n + 1) / 3).\n - All other indices (i = 1, 3, 4, 6, 7...) result in a[i] % 3 == 1.\n\n A triple (x, y, z) sums to a multiple of 3 if:\n 1. x % 3 == 0, y % 3 == 0, and z % 3 == 0 => Combination(c0, 3) ways.\n 2. x % 3 == 1, y % 3 == 1, and z % 3 == 1 => Combination(c1, 3) ways.\n 3. One of each remainder (0, 1, 2). Since there are no elements with remainder 2, this is impossible.\n\n Total triples = Combination(c0, 3) + Combination(c1, 3).\n \"\"\"\n # Count how many i in [1, n] satisfy i % 3 == 2\n c0 = (n + 1) // 3\n # The rest of the elements have remainder 1 modulo 3\n c1 = n - c0\n\n def combinations_of_3(count):\n if count < 3:\n return 0\n # Formula for nC3 is (n * (n-1) * (n-2)) / 6\n return (count * (count - 1) * (count - 2)) // 6\n\n return combinations_of_3(c0) + combinations_of_3(c1)"}
{"task_id": "HumanEval/148", "solution": "def bf(planet1, planet2):\n '''\n There are eight planets in our solar system: the closerst to the Sun \n is Mercury, the next one is Venus, then Earth, Mars, Jupiter, Saturn, \n Uranus, Neptune.\n Write a function that takes two planet names as strings planet1 and planet2. \n The function should return a tuple containing all planets whose orbits are \n located between the orbit of planet1 and the orbit of planet2, sorted by \n the proximity to the sun. \n The function should return an empty tuple if planet1 or planet2\n are not correct planet names. \n Examples\n bf(\"Jupiter\", \"Neptune\") ==> (\"Saturn\", \"Uranus\")\n bf(\"Earth\", \"Mercury\") ==> (\"Venus\")\n bf(\"Mercury\", \"Uranus\") ==> (\"Venus\", \"Earth\", \"Mars\", \"Jupiter\", \"Saturn\")\n '''\n # List of planets sorted by proximity to the Sun\n planets = [\n \"Mercury\", \"Venus\", \"Earth\", \"Mars\", \n \"Jupiter\", \"Saturn\", \"Uranus\", \"Neptune\"\n ]\n \n # Check if both provided planet names are valid\n if planet1 not in planets or planet2 not in planets:\n return ()\n \n # Find the indices of the two planets\n idx1 = planets.index(planet1)\n idx2 = planets.index(planet2)\n \n # Determine the range between the two indices\n start_idx = min(idx1, idx2)\n end_idx = max(idx1, idx2)\n \n # Slice the list to get planets strictly between the two orbits\n # We start at start_idx + 1 and end before end_idx\n result = planets[start_idx + 1 : end_idx]\n \n return tuple(result)"}
{"task_id": "HumanEval/149", "solution": "def sorted_list_sum(lst):\n \"\"\"Write a function that accepts a list of strings as a parameter,\n deletes the strings that have odd lengths from it,\n and returns the resulted list with a sorted order,\n The list is always a list of strings and never an array of numbers,\n and it may contain duplicates.\n The order of the list should be ascending by length of each word, and you\n should return the list sorted by that rule.\n If two words have the same length, sort the list alphabetically.\n The function should return a list of strings in sorted order.\n \"\"\"\n # Filter out strings with odd lengths using a list comprehension\n filtered_list = [s for s in lst if len(s) % 2 == 0]\n \n # Sort the filtered list. \n # The key is a tuple: (length of string, the string itself).\n # Python sorts tuples element by element; it will sort by length first,\n # and then alphabetically for strings of the same length.\n filtered_list.sort(key=lambda x: (len(x), x))\n \n return filtered_list"}
{"task_id": "HumanEval/150", "solution": "def x_or_y(n, x, y):\n \"\"\"A simple program which should return the value of x if n is \n a prime number and should return the value of y otherwise.\n\n Examples:\n x_or_y(7, 34, 12) == 34\n x_or_y(15, 8, 5) == 5\n \"\"\"\n # Prime numbers must be greater than 1\n if n <= 1:\n return y\n \n # Check for primality\n is_prime = True\n # We only need to check up to the square root of n\n for i in range(2, int(n**0.5) + 1):\n if n % i == 0:\n is_prime = False\n break\n \n return x if is_prime else y"}
{"task_id": "HumanEval/151", "solution": "def double_the_difference(lst):\n '''\n Given a list of numbers, return the sum of squares of the numbers\n in the list that are odd. Ignore numbers that are negative or not integers.\n \n double_the_difference([1, 3, 2, 0]) == 1 + 9 + 0 + 0 = 10\n double_the_difference([-1, -2, 0]) == 0\n double_the_difference([9, -2]) == 81\n double_the_difference([0]) == 0 \n \n If the input list is empty, return 0.\n '''\n # If the input list is empty, return 0 as specified\n if not lst:\n return 0\n \n total_sum = 0\n for num in lst:\n # Check if the number is an integer (excluding booleans)\n # and check if it is non-negative and odd\n if type(num) == int and num >= 0 and num % 2 != 0:\n total_sum += num ** 2\n \n return total_sum"}
{"task_id": "HumanEval/152", "solution": "def compare(game, guess):\n \"\"\"I think we all remember that feeling when the result of some long-awaited\n event is finally known. The feelings and thoughts you have at that moment are\n definitely worth noting down and comparing.\n Your task is to determine if a person correctly guessed the results of a number of matches.\n You are given two arrays of scores and guesses of equal length, where each index shows a match. \n Return an array of the same length denoting how far off each guess was. If they have guessed correctly,\n the value is 0, and if not, the value is the absolute difference between the guess and the score.\n \n example:\n\n compare([1,2,3,4,5,1],[1,2,3,4,2,-2]) -> [0,0,0,0,3,3]\n compare([0,5,0,0,0,4],[4,1,1,0,0,-2]) -> [4,4,1,0,0,6]\n \"\"\"\n # Use a list comprehension to iterate through both lists simultaneously using zip.\n # abs(a - b) calculates the absolute difference between two numbers.\n return [abs(score - g) for score, g in zip(game, guess)]"}
{"task_id": "HumanEval/153", "solution": "def Strongest_Extension(class_name, extensions):\n \"\"\"You will be given the name of a class (a string) and a list of extensions.\n The extensions are to be used to load additional classes to the class. The\n strength of the extension is as follows: Let CAP be the number of the uppercase\n letters in the extension's name, and let SM be the number of lowercase letters \n in the extension's name, the strength is given by the fraction CAP - SM. \n You should find the strongest extension and return a string in this \n format: ClassName.StrongestExtensionName.\n If there are two or more extensions with the same strength, you should\n choose the one that comes first in the list.\n \"\"\"\n # Initialize variables to track the maximum strength found and the corresponding extension\n max_strength = float('-inf')\n strongest_ext = None\n\n for ext in extensions:\n # Count uppercase letters (CAP)\n cap = sum(1 for char in ext if char.isupper())\n # Count lowercase letters (SM)\n sm = sum(1 for char in ext if char.islower())\n \n # Calculate strength as CAP - SM\n strength = cap - sm\n \n # We only update the strongest_ext if we find a strength strictly greater than \n # the current max_strength. This ensures that if two extensions have the same \n # strength, the one appearing first in the list is preserved.\n if strength > max_strength:\n max_strength = strength\n strongest_ext = ext\n\n # Return the result in the format ClassName.StrongestExtensionName\n return f\"{class_name}.{strongest_ext}\""}
{"task_id": "HumanEval/154", "solution": "def cycpattern_check(a, b):\n \"\"\"\n You are given 2 words. You need to return True if the second word or any of its rotations is a substring in the first word.\n \n cycpattern_check(\"abcd\",\"abd\") => False\n cycpattern_check(\"hello\",\"ell\") => True\n cycpattern_check(\"whassup\",\"psus\") => False\n cycpattern_check(\"abab\",\"baa\") => True\n cycpattern_check(\"efef\",\"eeff\") => False\n cycpattern_check(\"himenss\",\"simen\") => True\n \"\"\"\n # If the second word is empty, it's technically a substring of any string.\n if not b:\n return True\n \n # Length of the second word to generate all possible rotations.\n n = len(b)\n \n # A cyclic rotation is created by shifting characters from the front to the back.\n # We iterate through every possible starting index for a rotation.\n for i in range(n):\n # Create the rotation: slice from index i to end, then append slice from start to i.\n rotation = b[i:] + b[:i]\n \n # Check if this specific rotation exists as a substring within string 'a'.\n if rotation in a:\n return True\n \n # If no rotations were found in 'a', return False.\n return False"}
{"task_id": "HumanEval/155", "solution": "def even_odd_count(num):\n \"\"\"Given an integer. return a tuple that has the number of even and odd digits respectively.\n\n Example:\n even_odd_count(-12) ==> (1, 1)\n even_odd_count(123) ==> (1, 2)\n \"\"\"\n # Use absolute value to handle negative numbers\n num_str = str(abs(num))\n \n even_count = 0\n odd_count = 0\n \n for digit in num_str:\n if int(digit) % 2 == 0:\n even_count += 1\n else:\n odd_count += 1\n \n return (even_count, odd_count)"}
{"task_id": "HumanEval/156", "solution": "def int_to_mini_roman(number):\n \"\"\"\n Given a positive integer, obtain its roman numeral equivalent as a string,\n and return it in lowercase.\n Restrictions: 1 <= num <= 1000\n\n Examples:\n >>> int_to_mini_roman(19) == 'xix'\n >>> int_to_mini_roman(152) == 'clii'\n >>> int_to_mini_roman(426) == 'cdxxvi'\n \"\"\"\n # Define the mapping of integer values to Roman numeral symbols in descending order.\n # We include the subtractive combinations (like 900, 400, etc.) as distinct entries.\n roman_map = [\n (1000, 'm'),\n (900, 'cm'),\n (500, 'd'),\n (400, 'cd'),\n (100, 'c'),\n (90, 'xc'),\n (50, 'l'),\n (40, 'xl'),\n (10, 'x'),\n (9, 'ix'),\n (5, 'v'),\n (4, 'iv'),\n (1, 'i')\n ]\n \n result = []\n \n # Iterate through the map and subtract values from the number while appending symbols.\n for value, symbol in roman_map:\n while number >= value:\n result.append(symbol)\n number -= value\n \n return \"\".join(result)"}
{"task_id": "HumanEval/157", "solution": "def right_angle_triangle(a, b, c):\n '''\n Given the lengths of the three sides of a triangle. Return True if the three\n sides form a right-angled triangle, False otherwise.\n A right-angled triangle is a triangle in which one angle is right angle or \n 90 degree.\n Example:\n right_angle_triangle(3, 4, 5) == True\n right_angle_triangle(1, 2, 3) == False\n '''\n # A triangle is right-angled if the square of the longest side (hypotenuse)\n # is equal to the sum of the squares of the other two sides.\n \n # First, we sort the sides so that the largest value is always at the end.\n sides = sorted([a, b, c])\n \n # Check the Pythagorean theorem: a^2 + b^2 = c^2\n return (sides[0]**2 + sides[1]**2) == sides[2]**2"}
{"task_id": "HumanEval/158", "solution": "def find_max(words):\n \"\"\"Write a function that accepts a list of strings.\n The list contains different words. Return the word with maximum number\n of unique characters. If multiple strings have maximum number of unique\n characters, return the one which comes first in lexicographical order.\n\n find_max([\"name\", \"of\", \"string\"]) == \"string\"\n find_max([\"name\", \"enam\", \"game\"]) == \"enam\"\n find_max([\"aaaaaaa\", \"bb\" ,\"cc\"]) == \"aaaaaaa\"\n \"\"\"\n if not words:\n return \"\"\n\n # Initialize with the first word in the list\n best_word = words[0]\n max_unique_count = len(set(best_word))\n\n for i in range(1, len(words)):\n current_word = words[i]\n current_unique_count = len(set(current_word))\n\n # Condition 1: Current word has more unique characters than the current best\n if current_unique_count > max_unique_count:\n max_unique_count = current_unique_count\n best_word = current_word\n \n # Condition 2: Tie in unique character count, use lexicographical order\n elif current_unique_count == max_unique_count:\n if current_word < best_word:\n best_word = current_word\n\n return best_word"}
{"task_id": "HumanEval/159", "solution": "def eat(number, need, remaining):\n \"\"\"\n You're a hungry rabbit, and you already have eaten a certain number of carrots,\n but now you need to eat more carrots to complete the day's meals.\n you should return an array of [ total number of eaten carrots after your meals,\n the number of carrots left after your meals ]\n if there are not enough remaining carrots, you will eat all remaining carrots, but will still be hungry.\n \n Example:\n * eat(5, 6, 10) -> [11, 4]\n * eat(4, 8, 9) -> [12, 1]\n * eat(1, 10, 10) -> [11, 0]\n * eat(2, 11, 5) -> [7, 0]\n \n Variables:\n @number : integer\n the number of carrots that you have eaten.\n @need : integer\n the number of carrots that you need to eat.\n @remaining : integer\n the number of remaining carrots thet exist in stock\n \n Constrain:\n * 0 <= number <= 1000\n * 0 <= need <= 1000\n * 0 <= remaining <= 1000\n\n Have fun :)\n \"\"\"\n # Determine how many carrots the rabbit actually eats.\n # It's either the amount needed or all that is remaining, whichever is smaller.\n amount_eaten = min(need, remaining)\n \n # Calculate total eaten: previous count + what was just eaten\n total_eaten = number + amount_eaten\n \n # Calculate leftover carrots in stock\n leftover = remaining - amount_eaten\n \n return [total_eaten, leftover]"}
{"task_id": "HumanEval/160", "solution": "def do_algebra(operator, operand):\n \"\"\"\n Given two lists operator, and operand. The first list has basic algebra operations, and \n the second list is a list of integers. Use the two given lists to build the algebric \n expression and return the evaluation of this expression.\n\n The basic algebra operations:\n Addition ( + ) \n Subtraction ( - ) \n Multiplication ( * ) \n Floor division ( // ) \n Exponentiation ( ** ) \n\n Example:\n operator = ['+', '*', '-']\n operand = [2, 3, 4, 5]\n result = 2 + 3 * 4 - 5\n => result = 9\n \"\"\"\n # Initialize the expression string with the first operand\n expression = str(operand[0])\n \n # Interleave operators and operands to build the full algebraic string\n for i in range(len(operator)):\n # Append the operator followed by the next operand\n expression += f\" {operator[i]} {operand[i+1]}\"\n \n # eval() evaluates the string as a Python expression, \n # respecting standard mathematical order of operations (PEMDAS)\n return eval(expression)"}
{"task_id": "HumanEval/161", "solution": "def solve(s):\n \"\"\"You are given a string s.\n if s[i] is a letter, reverse its case from lower to upper or vise versa, \n otherwise keep it as it is.\n If the string contains no letters, reverse the string.\n The function should return the resulted string.\n \"\"\"\n # Check if there are any alphabetic characters in the string\n has_letters = any(char.isalpha() for char in s)\n \n if has_letters:\n # .swapcase() converts uppercase to lowercase and vice versa, \n # while leaving non-alphabetic characters untouched.\n return s.swapcase()\n else:\n # If no letters are present, return the reversed string using slicing\n return s[::-1]"}
{"task_id": "HumanEval/162", "solution": "import hashlib\ndef string_to_md5(text):\n \"\"\"\n Given a string 'text', return its md5 hash equivalent string.\n If 'text' is an empty string, return None.\n\n >>> string_to_md5('Hello world') == '3e25960a79dbc69b674cd4ec67a72c62'\n True\n \"\"\"\n # Check if the input text is an empty string\n if text == \"\":\n return None\n \n # MD5 requires bytes, so we encode the string to utf-8 first\n encoded_text = text.encode('utf-8')\n \n # Create the md5 hash object and return the hexadecimal representation\n return hashlib.md5(encoded_text).hexdigest()"}
{"task_id": "HumanEval/163", "solution": "def generate_integers(a, b):\n \"\"\"\n Given two positive integers a and b, return the even digits between a\n and b, in ascending order.\n\n For example:\n generate_integers(2, 8) => [2, 4, 6, 8]\n generate_integers(8, 2) => [2, 4, 6, 8]\n generate_integers(10, 14) => []\n \"\"\"\n # Determine the range boundaries regardless of order\n start = min(a, b)\n end = max(a, b)\n \n result = []\n # Iterate through the range inclusive of both endpoints\n for i in range(start, end + 1):\n # A 'digit' is a single-digit integer (0-9).\n # We check if the number is within that range and if it is even.\n if 0 <= i <= 9 and i % 2 == 0:\n result.append(i)\n \n return result"}
=== raw completions jsonl ===
{"task_id": "HumanEval/0", "solution": "```python\nfrom typing import List\n\n\ndef has_close_elements(numbers: List[float], threshold: float) -> bool:\n \"\"\" Check if in given list of numbers, are any two numbers closer to each other than\n given threshold.\n >>> has_close_elements([1.0, 2.0, 3.0], 0.5)\n False\n >>> has_close_elements([1.0, 2.8, 3.0, 4.0, 5.0, 2.0], 0.3)\n True\n \"\"\"\n # Sort the numbers to ensure that the closest elements are adjacent\n sorted_numbers = sorted(numbers)\n \n # Iterate through the sorted list and check the difference between neighbors\n for i in range(len(sorted_numbers) - 1):\n if sorted_numbers[i + 1] - sorted_numbers[i] < threshold:\n return True\n \n return False\n\n\nif __name__ == \"__main__\":\n # Test cases provided in the docstring\n print(f\"Test 1: {has_close_elements([1.0, 2.0, 3.0], 0.5)}\") # Expected: False\n print(f\"Test 2: {has_close_elements([1.0, 2.8, 3.0, 4.0, 5.0, 2.0], 0.3)}\") # Expected: True\n \n # Additional test cases\n print(f\"Test 3 (Empty): {has_close_elements([], 1.0)}\") # Expected: False\n print(f\"Test 4 (Single): {has_close_elements([1.0], 1.0)}\") # Expected: False\n print(f\"Test 5 (Exact threshold): {has_close_elements([1.0, 2.0], 1.0)}\") # Expected: False (must be closer than)\n```"}
{"task_id": "HumanEval/1", "solution": "```python\nfrom typing import List\n\n\ndef separate_paren_groups(paren_string: str) -> List[str]:\n \"\"\" Input to this function is a string containing multiple groups of nested parentheses. Your goal is to\n separate those group into separate strings and return the list of those.\n Separate groups are balanced (each open brace is properly closed) and not nested within each other\n Ignore any spaces in the input string.\n >>> separate_paren_groups('( ) (( )) (( )( ))')\n ['()', '(())', '(()())']\n \"\"\"\n # Remove all whitespace from the input string as per requirements\n cleaned_string = \"\".join(paren_string.split())\n \n result = []\n current_group = []\n balance = 0\n \n for char in cleaned_string:\n if char == '(':\n balance += 1\n current_group.append(char)\n elif char == ')':\n balance -= 1\n current_group.append(char)\n \n # When balance returns to 0, we have completed a top-level group\n if balance == 0:\n result.append(\"\".join(current_group))\n current_group = []\n \n return result\n\n\nif __name__ == \"__main__\":\n # Test cases\n test_cases = [\n ('( ) (( )) (( )( ))', ['()', '(())', '(()())']),\n ('((()))', ['((()))']),\n ('() () ()', ['()', '()', '()']),\n (' ( ( ) ) ( ) ', ['(())', '()']),\n ('', []),\n ]\n\n for input_str, expected in test_cases:\n actual = separate_paren_groups(input_str)\n assert actual == expected, f\"Failed on {input_str}: expected {expected}, got {actual}\"\n \n print(\"All tests passed!\")\n```"}
{"task_id": "HumanEval/2", "solution": "```python\ndef truncate_number(number: float) -> float:\n \"\"\" Given a positive floating point number, it can be decomposed into\n and integer part (largest integer smaller than given number) and decimals\n (leftover part always smaller than 1).\n\n Return the decimal part of the number.\n >>> truncate_number(3.5)\n 0.5\n \"\"\"\n return number - int(number)\n\nif __name__ == \"__main__\":\n # Test cases\n print(f\"truncate_number(3.5) -> {truncate_number(3.5)}\") # Expected: 0.5\n print(f\"truncate_number(4.25) -> {truncate_number(4.25)}\") # Expected: 0.25\n print(f\"truncate_number(1.0) -> {truncate_number(1.0)}\") # Expected: 0.0\n print(f\"truncate_number(0.75) -> {truncate_number(0.75)}\") # Expected: 0.75\n```"}
{"task_id": "HumanEval/3", "solution": "```python\nfrom typing import List\n\n\ndef below_zero(operations: List[int]) -> bool:\n \"\"\" You're given a list of deposit and withdrawal operations on a bank account that starts with\n zero balance. Your task is to detect if at any point the balance of account fallls below zero, and\n at that point function should return True. Otherwise it should return False.\n >>> below_zero([1, 2, 3])\n False\n >>> below_zero([1, 2, -4, 5])\n True\n \"\"\"\n balance = 0\n for op in operations:\n balance += op\n if balance < 0:\n return True\n return False\n\n\nif __name__ == \"__main__\":\n # Test cases from the docstring\n assert below_zero([1, 2, 3]) == False\n assert below_zero([1, 2, -4, 5]) == True\n \n # Additional test cases\n assert below_zero([]) == False # Empty list should not fall below zero\n assert below_zero([-1]) == True # Immediate drop below zero\n assert below_zero([10, -10, 5]) == False # Hits exactly zero but doesn't go below\n assert below_zero([10, -11]) == True # Drops below zero at the end\n \n print(\"All tests passed!\")\n```"}
{"task_id": "HumanEval/4", "solution": "```python\nfrom typing import List\n\n\ndef mean_absolute_deviation(numbers: List[float]) -> float:\n \"\"\" For a given list of input numbers, calculate Mean Absolute Deviation\n around the mean of this dataset.\n Mean Absolute Deviation is the average absolute difference between each\n element and a centerpoint (mean in this case):\n MAD = average | x - x_mean |\n >>> mean_absolute_deviation([1.0, 2.0, 3.0, 4.0])\n 1.0\n \"\"\"\n if not numbers:\n return 0.0\n\n # Calculate the arithmetic mean of the dataset\n mean = sum(numbers) / len(numbers)\n \n # Calculate the sum of absolute differences between each element and the mean\n total_absolute_deviation = sum(abs(x - mean) for x in numbers)\n \n # Return the average of these absolute differences\n return total_absolute_deviation / len(numbers)\n\n\nif __name__ == \"__main__\":\n # Test case from docstring\n test_data = [1.0, 2.0, 3.0, 4.0]\n result = mean_absolute_deviation(test_data)\n print(f\"The Mean Absolute Deviation of {test_data} is: {result}\")\n \n # Additional test case\n test_data_2 = [10, 15, 10, 20] # Mean = 13.75\n # |10-13.75|=3.75, |15-13.75|=1.25, |10-13.75|=3.75, |20-13.75|=6.25\n # Sum = 15.0 / 4 = 3.75\n print(f\"The Mean Absolute Deviation of {test_data_2} is: {mean_absolute_deviation(test_data_2)}\")\n```"}
{"task_id": "HumanEval/5", "solution": "```python\nfrom typing import List\n\n\ndef intersperse(numbers: List[int], delimeter: int) -> List[int]:\n \"\"\" Insert a number 'delimeter' between every two consecutive elements of input list `numbers'\n >>> intersperse([], 4)\n []\n >>> intersperse([1, 2, 3], 4)\n [1, 4, 2, 4, 3]\n \"\"\"\n if not numbers:\n return []\n\n result = []\n for i in range(len(numbers)):\n result.append(numbers[i])\n # Append the delimiter only if we are not at the last element\n if i < len(numbers) - 1:\n result.append(delimeter)\n \n return result\n\n\nif __name__ == \"__main__\":\n # Test cases to verify functionality\n print(f\"Test 1 (Empty): {intersperse([], 4)} Expected: []\")\n print(f\"Test 2 (Single): {intersperse([1], 4)} Expected: [1]\")\n print(f\"Test 3 (Multiple): {intersperse([1, 2, 3], 4)} Expected: [1, 4, 2, 4, 3]\")\n```"}
{"task_id": "HumanEval/6", "solution": "```python\nfrom typing import List\n\n\ndef parse_nested_parens(paren_string: str) -> List[int]:\n \"\"\" Input to this function is a string represented multiple groups for nested parentheses separated by spaces.\n For each of the group, output the deepest level of nesting of parentheses.\n E.g. (()()) has maximum two levels of nesting while ((())) has three.\n\n >>> parse_nested_parens('(()()) ((())) () ((())()())')\n [2, 3, 1, 3]\n \"\"\"\n # Split the input string into individual groups based on spaces\n groups = paren_string.split()\n results = []\n\n for group in groups:\n current_depth = 0\n max_depth = 0\n \n # Iterate through each character in the current parenthesis group\n for char in group:\n if char == '(':\n current_depth += 1\n # Update max_depth if the current nesting level is the deepest seen so far\n if current_depth > max_depth:\n max_depth = current_depth\n elif char == ')':\n current_depth -= 1\n \n results.append(max_depth)\n\n return results\n\n\nif __name__ == \"__main__\":\n # Test the function with the provided example\n test_input = '(()()) ((())) () ((())()())'\n expected_output = [2, 3, 1, 3]\n result = parse_nested_parens(test_input)\n print(f\"Input: {test_input}\")\n print(f\"Expected: {expected_output}\")\n print(f\"Result: {result}\")\n assert result == expected_output, \"The function output does not match the expected output.\"\n```"}
{"task_id": "HumanEval/7", "solution": "```python\nfrom typing import List\n\n\ndef filter_by_substring(strings: List[str], substring: str) -> List[str]:\n \"\"\" Filter an input list of strings only for ones that contain given substring\n >>> filter_by_substring([], 'a')\n []\n >>> filter_by_substring(['abc', 'bacd', 'cde', 'array'], 'a')\n ['abc', 'bacd', 'array']\n \"\"\"\n return [s for s in strings if substring in s]\n\n\nif __name__ == \"__main__\":\n # Test cases to verify the function\n test_cases = [\n ([], 'a', []),\n (['abc', 'bacd', 'cde', 'array'], 'a', ['abc', 'bacd', 'array']),\n (['hello', 'world', 'python'], 'o', ['hello', 'world', 'python']),\n (['apple', 'banana', 'cherry'], 'z', []),\n ]\n\n for strings, sub, expected in test_cases:\n result = filter_by_substring(strings, sub)\n assert result == expected, f\"Failed for {strings}, {sub}: expected {expected}, got {result}\"\n \n print(\"All tests passed!\")\n```"}
{"task_id": "HumanEval/8", "solution": "```python\nfrom typing import List, Tuple\n\n\ndef sum_product(numbers: List[int]) -> Tuple[int, int]:\n \"\"\" For a given list of integers, return a tuple consisting of a sum and a product of all the integers in a list.\n Empty sum should be equal to 0 and empty product should be equal to 1.\n >>> sum_product([])\n (0, 1)\n >>> sum_product([1, 2, 3, 4])\n (10, 24)\n \"\"\"\n total_sum = 0\n total_product = 1\n \n for num in numbers:\n total_sum += num\n total_product *= num\n \n return (total_sum, total_product)\n\n\nif __name__ == \"__main__\":\n # Test cases to verify the function\n test_cases = [\n ([], (0, 1)),\n ([1, 2, 3, 4], (10, 24)),\n ([5, 10], (15, 50)),\n ([-1, 1], (0, -1)),\n ([0, 5], (5, 0)),\n ]\n\n for input_list, expected in test_cases:\n result = sum_product(input_list)\n assert result == expected, f\"Failed for {input_list}: expected {expected}, got {result}\"\n print(f\"sum_product({input_list}) -> {result} (Success)\")\n```"}
{"task_id": "HumanEval/9", "solution": "```python\nfrom typing import List\n\ndef rolling_max(numbers: List[int]) -> List[int]:\n \"\"\" From a given list of integers, generate a list of rolling maximum element found until given moment\n in the sequence.\n >>> rolling_max([1, 2, 3, 2, 3, 4, 2])\n [1, 2, 3, 3, 3, 4, 4]\n \"\"\"\n if not numbers:\n return []\n\n result = []\n # Initialize current_max with the first element of the list\n current_max = numbers[0]\n \n for num in numbers:\n # Update current_max if the current number is larger\n if num > current_max:\n current_max = num\n result.append(current_max)\n \n return result\n\nif __name__ == \"__main__\":\n # Test cases\n test_cases = [\n ([1, 2, 3, 2, 3, 4, 2], [1, 2, 3, 3, 3, 4, 4]),\n ([5, 4, 3, 2, 1], [5, 5, 5, 5, 5]),\n ([1, 2, 3, 4, 5], [1, 2, 3, 4, 5]),\n ([-1, -5, -2, -10, 0], [-1, -1, -1, -1, 0]),\n ([], []),\n ([10], [10]),\n ]\n\n for input_list, expected in test_cases:\n actual = rolling_max(input_list)\n assert actual == expected, f\"Failed for {input_list}: expected {expected}, got {actual}\"\n \n print(\"All tests passed!\")\n```"}
{"task_id": "HumanEval/10", "solution": "```python\ndef is_palindrome(string: str) -> bool:\n \"\"\" Test if given string is a palindrome \"\"\"\n return string == string[::-1]\n\n\ndef make_palindrome(string: str) -> str:\n \"\"\" Find the shortest palindrome that begins with a supplied string.\n Algorithm idea is simple:\n - Find the longest postfix of supplied string that is a palindrome.\n - Append to the end of the string reverse of a string prefix that comes before the palindromic suffix.\n >>> make_palindrome('')\n ''\n >>> make_palindrome('cat')\n 'catac'\n >>> make_palindrome('cata')\n 'catac'\n \"\"\"\n if not string:\n return \"\"\n\n # We look for the longest palindromic suffix.\n # By iterating from the start of the string (index 0), \n # the first index 'i' that makes string[i:] a palindrome \n # will give us the longest possible palindromic suffix.\n for i in range(len(string)):\n suffix = string[i:]\n if is_palindrome(suffix):\n # The part of the string before the palindromic suffix\n prefix = string[:i]\n # Append the reverse of that prefix to the original string\n return string + prefix[::-1]\n \n return string # Fallback, though logic above covers all cases\n\n\nif __name__ == \"__main__\":\n # Test cases from docstring\n test_cases = [\n (\"\", \"\"),\n (\"cat\", \"catac\"),\n (\"cata\", \"catac\"),\n (\"racecar\", \"racecar\"),\n (\"apple\", \"applelppa\"), # 'e' is the longest palindromic suffix, prefix 'appl'\n ]\n\n for input_str, expected in test_cases:\n result = make_palindrome(input_str)\n print(f\"Input: '{input_str}' | Expected: '{expected}' | Result: '{result}' | {'Pass' if result == expected else 'Fail'}\")\n```"}
{"task_id": "HumanEval/11", "solution": "```python\nfrom typing import List\n\n\ndef string_xor(a: str, b: str) -> str:\n \"\"\" Input are two strings a and b consisting only of 1s and 0s.\n Perform binary XOR on these inputs and return result also as a string.\n >>> string_xor('010', '110')\n '100'\n \"\"\"\n # Use zip to iterate through both strings simultaneously.\n # In binary, XOR is 1 if the bits are different and 0 if they are the same.\n return \"\".join('1' if x != y else '0' for x, y in zip(a, b))\n\n\nif __name__ == \"__main__\":\n # Test cases to verify the function\n test_cases = [\n ('010', '110', '100'),\n ('111', '111', '000'),\n ('000', '000', '000'),\n ('1010', '0101', '1111'),\n ('1', '0', '1'),\n ('1', '1', '0'),\n ]\n\n for a, b, expected in test_cases:\n result = string_xor(a, b)\n assert result == expected, f\"Failed on {a}, {b}: expected {expected}, got {result}\"\n \n print(\"All tests passed!\")\n```"}
{"task_id": "HumanEval/12", "solution": "```python\nfrom typing import List, Optional\n\n\ndef longest(strings: List[str]) -> Optional[str]:\n \"\"\" Out of list of strings, return the longest one. Return the first one in case of multiple\n strings of the same length. Return None in case the input list is empty.\n >>> longest([])\n None\n >>> longest(['a', 'b', 'c'])\n 'a'\n >>> longest(['a', 'bb', 'ccc'])\n 'ccc'\n \"\"\"\n if not strings:\n return None\n \n # Python's max() function is stable, meaning if multiple elements have the \n # same key value (length in this case), it returns the first one encountered.\n return max(strings, key=len)\n\n\nif __name__ == \"__main__\":\n # Test cases to verify functionality\n print(f\"Test empty: {longest([])}\") # Expected: None\n print(f\"Test same length: {longest(['a', 'b', 'c'])}\") # Expected: 'a'\n print(f\"Test different lengths: {longest(['a', 'bb', 'ccc'])}\") # Expected: 'ccc'\n print(f\"Test tie-break: {longest(['apple', 'pear', 'peach'])}\") # Expected: 'apple'\n```"}
{"task_id": "HumanEval/13", "solution": "```python\ndef greatest_common_divisor(a: int, b: int) -> int:\n \"\"\" Return a greatest common divisor of two integers a and b\n >>> greatest_common_divisor(3, 5)\n 1\n >>> greatest_common_divisor(25, 15)\n 5\n \"\"\"\n while b:\n a, b = b, a % b\n return a\n\nif __name__ == \"__main__\":\n # Test cases to verify the function\n test_cases = [\n (3, 5, 1),\n (25, 15, 5),\n (48, 18, 6),\n (101, 10, 1),\n (0, 5, 5),\n ]\n\n for a, b, expected in test_cases:\n result = greatest_common_divisor(a, b)\n print(f\"GCD of {a} and {b}: Expected {expected}, Got {result} - {'PASSED' if result == expected else 'FAILED'}\")\n```"}
{"task_id": "HumanEval/14", "solution": "```python\nfrom typing import List\n\n\ndef all_prefixes(string: str) -> List[str]:\n \"\"\" Return list of all prefixes from shortest to longest of the input string\n >>> all_prefixes('abc')\n ['a', 'ab', 'abc']\n \"\"\"\n return [string[:i] for i in range(1, len(string) + 1)]\n\n\nif __name__ == \"__main__\":\n # Test cases to verify the function\n test_cases = {\n \"abc\": [\"a\", \"ab\", \"abc\"],\n \"hello\": [\"h\", \"he\", \"hel\", \"hell\", \"hello\"],\n \"\": [],\n \"a\": [\"a\"],\n }\n\n for input_str, expected in test_cases.items():\n result = all_prefixes(input_str)\n assert result == expected, f\"Failed for '{input_str}': expected {expected}, got {result}\"\n \n print(\"All tests passed!\")\n```"}
{"task_id": "HumanEval/15", "solution": "```python\ndef string_sequence(n: int) -> str:\n \"\"\" Return a string containing space-delimited numbers starting from 0 upto n inclusive.\n >>> string_sequence(0)\n '0'\n >>> string_sequence(5)\n '0 1 2 3 4 5'\n \"\"\"\n # range(n + 1) generates integers from 0 up to and including n.\n # map(str, ...) converts each integer in that range into a string.\n # ' '.join(...) concatenates those strings with a space between them.\n return ' '.join(map(str, range(n + 1)))\n\nif __name__ == \"__main__\":\n # Test cases from the docstring\n print(f\"Test n=0: {string_sequence(0)}\") # Expected: '0'\n print(f\"Test n=5: {string_sequence(5)}\") # Expected: '0 1 2 3 4 5'\n```"}
{"task_id": "HumanEval/16", "solution": "```python\ndef count_distinct_characters(string: str) -> int:\n \"\"\" Given a string, find out how many distinct characters (regardless of case) does it consist of\n >>> count_distinct_characters('xyzXYZ')\n 3\n >>> count_distinct_characters('Jerry')\n 4\n \"\"\"\n # Convert the string to lowercase to ensure case-insensitivity\n lowered_string = string.lower()\n \n # Use a set to store unique characters and return its length\n return len(set(lowered_string))\n\nif __name__ == \"__main__\":\n # Test cases provided in the docstring\n print(f\"Test 'xyzXYZ': {count_distinct_characters('xyzXYZ')}\") # Expected: 3\n print(f\"Test 'Jerry': {count_distinct_characters('Jerry')}\") # Expected: 4\n \n # Additional test cases\n print(f\"Test 'abcABC123': {count_distinct_characters('abcABC123')}\") # Expected: 6 (a, b, c, 1, 2, 3)\n print(f\"Test '': {count_distinct_characters('')}\") # Expected: 0\n```"}
{"task_id": "HumanEval/17", "solution": "```python\nfrom typing import List\n\n\ndef parse_music(music_string: str) -> List[int]:\n \"\"\" Input to this function is a string representing musical notes in a special ASCII format.\n Your task is to parse this string and return list of integers corresponding to how many beats does each\n not last.\n\n Here is a legend:\n 'o' - whole note, lasts four beats\n 'o|' - half note, lasts two beats\n '.|' - quater note, lasts one beat\n\n >>> parse_music('o o| .| o| o| .| .| .| .| o o')\n [4, 2, 1, 2, 2, 1, 1, 1, 1, 4, 4]\n \"\"\"\n # Define the mapping of note symbols to their beat values\n note_map = {\n 'o': 4,\n 'o|': 2,\n '.|': 1\n }\n \n # Split the input string by whitespace to isolate each note token\n tokens = music_string.split()\n \n # Map each token to its corresponding beat value using the dictionary\n beats = [note_map[token] for token in tokens]\n \n return beats\n\n\nif __name__ == \"__main__\":\n # Test case from the docstring\n input_str = 'o o| .| o| o| .| .| .| .| o o'\n expected_output = [4, 2, 1, 2, 2, 1, 1, 1, 1, 4, 4]\n result = parse_music(input_str)\n \n print(f\"Input: {input_str}\")\n print(f\"Result: {result}\")\n print(f\"Expected: {expected_output}\")\n assert result == expected_output, \"The output does not match the expected result.\"\n```"}
{"task_id": "HumanEval/18", "solution": "```python\ndef how_many_times(string: str, substring: str) -> int:\n \"\"\" Find how many times a given substring can be found in the original string. Count overlaping cases.\n >>> how_many_times('', 'a')\n 0\n >>> how_many_times('aaa', 'a')\n 3\n >>> how_many_times('aaaa', 'aa')\n 3\n \"\"\"\n if not substring:\n return 0\n \n count = 0\n # Iterate through the string and check slices of the same length as the substring\n for i in range(len(string) - len(substring) + 1):\n if string[i : i + len(substring)] == substring:\n count += 1\n \n return count\n\nif __name__ == \"__main__\":\n # Test cases from the docstring\n print(f\"Test 1 ('', 'a'): {how_many_times('', 'a')} (Expected: 0)\")\n print(f\"Test 2 ('aaa', 'a'): {how_many_times('aaa', 'a')} (Expected: 3)\")\n print(f\"Test 3 ('aaaa', 'aa'): {how_many_times('aaaa', 'aa')} (Expected: 3)\")\n```"}
{"task_id": "HumanEval/19", "solution": "```python\nfrom typing import List\n\n\ndef sort_numbers(numbers: str) -> str:\n \"\"\" Input is a space-delimited string of numberals from 'zero' to 'nine'.\n Valid choices are 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight' and 'nine'.\n Return the string with numbers sorted from smallest to largest\n >>> sort_numbers('three one five')\n 'one three five'\n \"\"\"\n # Mapping of number words to their integer values for sorting purposes\n num_map = {\n 'zero': 0,\n 'one': 1,\n 'two': 2,\n 'three': 3,\n 'four': 4,\n 'five': 5,\n 'six': 6,\n 'seven': 7,\n 'eight': 8,\n 'nine': 9\n }\n \n # Split the input string into a list of words\n words = numbers.split()\n \n # Sort the words using the integer value from the map as the sort key\n sorted_words = sorted(words, key=lambda x: num_map[x])\n \n # Join the sorted list back into a space-delimited string\n return ' '.join(sorted_words)\n\nif __name__ == \"__main__\":\n # Test cases\n print(f\"Test 1: {sort_numbers('three one five')} (Expected: 'one three five')\")\n print(f\"Test 2: {sort_numbers('nine zero two')} (Expected: 'zero two nine')\")\n print(f\"Test 3: {sort_numbers('five four three two one')} (Expected: 'one two three four five')\")\n```"}
{"task_id": "HumanEval/20", "solution": "```python\nfrom typing import List, Tuple\n\ndef find_closest_elements(numbers: List[float]) -> Tuple[float, float]:\n \"\"\" From a supplied list of numbers (of length at least two) select and return two that are the closest to each\n other and return them in order (smaller number, larger number).\n >>> find_closest_elements([1.0, 2.0, 3.0, 4.0, 5.0, 2.2])\n (2.0, 2.2)\n >>> find_closest_elements([1.0, 2.0, 3.0, 4.0, 5.0, 2.0])\n (2.0, 2.0)\n \"\"\"\n # First, sort the numbers to ensure that the closest elements are adjacent\n sorted_nums = sorted(numbers)\n \n # Initialize variables to track the minimum difference and the resulting pair\n # We start with the first two elements as the initial baseline\n min_diff = float('inf')\n closest_pair = (sorted_nums[0], sorted_nums[1])\n \n # Iterate through the sorted list and compare adjacent pairs\n for i in range(len(sorted_nums) - 1):\n current_num = sorted_nums[i]\n next_num = sorted_nums[i + 1]\n diff = next_num - current_num\n \n if diff < min_diff:\n min_diff = diff\n closest_pair = (current_num, next_num)\n \n return closest_pair\n\nif __name__ == \"__main__\":\n # Test cases provided in the docstring\n print(find_closest_elements([1.0, 2.0, 3.0, 4.0, 5.0, 2.2])) # Expected: (2.0, 2.2)\n print(find_closest_elements([1.0, 2.0, 3.0, 4.0, 5.0, 2.0])) # Expected: (2.0, 2.0)\n```"}
{"task_id": "HumanEval/21", "solution": "```python\nfrom typing import List\n\n\ndef rescale_to_unit(numbers: List[float]) -> List[float]:\n \"\"\" Given list of numbers (of at least two elements), apply a linear transform to that list,\n such that the smallest number will become 0 and the largest will become 1\n >>> rescale_to_unit([1.0, 2.0, 3.0, 4.0, 5.0])\n [0.0, 0.25, 0.5, 0.75, 1.0]\n \"\"\"\n min_val = min(numbers)\n max_val = max(numbers)\n diff = max_val - min_val\n\n # Handle the case where all elements in the list are the same to avoid division by zero\n if diff == 0:\n return [0.0] * len(numbers)\n\n return [(x - min_val) / diff for x in numbers]\n\n\nif __name__ == \"__main__\":\n # Test case from docstring\n test_input = [1.0, 2.0, 3.0, 4.0, 5.0]\n expected_output = [0.0, 0.25, 0.5, 0.75, 1.0]\n result = rescale_to_unit(test_input)\n print(f\"Input: {test_input} -> Result: {result}\")\n assert result == expected_output\n\n # Additional test case with different range\n test_input_2 = [10.0, 20.0, 30.0]\n expected_output_2 = [0.0, 0.5, 1.0]\n result_2 = rescale_to_unit(test_input_2)\n print(f\"Input: {test_input_2} -> Result: {result_2}\")\n assert result_2 == expected_output_2\n```"}
{"task_id": "HumanEval/22", "solution": "```python\nfrom typing import List, Any\n\n\ndef filter_integers(values: List[Any]) -> List[int]:\n \"\"\" Filter given list of any python values only for integers\n >>> filter_integers(['a', 3.14, 5])\n [5]\n >>> filter_integers([1, 2, 3, 'abc', {}, []])\n [1, 2, 3]\n \"\"\"\n # We use type(x) is int instead of isinstance(x, int) because \n # in Python, bools are a subclass of ints (isinstance(True, int) is True).\n return [x for x in values if type(x) is int]\n\n\nif __name__ == \"__main__\":\n import doctest\n doctest.testmod()\n```"}
{"task_id": "HumanEval/23", "solution": "```python\ndef strlen(string: str) -> int:\n \"\"\" Return length of given string\n >>> strlen('')\n 0\n >>> strlen('abc')\n 3\n \"\"\"\n return len(string)\n\nif __name__ == \"__main__\":\n import doctest\n # This will run the examples provided in the docstring to verify correctness\n result = doctest.testmod()\n if result.failed == 0:\n print(\"All tests passed!\")\n```"}
{"task_id": "HumanEval/24", "solution": "```python\ndef largest_divisor(n: int) -> int:\n \"\"\" For a given number n, find the largest number that divides n evenly, smaller than n\n >>> largest_divisor(15)\n 5\n \"\"\"\n # The largest divisor of n (smaller than n) is equal to n divided by \n # the smallest prime factor of n.\n # We iterate from 2 up to the square root of n to find the smallest factor.\n for i in range(2, int(n**0.5) + 1):\n if n % i == 0:\n return n // i\n \n # If no divisor is found between 2 and sqrt(n), then n is prime (or n=1).\n # In the case of a prime number, the only divisor smaller than itself is 1.\n return 1\n\nif __name__ == \"__main__\":\n import doctest\n doctest.testmod()\n \n # Additional test cases\n print(f\"Largest divisor of 15: {largest_divisor(15)}\") # Expected: 5\n print(f\"Largest divisor of 7: {largest_divisor(7)}\") # Expected: 1\n print(f\"Largest divisor of 100: {largest_divisor(100)}\") # Expected: 50\n```"}
{"task_id": "HumanEval/25", "solution": "```python\nfrom typing import List\n\n\ndef factorize(n: int) -> List[int]:\n \"\"\" Return list of prime factors of given integer in the order from smallest to largest.\n Each of the factors should be listed number of times corresponding to how many times it appeares in factorization.\n Input number should be equal to the product of all factors\n >>> factorize(8)\n [2, 2, 2]\n >>> factorize(25)\n [5, 5]\n >>> factorize(70)\n [2, 5, 7]\n \"\"\"\n factors = []\n # Handle the smallest prime factor 2 separately to allow stepping by 2 in the loop\n while n % 2 == 0:\n factors.append(2)\n n //= 2\n \n # Check odd numbers starting from 3 up to the square root of n\n d = 3\n while d * d <= n:\n while n % d == 0:\n factors.append(d)\n n //= d\n d += 2\n \n # If n is still greater than 1, then the remaining n must be prime\n if n > 1:\n factors.append(n)\n \n return factors\n\n\nif __name__ == \"__main__\":\n # Test cases from docstring\n print(f\"factorize(8) -> {factorize(8)}\") # Expected: [2, 2, 2]\n print(f\"factorize(25) -> {factorize(25)}\") # Expected: [5, 5]\n print(f\"factorize(70) -> {factorize(70)}\") # Expected: [2, 5, 7]\n```"}
{"task_id": "HumanEval/26", "solution": "```python\nfrom typing import List\nfrom collections import Counter\n\ndef remove_duplicates(numbers: List[int]) -> List[int]:\n \"\"\" From a list of integers, remove all elements that occur more than once.\n Keep order of elements left the same as in the input.\n >>> remove_duplicates([1, 2, 3, 2, 4])\n [1, 3, 4]\n \"\"\"\n # Count occurrences of each number in the list\n counts = Counter(numbers)\n \n # Return a new list containing only elements that appeared exactly once,\n # preserving the original order.\n return [x for x in numbers if counts[x] == 1]\n\nif __name__ == \"__main__\":\n # Test case from docstring\n test_input = [1, 2, 3, 2, 4]\n expected_output = [1, 3, 4]\n result = remove_duplicates(test_input)\n print(f\"Input: {test_input} | Result: {result} | Expected: {expected_output}\")\n assert result == expected_output\n\n # Additional test cases\n assert remove_duplicates([1, 1, 1]) == []\n assert remove_duplicates([1, 2, 3]) == [1, 2, 3]\n assert remove_duplicates([]) == []\n print(\"All tests passed!\")\n```"}
{"task_id": "HumanEval/27", "solution": "```python\ndef flip_case(string: str) -> str:\n \"\"\" For a given string, flip lowercase characters to uppercase and uppercase to lowercase.\n >>> flip_case('Hello')\n 'hELLO'\n \"\"\"\n return string.swapcase()\n\nif __name__ == \"__main__\":\n # Test cases\n test_cases = [\"Hello\", \"python\", \"WORLD\", \"PyThOn\", \"123!@#\"]\n for tc in test_cases:\n print(f\"Input: {tc} -> Output: {flip_case(tc)}\")\n\n # Running the doctest to verify the example provided in the docstring\n import doctest\n doctest.testmod()\n```"}
{"task_id": "HumanEval/28", "solution": "```python\nfrom typing import List\n\ndef concatenate(strings: List[str]) -> str:\n \"\"\" Concatenate list of strings into a single string\n >>> concatenate([])\n ''\n >>> concatenate(['a', 'b', 'c'])\n 'abc'\n \"\"\"\n return \"\".join(strings)\n\nif __name__ == \"__main__\":\n import doctest\n doctest.testmod()\n```"}
{"task_id": "HumanEval/29", "solution": "```python\nfrom typing import List\n\ndef filter_by_prefix(strings: List[str], prefix: str) -> List[str]:\n \"\"\" Filter an input list of strings only for ones that start with a given prefix.\n >>> filter_by_prefix([], 'a')\n []\n >>> filter_by_prefix(['abc', 'bcd', 'cde', 'array'], 'a')\n ['abc', 'array']\n \"\"\"\n return [s for s in strings if s.startswith(prefix)]\n\nif __name__ == \"__main__\":\n # Testing the function with provided examples\n test_cases = [\n ([], 'a', []),\n (['abc', 'bcd', 'cde', 'array'], 'a', ['abc', 'array']),\n (['apple', 'banana', 'apricot', 'cherry'], 'ap', ['apple', 'apricot']),\n (['hello', 'world'], 'z', []),\n ]\n\n for strings, prefix, expected in test_cases:\n result = filter_by_prefix(strings, prefix)\n assert result == expected, f\"Failed on {strings} with prefix {prefix}: expected {expected}, got {result}\"\n \n print(\"All tests passed!\")\n```"}
{"task_id": "HumanEval/30", "solution": "```python\ndef get_positive(l: list):\n \"\"\"Return only positive numbers in the list.\n >>> get_positive([-1, 2, -4, 5, 6])\n [2, 5, 6]\n >>> get_positive([5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10])\n [5, 3, 2, 3, 9, 123, 1]\n \"\"\"\n return [x for x in l if x > 0]\n\nif __name__ == \"__main__\":\n import doctest\n doctest.testmod()\n```"}
{"task_id": "HumanEval/31", "solution": "```python\nimport math\n\ndef is_prime(n):\n \"\"\"Return true if a given number is prime, and false otherwise.\n >>> is_prime(6)\n False\n >>> is_prime(101)\n True\n >>> is_prime(11)\n True\n >>> is_prime(13441)\n True\n >>> is_prime(61)\n True\n >>> is_prime(4)\n False\n >>> is_prime(1)\n False\n \"\"\"\n # Prime numbers must be greater than 1\n if n <= 1:\n return False\n \n # 2 is the only even prime number\n if n == 2:\n return True\n \n # Eliminate all other even numbers immediately\n if n % 2 == 0:\n return False\n \n # Check for factors from 3 up to the square root of n.\n # We only need to check odd numbers because we've already handled evens.\n limit = int(math.sqrt(n)) + 1\n for i in range(3, limit, 2):\n if n % i == 0:\n return False\n \n return True\n\nif __name__ == \"__main__\":\n # Testing the function with the provided examples\n test_cases = [\n (6, False),\n (101, True),\n (11, True),\n (13441, True),\n (61, True),\n (4, False),\n (1, False),\n ]\n\n for val, expected in test_cases:\n result = is_prime(val)\n print(f\"is_prime({val}) -> Expected: {expected}, Got: {result} | {'PASS' if result == expected else 'FAIL'}\")\n```"}
{"task_id": "HumanEval/32", "solution": "```python\nimport math\n\n\ndef poly(xs: list, x: float):\n \"\"\"\n Evaluates polynomial with coefficients xs at point x.\n return xs[0] + xs[1] * x + xs[2] * x^2 + .... xs[n] * x^n\n \"\"\"\n return sum([coeff * math.pow(x, i) for i, coeff in enumerate(xs)])\n\n\ndef find_zero(xs: list):\n \"\"\" \n xs are coefficients of a polynomial.\n find_zero finds x such that poly(x) = 0.\n find_zero returns only one zero point, even if there are many.\n Moreover, find_zero only takes list xs having even number of coefficients\n and largest non zero coefficient as it guarantees a solution.\n \n >>> round(find_zero([1, 2]), 2) # f(x) = 1 + 2x\n -0.5\n >>> round(find_zero([-6, 11, -6, 1]), 2) # (x - 1) * (x - 2) * (x - 3) = -6 + 11x - 6x^2 + x^3\n 1.0\n \"\"\"\n # The problem states the list has an even number of coefficients, meaning the degree n is odd.\n # A real polynomial of odd degree always has at least one real root.\n \n # We use Cauchy's bound to find an interval [-M, M] that contains all roots.\n # For f(x) = a_n*x^n + ... + a_0, any root z satisfies |z| <= 1 + max(|a_0|, ..., |a_{n-1}|) / |a_n|\n n = len(xs) - 1\n an = abs(xs[n])\n \n # Handle the case where leading coefficient might be zero (though constraints suggest otherwise)\n if an == 0:\n # Find the actual degree by looking for the last non-zero coefficient\n while n > 0 and xs[n] == 0:\n n -= 1\n an = abs(xs[n])\n\n max_coeff = max(abs(c) for c in xs[:n])\n M = 1 + (max_coeff / an if an != 0 else 1.0)\n\n # Bisection Method\n low = -M\n high = M\n f_low = poly(xs, low)\n f_high = poly(xs, high)\n\n # If the boundaries don't have opposite signs (which shouldn't happen for odd degree), \n # we expand slightly or shift. But for odd degrees, f(-inf) and f(+inf) always differ in sign.\n if f_low * f_high > 0:\n # This is a fallback; theoretically not reached for odd-degree polynomials with an != 0\n return None\n\n # Iterate to narrow down the root (100 iterations provide high precision)\n for _ in range(100):\n mid = (low + high) / 2\n f_mid = poly(xs, mid)\n \n if f_mid == 0:\n return mid\n \n # Check which sub-interval contains the root\n if f_low * f_mid < 0:\n high = mid\n f_high = f_mid\n else:\n low = mid\n f_low = f_mid\n\n return (low + high) / 2\n\n\nif __name__ == \"__main__\":\n # Test cases from docstring\n print(f\"Test 1: {round(find_zero([1, 2]), 2)}\") # Expected -0.5\n print(f\"Test 2: {round(find_zero([-6, 11, -6, 1]), 2)}\") # Expected 1.0 (or 2.0 or 3.0)\n```"}
{"task_id": "HumanEval/33", "solution": "```python\ndef sort_third(l: list):\n \"\"\"This function takes a list l and returns a list l' such that\n l' is identical to l in the indices that are not divisible by three, while its values at the indices that are divisible by three are equal\n to the values of the corresponding indices of l, but sorted.\n >>> sort_third([1, 2, 3])\n [1, 2, 3]\n >>> sort_third([5, 6, 3, 4, 8, 9, 2])\n [2, 6, 3, 4, 8, 9, 5]\n \"\"\"\n # Extract elements at indices divisible by 3 (0, 3, 6, ...)\n thirds = [l[i] for i in range(len(l)) if i % 3 == 0]\n \n # Sort the extracted elements\n thirds.sort()\n \n # Create a new list to store the result\n result = []\n third_ptr = 0\n \n for i in range(len(l)):\n if i % 3 == 0:\n # If index is divisible by 3, insert the next sorted element\n result.append(thirds[third_ptr])\n third_ptr += 1\n else:\n # Otherwise, keep the original element\n result.append(l[i])\n \n return result\n\nif __name__ == \"__main__\":\n import doctest\n # Run the docstring tests to verify correctness\n doctest.testmod()\n \n # Additional manual test cases\n print(f\"Test 1: {sort_third([1, 2, 3])}\") # Expected: [1, 2, 3]\n print(f\"Test 2: {sort_third([5, 6, 3, 4, 8, 9, 2])}\") # Expected: [2, 6, 3, 4, 8, 9, 5]\n```"}
{"task_id": "HumanEval/34", "solution": "```python\ndef unique(l: list):\n \"\"\"Return sorted unique elements in a list\n >>> unique([5, 3, 5, 2, 3, 3, 9, 0, 123])\n [0, 2, 3, 5, 9, 123]\n \"\"\"\n # set(l) removes all duplicate elements\n # sorted() returns a new list containing all elements from the iterable in ascending order\n return sorted(set(l))\n\nif __name__ == \"__main__\":\n import doctest\n # This will run the example provided in the docstring to verify correctness\n result = doctest.testmod()\n if result.failed == 0:\n print(\"All tests passed!\")\n else:\n print(f\"{result.failed} tests failed.\")\n```"}
{"task_id": "HumanEval/35", "solution": "```python\ndef max_element(l: list):\n \"\"\"Return maximum element in the list.\n >>> max_element([1, 2, 3])\n 3\n >>> max_element([5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10])\n 123\n \"\"\"\n return max(l)\n\nif __name__ == \"__main__\":\n import doctest\n doctest.testmod()\n```"}
{"task_id": "HumanEval/36", "solution": "```python\ndef fizz_buzz(n: int):\n \"\"\"Return the number of times the digit 7 appears in integers less than n which are divisible by 11 or 13.\n >>> fizz_buzz(50)\n 0\n >>> fizz_buzz(78)\n 2\n >>> fizz_buzz(79)\n 3\n \"\"\"\n count = 0\n for i in range(n):\n # Check if the number is divisible by 11 or 13\n if i % 11 == 0 or i % 13 == 0:\n # Convert the number to a string and count occurrences of '7'\n count += str(i).count('7')\n return count\n\nif __name__ == \"__main__\":\n import doctest\n # Run the provided docstring tests\n result = doctest.testmod()\n if result.failed == 0:\n print(\"All tests passed!\")\n else:\n print(f\"{result.failed} tests failed.\")\n```"}
{"task_id": "HumanEval/37", "solution": "```python\ndef sort_even(l: list):\n \"\"\"This function takes a list l and returns a list l' such that\n l' is identical to l in the odd indicies, while its values at the even indicies are equal\n to the values of the even indicies of l, but sorted.\n >>> sort_even([1, 2, 3])\n [1, 2, 3]\n >>> sort_even([5, 6, 3, 4])\n [3, 6, 5, 4]\n \"\"\"\n # Create a copy of the original list to avoid mutating the input\n result = l[:]\n \n # Extract elements at even indices (0, 2, 4...) using slicing [start:stop:step]\n even_elements = l[0::2]\n \n # Sort the extracted even-indexed elements\n sorted_evens = sorted(even_elements)\n \n # Assign the sorted values back into the even indices of the result list\n result[0::2] = sorted_evens\n \n return result\n\nif __name__ == \"__main__\":\n # Test cases provided in the docstring\n print(f\"Test 1: {sort_even([1, 2, 3])} (Expected: [1, 2, 3])\")\n print(f\"Test 2: {sort_even([5, 6, 3, 4])} (Expected: [3, 6, 5, 4])\")\n \n # Additional test cases\n print(f\"Test 3: {sort_even([10, 1, 8, 2, 6, 3])} (Expected: [6, 1, 8, 2, 10, 3])\")\n print(f\"Test 4: {sort_even([1])} (Expected: [1])\")\n print(f\"Test 5: {sort_even([])} (Expected: [])\")\n```"}
{"task_id": "HumanEval/38", "solution": "```python\ndef encode_cyclic(s: str):\n \"\"\"\n returns encoded string by cycling groups of three characters.\n \"\"\"\n # split string to groups. Each of length 3.\n groups = [s[(3 * i):min((3 * i + 3), len(s))] for i in range((len(s) + 2) // 3)]\n # cycle elements in each group. Unless group has fewer elements than 3.\n groups = [(group[1:] + group[0]) if len(group) == 3 else group for group in groups]\n return \"\".join(groups)\n\n\ndef decode_cyclic(s: str):\n \"\"\"\n takes as input string encoded with encode_cyclic function. Returns decoded string.\n \"\"\"\n # Split the encoded string into groups of three characters, just like in encode_cyclic.\n groups = [s[(3 * i):min((3 * i + 3), len(s))] for i in range((len(s) + 2) // 3)]\n \n # In encode_cyclic, a group (0, 1, 2) became (1, 2, 0).\n # To reverse this, the encoded group (E0, E1, E2) must become (E2, E0, E1).\n decoded_groups = []\n for group in groups:\n if len(group) == 3:\n # Shift the last character to the front\n decoded_group = group[2] + group[0:2]\n decoded_groups.append(decoded_group)\n else:\n # Groups with fewer than 3 characters were not changed during encoding\n decoded_groups.append(group)\n \n return \"\".join(decoded_groups)\n\n# Example usage and verification\nif __name__ == \"__main__\":\n test_strings = [\"abcdefgh\", \"hello world\", \"python\", \"a\", \"ab\", \"abc\", \"abcd\"]\n for text in test_strings:\n encoded = encode_cyclic(text)\n decoded = decode_cyclic(encoded)\n print(f\"Original: {text!r} -> Encoded: {encoded!r} -> Decoded: {decoded!r}\")\n assert text == decoded\n```"}
{"task_id": "HumanEval/39", "solution": "```python\ndef prime_fib(n: int):\n \"\"\"\n prime_fib returns n-th number that is a Fibonacci number and it's also prime.\n >>> prime_fib(1)\n 2\n >>> prime_fib(2)\n 3\n >>> prime_fib(3)\n 5\n >>> prime_fib(4)\n 13\n >>> prime_fib(5)\n 89\n \"\"\"\n def is_prime(num):\n \"\"\"Helper function to check if a number is prime.\"\"\"\n if num < 2:\n return False\n if num == 2:\n return True\n if num % 2 == 0:\n return False\n # Check odd divisors up to the square root of the number\n for i in range(3, int(num**0.5) + 1, 2):\n if num % i == 0:\n return False\n return True\n\n count = 0\n a, b = 0, 1\n \n # Generate Fibonacci numbers and check for primality until the n-th prime is found\n while count < n:\n # Calculate next Fibonacci number\n a, b = b, a + b\n if is_prime(b):\n count += 1\n \n return b\n\nif __name__ == \"__main__\":\n # Test cases based on the docstring\n test_cases = {1: 2, 2: 3, 3: 5, 4: 13, 5: 89}\n for n, expected in test_cases.items():\n result = prime_fib(n)\n print(f\"prime_fib({n}) = {result}; Expected: {expected} - {'PASSED' if result == expected else 'FAILED'}\")\n```"}
{"task_id": "HumanEval/40", "solution": "```python\ndef triples_sum_to_zero(l: list):\n \"\"\"\n triples_sum_to_zero takes a list of integers as an input.\n it returns True if there are three distinct elements in the list that\n sum to zero, and False otherwise.\n\n >>> triples_sum_to_zero([1, 3, 5, 0])\n False\n >>> triples_sum_to_zero([1, 3, -2, 1])\n True\n >>> triples_sum_to_zero([1, 2, 3, 7])\n False\n >>> triples_sum_to_zero([2, 4, -5, 3, 9, 7])\n True\n >>> triples_sum_to_zero([1])\n False\n \"\"\"\n n = len(l)\n if n < 3:\n return False\n\n # Sort the list to enable the two-pointer approach\n # Time Complexity: O(n log n) for sorting, O(n^2) for searching. Total: O(n^2).\n # Space Complexity: O(1) or O(n) depending on sort implementation.\n nums = sorted(l)\n\n for i in range(n - 2):\n # Use two pointers to find if any pair sums to the negative of nums[i]\n left = i + 1\n right = n - 1\n \n while left < right:\n current_sum = nums[i] + nums[left] + nums[right]\n if current_sum == 0:\n return True\n elif current_sum < 0:\n left += 1\n else:\n right -= 1\n \n return False\n\nif __name__ == \"__main__\":\n import doctest\n # Run the provided docstring tests to verify correctness\n result = doctest.testmod()\n if result.failed == 0:\n print(\"All tests passed!\")\n```"}
{"task_id": "HumanEval/41", "solution": "```python\ndef car_race_collision(n: int):\n \"\"\"\n Imagine a road that's a perfectly straight infinitely long line.\n n cars are driving left to right; simultaneously, a different set of n cars\n are driving right to left. The two sets of cars start out being very far from\n each other. All cars move in the same speed. Two cars are said to collide\n when a car that's moving left to right hits a car that's moving right to left.\n However, the cars are infinitely sturdy and strong; as a result, they continue moving\n in their trajectory as if they did not collide.\n\n This function outputs the number of such collisions.\n \"\"\"\n # Analysis:\n # 1. There are n cars moving Left -> Right (L2R).\n # 2. There are n cars moving Right -> Left (R2L).\n # 3. The problem states they start \"very far from each other,\" implying that all \n # L2R cars begin to the left of all R2L cars.\n # 4. Since every L2R car is moving towards every R2L car and they pass through \n # each other without changing direction or speed, every single L2R car will \n # eventually collide with every single R2L car exactly once.\n # 5. Therefore, the total number of collisions is the product of the sizes of \n # the two sets: n * n.\n \n return n * n\n\nif __name__ == \"__main__\":\n # Test cases\n test_values = [0, 1, 2, 5, 10]\n for v in test_values:\n print(f\"n={v}, collisions={car_race_collision(v)}\")\n```"}
{"task_id": "HumanEval/42", "solution": "```python\ndef incr_list(l: list):\n \"\"\"Return list with elements incremented by 1.\n >>> incr_list([1, 2, 3])\n [2, 3, 4]\n >>> incr_list([5, 3, 5, 2, 3, 3, 9, 0, 123])\n [6, 4, 6, 3, 4, 4, 10, 1, 124]\n \"\"\"\n return [x + 1 for x in l]\n\nif __name__ == \"__main__\":\n import doctest\n # Run the tests provided in the docstring\n result = doctest.testmod()\n if result.failed == 0:\n print(\"All tests passed!\")\n```"}
{"task_id": "HumanEval/43", "solution": "```python\ndef pairs_sum_to_zero(l):\n \"\"\"\n pairs_sum_to_zero takes a list of integers as an input.\n it returns True if there are two distinct elements in the list that\n sum to zero, and False otherwise.\n >>> pairs_sum_to_zero([1, 3, 5, 0])\n False\n >>> pairs_sum_to_zero([1, 3, -2, 1])\n False\n >>> pairs_sum_to_zero([1, 2, 3, 7])\n False\n >>> pairs_sum_to_zero([2, 4, -5, 3, 5, 7])\n True\n >>> pairs_sum_to_zero([1])\n False\n \"\"\"\n # We use a set to keep track of the numbers we have encountered so far.\n # This allows us to check if the additive inverse (negative) of the current \n # number exists in the list in O(1) average time complexity.\n seen = set()\n \n for num in l:\n # If -num is already in our set, we have found two distinct elements that sum to zero.\n if -num in seen:\n return True\n # Otherwise, add the current number to the set and continue.\n seen.add(num)\n \n return False\n\nif __name__ == \"__main__\":\n # Test cases provided in the docstring\n assert pairs_sum_to_zero([1, 3, 5, 0]) == False\n assert pairs_sum_to_zero([1, 3, -2, 1]) == False\n assert pairs_sum_to_zero([1, 2, 3, 7]) == False\n assert pairs_sum_to_zero([2, 4, -5, 3, 5, 7]) == True\n assert pairs_sum_to_zero([1]) == False\n \n # Additional edge cases\n assert pairs_sum_to_zero([0, 0]) == True # Two distinct elements (indices) that sum to zero\n assert pairs_sum_to_zero([0]) == False # Only one element, cannot form a pair\n assert pairs_sum_to_zero([]) == False # Empty list\n \n print(\"All test cases passed!\")\n```"}
{"task_id": "HumanEval/44", "solution": "```python\ndef change_base(x: int, base: int):\n \"\"\"Change numerical base of input number x to base.\n return string representation after the conversion.\n base numbers are less than 10.\n >>> change_base(8, 3)\n '22'\n >>> change_base(8, 2)\n '1000'\n >>> change_base(7, 2)\n '111'\n \"\"\"\n if x == 0:\n return '0'\n \n digits = []\n while x > 0:\n # Get the remainder of division by base (the current digit)\n digits.append(str(x % base))\n # Update x to be the quotient\n x //= base\n \n # The digits were collected from least significant to most significant,\n # so we reverse them and join into a single string.\n return \"\".join(reversed(digits))\n\nif __name__ == \"__main__\":\n import doctest\n # Run the examples provided in the docstring to verify correctness\n result = doctest.testmod()\n if result.failed == 0:\n print(\"All tests passed!\")\n else:\n print(f\"{result.failed} tests failed.\")\n```"}
{"task_id": "HumanEval/45", "solution": "```python\ndef triangle_area(a, h):\n \"\"\"Given length of a side and high return area for a triangle.\n >>> triangle_area(5, 3)\n 7.5\n \"\"\"\n return 0.5 * a * h\n\nif __name__ == \"__main__\":\n # Test the function with the provided example\n result = triangle_area(5, 3)\n print(f\"The area of a triangle with side 5 and height 3 is: {result}\")\n```"}
{"task_id": "HumanEval/46", "solution": "```python\ndef fib4(n: int):\n \"\"\"The Fib4 number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:\n fib4(0) -> 0\n fib4(1) -> 0\n fib4(2) -> 2\n fib4(3) -> 0\n fib4(n) -> fib4(n-1) + fib4(n-2) + fib4(n-3) + fib4(n-4).\n Please write a function to efficiently compute the n-th element of the fib4 number sequence. Do not use recursion.\n >>> fib4(5)\n 4\n >>> fib4(6)\n 8\n >>> fib4(7)\n 14\n \"\"\"\n # Base cases for n < 4\n if n == 0:\n return 0\n if n == 1:\n return 0\n if n == 2:\n return 2\n if n == 3:\n return 0\n\n # We use a sliding window of the last four values to compute the next value.\n # Initial state for fib4(0), fib4(1), fib4(2), fib4(3)\n a, b, c, d = 0, 0, 2, 0\n\n # Iterate from index 4 up to n\n for _ in range(4, n + 1):\n # The next element is the sum of the previous four elements\n current = a + b + c + d\n # Shift the window forward:\n # a becomes fib4(i-3), b becomes fib4(i-2), etc.\n a, b, c, d = b, c, d, current\n\n return d\n\nif __name__ == \"__main__\":\n import doctest\n doctest.testmod()\n \n # Additional manual tests\n print(f\"fib4(5): {fib4(5)}\") # Expected: 4\n print(f\"fib4(6): {fib4(6)}\") # Expected: 8\n print(f\"fib4(7): {fib4(7)}\") # Expected: 14\n```"}
{"task_id": "HumanEval/47", "solution": "```python\ndef median(l: list):\n \"\"\"Return median of elements in the list l.\n >>> median([3, 1, 2, 4, 5])\n 3\n >>> median([-10, 4, 6, 1000, 10, 20])\n 8.0\n \"\"\"\n # First, sort the list in ascending order\n sorted_l = sorted(l)\n n = len(sorted_l)\n \n # If the list is empty, we cannot calculate a median\n if n == 0:\n return None\n \n mid = n // 2\n \n # If the number of elements is odd, return the middle element\n if n % 2 == 1:\n return sorted_l[mid]\n # If the number of elements is even, return the average of the two middle elements\n else:\n return (sorted_l[mid - 1] + sorted_l[mid]) / 2.0\n\nif __name__ == \"__main__\":\n import doctest\n # Note: The prompt's docstring example median([-10, 4, 6, 1000, 10, 20]) -> 15.0 \n # is mathematically incorrect for a standard median calculation. \n # Sorted list: [-10, 4, 6, 10, 20, 1000]. Middle elements are 6 and 10. \n # (6 + 10) / 2 = 8.0. We have updated the docstring to reflect this.\n doctest.testmod()\n```"}
{"task_id": "HumanEval/48", "solution": "```python\ndef is_palindrome(text: str):\n \"\"\"\n Checks if given string is a palindrome\n >>> is_palindrome('')\n True\n >>> is_palindrome('aba')\n True\n >>> is_palindrome('aaaaa')\n True\n >>> is_palindrome('zbcd')\n False\n \"\"\"\n return text == text[::-1]\n\nif __name__ == \"__main__\":\n import doctest\n # Run the tests provided in the docstring\n result = doctest.testmod()\n if result.failed == 0:\n print(\"All tests passed!\")\n```"}
{"task_id": "HumanEval/49", "solution": "```python\ndef modp(n: int, p: int):\n \"\"\"Return 2^n modulo p (be aware of numerics).\n >>> modp(3, 5)\n 3\n >>> modp(1101, 101)\n 2\n >>> modp(0, 101)\n 1\n >>> modp(3, 11)\n 8\n >>> modp(100, 101)\n 1\n \"\"\"\n # Python's built-in pow(base, exp, mod) function implements \n # modular exponentiation efficiently using the square-and-multiply algorithm.\n return pow(2, n, p)\n\nif __name__ == \"__main__\":\n import doctest\n # Run the tests provided in the docstring to ensure correctness\n result = doctest.testmod()\n if result.failed == 0:\n print(\"All tests passed!\")\n```"}
{"task_id": "HumanEval/50", "solution": "```python\ndef encode_shift(s: str):\n \"\"\"\n returns encoded string by shifting every character by 5 in the alphabet.\n \"\"\"\n return \"\".join([chr(((ord(ch) + 5 - ord(\"a\")) % 26) + ord(\"a\")) for ch in s])\n\n\ndef decode_shift(s: str):\n \"\"\"\n takes as input string encoded with encode_shift function. Returns decoded string.\n \"\"\"\n # To reverse a shift of +5, we shift by -5.\n return \"\".join([chr(((ord(ch) - 5 - ord(\"a\")) % 26) + ord(\"a\")) for ch in s])\n\n\n# Example usage and verification\nif __name__ == \"__main__\":\n original_text = \"hello world\".replace(\" \", \"\") # encode_shift assumes lowercase a-z\n encoded = encode_shift(original_text)\n decoded = decode_shift(encoded)\n\n print(f\"Original: {original_text}\")\n print(f\"Encoded: {encoded}\")\n print(f\"Decoded: {decoded}\")\n \n assert original_text == decoded, \"The decoded string should match the original!\"\n```"}
{"task_id": "HumanEval/51", "solution": "```python\ndef remove_vowels(text):\n \"\"\"\n remove_vowels is a function that takes string and returns string without vowels.\n >>> remove_vowels('')\n ''\n >>> remove_vowels(\"abcdef\\nghijklm\")\n 'bcdf\\nghjklm'\n >>> remove_vowels('abcdef')\n 'bcdf'\n >>> remove_vowels('aaaaa')\n ''\n >>> remove_vowels('aaBAA')\n 'B'\n >>> remove_vowels('zbcd')\n 'zbcd'\n \"\"\"\n vowels = \"aeiouAEIOU\"\n return \"\".join([char for char in text if char not in vowels])\n\nif __name__ == \"__main__\":\n import doctest\n doctest.testmod()\n```"}
{"task_id": "HumanEval/52", "solution": "```python\ndef below_threshold(l: list, t: int):\n \"\"\"Return True if all numbers in the list l are below threshold t.\n >>> below_threshold([1, 2, 4, 10], 100)\n True\n >>> below_threshold([1, 20, 4, 10], 5)\n False\n \"\"\"\n return all(x < t for x in l)\n\nif __name__ == \"__main__\":\n import doctest\n doctest.testmod()\n```"}
{"task_id": "HumanEval/53", "solution": "```python\ndef add(x: int, y: int) -> int:\n \"\"\"Add two numbers x and y\n >>> add(2, 3)\n 5\n >>> add(5, 7)\n 12\n \"\"\"\n return x + y\n\nif __name__ == \"__main__\":\n import doctest\n # This will run the examples provided in the docstring to verify correctness\n result = doctest.testmod()\n if result.failed == 0:\n print(\"All tests passed!\")\n```"}
{"task_id": "HumanEval/54", "solution": "```python\ndef same_chars(s0: str, s1: str):\n \"\"\"\n Check if two words have the same characters.\n >>> same_chars('eabcdzzzz', 'dddzzzzzzzddeddabc')\n True\n >>> same_chars('abcd', 'dddddddabc')\n True\n >>> same_chars('dddddddabc', 'abcd')\n True\n >>> same_chars('eabcd', 'dddddddabc')\n False\n >>> same_chars('abcd', 'dddddddabce')\n False\n >>> same_chars('eabcdzzzz', 'dddzzzzzzzddddabc')\n False\n \"\"\"\n # Convert both strings to sets of characters and compare them.\n # A set contains only unique elements, so this effectively checks \n # if the collection of distinct characters in s0 is identical to that in s1.\n return set(s0) == set(s1)\n\nif __name__ == \"__main__\":\n import doctest\n # Run the tests provided in the docstring\n result = doctest.testmod()\n if result.failed == 0:\n print(\"All tests passed!\")\n```"}
{"task_id": "HumanEval/55", "solution": "```python\ndef fib(n: int):\n \"\"\"Return n-th Fibonacci number.\n >>> fib(10)\n 55\n >>> fib(1)\n 1\n >>> fib(8)\n 21\n \"\"\"\n if n <= 0:\n return 0\n elif n == 1:\n return 1\n \n a, b = 0, 1\n for _ in range(2, n + 1):\n a, b = b, a + b\n return b\n\nif __name__ == \"__main__\":\n import doctest\n # This will run the examples provided in the docstring to verify correctness\n result = doctest.testmod()\n if result.failed == 0:\n print(\"All tests passed!\")\n```"}
{"task_id": "HumanEval/56", "solution": "```python\ndef correct_bracketing(brackets: str):\n \"\"\" brackets is a string of \"<\" and \">\".\n return True if every opening bracket has a corresponding closing bracket.\n\n >>> correct_bracketing(\"<\")\n False\n >>> correct_bracketing(\"<>\")\n True\n >>> correct_bracketing(\"<<><>>\")\n True\n >>> correct_bracketing(\"><<>\")\n False\n \"\"\"\n balance = 0\n for char in brackets:\n if char == '<':\n balance += 1\n elif char == '>':\n balance -= 1\n \n # If balance is negative, a closing bracket appeared without an opening one\n if balance < 0:\n return False\n \n # The string is correct if all opened brackets were closed (balance returns to 0)\n return balance == 0\n\nif __name__ == \"__main__\":\n import doctest\n # Run the examples provided in the docstring to verify correctness\n result = doctest.testmod()\n if result.failed == 0:\n print(\"All tests passed!\")\n```"}
{"task_id": "HumanEval/57", "solution": "```python\ndef monotonic(l: list):\n \"\"\"Return True is list elements are monotonically increasing or decreasing.\n >>> monotonic([1, 2, 4, 20])\n True\n >>> monotonic([1, 20, 4, 10])\n False\n >>> monotonic([4, 1, 0, -10])\n True\n \"\"\"\n # An empty list or a list with one element is monotonically both increasing and decreasing.\n if len(l) <= 1:\n return True\n\n is_increasing = True\n is_decreasing = True\n\n for i in range(len(l) - 1):\n if l[i] > l[i+1]:\n is_increasing = False\n if l[i] < l[i+1]:\n is_decreasing = False\n \n return is_increasing or is_decreasing\n\nif __name__ == \"__main__\":\n import doctest\n doctest.testmod()\n \n # Additional manual tests\n print(f\"Test [1, 2, 4, 20]: {monotonic([1, 2, 4, 20])}\") # Expected: True\n print(f\"Test [1, 20, 4, 10]: {monotonic([1, 20, 4, 10])}\") # Expected: False\n print(f\"Test [4, 1, 0, -10]: {monotonic([4, 1, 0, -10])}\") # Expected: True\n print(f\"Test [1, 1, 1]: {monotonic([1, 1, 1])}\") # Expected: True\n```"}
{"task_id": "HumanEval/58", "solution": "```python\ndef common(l1: list, l2: list):\n \"\"\"Return sorted unique common elements for two lists.\n >>> common([1, 4, 3, 34, 653, 2, 5], [5, 7, 1, 5, 9, 653, 121])\n [1, 5, 653]\n >>> common([5, 3, 2, 8], [3, 2])\n [2, 3]\n \"\"\"\n # Convert lists to sets to find the intersection (common elements)\n # and automatically handle uniqueness.\n set1 = set(l1)\n set2 = set(l2)\n \n # Find common elements using the intersection operator '&'\n intersect = set1 & set2\n \n # Return the result as a sorted list\n return sorted(list(intersect))\n\nif __name__ == \"__main__\":\n # Test cases from docstring\n test1_l1, test1_l2 = [1, 4, 3, 34, 653, 2, 5], [5, 7, 1, 5, 9, 653, 121]\n print(f\"Test 1: {common(test1_l1, test1_l2)}\") # Expected: [1, 5, 653]\n\n test2_l1, test2_l2 = [5, 3, 2, 8], [3, 2]\n print(f\"Test 2: {common(test2_l1, test2_l2)}\") # Expected: [2, 3]\n```"}
{"task_id": "HumanEval/59", "solution": "```python\ndef largest_prime_factor(n: int):\n \"\"\"Return the largest prime factor of n. Assume n > 1 and is not a prime.\n >>> largest_prime_factor(13195)\n 29\n >>> largest_prime_factor(2048)\n 2\n \"\"\"\n i = 2\n max_f = 0\n # Iterate from the smallest possible prime factor (2) up to sqrt(n)\n while i * i <= n:\n if n % i == 0:\n # If i divides n, it is a prime factor because we are iterating upwards\n # and have already removed all smaller factors.\n max_f = i\n # Divide out all occurrences of this factor\n while n % i == 0:\n n //= i\n i += 1\n \n # If after the loop n is still greater than 1, then the remaining n \n # must be a prime number and it will be the largest prime factor.\n if n > 1:\n max_f = n\n \n return max_f\n\nif __name__ == \"__main__\":\n import doctest\n doctest.testmod()\n \n # Additional test cases\n print(f\"Largest prime factor of 13195 is: {largest_prime_factor(13195)}\") # Expected: 29\n print(f\"Largest prime factor of 2048 is: {largest_prime_factor(2048)}\") # Expected: 2\n print(f\"Largest prime factor of 600851475143 is: {largest_prime_factor(600851475143)}\") # Expected: 6857\n```"}
{"task_id": "HumanEval/60", "solution": "```python\ndef sum_to_n(n: int):\n \"\"\"sum_to_n is a function that sums numbers from 1 to n.\n >>> sum_to_n(30)\n 465\n >>> sum_to_n(100)\n 5050\n >>> sum_to_n(5)\n 15\n >>> sum_to_n(10)\n 55\n >>> sum_to_n(1)\n 1\n \"\"\"\n # Using the arithmetic series formula: Sum = n * (n + 1) / 2\n return n * (n + 1) // 2\n\nif __name__ == \"__main__\":\n import doctest\n # This will run the examples provided in the docstring to verify correctness\n result = doctest.testmod()\n if result.failed == 0:\n print(\"All tests passed!\")\n```"}
{"task_id": "HumanEval/61", "solution": "```python\ndef correct_bracketing(brackets: str):\n \"\"\" brackets is a string of \"(\" and \")\".\n return True if every opening bracket has a corresponding closing bracket.\n\n >>> correct_bracketing(\"(\")\n False\n >>> correct_bracketing(\"()\")\n True\n >>> correct_bracketing(\"(()())\")\n True\n >>> correct_bracketing(\")(()\")\n False\n \"\"\"\n balance = 0\n for char in brackets:\n if char == '(':\n balance += 1\n elif char == ')':\n balance -= 1\n \n # If balance is negative, a closing bracket appeared without a matching opening one\n if balance < 0:\n return False\n \n # The string is correct if all opened brackets were closed (balance returns to 0)\n return balance == 0\n\nif __name__ == \"__main__\":\n import doctest\n # Run the tests provided in the docstring\n result = doctest.testmod()\n if result.failed == 0:\n print(\"All tests passed!\")\n```"}
{"task_id": "HumanEval/62", "solution": "```python\ndef derivative(xs: list):\n \"\"\" xs represent coefficients of a polynomial.\n xs[0] + xs[1] * x + xs[2] * x^2 + ....\n Return derivative of this polynomial in the same form.\n >>> derivative([3, 1, 2, 4, 5])\n [1, 4, 12, 20]\n >>> derivative([1, 2, 3])\n [2, 6]\n \"\"\"\n # The derivative of a constant (xs[0]) is 0.\n # For terms xs[i] * x^i where i > 0, the derivative is (i * xs[i]) * x^(i-1).\n # Therefore, we start iterating from index 1 and multiply each coefficient by its power.\n return [i * xs[i] for i in range(1, len(xs))]\n\nif __name__ == \"__main__\":\n # Test cases provided in the docstring\n test_cases = [\n ([3, 1, 2, 4, 5], [1, 4, 12, 20]),\n ([1, 2, 3], [2, 6]),\n ([5], []), # Derivative of a constant is 0 (empty list represents no x terms)\n ([], []), # Empty polynomial\n ]\n\n for inp, expected in test_cases:\n result = derivative(inp)\n assert result == expected, f\"Failed on {inp}: expected {expected}, got {result}\"\n print(f\"Input: {inp} -> Derivative: {result}\")\n\n print(\"All tests passed!\")\n```"}
{"task_id": "HumanEval/63", "solution": "```python\ndef fibfib(n: int):\n \"\"\"The FibFib number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:\n fibfib(0) == 0\n fibfib(1) == 0\n fibfib(2) == 1\n fibfib(n) == fibfib(n-1) + fibfib(n-2) + fibfib(n-3).\n Please write a function to efficiently compute the n-th element of the fibfib number sequence.\n >>> fibfib(1)\n 0\n >>> fibfib(5)\n 4\n >>> fibfib(8)\n 24\n \"\"\"\n # Base cases for n = 0, 1, 2\n if n == 0:\n return 0\n if n == 1:\n return 0\n if n == 2:\n return 1\n\n # We use an iterative approach to achieve O(n) time complexity and O(1) space complexity.\n # a, b, c represent fibfib(i-3), fibfib(i-2), and fibfib(i-1) respectively.\n a, b, c = 0, 0, 1\n \n for _ in range(3, n + 1):\n # The next element is the sum of the previous three elements\n next_val = a + b + c\n # Shift values forward for the next iteration\n a, b, c = b, c, next_val\n \n return c\n\nif __name__ == \"__main__\":\n import doctest\n # Run the docstring tests to verify correctness\n doctest.testmod()\n \n # Additional manual verification\n print(f\"fibfib(1): {fibfib(1)}\") # Expected: 0\n print(f\"fibfib(5): {fibfib(5)}\") # Expected: 4\n print(f\"fibfib(8): {fibfib(8)}\") # Expected: 24\n```"}
{"task_id": "HumanEval/64", "solution": "```python\ndef vowels_count(s):\n \"\"\"Write a function vowels_count which takes a string representing\n a word as input and returns the number of vowels in the string.\n Vowels in this case are 'a', 'e', 'i', 'o', 'u'. Here, 'y' is also a\n vowel, but only when it is at the end of the given word.\n\n Example:\n >>> vowels_count(\"abcde\")\n 2\n >>> vowels_count(\"ACEDY\")\n 3\n \"\"\"\n # Convert string to lowercase to handle case-insensitivity\n s_lower = s.lower()\n vowels = \"aeiou\"\n count = 0\n \n # Count standard vowels\n for char in s_lower:\n if char in vowels:\n count += 1\n \n # Check if 'y' is at the end of the word\n if s_lower and s_lower[-1] == 'y':\n count += 1\n \n return count\n\nif __name__ == \"__main__\":\n # Test cases provided in the docstring\n assert vowels_count(\"abcde\") == 2\n assert vowels_count(\"ACEDY\") == 3\n \n # Additional test cases\n assert vowels_count(\"apple\") == 2 # a, e\n assert vowels_count(\"sky\") == 1 # y at end\n assert vowels_count(\"yellow\") == 2 # e, o (y is at start)\n assert vowels_count(\"rhythm\") == 0 # no standard vowels, y not at end\n assert vowels_count(\"fly\") == 1 # y at end\n assert vowels_count(\"\") == 0 # empty string\n assert vowels_count(\"Y\") == 1 # single char Y is at the end\n assert vowels_count(\"AEIOU\") == 5 # all standard vowels\n assert vowels_count(\"syzygy\") == 1 # only last y counts\n \n print(\"All test cases passed!\")\n```"}
{"task_id": "HumanEval/65", "solution": "```python\ndef circular_shift(x, shift):\n \"\"\"Circular shift the digits of the integer x, shift the digits right by shift\n and return the result as a string.\n If shift > number of digits, return digits reversed.\n >>> circular_shift(12, 1)\n \"21\"\n >>> circular_shift(12, 2)\n \"12\"\n \"\"\"\n # Convert integer to string to manipulate digits\n s = str(x)\n n = len(s)\n \n if shift > n:\n # If shift is greater than the number of digits, return reversed string\n return s[::-1]\n elif shift == 0:\n # A shift of 0 returns the original string\n return s\n else:\n # Perform circular right shift:\n # Take the last 'shift' characters and move them to the front\n # The slice s[n-shift:] gets the tail, s[:n-shift] gets the head\n return s[n - shift:] + s[:n - shift]\n\nif __name__ == \"__main__\":\n # Test cases provided in docstring\n print(f\"Test 1 (12, 1): {circular_shift(12, 1)}\") # Expected: \"21\"\n print(f\"Test 2 (12, 2): {circular_shift(12, 2)}\") # Expected: \"12\"\n \n # Additional test cases\n print(f\"Test 3 (123, 1): {circular_shift(123, 1)}\") # Expected: \"312\"\n print(f\"Test 4 (123, 4): {circular_shift(123, 4)}\") # Expected: \"321\" (reversed)\n print(f\"Test 5 (5678, 2): {circular_shift(5678, 2)}\") # Expected: \"7856\"\n```"}
{"task_id": "HumanEval/66", "solution": "```python\ndef digitSum(s):\n \"\"\"Task\n Write a function that takes a string as input and returns the sum of the upper characters only'\n ASCII codes.\n\n Examples:\n digitSum(\"\") => 0\n digitSum(\"abAB\") => 131\n digitSum(\"abcCd\") => 67\n digitSum(\"helloE\") => 69\n digitSum(\"woArBld\") => 131\n digitSum(\"aAaaaXa\") => 153\n \"\"\"\n # Use a generator expression to iterate through the string, \n # filter for uppercase characters using .isupper(), \n # get their ASCII values with ord(), and sum them up.\n return sum(ord(char) for char in s if char.isupper())\n\n# Test cases to verify the function\nif __name__ == \"__main__\":\n test_cases = [\n (\"\", 0),\n (\"abAB\", 131),\n (\"abcCd\", 67),\n (\"helloE\", 69),\n (\"woArBld\", 131),\n (\"aAaaaXa\", 153),\n ]\n\n for input_str, expected in test_cases:\n result = digitSum(input_str)\n print(f\"digitSum('{input_str}') => Expected: {expected}, Got: {result} | {'Pass' if result == expected else 'Fail'}\")\n```"}
{"task_id": "HumanEval/67", "solution": "```python\nimport re\n\ndef fruit_distribution(s, n):\n \"\"\"\n In this task, you will be given a string that represents a number of apples and oranges \n that are distributed in a basket of fruit this basket contains \n apples, oranges, and mango fruits. Given the string that represents the total number of \n the oranges and apples and an integer that represent the total number of the fruits \n in the basket return the number of the mango fruits in the basket.\n \n Example:\n fruit_distribution(\"5 apples and 6 oranges\", 19) -> 19 - 5 - 6 = 8\n \"\"\"\n # Use regular expressions to find all sequences of digits in the string\n numbers = re.findall(r'\\d+', s)\n \n # Convert the extracted strings to integers\n fruit_counts = [int(num) for num in numbers]\n \n # Calculate the sum of apples and oranges\n total_apples_and_oranges = sum(fruit_counts)\n \n # The number of mangoes is the total fruits minus (apples + oranges)\n return n - total_apples_and_oranges\n\n# Test cases to verify the function\nif __name__ == \"__main__\":\n test_cases = [\n (\"5 apples and 6 oranges\", 19, 8),\n (\"0 apples and 1 oranges\", 3, 2),\n (\"2 apples and 3 oranges\", 100, 95),\n (\"100 apples and 1 oranges\", 120, 19),\n ]\n\n for s, n, expected in test_cases:\n result = fruit_distribution(s, n)\n print(f\"fruit_distribution('{s}', {n}) -> Expected: {expected}, Got: {result} | {'Pass' if result == expected else 'Fail'}\")\n```"}
{"task_id": "HumanEval/68", "solution": "```python\ndef pluck(arr):\n \"\"\"\n Given an array representing a branch of a tree that has non-negative integer nodes,\n your task is to pluck one of the nodes and return it.\n The plucked node should be the node with the smallest even value.\n If multiple nodes with the same smallest even value are found, return the node \n that has the smallest index.\n\n The plucked node should be returned in a list: [smallest_value, its_index].\n If there are no even values or the given array is empty, return [].\n \"\"\"\n # Initialize variables to track the minimum even value and its corresponding index\n min_val = float('inf')\n min_idx = -1\n\n for idx, val in enumerate(arr):\n # Check if the current node value is even\n if val % 2 == 0:\n # We only update if we find a value strictly smaller than our current minimum.\n # This naturally handles the requirement to return the smallest index \n # because we iterate from left to right and ignore equal values.\n if val < min_val:\n min_val = val\n min_idx = idx\n\n # If min_idx remains -1, it means no even number was found or array was empty\n if min_idx == -1:\n return []\n \n return [min_val, min_idx]\n\n# Test cases to verify the implementation\nif __name__ == \"__main__\":\n test_cases = [\n ([4, 2, 3], [2, 1]),\n ([1, 2, 3], [2, 1]),\n ([], []),\n ([5, 0, 3, 0, 4, 2], [0, 1]),\n ([1, 3, 5], []),\n ([10, 8, 6, 4], [4, 3]),\n ]\n\n for input_arr, expected in test_cases:\n result = pluck(input_arr)\n print(f\"Input: {input_arr} | Expected: {expected} | Result: {result} | {'Pass' if result == expected else 'Fail'}\")\n```"}
{"task_id": "HumanEval/69", "solution": "```python\ndef search(lst):\n '''\n You are given a non-empty list of positive integers. Return the greatest integer that is greater than \n zero, and has a frequency greater than or equal to the value of the integer itself. \n The frequency of an integer is the number of times it appears in the list.\n If no such a value exist, return -1.\n Examples:\n search([4, 1, 2, 2, 3, 1]) == 2\n search([1, 2, 2, 3, 3, 3, 4, 4, 4]) == 3\n search([5, 5, 4, 4, 4]) == -1\n '''\n # Create a dictionary to store the frequency of each number in the list\n counts = {}\n for num in lst:\n counts[num] = counts.get(num, 0) + 1\n \n max_val = -1\n \n # Iterate through the unique numbers and their frequencies\n for val, freq in counts.items():\n # Check if the frequency is greater than or equal to the value itself\n if freq >= val:\n # We are looking for the greatest such integer\n if val > max_val:\n max_val = val\n \n return max_val\n\n# Test cases\nif __name__ == \"__main__\":\n assert search([4, 1, 2, 2, 3, 1]) == 2\n assert search([1, 2, 2, 3, 3, 3, 4, 4, 4]) == 3\n assert search([5, 5, 4, 4, 4]) == -1\n print(\"All test cases passed!\")\n```"}
{"task_id": "HumanEval/70", "solution": "```python\ndef strange_sort_list(lst):\n '''\n Given list of integers, return list in strange order.\n Strange sorting, is when you start with the minimum value,\n then maximum of the remaining integers, then minimum and so on.\n\n Examples:\n strange_sort_list([1, 2, 3, 4]) == [1, 4, 2, 3]\n strange_sort_list([5, 5, 5, 5]) == [5, 5, 5, 5]\n strange_sort_list([]) == []\n '''\n # First, sort the list to easily access minimums and maximums\n sorted_lst = sorted(lst)\n result = []\n \n # Use two pointers: one at the start (min) and one at the end (max)\n left = 0\n right = len(sorted_lst) - 1\n \n while left <= right:\n # Append the current minimum\n result.append(sorted_lst[left])\n left += 1\n \n # Check if there are still elements remaining to avoid duplicating the middle element\n if left <= right:\n # Append the current maximum\n result.append(sorted_lst[right])\n right -= 1\n \n return result\n\n# Test cases to verify correctness\nif __name__ == \"__main__\":\n assert strange_sort_list([1, 2, 3, 4]) == [1, 4, 2, 3]\n assert strange_sort_list([5, 5, 5, 5]) == [5, 5, 5, 5]\n assert strange_sort_list([]) == []\n assert strange_sort_list([1, 2, 3]) == [1, 3, 2]\n assert strange_sort_list([10, -10, 20, -20]) == [-20, 20, -10, 10]\n print(\"All test cases passed!\")\n```"}
{"task_id": "HumanEval/71", "solution": "```python\nimport math\n\ndef triangle_area(a, b, c):\n '''\n Given the lengths of the three sides of a triangle. Return the area of\n the triangle rounded to 2 decimal points if the three sides form a valid triangle. \n Otherwise return -1\n Three sides make a valid triangle when the sum of any two sides is greater \n than the third side.\n Example:\n triangle_area(3, 4, 5) == 6.00\n triangle_area(1, 2, 10) == -1\n '''\n # Check if the three sides form a valid triangle\n if (a + b > c) and (a + c > b) and (b + c > a):\n # Calculate the semi-perimeter\n s = (a + b + c) / 2\n # Use Heron's formula to calculate the area\n area = math.sqrt(s * (s - a) * (s - b) * (s - c))\n return round(area, 2)\n else:\n # Return -1 if it is not a valid triangle\n return -1\n\n# Test cases to verify the function\nif __name__ == \"__main__\":\n print(f\"Test 3, 4, 5: {triangle_area(3, 4, 5)}\") # Expected: 6.0\n print(f\"Test 1, 2, 10: {triangle_area(1, 2, 10)}\") # Expected: -1\n print(f\"Test 7, 10, 5: {triangle_area(7, 10, 5)}\") # Expected: 16.25 (approx)\n```"}
{"task_id": "HumanEval/72", "solution": "```python\ndef will_it_fly(q, w):\n '''\n Write a function that returns True if the object q will fly, and False otherwise.\n The object q will fly if it's balanced (it is a palindromic list) and the sum of its elements is less than or equal the maximum possible weight w.\n\n Example:\n will_it_fly([1, 2], 5) \u279e False \n # 1+2 is less than the maximum possible weight, but it's unbalanced.\n\n will_it_fly([3, 2, 3], 1) \u279e False\n # it's balanced, but 3+2+3 is more than the maximum possible weight.\n\n will_it_fly([3, 2, 3], 9) \u279e True\n # 3+2+3 is less than the maximum possible weight, and it's balanced.\n\n will_it_fly([3], 5) \u279e True\n # 3 is less than the maximum possible weight, and it's balanced.\n '''\n # Check if the list is a palindrome (reads the same forwards and backwards)\n is_balanced = q == q[::-1]\n \n # Check if the sum of elements is less than or equal to the max weight w\n is_light_enough = sum(q) <= w\n \n return is_balanced and is_light_enough\n\n# Test cases\nif __name__ == \"__main__\":\n print(will_it_fly([1, 2], 5)) # Expected: False\n print(will_it_fly([3, 2, 3], 1)) # Expected: False\n print(will_it_fly([3, 2, 3], 9)) # Expected: True\n print(will_it_fly([3], 5)) # Expected: True\n```"}
{"task_id": "HumanEval/73", "solution": "```python\ndef smallest_change(arr):\n \"\"\"\n Given an array arr of integers, find the minimum number of elements that\n need to be changed to make the array palindromic. A palindromic array is an array that\n is read the same backwards and forwards. In one change, you can change one element to any other element.\n\n For example:\n smallest_change([1,2,3,5,4,7,9,6]) == 4\n smallest_change([1, 2, 3, 4, 3, 2, 2]) == 1\n smallest_change([1, 2, 3, 2, 1]) == 0\n \"\"\"\n n = len(arr)\n changes = 0\n \n # We only need to iterate through the first half of the array.\n # For each element at index i, its corresponding mirror element is at index n - 1 - i.\n for i in range(n // 2):\n if arr[i] != arr[n - 1 - i]:\n changes += 1\n \n return changes\n\n# Test cases to verify the function\nif __name__ == \"__main__\":\n assert smallest_change([1, 2, 3, 5, 4, 7, 9, 6]) == 4\n assert smallest_change([1, 2, 3, 4, 3, 2, 2]) == 1\n assert smallest_change([1, 2, 3, 2, 1]) == 0\n assert smallest_change([]) == 0\n assert smallest_change([1]) == 0\n assert smallest_change([1, 1]) == 0\n assert smallest_change([1, 2]) == 1\n print(\"All test cases passed!\")\n```"}
{"task_id": "HumanEval/74", "solution": "```python\ndef total_match(lst1, lst2):\n '''\n Write a function that accepts two lists of strings and returns the list that has \n total number of chars in the all strings of the list less than the other list.\n\n if the two lists have the same number of chars, return the first list.\n\n Examples\n total_match([], []) \u279e []\n total_match(['hi', 'admin'], ['hI', 'Hi']) \u279e ['hI', 'Hi']\n total_match(['hi', 'admin'], ['hi', 'hi', 'admin', 'project']) \u279e ['hi', 'admin']\n total_match(['hi', 'admin'], ['hI', 'hi', 'hi']) \u279e ['hI', 'hi', 'hi']\n total_match(['4'], ['1', '2', '3', '4', '5']) \u279e ['4']\n '''\n # Calculate the total number of characters in the first list\n sum1 = sum(len(s) for s in lst1)\n # Calculate the total number of characters in the second list\n sum2 = sum(len(s) for s in lst2)\n \n # Return the second list only if its total length is strictly less than the first.\n # Otherwise (if lst1 is shorter or they are equal), return the first list.\n if sum2 < sum1:\n return lst2\n else:\n return lst1\n\n# Test cases to verify the function\nif __name__ == \"__main__\":\n assert total_match([], []) == []\n assert total_match(['hi', 'admin'], ['hI', 'Hi']) == ['hI', 'Hi']\n assert total_match(['hi', 'admin'], ['hi', 'hi', 'admin', 'project']) == ['hi', 'admin']\n assert total_match(['hi', 'admin'], ['hI', 'hi', 'hi']) == ['hI', 'hi', 'hi']\n assert total_match(['4'], ['1', '2', '3', '4', '5']) == ['4']\n print(\"All test cases passed!\")\n```"}
{"task_id": "HumanEval/75", "solution": "```python\ndef is_multiply_prime(a):\n \"\"\"\n Returns True if the given number 'a' is the product of exactly 3 prime numbers,\n and False otherwise.\n \n Example:\n is_multiply_prime(30) == True # 2 * 3 * 5\n is_multiply_prime(8) == True # 2 * 2 * 2\n is_multiply_prime(12) == True # 2 * 2 * 3\n is_multiply_prime(7) == False # Only 1 prime factor\n \"\"\"\n if a < 2:\n return False\n \n count = 0\n temp = a\n d = 2\n \n # Perform prime factorization\n while d * d <= temp:\n while temp % d == 0:\n count += 1\n temp //= d\n d += 1\n \n # If there is a remaining factor greater than 1, it must be prime\n if temp > 1:\n count += 1\n \n # Return True if the total number of prime factors (with multiplicity) is exactly 3\n return count == 3\n\n# Test cases to verify the function\nif __name__ == \"__main__\":\n test_cases = {\n 30: True, # 2 * 3 * 5\n 8: True, # 2 * 2 * 2\n 12: True, # 2 * 2 * 3\n 18: True, # 2 * 3 * 3\n 20: True, # 2 * 2 * 5\n 7: False, # Prime (1 factor)\n 4: False, # 2 * 2 (2 factors)\n 16: False, # 2 * 2 * 2 * 2 (4 factors)\n 1: False, # Not a product of primes\n 0: False # Not a product of primes\n }\n\n for val, expected in test_cases.items():\n result = is_multiply_prime(val)\n print(f\"is_multiply_prime({val}) = {result}; Expected: {expected} {'\u2705' if result == expected else '\u274c'}\")\n```"}
{"task_id": "HumanEval/76", "solution": "```python\ndef is_simple_power(x, n):\n \"\"\"Your task is to write a function that returns true if a number x is a simple\n power of n and false in other cases.\n x is a simple power of n if n**int=x\n For example:\n is_simple_power(1, 4) => true\n is_simple_power(2, 2) => true\n is_simple_power(8, 2) => true\n is_simple_power(3, 2) => false\n is_simple_power(3, 1) => false\n is_simple_power(5, 3) => false\n \"\"\"\n # Any number n raised to the power of 0 is 1 (n**0 = 1).\n if x == 1:\n return True\n \n # If n is 1, it can only result in 1 (handled above).\n # If n is 0, it can result in 0 (for int > 0) or 1 (for int = 0).\n if n <= 1:\n if n == 0 and x == 0:\n return True\n return False\n\n # For n > 1, we repeatedly divide x by n as long as it is divisible.\n # If we eventually reach 1, then x was a power of n.\n while x > 1 and x % n == 0:\n x //= n\n \n return x == 1\n\n# Test cases to verify the function\nif __name__ == \"__main__\":\n assert is_simple_power(1, 4) == True\n assert is_simple_power(2, 2) == True\n assert is_simple_power(8, 2) == True\n assert is_simple_power(3, 2) == False\n assert is_simple_power(3, 1) == False\n assert is_simple_power(5, 3) == False\n print(\"All test cases passed!\")\n```"}
{"task_id": "HumanEval/77", "solution": "```python\ndef iscube(a):\n '''\n Write a function that takes an integer a and returns True \n if this integer is a cube of some integer number.\n Note: you may assume the input is always valid.\n Examples:\n iscube(1) ==> True\n iscube(2) ==> False\n iscube(-1) ==> True\n iscube(64) ==> True\n iscube(0) ==> True\n iscube(180) ==> False\n '''\n # We take the absolute value of 'a' because Python's power operator (**) \n # with a fractional exponent on a negative number returns a complex number.\n # Since (-n)^3 = -(n^3), we only need to check if the magnitude is a perfect cube.\n root = round(abs(a)**(1/3))\n return root**3 == abs(a)\n\n# Test cases to verify the function\nif __name__ == \"__main__\":\n test_cases = [\n (1, True),\n (2, False),\n (-1, True),\n (64, True),\n (0, True),\n (180, False),\n (-64, True),\n (-27, True),\n (125, True),\n (10, False)\n ]\n\n for val, expected in test_cases:\n result = iscube(val)\n print(f\"iscube({val}) ==> {result} | Expected: {expected} | {'PASS' if result == expected else 'FAIL'}\")\n```"}
{"task_id": "HumanEval/78", "solution": "```python\ndef hex_key(num):\n \"\"\"You have been tasked to write a function that receives \n a hexadecimal number as a string and counts the number of hexadecimal \n digits that are primes (prime number, or a prime, is a natural number \n greater than 1 that is not a product of two smaller natural numbers).\n Hexadecimal digits are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F.\n Prime numbers are 2, 3, 5, 7, 11, 13, 17,...\n So you have to determine a number of the following digits: 2, 3, 5, 7, \n B (=decimal 11), D (=decimal 13).\n Note: you may assume the input is always correct or empty string, \n and symbols A,B,C,D,E,F are always uppercase.\n Examples:\n For num = \"AB\" the output should be 1.\n For num = \"1077E\" the output should be 2.\n For num = \"ABED1A33\" the output should be 4.\n For num = \"123456789ABCDEF0\" the output should be 6.\n For num = \"2020\" the output should be 2.\n \"\"\"\n # Define the set of hexadecimal digits that correspond to prime numbers:\n # 2 -> 2 (prime)\n # 3 -> 3 (prime)\n # 5 -> 5 (prime)\n # 7 -> 7 (prime)\n # B -> 11 (prime)\n # D -> 13 (prime)\n primes = {'2', '3', '5', '7', 'B', 'D'}\n \n count = 0\n for char in num:\n if char in primes:\n count += 1\n \n return count\n\n# Test cases to verify the function\nif __name__ == \"__main__\":\n test_cases = [\n (\"AB\", 1),\n (\"1077E\", 2),\n (\"ABED1A33\", 4),\n (\"123456789ABCDEF0\", 6),\n (\"2020\", 2),\n (\"\", 0),\n ]\n\n for input_str, expected in test_cases:\n result = hex_key(input_str)\n print(f\"Input: {input_str} | Expected: {expected} | Result: {result} | {'Pass' if result == expected else 'Fail'}\")\n```"}
{"task_id": "HumanEval/79", "solution": "```python\ndef decimal_to_binary(decimal):\n \"\"\"You will be given a number in decimal form and your task is to convert it to\n binary format. The function should return a string, with each character representing a binary\n number. Each character in the string will be '0' or '1'.\n\n There will be an extra couple of characters 'db' at the beginning and at the end of the string.\n The extra characters are there to help with the format.\n\n Examples:\n decimal_to_binary(15) # returns \"db1111db\"\n decimal_to_binary(32) # returns \"db100000db\"\n \"\"\"\n # bin() converts an integer to a binary string prefixed with '0b'\n # We slice from index 2 onwards to remove the '0b' prefix\n binary_string = bin(decimal)[2:]\n \n # Wrap the result in 'db' at the start and end\n return f\"db{binary_string}db\"\n\n# Test cases to verify the function\nif __name__ == \"__main__\":\n test_cases = [\n (15, \"db1111db\"),\n (32, \"db100000db\"),\n (0, \"db0db\"),\n (7, \"db111db\"),\n (10, \"db1010db\"),\n ]\n\n for decimal_val, expected in test_cases:\n result = decimal_to_binary(decimal_val)\n print(f\"Decimal: {decimal_val} | Expected: {expected} | Result: {result} | {'Pass' if result == expected else 'Fail'}\")\n```"}
{"task_id": "HumanEval/80", "solution": "```python\ndef is_happy(s):\n \"\"\"You are given a string s.\n Your task is to check if the string is happy or not.\n A string is happy if its length is at least 3 and every 3 consecutive letters are distinct\n For example:\n is_happy(\"a\") => False\n is_happy(\"aa\") => False\n is_happy(\"abcd\") => True\n is_happy(\"aabb\") => False\n is_happy(\"adb\") => True\n is_happy(\"xyy\") => False\n \"\"\"\n # A string is happy if its length is at least 3\n if len(s) < 3:\n return False\n \n # Check every sequence of 3 consecutive letters\n for i in range(len(s) - 2):\n # Extract the triplet starting at index i\n triplet = s[i : i + 3]\n # A set removes duplicates; if length is not 3, characters were not distinct\n if len(set(triplet)) != 3:\n return False\n \n return True\n\n# Test cases to verify the function\nif __name__ == \"__main__\":\n assert is_happy(\"a\") == False\n assert is_happy(\"aa\") == False\n assert is_happy(\"abcd\") == True\n assert is_happy(\"aabb\") == False\n assert is_happy(\"adb\") == True\n assert is_happy(\"xyy\") == False\n print(\"All test cases passed!\")\n```"}
{"task_id": "HumanEval/81", "solution": "```python\ndef numerical_letter_grade(grades):\n \"\"\"It is the last week of the semester and the teacher has to give the grades\n to students. The teacher has been making her own algorithm for grading.\n The only problem is, she has lost the code she used for grading.\n She has given you a list of GPAs for some students and you have to write \n a function that can output a list of letter grades using the following table:\n GPA | Letter grade\n 4.0 A+\n > 3.7 A \n > 3.3 A- \n > 3.0 B+\n > 2.7 B \n > 2.3 B-\n > 2.0 C+\n > 1.7 C\n > 1.3 C-\n > 1.0 D+ \n > 0.7 D \n > 0.0 D-\n 0.0 E\n\n Example:\n numerical_letter_grade([4.0, 3, 1.7, 2, 3.5]) ==> ['A+', 'B', 'C-', 'C', 'A-']\n \"\"\"\n letter_grades = []\n for gpa in grades:\n if gpa == 4.0:\n letter_grades.append('A+')\n elif gpa > 3.7:\n letter_grades.append('A')\n elif gpa > 3.3:\n letter_grades.append('A-')\n elif gpa > 3.0:\n letter_grades.append('B+')\n elif gpa > 2.7:\n letter_grades.append('B')\n elif gpa > 2.3:\n letter_grades.append('B-')\n elif gpa > 2.0:\n letter_grades.append('C+')\n elif gpa > 1.7:\n letter_grades.append('C')\n elif gpa > 1.3:\n letter_grades.append('C-')\n elif gpa > 1.0:\n letter_grades.append('D+')\n elif gpa > 0.7:\n letter_grades.append('D')\n elif gpa > 0.0:\n letter_grades.append('D-')\n else:\n letter_grades.append('E')\n return letter_grades\n\n# Test the function with the provided example\nif __name__ == \"__main__\":\n test_cases = [\n ([4.0, 3, 1.7, 2, 3.5], ['A+', 'B', 'C-', 'C', 'A-']),\n ([0.0, 0.5, 1.1, 3.8], ['E', 'D-', 'D+', 'A']),\n ]\n\n for inputs, expected in test_cases:\n result = numerical_letter_grade(inputs)\n print(f\"Input: {inputs} | Expected: {expected} | Result: {result} | {'Pass' if result == expected else 'Fail'}\")\n```"}
{"task_id": "HumanEval/82", "solution": "```python\ndef prime_length(string):\n \"\"\"Write a function that takes a string and returns True if the string\n length is a prime number or False otherwise\n Examples\n prime_length('Hello') == True\n prime_length('abcdcba') == True\n prime_length('kittens') == True\n prime_length('orange') == False\n \"\"\"\n n = len(string)\n \n # Prime numbers must be greater than 1\n if n < 2:\n return False\n \n # Check for factors from 2 up to the square root of n\n for i in range(2, int(n**0.5) + 1):\n if n % i == 0:\n return False\n \n return True\n\n# Test cases\nif __name__ == \"__main__\":\n assert prime_length('Hello') == True # length 5 is prime\n assert prime_length('abcdcba') == True # length 7 is prime\n assert prime_length('kittens') == True # length 7 is prime\n assert prime_length('orange') == False # length 6 is not prime\n assert prime_length('') == False # length 0 is not prime\n assert prime_length('a') == False # length 1 is not prime\n assert prime_length('abcd') == False # length 4 is not prime\n print(\"All tests passed!\")\n```"}
{"task_id": "HumanEval/83", "solution": "```python\ndef starts_one_ends(n):\n \"\"\"\n Given a positive integer n, return the count of the numbers of n-digit\n positive integers that start or end with 1.\n \"\"\"\n # Case for single digit numbers: only the number '1' satisfies the condition.\n if n == 1:\n return 1\n \n # For n > 1, we use the Principle of Inclusion-Exclusion:\n # Total = |Starts with 1| + |Ends with 1| - |Starts and Ends with 1|\n \n # 1. Numbers that start with 1:\n # The first digit is fixed as '1'. The remaining (n-1) digits can be any of 0-9.\n # Count = 1 * 10**(n-1)\n starts_with_one = 10**(n - 1)\n \n # 2. Numbers that end with 1:\n # The last digit is fixed as '1'. \n # The first digit can be any of 1-9 (cannot be 0).\n # The middle (n-2) digits can be any of 0-9.\n # Count = 9 * 10**(n-2) * 1\n ends_with_one = 9 * 10**(n - 2)\n \n # 3. Numbers that both start and end with 1:\n # The first digit is fixed as '1'.\n # The last digit is fixed as '1'.\n # The middle (n-2) digits can be any of 0-9.\n # Count = 1 * 10**(n-2) * 1\n both_start_end_one = 10**(n - 2)\n \n return starts_with_one + ends_with_one - both_start_end_one\n\n# Example usage and testing:\nif __name__ == \"__main__\":\n test_cases = {\n 1: 1, # Only [1]\n 2: 18, # Starts with 1: [10-19] (10), Ends with 1: [11, 21...91] (9). Intersection: [11]. 10+9-1 = 18.\n 3: 180, # Starts: 100, Ends: 90, Both: 10. 100+90-10 = 180.\n }\n \n for n_val, expected in test_cases.items():\n result = starts_one_ends(n_val)\n print(f\"n={n_val}: Expected {expected}, Got {result} - {'Correct' if result == expected else 'Wrong'}\")\n```"}
{"task_id": "HumanEval/84", "solution": "```python\ndef solve(N):\n \"\"\"Given a positive integer N, return the total sum of its digits in binary.\n \n Example\n For N = 1000, the sum of digits will be 1 the output should be \"1\".\n For N = 150, the sum of digits will be 6 the output should be \"110\".\n For N = 147, the sum of digits will be 12 the output should be \"1100\".\n \n Variables:\n @N integer\n Constraints: 0 \u2264 N \u2264 10000.\n Output:\n a string of binary number\n \"\"\"\n # Step 1: Calculate the sum of digits of N in base 10\n # We convert N to a string, iterate through each character, \n # convert it back to an integer and sum them up.\n digit_sum = sum(int(digit) for digit in str(N))\n \n # Step 2: Convert the resulting sum into its binary representation\n # bin() returns a string starting with '0b', so we slice from index 2 onwards.\n binary_representation = bin(digit_sum)[2:]\n \n return binary_representation\n\n# Test cases to verify the function\nif __name__ == \"__main__\":\n test_cases = [\n (1000, \"1\"),\n (150, \"110\"),\n (147, \"1100\"),\n (0, \"0\"),\n (9999, \"100100\") # Sum is 36, binary of 36 is 100100\n ]\n \n for n_val, expected in test_cases:\n result = solve(n_val)\n print(f\"N = {n_val}, Expected = {expected}, Result = {result} | {'Pass' if result == expected else 'Fail'}\")\n```"}
{"task_id": "HumanEval/85", "solution": "```python\ndef add(lst):\n \"\"\"Given a non-empty list of integers lst, add the even elements that are at odd indices.\n\n Examples:\n add([4, 2, 6, 7]) ==> 2 \n \"\"\"\n # We iterate through the list starting from index 1 (the first odd index),\n # stepping by 2 to only visit odd indices.\n total = 0\n for i in range(1, len(lst), 2):\n if lst[i] % 2 == 0:\n total += lst[i]\n return total\n\n# Test cases to verify the function\nif __name__ == \"__main__\":\n test_cases = [\n ([4, 2, 6, 7], 2), # Index 1 is 2 (even), Index 3 is 7 (odd). Sum: 2\n ([1, 2, 3, 4], 6), # Index 1 is 2 (even), Index 3 is 4 (even). Sum: 6\n ([1, 1, 1, 1], 0), # Index 1 is 1 (odd), Index 3 is 1 (odd). Sum: 0\n ([2, 4, 8, 10], 14), # Index 1 is 4 (even), Index 3 is 10 (even). Sum: 14\n ([5], 0), # No odd indices. Sum: 0\n ]\n\n for lst, expected in test_cases:\n result = add(lst)\n print(f\"add({lst}) ==> Expected: {expected}, Got: {result} | {'Pass' if result == expected else 'Fail'}\")\n```"}
{"task_id": "HumanEval/86", "solution": "```python\ndef anti_shuffle(s):\n \"\"\"\n Write a function that takes a string and returns an ordered version of it.\n Ordered version of string, is a string where all words (separated by space)\n are replaced by a new word where all the characters arranged in\n ascending order based on ascii value.\n Note: You should keep the order of words and blank spaces in the sentence.\n\n For example:\n anti_shuffle('Hi') returns 'Hi'\n anti_shuffle('hello') returns 'ehllo'\n anti_shuffle('Hello World!!!') returns 'Hello !!!Wdlor'\n \"\"\"\n # Split the string by a single space to preserve multiple spaces if they exist.\n words = s.split(' ')\n \n sorted_words = []\n for word in words:\n # sorted() takes an iterable and returns a list of elements \n # sorted in ascending order based on their ASCII values.\n sorted_chars = sorted(word)\n # Join the sorted characters back into a single string.\n sorted_words.append(\"\".join(sorted_chars))\n \n # Join the processed words back together using a single space as the separator.\n return \" \".join(sorted_words)\n\n# Test cases to verify the functionality\nif __name__ == \"__main__\":\n test_cases = [\n ('Hi', 'Hi'),\n ('hello', 'ehllo'),\n ('Hello World!!!', 'Hello !!!Wdlor'),\n (' multiple spaces ', ' multiple acesps '), # Testing edge case with spaces\n ('', ''), # Testing empty string\n ]\n\n for input_str, expected in test_cases:\n result = anti_shuffle(input_str)\n print(f\"Input: '{input_str}' | Expected: '{expected}' | Result: '{result}' | Success: {result == expected}\")\n```"}
{"task_id": "HumanEval/87", "solution": "```python\ndef get_row(lst, x):\n \"\"\"\n You are given a 2 dimensional data, as a nested lists,\n which is similar to matrix, however, unlike matrices,\n each row may contain a different number of columns.\n Given lst, and integer x, find integers x in the list,\n and return list of tuples, [(x1, y1), (x2, y2) ...] such that\n each tuple is a coordinate - (row, columns), starting with 0.\n Sort coordinates initially by rows in ascending order.\n Also, sort coordinates of the row by columns in descending order.\n \"\"\"\n result = []\n \n # Iterate through each row and its index\n for r_idx, row in enumerate(lst):\n # Find all column indices where the value equals x\n cols = [c_idx for c_idx, val in enumerate(row) if val == x]\n \n # Sort the column indices for this specific row in descending order\n cols.sort(reverse=True)\n \n # Append the coordinates as tuples to the result list\n for c_idx in cols:\n result.append((r_idx, c_idx))\n \n return result\n\n# Test cases to verify the implementation\nif __name__ == \"__main__\":\n test1 = get_row([\n [1,2,3,4,5,6],\n [1,2,3,4,1,6],\n [1,2,3,4,5,1]\n ], 1)\n print(f\"Test 1: {test1} == [(0, 0), (1, 4), (1, 0), (2, 5), (2, 0)]\")\n assert test1 == [(0, 0), (1, 4), (1, 0), (2, 5), (2, 0)]\n\n test2 = get_row([], 1)\n print(f\"Test 2: {test2} == []\")\n assert test2 == []\n\n test3 = get_row([[], [1], [1, 2, 3]], 3)\n print(f\"Test 3: {test3} == [(2, 2)]\")\n assert test3 == [(2, 2)]\n \n print(\"All tests passed!\")\n```"}
{"task_id": "HumanEval/88", "solution": "```python\ndef sort_array(array):\n \"\"\"\n Given an array of non-negative integers, return a copy of the given array after sorting,\n you will sort the given array in ascending order if the sum( first index value, last index value) is odd,\n or sort it in descending order if the sum( first index value, last index value) is even.\n\n Note:\n * don't change the given array.\n\n Examples:\n * sort_array([]) => []\n * sort_array([5]) => [5]\n * sort_array([2, 4, 3, 0, 1, 5]) => [0, 1, 2, 3, 4, 5]\n * sort_array([2, 4, 3, 0, 1, 5, 6]) => [6, 5, 4, 3, 2, 1, 0]\n \"\"\"\n # Handle empty array case\n if not array:\n return []\n\n # Calculate the sum of the first and last elements\n first_val = array[0]\n last_val = array[-1]\n total_sum = first_val + last_val\n\n # Determine sorting order based on parity of the sum\n if total_sum % 2 != 0:\n # Sum is odd: sort in ascending order\n return sorted(array)\n else:\n # Sum is even: sort in descending order\n return sorted(array, reverse=True)\n\n# Test cases to verify the implementation\nif __name__ == \"__main__\":\n assert sort_array([]) == []\n assert sort_array([5]) == [5]\n assert sort_array([2, 4, 3, 0, 1, 5]) == [0, 1, 2, 3, 4, 5]\n assert sort_array([2, 4, 3, 0, 1, 5, 6]) == [6, 5, 4, 3, 2, 1, 0]\n print(\"All test cases passed!\")\n```"}
{"task_id": "HumanEval/89", "solution": "```python\ndef encrypt(s):\n \"\"\"Create a function encrypt that takes a string as an argument and\n returns a string encrypted with the alphabet being rotated. \n The alphabet should be rotated in a manner such that the letters \n shift down by two multiplied to two places (2 * 2 = 4).\n \n For example:\n encrypt('hi') returns 'lm'\n encrypt('asdfghjkl') returns 'ewhjklnop'\n encrypt('gf') returns 'kj'\n encrypt('et') returns 'ix'\n \"\"\"\n # The shift is defined as \"two multiplied to two places\", which equals 4.\n shift = 4\n result = []\n\n for char in s:\n if 'a' <= char <= 'z':\n # Calculate the new character for lowercase letters\n # ord('a') provides the ASCII value of 'a' (97)\n shifted_char = chr((ord(char) - ord('a') + shift) % 26 + ord('a'))\n result.append(shifted_char)\n elif 'A' <= char <= 'Z':\n # Calculate the new character for uppercase letters\n # ord('A') provides the ASCII value of 'A' (65)\n shifted_char = chr((ord(char) - ord('A') + shift) % 26 + ord('A'))\n result.append(shifted_char)\n else:\n # If the character is not a letter, keep it as is\n result.append(char)\n\n return \"\".join(result)\n\n# Test cases to verify the function\nif __name__ == \"__main__\":\n test_cases = {\n 'hi': 'lm',\n 'asdfghjkl': 'ewhjklnop',\n 'gf': 'kj',\n 'et': 'ix'\n }\n\n for input_str, expected in test_cases.items():\n actual = encrypt(input_str)\n print(f\"encrypt('{input_str}') -> Expected: '{expected}', Actual: '{actual}' | {'Pass' if actual == expected else 'Fail'}\")\n```"}
{"task_id": "HumanEval/90", "solution": "```python\ndef next_smallest(lst):\n \"\"\"\n You are given a list of integers.\n Write a function next_smallest() that returns the 2nd smallest element of the list.\n Return None if there is no such element.\n \n next_smallest([1, 2, 3, 4, 5]) == 2\n next_smallest([5, 1, 4, 3, 2]) == 2\n next_smallest([]) == None\n next_smallest([1, 1]) == None\n \"\"\"\n # Remove duplicates by converting the list to a set\n unique_elements = set(lst)\n \n # Sort the unique elements in ascending order\n sorted_elements = sorted(list(unique_elements))\n \n # If there are fewer than 2 unique elements, return None\n if len(sorted_elements) < 2:\n return None\n \n # Return the second element in the sorted list\n return sorted_elements[1]\n\n# Test cases to verify the function\nif __name__ == \"__main__\":\n assert next_smallest([1, 2, 3, 4, 5]) == 2\n assert next_smallest([5, 1, 4, 3, 2]) == 2\n assert next_smallest([]) == None\n assert next_smallest([1, 1]) == None\n assert next_smallest([10, 20, 10, 30]) == 20\n assert next_smallest([5]) == None\n print(\"All test cases passed!\")\n```"}
{"task_id": "HumanEval/91", "solution": "```python\nimport re\n\ndef is_bored(S):\n \"\"\"\n You'll be given a string of words, and your task is to count the number\n of boredoms. A boredom is a sentence that starts with the word \"I\".\n Sentences are delimited by '.', '?' or '!'.\n \n For example:\n >>> is_bored(\"Hello world\")\n 0\n >>> is_bored(\"The sky is blue. The sun is shining. I love this weather\")\n 1\n \"\"\"\n # Use regular expressions to split the string by any of the delimiters '.', '?', or '!'\n sentences = re.split(r'[.?!]', S)\n \n count = 0\n for sentence in sentences:\n # Remove leading and trailing whitespace from the sentence\n sentence = sentence.strip()\n \n # Skip empty strings resulting from consecutive delimiters or trailing punctuation\n if not sentence:\n continue\n \n # Split the sentence into words to isolate the first word\n words = sentence.split()\n \n # Check if the list of words is not empty and the first word is exactly \"I\"\n if words and words[0] == \"I\":\n count += 1\n \n return count\n\n# Test cases\nif __name__ == \"__main__\":\n print(f\"Test 1: {is_bored('Hello world')} (Expected: 0)\")\n print(f\"Test 2: {is_bored('The sky is blue. The sun is shining. I love this weather')} (Expected: 1)\")\n print(f\"Test 3: {is_bored('I am bored! I hate this. Why am I here? I want to leave.')} (Expected: 3)\")\n print(f\"Test 4: {is_bored('Ice cream is great. I like it!')} (Expected: 1)\")\n print(f\"Test 5: {is_bored('')} (Expected: 0)\")\n```"}
{"task_id": "HumanEval/92", "solution": "```python\ndef any_int(x, y, z):\n '''\n Create a function that takes 3 numbers.\n Returns true if one of the numbers is equal to the sum of the other two, and all numbers are integers.\n Returns false in any other cases.\n \n Examples:\n any_int(5, 2, 7) \u279e True\n any_int(3, 2, 2) \u279e False\n any_int(3, -2, 1) \u279e True\n any_int(3.6, -2.2, 2) \u279e False\n '''\n # First, check if all three inputs are of type int\n if not (isinstance(x, int) and isinstance(y, int) and isinstance(z, int)):\n return False\n \n # Check if any one number is the sum of the other two\n return (x + y == z) or (x + z == y) or (y + z == x)\n\n# Test cases to verify the function\nif __name__ == \"__main__\":\n print(f\"any_int(5, 2, 7) \u279e {any_int(5, 2, 7)}\") # Expected: True\n print(f\"any_int(3, 2, 2) \u279e {any_int(3, 2, 2)}\") # Expected: False\n print(f\"any_int(3, -2, 1) \u279e {any_int(3, -2, 1)}\") # Expected: True\n print(f\"any_int(3.6, -2.2, 2) \u279e {any_int(3.6, -2.2, 2)}\") # Expected: False\n```"}
{"task_id": "HumanEval/93", "solution": "```python\ndef encode(message):\n \"\"\"\n Write a function that takes a message, and encodes in such a \n way that it swaps case of all letters, replaces all vowels in \n the message with the letter that appears 2 places ahead of that \n vowel in the english alphabet. \n Assume only letters. \n \n Examples:\n >>> encode('test')\n 'TGST'\n >>> encode('This is a message')\n 'tHKS KS C MGSSCGG'\n \"\"\"\n vowels = \"aeiouAEIOU\"\n result = []\n \n for char in message:\n # First, swap the case of the character\n swapped_char = char.swapcase()\n \n # If the original character was a vowel, shift the swapped version 2 places ahead\n if char in vowels:\n # ord() gets ASCII value, chr() converts it back to a character\n encoded_char = chr(ord(swapped_char) + 2)\n result.append(encoded_char)\n else:\n # If not a vowel, just use the swapped case version\n result.append(swapped_char)\n \n return \"\".join(result)\n\nif __name__ == \"__main__\":\n # Test cases provided in the docstring\n test1 = 'test'\n expected1 = 'TGST'\n print(f\"Input: {test1} | Expected: {expected1} | Result: {encode(test1)}\")\n \n test2 = 'This is a message'\n expected2 = 'tHKS KS C MGSSCGG'\n print(f\"Input: {test2} | Expected: {expected2} | Result: {encode(test2)}\")\n\n # Additional test case for uppercase vowels\n test3 = 'Apple'\n # A (vowel) -> a -> c\n # p -> P\n # p -> P\n # l -> L\n # e (vowel) -> E -> G\n expected3 = 'cPP LG' # Wait, Apple has 5 letters. Let's trace: A(c), p(P), p(P), l(L), e(G) -> cPPLG\n print(f\"Input: {test3} | Result: {encode(test3)}\")\n```"}
{"task_id": "HumanEval/94", "solution": "```python\ndef skjkasdkd(lst):\n \"\"\"You are given a list of integers.\n You need to find the largest prime value and return the sum of its digits.\n\n Examples:\n For lst = [0,3,2,1,3,5,7,4,5,5,5,2,181,32,4,32,3,2,32,324,4,3] the output should be 10\n For lst = [1,0,1,8,2,4597,2,1,3,40,1,2,1,2,4,2,5,1] the output should be 25\n For lst = [1,3,1,32,5107,34,83278,109,163,23,2323,32,30,1,9,3] the output should be 13\n For lst = [0,724,32,71,99,32,6,0,5,91,83,0,5,6] the output should be 11\n For lst = [0,81,12,3,1,21] the output should be 3\n For lst = [0,8,1,2,1,7] the output should be 7\n \"\"\"\n\n def is_prime(n):\n \"\"\"Helper function to check if a number is prime.\"\"\"\n if n < 2:\n return False\n if n == 2:\n return True\n if n % 2 == 0:\n return False\n # Check odd divisors up to the square root of n\n for i in range(3, int(n**0.5) + 1, 2):\n if n % i == 0:\n return False\n return True\n\n max_prime = -1\n \n # Iterate through the list to find the largest prime number\n for num in lst:\n if is_prime(num):\n if num > max_prime:\n max_prime = num\n \n # If no prime was found, return 0 or a suitable default value\n if max_prime == -1:\n return 0\n \n # Calculate the sum of digits of the largest prime number\n digit_sum = sum(int(digit) for digit in str(max_prime))\n \n return digit_sum\n\n# Test cases to verify the function\nif __name__ == \"__main__\":\n test_cases = [\n ([0,3,2,1,3,5,7,4,5,5,5,2,181,32,4,32,3,2,32,324,4,3], 10),\n ([1,0,1,8,2,4597,2,1,3,40,1,2,1,2,4,2,5,1], 25),\n ([1,3,1,32,5107,34,83278,109,163,23,2323,32,30,1,9,3], 13),\n ([0,724,32,71,99,32,6,0,5,91,83,0,5,6], 11),\n ([0,81,12,3,1,21], 3),\n ([0,8,1,2,1,7], 7),\n ]\n\n for lst, expected in test_cases:\n result = skjkasdkd(lst)\n print(f\"Input: {lst} | Expected: {expected} | Result: {result} | {'Pass' if result == expected else 'Fail'}\")\n```"}
{"task_id": "HumanEval/95", "solution": "```python\ndef check_dict_case(dictionary):\n \"\"\"\n Given a dictionary, return True if all keys are strings in lower \n case or all keys are strings in upper case, else return False.\n The function should return False is the given dictionary is empty.\n Examples:\n check_dict_case({\"a\":\"apple\", \"b\":\"banana\"}) should return True.\n check_dict_case({\"a\":\"apple\", \"A\":\"banana\", \"B\":\"banana\"}) should return False.\n check_dict_case({\"a\":\"apple\", 8:\"banana\", \"a\":\"apple\"}) should return False.\n check_dict_case({\"Name\":\"John\", \"Age\":\"36\", \"City\":\"Houston\"}) should return False.\n check_dict_case({\"STATE\":\"NC\", \"ZIP\":\"12345\" }) should return True.\n \"\"\"\n # Return False if the dictionary is empty\n if not dictionary:\n return False\n\n keys = list(dictionary.keys())\n\n # Check if all keys are strings; if any key is not a string, return False\n for key in keys:\n if not isinstance(key, str):\n return False\n\n # A key is considered \"lowercase\" if it equals its own lowercase version\n # and \"uppercase\" if it equals its own uppercase version.\n # We check if every single key satisfies the lower condition OR \n # every single key satisfies the upper condition.\n all_lower = all(key == key.lower() for key in keys)\n all_upper = all(key == key.upper() for key in keys)\n\n return all_lower or all_upper\n\n# Test cases to verify the function\nif __name__ == \"__main__\":\n test_cases = [\n ({\"a\": \"apple\", \"b\": \"banana\"}, True),\n ({\"a\": \"apple\", \"A\": \"banana\", \"B\": \"banana\"}, False),\n ({\"a\": \"apple\", 8: \"banana\", \"a\": \"apple\"}, False),\n ({\"Name\": \"John\", \"Age\": \"36\", \"City\": \"Houston\"}, False),\n ({\"STATE\": \"NC\", \"ZIP\": \"12345\"}, True),\n ({}, False), # Empty dictionary case\n ]\n\n for i, (input_dict, expected) in enumerate(test_cases):\n result = check_dict_case(input_dict)\n print(f\"Test {i+1}: Input={input_dict}, Expected={expected}, Result={result} {'\u2705' if result == expected else '\u274c'}\")\n```"}
{"task_id": "HumanEval/96", "solution": "```python\ndef count_up_to(n):\n \"\"\"Implement a function that takes an non-negative integer and returns an array of the first n\n integers that are prime numbers and less than n.\n for example:\n count_up_to(5) => [2,3]\n count_up_to(11) => [2,3,5,7]\n count_up_to(0) => []\n count_up_to(20) => [2,3,5,7,11,13,17,19]\n count_up_to(1) => []\n count_up_to(18) => [2,3,5,7,11,13,17]\n \"\"\"\n def is_prime(num):\n if num < 2:\n return False\n for i in range(2, int(num**0.5) + 1):\n if num % i == 0:\n return False\n return True\n\n primes = []\n # We iterate from 2 up to (but not including) n\n for i in range(2, n):\n if is_prime(i):\n primes.append(i)\n return primes\n\n# Test cases to verify the implementation\nif __name__ == \"__main__\":\n test_cases = [\n (5, [2, 3]),\n (11, [2, 3, 5, 7]),\n (0, []),\n (20, [2, 3, 5, 7, 11, 13, 17, 19]),\n (1, []),\n (18, [2, 3, 5, 7, 11, 13, 17]),\n ]\n\n for val, expected in test_cases:\n result = count_up_to(val)\n print(f\"count_up_to({val}) => {result} | Expected: {expected} | {'PASS' if result == expected else 'FAIL'}\")\n```"}
{"task_id": "HumanEval/97", "solution": "```python\ndef multiply(a, b):\n \"\"\"Complete the function that takes two integers and returns \n the product of their unit digits.\n Assume the input is always valid.\n Examples:\n multiply(148, 412) should return 16.\n multiply(19, 28) should return 72.\n multiply(2020, 1851) should return 0.\n multiply(14,-15) should return 20.\n \"\"\"\n # The unit digit is the last digit of a number.\n # We use abs() to ensure that negative numbers are treated by their absolute value,\n # as the \"unit digit\" of -15 is typically considered to be 5.\n digit_a = abs(a) % 10\n digit_b = abs(b) % 10\n return digit_a * digit_b\n\n# Test cases to verify the function\nif __name__ == \"__main__\":\n test_cases = [\n (148, 412, 16),\n (19, 28, 72),\n (2020, 1851, 0),\n (14, -15, 20),\n ]\n\n for a, b, expected in test_cases:\n result = multiply(a, b)\n print(f\"multiply({a}, {b}) -> Expected: {expected}, Got: {result} | {'Pass' if result == expected else 'Fail'}\")\n```"}
{"task_id": "HumanEval/98", "solution": "```python\ndef count_upper(s):\n \"\"\"\n Given a string s, count the number of uppercase vowels in even indices.\n \n For example:\n count_upper('aBCdEf') returns 1\n count_upper('abcdefg') returns 0\n count_upper('dBBE') returns 0\n \"\"\"\n # Define the set of uppercase vowels\n vowels = {'A', 'E', 'I', 'O', 'U'}\n count = 0\n \n # Iterate through the string using a step of 2 to only visit even indices (0, 2, 4...)\n for i in range(0, len(s), 2):\n if s[i] in vowels:\n count += 1\n \n return count\n\n# Test cases\nif __name__ == \"__main__\":\n assert count_upper('aBCdEf') == 1\n assert count_upper('abcdefg') == 0\n assert count_upper('dBBE') == 0\n assert count_upper('AEIOU') == 3 # Indices 0(A), 2(I), 4(U) are uppercase vowels\n assert count_upper('AbCdEfIg') == 1 # Index 6 is 'I' (uppercase vowel)\n print(\"All tests passed!\")\n```"}
{"task_id": "HumanEval/99", "solution": "```python\nimport math\n\ndef closest_integer(value):\n '''\n Create a function that takes a value (string) representing a number\n and returns the closest integer to it. If the number is equidistant\n from two integers, round it away from zero.\n\n Examples\n >>> closest_integer(\"10\")\n 10\n >>> closest_integer(\"15.3\")\n 15\n >>> closest_integer(\"14.5\")\n 15\n >>> closest_integer(\"-14.5\")\n -15\n '''\n # Convert the input string to a float for calculation\n num = float(value)\n \n if num >= 0:\n # For positive numbers, adding 0.5 and flooring handles \"round half up\"\n # e.g., 14.4 + 0.5 = 14.9 -> floor is 14\n # e.g., 14.5 + 0.5 = 15.0 -> floor is 15\n return int(math.floor(num + 0.5))\n else:\n # For negative numbers, subtracting 0.5 and ceiling handles \"round half down\" (away from zero)\n # e.g., -14.4 - 0.5 = -14.9 -> ceil is -14\n # e.g., -14.5 - 0.5 = -15.0 -> ceil is -15\n return int(math.ceil(num - 0.5))\n\nif __name__ == \"__main__\":\n # Test cases to verify the logic\n test_cases = [\n (\"10\", 10),\n (\"15.3\", 15),\n (\"14.5\", 15),\n (\"-14.5\", -15),\n (\"14.4\", 14),\n (\"-14.4\", -14),\n (\"0\", 0),\n (\"-0.5\", -1),\n (\"0.5\", 1),\n ]\n\n for val, expected in test_cases:\n result = closest_integer(val)\n print(f\"Input: {val} | Expected: {expected} | Result: {result} | {'\u2705' if result == expected else '\u274c'}\")\n```"}
{"task_id": "HumanEval/100", "solution": "```python\ndef make_a_pile(n):\n \"\"\"\n Given a positive integer n, you have to make a pile of n levels of stones.\n The first level has n stones.\n The number of stones in the next level is:\n - the next odd number if n is odd.\n - the next even number if n is even.\n Return the number of stones in each level in a list, where element at index\n i represents the number of stones in the level (i+1).\n\n Examples:\n >>> make_a_pile(3)\n [3, 5, 7]\n \"\"\"\n # The problem describes an arithmetic progression starting at n with a common difference of 2.\n # Since we need n levels, the sequence will be [n, n+2, n+4, ..., n + 2*(n-1)].\n return [n + 2 * i for i in range(n)]\n\nif __name__ == \"__main__\":\n # Test cases\n print(f\"make_a_pile(3): {make_a_pile(3)}\") # Expected: [3, 5, 7]\n print(f\"make_a_pile(4): {make_a_pile(4)}\") # Expected: [4, 6, 8, 10]\n print(f\"make_a_pile(1): {make_a_pile(1)}\") # Expected: [1]\n```"}
{"task_id": "HumanEval/101", "solution": "```python\ndef words_string(s):\n \"\"\"\n You will be given a string of words separated by commas or spaces. Your task is\n to split the string into words and return an array of the words.\n \n For example:\n words_string(\"Hi, my name is John\") == [\"Hi\", \"my\", \"name\", \"is\", \"John\"]\n words_string(\"One, two, three, four, five, six\") == [\"One\", \"two\", \"three\", \"four\", \"five\", \"six\"]\n \"\"\"\n # Replace all commas with spaces so that the string only contains space-separated words.\n # Then use .split() without arguments, which splits by any whitespace \n # and automatically discards empty strings resulting from multiple separators.\n return s.replace(',', ' ').split()\n\n# Test cases to verify the solution\nif __name__ == \"__main__\":\n test_cases = [\n (\"Hi, my name is John\", [\"Hi\", \"my\", \"name\", \"is\", \"John\"]),\n (\"One, two, three, four, five, six\", [\"One\", \"two\", \"three\", \"four\", \"five\", \"six\"]),\n (\"Hello world\", [\"Hello\", \"world\"]),\n (\"Apple,Banana,Orange\", [\"Apple\", \"Banana\", \"Orange\"]),\n (\" Multiple spaces and , commas \", [\"Multiple\", \"spaces\", \"and\", \"commas\"]),\n ]\n\n for input_str, expected in test_cases:\n result = words_string(input_str)\n assert result == expected, f\"Failed on {input_str}: expected {expected}, got {result}\"\n \n print(\"All tests passed!\")\n```"}
{"task_id": "HumanEval/102", "solution": "```python\ndef choose_num(x, y):\n \"\"\"This function takes two positive numbers x and y and returns the\n biggest even integer number that is in the range [x, y] inclusive. If \n there's no such number, then the function should return -1.\n\n For example:\n choose_num(12, 15) = 14\n choose_num(13, 12) = -1\n \"\"\"\n # If x is greater than y, the range [x, y] is empty\n if x > y:\n return -1\n \n # Start checking from the upper bound y downwards\n # If y is even, it's the biggest even number in the range\n if y % 2 == 0:\n return y\n \n # If y is odd, check if the number immediately below it (y-1) \n # is within the lower bound x. Since y is odd, y-1 must be even.\n if y - 1 >= x:\n return y - 1\n \n # If neither y nor y-1 are valid even numbers in [x, y], return -1\n return -1\n\n# Test cases to verify the function\nif __name__ == \"__main__\":\n print(f\"choose_num(12, 15): {choose_num(12, 15)}\") # Expected: 14\n print(f\"choose_num(13, 12): {choose_num(13, 12)}\") # Expected: -1\n print(f\"choose_num(10, 10): {choose_num(10, 10)}\") # Expected: 10\n print(f\"choose_num(11, 11): {choose_num(11, 11)}\") # Expected: -1\n print(f\"choose_num(5, 6): {choose_num(5, 6)}\") # Expected: 6\n print(f\"choose_num(5, 5): {choose_num(5, 5)}\") # Expected: -1\n```"}
{"task_id": "HumanEval/103", "solution": "```python\ndef rounded_avg(n, m):\n \"\"\"You are given two positive integers n and m, and your task is to compute the\n average of the integers from n through m (including n and m). \n Round the answer to the nearest integer and convert that to binary.\n If n is greater than m, return -1.\n Example:\n rounded_avg(1, 5) => \"0b11\"\n rounded_avg(7, 5) => -1\n rounded_avg(10, 20) => \"0b1111\"\n rounded_avg(20, 33) => \"0b11010\"\n \"\"\"\n # If n is greater than m, return -1 as per requirements.\n if n > m:\n return -1\n \n # The average of a sequence of consecutive integers from n to m is (n + m) / 2.\n # This is derived from the sum formula: Sum = ((m - n + 1) * (n + m)) / 2\n # Average = Sum / count = (((m - n + 1) * (n + m)) / 2) / (m - n + 1) = (n + m) / 2.\n avg = (n + m) / 2\n \n # Round the average to the nearest integer.\n # Python's round() function rounds half to even, which matches the example:\n # rounded_avg(20, 33) -> avg is 26.5 -> round(26.5) is 26 -> bin(26) is '0b11010'.\n rounded_val = round(avg)\n \n # Convert the integer to its binary representation string.\n return bin(rounded_val)\n\nif __name__ == \"__main__\":\n # Test cases provided in the docstring\n print(f\"rounded_avg(1, 5): {rounded_avg(1, 5)}\") # Expected: \"0b11\"\n print(f\"rounded_avg(7, 5): {rounded_avg(7, 5)}\") # Expected: -1\n print(f\"rounded_avg(10, 20): {rounded_avg(10, 20)}\") # Expected: \"0b1111\"\n print(f\"rounded_avg(20, 33): {rounded_avg(20, 33)}\") # Expected: \"0b11010\"\n```"}
{"task_id": "HumanEval/104", "solution": "```python\ndef unique_digits(x):\n \"\"\"Given a list of positive integers x, return a sorted list of all \n elements that haven't any even digit.\n\n Note: Returned list should be sorted in increasing order.\n \n For example:\n >>> unique_digits([15, 33, 1422, 1])\n [1, 15, 33]\n >>> unique_digits([152, 323, 1422, 10])\n []\n \"\"\"\n result = []\n for num in x:\n # Convert the number to a string to iterate through each digit\n s_num = str(num)\n # Check if all digits in the string are odd\n # A digit is odd if int(digit) % 2 != 0\n if all(int(digit) % 2 != 0 for digit in s_num):\n result.append(num)\n \n # Return the filtered list sorted in increasing order\n return sorted(result)\n\nif __name__ == \"__main__\":\n # Test cases\n print(unique_digits([15, 33, 1422, 1])) # Expected: [1, 15, 33]\n print(unique_digits([152, 323, 1422, 10])) # Expected: []\n```"}
{"task_id": "HumanEval/105", "solution": "```python\ndef by_length(arr):\n \"\"\"\n Given an array of integers, sort the integers that are between 1 and 9 inclusive,\n reverse the resulting array, and then replace each digit by its corresponding name from\n \"One\", \"Two\", \"Three\", \"Four\", \"Five\", \"Six\", \"Seven\", \"Eight\", \"Nine\".\n\n For example:\n arr = [2, 1, 1, 4, 5, 8, 2, 3] \n -> sort arr -> [1, 1, 2, 2, 3, 4, 5, 8] \n -> reverse arr -> [8, 5, 4, 3, 2, 2, 1, 1]\n return [\"Eight\", \"Five\", \"Four\", \"Three\", \"Two\", \"Two\", \"One\", \"One\"]\n \n If the array is empty, return an empty array:\n arr = []\n return []\n \n If the array has any strange number ignore it:\n arr = [1, -1 , 55] \n -> sort arr -> [-1, 1, 55]\n -> reverse arr -> [55, 1, -1]\n return = ['One']\n \"\"\"\n # Mapping of integers to their corresponding names\n digit_map = {\n 1: \"One\",\n 2: \"Two\",\n 3: \"Three\",\n 4: \"Four\",\n 5: \"Five\",\n 6: \"Six\",\n 7: \"Seven\",\n 8: \"Eight\",\n 9: \"Nine\"\n }\n\n # 1. Filter the array to keep only integers between 1 and 9 inclusive\n filtered_arr = [x for x in arr if 1 <= x <= 9]\n\n # 2. Sort the filtered integers (ascending)\n filtered_arr.sort()\n\n # 3. Reverse the resulting array (descending)\n filtered_arr.reverse()\n\n # 4. Replace each digit by its corresponding name from the map\n result = [digit_map[x] for x in filtered_arr]\n\n return result\n\n# Test cases to verify functionality\nif __name__ == \"__main__\":\n test_cases = [\n ([2, 1, 1, 4, 5, 8, 2, 3], [\"Eight\", \"Five\", \"Four\", \"Three\", \"Two\", \"Two\", \"One\", \"One\"]),\n ([], []),\n ([1, -1, 55], [\"One\"]),\n ([9, 1, 5], [\"Nine\", \"Five\", \"One\"]),\n ([10, 0, -5], []),\n ]\n\n for input_arr, expected in test_cases:\n actual = by_length(input_arr)\n print(f\"Input: {input_arr} | Expected: {expected} | Actual: {actual} | {'PASS' if actual == expected else 'FAIL'}\")\n```"}
{"task_id": "HumanEval/106", "solution": "```python\nimport math\n\ndef f(n):\n \"\"\" Implement the function f that takes n as a parameter,\n and returns a list of size n, such that the value of the element at index i is the factorial of i if i is even\n or the sum of numbers from 1 to i otherwise.\n i starts from 1.\n the factorial of i is the multiplication of the numbers from 1 to i (1 * 2 * ... * i).\n Example:\n f(5) == [1, 2, 6, 24, 15]\n \"\"\"\n result = []\n # The problem states i starts from 1 and the list size is n.\n for i in range(1, n + 1):\n if i % 2 == 0:\n # If i is even, calculate factorial of i\n result.append(math.factorial(i))\n else:\n # If i is odd, calculate the sum from 1 to i\n # Formula for sum of first n integers: (n * (n + 1)) // 2\n result.append((i * (i + 1)) // 2)\n return result\n\nif __name__ == \"__main__\":\n # Test the function with the provided example\n print(f(5)) # Expected output: [1, 2, 6, 24, 15]\n```"}
{"task_id": "HumanEval/107", "solution": "```python\ndef even_odd_palindrome(n):\n \"\"\"\n Given a positive integer n, return a tuple that has the number of even and odd\n integer palindromes that fall within the range(1, n), inclusive.\n\n Example 1:\n Input: 3\n Output: (1, 2)\n Explanation:\n Integer palindrome are 1, 2, 3. one of them is even, and two of them are odd.\n\n Example 2:\n Input: 12\n Output: (4, 6)\n Explanation:\n Integer palindrome are 1, 2, 3, 4, 5, 6, 7, 8, 9, 11. four of them are even, and 6 of them are odd.\n\n Note:\n 1. 1 <= n <= 10^3\n 2. returned tuple has the number of even and odd integer palindromes respectively.\n \"\"\"\n even_count = 0\n odd_count = 0\n \n # Iterate through all numbers from 1 to n inclusive\n for i in range(1, n + 1):\n # Convert the number to a string to check if it's a palindrome\n s = str(i)\n if s == s[::-1]:\n # If it is a palindrome, check if the integer is even or odd\n if i % 2 == 0:\n even_count += 1\n else:\n odd_count += 1\n \n return (even_count, odd_count)\n\n# Test cases to verify the function\nif __name__ == \"__main__\":\n print(f\"Input: 3, Output: {even_odd_palindrome(3)}\") # Expected: (1, 2)\n print(f\"Input: 12, Output: {even_odd_palindrome(12)}\") # Expected: (4, 6)\n```"}
{"task_id": "HumanEval/108", "solution": "```python\ndef count_nums(arr):\n \"\"\"\n Write a function count_nums which takes an array of integers and returns\n the number of elements which has a sum of digits > 0.\n If a number is negative, then its first signed digit will be negative:\n e.g. -123 has signed digits -1, 2, and 3.\n >>> count_nums([]) == 0\n >>> count_nums([-1, 11, -11]) == 1\n >>> count_nums([1, 1, 2]) == 3\n \"\"\"\n count = 0\n for num in arr:\n # Convert the absolute value of the number to a string to iterate through digits\n s = str(abs(num))\n digits = [int(d) for d in s]\n \n # If the original number was negative, the first digit is treated as negative\n if num < 0:\n digits[0] = -digits[0]\n \n # Calculate the sum of these signed digits\n if sum(digits) > 0:\n count += 1\n \n return count\n\nif __name__ == \"__main__\":\n # Test cases provided in the docstring\n print(f\"Test 1 (Empty): {count_nums([]) == 0}\")\n print(f\"Test 2 (Mixed): {count_nums([-1, 11, -11]) == 1}\")\n print(f\"Test 3 (Positive): {count_nums([1, 1, 2]) == 3}\")\n \n # Additional test cases\n print(f\"Test 4 (-123 -> sum is -1+2+3=4): {count_nums([-123]) == 1}\")\n print(f\"Test 5 (0 -> sum is 0): {count_nums([0]) == 0}\")\n```"}
{"task_id": "HumanEval/109", "solution": "```python\ndef move_one_ball(arr):\n \"\"\"We have an array 'arr' of N integers arr[1], arr[2], ..., arr[N].The\n numbers in the array will be randomly ordered. Your task is to determine if\n it is possible to get an array sorted in non-decreasing order by performing \n the following operation on the given array:\n You are allowed to perform right shift operation any number of times.\n \n One right shift operation means shifting all elements of the array by one\n position in the right direction. The last element of the array will be moved to\n the starting position in the array i.e. 0th index. \n\n If it is possible to obtain the sorted array by performing the above operation\n then return True else return False.\n If the given array is empty then return True.\n\n Note: The given list is guaranteed to have unique elements.\n\n For Example:\n \n move_one_ball([3, 4, 5, 1, 2])==>True\n Explanation: By performin 2 right shift operations, non-decreasing order can\n be achieved for the given array.\n move_one_ball([3, 5, 4, 1, 2])==>False\n Explanation:It is not possible to get non-decreasing order for the given\n array by performing any number of right shift operations.\n \n \"\"\"\n # If the array is empty, return True as per problem description.\n if not arr:\n return True\n \n n = len(arr)\n # A sequence can be rotated to become sorted if and only if there is at most \n # one point in the cyclic order where an element is greater than the next one.\n # For unique elements, a perfectly sorted array will have exactly one such drop \n # when considering the wrap-around from the last element back to the first.\n \n drops = 0\n for i in range(n):\n # Compare current element with the next element (using modulo for cyclic check)\n if arr[i] > arr[(i + 1) % n]:\n drops += 1\n \n # If there is more than one drop, it's impossible to sort by rotation.\n # If there is 0 or 1 drop, it can be sorted (or is already sorted).\n return drops <= 1\n\n# Test cases\nif __name__ == \"__main__\":\n assert move_one_ball([3, 4, 5, 1, 2]) == True\n assert move_one_ball([3, 5, 4, 1, 2]) == False\n assert move_one_ball([]) == True\n assert move_one_ball([1, 2, 3]) == True\n assert move_one_ball([2, 3, 1]) == True\n assert move_one_ball([3, 2, 1]) == False\n print(\"All test cases passed!\")\n\n```"}
{"task_id": "HumanEval/110", "solution": "```python\ndef exchange(lst1, lst2):\n \"\"\"In this problem, you will implement a function that takes two lists of numbers,\n and determines whether it is possible to perform an exchange of elements\n between them to make lst1 a list of only even numbers.\n There is no limit on the number of exchanged elements between lst1 and lst2.\n If it is possible to exchange elements between the lst1 and lst2 to make\n all the elements of lst1 to be even, return \"YES\".\n Otherwise, return \"NO\".\n For example:\n exchange([1, 2, 3, 4], [1, 2, 3, 4]) => \"YES\"\n exchange([1, 2, 3, 4], [1, 5, 3, 4]) => \"NO\"\n It is assumed that the input lists will be non-empty.\n \"\"\"\n # Count how many odd numbers are currently in lst1.\n # These are the elements that MUST be replaced to make lst1 all even.\n odds_in_lst1 = len([x for x in lst1 if x % 2 != 0])\n \n # Count how many even numbers are available in lst2.\n # These are the only candidates that can replace odd numbers in lst1 to maintain/achieve parity.\n evens_in_lst2 = len([x for x in lst2 if x % 2 == 0])\n \n # If we have at least as many even numbers in lst2 as there are odd numbers in lst1,\n # we can swap every odd number in lst1 with an even number from lst2.\n if evens_in_lst2 >= odds_in_lst1:\n return \"YES\"\n else:\n return \"NO\"\n\n# Test cases to verify the implementation\nif __name__ == \"__main__\":\n assert exchange([1, 2, 3, 4], [1, 2, 3, 4]) == \"YES\"\n assert exchange([1, 2, 3, 4], [1, 5, 3, 4]) == \"NO\"\n assert exchange([2, 4, 6], [1, 3, 5]) == \"YES\"\n assert exchange([1, 3, 5], [2, 4, 6]) == \"YES\"\n assert exchange([1, 3, 5], [2, 4]) == \"NO\"\n print(\"All test cases passed!\")\n```"}
{"task_id": "HumanEval/111", "solution": "```python\ndef histogram(test):\n \"\"\"Given a string representing a space separated lowercase letters, return a dictionary\n of the letter with the most repetition and containing the corresponding count.\n If several letters have the same occurrence, return all of them.\n \n Example:\n histogram('a b c') == {'a': 1, 'b': 1, 'c': 1}\n histogram('a b b a') == {'a': 2, 'b': 2}\n histogram('a b c a b') == {'a': 2, 'b': 2}\n histogram('b b b b a') == {'b': 4}\n histogram('') == {}\n \"\"\"\n # Handle the empty string case immediately\n if not test.strip():\n return {}\n\n # Split the input string into individual characters based on whitespace\n letters = test.split()\n \n # Create a frequency map of all letters present in the list\n counts = {}\n for char in letters:\n counts[char] = counts.get(char, 0) + 1\n \n # Determine the maximum number of occurrences found\n max_count = max(counts.values())\n \n # Extract all keys that have a value equal to the maximum count\n result = {k: v for k, v in counts.items() if v == max_count}\n \n return result\n\n# Test cases to verify correctness\nif __name__ == \"__main__\":\n assert histogram('a b c') == {'a': 1, 'b': 1, 'c': 1}\n assert histogram('a b b a') == {'a': 2, 'b': 2}\n assert histogram('a b c a b') == {'a': 2, 'b': 2}\n assert histogram('b b b b a') == {'b': 4}\n assert histogram('') == {}\n print(\"All test cases passed!\")\n```"}
{"task_id": "HumanEval/112", "solution": "```python\ndef reverse_delete(s, c):\n \"\"\"Task\n We are given two strings s and c, you have to deleted all the characters in s that are equal to any character in c\n then check if the result string is palindrome.\n A string is called palindrome if it reads the same backward as forward.\n You should return a tuple containing the result string and True/False for the check.\n Example\n For s = \"abcde\", c = \"ae\", the result should be ('bcd',False)\n For s = \"abcdef\", c = \"b\" the result should be ('acdef',False)\n For s = \"abcdedcba\", c = \"ab\", the result should be ('cdedc',True)\n \"\"\"\n # Create a set of characters to delete for O(1) lookup time\n chars_to_delete = set(c)\n \n # Filter out characters in s that are present in the deletion set\n result_string = \"\".join([char for char in s if char not in chars_to_delete])\n \n # A string is a palindrome if it equals its reverse\n is_palindrome = result_string == result_string[::-1]\n \n return (result_string, is_palindrome)\n\n# Test cases to verify the function\nif __name__ == \"__main__\":\n test_cases = [\n (\"abcde\", \"ae\", ('bcd', False)),\n (\"abcdef\", \"b\", ('acdef', False)),\n (\"abcdedcba\", \"ab\", ('cdedc', True)),\n (\"racecar\", \"\", ('racecar', True)),\n (\"hello\", \"helo\", ('', True)), # Empty string is considered a palindrome\n ]\n\n for s, c, expected in test_cases:\n result = reverse_delete(s, c)\n print(f\"s='{s}', c='{c}' -> Result: {result}, Expected: {expected}, Match: {result == expected}\")\n```"}
{"task_id": "HumanEval/113", "solution": "```python\ndef odd_count(lst):\n \"\"\"Given a list of strings, where each string consists of only digits, return a list.\n Each element i of the output should be \"the number of odd elements in the\n string i of the input.\" where all the i's should be replaced by the number\n of odd digits in the i'th string of the input.\n\n >>> odd_count(['1234567'])\n [\"the number of odd elements 4n the str4ng 4 of the 4nput.\"]\n >>> odd_count(['3',\"11111111\"])\n [\"the number of odd elements 1n the str1ng 1 of the 1nput.\",\n \"the number of odd elements 8n the str8ng 8 of the 8nput.\"]\n \"\"\"\n result = []\n # The template sentence containing 'i' characters to be replaced.\n template = \"the number of odd elements in the string i of the input.\"\n \n for s in lst:\n # Count how many digits in the current string are odd.\n count = 0\n for char in s:\n if int(char) % 2 != 0:\n count += 1\n \n # Replace every occurrence of 'i' with the calculated count.\n modified_sentence = template.replace('i', str(count))\n result.append(modified_sentence)\n \n return result\n\nif __name__ == \"__main__\":\n import doctest\n doctest.testmod()\n```"}
{"task_id": "HumanEval/114", "solution": "```python\ndef minSubArraySum(nums):\n \"\"\"\n Given an array of integers nums, find the minimum sum of any non-empty sub-array\n of nums.\n Example\n minSubArraySum([2, 3, 4, 1, 2, 4]) == 1\n minSubArraySum([-1, -2, -3]) == -6\n \"\"\"\n if not nums:\n return 0\n\n # We use a variation of Kadane's Algorithm.\n # Instead of tracking the maximum subarray sum, we track the minimum.\n \n # Initialize current_min and min_so_far with the first element to handle non-empty requirement.\n current_min = nums[0]\n min_so_far = nums[0]\n\n for i in range(1, len(nums)):\n # At each index, we decide whether to start a new subarray at the current element\n # or extend the existing minimum subarray ending at the previous index.\n current_min = min(nums[i], current_min + nums[i])\n \n # Update the global minimum found so far.\n min_so_far = min(min_so_far, current_min)\n\n return min_so_far\n\nif __name__ == \"__main__\":\n # Test cases\n test_cases = [\n ([2, 3, 4, 1, 2, 4], 1),\n ([-1, -2, -3], -6),\n ([1, -2, 3], -2),\n ([10, -5, -2, 10], -7),\n ([5], 5),\n ([-5], -5),\n ]\n\n for nums, expected in test_cases:\n result = minSubArraySum(nums)\n print(f\"minSubArraySum({nums}) = {result}; Expected: {expected} | {'PASS' if result == expected else 'FAIL'}\")\n```"}
{"task_id": "HumanEval/115", "solution": "```python\nimport math\n\ndef max_fill(grid, capacity):\n \"\"\"\n You are given a rectangular grid of wells. Each row represents a single well,\n and each 1 in a row represents a single unit of water.\n Each well has a corresponding bucket that can be used to extract water from it, \n and all buckets have the same capacity.\n Your task is to use the buckets to empty the wells.\n Output the number of times you need to lower the buckets.\n\n Example 1:\n Input: \n grid : [[0,0,1,0], [0,1,0,0], [1,1,1,1]]\n bucket_capacity : 1\n Output: 6\n\n Example 2:\n Input: \n grid : [[0,0,1,1], [0,0,0,0], [1,1,1,1], [0,1,1,1]]\n bucket_capacity : 2\n Output: 5\n \n Example 3:\n Input: \n grid : [[0,0,0], [0,0,0]]\n bucket_capacity : 5\n Output: 0\n \"\"\"\n total_trips = 0\n \n for row in grid:\n # Count the number of units of water (1s) in the current well\n water_count = sum(row)\n \n # Calculate how many times the bucket must be lowered for this specific well.\n # We use ceiling division because any remaining water requires an additional trip.\n trips_for_well = math.ceil(water_count / capacity)\n \n total_trips += trips_for_well\n \n return total_trips\n\n# Test cases to verify the implementation\nif __name__ == \"__main__\":\n test_cases = [\n {\n \"grid\": [[0, 0, 1, 0], [0, 1, 0, 0], [1, 1, 1, 1]],\n \"capacity\": 1,\n \"expected\": 6\n },\n {\n \"grid\": [[0, 0, 1, 1], [0, 0, 0, 0], [1, 1, 1, 1], [0, 1, 1, 1]],\n \"capacity\": 2,\n \"expected\": 5\n },\n {\n \"grid\": [[0, 0, 0], [0, 0, 0]],\n \"capacity\": 5,\n \"expected\": 0\n }\n ]\n\n for i, tc in enumerate(test_cases):\n result = max_fill(tc[\"grid\"], tc[\"capacity\"])\n print(f\"Example {i+1}: Expected {tc['expected']}, Got {result} - {'PASSED' if result == tc['expected'] else 'FAILED'}\")\n\n```"}
{"task_id": "HumanEval/116", "solution": "```python\ndef sort_array(arr):\n \"\"\"\n Sorts an array of integers according to the number of ones in their \n binary representation in ascending order. For numbers with the same \n number of ones, they are sorted based on their decimal value in ascending order.\n\n Note: In Python, bin() for negative numbers returns a string like '-0b101'.\n The count of '1's is performed on the binary representation of the absolute value.\n \"\"\"\n # The key function returns a tuple (primary_key, secondary_key)\n # Primary key: number of ones in binary representation\n # Secondary key: the decimal value itself\n return sorted(arr, key=lambda x: (bin(x).count('1'), x))\n\nif __name__ == \"__main__\":\n # Test Case 1: Mixed positive integers\n # 1 (0b1) -> 1 one\n # 2 (0b10) -> 1 one\n # 4 (0b100) -> 1 one\n # 3 (0b11) -> 2 ones\n # 5 (0b101) -> 2 ones\n # Expected: [1, 2, 4, 3, 5]\n test1 = [1, 5, 2, 3, 4]\n result1 = sort_array(test1)\n print(f\"Input: {test1} -> Result: {result1}\")\n\n # Test Case 2: Negative integers (based on absolute binary representation)\n # -2 (-0b10) -> 1 one\n # -4 (-0b100) -> 1 one\n # -3 (-0b11) -> 2 ones\n # -5 (-0b101) -> 2 ones\n # -6 (-0b110) -> 2 ones\n # Expected: [-4, -2, -6, -5, -3]\n test2 = [-2, -3, -4, -5, -6]\n result2 = sort_array(test2)\n print(f\"Input: {test2} -> Result: {result2}\")\n\n # Test Case 3: Including zero\n # 0 (0b0) -> 0 ones\n # 1 (0b1) -> 1 one\n # 2 (0b10) -> 1 one\n # 4 (0b100) -> 1 one\n # 3 (0b11) -> 2 ones\n # Expected: [0, 1, 2, 4, 3]\n test3 = [1, 0, 2, 3, 4]\n result3 = sort_array(test3)\n print(f\"Input: {test3} -> Result: {result3}\")\n\n # Verification against the logic described in the prompt text\n assert result1 == [1, 2, 4, 3, 5], \"Test Case 1 Failed\"\n assert result2 == [-4, -2, -6, -5, -3], \"Test Case 2 Failed\"\n assert result3 == [0, 1, 2, 4, 3], \"Test Case 3 Failed\"\n print(\"\\nAll tests passed based on the written logic!\")\n```"}
{"task_id": "HumanEval/117", "solution": "```python\ndef select_words(s, n):\n \"\"\"Given a string s and a natural number n, you have been tasked to implement \n a function that returns a list of all words from string s that contain exactly \n n consonants, in order these words appear in the string s.\n If the string s is empty then the function should return an empty list.\n Note: you may assume the input string contains only letters and spaces.\n Examples:\n select_words(\"Mary had a little lamb\", 4) ==> [\"little\"]\n select_words(\"Mary had a little lamb\", 3) ==> [\"Mary\", \"lamb\"]\n select_words(\"simple white space\", 2) ==> []\n select_words(\"Hello world\", 4) ==> [\"world\"]\n select_words(\"Uncle sam\", 3) ==> [\"Uncle\"]\n \"\"\"\n if not s:\n return []\n\n # Define vowels for comparison. \n # Based on the examples provided, 'y' is treated as a consonant.\n vowels = set(\"aeiouAEIOU\")\n \n # Split the string into words based on whitespace\n words = s.split()\n result = []\n\n for word in words:\n # Count characters that are not vowels\n # Since input is guaranteed to be only letters and spaces, \n # any character in a word that isn't a vowel is a consonant.\n consonant_count = sum(1 for char in word if char not in vowels)\n \n if consonant_count == n:\n result.append(word)\n\n return result\n\n# Test cases to verify the implementation\nif __name__ == \"__main__\":\n assert select_words(\"Mary had a little lamb\", 4) == [\"little\"]\n assert select_words(\"Mary had a little lamb\", 3) == [\"Mary\", \"lamb\"]\n assert select_words(\"simple white space\", 2) == []\n assert select_words(\"Hello world\", 4) == [\"world\"]\n assert select_words(\"Uncle sam\", 3) == [\"Uncle\"]\n assert select_words(\"\", 3) == []\n print(\"All test cases passed!\")\n```"}
{"task_id": "HumanEval/118", "solution": "```python\ndef get_closest_vowel(word):\n \"\"\"You are given a word. Your task is to find the closest vowel that stands between \n two consonants from the right side of the word (case sensitive).\n \n Vowels in the beginning and ending doesn't count. Return empty string if you didn't\n find any vowel met the above condition. \n\n You may assume that the given string contains English letter only.\n\n Example:\n get_closest_vowel(\"yogurt\") ==> \"u\"\n get_closest_vowel(\"FULL\") ==> \"U\"\n get_closest_vowel(\"quick\") ==> \"\"\n get_closest_vowel(\"ab\") ==> \"\"\n \"\"\"\n vowels = set(\"aeiouAEIOU\")\n \n # We iterate from the right side of the word.\n # A vowel must be between two consonants, so it cannot be at index 0 or index len(word)-1.\n # Therefore, we check indices from len(word) - 2 down to 1.\n for i in range(len(word) - 2, 0, -1):\n char = word[i]\n if char in vowels:\n # Check if the character to the left and right are consonants.\n # Since we assume only English letters, a consonant is any letter not in the vowel set.\n left_char = word[i - 1]\n right_char = word[i + 1]\n \n if left_char not in vowels and right_char not in vowels:\n return char\n \n return \"\"\n\n# Test cases to verify the logic\nif __name__ == \"__main__\":\n assert get_closest_vowel(\"yogurt\") == \"u\"\n assert get_closest_vowel(\"FULL\") == \"U\"\n assert get_closest_vowel(\"quick\") == \"\"\n assert get_closest_vowel(\"ab\") == \"\"\n print(\"All test cases passed!\")\n```"}
{"task_id": "HumanEval/119", "solution": "```python\ndef match_parens(lst):\n '''\n You are given a list of two strings, both strings consist of open\n parentheses '(' or close parentheses ')' only.\n Your job is to check if it is possible to concatenate the two strings in\n some order, that the resulting string will be good.\n A string S is considered to be good if and only if all parentheses in S\n are balanced. For example: the string '(())()' is good, while the string\n '())' is not.\n Return 'Yes' if there's a way to make a good string, and return 'No' otherwise.\n\n Examples:\n match_parens(['()(', ')']) == 'Yes'\n match_parens([')', ')']) == 'No'\n '''\n def is_balanced(s):\n \"\"\"Helper function to check if a parentheses string is balanced.\"\"\"\n balance = 0\n for char in s:\n if char == '(':\n balance += 1\n else:\n balance -= 1\n # If balance drops below zero, there are more closing than opening parens at this point\n if balance < 0:\n return False\n # The string is balanced only if the final count of open and close parens are equal\n return balance == 0\n\n s1 = lst[0]\n s2 = lst[1]\n\n # Check both possible concatenation orders: s1 + s2 and s2 + s1\n if is_balanced(s1 + s2) or is_balanced(s2 + s1):\n return 'Yes'\n else:\n return 'No'\n\n# Test cases to verify the solution\nif __name__ == \"__main__\":\n assert match_parens(['()(', ')']) == 'Yes'\n assert match_parens([')', ')']) == 'No'\n assert match_parens(['((', '))']) == 'Yes'\n assert match_parens(['))', '((']) == 'Yes' # s2 + s1 is balanced\n assert match_parens(['(', ')']) == 'Yes'\n assert match_parens(['(', '(']) == 'No'\n print(\"All tests passed!\")\n```"}
{"task_id": "HumanEval/120", "solution": "```python\ndef maximum(arr, k):\n \"\"\"\n Given an array arr of integers and a positive integer k, return a sorted list \n of length k with the maximum k numbers in arr.\n\n Example 1:\n Input: arr = [-3, -4, 5], k = 3\n Output: [-4, -3, 5]\n\n Example 2:\n Input: arr = [4, -4, 4], k = 2\n Output: [4, 4]\n\n Example 3:\n Input: arr = [-3, 2, 1, 2, -1, -2, 1], k = 1\n Output: [2]\n \"\"\"\n # If k is 0, return an empty list as per the constraints (0 <= k <= len(arr))\n if k == 0:\n return []\n\n # Sort the array in ascending order.\n # Time Complexity: O(N log N) where N is the length of the array.\n sorted_arr = sorted(arr)\n \n # The maximum k numbers will be at the end of the sorted list.\n # Slicing from index -k to the end gives us these elements in ascending order.\n return sorted_arr[-k:]\n\n# Test cases to verify the implementation\nif __name__ == \"__main__\":\n test_cases = [\n ([-3, -4, 5], 3, [-4, -3, 5]),\n ([4, -4, 4], 2, [4, 4]),\n ([-3, 2, 1, 2, -1, -2, 1], 1, [2]),\n ([1, 2, 3, 4, 5], 0, []),\n ([10, 20, 30], 2, [20, 30]),\n ]\n\n for i, (arr, k, expected) in enumerate(test_cases):\n result = maximum(arr, k)\n print(f\"Test Case {i+1}: Input arr={arr}, k={k} | Expected: {expected} | Result: {result} | {'PASSED' if result == expected else 'FAILED'}\")\n```"}
{"task_id": "HumanEval/121", "solution": "```python\ndef solution(lst):\n \"\"\"Given a non-empty list of integers, return the sum of all of the odd elements that are in even positions.\n \n\n Examples\n solution([5, 8, 7, 1]) ==> 12\n solution([3, 3, 3, 3, 3]) ==> 9\n solution([30, 13, 24, 321]) ==> 0\n \"\"\"\n # lst[::2] slices the list to get elements at indices 0, 2, 4... (even positions)\n # We then filter for elements that are odd (x % 2 != 0) and sum them.\n return sum(x for x in lst[::2] if x % 2 != 0)\n\n# Test cases to verify the solution\nif __name__ == \"__main__\":\n assert solution([5, 8, 7, 1]) == 12\n assert solution([3, 3, 3, 3, 3]) == 9\n assert solution([30, 13, 24, 321]) == 0\n print(\"All tests passed!\")\n```"}
{"task_id": "HumanEval/122", "solution": "```python\ndef add_elements(arr, k):\n \"\"\"\n Given a non-empty array of integers arr and an integer k, return\n the sum of the elements with at most two digits from the first k elements of arr.\n\n Example:\n Input: arr = [111, 21, 3, 4000, 5, 6, 7, 8, 9], k = 4\n Output: 24 # sum of 21 + 3\n\n Constraints:\n 1. 1 <= len(arr) <= 100\n 2. 1 <= k <= len(arr)\n \"\"\"\n # Slice the array to get only the first k elements\n first_k = arr[:k]\n \n # Initialize sum variable\n total_sum = 0\n \n for num in first_k:\n # A number has at most two digits if its absolute value is less than 100.\n # This covers numbers from -99 to 99.\n if abs(num) < 100:\n total_sum += num\n \n return total_sum\n\n# Test cases to verify the solution\nif __name__ == \"__main__\":\n test_cases = [\n {\"arr\": [111, 21, 3, 4000, 5, 6, 7, 8, 9], \"k\": 4, \"expected\": 24},\n {\"arr\": [1, 2, 3, 4, 5], \"k\": 5, \"expected\": 15},\n {\"arr\": [100, 200, 300], \"k\": 3, \"expected\": 0},\n {\"arr\": [10, -10, 100, -100], \"k\": 4, \"expected\": 0}, # 10 + (-10) = 0\n {\"arr\": [5, 15, 25, 105], \"k\": 4, \"expected\": 45}, # 5 + 15 + 25 = 45\n ]\n\n for i, tc in enumerate(test_cases):\n result = add_elements(tc[\"arr\"], tc[\"k\"])\n print(f\"Test Case {i+1}: Input arr={tc['arr']}, k={tc['k']} | Expected: {tc['expected']}, Result: {result} | {'PASSED' if result == tc['expected'] else 'FAILED'}\")\n```"}
{"task_id": "HumanEval/123", "solution": "```python\ndef get_odd_collatz(n):\n \"\"\"\n Given a positive integer n, return a sorted list that has the odd numbers in collatz sequence.\n\n The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined\n as follows: start with any positive integer n. Then each term is obtained from the \n previous term as follows: if the previous term is even, the next term is one half of \n the previous term. If the previous term is odd, the next term is 3 times the previous\n term plus 1. The conjecture is that no matter what value of n, the sequence will always reach 1.\n\n Note: \n 1. Collatz(1) is [1].\n 2. returned list sorted in increasing order.\n\n For example:\n get_odd_collatz(5) returns [1, 5] # The collatz sequence for 5 is [5, 16, 8, 4, 2, 1], so the odd numbers are only 1, and 5.\n \"\"\"\n odds = []\n current = n\n \n # Generate the Collatz sequence until it reaches 1\n while current != 1:\n if current % 2 != 0:\n odds.append(current)\n current = 3 * current + 1\n else:\n current = current // 2\n \n # The loop stops when current == 1, and since 1 is odd, we add it to the list\n odds.append(1)\n \n # Return the list sorted in increasing order\n return sorted(odds)\n\n# Test cases to verify the function\nif __name__ == \"__main__\":\n print(f\"get_odd_collatz(5): {get_odd_collatz(5)}\") # Expected: [1, 5]\n print(f\"get_odd_collatz(1): {get_odd_collatz(1)}\") # Expected: [1]\n print(f\"get_odd_collatz(7): {get_odd_collatz(7)}\") # Sequence: 7, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1\n # Odds: [7, 11, 17, 13, 5, 1] -> Sorted: [1, 5, 13, 17, 11, 7] is wrong.\n # Correct sorted odds for 7: [1, 5, 11, 13, 17, 7] wait... [1, 5, 11, 13, 17, 7] no.\n # Sorted: [1, 5, 11, 13, 17, 7] -> [1, 5, 7, 11, 13, 17]\n```"}
{"task_id": "HumanEval/124", "solution": "```python\ndef valid_date(date):\n \"\"\"You have to write a function which validates a given date string and\n returns True if the date is valid otherwise False.\n The date is valid if all of the following rules are satisfied:\n 1. The date string is not empty.\n 2. The number of days is not less than 1 or higher than 31 days for months 1,3,5,7,8,10,12. \n And the number of days is not less than 1 or higher than 30 days for months 4,6,9,11. \n And, the number of days is not less than 1 or higher than 29 for the month 2.\n 3. The months should not be less than 1 or higher than 12.\n 4. The date should be in the format: mm-dd-yyyy\n \"\"\"\n # Rule 1: Check if the string is empty\n if not date:\n return False\n\n # Rule 4: Check for correct format (mm-dd-yyyy)\n # Split by '-' to isolate month, day, and year\n parts = date.split('-')\n if len(parts) != 3:\n return False\n\n month_str, day_str, year_str = parts\n\n # Ensure the format is strictly mm-dd-yyyy (lengths must be 2, 2, 4)\n # and that all components consist only of digits.\n if len(month_str) != 2 or len(day_str) != 2 or len(year_str) != 4:\n return False\n \n if not (month_str.isdigit() and day_str.isdigit() and year_str.isdigit()):\n return False\n\n # Convert strings to integers for value validation\n try:\n m = int(month_str)\n d = int(day_str)\n y = int(year_str)\n except ValueError:\n return False\n\n # Rule 3: The months should not be less than 1 or higher than 12.\n if m < 1 or m > 12:\n return False\n\n # Rule 2: Validate days based on the month\n if m in [1, 3, 5, 7, 8, 10, 12]:\n if d < 1 or d > 31:\n return False\n elif m in [4, 6, 9, 11]:\n if d < 1 or d > 30:\n return False\n elif m == 2:\n # The prompt specifies a hard limit of 29 for February regardless of leap year logic.\n if d < 1 or d > 29:\n return False\n\n return True\n\n# Test cases provided in the docstring\nif __name__ == \"__main__\":\n print(valid_date('03-11-2000')) # Expected: True\n print(valid_date('15-01-2012')) # Expected: False\n print(valid_date('04-0-2040')) # Expected: False\n print(valid_date('06-04-2020')) # Expected: True\n print(valid_date('06/04/2020')) # Expected: False\n```"}
{"task_id": "HumanEval/125", "solution": "```python\ndef split_words(txt):\n '''\n Given a string of words, return a list of words split on whitespace, if no whitespaces exists in the text you\n should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the\n alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25\n Examples\n split_words(\"Hello world!\") \u279e [\"Hello\", \"world!\"]\n split_words(\"Hello,world!\") \u279e [\"Hello\", \"world!\"]\n split_words(\"abcdef\") == 3 \n '''\n # Check if any whitespace characters exist in the string\n if any(char.isspace() for char in txt):\n return txt.split()\n \n # If no whitespaces, check if commas exist\n if ',' in txt:\n return txt.split(',')\n \n # If neither whitespaces nor commas exist, count lowercase letters with odd alphabet indices\n count = 0\n for char in txt:\n if 'a' <= char <= 'z':\n # Calculate index: a=0, b=1, c=2...\n index = ord(char) - ord('a')\n if index % 2 != 0:\n count += 1\n return count\n\n# Test cases to verify the functionality\nif __name__ == \"__main__\":\n print(f\"Test 1 ('Hello world!'): {split_words('Hello world!')}\") # Expected: [\"Hello\", \"world!\"]\n print(f\"Test 2 ('Hello,world!'): {split_words('Hello,world!')}\") # Expected: [\"Hello\", \"world!\"]\n print(f\"Test 3 ('abcdef'): {split_words('abcdef')}\") # Expected: 3 (b=1, d=3, f=5)\n print(f\"Test 4 ('xyz'): {split_words('xyz')}\") # Expected: 1 (y=24 is even, z=25 is odd, x=23 is odd? No: x=23, y=24, z=25. Odd are x and z)\n # Let's re-verify alphabet indices:\n # a:0, b:1, c:2, d:3, e:4, f:5, g:6, h:7, i:8, j:9, k:10, l:11, m:12, n:13, o:14, p:15, q:16, r:17, s:18, t:19, u:20, v:21, w:22, x:23, y:24, z:25\n # For 'xyz': x(23), y(24), z(25) -> 23 and 25 are odd. Result should be 2.\n```"}
{"task_id": "HumanEval/126", "solution": "```python\ndef is_sorted(lst):\n '''\n Given a list of numbers, return whether or not they are sorted\n in ascending order. If list has more than 1 duplicate of the same\n number (meaning 3 or more occurrences), return False. Assume no negative numbers and only integers.\n\n Examples\n is_sorted([5]) \u279e True\n is_sorted([1, 2, 3, 4, 5]) \u279e True\n is_sorted([1, 3, 2, 4, 5]) \u279e False\n is_sorted([1, 2, 3, 4, 5, 6]) \u279e True\n is_sorted([1, 2, 3, 4, 5, 6, 7]) \u279e True\n is_sorted([1, 3, 2, 4, 5, 6, 7]) \u279e False\n is_sorted([1, 2, 2, 3, 3, 4]) \u279e True\n is_sorted([1, 2, 2, 2, 3, 4]) \u279e False\n '''\n # Check if the list is sorted in ascending order\n for i in range(len(lst) - 1):\n if lst[i] > lst[i + 1]:\n return False\n\n # Check if any number appears more than twice\n # Since we already verified it's sorted, duplicates must be adjacent.\n # However, using a dictionary/count is cleaner and works regardless of order.\n counts = {}\n for num in lst:\n counts[num] = counts.get(num, 0) + 1\n if counts[num] > 2:\n return False\n\n return True\n\n# Test cases to verify the implementation\nif __name__ == \"__main__\":\n test_cases = [\n ([5], True),\n ([1, 2, 3, 4, 5], True),\n ([1, 3, 2, 4, 5], False),\n ([1, 2, 3, 4, 5, 6], True),\n ([1, 2, 3, 4, 5, 6, 7], True),\n ([1, 3, 2, 4, 5, 6, 7], False),\n ([1, 2, 2, 3, 3, 4], True),\n ([1, 2, 2, 2, 3, 4], False),\n ]\n\n for lst, expected in test_cases:\n result = is_sorted(lst)\n print(f\"is_sorted({lst}) \u279e {result} | Expected: {expected} | {'PASS' if result == expected else 'FAIL'}\")\n```"}
{"task_id": "HumanEval/127", "solution": "```python\ndef intersection(interval1, interval2):\n \"\"\"You are given two intervals,\n where each interval is a pair of integers. For example, interval = (start, end) = (1, 2).\n The given intervals are closed which means that the interval (start, end)\n includes both start and end.\n For each given interval, it is assumed that its start is less or equal its end.\n Your task is to determine whether the length of intersection of these two \n intervals is a prime number.\n Example, the intersection of the intervals (1, 3), (2, 4) is (2, 3)\n which its length is 1, which not a prime number.\n If the length of the intersection is a prime number, return \"YES\",\n otherwise, return \"NO\".\n If the two intervals don't intersect, return \"NO\".\n\n\n [input/output] samples:\n intersection((1, 2), (2, 3)) ==> \"NO\"\n intersection((-1, 1), (0, 4)) ==> \"NO\"\n intersection((-3, -1), (-5, 5)) ==> \"YES\"\n \"\"\"\n\n def is_prime(n):\n \"\"\"Helper function to check if a number is prime.\"\"\"\n if n < 2:\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\n # Extract start and end points of the intervals\n start1, end1 = interval1\n start2, end2 = interval2\n\n # The intersection of two closed intervals [a, b] and [c, d] is [max(a, c), min(b, d)]\n max_start = max(start1, start2)\n min_end = min(end1, end2)\n\n # If the maximum start point is greater than the minimum end point, \n # there is no intersection.\n if max_start > min_end:\n return \"NO\"\n\n # The length of a closed interval [a, b] is defined as (b - a).\n length = min_end - max_start\n\n # Check if the calculated length is a prime number.\n if is_prime(length):\n return \"YES\"\n else:\n return \"NO\"\n\n# Test cases to verify the implementation\nif __name__ == \"__main__\":\n assert intersection((1, 2), (2, 3)) == \"NO\"\n assert intersection((-1, 1), (0, 4)) == \"NO\"\n assert intersection((-3, -1), (-5, 5)) == \"YES\"\n print(\"All test cases passed!\")\n\n```"}
{"task_id": "HumanEval/128", "solution": "```python\ndef prod_signs(arr):\n \"\"\"\n You are given an array arr of integers and you need to return\n sum of magnitudes of integers multiplied by product of all signs\n of each number in the array, represented by 1, -1 or 0.\n Note: return None for empty arr.\n\n Example:\n >>> prod_signs([1, 2, 2, -4]) == -9\n >>> prod_signs([0, 1]) == 0\n >>> prod_signs([]) == None\n \"\"\"\n if not arr:\n return None\n\n # Calculate the sum of magnitudes (absolute values)\n sum_magnitudes = sum(abs(x) for x in arr)\n\n # Calculate the product of signs\n # Sign is 1 if x > 0, -1 if x < 0, and 0 if x == 0\n product_of_signs = 1\n for x in arr:\n if x > 0:\n sign = 1\n elif x < 0:\n sign = -1\n else:\n sign = 0\n \n product_of_signs *= sign\n \n # Optimization: if the product becomes 0, it will stay 0\n if product_of_signs == 0:\n break\n\n return sum_magnitudes * product_of_signs\n\nif __name__ == \"__main__\":\n # Test cases\n assert prod_signs([1, 2, 2, -4]) == -9\n assert prod_signs([0, 1]) == 0\n assert prod_signs([]) == None\n print(\"All tests passed!\")\n```"}
{"task_id": "HumanEval/129", "solution": "```python\ndef minPath(grid, k):\n \"\"\"\n Given a grid with N rows and N columns (N >= 2) and a positive integer k, \n each cell of the grid contains a value. Every integer in the range [1, N * N]\n inclusive appears exactly once on the cells of the grid.\n\n You have to find the minimum path of length k in the grid. You can start\n from any cell, and in each step you can move to any of the neighbor cells,\n in other words, you can go to cells which share an edge with your current\n cell.\n A path A (of length k) is considered less than a path B (of length k) if \n the sequence of values in A is lexicographically smaller than that in B.\n\n The strategy for the minimum path:\n 1. To minimize the sequence lexicographically, we must start at the cell with value 1.\n 2. If k = 1, the answer is simply [1].\n 3. If k > 1, the second element should be the smallest possible neighbor of the cell containing 1.\n 4. For the third element, since no value in the grid is smaller than 1, moving back to the \n cell with value 1 is always the optimal choice.\n 5. This pattern (1 -> min_neighbor -> 1 -> min_neighbor ...) continues for k elements.\n \"\"\"\n n = len(grid)\n \n # Find the coordinates of the cell containing the value 1\n start_r, start_c = -1, -1\n for r in range(n):\n for c in range(n):\n if grid[r][c] == 1:\n start_r, start_c = r, c\n break\n if start_r != -1:\n break\n \n # If the path length is 1, the smallest possible sequence is just [1]\n if k == 1:\n return [1]\n \n # Find the minimum value among the neighbors of cell (start_r, start_c)\n min_neighbor = float('inf')\n directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]\n for dr, dc in directions:\n nr, nc = start_r + dr, start_c + dc\n if 0 <= nr < n and 0 <= nc < n:\n if grid[nr][nc] < min_neighbor:\n min_neighbor = grid[nr][nc]\n \n # Construct the path by alternating between 1 and its smallest neighbor\n path = []\n for i in range(k):\n if i % 2 == 0:\n path.append(1)\n else:\n path.append(min_neighbor)\n \n return path\n\n# Example usage:\nif __name__ == \"__main__\":\n print(minPath([[1, 2, 3], [4, 5, 6], [7, 8, 9]], 3)) # Expected Output: [1, 2, 1]\n print(minPath([[5, 9, 3], [4, 1, 6], [7, 8, 2]], 1)) # Expected Output: [1]\n```"}
{"task_id": "HumanEval/130", "solution": "```python\ndef tri(n):\n \"\"\"Everyone knows Fibonacci sequence, it was studied deeply by mathematicians in \n the last couple centuries. However, what people don't know is Tribonacci sequence.\n Tribonacci sequence is defined by the recurrence:\n tri(1) = 3\n tri(n) = 1 + n / 2, if n is even.\n tri(n) = tri(n - 1) + tri(n - 2) + tri(n + 1), if n is odd.\n For example:\n tri(2) = 1 + (2 / 2) = 2\n tri(4) = 3\n tri(3) = tri(2) + tri(1) + tri(4)\n = 2 + 3 + 3 = 8 \n You are given a non-negative integer number n, you have to return a list of the \n first n + 1 numbers of the Tribonacci sequence.\n Examples:\n tri(3) = [1, 3, 2, 8]\n \"\"\"\n # Initialize an empty list to store the sequence values from index 0 up to n\n sequence = []\n \n for i in range(n + 1):\n if i == 1:\n # Explicit definition for tri(1)\n val = 3\n elif i % 2 == 0:\n # Rule for even indices: tri(n) = 1 + n / 2\n val = 1 + (i // 2)\n else:\n # Rule for odd indices (where i > 1): tri(n) = tri(n-1) + tri(n-2) + tri(n+1)\n # Since we are iterating sequentially, sequence[i-1] and sequence[i-2] are already computed.\n # Because i is odd, (i + 1) is even, so we can calculate tri(i+1) using the even rule.\n tri_prev1 = sequence[i - 1]\n tri_prev2 = sequence[i - 2]\n tri_next = 1 + ((i + 1) // 2)\n val = tri_prev1 + tri_prev2 + tri_next\n \n sequence.append(val)\n \n return sequence\n\n# Test cases to verify the implementation\nif __name__ == \"__main__\":\n print(f\"tri(3): {tri(3)}\") # Expected: [1, 3, 2, 8]\n print(f\"tri(0): {tri(0)}\") # Expected: [1]\n print(f\"tri(1): {tri(1)}\") # Expected: [1, 3]\n print(f\"tri(2): {tri(2)}\") # Expected: [1, 3, 2]\n print(f\"tri(4): {tri(4)}\") # Expected: [1, 3, 2, 8, 3]\n print(f\"tri(5): {tri(5)}\") # Expected: [1, 3, 2, 8, 3, 15] (since tri(5) = 3 + 8 + (1+6/2)=15)\n```"}
{"task_id": "HumanEval/131", "solution": "```python\ndef digits(n):\n \"\"\"Given a positive integer n, return the product of the odd digits.\n Return 0 if all digits are even.\n For example:\n digits(1) == 1\n digits(4) == 0\n digits(235) == 15\n \"\"\"\n # Convert integer to string to iterate through each digit\n s = str(n)\n product = 1\n found_odd = False\n \n for char in s:\n digit = int(char)\n # Check if the digit is odd\n if digit % 2 != 0:\n product *= digit\n found_odd = True\n \n # If no odd digits were found, return 0 as per requirements\n return product if found_odd else 0\n\n# Test cases to verify the function\nif __name__ == \"__main__\":\n assert digits(1) == 1\n assert digits(4) == 0\n assert digits(235) == 15\n assert digits(2468) == 0\n assert digits(13579) == 945 # 1 * 3 * 5 * 7 * 9 = 945\n print(\"All test cases passed!\")\n```"}
{"task_id": "HumanEval/132", "solution": "```python\ndef is_nested(string):\n \"\"\"\n Create a function that takes a string as input which contains only square brackets.\n The function should return True if and only if there is a valid subsequence of brackets \n where at least one bracket in the subsequence is nested.\n\n A \"valid nested subsequence\" essentially means we can find four indices i < j < k < l \n such that string[i] == '[', string[j] == '[', string[k] == ']', and string[l] == ']'.\n This forms the pattern [[ ]], which is the simplest form of nesting. Any more complex \n nested valid sequence will also contain this subsequence.\n\n is_nested('[[]]') \u279e True\n is_nested('[]]]]]]][[[[[]') \u279e False\n is_nested('[][]') \u279e False\n is_nested('[]') \u279e False\n is_nested('[[][]]') \u279e True\n is_nested('[[]][[') \u279e True\n \"\"\"\n # Collect the indices of all opening brackets\n opens = [i for i, char in enumerate(string) if char == '[']\n # Collect the indices of all closing brackets\n closes = [i for i, char in enumerate(string) if char == ']']\n \n # To have a nested subsequence [[ ]], we need at least two opening \n # and two closing brackets.\n if len(opens) < 2 or len(closes) < 2:\n return False\n \n # The most likely candidates to satisfy the condition i < j < k < l are:\n # - The first two opening brackets (smallest indices)\n # - The last two closing brackets (largest indices)\n # If the second opening bracket appears before the second-to-last \n # closing bracket, then we have found a nested subsequence.\n return opens[1] < closes[-2]\n\n# Test cases\nif __name__ == \"__main__\":\n assert is_nested('[[]]') == True\n assert is_nested('[]]]]]]][[[[[]') == False\n assert is_nested('[][]') == False\n assert is_nested('[]') == False\n assert is_nested('[[][]]') == True\n assert is_nested('[[]][[') == True\n print(\"All test cases passed!\")\n```"}
{"task_id": "HumanEval/133", "solution": "```python\nimport math\n\ndef sum_squares(lst):\n \"\"\"You are given a list of numbers.\n You need to return the sum of squared numbers in the given list,\n round each element in the list to the upper int(Ceiling) first.\n Examples:\n For lst = [1,2,3] the output should be 14\n For lst = [1,4,9] the output should be 98\n For lst = [1,3,5,7] the output should be 84\n For lst = [1.4,4.2,0] the output should be 29\n For lst = [-2.4,1,1] the output should be 6\n \"\"\"\n return sum(math.ceil(x)**2 for x in lst)\n\n# Test cases to verify the function\nif __name__ == \"__main__\":\n test_cases = [\n ([1, 2, 3], 14),\n ([1, 4, 9], 98),\n ([1, 3, 5, 7], 84),\n ([1.4, 4.2, 0], 29),\n ([-2.4, 1, 1], 6),\n ]\n\n for lst, expected in test_cases:\n result = sum_squares(lst)\n print(f\"sum_squares({lst}) = {result}; Expected: {expected} - {'PASSED' if result == expected else 'FAILED'}\")\n```"}
{"task_id": "HumanEval/134", "solution": "```python\ndef check_if_last_char_is_a_letter(txt):\n '''\n Create a function that returns True if the last character\n of a given string is an alphabetical character and is not\n a part of a word, and False otherwise.\n Note: \"word\" is a group of characters separated by space.\n\n Examples:\n check_if_last_char_is_a_letter(\"apple pie\") \u279e False\n check_if_last_char_is_a_letter(\"apple pi e\") \u279e True\n check_if_last_char_is_a_letter(\"apple pi e \") \u279e False\n check_if_last_char_is_a_letter(\"\") \u279e False \n '''\n # Check if the string is empty\n if not txt:\n return False\n \n # Get the last character of the string\n last_char = txt[-1]\n \n # The last character must be an alphabetical letter\n if not last_char.isalpha():\n return False\n \n # To \"not be part of a word\", the character must either:\n # 1. Be the only character in the string\n # 2. Be preceded by a space\n if len(txt) == 1 or txt[-2] == ' ':\n return True\n \n return False\n\n# Test cases to verify the function\nif __name__ == \"__main__\":\n test_cases = [\n (\"apple pie\", False),\n (\"apple pi e\", True),\n (\"apple pi e \", False),\n (\"\", False),\n (\"a\", True),\n (\"hello z\", True),\n (\"hello 1\", False),\n (\"word\", False),\n ]\n\n for s, expected in test_cases:\n result = check_if_last_char_is_a_letter(s)\n print(f\"Input: '{s}' | Expected: {expected} | Result: {result} | {'\u2705' if result == expected else '\u274c'}\")\n```"}
{"task_id": "HumanEval/135", "solution": "```python\ndef can_arrange(arr):\n \"\"\"Create a function which returns the largest index of an element which\n is not greater than or equal to the element immediately preceding it. If\n no such element exists then return -1. The given array will not contain\n duplicate values.\n\n Examples:\n can_arrange([1,2,4,3,5]) = 3\n can_arrange([1,2,3]) = -1\n \"\"\"\n last_index = -1\n # Start from the second element (index 1) to compare with the preceding one\n for i in range(1, len(arr)):\n # \"Not greater than or equal to\" is equivalent to \"strictly less than\"\n if arr[i] < arr[i-1]:\n last_index = i\n \n return last_index\n\n# Test cases\nif __name__ == \"__main__\":\n assert can_arrange([1, 2, 4, 3, 5]) == 3\n assert can_arrange([1, 2, 3]) == -1\n assert can_arrange([5, 4, 3, 2, 1]) == 4\n assert can_arrange([1, 5, 2, 4, 3]) == 4\n assert can_arrange([]) == -1\n assert can_arrange([10]) == -1\n print(\"All tests passed!\")\n```"}
{"task_id": "HumanEval/136", "solution": "```python\ndef largest_smallest_integers(lst):\n '''\n Create a function that returns a tuple (a, b), where 'a' is\n the largest of negative integers, and 'b' is the smallest\n of positive integers in a list.\n If there is no negative or positive integers, return them as None.\n\n Examples:\n largest_smallest_integers([2, 4, 1, 3, 5, 7]) == (None, 1)\n largest_smallest_integers([]) == (None, None)\n largest_smallest_integers([0]) == (None, None)\n '''\n # Filter the list to get only negative integers\n negatives = [x for x in lst if x < 0]\n # Filter the list to get only positive integers\n positives = [x for x in lst if x > 0]\n \n # Find the maximum of negatives if they exist, otherwise None\n a = max(negatives) if negatives else None\n # Find the minimum of positives if they exist, otherwise None\n b = min(positives) if positives else None\n \n return (a, b)\n\n# Test cases to verify the function\nif __name__ == \"__main__\":\n assert largest_smallest_integers([2, 4, 1, 3, 5, 7]) == (None, 1)\n assert largest_smallest_integers([]) == (None, None)\n assert largest_smallest_integers([0]) == (None, None)\n assert largest_smallest_integers([-1, -2, -3, 4, 5, 6]) == (-1, 4)\n assert largest_smallest_integers([-10, -5, 0, 2, 8]) == (-5, 2)\n assert largest_smallest_integers([-1, -2, -3]) == (-1, None)\n assert largest_smallest_integers([1, 2, 3]) == (None, 1)\n print(\"All test cases passed!\")\n```"}
{"task_id": "HumanEval/137", "solution": "```python\ndef compare_one(a, b):\n \"\"\"\n Create a function that takes integers, floats, or strings representing\n real numbers, and returns the larger variable in its given variable type.\n Return None if the values are equal.\n Note: If a real number is represented as a string, the floating point might be . or ,\n \"\"\"\n def to_float(val):\n # If the value is a string, handle potential comma decimal separators\n if isinstance(val, str):\n return float(val.replace(',', '.'))\n # Otherwise, cast directly to float (handles int and float)\n return float(val)\n\n # Convert both inputs to floats for comparison\n num_a = to_float(a)\n num_b = to_float(b)\n\n if num_a > num_b:\n return a\n elif num_b > num_a:\n return b\n else:\n return None\n\n# Test cases\nif __name__ == \"__main__\":\n print(f'compare_one(1, 2.5) \u279e {compare_one(1, 2.5)}') # Expected: 2.5\n print(f'compare_one(1, \"2,3\") \u279e {compare_one(1, \"2,3\")}') # Expected: \"2,3\"\n print(f'compare_one(\"5,1\", \"6\") \u279e {compare_one(\"5,1\", \"6\")}') # Expected: \"6\"\n print(f'compare_one(\"1\", 1) \u279e {compare_one(\"1\", 1)}') # Expected: None\n```"}
{"task_id": "HumanEval/138", "solution": "```python\ndef is_equal_to_sum_even(n):\n \"\"\"Evaluate whether the given number n can be written as the sum of exactly 4 positive even numbers\n Example\n is_equal_to_sum_even(4) == False\n is_equal_to_sum_even(6) == False\n is_equal_to_sum_even(8) == True\n \"\"\"\n # A number n can be written as the sum of 4 positive even numbers if:\n # 1. n is even (since the sum of any number of even integers is always even).\n # 2. n is at least 8 (the smallest positive even number is 2, and 2 * 4 = 8).\n return n >= 8 and n % 2 == 0\n\nif __name__ == \"__main__\":\n # Test cases provided in the docstring\n assert is_equal_to_sum_even(4) == False\n assert is_equal_to_sum_even(6) == False\n assert is_equal_to_sum_even(8) == True\n \n # Additional test cases\n assert is_equal_to_sum_even(10) == True # 2 + 2 + 2 + 4\n assert is_equal_to_sum_even(7) == False # Odd number\n assert is_equal_to_sum_even(2) == False # Too small\n print(\"All tests passed!\")\n```"}
{"task_id": "HumanEval/139", "solution": "```python\nimport math\n\ndef special_factorial(n):\n \"\"\"The Brazilian factorial is defined as:\n brazilian_factorial(n) = n! * (n-1)! * (n-2)! * ... * 1!\n where n > 0\n\n For example:\n >>> special_factorial(4)\n 288\n\n The function will receive an integer as input and should return the special\n factorial of this integer.\n \"\"\"\n if n <= 0:\n return 0 # Or handle based on specific requirements for non-positive integers\n \n result = 1\n current_factorial = 1\n \n # We iterate from 1 to n. In each step, we update the current factorial (i!)\n # and multiply it into our running total product.\n for i in range(1, n + 1):\n current_factorial *= i\n result *= current_factorial\n \n return result\n\nif __name__ == \"__main__\":\n # Test the example provided in the docstring\n test_val = 4\n print(f\"The special factorial of {test_val} is: {special_factorial(test_val)}\")\n # Expected output: 288\n```"}
{"task_id": "HumanEval/140", "solution": "```python\nimport re\n\ndef fix_spaces(text):\n \"\"\"\n Given a string text, replace all spaces in it with underscores, \n and if a string has more than 2 consecutive spaces, \n then replace all consecutive spaces with - \n \n fix_spaces(\"Example\") == \"Example\"\n fix_spaces(\"Example 1\") == \"Example_1\"\n fix_spaces(\" Example 2\") == \"_Example_2\"\n fix_spaces(\" Example 3\") == \"_Example-3\"\n \"\"\"\n # First, handle the case of more than 2 consecutive spaces.\n # We use a regular expression to find sequences of 3 or more spaces (' {3,}')\n # and replace each such sequence with a single hyphen '-'.\n text = re.sub(r' {3,}', '-', text)\n \n # Then, handle the remaining spaces (single or double).\n # According to the rule \"replace all spaces in it with underscores\",\n # every individual space character left should be converted to an underscore.\n text = text.replace(' ', '_')\n \n return text\n\n# Test cases to verify the functionality\nif __name__ == \"__main__\":\n assert fix_spaces(\"Example\") == \"Example\"\n assert fix_spaces(\"Example 1\") == \"Example_1\"\n assert fix_spaces(\" Example 2\") == \"_Example_2\"\n assert fix_spaces(\" Example 3\") == \"_Example-3\"\n # Additional test for exactly 2 spaces (should become __ based on \"replace all spaces\")\n assert fix_spaces(\"A B\") == \"A__B\"\n # Additional test for more than 3 spaces\n assert fix_spaces(\"A B\") == \"A-B\"\n print(\"All tests passed!\")\n```"}
{"task_id": "HumanEval/141", "solution": "```python\ndef file_name_check(file_name):\n \"\"\"Create a function which takes a string representing a file's name, and returns\n 'Yes' if the the file's name is valid, and returns 'No' otherwise.\n A file's name is considered to be valid if and only if all the following conditions \n are met:\n - There should not be more than three digits ('0'-'9') in the file's name.\n - The file's name contains exactly one dot '.'\n - The substring before the dot should not be empty, and it starts with a letter from \n the latin alphapet ('a'-'z' and 'A'-'Z').\n - The substring after the dot should be one of these: ['txt', 'exe', 'dll']\n \"\"\"\n # Condition 2: Exactly one dot '.'\n if file_name.count('.') != 1:\n return 'No'\n \n # Split the name into prefix and suffix based on the single dot\n prefix, suffix = file_name.split('.')\n \n # Condition 4: The substring after the dot should be one of ['txt', 'exe', 'dll']\n if suffix not in ['txt', 'exe', 'dll']:\n return 'No'\n \n # Condition 3: Substring before the dot should not be empty and starts with a latin letter\n if not prefix:\n return 'No'\n \n first_char = prefix[0]\n if not (('a' <= first_char <= 'z') or ('A' <= first_char <= 'Z')):\n return 'No'\n \n # Condition 1: There should not be more than three digits ('0'-'9') in the file's name\n digit_count = sum(c.isdigit() for c in file_name)\n if digit_count > 3:\n return 'No'\n \n return 'Yes'\n\n# Test cases\nif __name__ == \"__main__\":\n print(file_name_check(\"example.txt\")) # Expected: 'Yes'\n print(file_name_check(\"1example.dll\")) # Expected: 'No' (starts with digit)\n print(file_name_check(\"my_file123.exe\")) # Expected: 'Yes' (exactly 3 digits)\n print(file_name_check(\"my_file1234.exe\")) # Expected: 'No' (more than 3 digits)\n print(file_name_check(\"test.pdf\")) # Expected: 'No' (invalid extension)\n print(file_name_check(\".txt\")) # Expected: 'No' (empty prefix)\n print(file_name_check(\"archive.tar.gz\")) # Expected: 'No' (more than one dot)\n```"}
{"task_id": "HumanEval/142", "solution": "```python\ndef sum_squares(lst):\n \"\"\"\n This function will take a list of integers. For all entries in the list, the function shall square the integer entry if its index is a \n multiple of 3 and will cube the integer entry if its index is a multiple of 4 and not a multiple of 3. The function will not \n change the entries in the list whose indexes are not a multiple of 3 or 4. The function shall then return the sum of all entries. \n \n Examples:\n For lst = [1,2,3] the output should be 6\n For lst = [] the output should be 0\n For lst = [-1,-5,2,-1,-5] the output should be -126\n \"\"\"\n total_sum = 0\n for i, val in enumerate(lst):\n if i % 3 == 0:\n # Square the entry if index is a multiple of 3\n total_sum += val ** 2\n elif i % 4 == 0:\n # Cube the entry if index is a multiple of 4 and NOT a multiple of 3\n total_sum += val ** 3\n else:\n # Keep the entry as is otherwise\n total_sum += val\n \n return total_sum\n\n# Test cases to verify the function\nif __name__ == \"__main__\":\n test_cases = [\n ([1, 2, 3], 6),\n ([], 0),\n ([-1, -5, 2, -1, -5], -126),\n ]\n\n for lst, expected in test_cases:\n result = sum_squares(lst)\n print(f\"Input: {lst} | Expected: {expected} | Result: {result} | {'Pass' if result == expected else 'Fail'}\")\n```"}
{"task_id": "HumanEval/143", "solution": "```python\ndef words_in_sentence(sentence):\n \"\"\"\n You are given a string representing a sentence,\n the sentence contains some words separated by a space,\n and you have to return a string that contains the words from the original sentence,\n whose lengths are prime numbers,\n the order of the words in the new string should be the same as the original one.\n\n Example 1:\n Input: sentence = \"This is a test\"\n Output: \"is\"\n\n Example 2:\n Input: sentence = \"lets go for swimming\"\n Output: \"go for\"\n\n Constraints:\n * 1 <= len(sentence) <= 100\n * sentence contains only letters\n \"\"\"\n def is_prime(n):\n \"\"\"Helper function to check if a number is prime.\"\"\"\n if n < 2:\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\n # Split the sentence into individual words based on spaces\n words = sentence.split()\n \n # Filter words whose length is a prime number\n prime_length_words = [word for word in words if is_prime(len(word))]\n \n # Join the filtered words back into a single string separated by space\n return \" \".join(prime_length_words)\n\n# Test cases to verify the implementation\nif __name__ == \"__main__\":\n test_cases = [\n (\"This is a test\", \"is\"),\n (\"lets go for swimming\", \"go for\"),\n (\"Hello world\", \"\"), # Hello (5), world (5) -> both prime. Wait, 5 is prime. Result should be \"Hello world\"\n (\"a b c d e\", \"\"), # All length 1, not prime\n (\"The quick brown fox jumps over the lazy dog\", \"The quick brown fox jumps over the\"), # lengths: 3, 5, 5, 3, 5, 4, 3, 4, 3 -> primes: 3, 5, 5, 3, 5, 3, 3\n ]\n \n # Correcting my manual trace for \"Hello world\": len(\"Hello\")=5 (prime), len(\"world\")=5 (prime)\n # Let's run the actual function.\n \n print(f\"Test 1: {words_in_sentence('This is a test')} | Expected: 'is'\")\n print(f\"Test 2: {words_in_sentence('lets go for swimming')} | Expected: 'go for'\")\n print(f\"Test 3: {words_in_sentence('Hello world')} | Expected: 'Hello world'\")\n```"}
{"task_id": "HumanEval/144", "solution": "```python\ndef simplify(x, n):\n \"\"\"Your task is to implement a function that will simplify the expression\n x * n. The function returns True if x * n evaluates to a whole number and False\n otherwise. Both x and n, are string representation of a fraction, and have the following format,\n <numerator>/<denominator> where both numerator and denominator are positive whole numbers.\n\n You can assume that x, and n are valid fractions, and do not have zero as denominator.\n\n simplify(\"1/5\", \"5/1\") = True\n simplify(\"1/6\", \"2/1\") = False\n simplify(\"7/10\", \"10/2\") = False\n \"\"\"\n # Split the input strings to extract numerators and denominators\n num_x, den_x = map(int, x.split('/'))\n num_n, den_n = map(int, n.split('/'))\n \n # The product of two fractions (a/b) * (c/d) is (a*c) / (b*d)\n numerator_product = num_x * num_n\n denominator_product = den_x * den_n\n \n # A fraction represents a whole number if the numerator is divisible by the denominator\n return numerator_product % denominator_product == 0\n\n# Test cases to verify the implementation\nif __name__ == \"__main__\":\n assert simplify(\"1/5\", \"5/1\") == True\n assert simplify(\"1/6\", \"2/1\") == False\n assert simplify(\"7/10\", \"10/2\") == False\n print(\"All test cases passed!\")\n```"}
{"task_id": "HumanEval/145", "solution": "```python\ndef order_by_points(nums):\n \"\"\"\n Write a function which sorts the given list of integers\n in ascending order according to the sum of their digits.\n Note: if there are several items with similar sum of their digits,\n order them based on their index in original list.\n\n For example:\n >>> order_by_points([1, 11, -1, -11, -12]) == [-1, -11, 1, -12, 11]\n >>> order_by_points([]) == []\n \"\"\"\n def get_digit_sum(n):\n \"\"\"\n Calculates the sum of digits based on the logic derived from the example:\n - For positive numbers, it is the standard sum of digits.\n - For negative numbers, the first digit (most significant) is treated as \n negative, and all subsequent digits are treated as positive.\n Example: -123 -> (-1) + 2 + 3 = 4\n \"\"\"\n s = str(n)\n if s[0] == '-':\n # The first digit includes the minus sign (e.g., \"-1\")\n # and is added to the sum of the remaining digits.\n first_digit_val = int(s[0] + s[1])\n remaining_digits_sum = sum(int(d) for d in s[2:])\n return first_digit_val + remaining_digits_sum\n else:\n # Standard sum of digits for non-negative integers.\n return sum(int(d) for d in s)\n\n # Python's sorted() function is stable, meaning it preserves the original \n # order of elements that have equal sort keys. This satisfies the requirement \n # to order items based on their index in the original list as a tie-breaker.\n return sorted(nums, key=get_digit_sum)\n\nif __name__ == \"__main__\":\n # Test cases provided in the docstring\n assert order_by_points([1, 11, -1, -11, -12]) == [-1, -11, 1, -12, 11]\n assert order_by_points([]) == []\n print(\"All tests passed!\")\n\n```"}
{"task_id": "HumanEval/146", "solution": "```python\ndef specialFilter(nums):\n \"\"\"Write a function that takes an array of numbers as input and returns \n the number of elements in the array that are greater than 10 and both \n first and last digits of a number are odd (1, 3, 5, 7, 9).\n For example:\n specialFilter([15, -73, 14, -15]) => 1 \n specialFilter([33, -2, -3, 45, 21, 109]) => 2\n \"\"\"\n count = 0\n # Set of odd digits as strings for quick lookup\n odd_digits = {'1', '3', '5', '7', '9'}\n \n for num in nums:\n # Condition 1: Number must be greater than 10\n if num > 10:\n # Convert number to string to easily access the first and last digits\n s = str(num)\n first_digit = s[0]\n last_digit = s[-1]\n \n # Condition 2 & 3: First and last digits must be odd\n if first_digit in odd_digits and last_digit in odd_digits:\n count += 1\n \n return count\n\n# Test cases to verify the function\nif __name__ == \"__main__\":\n test1 = [15, -73, 14, -15]\n print(f\"Test 1: {specialFilter(test1)} (Expected: 1)\") # Only 15 matches\n\n test2 = [33, -2, -3, 45, 21, 109]\n print(f\"Test 2: {specialFilter(test2)} (Expected: 2)\") # 33 and 109 match\n\n test3 = [11, 13, 15, 17, 19, 21, 31]\n print(f\"Test 3: {specialFilter(test3)} (Expected: 6)\") # All except 21 match\n```"}
{"task_id": "HumanEval/147", "solution": "```python\ndef get_max_triples(n):\n \"\"\"\n You are given a positive integer n. You have to create an integer array a of length n.\n For each i (1 \u2264 i \u2264 n), the value of a[i] = i * i - i + 1.\n Return the number of triples (a[i], a[j], a[k]) of a where i < j < k, \n and a[i] + a[j] + a[k] is a multiple of 3.\n\n Analysis:\n The condition for a triple to be a multiple of 3 depends on the remainders of each element modulo 3.\n Let's analyze a[i] = i^2 - i + 1 (mod 3):\n - If i % 3 == 0, then a[i] = 0^2 - 0 + 1 = 1 (mod 3)\n - If i % 3 == 1, then a[i] = 1^2 - 1 + 1 = 1 (mod 3)\n - If i % 3 == 2, then a[i] = 2^2 - 2 + 1 = 4 - 2 + 1 = 3 = 0 (mod 3)\n\n So, the elements of array 'a' only have remainders 0 or 1 modulo 3.\n Let c0 be the count of elements where a[i] % 3 == 0 and c1 be the count where a[i] % 3 == 1.\n - i = 2, 5, 8... result in a[i] % 3 == 0. The number of such indices is floor((n + 1) / 3).\n - All other indices (i = 1, 3, 4, 6, 7...) result in a[i] % 3 == 1.\n\n A triple (x, y, z) sums to a multiple of 3 if:\n 1. x % 3 == 0, y % 3 == 0, and z % 3 == 0 => Combination(c0, 3) ways.\n 2. x % 3 == 1, y % 3 == 1, and z % 3 == 1 => Combination(c1, 3) ways.\n 3. One of each remainder (0, 1, 2). Since there are no elements with remainder 2, this is impossible.\n\n Total triples = Combination(c0, 3) + Combination(c1, 3).\n \"\"\"\n # Count how many i in [1, n] satisfy i % 3 == 2\n c0 = (n + 1) // 3\n # The rest of the elements have remainder 1 modulo 3\n c1 = n - c0\n\n def combinations_of_3(count):\n if count < 3:\n return 0\n # Formula for nC3 is (n * (n-1) * (n-2)) / 6\n return (count * (count - 1) * (count - 2)) // 6\n\n return combinations_of_3(c0) + combinations_of_3(c1)\n\n# Example usage and testing\nif __name__ == \"__main__\":\n test_cases = [\n (5, 1), # a = [1, 3, 7, 13, 21], triple (1, 7, 13) sum=21\n (4, 1), # a = [1, 3, 7, 13], triple (1, 7, 13) sum=21\n (3, 0), # a = [1, 3, 7], sum=11\n (6, 4), # c0=2, c1=4 -> 0 + 4C3 = 4\n ]\n\n for n_val, expected in test_cases:\n result = get_max_triples(n_val)\n print(f\"Input: n={n_val}, Expected: {expected}, Result: {result} - {'Pass' if result == expected else 'Fail'}\")\n\n```"}
{"task_id": "HumanEval/148", "solution": "```python\ndef bf(planet1, planet2):\n '''\n There are eight planets in our solar system: the closerst to the Sun \n is Mercury, the next one is Venus, then Earth, Mars, Jupiter, Saturn, \n Uranus, Neptune.\n Write a function that takes two planet names as strings planet1 and planet2. \n The function should return a tuple containing all planets whose orbits are \n located between the orbit of planet1 and the orbit of planet2, sorted by \n the proximity to the sun. \n The function should return an empty tuple if planet1 or planet2\n are not correct planet names. \n Examples\n bf(\"Jupiter\", \"Neptune\") ==> (\"Saturn\", \"Uranus\")\n bf(\"Earth\", \"Mercury\") ==> (\"Venus\")\n bf(\"Mercury\", \"Uranus\") ==> (\"Venus\", \"Earth\", \"Mars\", \"Jupiter\", \"Saturn\")\n '''\n # List of planets sorted by proximity to the Sun\n planets = [\n \"Mercury\", \"Venus\", \"Earth\", \"Mars\", \n \"Jupiter\", \"Saturn\", \"Uranus\", \"Neptune\"\n ]\n \n # Check if both provided planet names are valid\n if planet1 not in planets or planet2 not in planets:\n return ()\n \n # Find the indices of the two planets\n idx1 = planets.index(planet1)\n idx2 = planets.index(planet2)\n \n # Determine the range between the two indices\n start_idx = min(idx1, idx2)\n end_idx = max(idx1, idx2)\n \n # Slice the list to get planets strictly between the two orbits\n # We start at start_idx + 1 and end before end_idx\n result = planets[start_idx + 1 : end_idx]\n \n return tuple(result)\n\n# Test cases\nif __name__ == \"__main__\":\n print(bf(\"Jupiter\", \"Neptune\")) # Expected: (\"Saturn\", \"Uranus\")\n print(bf(\"Earth\", \"Mercury\")) # Expected: (\"Venus\",)\n print(bf(\"Mercury\", \"Uranus\")) # Expected: (\"Venus\", \"Earth\", \"Mars\", \"Jupiter\", \"Saturn\")\n print(bf(\"Pluto\", \"Earth\")) # Expected: ()\n```"}
{"task_id": "HumanEval/149", "solution": "```python\ndef sorted_list_sum(lst):\n \"\"\"Write a function that accepts a list of strings as a parameter,\n deletes the strings that have odd lengths from it,\n and returns the resulted list with a sorted order,\n The list is always a list of strings and never an array of numbers,\n and it may contain duplicates.\n The order of the list should be ascending by length of each word, and you\n should return the list sorted by that rule.\n If two words have the same length, sort the list alphabetically.\n The function should return a list of strings in sorted order.\n \"\"\"\n # Filter out strings with odd lengths using a list comprehension\n filtered_list = [s for s in lst if len(s) % 2 == 0]\n \n # Sort the filtered list. \n # The key is a tuple: (length of string, the string itself).\n # Python sorts tuples element by element; it will sort by length first,\n # and then alphabetically for strings of the same length.\n filtered_list.sort(key=lambda x: (len(x), x))\n \n return filtered_list\n\n# Test cases to verify the functionality\nif __name__ == \"__main__\":\n assert sorted_list_sum([\"aa\", \"a\", \"aaa\"]) == [\"aa\"]\n assert sorted_list_sum([\"ab\", \"a\", \"aaa\", \"cd\"]) == [\"ab\", \"cd\"]\n assert sorted_list_sum([\"apple\", \"pear\", \"banana\", \"kiwi\", \"plum\"]) == [\"kiwi\", \"pear\", \"banana\"] \n # Explanation for last case: \n # apple(5), pear(4), banana(6), kiwi(4), plum(4) -> Keep [pear, banana, kiwi, plum]\n # Sorted by length then alpha: [kiwi, pear, plum, banana] (Wait, plum is also len 4)\n # Let's re-check: \"kiwi\"(4), \"pear\"(4), \"plum\"(4) are alphabetical. Then \"banana\"(6).\n assert sorted_list_sum([\"apple\", \"pear\", \"banana\", \"kiwi\", \"plum\"]) == [\"kiwi\", \"pear\", \"plum\", \"banana\"]\n print(\"All tests passed!\")\n```"}
{"task_id": "HumanEval/150", "solution": "```python\ndef x_or_y(n, x, y):\n \"\"\"A simple program which should return the value of x if n is \n a prime number and should return the value of y otherwise.\n\n Examples:\n x_or_y(7, 34, 12) == 34\n x_or_y(15, 8, 5) == 5\n \"\"\"\n # Prime numbers must be greater than 1\n if n <= 1:\n return y\n \n # Check for primality\n is_prime = True\n # We only need to check up to the square root of n\n for i in range(2, int(n**0.5) + 1):\n if n % i == 0:\n is_prime = False\n break\n \n return x if is_prime else y\n\n# Test cases to verify the function\nif __name__ == \"__main__\":\n assert x_or_y(7, 34, 12) == 34, \"Test Case 1 Failed\"\n assert x_or_y(15, 8, 5) == 5, \"Test Case 2 Failed\"\n assert x_or_y(2, 10, 20) == 10, \"Test Case 3 Failed (2 is prime)\"\n assert x_or_y(1, 10, 20) == 20, \"Test Case 4 Failed (1 is not prime)\"\n print(\"All test cases passed!\")\n```"}
{"task_id": "HumanEval/151", "solution": "```python\ndef double_the_difference(lst):\n '''\n Given a list of numbers, return the sum of squares of the numbers\n in the list that are odd. Ignore numbers that are negative or not integers.\n \n double_the_difference([1, 3, 2, 0]) == 1 + 9 + 0 + 0 = 10\n double_the_difference([-1, -2, 0]) == 0\n double_the_difference([9, -2]) == 81\n double_the_difference([0]) == 0 \n \n If the input list is empty, return 0.\n '''\n # If the input list is empty, return 0 as specified\n if not lst:\n return 0\n \n total_sum = 0\n for num in lst:\n # Check if the number is an integer (excluding booleans)\n # and check if it is non-negative and odd\n if type(num) == int and num >= 0 and num % 2 != 0:\n total_sum += num ** 2\n \n return total_sum\n\n# Test cases to verify the function\nif __name__ == \"__main__\":\n assert double_the_difference([1, 3, 2, 0]) == 10\n assert double_the_difference([-1, -2, 0]) == 0\n assert double_the_difference([9, -2]) == 81\n assert double_the_difference([0]) == 0\n assert double_the_difference([]) == 0\n assert double_the_difference([1.5, 3.0, 5]) == 25 # Only 5 is an integer and odd\n print(\"All test cases passed!\")\n```"}
{"task_id": "HumanEval/152", "solution": "```python\ndef compare(game, guess):\n \"\"\"I think we all remember that feeling when the result of some long-awaited\n event is finally known. The feelings and thoughts you have at that moment are\n definitely worth noting down and comparing.\n Your task is to determine if a person correctly guessed the results of a number of matches.\n You are given two arrays of scores and guesses of equal length, where each index shows a match. \n Return an array of the same length denoting how far off each guess was. If they have guessed correctly,\n the value is 0, and if not, the value is the absolute difference between the guess and the score.\n \n example:\n\n compare([1,2,3,4,5,1],[1,2,3,4,2,-2]) -> [0,0,0,0,3,3]\n compare([0,5,0,0,0,4],[4,1,1,0,0,-2]) -> [4,4,1,0,0,6]\n \"\"\"\n # Use a list comprehension to iterate through both lists simultaneously using zip.\n # abs(a - b) calculates the absolute difference between two numbers.\n return [abs(score - g) for score, g in zip(game, guess)]\n\n# Test cases to verify the function\nif __name__ == \"__main__\":\n test_cases = [\n ([1, 2, 3, 4, 5, 1], [1, 2, 3, 4, 2, -2], [0, 0, 0, 0, 3, 3]),\n ([0, 5, 0, 0, 0, 4], [4, 1, 1, 0, 0, -2], [4, 4, 1, 0, 0, 6]),\n ]\n\n for game, guess, expected in test_cases:\n result = compare(game, guess)\n print(f\"Game: {game}, Guess: {guess} -> Result: {result} (Expected: {expected})\")\n assert result == expected\n```"}
{"task_id": "HumanEval/153", "solution": "```python\ndef Strongest_Extension(class_name, extensions):\n \"\"\"You will be given the name of a class (a string) and a list of extensions.\n The extensions are to be used to load additional classes to the class. The\n strength of the extension is as follows: Let CAP be the number of the uppercase\n letters in the extension's name, and let SM be the number of lowercase letters \n in the extension's name, the strength is given by the fraction CAP - SM. \n You should find the strongest extension and return a string in this \n format: ClassName.StrongestExtensionName.\n If there are two or more extensions with the same strength, you should\n choose the one that comes first in the list.\n \"\"\"\n # Initialize variables to track the maximum strength found and the corresponding extension\n max_strength = float('-inf')\n strongest_ext = None\n\n for ext in extensions:\n # Count uppercase letters (CAP)\n cap = sum(1 for char in ext if char.isupper())\n # Count lowercase letters (SM)\n sm = sum(1 for char in ext if char.islower())\n \n # Calculate strength as CAP - SM\n strength = cap - sm\n \n # We only update the strongest_ext if we find a strength strictly greater than \n # the current max_strength. This ensures that if two extensions have the same \n # strength, the one appearing first in the list is preserved.\n if strength > max_strength:\n max_strength = strength\n strongest_ext = ext\n\n # Return the result in the format ClassName.StrongestExtensionName\n return f\"{class_name}.{strongest_ext}\"\n\n# Test cases to verify the functionality\nif __name__ == \"__main__\":\n # Example 1 from prompt\n assert Strongest_Extension('Slices', ['SErviNGSliCes', 'Cheese', 'StuFfed']) == 'Slices.SErviNGSliCes'\n \n # Example 2 from prompt (Tie-breaker test)\n assert Strongest_Extension('my_class', ['AA', 'Be', 'CC']) == 'my_class.AA'\n \n # Additional test case: All lowercase\n assert Strongest_Extension('Test', ['abc', 'defg']) == 'Test.abc'\n \n # Additional test case: Mixed characters (numbers/symbols should be ignored)\n assert Strongest_Extension('Class', ['A1b2C3', 'D4e5F6']) == 'Class.A1b2C3'\n\n print(\"All tests passed!\")\n```"}
{"task_id": "HumanEval/154", "solution": "```python\ndef cycpattern_check(a, b):\n \"\"\"\n You are given 2 words. You need to return True if the second word or any of its rotations is a substring in the first word.\n \n cycpattern_check(\"abcd\",\"abd\") => False\n cycpattern_check(\"hello\",\"ell\") => True\n cycpattern_check(\"whassup\",\"psus\") => False\n cycpattern_check(\"abab\",\"baa\") => True\n cycpattern_check(\"efef\",\"eeff\") => False\n cycpattern_check(\"himenss\",\"simen\") => True\n \"\"\"\n # If the second word is empty, it's technically a substring of any string.\n if not b:\n return True\n \n # Length of the second word to generate all possible rotations.\n n = len(b)\n \n # A cyclic rotation is created by shifting characters from the front to the back.\n # We iterate through every possible starting index for a rotation.\n for i in range(n):\n # Create the rotation: slice from index i to end, then append slice from start to i.\n rotation = b[i:] + b[:i]\n \n # Check if this specific rotation exists as a substring within string 'a'.\n if rotation in a:\n return True\n \n # If no rotations were found in 'a', return False.\n return False\n\n# Test cases to verify the function\nif __name__ == \"__main__\":\n assert cycpattern_check(\"abcd\", \"abd\") == False\n assert cycpattern_check(\"hello\", \"ell\") == True\n assert cycpattern_check(\"whassup\", \"psus\") == False\n assert cycpattern_check(\"abab\", \"baa\") == True\n assert cycpattern_check(\"efef\", \"eeff\") == False\n assert cycpattern_check(\"himenss\", \"simen\") == True\n print(\"All test cases passed!\")\n```"}
{"task_id": "HumanEval/155", "solution": "```python\ndef even_odd_count(num):\n \"\"\"Given an integer. return a tuple that has the number of even and odd digits respectively.\n\n Example:\n even_odd_count(-12) ==> (1, 1)\n even_odd_count(123) ==> (1, 2)\n \"\"\"\n # Use absolute value to handle negative numbers\n num_str = str(abs(num))\n \n even_count = 0\n odd_count = 0\n \n for digit in num_str:\n if int(digit) % 2 == 0:\n even_count += 1\n else:\n odd_count += 1\n \n return (even_count, odd_count)\n\n# Test cases to verify the function\nif __name__ == \"__main__\":\n test_cases = [\n (-12, (1, 1)),\n (123, (1, 2)),\n (0, (1, 0)),\n (2468, (4, 0)),\n (1357, (0, 4)),\n (-135, (0, 3)),\n ]\n\n for val, expected in test_cases:\n result = even_odd_count(val)\n print(f\"Input: {val} | Expected: {expected} | Result: {result} | {'Pass' if result == expected else 'Fail'}\")\n```"}
{"task_id": "HumanEval/156", "solution": "```python\ndef int_to_mini_roman(number):\n \"\"\"\n Given a positive integer, obtain its roman numeral equivalent as a string,\n and return it in lowercase.\n Restrictions: 1 <= num <= 1000\n\n Examples:\n >>> int_to_mini_roman(19) == 'xix'\n >>> int_to_mini_roman(152) == 'clii'\n >>> int_to_mini_roman(426) == 'cdxxvi'\n \"\"\"\n # Define the mapping of integer values to Roman numeral symbols in descending order.\n # We include the subtractive combinations (like 900, 400, etc.) as distinct entries.\n roman_map = [\n (1000, 'm'),\n (900, 'cm'),\n (500, 'd'),\n (400, 'cd'),\n (100, 'c'),\n (90, 'xc'),\n (50, 'l'),\n (40, 'xl'),\n (10, 'x'),\n (9, 'ix'),\n (5, 'v'),\n (4, 'iv'),\n (1, 'i')\n ]\n \n result = []\n \n # Iterate through the map and subtract values from the number while appending symbols.\n for value, symbol in roman_map:\n while number >= value:\n result.append(symbol)\n number -= value\n \n return \"\".join(result)\n\nif __name__ == \"__main__\":\n # Test cases provided in the docstring\n assert int_to_mini_roman(19) == 'xix'\n assert int_to_mini_roman(152) == 'clii'\n assert int_to_mini_roman(426) == 'cdxxvi'\n \n # Additional test cases\n assert int_to_mini_roman(1) == 'i'\n assert int_to_mini_roman(4) == 'iv'\n assert int_to_mini_roman(9) == 'ix'\n assert int_to_mini_roman(40) == 'xl'\n assert int_to_mini_roman(90) == 'xc'\n assert int_to_mini_roman(400) == 'cd'\n assert int_to_mini_roman(900) == 'cm'\n assert int_to_mini_roman(1000) == 'm'\n \n print(\"All tests passed!\")\n```"}
{"task_id": "HumanEval/157", "solution": "```python\ndef right_angle_triangle(a, b, c):\n '''\n Given the lengths of the three sides of a triangle. Return True if the three\n sides form a right-angled triangle, False otherwise.\n A right-angled triangle is a triangle in which one angle is right angle or \n 90 degree.\n Example:\n right_angle_triangle(3, 4, 5) == True\n right_angle_triangle(1, 2, 3) == False\n '''\n # A triangle is right-angled if the square of the longest side (hypotenuse)\n # is equal to the sum of the squares of the other two sides.\n \n # First, we sort the sides so that the largest value is always at the end.\n sides = sorted([a, b, c])\n \n # Check the Pythagorean theorem: a^2 + b^2 = c^2\n return (sides[0]**2 + sides[1]**2) == sides[2]**2\n\n# Test cases to verify the function\nif __name__ == \"__main__\":\n assert right_angle_triangle(3, 4, 5) == True\n assert right_angle_triangle(1, 2, 3) == False\n assert right_angle_triangle(5, 12, 13) == True\n assert right_angle_triangle(8, 15, 17) == True\n assert right_angle_triangle(5, 4, 3) == True # Testing different order\n assert right_angle_triangle(10, 10, 10) == False\n print(\"All test cases passed!\")\n```"}
{"task_id": "HumanEval/158", "solution": "```python\ndef find_max(words):\n \"\"\"Write a function that accepts a list of strings.\n The list contains different words. Return the word with maximum number\n of unique characters. If multiple strings have maximum number of unique\n characters, return the one which comes first in lexicographical order.\n\n find_max([\"name\", \"of\", \"string\"]) == \"string\"\n find_max([\"name\", \"enam\", \"game\"]) == \"enam\"\n find_max([\"aaaaaaa\", \"bb\" ,\"cc\"]) == \"aaaaaaa\"\n \"\"\"\n if not words:\n return \"\"\n\n # Initialize with the first word in the list\n best_word = words[0]\n max_unique_count = len(set(best_word))\n\n for i in range(1, len(words)):\n current_word = words[i]\n current_unique_count = len(set(current_word))\n\n # Condition 1: Current word has more unique characters than the current best\n if current_unique_count > max_unique_count:\n max_unique_count = current_unique_count\n best_word = current_word\n \n # Condition 2: Tie in unique character count, use lexicographical order\n elif current_unique_count == max_unique_count:\n if current_word < best_word:\n best_word = current_word\n\n return best_word\n\n# Test cases to verify the functionality\nif __name__ == \"__main__\":\n test_cases = [\n ([\"name\", \"of\", \"string\"], \"string\"),\n ([\"name\", \"enam\", \"game\"], \"enam\"),\n ([\"aaaaaaa\", \"bb\", \"cc\"], \"aaaaaaa\"),\n ([], \"\"), # Edge case: empty list\n ([\"apple\", \"pear\", \"peach\"], \"peach\"), # apple(4), pear(4), peach(5) -> peach\n ]\n\n for words, expected in test_cases:\n result = find_max(words)\n print(f\"find_max({words}) == '{result}' | Expected: '{expected}' | {'PASS' if result == expected else 'FAIL'}\")\n```"}
{"task_id": "HumanEval/159", "solution": "```python\ndef eat(number, need, remaining):\n \"\"\"\n You're a hungry rabbit, and you already have eaten a certain number of carrots,\n but now you need to eat more carrots to complete the day's meals.\n you should return an array of [ total number of eaten carrots after your meals,\n the number of carrots left after your meals ]\n if there are not enough remaining carrots, you will eat all remaining carrots, but will still be hungry.\n \n Example:\n * eat(5, 6, 10) -> [11, 4]\n * eat(4, 8, 9) -> [12, 1]\n * eat(1, 10, 10) -> [11, 0]\n * eat(2, 11, 5) -> [7, 0]\n \n Variables:\n @number : integer\n the number of carrots that you have eaten.\n @need : integer\n the number of carrots that you need to eat.\n @remaining : integer\n the number of remaining carrots thet exist in stock\n \n Constrain:\n * 0 <= number <= 1000\n * 0 <= need <= 1000\n * 0 <= remaining <= 1000\n\n Have fun :)\n \"\"\"\n # Determine how many carrots the rabbit actually eats.\n # It's either the amount needed or all that is remaining, whichever is smaller.\n amount_eaten = min(need, remaining)\n \n # Calculate total eaten: previous count + what was just eaten\n total_eaten = number + amount_eaten\n \n # Calculate leftover carrots in stock\n leftover = remaining - amount_eaten\n \n return [total_eaten, leftover]\n\nif __name__ == \"__main__\":\n # Test cases provided in the docstring\n test_cases = [\n (5, 6, 10, [11, 4]),\n (4, 8, 9, [12, 1]),\n (1, 10, 10, [11, 0]),\n (2, 11, 5, [7, 0]),\n ]\n\n for num, need, rem, expected in test_cases:\n result = eat(num, need, rem)\n print(f\"eat({num}, {need}, {rem}) -> Expected: {expected}, Got: {result} | {'PASS' if result == expected else 'FAIL'}\")\n```"}
{"task_id": "HumanEval/160", "solution": "```python\ndef do_algebra(operator, operand):\n \"\"\"\n Given two lists operator, and operand. The first list has basic algebra operations, and \n the second list is a list of integers. Use the two given lists to build the algebric \n expression and return the evaluation of this expression.\n\n The basic algebra operations:\n Addition ( + ) \n Subtraction ( - ) \n Multiplication ( * ) \n Floor division ( // ) \n Exponentiation ( ** ) \n\n Example:\n operator = ['+', '*', '-']\n operand = [2, 3, 4, 5]\n result = 2 + 3 * 4 - 5\n => result = 9\n \"\"\"\n # Initialize the expression string with the first operand\n expression = str(operand[0])\n \n # Interleave operators and operands to build the full algebraic string\n for i in range(len(operator)):\n # Append the operator followed by the next operand\n expression += f\" {operator[i]} {operand[i+1]}\"\n \n # eval() evaluates the string as a Python expression, \n # respecting standard mathematical order of operations (PEMDAS)\n return eval(expression)\n\n# Test cases to verify the functionality\nif __name__ == \"__main__\":\n test_cases = [\n {\n \"operator\": ['+', '*', '-'],\n \"operand\": [2, 3, 4, 5],\n \"expected\": 9 # 2 + (3 * 4) - 5 = 2 + 12 - 5 = 9\n },\n {\n \"operator\": ['**', '+'],\n \"operand\": [2, 3, 10],\n \"expected\": 18 # (2 ** 3) + 10 = 8 + 10 = 18\n },\n {\n \"operator\": ['//', '*'],\n \"operand\": [10, 3, 2],\n \"expected\": 6 # (10 // 3) * 2 = 3 * 2 = 6\n },\n {\n \"operator\": ['+', '-'],\n \"operand\": [10, 5, 2],\n \"expected\": 13 # 10 + 5 - 2 = 13\n }\n ]\n\n for i, test in enumerate(test_cases):\n res = do_algebra(test[\"operator\"], test[\"operand\"])\n print(f\"Test {i+1}: {'Passed' if res == test['expected'] else 'Failed'} (Result: {res}, Expected: {test['expected']})\")\n```"}
{"task_id": "HumanEval/161", "solution": "```python\ndef solve(s):\n \"\"\"You are given a string s.\n if s[i] is a letter, reverse its case from lower to upper or vise versa, \n otherwise keep it as it is.\n If the string contains no letters, reverse the string.\n The function should return the resulted string.\n \"\"\"\n # Check if there are any alphabetic characters in the string\n has_letters = any(char.isalpha() for char in s)\n \n if has_letters:\n # .swapcase() converts uppercase to lowercase and vice versa, \n # while leaving non-alphabetic characters untouched.\n return s.swapcase()\n else:\n # If no letters are present, return the reversed string using slicing\n return s[::-1]\n\n# Test cases\nif __name__ == \"__main__\":\n assert solve(\"1234\") == \"4321\"\n assert solve(\"ab\") == \"AB\"\n assert solve(\"#a@C\") == \"#A@c\"\n print(\"All tests passed!\")\n```"}
{"task_id": "HumanEval/162", "solution": "```python\nimport hashlib\n\ndef string_to_md5(text):\n \"\"\"\n Given a string 'text', return its md5 hash equivalent string.\n If 'text' is an empty string, return None.\n\n >>> string_to_md5('Hello world') == '3e25960a79dbc69b674cd4ec67a72c62'\n True\n \"\"\"\n # Check if the input text is an empty string\n if text == \"\":\n return None\n \n # MD5 requires bytes, so we encode the string to utf-8 first\n encoded_text = text.encode('utf-8')\n \n # Create the md5 hash object and return the hexadecimal representation\n return hashlib.md5(encoded_text).hexdigest()\n\nif __name__ == \"__main__\":\n # Test cases\n test_cases = [\n (\"Hello world\", \"3e25960a79dbc69b674cd4ec67a72c62\"),\n (\"\", None),\n (\"Python\", \"8f14e7dbd73075757331333333333333\"), # This is a placeholder, actual hash differs\n ]\n \n # Actual verification for the provided example\n result = string_to_md5('Hello world')\n print(f\"Input: 'Hello world' -> MD5: {result}\")\n assert result == '3e25960a79dbc69b674cd4ec67a72c62'\n \n # Verification for empty string\n result_empty = string_to_md5('')\n print(f\"Input: '' -> MD5: {result_empty}\")\n assert result_empty is None\n \n print(\"All tests passed!\")\n```"}
{"task_id": "HumanEval/163", "solution": "```python\ndef generate_integers(a, b):\n \"\"\"\n Given two positive integers a and b, return the even digits between a\n and b, in ascending order.\n\n For example:\n generate_integers(2, 8) => [2, 4, 6, 8]\n generate_integers(8, 2) => [2, 4, 6, 8]\n generate_integers(10, 14) => []\n \"\"\"\n # Determine the range boundaries regardless of order\n start = min(a, b)\n end = max(a, b)\n \n result = []\n # Iterate through the range inclusive of both endpoints\n for i in range(start, end + 1):\n # A 'digit' is a single-digit integer (0-9).\n # We check if the number is within that range and if it is even.\n if 0 <= i <= 9 and i % 2 == 0:\n result.append(i)\n \n return result\n\n# Test cases to verify the functionality\nif __name__ == \"__main__\":\n print(f\"Test (2, 8): {generate_integers(2, 8)}\") # Expected: [2, 4, 6, 8]\n print(f\"Test (8, 2): {generate_integers(8, 2)}\") # Expected: [2, 4, 6, 8]\n print(f\"Test (10, 14): {generate_integers(10, 14)}\") # Expected: []\n print(f\"Test (1, 5): {generate_integers(1, 5)}\") # Expected: [2, 4]\n```"}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment