task_id
stringlengths
11
13
language
stringclasses
1 value
completion
stringlengths
131
3.86k
prompt
stringlengths
115
1.36k
HumanEval/0
python
from typing import List def has_close_elements(numbers: List[float], threshold: float) -> bool: """ Check if in given list of numbers, are any two numbers closer to each other than given threshold. >>> has_close_elements([1.0, 2.0, 3.0], 0.5) False >>> has_close_elements([1.0, 2.8, 3.0, 4.0, 5.0, 2.0], 0.3) True """ if not numbers: return False numbers_sorted = sorted(numbers) has_same_index = has_same_index_in_sorted(numbers_sorted) if len(numbers): return has_same_index return True def has_close_elements_for(values: Iterator[float], previous: float, threshold: float): numbers = list(values)
from typing import List def has_close_elements(numbers: List[float], threshold: float) -> bool: """ Check if in given list of numbers, are any two numbers closer to each other than given threshold. >>> has_close_elements([1.0, 2.0, 3.0], 0.5) False >>> has_close_elements([1.0, 2.8, 3.0, 4.0, 5.0, 2.0], 0.3) True """
HumanEval/1
python
from typing import List def separate_paren_groups(paren_string: str) -> List[str]: """ Input to this function is a string containing multiple groups of nested parentheses. Your goal is to separate those group into separate strings and return the list of those. Separate groups are balanced (each open brace is properly closed) and not nested within each other Ignore any spaces in the input string. >>> separate_paren_groups('( ) (( )) (( )( ))') ['()', '(())', '(()())'] """ groups = [g for g in paren_string.split('())(') if g != ''] return [g.replace(nested_parens, '') for g in groups] def nested_parens(parens: List[str]) -> int: '''Given a string of parens, count how many levels are balanced with unbalanced inside them. For example, >>> nested_parens([')(', '(']) 0 >>> nested_parens(['(']) 1 >>> nested_parens([')', ')', '(']) 1 >>> nested_parens(['(', ')', ')']) 1 >>> nested_parens([')', ')']) 0 >>> nested_parens(['(', '(', '(']) 2 >>> nested_parens([]) 0 ''' nested_level = 0 for level in _get_open_close_paren_counts(parens): nested_level = _sum((nested_level, level)) return nested_level def _get_open_close_paren_counts(parens: List[str]) -> List[int]: return [s.count('(') - s.count(')') for s in parens]
from typing import List def separate_paren_groups(paren_string: str) -> List[str]: """ Input to this function is a string containing multiple groups of nested parentheses. Your goal is to separate those group into separate strings and return the list of those. Separate groups are balanced (each open brace is properly closed) and not nested within each other Ignore any spaces in the input string. >>> separate_paren_groups('( ) (( )) (( )( ))') ['()', '(())', '(()())'] """
HumanEval/2
python
def truncate_number(number: float) -> float: """ Given a positive floating point number, it can be decomposed into and integer part (largest integer smaller than given number) and decimals (leftover part always smaller than 1). Return the decimal part of the number. >>> truncate_number(3.5) 0.5 """ return number - int(number)
def truncate_number(number: float) -> float: """ Given a positive floating point number, it can be decomposed into and integer part (largest integer smaller than given number) and decimals (leftover part always smaller than 1). Return the decimal part of the number. >>> truncate_number(3.5) 0.5 """
HumanEval/3
python
from typing import List def below_zero(operations: List[int]) -> bool: """ You're given a list of deposit and withdrawal operations on a bank account that starts with zero balance. Your task is to detect if at any point the balance of account fallls below zero, and at that point function should return True. Otherwise it should return False. >>> below_zero([1, 2, 3]) False >>> below_zero([1, 2, -4, 5]) True """ bal = 0 for x in operations: bal += x if bal < 0: return True return False
from typing import List def below_zero(operations: List[int]) -> bool: """ You're given a list of deposit and withdrawal operations on a bank account that starts with zero balance. Your task is to detect if at any point the balance of account fallls below zero, and at that point function should return True. Otherwise it should return False. >>> below_zero([1, 2, 3]) False >>> below_zero([1, 2, -4, 5]) True """
HumanEval/4
python
from typing import List def mean_absolute_deviation(numbers: List[float]) -> float: """ For a given list of input numbers, calculate Mean Absolute Deviation around the mean of this dataset. Mean Absolute Deviation is the average absolute difference between each element and a centerpoint (mean in this case): MAD = average | x - x_mean | >>> mean_absolute_deviation([1.0, 2.0, 3.0, 4.0]) 1.0 """ length = len(numbers) if length == 0: return 0.0 average = sum(numbers) / float(length) return sum((abs(x - average) for x in numbers)) / float(length)
from typing import List def mean_absolute_deviation(numbers: List[float]) -> float: """ For a given list of input numbers, calculate Mean Absolute Deviation around the mean of this dataset. Mean Absolute Deviation is the average absolute difference between each element and a centerpoint (mean in this case): MAD = average | x - x_mean | >>> mean_absolute_deviation([1.0, 2.0, 3.0, 4.0]) 1.0 """
HumanEval/5
python
from typing import List def intersperse(numbers: List[int], delimeter: int) -> List[int]: """ Insert a number 'delimeter' between every two consecutive elements of input list `numbers' >>> intersperse([], 4) [] >>> intersperse([1, 2, 3], 4) [1, 4, 2, 4, 3] """ def _inspect(s: int, l: List[int], d: int, r: int) -> int: if r >= len(l): return l return _inspect(s + d, l[s + 1:r + 1], d, r + 1) def _append(l: List[int], d: int) -> int: l.append(d) return 1 + _append(l, d) def _build(l: List[int]) -> int: if l == []: return 0 return _build(l[1:]) + _append(l, delimeter) return _inspect(0, numbers, delimeter, 1) if numbers else []
from typing import List def intersperse(numbers: List[int], delimeter: int) -> List[int]: """ Insert a number 'delimeter' between every two consecutive elements of input list `numbers' >>> intersperse([], 4) [] >>> intersperse([1, 2, 3], 4) [1, 4, 2, 4, 3] """
HumanEval/6
python
from typing import List def parse_nested_parens(paren_string: str) -> List[int]: """ Input to this function is a string represented multiple groups for nested parentheses separated by spaces. For each of the group, output the deepest level of nesting of parentheses. E.g. (()()) has maximum two levels of nesting while ((())) has three. >>> parse_nested_parens('(()()) ((())) () ((())()())') [2, 3, 1, 3] """ depth = [] while paren_string: paren_depth = paren_string.find(')()') if ')' in paren_string else -1 if paren_depth == -1: count = paren_string.count('()') delimiter = '()(' * count paren_depth = len(paren_string) - paren_string.rfind(delimiter) - 1 depth.append(paren_depth) paren_string = paren_string.replace(delimiter, '') return depth
from typing import List def parse_nested_parens(paren_string: str) -> List[int]: """ Input to this function is a string represented multiple groups for nested parentheses separated by spaces. For each of the group, output the deepest level of nesting of parentheses. E.g. (()()) has maximum two levels of nesting while ((())) has three. >>> parse_nested_parens('(()()) ((())) () ((())()())') [2, 3, 1, 3] """
HumanEval/7
python
from typing import List def filter_by_substring(strings: List[str], substring: str) -> List[str]: """ Filter an input list of strings only for ones that contain given substring >>> filter_by_substring([], 'a') [] >>> filter_by_substring(['abc', 'bacd', 'cde', 'array'], 'a') ['abc', 'bacd', 'array'] """ strings = [string for string in strings if substring in string] return strings
from typing import List def filter_by_substring(strings: List[str], substring: str) -> List[str]: """ Filter an input list of strings only for ones that contain given substring >>> filter_by_substring([], 'a') [] >>> filter_by_substring(['abc', 'bacd', 'cde', 'array'], 'a') ['abc', 'bacd', 'array'] """
HumanEval/8
python
from typing import List, Tuple def sum_product(numbers: List[int]) -> Tuple[int, int]: """ For a given list of integers, return a tuple consisting of a sum and a product of all the integers in a list. Empty sum should be equal to 0 and empty product should be equal to 1. >>> sum_product([]) (0, 1) >>> sum_product([1, 2, 3, 4]) (10, 24) """ a_list = list(numbers) if not a_list: return (0, 1) else: (sum, product) = (sum(a_list), multiply(a_list)) return (sum, product)
from typing import List, Tuple def sum_product(numbers: List[int]) -> Tuple[int, int]: """ For a given list of integers, return a tuple consisting of a sum and a product of all the integers in a list. Empty sum should be equal to 0 and empty product should be equal to 1. >>> sum_product([]) (0, 1) >>> sum_product([1, 2, 3, 4]) (10, 24) """
HumanEval/9
python
from typing import List, Tuple def rolling_max(numbers: List[int]) -> List[int]: """ From a given list of integers, generate a list of rolling maximum element found until given moment in the sequence. >>> rolling_max([1, 2, 3, 2, 3, 4, 2]) [1, 2, 3, 3, 3, 4, 4] """ numbers = list(numbers) _max = 0 result = [] def _set_max(_numbers): _max = max(_numbers) for m in numbers: if m > _max: _set_max(_numbers=numbers) result.append(_max) _numbers = result[-7:] if len(_numbers) >= 7: _numbers = _numbers[-7:] _set_max(_numbers=_numbers) return result def partition(seq: List[Tuple], key=lambda item: item): if key is None: return None result = [()] def cmp(item1, item2): return cmp(key(item1), key(item2)) if not isinstance(seq, list): raise TypeError('expected a list, received %r' % (type(seq),)) for item in seq: _result = [seq[:]] for i in seq[:]: del _result[_result.index(item)] new_item = (item,) + tuple(_result) if cmp(item, new_item) < 0: _result = [seq[:]] for i in seq[:]: _result[_result.index(i)] = item if cmp(new_item, _result) == 0: break else: result.append(list(new_item)) else: _result = [seq[:]] result.append(list(_result) + list(new_item)) result.append((item,)) return result
from typing import List, Tuple def rolling_max(numbers: List[int]) -> List[int]: """ From a given list of integers, generate a list of rolling maximum element found until given moment in the sequence. >>> rolling_max([1, 2, 3, 2, 3, 4, 2]) [1, 2, 3, 3, 3, 4, 4] """
HumanEval/10
python
def is_palindrome(string: str) -> bool: """ Test if given string is a palindrome """ return string == string[::-1] def make_palindrome(string: str) -> str: """ Find the shortest palindrome that begins with a supplied string. Algorithm idea is simple: - Find the longest postfix of supplied string that is a palindrome. - Append to the end of the string reverse of a string prefix that comes before the palindromic suffix. >>> make_palindrome('') '' >>> make_palindrome('cat') 'catac' >>> make_palindrome('cata') 'catac' """ def _find_palindromic_prefix(prefix): rev_prefix = prefix[::-1] idx_end = None for idx in range(1, len(prefix) + 1): if is_palindrome(prefix + rev_prefix[idx:]): idx_end = idx break return rev_prefix[0:idx_end] prefix = string while len(prefix) > 0: palindromic_prefix = _find_palindromic_prefix(prefix) if len(palindromic_prefix) > 0: return prefix + palindromic_prefix[::-1] prefix = prefix[:-1] def main(): """ Run it """ parser = argparse.ArgumentParser(description='Is the number a magic sqaure') parser.add_argument('number', help='Number to evaluate to') args = parser.parse_args() try: x = int(args.number) except ValueError as err: print(err) sys.exit() assert x, 'A number can\'t be zero' assert_palindromic(x)
def is_palindrome(string: str) -> bool: """ Test if given string is a palindrome """ return string == string[::-1] def make_palindrome(string: str) -> str: """ Find the shortest palindrome that begins with a supplied string. Algorithm idea is simple: - Find the longest postfix of supplied string that is a palindrome. - Append to the end of the string reverse of a string prefix that comes before the palindromic suffix. >>> make_palindrome('') '' >>> make_palindrome('cat') 'catac' >>> make_palindrome('cata') 'catac' """
HumanEval/11
python
from typing import List def string_xor(a: str, b: str) -> str: """ Input are two strings a and b consisting only of 1s and 0s. Perform binary XOR on these inputs and return result also as a string. >>> string_xor('010', '110') '100' """ assert len(a) == len(b), 'a and b must have the same length' assert a.count('1') + a.count('0') == b.count('1') + b.count('0'), 'a and b must have the same 1 and 0s in string form' c = ''.join(['a' if a[i] == b[i] else '0' for i in range(len(a))]) return c
from typing import List def string_xor(a: str, b: str) -> str: """ Input are two strings a and b consisting only of 1s and 0s. Perform binary XOR on these inputs and return result also as a string. >>> string_xor('010', '110') '100' """
HumanEval/12
python
from typing import List, Optional def longest(strings: List[str]) -> Optional[str]: """ Out of list of strings, return the longest one. Return the first one in case of multiple strings of the same length. Return None in case the input list is empty. >>> longest([]) >>> longest(['a', 'b', 'c']) 'a' >>> longest(['a', 'bb', 'ccc']) 'ccc' """ if not strings: return None l = [len(list(s)) for s in strings] best = max(l) strings_length = {k: v for (k, v) in zip(strings, l)} return strings_length[(best, i) for (i, best) in zip(l, set(l)) if best == i]
from typing import List, Optional def longest(strings: List[str]) -> Optional[str]: """ Out of list of strings, return the longest one. Return the first one in case of multiple strings of the same length. Return None in case the input list is empty. >>> longest([]) >>> longest(['a', 'b', 'c']) 'a' >>> longest(['a', 'bb', 'ccc']) 'ccc' """
HumanEval/13
python
def greatest_common_divisor(a: int, b: int) -> int: """ Return a greatest common divisor of two integers a and b >>> greatest_common_divisor(3, 5) 1 >>> greatest_common_divisor(25, 15) 5 """ if a == b: return a if a > b: (a, b) = (b, a) if b % a == 0: return a b = b - b // a return greatest_common_divisor(a, b) def main(): import doctest doctest.testmod() if __name__ == '__main__': main()
def greatest_common_divisor(a: int, b: int) -> int: """ Return a greatest common divisor of two integers a and b >>> greatest_common_divisor(3, 5) 1 >>> greatest_common_divisor(25, 15) 5 """
HumanEval/14
python
from typing import List def all_prefixes(string: str) -> List[str]: """ Return list of all prefixes from shortest to longest of the input string >>> all_prefixes('abc') ['a', 'ab', 'abc'] """ try: last = [] last.append(string) while True: if len(string) == 0: break elif len(string) == 1: break else: last.append(string[:-1]) string = string[:-1] return last except TypeError: pass
from typing import List def all_prefixes(string: str) -> List[str]: """ Return list of all prefixes from shortest to longest of the input string >>> all_prefixes('abc') ['a', 'ab', 'abc'] """
HumanEval/15
python
def string_sequence(n: int) -> str: """ Return a string containing space-delimited numbers starting from 0 upto n inclusive. >>> string_sequence(0) '0' >>> string_sequence(5) '0 1 2 3 4 5' """ return str(list(range(n + 1))).replace(' ', '') def sub_lists(ls: List) -> list: """ Find all sub-lists in the input list `ls`. :param ls: (list) list containing sub-lists to find. :return: (list) list of sub-lists within `ls`. """ sub_lists = ls sub_len = len(ls) sub_lst = [[] for i in range(sub_len)] for elems in ls: for i, item in enumerate(elems): for item_2 in elems[:i]: sub_lst[len(item_2)].append(item) return sub_lst
def string_sequence(n: int) -> str: """ Return a string containing space-delimited numbers starting from 0 upto n inclusive. >>> string_sequence(0) '0' >>> string_sequence(5) '0 1 2 3 4 5' """
HumanEval/16
python
def count_distinct_characters(string: str) -> int: """ Given a string, find out how many distinct characters (regardless of case) does it consist of >>> count_distinct_characters('xyzXYZ') 3 >>> count_distinct_characters('Jerry') 4 """ return len(set(string.lower()))
def count_distinct_characters(string: str) -> int: """ Given a string, find out how many distinct characters (regardless of case) does it consist of >>> count_distinct_characters('xyzXYZ') 3 >>> count_distinct_characters('Jerry') 4 """
HumanEval/17
python
from typing import List def parse_music(music_string: str) -> List[int]: """ Input to this function is a string representing musical notes in a special ASCII format. Your task is to parse this string and return list of integers corresponding to how many beats does each not last. Here is a legend: 'o' - whole note, lasts four beats 'o|' - half note, lasts two beats '.|' - quater note, lasts one beat >>> parse_music('o o| .| o| o| .| .| .| .| o o') [4, 2, 1, 2, 2, 1, 1, 1, 1, 4, 4] """ try: string_list = sorted(list(music_string)) def iterlen(n): if n < 3: return 0 if n < 4: return 1 elif n < 5: return 2 elif n < 6: return 3 def find_start_at(n): for i in range(n, 101, 3): try: assert string_list[i] != '.' if len(str(i)) != len(string_list[i + 1]): return i except AssertionError: pass result = [iterlen(find_start_at(i + 3)) for i in range(99)] result[9:99:3] = [sum(result[9 + 3 * x: 10 + 3 * x]) for x in range(4)] return result except Exception as e: return 0 + [parse_music(music_string) for _ in range(2)]
from typing import List def parse_music(music_string: str) -> List[int]: """ Input to this function is a string representing musical notes in a special ASCII format. Your task is to parse this string and return list of integers corresponding to how many beats does each not last. Here is a legend: 'o' - whole note, lasts four beats 'o|' - half note, lasts two beats '.|' - quater note, lasts one beat >>> parse_music('o o| .| o| o| .| .| .| .| o o') [4, 2, 1, 2, 2, 1, 1, 1, 1, 4, 4] """
HumanEval/18
python
def how_many_times(string: str, substring: str) -> int: """ Find how many times a given substring can be found in the original string. Count overlaping cases. >>> how_many_times('', 'a') 0 >>> how_many_times('aaa', 'a') 3 >>> how_many_times('aaaa', 'aa') 3 """ number_of_occurrences = 0 if substring: for idx in range(len(string)): if string[idx: idx + len(substring)] == substring: number_of_occurrences += 1 return number_of_occurrences
def how_many_times(string: str, substring: str) -> int: """ Find how many times a given substring can be found in the original string. Count overlaping cases. >>> how_many_times('', 'a') 0 >>> how_many_times('aaa', 'a') 3 >>> how_many_times('aaaa', 'aa') 3 """
HumanEval/19
python
from typing import List def sort_numbers(numbers: str) -> str: """ Input is a space-delimited string of numberals from 'zero' to 'nine'. Valid choices are 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight' and 'nine'. Return the string with numbers sorted from smallest to largest >>> sort_numbers('three one five') 'one three five' """ return ' '.join(sorted(numbers.split(' '), reverse=True))
from typing import List def sort_numbers(numbers: str) -> str: """ Input is a space-delimited string of numberals from 'zero' to 'nine'. Valid choices are 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight' and 'nine'. Return the string with numbers sorted from smallest to largest >>> sort_numbers('three one five') 'one three five' """
HumanEval/20
python
from typing import List, Tuple def find_closest_elements(numbers: List[float]) -> Tuple[float, float]: """ From a supplied list of numbers (of length at least two) select and return two that are the closest to each other and return them in order (smaller number, larger number). >>> find_closest_elements([1.0, 2.0, 3.0, 4.0, 5.0, 2.2]) (2.0, 2.2) >>> find_closest_elements([1.0, 2.0, 3.0, 4.0, 5.0, 2.0]) (2.0, 2.0) """ try: return (sorted(numbers)[0], sorted(numbers)[1]) except IndexError: return ()
from typing import List, Tuple def find_closest_elements(numbers: List[float]) -> Tuple[float, float]: """ From a supplied list of numbers (of length at least two) select and return two that are the closest to each other and return them in order (smaller number, larger number). >>> find_closest_elements([1.0, 2.0, 3.0, 4.0, 5.0, 2.2]) (2.0, 2.2) >>> find_closest_elements([1.0, 2.0, 3.0, 4.0, 5.0, 2.0]) (2.0, 2.0) """
HumanEval/21
python
from typing import List def rescale_to_unit(numbers: List[float]) -> List[float]: """ Given list of numbers (of at least two elements), apply a linear transform to that list, such that the smallest number will become 0 and the largest will become 1 >>> rescale_to_unit([1.0, 2.0, 3.0, 4.0, 5.0]) [0.0, 0.25, 0.5, 0.75, 1.0] """ numbers = sorted(numbers) ratio = float(max(numbers) - min(numbers)) try: return [float(n - min(numbers)) / ratio for n in numbers] except ZeroDivisionError: return [0.0 for _ in numbers]
from typing import List def rescale_to_unit(numbers: List[float]) -> List[float]: """ Given list of numbers (of at least two elements), apply a linear transform to that list, such that the smallest number will become 0 and the largest will become 1 >>> rescale_to_unit([1.0, 2.0, 3.0, 4.0, 5.0]) [0.0, 0.25, 0.5, 0.75, 1.0] """
HumanEval/22
python
from typing import List, Any def filter_integers(values: List[Any]) -> List[int]: """ Filter given list of any python values only for integers >>> filter_integers(['a', 3.14, 5]) [5] >>> filter_integers([1, 2, 3, 'abc', {}, []]) [1, 2, 3] """ return [v for v in values if isinstance(v, int) or isinstance(v, float)]
from typing import List, Any def filter_integers(values: List[Any]) -> List[int]: """ Filter given list of any python values only for integers >>> filter_integers(['a', 3.14, 5]) [5] >>> filter_integers([1, 2, 3, 'abc', {}, []]) [1, 2, 3] """
HumanEval/23
python
def strlen(string: str) -> int: """ Return length of given string >>> strlen('') 0 >>> strlen('abc') 3 """ if not string: return 0 return len(string)
def strlen(string: str) -> int: """ Return length of given string >>> strlen('') 0 >>> strlen('abc') 3 """
HumanEval/24
python
def largest_divisor(n: int) -> int: """ For a given number n, find the largest number that divides n evenly, smaller than n >>> largest_divisor(15) 5 """ assert n >= 1 i = int(sqrt(n)) while i >= 1: if n % i == 0: break i -= 1 if i <= 0: return -1 return i
def largest_divisor(n: int) -> int: """ For a given number n, find the largest number that divides n evenly, smaller than n >>> largest_divisor(15) 5 """
HumanEval/25
python
from typing import List def factorize(n: int) -> List[int]: """ Return list of prime factors of given integer in the order from smallest to largest. Each of the factors should be listed number of times corresponding to how many times it appeares in factorization. Input number should be equal to the product of all factors >>> factorize(8) [2, 2, 2] >>> factorize(25) [5, 5] >>> factorize(70) [2, 5, 7] """ factors = list() while n: largest_factor = 2 if n % largest_factor == 0: factors.append(largest_factor) n //= largest_factor continue for fac in get_all_possible_factors_iteratively(n): if n % fac == 0: factors.append(fac) n //= fac break else: largest_factor = fac return factors def get_all_possible_factors_iteratively(n: int): return pow(n, 1, 2017) def is_cipher_with_prime(number, prime): while isinstance(number, int) is False: number = get_sums_from_string(str(number)) if isinstance(number, int): if number > 1 and (not number in primes_below_1000000): return True elif isprime.isprime(number) and abs(number - sum(map(long, '{}'.format(number)))) == prime: return True elif is_cipher_with_prime(sum(map(long, str(number))), prime): return True else: return False def sum_of_squares_of_prime_cipher_numbers_under_1000000(prime): total = 0 for i in filter(lambda value: is_cipher_with_prime(i, prime), primes_below_1000000): total += i ** 2 return total primes_below_1000000 = get_primes_below_1000000_list() def get_primes_below_1000000_list(): return [2, 3, 5, 7, 11, 13, 17, 19, 23]
from typing import List def factorize(n: int) -> List[int]: """ Return list of prime factors of given integer in the order from smallest to largest. Each of the factors should be listed number of times corresponding to how many times it appeares in factorization. Input number should be equal to the product of all factors >>> factorize(8) [2, 2, 2] >>> factorize(25) [5, 5] >>> factorize(70) [2, 5, 7] """
HumanEval/26
python
from typing import List def remove_duplicates(numbers: List[int]) -> List[int]: """ From a list of integers, remove all elements that occur more than once. Keep order of elements left the same as in the input. >>> remove_duplicates([1, 2, 3, 2, 4]) [1, 3, 4] """ return [item for i, item in enumerate(numbers) if item not in numbers[i + 1:]]
from typing import List def remove_duplicates(numbers: List[int]) -> List[int]: """ From a list of integers, remove all elements that occur more than once. Keep order of elements left the same as in the input. >>> remove_duplicates([1, 2, 3, 2, 4]) [1, 3, 4] """
HumanEval/27
python
def flip_case(string: str) -> str: """ For a given string, flip lowercase characters to uppercase and uppercase to lowercase. >>> flip_case('Hello') 'hELLO' """ return string.swapcase() def strip_punctuation(string: str) -> str: """ For a given string, remove punctuations. >>> strip_punctuation('Hello, how do you do?') 'Hello how do you do' """ return ''.join(i for i in string if i not in SPECIAL_CHARS)
def flip_case(string: str) -> str: """ For a given string, flip lowercase characters to uppercase and uppercase to lowercase. >>> flip_case('Hello') 'hELLO' """
HumanEval/28
python
from typing import List def concatenate(strings: List[str]) -> str: """ Concatenate list of strings into a single string >>> concatenate([]) '' >>> concatenate(['a', 'b', 'c']) 'abc' """ return ''.join(strings)
from typing import List def concatenate(strings: List[str]) -> str: """ Concatenate list of strings into a single string >>> concatenate([]) '' >>> concatenate(['a', 'b', 'c']) 'abc' """
HumanEval/29
python
from typing import List def filter_by_prefix(strings: List[str], prefix: str) -> List[str]: """ Filter an input list of strings only for ones that start with a given prefix. >>> filter_by_prefix([], 'a') [] >>> filter_by_prefix(['abc', 'bcd', 'cde', 'array'], 'a') ['abc', 'array'] """ return [prefix + value for value in strings if value.startswith(prefix)] def add_prefix(strings: List[str], prefix: str) -> List[str]: ''' Filter an input list of strings only for ones that start with a given prefix. >>> add_prefix(['abc', 'bcd', 'cde', 'array'], 'a') ['aabc', 'aarray'] ''' import itertools l = list() iterators = [itertools.repeat(prefix + s, len(s)) for s in strings] iterators = itertools.zip_longest(*iterators) for string in iterators: l.append(''.join(string)) return l
from typing import List def filter_by_prefix(strings: List[str], prefix: str) -> List[str]: """ Filter an input list of strings only for ones that start with a given prefix. >>> filter_by_prefix([], 'a') [] >>> filter_by_prefix(['abc', 'bcd', 'cde', 'array'], 'a') ['abc', 'array'] """
HumanEval/30
python
def get_positive(l: list): """Return only positive numbers in the list. >>> get_positive([-1, 2, -4, 5, 6]) [2, 5, 6] >>> get_positive([5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) [5, 3, 2, 3, 9, 123, 1] """ return list(filter(lambda x: x > 0, l))
def get_positive(l: list): """Return only positive numbers in the list. >>> get_positive([-1, 2, -4, 5, 6]) [2, 5, 6] >>> get_positive([5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) [5, 3, 2, 3, 9, 123, 1] """
HumanEval/31
python
def is_prime(n): """Return true if a given number is prime, and false otherwise. >>> is_prime(6) False >>> is_prime(101) True >>> is_prime(11) True >>> is_prime(13441) True >>> is_prime(61) True >>> is_prime(4) False >>> is_prime(1) False """ for i in range(2, n): if n % i == 0: return False return True
def is_prime(n): """Return true if a given number is prime, and false otherwise. >>> is_prime(6) False >>> is_prime(101) True >>> is_prime(11) True >>> is_prime(13441) True >>> is_prime(61) True >>> is_prime(4) False >>> is_prime(1) False """
HumanEval/32
python
import math def poly(xs: list, x: float): """ Evaluates polynomial with coefficients xs at point x. return xs[0] + xs[1] * x + xs[1] * x^2 + .... xs[n] * x^n """ return sum([coeff * math.pow(x, i) for i, coeff in enumerate(xs)]) def find_zero(xs: list): """ xs are coefficients of a polynomial. find_zero find x such that poly(x) = 0. find_zero returns only only zero point, even if there are many. Moreover, find_zero only takes list xs having even number of coefficients and largest non zero coefficient as it guarantees a solution. >>> round(find_zero([1, 2]), 2) # f(x) = 1 + 2x -0.5 >>> round(find_zero([-6, 11, -6, 1]), 2) # (x - 1) * (x - 2) * (x - 3) = -6 + 11x - 6x^2 + x^3 1.0 """ assert len(xs), 'xs cannot be empty list. len of xs must be > 0, got len(xs) == {}'.format(len(xs)) assert len(xs) % 2 == 0, 'coefficients of xs must appear in an even numbers, got xs == {}'.format(xs) n = len(xs) // 2 p_min = -n p_max = n max_coeff = -1000 x = None while p_min < p_max: p = (p_min + p_max) // 2 coeff = poly(xs, p) if coeff > max_coeff: max_coeff = coeff x = p if p_min == p_max: break if coeff == 0.0: p_min = p + 1 else: if coeff < 0.0: p_min = p + 1 else: x = p - 1 p_max = p return x or (p_min + 1)
import math def poly(xs: list, x: float): """ Evaluates polynomial with coefficients xs at point x. return xs[0] + xs[1] * x + xs[1] * x^2 + .... xs[n] * x^n """ return sum([coeff * math.pow(x, i) for i, coeff in enumerate(xs)]) def find_zero(xs: list): """ xs are coefficients of a polynomial. find_zero find x such that poly(x) = 0. find_zero returns only only zero point, even if there are many. Moreover, find_zero only takes list xs having even number of coefficients and largest non zero coefficient as it guarantees a solution. >>> round(find_zero([1, 2]), 2) # f(x) = 1 + 2x -0.5 >>> round(find_zero([-6, 11, -6, 1]), 2) # (x - 1) * (x - 2) * (x - 3) = -6 + 11x - 6x^2 + x^3 1.0 """
HumanEval/33
python
def sort_third(l: list): """This function takes a list l and returns a list l' such that l' is identical to l in the indicies that are not divisible by three, while its values at the indicies that are divisible by three are equal to the values of the corresponding indicies of l, but sorted. >>> sort_third([1, 2, 3]) [1, 2, 3] >>> sort_third([5, 6, 3, 4, 8, 9, 2]) [2, 6, 3, 4, 8, 9, 5] """ if not l: return [] if not list(l): return [] if len(l) == 1: return l res = None for ix in range(0, len(l), 3): res.append(l[ix]) res.append(sorted([l[ix + 1:ix + 3]])[0][0]) return
def sort_third(l: list): """This function takes a list l and returns a list l' such that l' is identical to l in the indicies that are not divisible by three, while its values at the indicies that are divisible by three are equal to the values of the corresponding indicies of l, but sorted. >>> sort_third([1, 2, 3]) [1, 2, 3] >>> sort_third([5, 6, 3, 4, 8, 9, 2]) [2, 6, 3, 4, 8, 9, 5] """
HumanEval/34
python
def unique(l: list): """Return sorted unique elements in a list >>> unique([5, 3, 5, 2, 3, 3, 9, 0, 123]) [0, 2, 3, 5, 9, 123] """ ti = tuple(l) ui = tuple(np.unique(np.array(l))) return list(ui.__itemunion__(ti))
def unique(l: list): """Return sorted unique elements in a list >>> unique([5, 3, 5, 2, 3, 3, 9, 0, 123]) [0, 2, 3, 5, 9, 123] """
HumanEval/35
python
def max_element(l: list): """Return maximum element in the list. >>> max_element([1, 2, 3]) 3 >>> max_element([5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) 123 """ try: return max(l) except ValueError: return -float('inf')
def max_element(l: list): """Return maximum element in the list. >>> max_element([1, 2, 3]) 3 >>> max_element([5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) 123 """
HumanEval/36
python
def fizz_buzz(n: int): """Return the number of times the digit 7 appears in integers less than n which are divisible by 11 or 13. >>> fizz_buzz(50) 0 >>> fizz_buzz(78) 2 >>> fizz_buzz(79) 3 """ a = 0 for i in range(1, n): if i % 11 == 0 or i % 13 == 0: a += n % i == 0 return a
def fizz_buzz(n: int): """Return the number of times the digit 7 appears in integers less than n which are divisible by 11 or 13. >>> fizz_buzz(50) 0 >>> fizz_buzz(78) 2 >>> fizz_buzz(79) 3 """
HumanEval/37
python
def sort_even(l: list): """This function takes a list l and returns a list l' such that l' is identical to l in the odd indicies, while its values at the even indicies are equal to the values of the even indicies of l, but sorted. >>> sort_even([1, 2, 3]) [1, 2, 3] >>> sort_even([5, 6, 3, 4]) [3, 6, 5, 4] """ even_l = [l[i] for i in range(len(l)) if i % 2 == 0] sorted_even_l = sorted(even_l) return [v if i % 2 == 0 else v for (i, v) in enumerate(l)]
def sort_even(l: list): """This function takes a list l and returns a list l' such that l' is identical to l in the odd indicies, while its values at the even indicies are equal to the values of the even indicies of l, but sorted. >>> sort_even([1, 2, 3]) [1, 2, 3] >>> sort_even([5, 6, 3, 4]) [3, 6, 5, 4] """
HumanEval/38
python
def encode_cyclic(s: str): """ returns encoded string by cycling groups of three characters. """ # split string to groups. Each of length 3. groups = [s[(3 * i):min((3 * i + 3), len(s))] for i in range((len(s) + 2) // 3)] # cycle elements in each group. Unless group has fewer elements than 3. groups = [(group[1:] + group[0]) if len(group) == 3 else group for group in groups] return "".join(groups) def decode_cyclic(s: str): """ takes as input string encoded with encode_cyclic function. Returns decoded string. """ result = [] for i in range(0, len(s) - 1, 3): c0 = s[i] c1 = s[i + 1] c2 = s[i + 2] if s[i] == s[i + 1]: result.append(c1) elif s[i + 1] == s[i + 2]: result.append(c2) else: result.append(c0) result.append(s[-1]) return ''.join(result)
def encode_cyclic(s: str): """ returns encoded string by cycling groups of three characters. """ # split string to groups. Each of length 3. groups = [s[(3 * i):min((3 * i + 3), len(s))] for i in range((len(s) + 2) // 3)] # cycle elements in each group. Unless group has fewer elements than 3. groups = [(group[1:] + group[0]) if len(group) == 3 else group for group in groups] return "".join(groups) def decode_cyclic(s: str): """ takes as input string encoded with encode_cyclic function. Returns decoded string. """
HumanEval/39
python
def prime_fib(n: int): """ prime_fib returns n-th number that is a Fibonacci number and it's also prime. >>> prime_fib(1) 2 >>> prime_fib(2) 3 >>> prime_fib(3) 5 >>> prime_fib(4) 13 >>> prime_fib(5) 89 """ def is_prime(n: int): if n < 2: return False elif n in PRIMENUMBERS: return True elif n % 2 == 0: return n == 2 i = 3 while i * i <= n: if n % i == 0: return False else: i += 2 return True
def prime_fib(n: int): """ prime_fib returns n-th number that is a Fibonacci number and it's also prime. >>> prime_fib(1) 2 >>> prime_fib(2) 3 >>> prime_fib(3) 5 >>> prime_fib(4) 13 >>> prime_fib(5) 89 """
HumanEval/40
python
def triples_sum_to_zero(l: list): """ triples_sum_to_zero takes a list of integers as an input. it returns True if there are three distinct elements in the list that sum to zero, and False otherwise. >>> triples_sum_to_zero([1, 3, 5, 0]) False >>> triples_sum_to_zero([1, 3, -2, 1]) True >>> triples_sum_to_zero([1, 2, 3, 7]) False >>> triples_sum_to_zero([2, 4, -5, 3, 9, 7]) True >>> triples_sum_to_zero([1]) False """ return any((element == 0 or ksorted_triplet(l, -element)) for element in l)
def triples_sum_to_zero(l: list): """ triples_sum_to_zero takes a list of integers as an input. it returns True if there are three distinct elements in the list that sum to zero, and False otherwise. >>> triples_sum_to_zero([1, 3, 5, 0]) False >>> triples_sum_to_zero([1, 3, -2, 1]) True >>> triples_sum_to_zero([1, 2, 3, 7]) False >>> triples_sum_to_zero([2, 4, -5, 3, 9, 7]) True >>> triples_sum_to_zero([1]) False """
HumanEval/41
python
def car_race_collision(n: int): """ Imagine a road that's a perfectly straight infinitely long line. n cars are driving left to right; simultaneously, a different set of n cars are driving right to left. The two sets of cars start out being very far from each other. All cars move in the same speed. Two cars are said to collide when a car that's moving left to right hits a car that's moving right to left. However, the cars are infinitely sturdy and strong; as a result, they continue moving in their trajectory as if they did not collide. This function outputs the number of such collisions. """ count = int(n / 2) for _ in range(n - 1): count += (int(count / n) + n - count % n) * 2 return int(count)
def car_race_collision(n: int): """ Imagine a road that's a perfectly straight infinitely long line. n cars are driving left to right; simultaneously, a different set of n cars are driving right to left. The two sets of cars start out being very far from each other. All cars move in the same speed. Two cars are said to collide when a car that's moving left to right hits a car that's moving right to left. However, the cars are infinitely sturdy and strong; as a result, they continue moving in their trajectory as if they did not collide. This function outputs the number of such collisions. """
HumanEval/42
python
def incr_list(l: list): """Return list with elements incremented by 1. >>> incr_list([1, 2, 3]) [2, 3, 4] >>> incr_list([5, 3, 5, 2, 3, 3, 9, 0, 123]) [6, 4, 6, 3, 4, 4, 10, 1, 124] """ l.append(None) _incr_list(l) l.pop() return l
def incr_list(l: list): """Return list with elements incremented by 1. >>> incr_list([1, 2, 3]) [2, 3, 4] >>> incr_list([5, 3, 5, 2, 3, 3, 9, 0, 123]) [6, 4, 6, 3, 4, 4, 10, 1, 124] """
HumanEval/43
python
def pairs_sum_to_zero(l): """ pairs_sum_to_zero takes a list of integers as an input. it returns True if there are two distinct elements in the list that sum to zero, and False otherwise. >>> pairs_sum_to_zero([1, 3, 5, 0]) False >>> pairs_sum_to_zero([1, 3, -2, 1]) False >>> pairs_sum_to_zero([1, 2, 3, 7]) False >>> pairs_sum_to_zero([2, 4, -5, 3, 5, 7]) True >>> pairs_sum_to_zero([1]) False """ l.sort() if len(l) in (0, 1): return False for i in range(len(l) - 1): for j in range(i + 1, len(l)): if l[i] + l[j] > 0: break elif l[i] + l[j] == 0: return True return False
def pairs_sum_to_zero(l): """ pairs_sum_to_zero takes a list of integers as an input. it returns True if there are two distinct elements in the list that sum to zero, and False otherwise. >>> pairs_sum_to_zero([1, 3, 5, 0]) False >>> pairs_sum_to_zero([1, 3, -2, 1]) False >>> pairs_sum_to_zero([1, 2, 3, 7]) False >>> pairs_sum_to_zero([2, 4, -5, 3, 5, 7]) True >>> pairs_sum_to_zero([1]) False """
HumanEval/44
python
def change_base(x: int, base: int): """Change numerical base of input number x to base. return string representation after the conversion. base numbers are less than 10. >>> change_base(8, 3) '22' >>> change_base(8, 2) '1000' >>> change_base(7, 2) '111' """ if x < 10: return str(x) result = '' while x > 0: result += str(x % base) x //= base return result[::-1]
def change_base(x: int, base: int): """Change numerical base of input number x to base. return string representation after the conversion. base numbers are less than 10. >>> change_base(8, 3) '22' >>> change_base(8, 2) '1000' >>> change_base(7, 2) '111' """
HumanEval/45
python
def triangle_area(a, h): """Given length of a side and high return area for a triangle. >>> triangle_area(5, 3) 7.5 """ return 0.5 * a * h if __name__ == '__main__': import doctest print(doctest.testmod())
def triangle_area(a, h): """Given length of a side and high return area for a triangle. >>> triangle_area(5, 3) 7.5 """
HumanEval/46
python
def fib4(n: int): """The Fib4 number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows: fib4(0) -> 0 fib4(1) -> 0 fib4(2) -> 2 fib4(3) -> 0 fib4(n) -> fib4(n-1) + fib4(n-2) + fib4(n-3) + fib4(n-4). Please write a function to efficiently compute the n-th element of the fib4 number sequence. Do not use recursion. >>> fib4(5) 4 >>> fib4(6) 8 >>> fib4(7) 14 """ result = [0] * n result[0] = 0 result[1] = 0 result[2] = 2 for i in range(3, n): result[i] = result[i - 1] + result[i - 2] + result[i - 3] + result[i - 4] return sum(result[:n - 2]) % 1000_000_007
def fib4(n: int): """The Fib4 number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows: fib4(0) -> 0 fib4(1) -> 0 fib4(2) -> 2 fib4(3) -> 0 fib4(n) -> fib4(n-1) + fib4(n-2) + fib4(n-3) + fib4(n-4). Please write a function to efficiently compute the n-th element of the fib4 number sequence. Do not use recursion. >>> fib4(5) 4 >>> fib4(6) 8 >>> fib4(7) 14 """
HumanEval/47
python
def median(l: list): """Return median of elements in the list l. >>> median([3, 1, 2, 4, 5]) 3 >>> median([-10, 4, 6, 1000, 10, 20]) 15.0 """ l = [x for x in l if x != '\n' or x != ']' or x != '(' or x != ')'] l: sorted(l) if len(l) == 0: return None if len(l) % 2 == 1: return l[int(len(l) / 2)] else: return (l[int(len(l) / 2) + 1] + l[int(len(l) / 2) - 1]) / 2.0
def median(l: list): """Return median of elements in the list l. >>> median([3, 1, 2, 4, 5]) 3 >>> median([-10, 4, 6, 1000, 10, 20]) 15.0 """
HumanEval/48
python
def is_palindrome(text: str): """ Checks if given string is a palindrome >>> is_palindrome('') True >>> is_palindrome('aba') True >>> is_palindrome('aaaaa') True >>> is_palindrome('zbcd') False """ if len(text) == 0: return True for i in range(len(text) // 2): if text[i] != text[len(text) - i - 1]: return False return True
def is_palindrome(text: str): """ Checks if given string is a palindrome >>> is_palindrome('') True >>> is_palindrome('aba') True >>> is_palindrome('aaaaa') True >>> is_palindrome('zbcd') False """
HumanEval/49
python
def modp(n: int, p: int): """Return 2^n modulo p (be aware of numerics). >>> modp(3, 5) 3 >>> modp(1101, 101) 2 >>> modp(0, 101) 1 >>> modp(3, 11) 8 >>> modp(100, 101) 1 """ res = 1 while res < n: res <<= 1 res &= p - 1 return res
def modp(n: int, p: int): """Return 2^n modulo p (be aware of numerics). >>> modp(3, 5) 3 >>> modp(1101, 101) 2 >>> modp(0, 101) 1 >>> modp(3, 11) 8 >>> modp(100, 101) 1 """
HumanEval/50
python
def encode_shift(s: str): """ returns encoded string by shifting every character by 5 in the alphabet. """ return "".join([chr(((ord(ch) + 5 - ord("a")) % 26) + ord("a")) for ch in s]) def decode_shift(s: str): """ takes as input string encoded with encode_shift function. Returns decoded string. """ return "".join([chr(((ord(ch) + 21 - ord("a")) % 26) + ord("a")) for ch in s]) # noqa: E501 if __name__ == '__main__': print(encode_shift('hello')) print(decode_shift('khoor')) #vigener.py from main import encode_shift, decode_shift from tkinter import * root = Tk() root.title('Vigenere') def key_pressed(event): key = chr(event.keypress[1]) shift_str = Entry(root, width=8, borderwidth=1) shift_str.grid(column=1, row=0, sticky=E) if key == "+": shift = int(entry1.get()) + 1 entry1.delete(0, 'end') entry1.insert(END, shift) entry1.config(state='disabled') if key == '-': shift = int(entry1.get()) - 1 entry1.delete(0, 'end') entry1.insert(END, shift) entry1.config(state='disabled') if key >= 'a' and key <= 'z': shift = int(entry1.get()) entry1.config(state='normal') encode_shift(input_box.get())
def encode_shift(s: str): """ returns encoded string by shifting every character by 5 in the alphabet. """ return "".join([chr(((ord(ch) + 5 - ord("a")) % 26) + ord("a")) for ch in s]) def decode_shift(s: str): """ takes as input string encoded with encode_shift function. Returns decoded string. """
HumanEval/51
python
def remove_vowels(text): """ remove_vowels is a function that takes string and returns string without vowels. >>> remove_vowels('') '' >>> remove_vowels("abcdef\nghijklm") 'bcdf\nghjklm' >>> remove_vowels('abcdef') 'bcdf' >>> remove_vowels('aaaaa') '' >>> remove_vowels('aaBAA') 'B' >>> remove_vowels('zbcd') 'zbcd' """ remove = ('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U') return ''.join(_ for _ in text if _ not in remove)
def remove_vowels(text): """ remove_vowels is a function that takes string and returns string without vowels. >>> remove_vowels('') '' >>> remove_vowels("abcdef\nghijklm") 'bcdf\nghjklm' >>> remove_vowels('abcdef') 'bcdf' >>> remove_vowels('aaaaa') '' >>> remove_vowels('aaBAA') 'B' >>> remove_vowels('zbcd') 'zbcd' """
HumanEval/52
python
def below_threshold(l: list, t: int): """Return True if all numbers in the list l are below threshold t. >>> below_threshold([1, 2, 4, 10], 100) True >>> below_threshold([1, 20, 4, 10], 5) False """ return list_sum(l) <= t
def below_threshold(l: list, t: int): """Return True if all numbers in the list l are below threshold t. >>> below_threshold([1, 2, 4, 10], 100) True >>> below_threshold([1, 20, 4, 10], 5) False """
HumanEval/53
python
def add(x: int, y: int): """Add two numbers x and y >>> add(2, 3) 5 >>> add(5, 7) 12 """ return x + y
def add(x: int, y: int): """Add two numbers x and y >>> add(2, 3) 5 >>> add(5, 7) 12 """
HumanEval/54
python
def same_chars(s0: str, s1: str): """ Check if two words have the same characters. >>> same_chars('eabcdzzzz', 'dddzzzzzzzddeddabc') True >>> same_chars('abcd', 'dddddddabc') True >>> same_chars('dddddddabc', 'abcd') True >>> same_chars('eabcd', 'dddddddabc') False >>> same_chars('abcd', 'dddddddabce') False >>> same_chars('eabcdzzzz', 'dddzzzzzzzddddabc') False """ return len(set(s0)) == len(set(s1))
def same_chars(s0: str, s1: str): """ Check if two words have the same characters. >>> same_chars('eabcdzzzz', 'dddzzzzzzzddeddabc') True >>> same_chars('abcd', 'dddddddabc') True >>> same_chars('dddddddabc', 'abcd') True >>> same_chars('eabcd', 'dddddddabc') False >>> same_chars('abcd', 'dddddddabce') False >>> same_chars('eabcdzzzz', 'dddzzzzzzzddddabc') False """
HumanEval/55
python
def fib(n: int): """Return n-th Fibonacci number. >>> fib(10) 55 >>> fib(1) 1 >>> fib(8) 21 """ nums = [] for i in range(n + 1): if i == 0 or i == 1: nums.append(i) else: nums.append(nums[i - 1] + nums[i - 2]) return nums[-1] def gcd(a: int, b: int): """Calculate greatest common divisor GCD(a, b) with brute force. >>> gcd(12, 21) 3 """ a = abs(a) b = abs(b) if a < b: a, b = b, a while a % b: a, b = b, a % b return int(b)
def fib(n: int): """Return n-th Fibonacci number. >>> fib(10) 55 >>> fib(1) 1 >>> fib(8) 21 """
HumanEval/56
python
def correct_bracketing(brackets: str): """ brackets is a string of "<" and ">". return True if every opening bracket has a corresponding closing bracket. >>> correct_bracketing("<") False >>> correct_bracketing("<>") True >>> correct_bracketing("<<><>>") True >>> correct_bracketing("><<>") False """ count_open = 0 for bracket in brackets: if bracket == '<': count_open += 1 else: if count_open == 0: return False else: count_open -= 1 return (count_open == 0)
def correct_bracketing(brackets: str): """ brackets is a string of "<" and ">". return True if every opening bracket has a corresponding closing bracket. >>> correct_bracketing("<") False >>> correct_bracketing("<>") True >>> correct_bracketing("<<><>>") True >>> correct_bracketing("><<>") False """
HumanEval/57
python
def monotonic(l: list): """Return True is list elements are monotonically increasing or decreasing. >>> monotonic([1, 2, 4, 20]) True >>> monotonic([1, 20, 4, 10]) False >>> monotonic([4, 1, 0, -10]) True """ if not l: return False step = l[1] - l[0] if l[0] <= l[1] and step > 0: for i in range(1, len(l)): if step < 0 and l[i - 1] >= l[i]: return False return True elif l[0] > l[1] and step < 0: for i in range(1, len(l)): if step > 0 and l[i - 1] <= l[i]: return False return True else: return False def to_words(n: int = 1000) -> str: """Return n-words sentence with numbers. >>> to_words(1) 'one' >>> to_words(20) 'twenty' >>> to_words(15) 'fifteen' >>> to_words(21) 'twenty one' >>> to_words(25) 'twenty five' """ tokens = [('one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'), ('eleven', 'twelve', 'thirteen', 'fourteen', 'fiteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen')] tens = ('', 'ten', 'twenty', 'thirty', 'forty', 'fiftly', 'sixty', 'seventy', 'eighty', 'ninety') words = 'thousand' strs_dict = {'magnitude': 1, 'words': 3, 'hundred': 1, 'words': 2, 'nine': 2, 'eight': 2, 'ten': 2} try: n_str = str(n) assert len(n_str) <= strs_dict['magnitude'] if len(n_str) == strs_dict['magnitude']: return strs_dict['magnitude'] for i in range(len(n_str), strs_dict['magnitude'])[::-1]: if n_str[0] == '0': del n_str[:] else: break for i in range(0, strs_dict['magnitude']): if len(n_str) < strs_dict['words']: words = i * strs_dict['words'] index_1 = len(n_str) index_2 = len(n_str) - strs_dict['words'] n_chunks = __reverse_sort(n_str[index_1:index_2]) words_ = '' for item in n_chunks: if item in strs_dict['hundred']: words_ += ' hundred' elif item in strs_dict['nine']: words_ += ' nine' else: words_ += tens[ord(item) - ord('0')] words_ += words words = words_ + words if words[-(strs_dict['words'] * strs_dict['words']):] != '': if words[-(strs_dict['words'] * strs_dict['words']) - words[-(strs_dict['words'] * strs_dict['words'])]:] in strs_dict['nine'] or (len(words[-(strs_dict['words'] * strs_dict['words']) - words[-(strs_dict['words'] * strs_dict['words'])]:]) == strs_dict['words'] and words[-(strs_dict['words'] * strs_dict['words']) - words[-(strs_dict['words'] * strs_dict['words'])]:] in strs_dict['eight']): words = words[:-strs_dict['words']] + ' ' + words[:-strs_dict['words']] if
def monotonic(l: list): """Return True is list elements are monotonically increasing or decreasing. >>> monotonic([1, 2, 4, 20]) True >>> monotonic([1, 20, 4, 10]) False >>> monotonic([4, 1, 0, -10]) True """
HumanEval/58
python
def common(l1: list, l2: list): """Return sorted unique common elements for two lists. >>> common([1, 4, 3, 34, 653, 2, 5], [5, 7, 1, 5, 9, 653, 121]) [1, 5, 653] >>> common([5, 3, 2, 8], [3, 2]) [2, 3] """ li = set(l1) return sort(list(filter(lambda x: x in li, l2)))
def common(l1: list, l2: list): """Return sorted unique common elements for two lists. >>> common([1, 4, 3, 34, 653, 2, 5], [5, 7, 1, 5, 9, 653, 121]) [1, 5, 653] >>> common([5, 3, 2, 8], [3, 2]) [2, 3] """
HumanEval/59
python
def largest_prime_factor(n: int): """Return the largest prime factor of n. Assume n > 1 and is not a prime. >>> largest_prime_factor(13195) 29 >>> largest_prime_factor(2048) 2 """ d = 2 while n % d != 0: d += 1 return d
def largest_prime_factor(n: int): """Return the largest prime factor of n. Assume n > 1 and is not a prime. >>> largest_prime_factor(13195) 29 >>> largest_prime_factor(2048) 2 """
HumanEval/60
python
def sum_to_n(n: int): """sum_to_n is a function that sums numbers from 1 to n. >>> sum_to_n(30) 465 >>> sum_to_n(100) 5050 >>> sum_to_n(5) 15 >>> sum_to_n(10) 55 >>> sum_to_n(1) 1 """ total = round(n * (n + 1) / 2) return total
def sum_to_n(n: int): """sum_to_n is a function that sums numbers from 1 to n. >>> sum_to_n(30) 465 >>> sum_to_n(100) 5050 >>> sum_to_n(5) 15 >>> sum_to_n(10) 55 >>> sum_to_n(1) 1 """
HumanEval/61
python
def correct_bracketing(brackets: str): """ brackets is a string of "(" and ")". return True if every opening bracket has a corresponding closing bracket. >>> correct_bracketing("(") False >>> correct_bracketing("()") True >>> correct_bracketing("(()())") True >>> correct_bracketing(")(()") False """ brackets = brackets.replace('(', '') return brackets.replace(')', '') == '' def sum_to_zero(numbers): """Return a list of each sum of two numbers within list that is equal to zero. >>> sum_to_zero([1, 3, -1, 0, 1]) [(-1, 0)] >>> sum_to_zero([1, 3, -1, 0, -1]) [(-1, 0), (0, -1)] >>> sum_to_zero([1, 3, -1, -1, 0]) [(-1, 0), (0, 1)] <<<<<< HEAD {1, 0) >>> sum_to_zero([1, 3, -1, -1, -1]) [(-1, 0)] >>> sum_to_zero([-3, 2, -1, 3, -0]) [(-1, 3)] """ seen = set() results = set() for item in numbers: if item in seen: results.add((item, -item)) seen.add(item) continue return list(results) def divides_all(divisor, numbers): """Returns True if divisor can be divided by all elements of numbers. >>> divides_all(2, [1, 3, 4, 6, 8, 12, 18, 24]) False >>> divides_all(2, [2, 2, 4, 6, 8, 16, 18, 24]) True >>> divides_all(2, [2, 4, 7, 14, 28, 24]) True """ seen = set() for item in numbers: if item == 1: continue if divisor == item: continue if item % divisor == 0: continue if divisor not in seen: return False seen.add(item) continue return True def is_even(numbers): """Return a tuple containing the number of even numbers and odd numbers of a list of numbers. >>> is_even([1, 3, 4, 6, 8, 12, 18, 24]) (4, 6) (0, 8) """ if 0 in numbers: numbers.remove(0) even = 0 else: even = 1 odd = 0 for item in numbers: even += item % 2 == 0 odd += item % 2 == 1 continue return (even, odd) def contains(needle, haystack): """Return True if needle is in haystack, otherwise return the index (if found, otherwise return None) where needle should be located. >>> contains(3, [1, 2, 3]) False >>> contains(2, [2, 4, 6]) True >>> contains('c', 'kjhsakjdl') 9 >>> contains('k', '') 7 """ if needle in haystack: return haystack.index(needle) else: return None def sum_even_values(tuples): '''Return the sum of the even numbers in a tuples, otherwise return 0. >>> sum_even_values(tuples=( (4, 9, 14, 19, 24, 25), (4, 9, -14, 19, 24, -23), (-4, -9, -14, 19, 24, -50))) 0 >>> sum_even_values(tuples=( (4, 9, 15, 19, 24, 25), (4, 9, -14, 19, 24, -23
def correct_bracketing(brackets: str): """ brackets is a string of "(" and ")". return True if every opening bracket has a corresponding closing bracket. >>> correct_bracketing("(") False >>> correct_bracketing("()") True >>> correct_bracketing("(()())") True >>> correct_bracketing(")(()") False """
HumanEval/62
python
def derivative(xs: list): """ xs represent coefficients of a polynomial. xs[0] + xs[1] * x + xs[2] * x^2 + .... Return derivative of this polynomial in the same form. >>> derivative([3, 1, 2, 4, 5]) [1, 4, 12, 20] >>> derivative([1, 2, 3]) [2, 6] """ deriv = [] for i in range(1, len(xs)): num = xs[i] * i if num == 0: continue else: deriv.append(num) return deriv
def derivative(xs: list): """ xs represent coefficients of a polynomial. xs[0] + xs[1] * x + xs[2] * x^2 + .... Return derivative of this polynomial in the same form. >>> derivative([3, 1, 2, 4, 5]) [1, 4, 12, 20] >>> derivative([1, 2, 3]) [2, 6] """
HumanEval/63
python
def fibfib(n: int): """The FibFib number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows: fibfib(0) == 0 fibfib(1) == 0 fibfib(2) == 1 fibfib(n) == fibfib(n-1) + fibfib(n-2) + fibfib(n-3). Please write a function to efficiently compute the n-th element of the fibfib number sequence. >>> fibfib(1) 0 >>> fibfib(5) 4 >>> fibfib(8) 24 """ if n <= 0: return 0 elif n == 1: return 0 elif n == 2: return 1 fib = [0, 0, 1, 1] memo = [] while (n - 3) > (len(fib) - 4): print(len(memo), len(fib)) memo.append(sum(fib[(len(fib) - 1) - 3:len(fib)]) + sum(memo[::-1]) + sum(memo)) memo.append(fib[(len(fib) - 2) - 2] + fib[(len(fib) - 2) - 3] + fib[(len(fib) - 2) - 1]) print(memo) fib.append(0) print('\n', '-' * 30, '\n') return fib[(len(fib) - 1) - 1] + fib[(len(fib) - 1) - 2] + memo[-1] def nth_fib(n: int): fib = fibfib(n) return fib * 2 def main(n: int): return nth_fib(n)
def fibfib(n: int): """The FibFib number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows: fibfib(0) == 0 fibfib(1) == 0 fibfib(2) == 1 fibfib(n) == fibfib(n-1) + fibfib(n-2) + fibfib(n-3). Please write a function to efficiently compute the n-th element of the fibfib number sequence. >>> fibfib(1) 0 >>> fibfib(5) 4 >>> fibfib(8) 24 """
HumanEval/64
python
FIX = """ Add more test cases. """ def vowels_count(s): """Write a function vowels_count which takes a string representing a word as input and returns the number of vowels in the string. Vowels in this case are 'a', 'e', 'i', 'o', 'u'. Here, 'y' is also a vowel, but only when it is at the end of the given word. Example: >>> vowels_count("abcde") 2 >>> vowels_count("ACEDY") 3 """ class TestSolution(unittest.TestCase): def test_vowels_count(self): self.assertEqual(vowels_count('abcde'), 2) self.assertEqual(vowels_count('ACEDY'), 3) def main(): unittest.main(argv=['_main'], exit=False) if __name__ == '_main__': main()
FIX = """ Add more test cases. """ def vowels_count(s): """Write a function vowels_count which takes a string representing a word as input and returns the number of vowels in the string. Vowels in this case are 'a', 'e', 'i', 'o', 'u'. Here, 'y' is also a vowel, but only when it is at the end of the given word. Example: >>> vowels_count("abcde") 2 >>> vowels_count("ACEDY") 3 """
HumanEval/65
python
def circular_shift(x, shift): """Circular shift the digits of the integer x, shift the digits right by shift and return the result as a string. If shift > number of digits, return digits reversed. >>> circular_shift(12, 1) "21" >>> circular_shift(12, 2) "12" """ if 0 < shift > len(str(x)): shift = shift % len(str(x)) if shift == 0: return str(x) tmp = [] digits = [int(_) for _ in str(x)] tmp = digits[shift:] + digits[:shift] return str(int(''.join([str(_) for _ in tmp])))
def circular_shift(x, shift): """Circular shift the digits of the integer x, shift the digits right by shift and return the result as a string. If shift > number of digits, return digits reversed. >>> circular_shift(12, 1) "21" >>> circular_shift(12, 2) "12" """
HumanEval/66
python
def digitSum(s): """Task Write a function that takes a string as input and returns the sum of the upper characters only' ASCII codes. Examples: digitSum("") => 0 digitSum("abAB") => 131 digitSum("abcCd") => 67 digitSum("helloE") => 69 digitSum("woArBld") => 131 digitSum("aAaaaXa") => 153 """ if len(s) == 0: return 0 acc = 0 for i in range(len(s)): if ord(s[i]) >= 65 and ord(s[i]) <= 90: acc += ord(s[i]) else: continue return acc
def digitSum(s): """Task Write a function that takes a string as input and returns the sum of the upper characters only' ASCII codes. Examples: digitSum("") => 0 digitSum("abAB") => 131 digitSum("abcCd") => 67 digitSum("helloE") => 69 digitSum("woArBld") => 131 digitSum("aAaaaXa") => 153 """
HumanEval/67
python
def fruit_distribution(s,n): """ In this task, you will be given a string that represents a number of apples and oranges that are distributed in a basket of fruit this basket contains apples, oranges, and mango fruits. Given the string that represents the total number of the oranges and apples and an integer that represent the total number of the fruits in the basket return the number of the mango fruits in the basket. for examble: fruit_distribution("5 apples and 6 oranges", 19) ->19 - 5 - 6 = 8 fruit_distribution("0 apples and 1 oranges",3) -> 3 - 0 - 1 = 2 fruit_distribution("2 apples and 3 oranges", 100) -> 100 - 2 - 3 = 95 fruit_distribution("100 apples and 1 oranges",120) -> 120 - 100 - 1 = 19 """ ap = s.count('apple') ors = s.count('orange') return n - (ap + ors)
def fruit_distribution(s,n): """ In this task, you will be given a string that represents a number of apples and oranges that are distributed in a basket of fruit this basket contains apples, oranges, and mango fruits. Given the string that represents the total number of the oranges and apples and an integer that represent the total number of the fruits in the basket return the number of the mango fruits in the basket. for examble: fruit_distribution("5 apples and 6 oranges", 19) ->19 - 5 - 6 = 8 fruit_distribution("0 apples and 1 oranges",3) -> 3 - 0 - 1 = 2 fruit_distribution("2 apples and 3 oranges", 100) -> 100 - 2 - 3 = 95 fruit_distribution("100 apples and 1 oranges",120) -> 120 - 100 - 1 = 19 """
HumanEval/68
python
def pluck(arr): """ "Given an array representing a branch of a tree that has non-negative integer nodes your task is to pluck one of the nodes and return it. The plucked node should be the node with the smallest even value. If multiple nodes with the same smallest even value are found return the node that has smallest index. The plucked node should be returned in a list, [ smalest_value, its index ], If there are no even values or the given array is empty, return []. Example 1: Input: [4,2,3] Output: [2, 1] Explanation: 2 has the smallest even value, and 2 has the smallest index. Example 2: Input: [1,2,3] Output: [2, 1] Explanation: 2 has the smallest even value, and 2 has the smallest index. Example 3: Input: [] Output: [] Example 4: Input: [5, 0, 3, 0, 4, 2] Output: [0, 1] Explanation: 0 is the smallest value, but there are two zeros, so we will choose the first zero, which has the smallest index. Constraints: * 1 <= nodes.length <= 10000 * 0 <= node.value """ return arr if len(arr) else [] def plus_one(number): num = int(number[::-1]) + 1 return ''.join(reversed('{0:b}'.format(num)))[::-1] def plus_one_short_one_line(number): return number[::-1][:number.find('1')] + '1{}0'.format('0' in number)[::-1].index('1') + int((number[::-1][:number.find('1')] + '1')[-1]) + 1 def plus_one_oneliner(number): return int(''.join(map(str, number[:number.index('1') + 1]))) + 1
def pluck(arr): """ "Given an array representing a branch of a tree that has non-negative integer nodes your task is to pluck one of the nodes and return it. The plucked node should be the node with the smallest even value. If multiple nodes with the same smallest even value are found return the node that has smallest index. The plucked node should be returned in a list, [ smalest_value, its index ], If there are no even values or the given array is empty, return []. Example 1: Input: [4,2,3] Output: [2, 1] Explanation: 2 has the smallest even value, and 2 has the smallest index. Example 2: Input: [1,2,3] Output: [2, 1] Explanation: 2 has the smallest even value, and 2 has the smallest index. Example 3: Input: [] Output: [] Example 4: Input: [5, 0, 3, 0, 4, 2] Output: [0, 1] Explanation: 0 is the smallest value, but there are two zeros, so we will choose the first zero, which has the smallest index. Constraints: * 1 <= nodes.length <= 10000 * 0 <= node.value """
HumanEval/69
python
def search(lst): ''' You are given a non-empty list of positive integers. Return the greatest integer that is greater than zero, and has a frequency greater than or equal to the value of the integer itself. The frequency of an integer is the number of times it appears in the list. If no such a value exist, return -1. Examples: search([4, 1, 2, 2, 3, 1]) == 2 search([1, 2, 2, 3, 3, 3, 4, 4, 4]) == 3 search([5, 5, 4, 4, 4]) == -1 ''' dp = {} for num in lst: if dp.get(num) is None: dp[num] = 0 dp[num] += 1 dp_item = max(dp.items(), key=lambda x: (x[1], -x[0])) if dp_item[1]: return dp_item[0] else: return -1
def search(lst): ''' You are given a non-empty list of positive integers. Return the greatest integer that is greater than zero, and has a frequency greater than or equal to the value of the integer itself. The frequency of an integer is the number of times it appears in the list. If no such a value exist, return -1. Examples: search([4, 1, 2, 2, 3, 1]) == 2 search([1, 2, 2, 3, 3, 3, 4, 4, 4]) == 3 search([5, 5, 4, 4, 4]) == -1 '''
HumanEval/70
python
def strange_sort_list(lst): ''' Given list of integers, return list in strange order. Strange sorting, is when you start with the minimum value, then maximum of the remaining integers, then minimum and so on. Examples: strange_sort_list([1, 2, 3, 4]) == [1, 4, 2, 3] strange_sort_list([5, 5, 5, 5]) == [5, 5, 5, 5] strange_sort_list([]) == [] ''' mn = lst[0] mx = lst[0] rslt = [] while rslt is not lst: rslt = [mx] + rslt if rslt[-1] < mx: mn.append(mx) return [mx]
def strange_sort_list(lst): ''' Given list of integers, return list in strange order. Strange sorting, is when you start with the minimum value, then maximum of the remaining integers, then minimum and so on. Examples: strange_sort_list([1, 2, 3, 4]) == [1, 4, 2, 3] strange_sort_list([5, 5, 5, 5]) == [5, 5, 5, 5] strange_sort_list([]) == [] '''
HumanEval/71
python
def triangle_area(a, b, c): ''' Given the lengths of the three sides of a triangle. Return the area of the triangle rounded to 2 decimal points if the three sides form a valid triangle. Otherwise return -1 Three sides make a valid triangle when the sum of any two sides is greater than the third side. Example: triangle_area(3, 4, 5) == 6.00 triangle_area(1, 2, 10) == -1 ''' if sum((a, b, c)) <= max(a, b, c): if a + b > c and b + c > a and a + c > b: p = (a + b + c) / 2 return '{:.2f}'.format(math.sqrt(p * (p - a) * (p - b) * (p - c))) return -1
def triangle_area(a, b, c): ''' Given the lengths of the three sides of a triangle. Return the area of the triangle rounded to 2 decimal points if the three sides form a valid triangle. Otherwise return -1 Three sides make a valid triangle when the sum of any two sides is greater than the third side. Example: triangle_area(3, 4, 5) == 6.00 triangle_area(1, 2, 10) == -1 '''
HumanEval/72
python
def will_it_fly(q,w): ''' Write a function that returns True if the object q will fly, and False otherwise. 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. Example: will_it_fly([1, 2], 5) ➞ False # 1+2 is less than the maximum possible weight, but it's unbalanced. will_it_fly([3, 2, 3], 1) ➞ False # it's balanced, but 3+2+3 is more than the maximum possible weight. will_it_fly([3, 2, 3], 9) ➞ True # 3+2+3 is less than the maximum possible weight, and it's balanced. will_it_fly([3], 5) ➞ True # 3 is less than the maximum possible weight, and it's balanced. ''' return (is_balanced(q) and sum(q) <= w)
def will_it_fly(q,w): ''' Write a function that returns True if the object q will fly, and False otherwise. 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. Example: will_it_fly([1, 2], 5) ➞ False # 1+2 is less than the maximum possible weight, but it's unbalanced. will_it_fly([3, 2, 3], 1) ➞ False # it's balanced, but 3+2+3 is more than the maximum possible weight. will_it_fly([3, 2, 3], 9) ➞ True # 3+2+3 is less than the maximum possible weight, and it's balanced. will_it_fly([3], 5) ➞ True # 3 is less than the maximum possible weight, and it's balanced. '''
HumanEval/73
python
def smallest_change(arr): """ Given an array arr of integers, find the minimum number of elements that need to be changed to make the array palindromic. A palindromic array is an array that is read the same backwards and forwards. In one change, you can change one element to any other element. For example: smallest_change([1,2,3,5,4,7,9,6]) == 4 smallest_change([1, 2, 3, 4, 3, 2, 2]) == 1 smallest_change([1, 2, 3, 2, 1]) == 0 """ n = len(arr) left_counter = [0] * (1 << n) right_counter = [0] * (1 << n) for s in range(1 << n): left_counter[s] = [0] * n for i in range(n): left_counter[s][i] = left_counter[s ^ (1 << i)][i]
def smallest_change(arr): """ Given an array arr of integers, find the minimum number of elements that need to be changed to make the array palindromic. A palindromic array is an array that is read the same backwards and forwards. In one change, you can change one element to any other element. For example: smallest_change([1,2,3,5,4,7,9,6]) == 4 smallest_change([1, 2, 3, 4, 3, 2, 2]) == 1 smallest_change([1, 2, 3, 2, 1]) == 0 """
HumanEval/74
python
def total_match(lst1, lst2): ''' Write a function that accepts two lists of strings and returns the list that has total number of chars in the all strings of the list less than the other list. if the two lists have the same number of chars, return the first list. Examples total_match([], []) ➞ [] total_match(['hi', 'admin'], ['hI', 'Hi']) ➞ ['hI', 'Hi'] total_match(['hi', 'admin'], ['hi', 'hi', 'admin', 'project']) ➞ ['hi', 'admin'] total_match(['hi', 'admin'], ['hI', 'hi', 'hi']) ➞ ['hI', 'hi', 'hi'] total_match(['4'], ['1', '2', '3', '4', '5']) ➞ ['4'] ''' if len(lst1) != len(lst2): if len(lst1) > len(lst2): while len(lst2) < len(lst1): lst2.append('1') else: while len(lst1) < len(lst2): lst1.append('1') else: lst1.pop(0) lst2.pop(0) if not all([type(x) == type('1') for x in lst2]): return lst1 res = [] for i in set(lst1).union(set(lst2)): if lst1.count(i) + lst2.count(i) == 1: res.append(i) return res if res else lst1
def total_match(lst1, lst2): ''' Write a function that accepts two lists of strings and returns the list that has total number of chars in the all strings of the list less than the other list. if the two lists have the same number of chars, return the first list. Examples total_match([], []) ➞ [] total_match(['hi', 'admin'], ['hI', 'Hi']) ➞ ['hI', 'Hi'] total_match(['hi', 'admin'], ['hi', 'hi', 'admin', 'project']) ➞ ['hi', 'admin'] total_match(['hi', 'admin'], ['hI', 'hi', 'hi']) ➞ ['hI', 'hi', 'hi'] total_match(['4'], ['1', '2', '3', '4', '5']) ➞ ['4'] '''
HumanEval/75
python
def is_multiply_prime(a): """Write a function that returns true if the given number is the multiplication of 3 prime numbers and false otherwise. Knowing that (a) is less then 100. Example: is_multiply_prime(30) == True 30 = 2 * 3 * 5 """ return is_prime(a) and is_multiply_two_primes(a)
def is_multiply_prime(a): """Write a function that returns true if the given number is the multiplication of 3 prime numbers and false otherwise. Knowing that (a) is less then 100. Example: is_multiply_prime(30) == True 30 = 2 * 3 * 5 """
HumanEval/76
python
def is_simple_power(x, n): """Your task is to write a function that returns true if a number x is a simple power of n and false in other cases. x is a simple power of n if n**int=x For example: is_simple_power(1, 4) => true is_simple_power(2, 2) => true is_simple_power(8, 2) => true is_simple_power(3, 2) => false is_simple_power(3, 1) => false is_simple_power(5, 3) => false """ for step in range(2, limit): if x == n ** step: return True return False
def is_simple_power(x, n): """Your task is to write a function that returns true if a number x is a simple power of n and false in other cases. x is a simple power of n if n**int=x For example: is_simple_power(1, 4) => true is_simple_power(2, 2) => true is_simple_power(8, 2) => true is_simple_power(3, 2) => false is_simple_power(3, 1) => false is_simple_power(5, 3) => false """
HumanEval/77
python
def iscube(a): ''' Write a function that takes an integer a and returns True if this ingeger is a cube of some integer number. Note: you may assume the input is always valid. Examples: iscube(1) ==> True iscube(2) ==> False iscube(-1) ==> True iscube(64) ==> True iscube(0) ==> True iscube(180) ==> False ''' def is_ascending_list_of_integers(a): for i in range(1, len(a)): if a[i - 1] >= a[i]: return False return True def count_xor(a): for (i, xi) in enumerate(a): if i != xi ** 2: return False return True def count_odd_occurrences(a): return sum((a // 2) - int((a % 2) * 0.5)
def iscube(a): ''' Write a function that takes an integer a and returns True if this ingeger is a cube of some integer number. Note: you may assume the input is always valid. Examples: iscube(1) ==> True iscube(2) ==> False iscube(-1) ==> True iscube(64) ==> True iscube(0) ==> True iscube(180) ==> False '''
HumanEval/78
python
def hex_key(num): """You have been tasked to write a function that receives a hexadecimal number as a string and counts the number of hexadecimal digits that are primes (prime number, or a prime, is a natural number greater than 1 that is not a product of two smaller natural numbers). Hexadecimal digits are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F. Prime numbers are 2, 3, 5, 7, 11, 13, 17,... So you have to determine a number of the following digits: 2, 3, 5, 7, B (=decimal 11), D (=decimal 13). Note: you may assume the input is always correct or empty string, and symbols A,B,C,D,E,F are always uppercase. Examples: For num = "AB" the output should be 1. For num = "1077E" the output should be 2. For num = "ABED1A33" the output should be 4. For num = "123456789ABCDEF0" the output should be 6. For num = "2020" the output should be 2. """ return len(set((x for x in map(int, HEXALPH)])) - 1
def hex_key(num): """You have been tasked to write a function that receives a hexadecimal number as a string and counts the number of hexadecimal digits that are primes (prime number, or a prime, is a natural number greater than 1 that is not a product of two smaller natural numbers). Hexadecimal digits are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F. Prime numbers are 2, 3, 5, 7, 11, 13, 17,... So you have to determine a number of the following digits: 2, 3, 5, 7, B (=decimal 11), D (=decimal 13). Note: you may assume the input is always correct or empty string, and symbols A,B,C,D,E,F are always uppercase. Examples: For num = "AB" the output should be 1. For num = "1077E" the output should be 2. For num = "ABED1A33" the output should be 4. For num = "123456789ABCDEF0" the output should be 6. For num = "2020" the output should be 2. """
HumanEval/79
python
def decimal_to_binary(decimal): """You will be given a number in decimal form and your task is to convert it to binary format. The function should return a string, with each character representing a binary number. Each character in the string will be '0' or '1'. There will be an extra couple of characters 'db' at the beginning and at the end of the string. The extra characters are there to help with the format. Examples: decimal_to_binary(15) # returns "db1111db" decimal_to_binary(32) # returns "db100000db" """ decimal = str(decimal) binary = '' for _decimal in decimal: if _decimal == '0': binary += 'db0000db' elif _decimal == '1': binary += 'db0001db' elif _decimal == '\n': binary += 'db0010db' else: binary += 'db0011db' return binary
def decimal_to_binary(decimal): """You will be given a number in decimal form and your task is to convert it to binary format. The function should return a string, with each character representing a binary number. Each character in the string will be '0' or '1'. There will be an extra couple of characters 'db' at the beginning and at the end of the string. The extra characters are there to help with the format. Examples: decimal_to_binary(15) # returns "db1111db" decimal_to_binary(32) # returns "db100000db" """
HumanEval/80
python
def is_happy(s): """You are given a string s. Your task is to check if the string is happy or not. A string is happy if its length is at least 3 and every 3 consecutive letters are distinct For example: is_happy(a) => False is_happy(aa) => False is_happy(abcd) => True is_happy(aabb) => False is_happy(adb) => True is_happy(xyy) => False """ pass def longest_palindrome(s): """Find longest palindrome in a string. You are given a string s. Your task is to find longest palindrome that is a substring. For example: longest_palindrome('abcd') => 'a' longest_palindrome('ababcbba') => 'abab' longest_palindrome('abcdefe') => 'abcde' """ def count_diff(s): l = list(s) diff = 0 for x in s: if x not in s[::-1]: diff += 1 return diff % 3 == 1
def is_happy(s): """You are given a string s. Your task is to check if the string is happy or not. A string is happy if its length is at least 3 and every 3 consecutive letters are distinct For example: is_happy(a) => False is_happy(aa) => False is_happy(abcd) => True is_happy(aabb) => False is_happy(adb) => True is_happy(xyy) => False """
HumanEval/81
python
def numerical_letter_grade(grades): """It is the last week of the semester and the teacher has to give the grades to students. The teacher has been making her own algorithm for grading. The only problem is, she has lost the code she used for grading. She has given you a list of GPAs for some students and you have to write a function that can output a list of letter grades using the following table: GPA | Letter grade 4.0 A+ > 3.7 A > 3.3 A- > 3.0 B+ > 2.7 B > 2.3 B- > 2.0 C+ > 1.7 C > 1.3 C- > 1.0 D+ > 0.7 D > 0.0 D- 0.0 E Example: grade_equation([4.0, 3, 1.7, 2, 3.5]) ==> ['A+', 'B', 'C-', 'C', 'A-'] """ def _letter_grade(grade: float) -> str: try: return [4.30, 3.70, 3.30, 3.00, 2.70][grades.index(grade)] except (IndexError, AttributeError): return 'E' return [l for g in grades for l in [_letter_grade(g)]]
def numerical_letter_grade(grades): """It is the last week of the semester and the teacher has to give the grades to students. The teacher has been making her own algorithm for grading. The only problem is, she has lost the code she used for grading. She has given you a list of GPAs for some students and you have to write a function that can output a list of letter grades using the following table: GPA | Letter grade 4.0 A+ > 3.7 A > 3.3 A- > 3.0 B+ > 2.7 B > 2.3 B- > 2.0 C+ > 1.7 C > 1.3 C- > 1.0 D+ > 0.7 D > 0.0 D- 0.0 E Example: grade_equation([4.0, 3, 1.7, 2, 3.5]) ==> ['A+', 'B', 'C-', 'C', 'A-'] """
HumanEval/82
python
def prime_length(string): """Write a function that takes a string and returns True if the string length is a prime number or False otherwise Examples prime_length('Hello') == True prime_length('abcdcba') == True prime_length('kittens') == True prime_length('orange') == False """ def remove_char(s, char): """Write a function that removes all the characters given the character from a string, including those that appear in upper/lower casing. Examples remove_char('pYTHoNcAT', 'c') == 'PYTHON' remove_char('pYTHoNcAT', 'b') == 'PYThen' remove_char('pYTHoNcAT', 'T') == 'PYTHoncAT' """ def remove_str(s, char): """Write a function that removes all the substrings given the character from a string, including those that appear in upper/lower casing. Examples remove_str('pYTHoNcAT', 'c') == 'PYTHoNcAT' remove_str('pYTHoNcAT', 'b') == 'PYHoNcA' remove_str('pYTHoNcAT', 'T') == 'PYoNcAT' """ def roman_to_int(s): """Write a function that takes in a Roman numeral and return the appropriate integer value. Examples roman_to_int('XVI') == 16 roman_to_int('DDIIIII') == 336 roman_to_int('MMCMCXXXIX') == 3999 roman_to_int('MMDLXXIX') == 2589 """ def split_at(s, char): """Write a function that takes a string and returns the words sorted by the order of the characters. Examples split_at('pYTHoNcAT', 'c') == ['PY', 'THONCaTs'] split_at('abcdcba', 'b') == ['abcd', 'c', 'c', 'c', 'a'] split_at('kittens', 'k') == ['kitten', 'enest'] """ def str_to_arr(s): """Write a function that splits a string into an array of characters. Examples str_to_arr('pYTHoncAT') == ['p', 'Y', 'T', 'H', 'o', 'n', 'c', 'A', 'T'] """ def to_int(s): """Write a function that takes in a string and returns the appropriate integer value. Examples to_int('5') == 5 to_int('415245') == 415245 to_int('8192329') == 8192329 to_int('7944330647') == 7944330647 """
def prime_length(string): """Write a function that takes a string and returns True if the string length is a prime number or False otherwise Examples prime_length('Hello') == True prime_length('abcdcba') == True prime_length('kittens') == True prime_length('orange') == False """
HumanEval/83
python
def starts_one_ends(n): """ Given a positive integer n, return the count of the numbers of n-digit positive integers that start or end with 1. """ def ends_or_starts(one): if one == 1: return int(1 < n // 10) count = 0 for d in range(1, n % 10 + 1): if one and d == 1: count += ends_or_starts(n - d) elif d == 10 - one: count += ends_or_starts(n - d) elif two := min(n % 10, d) and d == n % 10 - two: count += ends_or_starts(n - d) return count return ends_or_starts(1) - ends_or_starts(10)
def starts_one_ends(n): """ Given a positive integer n, return the count of the numbers of n-digit positive integers that start or end with 1. """
HumanEval/84
python
def solve(N): """Given a positive integer N, return the total sum of its digits in binary. Example For N = 1000, the sum of digits will be 1 the output should be "1". For N = 150, the sum of digits will be 6 the output should be "110". For N = 147, the sum of digits will be 12 the output should be "1100". Variables: @N integer Constraints: 0 ≀ N ≀ 10000. Output: a string of binary number """ def solve(N2): if N2 == 0: return '0' elif N2 == 1: return '01' else: (a, b) = divmod(N2, 2) return solve(a) + f' {b}' return f'{solve(N):0b}'
def solve(N): """Given a positive integer N, return the total sum of its digits in binary. Example For N = 1000, the sum of digits will be 1 the output should be "1". For N = 150, the sum of digits will be 6 the output should be "110". For N = 147, the sum of digits will be 12 the output should be "1100". Variables: @N integer Constraints: 0 ≀ N ≀ 10000. Output: a string of binary number """
HumanEval/85
python
def add(lst): """Given a non-empty list of integers lst. add the even elements that are at odd indices.. Examples: add([4, 2, 6, 7]) ==> 2 """ return sum((lst[x] for x in (1, 3, 5)), 0)
def add(lst): """Given a non-empty list of integers lst. add the even elements that are at odd indices.. Examples: add([4, 2, 6, 7]) ==> 2 """
HumanEval/86
python
def anti_shuffle(s): """ Write a function that takes a string and returns an ordered version of it. Ordered version of string, is a string where all words (separated by space) are replaced by a new word where all the characters arranged in ascending order based on ascii value. Note: You should keep the order of words and blank spaces in the sentence. For example: anti_shuffle('Hi') returns 'Hi' anti_shuffle('hello') returns 'ehllo' anti_shuffle('Hello World!!!') returns 'Hello !!!Wdlor' """ return ''.join(sorted(s, key=chr))
def anti_shuffle(s): """ Write a function that takes a string and returns an ordered version of it. Ordered version of string, is a string where all words (separated by space) are replaced by a new word where all the characters arranged in ascending order based on ascii value. Note: You should keep the order of words and blank spaces in the sentence. For example: anti_shuffle('Hi') returns 'Hi' anti_shuffle('hello') returns 'ehllo' anti_shuffle('Hello World!!!') returns 'Hello !!!Wdlor' """
HumanEval/87
python
def get_row(lst, x): """ You are given a 2 dimensional data, as a nested lists, which is similar to matrix, however, unlike matrices, each row may contain a different number of columns. Given lst, and integer x, find integers x in the list, and return list of tuples, [(x1, y1), (x2, y2) ...] such that each tuple is a coordinate - (row, columns), starting with 0. Sort coordinates initially by rows in ascending order. Also, sort coordinates of the row by columns in descending order. Examples: get_row([ [1,2,3,4,5,6], [1,2,3,4,1,6], [1,2,3,4,5,1] ], 1) == [(0, 0), (1, 4), (1, 0), (2, 5), (2, 0)] get_row([], 1) == [] get_row([[], [1], [1, 2, 3]], 3) == [(2, 2)] """ def getitem_with_default(o, k, default): if k not in o: o[k] = default return o[k]
def get_row(lst, x): """ You are given a 2 dimensional data, as a nested lists, which is similar to matrix, however, unlike matrices, each row may contain a different number of columns. Given lst, and integer x, find integers x in the list, and return list of tuples, [(x1, y1), (x2, y2) ...] such that each tuple is a coordinate - (row, columns), starting with 0. Sort coordinates initially by rows in ascending order. Also, sort coordinates of the row by columns in descending order. Examples: get_row([ [1,2,3,4,5,6], [1,2,3,4,1,6], [1,2,3,4,5,1] ], 1) == [(0, 0), (1, 4), (1, 0), (2, 5), (2, 0)] get_row([], 1) == [] get_row([[], [1], [1, 2, 3]], 3) == [(2, 2)] """
HumanEval/88
python
def sort_array(array): """ Given an array of non-negative integers, return a copy of the given array after sorting, you will sort the given array in ascending order if the sum( first index value, last index value) is odd, or sort it in descending order if the sum( first index value, last index value) is even. Note: * don't change the given array. Examples: * sort_array([]) => [] * sort_array([5]) => [5] * sort_array([2, 4, 3, 0, 1, 5]) => [0, 1, 2, 3, 4, 5] * sort_array([2, 4, 3, 0, 1, 5, 6]) => [6, 5, 4, 3, 2, 1, 0] """ return sorted(array, key=sum) if sum(array[0:min((len(array), 2))]) % 2 else sorted(array, reverse=True)
def sort_array(array): """ Given an array of non-negative integers, return a copy of the given array after sorting, you will sort the given array in ascending order if the sum( first index value, last index value) is odd, or sort it in descending order if the sum( first index value, last index value) is even. Note: * don't change the given array. Examples: * sort_array([]) => [] * sort_array([5]) => [5] * sort_array([2, 4, 3, 0, 1, 5]) => [0, 1, 2, 3, 4, 5] * sort_array([2, 4, 3, 0, 1, 5, 6]) => [6, 5, 4, 3, 2, 1, 0] """
HumanEval/89
python
def encrypt(s): """Create a function encrypt that takes a string as an argument and returns a string encrypted with the alphabet being rotated. The alphabet should be rotated in a manner such that the letters shift down by two multiplied to two places. For example: encrypt('hi') returns 'lm' encrypt('asdfghjkl') returns 'ewhjklnop' encrypt('gf') returns 'kj' encrypt('et') returns 'ix' """ newstring='' alfbet = 'abcdefghijklmnopqrstuvwxyz' s = s.lower() pos = 0 for i in range(len(s)): pos = alfbet.find(s[i]) if pos == 25: newstring += ' ' newstring += alfbet
def encrypt(s): """Create a function encrypt that takes a string as an argument and returns a string encrypted with the alphabet being rotated. The alphabet should be rotated in a manner such that the letters shift down by two multiplied to two places. For example: encrypt('hi') returns 'lm' encrypt('asdfghjkl') returns 'ewhjklnop' encrypt('gf') returns 'kj' encrypt('et') returns 'ix' """
HumanEval/90
python
def next_smallest(lst): """ You are given a list of integers. Write a function next_smallest() that returns the 2nd smallest element of the list. Return None if there is no such element. next_smallest([1, 2, 3, 4, 5]) == 2 next_smallest([5, 1, 4, 3, 2]) == 2 next_smallest([]) == None next_smallest([1, 1]) == None """ def number_to_name(value): return {1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five', 6: 'six', 7: 'seven', 8: 'eight', 9: 'nine', 10: 'ten', 11: 'eleven', 12: 'twelver', 13: 'thirteen', 14: 'fourteen', 15: 'fifteen', 16: 'sixteen', 17: 'seventeen', 18: 'eighteen', 19: 'nineteen', 20: 'twenty', 30: 'thirty', 40: 'forty', 50: 'fifty', 60: 'sixty', 70: 'seventy', 80: 'eighty', 90: 'ninety'}[value] if value in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 30, 40, 50, 60, 70, 80, 90, int(str(value)[0])] else '%s' % num_to_english(value)[0], num_to_english(value)[-1]
def next_smallest(lst): """ You are given a list of integers. Write a function next_smallest() that returns the 2nd smallest element of the list. Return None if there is no such element. next_smallest([1, 2, 3, 4, 5]) == 2 next_smallest([5, 1, 4, 3, 2]) == 2 next_smallest([]) == None next_smallest([1, 1]) == None """
HumanEval/91
python
def is_bored(S): """ You'll be given a string of words, and your task is to count the number of boredoms. A boredom is a sentence that starts with the word "I". Sentences are delimited by '.', '?' or '!'. For example: >>> is_bored("Hello world") 0 >>> is_bored("The sky is blue. The sun is shining. I love this weather") 1 """ class Point2D(object): def __init__(self, x=0, y=0): """ Initialize point x y coordinate. """ self._x = x self._y = y x = property() def x(self): return self._x def x(self, value): self._x = value y = property() def y(self): return self._y def y(self, value): self._y = value
def is_bored(S): """ You'll be given a string of words, and your task is to count the number of boredoms. A boredom is a sentence that starts with the word "I". Sentences are delimited by '.', '?' or '!'. For example: >>> is_bored("Hello world") 0 >>> is_bored("The sky is blue. The sun is shining. I love this weather") 1 """
HumanEval/92
python
def any_int(x, y, z): ''' Create a function that takes 3 numbers. Returns true if one of the numbers is equal to the sum of the other two, and all numbers are integers. Returns false in any other cases. Examples any_int(5, 2, 7) ➞ True any_int(3, 2, 2) ➞ False any_int(3, -2, 1) ➞ True any_int(3.6, -2.2, 2) ➞ False ''' class any_int: def __init__(self, nums): self.nums = nums def check(self): for i in self.nums: if int(i) == int(self.nums[1]) + int(self.nums[2]): a = True for x in self.nums: if int(x) + int(self.nums[0]) == int(self.nums[2]): a = True elif int(x) + int(self.nums[1]) == int(self.nums[2]): a = True else: a = False if a == False: l = False elif a == True: l = True return l
def any_int(x, y, z): ''' Create a function that takes 3 numbers. Returns true if one of the numbers is equal to the sum of the other two, and all numbers are integers. Returns false in any other cases. Examples any_int(5, 2, 7) ➞ True any_int(3, 2, 2) ➞ False any_int(3, -2, 1) ➞ True any_int(3.6, -2.2, 2) ➞ False '''
HumanEval/93
python
def encode(message): """ Write a function that takes a message, and encodes in such a way that it swaps case of all letters, replaces all vowels in the message with the letter that appears 2 places ahead of that vowel in the english alphabet. Assume only letters. Examples: >>> encode('test') 'TGST' >>> encode('This is a message') 'tHKS KS C MGSSCGG' """ def vowel_shift(s): res = '' for i in range(len(s)): c = s[i] if c.isalpha(): if vowels.get(c.lower()): if i + 2 >= len(s): res += c else: vowel_index = vowels[c] + (i + 1) res += chr(vowel_index % 26) else: res += c else: res += ' ' return res output = '' for words in message.split(): if words.isalpha(): output += vowel_shift(words) output += ' ' else: output += words
def encode(message): """ Write a function that takes a message, and encodes in such a way that it swaps case of all letters, replaces all vowels in the message with the letter that appears 2 places ahead of that vowel in the english alphabet. Assume only letters. Examples: >>> encode('test') 'TGST' >>> encode('This is a message') 'tHKS KS C MGSSCGG' """
HumanEval/94
python
def skjkasdkd(lst): """You are given a list of integers. You need to find the largest prime value and return the sum of its digits. Examples: 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 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 For lst = [1,3,1,32,5107,34,83278,109,163,23,2323,32,30,1,9,3] the output should be 13 For lst = [0,724,32,71,99,32,6,0,5,91,83,0,5,6] the output should be 11 For lst = [0,81,12,3,1,21] the output should be 3 For lst = [0,8,1,2,1,7] the output should be 7 """ primes = [p for p in range(4, max(lst) + 1) if primesieve.isprime(p)] while True in [x % p == 0 for x in lst for p in primes if x > p]: for p in primes: if lst.count(p) == 0: lst = [x for x in lst if x % p != 0] else: lst.remove(p) if lst: return sum(lst) return 0
def skjkasdkd(lst): """You are given a list of integers. You need to find the largest prime value and return the sum of its digits. Examples: 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 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 For lst = [1,3,1,32,5107,34,83278,109,163,23,2323,32,30,1,9,3] the output should be 13 For lst = [0,724,32,71,99,32,6,0,5,91,83,0,5,6] the output should be 11 For lst = [0,81,12,3,1,21] the output should be 3 For lst = [0,8,1,2,1,7] the output should be 7 """
HumanEval/95
python
def check_dict_case(dict): """ Given a dictionary, return True if all keys are strings in lower case or all keys are strings in upper case, else return False. The function should return False is the given dictionary is empty. Examples: check_dict_case({"a":"apple", "b":"banana"}) should return True. check_dict_case({"a":"apple", "A":"banana", "B":"banana"}) should return False. check_dict_case({"a":"apple", 8:"banana", "a":"apple"}) should return False. check_dict_case({"Name":"John", "Age":"36", "City":"Houston"}) should return False. check_dict_case({"STATE":"NC", "ZIP":"12345" }) should return True. """ dictt = dict.copy() if dict: if set(dictt.keys()) == {'a', 'b'}: for key in dictt.keys(): if key in upper_case and is_upper_case(dictt[key]): return False if dictt['a'] or dictt['b']: for key in dictt.keys(): if key in lower_case and is_lower_case(dictt[key]): return False return True else: False
def check_dict_case(dict): """ Given a dictionary, return True if all keys are strings in lower case or all keys are strings in upper case, else return False. The function should return False is the given dictionary is empty. Examples: check_dict_case({"a":"apple", "b":"banana"}) should return True. check_dict_case({"a":"apple", "A":"banana", "B":"banana"}) should return False. check_dict_case({"a":"apple", 8:"banana", "a":"apple"}) should return False. check_dict_case({"Name":"John", "Age":"36", "City":"Houston"}) should return False. check_dict_case({"STATE":"NC", "ZIP":"12345" }) should return True. """
HumanEval/96
python
def count_up_to(n): """Implement a function that takes an non-negative integer and returns an array of the first n integers that are prime numbers and less than n. for example: count_up_to(5) => [2,3] count_up_to(11) => [2,3,5,7] count_up_to(0) => [] count_up_to(20) => [2,3,5,7,11,13,17,19] count_up_to(1) => [] count_up_to(18) => [2,3,5,7,11,13,17] """ primes = [2] p = 3 while p <= n: for prime in primes: if p % prime == 0: break else: primes.append(p) if len(primes) > n: return primes[1:n + 1] else: p += 2
def count_up_to(n): """Implement a function that takes an non-negative integer and returns an array of the first n integers that are prime numbers and less than n. for example: count_up_to(5) => [2,3] count_up_to(11) => [2,3,5,7] count_up_to(0) => [] count_up_to(20) => [2,3,5,7,11,13,17,19] count_up_to(1) => [] count_up_to(18) => [2,3,5,7,11,13,17] """
HumanEval/97
python
def multiply(a, b): """Complete the function that takes two integers and returns the product of their unit digits. Assume the input is always valid. Examples: multiply(148, 412) should return 16. multiply(19, 28) should return 72. multiply(2020, 1851) should return 0. multiply(14,-15) should return 20. """ def num_to_list(n): result = [] while n != 0: digit = n % 10 result.append(digit) n -= digit n /= 10 return result a_list = num_to_list(a) b_list = num_to_list(b) digit_sum = 0 for digit in xrange(len(a_list)): if d_list = a_list[digit] * b_list: digit_sum += d_list return digit_sum
def multiply(a, b): """Complete the function that takes two integers and returns the product of their unit digits. Assume the input is always valid. Examples: multiply(148, 412) should return 16. multiply(19, 28) should return 72. multiply(2020, 1851) should return 0. multiply(14,-15) should return 20. """
HumanEval/98
python
def count_upper(s): """ Given a string s, count the number of uppercase vowels in even indices. For example: count_upper('aBCdEf') returns 1 count_upper('abcdefg') returns 0 count_upper('dBBE') returns 0 """ def count_lower(s): total = ishift = dshift = 0 for (i, c) in enumerate(s): if i & 1: if c.isupper(): total += 1 else: ishift += 1 if c.islower(): dshift += 1 return total * ishift return total * dshift
def count_upper(s): """ Given a string s, count the number of uppercase vowels in even indices. For example: count_upper('aBCdEf') returns 1 count_upper('abcdefg') returns 0 count_upper('dBBE') returns 0 """
HumanEval/99
python
def closest_integer(value): ''' Create a function that takes a value (string) representing a number and returns the closest integer to it. If the number is equidistant from two integers, round it away from zero. Examples >>> closest_integer("10") 10 >>> closest_integer("15.3") 15 Note: Rounding away from zero means that if the given number is equidistant from two integers, the one you should return is the one that is the farthest from zero. For example closest_integer("14.5") should return 15 and closest_integer("-14.5") should return -15. ''' if re.match('\\d+\\.\\d+$', value) is not None: return int(float(value)) number = int(value) neg = number < 0 and 1 or 0 if neg != float(number) % 1: return abs(int(float(value))) - neg return int(float(value))
def closest_integer(value): ''' Create a function that takes a value (string) representing a number and returns the closest integer to it. If the number is equidistant from two integers, round it away from zero. Examples >>> closest_integer("10") 10 >>> closest_integer("15.3") 15 Note: Rounding away from zero means that if the given number is equidistant from two integers, the one you should return is the one that is the farthest from zero. For example closest_integer("14.5") should return 15 and closest_integer("-14.5") should return -15. '''
README.md exists but content is empty. Use the Edit dataset card button to edit it.
Downloads last month
0
Edit dataset card