imports
stringclasses
16 values
function1_signature
stringlengths
129
1.27k
function1_human
stringlengths
152
1.91k
function1_name
stringlengths
1
30
function2_signature
stringlengths
143
1.53k
function2_human
stringlengths
169
1.59k
function2_name
stringlengths
3
62
tests
stringlengths
164
1.07k
stop_tokens
sequencelengths
4
4
function1_docstring
stringlengths
66
1.13k
function2_docstring
stringlengths
82
1.36k
function1_implementation
stringlengths
17
858
function2_implementation
stringlengths
25
397
function1_declaration
stringlengths
18
97
function2_declaration
stringlengths
15
89
from typing import List
def has_close_elements(numbers: List[float], threshold: float) -> bool: """Check if in given list of numbers, are any two numbers closer to each other than given threshold. >>> has_close_elements([1.0, 2.0, 3.0], 0.5) False >>> has_close_elements([1.0, 2.8, 3.0, 4.0, 5.0, 2.0], 0.3) True """
def has_close_elements(numbers: List[float], threshold: float) -> bool: """Check if in given list of numbers, are any two numbers closer to each other than given threshold. >>> has_close_elements([1.0, 2.0, 3.0], 0.5) False >>> has_close_elements([1.0, 2.8, 3.0, 4.0, 5.0, 2.0], 0.3) True """ 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
has_close_elements
def has_close_elements_in_array(array: List[List[float]], threshold: float) -> bool: """Check if in given array, are any two numbers closer to each other than given threshold. >>> has_close_elements_in_array([[1.0, 2.0, 3.0], [1.0, 2.0, 3.0]], 0.5) True >>> has_close_elements_in_array([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]], 0.3) False """
def has_close_elements_in_array(array: List[List[float]], threshold: float) -> bool: """Check if in given array, are any two numbers closer to each other than given threshold. >>> has_close_elements_in_array([[1.0, 2.0, 3.0], [1.0, 2.0, 3.0]], 0.5) True >>> has_close_elements_in_array([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]], 0.3) False """ return has_close_elements([item for sublist in array for item in sublist], threshold)
has_close_elements_in_array
def check(candidate): assert candidate([[2.0, 3.0, 1.0], [100.0, 101.0, 17.8]], 2.2) is True assert candidate([[31.0, 22.7, 38.8], [34.8, 14.8, 22.5]], 0.5) is True assert candidate([[1.0, 2.1, 1.6], [2.4, 2.7, 1.3]], 0.2) is False def test_check(): check(has_close_elements_in_array) test_check()
[ "\ndef", "\n#", "\nif", "\nclass" ]
Check if in given list of numbers, are any two numbers closer to each other than given threshold. >>> has_close_elements([1.0, 2.0, 3.0], 0.5) False >>> has_close_elements([1.0, 2.8, 3.0, 4.0, 5.0, 2.0], 0.3) True
Check if in given array, are any two numbers closer to each other than given threshold. >>> has_close_elements_in_array([[1.0, 2.0, 3.0], [1.0, 2.0, 3.0]], 0.5) True >>> has_close_elements_in_array([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]], 0.3) False
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
return has_close_elements([item for sublist in array for item in sublist], threshold)
has_close_elements(numbers: List[float], threshold: float) -> bool
has_close_elements_in_array(array: List[List[float]], threshold: float) -> bool
from typing import Any, List
def separate_paren_groups(paren_string: str) -> List[str]: """Input to this function is a string containing multiple groups of nested parentheses. Your goal is to separate those group into separate strings and return the list of those. Separate groups are balanced (each open brace is properly closed) and not nested within each other Ignore any spaces in the input string. >>> separate_paren_groups('( ) (( )) (( )( ))') ['()', '(())', '(()())'] """
def separate_paren_groups(paren_string: str) -> List[str]: """Input to this function is a string containing multiple groups of nested parentheses. Your goal is to separate those group into separate strings and return the list of those. Separate groups are balanced (each open brace is properly closed) and not nested within each other Ignore any spaces in the input string. >>> separate_paren_groups('( ) (( )) (( )( ))') ['()', '(())', '(()())'] """ 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
separate_paren_groups
def nested_separate_paren_groups(paren_string: str) -> Any: """Input to this function is a string containing multiple groups of nested parentheses. Your goal is to separate those group into separate strings and return the list of those. Different from separate_paren_groups, you have to recursively separate a group into subgroups if it is nested. Separate groups are balanced (each open brace is properly closed) and nested within each other Ignore any spaces in the input string. >>> nested_separate_paren_groups('( ) (( )) (( )( ))') ['()', ['()'], ['()', '()']] """
def nested_separate_paren_groups(paren_string: str) -> Any: """Input to this function is a string containing multiple groups of nested parentheses. Your goal is to separate those group into separate strings and return the list of those. Different from separate_paren_groups, you have to recursively separate a group into subgroups if it is nested. Separate groups are balanced (each open brace is properly closed) and nested within each other Ignore any spaces in the input string. >>> nested_separate_paren_groups('( ) (( )) (( )( ))') ['()', ['()'], ['()', '()']] """ print(paren_string) groups = separate_paren_groups(paren_string) for idx in range(len(groups)): if groups[idx] == '()': continue else: groups[idx] = nested_separate_paren_groups(groups[idx][1:-1]) return groups
nested_separate_paren_groups
def check(candidate): assert candidate('(()(()))()()') == [['()', ['()']], '()', '()'] assert candidate('((((()))))') == [[[[['()']]]]] assert candidate('()((()())())()(())') == ['()', [['()', '()'], '()'], '()', ['()']] def test_check(): check(nested_separate_paren_groups) test_check()
[ "\ndef", "\n#", "\nif", "\nclass" ]
Input to this function is a string containing multiple groups of nested parentheses. Your goal is to separate those group into separate strings and return the list of those. Separate groups are balanced (each open brace is properly closed) and not nested within each other Ignore any spaces in the input string. >>> separate_paren_groups('( ) (( )) (( )( ))') ['()', '(())', '(()())']
Input to this function is a string containing multiple groups of nested parentheses. Your goal is to separate those group into separate strings and return the list of those. Different from separate_paren_groups, you have to recursively separate a group into subgroups if it is nested. Separate groups are balanced (each open brace is properly closed) and nested within each other Ignore any spaces in the input string. >>> nested_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
print(paren_string) groups = separate_paren_groups(paren_string) for idx in range(len(groups)): if groups[idx] == '()': continue else: groups[idx] = nested_separate_paren_groups(groups[idx][1:-1]) return groups
separate_paren_groups(paren_string: str) -> List[str]
nested_separate_paren_groups(paren_string: str) -> Any
def truncate_number(number: float) -> float: """Given a positive floating point number, it can be decomposed into and integer part (largest integer smaller than given number) and decimals (leftover part always smaller than 1). Return the decimal part of the number. >>> truncate_number(3.5) 0.5 """
def truncate_number(number: float) -> float: """Given a positive floating point number, it can be decomposed into and integer part (largest integer smaller than given number) and decimals (leftover part always smaller than 1). Return the decimal part of the number. >>> truncate_number(3.5) 0.5 """ return number % 1.0
truncate_number
def is_number_rounded_up(number: float) -> bool: """Given a positive floating point number, return True if the number is rounded up, False otherwise. >>> is_number_rounded_up(3.5) True >>> is_number_rounded_up(3.4) False """
def is_number_rounded_up(number: float) -> bool: """Given a positive floating point number, return True if the number is rounded up, False otherwise. >>> is_number_rounded_up(3.5) True >>> is_number_rounded_up(3.4) False """ return truncate_number(number) >= 0.5
is_number_rounded_up
def check(candidate): assert candidate(4.2) is False assert candidate(3.141592) is False assert candidate(19.865) is True assert candidate(1.501) is True def test_check(): check(is_number_rounded_up) test_check()
[ "\ndef", "\n#", "\nif", "\nclass" ]
Given a positive floating point number, it can be decomposed into and integer part (largest integer smaller than given number) and decimals (leftover part always smaller than 1). Return the decimal part of the number. >>> truncate_number(3.5) 0.5
Given a positive floating point number, return True if the number is rounded up, False otherwise. >>> is_number_rounded_up(3.5) True >>> is_number_rounded_up(3.4) False
return number % 1.0
return truncate_number(number) >= 0.5
truncate_number(number: float) -> float
is_number_rounded_up(number: float) -> bool
from typing import List
def below_zero(operations: List[int]) -> bool: """You're given a list of deposit and withdrawal operations on a bank account that starts with zero balance. Your task is to detect if at any point the balance of account fallls below zero, and at that point function should return True. Otherwise it should return False. >>> below_zero([1, 2, 3]) False >>> below_zero([1, 2, -4, 5]) True """
def below_zero(operations: List[int]) -> bool: """You're given a list of deposit and withdrawal operations on a bank account that starts with zero balance. Your task is to detect if at any point the balance of account fallls below zero, and at that point function should return True. Otherwise it should return False. >>> below_zero([1, 2, 3]) False >>> below_zero([1, 2, -4, 5]) True """ balance = 0 for op in operations: balance += op if balance < 0: return True return False
below_zero
def below_zero_with_initial_value(operations: List[int], initial: int) -> bool: """You're given a list of deposit and withdrawal operations on a bank account that starts with non-negative initial balance. Your task is to detect if at any point the balance of account fallls below zero, and at that point function should return True. Otherwise it should return False. >>> below_zero_with_initial_value([1, 2, 3], 0) False >>> below_zero_with_initial_value([1, 2, -4, 5], 3) False """
def below_zero_with_initial_value(operations: List[int], initial: int) -> bool: """You're given a list of deposit and withdrawal operations on a bank account that starts with non-negative initial balance. Your task is to detect if at any point the balance of account fallls below zero, and at that point function should return True. Otherwise it should return False. >>> below_zero_with_initial_value([1, 2, 3], 0) False >>> below_zero_with_initial_value([1, 2, -4, 5], 3) False """ return below_zero([initial] + operations)
below_zero_with_initial_value
def check(candidate): assert candidate([3, -15, 4, 2, 1], 14) is False assert candidate([-2, -3, -4, -5], 14) is False assert candidate([2, -4, 3], 1) is True assert candidate([1, 2, -4, 5], 0) is True def test_check(): check(below_zero_with_initial_value) test_check()
[ "\ndef", "\n#", "\nif", "\nclass" ]
You're given a list of deposit and withdrawal operations on a bank account that starts with zero balance. Your task is to detect if at any point the balance of account fallls below zero, and at that point function should return True. Otherwise it should return False. >>> below_zero([1, 2, 3]) False >>> below_zero([1, 2, -4, 5]) True
You're given a list of deposit and withdrawal operations on a bank account that starts with non-negative initial balance. Your task is to detect if at any point the balance of account fallls below zero, and at that point function should return True. Otherwise it should return False. >>> below_zero_with_initial_value([1, 2, 3], 0) False >>> below_zero_with_initial_value([1, 2, -4, 5], 3) False
balance = 0 for op in operations: balance += op if balance < 0: return True return False
return below_zero([initial] + operations)
below_zero(operations: List[int]) -> bool
below_zero_with_initial_value(operations: List[int], initial: int) -> bool
from typing import List
def mean_absolute_deviation(numbers: List[float]) -> float: """For a given list of input numbers, calculate Mean Absolute Deviation around the mean of this dataset. Mean Absolute Deviation is the average absolute difference between each element and a centerpoint (mean in this case): MAD = average | x - x_mean | >>> mean_absolute_deviation([1.0, 2.0, 3.0, 4.0]) 1.0 """
def mean_absolute_deviation(numbers: List[float]) -> float: """For a given list of input numbers, calculate Mean Absolute Deviation around the mean of this dataset. Mean Absolute Deviation is the average absolute difference between each element and a centerpoint (mean in this case): MAD = average | x - x_mean | >>> mean_absolute_deviation([1.0, 2.0, 3.0, 4.0]) 1.0 """ mean = sum(numbers) / len(numbers) return sum((abs(x - mean) for x in numbers)) / len(numbers)
mean_absolute_deviation
def find_outlier(numbers: List[float]) -> List[float]: """For a given list of input numbers, find the outlier. Outliers are defined as data whose distance from the mean is greater than the mean absolute deviation. The order of the outliers in the output list should be the same as in the input list. >>> find_outlier([1.0, 2.0, 3.0, 4.0]) [1.0, 4.0] """
def find_outlier(numbers: List[float]) -> List[float]: """For a given list of input numbers, find the outlier. Outliers are defined as data whose distance from the mean is greater than the mean absolute deviation. The order of the outliers in the output list should be the same as in the input list. >>> find_outlier([1.0, 2.0, 3.0, 4.0]) [1.0, 4.0] """ mean = sum(numbers) / len(numbers) mae = mean_absolute_deviation(numbers) return [number for number in numbers if abs(number - mean) > mae]
find_outlier
def check(candidate): assert candidate([3.0, 2.0, 1.0, 4.0]) == [1.0, 4.0] assert candidate([1.0, 5.0]) == [] assert candidate([-5.0, 1.0, 0.0, 1.0]) == [-5.0] assert candidate([1, 2, -4, 5]) == [-4, 5] def test_check(): check(find_outlier) test_check()
[ "\ndef", "\n#", "\nif", "\nclass" ]
For a given list of input numbers, calculate Mean Absolute Deviation around the mean of this dataset. Mean Absolute Deviation is the average absolute difference between each element and a centerpoint (mean in this case): MAD = average | x - x_mean | >>> mean_absolute_deviation([1.0, 2.0, 3.0, 4.0]) 1.0
For a given list of input numbers, find the outlier. Outliers are defined as data whose distance from the mean is greater than the mean absolute deviation. The order of the outliers in the output list should be the same as in the input list. >>> find_outlier([1.0, 2.0, 3.0, 4.0]) [1.0, 4.0]
mean = sum(numbers) / len(numbers) return sum((abs(x - mean) for x in numbers)) / len(numbers)
mean = sum(numbers) / len(numbers) mae = mean_absolute_deviation(numbers) return [number for number in numbers if abs(number - mean) > mae]
mean_absolute_deviation(numbers: List[float]) -> float
find_outlier(numbers: List[float]) -> List[float]
from typing import List
def intersperse(numbers: List[int], delimeter: int) -> List[int]: """Insert a number 'delimeter' between every two consecutive elements of input list `numbers' >>> intersperse([], 4) [] >>> intersperse([1, 2, 3], 4) [1, 4, 2, 4, 3] """
def intersperse(numbers: List[int], delimeter: int) -> List[int]: """Insert a number 'delimeter' between every two consecutive elements of input list `numbers' >>> intersperse([], 4) [] >>> intersperse([1, 2, 3], 4) [1, 4, 2, 4, 3] """ if not numbers: return [] result = [] for n in numbers[:-1]: result.append(n) result.append(delimeter) result.append(numbers[-1]) return result
intersperse
def intersperse_with_start_end(numbers: List[int], delimeter: int) -> List[int]: """Insert a number 'delimeter' between every two consecutive elements of input list `numbers' and also add 'delimeter' at the beginning and end of the list. >>> intersperse_with_start_end([], 4) [4, 4] >>> intersperse_with_start_end([1, 2, 3], 4) [4, 1, 4, 2, 4, 3, 4] """
def intersperse_with_start_end(numbers: List[int], delimeter: int) -> List[int]: """Insert a number 'delimeter' between every two consecutive elements of input list `numbers' and also add 'delimeter' at the beginning and end of the list. >>> intersperse_with_start_end([], 4) [4, 4] >>> intersperse_with_start_end([1, 2, 3], 4) [4, 1, 4, 2, 4, 3, 4] """ return [delimeter] + intersperse(numbers, delimeter) + [delimeter]
intersperse_with_start_end
def check(candidate): assert candidate([], 100) == [100, 100] assert candidate([7, 7, 7], 1) == [1, 7, 1, 7, 1, 7, 1] assert candidate([3, 6, 9, 12, 15], 6) == [6, 3, 6, 6, 6, 9, 6, 12, 6, 15, 6] assert candidate([7, 5, 3, 2], 1) == [1, 7, 1, 5, 1, 3, 1, 2, 1] assert candidate([101, 100, 98, 95], 100) == [100, 101, 100, 100, 100, 98, 100, 95, 100] def test_check(): check(intersperse_with_start_end) test_check()
[ "\ndef", "\n#", "\nif", "\nclass" ]
Insert a number 'delimeter' between every two consecutive elements of input list `numbers' >>> intersperse([], 4) [] >>> intersperse([1, 2, 3], 4) [1, 4, 2, 4, 3]
Insert a number 'delimeter' between every two consecutive elements of input list `numbers' and also add 'delimeter' at the beginning and end of the list. >>> intersperse_with_start_end([], 4) [4, 4] >>> intersperse_with_start_end([1, 2, 3], 4) [4, 1, 4, 2, 4, 3, 4]
if not numbers: return [] result = [] for n in numbers[:-1]: result.append(n) result.append(delimeter) result.append(numbers[-1]) return result
return [delimeter] + intersperse(numbers, delimeter) + [delimeter]
intersperse(numbers: List[int], delimeter: int) -> List[int]
intersperse_with_start_end(numbers: List[int], delimeter: int) -> List[int]
from typing import List
def parse_nested_parens(paren_string: str) -> List[int]: """Input to this function is a string represented multiple groups for nested parentheses separated by spaces. For each of the group, output the deepest level of nesting of parentheses. E.g. (()()) has maximum two levels of nesting while ((())) has three. >>> parse_nested_parens('(()()) ((())) () ((())()())') [2, 3, 1, 3] """
def parse_nested_parens(paren_string: str) -> List[int]: """Input to this function is a string represented multiple groups for nested parentheses separated by spaces. For each of the group, output the deepest level of nesting of parentheses. E.g. (()()) has maximum two levels of nesting while ((())) has three. >>> parse_nested_parens('(()()) ((())) () ((())()())') [2, 3, 1, 3] """ 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]
parse_nested_parens
def remove_nested_parens(paren_string: str) -> str: """Input to this function is a string represented multiple groups for nested parentheses separated by spaces. Filter out the group whose deepest level of nesting of parentheses is greater than 2. E.g. (()()) has maximum two levels of nesting while ((())) has three. >>> remove_nested_parens('(()()) ((())) () ((())()())') '(()()) ()' """
def remove_nested_parens(paren_string: str) -> str: """Input to this function is a string represented multiple groups for nested parentheses separated by spaces. Filter out the group whose deepest level of nesting of parentheses is greater than 2. E.g. (()()) has maximum two levels of nesting while ((())) has three. >>> remove_nested_parens('(()()) ((())) () ((())()())') '(()()) ()' """ depths = parse_nested_parens(paren_string) return ' '.join((group for (group, depth) in zip(paren_string.split(), depths) if depth <= 2))
remove_nested_parens
def check(candidate): assert candidate('(()) () ()') == '(()) () ()' assert candidate('((())) ((()))') == '' assert candidate('() (()()) () ((())())') == '() (()()) ()' assert candidate('(()) (()) (())') == '(()) (()) (())' assert candidate('(()()()()) (()()()) (()()) (())') == '(()()()()) (()()()) (()()) (())' def test_check(): check(remove_nested_parens) test_check()
[ "\ndef", "\n#", "\nif", "\nclass" ]
Input to this function is a string represented multiple groups for nested parentheses separated by spaces. For each of the group, output the deepest level of nesting of parentheses. E.g. (()()) has maximum two levels of nesting while ((())) has three. >>> parse_nested_parens('(()()) ((())) () ((())()())') [2, 3, 1, 3]
Input to this function is a string represented multiple groups for nested parentheses separated by spaces. Filter out the group whose deepest level of nesting of parentheses is greater than 2. E.g. (()()) has maximum two levels of nesting while ((())) has three. >>> remove_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]
depths = parse_nested_parens(paren_string) return ' '.join((group for (group, depth) in zip(paren_string.split(), depths) if depth <= 2))
parse_nested_parens(paren_string: str) -> List[int]
remove_nested_parens(paren_string: str) -> str
from typing import List
def filter_by_substring(strings: List[str], substring: str) -> List[str]: """Filter an input list of strings only for ones that contain given substring >>> filter_by_substring([], 'a') [] >>> filter_by_substring(['abc', 'bacd', 'cde', 'array'], 'a') ['abc', 'bacd', 'array'] """
def filter_by_substring(strings: List[str], substring: str) -> List[str]: """Filter an input list of strings only for ones that contain given substring >>> filter_by_substring([], 'a') [] >>> filter_by_substring(['abc', 'bacd', 'cde', 'array'], 'a') ['abc', 'bacd', 'array'] """ return [x for x in strings if substring in x]
filter_by_substring
def filter_by_substrings(strings: List[str], substrings: List[str]) -> List[str]: """Filter an input list of strings only for ones that contain all of given substrings >>> filter_by_substrings([], ['a', 'b']) [] >>> filter_by_substrings(['abc', 'bacd', 'cde', 'array'], ['a', 'b']) ['abc', 'bacd'] """
def filter_by_substrings(strings: List[str], substrings: List[str]) -> List[str]: """Filter an input list of strings only for ones that contain all of given substrings >>> filter_by_substrings([], ['a', 'b']) [] >>> filter_by_substrings(['abc', 'bacd', 'cde', 'array'], ['a', 'b']) ['abc', 'bacd'] """ for substring in substrings: strings = filter_by_substring(strings, substring) return strings
filter_by_substrings
def check(candidate): assert candidate(['prefix', 'suffix', 'infix'], ['fix', 'pre']) == ['prefix'] assert candidate(['prefix', 'suffix', 'infix'], ['fix', 'pre', 'in']) == [] assert candidate(['hot', 'cold', 'warm'], ['o']) == ['hot', 'cold'] assert candidate(['abcdef', 'aboekxdeji', 'abekfj'], ['ab', 'de']) == ['abcdef', 'aboekxdeji'] def test_check(): check(filter_by_substrings) test_check()
[ "\ndef", "\n#", "\nif", "\nclass" ]
Filter an input list of strings only for ones that contain given substring >>> filter_by_substring([], 'a') [] >>> filter_by_substring(['abc', 'bacd', 'cde', 'array'], 'a') ['abc', 'bacd', 'array']
Filter an input list of strings only for ones that contain all of given substrings >>> filter_by_substrings([], ['a', 'b']) [] >>> filter_by_substrings(['abc', 'bacd', 'cde', 'array'], ['a', 'b']) ['abc', 'bacd']
return [x for x in strings if substring in x]
for substring in substrings: strings = filter_by_substring(strings, substring) return strings
filter_by_substring(strings: List[str], substring: str) -> List[str]
filter_by_substrings(strings: List[str], substrings: List[str]) -> List[str]
from typing import List, Tuple
def sum_product(numbers: List[int]) -> Tuple[int, int]: """For a given list of integers, return a tuple consisting of a sum and a product of all the integers in a list. Empty sum should be equal to 0 and empty product should be equal to 1. >>> sum_product([]) (0, 1) >>> sum_product([1, 2, 3, 4]) (10, 24) """
def sum_product(numbers: List[int]) -> Tuple[int, int]: """For a given list of integers, return a tuple consisting of a sum and a product of all the integers in a list. Empty sum should be equal to 0 and empty product should be equal to 1. >>> sum_product([]) (0, 1) >>> sum_product([1, 2, 3, 4]) (10, 24) """ sum_value = 0 prod_value = 1 for n in numbers: sum_value += n prod_value *= n return (sum_value, prod_value)
sum_product
def product_sum(numbers: List[int]) -> Tuple[int, int]: """For a given list of integers, return a tuple consisting of a product and a sum of all the integers in a list. Empty sum should be equal to 0 and empty product should be equal to 1. >>> product_sum([]) (1, 0) >>> product_sum([1, 2, 3, 4]) (24, 10) """
def product_sum(numbers: List[int]) -> Tuple[int, int]: """For a given list of integers, return a tuple consisting of a product and a sum of all the integers in a list. Empty sum should be equal to 0 and empty product should be equal to 1. >>> product_sum([]) (1, 0) >>> product_sum([1, 2, 3, 4]) (24, 10) """ (s, p) = sum_product(numbers) return (p, s)
product_sum
def check(candidate): assert candidate([]) == (1, 0) assert candidate([4, 3, 0, 8]) == (0, 15) assert candidate([9, 2]) == (18, 11) assert candidate([100, 101, 102]) == (1030200, 303) def test_check(): check(product_sum) test_check()
[ "\ndef", "\n#", "\nif", "\nclass" ]
For a given list of integers, return a tuple consisting of a sum and a product of all the integers in a list. Empty sum should be equal to 0 and empty product should be equal to 1. >>> sum_product([]) (0, 1) >>> sum_product([1, 2, 3, 4]) (10, 24)
For a given list of integers, return a tuple consisting of a product and a sum of all the integers in a list. Empty sum should be equal to 0 and empty product should be equal to 1. >>> product_sum([]) (1, 0) >>> product_sum([1, 2, 3, 4]) (24, 10)
sum_value = 0 prod_value = 1 for n in numbers: sum_value += n prod_value *= n return (sum_value, prod_value)
(s, p) = sum_product(numbers) return (p, s)
sum_product(numbers: List[int]) -> Tuple[int, int]
product_sum(numbers: List[int]) -> Tuple[int, int]
from typing import List
def rolling_max(numbers: List[int]) -> List[int]: """From a given list of integers, generate a list of rolling maximum element found until given moment in the sequence. >>> rolling_max([1, 2, 3, 2, 3, 4, 2]) [1, 2, 3, 3, 3, 4, 4] """
def rolling_max(numbers: List[int]) -> List[int]: """From a given list of integers, generate a list of rolling maximum element found until given moment in the sequence. >>> rolling_max([1, 2, 3, 2, 3, 4, 2]) [1, 2, 3, 3, 3, 4, 4] """ 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
rolling_max
def rolling_max_with_initial_value(numbers: List[int], initial: int) -> List[int]: """From a given list of integers, generate a list of rolling maximum element found until given moment in the sequence. Additionally, the maximum value starts with `initial`. >>> rolling_max_with_initial_value([1, 2, 3, 2, 3, 4, 2], 3) [3, 3, 3, 3, 3, 4, 4] """
def rolling_max_with_initial_value(numbers: List[int], initial: int) -> List[int]: """From a given list of integers, generate a list of rolling maximum element found until given moment in the sequence. Additionally, the maximum value starts with `initial`. >>> rolling_max_with_initial_value([1, 2, 3, 2, 3, 4, 2], 3) [3, 3, 3, 3, 3, 4, 4] """ return rolling_max([initial] + numbers)[1:]
rolling_max_with_initial_value
def check(candidate): assert candidate([2, 4, 3, 2, 3, 2, 5, 4, 6], 3) == [3, 4, 4, 4, 4, 4, 5, 5, 6] assert candidate([8, 3, 5, 9, 9, 11, 6, 4], 13) == [13, 13, 13, 13, 13, 13, 13, 13] assert candidate([2, 2, 3, 7], 1) == [2, 2, 3, 7] assert candidate([72, 74, 75, 76], 74) == [74, 74, 75, 76] def test_check(): check(rolling_max_with_initial_value) test_check()
[ "\ndef", "\n#", "\nif", "\nclass" ]
From a given list of integers, generate a list of rolling maximum element found until given moment in the sequence. >>> rolling_max([1, 2, 3, 2, 3, 4, 2]) [1, 2, 3, 3, 3, 4, 4]
From a given list of integers, generate a list of rolling maximum element found until given moment in the sequence. Additionally, the maximum value starts with `initial`. >>> rolling_max_with_initial_value([1, 2, 3, 2, 3, 4, 2], 3) [3, 3, 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
return rolling_max([initial] + numbers)[1:]
rolling_max(numbers: List[int]) -> List[int]
rolling_max_with_initial_value(numbers: List[int], initial: int) -> List[int]
def make_palindrome(string: str) -> str: """Find the shortest palindrome that begins with a supplied string. Algorithm idea is simple: - Find the longest postfix of supplied string that is a palindrome. - Append to the end of the string reverse of a string prefix that comes before the palindromic suffix. >>> make_palindrome('') '' >>> make_palindrome('cat') 'catac' >>> make_palindrome('cata') 'catac' """
def make_palindrome(string: str) -> str: """Find the shortest palindrome that begins with a supplied string. Algorithm idea is simple: - Find the longest postfix of supplied string that is a palindrome. - Append to the end of the string reverse of a string prefix that comes before the palindromic suffix. >>> make_palindrome('') '' >>> make_palindrome('cat') 'catac' >>> make_palindrome('cata') 'catac' """ def is_palindrome(string: str) -> bool: return string == string[::-1] 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]
make_palindrome
def find_shortest_palindrome_prefix(string: str) -> str: """Find the shortest prefix that generates the same shortest palindrome that begins with the supplied string. >>> find_shortest_palindrome_prefix('') '' >>> find_shortest_palindrome_prefix('cat') 'cat' >>> find_shortest_palindrome_prefix('cata') 'cat' """
def find_shortest_palindrome_prefix(string: str) -> str: """Find the shortest prefix that generates the same shortest palindrome that begins with the supplied string. >>> find_shortest_palindrome_prefix('') '' >>> find_shortest_palindrome_prefix('cat') 'cat' >>> find_shortest_palindrome_prefix('cata') 'cat' """ if len(string) == 0 or len(string) == 1: return string p = make_palindrome(string) for idx in range(len(string) - 1, 0, -1): if p != make_palindrome(string[:idx]): return string[:idx + 1]
find_shortest_palindrome_prefix
def check(candidate): assert candidate('owienfh') == 'owienfh' assert candidate('abcdedcb') == 'abcde' assert candidate('abababa') == 'ababab' def test_check(): check(find_shortest_palindrome_prefix) test_check()
[ "\ndef", "\n#", "\nif", "\nclass" ]
Find the shortest palindrome that begins with a supplied string. Algorithm idea is simple: - Find the longest postfix of supplied string that is a palindrome. - Append to the end of the string reverse of a string prefix that comes before the palindromic suffix. >>> make_palindrome('') '' >>> make_palindrome('cat') 'catac' >>> make_palindrome('cata') 'catac'
Find the shortest prefix that generates the same shortest palindrome that begins with the supplied string. >>> find_shortest_palindrome_prefix('') '' >>> find_shortest_palindrome_prefix('cat') 'cat' >>> find_shortest_palindrome_prefix('cata') 'cat'
def is_palindrome(string: str) -> bool: return string == string[::-1] 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]
if len(string) == 0 or len(string) == 1: return string p = make_palindrome(string) for idx in range(len(string) - 1, 0, -1): if p != make_palindrome(string[:idx]): return string[:idx + 1]
make_palindrome(string: str) -> str
find_shortest_palindrome_prefix(string: str) -> str
def string_xor(a: str, b: str) -> str: """Input are two strings a and b consisting only of 1s and 0s. Perform binary XOR on these inputs and return result also as a string. >>> string_xor('010', '110') '100' """
def string_xor(a: str, b: str) -> str: """Input are two strings a and b consisting only of 1s and 0s. Perform binary XOR on these inputs and return result also as a string. >>> string_xor('010', '110') '100' """ def xor(i, j): if i == j: return '0' else: return '1' return ''.join((xor(x, y) for (x, y) in zip(a, b)))
string_xor
def string_xor_three(a: str, b: str, c: str) -> str: """Input are three strings a, b, and c consisting only of 1s and 0s. Perform binary XOR on these inputs and return result also as a string. >>> string_xor('010', '110', '001') '101' """
def string_xor_three(a: str, b: str, c: str) -> str: """Input are three strings a, b, and c consisting only of 1s and 0s. Perform binary XOR on these inputs and return result also as a string. >>> string_xor('010', '110', '001') '101' """ return string_xor(string_xor(a, b), c)
string_xor_three
def check(candidate): assert candidate('000', '101', '110') == '011' assert candidate('1100', '1011', '1111') == '1000' assert candidate('010', '110', '100') == '000' def test_check(): check(string_xor_three) test_check()
[ "\ndef", "\n#", "\nif", "\nclass" ]
Input are two strings a and b consisting only of 1s and 0s. Perform binary XOR on these inputs and return result also as a string. >>> string_xor('010', '110') '100'
Input are three strings a, b, and c consisting only of 1s and 0s. Perform binary XOR on these inputs and return result also as a string. >>> string_xor('010', '110', '001') '101'
def xor(i, j): if i == j: return '0' else: return '1' return ''.join((xor(x, y) for (x, y) in zip(a, b)))
return string_xor(string_xor(a, b), c)
string_xor(a: str, b: str) -> str
string_xor_three(a: str, b: str, c: str) -> str
from typing import List, Optional
def longest(strings: List[str]) -> Optional[str]: """Out of list of strings, return the longest one. Return the first one in case of multiple strings of the same length. Return None in case the input list is empty. >>> longest([]) >>> longest(['a', 'b', 'c']) 'a' >>> longest(['a', 'bb', 'ccc']) 'ccc' """
def longest(strings: List[str]) -> Optional[str]: """Out of list of strings, return the longest one. Return the first one in case of multiple strings of the same length. Return None in case the input list is empty. >>> longest([]) >>> longest(['a', 'b', 'c']) 'a' >>> longest(['a', 'bb', 'ccc']) 'ccc' """ if not strings: return None maxlen = max((len(x) for x in strings)) for s in strings: if len(s) == maxlen: return s
longest
def second_longest(strings: List[str]) -> Optional[str]: """Out of list of strings, return the second longest one. Return the first one in case of multiple strings of the same length. Return None in case the input list doesn't have the second longest elements. >>> second_longest([]) None >>> second_longest(['a', 'b', 'c']) None >>> second_longest(['a', 'bb', 'ccc']) 'bb' """
def second_longest(strings: List[str]) -> Optional[str]: """Out of list of strings, return the second longest one. Return the first one in case of multiple strings of the same length. Return None in case the input list doesn't have the second longest elements. >>> second_longest([]) None >>> second_longest(['a', 'b', 'c']) None >>> second_longest(['a', 'bb', 'ccc']) 'bb' """ longest_string = longest(strings) if longest_string is None: return None strings = [string for string in strings if len(string) < len(longest_string)] return longest(strings)
second_longest
def check(candidate): assert candidate([]) is None assert candidate(['albha', 'iehwknsj', 'lwi', 'wihml']) == 'albha' assert candidate(['apple', 'banana', 'kiwiiiiiii', 'xxxxxx', 'appledish']) == 'appledish' assert candidate(['what', 'is', 'this']) == 'is' def test_check(): check(second_longest) test_check()
[ "\ndef", "\n#", "\nif", "\nclass" ]
Out of list of strings, return the longest one. Return the first one in case of multiple strings of the same length. Return None in case the input list is empty. >>> longest([]) >>> longest(['a', 'b', 'c']) 'a' >>> longest(['a', 'bb', 'ccc']) 'ccc'
Out of list of strings, return the second longest one. Return the first one in case of multiple strings of the same length. Return None in case the input list doesn't have the second longest elements. >>> second_longest([]) None >>> second_longest(['a', 'b', 'c']) None >>> second_longest(['a', 'bb', 'ccc']) 'bb'
if not strings: return None maxlen = max((len(x) for x in strings)) for s in strings: if len(s) == maxlen: return s
longest_string = longest(strings) if longest_string is None: return None strings = [string for string in strings if len(string) < len(longest_string)] return longest(strings)
longest(strings: List[str]) -> Optional[str]
second_longest(strings: List[str]) -> Optional[str]
from typing import Tuple
def greatest_common_divisor(a: int, b: int) -> int: """Return a greatest common divisor of two integers a and b >>> greatest_common_divisor(3, 5) 1 >>> greatest_common_divisor(25, 15) 5 """
def greatest_common_divisor(a: int, b: int) -> int: """Return a greatest common divisor of two integers a and b >>> greatest_common_divisor(3, 5) 1 >>> greatest_common_divisor(25, 15) 5 """ while b: (a, b) = (b, a % b) return a
greatest_common_divisor
def reduce_fraction(nominator: int, denominator: int) -> Tuple[int, int]: """Given nominator and denominator, reduce them to the simplest form. Reducing fractions means simplifying a fraction, wherein we divide the numerator and denominator by a common divisor until the common factor becomes 1. >>> reduce_fraction(3, 5) (3, 5) >>> reduce_fraction(25, 15) (5, 3) """
def reduce_fraction(nominator: int, denominator: int) -> Tuple[int, int]: """Given nominator and denominator, reduce them to the simplest form. Reducing fractions means simplifying a fraction, wherein we divide the numerator and denominator by a common divisor until the common factor becomes 1. >>> reduce_fraction(3, 5) (3, 5) >>> reduce_fraction(25, 15) (5, 3) """ gcd = greatest_common_divisor(nominator, denominator) return (nominator // gcd, denominator // gcd)
reduce_fraction
def check(candidate): assert candidate(51, 34) == (3, 2) assert candidate(81, 9) == (9, 1) assert candidate(39, 52) == (3, 4) def test_check(): check(reduce_fraction) test_check()
[ "\ndef", "\n#", "\nif", "\nclass" ]
Return a greatest common divisor of two integers a and b >>> greatest_common_divisor(3, 5) 1 >>> greatest_common_divisor(25, 15) 5
Given nominator and denominator, reduce them to the simplest form. Reducing fractions means simplifying a fraction, wherein we divide the numerator and denominator by a common divisor until the common factor becomes 1. >>> reduce_fraction(3, 5) (3, 5) >>> reduce_fraction(25, 15) (5, 3)
while b: (a, b) = (b, a % b) return a
gcd = greatest_common_divisor(nominator, denominator) return (nominator // gcd, denominator // gcd)
greatest_common_divisor(a: int, b: int) -> int
reduce_fraction(nominator: int, denominator: int) -> Tuple[int, int]
from typing import List
def all_prefixes(string: str) -> List[str]: """Return list of all prefixes from shortest to longest of the input string >>> all_prefixes('abc') ['a', 'ab', 'abc'] """
def all_prefixes(string: str) -> List[str]: """Return list of all prefixes from shortest to longest of the input string >>> all_prefixes('abc') ['a', 'ab', 'abc'] """ result = [] for i in range(len(string)): result.append(string[:i + 1]) return result
all_prefixes
def all_suffixes_prefixes(string: str) -> List[str]: """Return list of suffixes which are also a prefix from shortest to longest of the input string >>> all_suffixes('abc') ['abc'] """
def all_suffixes_prefixes(string: str) -> List[str]: """Return list of suffixes which are also a prefix from shortest to longest of the input string >>> all_suffixes('abc') ['abc'] """ prefixes = all_prefixes(string) suffixes = [x[::-1] for x in all_prefixes(string[::-1])] return [x for x in suffixes if x in prefixes]
all_suffixes_prefixes
def check(candidate): assert candidate('abcabc') == ['abc', 'abcabc'] assert candidate('ababab') == ['ab', 'abab', 'ababab'] assert candidate('dxewfoird') == ['d', 'dxewfoird'] def test_check(): check(all_suffixes_prefixes) test_check()
[ "\ndef", "\n#", "\nif", "\nclass" ]
Return list of all prefixes from shortest to longest of the input string >>> all_prefixes('abc') ['a', 'ab', 'abc']
Return list of suffixes which are also a prefix from shortest to longest of the input string >>> all_suffixes('abc') ['abc']
result = [] for i in range(len(string)): result.append(string[:i + 1]) return result
prefixes = all_prefixes(string) suffixes = [x[::-1] for x in all_prefixes(string[::-1])] return [x for x in suffixes if x in prefixes]
all_prefixes(string: str) -> List[str]
all_suffixes_prefixes(string: str) -> List[str]
def string_sequence(n: int) -> str: """Return a string containing space-delimited numbers starting from 0 upto n inclusive. >>> string_sequence(0) '0' >>> string_sequence(5) '0 1 2 3 4 5' """
def string_sequence(n: int) -> str: """Return a string containing space-delimited numbers starting from 0 upto n inclusive. >>> string_sequence(0) '0' >>> string_sequence(5) '0 1 2 3 4 5' """ return ' '.join([str(x) for x in range(n + 1)])
string_sequence
def digit_sum(n: int) -> str: """Return the sum of all digits from 0 upto n inclusive. >>> digit_sum(0) 0 >>> digit_sum(5) 15 """
def digit_sum(n: int) -> str: """Return the sum of all digits from 0 upto n inclusive. >>> digit_sum(0) 0 >>> digit_sum(5) 15 """ sequence = string_sequence(n) return sum((int(x) for x in sequence if x != ' '))
digit_sum
def check(candidate): assert candidate(14) == 60 assert candidate(21) == 105 assert candidate(104) == 915 def test_check(): check(digit_sum) test_check()
[ "\ndef", "\n#", "\nif", "\nclass" ]
Return a string containing space-delimited numbers starting from 0 upto n inclusive. >>> string_sequence(0) '0' >>> string_sequence(5) '0 1 2 3 4 5'
Return the sum of all digits from 0 upto n inclusive. >>> digit_sum(0) 0 >>> digit_sum(5) 15
return ' '.join([str(x) for x in range(n + 1)])
sequence = string_sequence(n) return sum((int(x) for x in sequence if x != ' '))
string_sequence(n: int) -> str
digit_sum(n: int) -> str
from typing import List
def count_distinct_characters(string: str) -> int: """Given a string, find out how many distinct characters (regardless of case) does it consist of >>> count_distinct_characters('xyzXYZ') 3 >>> count_distinct_characters('Jerry') 4 """
def count_distinct_characters(string: str) -> int: """Given a string, find out how many distinct characters (regardless of case) does it consist of >>> count_distinct_characters('xyzXYZ') 3 >>> count_distinct_characters('Jerry') 4 """ return len(set(string.lower()))
count_distinct_characters
def count_words_with_distinct_characters(strings: List[str]) -> int: """Given a list of strings, count the number of words made up of all different letters (regardless of case) >>> count_words_with_distinct_characters(['xyz', 'Jerry']) 1 >>> count_words_with_distinct_characters(['apple', 'bear', 'Take']) 2 """
def count_words_with_distinct_characters(strings: List[str]) -> int: """Given a list of strings, count the number of words made up of all different letters (regardless of case) >>> count_words_with_distinct_characters(['xyz', 'Jerry']) 1 >>> count_words_with_distinct_characters(['apple', 'bear', 'Take']) 2 """ return len([string for string in strings if count_distinct_characters(string) == len(string)])
count_words_with_distinct_characters
def check(candidate): assert candidate(['valid', 'heart', 'orientation', 'class']) == 2 assert candidate(['hunter', 'frog']) == 2 assert candidate(['scratch']) == 0 def test_check(): check(count_words_with_distinct_characters) test_check()
[ "\ndef", "\n#", "\nif", "\nclass" ]
Given a string, find out how many distinct characters (regardless of case) does it consist of >>> count_distinct_characters('xyzXYZ') 3 >>> count_distinct_characters('Jerry') 4
Given a list of strings, count the number of words made up of all different letters (regardless of case) >>> count_words_with_distinct_characters(['xyz', 'Jerry']) 1 >>> count_words_with_distinct_characters(['apple', 'bear', 'Take']) 2
return len(set(string.lower()))
return len([string for string in strings if count_distinct_characters(string) == len(string)])
count_distinct_characters(string: str) -> int
count_words_with_distinct_characters(strings: List[str]) -> int
from typing import List
def parse_music(music_string: str) -> List[int]: """Input to this function is a string representing musical notes in a special ASCII format. Your task is to parse this string and return list of integers corresponding to how many beats does each not last. Here is a legend: 'o' - whole note, lasts four beats 'o|' - half note, lasts two beats '.|' - quater note, lasts one beat >>> parse_music('o o| .| o| o| .| .| .| .| o o') [4, 2, 1, 2, 2, 1, 1, 1, 1, 4, 4] """
def parse_music(music_string: str) -> List[int]: """Input to this function is a string representing musical notes in a special ASCII format. Your task is to parse this string and return list of integers corresponding to how many beats does each not last. Here is a legend: 'o' - whole note, lasts four beats 'o|' - half note, lasts two beats '.|' - quater note, lasts one beat >>> parse_music('o o| .| o| o| .| .| .| .| o o') [4, 2, 1, 2, 2, 1, 1, 1, 1, 4, 4] """ note_map = {'o': 4, 'o|': 2, '.|': 1} return [note_map[x] for x in music_string.split(' ') if x]
parse_music
def count_beats(music_string: str) -> int: """Input to this function is a string representing musical notes in a special ASCII format. Your task is to parse this string and return the total number of beats in the song. Here is a legend: 'o' - whole note, lasts four beats 'o|' - half note, lasts two beats '.|' - quater note, lasts one beat >>> count_beats('o o| .| o| o| .| .| .| .| o o') 24 """
def count_beats(music_string: str) -> int: """Input to this function is a string representing musical notes in a special ASCII format. Your task is to parse this string and return the total number of beats in the song. Here is a legend: 'o' - whole note, lasts four beats 'o|' - half note, lasts two beats '.|' - quater note, lasts one beat >>> count_beats('o o| .| o| o| .| .| .| .| o o') 24 """ return sum(parse_music(music_string))
count_beats
def check(candidate): assert candidate('o o| .|') == 7 assert candidate('o| o| o|') == 6 assert candidate('o .| o| o o| .| o|') == 16 def test_check(): check(count_beats) test_check()
[ "\ndef", "\n#", "\nif", "\nclass" ]
Input to this function is a string representing musical notes in a special ASCII format. Your task is to parse this string and return list of integers corresponding to how many beats does each not last. Here is a legend: 'o' - whole note, lasts four beats 'o|' - half note, lasts two beats '.|' - quater note, lasts one beat >>> parse_music('o o| .| o| o| .| .| .| .| o o') [4, 2, 1, 2, 2, 1, 1, 1, 1, 4, 4]
Input to this function is a string representing musical notes in a special ASCII format. Your task is to parse this string and return the total number of beats in the song. Here is a legend: 'o' - whole note, lasts four beats 'o|' - half note, lasts two beats '.|' - quater note, lasts one beat >>> count_beats('o o| .| o| o| .| .| .| .| o o') 24
note_map = {'o': 4, 'o|': 2, '.|': 1} return [note_map[x] for x in music_string.split(' ') if x]
return sum(parse_music(music_string))
parse_music(music_string: str) -> List[int]
count_beats(music_string: str) -> int
def how_many_times(string: str, substring: str) -> int: """Find how many times a given substring can be found in the original string. Count overlaping cases. >>> how_many_times('', 'a') 0 >>> how_many_times('aaa', 'a') 3 >>> how_many_times('aaaa', 'aa') 3 """
def how_many_times(string: str, substring: str) -> int: """Find how many times a given substring can be found in the original string. Count overlaping cases. >>> how_many_times('', 'a') 0 >>> how_many_times('aaa', 'a') 3 >>> how_many_times('aaaa', 'aa') 3 """ times = 0 for i in range(len(string) - len(substring) + 1): if string[i:i + len(substring)] == substring: times += 1 return times
how_many_times
def match_cancer_pattern(dna: str, cancer_pattern: str) -> int: """Find how many times a given cancer pattern can be found in the given DNA. Count overlaping cases. >>> match_cancer_pattern('ATGCGATACGCTTGA', 'CG') 3 >>> match_cancer_pattern('ATGCGATACGCTTGA', 'CGC') 1 """
def match_cancer_pattern(dna: str, cancer_pattern: str) -> int: """Find how many times a given cancer pattern can be found in the given DNA. Count overlaping cases. >>> match_cancer_pattern('ATGCGATACGCTTGA', 'CG') 3 >>> match_cancer_pattern('ATGCGATACGCTTGA', 'CGC') 1 """ return how_many_times(dna, cancer_pattern)
match_cancer_pattern
def check(candidate): assert candidate('ATATATAT', 'ATA') == 3 assert candidate('ATGCATGCATGCATGC', 'ATGCATGC') == 3 assert candidate('AGCTCTGATCGAT', 'GAT') == 2 def test_check(): check(match_cancer_pattern) test_check()
[ "\ndef", "\n#", "\nif", "\nclass" ]
Find how many times a given substring can be found in the original string. Count overlaping cases. >>> how_many_times('', 'a') 0 >>> how_many_times('aaa', 'a') 3 >>> how_many_times('aaaa', 'aa') 3
Find how many times a given cancer pattern can be found in the given DNA. Count overlaping cases. >>> match_cancer_pattern('ATGCGATACGCTTGA', 'CG') 3 >>> match_cancer_pattern('ATGCGATACGCTTGA', 'CGC') 1
times = 0 for i in range(len(string) - len(substring) + 1): if string[i:i + len(substring)] == substring: times += 1 return times
return how_many_times(dna, cancer_pattern)
how_many_times(string: str, substring: str) -> int
match_cancer_pattern(dna: str, cancer_pattern: str) -> int
def sort_numbers(numbers: str) -> str: """Input is a space-delimited string of numberals from 'zero' to 'nine'. Valid choices are 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight' and 'nine'. Return the string with numbers sorted from smallest to largest >>> sort_numbers('three one five') 'one three five' """
def sort_numbers(numbers: str) -> str: """Input is a space-delimited string of numberals from 'zero' to 'nine'. Valid choices are 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight' and 'nine'. Return the string with numbers sorted from smallest to largest >>> sort_numbers('three one five') 'one three five' """ 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]))
sort_numbers
def sort_numbers_descending(numbers: str) -> str: """Input is a space-delimited string of numberals from 'zero' to 'nine'. Valid choices are 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight' and 'nine'. Return the string with numbers sorted from largest to smallest >>> sort_numbers_descending('three one five') 'five three one' """
def sort_numbers_descending(numbers: str) -> str: """Input is a space-delimited string of numberals from 'zero' to 'nine'. Valid choices are 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight' and 'nine'. Return the string with numbers sorted from largest to smallest >>> sort_numbers_descending('three one five') 'five three one' """ return ' '.join((x for x in reversed(sort_numbers(numbers).split(' '))))
sort_numbers_descending
def check(candidate): assert candidate('two three four') == 'four three two' assert candidate('nine zero six seven') == 'nine seven six zero' assert candidate('five one three eight') == 'eight five three one' def test_check(): check(sort_numbers_descending) test_check()
[ "\ndef", "\n#", "\nif", "\nclass" ]
Input is a space-delimited string of numberals from 'zero' to 'nine'. Valid choices are 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight' and 'nine'. Return the string with numbers sorted from smallest to largest >>> sort_numbers('three one five') 'one three five'
Input is a space-delimited string of numberals from 'zero' to 'nine'. Valid choices are 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight' and 'nine'. Return the string with numbers sorted from largest to smallest >>> sort_numbers_descending('three one five') 'five three one'
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]))
return ' '.join((x for x in reversed(sort_numbers(numbers).split(' '))))
sort_numbers(numbers: str) -> str
sort_numbers_descending(numbers: str) -> str
from typing import List, Tuple
def find_closest_elements(numbers: List[float]) -> Tuple[float, float]: """From a supplied list of numbers (of length at least two) select and return two that are the closest to each other and return them in order (smaller number, larger number). >>> find_closest_elements([1.0, 2.0, 3.0, 4.0, 5.0, 2.2]) (2.0, 2.2) >>> find_closest_elements([1.0, 2.0, 3.0, 4.0, 5.0, 2.0]) (2.0, 2.0) """
def find_closest_elements(numbers: List[float]) -> Tuple[float, float]: """From a supplied list of numbers (of length at least two) select and return two that are the closest to each other and return them in order (smaller number, larger number). >>> find_closest_elements([1.0, 2.0, 3.0, 4.0, 5.0, 2.2]) (2.0, 2.2) >>> find_closest_elements([1.0, 2.0, 3.0, 4.0, 5.0, 2.0]) (2.0, 2.0) """ 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
find_closest_elements
def find_closest_distance(numbers: List[float]) -> float: """From a supplied list of numbers (of length at least two) select and return the distance between two that are the closest to each other. >>> find_closest_distance([1.0, 2.0, 3.0, 4.0, 5.0, 2.2]) 0.2 >>> find_closest_distance([1.0, 2.0, 3.0, 4.0, 5.0, 2.0]) 0.0 """
def find_closest_distance(numbers: List[float]) -> float: """From a supplied list of numbers (of length at least two) select and return the distance between two that are the closest to each other. >>> find_closest_distance([1.0, 2.0, 3.0, 4.0, 5.0, 2.2]) 0.2 >>> find_closest_distance([1.0, 2.0, 3.0, 4.0, 5.0, 2.0]) 0.0 """ (x, y) = find_closest_elements(numbers) return y - x
find_closest_distance
def check(candidate): assert round(candidate([1.7, 0.5, 3.1, 1.2, 2.1]), 2) == 0.4 assert round(candidate([3.0, 4.0, 5.0, 4.0, 3.9]), 2) == 0.0 assert round(candidate([1.0, 2.0, 3.0, 10.0]), 2) == 1.0 def test_check(): check(find_closest_distance) test_check()
[ "\ndef", "\n#", "\nif", "\nclass" ]
From a supplied list of numbers (of length at least two) select and return two that are the closest to each other and return them in order (smaller number, larger number). >>> find_closest_elements([1.0, 2.0, 3.0, 4.0, 5.0, 2.2]) (2.0, 2.2) >>> find_closest_elements([1.0, 2.0, 3.0, 4.0, 5.0, 2.0]) (2.0, 2.0)
From a supplied list of numbers (of length at least two) select and return the distance between two that are the closest to each other. >>> find_closest_distance([1.0, 2.0, 3.0, 4.0, 5.0, 2.2]) 0.2 >>> find_closest_distance([1.0, 2.0, 3.0, 4.0, 5.0, 2.0]) 0.0
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
(x, y) = find_closest_elements(numbers) return y - x
find_closest_elements(numbers: List[float]) -> Tuple[float, float]
find_closest_distance(numbers: List[float]) -> float
from typing import List
def rescale_to_unit(numbers: List[float]) -> List[float]: """Given list of numbers (of at least two elements), apply a linear transform to that list, such that the smallest number will become 0 and the largest will become 1 >>> rescale_to_unit([1.0, 2.0, 3.0, 4.0, 5.0]) [0.0, 0.25, 0.5, 0.75, 1.0] """
def rescale_to_unit(numbers: List[float]) -> List[float]: """Given list of numbers (of at least two elements), apply a linear transform to that list, such that the smallest number will become 0 and the largest will become 1 >>> rescale_to_unit([1.0, 2.0, 3.0, 4.0, 5.0]) [0.0, 0.25, 0.5, 0.75, 1.0] """ min_number = min(numbers) max_number = max(numbers) return [(x - min_number) / (max_number - min_number) for x in numbers]
rescale_to_unit
def rescale_to_percentile(numbers: List[float]) -> List[float]: """Given list of numbers (of at least two elements), apply a linear transform to that list, such that the smallest number will become 0 and the largest will become 100 >>> rescale_to_percentile([1.0, 2.0, 3.0, 4.0, 5.0]) [0.0, 25.0, 50.0, 75.0, 100.0] """
def rescale_to_percentile(numbers: List[float]) -> List[float]: """Given list of numbers (of at least two elements), apply a linear transform to that list, such that the smallest number will become 0 and the largest will become 100 >>> rescale_to_percentile([1.0, 2.0, 3.0, 4.0, 5.0]) [0.0, 25.0, 50.0, 75.0, 100.0] """ return [x * 100 for x in rescale_to_unit(numbers)]
rescale_to_percentile
def check(candidate): assert list(map(lambda x: round(x, 2), candidate([38.7, 91.9, 3.4, 94.7, 33.2, 19.1]))) == [38.66, 96.93, 0.0, 100.0, 32.64, 17.2] assert list(map(lambda x: round(x, 2), candidate([3.0, 4.0, 5.0, 4.0, 3.9]))) == [0.0, 50.0, 100.0, 50.0, 45.0] assert list(map(lambda x: round(x, 2), candidate([1.0, 2.0, 3.0, 10.0]))) == [0.0, 11.11, 22.22, 100.0] def test_check(): check(rescale_to_percentile) test_check()
[ "\ndef", "\n#", "\nif", "\nclass" ]
Given list of numbers (of at least two elements), apply a linear transform to that list, such that the smallest number will become 0 and the largest will become 1 >>> rescale_to_unit([1.0, 2.0, 3.0, 4.0, 5.0]) [0.0, 0.25, 0.5, 0.75, 1.0]
Given list of numbers (of at least two elements), apply a linear transform to that list, such that the smallest number will become 0 and the largest will become 100 >>> rescale_to_percentile([1.0, 2.0, 3.0, 4.0, 5.0]) [0.0, 25.0, 50.0, 75.0, 100.0]
min_number = min(numbers) max_number = max(numbers) return [(x - min_number) / (max_number - min_number) for x in numbers]
return [x * 100 for x in rescale_to_unit(numbers)]
rescale_to_unit(numbers: List[float]) -> List[float]
rescale_to_percentile(numbers: List[float]) -> List[float]
from typing import Any, List
def filter_integers(values: List[Any]) -> List[int]: """Filter given list of any python values only for integers >>> filter_integers(['a', 3.14, 5]) [5] >>> filter_integers([1, 2, 3, 'abc', { }, []]) [1, 2, 3] """
def filter_integers(values: List[Any]) -> List[int]: """Filter given list of any python values only for integers >>> filter_integers(['a', 3.14, 5]) [5] >>> filter_integers([1, 2, 3, 'abc', { }, []]) [1, 2, 3] """ return [x for x in values if isinstance(x, int)]
filter_integers
def get_second_integer(values: List[Any]) -> List[int]: """Return the second integer element in the list If there is no second integer element, return None >>> get_second_observed_integer(['a', 3.14, 5]) None >>> get_second_observed_integer([1, 2, 3, 'abc', {}, []]) 2 """
def get_second_integer(values: List[Any]) -> List[int]: """Return the second integer element in the list If there is no second integer element, return None >>> get_second_observed_integer(['a', 3.14, 5]) None >>> get_second_observed_integer([1, 2, 3, 'abc', {}, []]) 2 """ integers = filter_integers(values) if len(integers) < 2: return None return filter_integers(values)[1]
get_second_integer
def check(candidate): assert candidate([75, '75', 'scv', 7.3]) is None assert candidate(['wwkdjf', 'three', 97, 'wild', 3]) == 3 assert candidate([85, 92, 77, 94, 77]) == 92 def test_check(): check(get_second_integer) test_check()
[ "\ndef", "\n#", "\nif", "\nclass" ]
Filter given list of any python values only for integers >>> filter_integers(['a', 3.14, 5]) [5] >>> filter_integers([1, 2, 3, 'abc', { }, []]) [1, 2, 3]
Return the second integer element in the list If there is no second integer element, return None >>> get_second_observed_integer(['a', 3.14, 5]) None >>> get_second_observed_integer([1, 2, 3, 'abc', {}, []]) 2
return [x for x in values if isinstance(x, int)]
integers = filter_integers(values) if len(integers) < 2: return None return filter_integers(values)[1]
filter_integers(values: List[Any]) -> List[int]
get_second_integer(values: List[Any]) -> List[int]
def strlen(string: str) -> int: """Return length of given string >>> strlen('') 0 >>> strlen('abc') 3 """
def strlen(string: str) -> int: """Return length of given string >>> strlen('') 0 >>> strlen('abc') 3 """ return len(string)
strlen
def is_string_length_odd(string: str) -> str: """Return 'odd' if length of given string is odd, otherwise 'even' >>> is_string_length_odd('') 'even' >>> is_string_length_odd('abc') 'odd' """
def is_string_length_odd(string: str) -> str: """Return 'odd' if length of given string is odd, otherwise 'even' >>> is_string_length_odd('') 'even' >>> is_string_length_odd('abc') 'odd' """ return 'odd' if strlen(string) % 2 else 'even'
is_string_length_odd
def check(candidate): assert candidate('apple') == 'odd' assert candidate('working') == 'odd' assert candidate('book') == 'even' def test_check(): check(is_string_length_odd) test_check()
[ "\ndef", "\n#", "\nif", "\nclass" ]
Return length of given string >>> strlen('') 0 >>> strlen('abc') 3
Return 'odd' if length of given string is odd, otherwise 'even' >>> is_string_length_odd('') 'even' >>> is_string_length_odd('abc') 'odd'
return len(string)
return 'odd' if strlen(string) % 2 else 'even'
strlen(string: str) -> int
is_string_length_odd(string: str) -> str
def largest_divisor(n: int) -> int: """For a given number n, find the largest number that divides n evenly, smaller than n >>> largest_divisor(15) 5 """
def largest_divisor(n: int) -> int: """For a given number n, find the largest number that divides n evenly, smaller than n >>> largest_divisor(15) 5 """ for i in reversed(range(n)): if n % i == 0: return i
largest_divisor
def get_smallest_chunk_num(n: int) -> bool: """Given n, find the smallest k such that a number n can be made from k chunks of the same size. Chunk size must be smaller than n. >>> get_smallest_chunk_num(15) 3 """
def get_smallest_chunk_num(n: int) -> bool: """Given n, find the smallest k such that a number n can be made from k chunks of the same size. Chunk size must be smaller than n. >>> get_smallest_chunk_num(15) 3 """ return n // largest_divisor(n)
get_smallest_chunk_num
def check(candidate): assert candidate(370) == 2 assert candidate(23) == 23 assert candidate(77) == 7 def test_check(): check(get_smallest_chunk_num) test_check()
[ "\ndef", "\n#", "\nif", "\nclass" ]
For a given number n, find the largest number that divides n evenly, smaller than n >>> largest_divisor(15) 5
Given n, find the smallest k such that a number n can be made from k chunks of the same size. Chunk size must be smaller than n. >>> get_smallest_chunk_num(15) 3
for i in reversed(range(n)): if n % i == 0: return i
return n // largest_divisor(n)
largest_divisor(n: int) -> int
get_smallest_chunk_num(n: int) -> bool
from typing import List
def factorize(n: int) -> List[int]: """Return list of prime factors of given integer in the order from smallest to largest. Each of the factors should be listed number of times corresponding to how many times it appeares in factorization. Input number should be equal to the product of all factors >>> factorize(8) [2, 2, 2] >>> factorize(25) [5, 5] >>> factorize(70) [2, 5, 7] """
def factorize(n: int) -> List[int]: """Return list of prime factors of given integer in the order from smallest to largest. Each of the factors should be listed number of times corresponding to how many times it appeares in factorization. Input number should be equal to the product of all factors >>> factorize(8) [2, 2, 2] >>> factorize(25) [5, 5] >>> factorize(70) [2, 5, 7] """ 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
factorize
def count_unique_prime_factors(n: int) -> int: """Return the number of unique prime factors of given integer >>> count_unique_prime_factors(8) 1 >>> count_unique_prime_factors(25) 1 >>> count_unique_prime_factors(70) 3 """
def count_unique_prime_factors(n: int) -> int: """Return the number of unique prime factors of given integer >>> count_unique_prime_factors(8) 1 >>> count_unique_prime_factors(25) 1 >>> count_unique_prime_factors(70) 3 """ return len(set(factorize(n)))
count_unique_prime_factors
def check(candidate): assert candidate(910) == 4 assert candidate(256) == 1 assert candidate(936) == 3 def test_check(): check(count_unique_prime_factors) test_check()
[ "\ndef", "\n#", "\nif", "\nclass" ]
Return list of prime factors of given integer in the order from smallest to largest. Each of the factors should be listed number of times corresponding to how many times it appeares in factorization. Input number should be equal to the product of all factors >>> factorize(8) [2, 2, 2] >>> factorize(25) [5, 5] >>> factorize(70) [2, 5, 7]
Return the number of unique prime factors of given integer >>> count_unique_prime_factors(8) 1 >>> count_unique_prime_factors(25) 1 >>> count_unique_prime_factors(70) 3
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
return len(set(factorize(n)))
factorize(n: int) -> List[int]
count_unique_prime_factors(n: int) -> int
from typing import List
def remove_duplicates(numbers: List[int]) -> List[int]: """From a list of integers, remove all elements that occur more than once. Keep order of elements left the same as in the input. >>> remove_duplicates([1, 2, 3, 2, 4]) [1, 3, 4] """
def remove_duplicates(numbers: List[int]) -> List[int]: """From a list of integers, remove all elements that occur more than once. Keep order of elements left the same as in the input. >>> remove_duplicates([1, 2, 3, 2, 4]) [1, 3, 4] """ import collections c = collections.Counter(numbers) return [n for n in numbers if c[n] <= 1]
remove_duplicates
def count_duplicates(numbers: List[int]) -> int: """From a list of integers, count how many elements occur more than once. >>> count_duplicates([1, 2, 3, 2, 4]) 2 >>> count_duplicates([2, 2, 3, 2, 3]) 5 """
def count_duplicates(numbers: List[int]) -> int: """From a list of integers, count how many elements occur more than once. >>> count_duplicates([1, 2, 3, 2, 4]) 2 >>> count_duplicates([2, 2, 3, 2, 3]) 5 """ return len(numbers) - len(remove_duplicates(numbers))
count_duplicates
def check(candidate): assert candidate([9, 4, 3, 3, 3]) == 3 assert candidate([1, 2, 3, 4, 5, 6, 7, 8, 6, 4, 2]) == 6 assert candidate([96, 33, 27, 96, 2, 11]) == 2 def test_check(): check(count_duplicates) test_check()
[ "\ndef", "\n#", "\nif", "\nclass" ]
From a list of integers, remove all elements that occur more than once. Keep order of elements left the same as in the input. >>> remove_duplicates([1, 2, 3, 2, 4]) [1, 3, 4]
From a list of integers, count how many elements occur more than once. >>> count_duplicates([1, 2, 3, 2, 4]) 2 >>> count_duplicates([2, 2, 3, 2, 3]) 5
import collections c = collections.Counter(numbers) return [n for n in numbers if c[n] <= 1]
return len(numbers) - len(remove_duplicates(numbers))
remove_duplicates(numbers: List[int]) -> List[int]
count_duplicates(numbers: List[int]) -> int
def flip_case(string: str) -> str: """For a given string, flip lowercase characters to uppercase and uppercase to lowercase. >>> flip_case('Hello') 'hELLO' """
def flip_case(string: str) -> str: """For a given string, flip lowercase characters to uppercase and uppercase to lowercase. >>> flip_case('Hello') 'hELLO' """ return string.swapcase()
flip_case
def get_more_uppercase_word(string: str) -> str: """Return string if string has more or equal number of uppercase characters than the number of lowercase characters. Otherwise, return string whose characters are flipped by their case. >>> flip_alternative_words('Hello') 'hELLO' >>> flip_alternative_words('SotA') 'SotA' """
def get_more_uppercase_word(string: str) -> str: """Return string if string has more or equal number of uppercase characters than the number of lowercase characters. Otherwise, return string whose characters are flipped by their case. >>> flip_alternative_words('Hello') 'hELLO' >>> flip_alternative_words('SotA') 'SotA' """ if sum((1 for c in string if c.isupper())) >= sum((1 for c in string if c.islower())): return string else: return flip_case(string)
get_more_uppercase_word
def check(candidate): assert candidate('What') == 'wHAT' assert candidate('APpLe') == 'APpLe' assert candidate('noTeBooK') == 'NOtEbOOk' def test_check(): check(get_more_uppercase_word) test_check()
[ "\ndef", "\n#", "\nif", "\nclass" ]
For a given string, flip lowercase characters to uppercase and uppercase to lowercase. >>> flip_case('Hello') 'hELLO'
Return string if string has more or equal number of uppercase characters than the number of lowercase characters. Otherwise, return string whose characters are flipped by their case. >>> flip_alternative_words('Hello') 'hELLO' >>> flip_alternative_words('SotA') 'SotA'
return string.swapcase()
if sum((1 for c in string if c.isupper())) >= sum((1 for c in string if c.islower())): return string else: return flip_case(string)
flip_case(string: str) -> str
get_more_uppercase_word(string: str) -> str
from typing import List
def concatenate(strings: List[str]) -> str: """Concatenate list of strings into a single string >>> concatenate([]) '' >>> concatenate(['a', 'b', 'c']) 'abc' """
def concatenate(strings: List[str]) -> str: """Concatenate list of strings into a single string >>> concatenate([]) '' >>> concatenate(['a', 'b', 'c']) 'abc' """ return ''.join(strings)
concatenate
def create_multiline_string(strings: List[str]) -> str: """Create a multiline string from a list of strings. Note that last line should also end with a newline. If string is empty, return empty string. >>> create_multiline_string([]) '' >>> create_multiline_string(['a', 'b', 'c']) 'a\\nb\\nc ' """
def create_multiline_string(strings: List[str]) -> str: """Create a multiline string from a list of strings. Note that last line should also end with a newline. If string is empty, return empty string. >>> create_multiline_string([]) '' >>> create_multiline_string(['a', 'b', 'c']) 'a\\nb\\nc ' """ return concatenate([s + '\n' for s in strings])
create_multiline_string
def check(candidate): assert candidate(['return scroll', 'might be', ' .']) == 'return scroll\nmight be\n .\n' assert candidate(["I don't know"]) == "I don't know\n" assert candidate([]) == '' def test_check(): check(create_multiline_string) test_check()
[ "\ndef", "\n#", "\nif", "\nclass" ]
Concatenate list of strings into a single string >>> concatenate([]) '' >>> concatenate(['a', 'b', 'c']) 'abc'
Create a multiline string from a list of strings. Note that last line should also end with a newline. If string is empty, return empty string. >>> create_multiline_string([]) '' >>> create_multiline_string(['a', 'b', 'c']) 'a\nb\nc '
return ''.join(strings)
return concatenate([s + '\n' for s in strings])
concatenate(strings: List[str]) -> str
create_multiline_string(strings: List[str]) -> str
from typing import List
def filter_by_prefix(strings: List[str], prefix: str) -> List[str]: """Filter an input list of strings only for ones that start with a given prefix. >>> filter_by_prefix([], 'a') [] >>> filter_by_prefix(['abc', 'bcd', 'cde', 'array'], 'a') ['abc', 'array'] """
def filter_by_prefix(strings: List[str], prefix: str) -> List[str]: """Filter an input list of strings only for ones that start with a given prefix. >>> filter_by_prefix([], 'a') [] >>> filter_by_prefix(['abc', 'bcd', 'cde', 'array'], 'a') ['abc', 'array'] """ return [x for x in strings if x.startswith(prefix)]
filter_by_prefix
def create_autocomplete_options(input: str, options: List[str]) -> List[str]: """Create autocomplete options for a given input string from a list of options. Options should be sorted alphabetically. >>> create_autocomplete_options('a', []) [] >>> create_autocomplete_options('a', ['abc', 'bcd', 'cde', 'array']) ['abc', 'array'] """
def create_autocomplete_options(input: str, options: List[str]) -> List[str]: """Create autocomplete options for a given input string from a list of options. Options should be sorted alphabetically. >>> create_autocomplete_options('a', []) [] >>> create_autocomplete_options('a', ['abc', 'bcd', 'cde', 'array']) ['abc', 'array'] """ return sorted(filter_by_prefix(options, input))
create_autocomplete_options
def check(candidate): assert candidate('mac', ['machanic', 'machine', 'mad', 'sort']) == ['machanic', 'machine'] assert candidate('le', ['learning', 'lora', 'lecun', 'lemon']) == ['learning', 'lecun', 'lemon'] assert candidate('program', ['array', 'bolt', 'programming', 'program']) == ['program', 'programming'] def test_check(): check(create_autocomplete_options) test_check()
[ "\ndef", "\n#", "\nif", "\nclass" ]
Filter an input list of strings only for ones that start with a given prefix. >>> filter_by_prefix([], 'a') [] >>> filter_by_prefix(['abc', 'bcd', 'cde', 'array'], 'a') ['abc', 'array']
Create autocomplete options for a given input string from a list of options. Options should be sorted alphabetically. >>> create_autocomplete_options('a', []) [] >>> create_autocomplete_options('a', ['abc', 'bcd', 'cde', 'array']) ['abc', 'array']
return [x for x in strings if x.startswith(prefix)]
return sorted(filter_by_prefix(options, input))
filter_by_prefix(strings: List[str], prefix: str) -> List[str]
create_autocomplete_options(input: str, options: List[str]) -> List[str]
from typing import List
def get_positive(l: List[int]) -> List[int]: """Return only positive numbers in the list. >>> get_positive([-1, 2, -4, 5, 6]) [2, 5, 6] >>> get_positive([5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) [5, 3, 2, 3, 9, 123, 1] """
def get_positive(l: List[int]) -> List[int]: """Return only positive numbers in the list. >>> get_positive([-1, 2, -4, 5, 6]) [2, 5, 6] >>> get_positive([5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) [5, 3, 2, 3, 9, 123, 1] """ return [e for e in l if e > 0]
get_positive
def sum_positive(l: list) -> int: """Return the sum of all positive numbers in the list. >>> sum_positive([-1, 2, -4, 5, 6]) 13 >>> sum_positive([5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) 146 """
def sum_positive(l: list) -> int: """Return the sum of all positive numbers in the list. >>> sum_positive([-1, 2, -4, 5, 6]) 13 >>> sum_positive([5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) 146 """ return sum(get_positive(l))
sum_positive
def check(candidate): assert candidate([40, 0, 4]) == 44 assert candidate([-1, -2, -3, -4]) == 0 assert candidate([7, -6, 10, -22, -1, 0]) == 17 def test_check(): check(sum_positive) test_check()
[ "\ndef", "\n#", "\nif", "\nclass" ]
Return only positive numbers in the list. >>> get_positive([-1, 2, -4, 5, 6]) [2, 5, 6] >>> get_positive([5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) [5, 3, 2, 3, 9, 123, 1]
Return the sum of all positive numbers in the list. >>> sum_positive([-1, 2, -4, 5, 6]) 13 >>> sum_positive([5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) 146
return [e for e in l if e > 0]
return sum(get_positive(l))
get_positive(l: List[int]) -> List[int]
sum_positive(l: list) -> int
def is_prime(n: int) -> bool: """Return true if a given number is prime, and false otherwise. >>> is_prime(6) False >>> is_prime(101) True >>> is_prime(11) True >>> is_prime(13441) True >>> is_prime(61) True >>> is_prime(4) False >>> is_prime(1) False """
def is_prime(n: int) -> bool: """Return true if a given number is prime, and false otherwise. >>> is_prime(6) False >>> is_prime(101) True >>> is_prime(11) True >>> is_prime(13441) True >>> is_prime(61) True >>> is_prime(4) False >>> is_prime(1) False """ if n < 2: return False for k in range(2, n - 1): if n % k == 0: return False return True
is_prime
def get_prime_times_prime(n: int) -> bool: """Returns a sorted list of numbers less than n that are the product of two distinct primes. >>> get_number(6) [] >>> get_number(20) [6, 10, 14, 15] """
def get_prime_times_prime(n: int) -> bool: """Returns a sorted list of numbers less than n that are the product of two distinct primes. >>> get_number(6) [] >>> get_number(20) [6, 10, 14, 15] """ primes = [i for i in range(2, n) if is_prime(i)] results = [] for i in range(len(primes)): for j in range(i + 1, len(primes)): if primes[i] * primes[j] < n: results.append(primes[i] * primes[j]) return sorted(results)
get_prime_times_prime
def check(candidate): assert candidate(35) == [6, 10, 14, 15, 21, 22, 26, 33, 34] assert candidate(49) == [6, 10, 14, 15, 21, 22, 26, 33, 34, 35, 38, 39, 46] assert candidate(100) == [6, 10, 14, 15, 21, 22, 26, 33, 34, 35, 38, 39, 46, 51, 55, 57, 58, 62, 65, 69, 74, 77, 82, 85, 86, 87, 91, 93, 94, 95] def test_check(): check(get_prime_times_prime) test_check()
[ "\ndef", "\n#", "\nif", "\nclass" ]
Return true if a given number is prime, and false otherwise. >>> is_prime(6) False >>> is_prime(101) True >>> is_prime(11) True >>> is_prime(13441) True >>> is_prime(61) True >>> is_prime(4) False >>> is_prime(1) False
Returns a sorted list of numbers less than n that are the product of two distinct primes. >>> get_number(6) [] >>> get_number(20) [6, 10, 14, 15]
if n < 2: return False for k in range(2, n - 1): if n % k == 0: return False return True
primes = [i for i in range(2, n) if is_prime(i)] results = [] for i in range(len(primes)): for j in range(i + 1, len(primes)): if primes[i] * primes[j] < n: results.append(primes[i] * primes[j]) return sorted(results)
is_prime(n: int) -> bool
get_prime_times_prime(n: int) -> bool
from typing import List
def sort_third(l: List[int]) -> List[int]: """This function takes a list l and returns a list l' such that l' is identical to l in the indicies that are not divisible by three, while its values at the indicies that are divisible by three are equal to the values of the corresponding indicies of l, but sorted. >>> sort_third([1, 2, 3]) [1, 2, 3] >>> sort_third([5, 6, 3, 4, 8, 9, 2]) [2, 6, 3, 4, 8, 9, 5] """
def sort_third(l: List[int]) -> List[int]: """This function takes a list l and returns a list l' such that l' is identical to l in the indicies that are not divisible by three, while its values at the indicies that are divisible by three are equal to the values of the corresponding indicies of l, but sorted. >>> sort_third([1, 2, 3]) [1, 2, 3] >>> sort_third([5, 6, 3, 4, 8, 9, 2]) [2, 6, 3, 4, 8, 9, 5] """ l = list(l) l[::3] = sorted(l[::3]) return l
sort_third
def sort_first_column(l: List[List[int]]): """This function takes an array of n by 3. It returns an array of N x 3 such that the elements in the first column are sorted. >>> sort_last_column([[1, 2, 3], [9, 6, 4], [5, 3, 2]]) [[1, 2, 3], [5, 6, 4], [9, 3, 2]] >>> sort_last_column([[8, 9, 8], [6, 6, 6], [2, 9, 1]]) [[2, 9, 8], [6, 6, 6], [8, 9, 1]] """
def sort_first_column(l: List[List[int]]): """This function takes an array of n by 3. It returns an array of N x 3 such that the elements in the first column are sorted. >>> sort_last_column([[1, 2, 3], [9, 6, 4], [5, 3, 2]]) [[1, 2, 3], [5, 6, 4], [9, 3, 2]] >>> sort_last_column([[8, 9, 8], [6, 6, 6], [2, 9, 1]]) [[2, 9, 8], [6, 6, 6], [8, 9, 1]] """ l = [y for x in l for y in x] l = sort_third(l) return [[l[3 * i], l[3 * i + 1], l[3 * i + 2]] for i in range(len(l) // 3)]
sort_first_column
def check(candidate): assert candidate([[5, 9, 2], [4, 3, 11], [2, 67, 4]]) == [[2, 9, 2], [4, 3, 11], [5, 67, 4]] assert candidate([[32, 5, 7], [25, 4, 32]]) == [[25, 5, 7], [32, 4, 32]] assert candidate([[4, 8, 3], [9, 5, 2], [1, 5, 2], [5, 5, 8]]) == [[1, 8, 3], [4, 5, 2], [5, 5, 2], [9, 5, 8]] def test_check(): check(sort_first_column) test_check()
[ "\ndef", "\n#", "\nif", "\nclass" ]
This function takes a list l and returns a list l' such that l' is identical to l in the indicies that are not divisible by three, while its values at the indicies that are divisible by three are equal to the values of the corresponding indicies of l, but sorted. >>> sort_third([1, 2, 3]) [1, 2, 3] >>> sort_third([5, 6, 3, 4, 8, 9, 2]) [2, 6, 3, 4, 8, 9, 5]
This function takes an array of n by 3. It returns an array of N x 3 such that the elements in the first column are sorted. >>> sort_last_column([[1, 2, 3], [9, 6, 4], [5, 3, 2]]) [[1, 2, 3], [5, 6, 4], [9, 3, 2]] >>> sort_last_column([[8, 9, 8], [6, 6, 6], [2, 9, 1]]) [[2, 9, 8], [6, 6, 6], [8, 9, 1]]
l = list(l) l[::3] = sorted(l[::3]) return l
l = [y for x in l for y in x] l = sort_third(l) return [[l[3 * i], l[3 * i + 1], l[3 * i + 2]] for i in range(len(l) // 3)]
sort_third(l: List[int]) -> List[int]
sort_first_column(l: List[List[int]])
from typing import List
def max_element(l: List[int]) -> int: """Return maximum element in the list. >>> max_element([1, 2, 3]) 3 >>> max_element([5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) 123 """
def max_element(l: List[int]) -> int: """Return maximum element in the list. >>> max_element([1, 2, 3]) 3 >>> max_element([5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) 123 """ m = l[0] for e in l: if e > m: m = e return m
max_element
def max_element_nested_list(l: list): """Return maximum element in a nested list. l could be nested by any depth. >>> max_element_nested_list([1, 2, 3]) 3 >>> max_element_nested_list([[5, 3], [[-5], [2, -3, 3], [[9, 0], [123]], 1], -10]) 123 """
def max_element_nested_list(l: list): """Return maximum element in a nested list. l could be nested by any depth. >>> max_element_nested_list([1, 2, 3]) 3 >>> max_element_nested_list([[5, 3], [[-5], [2, -3, 3], [[9, 0], [123]], 1], -10]) 123 """ return max_element([max_element_nested_list(e) if isinstance(e, list) else e for e in l])
max_element_nested_list
def check(candidate): assert candidate([[1, 2], [3], [[4], [5, 6]]]) == 6 assert candidate([[[[6]], [5, 4, 3, 2], [1]], 0]) == 6 assert candidate([53, [23, [34, 23], [22, 15, 52]]]) == 53 def test_check(): check(max_element_nested_list) test_check()
[ "\ndef", "\n#", "\nif", "\nclass" ]
Return maximum element in the list. >>> max_element([1, 2, 3]) 3 >>> max_element([5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) 123
Return maximum element in a nested list. l could be nested by any depth. >>> max_element_nested_list([1, 2, 3]) 3 >>> max_element_nested_list([[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
return max_element([max_element_nested_list(e) if isinstance(e, list) else e for e in l])
max_element(l: List[int]) -> int
max_element_nested_list(l: list)
def fizz_buzz(n: int) -> int: """Return the number of times the digit 7 appears in integers less than n which are divisible by 11 or 13. >>> fizz_buzz(50) 0 >>> fizz_buzz(78) 2 >>> fizz_buzz(79) 3 """
def fizz_buzz(n: int) -> int: """Return the number of times the digit 7 appears in integers less than n which are divisible by 11 or 13. >>> fizz_buzz(50) 0 >>> fizz_buzz(78) 2 >>> fizz_buzz(79) 3 """ 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
fizz_buzz
def lucky_number(k: int) -> int: """Return the smallest non-negative number n that the digit 7 appears at least k times in integers less than n which are divisible by 11 or 13. >>> lucky_number(3) 79 >>> lucky_number(0) 0 """
def lucky_number(k: int) -> int: """Return the smallest non-negative number n that the digit 7 appears at least k times in integers less than n which are divisible by 11 or 13. >>> lucky_number(3) 79 >>> lucky_number(0) 0 """ n = 0 while fizz_buzz(n) < k: n += 1 return n
lucky_number
def check(candidate): assert candidate(1) == 78 assert candidate(2) == 78 assert candidate(4) == 118 def test_check(): check(lucky_number) test_check()
[ "\ndef", "\n#", "\nif", "\nclass" ]
Return the number of times the digit 7 appears in integers less than n which are divisible by 11 or 13. >>> fizz_buzz(50) 0 >>> fizz_buzz(78) 2 >>> fizz_buzz(79) 3
Return the smallest non-negative number n that the digit 7 appears at least k times in integers less than n which are divisible by 11 or 13. >>> lucky_number(3) 79 >>> lucky_number(0) 0
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
n = 0 while fizz_buzz(n) < k: n += 1 return n
fizz_buzz(n: int) -> int
lucky_number(k: int) -> int
def sort_even(l: list[int]) -> list[int]: """This function takes a list l and returns a list l' such that l' is identical to l in the odd indicies, while its values at the even indicies are equal to the values of the even indicies of l, but sorted. >>> sort_even([1, 2, 3]) [1, 2, 3] >>> sort_even([5, 6, 3, 4]) [3, 6, 5, 4] """
def sort_even(l: list[int]) -> list[int]: """This function takes a list l and returns a list l' such that l' is identical to l in the odd indicies, while its values at the even indicies are equal to the values of the even indicies of l, but sorted. >>> sort_even([1, 2, 3]) [1, 2, 3] >>> sort_even([5, 6, 3, 4]) [3, 6, 5, 4] """ 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
sort_even
def paired_sort(l: list[int]) -> list[int]: """This function takes a list l and returns a list l' such that l' is sorted to l in the odd indicies, also its values at the even indicies are equal to the values of the even indicies of l, but sorted. >>> sort_even([1, 2, 3]) [1, 2, 3] >>> sort_even([5, 6, 3, 4]) [3, 4, 5, 6] """
def paired_sort(l: list[int]) -> list[int]: """This function takes a list l and returns a list l' such that l' is sorted to l in the odd indicies, also its values at the even indicies are equal to the values of the even indicies of l, but sorted. >>> sort_even([1, 2, 3]) [1, 2, 3] >>> sort_even([5, 6, 3, 4]) [3, 4, 5, 6] """ l = [l[0]] + sort_even(l[1:]) l = sort_even(l) return l
paired_sort
def check(candidate): assert candidate([5, 2, 4, 3]) == [4, 2, 5, 3] assert candidate([5, 4, 8, 6, 4, 2]) == [4, 2, 5, 4, 8, 6] assert candidate([1, 7, 8, 9, 4, 3, 8]) == [1, 3, 4, 7, 8, 9, 8] def test_check(): check(paired_sort) test_check()
[ "\ndef", "\n#", "\nif", "\nclass" ]
This function takes a list l and returns a list l' such that l' is identical to l in the odd indicies, while its values at the even indicies are equal to the values of the even indicies of l, but sorted. >>> sort_even([1, 2, 3]) [1, 2, 3] >>> sort_even([5, 6, 3, 4]) [3, 6, 5, 4]
This function takes a list l and returns a list l' such that l' is sorted to l in the odd indicies, also its values at the even indicies are equal to the values of the even indicies of l, but sorted. >>> sort_even([1, 2, 3]) [1, 2, 3] >>> sort_even([5, 6, 3, 4]) [3, 4, 5, 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
l = [l[0]] + sort_even(l[1:]) l = sort_even(l) return l
sort_even(l: list[int]) -> list[int]
paired_sort(l: list[int]) -> list[int]
def prime_fib(n: int) -> int: """ prime_fib returns n-th number that is a Fibonacci number and it's also prime. >>> prime_fib(1) 2 >>> prime_fib(2) 3 >>> prime_fib(3) 5 >>> prime_fib(4) 13 >>> prime_fib(5) 89 """
def prime_fib(n: int) -> int: """ prime_fib returns n-th number that is a Fibonacci number and it's also prime. >>> prime_fib(1) 2 >>> prime_fib(2) 3 >>> prime_fib(3) 5 >>> prime_fib(4) 13 >>> prime_fib(5) 89 """ 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]
prime_fib
def prime_fib_diff(n: int): """Return the difference between the n-th number that is a Fibonacci number and it's also prime and the (n+1)-th number that is a Fibonacci number and it's also prime. >>> prime_fib_dif(1) 1 >>> prime_fib_dif(2) 2 >>> prime_fib_dif(3) 8 >>> prime_fib_dif(4) 76 """
def prime_fib_diff(n: int): """Return the difference between the n-th number that is a Fibonacci number and it's also prime and the (n+1)-th number that is a Fibonacci number and it's also prime. >>> prime_fib_dif(1) 1 >>> prime_fib_dif(2) 2 >>> prime_fib_dif(3) 8 >>> prime_fib_dif(4) 76 """ return prime_fib(n + 1) - prime_fib(n)
prime_fib_diff
def check(candidate): assert candidate(8) == 485572 assert candidate(3) == 8 assert candidate(10) == 2537720636 def test_check(): check(prime_fib_diff) test_check()
[ "\ndef", "\n#", "\nif", "\nclass" ]
prime_fib returns n-th number that is a Fibonacci number and it's also prime. >>> prime_fib(1) 2 >>> prime_fib(2) 3 >>> prime_fib(3) 5 >>> prime_fib(4) 13 >>> prime_fib(5) 89
Return the difference between the n-th number that is a Fibonacci number and it's also prime and the (n+1)-th number that is a Fibonacci number and it's also prime. >>> prime_fib_dif(1) 1 >>> prime_fib_dif(2) 2 >>> prime_fib_dif(3) 8 >>> prime_fib_dif(4) 76
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]
return prime_fib(n + 1) - prime_fib(n)
prime_fib(n: int) -> int
prime_fib_diff(n: int)
def triples_sum_to_zero(l: list[int]) -> bool: """ triples_sum_to_zero takes a list of integers as an input. it returns True if there are three distinct elements in the list that sum to zero, and False otherwise. >>> triples_sum_to_zero([1, 3, 5, 0]) False >>> triples_sum_to_zero([1, 3, -2, 1]) True >>> triples_sum_to_zero([1, 2, 3, 7]) False >>> triples_sum_to_zero([2, 4, -5, 3, 9, 7]) True >>> triples_sum_to_zero([1]) False """
def triples_sum_to_zero(l: list[int]) -> bool: """ triples_sum_to_zero takes a list of integers as an input. it returns True if there are three distinct elements in the list that sum to zero, and False otherwise. >>> triples_sum_to_zero([1, 3, 5, 0]) False >>> triples_sum_to_zero([1, 3, -2, 1]) True >>> triples_sum_to_zero([1, 2, 3, 7]) False >>> triples_sum_to_zero([2, 4, -5, 3, 9, 7]) True >>> triples_sum_to_zero([1]) False """ 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
triples_sum_to_zero
def get_shortest_prefix_triples_sum_to_zero(l: list) -> list: """ get_shortest_prefix_triples_sum_to_zero takes a list of integers as an input. it returns the shortest prefix of the list such that there are three distinct elements in the prefix that sum to zero, and an empty list if no such prefix exists. >>> get_shortest_prefix_triples_sum_to_zero([1, 3, 5, 0]) [] >>> get_shortest_prefix_triples_sum_to_zero([1, 3, -2, 1]) [1, 3, -2] >>> get_shortest_prefix_triples_sum_to_zero([1, 2, 3, 7]) [] >>> get_shortest_prefix_triples_sum_to_zero([2, 4, -5, 3, 9, 7]) [2, 4, -5, 3] >>> get_shortest_prefix_triples_sum_to_zero([1]) [] """
def get_shortest_prefix_triples_sum_to_zero(l: list) -> list: """ get_shortest_prefix_triples_sum_to_zero takes a list of integers as an input. it returns the shortest prefix of the list such that there are three distinct elements in the prefix that sum to zero, and an empty list if no such prefix exists. >>> get_shortest_prefix_triples_sum_to_zero([1, 3, 5, 0]) [] >>> get_shortest_prefix_triples_sum_to_zero([1, 3, -2, 1]) [1, 3, -2] >>> get_shortest_prefix_triples_sum_to_zero([1, 2, 3, 7]) [] >>> get_shortest_prefix_triples_sum_to_zero([2, 4, -5, 3, 9, 7]) [2, 4, -5, 3] >>> get_shortest_prefix_triples_sum_to_zero([1]) [] """ for i in range(1, len(l) + 1): if triples_sum_to_zero(l[:i]): return l[:i] return []
get_shortest_prefix_triples_sum_to_zero
def check(candidate): assert candidate([4, 8, 8, -16, 3]) == [4, 8, 8, -16] assert candidate([-5, 2, 2, 1, 0]) == [] assert candidate([3, 2, -9, -8, 6, 7]) == [3, 2, -9, -8, 6] def test_check(): check(get_shortest_prefix_triples_sum_to_zero) test_check()
[ "\ndef", "\n#", "\nif", "\nclass" ]
triples_sum_to_zero takes a list of integers as an input. it returns True if there are three distinct elements in the list that sum to zero, and False otherwise. >>> triples_sum_to_zero([1, 3, 5, 0]) False >>> triples_sum_to_zero([1, 3, -2, 1]) True >>> triples_sum_to_zero([1, 2, 3, 7]) False >>> triples_sum_to_zero([2, 4, -5, 3, 9, 7]) True >>> triples_sum_to_zero([1]) False
get_shortest_prefix_triples_sum_to_zero takes a list of integers as an input. it returns the shortest prefix of the list such that there are three distinct elements in the prefix that sum to zero, and an empty list if no such prefix exists. >>> get_shortest_prefix_triples_sum_to_zero([1, 3, 5, 0]) [] >>> get_shortest_prefix_triples_sum_to_zero([1, 3, -2, 1]) [1, 3, -2] >>> get_shortest_prefix_triples_sum_to_zero([1, 2, 3, 7]) [] >>> get_shortest_prefix_triples_sum_to_zero([2, 4, -5, 3, 9, 7]) [2, 4, -5, 3] >>> get_shortest_prefix_triples_sum_to_zero([1]) []
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
for i in range(1, len(l) + 1): if triples_sum_to_zero(l[:i]): return l[:i] return []
triples_sum_to_zero(l: list[int]) -> bool
get_shortest_prefix_triples_sum_to_zero(l: list) -> list
def car_race_collision(n: int) -> int: """ Imagine a road that's a perfectly straight infinitely long line. n cars are driving left to right; simultaneously, a different set of n cars are driving right to left. The two sets of cars start out being very far from each other. All cars move in the same speed. Two cars are said to collide when a car that's moving left to right hits a car that's moving right to left. However, the cars are infinitely sturdy and strong; as a result, they continue moving in their trajectory as if they did not collide. This function outputs the number of such collisions. """
def car_race_collision(n: int) -> int: """ Imagine a road that's a perfectly straight infinitely long line. n cars are driving left to right; simultaneously, a different set of n cars are driving right to left. The two sets of cars start out being very far from each other. All cars move in the same speed. Two cars are said to collide when a car that's moving left to right hits a car that's moving right to left. However, the cars are infinitely sturdy and strong; as a result, they continue moving in their trajectory as if they did not collide. This function outputs the number of such collisions. """ return n ** 2
car_race_collision
def ball_collision(n: int): """Imagine a road that's a perfectly straight infinitely long line. n balls are rolling left to right; simultaneously, a different set of n balls are rolling right to left. The two sets of balls start out being very far from each other. All balls move in the same speed. Two balls are said to collide when a ball that's moving left to right hits a ball that's moving right to left. However, the balls are infinitely sturdy and strong; as a result, they continue moving in their trajectory as if they did not collide. This function outputs the number of such collisions. """
def ball_collision(n: int): """Imagine a road that's a perfectly straight infinitely long line. n balls are rolling left to right; simultaneously, a different set of n balls are rolling right to left. The two sets of balls start out being very far from each other. All balls move in the same speed. Two balls are said to collide when a ball that's moving left to right hits a ball that's moving right to left. However, the balls are infinitely sturdy and strong; as a result, they continue moving in their trajectory as if they did not collide. This function outputs the number of such collisions. """ return car_race_collision(n)
ball_collision
def check(candidate): assert candidate(15) == 225 assert candidate(4) == 16 assert candidate(9) == 81 def test_check(): check(ball_collision) test_check()
[ "\ndef", "\n#", "\nif", "\nclass" ]
Imagine a road that's a perfectly straight infinitely long line. n cars are driving left to right; simultaneously, a different set of n cars are driving right to left. The two sets of cars start out being very far from each other. All cars move in the same speed. Two cars are said to collide when a car that's moving left to right hits a car that's moving right to left. However, the cars are infinitely sturdy and strong; as a result, they continue moving in their trajectory as if they did not collide. This function outputs the number of such collisions.
Imagine a road that's a perfectly straight infinitely long line. n balls are rolling left to right; simultaneously, a different set of n balls are rolling right to left. The two sets of balls start out being very far from each other. All balls move in the same speed. Two balls are said to collide when a ball that's moving left to right hits a ball that's moving right to left. However, the balls are infinitely sturdy and strong; as a result, they continue moving in their trajectory as if they did not collide. This function outputs the number of such collisions.
return n ** 2
return car_race_collision(n)
car_race_collision(n: int) -> int
ball_collision(n: int)
def incr_list(l: list[int]) -> list[int]: """Return list with elements incremented by 1. >>> incr_list([1, 2, 3]) [2, 3, 4] >>> incr_list([5, 3, 5, 2, 3, 3, 9, 0, 123]) [6, 4, 6, 3, 4, 4, 10, 1, 124] """
def incr_list(l: list[int]) -> list[int]: """Return list with elements incremented by 1. >>> incr_list([1, 2, 3]) [2, 3, 4] >>> incr_list([5, 3, 5, 2, 3, 3, 9, 0, 123]) [6, 4, 6, 3, 4, 4, 10, 1, 124] """ return [e + 1 for e in l]
incr_list
def incr_sublist(l: list, start: int, end: int): """Return list that the element in the sublist from `start` (inclusive) to `end` (exclusive) incremented by 1. >>> incr_until_10([1, 2, 3], 0, 2) [2, 3, 3] >>> incr_until_10([5, 3, 5, 2, 3, 3, 9, 0, 123], 3, 7) [5, 3, 5, 3, 4, 4, 10, 0, 123] """
def incr_sublist(l: list, start: int, end: int): """Return list that the element in the sublist from `start` (inclusive) to `end` (exclusive) incremented by 1. >>> incr_until_10([1, 2, 3], 0, 2) [2, 3, 3] >>> incr_until_10([5, 3, 5, 2, 3, 3, 9, 0, 123], 3, 7) [5, 3, 5, 3, 4, 4, 10, 0, 123] """ return l[:start] + incr_list(l[start:end]) + l[end:]
incr_sublist
def check(candidate): assert candidate([3, 6, 32, 6, 8, 8], 2, 6) == [3, 6, 33, 7, 9, 9] assert candidate([8, 1, 5, 2, 7, 89, 9, 5, 4], 4, 8) == [8, 1, 5, 2, 8, 90, 10, 6, 4] assert candidate([1, 56, 5, 24, 9, 45, 6, 34], 3, 4) == [1, 56, 5, 25, 9, 45, 6, 34] def test_check(): check(incr_sublist) test_check()
[ "\ndef", "\n#", "\nif", "\nclass" ]
Return list with elements incremented by 1. >>> incr_list([1, 2, 3]) [2, 3, 4] >>> incr_list([5, 3, 5, 2, 3, 3, 9, 0, 123]) [6, 4, 6, 3, 4, 4, 10, 1, 124]
Return list that the element in the sublist from `start` (inclusive) to `end` (exclusive) incremented by 1. >>> incr_until_10([1, 2, 3], 0, 2) [2, 3, 3] >>> incr_until_10([5, 3, 5, 2, 3, 3, 9, 0, 123], 3, 7) [5, 3, 5, 3, 4, 4, 10, 0, 123]
return [e + 1 for e in l]
return l[:start] + incr_list(l[start:end]) + l[end:]
incr_list(l: list[int]) -> list[int]
incr_sublist(l: list, start: int, end: int)
from typing import List
def pairs_sum_to_zero(l: List[int]) -> bool: """ pairs_sum_to_zero takes a list of integers as an input. it returns True if there are two distinct elements in the list that sum to zero, and False otherwise. >>> pairs_sum_to_zero([1, 3, 5, 0]) False >>> pairs_sum_to_zero([1, 3, -2, 1]) False >>> pairs_sum_to_zero([1, 2, 3, 7]) False >>> pairs_sum_to_zero([2, 4, -5, 3, 5, 7]) True >>> pairs_sum_to_zero([1]) False """
def pairs_sum_to_zero(l: List[int]) -> bool: """ pairs_sum_to_zero takes a list of integers as an input. it returns True if there are two distinct elements in the list that sum to zero, and False otherwise. >>> pairs_sum_to_zero([1, 3, 5, 0]) False >>> pairs_sum_to_zero([1, 3, -2, 1]) False >>> pairs_sum_to_zero([1, 2, 3, 7]) False >>> pairs_sum_to_zero([2, 4, -5, 3, 5, 7]) True >>> pairs_sum_to_zero([1]) False """ for (i, l1) in enumerate(l): for j in range(i + 1, len(l)): if l1 + l[j] == 0: return True return False
pairs_sum_to_zero
def triple_sum_to_zero_with_zero(l): """triple_sum_to_zero_with_zero takes a list of integers as an input. it returns True if there are three distinct elements in the list that sum to zero and one of elements must be zero, and False otherwise. >>> triple_sum_to_zero_with_zero([1, 3, -1, 0]) True >>> triple_sum_to_zero_with_zero([1, 3, -2, 1]) False >>> triple_sum_to_zero_with_zero([1, 2, 3, 7]) False >>> triple_sum_to_zero_with_zero([2, 4, -5, 0, 3, 5, 7]) True >>> triple_sum_to_zero_with_zero([1]) False """
def triple_sum_to_zero_with_zero(l): """triple_sum_to_zero_with_zero takes a list of integers as an input. it returns True if there are three distinct elements in the list that sum to zero and one of elements must be zero, and False otherwise. >>> triple_sum_to_zero_with_zero([1, 3, -1, 0]) True >>> triple_sum_to_zero_with_zero([1, 3, -2, 1]) False >>> triple_sum_to_zero_with_zero([1, 2, 3, 7]) False >>> triple_sum_to_zero_with_zero([2, 4, -5, 0, 3, 5, 7]) True >>> triple_sum_to_zero_with_zero([1]) False """ if 0 not in l: return False else: l.remove(0) return pairs_sum_to_zero(l)
triple_sum_to_zero_with_zero
def check(candidate): assert candidate([3, 6, 32, 6, 8, 8]) == False assert candidate([-8, 1, 0, -5, 2, 7, -89, 9, 5, -4]) == True assert candidate([1, 0, 56, -5, -24, 9, -45, 6, 34]) == False def test_check(): check(triple_sum_to_zero_with_zero) test_check()
[ "\ndef", "\n#", "\nif", "\nclass" ]
pairs_sum_to_zero takes a list of integers as an input. it returns True if there are two distinct elements in the list that sum to zero, and False otherwise. >>> pairs_sum_to_zero([1, 3, 5, 0]) False >>> pairs_sum_to_zero([1, 3, -2, 1]) False >>> pairs_sum_to_zero([1, 2, 3, 7]) False >>> pairs_sum_to_zero([2, 4, -5, 3, 5, 7]) True >>> pairs_sum_to_zero([1]) False
triple_sum_to_zero_with_zero takes a list of integers as an input. it returns True if there are three distinct elements in the list that sum to zero and one of elements must be zero, and False otherwise. >>> triple_sum_to_zero_with_zero([1, 3, -1, 0]) True >>> triple_sum_to_zero_with_zero([1, 3, -2, 1]) False >>> triple_sum_to_zero_with_zero([1, 2, 3, 7]) False >>> triple_sum_to_zero_with_zero([2, 4, -5, 0, 3, 5, 7]) True >>> triple_sum_to_zero_with_zero([1]) False
for (i, l1) in enumerate(l): for j in range(i + 1, len(l)): if l1 + l[j] == 0: return True return False
if 0 not in l: return False else: l.remove(0) return pairs_sum_to_zero(l)
pairs_sum_to_zero(l: List[int]) -> bool
triple_sum_to_zero_with_zero(l)
def change_base(x: int, base: int) -> str: """Change numerical base of input number x to base. return string representation after the conversion. base numbers are less than 10. >>> change_base(8, 3) '22' >>> change_base(8, 2) '1000' >>> change_base(7, 2) '111' """
def change_base(x: int, base: int) -> str: """Change numerical base of input number x to base. return string representation after the conversion. base numbers are less than 10. >>> change_base(8, 3) '22' >>> change_base(8, 2) '1000' >>> change_base(7, 2) '111' """ ret = '' while x > 0: ret = str(x % base) + ret x //= base return ret
change_base
def change_base_extension(n: str, base_from: int, base_to: int) -> str: """Change numerical base of input number n represented as string from base_from to base_to. return string representation after the conversion. base numbers are less than 10. >>> change_base_extension('22', 3, 2) '1000' >>> change_base_extension('1000', 2, 3) '22' >>> change_base_extension('111', 2, 10) '7' """
def change_base_extension(n: str, base_from: int, base_to: int) -> str: """Change numerical base of input number n represented as string from base_from to base_to. return string representation after the conversion. base numbers are less than 10. >>> change_base_extension('22', 3, 2) '1000' >>> change_base_extension('1000', 2, 3) '22' >>> change_base_extension('111', 2, 10) '7' """ return change_base(int(n, base_from), base_to)
change_base_extension
def check(candidate): assert candidate('43', 7, 2) == '11111' assert candidate('101101', 2, 4) == '231' assert candidate('3128', 10, 5) == '100003' def test_check(): check(change_base_extension) test_check()
[ "\ndef", "\n#", "\nif", "\nclass" ]
Change numerical base of input number x to base. return string representation after the conversion. base numbers are less than 10. >>> change_base(8, 3) '22' >>> change_base(8, 2) '1000' >>> change_base(7, 2) '111'
Change numerical base of input number n represented as string from base_from to base_to. return string representation after the conversion. base numbers are less than 10. >>> change_base_extension('22', 3, 2) '1000' >>> change_base_extension('1000', 2, 3) '22' >>> change_base_extension('111', 2, 10) '7'
ret = '' while x > 0: ret = str(x % base) + ret x //= base return ret
return change_base(int(n, base_from), base_to)
change_base(x: int, base: int) -> str
change_base_extension(n: str, base_from: int, base_to: int) -> str
import math
def triangle_area(a: int, h: int) -> float: """Given length of a side and high return area for a triangle. >>> triangle_area(5, 3) 7.5 """
def triangle_area(a: int, h: int) -> float: """Given length of a side and high return area for a triangle. >>> triangle_area(5, 3) 7.5 """ return a * h / 2.0
triangle_area
def equilaternal_triangle_area(a): """Given length of a side return area for an equilaternal triangle. >>> round(equilaternal_triangle_area(5), 2) 10.83 """
def equilaternal_triangle_area(a): """Given length of a side return area for an equilaternal triangle. >>> round(equilaternal_triangle_area(5), 2) 10.83 """ return triangle_area(a, a * math.sqrt(3) / 2.0)
equilaternal_triangle_area
def check(candidate): assert round(candidate(3.5), 2) == 5.3 assert round(candidate(10), 2) == 43.3 assert round(candidate(7.8), 2) == 26.34 def test_check(): check(equilaternal_triangle_area) test_check()
[ "\ndef", "\n#", "\nif", "\nclass" ]
Given length of a side and high return area for a triangle. >>> triangle_area(5, 3) 7.5
Given length of a side return area for an equilaternal triangle. >>> round(equilaternal_triangle_area(5), 2) 10.83
return a * h / 2.0
return triangle_area(a, a * math.sqrt(3) / 2.0)
triangle_area(a: int, h: int) -> float
equilaternal_triangle_area(a)
def fib4(n: int) -> int: """The Fib4 number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows: fib4(0) -> 0 fib4(1) -> 0 fib4(2) -> 2 fib4(3) -> 0 fib4(n) -> fib4(n-1) + fib4(n-2) + fib4(n-3) + fib4(n-4). Please write a function to efficiently compute the n-th element of the fib4 number sequence. Do not use recursion. >>> fib4(5) 4 >>> fib4(6) 8 >>> fib4(7) 14 """
def fib4(n: int) -> int: """The Fib4 number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows: fib4(0) -> 0 fib4(1) -> 0 fib4(2) -> 2 fib4(3) -> 0 fib4(n) -> fib4(n-1) + fib4(n-2) + fib4(n-3) + fib4(n-4). Please write a function to efficiently compute the n-th element of the fib4 number sequence. Do not use recursion. >>> fib4(5) 4 >>> fib4(6) 8 >>> fib4(7) 14 """ 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]
fib4
def fib2_to_4(n: int): """Return the n-th value of sequence defined by the following recurrence relation. fib2_to_4(0) -> 0 fib2_to_4(1) -> 1 fib2_to_4(n) -> fib4(n) if n is even fib2_to_4(n) -> fib2_to_4(n-1) + fib2_to_4(n-2) if n is odd >>> fib2_to_4(5) 8 >>> fib2_to_4(0) 0 >>> get_smallest_fib4_number(10) 14 """
def fib2_to_4(n: int): """Return the n-th value of sequence defined by the following recurrence relation. fib2_to_4(0) -> 0 fib2_to_4(1) -> 1 fib2_to_4(n) -> fib4(n) if n is even fib2_to_4(n) -> fib2_to_4(n-1) + fib2_to_4(n-2) if n is odd >>> fib2_to_4(5) 8 >>> fib2_to_4(0) 0 >>> get_smallest_fib4_number(10) 14 """ if n < 2: return n if n % 2 == 0: return fib4(n) else: return fib2_to_4(n - 1) + fib2_to_4(n - 2)
fib2_to_4
def check(candidate): assert candidate(4) == 2 assert candidate(8) == 28 assert candidate(11) == 145 def test_check(): check(fib2_to_4) test_check()
[ "\ndef", "\n#", "\nif", "\nclass" ]
The Fib4 number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows: fib4(0) -> 0 fib4(1) -> 0 fib4(2) -> 2 fib4(3) -> 0 fib4(n) -> fib4(n-1) + fib4(n-2) + fib4(n-3) + fib4(n-4). Please write a function to efficiently compute the n-th element of the fib4 number sequence. Do not use recursion. >>> fib4(5) 4 >>> fib4(6) 8 >>> fib4(7) 14
Return the n-th value of sequence defined by the following recurrence relation. fib2_to_4(0) -> 0 fib2_to_4(1) -> 1 fib2_to_4(n) -> fib4(n) if n is even fib2_to_4(n) -> fib2_to_4(n-1) + fib2_to_4(n-2) if n is odd >>> fib2_to_4(5) 8 >>> fib2_to_4(0) 0 >>> get_smallest_fib4_number(10) 14
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]
if n < 2: return n if n % 2 == 0: return fib4(n) else: return fib2_to_4(n - 1) + fib2_to_4(n - 2)
fib4(n: int) -> int
fib2_to_4(n: int)
from typing import List
def median(l: List[int]) -> float: """Return median of elements in the list l. >>> median([3, 1, 2, 4, 5]) 3 >>> median([-10, 4, 6, 1000, 10, 20]) 15.0 """
def median(l: List[int]) -> float: """Return median of elements in the list l. >>> median([3, 1, 2, 4, 5]) 3 >>> median([-10, 4, 6, 1000, 10, 20]) 15.0 """ l = 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
median
def is_skewed(l: list): """Return "positive" if the list l is positive skewed, "negative" if the list l is negative skewed. Otherwise, return "neutral". A distribution with negative skew can have its mean greater than the median. A distribution with positive skew can have its mean less than the median. >>> is_skewed([1, 2, 3, 4, 5]) "neutral" >>> is_skewed([-10, 4, 6, 1000, 10, 20]) "positive" """
def is_skewed(l: list): """Return "positive" if the list l is positive skewed, "negative" if the list l is negative skewed. Otherwise, return "neutral". A distribution with negative skew can have its mean greater than the median. A distribution with positive skew can have its mean less than the median. >>> is_skewed([1, 2, 3, 4, 5]) "neutral" >>> is_skewed([-10, 4, 6, 1000, 10, 20]) "positive" """ median_val = median(l) mean_val = sum(l) / len(l) if mean_val > median_val: return 'positive' elif mean_val < median_val: return 'negative' else: return 'neutral'
is_skewed
def check(candidate): assert candidate([1, 1, 1, 1, 1]) == 'neutral' assert candidate([3, 4, 8, 9, 10]) == 'negative' assert candidate([8, 3, 6, 2, 3, 4, 5, 7]) == 'positive' def test_check(): check(is_skewed) test_check()
[ "\ndef", "\n#", "\nif", "\nclass" ]
Return median of elements in the list l. >>> median([3, 1, 2, 4, 5]) 3 >>> median([-10, 4, 6, 1000, 10, 20]) 15.0
Return "positive" if the list l is positive skewed, "negative" if the list l is negative skewed. Otherwise, return "neutral". A distribution with negative skew can have its mean greater than the median. A distribution with positive skew can have its mean less than the median. >>> is_skewed([1, 2, 3, 4, 5]) "neutral" >>> is_skewed([-10, 4, 6, 1000, 10, 20]) "positive"
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
median_val = median(l) mean_val = sum(l) / len(l) if mean_val > median_val: return 'positive' elif mean_val < median_val: return 'negative' else: return 'neutral'
median(l: List[int]) -> float
is_skewed(l: list)
def is_palindrome(text: str) -> bool: """ Checks if given string is a palindrome >>> is_palindrome('') True >>> is_palindrome('aba') True >>> is_palindrome('aaaaa') True >>> is_palindrome('zbcd') False """
def is_palindrome(text: str) -> bool: """ Checks if given string is a palindrome >>> 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
is_palindrome
def is_even_palidrome(s: str) -> bool: """ Checks if the chacters located in the even indices in the given string is a palindrome. >>> is_palindrome('') True >>> is_palindrome('aba') True >>> is_palindrome('acaaa') True >>> is_palindrome('zbcd') False """
def is_even_palidrome(s: str) -> bool: """ Checks if the chacters located in the even indices in the given string is a palindrome. >>> is_palindrome('') True >>> is_palindrome('aba') True >>> is_palindrome('acaaa') True >>> is_palindrome('zbcd') False """ return is_palindrome(s[::2])
is_even_palidrome
def check(candidate): assert candidate('afbwccdhcebwa') == True assert candidate('dabbrctdscfbeaa') == False assert candidate('aabbcccybua') == True def test_check(): check(is_even_palidrome) test_check()
[ "\ndef", "\n#", "\nif", "\nclass" ]
Checks if given string is a palindrome >>> is_palindrome('') True >>> is_palindrome('aba') True >>> is_palindrome('aaaaa') True >>> is_palindrome('zbcd') False
Checks if the chacters located in the even indices in the given string is a palindrome. >>> is_palindrome('') True >>> is_palindrome('aba') True >>> is_palindrome('acaaa') True >>> is_palindrome('zbcd') False
for i in range(len(text)): if text[i] != text[len(text) - 1 - i]: return False return True
return is_palindrome(s[::2])
is_palindrome(text: str) -> bool
is_even_palidrome(s: str) -> bool
def modp(n: int, p: int) -> int: """Return 2^n modulo p (be aware of numerics). >>> modp(3, 5) 3 >>> modp(1101, 101) 2 >>> modp(0, 101) 1 >>> modp(3, 11) 8 >>> modp(100, 101) 1 """
def modp(n: int, p: int) -> int: """Return 2^n modulo p (be aware of numerics). >>> modp(3, 5) 3 >>> modp(1101, 101) 2 >>> modp(0, 101) 1 >>> modp(3, 11) 8 >>> modp(100, 101) 1 """ ret = 1 for i in range(n): ret = 2 * ret % p return ret
modp
def modp4(n: int, p: int) -> int: """Return 4^n modulo p (be aware of numerics). >>> modp4(3, 5) 4 >>> modp4(1101, 101) """
def modp4(n: int, p: int) -> int: """Return 4^n modulo p (be aware of numerics). >>> modp4(3, 5) 4 >>> modp4(1101, 101) """ return modp(2 * n, p)
modp4
def check(candidate): assert candidate(403, 22) == 20 assert candidate(441, 2) == 0 assert candidate(9, 9) == 1 def test_check(): check(modp4) test_check()
[ "\ndef", "\n#", "\nif", "\nclass" ]
Return 2^n modulo p (be aware of numerics). >>> modp(3, 5) 3 >>> modp(1101, 101) 2 >>> modp(0, 101) 1 >>> modp(3, 11) 8 >>> modp(100, 101) 1
Return 4^n modulo p (be aware of numerics). >>> modp4(3, 5) 4 >>> modp4(1101, 101)
ret = 1 for i in range(n): ret = 2 * ret % p return ret
return modp(2 * n, p)
modp(n: int, p: int) -> int
modp4(n: int, p: int) -> int
def remove_vowels(text: str) -> str: """ remove_vowels is a function that takes string and returns string without vowels. >>> remove_vowels('') '' >>> remove_vowels('abcdef') 'bcdf' >>> remove_vowels('aaaaa') '' >>> remove_vowels('aaBAA') 'B' >>> remove_vowels('zbcd') 'zbcd' """
def remove_vowels(text: str) -> str: """ remove_vowels is a function that takes string and returns string without vowels. >>> remove_vowels('') '' >>> remove_vowels('abcdef') 'bcdf' >>> remove_vowels('aaaaa') '' >>> remove_vowels('aaBAA') 'B' >>> remove_vowels('zbcd') 'zbcd' """ return ''.join([s for s in text if s.lower() not in ['a', 'e', 'i', 'o', 'u']])
remove_vowels
def equal(text1: str, text2: str) -> bool: """ check if the non-vowel characters in text1 and the non-vowel characters in texts is equal or not. >>> count_vowels('apple', 'pple') True >>> count_vowels("pear", "par") True >>> count_vowels("test", "text") False """
def equal(text1: str, text2: str) -> bool: """ check if the non-vowel characters in text1 and the non-vowel characters in texts is equal or not. >>> count_vowels('apple', 'pple') True >>> count_vowels("pear", "par") True >>> count_vowels("test", "text") False """ return remove_vowels(text1) == remove_vowels(text2)
equal
def check(candidate): assert candidate('coke', 'cake') == True assert candidate('desk', 'dust') == False assert candidate('pandas', 'aeponeedosi') == True def test_check(): check(equal) test_check()
[ "\ndef", "\n#", "\nif", "\nclass" ]
remove_vowels is a function that takes string and returns string without vowels. >>> remove_vowels('') '' >>> remove_vowels('abcdef') 'bcdf' >>> remove_vowels('aaaaa') '' >>> remove_vowels('aaBAA') 'B' >>> remove_vowels('zbcd') 'zbcd'
check if the non-vowel characters in text1 and the non-vowel characters in texts is equal or not. >>> count_vowels('apple', 'pple') True >>> count_vowels("pear", "par") True >>> count_vowels("test", "text") False
return ''.join([s for s in text if s.lower() not in ['a', 'e', 'i', 'o', 'u']])
return remove_vowels(text1) == remove_vowels(text2)
remove_vowels(text: str) -> str
equal(text1: str, text2: str) -> bool
from typing import List
def below_threshold(l: List[int], t: int) -> bool: """Return True if all numbers in the list l are below threshold t. >>> below_threshold([1, 2, 4, 10], 100) True >>> below_threshold([1, 20, 4, 10], 5) False """
def below_threshold(l: List[int], t: int) -> bool: """Return True if all numbers in the list l are below threshold t. >>> below_threshold([1, 2, 4, 10], 100) True >>> below_threshold([1, 20, 4, 10], 5) False """ for e in l: if e >= t: return False return True
below_threshold
def detect_high_blood_sugar(blood_sugar_graph: list) -> bool: """Return True if the symptom of high blood sugar is detected in the blood sugar graph. High blood sugar rate means that the blood sugar level is above 100. High blood sugar is detected even if only one high blood sugar level is present. >>> blood_sugar_graph([65, 66, 70, 84, 81]) False >>> blood_sugar_graph([65, 76, 81, 95, 101]) True """
def detect_high_blood_sugar(blood_sugar_graph: list) -> bool: """Return True if the symptom of high blood sugar is detected in the blood sugar graph. High blood sugar rate means that the blood sugar level is above 100. High blood sugar is detected even if only one high blood sugar level is present. >>> blood_sugar_graph([65, 66, 70, 84, 81]) False >>> blood_sugar_graph([65, 76, 81, 95, 101]) True """ return not below_threshold(blood_sugar_graph, 100)
detect_high_blood_sugar
def check(candidate): assert round(candidate([77, 79, 75, 81, 82, 81, 84])) == False assert round(candidate([101, 102, 99, 95, 93, 90])) == True assert round(candidate([91, 95, 98, 101, 99])) == True def test_check(): check(detect_high_blood_sugar) test_check()
[ "\ndef", "\n#", "\nif", "\nclass" ]
Return True if all numbers in the list l are below threshold t. >>> below_threshold([1, 2, 4, 10], 100) True >>> below_threshold([1, 20, 4, 10], 5) False
Return True if the symptom of high blood sugar is detected in the blood sugar graph. High blood sugar rate means that the blood sugar level is above 100. High blood sugar is detected even if only one high blood sugar level is present. >>> blood_sugar_graph([65, 66, 70, 84, 81]) False >>> blood_sugar_graph([65, 76, 81, 95, 101]) True
for e in l: if e >= t: return False return True
return not below_threshold(blood_sugar_graph, 100)
below_threshold(l: List[int], t: int) -> bool
detect_high_blood_sugar(blood_sugar_graph: list) -> bool
def fib(n: int) -> int: """Return n-th Fibonacci number. >>> fib(10) 55 >>> fib(1) 1 >>> fib(8) 21 """
def fib(n: int) -> int: """Return n-th Fibonacci number. >>> 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)
fib
def sum_fib(n: int): """Return sum of first n Fibonacci numbers. You can use this property: sum_{i=1}^{n} F_i = F_{n+2} - 1 >>> sum_fib(8) 54 >>> sum_fib(1) 1 >>> sum_fib(6) 20 """
def sum_fib(n: int): """Return sum of first n Fibonacci numbers. You can use this property: sum_{i=1}^{n} F_i = F_{n+2} - 1 >>> sum_fib(8) 54 >>> sum_fib(1) 1 >>> sum_fib(6) 20 """ return fib(n + 2) - 1
sum_fib
def check(candidate): assert candidate(3) == 4 assert candidate(10) == 143 assert candidate(7) == 33 def test_check(): check(sum_fib) test_check()
[ "\ndef", "\n#", "\nif", "\nclass" ]
Return n-th Fibonacci number. >>> fib(10) 55 >>> fib(1) 1 >>> fib(8) 21
Return sum of first n Fibonacci numbers. You can use this property: sum_{i=1}^{n} F_i = F_{n+2} - 1 >>> sum_fib(8) 54 >>> sum_fib(1) 1 >>> sum_fib(6) 20
if n == 0: return 0 if n == 1: return 1 return fib(n - 1) + fib(n - 2)
return fib(n + 2) - 1
fib(n: int) -> int
sum_fib(n: int)
def correct_bracketing(brackets: str) -> bool: """brackets is a string of "<" and ">". return True if every opening bracket has a corresponding closing bracket. >>> correct_bracketing('<') False >>> correct_bracketing('<>') True >>> correct_bracketing('<<><>>') True >>> correct_bracketing('><<>') False """
def correct_bracketing(brackets: str) -> bool: """brackets is a string of "<" and ">". return True if every opening bracket has a corresponding closing bracket. >>> correct_bracketing('<') False >>> correct_bracketing('<>') True >>> correct_bracketing('<<><>>') True >>> correct_bracketing('><<>') False """ depth = 0 for b in brackets: if b == '<': depth += 1 else: depth -= 1 if depth < 0: return False return depth == 0
correct_bracketing
def extended_correct_bracketing(brackets: str) -> bool: """brackets is a string of "<", "(", ">" and ")". There is opening bracket "<" and "(" and closing bracket ">", ")". return True if every opening bracket has a corresponding closing bracket. Note that it is ok not to match the shape between opening bracket and closing bracket. For example, "<)" is also true. >>> extended_correct_bracketing("(>") True >>> extended_correct_bracketing("(<)<<)>)") True >>> extended_correct_bracketing("><)(<>)") False """
def extended_correct_bracketing(brackets: str) -> bool: """brackets is a string of "<", "(", ">" and ")". There is opening bracket "<" and "(" and closing bracket ">", ")". return True if every opening bracket has a corresponding closing bracket. Note that it is ok not to match the shape between opening bracket and closing bracket. For example, "<)" is also true. >>> extended_correct_bracketing("(>") True >>> extended_correct_bracketing("(<)<<)>)") True >>> extended_correct_bracketing("><)(<>)") False """ return correct_bracketing(brackets.replace('(', '<').replace(')', '>'))
extended_correct_bracketing
def check(candidate): assert candidate('(<(>)>') == True assert candidate('<<>)<()<>>') == True assert candidate('<<(<))<>))<>>') == False def test_check(): check(extended_correct_bracketing) test_check()
[ "\ndef", "\n#", "\nif", "\nclass" ]
brackets is a string of "<" and ">". return True if every opening bracket has a corresponding closing bracket. >>> correct_bracketing('<') False >>> correct_bracketing('<>') True >>> correct_bracketing('<<><>>') True >>> correct_bracketing('><<>') False
brackets is a string of "<", "(", ">" and ")". There is opening bracket "<" and "(" and closing bracket ">", ")". return True if every opening bracket has a corresponding closing bracket. Note that it is ok not to match the shape between opening bracket and closing bracket. For example, "<)" is also true. >>> extended_correct_bracketing("(>") True >>> extended_correct_bracketing("(<)<<)>)") True >>> extended_correct_bracketing("><)(<>)") False
depth = 0 for b in brackets: if b == '<': depth += 1 else: depth -= 1 if depth < 0: return False return depth == 0
return correct_bracketing(brackets.replace('(', '<').replace(')', '>'))
correct_bracketing(brackets: str) -> bool
extended_correct_bracketing(brackets: str) -> bool
def monotonic(l: list[int]) -> bool: """Return True is list elements are monotonically increasing or decreasing. >>> monotonic([1, 2, 4, 20]) True >>> monotonic([1, 20, 4, 10]) False >>> monotonic([4, 1, 0, -10]) True """
def monotonic(l: list[int]) -> bool: """Return True is list elements are monotonically increasing or decreasing. >>> monotonic([1, 2, 4, 20]) True >>> monotonic([1, 20, 4, 10]) False >>> monotonic([4, 1, 0, -10]) True """ if l == sorted(l) or l == sorted(l, reverse=True): return True return False
monotonic
def monotonic_2d(arr: list[list[int]]) -> bool: """Check if all rows and columns in the given array is monotonimally increasing or decreasing. Assume that the given array is rectangular. >>> monotonic_2d([[0, 1, 2], [3, 4, 5], [6, 7, 8]]) True >>> monotonic_2d([[3, 5, 8], [2, 6, 9], [4, 7, 10]]) False """
def monotonic_2d(arr: list[list[int]]) -> bool: """Check if all rows and columns in the given array is monotonimally increasing or decreasing. Assume that the given array is rectangular. >>> monotonic_2d([[0, 1, 2], [3, 4, 5], [6, 7, 8]]) True >>> monotonic_2d([[3, 5, 8], [2, 6, 9], [4, 7, 10]]) False """ for i in range(len(arr)): if not monotonic(arr[i]): return False for j in range(len(arr[0])): if not monotonic([arr[i][j] for i in range(len(arr))]): return False return True
monotonic_2d
def check(candidate): assert candidate([[4, 9, 13], [24, 19, 15], [25, 26, 27]]) == True assert candidate([[100, 0], [0, 100]]) == True assert candidate([[8, 6, 4], [8, 6, 4], [7, 8, 5]]) == False def test_check(): check(monotonic_2d) test_check()
[ "\ndef", "\n#", "\nif", "\nclass" ]
Return True is list elements are monotonically increasing or decreasing. >>> monotonic([1, 2, 4, 20]) True >>> monotonic([1, 20, 4, 10]) False >>> monotonic([4, 1, 0, -10]) True
Check if all rows and columns in the given array is monotonimally increasing or decreasing. Assume that the given array is rectangular. >>> monotonic_2d([[0, 1, 2], [3, 4, 5], [6, 7, 8]]) True >>> monotonic_2d([[3, 5, 8], [2, 6, 9], [4, 7, 10]]) False
if l == sorted(l) or l == sorted(l, reverse=True): return True return False
for i in range(len(arr)): if not monotonic(arr[i]): return False for j in range(len(arr[0])): if not monotonic([arr[i][j] for i in range(len(arr))]): return False return True
monotonic(l: list[int]) -> bool
monotonic_2d(arr: list[list[int]]) -> bool
def largest_prime_factor(n: int) -> int: """Return the largest prime factor of n. Assume n > 1 and is not a prime. >>> largest_prime_factor(13195) 29 >>> largest_prime_factor(2048) 2 """
def largest_prime_factor(n: int) -> int: """Return the largest prime factor of n. Assume n > 1 and is not a prime. >>> largest_prime_factor(13195) 29 >>> largest_prime_factor(2048) 2 """ 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
largest_prime_factor
def get_exponent_of_largest_prime_factor(n: int): """Return the exponent of largest prime factor after factorizing n. Assume n > 1 and is not a prime. >>> get_exponent_of_largest_prime_factor(13195) # 13195 = 5 * 7 * 13 * 29 1 >>> get_exponent_of_largest_prime_factor(2048) # 2048 = 2^11 11 """
def get_exponent_of_largest_prime_factor(n: int): """Return the exponent of largest prime factor after factorizing n. Assume n > 1 and is not a prime. >>> get_exponent_of_largest_prime_factor(13195) # 13195 = 5 * 7 * 13 * 29 1 >>> get_exponent_of_largest_prime_factor(2048) # 2048 = 2^11 11 """ largest = largest_prime_factor(n) ans = 1 while largest_prime_factor(n // largest) == largest: ans += 1 n = n // largest return ans
get_exponent_of_largest_prime_factor
def check(candidate): assert candidate(162) == 4 assert candidate(506250) == 5 assert candidate(1071875) == 3 def test_check(): check(get_exponent_of_largest_prime_factor) test_check()
[ "\ndef", "\n#", "\nif", "\nclass" ]
Return the largest prime factor of n. Assume n > 1 and is not a prime. >>> largest_prime_factor(13195) 29 >>> largest_prime_factor(2048) 2
Return the exponent of largest prime factor after factorizing n. Assume n > 1 and is not a prime. >>> get_exponent_of_largest_prime_factor(13195) # 13195 = 5 * 7 * 13 * 29 1 >>> get_exponent_of_largest_prime_factor(2048) # 2048 = 2^11 11
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
largest = largest_prime_factor(n) ans = 1 while largest_prime_factor(n // largest) == largest: ans += 1 n = n // largest return ans
largest_prime_factor(n: int) -> int
get_exponent_of_largest_prime_factor(n: int)
def derivative(xs: list[int]) -> list[int]: """xs represent coefficients of a polynomial. xs[0] + xs[1] * x + xs[2] * x^2 + .... Return derivative of this polynomial in the same form. >>> derivative([3, 1, 2, 4, 5]) [1, 4, 12, 20] >>> derivative([1, 2, 3]) [2, 6] """
def derivative(xs: list[int]) -> list[int]: """xs represent coefficients of a polynomial. xs[0] + xs[1] * x + xs[2] * x^2 + .... Return derivative of this polynomial in the same form. >>> derivative([3, 1, 2, 4, 5]) [1, 4, 12, 20] >>> derivative([1, 2, 3]) [2, 6] """ return [i * x for (i, x) in enumerate(xs)][1:]
derivative
def second_derivative(xs: list[int]) -> list[int]: """xs represent coefficients of a polynomial. xs[0] + xs[1] * x + xs[2] * x^2 + .... Return second derivative of this polynomial in the same form. >>> derivative([3, 1, 2, 4, 5]) [4, 24, 60] >>> derivative([1, 2, 3]) [6] """
def second_derivative(xs: list[int]) -> list[int]: """xs represent coefficients of a polynomial. xs[0] + xs[1] * x + xs[2] * x^2 + .... Return second derivative of this polynomial in the same form. >>> derivative([3, 1, 2, 4, 5]) [4, 24, 60] >>> derivative([1, 2, 3]) [6] """ return derivative(derivative(xs))
second_derivative
def check(candidate): assert candidate([4, 9, 5, 2]) == [10, 12] assert candidate([9, 8, 2, 5, 3]) == [4, 30, 36] assert candidate([10, 8, 43, 4, 23, 4]) == [86, 24, 276, 80] def test_check(): check(second_derivative) test_check()
[ "\ndef", "\n#", "\nif", "\nclass" ]
xs represent coefficients of a polynomial. xs[0] + xs[1] * x + xs[2] * x^2 + .... Return derivative of this polynomial in the same form. >>> derivative([3, 1, 2, 4, 5]) [1, 4, 12, 20] >>> derivative([1, 2, 3]) [2, 6]
xs represent coefficients of a polynomial. xs[0] + xs[1] * x + xs[2] * x^2 + .... Return second derivative of this polynomial in the same form. >>> derivative([3, 1, 2, 4, 5]) [4, 24, 60] >>> derivative([1, 2, 3]) [6]
return [i * x for (i, x) in enumerate(xs)][1:]
return derivative(derivative(xs))
derivative(xs: list[int]) -> list[int]
second_derivative(xs: list[int]) -> list[int]
def vowels_count(s: str) -> int: """Write a function vowels_count which takes a string representing a word as input and returns the number of vowels in the string. Vowels in this case are 'a', 'e', 'i', 'o', 'u'. Here, 'y' is also a vowel, but only when it is at the end of the given word. Example: >>> vowels_count('abcde') 2 >>> vowels_count('ACEDY') 3 """
def vowels_count(s: str) -> int: """Write a function vowels_count which takes a string representing a word as input and returns the number of vowels in the string. Vowels in this case are 'a', 'e', 'i', 'o', 'u'. Here, 'y' is also a vowel, but only when it is at the end of the given word. Example: >>> vowels_count('abcde') 2 >>> vowels_count('ACEDY') 3 """ 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
vowels_count
def is_vowel_enough(s: str) -> bool: """Check if the given string contains at least 30% of vowels. >>> is_vowel_enough("abcde") True >>> is_vowel_enough("abc") False """
def is_vowel_enough(s: str) -> bool: """Check if the given string contains at least 30% of vowels. >>> is_vowel_enough("abcde") True >>> is_vowel_enough("abc") False """ return vowels_count(s) / len(s) >= 0.3
is_vowel_enough
def check(candidate): assert candidate('Eulogia') == True assert candidate('Drain') == True assert candidate('hardship') == False def test_check(): check(is_vowel_enough) test_check()
[ "\ndef", "\n#", "\nif", "\nclass" ]
Write a function vowels_count which takes a string representing a word as input and returns the number of vowels in the string. Vowels in this case are 'a', 'e', 'i', 'o', 'u'. Here, 'y' is also a vowel, but only when it is at the end of the given word. Example: >>> vowels_count('abcde') 2 >>> vowels_count('ACEDY') 3
Check if the given string contains at least 30% of vowels. >>> is_vowel_enough("abcde") True >>> is_vowel_enough("abc") False
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
return vowels_count(s) / len(s) >= 0.3
vowels_count(s: str) -> int
is_vowel_enough(s: str) -> bool
def circular_shift(x: int, shift: int) -> str: """Circular shift the digits of the integer x, shift the digits right by shift and return the result as a string. If shift > number of digits, return digits reversed. >>> circular_shift(12, 1) '21' >>> circular_shift(12, 2) '12' """
def circular_shift(x: int, shift: int) -> str: """Circular shift the digits of the integer x, shift the digits right by shift and return the result as a string. If shift > number of digits, return digits reversed. >>> circular_shift(12, 1) '21' >>> circular_shift(12, 2) '12' """ s = str(x) if shift > len(s): return s[::-1] else: return s[len(s) - shift:] + s[:len(s) - shift]
circular_shift
def is_circular_same(x: int, y: int) -> bool: """Return True if x and y are circularly same, False otherwise. Circulary same means that any of circular shift of x is equal to any of circular shift of y. >>> is_circular_same(12, 21) True >>> is_circular_same(354, 453) False """
def is_circular_same(x: int, y: int) -> bool: """Return True if x and y are circularly same, False otherwise. Circulary same means that any of circular shift of x is equal to any of circular shift of y. >>> is_circular_same(12, 21) True >>> is_circular_same(354, 453) False """ xs = set((circular_shift(x, i) for i in range(len(str(x))))) ys = set((circular_shift(y, i) for i in range(len(str(y))))) return len(xs.intersection(ys)) > 0
is_circular_same
def check(candidate): assert candidate(40273, 73402) is True assert candidate(33, 23) is False assert candidate(9447, 4794) is True def test_check(): check(is_circular_same) test_check()
[ "\ndef", "\n#", "\nif", "\nclass" ]
Circular shift the digits of the integer x, shift the digits right by shift and return the result as a string. If shift > number of digits, return digits reversed. >>> circular_shift(12, 1) '21' >>> circular_shift(12, 2) '12'
Return True if x and y are circularly same, False otherwise. Circulary same means that any of circular shift of x is equal to any of circular shift of y. >>> is_circular_same(12, 21) True >>> is_circular_same(354, 453) False
s = str(x) if shift > len(s): return s[::-1] else: return s[len(s) - shift:] + s[:len(s) - shift]
xs = set((circular_shift(x, i) for i in range(len(str(x))))) ys = set((circular_shift(y, i) for i in range(len(str(y))))) return len(xs.intersection(ys)) > 0
circular_shift(x: int, shift: int) -> str
is_circular_same(x: int, y: int) -> bool
from typing import List
def digitSum(s: str) -> int: """Task Write a function that takes a string as input and returns the sum of the upper characters only' ASCII codes. Examples: >>> digitSum('') 0 >>> digitSum('abAB') 131 >>> digitSum('abcCd') 67 >>> digitSum('helloE') 69 >>> digitSum('woArBld') 131 >>> digitSum('aAaaaXa') 153 """
def digitSum(s: str) -> int: """Task Write a function that takes a string as input and returns the sum of the upper characters only' ASCII codes. Examples: >>> digitSum('') 0 >>> digitSum('abAB') 131 >>> digitSum('abcCd') 67 >>> digitSum('helloE') 69 >>> digitSum('woArBld') 131 >>> digitSum('aAaaaXa') 153 """ if s == '': return 0 return sum((ord(char) if char.isupper() else 0 for char in s))
digitSum
def sort_by_sum_upper_character_ascii(s: List[str]) -> List[str]: """Sort string based on the custom key defined as the sum of the upper characters only' ASCII codes. The order of string should be preserved in case of a tie. Examples: sort_by_digitsum(["", "abAB", "abcCd", "helloE"]) => ["", "abcCd", "helloE", "abAB"] """
def sort_by_sum_upper_character_ascii(s: List[str]) -> List[str]: """Sort string based on the custom key defined as the sum of the upper characters only' ASCII codes. The order of string should be preserved in case of a tie. Examples: sort_by_digitsum(["", "abAB", "abcCd", "helloE"]) => ["", "abcCd", "helloE", "abAB"] """ return sorted(s, key=digitSum)
sort_by_sum_upper_character_ascii
def check(candidate): assert candidate(['abAB', 'ABab']) == ['abAB', 'ABab'] assert candidate(['AAAAAAAA', 'zzzzzzzzz', 'B']) == ['zzzzzzzzz', 'B', 'AAAAAAAA'] assert candidate(['My', 'Name', 'Is', 'Hulk']) == ['Hulk', 'Is', 'My', 'Name'] def test_check(): check(sort_by_sum_upper_character_ascii) test_check()
[ "\ndef", "\n#", "\nif", "\nclass" ]
Task Write a function that takes a string as input and returns the sum of the upper characters only' ASCII codes. Examples: >>> digitSum('') 0 >>> digitSum('abAB') 131 >>> digitSum('abcCd') 67 >>> digitSum('helloE') 69 >>> digitSum('woArBld') 131 >>> digitSum('aAaaaXa') 153
Sort string based on the custom key defined as the sum of the upper characters only' ASCII codes. The order of string should be preserved in case of a tie. Examples: sort_by_digitsum(["", "abAB", "abcCd", "helloE"]) => ["", "abcCd", "helloE", "abAB"]
if s == '': return 0 return sum((ord(char) if char.isupper() else 0 for char in s))
return sorted(s, key=digitSum)
digitSum(s: str) -> int
sort_by_sum_upper_character_ascii(s: List[str]) -> List[str]
def fruit_distribution(s: str, n: int) -> int: """ In this task, you will be given a string that represents a number of apples and oranges that are distributed in a basket of fruit this basket contains apples, oranges, and mango fruits. Given the string that represents the total number of the oranges and apples and an integer that represent the total number of the fruits in the basket return the number of the mango fruits in the basket. for examble: >>> fruit_distribution('5 apples and 6 oranges', 19) 8 >>> fruit_distribution('0 apples and 1 oranges', 3) 2 >>> fruit_distribution('2 apples and 3 oranges', 100) 95 >>> fruit_distribution('100 apples and 1 oranges', 120) 19 """
def fruit_distribution(s: str, n: int) -> int: """ In this task, you will be given a string that represents a number of apples and oranges that are distributed in a basket of fruit this basket contains apples, oranges, and mango fruits. Given the string that represents the total number of the oranges and apples and an integer that represent the total number of the fruits in the basket return the number of the mango fruits in the basket. for examble: >>> fruit_distribution('5 apples and 6 oranges', 19) 8 >>> fruit_distribution('0 apples and 1 oranges', 3) 2 >>> fruit_distribution('2 apples and 3 oranges', 100) 95 >>> fruit_distribution('100 apples and 1 oranges', 120) 19 """ lis = list() for i in s.split(' '): if i.isdigit(): lis.append(int(i)) return n - sum(lis)
fruit_distribution
def happy_fruit_distribution(s: str, n: int) -> int: """ In this task, you will be given a string that represents a number of apples and oranges that are distributed in a basket of fruit this basket contains apples, oranges, and mango fruits. Given the string that represents the total number of the oranges and apples and an integer that represent the total number of the fruits in the basket, your task is to check the fruit distribution is happy or not. The fruit distribution is happy when the number of the mango fruits is more than the total number of remainders. for example: >>> happy_fruit_distribution('5 apples and 6 oranges', 19) 'not happy' >>> fruit_distribution('0 apples and 1 oranges', 3) 'happy' >>> fruit_distribution('2 apples and 3 oranges', 100) 'happy' >>> fruit_distribution('100 apples and 1 oranges', 120) 'not happy' """
def happy_fruit_distribution(s: str, n: int) -> int: """ In this task, you will be given a string that represents a number of apples and oranges that are distributed in a basket of fruit this basket contains apples, oranges, and mango fruits. Given the string that represents the total number of the oranges and apples and an integer that represent the total number of the fruits in the basket, your task is to check the fruit distribution is happy or not. The fruit distribution is happy when the number of the mango fruits is more than the total number of remainders. for example: >>> happy_fruit_distribution('5 apples and 6 oranges', 19) 'not happy' >>> fruit_distribution('0 apples and 1 oranges', 3) 'happy' >>> fruit_distribution('2 apples and 3 oranges', 100) 'happy' >>> fruit_distribution('100 apples and 1 oranges', 120) 'not happy' """ return 'happy' if fruit_distribution(s, n) > n // 2 else 'not happy'
happy_fruit_distribution
def check(candidate): assert candidate('3 apples and 3 oranges', 9) == 'not happy' assert candidate('9 apples and 1 oranges', 21) == 'happy' assert candidate('0 apples and 0 oranges', 1) == 'happy' def test_check(): check(happy_fruit_distribution) test_check()
[ "\ndef", "\n#", "\nif", "\nclass" ]
In this task, you will be given a string that represents a number of apples and oranges that are distributed in a basket of fruit this basket contains apples, oranges, and mango fruits. Given the string that represents the total number of the oranges and apples and an integer that represent the total number of the fruits in the basket return the number of the mango fruits in the basket. for examble: >>> fruit_distribution('5 apples and 6 oranges', 19) 8 >>> fruit_distribution('0 apples and 1 oranges', 3) 2 >>> fruit_distribution('2 apples and 3 oranges', 100) 95 >>> fruit_distribution('100 apples and 1 oranges', 120) 19
In this task, you will be given a string that represents a number of apples and oranges that are distributed in a basket of fruit this basket contains apples, oranges, and mango fruits. Given the string that represents the total number of the oranges and apples and an integer that represent the total number of the fruits in the basket, your task is to check the fruit distribution is happy or not. The fruit distribution is happy when the number of the mango fruits is more than the total number of remainders. for example: >>> happy_fruit_distribution('5 apples and 6 oranges', 19) 'not happy' >>> fruit_distribution('0 apples and 1 oranges', 3) 'happy' >>> fruit_distribution('2 apples and 3 oranges', 100) 'happy' >>> fruit_distribution('100 apples and 1 oranges', 120) 'not happy'
lis = list() for i in s.split(' '): if i.isdigit(): lis.append(int(i)) return n - sum(lis)
return 'happy' if fruit_distribution(s, n) > n // 2 else 'not happy'
fruit_distribution(s: str, n: int) -> int
happy_fruit_distribution(s: str, n: int) -> int
from typing import List
def pluck(arr: List[int]) -> List[int]: """ "Given an array representing a branch of a tree that has non-negative integer nodes your task is to pluck one of the nodes and return it. The plucked node should be the node with the smallest even value. If multiple nodes with the same smallest even value are found return the node that has smallest index. The plucked node should be returned in a list, [ smalest_value, its index ], If there are no even values or the given array is empty, return []. Example 1: >>> pluck([4, 2, 3]) [2, 1] Explanation: 2 has the smallest even value, and 2 has the smallest index. Example 2: >>> pluck([1, 2, 3]) [2, 1] Explanation: 2 has the smallest even value, and 2 has the smallest index. Example 3: >>> pluck([]) [] Example 4: >>> pluck([5, 0, 3, 0, 4, 2]) [0, 1] Explanation: 0 is the smallest value, but there are two zeros, so we will choose the first zero, which has the smallest index. Constraints: * 1 <= nodes.length <= 10000 * 0 <= node.value """
def pluck(arr: List[int]) -> List[int]: """ "Given an array representing a branch of a tree that has non-negative integer nodes your task is to pluck one of the nodes and return it. The plucked node should be the node with the smallest even value. If multiple nodes with the same smallest even value are found return the node that has smallest index. The plucked node should be returned in a list, [ smalest_value, its index ], If there are no even values or the given array is empty, return []. Example 1: >>> pluck([4, 2, 3]) [2, 1] Explanation: 2 has the smallest even value, and 2 has the smallest index. Example 2: >>> pluck([1, 2, 3]) [2, 1] Explanation: 2 has the smallest even value, and 2 has the smallest index. Example 3: >>> pluck([]) [] Example 4: >>> pluck([5, 0, 3, 0, 4, 2]) [0, 1] Explanation: 0 is the smallest value, but there are two zeros, so we will choose the first zero, which has the smallest index. Constraints: * 1 <= nodes.length <= 10000 * 0 <= node.value """ if len(arr) == 0: return [] evens = list(filter(lambda x: x % 2 == 0, arr)) if evens == []: return [] return [min(evens), arr.index(min(evens))]
pluck
def pluck_and_select_larger_branch(arr: List[int]) -> List[int]: """ Given a branch represented as a list of non-negative integers, plucking (and then cutting) a node will result in the branch being split into two (or fewer) seperate branches. Among the divided branches, return the one with a larger sum of the nodes that compose it. If the sum of nodes in the divided branches is the same, return the branch with the smaller index. Assuming the sum of nodes in an empty branch is -1, return `[]` if there are only empty branches remaining after plucking. Examples: >>> pluck_and_select_larger_branch([1, 3, 2, 4, 5]) [4, 5] >>> pluck_and_select_larger_branch([1, 3, 2, 3, 1]) [1, 3] >>> pluck_and_select_larger_branch([2, 1, 2, 1]) [1, 2, 1] >>> pluck_and_select_larger_branch([2]) [] >>> pluck_and_select_larger_branch([1, 3, 5, 7, 9]) [1, 3, 5, 7, 9] """
def pluck_and_select_larger_branch(arr: List[int]) -> List[int]: """ Given a branch represented as a list of non-negative integers, plucking (and then cutting) a node will result in the branch being split into two (or fewer) seperate branches. Among the divided branches, return the one with a larger sum of the nodes that compose it. If the sum of nodes in the divided branches is the same, return the branch with the smaller index. Assuming the sum of nodes in an empty branch is -1, return `[]` if there are only empty branches remaining after plucking. Examples: >>> pluck_and_select_larger_branch([1, 3, 2, 4, 5]) [4, 5] >>> pluck_and_select_larger_branch([1, 3, 2, 3, 1]) [1, 3] >>> pluck_and_select_larger_branch([2, 1, 2, 1]) [1, 2, 1] >>> pluck_and_select_larger_branch([2]) [] >>> pluck_and_select_larger_branch([1, 3, 5, 7, 9]) [1, 3, 5, 7, 9] """ plucked_node = pluck(arr) if plucked_node == []: return arr (_, index) = plucked_node left_branch = arr[:index] right_branch = arr[index + 1:] left_branch_value = sum(left_branch) if left_branch != [] else -1 right_branch_value = sum(right_branch) if right_branch != [] else -1 return left_branch if left_branch_value >= right_branch_value else right_branch
pluck_and_select_larger_branch
def check(candidate): assert candidate([33, 12, 10, 10, 1, 3, 1]) == [33, 12] assert candidate([1, 7, 12, 5, 3]) == [1, 7] assert candidate([12, 9, 7, 8]) == [12, 9, 7] assert candidate([100]) == [] assert candidate([11, 21, 31, 41, 51]) == [11, 21, 31, 41, 51] assert candidate([]) == [] def test_check(): check(pluck_and_select_larger_branch) test_check()
[ "\ndef", "\n#", "\nif", "\nclass" ]
"Given an array representing a branch of a tree that has non-negative integer nodes your task is to pluck one of the nodes and return it. The plucked node should be the node with the smallest even value. If multiple nodes with the same smallest even value are found return the node that has smallest index. The plucked node should be returned in a list, [ smalest_value, its index ], If there are no even values or the given array is empty, return []. Example 1: >>> pluck([4, 2, 3]) [2, 1] Explanation: 2 has the smallest even value, and 2 has the smallest index. Example 2: >>> pluck([1, 2, 3]) [2, 1] Explanation: 2 has the smallest even value, and 2 has the smallest index. Example 3: >>> pluck([]) [] Example 4: >>> pluck([5, 0, 3, 0, 4, 2]) [0, 1] Explanation: 0 is the smallest value, but there are two zeros, so we will choose the first zero, which has the smallest index. Constraints: * 1 <= nodes.length <= 10000 * 0 <= node.value
Given a branch represented as a list of non-negative integers, plucking (and then cutting) a node will result in the branch being split into two (or fewer) seperate branches. Among the divided branches, return the one with a larger sum of the nodes that compose it. If the sum of nodes in the divided branches is the same, return the branch with the smaller index. Assuming the sum of nodes in an empty branch is -1, return `[]` if there are only empty branches remaining after plucking. Examples: >>> pluck_and_select_larger_branch([1, 3, 2, 4, 5]) [4, 5] >>> pluck_and_select_larger_branch([1, 3, 2, 3, 1]) [1, 3] >>> pluck_and_select_larger_branch([2, 1, 2, 1]) [1, 2, 1] >>> pluck_and_select_larger_branch([2]) [] >>> pluck_and_select_larger_branch([1, 3, 5, 7, 9]) [1, 3, 5, 7, 9]
if len(arr) == 0: return [] evens = list(filter(lambda x: x % 2 == 0, arr)) if evens == []: return [] return [min(evens), arr.index(min(evens))]
plucked_node = pluck(arr) if plucked_node == []: return arr (_, index) = plucked_node left_branch = arr[:index] right_branch = arr[index + 1:] left_branch_value = sum(left_branch) if left_branch != [] else -1 right_branch_value = sum(right_branch) if right_branch != [] else -1 return left_branch if left_branch_value >= right_branch_value else right_branch
pluck(arr: List[int]) -> List[int]
pluck_and_select_larger_branch(arr: List[int]) -> List[int]
from typing import List
def search(lst: List[int]) -> int: """ You are given a non-empty list of positive integers. Return the greatest integer that is greater than zero, and has a frequency greater than or equal to the value of the integer itself. The frequency of an integer is the number of times it appears in the list. If no such a value exist, return -1. Examples: >>> search([4, 1, 2, 2, 3, 1]) 2 >>> search([1, 2, 2, 3, 3, 3, 4, 4, 4]) 3 >>> search([5, 5, 4, 4, 4]) -1 """
def search(lst: List[int]) -> int: """ You are given a non-empty list of positive integers. Return the greatest integer that is greater than zero, and has a frequency greater than or equal to the value of the integer itself. The frequency of an integer is the number of times it appears in the list. If no such a value exist, return -1. Examples: >>> search([4, 1, 2, 2, 3, 1]) 2 >>> search([1, 2, 2, 3, 3, 3, 4, 4, 4]) 3 >>> search([5, 5, 4, 4, 4]) -1 """ 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
search
def remove_integers_with_higher_frequency(lst: List[int]) -> List[int]: """ Return a list obtained from the given non-empty list of positive integers by removing all integers whose frequency is greater than or equal to the integer itself. Ensure that the order of elements between them is preserverd. Examples: >>> remove_integers_with_higher_frequency([2, 3, 3, 3, 3, 3, 4, 4]) [2, 4, 4] >>> remove_integers_with_higher_frequency([3, 2, 4, 5, 1, 4, 3, 2]) [3, 4, 5, 4, 3] >>> remove_integers_with_higher_frequency([2, 3, 3, 4, 4, 4]) [2, 3, 3, 4, 4, 4] """
def remove_integers_with_higher_frequency(lst: List[int]) -> List[int]: """ Return a list obtained from the given non-empty list of positive integers by removing all integers whose frequency is greater than or equal to the integer itself. Ensure that the order of elements between them is preserverd. Examples: >>> remove_integers_with_higher_frequency([2, 3, 3, 3, 3, 3, 4, 4]) [2, 4, 4] >>> remove_integers_with_higher_frequency([3, 2, 4, 5, 1, 4, 3, 2]) [3, 4, 5, 4, 3] >>> remove_integers_with_higher_frequency([2, 3, 3, 4, 4, 4]) [2, 3, 3, 4, 4, 4] """ integer = search(lst) while integer != -1: lst = [i for i in lst if i != integer] integer = search(lst) return lst
remove_integers_with_higher_frequency
def check(candidate): assert candidate([11, 5, 4, 22, 4, 33, 5, 5, 5, 44, 4, 55, 4, 5]) == [11, 22, 33, 44, 55] assert candidate([1, 5, 2, 4, 3, 5, 4, 5, 3, 1, 2, 1, 3, 4, 3, 3, 2, 5]) == [5, 4, 5, 4, 5, 4, 5] assert candidate([3, 4, 4, 2, 4, 3]) == [3, 4, 4, 2, 4, 3] assert candidate([10, 10, 10, 10, 10, 10, 10, 10, 10]) == [10, 10, 10, 10, 10, 10, 10, 10, 10] assert candidate([100]) == [100] def test_check(): check(remove_integers_with_higher_frequency) test_check()
[ "\ndef", "\n#", "\nif", "\nclass" ]
You are given a non-empty list of positive integers. Return the greatest integer that is greater than zero, and has a frequency greater than or equal to the value of the integer itself. The frequency of an integer is the number of times it appears in the list. If no such a value exist, return -1. Examples: >>> search([4, 1, 2, 2, 3, 1]) 2 >>> search([1, 2, 2, 3, 3, 3, 4, 4, 4]) 3 >>> search([5, 5, 4, 4, 4]) -1
Return a list obtained from the given non-empty list of positive integers by removing all integers whose frequency is greater than or equal to the integer itself. Ensure that the order of elements between them is preserverd. Examples: >>> remove_integers_with_higher_frequency([2, 3, 3, 3, 3, 3, 4, 4]) [2, 4, 4] >>> remove_integers_with_higher_frequency([3, 2, 4, 5, 1, 4, 3, 2]) [3, 4, 5, 4, 3] >>> remove_integers_with_higher_frequency([2, 3, 3, 4, 4, 4]) [2, 3, 3, 4, 4, 4]
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
integer = search(lst) while integer != -1: lst = [i for i in lst if i != integer] integer = search(lst) return lst
search(lst: List[int]) -> int
remove_integers_with_higher_frequency(lst: List[int]) -> List[int]

Related github repository: https://github.com/sh0416/humanextension

Downloads last month
38