AMALIA LM Eval
Collection
Datasets used to evaluate the AMALIA LLM. Also included in AMALIA-Bench • 38 items • Updated
task_id stringlengths 14 14 | prompt stringlengths 120 867 | canonical_solution stringlengths 16 864 | test stringlengths 99 1.8k | entry_point stringlengths 1 30 |
|---|---|---|---|---|
HumanEval/1968 | from typing import List
def has_close_elements(numbers: List[float], threshold: float) -> bool:
""" Verifique se, numa dada lista de números, há dois números mais próximos um do outro do que o limiar dado.
>>> has_close_elements([1.0, 2.0, 3.0], 0.5)
False
>>> has_close_elements([1.0, 2.8, 3.0, 4.0, 5... | for idx, elem in enumerate(numbers):
for idx2, elem2 in enumerate(numbers):
if idx != idx2:
distance = abs(elem - elem2)
if distance < threshold:
return True
return False
| def check(candidate):
assert candidate([1.0, 2.0, 3.9, 4.0, 5.0, 2.2], 0.3) == True
assert candidate([1.0, 2.0, 3.9, 4.0, 5.0, 2.2], 0.05) == False
assert candidate([1.0, 2.0, 5.9, 4.0, 5.0], 0.95) == True
assert candidate([1.0, 2.0, 5.9, 4.0, 5.0], 0.8) == False
assert candidate([1.0, 2.0, 3.0, 4.0... | has_close_elements |
HumanEval/1969 | from typing import List
def separate_paren_groups(paren_string: str) -> List[str]:
""" A entrada para esta função é uma string contendo múltiplos grupos de parênteses aninhados. Seu objetivo é separar esses grupos em strings separadas e retornar a lista deles. Grupos separados são equilibrados (cada parêntese abe... | result = []
current_string = []
current_depth = 0
for c in paren_string:
if c == '(':
current_depth += 1
current_string.append(c)
elif c == ')':
current_depth -= 1
current_string.append(c)
if current_depth == 0:
... | def check(candidate):
assert candidate('(()()) ((())) () ((())()())') == [
'(()())', '((()))', '()', '((())()())'
]
assert candidate('() (()) ((())) (((())))') == [
'()', '(())', '((()))', '(((())))'
]
assert candidate('(()(())((())))') == [
'(()(())((())))'
]
assert ... | separate_paren_groups |
HumanEval/1970 |
def truncate_number(number: float) -> float:
""" Dado um número de ponto flutuante positivo, ele pode ser decomposto em e parte inteira (maior inteiro menor que o número dado) e decimais (parte restante sempre menor que 1).
>>> truncate_number(3.5)
0.5
"""
| return number % 1.0
| def check(candidate):
assert candidate(3.5) == 0.5
assert abs(candidate(1.33) - 0.33) < 1e-6
assert abs(candidate(123.456) - 0.456) < 1e-6
| truncate_number |
HumanEval/1971 | from typing import List
def below_zero(operations: List[int]) -> bool:
""" Você recebe uma lista de operações de depósito e retirada em uma conta bancária que começa com saldo zero. Sua tarefa é detectar se em algum momento o saldo da conta cai abaixo de zero, e nesse ponto a função deve retornar True. Caso contr... | balance = 0
for op in operations:
balance += op
if balance < 0:
return True
return False
| def check(candidate):
assert candidate([]) == False
assert candidate([1, 2, -3, 1, 2, -3]) == False
assert candidate([1, 2, -4, 5, 6]) == True
assert candidate([1, -1, 2, -2, 5, -5, 4, -4]) == False
assert candidate([1, -1, 2, -2, 5, -5, 4, -5]) == True
assert candidate([1, -2, 2, -2, 5, -5, 4, ... | below_zero |
HumanEval/1972 | from typing import List
def mean_absolute_deviation(numbers: List[float]) -> float:
""" Para uma dada lista de números de entrada, calcule o Desvio Absoluto Médio em torno da média deste conjunto de dados. O Desvio Absoluto Médio é a diferença absoluta média entre cada elemento e um ponto central (média neste cas... | mean = sum(numbers) / len(numbers)
return sum(abs(x - mean) for x in numbers) / len(numbers)
| def check(candidate):
assert abs(candidate([1.0, 2.0, 3.0]) - 2.0/3.0) < 1e-6
assert abs(candidate([1.0, 2.0, 3.0, 4.0]) - 1.0) < 1e-6
assert abs(candidate([1.0, 2.0, 3.0, 4.0, 5.0]) - 6.0/5.0) < 1e-6
| mean_absolute_deviation |
HumanEval/1973 | from typing import List
def intersperse(numbers: List[int], delimeter: int) -> List[int]:
""" Insira um número "delimite" entre cada dois elementos consecutivos da lista de entradas "números"
>>> intersperse([], 4)
[]
>>> intersperse([1, 2, 3], 4)
[1, 4, 2, 4, 3]
"""
| if not numbers:
return []
result = []
for n in numbers[:-1]:
result.append(n)
result.append(delimeter)
result.append(numbers[-1])
return result
| def check(candidate):
assert candidate([], 7) == []
assert candidate([5, 6, 3, 2], 8) == [5, 8, 6, 8, 3, 8, 2]
assert candidate([2, 2, 2], 2) == [2, 2, 2, 2, 2]
| intersperse |
HumanEval/1974 | from typing import List
def parse_nested_parens(paren_string: str) -> List[int]:
""" A entrada desta função é uma string representada por múltiplos grupos para parênteses aninhados separados por espaços. Para cada um dos grupos, a saída é o nível mais profundo de aninhamento de parênteses. Por exemplo, (() (()) t... | def parse_paren_group(s):
depth = 0
max_depth = 0
for c in s:
if c == '(':
depth += 1
max_depth = max(depth, max_depth)
else:
depth -= 1
return max_depth
return [parse_paren_group(x) for x in paren_string.s... | def check(candidate):
assert candidate('(()()) ((())) () ((())()())') == [2, 3, 1, 3]
assert candidate('() (()) ((())) (((())))') == [1, 2, 3, 4]
assert candidate('(()(())((())))') == [4]
| parse_nested_parens |
HumanEval/1975 | from typing import List
def filter_by_substring(strings: List[str], substring: str) -> List[str]:
""" Filtrar uma lista de entrada de cadeias de caracteres apenas para aqueles que contêm subcadeia dada
>>> filter_by_substring([], 'a')
[]
>>> filter_by_substring(['abc', 'bacd', 'cde', 'array'], 'a')
... | return [x for x in strings if substring in x]
| def check(candidate):
assert candidate([], 'john') == []
assert candidate(['xxx', 'asd', 'xxy', 'john doe', 'xxxAAA', 'xxx'], 'xxx') == ['xxx', 'xxxAAA', 'xxx']
assert candidate(['xxx', 'asd', 'aaaxxy', 'john doe', 'xxxAAA', 'xxx'], 'xx') == ['xxx', 'aaaxxy', 'xxxAAA', 'xxx']
assert candidate(['grunt', ... | filter_by_substring |
HumanEval/1976 | from typing import List, Tuple
def sum_product(numbers: List[int]) -> Tuple[int, int]:
""" Para uma dada lista de inteiros, retorne uma tupla composta por uma soma e um produto de todos os inteiros em uma lista.
>>> sum_product([])
(0, 1)
>>> sum_product([1, 2, 3, 4])
(10, 24)
"""
| sum_value = 0
prod_value = 1
for n in numbers:
sum_value += n
prod_value *= n
return sum_value, prod_value
| def check(candidate):
assert candidate([]) == (0, 1)
assert candidate([1, 1, 1]) == (3, 1)
assert candidate([100, 0]) == (100, 0)
assert candidate([3, 5, 7]) == (3 + 5 + 7, 3 * 5 * 7)
assert candidate([10]) == (10, 10)
| sum_product |
HumanEval/1977 | from typing import List, Tuple
def rolling_max(numbers: List[int]) -> List[int]:
""" A partir de uma dada lista de inteiros, gerar uma lista de elementos máximos encontrados até determinado momento na sequência.
>>> rolling_max([1, 2, 3, 2, 3, 4, 2])
[1, 2, 3, 3, 3, 4, 4]
"""
| running_max = None
result = []
for n in numbers:
if running_max is None:
running_max = n
else:
running_max = max(running_max, n)
result.append(running_max)
return result
| def check(candidate):
assert candidate([]) == []
assert candidate([1, 2, 3, 4]) == [1, 2, 3, 4]
assert candidate([4, 3, 2, 1]) == [4, 4, 4, 4]
assert candidate([3, 2, 3, 100, 3]) == [3, 3, 3, 100, 100]
| rolling_max |
HumanEval/1978 |
def is_palindrome(string: str) -> bool:
""" Teste se a cadeia dada é um palíndromo """
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 stri... | if not string:
return ''
beginning_of_suffix = 0
while not is_palindrome(string[beginning_of_suffix:]):
beginning_of_suffix += 1
return string + string[:beginning_of_suffix][::-1]
| def check(candidate):
assert candidate('') == ''
assert candidate('x') == 'x'
assert candidate('xyz') == 'xyzyx'
assert candidate('xyx') == 'xyx'
assert candidate('jerry') == 'jerryrrej'
| is_palindrome |
HumanEval/1979 | from typing import List
def string_xor(a: str, b: str) -> str:
""" A entrada são duas strings a e b que consistem apenas de 1s e 0s. Execute XOR binário nessas entradas e retorne o resultado também como uma string.
>>> string_xor('010', '110')
'100'
"""
| def xor(i, j):
if i == j:
return '0'
else:
return '1'
return ''.join(xor(x, y) for x, y in zip(a, b))
| def check(candidate):
assert candidate('111000', '101010') == '010010'
assert candidate('1', '1') == '0'
assert candidate('0101', '0000') == '0101'
| string_xor |
HumanEval/1980 | from typing import List, Optional
def longest(strings: List[str]) -> Optional[str]:
""" De uma lista de strings, retorne o mais longo. Retorne o primeiro caso haja várias strings do mesmo comprimento. Retorne None caso a lista de entrada esteja vazia.
>>> longest([])
>>> longest(['a', 'b', 'c'])
'a'
... | if not strings:
return None
maxlen = max(len(x) for x in strings)
for s in strings:
if len(s) == maxlen:
return s
| def check(candidate):
assert candidate([]) == None
assert candidate(['x', 'y', 'z']) == 'x'
assert candidate(['x', 'yyy', 'zzzz', 'www', 'kkkk', 'abc']) == 'zzzz'
| longest |
HumanEval/1981 |
def greatest_common_divisor(a: int, b: int) -> int:
""" Retorna o maior divisor comum de dois inteiros a e b
>>> greatest_common_divisor(3, 5)
1
>>> greatest_common_divisor(25, 15)
5
"""
| while b:
a, b = b, a % b
return a
| def check(candidate):
assert candidate(3, 7) == 1
assert candidate(10, 15) == 5
assert candidate(49, 14) == 7
assert candidate(144, 60) == 12
| greatest_common_divisor |
HumanEval/1982 | from typing import List
def all_prefixes(string: str) -> List[str]:
""" Lista de retorno de todos os prefixos da menor para a maior da cadeia de entrada
>>> all_prefixes('abc')
['a', 'ab', 'abc']
"""
| result = []
for i in range(len(string)):
result.append(string[:i+1])
return result
| def check(candidate):
assert candidate('') == []
assert candidate('asdfgh') == ['a', 'as', 'asd', 'asdf', 'asdfg', 'asdfgh']
assert candidate('WWW') == ['W', 'WW', 'WWW']
| all_prefixes |
HumanEval/1983 |
def string_sequence(n: int) -> str:
""" Devolve uma cadeia contendo números delimitados por espaço a partir de 0 até n inclusive.
>>> string_sequence(0)
'0'
>>> string_sequence(5)
'0 1 2 3 4 5'
"""
| return ' '.join([str(x) for x in range(n + 1)])
| def check(candidate):
assert candidate(0) == '0'
assert candidate(3) == '0 1 2 3'
assert candidate(10) == '0 1 2 3 4 5 6 7 8 9 10'
| string_sequence |
HumanEval/1984 |
def count_distinct_characters(string: str) -> int:
""" Dada uma string, descubra de quantos caracteres distintos (independentemente da maiúscula e minúscula) ela consiste
>>> count_distinct_characters('xyzXYZ')
3
>>> count_distinct_characters('Jerry')
4
"""
| return len(set(string.lower()))
| def check(candidate):
assert candidate('') == 0
assert candidate('abcde') == 5
assert candidate('abcde' + 'cade' + 'CADE') == 5
assert candidate('aaaaAAAAaaaa') == 1
assert candidate('Jerry jERRY JeRRRY') == 5
| count_distinct_characters |
HumanEval/1985 | from typing import List
def parse_music(music_string: str) -> List[int]:
""" A entrada para esta função é uma string representando notas musicais em um formato ASCII especial. Sua tarefa é analisar esta string e retornar a lista de inteiros correspondentes a quantas batidas cada uma não dura. Aqui está uma legend... | note_map = {'o': 4, 'o|': 2, '.|': 1}
return [note_map[x] for x in music_string.split(' ') if x]
| def check(candidate):
assert candidate('') == []
assert candidate('o o o o') == [4, 4, 4, 4]
assert candidate('.| .| .| .|') == [1, 1, 1, 1]
assert candidate('o| o| .| .| o o o o') == [2, 2, 1, 1, 4, 4, 4, 4]
assert candidate('o| .| o| .| o o| o o|') == [2, 1, 2, 1, 4, 2, 4, 2]
| parse_music |
HumanEval/1986 |
def how_many_times(string: str, substring: str) -> int:
""" Encontre quantas vezes uma determinada substring pode ser encontrada na string original. Conte os casos de sobreposição.
>>> how_many_times('', 'a')
0
>>> how_many_times('aaa', 'a')
3
>>> how_many_times('aaaa', 'aa')
3
"""
| times = 0
for i in range(len(string) - len(substring) + 1):
if string[i:i+len(substring)] == substring:
times += 1
return times
| def check(candidate):
assert candidate('', 'x') == 0
assert candidate('xyxyxyx', 'x') == 4
assert candidate('cacacacac', 'cac') == 4
assert candidate('john doe', 'john') == 1
| how_many_times |
HumanEval/1987 | from typing import List
def sort_numbers(numbers: str) -> str:
""" A entrada é uma sequência de números delimitada por espaço de 'zero' a 'nove'. As opções válidas são 'zero', 'um', 'dois', 'três', 'quatro', 'cinco','seis','sete', 'oito' e 'nove'. Retorna a sequência com números ordenados do menor ao maior
>>... | value_map = {
'zero': 0,
'one': 1,
'two': 2,
'three': 3,
'four': 4,
'five': 5,
'six': 6,
'seven': 7,
'eight': 8,
'nine': 9
}
return ' '.join(sorted([x for x in numbers.split(' ') if x], key=lambda x: value_map[x]))
| def check(candidate):
assert candidate('') == ''
assert candidate('three') == 'three'
assert candidate('three five nine') == 'three five nine'
assert candidate('five zero four seven nine eight') == 'zero four five seven eight nine'
assert candidate('six five four three two one zero') == 'zero one tw... | sort_numbers |
HumanEval/1988 | from typing import List, Tuple
def find_closest_elements(numbers: List[float]) -> Tuple[float, float]:
""" De uma lista fornecida de números (de comprimento, pelo menos, dois), selecione e devolva dois que estejam mais próximos um do outro e devolva-os por ordem (número menor, número maior).
>>> find_closest_... | closest_pair = None
distance = None
for idx, elem in enumerate(numbers):
for idx2, elem2 in enumerate(numbers):
if idx != idx2:
if distance is None:
distance = abs(elem - elem2)
closest_pair = tuple(sorted([elem, elem2]))
... | def check(candidate):
assert candidate([1.0, 2.0, 3.9, 4.0, 5.0, 2.2]) == (3.9, 4.0)
assert candidate([1.0, 2.0, 5.9, 4.0, 5.0]) == (5.0, 5.9)
assert candidate([1.0, 2.0, 3.0, 4.0, 5.0, 2.2]) == (2.0, 2.2)
assert candidate([1.0, 2.0, 3.0, 4.0, 5.0, 2.0]) == (2.0, 2.0)
assert candidate([1.1, 2.2, 3.1... | find_closest_elements |
HumanEval/1989 | from typing import List
def rescale_to_unit(numbers: List[float]) -> List[float]:
""" Dada uma lista de números (de pelo menos dois elementos), aplique uma transformação linear a essa lista, de modo que o menor número se torne 0 e o maior se torne 1
>>> rescale_to_unit([1.0, 2.0, 3.0, 4.0, 5.0])
[0.0, 0.2... | min_number = min(numbers)
max_number = max(numbers)
return [(x - min_number) / (max_number - min_number) for x in numbers]
| def check(candidate):
assert candidate([2.0, 49.9]) == [0.0, 1.0]
assert candidate([100.0, 49.9]) == [1.0, 0.0]
assert candidate([1.0, 2.0, 3.0, 4.0, 5.0]) == [0.0, 0.25, 0.5, 0.75, 1.0]
assert candidate([2.0, 1.0, 5.0, 3.0, 4.0]) == [0.25, 0.0, 1.0, 0.5, 0.75]
assert candidate([12.0, 11.0, 15.0, 13... | rescale_to_unit |
HumanEval/1990 | from typing import List, Any
def filter_integers(values: List[Any]) -> List[int]:
""" Filtrar a lista dada de quaisquer valores de Python apenas para inteiros
>>> filter_integers(['a', 3.14, 5])
[5]
>>> filter_integers([1, 2, 3, 'abc', {}, []])
[1, 2, 3]
"""
| return [x for x in values if isinstance(x, int)]
| def check(candidate):
assert candidate([]) == []
assert candidate([4, {}, [], 23.2, 9, 'adasd']) == [4, 9]
assert candidate([3, 'c', 3, 3, 'a', 'b']) == [3, 3, 3]
| filter_integers |
HumanEval/1991 |
def strlen(string: str) -> int:
""" Retorno comprimento da cadeia dada
>>> strlen('')
0
>>> strlen('abc')
3
"""
| return len(string)
| def check(candidate):
assert candidate('') == 0
assert candidate('x') == 1
assert candidate('asdasnakj') == 9
| strlen |
HumanEval/1992 |
def largest_divisor(n: int) -> int:
""" Para um dado número n, encontre o maior número que divide n uniformemente, menor que n
>>> largest_divisor(15)
5
"""
| for i in reversed(range(n)):
if n % i == 0:
return i
| def check(candidate):
assert candidate(3) == 1
assert candidate(7) == 1
assert candidate(10) == 5
assert candidate(100) == 50
assert candidate(49) == 7
| largest_divisor |
HumanEval/1993 | from typing import List
def factorize(n: int) -> List[int]:
""" Retorna lista de fatores primos de um dado inteiro na ordem de menor a maior. Cada um dos fatores deve ser listado o número de vezes correspondente ao número de vezes que aparece na fatorização. O número de entrada deve ser igual ao produto de todos ... | import math
fact = []
i = 2
while i <= int(math.sqrt(n) + 1):
if n % i == 0:
fact.append(i)
n //= i
else:
i += 1
if n > 1:
fact.append(n)
return fact
| def check(candidate):
assert candidate(2) == [2]
assert candidate(4) == [2, 2]
assert candidate(8) == [2, 2, 2]
assert candidate(3 * 19) == [3, 19]
assert candidate(3 * 19 * 3 * 19) == [3, 3, 19, 19]
assert candidate(3 * 19 * 3 * 19 * 3 * 19) == [3, 3, 3, 19, 19, 19]
assert candidate(3 * 19 ... | factorize |
HumanEval/1994 | from typing import List
def remove_duplicates(numbers: List[int]) -> List[int]:
""" De uma lista de inteiros, remova todos os elementos que ocorrem mais de uma vez. Mantenha a ordem dos elementos deixados a mesma que na entrada.
>>> remove_duplicates([1, 2, 3, 2, 4])
[1, 3, 4]
"""
| import collections
c = collections.Counter(numbers)
return [n for n in numbers if c[n] <= 1]
| def check(candidate):
assert candidate([]) == []
assert candidate([1, 2, 3, 4]) == [1, 2, 3, 4]
assert candidate([1, 2, 3, 2, 4, 3, 5]) == [1, 4, 5]
| remove_duplicates |
HumanEval/1995 |
def flip_case(string: str) -> str:
""" Para uma determinada sequência, inverta caracteres minúsculos para maiúsculos e maiúsculos para minúsculos.
>>> flip_case('Hello')
'hELLO'
"""
| return string.swapcase()
| def check(candidate):
assert candidate('') == ''
assert candidate('Hello!') == 'hELLO!'
assert candidate('These violent delights have violent ends') == 'tHESE VIOLENT DELIGHTS HAVE VIOLENT ENDS'
| flip_case |
HumanEval/1996 | from typing import List
def concatenate(strings: List[str]) -> str:
""" Concatenate lista de strings em uma única string
>>> concatenate([])
''
>>> concatenate(['a', 'b', 'c'])
'abc'
"""
| return ''.join(strings)
| def check(candidate):
assert candidate([]) == ''
assert candidate(['x', 'y', 'z']) == 'xyz'
assert candidate(['x', 'y', 'z', 'w', 'k']) == 'xyzwk'
| concatenate |
HumanEval/1997 | from typing import List
def filter_by_prefix(strings: List[str], prefix: str) -> List[str]:
""" Filtre uma lista de entrada de strings apenas para aqueles que começam com um prefixo dado.
>>> filter_by_prefix([], 'a')
[]
>>> filter_by_prefix(['abc', 'bcd', 'cde', 'array'], 'a')
['abc', 'array']
... | return [x for x in strings if x.startswith(prefix)]
| def check(candidate):
assert candidate([], 'john') == []
assert candidate(['xxx', 'asd', 'xxy', 'john doe', 'xxxAAA', 'xxx'], 'xxx') == ['xxx', 'xxxAAA', 'xxx']
| filter_by_prefix |
HumanEval/1998 |
def get_positive(l: list):
"""Devolve apenas números positivos na lista.
>>> 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 [e for e in l if e > 0]
| def check(candidate):
assert candidate([-1, -2, 4, 5, 6]) == [4, 5, 6]
assert candidate([5, 3, -5, 2, 3, 3, 9, 0, 123, 1, -10]) == [5, 3, 2, 3, 3, 9, 123, 1]
assert candidate([-1, -2]) == []
assert candidate([]) == []
| get_positive |
HumanEval/1999 |
def is_prime(n):
"""Retorna verdadeiro se um dado número for primo, e falso caso contrário.
>>> 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
"""
| if n < 2:
return False
for k in range(2, n - 1):
if n % k == 0:
return False
return True
| def check(candidate):
assert candidate(6) == False
assert candidate(101) == True
assert candidate(11) == True
assert candidate(13441) == True
assert candidate(61) == True
assert candidate(4) == False
assert candidate(1) == False
assert candidate(5) == True
assert candidate(11) == Tru... | is_prime |
HumanEval/2000 | import math
def poly(xs: list, x: float):
"""
Avalia polinômio com coeficientes xs no ponto x. retorna 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.
fi... | begin, end = -1., 1.
while poly(xs, begin) * poly(xs, end) > 0:
begin *= 2.0
end *= 2.0
while end - begin > 1e-10:
center = (begin + end) / 2.0
if poly(xs, center) * poly(xs, begin) > 0:
begin = center
else:
end = center
return begin
| def check(candidate):
import math
import random
rng = random.Random(42)
import copy
for _ in range(100):
ncoeff = 2 * rng.randint(1, 4)
coeffs = []
for _ in range(ncoeff):
coeff = rng.randint(-10, 10)
if coeff == 0:
coeff = 1
... | poly |
HumanEval/2001 |
def sort_third(l: list):
"""Esta função toma uma lista l e retorna uma lista l' tal que l' é idêntica a l nos índices que não são divisíveis por três, enquanto os seus valores nos índices que são divisíveis por três são iguais aos valores dos índices correspondentes de l, mas ordenados.
>>> sort_third([1, 2, ... | l = list(l)
l[::3] = sorted(l[::3])
return l
| def check(candidate):
assert tuple(candidate([1, 2, 3])) == tuple(sort_third([1, 2, 3]))
assert tuple(candidate([5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10])) == tuple(sort_third([5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]))
assert tuple(candidate([5, 8, -12, 4, 23, 2, 3, 11, 12, -10])) == tuple(sort_third([5, 8, -1... | sort_third |
HumanEval/2002 |
def unique(l: list):
"""Devolver elementos únicos ordenados numa lista
>>> unique([5, 3, 5, 2, 3, 3, 9, 0, 123])
[0, 2, 3, 5, 9, 123]
"""
| return sorted(list(set(l)))
| def check(candidate):
assert candidate([5, 3, 5, 2, 3, 3, 9, 0, 123]) == [0, 2, 3, 5, 9, 123]
| unique |
HumanEval/2003 |
def max_element(l: list):
"""Devolve o elemento máximo da lista.
>>> max_element([1, 2, 3])
3
>>> max_element([5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10])
123
"""
| m = l[0]
for e in l:
if e > m:
m = e
return m
| def check(candidate):
assert candidate([1, 2, 3]) == 3
assert candidate([5, 3, -5, 2, -3, 3, 9, 0, 124, 1, -10]) == 124
| max_element |
HumanEval/2004 |
def fizz_buzz(n: int):
"""Retorna o número de vezes que o dígito 7 aparece em números inteiros menores que n que são divisíveis por 11 ou 13.
>>> fizz_buzz(50)
0
>>> fizz_buzz(78)
2
>>> fizz_buzz(79)
3
"""
| ns = []
for i in range(n):
if i % 11 == 0 or i % 13 == 0:
ns.append(i)
s = ''.join(list(map(str, ns)))
ans = 0
for c in s:
ans += (c == '7')
return ans
| def check(candidate):
assert candidate(50) == 0
assert candidate(78) == 2
assert candidate(79) == 3
assert candidate(100) == 3
assert candidate(200) == 6
assert candidate(4000) == 192
assert candidate(10000) == 639
assert candidate(100000) == 8026
| fizz_buzz |
HumanEval/2005 |
def sort_even(l: list):
"""Esta função toma uma lista l e retorna uma lista l' tal que l' é idêntica a l nos índices ímpares, enquanto seus valores nos índices pares são iguais aos valores dos índices pares de l, mas ordenados.
>>> sort_even([1, 2, 3])
[1, 2, 3]
>>> sort_even([5, 6, 3, 4])
[3, 6, ... | evens = l[::2]
odds = l[1::2]
evens.sort()
ans = []
for e, o in zip(evens, odds):
ans.extend([e, o])
if len(evens) > len(odds):
ans.append(evens[-1])
return ans
| def check(candidate):
assert tuple(candidate([1, 2, 3])) == tuple([1, 2, 3])
assert tuple(candidate([5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10])) == tuple([-10, 3, -5, 2, -3, 3, 5, 0, 9, 1, 123])
assert tuple(candidate([5, 8, -12, 4, 23, 2, 3, 11, 12, -10])) == tuple([-12, 8, 3, 4, 5, 2, 12, 11, 23, -10])
| sort_even |
HumanEval/2006 |
def encode_cyclic(s: str):
"""
retorna uma sequência codificada por grupos de ciclos de três caracteres.
"""
# 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 eleme... | return encode_cyclic(encode_cyclic(s))
| def check(candidate):
from random import randint, choice
import string
letters = string.ascii_lowercase
for _ in range(100):
str = ''.join(choice(letters) for i in range(randint(10, 20)))
encoded_str = encode_cyclic(str)
assert candidate(encoded_str) == str
| encode_cyclic |
HumanEval/2007 |
def prime_fib(n: int):
"""
prime_fib retorna o n-ésimo número que é um número de Fibonacci e também é primo.
>>> prime_fib(1)
2
>>> prime_fib(2)
3
>>> prime_fib(3)
5
>>> prime_fib(4)
13
>>> prime_fib(5)
89
"""
| import math
def is_prime(p):
if p < 2:
return False
for k in range(2, min(int(math.sqrt(p)) + 1, p - 1)):
if p % k == 0:
return False
return True
f = [0, 1]
while True:
f.append(f[-1] + f[-2])
if is_prime(f[-1]):
... | def check(candidate):
assert candidate(1) == 2
assert candidate(2) == 3
assert candidate(3) == 5
assert candidate(4) == 13
assert candidate(5) == 89
assert candidate(6) == 233
assert candidate(7) == 1597
assert candidate(8) == 28657
assert candidate(9) == 514229
assert candidate(... | prime_fib |
HumanEval/2008 |
def triples_sum_to_zero(l: list):
"""
triples_sum_to_zero leva uma lista de inteiros como entrada. Retorna True se houver três elementos distintos na lista que somam zero, e False caso contrário.
>>> triples_sum_to_zero([1, 3, 5, 0])
False
>>> triples_sum_to_zero([1, 3, -2, 1])
True
>>> t... | for i in range(len(l)):
for j in range(i + 1, len(l)):
for k in range(j + 1, len(l)):
if l[i] + l[j] + l[k] == 0:
return True
return False
| def check(candidate):
assert candidate([1, 3, 5, 0]) == False
assert candidate([1, 3, 5, -1]) == False
assert candidate([1, 3, -2, 1]) == True
assert candidate([1, 2, 3, 7]) == False
assert candidate([1, 2, 5, 7]) == False
assert candidate([2, 4, -5, 3, 9, 7]) == True
assert candidate([1]) =... | triples_sum_to_zero |
HumanEval/2009 |
def car_race_collision(n: int):
"""
Imagine uma estrada que é uma linha infinitamente longa e perfeitamente reta. n carros estão dirigindo da esquerda para a direita; simultaneamente, um conjunto diferente de n carros estão dirigindo da direita para a esquerda. Os dois conjuntos de carros começam sendo muito ... | return n**2
| def check(candidate):
assert candidate(2) == 4
assert candidate(3) == 9
assert candidate(4) == 16
assert candidate(8) == 64
assert candidate(10) == 100
| car_race_collision |
HumanEval/2010 |
def incr_list(l: list):
"""Lista de devolução com elementos incrementados por 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]
"""
| return [(e + 1) for e in l]
| def check(candidate):
assert candidate([]) == []
assert candidate([3, 2, 1]) == [4, 3, 2]
assert candidate([5, 2, 5, 2, 3, 3, 9, 0, 123]) == [6, 3, 6, 3, 4, 4, 10, 1, 124]
| incr_list |
HumanEval/2011 |
def pairs_sum_to_zero(l):
"""
pairs_sum_to_zero leva uma lista de inteiros como entrada. Retorna True se houver dois elementos distintos na lista que somam zero, e False caso contrário.
>>> pairs_sum_to_zero([1, 3, 5, 0])
False
>>> pairs_sum_to_zero([1, 3, -2, 1])
False
>>> pairs_sum_to_ze... | for i, l1 in enumerate(l):
for j in range(i + 1, len(l)):
if l1 + l[j] == 0:
return True
return False
| def check(candidate):
assert candidate([1, 3, 5, 0]) == False
assert candidate([1, 3, -2, 1]) == False
assert candidate([1, 2, 3, 7]) == False
assert candidate([2, 4, -5, 3, 5, 7]) == True
assert candidate([1]) == False
assert candidate([-3, 9, -1, 3, 2, 30]) == True
assert candidate([-3, 9... | pairs_sum_to_zero |
HumanEval/2012 |
def change_base(x: int, base: int):
"""Alterar a base numérica do número de entrada x para base. Retornar representação de string após a conversão. Números de base são menores que 10.
>>> change_base(8, 3)
'22'
>>> change_base(8, 2)
'1000'
>>> change_base(7, 2)
'111'
"""
| ret = ""
while x > 0:
ret = str(x % base) + ret
x //= base
return ret
| def check(candidate):
assert candidate(8, 3) == "22"
assert candidate(9, 3) == "100"
assert candidate(234, 2) == "11101010"
assert candidate(16, 2) == "10000"
assert candidate(8, 2) == "1000"
assert candidate(7, 2) == "111"
for x in range(2, 8):
assert candidate(x, x + 1) == str(x)
| change_base |
HumanEval/2013 |
def triangle_area(a, h):
"""Dado o comprimento de um lado e a área de retorno mais alta para um triângulo.
>>> triangle_area(5, 3)
7.5
"""
| return a * h / 2.0
| def check(candidate):
assert candidate(5, 3) == 7.5
assert candidate(2, 2) == 2.0
assert candidate(10, 8) == 40.0
| triangle_area |
HumanEval/2014 |
def fib4(n: int):
"""A sequência de números Fib4 é uma sequência semelhante à sequência de Fibbonacci que é definida da seguinte forma: 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). Escreva uma função para calcular eficientemente o n-ésimo elemento d... | results = [0, 0, 2, 0]
if n < 4:
return results[n]
for _ in range(4, n + 1):
results.append(results[-1] + results[-2] + results[-3] + results[-4])
results.pop(0)
return results[-1]
| def check(candidate):
assert candidate(5) == 4
assert candidate(8) == 28
assert candidate(10) == 104
assert candidate(12) == 386
| fib4 |
HumanEval/2015 |
def median(l: list):
"""Retornar mediana dos elementos da lista l.
>>> median([3, 1, 2, 4, 5])
3
>>> median([-10, 4, 6, 1000, 10, 20])
15.0
"""
| l = sorted(l)
if len(l) % 2 == 1:
return l[len(l) // 2]
else:
return (l[len(l) // 2 - 1] + l[len(l) // 2]) / 2.0
| def check(candidate):
assert candidate([3, 1, 2, 4, 5]) == 3
assert candidate([-10, 4, 6, 1000, 10, 20]) == 8.0
assert candidate([5]) == 5
assert candidate([6, 5]) == 5.5
assert candidate([8, 1, 3, 9, 9, 2, 7]) == 7
| median |
HumanEval/2016 |
def is_palindrome(text: str):
"""
Verifica se a sequência dada é um palíndromo
>>> is_palindrome('')
True
>>> is_palindrome('aba')
True
>>> is_palindrome('aaaaa')
True
>>> is_palindrome('zbcd')
False
"""
| for i in range(len(text)):
if text[i] != text[len(text) - 1 - i]:
return False
return True
| def check(candidate):
assert candidate('') == True
assert candidate('aba') == True
assert candidate('aaaaa') == True
assert candidate('zbcd') == False
assert candidate('xywyx') == True
assert candidate('xywyz') == False
assert candidate('xywzx') == False
| is_palindrome |
HumanEval/2017 |
def modp(n: int, p: int):
"""Retorne 2^n módulo p (tenha em mente os números).
>>> modp(3, 5)
3
>>> modp(1101, 101)
2
>>> modp(0, 101)
1
>>> modp(3, 11)
8
>>> modp(100, 101)
1
"""
| ret = 1
for i in range(n):
ret = (2 * ret) % p
return ret
| def check(candidate):
assert candidate(3, 5) == 3
assert candidate(1101, 101) == 2
assert candidate(0, 101) == 1
assert candidate(3, 11) == 8
assert candidate(100, 101) == 1
assert candidate(30, 5) == 4
assert candidate(31, 5) == 3
| modp |
HumanEval/2018 |
def encode_shift(s: str):
"""
retorna string codificado por deslocar cada caractere por 5 no alfabeto.
"""
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 str... | return "".join([chr(((ord(ch) - 5 - ord("a")) % 26) + ord("a")) for ch in s])
| def check(candidate):
from random import randint, choice
import copy
import string
letters = string.ascii_lowercase
for _ in range(100):
str = ''.join(choice(letters) for i in range(randint(10, 20)))
encoded_str = encode_shift(str)
assert candidate(copy.deepcopy(encoded_str)... | encode_shift |
HumanEval/2019 |
def remove_vowels(text):
"""
remove_vowels é uma função que pega string e retorna string sem vogais.
>>> remove_vowels('')
''
>>> remove_vowels("abcdef\nghijklm")
'bcdf\nghjklm'
>>> remove_vowels('abcdef')
'bcdf'
>>> remove_vowels('aaaaa')
''
>>> remove_vowels('aaBAA')
... | return "".join([s for s in text if s.lower() not in ["a", "e", "i", "o", "u"]])
| def check(candidate):
assert candidate('') == ''
assert candidate("abcdef\nghijklm") == 'bcdf\nghjklm'
assert candidate('fedcba') == 'fdcb'
assert candidate('eeeee') == ''
assert candidate('acBAA') == 'cB'
assert candidate('EcBOO') == 'cB'
assert candidate('ybcd') == 'ybcd'
| remove_vowels |
HumanEval/2020 |
def below_threshold(l: list, t: int):
"""Retorna True se todos os números da lista l estiverem abaixo do limiar t.
>>> below_threshold([1, 2, 4, 10], 100)
True
>>> below_threshold([1, 20, 4, 10], 5)
False
"""
| for e in l:
if e >= t:
return False
return True
| def check(candidate):
assert candidate([1, 2, 4, 10], 100)
assert not candidate([1, 20, 4, 10], 5)
assert candidate([1, 20, 4, 10], 21)
assert candidate([1, 20, 4, 10], 22)
assert candidate([1, 8, 4, 10], 11)
assert not candidate([1, 8, 4, 10], 10)
| below_threshold |
HumanEval/2021 |
def add(x: int, y: int):
"""Adicionar dois números x e y
>>> add(2, 3)
5
>>> add(5, 7)
12
"""
| return x + y
| def check(candidate):
import random
assert candidate(0, 1) == 1
assert candidate(1, 0) == 1
assert candidate(2, 3) == 5
assert candidate(5, 7) == 12
assert candidate(7, 5) == 12
for i in range(100):
x, y = random.randint(0, 1000), random.randint(0, 1000)
assert candidate(x,... | add |
HumanEval/2022 |
def same_chars(s0: str, s1: str):
"""
Verifique se duas palavras têm os mesmos caracteres.
>>> same_chars('eabcdzzzz', 'dddzzzzzzzddeddabc')
True
>>> same_chars('abcd', 'dddddddabc')
True
>>> same_chars('dddddddabc', 'abcd')
True
>>> same_chars('eabcd', 'dddddddabc')
False
... | return set(s0) == set(s1)
| def check(candidate):
assert candidate('eabcdzzzz', 'dddzzzzzzzddeddabc') == True
assert candidate('abcd', 'dddddddabc') == True
assert candidate('dddddddabc', 'abcd') == True
assert candidate('eabcd', 'dddddddabc') == False
assert candidate('abcd', 'dddddddabcf') == False
assert candidate('eabc... | same_chars |
HumanEval/2023 |
def fib(n: int):
"""Retorna o n-ésimo número de Fibonacci.
>>> fib(10)
55
>>> fib(1)
1
>>> fib(8)
21
"""
| if n == 0:
return 0
if n == 1:
return 1
return fib(n - 1) + fib(n - 2)
| def check(candidate):
assert candidate(10) == 55
assert candidate(1) == 1
assert candidate(8) == 21
assert candidate(11) == 89
assert candidate(12) == 144
| fib |
HumanEval/2024 |
def correct_bracketing(brackets: str):
""" brackets é uma sequência de "<" e ">". return True se cada parêntese de abertura tiver uma correspondente parêntese de fechamento.
>>> correct_bracketing("<")
False
>>> correct_bracketing("<>")
True
>>> correct_bracketing("<<><>>")
True
>>> c... | depth = 0
for b in brackets:
if b == "<":
depth += 1
else:
depth -= 1
if depth < 0:
return False
return depth == 0
| def check(candidate):
assert candidate("<>")
assert candidate("<<><>>")
assert candidate("<><><<><>><>")
assert candidate("<><><<<><><>><>><<><><<>>>")
assert not candidate("<<<><>>>>")
assert not candidate("><<>")
assert not candidate("<")
assert not candidate("<<<<")
assert not can... | correct_bracketing |
HumanEval/2025 |
def monotonic(l: list):
"""Retornar True é a lista de elementos estão monotonicamente aumentando ou diminuindo.
>>> monotonic([1, 2, 4, 20])
True
>>> monotonic([1, 20, 4, 10])
False
>>> monotonic([4, 1, 0, -10])
True
"""
| if l == sorted(l) or l == sorted(l, reverse=True):
return True
return False
| def check(candidate):
assert candidate([1, 2, 4, 10]) == True
assert candidate([1, 2, 4, 20]) == True
assert candidate([1, 20, 4, 10]) == False
assert candidate([4, 1, 0, -10]) == True
assert candidate([4, 1, 1, 0]) == True
assert candidate([1, 2, 3, 2, 5, 60]) == False
assert candidate([1, ... | monotonic |
HumanEval/2026 |
def common(l1: list, l2: list):
"""Devolve elementos comuns únicos ordenados para duas listas.
>>> 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]
"""
| ret = set()
for e1 in l1:
for e2 in l2:
if e1 == e2:
ret.add(e1)
return sorted(list(ret))
| def check(candidate):
assert candidate([1, 4, 3, 34, 653, 2, 5], [5, 7, 1, 5, 9, 653, 121]) == [1, 5, 653]
assert candidate([5, 3, 2, 8], [3, 2]) == [2, 3]
assert candidate([4, 3, 2, 8], [3, 2, 4]) == [2, 3, 4]
assert candidate([4, 3, 2, 8], []) == []
| common |
HumanEval/2027 |
def largest_prime_factor(n: int):
"""Retorne o maior fator primo de n. Assuma n > 1 e não é um primo.
>>> largest_prime_factor(13195)
29
>>> largest_prime_factor(2048)
2
"""
| def is_prime(k):
if k < 2:
return False
for i in range(2, k - 1):
if k % i == 0:
return False
return True
largest = 1
for j in range(2, n + 1):
if n % j == 0 and is_prime(j):
largest = max(largest, j)
return largest
| def check(candidate):
assert candidate(15) == 5
assert candidate(27) == 3
assert candidate(63) == 7
assert candidate(330) == 11
assert candidate(13195) == 29
| largest_prime_factor |
HumanEval/2028 |
def sum_to_n(n: int):
"""sum_to_n é uma função que soma números de 1 a 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
"""
| return sum(range(n + 1))
| def check(candidate):
assert candidate(1) == 1
assert candidate(6) == 21
assert candidate(11) == 66
assert candidate(30) == 465
assert candidate(100) == 5050
| sum_to_n |
HumanEval/2029 |
def correct_bracketing(brackets: str):
""" brackets é uma sequência de "(" e "". retorna True se cada parêntese de abertura tiver uma correspondente parêntese de fechamento.
>>> correct_bracketing("(")
False
>>> correct_bracketing("()")
True
>>> correct_bracketing("(()())")
True
>>> c... | depth = 0
for b in brackets:
if b == "(":
depth += 1
else:
depth -= 1
if depth < 0:
return False
return depth == 0
| def check(candidate):
assert candidate("()")
assert candidate("(()())")
assert candidate("()()(()())()")
assert candidate("()()((()()())())(()()(()))")
assert not candidate("((()())))")
assert not candidate(")(()")
assert not candidate("(")
assert not candidate("((((")
assert not can... | correct_bracketing |
HumanEval/2030 |
def derivative(xs: list):
""" xs representam coeficientes de um polinômio. xs[0] + xs[1] * x + xs[2] * x^2 +.... Retorna a derivada deste polinômio na mesma forma.
>>> derivative([3, 1, 2, 4, 5])
[1, 4, 12, 20]
>>> derivative([1, 2, 3])
[2, 6]
"""
| return [(i * x) for i, x in enumerate(xs)][1:]
| def check(candidate):
assert candidate([3, 1, 2, 4, 5]) == [1, 4, 12, 20]
assert candidate([1, 2, 3]) == [2, 6]
assert candidate([3, 2, 1]) == [2, 2]
assert candidate([3, 2, 1, 0, 4]) == [2, 2, 0, 16]
assert candidate([1]) == []
| derivative |
HumanEval/2031 |
def fibfib(n: int):
"""A sequência de números FibFib é uma sequência semelhante à sequência de Fibbonacci que é definida da seguinte forma: fibfib(0) == 0 fibfib(1) == 0 fibfib(2) == 1 fibfib(n) == fibfib(n-1) + fibfib(n-2) + fibfib(n-3). Escreva uma função para calcular eficientemente o n-ésimo elemento da sequê... | if n == 0:
return 0
if n == 1:
return 0
if n == 2:
return 1
return fibfib(n - 1) + fibfib(n - 2) + fibfib(n - 3)
| def check(candidate):
assert candidate(2) == 1
assert candidate(1) == 0
assert candidate(5) == 4
assert candidate(8) == 24
assert candidate(10) == 81
assert candidate(12) == 274
assert candidate(14) == 927
| fibfib |
HumanEval/2032 |
FIX = """
Adicione mais casos de teste.
"""
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... | vowels = "aeiouAEIOU"
n_vowels = sum(c in vowels for c in s)
if s[-1] == 'y' or s[-1] == 'Y':
n_vowels += 1
return n_vowels
| def check(candidate):
# Check some simple cases
assert candidate("abcde") == 2, "Test 1"
assert candidate("Alone") == 3, "Test 2"
assert candidate("key") == 2, "Test 3"
assert candidate("bye") == 1, "Test 4"
assert candidate("keY") == 2, "Test 5"
assert candidate("bYe") == 1, "Test 6"
a... | vowels_count |
HumanEval/2033 |
def circular_shift(x, shift):
"""Circular deslocar os dígitos do inteiro x, deslocar os dígitos para a direita por deslocamento e retornar o resultado como uma string. Se deslocar > número de dígitos, retornar dígitos invertidos.
>>> circular_shift(12, 1)
"21"
>>> circular_shift(12, 2)
"12"
"""... | s = str(x)
if shift > len(s):
return s[::-1]
else:
return s[len(s) - shift:] + s[:len(s) - shift]
| def check(candidate):
# Check some simple cases
assert candidate(100, 2) == "001"
assert candidate(12, 2) == "12"
assert candidate(97, 8) == "79"
assert candidate(12, 1) == "21", "This prints if this assert fails 1 (good for debugging!)"
# Check some edge cases that are easy to work out by han... | circular_shift |
HumanEval/2034 |
def digitSum(s):
"""Tarea Escrever uma função que toma uma string como entrada e retorna a soma dos caracteres superiores apenas' códigos ASCII. Exemplos: digitSum("") => 0 digitSum("abAB") => 131 digitSum("abcCd") => 67 digitSum("helloE") => 69 digitSum("woArBld") => 131 digitSum("aAaaaXa") => 153
"""
| if s == "": return 0
return sum(ord(char) if char.isupper() else 0 for char in s)
| def check(candidate):
# Check some simple cases
assert True, "This prints if this assert fails 1 (good for debugging!)"
assert candidate("") == 0, "Error"
assert candidate("abAB") == 131, "Error"
assert candidate("abcCd") == 67, "Error"
assert candidate("helloE") == 69, "Error"
assert candi... | digitSum |
HumanEval/2035 |
def fruit_distribution(s,n):
"""
Nesta tarefa, você receberá uma string que representa um número de maçãs e laranjas que são distribuídas em uma cesta de frutas esta cesta contém maçãs, laranjas e frutas de manga. Dada a string que representa o número total de laranjas e maçãs e um número inteiro que represent... | lis = list()
for i in s.split(' '):
if i.isdigit():
lis.append(int(i))
return n - sum(lis)
| def check(candidate):
# Check some simple cases
assert candidate("5 apples and 6 oranges",19) == 8
assert candidate("5 apples and 6 oranges",21) == 10
assert candidate("0 apples and 1 oranges",3) == 2
assert candidate("1 apples and 0 oranges",3) == 2
assert candidate("2 apples and 3 oranges",10... | fruit_distribution |
HumanEval/2036 |
def pluck(arr):
"""
"Dada uma matriz representando um ramo de uma árvore que tem nós inteiros não negativos, sua tarefa é pegar um dos nós e retorná-lo. O nó pegar deve ser o nó com o menor valor par. Se vários nós com o mesmo menor valor par são encontrados, retorne o nó que tem menor índice. O nó pegar deve ... | if(len(arr) == 0): return []
evens = list(filter(lambda x: x%2 == 0, arr))
if(evens == []): return []
return [min(evens), arr.index(min(evens))]
| def check(candidate):
# Check some simple cases
assert True, "This prints if this assert fails 1 (good for debugging!)"
assert candidate([4,2,3]) == [2, 1], "Error"
assert candidate([1,2,3]) == [2, 1], "Error"
assert candidate([]) == [], "Error"
assert candidate([5, 0, 3, 0, 4, 2]) == [0, 1], "... | pluck |
HumanEval/2037 |
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 va... | frq = [0] * (max(lst) + 1)
for i in lst:
frq[i] += 1;
ans = -1
for i in range(1, len(frq)):
if frq[i] >= i:
ans = i
return ans
| def check(candidate):
# manually generated tests
assert candidate([5, 5, 5, 5, 1]) == 1
assert candidate([4, 1, 4, 1, 4, 4]) == 4
assert candidate([3, 3]) == -1
assert candidate([8, 8, 8, 8, 8, 8, 8, 8]) == 8
assert candidate([2, 3, 3, 2, 2]) == 2
# automatically generated tests
assert... | search |
HumanEval/2038 |
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... | res, switch = [], True
while lst:
res.append(min(lst) if switch else max(lst))
lst.remove(res[-1])
switch = not switch
return res
| def check(candidate):
# Check some simple cases
assert candidate([1, 2, 3, 4]) == [1, 4, 2, 3]
assert candidate([5, 6, 7, 8, 9]) == [5, 9, 6, 8, 7]
assert candidate([1, 2, 3, 4, 5]) == [1, 5, 2, 4, 3]
assert candidate([5, 6, 7, 8, 9, 1]) == [1, 9, 5, 8, 6, 7]
assert candidate([5, 5, 5, 5]) == [... | strange_sort_list |
HumanEval/2039 |
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 thi... | if a + b <= c or a + c <= b or b + c <= a:
return -1
s = (a + b + c)/2
area = (s * (s - a) * (s - b) * (s - c)) ** 0.5
area = round(area, 2)
return area
| def check(candidate):
# Check some simple cases
assert candidate(3, 4, 5) == 6.00, "This prints if this assert fails 1 (good for debugging!)"
assert candidate(1, 2, 10) == -1
assert candidate(4, 8, 5) == 8.18
assert candidate(2, 2, 2) == 1.73
assert candidate(1, 2, 3) == -1
assert candidate... | triangle_area |
HumanEval/2040 |
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 ... | if sum(q) > w:
return False
i, j = 0, len(q)-1
while i<j:
if q[i] != q[j]:
return False
i+=1
j-=1
return True
| def check(candidate):
# Check some simple cases
assert candidate([3, 2, 3], 9) is True
assert candidate([1, 2], 5) is False
assert candidate([3], 5) is True
assert candidate([3, 2, 3], 1) is False
# Check some edge cases that are easy to work out by hand.
assert candidate([1, 2, 3], 6) is... | will_it_fly |
HumanEval/2041 |
def smallest_change(arr):
"""
Dado um array de inteiros, encontre o número mínimo de elementos que precisam ser alterados para tornar o array palindrômico. Um array palindrômico é um array que é lido da mesma forma para trás e para a frente. Em uma mudança, você pode alterar um elemento para qualquer outro ele... | ans = 0
for i in range(len(arr) // 2):
if arr[i] != arr[len(arr) - i - 1]:
ans += 1
return ans
| def check(candidate):
# Check some simple cases
assert candidate([1,2,3,5,4,7,9,6]) == 4
assert candidate([1, 2, 3, 4, 3, 2, 2]) == 1
assert candidate([1, 4, 2]) == 1
assert candidate([1, 4, 4, 2]) == 1
# Check some edge cases that are easy to work out by hand.
assert candidate([1, 2, 3, 2... | smallest_change |
HumanEval/2042 |
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([], [])... | l1 = 0
for st in lst1:
l1 += len(st)
l2 = 0
for st in lst2:
l2 += len(st)
if l1 <= l2:
return lst1
else:
return lst2
| def check(candidate):
# Check some simple cases
assert True, "This prints if this assert fails 1 (good for debugging!)"
assert candidate([], []) == []
assert candidate(['hi', 'admin'], ['hi', 'hi']) == ['hi', 'hi']
assert candidate(['hi', 'admin'], ['hi', 'hi', 'admin', 'project']) == ['hi', 'admin... | total_match |
HumanEval/2043 |
def is_multiply_prime(a):
"""Escreva uma função que retorne verdadeiro se o número dado for a multiplicação de 3 números primos e falso caso contrário. Sabendo que (a) é menor que 100.
"""
| def is_prime(n):
for j in range(2,n):
if n%j == 0:
return False
return True
for i in range(2,101):
if not is_prime(i): continue
for j in range(2,101):
if not is_prime(j): continue
for k in range(2,101):
if not i... | def check(candidate):
assert candidate(5) == False
assert candidate(30) == True
assert candidate(8) == True
assert candidate(10) == False
assert candidate(125) == True
assert candidate(3 * 5 * 7) == True
assert candidate(3 * 6 * 7) == False
assert candidate(9 * 9 * 9) == False
asser... | is_multiply_prime |
HumanEval/2044 |
def is_simple_power(x, n):
"""Sua tarefa é escrever uma função que retorne verdadeiro se um número x é uma potência simples de n e falso em outros casos. x é uma potência simples de n se n**int=x Por exemplo: is_simple_power(1, 4) => true is_simple_power(2, 2) => true is_simple_power(8, 2) => true is_simple_power(... | if (n == 1):
return (x == 1)
power = 1
while (power < x):
power = power * n
return (power == x)
| def check(candidate):
# Check some simple cases
assert candidate(16, 2)== True, "This prints if this assert fails 1 (good for debugging!)"
assert candidate(143214, 16)== False, "This prints if this assert fails 1 (good for debugging!)"
assert candidate(4, 2)==True, "This prints if this assert fails 1 (... | is_simple_power |
HumanEval/2045 |
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) ==> ... | a = abs(a)
return int(round(a ** (1. / 3))) ** 3 == a
| def check(candidate):
# Check some simple cases
assert candidate(1) == True, "First test error: " + str(candidate(1))
assert candidate(2) == False, "Second test error: " + str(candidate(2))
assert candidate(-1) == True, "Third test error: " + str(candidate(-1))
assert candidate(64) == True, "Fourth... | iscube |
HumanEval/2046 |
def hex_key(num):
"""Você foi incumbido de escrever uma função que recebe um número hexadecimal como uma string e conta o número de dígitos hexadecimal que são primos (um número primo, ou um primo, é um número natural maior que 1 que não é um produto de dois números naturais menores). Os dígitos hexadecimais são 0... | primes = ('2', '3', '5', '7', 'B', 'D')
total = 0
for i in range(0, len(num)):
if num[i] in primes:
total += 1
return total
| def check(candidate):
# Check some simple cases
assert candidate("AB") == 1, "First test error: " + str(candidate("AB"))
assert candidate("1077E") == 2, "Second test error: " + str(candidate("1077E"))
assert candidate("ABED1A33") == 4, "Third test error: " + str(candidate("ABED1A33"))
... | hex_key |
HumanEval/2047 |
def decimal_to_binary(decimal):
"""A função deve retornar uma string, com cada caractere representando um número binário. Cada caractere na string será '0' ou '1'. Haverá um par extra de caracteres 'db' no início e no final da string. Os caracteres extras estão lá para ajudar com o formato. Exemplos: decimal_to_bi... | return "db" + bin(decimal)[2:] + "db"
| def check(candidate):
# Check some simple cases
assert candidate(0) == "db0db"
assert candidate(32) == "db100000db"
assert candidate(103) == "db1100111db"
assert candidate(15) == "db1111db", "This prints if this assert fails 1 (good for debugging!)"
# Check some edge cases that are easy to wor... | decimal_to_binary |
HumanEval/2048 |
def is_happy(s):
"""Você recebe uma string s. Sua tarefa é verificar se a string é feliz ou não. Uma string é feliz se o seu comprimento é de pelo menos 3 e cada 3 letras consecutivas são distintas Por exemplo: is_happy(a) => Falso is_happy(aa) => Falso is_happy(abcd) => Verdadeiro is_happy(aabb) => Falso is_happy... | if len(s) < 3:
return False
for i in range(len(s) - 2):
if s[i] == s[i+1] or s[i+1] == s[i+2] or s[i] == s[i+2]:
return False
return True
| def check(candidate):
# Check some simple cases
assert candidate("a") == False , "a"
assert candidate("aa") == False , "aa"
assert candidate("abcd") == True , "abcd"
assert candidate("aabb") == False , "aabb"
assert candidate("adb") == True , "adb"
assert candidate("xyy") == False , "xyy"
... | is_happy |
HumanEval/2049 |
def numerical_letter_grade(grades):
"""É a última semana do semestre e a professora tem que dar as notas aos alunos. A professora tem feito seu próprio algoritmo para classificação. O único problema é que ela perdeu o código que ela usou para classificação. Ela deu uma lista de GPAs para alguns alunos e você tem q... |
letter_grade = []
for gpa in grades:
if gpa == 4.0:
letter_grade.append("A+")
elif gpa > 3.7:
letter_grade.append("A")
elif gpa > 3.3:
letter_grade.append("A-")
elif gpa > 3.0:
letter_grade.append("B+")
elif gpa > 2.7:
... | def check(candidate):
# Check some simple cases
assert candidate([4.0, 3, 1.7, 2, 3.5]) == ['A+', 'B', 'C-', 'C', 'A-']
assert candidate([1.2]) == ['D+']
assert candidate([0.5]) == ['D-']
assert candidate([0.0]) == ['E']
assert candidate([1, 0.3, 1.5, 2.8, 3.3]) == ['D', 'D-', 'C-', 'B', 'B+']
... | numerical_letter_grade |
HumanEval/2050 |
def prime_length(string):
"""Escreva uma função que pegue uma string e retorne True se o comprimento da string for um número primo ou False caso contrário Exemplos prime_length{'Hello') == True prime_length{'abcdcba') == True prime_length{'kittens') == True prime_length{'orange') == False
"""
| l = len(string)
if l == 0 or l == 1:
return False
for i in range(2, l):
if l % i == 0:
return False
return True
| def check(candidate):
# Check some simple cases
assert candidate('Hello') == True
assert candidate('abcdcba') == True
assert candidate('kittens') == True
assert candidate('orange') == False
assert candidate('wow') == True
assert candidate('world') == True
assert candidate('MadaM') == Tr... | prime_length |
HumanEval/2051 |
def starts_one_ends(n):
"""
Dado um inteiro positivo n, retorna a contagem dos números de n dígitos inteiros positivos que começam ou terminam com 1.
"""
| if n == 1: return 1
return 18 * (10 ** (n - 2))
| def check(candidate):
# Check some simple cases
assert True, "This prints if this assert fails 1 (good for debugging!)"
assert candidate(1) == 1
assert candidate(2) == 18
assert candidate(3) == 180
assert candidate(4) == 1800
assert candidate(5) == 18000
# Check some edge cases that ar... | starts_one_ends |
HumanEval/2052 |
def solve(N):
"""Dado um inteiro positivo N, retorne a soma total de seus dígitos em binário. Exemplo Para N = 1000, a soma dos dígitos será 1 a saída deve ser "1". Para N = 150, a soma dos dígitos será 6 a saída deve ser "110". Para N = 147, a soma dos dígitos será 12 a saída deve ser "1100". Variaveis: @N inteir... | return bin(sum(int(i) for i in str(N)))[2:]
| def check(candidate):
# Check some simple cases
assert True, "This prints if this assert fails 1 (good for debugging!)"
assert candidate(1000) == "1", "Error"
assert candidate(150) == "110", "Error"
assert candidate(147) == "1100", "Error"
# Check some edge cases that are easy to work out by h... | solve |
HumanEval/2053 |
def add(lst):
"""Dada uma lista não vazia de inteiros, primeiro adicione os elementos pares que estão em índices ímpares. Exemplos: adicionar ([4, 2, 6, 7]) ==> 2
"""
| return sum([lst[i] for i in range(1, len(lst), 2) if lst[i]%2 == 0])
| def check(candidate):
# Check some simple cases
assert candidate([4, 88]) == 88
assert candidate([4, 5, 6, 7, 2, 122]) == 122
assert candidate([4, 0, 6, 7]) == 0
assert candidate([4, 4, 6, 8]) == 12
# Check some edge cases that are easy to work out by hand.
| add |
HumanEval/2054 |
def anti_shuffle(s):
"""
Escreva uma função que pegue uma string e retorne uma versão ordenada dela. Versão ordenada de string, é uma string onde todas as palavras (separadas por espaço) são substituídas por uma nova palavra onde todos os caracteres estão dispostos em ordem ascendente baseada no valor ascii. N... | return ' '.join([''.join(sorted(list(i))) for i in s.split(' ')])
| def check(candidate):
# Check some simple cases
assert candidate('Hi') == 'Hi'
assert candidate('hello') == 'ehllo'
assert candidate('number') == 'bemnru'
assert candidate('abcd') == 'abcd'
assert candidate('Hello World!!!') == 'Hello !!!Wdlor'
assert candidate('') == ''
assert candidat... | anti_shuffle |
HumanEval/2055 |
def get_row(lst, x):
"""
Você recebe um dado bidimensional, como uma lista aninhada, que é semelhante a uma matriz, no entanto, ao contrário das matrizes, cada linha pode conter um número diferente de colunas. Dado lst e inteiro x, encontre inteiros x na lista e retorne lista de tuplas, [(x1, y1), (x2, y2)...]... | coords = [(i, j) for i in range(len(lst)) for j in range(len(lst[i])) if lst[i][j] == x]
return sorted(sorted(coords, key=lambda x: x[1], reverse=True), key=lambda x: x[0])
| def check(candidate):
# Check some simple cases
assert candidate([
[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)]
assert candidate([
[1,2,3,4,5,6],
[1,2,3,4,5,6],
[1,2,3,4,5,6],
[1,2,3,4,5,6],
... | get_row |
HumanEval/2056 |
def sort_array(array):
"""
Dado um array de inteiros não negativos, retorne uma cópia do array dado após a classificação, você classificará o array dado em ordem ascendente se a soma ((primeiro valor de índice, último valor de índice) for ímpar, ou classificá-lo em ordem decrescente se a soma ((primeiro valor ... | return [] if len(array) == 0 else sorted(array, reverse= (array[0]+array[-1]) % 2 == 0)
| def check(candidate):
# Check some simple cases
assert True, "This prints if this assert fails 1 (good for debugging!)"
assert candidate([]) == [], "Error"
assert candidate([5]) == [5], "Error"
assert candidate([2, 4, 3, 0, 1, 5]) == [0, 1, 2, 3, 4, 5], "Error"
assert candidate([2, 4, 3, 0, 1, ... | sort_array |
HumanEval/2057 |
def encrypt(s):
"""Criar uma função encrypt que toma uma string como argumento e retorna uma string criptografada com o alfabeto sendo girado. O alfabeto deve ser girado de tal forma que as letras mudem para baixo por dois multiplicados por dois lugares. Por exemplo: encrypt('hi') retorna 'lm' encrypt('asdfghjkl')... | d = 'abcdefghijklmnopqrstuvwxyz'
out = ''
for c in s:
if c in d:
out += d[(d.index(c)+2*2) % 26]
else:
out += c
return out
| def check(candidate):
# Check some simple cases
assert candidate('hi') == 'lm', "This prints if this assert fails 1 (good for debugging!)"
assert candidate('asdfghjkl') == 'ewhjklnop', "This prints if this assert fails 1 (good for debugging!)"
assert candidate('gf') == 'kj', "This prints if this assert... | encrypt |
HumanEval/2058 |
def next_smallest(lst):
"""
Você recebe uma lista de inteiros. Escreva uma função next_smallest() que retorna o segundo menor elemento da lista. Retorna None se não houver tal elemento. next_smallest([1, 2, 3, 4, 5]) == 2 next_smallest([5, 1, 4, 3, 2]) == 2 next_smallest([]) == Nenhum next_smallest([1, 1]) == ... | lst = sorted(set(lst))
return None if len(lst) < 2 else lst[1]
| def check(candidate):
# Check some simple cases
assert candidate([1, 2, 3, 4, 5]) == 2
assert candidate([5, 1, 4, 3, 2]) == 2
assert candidate([]) == None
assert candidate([1, 1]) == None
assert candidate([1,1,1,1,0]) == 1
assert candidate([1, 0**0]) == None
assert candidate([-35, 34, 1... | next_smallest |
HumanEval/2059 |
def is_bored(S):
"""
Você receberá uma sequência de palavras e sua tarefa é contar o número de aborrecimentos. Um aborrecimento é uma frase que começa com a palavra "I". As frases são delimitadas por '.', '?' ou '!'. Por exemplo:
>>> is_bored("Hello world")
0
>>> is_bored("The sky is blue. The sun ... | import re
sentences = re.split(r'[.?!]\s*', S)
return sum(sentence[0:2] == 'I ' for sentence in sentences)
| def check(candidate):
# Check some simple cases
assert candidate("Hello world") == 0, "Test 1"
assert candidate("Is the sky blue?") == 0, "Test 2"
assert candidate("I love It !") == 1, "Test 3"
assert candidate("bIt") == 0, "Test 4"
assert candidate("I feel good today. I will be productive. wil... | is_bored |
HumanEval/2060 |
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... |
if isinstance(x,int) and isinstance(y,int) and isinstance(z,int):
if (x+y==z) or (x+z==y) or (y+z==x):
return True
return False
return False
| def check(candidate):
# Check some simple cases
assert candidate(2, 3, 1)==True, "This prints if this assert fails 1 (good for debugging!)"
assert candidate(2.5, 2, 3)==False, "This prints if this assert fails 2 (good for debugging!)"
assert candidate(1.5, 5, 3.5)==False, "This prints if this assert fa... | any_int |
HumanEval/2061 |
def encode(message):
"""
Escreva uma função que recebe uma mensagem e codifica de tal forma que troca de case de todas as letras, substitui todas as vogais na mensagem com a letra que aparece 2 lugares à frente dessa vogal no alfabeto inglês.
>>> encode('test')
'TGST'
>>> encode('This is a message'... | vowels = "aeiouAEIOU"
vowels_replace = dict([(i, chr(ord(i) + 2)) for i in vowels])
message = message.swapcase()
return ''.join([vowels_replace[i] if i in vowels else i for i in message])
| def check(candidate):
# Check some simple cases
assert candidate('TEST') == 'tgst', "This prints if this assert fails 1 (good for debugging!)"
assert candidate('Mudasir') == 'mWDCSKR', "This prints if this assert fails 2 (good for debugging!)"
assert candidate('YES') == 'ygs', "This prints if this asse... | encode |
HumanEval/2062 |
def skjkasdkd(lst):
"""Você recebe uma lista de números inteiros. Você precisa encontrar o maior valor primo e retornar a soma de seus dígitos. Exemplos: Para lst = [0,3,2,1,3,5,7,4,5,5,5,2,181,32,4,32,3,2,32,324,4,3] a saída deve ser 10 Para lst = [1,0,1,8,2,4597,2,1,3,40,1,2,1,2,4,2,5,1] a saída deve ser 25 Par... | def isPrime(n):
for i in range(2,int(n**0.5)+1):
if n%i==0:
return False
return True
maxx = 0
i = 0
while i < len(lst):
if(lst[i] > maxx and isPrime(lst[i])):
maxx = lst[i]
i+=1
result = sum(int(digit) for digit in str(maxx))
... | def check(candidate):
# Check some simple cases
assert candidate([0,3,2,1,3,5,7,4,5,5,5,2,181,32,4,32,3,2,32,324,4,3]) == 10, "This prints if this assert fails 1 (good for debugging!)"
# Check some edge cases that are easy to work out by hand.
assert candidate([1,0,1,8,2,4597,2,1,3,40,1,2,1,2,4,2,5,1]... | skjkasdkd |
HumanEval/2063 |
def check_dict_case(dict):
"""
Dado um dicionário, retorne True se todas as chaves forem strings em minúsculas ou todas as chaves forem strings em maiúsculas, caso contrário retorne False. A função deve retornar False se o dicionário dado estiver vazio. Exemplos: check_dict_case{"a":"apple", "b":"banana"}) dev... | if len(dict.keys()) == 0:
return False
else:
state = "start"
for key in dict.keys():
if isinstance(key, str) == False:
state = "mixed"
break
if state == "start":
if key.isupper():
state = "upper"... | def check(candidate):
# Check some simple cases
assert candidate({"p":"pineapple", "b":"banana"}) == True, "First test error: " + str(candidate({"p":"pineapple", "b":"banana"}))
assert candidate({"p":"pineapple", "A":"banana", "B":"banana"}) == False, "Second test error: " + str(candidate({"p":"pineapple",... | check_dict_case |
HumanEval/2064 |
def count_up_to(n):
"""Implementar uma função que toma um inteiro não negativo e retorna um array dos primeiros n inteiros que são números primos e menores que n. Por exemplo: 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) => [] cou... | primes = []
for i in range(2, n):
is_prime = True
for j in range(2, i):
if i % j == 0:
is_prime = False
break
if is_prime:
primes.append(i)
return primes
| def check(candidate):
assert candidate(5) == [2,3]
assert candidate(6) == [2,3,5]
assert candidate(7) == [2,3,5]
assert candidate(10) == [2,3,5,7]
assert candidate(0) == []
assert candidate(22) == [2,3,5,7,11,13,17,19]
assert candidate(1) == []
assert candidate(18) == [2,3,5,7,11,13,17]... | count_up_to |
HumanEval/2065 |
def multiply(a, b):
"""Exemplo: multiplicar 148, 412 deve retornar 16, multiplicar 19 28, 72, multiplicar 2020, 1851 deve retornar 0, multiplicar 14,15 deve retornar 20.
"""
| return abs(a % 10) * abs(b % 10)
| def check(candidate):
# Check some simple cases
assert candidate(148, 412) == 16, "First test error: " + str(candidate(148, 412))
assert candidate(19, 28) == 72, "Second test error: " + str(candidate(19, 28))
assert candidate(2020, 1851) == 0, "Third test error: " + str(c... | multiply |
HumanEval/2066 |
def count_upper(s):
"""
Dada uma string s, conte o número de vogais maiúsculas em índices pares. Por exemplo: count_upper (('aBCdEf') retorna 1 count_upper (('abcdefg') retorna 0 count_upper (('dBBE') retorna 0
"""
| count = 0
for i in range(0,len(s),2):
if s[i] in "AEIOU":
count += 1
return count
| def check(candidate):
# Check some simple cases
assert candidate('aBCdEf') == 1
assert candidate('abcdefg') == 0
assert candidate('dBBE') == 0
assert candidate('B') == 0
assert candidate('U') == 1
assert candidate('') == 0
assert candidate('EEEE') == 2
# Check some edge cases th... | count_upper |
HumanEval/2067 |
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
... | from math import floor, ceil
if value.count('.') == 1:
# remove trailing zeros
while (value[-1] == '0'):
value = value[:-1]
num = float(value)
if value[-2:] == '.5':
if num > 0:
res = ceil(num)
else:
res = floor(num)
elif len(valu... | def check(candidate):
# Check some simple cases
assert candidate("10") == 10, "Test 1"
assert candidate("14.5") == 15, "Test 2"
assert candidate("-15.5") == -16, "Test 3"
assert candidate("15.3") == 15, "Test 3"
# Check some edge cases that are easy to work out by hand.
assert candidate("0... | closest_integer |
Portuguese version of HumanEval, a code generation benchmark with programming problems and test cases.
Translated using NLLB-200.
Original Dataset: https://huggingface.co/datasets/openai/openai_humaneval
Note: This dataset is machine translated and may contain translation errors or artifacts.
This dataset is provided as part of the AMALIA project and is included in AMALIA-Bench, a comprehensive benchmark suite for evaluating large language models on European Portuguese.
If you use this dataset or AMALIA in your work, please cite:
@inproceedings{simplicio-etal-2026-amalia,
title = "{AMALIA}: A Fully Open Large Language Model for {E}uropean {P}ortuguese",
author = "Simpl{{\'i}}cio, Afonso and Vinagre, Gon{{\c{{c}}}}alo and Ramos, Miguel Moura and Tavares, Diogo and Ferreira, Rafael and Attanasio, Giuseppe and Alves, Duarte M. and Calvo, In{{\^e}}s and Vieira, In{{\^e}}s and Guerra, Rui and Furtado, James and Canaverde, Beatriz and Paulo, Iago and Ramos, Vasco and Gl{{\'o}}ria-Silva, Diogo and Faria, Miguel and Treviso, Marcos and Gomes, Daniel and Gomes, Pedro and Semedo, David and Martins, Andr{{\'e}} and Magalh{{\~a}}es, Jo{{\~a}}o",
booktitle = "Proceedings of the 17th International Conference on Computational Processing of {{P}}ortuguese ({{PROPOR}} 2026) - Vol. 1",
month = apr,
year = "2026",
address = "Salvador, Brazil",
publisher = "Association for Computational Linguistics",
url = "https://aclanthology.org/2026.propor-1.38/",
pages = "380--391",
isbn = "979-8-89176-387-6"
}
@misc{simplicio2026amaliatechnicalreportfully,
title = {AMALIA Technical Report: A Fully Open Source Large Language Model for European Portuguese},
author = {Afonso Simplício and Gonçalo Vinagre and Miguel Moura Ramos and Diogo Tavares and Rafael Ferreira and Giuseppe Attanasio and Duarte M. Alves and Inês Calvo and Inês Vieira and Rui Guerra and James Furtado and Beatriz Canaverde and Iago Paulo and Vasco Ramos and Diogo Glória-Silva and Miguel Faria and Marcos Treviso and Daniel Gomes and Pedro Gomes and David Semedo and André Martins and João Magalhães},
year = {2026},
eprint = {2603.26511},
archivePrefix = {arXiv},
primaryClass = {cs.CL},
url = {https://arxiv.org/abs/2603.26511}
}