Dataset Viewer
task_id
stringlengths 14
16
| prompt
stringlengths 92
811
| entry_point
stringlengths 1
30
| canonical_solution
stringlengths 16
864
| test
stringlengths 117
1.8k
|
---|---|---|---|---|
KR_HumanEval/0
|
from typing import List
def has_close_elements(numbers: List[float], threshold: float) -> bool:
""" 주어진 숫자 목록에서 주어진 임계값보다 서로 가까운 두 숫자가 있는지 확인합니다.
>>> 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
"""
|
has_close_elements
|
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
|
METADATA = {
'author': 'jt',
'dataset': 'test'
}
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, 5.0, 2.0], 0.1) == True
assert candidate([1.1, 2.2, 3.1, 4.1, 5.1], 1.0) == True
assert candidate([1.1, 2.2, 3.1, 4.1, 5.1], 0.5) == False
|
KR_HumanEval/1
|
from typing import List
def separate_paren_groups(paren_string: str) -> List[str]:
""" 이 함수에 입력하는 문자열은 여러 개의 중첩된 괄호 그룹이 포함된 문자열입니다. 목표는 해당 그룹을
별도의 문자열로 분리하고 그 목록을 반환하는 것입니다.
각 그룹은 균형을 이루고(각 열린 중괄호가 올바르게 닫힘) 서로 중첩되지 않습니다.
입력 문자열의 공백은 무시합니다.
>>> separate_paren_groups('( ) (( ))) (( )( ))')
['()', '(())', '(()())']
"""
|
separate_paren_groups
|
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:
result.append(''.join(current_string))
current_string.clear()
return result
|
METADATA = {
'author': 'jt',
'dataset': 'test'
}
def check(candidate):
assert candidate('(()()) ((())) () ((())()())') == [
'(()())', '((()))', '()', '((())()())'
]
assert candidate('() (()) ((())) (((())))') == [
'()', '(())', '((()))', '(((())))'
]
assert candidate('(()(())((())))') == [
'(()(())((())))'
]
assert candidate('( ) (( )) (( )( ))') == ['()', '(())', '(()())']
|
KR_HumanEval/2
|
def truncate_number(number: float) -> float:
""" 양수 부동 소수점 숫자가 주어지면 정수 부분(주어진 숫자보다 큰 정수 부분)과
소수(항상 1보다 작은 남은 부분)으로 분해할 수 있습니다.
숫자의 소수 부분을 반환합니다.
>>> truncate_number(3.5)
0.5
"""
|
truncate_number
|
return number % 1.0
|
METADATA = {
'author': 'jt',
'dataset': 'test'
}
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
|
KR_HumanEval/3
|
from typing import List
def below_zero(operations: List[int]) -> bool:
""" 잔액이 0으로 시작하는 은행 계좌의 입출금 작업 목록이 주어집니다.
여러분의 임무는 어느 시점에서 계좌 잔액이 0 이하로 떨어지는지 감지하는 것이며,
그 시점에서 함수는 참을 반환해야 합니다. 그렇지 않으면 False를 반환해야 합니다.
>>> below_zero([1, 2, 3])
False
>>> below_zero([1, 2, -4, 5])
True
"""
|
below_zero
|
balance = 0
for op in operations:
balance += op
if balance < 0:
return True
return False
|
METADATA = {
'author': 'jt',
'dataset': 'test'
}
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, -4]) == True
|
KR_HumanEval/4
|
from typing import List
def mean_absolute_deviation(numbers: List[float]) -> float:
""" 주어진 입력 숫자 목록에 대해 이 데이터 집합의 평균을 중심으로 평균 절대 편차 (MAD)를 계산합니다.
평균 절대 편차는 각 요소와 중심점 사이의 평균 절대 차이입니다 (이 경우 평균).
MAD = 평균 | x - x_평균 |
>>> mean_absolute_deviation([1.0, 2.0, 3.0, 4.0])
1.0
"""
|
mean_absolute_deviation
|
mean = sum(numbers) / len(numbers)
return sum(abs(x - mean) for x in numbers) / len(numbers)
|
METADATA = {
'author': 'jt',
'dataset': 'test'
}
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
|
KR_HumanEval/5
|
from typing import List
def intersperse(numbers: List[int], delimeter: int) -> List[int]:
""" 입력 목록 'numbers'의 연속된 두 요소 사이에 숫자 '구분 기호'를 삽입합니다.
>>> intersperse([], 4)
[]
>>> intersperse([1, 2, 3], 4)
[1, 4, 2, 4, 3]
"""
|
intersperse
|
if not numbers:
return []
result = []
for n in numbers[:-1]:
result.append(n)
result.append(delimeter)
result.append(numbers[-1])
return result
|
METADATA = {
'author': 'jt',
'dataset': 'test'
}
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]
|
KR_HumanEval/6
|
from typing import List
def parse_nested_parens(paren_string: str) -> List[int]:
""" 이 함수에 입력되는 문자열은 공백으로 구분된 중첩된 괄호의 여러 그룹을 나타냅니다.
각 그룹에 대해 괄호 중첩의 가장 깊은 수준을 출력합니다.
예를 들어 ((()())는 중첩 수준이 최대 2단계이고 ((()))는 3단계입니다.
>>> parse_nested_parens('(()()) ((())) () ((())()())')
[2, 3, 1, 3]
"""
|
parse_nested_parens
|
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.split(' ') if x]
|
METADATA = {
'author': 'jt',
'dataset': 'test'
}
def check(candidate):
assert candidate('(()()) ((())) () ((())()())') == [2, 3, 1, 3]
assert candidate('() (()) ((())) (((())))') == [1, 2, 3, 4]
assert candidate('(()(())((())))') == [4]
|
KR_HumanEval/7
|
from typing import List
def filter_by_substring(strings: List[str], substring: str) -> List[str]:
""" 주어진 부분 문자열을 포함하는 문자열에 대해서만 입력 문자열 목록을 필터링합니다.
>>> filter_by_substring([], 'a')
[]
>>> filter_by_substring(['abc', 'bacd', 'cde', 'array'], 'a')
['abc', 'bacd', 'array']
"""
|
filter_by_substring
|
return [x for x in strings if substring in x]
|
METADATA = {
'author': 'jt',
'dataset': 'test'
}
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', 'trumpet', 'prune', 'gruesome'], 'run') == ['grunt', 'prune']
|
KR_HumanEval/8
|
from typing import List, Tuple
def sum_product(numbers: List[int]) -> Tuple[int, int]:
""" 주어진 정수 목록에 대해 목록에 있는 모든 정수의 합계와 곱으로 구성된 튜플을 반환합니다.
빈 합계는 0이고 빈 곱은 1이어야 합니다.
>>> sum_product([])
(0, 1)
>>> sum_product([1, 2, 3, 4])
(10, 24)
"""
|
sum_product
|
sum_value = 0
prod_value = 1
for n in numbers:
sum_value += n
prod_value *= n
return sum_value, prod_value
|
METADATA = {
'author': 'jt',
'dataset': 'test'
}
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)
|
KR_HumanEval/9
|
from typing import List, Tuple
def rolling_max(numbers: List[int]) -> List[int]:
""" 주어진 정수 목록에서 시퀀스에서 주어진 순간까지 발견된 롤링 최대 요소의 목록을 생성합니다.
>>> rolling_max([1, 2, 3, 2, 3, 4, 2])
[1, 2, 3, 3, 3, 4, 4]
"""
|
rolling_max
|
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
|
METADATA = {
'author': 'jt',
'dataset': 'test'
}
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]
|
KR_HumanEval/10
|
def is_palindrome(string: str) -> bool:
""" 주어진 문자열이 팔린드롬인지 테스트"""
return string == string[::-1]
def make_palindrome(string: str) -> str:
""" 제공된 문자열로 시작하는 가장 짧은 팔린드롬을 구합니다.
알고리즘 아이디어는 간단합니다:
- 제공된 문자열의 가장 긴 접미사 중 팔린드롬인 접미사를 찾습니다.
- 팔린드롬 접미사 앞에 오는 문자열 접두사의 역방향 문자열 끝에 추가합니다.
>>> make_palindrome('')
''
>>> make_palindrome('cat')
'catac'
>>> make_palindrome('cata')
'catac'
"""
|
make_palindrome
|
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]
|
METADATA = {
'author': 'jt',
'dataset': 'test'
}
def check(candidate):
assert candidate('') == ''
assert candidate('x') == 'x'
assert candidate('xyz') == 'xyzyx'
assert candidate('xyx') == 'xyx'
assert candidate('jerry') == 'jerryrrej'
|
KR_HumanEval/11
|
from typing import List
def string_xor(a: str, b: str) -> str:
""" 입력은 1과 0으로만 구성된 두 개의 문자열 a와 b입니다.
이 입력에 대해 이진 XOR을 수행하고 결과를 문자열로 반환합니다.
>>> string_xor('010', '110')
'100'
"""
|
string_xor
|
def xor(i, j):
if i == j:
return '0'
else:
return '1'
return ''.join(xor(x, y) for x, y in zip(a, b))
|
METADATA = {
'author': 'jt',
'dataset': 'test'
}
def check(candidate):
assert candidate('111000', '101010') == '010010'
assert candidate('1', '1') == '0'
assert candidate('0101', '0000') == '0101'
|
KR_HumanEval/12
|
from typing import List, Optional
def longest(strings: List[str]) -> Optional[str]:
""" 문자열 목록 중 가장 긴 문자열을 반환합니다. 길이가 같은 문자열이 여러 개 있는 경우
첫 번째 문자열을 반환합니다. 입력 목록이 비어 있으면 None을 반환합니다.
>>> longest([])
>>> longest(['a', 'b', 'c'])
'a'
>>> longest(['a', 'bb', 'ccc'])
'ccc'
"""
|
longest
|
if not strings:
return None
maxlen = max(len(x) for x in strings)
for s in strings:
if len(s) == maxlen:
return s
|
METADATA = {
'author': 'jt',
'dataset': 'test'
}
def check(candidate):
assert candidate([]) == None
assert candidate(['x', 'y', 'z']) == 'x'
assert candidate(['x', 'yyy', 'zzzz', 'www', 'kkkk', 'abc']) == 'zzzz'
|
KR_HumanEval/13
|
def greatest_common_divisor(a: int, b: int) -> int:
""" 두 정수 a와 b의 최대공약수를 반환합니다.
>>> greatest_common_divisor(3, 5)
1
>>> greatest_common_divisor(25, 15)
5
"""
|
greatest_common_divisor
|
while b:
a, b = b, a % b
return a
|
METADATA = {
'author': 'jt',
'dataset': 'test'
}
def check(candidate):
assert candidate(3, 7) == 1
assert candidate(10, 15) == 5
assert candidate(49, 14) == 7
assert candidate(144, 60) == 12
|
KR_HumanEval/14
|
from typing import List
def all_prefixes(string: str) -> List[str]:
""" 입력 문자열의 가장 짧은 접두사부터 가장 긴 접두사까지 모든 접두사 목록을 반환합니다.
>>> all_prefixes('abc')
['a', 'ab', 'abc']
"""
|
all_prefixes
|
result = []
for i in range(len(string)):
result.append(string[:i+1])
return result
|
METADATA = {
'author': 'jt',
'dataset': 'test'
}
def check(candidate):
assert candidate('') == []
assert candidate('asdfgh') == ['a', 'as', 'asd', 'asdf', 'asdfg', 'asdfgh']
assert candidate('WWW') == ['W', 'WW', 'WWW']
|
KR_HumanEval/15
|
def string_sequence(n: int) -> str:
""" 0부터 n까지 공백으로 구분된 숫자가 포함된 문자열을 반환합니다.
>>> string_sequence(0)
'0'
>>> string_sequence(5)
'0 1 2 3 4 5'
"""
|
string_sequence
|
return ' '.join([str(x) for x in range(n + 1)])
|
METADATA = {
'author': 'jt',
'dataset': 'test'
}
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'
|
KR_HumanEval/16
|
def count_distinct_characters(string: str) -> int:
""" 문자열이 주어졌을 때, 대소문자 구분 없이 몇 개의 고유 문자로 구성되어 있는지 알아냅니다.
>>> count_distinct_characters('xyzXYZ')
3
>>> count_distinct_characters('Jerry')
4
"""
|
count_distinct_characters
|
return len(set(string.lower()))
|
METADATA = {
'author': 'jt',
'dataset': 'test'
}
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
|
KR_HumanEval/17
|
from typing import List
def parse_music(music_string: str) -> List[int]:
""" 이 함수에 입력되는 것은 음표를 특수 ASCII 형식으로 나타내는 문자열입니다.
여러분의 임무는 이 문자열을 구문 분석하여 각 음표가 몇 박자 동안 지속되는지에 해당하는 정수 목록을 반환하는 것입니다.
다음은 범례입니다:
'o' - 전체 음표, 4박자 지속
'o|' - 반음표, 2박자 지속
'.|' - 쿼터 음표, 한 박자 지속
>>> parse_music('o o| .| o| o| .| .| .| .| .| o o')
[4, 2, 1, 2, 2, 1, 1, 1, 1, 4, 4]
"""
|
parse_music
|
note_map = {'o': 4, 'o|': 2, '.|': 1}
return [note_map[x] for x in music_string.split(' ') if x]
|
METADATA = {
'author': 'jt',
'dataset': 'test'
}
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]
|
KR_HumanEval/18
|
def how_many_times(string: str, substring: str) -> int:
""" 주어진 부분 문자열이 원본 문자열에서 몇 번이나 발견될 수 있는지 구합니다. 겹치는 대소문자를 계산합니다.
>>> how_many_times('', 'a')
0
>>> how_many_times('aaa', 'a')
3
>>> how_many_times('aaaa', 'aa')
3
"""
|
how_many_times
|
times = 0
for i in range(len(string) - len(substring) + 1):
if string[i:i+len(substring)] == substring:
times += 1
return times
|
METADATA = {
'author': 'jt',
'dataset': 'test'
}
def check(candidate):
assert candidate('', 'x') == 0
assert candidate('xyxyxyx', 'x') == 4
assert candidate('cacacacac', 'cac') == 4
assert candidate('john doe', 'john') == 1
|
KR_HumanEval/19
|
from typing import List
def sort_numbers(numbers: str) -> str:
""" 입력은 'zero'부터 'nine'까지 공백으로 구분된 숫자 문자열입니다.
유효한 선택지는 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight' 및 'nine'입니다.
숫자가 가장 작은 것부터 가장 큰 것까지 정렬된 문자열을 반환합니다.
>>> sort_numbers('three one five')
'one three five'
"""
|
sort_numbers
|
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]))
|
METADATA = {
'author': 'jt',
'dataset': 'test'
}
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 two three four five six'
|
KR_HumanEval/20
|
from typing import List, Tuple
def find_closest_elements(numbers: List[float]) -> Tuple[float, float]:
""" 제공된 숫자 목록(길이가 2개 이상인)에서 서로 가장 가까운 숫자 두 개를 선택하여 반환하고
순서대로(작은 숫자, 큰 숫자) 반환합니다.
>>> 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)
"""
|
find_closest_elements
|
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]))
else:
new_distance = abs(elem - elem2)
if new_distance < distance:
distance = new_distance
closest_pair = tuple(sorted([elem, elem2]))
return closest_pair
|
METADATA = {
'author': 'jt',
'dataset': 'test'
}
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, 4.1, 5.1]) == (2.2, 3.1)
|
KR_HumanEval/21
|
from typing import List
def rescale_to_unit(numbers: List[float]) -> List[float]:
""" 두 개 이상의 요소로 구성된 숫자 목록이 주어지면 해당 목록에 선형 변환을 적용합니다,
가장 작은 숫자가 0이 되고 가장 큰 숫자가 1이 되도록 선형 변환을 적용합니다.
>>> rescale_to_unit([1.0, 2.0, 3.0, 4.0, 5.0])
[0.0, 0.25, 0.5, 0.75, 1.0]
"""
|
rescale_to_unit
|
min_number = min(numbers)
max_number = max(numbers)
return [(x - min_number) / (max_number - min_number) for x in numbers]
|
METADATA = {
'author': 'jt',
'dataset': 'test'
}
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.0, 14.0]) == [0.25, 0.0, 1.0, 0.5, 0.75]
|
KR_HumanEval/22
|
from typing import List, Any
def filter_integers(values: List[Any]) -> List[int]:
""" 정수에 대해서만 파이썬 값의 주어진 목록을 필터링합니다.
>>> filter_integers(['a', 3.14, 5])
[5]
>>> filter_integers([1, 2, 3, 'abc', {}, []])
[1, 2, 3]
"""
|
filter_integers
|
return [x for x in values if isinstance(x, int)]
|
METADATA = {
'author': 'jt',
'dataset': 'test'
}
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]
|
KR_HumanEval/23
|
def strlen(string: str) -> int:
""" 주어진 문자열의 길이를 반환합니다.
>>> strlen('')
0
>>> strlen('abc')
3
"""
|
strlen
|
return len(string)
|
METADATA = {
'author': 'jt',
'dataset': 'test'
}
def check(candidate):
assert candidate('') == 0
assert candidate('x') == 1
assert candidate('asdasnakj') == 9
|
KR_HumanEval/24
|
def largest_divisor(n: int) -> int:
""" 주어진 숫자 n에 대해, n보다 작은 n을 균등하게 나누는 가장 큰 수를 구합니다.
>>> largest_divisor(15)
5
"""
|
largest_divisor
|
for i in reversed(range(n)):
if n % i == 0:
return i
|
METADATA = {
'author': 'jt',
'dataset': 'test'
}
def check(candidate):
assert candidate(3) == 1
assert candidate(7) == 1
assert candidate(10) == 5
assert candidate(100) == 50
assert candidate(49) == 7
|
KR_HumanEval/25
|
from typing import List
def factorize(n: int) -> List[int]:
""" 주어진 정수의 소인수 목록을 가장 작은 것부터 가장 큰 것 순서로 반환합니다.
각 소인수는 인수분해에서 나타나는 횟수에 해당하는 횟수만큼 나열되어야 합니다.
입력된 숫자는 모든 소인수의 곱과 같아야 합니다.
>>> factorize(8)
[2, 2, 2]
>>> factorize(25)
[5, 5]
>>> factorize(70)
[2, 5, 7]
"""
|
factorize
|
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
|
METADATA = {
'author': 'jt',
'dataset': 'test'
}
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 * 19 * 19) == [3, 19, 19, 19]
assert candidate(3 * 2 * 3) == [2, 3, 3]
|
KR_HumanEval/26
|
from typing import List
def remove_duplicates(numbers: List[int]) -> List[int]:
""" 정수 목록에서 두 번 이상 나타나는 요소를 모두 제거합니다.
요소의 순서는 입력과 동일하게 유지합니다.
>>> remove_duplicates([1, 2, 3, 2, 4])
[1, 3, 4]
"""
|
remove_duplicates
|
import collections
c = collections.Counter(numbers)
return [n for n in numbers if c[n] <= 1]
|
METADATA = {
'author': 'jt',
'dataset': 'test'
}
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]
|
KR_HumanEval/27
|
def flip_case(string: str) -> str:
""" 주어진 문자열에 대해 소문자를 대문자로, 대문자를 소문자로 뒤집습니다.
>>> flip_case('Hello')
'hELLO'
"""
|
flip_case
|
return string.swapcase()
|
METADATA = {
'author': 'jt',
'dataset': 'test'
}
def check(candidate):
assert candidate('') == ''
assert candidate('Hello!') == 'hELLO!'
assert candidate('These violent delights have violent ends') == 'tHESE VIOLENT DELIGHTS HAVE VIOLENT ENDS'
|
KR_HumanEval/28
|
from typing import List
def concatenate(strings: List[str]) -> str:
""" 문자열 목록을 하나의 문자열로 연결하기
>>> concatenate([])
''
>>> concatenate(['a', 'b', 'c'])
'abc'
"""
|
concatenate
|
return ''.join(strings)
|
METADATA = {
'author': 'jt',
'dataset': 'test'
}
def check(candidate):
assert candidate([]) == ''
assert candidate(['x', 'y', 'z']) == 'xyz'
assert candidate(['x', 'y', 'z', 'w', 'k']) == 'xyzwk'
|
KR_HumanEval/29
|
from typing import List
def filter_by_prefix(strings: List[str], prefix: str) -> List[str]:
""" 주어진 접두사로 시작하는 문자열에 대해서만 입력 문자열 목록을 필터링합니다.
>>> filter_by_prefix([], 'a')
[]
>>> filter_by_prefix(['abc', 'bcd', 'cde', 'array'], 'a')
['abc', 'array']]
"""
|
filter_by_prefix
|
return [x for x in strings if x.startswith(prefix)]
|
METADATA = {
'author': 'jt',
'dataset': 'test'
}
def check(candidate):
assert candidate([], 'john') == []
assert candidate(['xxx', 'asd', 'xxy', 'john doe', 'xxxAAA', 'xxx'], 'xxx') == ['xxx', 'xxxAAA', 'xxx']
|
KR_HumanEval/30
|
def get_positive(l: 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]
"""
|
get_positive
|
return [e for e in l if e > 0]
|
METADATA = {}
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([]) == []
|
KR_HumanEval/31
|
def is_prime(n):
"""주어진 숫자가 소수이면 참을 반환하고, 그렇지 않으면 거짓을 반환합니다.
>>> 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
"""
|
is_prime
|
if n < 2:
return False
for k in range(2, n - 1):
if n % k == 0:
return False
return True
|
METADATA = {}
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) == True
assert candidate(17) == True
assert candidate(5 * 17) == False
assert candidate(11 * 7) == False
assert candidate(13441 * 19) == False
|
KR_HumanEval/32
|
import math
def poly(xs: list, x: float):
"""
점 x에서 계수 xs를 가진 다항식을 평가합니다.
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는 다항식의 계수입니다.
find_zero는 poly(x) = 0이 되는 x를 찾습니다.
find_zero는 여러 개가 있어도 0점만 반환합니다.
또한 find_zero는 솔루션을 보장하기 때문에 계수가 짝수이고
0이 아닌 계수가 가장 큰 목록 xs만 받습니다.
>>> 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
"""
|
find_zero
|
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
|
METADATA = {}
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
coeffs.append(coeff)
solution = candidate(copy.deepcopy(coeffs))
assert math.fabs(poly(coeffs, solution)) < 1e-4
|
KR_HumanEval/33
|
def sort_third(l: list):
"""이 함수는 리스트 l을 받아, 3으로 나눌 수 없는 인디케이터의 값은 l과 동일하고
3으로 나눌 수 있는 인디케이터의 값은 l의 해당 인디케이터의 값과 같지만 정렬된 리스트 l' 을 반환합니다.
>>> sort_third([1, 2, 3])
[1, 2, 3]
>>> sort_third([5, 6, 3, 4, 8, 9, 2])
[2, 6, 3, 4, 8, 9, 5]
"""
|
sort_third
|
l = list(l)
l[::3] = sorted(l[::3])
return l
|
METADATA = {}
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, -12, 4, 23, 2, 3, 11, 12, -10]))
assert tuple(candidate([5, 6, 3, 4, 8, 9, 2])) == tuple([2, 6, 3, 4, 8, 9, 5])
assert tuple(candidate([5, 8, 3, 4, 6, 9, 2])) == tuple([2, 8, 3, 4, 6, 9, 5])
assert tuple(candidate([5, 6, 9, 4, 8, 3, 2])) == tuple([2, 6, 9, 4, 8, 3, 5])
assert tuple(candidate([5, 6, 3, 4, 8, 9, 2, 1])) == tuple([2, 6, 3, 4, 8, 9, 5, 1])
|
KR_HumanEval/34
|
def unique(l: list):
"""목록에서 정렬된 고유 엘리먼트 반환
>>> unique([5, 3, 5, 2, 3, 3, 9, 0, 123])
[0, 2, 3, 5, 9, 123]
"""
|
unique
|
return sorted(list(set(l)))
|
METADATA = {}
def check(candidate):
assert candidate([5, 3, 5, 2, 3, 3, 9, 0, 123]) == [0, 2, 3, 5, 9, 123]
|
KR_HumanEval/35
|
def max_element(l: list):
"""목록의 최대 요소를 반환합니다.
>>> max_element([1, 2, 3])
3
>>> max_element([5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10])
123
"""
|
max_element
|
m = l[0]
for e in l:
if e > m:
m = e
return m
|
METADATA = {}
def check(candidate):
assert candidate([1, 2, 3]) == 3
assert candidate([5, 3, -5, 2, -3, 3, 9, 0, 124, 1, -10]) == 124
|
KR_HumanEval/36
|
def fizz_buzz(n: int):
"""숫자 7이 11 또는 13으로 나눌 수 있는 n보다 작은 정수로 나타나는 횟수를 반환합니다.
>>> fizz_buzz(50)
0
>>> fizz_buzz(78)
2
>>> fizz_buzz(79)
3
"""
|
fizz_buzz
|
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
|
METADATA = {}
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
|
KR_HumanEval/37
|
def sort_even(l: list):
"""이 함수는 목록 l을 받아, 홀수 표시에서는 l과 동일하고
짝수 표시에서는 l의 짝수 표시 값과 같지만 정렬된 목록 l'을 반환합니다.
>>> sort_even([1, 2, 3])
[1, 2, 3]
>>> sort_even([5, 6, 3, 4])
[3, 6, 5, 4]
"""
|
sort_even
|
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
|
METADATA = {}
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])
|
KR_HumanEval/38
|
def encode_cyclic(s: str):
"""
세 개의 문자 그룹을 순환하여 인코딩된 문자열을 반환합니다.
"""
# 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):
"""
함수는 encode_cyclic 함수로 인코딩된 입력 문자열을 받습니다. 디코딩된 문자열을 반환합니다.
"""
|
decode_cyclic
|
return encode_cyclic(encode_cyclic(s))
|
METADATA = {}
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
|
KR_HumanEval/39
|
def prime_fib(n: int):
"""
prime_fib는 피보나치수인 n 번째 숫자를 반환하며, 이 숫자도 소수입니다.
>>> prime_fib(1)
2
>>> prime_fib(2)
3
>>> prime_fib(3)
5
>>> prime_fib(4)
13
>>> prime_fib(5)
89
"""
|
prime_fib
|
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]):
n -= 1
if n == 0:
return f[-1]
|
METADATA = {}
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(10) == 433494437
|
KR_HumanEval/40
|
def triples_sum_to_zero(l: list):
"""
정수 목록을 입력으로 받습니다.
목록에 합이 0인 별개의 요소가 세 개 있으면 True를 반환하고,
그렇지 않으면 False를 반환합니다.
>>> 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
"""
|
triples_sum_to_zero
|
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
|
METADATA = {}
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]) == False
assert candidate([1, 3, 5, -100]) == False
assert candidate([100, 3, 5, -100]) == False
|
KR_HumanEval/41
|
def car_race_collision(n: int):
"""
완벽하게 직선인 무한히 긴 도로를 상상해 보세요.
N대의 자동차가 왼쪽에서 오른쪽으로 주행하고 있고, 동시에 또 다른 N대의 자동차가
가 오른쪽에서 왼쪽으로 주행하고 있습니다. 두 세트의 자동차는 서로 매우 멀리 떨어져 있습니다.
서로 멀리 떨어져 있습니다. 모든 자동차는 같은 속도로 움직입니다. 두 대의 자동차가 충돌한다고 합니다.
왼쪽에서 오른쪽으로 이동하는 차가 오른쪽에서 왼쪽으로 이동하는 차에 부딪히면 충돌이라고 합니다.
하지만 자동차는 무한히 튼튼하고 강하기 때문에, 그 결과 두 자동차는 마치
마치 충돌하지 않은 것처럼 궤적을 따라 계속 움직입니다.
이 함수는 이러한 충돌 횟수를 출력합니다.
"""
|
car_race_collision
|
return n**2
|
METADATA = {}
def check(candidate):
assert candidate(2) == 4
assert candidate(3) == 9
assert candidate(4) == 16
assert candidate(8) == 64
assert candidate(10) == 100
|
KR_HumanEval/42
|
def incr_list(l: list):
"""요소가 1씩 증가된 목록을 반환합니다.
>>> incr_list([1, 2, 3])
[2, 3, 4]
>>> incr_list([5, 3, 5, 2, 3, 3, 3, 9, 0, 123])
[6, 4, 6, 3, 4, 4, 10, 1, 124]
"""
|
incr_list
|
return [(e + 1) for e in l]
|
METADATA = {}
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]
|
KR_HumanEval/43
|
def pairs_sum_to_zero(l):
"""
pairs_sum_to_zero는 정수 목록을 입력으로 받습니다.
목록에 합이 0이 되는 별개의 요소가 두 개 있으면 True를 반환하고,
그렇지 않으면 False를 반환합니다.
>>> 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
"""
|
pairs_sum_to_zero
|
for i, l1 in enumerate(l):
for j in range(i + 1, len(l)):
if l1 + l[j] == 0:
return True
return False
|
METADATA = {}
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, -1, 3, 2, 31]) == True
assert candidate([-3, 9, -1, 4, 2, 30]) == False
assert candidate([-3, 9, -1, 4, 2, 31]) == False
|
KR_HumanEval/44
|
def change_base(x: int, base: int):
"""입력 숫자 x를 주어진 진법으로 변경합니다.
변환 후 문자열 표현을 반환합니다. 진법 숫자는 10보다 작습니다.
>>> change_base(8, 3)
'22'
>>> change_base(8, 2)
'1000'
>>> change_base(7, 2)
'111'
"""
|
change_base
|
ret = ""
while x > 0:
ret = str(x % base) + ret
x //= base
return ret
|
METADATA = {}
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)
|
KR_HumanEval/45
|
def triangle_area(a, h):
"""한 변의 길이와 높이가 주어지면 삼각형의 넓이를 반환합니다.
>>> triangle_area(5, 3)
7.5
"""
|
triangle_area
|
return a * h / 2.0
|
METADATA = {}
def check(candidate):
assert candidate(5, 3) == 7.5
assert candidate(2, 2) == 2.0
assert candidate(10, 8) == 40.0
|
KR_HumanEval/46
|
def fib4(n: int):
"""Fib4 수열은 피보나치 수열과 유사한 수열로 다음과 같이 정의됩니다:
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).
fib4 숫자 시퀀스의 n번째 요소를 효율적으로 계산하는 함수를 작성하세요. 재귀를 사용하지 마세요.
>>> fib4(5)
4
>>> fib4(6)
8
>>> fib4(7)
14
"""
|
fib4
|
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]
|
METADATA = {}
def check(candidate):
assert candidate(5) == 4
assert candidate(8) == 28
assert candidate(10) == 104
assert candidate(12) == 386
|
KR_HumanEval/47
|
def median(l: list):
"""목록에 있는 요소의 중앙값을 반환합니다.
>>> median([3, 1, 2, 4, 5])
3
>>> median([-10, 4, 6, 1000, 10, 20])
15.0
"""
|
median
|
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
|
METADATA = {}
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
|
KR_HumanEval/48
|
def is_palindrome(text: str):
"""
주어진 문자열이 팔린드롬인지 확인합니다.
>>> is_palindrome('')
True
>>> is_palindrome('aba')
True
>>> is_palindrome('aaaaa')
True
>>> is_palindrome('zbcd')
False
"""
|
is_palindrome
|
for i in range(len(text)):
if text[i] != text[len(text) - 1 - i]:
return False
return True
|
METADATA = {}
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
|
KR_HumanEval/49
|
def modp(n: int, p: int):
"""2^n 모듈로 p를 반환합니다 (숫자에 유의하세요).
>>> modp(3, 5)
3
>>> modp(1101, 101)
2
>>> modp(0, 101)
1
3 >>> modp(3, 11)
8
>>> modp(100, 101)
1
"""
|
modp
|
ret = 1
for i in range(n):
ret = (2 * ret) % p
return ret
|
METADATA = {}
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
|
KR_HumanEval/50
|
def encode_shift(s: str):
"""
모든 문자를 알파벳에서 5씩 이동하여 인코딩된 문자열을 반환합니다.
"""
return "".join([chr(((ord(ch) + 5 - ord("a")) % 26) + ord("a")) for ch in s])
def decode_shift(s: str):
"""
encode_shift 함수로 인코딩된 입력 문자열을 받습니다. 디코딩된 문자열을 반환합니다.
"""
|
decode_shift
|
return "".join([chr(((ord(ch) - 5 - ord("a")) % 26) + ord("a")) for ch in s])
|
METADATA = {}
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)) == str
|
KR_HumanEval/51
|
def remove_vowels(text):
"""
remove_vowels는 문자열을 받아 모음이 없는 문자열을 반환하는 함수입니다.
>>> remove_vowels('')
''
>>> remove_vowels("abcdef
ghijklm")
'bcdf
ghjklm'
>>> remove_vowels('abcdef')
'bcdf'
>>> remove_vowels('aaaaa')
''
>>> remove_vowels('aaBAA')
'B'
>>> remove_vowels('zbcd')
'zbcd'
"""
|
remove_vowels
|
return "".join([s for s in text if s.lower() not in ["a", "e", "i", "o", "u"]])
|
METADATA = {}
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'
|
KR_HumanEval/52
|
def below_threshold(l: list, t: int):
"""목록 l의 모든 숫자가 임계값 t보다 작으면 True를 반환합니다.
>>> below_threshold([1, 2, 4, 10], 100)
True
>>> below_threshold([1, 20, 4, 10], 5)
False
"""
|
below_threshold
|
for e in l:
if e >= t:
return False
return True
|
METADATA = {}
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)
|
KR_HumanEval/53
|
def add(x: int, y: int):
"""두 개의 숫자 x와 y를 더하기
>>> add(2, 3)
5
5 >>> add(5, 7)
12
"""
|
add
|
return x + y
|
METADATA = {}
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, y) == x + y
|
KR_HumanEval/54
|
def same_chars(s0: str, s1: str):
"""
두 단어의 문자가 같은지 확인합니다.
>>> same_chars('eabcdzzzz', 'dddzzzzzddeddabc')
True
>>> same_chars('abcd', 'dddddddabc')
True
>>> same_chars('dddddddabc', 'abcd')
True
true >>> same_chars('eabcd', 'dddddddabc')
False
>>> same_chars('abcd', 'dddddddabce')
False
>>> same_chars('eabcdzzzz', 'dddzzzzzddddabc')
False
"""
|
same_chars
|
return set(s0) == set(s1)
|
METADATA = {}
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('eabcdzzzz', 'dddzzzzzzzddddabc') == False
assert candidate('aabb', 'aaccc') == False
|
KR_HumanEval/55
|
def fib(n: int):
"""n번째 피보나치 수를 반환합니다.
>>> fib(10)
55
>>> fib(1)
1
>>> fib(8)
21
"""
|
fib
|
if n == 0:
return 0
if n == 1:
return 1
return fib(n - 1) + fib(n - 2)
|
METADATA = {}
def check(candidate):
assert candidate(10) == 55
assert candidate(1) == 1
assert candidate(8) == 21
assert candidate(11) == 89
assert candidate(12) == 144
|
KR_HumanEval/56
|
def correct_bracketing(brackets: str):
""" 괄호는 "<" 및 ">"의 문자열입니다.
모든 여는 대괄호에 해당하는 닫는 대괄호가 있으면 True를 반환합니다.
>>> correct_bracketing("<")
False
>>> correct_bracketing("<>")
True
>>> correct_bracketing("<<><>>")
True
>>> correct_bracketing("><<>")
False
"""
|
correct_bracketing
|
depth = 0
for b in brackets:
if b == "<":
depth += 1
else:
depth -= 1
if depth < 0:
return False
return depth == 0
|
METADATA = {}
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 candidate(">")
assert not candidate("<<>")
assert not candidate("<><><<><>><>><<>")
assert not candidate("<><><<><>><>>><>")
|
KR_HumanEval/57
|
def monotonic(l: list):
"""목록 요소가 단조롭게 증가하거나 감소하는 경우 True를 반환합니다.
>>> monotonic([1, 2, 4, 20])
True
>>> monotonic([1, 20, 4, 10])
False
>>> monotonic([4, 1, 0, -10])
True
"""
|
monotonic
|
if l == sorted(l) or l == sorted(l, reverse=True):
return True
return False
|
METADATA = {}
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, 2, 3, 4, 5, 60]) == True
assert candidate([9, 9, 9, 9]) == True
|
KR_HumanEval/58
|
def common(l1: list, l2: list):
"""두 목록에 대해 정렬된 고유 공통 요소를 반환합니다.
>>> 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]
"""
|
common
|
ret = set()
for e1 in l1:
for e2 in l2:
if e1 == e2:
ret.add(e1)
return sorted(list(ret))
|
METADATA = {}
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], []) == []
|
KR_HumanEval/59
|
def largest_prime_factor(n: int):
"""n의 최대 소인수를 반환합니다. n이 1보다 크고 소수가 아니라고 가정합니다.
>>> largest_prime_factor(13195)
29
>>> largest_prime_factor(2048)
2
"""
|
largest_prime_factor
|
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
|
METADATA = {}
def check(candidate):
assert candidate(15) == 5
assert candidate(27) == 3
assert candidate(63) == 7
assert candidate(330) == 11
assert candidate(13195) == 29
|
KR_HumanEval/60
|
def sum_to_n(n: int):
"""sum_to_n은 1부터 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
"""
|
sum_to_n
|
return sum(range(n + 1))
|
METADATA = {}
def check(candidate):
assert candidate(1) == 1
assert candidate(6) == 21
assert candidate(11) == 66
assert candidate(30) == 465
assert candidate(100) == 5050
|
KR_HumanEval/61
|
def correct_bracketing(brackets: str):
""" brackets는 “(” 와 “)”의 문자열입니다. 모든 여는 괄호에 해당하는 닫는 괄호가 있으면 True를 반환합니다.
>>> correct_bracketing("(")
False
>>> correct_bracketing("(")")
True
>>> correct_bracketing("((()())")
True
>>> correct_bracketing(")(()")
False
"""
|
correct_bracketing
|
depth = 0
for b in brackets:
if b == "(":
depth += 1
else:
depth -= 1
if depth < 0:
return False
return depth == 0
|
METADATA = {}
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 candidate(")")
assert not candidate("(()")
assert not candidate("()()(()())())(()")
assert not candidate("()()(()())()))()")
|
KR_HumanEval/62
|
def derivative(xs: list):
""" xs는 다항식의 계수를 나타냅니다.
xs[0] + xs[1] * x + xs[2] * x^2 + ....
이 다항식의 도함수를 같은 형식으로 반환합니다.
>>> derivative([3, 1, 2, 4, 5])
[1, 4, 12, 20]
>>> derivative([1, 2, 3])
[2, 6]
"""
|
derivative
|
return [(i * x) for i, x in enumerate(xs)][1:]
|
METADATA = {}
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]) == []
|
KR_HumanEval/63
|
def fibfib(n: int):
"""피보나치 수열은 다음과 같이 정의되는 피보나치 수열과 유사한 수열입니다:
fibfib(0) == 0
fibfib(1) == 0
fibfib(2) == 1
fibfib(n) == fibfib(n-1) + fibfib(n-2) + fibfib(n-3).
fibfib 수열의 n번째 원소를 효율적으로 계산하는 함수를 작성하세요.
>>> fibfib(1)
0
>>> fibfib(5)
4
>>> fibfib(8)
24
"""
|
fibfib
|
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)
|
METADATA = {}
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
|
KR_HumanEval/64
|
FIX = """
테스트 사례를 더 추가하세요.
"""
def vowels_count(s):
"""단어를 나타내는 문자열을 입력으로 받아
문자열에 있는 모음의 수를 반환하는 함수 vowels_count를 작성합니다.
이 경우 모음은 'a', 'e', 'i', 'o', 'u'입니다.
여기서 'y'도 모음이지만 주어진 단어의 끝에 있는 경우에만 모음이 됩니다.
Example:
>>> vowels_count("abcde")
2
>>> vowels_count("ACEDY")
3
"""
|
vowels_count
|
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"
assert candidate("ACEDY") == 3, "Test 7"
# Check some edge cases that are easy to work out by hand.
assert True, "This prints if this assert fails 2 (also good for debugging!)"
|
KR_HumanEval/65
|
def circular_shift(x, shift):
"""정수 x의 자릿수를 원형 시프트하고, 시프트만큼 오른쪽으로 자릿수를 시프트한 다음 결과를 문자열로 반환합니다.
시프트 > 자릿수인 경우 자릿수를 반대로 반환합니다.
>>> circular_shift(12, 1)
"21"
>>> circular_shift(12, 2)
"12"
"""
|
circular_shift
|
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 hand.
assert candidate(11, 101) == "11", "This prints if this assert fails 2 (also good for debugging!)"
|
KR_HumanEval/66
|
def digitSum(s):
"""과제
문자열을 입력으로 받아 상위 문자만 ASCII 코드의 합을 반환하는 함수를 작성합니다.
예제
digitSum("") => 0
digitSum("abAB") => 131
digitSum("abcCd") => 67
digitSum("helloE") => 69
digitSum("woArBld") => 131
digitSum("aAaaaXa") => 153
"""
|
digitSum
|
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 candidate("woArBld") == 131, "Error"
assert candidate("aAaaaXa") == 153, "Error"
# Check some edge cases that are easy to work out by hand.
assert True, "This prints if this assert fails 2 (also good for debugging!)"
assert candidate(" How are yOu?") == 151, "Error"
assert candidate("You arE Very Smart") == 327, "Error"
|
KR_HumanEval/67
|
def fruit_distribution(s,n):
"""
이 문제에서는 과일 바구니에 들어 있는 사과와 오렌지의 개수를 나타내는 문자열이 주어집니다.
이 바구니에는 사과, 오렌지, 망고 과일이 들어 있습니다.
오렌지와 사과의 총 개수를 나타내는 문자열과 바구니에 있는 과일의 총 개수를 나타내는 정수가 주어지면
바구니에 있는 망고 과일의 개수를 반환합니다.
예를 들어:
fruit_distribution("사과 5개, 오렌지 6개", 19) ->19 - 5 - 6 = 8
fruit_distribution("사과 0개, 오렌지 1개",3) -> 3 - 0 - 1 = 2
fruit_distribution("사과 2개와 오렌지 3개", 100) -> 100 - 2 - 3 = 95
fruit_distribution("사과 100개와 오렌지 1개",120) -> 120 - 100 - 1 = 19
"""
|
fruit_distribution
|
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",100) == 95
assert candidate("2 apples and 3 oranges",5) == 0
assert candidate("1 apples and 100 oranges",120) == 19
|
KR_HumanEval/68
|
def pluck(arr):
"""
"음수가 아닌 정수 노드가 있는 트리의 가지를 나타내는 배열이 주어졌을 때,
노드 중 하나를 뽑아 반환하는 것이 과제입니다.
뽑은 노드는 가장 작은 짝수 값을 가진 노드여야 합니다.
동일한 최소 짝수 값을 가진 노드가 여러 개 발견되면 가장 작은 인덱스를 가진 노드를 반환합니다.
뽑은 노드는 [smalest_value, 해당 인덱스]라는 목록으로 반환되어야 합니다,
짝수 값이 없거나 주어진 배열이 비어 있으면 []를 반환합니다.
예제 1:
Input: [4,2,3]
Output: [2, 1]
설명: 2는 짝수값이 가장 작고, 2는 인덱스가 가장 작습니다.
예제 2:
입력: [1,2,3]
출력: [2, 1]
설명: 2는 짝수 값이 가장 작고, 2는 인덱스가 가장 작습니다.
예제 3:
입력: []
Output: []
예제 4:
입력 [5, 0, 3, 0, 4, 2]
Output: [0, 1]
설명: 0이 가장 작은 값이지만 0이 두 개 있습니다,
따라서 인덱스가 가장 작은 첫 번째 0을 선택합니다.
제약 조건:
* 1 <= nodes.length <= 10000
* 0 <= node.value
"""
|
pluck
|
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], "Error"
# Check some edge cases that are easy to work out by hand.
assert True, "This prints if this assert fails 2 (also good for debugging!)"
assert candidate([1, 2, 3, 0, 5, 3]) == [0, 3], "Error"
assert candidate([5, 4, 8, 4 ,8]) == [4, 1], "Error"
assert candidate([7, 6, 7, 1]) == [6, 1], "Error"
assert candidate([7, 9, 7, 1]) == [], "Error"
|
KR_HumanEval/69
|
def search(lst):
"""
비어 있지 않은 양의 정수 목록이 주어집니다.
0보다 크고 정수 자체의 값보다 크거나 같은 빈도를 갖는 가장 큰 정수를 반환합니다.
정수의 빈도는 목록에 나타나는 횟수입니다.
그러한 값이 존재하지 않으면 -1을 반환합니다.
예제
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
"""
|
search
|
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 candidate([2, 7, 8, 8, 4, 8, 7, 3, 9, 6, 5, 10, 4, 3, 6, 7, 1, 7, 4, 10, 8, 1]) == 1
assert candidate([3, 2, 8, 2]) == 2
assert candidate([6, 7, 1, 8, 8, 10, 5, 8, 5, 3, 10]) == 1
assert candidate([8, 8, 3, 6, 5, 6, 4]) == -1
assert candidate([6, 9, 6, 7, 1, 4, 7, 1, 8, 8, 9, 8, 10, 10, 8, 4, 10, 4, 10, 1, 2, 9, 5, 7, 9]) == 1
assert candidate([1, 9, 10, 1, 3]) == 1
assert candidate([6, 9, 7, 5, 8, 7, 5, 3, 7, 5, 10, 10, 3, 6, 10, 2, 8, 6, 5, 4, 9, 5, 3, 10]) == 5
assert candidate([1]) == 1
assert candidate([8, 8, 10, 6, 4, 3, 5, 8, 2, 4, 2, 8, 4, 6, 10, 4, 2, 1, 10, 2, 1, 1, 5]) == 4
assert candidate([2, 10, 4, 8, 2, 10, 5, 1, 2, 9, 5, 5, 6, 3, 8, 6, 4, 10]) == 2
assert candidate([1, 6, 10, 1, 6, 9, 10, 8, 6, 8, 7, 3]) == 1
assert candidate([9, 2, 4, 1, 5, 1, 5, 2, 5, 7, 7, 7, 3, 10, 1, 5, 4, 2, 8, 4, 1, 9, 10, 7, 10, 2, 8, 10, 9, 4]) == 4
assert candidate([2, 6, 4, 2, 8, 7, 5, 6, 4, 10, 4, 6, 3, 7, 8, 8, 3, 1, 4, 2, 2, 10, 7]) == 4
assert candidate([9, 8, 6, 10, 2, 6, 10, 2, 7, 8, 10, 3, 8, 2, 6, 2, 3, 1]) == 2
assert candidate([5, 5, 3, 9, 5, 6, 3, 2, 8, 5, 6, 10, 10, 6, 8, 4, 10, 7, 7, 10, 8]) == -1
assert candidate([10]) == -1
assert candidate([9, 7, 7, 2, 4, 7, 2, 10, 9, 7, 5, 7, 2]) == 2
assert candidate([5, 4, 10, 2, 1, 1, 10, 3, 6, 1, 8]) == 1
assert candidate([7, 9, 9, 9, 3, 4, 1, 5, 9, 1, 2, 1, 1, 10, 7, 5, 6, 7, 6, 7, 7, 6]) == 1
assert candidate([3, 10, 10, 9, 2]) == -1
|
KR_HumanEval/70
|
def strange_sort_list(lst):
"""
정수 목록이 주어지면 이상한 순서로 목록을 반환합니다.
이상한 정렬은 최소값부터 시작해서 나머지 정수의 최대값,
나머지 정수의 최대값, 최소값 순으로 정렬하는 것을 말합니다.
예시
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([]) == []
"""
|
strange_sort_list
|
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]) == [5, 5, 5, 5]
assert candidate([]) == []
assert candidate([1,2,3,4,5,6,7,8]) == [1, 8, 2, 7, 3, 6, 4, 5]
assert candidate([0,2,2,2,5,5,-5,-5]) == [-5, 5, -5, 5, 0, 2, 2, 2]
assert candidate([111111]) == [111111]
# Check some edge cases that are easy to work out by hand.
assert True
|
KR_HumanEval/71
|
def triangle_area(a, b, c):
"""
삼각형의 세 변의 길이가 주어집니다.
세 변이 유효한 삼각형을 형성하면 소수점 이하 2자리로 반올림한 삼각형의 면적을 반환합니다.
그렇지 않으면 -1을 반환합니다.
두 변의 합이 세 번째 변보다 클 때 유효한 삼각형이 됩니다.
예시:
triangle_area(3, 4, 5) == 6.00
triangle_area(1, 2, 10) == -1
"""
|
triangle_area
|
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(10, 5, 7) == 16.25
assert candidate(2, 6, 3) == -1
# Check some edge cases that are easy to work out by hand.
assert candidate(1, 1, 1) == 0.43, "This prints if this assert fails 2 (also good for debugging!)"
assert candidate(2, 2, 10) == -1
|
KR_HumanEval/72
|
def will_it_fly(q,w):
"""
물체 q가 날아갈 경우 True를 반환하고, 그렇지 않으면 False를 반환하는 함수를 작성합니다.
객체 q는 균형이 잡혀 있고(팔린드로믹 리스트) 그 요소의 합이 가능한 최대 가중치 w보다 작거나 같으면 날아갑니다.
예시:
will_it_fly([1, 2], 5) ➞ False
# 1+2가 가능한 최대 가중치보다 작지만 불균형입니다.
will_it_fly([3, 2, 3], 1) ➞ False
# 균형은 맞지만 3+2+3이 가능한 최대 가중치보다 큽니다.
will_it_fly([3, 2, 3], 9) ➞ True
# 3+2+3이 가능한 최대 가중치보다 작으며, 균형이 맞습니다.
will_it_fly([3], 5) ➞ True
# 3이 가능한 최대 가중치보다 작으며 균형이 맞습니다.
"""
|
will_it_fly
|
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 False
assert candidate([5], 5) is True
|
KR_HumanEval/73
|
def smallest_change(arr):
"""
정수의 배열 배열이 주어졌을 때, 배열을 팔린드롬 배열로 만들기 위해 변경해야 하는 최소 원소 수를 구합니다.
팔린드로믹 배열은 앞뒤로 똑같이 읽히는 배열입니다. 한 번의 변경으로 한 요소를 다른 요소로 변경할 수 있습니다.
예를 들어
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
"""
|
smallest_change
|
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, 1]) == 0
assert candidate([3, 1, 1, 3]) == 0
assert candidate([1]) == 0
assert candidate([0, 1]) == 1
|
KR_HumanEval/74
|
def total_match(lst1, lst2):
"""
두 개의 문자열 목록을 받아들이고 다음과 같은 목록을 반환하는 함수를 작성합니다.
목록의 모든 문자열의 총 문자 수가 다른 목록보다 적은 목록을 반환하는 함수를 작성합니다.
두 목록의 문자 수가 같으면 첫 번째 목록을 반환합니다.
예제
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']
"""
|
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']
assert candidate(['4'], ['1', '2', '3', '4', '5']) == ['4']
assert candidate(['hi', 'admin'], ['hI', 'Hi']) == ['hI', 'Hi']
assert candidate(['hi', 'admin'], ['hI', 'hi', 'hi']) == ['hI', 'hi', 'hi']
assert candidate(['hi', 'admin'], ['hI', 'hi', 'hii']) == ['hi', 'admin']
# Check some edge cases that are easy to work out by hand.
assert True, "This prints if this assert fails 2 (also good for debugging!)"
assert candidate([], ['this']) == []
assert candidate(['this'], []) == []
|
KR_HumanEval/75
|
def is_multiply_prime(a):
"""주어진 숫자가 소수 3의 곱이면 참을 반환하고 그렇지 않으면 거짓을 반환하는 함수를 작성합니다.
(a)가 100보다 작다는 것을 알고 있습니다.
예제
is_multiply_prime(30) == True
30 = 2 * 3 * 5
"""
|
is_multiply_prime
|
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 is_prime(k): continue
if i*j*k == a: return True
return False
|
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
assert candidate(11 * 9 * 9) == False
assert candidate(11 * 13 * 7) == True
|
KR_HumanEval/76
|
def is_simple_power(x, n):
"""여러분의 과제는 숫자 x가 n의 거듭제곱인 경우 참을 반환하고 그 외의 경우에는 거짓을 반환하는 함수를 작성하는 것입니다.
n**int=x인 경우 x는 n의 거듭제곱입니다.
예를 들어
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
"""
|
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 (good for debugging!)"
assert candidate(9, 3)==True, "This prints if this assert fails 1 (good for debugging!)"
assert candidate(16, 4)==True, "This prints if this assert fails 1 (good for debugging!)"
assert candidate(24, 2)==False, "This prints if this assert fails 1 (good for debugging!)"
assert candidate(128, 4)==False, "This prints if this assert fails 1 (good for debugging!)"
assert candidate(12, 6)==False, "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, 1)==True, "This prints if this assert fails 2 (also good for debugging!)"
assert candidate(1, 12)==True, "This prints if this assert fails 2 (also good for debugging!)"
|
KR_HumanEval/77
|
def iscube(a):
"""
정수 a를 받아 이 정수가 어떤 정수의 세제곱인 경우 True를 반환하는 함수를 작성합니다.
참고: 입력이 항상 유효하다고 가정할 수 있습니다.
예시
iscube(1) ==> True
iscube(2) ==> False
iscube(-1) ==> True
iscube(64) ==> True
iscube(0) ==> True
iscube(180) ==> False
"""
|
iscube
|
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 test error: " + str(candidate(64))
assert candidate(180) == False, "Fifth test error: " + str(candidate(180))
assert candidate(1000) == True, "Sixth test error: " + str(candidate(1000))
# Check some edge cases that are easy to work out by hand.
assert candidate(0) == True, "1st edge test error: " + str(candidate(0))
assert candidate(1729) == False, "2nd edge test error: " + str(candidate(1728))
|
KR_HumanEval/78
|
def hex_key(num):
"""16진수를 문자열로 받아 소수인 16진수 자릿수를 세는 함수를 작성하라는 과제가 주어졌습니다
(소수 또는 소수는 두 개의 작은 자연수의 곱이 아닌 1보다 큰 자연수입니다).
16진수는 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F이며
소수는 2, 3, 5, 7, 11, 13, 17,...입니다.
따라서 2, 3, 5, 7, B(=소수 11), D(=소수 13)의 숫자를 결정해야 합니다.
참고: 입력이 항상 정확하거나 빈 문자열이라고 가정할 수 있습니다,
그리고, 기호 A,B,C,D,E,F는 항상 대문자입니다.
예시:
num = "AB"의 경우 출력은 1이어야 합니다.
num = "1077E"의 경우 출력은 2가 되어야 합니다.
num = "ABED1A33"의 경우 출력은 4가 되어야 합니다.
num = "123456789ABCDEF0"의 경우 출력은 6이 되어야 합니다.
num = "2020"의 경우 출력은 2가 되어야 합니다.
"""
|
hex_key
|
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"))
assert candidate("2020") == 2, "Fourth test error: " + str(candidate("2020"))
assert candidate("123456789ABCDEF0") == 6, "Fifth test error: " + str(candidate("123456789ABCDEF0"))
assert candidate("112233445566778899AABBCCDDEEFF00") == 12, "Sixth test error: " + str(candidate("112233445566778899AABBCCDDEEFF00"))
# Check some edge cases that are easy to work out by hand.
assert candidate([]) == 0
|
KR_HumanEval/79
|
def decimal_to_binary(decimal):
"""십진수 형식의 숫자가 주어지며, 이를 이진 형식으로 변환하는 것이 과제입니다.
이 함수는 각 문자가 이진수를 나타내는 문자열을 반환해야 합니다.
문자열의 각 문자는 '0' 또는 '1'이 됩니다.
문자열의 시작과 끝에 'db' 문자가 추가로 몇 개 더 있습니다.
추가 문자는 형식에 도움을 주기 위한 것입니다.
예시
decimal_to_binary(15) # "db1111db" 반환
decimal_to_binary(32) # "db100000db" 반환
"""
|
decimal_to_binary
|
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 work out by hand.
assert True, "This prints if this assert fails 2 (also good for debugging!)"
|
KR_HumanEval/80
|
def is_happy(s):
"""문자열 s가 주어집니다.
여러분의 임무는 문자열이 행복한지 아닌지를 확인하는 것입니다.
문자열의 길이가 3 이상이고 연속된 3개의 문자가 모두 구별되는 경우 문자열은 행복합니다.
예를 들어
is_happy(a) => False
is_happy(aa) => False
is_happy(abcd) => True
is_happy(aabb) => False
is_happy(adb) => True
is_happy(xyy) => False
"""
|
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"
assert candidate("iopaxpoi") == True , "iopaxpoi"
assert candidate("iopaxioi") == False , "iopaxioi"
|
KR_HumanEval/81
|
def numerical_letter_grade(grades):
"""학기 마지막 주이고 교사는 학생들에게 성적을 부여해야 합니다.
선생님은 채점을 위해 자신만의 알고리즘을 만들고 있습니다.
문제는 채점에 사용한 코드를 잃어버렸다는 것입니다.
선생님이 일부 학생의 성적 목록을 주셨는데, 이 학생의 성적을 출력할 수 있는 함수 다음 표를 사용하여
문자 성적 목록을 출력할 수 있는 함수를 작성해야 합니다:
GPA | 문자 성적
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
예시
grade_equation([4.0, 3, 1.7, 2, 3.5]) ==> ['A+', 'B', 'C-', 'C', 'A-']
"""
|
numerical_letter_grade
|
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:
letter_grade.append("B")
elif gpa > 2.3:
letter_grade.append("B-")
elif gpa > 2.0:
letter_grade.append("C+")
elif gpa > 1.7:
letter_grade.append("C")
elif gpa > 1.3:
letter_grade.append("C-")
elif gpa > 1.0:
letter_grade.append("D+")
elif gpa > 0.7:
letter_grade.append("D")
elif gpa > 0.0:
letter_grade.append("D-")
else:
letter_grade.append("E")
return letter_grade
|
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+']
assert candidate([0, 0.7]) == ['E', 'D-']
# Check some edge cases that are easy to work out by hand.
assert True
|
KR_HumanEval/82
|
def prime_length(string):
"""문자열을 받아 문자열 길이가 소수이면 True를 반환하고 그렇지 않으면 False를 반환하는 함수를 작성합니다.
예제
prime_length('Hello') == True
prime_length('abcdcba') == True
prime_length('kittens') == True
prime_length('orange') == False
"""
|
prime_length
|
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') == True
assert candidate('Wow') == True
assert candidate('') == False
assert candidate('HI') == True
assert candidate('go') == True
assert candidate('gogo') == False
assert candidate('aaaaaaaaaaaaaaa') == False
# Check some edge cases that are easy to work out by hand.
assert candidate('Madam') == True
assert candidate('M') == False
assert candidate('0') == False
|
KR_HumanEval/83
|
def starts_one_ends(n):
"""
양의 정수 n이 주어지면 1로 시작하거나 끝나는 n자리 양의 정수의 개수를 반환합니다.
"""
|
starts_one_ends
|
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 are easy to work out by hand.
assert True, "This prints if this assert fails 2 (also good for debugging!)"
|
KR_HumanEval/84
|
def solve(N):
"""양의 정수 N이 주어지면, 그 자릿수의 총합을 2진법으로 반환합니다.
예제
N = 1000의 경우 자릿수의 합계는 1이므로 출력은 "1"이 되어야 합니다.
N = 150의 경우 자릿수의 합계는 6이 되고 출력은 "110"이 됩니다.
N = 147의 경우 자릿수 합계는 12가 되고 출력은 "1100"이 되어야 합니다.
변수
@N 정수
제약 조건: 0 ≤ N ≤ 10000.
출력:
이진수 문자열
"""
|
solve
|
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 hand.
assert True, "This prints if this assert fails 2 (also good for debugging!)"
assert candidate(333) == "1001", "Error"
assert candidate(963) == "10010", "Error"
|
KR_HumanEval/85
|
def add(lst):
"""비어 있지 않은 정수 목록이 주어졌을 때 홀수 인덱스에 있는 짝수 요소를 더합니다.
예제
add([4, 2, 6, 7]) ==> 2
"""
|
add
|
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.
|
KR_HumanEval/86
|
def anti_shuffle(s):
"""
문자열을 받아 정렬된 버전을 반환하는 함수를 작성합니다.
정렬된 버전의 문자열은 공백으로 구분된 모든 단어가 ascii 값을 기준으로
오름차순으로 배열된 새로운 단어로 대체되는 문자열입니다.
참고: 문장에서 단어와 공백의 순서를 유지해야 합니다.
예를 들어
anti_shuffle('안녕')은 '안녕'을 반환합니다.
anti_shuffle('hello')는 'ehllo'를 반환합니다.
anti_shuffle('Hello World!!!')은 'Hello !!!Wdlor'를 반환합니다.
"""
|
anti_shuffle
|
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 candidate('Hi. My name is Mister Robot. How are you?') == '.Hi My aemn is Meirst .Rboot How aer ?ouy'
# Check some edge cases that are easy to work out by hand.
assert True
|
KR_HumanEval/87
|
def get_row(lst, x):
"""
2차원 데이터가 중첩된 목록으로 주어지는데,
행렬과 비슷하지만 행렬과 달리 각 행에 다른 수의 열이 포함될 수 있습니다.
lst와 정수 x가 주어지면 목록에서 정수 x를 구하고,
각 튜플이 0으로 시작하는 좌표 (행, 열)가 되도록 [(x1, y1), (x2, y2) ...]의 튜플 목록을 반환합니다.
좌표를 먼저 행을 기준으로 오름차순으로 정렬합니다.
또한 행의 좌표를 내림차순으로 열을 기준으로 정렬합니다.
예제
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)]
"""
|
get_row
|
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],
[1,2,3,4,5,6],
[1,2,3,4,5,6]
], 2) == [(0, 1), (1, 1), (2, 1), (3, 1), (4, 1), (5, 1)]
assert candidate([
[1,2,3,4,5,6],
[1,2,3,4,5,6],
[1,1,3,4,5,6],
[1,2,1,4,5,6],
[1,2,3,1,5,6],
[1,2,3,4,1,6],
[1,2,3,4,5,1]
], 1) == [(0, 0), (1, 0), (2, 1), (2, 0), (3, 2), (3, 0), (4, 3), (4, 0), (5, 4), (5, 0), (6, 5), (6, 0)]
assert candidate([], 1) == []
assert candidate([[1]], 2) == []
assert candidate([[], [1], [1, 2, 3]], 3) == [(2, 2)]
# Check some edge cases that are easy to work out by hand.
assert True
|
KR_HumanEval/88
|
def sort_array(array):
"""
음수가 아닌 정수의 배열이 주어지면 정렬 후 주어진 배열의 복사본을 반환하고,
합(첫 번째 인덱스 값, 마지막 인덱스 값)이 홀수이면 오름차순으로 정렬하고,
합(첫 번째 인덱스 값, 마지막 인덱스 값)이 짝수이면 내림차순으로 정렬합니다.
참고:
* 주어진 배열을 변경하지 마세요.
예시
* 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]
"""
|
sort_array
|
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, 5, 6]) == [6, 5, 4, 3, 2, 1, 0], "Error"
# Check some edge cases that are easy to work out by hand.
assert True, "This prints if this assert fails 2 (also good for debugging!)"
assert candidate([2, 1]) == [1, 2], "Error"
assert candidate([15, 42, 87, 32 ,11, 0]) == [0, 11, 15, 32, 42, 87], "Error"
assert candidate([21, 14, 23, 11]) == [23, 21, 14, 11], "Error"
|
KR_HumanEval/89
|
def encrypt(s):
"""문자열을 인수로 받고 회전 중인 알파벳으로 암호화된 문자열을 반환하는 함수 encrypt를 만듭니다.
알파벳은 문자가 2를 곱하여 두 자리 아래로 이동하는 방식으로 회전해야 합니다.
예를 들어
encrypt('hi')는 'lm'을 반환합니다.
encrypt('asdfghjkl')는 'ewhjklnop'를 반환합니다.
encrypt('gf')는 'kj'를 반환합니다.
encrypt('et')는 'ix'를 반환합니다.
"""
|
encrypt
|
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 fails 1 (good for debugging!)"
assert candidate('et') == 'ix', "This prints if this assert fails 1 (good for debugging!)"
assert candidate('faewfawefaewg')=='jeiajeaijeiak', "This prints if this assert fails 1 (good for debugging!)"
assert candidate('hellomyfriend')=='lippsqcjvmirh', "This prints if this assert fails 2 (good for debugging!)"
assert candidate('dxzdlmnilfuhmilufhlihufnmlimnufhlimnufhfucufh')=='hbdhpqrmpjylqmpyjlpmlyjrqpmqryjlpmqryjljygyjl', "This prints if this assert fails 3 (good for debugging!)"
# Check some edge cases that are easy to work out by hand.
assert candidate('a')=='e', "This prints if this assert fails 2 (also good for debugging!)"
|
KR_HumanEval/90
|
def next_smallest(lst):
"""
정수의 목록이 주어집니다.
목록에서 두 번째로 작은 요소를 반환하는 next_smallest() 함수를 작성합니다.
그러한 요소가 없으면 None을 반환합니다.
next_smallest([1, 2, 3, 4, 5]) == 2
next_smallest([5, 1, 4, 3, 2]) == 2
next_smallest([]) == None
next_smallest([1, 1]) == None
"""
|
next_smallest
|
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, 12, -45]) == -35
# Check some edge cases that are easy to work out by hand.
assert True
|
KR_HumanEval/91
|
def is_bored(S):
"""
한 줄의 단어가 주어지고 지루함의 개수를 세는 것이 과제입니다.
지루함이란 “I”라는 단어로 시작하는 문장을 말합니다.
문장은 '.', '?' 또는 '!'로 구분됩니다.
예를 들어
>>> is_bored("Hello world")
0
>>> is_bored("하늘은 파랗고, 태양은 빛나고, 나는 이 날씨가 좋아요")
1
"""
|
is_bored
|
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. will kill It") == 2, "Test 5"
assert candidate("You and I are going for a walk") == 0, "Test 6"
# Check some edge cases that are easy to work out by hand.
assert True, "This prints if this assert fails 2 (also good for debugging!)"
|
KR_HumanEval/92
|
def any_int(x, y, z):
"""
3개의 숫자를 받는 함수를 만듭니다.
숫자 중 하나가 다른 두 숫자의 합과 같고 모든 숫자가 정수인 경우 참을 반환합니다.
그 외의 경우에는 거짓을 반환합니다.
예제
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
"""
|
any_int
|
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 fails 3 (good for debugging!)"
assert candidate(2, 6, 2)==False, "This prints if this assert fails 4 (good for debugging!)"
assert candidate(4, 2, 2)==True, "This prints if this assert fails 5 (good for debugging!)"
assert candidate(2.2, 2.2, 2.2)==False, "This prints if this assert fails 6 (good for debugging!)"
assert candidate(-4, 6, 2)==True, "This prints if this assert fails 7 (good for debugging!)"
# Check some edge cases that are easy to work out by hand.
assert candidate(2,1,1)==True, "This prints if this assert fails 8 (also good for debugging!)"
assert candidate(3,4,7)==True, "This prints if this assert fails 9 (also good for debugging!)"
assert candidate(3.0,4,7)==False, "This prints if this assert fails 10 (also good for debugging!)"
|
KR_HumanEval/93
|
def encode(message):
"""
메시지를 받아 모든 문자의 대소문자를 바꾸고,
메시지의 모든 모음을 영어 알파벳에서 해당 모음보다 2자리 앞에 나타나는 문자로 대체하는 방식으로
인코딩하는 함수를 작성하세요.
문자만 가정합니다.
예시
>>> encode('test')
'TGST'
>>> encode('This is a message')
'tHKS KS C MGSSCGG'
"""
|
encode
|
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 assert fails 3 (good for debugging!)"
# Check some edge cases that are easy to work out by hand.
assert candidate('This is a message') == 'tHKS KS C MGSSCGG', "This prints if this assert fails 2 (also good for debugging!)"
assert candidate("I DoNt KnOw WhAt tO WrItE") == 'k dQnT kNqW wHcT Tq wRkTg', "This prints if this assert fails 2 (also good for debugging!)"
|
KR_HumanEval/94
|
def skjkasdkd(lst):
"""정수 목록이 주어집니다.
가장 큰 소수를 구하고 그 자릿수의 합을 반환해야 합니다.
예시
lst = [0,3,2,1,3,5,7,4,5,5,5,2,181,32,4,32,3,2,32,324,4,3]의 경우 출력은 10이 되어야 합니다.
lst = [1,0,1,8,2,4597,2,1,3,40,1,2,1,2,4,2,5,1]의 경우 출력은 25가 되어야 합니다.
lst = [1,3,1,32,5107,34,83278,109,163,23,2323,32,30,1,9,3]의 경우 출력은 13이 되어야 합니다.
lst = [0,724,32,71,99,32,6,0,5,91,83,0,5,6]의 경우 출력은 11이 되어야 합니다.
lst = [0,81,12,3,1,21]의 경우 출력은 3이 되어야 합니다.
lst = [0,8,1,2,1,7]의 경우 출력은 7이 되어야 합니다.
"""
|
skjkasdkd
|
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))
return result
|
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]) == 25, "This prints if this assert fails 2 (also good for debugging!)"
# Check some edge cases that are easy to work out by hand.
assert candidate([1,3,1,32,5107,34,83278,109,163,23,2323,32,30,1,9,3]) == 13, "This prints if this assert fails 3 (also good for debugging!)"
# Check some edge cases that are easy to work out by hand.
assert candidate([0,724,32,71,99,32,6,0,5,91,83,0,5,6]) == 11, "This prints if this assert fails 4 (also good for debugging!)"
# Check some edge cases that are easy to work out by hand.
assert candidate([0,81,12,3,1,21]) == 3, "This prints if this assert fails 5 (also good for debugging!)"
# Check some edge cases that are easy to work out by hand.
assert candidate([0,8,1,2,1,7]) == 7, "This prints if this assert fails 6 (also good for debugging!)"
assert candidate([8191]) == 19, "This prints if this assert fails 7 (also good for debugging!)"
assert candidate([8191, 123456, 127, 7]) == 19, "This prints if this assert fails 8 (also good for debugging!)"
assert candidate([127, 97, 8192]) == 10, "This prints if this assert fails 9 (also good for debugging!)"
|
KR_HumanEval/95
|
def check_dict_case(dict):
"""
사전이 주어지면 모든 키가 소문자 문자열이거나 모든 키가 대문자 문자열이면 True를 반환하고,
그렇지 않으면 False를 반환합니다.
주어진 사전이 비어 있으면 이 함수는 False를 반환해야 합니다.
예제
check_dict_case({"a":"apple", "b":"banana"})는 True를 반환해야 합니다.
check_dict_case({"a":"apple", "A":"banana", "B":"banana"})는 False를 반환해야 합니다.
check_dict_case({"a":"apple", 8:"banana", "a":"apple"})는 False를 반환해야 합니다.
check_dict_case({"Name":"John","Age":"36","City":"Houston"})는 False를 반환해야 합니다.
check_dict_case({"STATE":"NC", "ZIP":"12345" })는 True를 반환해야 합니다.
"""
|
check_dict_case
|
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"
elif key.islower():
state = "lower"
else:
break
elif (state == "upper" and not key.isupper()) or (state == "lower" and not key.islower()):
state = "mixed"
break
else:
break
return state == "upper" or state == "lower"
|
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", "A":"banana", "B":"banana"}))
assert candidate({"p":"pineapple", 5:"banana", "a":"apple"}) == False, "Third test error: " + str(candidate({"p":"pineapple", 5:"banana", "a":"apple"}))
assert candidate({"Name":"John", "Age":"36", "City":"Houston"}) == False, "Fourth test error: " + str(candidate({"Name":"John", "Age":"36", "City":"Houston"}))
assert candidate({"STATE":"NC", "ZIP":"12345" }) == True, "Fifth test error: " + str(candidate({"STATE":"NC", "ZIP":"12345" }))
assert candidate({"fruit":"Orange", "taste":"Sweet" }) == True, "Fourth test error: " + str(candidate({"fruit":"Orange", "taste":"Sweet" }))
# Check some edge cases that are easy to work out by hand.
assert candidate({}) == False, "1st edge test error: " + str(candidate({}))
|
KR_HumanEval/96
|
def count_up_to(n):
"""음수가 아닌 정수를 받아 소수이고 n보다 작은 처음 n개의 정수의 배열을 반환하는 함수를 구현합니다.
예를 들어
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]
"""
|
count_up_to
|
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]
assert candidate(47) == [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43]
assert candidate(101) == [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
|
KR_HumanEval/97
|
def multiply(a, b):
"""두 정수를 받아 단위 자릿수의 곱을 반환하는 함수를 완성합니다.
입력이 항상 유효하다고 가정합니다.
예시:
multiply(148, 412)는 16을 반환해야 합니다.
multiply(19, 28)은 72를 반환해야 합니다.
multiply(2020, 1851)은 0을 반환해야 합니다.
multiply(14,-15)는 20을 반환해야 합니다.
"""
|
multiply
|
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(candidate(2020, 1851))
assert candidate(14,-15) == 20, "Fourth test error: " + str(candidate(14,-15))
assert candidate(76, 67) == 42, "Fifth test error: " + str(candidate(76, 67))
assert candidate(17, 27) == 49, "Sixth test error: " + str(candidate(17, 27))
# Check some edge cases that are easy to work out by hand.
assert candidate(0, 1) == 0, "1st edge test error: " + str(candidate(0, 1))
assert candidate(0, 0) == 0, "2nd edge test error: " + str(candidate(0, 0))
|
KR_HumanEval/98
|
def count_upper(s):
"""
문자열 s가 주어지면 짝수 인덱스에 있는 대문자 모음의 개수를 세어봅니다.
예를 들어
count_upper('aBCdEf')는 1을 반환합니다.
count_upper('abcdefg')는 0을 반환합니다.
count_upper('dBBE')는 0을 반환합니다.
"""
|
count_upper
|
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 that are easy to work out by hand.
assert True
|
KR_HumanEval/99
|
def closest_integer(value):
"""
숫자를 나타내는 값(문자열)을 받아 가장 가까운 정수를 반환하는 함수를 만듭니다.
숫자가 두 정수에서 동일한 거리에 있다면, 0에서 멀어지는 방향으로 반올림합니다.
예제
>>> closest_integer("10")
10
>>> closest_integer("15.3")
15
참고:
0에서 멀어지는 방향으로 반올림한다는 것은 주어진 숫자가 두 정수에서 거리가 같을 경우
0에서 가장 멀리 떨어진 정수를 숫자를 반환해야 한다는 뜻입니다.
예를 들어 closest_integer(“14.5”)는 15를 반환해야 하고 closest_integer(“-14.5”)는 -15를 반환해야 합니다.
"""
|
closest_integer
|
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(value) > 0:
res = int(round(num))
else:
res = 0
return res
|
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") == 0, "Test 0"
|
End of preview. Expand
in Data Studio
KR-HumanEval Benchmark
The Korean version of the HumanEval benchmark, where the original docstrings are translated into Korean.
- Used DeepL translator API for translation.
- Performed manual post-processing and LLM-based quality evaluation after translation.
- Data format and benchmark performance evaluation method are identical to those of HumanEval.
- Related Paper: KR-HumanEval을 활용한 언어 모델의 한국어 프로그램 합성 성능 분석 (HCLT 2024, best paper award)
Benchmark Version
- KR_HumanEval_v0.jsonl: original benchmark presented in the paper
- KR_HumanEval_v1.jsonl: original benchmark with improved translation, taking into account the programming context
- E.g., replace '목록' with '배열' and '원소' with '요소'.
Acknowledgement
- Downloads last month
- 20