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
|
---|---|---|---|---|---|---|---|---|
from typing import List | def exchange(lst1: List[int], lst2: List[int]) -> str:
"""In this problem, you will implement a function that takes two lists of numbers,
and determines whether it is possible to perform an exchange of elements
between them to make lst1 a list of only even numbers.
There is no limit on the number of exchanged elements between lst1 and lst2.
If it is possible to exchange elements between the lst1 and lst2 to make
all the elements of lst1 to be even, return "YES".
Otherwise, return "NO".
For example:
>>> exchange([1, 2, 3, 4], [1, 2, 3, 4])
'YES'
>>> exchange([1, 2, 3, 4], [1, 5, 3, 4])
'NO'
It is assumed that the input lists will be non-empty.
""" | def exchange(lst1: List[int], lst2: List[int]) -> str:
"""In this problem, you will implement a function that takes two lists of numbers,
and determines whether it is possible to perform an exchange of elements
between them to make lst1 a list of only even numbers.
There is no limit on the number of exchanged elements between lst1 and lst2.
If it is possible to exchange elements between the lst1 and lst2 to make
all the elements of lst1 to be even, return "YES".
Otherwise, return "NO".
For example:
>>> exchange([1, 2, 3, 4], [1, 2, 3, 4])
'YES'
>>> exchange([1, 2, 3, 4], [1, 5, 3, 4])
'NO'
It is assumed that the input lists will be non-empty.
"""
odd = 0
even = 0
for i in lst1:
if i % 2 == 1:
odd += 1
for i in lst2:
if i % 2 == 0:
even += 1
if even >= odd:
return 'YES'
return 'NO' | exchange | def exchange_from_repetition(lst1: List[int], lst2: List[int], n: int) -> List[str]:
"""In this problem, you will implement a function that takes two lists of numbers (lst1 and lst2) and a number (n),
and determines whether it is possible to perform an exchange of elements
between "lst1" and "k-times repeated lst2" (k <= n) to make lst1 a list of only even numbers.
There is no limit on the number of exchanged elements between "lst1" and "k-times repeated lst2".
Return the array of length n whose k-th element is "YES" if it is possible to exchange elements between the "lst1"
and "k-times repeated lst2" to make all the elements of lst1 to be even.
Otherwise, k-th element is "NO".
For example:
>>> exchange_from_repetition([1, 2, 3, 4], [1, 5, 3, 4], 1)
['NO']
>>> exchange_from_repetition([1, 2, 3, 4], [1, 5, 3, 4], 3)
['NO', 'YES', 'YES']
It is assumed that the input lists will be non-empty.
""" | def exchange_from_repetition(lst1: List[int], lst2: List[int], n: int) -> List[str]:
"""In this problem, you will implement a function that takes two lists of numbers (lst1 and lst2) and a number (n),
and determines whether it is possible to perform an exchange of elements
between "lst1" and "k-times repeated lst2" (k <= n) to make lst1 a list of only even numbers.
There is no limit on the number of exchanged elements between "lst1" and "k-times repeated lst2".
Return the array of length n whose k-th element is "YES" if it is possible to exchange elements between the "lst1"
and "k-times repeated lst2" to make all the elements of lst1 to be even.
Otherwise, k-th element is "NO".
For example:
>>> exchange_from_repetition([1, 2, 3, 4], [1, 5, 3, 4], 1)
['NO']
>>> exchange_from_repetition([1, 2, 3, 4], [1, 5, 3, 4], 3)
['NO', 'YES', 'YES']
It is assumed that the input lists will be non-empty.
"""
return [exchange(lst1, lst2 * k) for k in range(1, n + 1)] | exchange_from_repetition | def check(candidate):
assert candidate([1, 2, 3, 4], [1, 2, 3, 4], 1) == ['YES']
assert candidate([1, 2, 3, 4], [1, 2, 3, 4], 2) == ['YES', 'YES']
assert candidate([1, 2, 3, 4], [1, 2, 3, 4], 3) == ['YES', 'YES', 'YES']
assert candidate([1, 2, 3, 4], [1, 5, 3, 4], 1) == ['NO']
assert candidate([1, 2, 3, 4], [1, 5, 3, 4], 2) == ['NO', 'YES']
assert candidate([1, 2, 3, 4], [1, 5, 3, 4], 3) == ['NO', 'YES', 'YES']
def test_check():
check(exchange_from_repetition)
test_check() | [
"\ndef",
"\n#",
"\nif",
"\nclass"
] |
from typing import Dict, Tuple | def histogram(test: str) -> Dict[str, int]:
"""Given a string representing a space separated lowercase letters, return a dictionary
of the letter with the most repetition and containing the corresponding count.
If several letters have the same occurrence, return all of them.
Example:
>>> histogram('a b c')
{ 'a': 1, 'b': 1, 'c': 1 }
>>> histogram('a b b a')
{ 'a': 2, 'b': 2 }
>>> histogram('a b c a b')
{ 'a': 2, 'b': 2 }
>>> histogram('b b b b a')
{ 'b': 4 }
>>> histogram('')
{ }
""" | def histogram(test: str) -> Dict[str, int]:
"""Given a string representing a space separated lowercase letters, return a dictionary
of the letter with the most repetition and containing the corresponding count.
If several letters have the same occurrence, return all of them.
Example:
>>> histogram('a b c')
{ 'a': 1, 'b': 1, 'c': 1 }
>>> histogram('a b b a')
{ 'a': 2, 'b': 2 }
>>> histogram('a b c a b')
{ 'a': 2, 'b': 2 }
>>> histogram('b b b b a')
{ 'b': 4 }
>>> histogram('')
{ }
"""
dict1 = {}
list1 = test.split(' ')
t = 0
for i in list1:
if list1.count(i) > t and i != '':
t = list1.count(i)
if t > 0:
for i in list1:
if list1.count(i) == t:
dict1[i] = t
return dict1 | histogram | def most_frequent_letter(test: str) -> Tuple[str, int]:
"""Given a string representing a space separated lowercase letters, return a tuple
of the letter with the most repetition and containing the corresponding count.
If several letters have the same occurrence, return the largest one in an alphabetical order.
Example:
>>> most_frequent_letter('a b c')
('c', 1)
>>> most_frequent_letter('a b b a')
('b', 2)
>>> most_frequent_letter('a b c a b')
('b', 2)
""" | def most_frequent_letter(test: str) -> Tuple[str, int]:
"""Given a string representing a space separated lowercase letters, return a tuple
of the letter with the most repetition and containing the corresponding count.
If several letters have the same occurrence, return the largest one in an alphabetical order.
Example:
>>> most_frequent_letter('a b c')
('c', 1)
>>> most_frequent_letter('a b b a')
('b', 2)
>>> most_frequent_letter('a b c a b')
('b', 2)
"""
return max([e for e in histogram(test).items()], key=lambda x: x[0]) | most_frequent_letter | def check(candidate):
assert candidate('a b c') == ('c', 1)
assert candidate('a b b a') == ('b', 2)
assert candidate('a b c a b') == ('b', 2)
assert candidate('a b a a b') == ('a', 3)
assert candidate('b b b b a') == ('b', 4)
assert candidate('a b c d e e e f f f') == ('f', 3)
def test_check():
check(most_frequent_letter)
test_check() | [
"\ndef",
"\n#",
"\nif",
"\nclass"
] |
from typing import List, Tuple | def reverse_delete(s: str, c: str) -> Tuple[str, bool]:
"""Task
We are given two strings s and c, you have to deleted all the characters in s that are equal to any character in c
then check if the result string is palindrome.
A string is called palindrome if it reads the same backward as forward.
You should return a tuple containing the result string and True/False for the check.
Example
>>> reverse_delete('abcde', 'ae')
('bcd', False)
>>> reverse_delete('abcdef', 'b')
('acdef', False)
>>> reverse_delete('abcdedcba', 'ab')
('cdedc', True)
""" | def reverse_delete(s: str, c: str) -> Tuple[str, bool]:
"""Task
We are given two strings s and c, you have to deleted all the characters in s that are equal to any character in c
then check if the result string is palindrome.
A string is called palindrome if it reads the same backward as forward.
You should return a tuple containing the result string and True/False for the check.
Example
>>> reverse_delete('abcde', 'ae')
('bcd', False)
>>> reverse_delete('abcdef', 'b')
('acdef', False)
>>> reverse_delete('abcdedcba', 'ab')
('cdedc', True)
"""
s = ''.join([char for char in s if char not in c])
return (s, s[::-1] == s) | reverse_delete | def reverse_delete_list(s: str, c: str) -> List[Tuple[str, bool]]:
"""Task
We are given two strings s and c, you have to deleted all the characters in s that are equal to each of the characters in c
then check if each result string is palindrome.
A string is called palindrome if it reads the same backward as forward.
You should return a list of the tuples containing result string and True/False for the check.
Example
>>> reverse_delete_list('abcde', 'ae')
[('bcde', False), ('abcd', 'False')]
>>> reverse_delete_list('abcdef', 'b')
[('acdef', False)]
>>> reverse_delete_list('abcdedcba', 'ab')
[('bcdedcb', True), ('acdedca', True)]
""" | def reverse_delete_list(s: str, c: str) -> List[Tuple[str, bool]]:
"""Task
We are given two strings s and c, you have to deleted all the characters in s that are equal to each of the characters in c
then check if each result string is palindrome.
A string is called palindrome if it reads the same backward as forward.
You should return a list of the tuples containing result string and True/False for the check.
Example
>>> reverse_delete_list('abcde', 'ae')
[('bcde', False), ('abcd', 'False')]
>>> reverse_delete_list('abcdef', 'b')
[('acdef', False)]
>>> reverse_delete_list('abcdedcba', 'ab')
[('bcdedcb', True), ('acdedca', True)]
"""
return [reverse_delete(s, e) for e in c] | reverse_delete_list | def check(candidate):
assert candidate('abcde', 'ae') == [('bcde', False), ('abcd', False)]
assert candidate('abcdef', 'b') == [('acdef', False)]
assert candidate('aabaa', 'b') == [('aaaa', True)]
assert candidate('abcdedcba', 'ab') == [('bcdedcb', True), ('acdedca', True)]
assert candidate('abcdedcba', 'abc') == [('bcdedcb', True), ('acdedca', True), ('abdedba', True)]
assert candidate('eabcdefdcba', 'ef') == [('abcdfdcba', True), ('eabcdedcba', False)]
def test_check():
check(reverse_delete_list)
test_check() | [
"\ndef",
"\n#",
"\nif",
"\nclass"
] |
from typing import List | def odd_count(lst: List[str]) -> List[str]:
"""Given a list of strings, where each string consists of only digits, return a list.
Each element i of the output should be "the number of odd elements in the
string i of the input." where all the i's should be replaced by the number
of odd digits in the i'th string of the input.
>>> odd_count(['1234567'])
['the number of odd elements 4n the str4ng 4 of the 4nput.']
>>> odd_count(['3', '11111111'])
['the number of odd elements 1n the str1ng 1 of the 1nput.', 'the number of odd elements 8n the str8ng 8 of the 8nput.']
""" | def odd_count(lst: List[str]) -> List[str]:
"""Given a list of strings, where each string consists of only digits, return a list.
Each element i of the output should be "the number of odd elements in the
string i of the input." where all the i's should be replaced by the number
of odd digits in the i'th string of the input.
>>> odd_count(['1234567'])
['the number of odd elements 4n the str4ng 4 of the 4nput.']
>>> odd_count(['3', '11111111'])
['the number of odd elements 1n the str1ng 1 of the 1nput.', 'the number of odd elements 8n the str8ng 8 of the 8nput.']
"""
res = []
for arr in lst:
n = sum((int(d) % 2 == 1 for d in arr))
res.append('the number of odd elements ' + str(n) + 'n the str' + str(n) + 'ng ' + str(n) + ' of the ' + str(n) + 'nput.')
return res | odd_count | def split_odd_count(lst: List[str], strsize: int) -> List[str]:
"""Given a list of strings, where each string consists of only digits,
first split each string into shorter ones with the length strsize and return a list.
Each element i of the output should be "the number of odd elements in the
string i of the input." where all the i's should be replaced by the number
of odd digits in the i'th string of the input.
>>> split_odd_count(['1234567'], 7)
['the number of odd elements 4n the str4ng 4 of the 4nput.']
>>> split_odd_count(['3', '11111111'], 4)
['the number of odd elements 1n the str1ng 1 of the 1nput.',
'the number of odd elements 4n the str4ng 4 of the 4nput.',
'the number of odd elements 4n the str4ng 4 of the 4nput.']
""" | def split_odd_count(lst: List[str], strsize: int) -> List[str]:
"""Given a list of strings, where each string consists of only digits,
first split each string into shorter ones with the length strsize and return a list.
Each element i of the output should be "the number of odd elements in the
string i of the input." where all the i's should be replaced by the number
of odd digits in the i'th string of the input.
>>> split_odd_count(['1234567'], 7)
['the number of odd elements 4n the str4ng 4 of the 4nput.']
>>> split_odd_count(['3', '11111111'], 4)
['the number of odd elements 1n the str1ng 1 of the 1nput.',
'the number of odd elements 4n the str4ng 4 of the 4nput.',
'the number of odd elements 4n the str4ng 4 of the 4nput.']
"""
split_lst = [s[i:i + strsize] for s in lst for i in range(0, len(s), strsize)]
return odd_count(split_lst) | split_odd_count | def check(candidate):
assert candidate(['1234567'], 7) == ['the number of odd elements 4n the str4ng 4 of the 4nput.']
assert candidate(['3', '11111111'], 4) == ['the number of odd elements 1n the str1ng 1 of the 1nput.', 'the number of odd elements 4n the str4ng 4 of the 4nput.', 'the number of odd elements 4n the str4ng 4 of the 4nput.']
assert candidate(['1', '2'], 2) == ['the number of odd elements 1n the str1ng 1 of the 1nput.', 'the number of odd elements 0n the str0ng 0 of the 0nput.']
assert candidate(['987234826349'], 6) == ['the number of odd elements 3n the str3ng 3 of the 3nput.', 'the number of odd elements 2n the str2ng 2 of the 2nput.']
assert candidate(['987234826349'], 8) == ['the number of odd elements 3n the str3ng 3 of the 3nput.', 'the number of odd elements 2n the str2ng 2 of the 2nput.']
assert candidate(['987234826349'], 10) == ['the number of odd elements 4n the str4ng 4 of the 4nput.', 'the number of odd elements 1n the str1ng 1 of the 1nput.']
def test_check():
check(split_odd_count)
test_check() | [
"\ndef",
"\n#",
"\nif",
"\nclass"
] |
from typing import List | def minSubArraySum(nums: List[int]) -> int:
"""
Given an array of integers nums, find the minimum sum of any non-empty sub-array
of nums.
Example
>>> minSubArraySum([2, 3, 4, 1, 2, 4])
1
>>> minSubArraySum([-1, -2, -3])
-6
""" | def minSubArraySum(nums: List[int]) -> int:
"""
Given an array of integers nums, find the minimum sum of any non-empty sub-array
of nums.
Example
>>> minSubArraySum([2, 3, 4, 1, 2, 4])
1
>>> minSubArraySum([-1, -2, -3])
-6
"""
max_sum = 0
s = 0
for num in nums:
s += -num
if s < 0:
s = 0
max_sum = max(s, max_sum)
if max_sum == 0:
max_sum = max((-i for i in nums))
min_sum = -max_sum
return min_sum | minSubArraySum | def minSubArraySumNonNegative(nums: List[int]) -> int:
"""
Given an array of integers nums, find the minimum sum of any non-empty sub-array
of nums. Consider all negative integers as 0.
Example
>>> minSubArraySumNonNegative([2, 3, 4, 1, 2, 4])
1
>>> minSubArraySumNonNegative([-1, -2, -3])
0
""" | def minSubArraySumNonNegative(nums: List[int]) -> int:
"""
Given an array of integers nums, find the minimum sum of any non-empty sub-array
of nums. Consider all negative integers as 0.
Example
>>> minSubArraySumNonNegative([2, 3, 4, 1, 2, 4])
1
>>> minSubArraySumNonNegative([-1, -2, -3])
0
"""
return minSubArraySum([max(e, 0) for e in nums]) | minSubArraySumNonNegative | def check(candidate):
assert candidate([2, 3, 4, 1, 2, 4]) == 1
assert candidate([-1, -2, -3]) == 0
assert candidate([1, 2, 3, 4, 1, 2, 3, 4]) == 1
assert candidate([1, 2, -1, -3, -4, -5, 6, 1]) == 0
assert candidate([0, 0, 0]) == 0
assert candidate([1, 0, -1]) == 0
def test_check():
check(minSubArraySumNonNegative)
test_check() | [
"\ndef",
"\n#",
"\nif",
"\nclass"
] |
import math
from typing import List | def max_fill(grid: List[List[int]], capacity: int) -> int:
"""
You are given a rectangular grid of wells. Each row represents a single well,
and each 1 in a row represents a single unit of water.
Each well has a corresponding bucket that can be used to extract water from it,
and all buckets have the same capacity.
Your task is to use the buckets to empty the wells.
Output the number of times you need to lower the buckets.
Example 1:
>>> max_fill([[0, 0, 1, 0], [0, 1, 0, 0], [1, 1, 1, 1]], 1)
6
Example 2:
>>> max_fill([[0, 0, 1, 1], [0, 0, 0, 0], [1, 1, 1, 1], [0, 1, 1, 1]], 2)
5
Example 3:
>>> max_fill([[0, 0, 0], [0, 0, 0]], 5)
0
Constraints:
* all wells have the same length
* 1 <= grid.length <= 10^2
* 1 <= grid[:,1].length <= 10^2
* grid[i][j] -> 0 | 1
* 1 <= capacity <= 10
""" | def max_fill(grid: List[List[int]], capacity: int) -> int:
"""
You are given a rectangular grid of wells. Each row represents a single well,
and each 1 in a row represents a single unit of water.
Each well has a corresponding bucket that can be used to extract water from it,
and all buckets have the same capacity.
Your task is to use the buckets to empty the wells.
Output the number of times you need to lower the buckets.
Example 1:
>>> max_fill([[0, 0, 1, 0], [0, 1, 0, 0], [1, 1, 1, 1]], 1)
6
Example 2:
>>> max_fill([[0, 0, 1, 1], [0, 0, 0, 0], [1, 1, 1, 1], [0, 1, 1, 1]], 2)
5
Example 3:
>>> max_fill([[0, 0, 0], [0, 0, 0]], 5)
0
Constraints:
* all wells have the same length
* 1 <= grid.length <= 10^2
* 1 <= grid[:,1].length <= 10^2
* grid[i][j] -> 0 | 1
* 1 <= capacity <= 10
"""
return sum([math.ceil(sum(arr) / capacity) for arr in grid]) | max_fill | def max_fill_buckets(grid: List[List[int]], capacities: List[int]) -> List[int]:
"""
You are given a rectangular grid of wells. Each row represents a single well,
and each 1 in a row represents a single unit of water.
Each well has corresponding buckets that can be used to extract water from it,
and all buckets have the same capacity.
Your task is to use the buckets with different capacities to empty the wells.
Output the list of the number of times you need to lower the buckets for each capacity.
Example 1:
>>> max_fill_buckets([[0, 0, 1, 0], [0, 1, 0, 0], [1, 1, 1, 1]], [1, 2])
[6, 4]
Example 2:
>>> max_fill_buckets([[0, 0, 1, 1], [0, 0, 0, 0], [1, 1, 1, 1], [0, 1, 1, 1]], [1, 2])
[9, 5]
Example 3:
>>> max_fill_buckets([[0, 0, 0], [0, 0, 0]], [5])
[0]
Constraints:
* all wells have the same length
* 1 <= grid.length <= 10^2
* 1 <= grid[:,1].length <= 10^2
* grid[i][j] -> 0 | 1
* 1 <= capacity <= 10
""" | def max_fill_buckets(grid: List[List[int]], capacities: List[int]) -> List[int]:
"""
You are given a rectangular grid of wells. Each row represents a single well,
and each 1 in a row represents a single unit of water.
Each well has corresponding buckets that can be used to extract water from it,
and all buckets have the same capacity.
Your task is to use the buckets with different capacities to empty the wells.
Output the list of the number of times you need to lower the buckets for each capacity.
Example 1:
>>> max_fill_buckets([[0, 0, 1, 0], [0, 1, 0, 0], [1, 1, 1, 1]], [1, 2])
[6, 4]
Example 2:
>>> max_fill_buckets([[0, 0, 1, 1], [0, 0, 0, 0], [1, 1, 1, 1], [0, 1, 1, 1]], [1, 2])
[9, 5]
Example 3:
>>> max_fill_buckets([[0, 0, 0], [0, 0, 0]], [5])
[0]
Constraints:
* all wells have the same length
* 1 <= grid.length <= 10^2
* 1 <= grid[:,1].length <= 10^2
* grid[i][j] -> 0 | 1
* 1 <= capacity <= 10
"""
return [max_fill(grid, capacity) for capacity in capacities] | max_fill_buckets | def check(candidate):
assert candidate([[0, 0, 1, 0], [0, 1, 0, 0], [1, 1, 1, 1]], [1, 2]) == [6, 4]
assert candidate([[0, 0, 1, 0], [0, 1, 0, 0], [1, 1, 1, 1]], [3, 4]) == [4, 3]
assert candidate([[0, 0, 1, 1], [0, 0, 0, 0], [1, 1, 1, 1], [0, 1, 1, 1]], [1, 2]) == [9, 5]
assert candidate([[0, 0, 1, 1], [0, 0, 0, 0], [1, 1, 1, 1], [0, 1, 1, 1]], [3, 4]) == [4, 3]
assert candidate([[0, 0, 0], [0, 0, 0]], [5]) == [0]
assert candidate([[0, 0, 0], [0, 0, 0]], [1, 2, 3, 4, 5]) == [0, 0, 0, 0, 0]
def test_check():
check(max_fill_buckets)
test_check() | [
"\ndef",
"\n#",
"\nif",
"\nclass"
] |
from typing import List | def sort_array(arr: List[int]) -> List[int]:
"""
In this Kata, you have to sort an array of non-negative integers according to
number of ones in their binary representation in ascending order.
For similar number of ones, sort based on decimal value.
It must be implemented like this:
>>> sort_array([1, 5, 2, 3, 4])
[1, 2, 4, 3, 5]
>>> sort_array([-2, -3, -4, -5, -6])
[-4, -2, -6, -5, -3]
>>> sort_array([1, 0, 2, 3, 4])
[0, 1, 2, 4, 3]
""" | def sort_array(arr: List[int]) -> List[int]:
"""
In this Kata, you have to sort an array of non-negative integers according to
number of ones in their binary representation in ascending order.
For similar number of ones, sort based on decimal value.
It must be implemented like this:
>>> sort_array([1, 5, 2, 3, 4])
[1, 2, 4, 3, 5]
>>> sort_array([-2, -3, -4, -5, -6])
[-4, -2, -6, -5, -3]
>>> sort_array([1, 0, 2, 3, 4])
[0, 1, 2, 4, 3]
"""
return sorted(sorted(arr), key=lambda x: bin(x)[2:].count('1')) | sort_array | def check_moving_sort_array(arr: List[int]) -> List[bool]:
"""
In this Kata, you have to sort an array of non-negative integers according to
number of ones in their binary representation in ascending order.
For similar number of ones, sort based on decimal value.
Compare the original array and its sorted array, and then return the list of whether each
element is moved or not from its original position. (True if it is moved, False otherwise.)
It must be implemented like this:
>>> check_moving_sort_array([1, 5, 2, 3, 4])
[False, True, True, False, True]
>>> check_moving_sort_array([-2, -3, -4, -5, -6])
[True, True, True, False, True]
>>> check_moving_sort_array([1, 0, 2, 3, 4])
[True, True, False, True, True]
""" | def check_moving_sort_array(arr: List[int]) -> List[bool]:
"""
In this Kata, you have to sort an array of non-negative integers according to
number of ones in their binary representation in ascending order.
For similar number of ones, sort based on decimal value.
Compare the original array and its sorted array, and then return the list of whether each
element is moved or not from its original position. (True if it is moved, False otherwise.)
It must be implemented like this:
>>> check_moving_sort_array([1, 5, 2, 3, 4])
[False, True, True, False, True]
>>> check_moving_sort_array([-2, -3, -4, -5, -6])
[True, True, True, False, True]
>>> check_moving_sort_array([1, 0, 2, 3, 4])
[True, True, False, True, True]
"""
sorted_arr = sort_array(arr)
return [True if a != b else False for (a, b) in zip(arr, sorted_arr)] | check_moving_sort_array | def check(candidate):
assert candidate([1, 5, 2, 3, 4]) == [False, True, True, False, True]
assert candidate([-2, -3, -4, -5, -6]) == [True, True, True, False, True]
assert candidate([1, 0, 2, 3, 4]) == [True, True, False, True, True]
assert candidate([1, 2, 3, 4, 5, 6, 7, 8]) == [False, False, True, True, True, True, True, True]
assert candidate([-4, -1, 9, 0, -9, 1, 4]) == [True, True, True, True, True, True, True]
assert candidate([11, 14]) == [False, False]
def test_check():
check(check_moving_sort_array)
test_check() | [
"\ndef",
"\n#",
"\nif",
"\nclass"
] |
from typing import List | def select_words(s: str, n: int) -> List[str]:
"""Given a string s and a natural number n, you have been tasked to implement
a function that returns a list of all words from string s that contain exactly
n consonants, in order these words appear in the string s.
If the string s is empty then the function should return an empty list.
Note: you may assume the input string contains only letters and spaces.
Examples:
>>> select_words('Mary had a little lamb', 4)
['little']
>>> select_words('Mary had a little lamb', 3)
['Mary', 'lamb']
>>> select_words('simple white space', 2)
[]
>>> select_words('Hello world', 4)
['world']
>>> select_words('Uncle sam', 3)
['Uncle']
""" | def select_words(s: str, n: int) -> List[str]:
"""Given a string s and a natural number n, you have been tasked to implement
a function that returns a list of all words from string s that contain exactly
n consonants, in order these words appear in the string s.
If the string s is empty then the function should return an empty list.
Note: you may assume the input string contains only letters and spaces.
Examples:
>>> select_words('Mary had a little lamb', 4)
['little']
>>> select_words('Mary had a little lamb', 3)
['Mary', 'lamb']
>>> select_words('simple white space', 2)
[]
>>> select_words('Hello world', 4)
['world']
>>> select_words('Uncle sam', 3)
['Uncle']
"""
result = []
for word in s.split():
n_consonants = 0
for i in range(0, len(word)):
if word[i].lower() not in ['a', 'e', 'i', 'o', 'u']:
n_consonants += 1
if n_consonants == n:
result.append(word)
return result | select_words | def select_largest_word(s: str, n: int) -> str:
"""Given a string s and a natural number n, you have been tasked to implement
a function that returns the word from string s that contain exactly n consonants.
If there exist multiple words satisfying the condition, return the largest one in an alphabetical order.
If the string s is empty then the function should return an empty string.
Note: you may assume the input string contains only letters and spaces.
Examples:
>>> select_largest_word('Mary had a little lamb', 4)
'little'
>>> select_largest_word('Mary had a little lamb', 3)
'lamb'
>>> select_largest_word('simple white space', 2)
''
>>> select_largest_word('Hello world', 4)
'world'
>>> select_largest_word('Uncle sam', 3)
'Uncle'
""" | def select_largest_word(s: str, n: int) -> str:
"""Given a string s and a natural number n, you have been tasked to implement
a function that returns the word from string s that contain exactly n consonants.
If there exist multiple words satisfying the condition, return the largest one in an alphabetical order.
If the string s is empty then the function should return an empty string.
Note: you may assume the input string contains only letters and spaces.
Examples:
>>> select_largest_word('Mary had a little lamb', 4)
'little'
>>> select_largest_word('Mary had a little lamb', 3)
'lamb'
>>> select_largest_word('simple white space', 2)
''
>>> select_largest_word('Hello world', 4)
'world'
>>> select_largest_word('Uncle sam', 3)
'Uncle'
"""
return max(select_words(s, n) + ['']) | select_largest_word | def check(candidate):
assert candidate('Mary had a little lamb', 4) == 'little'
assert candidate('Mary had a little lamb', 3) == 'lamb'
assert candidate('simple white space', 2) == ''
assert candidate('Hello world', 4) == 'world'
assert candidate('Uncle sam', 3) == 'Uncle'
assert candidate('baeiou aeiouz', 1) == 'baeiou'
def test_check():
check(select_largest_word)
test_check() | [
"\ndef",
"\n#",
"\nif",
"\nclass"
] |
def get_closest_vowel(word: str) -> str:
"""You are given a word. Your task is to find the closest vowel that stands between
two consonants from the right side of the word (case sensitive).
Vowels in the beginning and ending doesn't count. Return empty string if you didn't
find any vowel met the above condition.
You may assume that the given string contains English letter only.
Example:
>>> get_closest_vowel('yogurt')
'u'
>>> get_closest_vowel('FULL')
'U'
>>> get_closest_vowel('quick')
''
>>> get_closest_vowel('ab')
''
""" | def get_closest_vowel(word: str) -> str:
"""You are given a word. Your task is to find the closest vowel that stands between
two consonants from the right side of the word (case sensitive).
Vowels in the beginning and ending doesn't count. Return empty string if you didn't
find any vowel met the above condition.
You may assume that the given string contains English letter only.
Example:
>>> get_closest_vowel('yogurt')
'u'
>>> get_closest_vowel('FULL')
'U'
>>> get_closest_vowel('quick')
''
>>> get_closest_vowel('ab')
''
"""
if len(word) < 3:
return ''
vowels = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'O', 'U', 'I'}
for i in range(len(word) - 2, 0, -1):
if word[i] in vowels:
if word[i + 1] not in vowels and word[i - 1] not in vowels:
return word[i]
return '' | get_closest_vowel | def transform_closest_vowel(s: str) -> str:
"""You are given a string containing multiple words. Your task is to make a new string by changing each word
to its closest vowel that stands between two consonants from the right side of the word (case sensitive).
You need to concatenate all the closest vowels that are obtained from each word.
Vowels in the beginning and ending doesn't count. Ignore the word if you didn't
find any vowel met the above condition.
You may assume that the given string contains English letter only.
Example:
>>> transform_closest_vowel('yogurt FULL')
'uU'
>>> transform_closest_vowel('quick ab')
''
""" | def transform_closest_vowel(s: str) -> str:
"""You are given a string containing multiple words. Your task is to make a new string by changing each word
to its closest vowel that stands between two consonants from the right side of the word (case sensitive).
You need to concatenate all the closest vowels that are obtained from each word.
Vowels in the beginning and ending doesn't count. Ignore the word if you didn't
find any vowel met the above condition.
You may assume that the given string contains English letter only.
Example:
>>> transform_closest_vowel('yogurt FULL')
'uU'
>>> transform_closest_vowel('quick ab')
''
"""
return ''.join([get_closest_vowel(word) for word in s.split()]) | transform_closest_vowel | def check(candidate):
assert candidate('yogurt FULL') == 'uU'
assert candidate('quick ab') == ''
assert candidate('Alice loves Bob') == 'ieo'
assert candidate('happy sunny day ever') == 'auae'
assert candidate('aaa bbb ccc ddd') == ''
assert candidate('fox and dog') == 'oo'
def test_check():
check(transform_closest_vowel)
test_check() | [
"\ndef",
"\n#",
"\nif",
"\nclass"
] |
|
from typing import List | def match_parens(lst: List[str]) -> str:
"""
You are given a list of two strings, both strings consist of open
parentheses '(' or close parentheses ')' only.
Your job is to check if it is possible to concatenate the two strings in
some order, that the resulting string will be good.
A string S is considered to be good if and only if all parentheses in S
are balanced. For example: the string '(())()' is good, while the string
'())' is not.
Return 'Yes' if there's a way to make a good string, and return 'No' otherwise.
Examples:
>>> match_parens(['()(', ')'])
'Yes'
>>> match_parens([')', ')'])
'No'
""" | def match_parens(lst: List[str]) -> str:
"""
You are given a list of two strings, both strings consist of open
parentheses '(' or close parentheses ')' only.
Your job is to check if it is possible to concatenate the two strings in
some order, that the resulting string will be good.
A string S is considered to be good if and only if all parentheses in S
are balanced. For example: the string '(())()' is good, while the string
'())' is not.
Return 'Yes' if there's a way to make a good string, and return 'No' otherwise.
Examples:
>>> match_parens(['()(', ')'])
'Yes'
>>> match_parens([')', ')'])
'No'
"""
def check(s):
val = 0
for i in s:
if i == '(':
val = val + 1
else:
val = val - 1
if val < 0:
return False
return True if val == 0 else False
S1 = lst[0] + lst[1]
S2 = lst[1] + lst[0]
return 'Yes' if check(S1) or check(S2) else 'No' | match_parens | def match_parens_from_list(str1: str, lst2: List[str]) -> str:
"""
You are given a string (str1) and a list of strings (lst2), where every string consists of open
parentheses '(' or close parentheses ')' only.
Your job is to check if it is possible to concatenate a string (selected from the list lst2)
and the first string str1 in some order, that the resulting string will be good.
A string S is considered to be good if and only if all parentheses in S
are balanced. For example: the string '(())()' is good, while the string '())' is not.
Return 'Yes' if there's a way to make a good string, and return 'No' otherwise.
Examples:
>>> match_parens_from_list('()(' [')', '(((())(()())))'])
'Yes'
>>> match_parens_from_list(')', [')'])
'No'
""" | def match_parens_from_list(str1: str, lst2: List[str]) -> str:
"""
You are given a string (str1) and a list of strings (lst2), where every string consists of open
parentheses '(' or close parentheses ')' only.
Your job is to check if it is possible to concatenate a string (selected from the list lst2)
and the first string str1 in some order, that the resulting string will be good.
A string S is considered to be good if and only if all parentheses in S
are balanced. For example: the string '(())()' is good, while the string '())' is not.
Return 'Yes' if there's a way to make a good string, and return 'No' otherwise.
Examples:
>>> match_parens_from_list('()(' [')', '(((())(()())))'])
'Yes'
>>> match_parens_from_list(')', [')'])
'No'
"""
for str2 in lst2:
if match_parens([str1, str2]) == 'Yes':
return 'Yes'
return 'No' | match_parens_from_list | def check(candidate):
assert candidate('()(', [')', '(((())(()())))']) == 'Yes'
assert candidate(')', [')']) == 'No'
assert candidate('()((', ['))', '((()())']) == 'Yes'
assert candidate('()((', ['(((()()))', ')']) == 'No'
assert candidate('()((', ['(((()()))', ')', ')))', '))))']) == 'No'
assert candidate('()((', ['(((()()))', ')', '))']) == 'Yes'
def test_check():
check(match_parens_from_list)
test_check() | [
"\ndef",
"\n#",
"\nif",
"\nclass"
] |
from typing import List | def maximum(arr: List[int], k: int) -> List[int]:
"""
Given an array arr of integers and a positive integer k, return a sorted list
of length k with the maximum k numbers in arr.
Example 1:
>>> maximum([-3, -4, 5], 3)
[-4, -3, 5]
Example 2:
>>> maximum([4, -4, 4], 2)
[4, 4]
Example 3:
>>> maximum([-3, 2, 1, 2, -1, -2, 1], 1)
[2]
Note:
1. The length of the array will be in the range of [1, 1000].
2. The elements in the array will be in the range of [-1000, 1000].
3. 0 <= k <= len(arr)
""" | def maximum(arr: List[int], k: int) -> List[int]:
"""
Given an array arr of integers and a positive integer k, return a sorted list
of length k with the maximum k numbers in arr.
Example 1:
>>> maximum([-3, -4, 5], 3)
[-4, -3, 5]
Example 2:
>>> maximum([4, -4, 4], 2)
[4, 4]
Example 3:
>>> maximum([-3, 2, 1, 2, -1, -2, 1], 1)
[2]
Note:
1. The length of the array will be in the range of [1, 1000].
2. The elements in the array will be in the range of [-1000, 1000].
3. 0 <= k <= len(arr)
"""
if k == 0:
return []
arr.sort()
ans = arr[-k:]
return ans | maximum | def minimum_of_maximum_subarrays(arrays: List[List[int]], k: int) -> int:
"""
Given a list of arrays and a positive integer k, return the minimal integer among the arrays.
Example 1:
>>> minimum_of_maximum_subarrays([[-3, -4, 5], [4, -4, 4], [-3, 2, 1, 2, -1, -2, 1]], 2)
-3
Example 2:
>>> minimum_of_maximum_subarrays([[1, 2, 3], [4, 5, 6], [7, 8, 9]], 1)
3
Note:
1. Each array in the list will have length in the range of [1, 1000].
2. The elements in each array will be in the range of [-1000, 1000].
3. 1 <= k <= min([len(arr) for arr in arrays])
""" | def minimum_of_maximum_subarrays(arrays: List[List[int]], k: int) -> int:
"""
Given a list of arrays and a positive integer k, return the minimal integer among the arrays.
Example 1:
>>> minimum_of_maximum_subarrays([[-3, -4, 5], [4, -4, 4], [-3, 2, 1, 2, -1, -2, 1]], 2)
-3
Example 2:
>>> minimum_of_maximum_subarrays([[1, 2, 3], [4, 5, 6], [7, 8, 9]], 1)
3
Note:
1. Each array in the list will have length in the range of [1, 1000].
2. The elements in each array will be in the range of [-1000, 1000].
3. 1 <= k <= min([len(arr) for arr in arrays])
"""
mins = [maximum(arr, k)[0] for arr in arrays]
return min(mins) | minimum_of_maximum_subarrays | def check(candidate):
assert candidate([[9, 3, 7], [5, 6]], 2) == 5
assert candidate([[37, 51, 22], [99, 13, 45], [43, 36, 28], [28, 39, 22]], 1) == 39
assert candidate([[50, 40, 20, 10], [22, 62, 78, 90]], 4) == 10
def test_check():
check(minimum_of_maximum_subarrays)
test_check() | [
"\ndef",
"\n#",
"\nif",
"\nclass"
] |
from typing import List | def solution(lst: List[int]) -> int:
"""Given a non-empty list of integers, return the sum of all of the odd elements that are in even positions.
Examples
>>> solution([5, 8, 7, 1])
12
>>> solution([3, 3, 3, 3, 3])
9
>>> solution([30, 13, 24, 321])
0
""" | def solution(lst: List[int]) -> int:
"""Given a non-empty list of integers, return the sum of all of the odd elements that are in even positions.
Examples
>>> solution([5, 8, 7, 1])
12
>>> solution([3, 3, 3, 3, 3])
9
>>> solution([30, 13, 24, 321])
0
"""
return sum([x for (idx, x) in enumerate(lst) if idx % 2 == 0 and x % 2 == 1]) | solution | def alternate_sum(arrays: List[List[int]]) -> int:
"""Given a list of arrays, return the sum of all of the odd elements that are in even positions
of all arrays in even positions minus the sum of all of the odd elements that are in odd positions.
Examples
>>> alternate_sum([[5, 8, 7, 1], [3, 3, 3, 3, 3]])
3
>>> alternate_sum([[30, 13, 24, 321], [3, 3, 3, 3, 3]])
-9
""" | def alternate_sum(arrays: List[List[int]]) -> int:
"""Given a list of arrays, return the sum of all of the odd elements that are in even positions
of all arrays in even positions minus the sum of all of the odd elements that are in odd positions.
Examples
>>> alternate_sum([[5, 8, 7, 1], [3, 3, 3, 3, 3]])
3
>>> alternate_sum([[30, 13, 24, 321], [3, 3, 3, 3, 3]])
-9
"""
return sum([solution(x) for (idx, x) in enumerate(arrays) if idx % 2 == 0]) - sum([solution(x) for (idx, x) in enumerate(arrays) if idx % 2 == 1]) | alternate_sum | def check(candidate):
assert candidate([[1, 2, 3, 4], [5, 6, 7, 8, 9]]) == -17
assert candidate([[10, 11], [-4, -5, -6, -7], [1, 3, 5, 7, 9]]) == 15
assert candidate([[6, 4, 3, -1, -2], [8, 9, 10, 11]]) == 3
def test_check():
check(alternate_sum)
test_check() | [
"\ndef",
"\n#",
"\nif",
"\nclass"
] |
from typing import List | def add_elements(arr: List[int], k: int) -> int:
"""
Given a non-empty array of integers arr and an integer k, return
the sum of the elements with at most two digits from the first k elements of arr.
Example:
>>> add_elements([111, 21, 3, 4000, 5, 6, 7, 8, 9], 4)
24
Constraints:
1. 1 <= len(arr) <= 100
2. 1 <= k <= len(arr)
""" | def add_elements(arr: List[int], k: int) -> int:
"""
Given a non-empty array of integers arr and an integer k, return
the sum of the elements with at most two digits from the first k elements of arr.
Example:
>>> add_elements([111, 21, 3, 4000, 5, 6, 7, 8, 9], 4)
24
Constraints:
1. 1 <= len(arr) <= 100
2. 1 <= k <= len(arr)
"""
return sum((elem for elem in arr[:k] if len(str(elem)) <= 2)) | add_elements | def max_num_passengers(arr: List[int]) -> int:
"""
Given an array of integers arr where each element represents the weight of
passengers, return the maximum number of passengers that can be carried on
a single elevator given that the sum of all the weights must be less than 100.
Examples:
>>> max_num_passengers([111, 21, 3, 4000, 5, 6, 7, 8, 9])
7
>>> max_num_passengers([215, 327, 102])
0
Constraints:
1. 1 <= len(arr) <= 100
2. arr[i] > 0
""" | def max_num_passengers(arr: List[int]) -> int:
"""
Given an array of integers arr where each element represents the weight of
passengers, return the maximum number of passengers that can be carried on
a single elevator given that the sum of all the weights must be less than 100.
Examples:
>>> max_num_passengers([111, 21, 3, 4000, 5, 6, 7, 8, 9])
7
>>> max_num_passengers([215, 327, 102])
0
Constraints:
1. 1 <= len(arr) <= 100
2. arr[i] > 0
"""
arr.sort()
for k in range(1, len(arr) + 1):
if add_elements(arr, k) >= 100:
return k - 1
return len(arr) | max_num_passengers | def check(candidate):
assert candidate([70, 13, 25, 10, 10, 45]) == 4
assert candidate([60, 55, 42, 37, 97]) == 2
assert candidate([1, 2, 3, 4, 5, 6, 7, 8, 9]) == 9
def test_check():
check(max_num_passengers)
test_check() | [
"\ndef",
"\n#",
"\nif",
"\nclass"
] |
from typing import List | def get_odd_collatz(n: int) -> List[int]:
"""
Given a positive integer n, return a sorted list that has the odd numbers in collatz sequence.
The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined
as follows: start with any positive integer n. Then each term is obtained from the
previous term as follows: if the previous term is even, the next term is one half of
the previous term. If the previous term is odd, the next term is 3 times the previous
term plus 1. The conjecture is that no matter what value of n, the sequence will always reach 1.
Note:
1. Collatz(1) is [1].
2. returned list sorted in increasing order.
For example:
get_odd_collatz(5) returns [1, 5] # The collatz sequence for 5 is [5, 16, 8, 4, 2, 1], so the odd numbers are only 1, and 5.
>>> get_odd_collatz(5)
[1, 5]
""" | def get_odd_collatz(n: int) -> List[int]:
"""
Given a positive integer n, return a sorted list that has the odd numbers in collatz sequence.
The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined
as follows: start with any positive integer n. Then each term is obtained from the
previous term as follows: if the previous term is even, the next term is one half of
the previous term. If the previous term is odd, the next term is 3 times the previous
term plus 1. The conjecture is that no matter what value of n, the sequence will always reach 1.
Note:
1. Collatz(1) is [1].
2. returned list sorted in increasing order.
For example:
get_odd_collatz(5) returns [1, 5] # The collatz sequence for 5 is [5, 16, 8, 4, 2, 1], so the odd numbers are only 1, and 5.
>>> get_odd_collatz(5)
[1, 5]
"""
if n % 2 == 0:
odd_collatz = []
else:
odd_collatz = [n]
while n > 1:
if n % 2 == 0:
n = n / 2
else:
n = n * 3 + 1
if n % 2 == 1:
odd_collatz.append(int(n))
return sorted(odd_collatz) | get_odd_collatz | def sum_odd_collatz(n: int) -> int:
"""
Given a positive integer n, return the sum of odd numbers in collatz sequence.
Examples:
>>> sum_odd_collatz(5)
6
>>> sum_odd_collatz(10)
6
""" | def sum_odd_collatz(n: int) -> int:
"""
Given a positive integer n, return the sum of odd numbers in collatz sequence.
Examples:
>>> sum_odd_collatz(5)
6
>>> sum_odd_collatz(10)
6
"""
return sum(get_odd_collatz(n)) | sum_odd_collatz | def check(candidate):
assert candidate(11) == 47
assert candidate(7) == 54
assert candidate(100) == 19
def test_check():
check(sum_odd_collatz)
test_check() | [
"\ndef",
"\n#",
"\nif",
"\nclass"
] |
from typing import List | def valid_date(date: str) -> bool:
"""You have to write a function which validates a given date string and
returns True if the date is valid otherwise False.
The date is valid if all of the following rules are satisfied:
1. The date string is not empty.
2. The number of days is not less than 1 or higher than 31 days for months 1,3,5,7,8,10,12. And the number of days is not less than 1 or higher than 30 days for months 4,6,9,11. And, the number of days is not less than 1 or higher than 29 for the month 2.
3. The months should not be less than 1 or higher than 12.
4. The date should be in the format: mm-dd-yyyy
>>> valid_date('03-11-2000')
True
>>> valid_date('15-01-2012')
False
>>> valid_date('04-0-2040')
False
>>> valid_date('06-04-2020')
True
>>> valid_date('06/04/2020')
False
""" | def valid_date(date: str) -> bool:
"""You have to write a function which validates a given date string and
returns True if the date is valid otherwise False.
The date is valid if all of the following rules are satisfied:
1. The date string is not empty.
2. The number of days is not less than 1 or higher than 31 days for months 1,3,5,7,8,10,12. And the number of days is not less than 1 or higher than 30 days for months 4,6,9,11. And, the number of days is not less than 1 or higher than 29 for the month 2.
3. The months should not be less than 1 or higher than 12.
4. The date should be in the format: mm-dd-yyyy
>>> valid_date('03-11-2000')
True
>>> valid_date('15-01-2012')
False
>>> valid_date('04-0-2040')
False
>>> valid_date('06-04-2020')
True
>>> valid_date('06/04/2020')
False
"""
try:
date = date.strip()
(month, day, year) = date.split('-')
(month, day, year) = (int(month), int(day), int(year))
if month < 1 or month > 12:
return False
if month in [1, 3, 5, 7, 8, 10, 12] and day < 1 or day > 31:
return False
if month in [4, 6, 9, 11] and day < 1 or day > 30:
return False
if month == 2 and day < 1 or day > 29:
return False
except:
return False
return True | valid_date | def num_valid_birthdays(dates: List[str]) -> int:
"""Given a list of birthdays with valid dates, return the number of people
who can be given some birthday gifts.
>>> num_valid_birthdays(['03-11-2000', '15-01-2012', '04-0-2040', '06-04-2020'])
2
""" | def num_valid_birthdays(dates: List[str]) -> int:
"""Given a list of birthdays with valid dates, return the number of people
who can be given some birthday gifts.
>>> num_valid_birthdays(['03-11-2000', '15-01-2012', '04-0-2040', '06-04-2020'])
2
"""
return sum([valid_date(date) for date in dates]) | num_valid_birthdays | def check(candidate):
assert candidate(['06/04/2020', '12-11-1987', '04-00-1999', '08-15-1992']) == 3
assert candidate(['00-01-1951', '19-02-1994', '10-24-1992']) == 1
assert candidate(['12-05-1976', '01-01-2010', '01/01/2010']) == 2
def test_check():
check(num_valid_birthdays)
test_check() | [
"\ndef",
"\n#",
"\nif",
"\nclass"
] |
from typing import List, Union | def split_words(txt: str) -> Union[List[str], int]:
"""
Given a string of words, return a list of words split on whitespace, if no whitespaces exists in the text you
should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
Examples
>>> split_words('Hello world!')
['Hello', 'world!']
>>> split_words('Hello,world!')
['Hello', 'world!']
>>> split_words('abcdef')
3
""" | def split_words(txt: str) -> Union[List[str], int]:
"""
Given a string of words, return a list of words split on whitespace, if no whitespaces exists in the text you
should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
Examples
>>> split_words('Hello world!')
['Hello', 'world!']
>>> split_words('Hello,world!')
['Hello', 'world!']
>>> split_words('abcdef')
3
"""
if ' ' in txt:
return txt.split()
elif ',' in txt:
return txt.replace(',', ' ').split()
else:
return len([i for i in txt if i.islower() and ord(i) % 2 == 0]) | split_words | def num_words(txt: str) -> int:
"""
Given one sentence of words, return the number of words in it.
>>> num_words('Hello world!')
2
>>> num_words('Hello,world!')
2
>>> num_words('abcdef')
1
""" | def num_words(txt: str) -> int:
"""
Given one sentence of words, return the number of words in it.
>>> num_words('Hello world!')
2
>>> num_words('Hello,world!')
2
>>> num_words('abcdef')
1
"""
result = split_words(txt)
if isinstance(result, list):
return len(result)
else:
return 1 | num_words | def check(candidate):
assert candidate('The fox jumped over the fence.') == 6
assert candidate('The,fox,jumped,over,the,fence.') == 6
assert candidate('I, as a human, love to sleep.') == 7
def test_check():
check(num_words)
test_check() | [
"\ndef",
"\n#",
"\nif",
"\nclass"
] |
from typing import List | def is_sorted(lst: List[int]) -> bool:
"""
Given a list of numbers, return whether or not they are sorted
in ascending order. If list has more than 1 duplicate of the same
number, return False. Assume no negative numbers and only integers.
Examples
>>> is_sorted([5])
True
>>> is_sorted([1, 2, 3, 4, 5])
True
>>> is_sorted([1, 3, 2, 4, 5])
False
>>> is_sorted([1, 2, 3, 4, 5, 6])
True
>>> is_sorted([1, 2, 3, 4, 5, 6, 7])
True
>>> is_sorted([1, 3, 2, 4, 5, 6, 7])
False
>>> is_sorted([1, 2, 2, 3, 3, 4])
True
>>> is_sorted([1, 2, 2, 2, 3, 4])
False
""" | def is_sorted(lst: List[int]) -> bool:
"""
Given a list of numbers, return whether or not they are sorted
in ascending order. If list has more than 1 duplicate of the same
number, return False. Assume no negative numbers and only integers.
Examples
>>> is_sorted([5])
True
>>> is_sorted([1, 2, 3, 4, 5])
True
>>> is_sorted([1, 3, 2, 4, 5])
False
>>> is_sorted([1, 2, 3, 4, 5, 6])
True
>>> is_sorted([1, 2, 3, 4, 5, 6, 7])
True
>>> is_sorted([1, 3, 2, 4, 5, 6, 7])
False
>>> is_sorted([1, 2, 2, 3, 3, 4])
True
>>> is_sorted([1, 2, 2, 2, 3, 4])
False
"""
count_digit = dict([(i, 0) for i in lst])
for i in lst:
count_digit[i] += 1
if any((count_digit[i] > 2 for i in lst)):
return False
if all((lst[i - 1] <= lst[i] for i in range(1, len(lst)))):
return True
else:
return False | is_sorted | def all_sorted(lst: List[List[int]]) -> bool:
"""
Given a non-empty list of lists of integers, return a boolean values indicating
whether each sublist is sorted in ascending order without more than one duplicate of the same number.
Examples
>>> all_sorted([[5], [1, 2, 3, 4, 5], [1, 3, 2, 4, 5], [1, 2, 3, 4, 5, 6], [1, 2, 2, 2, 3, 4]])
False
>>> all_sorted([1, 2, 3, 4, 5, 6, 7], [1, 2, 2, 3, 3, 4], [3, 5, 7, 8])
True
""" | def all_sorted(lst: List[List[int]]) -> bool:
"""
Given a non-empty list of lists of integers, return a boolean values indicating
whether each sublist is sorted in ascending order without more than one duplicate of the same number.
Examples
>>> all_sorted([[5], [1, 2, 3, 4, 5], [1, 3, 2, 4, 5], [1, 2, 3, 4, 5, 6], [1, 2, 2, 2, 3, 4]])
False
>>> all_sorted([1, 2, 3, 4, 5, 6, 7], [1, 2, 2, 3, 3, 4], [3, 5, 7, 8])
True
"""
return all([is_sorted(sublist) for sublist in lst]) | all_sorted | def check(candidate):
assert candidate([1, 1, 1, 2], [2, 3, 5], [4, 4, 5]) is False
assert candidate([1, 2, 3, 4, 5], [5, 7, 10, 13]) is True
assert candidate([3, 3, 4], [1, 2, 3], [7, 6, 7]) is False
def test_check():
check(all_sorted)
test_check() | [
"\ndef",
"\n#",
"\nif",
"\nclass"
] |
from itertools import combinations
from typing import List, Tuple | def intersection(interval1: Tuple[int, int], interval2: Tuple[int, int]) -> str:
"""You are given two intervals,
where each interval is a pair of integers. For example, interval = (start, end) = (1, 2).
The given intervals are closed which means that the interval (start, end)
includes both start and end.
For each given interval, it is assumed that its start is less or equal its end.
Your task is to determine whether the length of intersection of these two
intervals is a prime number.
Example, the intersection of the intervals (1, 3), (2, 4) is (2, 3)
which its length is 1, which not a prime number.
If the length of the intersection is a prime number, return "YES",
otherwise, return "NO".
If the two intervals don't intersect, return "NO".
[input/output] samples:
>>> intersection((1, 2), (2, 3))
'NO'
>>> intersection((-1, 1), (0, 4))
'NO'
>>> intersection((-3, -1), (-5, 5))
'YES'
""" | def intersection(interval1: Tuple[int, int], interval2: Tuple[int, int]) -> str:
"""You are given two intervals,
where each interval is a pair of integers. For example, interval = (start, end) = (1, 2).
The given intervals are closed which means that the interval (start, end)
includes both start and end.
For each given interval, it is assumed that its start is less or equal its end.
Your task is to determine whether the length of intersection of these two
intervals is a prime number.
Example, the intersection of the intervals (1, 3), (2, 4) is (2, 3)
which its length is 1, which not a prime number.
If the length of the intersection is a prime number, return "YES",
otherwise, return "NO".
If the two intervals don't intersect, return "NO".
[input/output] samples:
>>> intersection((1, 2), (2, 3))
'NO'
>>> intersection((-1, 1), (0, 4))
'NO'
>>> intersection((-3, -1), (-5, 5))
'YES'
"""
def is_prime(num):
if num == 1 or num == 0:
return False
if num == 2:
return True
for i in range(2, num):
if num % i == 0:
return False
return True
l = max(interval1[0], interval2[0])
r = min(interval1[1], interval2[1])
length = r - l
if length > 0 and is_prime(length):
return 'YES'
return 'NO' | intersection | def all_prime_intersection(intervals: List[Tuple[int, int]]) -> bool:
"""Check if all intersections of given intervals are prime numbers.
[inpt/output] samples:
>>> all_prime_intersection([(1, 2), (2, 3), (3, 4)])
False
>>> all_prime_intersection([(-3, 4), (-5, 5), (1, 4)])
True
""" | def all_prime_intersection(intervals: List[Tuple[int, int]]) -> bool:
"""Check if all intersections of given intervals are prime numbers.
[inpt/output] samples:
>>> all_prime_intersection([(1, 2), (2, 3), (3, 4)])
False
>>> all_prime_intersection([(-3, 4), (-5, 5), (1, 4)])
True
"""
comb = combinations(intervals, 2)
for (interval1, interval2) in comb:
if intersection(interval1, interval2) == 'NO':
return False
return True | all_prime_intersection | def check(candidate):
assert candidate([(-3, -1), (-5, 5), (3, 4)]) is False
assert candidate([(-1, 7), (-5, 4), (1, 4)]) is True
assert candidate([(1, 8), (3, 8), (-2, 6)]) is True
def test_check():
check(all_prime_intersection)
test_check() | [
"\ndef",
"\n#",
"\nif",
"\nclass"
] |
from typing import List, Optional | def prod_signs(arr: List[int]) -> Optional[int]:
"""
You are given an array arr of integers and you need to return
sum of magnitudes of integers multiplied by product of all signs
of each number in the array, represented by 1, -1 or 0.
Note: return None for empty arr.
Example:
>>> prod_signs([1, 2, 2, -4])
9
>>> prod_signs([0, 1])
0
>>> prod_signs([])
None
""" | def prod_signs(arr: List[int]) -> Optional[int]:
"""
You are given an array arr of integers and you need to return
sum of magnitudes of integers multiplied by product of all signs
of each number in the array, represented by 1, -1 or 0.
Note: return None for empty arr.
Example:
>>> prod_signs([1, 2, 2, -4])
9
>>> prod_signs([0, 1])
0
>>> prod_signs([])
None
"""
if not arr:
return None
prod = 0 if 0 in arr else (-1) ** len(list(filter(lambda x: x < 0, arr)))
return prod * sum([abs(i) for i in arr]) | prod_signs | def prod_signs_within_threshold(arr: List[int], threshold: int) -> Optional[int]:
"""
You are given an array arr of integers and you need to return
sum of magnitudes of integers within the threshold value,
multiplied by product of all signs of each number in the array.
Note: return None for empty arr.
Example:
>>> prod_signs_within_threshold([1, 2, 2, -4], 3)
5
>>> prod_signs_within_threshold([0, 1], 1)
0
>>> prod_signs_within_threshold([], 1)
None
""" | def prod_signs_within_threshold(arr: List[int], threshold: int) -> Optional[int]:
"""
You are given an array arr of integers and you need to return
sum of magnitudes of integers within the threshold value,
multiplied by product of all signs of each number in the array.
Note: return None for empty arr.
Example:
>>> prod_signs_within_threshold([1, 2, 2, -4], 3)
5
>>> prod_signs_within_threshold([0, 1], 1)
0
>>> prod_signs_within_threshold([], 1)
None
"""
return prod_signs(list(filter(lambda x: abs(x) <= threshold, arr))) | prod_signs_within_threshold | def check(candidate):
assert candidate([-1, -3, -5, -7, -9], 5) == 4
assert candidate([-10, -20, 30, -40, 50, -60], 45) == -100
assert candidate([-3, -2, -1, 0, 1, 2, 3], 2) == 0
def test_check():
check(prod_signs_within_threshold)
test_check() | [
"\ndef",
"\n#",
"\nif",
"\nclass"
] |
def tri(n: int) -> list[int]:
"""Everyone knows Fibonacci sequence, it was studied deeply by mathematicians in
the last couple centuries. However, what people don't know is Tribonacci sequence.
Tribonacci sequence is defined by the recurrence:
tri(1) = 3
tri(n) = 1 + n / 2, if n is even.
tri(n) = tri(n - 1) + tri(n - 2) + tri(n + 1), if n is odd.
For example:
tri(2) = 1 + (2 / 2) = 2
tri(4) = 3
tri(3) = tri(2) + tri(1) + tri(4)
= 2 + 3 + 3 = 8
You are given a non-negative integer number n, you have to a return a list of the
first n + 1 numbers of the Tribonacci sequence.
Examples:
>>> tri(3)
[1, 3, 2, 8]
""" | def tri(n: int) -> list[int]:
"""Everyone knows Fibonacci sequence, it was studied deeply by mathematicians in
the last couple centuries. However, what people don't know is Tribonacci sequence.
Tribonacci sequence is defined by the recurrence:
tri(1) = 3
tri(n) = 1 + n / 2, if n is even.
tri(n) = tri(n - 1) + tri(n - 2) + tri(n + 1), if n is odd.
For example:
tri(2) = 1 + (2 / 2) = 2
tri(4) = 3
tri(3) = tri(2) + tri(1) + tri(4)
= 2 + 3 + 3 = 8
You are given a non-negative integer number n, you have to a return a list of the
first n + 1 numbers of the Tribonacci sequence.
Examples:
>>> tri(3)
[1, 3, 2, 8]
"""
if n == 0:
return [1]
my_tri = [1, 3]
for i in range(2, n + 1):
if i % 2 == 0:
my_tri.append(i / 2 + 1)
else:
my_tri.append(my_tri[i - 1] + my_tri[i - 2] + (i + 3) / 2)
return my_tri | tri | def beautiful_tri(start: int, end: int) -> list[int]:
"""Everyone knows Fibonacci sequence, it was studied deeply by mathematicians in
the last couple centuries. However, what people don't know is Tribonacci sequence.
Tribonacci sequence is defined by the recurrence:
tri(1) = 3
tri(n) = 1 + n / 2, if n is even.
tri(n) = tri(n - 1) + tri(n - 2) + tri(n + 1), if n is odd.
For example:
tri(2) = 1 + (2 / 2) = 2
tri(4) = 3
tri(3) = tri(2) + tri(1) + tri(4)
= 2 + 3 + 3 = 8
You are given a non-negative integer number n, you have to a return a list of the
start-th number and end-th number of the Tribonacci sequence that the number is
a multiple of 3.
Examples:
>>> tri(5, 10)
[3]
""" | def beautiful_tri(start: int, end: int) -> list[int]:
"""Everyone knows Fibonacci sequence, it was studied deeply by mathematicians in
the last couple centuries. However, what people don't know is Tribonacci sequence.
Tribonacci sequence is defined by the recurrence:
tri(1) = 3
tri(n) = 1 + n / 2, if n is even.
tri(n) = tri(n - 1) + tri(n - 2) + tri(n + 1), if n is odd.
For example:
tri(2) = 1 + (2 / 2) = 2
tri(4) = 3
tri(3) = tri(2) + tri(1) + tri(4)
= 2 + 3 + 3 = 8
You are given a non-negative integer number n, you have to a return a list of the
start-th number and end-th number of the Tribonacci sequence that the number is
a multiple of 3.
Examples:
>>> tri(5, 10)
[3]
"""
return [int(i) for i in tri(end)[start:] if i % 3 == 0] | beautiful_tri | def check(candidate):
assert candidate(5, 10) == [15, 24, 6]
assert candidate(21, 29) == [12, 168, 195, 15, 255]
assert candidate(33, 49) == [18, 360, 399, 21, 483, 528, 24, 624, 675]
def test_check():
check(beautiful_tri)
test_check() | [
"\ndef",
"\n#",
"\nif",
"\nclass"
] |
|
from typing import List | def digits(n: int) -> int:
"""Given a positive integer n, return the product of the odd digits.
Return 0 if all digits are even.
For example:
>>> digits(1)
1
>>> digits(4)
0
>>> digits(235)
15
""" | def digits(n: int) -> int:
"""Given a positive integer n, return the product of the odd digits.
Return 0 if all digits are even.
For example:
>>> digits(1)
1
>>> digits(4)
0
>>> digits(235)
15
"""
product = 1
odd_count = 0
for digit in str(n):
int_digit = int(digit)
if int_digit % 2 == 1:
product = product * int_digit
odd_count += 1
if odd_count == 0:
return 0
else:
return product | digits | def unique_odd_digits(lst: List[int]) -> int:
"""Given a list of positive integers, return the product of unique odd digits.
For example:
>>> unique_odd_digits([1, 4, 235])
15
>>> unique_odd_digits([123, 456, 789])
945
>>> unique_odd_digits([2, 4, 6, 8, 99])
9
""" | def unique_odd_digits(lst: List[int]) -> int:
"""Given a list of positive integers, return the product of unique odd digits.
For example:
>>> unique_odd_digits([1, 4, 235])
15
>>> unique_odd_digits([123, 456, 789])
945
>>> unique_odd_digits([2, 4, 6, 8, 99])
9
"""
concat = ''
for num in lst:
concat += str(num)
unique = set(concat)
return digits(int(''.join(unique))) | unique_odd_digits | def check(candidate):
assert candidate([0, 1, 2, 3, 4, 5]) == 15
assert candidate([22, 44, 66, 88]) == 0
assert candidate([1325, 540, 938]) == 135
def test_check():
check(unique_odd_digits)
test_check() | [
"\ndef",
"\n#",
"\nif",
"\nclass"
] |
from typing import List | def sum_squares(lst: List[float]) -> int:
"""You are given a list of numbers.
You need to return the sum of squared numbers in the given list,
round each element in the list to the upper int(Ceiling) first.
Examples:
>>> lst([1.0, 2.0, 3.0])
14
>>> lst([1.0, 4.0, 9.0])
98
>>> lst([1.0, 3.0, 5.0, 7.0])
84
>>> lst([1.4, 4.2, 0.0])
29
>>> lst([-2.4, 1.0, 1.0])
6
""" | def sum_squares(lst: List[float]) -> int:
"""You are given a list of numbers.
You need to return the sum of squared numbers in the given list,
round each element in the list to the upper int(Ceiling) first.
Examples:
>>> lst([1.0, 2.0, 3.0])
14
>>> lst([1.0, 4.0, 9.0])
98
>>> lst([1.0, 3.0, 5.0, 7.0])
84
>>> lst([1.4, 4.2, 0.0])
29
>>> lst([-2.4, 1.0, 1.0])
6
"""
import math
squared = 0
for i in lst:
squared += math.ceil(i) ** 2
return squared | sum_squares | def diff_ceil_floor_sum_squares(lst: List[float]) -> int:
"""You are given a list of numbers.
You need to return the absolute difference between the sum of squared numbers in the given list,
round each element in the list to the upper int(Ceiling) first,
and the sum of squared numbers in the given list,
round each element in the list to the lower int(Floor) first.
Examples:
>>> lst([1.0, 2.0, 3.0])
0
>>> lst([1.4, 4.2, 0.0])
12
>>> lst([-2.4, 1.0, 1.0])
5
""" | def diff_ceil_floor_sum_squares(lst: List[float]) -> int:
"""You are given a list of numbers.
You need to return the absolute difference between the sum of squared numbers in the given list,
round each element in the list to the upper int(Ceiling) first,
and the sum of squared numbers in the given list,
round each element in the list to the lower int(Floor) first.
Examples:
>>> lst([1.0, 2.0, 3.0])
0
>>> lst([1.4, 4.2, 0.0])
12
>>> lst([-2.4, 1.0, 1.0])
5
"""
return abs(sum_squares(lst) - sum_squares([-i for i in lst])) | diff_ceil_floor_sum_squares | def check(candidate):
assert candidate([-3.1, 2.5, 7.9]) == 13
assert candidate([0.5, -0.5, 3.0, -2.0]) == 0
assert candidate([-3.2, -2.8, -1.6, 0.7, 1.5, 2.8]) == 6
def test_check():
check(diff_ceil_floor_sum_squares)
test_check() | [
"\ndef",
"\n#",
"\nif",
"\nclass"
] |
def check_if_last_char_is_a_letter(txt: str) -> bool:
"""
Create a function that returns True if the last character
of a given string is an alphabetical character and is not
a part of a word, and False otherwise.
Note: "word" is a group of characters separated by space.
Examples:
>>> check_if_last_char_is_a_letter('apple pie')
False
>>> check_if_last_char_is_a_letter('apple pi e')
True
>>> check_if_last_char_is_a_letter('apple pi e ')
False
>>> check_if_last_char_is_a_letter('')
False
""" | def check_if_last_char_is_a_letter(txt: str) -> bool:
"""
Create a function that returns True if the last character
of a given string is an alphabetical character and is not
a part of a word, and False otherwise.
Note: "word" is a group of characters separated by space.
Examples:
>>> check_if_last_char_is_a_letter('apple pie')
False
>>> check_if_last_char_is_a_letter('apple pi e')
True
>>> check_if_last_char_is_a_letter('apple pi e ')
False
>>> check_if_last_char_is_a_letter('')
False
"""
check = txt.split(' ')[-1]
return True if len(check) == 1 and 97 <= ord(check.lower()) <= 122 else False | check_if_last_char_is_a_letter | def check_if_first_char_is_a_letter(txt: str) -> bool:
"""
Create a function that returns True if the first character
of a given string is an alphabetical character and is not
a part of a word, and False otherwise.
Note: "word" is a group of characters separated by space.
Examples:
>>> check_if_first_char_is_a_letter('apple pie')
False
>>> check_if_first_char_is_a_letter('a pple pie')
True
>>> check_if_first_char_is_a_letter(' a pple pie')
False
>>> check_if_first_char_is_a_letter('')
False
""" | def check_if_first_char_is_a_letter(txt: str) -> bool:
"""
Create a function that returns True if the first character
of a given string is an alphabetical character and is not
a part of a word, and False otherwise.
Note: "word" is a group of characters separated by space.
Examples:
>>> check_if_first_char_is_a_letter('apple pie')
False
>>> check_if_first_char_is_a_letter('a pple pie')
True
>>> check_if_first_char_is_a_letter(' a pple pie')
False
>>> check_if_first_char_is_a_letter('')
False
"""
return check_if_last_char_is_a_letter(txt[::-1]) | check_if_first_char_is_a_letter | def check(candidate):
assert candidate('a boat is on the river') is True
assert candidate(' over the rainbow') is False
assert candidate('life is good') is False
def test_check():
check(check_if_first_char_is_a_letter)
test_check() | [
"\ndef",
"\n#",
"\nif",
"\nclass"
] |
|
from typing import List | def can_arrange(arr: List[int]) -> int:
"""Create a function which returns the largest index of an element which
is not greater than or equal to the element immediately preceding it. If
no such element exists then return -1. The given array will not contain
duplicate values.
Examples:
>>> can_arrange([1, 2, 4, 3, 5])
3
>>> can_arrange([1, 2, 3])
-1
""" | def can_arrange(arr: List[int]) -> int:
"""Create a function which returns the largest index of an element which
is not greater than or equal to the element immediately preceding it. If
no such element exists then return -1. The given array will not contain
duplicate values.
Examples:
>>> can_arrange([1, 2, 4, 3, 5])
3
>>> can_arrange([1, 2, 3])
-1
"""
ind = -1
i = 1
while i < len(arr):
if arr[i] < arr[i - 1]:
ind = i
i += 1
return ind | can_arrange | def is_ordered(arr: List[int]) -> bool:
"""Create a function which returns True if the given array is sorted in
either ascending or descending order, otherwise return False.
Examples:
>>> is_ordered([1, 2, 4, 3, 5])
False
>>> is_ordered([1, 2, 3])
True
>>> is_ordered([3, 2, 1])
True
""" | def is_ordered(arr: List[int]) -> bool:
"""Create a function which returns True if the given array is sorted in
either ascending or descending order, otherwise return False.
Examples:
>>> is_ordered([1, 2, 4, 3, 5])
False
>>> is_ordered([1, 2, 3])
True
>>> is_ordered([3, 2, 1])
True
"""
return can_arrange(arr) == -1 or can_arrange(arr[::-1]) == -1 | is_ordered | def check(candidate):
assert candidate([6, 5, 4, 3, 2, 1]) is True
assert candidate([3, 5, 4, 2, 7, 9]) is False
assert candidate([-1, -2, -3, -5]) is True
def test_check():
check(is_ordered)
test_check() | [
"\ndef",
"\n#",
"\nif",
"\nclass"
] |
from typing import List, Optional, Tuple | def largest_smallest_integers(lst: List[int]) -> Tuple[Optional[int], Optional[int]]:
"""
Create a function that returns a tuple (a, b), where 'a' is
the largest of negative integers, and 'b' is the smallest
of positive integers in a list.
If there is no negative or positive integers, return them as None.
Examples:
>>> largest_smallest_integers([2, 4, 1, 3, 5, 7])
(None, 1)
>>> largest_smallest_integers([])
(None, None)
>>> largest_smallest_integers([0])
(None, None)
""" | def largest_smallest_integers(lst: List[int]) -> Tuple[Optional[int], Optional[int]]:
"""
Create a function that returns a tuple (a, b), where 'a' is
the largest of negative integers, and 'b' is the smallest
of positive integers in a list.
If there is no negative or positive integers, return them as None.
Examples:
>>> largest_smallest_integers([2, 4, 1, 3, 5, 7])
(None, 1)
>>> largest_smallest_integers([])
(None, None)
>>> largest_smallest_integers([0])
(None, None)
"""
smallest = list(filter(lambda x: x < 0, lst))
largest = list(filter(lambda x: x > 0, lst))
return (max(smallest) if smallest else None, min(largest) if largest else None) | largest_smallest_integers | def smallest_interval_including_zero(lst: List[int]) -> int:
"""
Create a function that returns the length of the smallest interval that includes zero.
If there is no such interval, return 0.
Examples:
>>> smallest_interval_including_zero([2, 4, 1, 3, 5, 7])
0
>>> smallest_interval_including_zero([0])
0
>>> smallest_interval_including_zero([-5, -3, 1, 2, 4])
4
""" | def smallest_interval_including_zero(lst: List[int]) -> int:
"""
Create a function that returns the length of the smallest interval that includes zero.
If there is no such interval, return 0.
Examples:
>>> smallest_interval_including_zero([2, 4, 1, 3, 5, 7])
0
>>> smallest_interval_including_zero([0])
0
>>> smallest_interval_including_zero([-5, -3, 1, 2, 4])
4
"""
(start, end) = largest_smallest_integers(lst)
if start is None or end is None:
return 0
return end - start | smallest_interval_including_zero | def check(candidate):
assert candidate([-2, 0, 1, 2, 3]) == 3
assert candidate([0, 1, 2, 3]) == 0
assert candidate([-5, -4, -3, -2, -1]) == 0
def test_check():
check(smallest_interval_including_zero)
test_check() | [
"\ndef",
"\n#",
"\nif",
"\nclass"
] |
from itertools import combinations
from typing import List, Union | def compare_one(a: Union[int, float, str], b: Union[int, float, str]) -> Union[int, float, str, None]:
"""
Create a function that takes integers, floats, or strings representing
real numbers, and returns the larger variable in its given variable type.
Return None if the values are equal.
Note: If a real number is represented as a string, the floating point might be . or ,
>>> compare_one(1, 2.5)
2.5
>>> compare_one(1, '2,3')
'2,3'
>>> compare_one('5,1', '6')
'6'
>>> compare_one('1', 1)
None
""" | def compare_one(a: Union[int, float, str], b: Union[int, float, str]) -> Union[int, float, str, None]:
"""
Create a function that takes integers, floats, or strings representing
real numbers, and returns the larger variable in its given variable type.
Return None if the values are equal.
Note: If a real number is represented as a string, the floating point might be . or ,
>>> compare_one(1, 2.5)
2.5
>>> compare_one(1, '2,3')
'2,3'
>>> compare_one('5,1', '6')
'6'
>>> compare_one('1', 1)
None
"""
(temp_a, temp_b) = (a, b)
if isinstance(temp_a, str):
temp_a = temp_a.replace(',', '.')
if isinstance(temp_b, str):
temp_b = temp_b.replace(',', '.')
if float(temp_a) == float(temp_b):
return None
return a if float(temp_a) > float(temp_b) else b | compare_one | def biggest(lst: List[Union[int, float, str]]) -> Union[int, float, str, None]:
"""
Create a function that takes a list of integers, floats, or strings representing
real numbers, and returns the non-duplicate largest variable in its given variable type.
Return None if the largest value is duplicated.
Note: If a real number is represented as a string, the floating point might be . or ,
>>> biggest([1, 2.5, '2,3'])
2.5
>>> biggest(['1', 1])
None
>>> biggest(['5,1', '-6'])
'5,1'
""" | def biggest(lst: List[Union[int, float, str]]) -> Union[int, float, str, None]:
"""
Create a function that takes a list of integers, floats, or strings representing
real numbers, and returns the non-duplicate largest variable in its given variable type.
Return None if the largest value is duplicated.
Note: If a real number is represented as a string, the floating point might be . or ,
>>> biggest([1, 2.5, '2,3'])
2.5
>>> biggest(['1', 1])
None
>>> biggest(['5,1', '-6'])
'5,1'
"""
bigger = [compare_one(a, b) for (a, b) in combinations(lst, 2)]
bigger = [elem for elem in bigger if elem is not None]
if not bigger:
return None
return max(bigger) | biggest | def check(candidate):
assert candidate([1, 1, 1, 1, 1]) is None
assert candidate(['8,4', 8.1, '-8,3', 8.2]) == '8,4'
assert candidate([10, 10, 8, 9, 6]) == 10
def test_check():
check(biggest)
test_check() | [
"\ndef",
"\n#",
"\nif",
"\nclass"
] |
from typing import List | def is_equal_to_sum_even(n: int) -> bool:
"""Evaluate whether the given number n can be written as the sum of exactly 4 positive even numbers
Example
>>> is_equal_to_sum_even(4)
False
>>> is_equal_to_sum_even(6)
False
>>> is_equal_to_sum_even(8)
True
""" | def is_equal_to_sum_even(n: int) -> bool:
"""Evaluate whether the given number n can be written as the sum of exactly 4 positive even numbers
Example
>>> is_equal_to_sum_even(4)
False
>>> is_equal_to_sum_even(6)
False
>>> is_equal_to_sum_even(8)
True
"""
return n % 2 == 0 and n >= 8 | is_equal_to_sum_even | def num_test_subjects(lst: List[int]) -> int:
"""In your country, people are obligated to take a inspection test every 2 years
after they turn 8.
You are given a list of ages of people in your country. Return the number of
people who are required to take the test in the next year.
Example
>>> num_test_subjects([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
2
>>> num_test_subjects([30, 42, 27, 21, 8, 1])
2
>>> num_test_subjects([7, 3, 5, 6, 8, 9])
2
""" | def num_test_subjects(lst: List[int]) -> int:
"""In your country, people are obligated to take a inspection test every 2 years
after they turn 8.
You are given a list of ages of people in your country. Return the number of
people who are required to take the test in the next year.
Example
>>> num_test_subjects([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
2
>>> num_test_subjects([30, 42, 27, 21, 8, 1])
2
>>> num_test_subjects([7, 3, 5, 6, 8, 9])
2
"""
return sum([is_equal_to_sum_even(x + 1) for x in lst]) | num_test_subjects | def check(candidate):
assert candidate([27, 28, 29, 30, 31, 32]) == 3
assert candidate([7, 6, 8, 9, 11, 13, 100]) == 4
assert candidate([37, 31, 30, 29, 8, 13, 14, 49, 57]) == 6
def test_check():
check(num_test_subjects)
test_check() | [
"\ndef",
"\n#",
"\nif",
"\nclass"
] |
def special_factorial(n: int) -> int:
"""The Brazilian factorial is defined as:
brazilian_factorial(n) = n! * (n-1)! * (n-2)! * ... * 1!
where n > 0
For example:
>>> special_factorial(4)
288
The function will receive an integer as input and should return the special
factorial of this integer.
""" | def special_factorial(n: int) -> int:
"""The Brazilian factorial is defined as:
brazilian_factorial(n) = n! * (n-1)! * (n-2)! * ... * 1!
where n > 0
For example:
>>> special_factorial(4)
288
The function will receive an integer as input and should return the special
factorial of this integer.
"""
fact_i = 1
special_fact = 1
for i in range(1, n + 1):
fact_i *= i
special_fact *= fact_i
return special_fact | special_factorial | def factorial(n: int) -> int:
"""The factorial of a positive integer n, denoted by n!, is the product of all
positive integers less than or equal to n.
For example:
>>> factorial(4)
24
>>> factorial(1)
1
>>> factorial(5)
120
The function will receive an integer as input and should return the factorial
of this integer.
""" | def factorial(n: int) -> int:
"""The factorial of a positive integer n, denoted by n!, is the product of all
positive integers less than or equal to n.
For example:
>>> factorial(4)
24
>>> factorial(1)
1
>>> factorial(5)
120
The function will receive an integer as input and should return the factorial
of this integer.
"""
fact = special_factorial(n)
for i in range(1, n):
fact //= special_factorial(i)
return fact | factorial | def check(candidate):
assert candidate(7) == 5040
assert candidate(6) == 720
assert candidate(10) == 3628800
def test_check():
check(factorial)
test_check() | [
"\ndef",
"\n#",
"\nif",
"\nclass"
] |
|
def fix_spaces(text: str) -> str:
"""
Given a string text, replace all spaces in it with underscores,
and if a string has more than 2 consecutive spaces,
then replace all consecutive spaces with -
>>> fix_spaces('Example')
'Example'
>>> fix_spaces('Example 1')
'Example_1'
>>> fix_spaces(' Example 2')
'_Example_2'
>>> fix_spaces(' Example 3')
'_Example-3'
""" | def fix_spaces(text: str) -> str:
"""
Given a string text, replace all spaces in it with underscores,
and if a string has more than 2 consecutive spaces,
then replace all consecutive spaces with -
>>> fix_spaces('Example')
'Example'
>>> fix_spaces('Example 1')
'Example_1'
>>> fix_spaces(' Example 2')
'_Example_2'
>>> fix_spaces(' Example 3')
'_Example-3'
"""
new_text = ''
i = 0
(start, end) = (0, 0)
while i < len(text):
if text[i] == ' ':
end += 1
else:
if end - start > 2:
new_text += '-' + text[i]
elif end - start > 0:
new_text += '_' * (end - start) + text[i]
else:
new_text += text[i]
(start, end) = (i + 1, i + 1)
i += 1
if end - start > 2:
new_text += '-'
elif end - start > 0:
new_text += '_'
return new_text | fix_spaces | def extended_fix_spaces(text: str) -> str:
"""
Given a string text, replace all spaces and tab in it with underscores.
Consider a tab as 4 spaces, and if a string has more than 2 consecutive spaces,
then replace all consecutive spaces with -
>>> extended_fix_spaces('Example')
'Example'
>>> extended_fix_spaces('Example 1')
'Example-1'
>>> extended_fix_spaces(' Example 2')
'-Example_2'
>>> extended_fix_spaces(' Example 3')
'_Example-3'
>>> extended_fix_spaces(' Example 4_')
'_Example-4_'
""" | def extended_fix_spaces(text: str) -> str:
"""
Given a string text, replace all spaces and tab in it with underscores.
Consider a tab as 4 spaces, and if a string has more than 2 consecutive spaces,
then replace all consecutive spaces with -
>>> extended_fix_spaces('Example')
'Example'
>>> extended_fix_spaces('Example 1')
'Example-1'
>>> extended_fix_spaces(' Example 2')
'-Example_2'
>>> extended_fix_spaces(' Example 3')
'_Example-3'
>>> extended_fix_spaces(' Example 4_')
'_Example-4_'
"""
return fix_spaces(text.replace('\t', ' ')) | extended_fix_spaces | def check(candidate):
assert candidate('\tcandidate([9, 2, 4, 3, 8, 9])') == '-candidate([9,_2,_4,_3,_8,_9])'
assert candidate('cool\tand aweesome function!') == 'cool-and_aweesome_function!'
assert candidate('\t\t\t\t') == '-'
def test_check():
check(extended_fix_spaces)
test_check() | [
"\ndef",
"\n#",
"\nif",
"\nclass"
] |
|
def file_name_check(file_name: str) -> str:
"""Create a function which takes a string representing a file's name, and returns
'Yes' if the the file's name is valid, and returns 'No' otherwise.
A file's name is considered to be valid if and only if all the following conditions
are met:
- There should not be more than three digits ('0'-'9') in the file's name.
- The file's name contains exactly one dot '.'
- The substring before the dot should not be empty, and it starts with a letter from
the latin alphapet ('a'-'z' and 'A'-'Z').
- The substring after the dot should be one of these: ['txt', 'exe', 'dll']
Examples:
>>> file_name_check('example.txt')
'Yes'
>>> file_name_check('1example.dll')
'No'
""" | def file_name_check(file_name: str) -> str:
"""Create a function which takes a string representing a file's name, and returns
'Yes' if the the file's name is valid, and returns 'No' otherwise.
A file's name is considered to be valid if and only if all the following conditions
are met:
- There should not be more than three digits ('0'-'9') in the file's name.
- The file's name contains exactly one dot '.'
- The substring before the dot should not be empty, and it starts with a letter from
the latin alphapet ('a'-'z' and 'A'-'Z').
- The substring after the dot should be one of these: ['txt', 'exe', 'dll']
Examples:
>>> file_name_check('example.txt')
'Yes'
>>> file_name_check('1example.dll')
'No'
"""
suf = ['txt', 'exe', 'dll']
lst = file_name.split(sep='.')
if len(lst) != 2:
return 'No'
if not lst[1] in suf:
return 'No'
if len(lst[0]) == 0:
return 'No'
if not lst[0][0].isalpha():
return 'No'
t = len([x for x in lst[0] if x.isdigit()])
if t > 3:
return 'No'
return 'Yes' | file_name_check | def download_link_check(link: str) -> str:
"""Create a function which takes a string representing a link address, and returns
'Yes' if the the link is valid, and returns 'No' otherwise.
A link name is considered to be valid if and only if all the following conditions
are met:
- There should not be more than three digits ('0'-'9') in the file's name.
- The file's name contains exactly one dot '.'
- The substring before the dot should not be empty, and it starts with a letter from
the latin alphapet ('a'-'z' and 'A'-'Z').
- The substring after the dot should be one of these: ['txt', 'exe', 'dll']
- The link should start with 'https://'
Examples:
>>> download_link_check('https://example.txt')
'Yes'
>>> file_name_check('https://1example.dll')
'No'
>>> file_name_check('example.txt')
'No'
""" | def download_link_check(link: str) -> str:
"""Create a function which takes a string representing a link address, and returns
'Yes' if the the link is valid, and returns 'No' otherwise.
A link name is considered to be valid if and only if all the following conditions
are met:
- There should not be more than three digits ('0'-'9') in the file's name.
- The file's name contains exactly one dot '.'
- The substring before the dot should not be empty, and it starts with a letter from
the latin alphapet ('a'-'z' and 'A'-'Z').
- The substring after the dot should be one of these: ['txt', 'exe', 'dll']
- The link should start with 'https://'
Examples:
>>> download_link_check('https://example.txt')
'Yes'
>>> file_name_check('https://1example.dll')
'No'
>>> file_name_check('example.txt')
'No'
"""
if not link.startswith('https://'):
return 'No'
return file_name_check(link[8:]) | download_link_check | def check(candidate):
assert candidate('https://hello-world.dll') == 'Yes'
assert candidate('file://cool010.exe') == 'No'
assert candidate('https://0010110.txt') == 'No'
def test_check():
check(download_link_check)
test_check() | [
"\ndef",
"\n#",
"\nif",
"\nclass"
] |
|
def sum_squares(lst: list[int]) -> int:
""" "
This function will take a list of integers. For all entries in the list, the function shall square the integer entry if its index is a
multiple of 3 and will cube the integer entry if its index is a multiple of 4 and not a multiple of 3. The function will not
change the entries in the list whose indexes are not a multiple of 3 or 4. The function shall then return the sum of all entries.
Examples:
>>> sum_squares([1, 2, 3])
6
>>> sum_squares([])
0
>>> sum_squares([-1, -5, 2, -1, -5])
-126
""" | def sum_squares(lst: list[int]) -> int:
""" "
This function will take a list of integers. For all entries in the list, the function shall square the integer entry if its index is a
multiple of 3 and will cube the integer entry if its index is a multiple of 4 and not a multiple of 3. The function will not
change the entries in the list whose indexes are not a multiple of 3 or 4. The function shall then return the sum of all entries.
Examples:
>>> sum_squares([1, 2, 3])
6
>>> sum_squares([])
0
>>> sum_squares([-1, -5, 2, -1, -5])
-126
"""
result = []
for i in range(len(lst)):
if i % 3 == 0:
result.append(lst[i] ** 2)
elif i % 4 == 0 and i % 3 != 0:
result.append(lst[i] ** 3)
else:
result.append(lst[i])
return sum(result) | sum_squares | def extended_sum_squares(lst: list[int]) -> int:
"""
This function will take a list of integers. For all entries in the list, the
function shall square the integer entry if its index is a multiple of 3 and
will cube the integer entry if its index is a multiple of 4 and not a
multiple of 3 and negate the integer entry if its index is a multiple of 5
and not a multiple of 3 and 4. The function will not change the entries in
the list whose indexes are not a multiple of 3 or 4 or 5. The function shall
then return the sum of all entries.
Examples:
>>> sum_squares([1, 2, 3])
6
>>> sum_squares([])
0
>>> sum_squares([-1, -5, 2, -1, -5, -6])
-120
""" | def extended_sum_squares(lst: list[int]) -> int:
"""
This function will take a list of integers. For all entries in the list, the
function shall square the integer entry if its index is a multiple of 3 and
will cube the integer entry if its index is a multiple of 4 and not a
multiple of 3 and negate the integer entry if its index is a multiple of 5
and not a multiple of 3 and 4. The function will not change the entries in
the list whose indexes are not a multiple of 3 or 4 or 5. The function shall
then return the sum of all entries.
Examples:
>>> sum_squares([1, 2, 3])
6
>>> sum_squares([])
0
>>> sum_squares([-1, -5, 2, -1, -5, -6])
-120
"""
return sum_squares([-x if idx % 5 == 0 and idx % 4 != 0 and (idx % 3 != 0) else x for (idx, x) in enumerate(lst)]) | extended_sum_squares | def check(candidate):
assert candidate([4, 7, 5, 3, 1, 1, 4, 6, 8, 9, 100]) == 552
assert candidate([3, 4, 1, 5, 0, 8, 8, 5]) == 100
assert candidate([2, 3, 5, 7, 11, 13, 17, 19]) == 1687
def test_check():
check(extended_sum_squares)
test_check() | [
"\ndef",
"\n#",
"\nif",
"\nclass"
] |
|
def words_in_sentence(sentence: str) -> str:
"""
You are given a string representing a sentence,
the sentence contains some words separated by a space,
and you have to return a string that contains the words from the original sentence,
whose lengths are prime numbers,
the order of the words in the new string should be the same as the original one.
Example 1:
>>> words_in_sentence('This is a test')
'is'
Example 2:
>>> words_in_sentence('lets go for swimming')
'go for'
Constraints:
* 1 <= len(sentence) <= 100
* sentence contains only letters
""" | def words_in_sentence(sentence: str) -> str:
"""
You are given a string representing a sentence,
the sentence contains some words separated by a space,
and you have to return a string that contains the words from the original sentence,
whose lengths are prime numbers,
the order of the words in the new string should be the same as the original one.
Example 1:
>>> words_in_sentence('This is a test')
'is'
Example 2:
>>> words_in_sentence('lets go for swimming')
'go for'
Constraints:
* 1 <= len(sentence) <= 100
* sentence contains only letters
"""
new_lst = []
for word in sentence.split():
flg = 0
if len(word) == 1:
flg = 1
for i in range(2, len(word)):
if len(word) % i == 0:
flg = 1
if flg == 0 or len(word) == 2:
new_lst.append(word)
return ' '.join(new_lst) | words_in_sentence | def extended_words_in_sentence(sentence: str, sep: str) -> str:
"""
You are given a string representing a sentence,
the sentence contains some words separated by `sep`,
and you have to return a string that contains the words from the original sentence,
whose lengths are prime numbers,
the order of the words in the new string should be the same as the original one.
Example 1:
>>> extended_words_in_sentence('This is a test', ' ')
'is'
Example 2:
>>> extended_words_in_sentence('lets,go,for,swimming', ',')
'go,for'
Constraints:
* 1 <= len(sentence) <= 100
* sentence contains only letters
""" | def extended_words_in_sentence(sentence: str, sep: str) -> str:
"""
You are given a string representing a sentence,
the sentence contains some words separated by `sep`,
and you have to return a string that contains the words from the original sentence,
whose lengths are prime numbers,
the order of the words in the new string should be the same as the original one.
Example 1:
>>> extended_words_in_sentence('This is a test', ' ')
'is'
Example 2:
>>> extended_words_in_sentence('lets,go,for,swimming', ',')
'go,for'
Constraints:
* 1 <= len(sentence) <= 100
* sentence contains only letters
"""
return words_in_sentence(sentence.replace(sep, ' ')).replace(' ', sep) | extended_words_in_sentence | def check(candidate):
assert candidate('apple|delta|for|much|quantity', '|') == 'apple|delta|for'
assert candidate('what-is-your-hobby', '-') == 'is-hobby'
assert candidate('your,task,is,to,support,your,colleague', ',') == 'is,to,support'
def test_check():
check(extended_words_in_sentence)
test_check() | [
"\ndef",
"\n#",
"\nif",
"\nclass"
] |
|
from typing import Optional | def simplify(x: str, n: str) -> bool:
"""Your task is to implement a function that will simplify the expression
x * n. The function returns True if x * n evaluates to a whole number and False
otherwise. Both x and n, are string representation of a fraction, and have the following format,
<numerator>/<denominator> where both numerator and denominator are positive whole numbers.
You can assume that x, and n are valid fractions, and do not have zero as denominator.
>>> simplify('1/5', '5/1')
True
>>> simplify('1/6', '2/1')
False
>>> simplify('7/10', '10/2')
False
""" | def simplify(x: str, n: str) -> bool:
"""Your task is to implement a function that will simplify the expression
x * n. The function returns True if x * n evaluates to a whole number and False
otherwise. Both x and n, are string representation of a fraction, and have the following format,
<numerator>/<denominator> where both numerator and denominator are positive whole numbers.
You can assume that x, and n are valid fractions, and do not have zero as denominator.
>>> simplify('1/5', '5/1')
True
>>> simplify('1/6', '2/1')
False
>>> simplify('7/10', '10/2')
False
"""
(a, b) = x.split('/')
(c, d) = n.split('/')
numerator = int(a) * int(c)
denom = int(b) * int(d)
if numerator / denom == int(numerator / denom):
return True
return False | simplify | def get_simplified_pair(l: list[str]) -> Optional[tuple[str, str]]:
"""Find a pair (a, b) which can be simplified in the given list of fractions.
Simplified means that a * b is a whole number. Both a and b are string representation
of a fraction, and have the following format, <numerator>/<denominator> where both
numerator and denominator are positive whole numbers.
If there is no such pair, return None.
If there is multiple such pair, return the first one.
Example:
>>> get_simplified_pair(['1/5', '5/1', '1/6', '2/1', '7/10', '10/2'])
('1/5', '5/1')
>>> get_simplified_pair(['1/6', '2/1', '7/10', '10/2'])
('2/1', '10/2')
""" | def get_simplified_pair(l: list[str]) -> Optional[tuple[str, str]]:
"""Find a pair (a, b) which can be simplified in the given list of fractions.
Simplified means that a * b is a whole number. Both a and b are string representation
of a fraction, and have the following format, <numerator>/<denominator> where both
numerator and denominator are positive whole numbers.
If there is no such pair, return None.
If there is multiple such pair, return the first one.
Example:
>>> get_simplified_pair(['1/5', '5/1', '1/6', '2/1', '7/10', '10/2'])
('1/5', '5/1')
>>> get_simplified_pair(['1/6', '2/1', '7/10', '10/2'])
('2/1', '10/2')
"""
for i in range(len(l)):
for j in range(i + 1, len(l)):
if simplify(l[i], l[j]):
return (l[i], l[j])
return None | get_simplified_pair | def check(candidate):
assert candidate(['3/5', '3/7', '9/3', '7/2']) is None
assert candidate(['4/9', '18/1', '7/3']) == ('4/9', '18/1')
assert candidate(['11/13', '7/3', '18/14', '4/6']) == ('7/3', '18/14')
def test_check():
check(get_simplified_pair)
test_check() | [
"\ndef",
"\n#",
"\nif",
"\nclass"
] |
def order_by_points(nums: list[int]) -> list[int]:
"""
Write a function which sorts the given list of integers
in ascending order according to the sum of their digits.
Note: if there are several items with similar sum of their digits,
order them based on their index in original list.
For example:
>>> order_by_points([1, 11, -1, -11, -12])
[-1, -11, 1, -12, 11]
>>> order_by_points([])
[]
""" | def order_by_points(nums: list[int]) -> list[int]:
"""
Write a function which sorts the given list of integers
in ascending order according to the sum of their digits.
Note: if there are several items with similar sum of their digits,
order them based on their index in original list.
For example:
>>> order_by_points([1, 11, -1, -11, -12])
[-1, -11, 1, -12, 11]
>>> order_by_points([])
[]
"""
def digits_sum(n):
neg = 1
if n < 0:
(n, neg) = (-1 * n, -1)
n = [int(i) for i in str(n)]
n[0] = n[0] * neg
return sum(n)
return sorted(nums, key=digits_sum) | order_by_points | def positive_order_by_points(nums: list[int]) -> list[int]:
"""Write a function which sorts the integers in the given list
that is greater than zero.
Note: if there are several items with similar sum of their digits,
order them based on their index in original list.
For example:
>>> positive_order_by_points([1, 11, -1, -11, -12])
[1, 11]
>>> positive_order_by_points([])
[]
""" | def positive_order_by_points(nums: list[int]) -> list[int]:
"""Write a function which sorts the integers in the given list
that is greater than zero.
Note: if there are several items with similar sum of their digits,
order them based on their index in original list.
For example:
>>> positive_order_by_points([1, 11, -1, -11, -12])
[1, 11]
>>> positive_order_by_points([])
[]
"""
return order_by_points([num for num in nums if num > 0]) | positive_order_by_points | def check(candidate):
assert candidate([302, 444, 97, 92, 114]) == [302, 114, 92, 444, 97]
assert candidate([4932, -30585, -392828, 1128]) == [1128, 4932]
assert candidate([85, -7, 877, 344]) == [344, 85, 877]
def test_check():
check(positive_order_by_points)
test_check() | [
"\ndef",
"\n#",
"\nif",
"\nclass"
] |
|
def specialFilter(nums: list[int]) -> int:
"""Write a function that takes an array of numbers as input and returns
the number of elements in the array that are greater than 10 and both
first and last digits of a number are odd (1, 3, 5, 7, 9).
For example:
>>> specialFilter([15, -73, 14, -15])
1
>>> specialFilter([33, -2, -3, 45, 21, 109])
2
""" | def specialFilter(nums: list[int]) -> int:
"""Write a function that takes an array of numbers as input and returns
the number of elements in the array that are greater than 10 and both
first and last digits of a number are odd (1, 3, 5, 7, 9).
For example:
>>> specialFilter([15, -73, 14, -15])
1
>>> specialFilter([33, -2, -3, 45, 21, 109])
2
"""
count = 0
for num in nums:
if num > 10:
odd_digits = (1, 3, 5, 7, 9)
number_as_string = str(num)
if int(number_as_string[0]) in odd_digits and int(number_as_string[-1]) in odd_digits:
count += 1
return count | specialFilter | def extended_special_filter(nums: list[int]) -> int:
"""Write a function that takes an array of numbers as input and returns
the number of elements in the array that are greater than 10 and both
first digits of a number are odd (1, 3, 5, 7, 9) and last digits of a number is even.
For example:
>>> specialFilter([15, -73, 14, -15])
1
>>> specialFilter([33, -2, -3, 45, 21, 109])
0
""" | def extended_special_filter(nums: list[int]) -> int:
"""Write a function that takes an array of numbers as input and returns
the number of elements in the array that are greater than 10 and both
first digits of a number are odd (1, 3, 5, 7, 9) and last digits of a number is even.
For example:
>>> specialFilter([15, -73, 14, -15])
1
>>> specialFilter([33, -2, -3, 45, 21, 109])
0
"""
count = 0
for num in nums:
if num > 10:
odd_digits = (1, 3, 5, 7, 9)
even_digits = (2, 4, 6, 8, 0)
number_as_string = str(num)
if int(number_as_string[0]) in odd_digits and int(number_as_string[-1]) in even_digits:
count += 1
return count | extended_special_filter | def check(candidate):
assert candidate([302, 444, 97, 92, 114]) == 3
assert candidate([4932, 30585, 392828, 1128]) == 2
assert candidate([66485, 9327, 88757, 344]) == 1
def test_check():
check(extended_special_filter)
test_check() | [
"\ndef",
"\n#",
"\nif",
"\nclass"
] |
|
def get_max_triples(n: int) -> int:
"""
You are given a positive integer n. You have to create an integer array a of length n.
For each i (1 ≤ i ≤ n), the value of a[i] = i * i - i + 1.
Return the number of triples (a[i], a[j], a[k]) of a where i < j < k,
and a[i] + a[j] + a[k] is a multiple of 3.
Example :
>>> get_max_triples(5)
1
Explanation:
a = [1, 3, 7, 13, 21]
The only valid triple is (1, 7, 13).
""" | def get_max_triples(n: int) -> int:
"""
You are given a positive integer n. You have to create an integer array a of length n.
For each i (1 ≤ i ≤ n), the value of a[i] = i * i - i + 1.
Return the number of triples (a[i], a[j], a[k]) of a where i < j < k,
and a[i] + a[j] + a[k] is a multiple of 3.
Example :
>>> get_max_triples(5)
1
Explanation:
a = [1, 3, 7, 13, 21]
The only valid triple is (1, 7, 13).
"""
A = [i * i - i + 1 for i in range(1, n + 1)]
ans = []
for i in range(n):
for j in range(i + 1, n):
for k in range(j + 1, n):
if (A[i] + A[j] + A[k]) % 3 == 0:
ans += [(A[i], A[j], A[k])]
return len(ans) | get_max_triples | def get_not_max_triple(n: int) -> int:
"""
You are given a positive integer n. You have to create an integer array a of length n.
For each i (1 ≤ i ≤ n), the value of a[i] = i * i - i + 1.
Return the number of triples (a[i], a[j], a[k]) of a where i < j < k,
and a[i] + a[j] + a[k] is not a multiple of 3.
Assume that n >= 3.
Example :
>>> get_not_max_triples(5)
9
""" | def get_not_max_triple(n: int) -> int:
"""
You are given a positive integer n. You have to create an integer array a of length n.
For each i (1 ≤ i ≤ n), the value of a[i] = i * i - i + 1.
Return the number of triples (a[i], a[j], a[k]) of a where i < j < k,
and a[i] + a[j] + a[k] is not a multiple of 3.
Assume that n >= 3.
Example :
>>> get_not_max_triples(5)
9
"""
return n * (n - 1) * (n - 2) // 6 - get_max_triples(n) | get_not_max_triple | def check(candidate):
assert candidate(8) == 45
assert candidate(13) == 198
assert candidate(16) == 385
def test_check():
check(get_not_max_triple)
test_check() | [
"\ndef",
"\n#",
"\nif",
"\nclass"
] |
|
from typing import Tuple | def bf(planet1: str, planet2: str) -> Tuple[str, ...]:
"""
There are eight planets in our solar system: the closerst to the Sun
is Mercury, the next one is Venus, then Earth, Mars, Jupiter, Saturn,
Uranus, Neptune.
Write a function that takes two planet names as strings planet1 and planet2.
The function should return a tuple containing all planets whose orbits are
located between the orbit of planet1 and the orbit of planet2, sorted by
the proximity to the sun.
The function should return an empty tuple if planet1 or planet2
are not correct planet names.
Examples
>>> bf('Jupiter', 'Neptune')
('Saturn', 'Uranus')
>>> bf('Earth', 'Mercury')
'Venus'
>>> bf('Mercury', 'Uranus')
('Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn')
""" | def bf(planet1: str, planet2: str) -> Tuple[str, ...]:
"""
There are eight planets in our solar system: the closerst to the Sun
is Mercury, the next one is Venus, then Earth, Mars, Jupiter, Saturn,
Uranus, Neptune.
Write a function that takes two planet names as strings planet1 and planet2.
The function should return a tuple containing all planets whose orbits are
located between the orbit of planet1 and the orbit of planet2, sorted by
the proximity to the sun.
The function should return an empty tuple if planet1 or planet2
are not correct planet names.
Examples
>>> bf('Jupiter', 'Neptune')
('Saturn', 'Uranus')
>>> bf('Earth', 'Mercury')
'Venus'
>>> bf('Mercury', 'Uranus')
('Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn')
"""
planet_names = ('Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune')
if planet1 not in planet_names or planet2 not in planet_names or planet1 == planet2:
return ()
planet1_index = planet_names.index(planet1)
planet2_index = planet_names.index(planet2)
if planet1_index < planet2_index:
return planet_names[planet1_index + 1:planet2_index]
else:
return planet_names[planet2_index + 1:planet1_index] | bf | def living_area(planet1: str, planet2: str) -> bool:
"""
There are eight planets in our solar system: the closerst to the Sun
is Mercury, the next one is Venus, then Earth, Mars, Jupiter, Saturn,
Uranus, Neptune.
Among this planets, Earth is the only planet that can live human.
Your task is to check whether there is a planet that can live human
between planet1 and planet2 exclusively.
Return true if there is a planet that can live human between planet1 and planet2.
Examples:
>>> living_area('Jupiter', 'Neptune')
False
>>> living_area('Earth', 'Mercury')
False
>>> living_area('Mercury', 'Uranus')
True
""" | def living_area(planet1: str, planet2: str) -> bool:
"""
There are eight planets in our solar system: the closerst to the Sun
is Mercury, the next one is Venus, then Earth, Mars, Jupiter, Saturn,
Uranus, Neptune.
Among this planets, Earth is the only planet that can live human.
Your task is to check whether there is a planet that can live human
between planet1 and planet2 exclusively.
Return true if there is a planet that can live human between planet1 and planet2.
Examples:
>>> living_area('Jupiter', 'Neptune')
False
>>> living_area('Earth', 'Mercury')
False
>>> living_area('Mercury', 'Uranus')
True
"""
return 'Earth' in bf(planet1, planet2) | living_area | def check(candidate):
assert candidate('Venus', 'Jupiter') is True
assert candidate('Uranus', 'Mars') is False
assert candidate('Mars', 'Mercury') is True
def test_check():
check(living_area)
test_check() | [
"\ndef",
"\n#",
"\nif",
"\nclass"
] |
from typing import List | def sorted_list_sum(lst: List[str]) -> List[str]:
"""Write a function that accepts a list of strings as a parameter,
deletes the strings that have odd lengths from it,
and returns the resulted list with a sorted order,
The list is always a list of strings and never an array of numbers,
and it may contain duplicates.
The order of the list should be ascending by length of each word, and you
should return the list sorted by that rule.
If two words have the same length, sort the list alphabetically.
The function should return a list of strings in sorted order.
You may assume that all words will have the same length.
For example:
>>> list_sort(['aa', 'a', 'aaa'])
['aa']
>>> list_sort(['ab', 'a', 'aaa', 'cd'])
['ab', 'cd']
""" | def sorted_list_sum(lst: List[str]) -> List[str]:
"""Write a function that accepts a list of strings as a parameter,
deletes the strings that have odd lengths from it,
and returns the resulted list with a sorted order,
The list is always a list of strings and never an array of numbers,
and it may contain duplicates.
The order of the list should be ascending by length of each word, and you
should return the list sorted by that rule.
If two words have the same length, sort the list alphabetically.
The function should return a list of strings in sorted order.
You may assume that all words will have the same length.
For example:
>>> list_sort(['aa', 'a', 'aaa'])
['aa']
>>> list_sort(['ab', 'a', 'aaa', 'cd'])
['ab', 'cd']
"""
lst.sort()
new_lst = []
for i in lst:
if len(i) % 2 == 0:
new_lst.append(i)
return sorted(new_lst, key=len) | sorted_list_sum | def extract_even_words(text: str) -> str:
"""Write a function that accepts a string as a parameter, and a string
is consisted of words separated by spaces, deletes the words that have
odd lengths from it, and returns the resulted string with a sorted order,
The order of the words should be ascending by length of each word, and you
should return the string sorted by that rule.
IF two words have the same length, sort the string alphabetically.
For example:
>>> extract_odd_words('aa a aaa')
'aa'
>>> extract_odd_words('ab a aaa cd')
'ab cd'
""" | def extract_even_words(text: str) -> str:
"""Write a function that accepts a string as a parameter, and a string
is consisted of words separated by spaces, deletes the words that have
odd lengths from it, and returns the resulted string with a sorted order,
The order of the words should be ascending by length of each word, and you
should return the string sorted by that rule.
IF two words have the same length, sort the string alphabetically.
For example:
>>> extract_odd_words('aa a aaa')
'aa'
>>> extract_odd_words('ab a aaa cd')
'ab cd'
"""
return ' '.join(sorted_list_sum(text.split())) | extract_even_words | def check(candidate):
assert candidate('apple sand pear black cheeze') == 'pear sand cheeze'
assert candidate('answer python analysis task mirror') == 'task answer mirror python analysis'
assert candidate('hand monitor cream tissue water') == 'hand tissue'
def test_check():
check(extract_even_words)
test_check() | [
"\ndef",
"\n#",
"\nif",
"\nclass"
] |
def x_or_y(n: int, x: int, y: int) -> int:
"""A simple program which should return the value of x if n is
a prime number and should return the value of y otherwise.
Examples:
>>> x_or_y(7, 34, 12)
34
>>> x_or_y(15, 8, 5)
5
""" | def x_or_y(n: int, x: int, y: int) -> int:
"""A simple program which should return the value of x if n is
a prime number and should return the value of y otherwise.
Examples:
>>> x_or_y(7, 34, 12)
34
>>> x_or_y(15, 8, 5)
5
"""
if n == 1:
return y
for i in range(2, n):
if n % i == 0:
return y
else:
return x | x_or_y | def list_x_or_y(ns: list[int], xs: list[int], ys: list[int]) -> list[int]:
"""A simple program which should return a list of values of x if the
corresponding value in ns is a prime number and should return the value of y
otherwise.
Examples:
>>> list_x_or_by([7, 15, 21], [34, 8, 3], [12, 5, 7])
[34, 5, 7]
>>> list_x_or_by([1, 2, 3], [34, 8, 3], [12, 5, 7])
[12, 8, 3]
""" | def list_x_or_y(ns: list[int], xs: list[int], ys: list[int]) -> list[int]:
"""A simple program which should return a list of values of x if the
corresponding value in ns is a prime number and should return the value of y
otherwise.
Examples:
>>> list_x_or_by([7, 15, 21], [34, 8, 3], [12, 5, 7])
[34, 5, 7]
>>> list_x_or_by([1, 2, 3], [34, 8, 3], [12, 5, 7])
[12, 8, 3]
"""
return [x_or_y(n, x, y) for (n, x, y) in zip(ns, xs, ys)] | list_x_or_y | def check(candidate):
assert candidate([9, 5, 13, 7, 15, 33], [3, 4, 6, 2, 6, 4], [2, 3, 7, 2, 4, 3]) == [2, 4, 6, 2, 4, 3]
assert candidate([44, 43, 42, 41, 40], [9, 3, 5, 3, 2], [8, 7, 6, 5, 4]) == [8, 3, 6, 3, 4]
assert candidate([95, 97, 45, 39], [11, 4, 38, 2], [10, 1, 4, 9]) == [10, 4, 4, 9]
def test_check():
check(list_x_or_y)
test_check() | [
"\ndef",
"\n#",
"\nif",
"\nclass"
] |
|
def double_the_difference(lst: list[float]) -> int:
"""
Given a list of numbers, return the sum of squares of the numbers
in the list that are odd. Ignore numbers that are negative or not integers.
>>> double_the_difference([1, 3, 2, 0])
10
>>> double_the_difference([-1, -2, 0])
0
>>> double_the_difference([9, -2])
81
>>> double_the_difference([0])
0
If the input list is empty, return 0.
""" | def double_the_difference(lst: list[float]) -> int:
"""
Given a list of numbers, return the sum of squares of the numbers
in the list that are odd. Ignore numbers that are negative or not integers.
>>> double_the_difference([1, 3, 2, 0])
10
>>> double_the_difference([-1, -2, 0])
0
>>> double_the_difference([9, -2])
81
>>> double_the_difference([0])
0
If the input list is empty, return 0.
"""
return sum([i ** 2 for i in lst if i > 0 and i % 2 != 0 and ('.' not in str(i))]) | double_the_difference | def extended_double_the_difference(lst: list[float]) -> int:
"""
Given a list of numbers, return the sum of squares of the numbers
in the list that are odd and the cubic of the number in the list that
are even. Ignore numbers that are negative or not integers.
>>> double_the_difference([1, 3, 2, 0])
18
>>> double_the_difference([-1, -2, 0])
0
>>> double_the_difference([9, -2])
81
>>> double_the_difference([0])
0
If the input list is empty, return 0.
""" | def extended_double_the_difference(lst: list[float]) -> int:
"""
Given a list of numbers, return the sum of squares of the numbers
in the list that are odd and the cubic of the number in the list that
are even. Ignore numbers that are negative or not integers.
>>> double_the_difference([1, 3, 2, 0])
18
>>> double_the_difference([-1, -2, 0])
0
>>> double_the_difference([9, -2])
81
>>> double_the_difference([0])
0
If the input list is empty, return 0.
"""
x = double_the_difference(lst)
x += sum((i ** 3 for i in lst if i > 0 and i % 2 == 0 and ('.' not in str(i))))
return x | extended_double_the_difference | def check(candidate):
assert candidate([-1, 9, -5, 5, 13, 7, 0, 15]) == 549
assert candidate([-5, -2, 7, 2, 1]) == 58
assert candidate([3, 4, 5, 6, 7]) == 363
def test_check():
check(extended_double_the_difference)
test_check() | [
"\ndef",
"\n#",
"\nif",
"\nclass"
] |
|
def compare(game: list[int], guess: list[int]) -> list[int]:
"""I think we all remember that feeling when the result of some long-awaited
event is finally known. The feelings and thoughts you have at that moment are
definitely worth noting down and comparing.
Your task is to determine if a person correctly guessed the results of a number of matches.
You are given two arrays of scores and guesses of equal length, where each index shows a match.
Return an array of the same length denoting how far off each guess was. If they have guessed correctly,
the value is 0, and if not, the value is the absolute difference between the guess and the score.
example:
>>> compare([1, 2, 3, 4, 5, 1], [1, 2, 3, 4, 2, -2])
[0, 0, 0, 0, 3, 3]
>>> compare([0, 5, 0, 0, 0, 4], [4, 1, 1, 0, 0, -2])
[4, 4, 1, 0, 0, 6]
""" | def compare(game: list[int], guess: list[int]) -> list[int]:
"""I think we all remember that feeling when the result of some long-awaited
event is finally known. The feelings and thoughts you have at that moment are
definitely worth noting down and comparing.
Your task is to determine if a person correctly guessed the results of a number of matches.
You are given two arrays of scores and guesses of equal length, where each index shows a match.
Return an array of the same length denoting how far off each guess was. If they have guessed correctly,
the value is 0, and if not, the value is the absolute difference between the guess and the score.
example:
>>> compare([1, 2, 3, 4, 5, 1], [1, 2, 3, 4, 2, -2])
[0, 0, 0, 0, 3, 3]
>>> compare([0, 5, 0, 0, 0, 4], [4, 1, 1, 0, 0, -2])
[4, 4, 1, 0, 0, 6]
"""
return [abs(x - y) for (x, y) in zip(game, guess)] | compare | def who_is_winner(game: list[int], guesses: list[list[int]]) -> int:
"""Return the index of guesses that is the most closely guess the game.
If there is a tie, return the index of the first guess that is the most
closely guess the game.
Example:
>>> who_is_winner([1, 2, 3], [[2, 0, 3], [1, 2, 3]])
1
>>> who_is_winner([1, 2, 3], [[2, 0, 3], [4, 5, 6]])
0
""" | def who_is_winner(game: list[int], guesses: list[list[int]]) -> int:
"""Return the index of guesses that is the most closely guess the game.
If there is a tie, return the index of the first guess that is the most
closely guess the game.
Example:
>>> who_is_winner([1, 2, 3], [[2, 0, 3], [1, 2, 3]])
1
>>> who_is_winner([1, 2, 3], [[2, 0, 3], [4, 5, 6]])
0
"""
return min(range(len(guesses)), key=lambda i: sum(compare(game, guesses[i]))) | who_is_winner | def check(candidate):
assert candidate([3, 9], [[1, 2], [3, 0], [0, 9]]) == 2
assert candidate([3, 3], [[3, 0], [0, 3]]) == 0
assert candidate([4, 2, 8], [[0, 3, 5], [5, 0, 7], [1, 2, 9]]) == 1
def test_check():
check(who_is_winner)
test_check() | [
"\ndef",
"\n#",
"\nif",
"\nclass"
] |
|
def Strongest_Extension(class_name: str, extensions: list[str]) -> str:
"""You will be given the name of a class (a string) and a list of extensions.
The extensions are to be used to load additional classes to the class. The
strength of the extension is as follows: Let CAP be the number of the uppercase
letters in the extension's name, and let SM be the number of lowercase letters
in the extension's name, the strength is given by the fraction CAP - SM.
You should find the strongest extension and return a string in this
format: ClassName.StrongestExtensionName.
If there are two or more extensions with the same strength, you should
choose the one that comes first in the list.
For example, if you are given "Slices" as the class and a list of the
extensions: ['SErviNGSliCes', 'Cheese', 'StuFfed'] then you should
return 'Slices.SErviNGSliCes' since 'SErviNGSliCes' is the strongest extension
(its strength is -1).
Example:
>>> Strongest_Extension('my_class', ['AA', 'Be', 'CC'])
'my_class.AA'
""" | def Strongest_Extension(class_name: str, extensions: list[str]) -> str:
"""You will be given the name of a class (a string) and a list of extensions.
The extensions are to be used to load additional classes to the class. The
strength of the extension is as follows: Let CAP be the number of the uppercase
letters in the extension's name, and let SM be the number of lowercase letters
in the extension's name, the strength is given by the fraction CAP - SM.
You should find the strongest extension and return a string in this
format: ClassName.StrongestExtensionName.
If there are two or more extensions with the same strength, you should
choose the one that comes first in the list.
For example, if you are given "Slices" as the class and a list of the
extensions: ['SErviNGSliCes', 'Cheese', 'StuFfed'] then you should
return 'Slices.SErviNGSliCes' since 'SErviNGSliCes' is the strongest extension
(its strength is -1).
Example:
>>> Strongest_Extension('my_class', ['AA', 'Be', 'CC'])
'my_class.AA'
"""
strong = extensions[0]
my_val = len([x for x in extensions[0] if x.isalpha() and x.isupper()]) - len([x for x in extensions[0] if x.isalpha() and x.islower()])
for s in extensions:
val = len([x for x in s if x.isalpha() and x.isupper()]) - len([x for x in s if x.isalpha() and x.islower()])
if val > my_val:
strong = s
my_val = val
ans = class_name + '.' + strong
return ans | Strongest_Extension | def extended_strongest_extension(extensions: list[str]) -> str:
"""You will be given a list of extensions. These extensions consist of package name and
function name such as `package1.function1`.
The strength of the extension is as follows: Let CAP be the number of the uppercase
letters in the function's name, and let SM be the number of lowercase letters
in the function's name, the strength is given by the fraction CAP - SM.
You should find the strongest functions and return a dictionary which has package name as key
and the strongest extension as value in this format: `package1.function1`.
If there are two or more extensions with the same strength in the same package, you should
choose the one that comes first in the list.
Example:
>>> extended_strongest_extension(['my_class.AA', 'my_class.Be', 'my_class2.Be', 'my_class2.CC'])
{'my_class': 'my_class.AA', 'my_class2': 'my_class2.CC'}
""" | def extended_strongest_extension(extensions: list[str]) -> str:
"""You will be given a list of extensions. These extensions consist of package name and
function name such as `package1.function1`.
The strength of the extension is as follows: Let CAP be the number of the uppercase
letters in the function's name, and let SM be the number of lowercase letters
in the function's name, the strength is given by the fraction CAP - SM.
You should find the strongest functions and return a dictionary which has package name as key
and the strongest extension as value in this format: `package1.function1`.
If there are two or more extensions with the same strength in the same package, you should
choose the one that comes first in the list.
Example:
>>> extended_strongest_extension(['my_class.AA', 'my_class.Be', 'my_class2.Be', 'my_class2.CC'])
{'my_class': 'my_class.AA', 'my_class2': 'my_class2.CC'}
"""
result = {}
for extension in extensions:
(package, function) = extension.split('.')
if package not in result:
result[package] = [function]
else:
result[package].append(function)
for package in result:
result[package] = Strongest_Extension(package, result[package])
return result | extended_strongest_extension | def check(candidate):
assert candidate(['pack1.func1', 'pack1.Func1', 'pack1.FunC1']) == {'pack1': 'pack1.FunC1'}
assert candidate(['math.MIN', 'math.MAX', 'abc.abstractmethod']) == {'math': 'math.MIN', 'abc': 'abc.abstractmethod'}
assert candidate(['mirror.iSNa', 'category.FUNC', 'mirror.IsnA']) == {'mirror': 'mirror.iSNa', 'category': 'category.FUNC'}
def test_check():
check(extended_strongest_extension)
test_check() | [
"\ndef",
"\n#",
"\nif",
"\nclass"
] |
|
def cycpattern_check(a: str, b: str) -> bool:
"""You are given 2 words. You need to return True if the second word or any
of its rotations is a substring in the first word
>>> cycpattern_check('abcd', 'abd')
False
>>> cycpattern_check('hello', 'ell')
True
>>> cycpattern_check('whassup', 'psus')
False
>>> cycpattern_check('abab', 'baa')
True
>>> cycpattern_check('efef', 'eeff')
False
>>> cycpattern_check('himenss', 'simen')
True
""" | def cycpattern_check(a: str, b: str) -> bool:
"""You are given 2 words. You need to return True if the second word or any
of its rotations is a substring in the first word
>>> cycpattern_check('abcd', 'abd')
False
>>> cycpattern_check('hello', 'ell')
True
>>> cycpattern_check('whassup', 'psus')
False
>>> cycpattern_check('abab', 'baa')
True
>>> cycpattern_check('efef', 'eeff')
False
>>> cycpattern_check('himenss', 'simen')
True
"""
l = len(b)
pat = b + b
for i in range(len(a) - l + 1):
for j in range(l + 1):
if a[i:i + l] == pat[j:j + l]:
return True
return False | cycpattern_check | def extended_cycpattern_check(a: str, b: str) -> bool:
"""You are given 2 words. You need to return True if the second word or any
of its rotations is a substring in the first word or any of its rotations
>>> cycpattern_check('abcd', 'abd')
True
>>> cycpattern_check('hello', 'ell')
True
>>> cycpattern_check('whassup', 'psus')
False
>>> cycpattern_check('abab', 'baa')
True
>>> cycpattern_check('efeff', 'eeff')
True
>>> cycpattern_check('himenss', 'simen')
True
""" | def extended_cycpattern_check(a: str, b: str) -> bool:
"""You are given 2 words. You need to return True if the second word or any
of its rotations is a substring in the first word or any of its rotations
>>> cycpattern_check('abcd', 'abd')
True
>>> cycpattern_check('hello', 'ell')
True
>>> cycpattern_check('whassup', 'psus')
False
>>> cycpattern_check('abab', 'baa')
True
>>> cycpattern_check('efeff', 'eeff')
True
>>> cycpattern_check('himenss', 'simen')
True
"""
return any((cycpattern_check(a[i:] + a[:i], b) for i in range(len(a)))) | extended_cycpattern_check | def check(candidate):
assert candidate('oossiie', 'iso') is False
assert candidate('rikkenwhwiejf', 'friwiej') is True
assert candidate('whatemfho', 'howhat') is True
def test_check():
check(extended_cycpattern_check)
test_check() | [
"\ndef",
"\n#",
"\nif",
"\nclass"
] |
|
from typing import Tuple | def even_odd_count(num: int) -> Tuple[int, int]:
"""Given an integer. return a tuple that has the number of even and odd digits respectively.
Example:
>>> even_odd_count(-12)
(1, 1)
>>> even_odd_count(123)
(1, 2)
""" | def even_odd_count(num: int) -> Tuple[int, int]:
"""Given an integer. return a tuple that has the number of even and odd digits respectively.
Example:
>>> even_odd_count(-12)
(1, 1)
>>> even_odd_count(123)
(1, 2)
"""
even_count = 0
odd_count = 0
for i in str(abs(num)):
if int(i) % 2 == 0:
even_count += 1
else:
odd_count += 1
return (even_count, odd_count) | even_odd_count | def balanced_number(num: int) -> bool:
"""Given an integer. return True if the number of even digits and odd digits
are the same.
Example:
>>> balanced_number(1324)
True
>>> balanced_number(9119)
False
""" | def balanced_number(num: int) -> bool:
"""Given an integer. return True if the number of even digits and odd digits
are the same.
Example:
>>> balanced_number(1324)
True
>>> balanced_number(9119)
False
"""
(even_count, odd_count) = even_odd_count(num)
return even_count == odd_count | balanced_number | def check(candidate):
assert candidate(1234) is True
assert candidate(12345) is False
assert candidate(10) is True
def test_check():
check(balanced_number)
test_check() | [
"\ndef",
"\n#",
"\nif",
"\nclass"
] |
def int_to_mini_roman(number: int) -> str:
"""
Given a positive integer, obtain its roman numeral equivalent as a string,
and return it in lowercase.
Restrictions: 1 <= num <= 1000
Examples:
>>> int_to_mini_roman(19)
'xix'
>>> int_to_mini_roman(152)
'clii'
>>> int_to_mini_roman(426)
'cdxxvi'
""" | def int_to_mini_roman(number: int) -> str:
"""
Given a positive integer, obtain its roman numeral equivalent as a string,
and return it in lowercase.
Restrictions: 1 <= num <= 1000
Examples:
>>> int_to_mini_roman(19)
'xix'
>>> int_to_mini_roman(152)
'clii'
>>> int_to_mini_roman(426)
'cdxxvi'
"""
num = [1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900, 1000]
sym = ['I', 'IV', 'V', 'IX', 'X', 'XL', 'L', 'XC', 'C', 'CD', 'D', 'CM', 'M']
i = 12
res = ''
while number:
div = number // num[i]
number %= num[i]
while div:
res += sym[i]
div -= 1
i -= 1
return res.lower() | int_to_mini_roman | def beautiful_roman_number(number: int) -> bool:
"""Check if a given number is a beautiful roman number.
A roman number is beautiful if it is a palindrome and its length is greater than 1.
Restrictions: 1 <= a * b <= 1000
Examples:
>>> beautiful_roman_number(2)
True
>>> beautiful_roman_number(4)
False
>>> beautiful_roman_number(19)
True
""" | def beautiful_roman_number(number: int) -> bool:
"""Check if a given number is a beautiful roman number.
A roman number is beautiful if it is a palindrome and its length is greater than 1.
Restrictions: 1 <= a * b <= 1000
Examples:
>>> beautiful_roman_number(2)
True
>>> beautiful_roman_number(4)
False
>>> beautiful_roman_number(19)
True
"""
x = int_to_mini_roman(number)
return x == x[::-1] and len(x) > 1 | beautiful_roman_number | def check(candidate):
assert candidate(30) is True
assert candidate(190) is True
assert candidate(450) is False
def test_check():
check(beautiful_roman_number)
test_check() | [
"\ndef",
"\n#",
"\nif",
"\nclass"
] |
|
def right_angle_triangle(a: int, b: int, c: int) -> bool:
"""
Given the lengths of the three sides of a triangle. Return True if the three
sides form a right-angled triangle, False otherwise.
A right-angled triangle is a triangle in which one angle is right angle or
90 degree.
Example:
>>> right_angle_triangle(3, 4, 5)
True
>>> right_angle_triangle(1, 2, 3)
False
""" | def right_angle_triangle(a: int, b: int, c: int) -> bool:
"""
Given the lengths of the three sides of a triangle. Return True if the three
sides form a right-angled triangle, False otherwise.
A right-angled triangle is a triangle in which one angle is right angle or
90 degree.
Example:
>>> right_angle_triangle(3, 4, 5)
True
>>> right_angle_triangle(1, 2, 3)
False
"""
return a * a == b * b + c * c or b * b == a * a + c * c or c * c == a * a + b * b | right_angle_triangle | def make_right_angle_triangle(a: int, b: int) -> int:
"""
Given the lengths of two sides of a triangle, return the integer length of
the third side if the three sides form a right-angled triangle, -1 otherwise.
All sides of the triangle could not exceed 1000.
If there is more than one possible value, return the smallest one.
A right-angled triangle is a triangle in which one angle is right angle or
90 degree.
Example:
>>> make_right_angle_triangle(3, 4)
5
>>> make_right_angle_triangle(1, 2)
-1
""" | def make_right_angle_triangle(a: int, b: int) -> int:
"""
Given the lengths of two sides of a triangle, return the integer length of
the third side if the three sides form a right-angled triangle, -1 otherwise.
All sides of the triangle could not exceed 1000.
If there is more than one possible value, return the smallest one.
A right-angled triangle is a triangle in which one angle is right angle or
90 degree.
Example:
>>> make_right_angle_triangle(3, 4)
5
>>> make_right_angle_triangle(1, 2)
-1
"""
if 1 <= a <= 1000 and 1 <= b <= 1000:
for c in range(1, 1000):
if right_angle_triangle(a, b, c):
return c
return -1 | make_right_angle_triangle | def check(candidate):
assert candidate(6, 10) == 8
assert candidate(13, 5) == 12
assert candidate(5, 11) == -1
def test_check():
check(make_right_angle_triangle)
test_check() | [
"\ndef",
"\n#",
"\nif",
"\nclass"
] |
|
def find_max(words: list[str]) -> str:
"""Write a function that accepts a list of strings.
The list contains different words. Return the word with maximum number
of unique characters. If multiple strings have maximum number of unique
characters, return the one which comes first in lexicographical order.
>>> find_max(['name', 'of', 'string'])
'string'
>>> find_max(['name', 'enam', 'game'])
'enam'
>>> find_max(['aaaaaaa', 'bb', 'cc'])
'aaaaaaa'
""" | def find_max(words: list[str]) -> str:
"""Write a function that accepts a list of strings.
The list contains different words. Return the word with maximum number
of unique characters. If multiple strings have maximum number of unique
characters, return the one which comes first in lexicographical order.
>>> find_max(['name', 'of', 'string'])
'string'
>>> find_max(['name', 'enam', 'game'])
'enam'
>>> find_max(['aaaaaaa', 'bb', 'cc'])
'aaaaaaa'
"""
return sorted(words, key=lambda x: (-len(set(x)), x))[0] | find_max | def contain_complicated_words(words: list[str]) -> int:
"""Check if the given list of words contains complicated words.
complicated words means the word contains more than 5 unique characters.
Return the index of the most complicated word in words and -1 if there
doesn't exist complicated word.
If there are multiple the most complicated words, return the index of
the first complicated word in lexicographical order.
>>> contain_complicated_words(['name', 'of', 'string'])
2
>>> contain_complicated_words(['name', 'enam', 'game'])
-1
>>> contain_complicated_words(['aaaaaaa', 'bb', 'cc'])
-1
""" | def contain_complicated_words(words: list[str]) -> int:
"""Check if the given list of words contains complicated words.
complicated words means the word contains more than 5 unique characters.
Return the index of the most complicated word in words and -1 if there
doesn't exist complicated word.
If there are multiple the most complicated words, return the index of
the first complicated word in lexicographical order.
>>> contain_complicated_words(['name', 'of', 'string'])
2
>>> contain_complicated_words(['name', 'enam', 'game'])
-1
>>> contain_complicated_words(['aaaaaaa', 'bb', 'cc'])
-1
"""
word = find_max(words)
if len(set(word)) > 5:
return words.index(word)
else:
return -1 | contain_complicated_words | def check(candidate):
assert candidate(['analysis', 'cheeze', 'accept', 'centered']) == 0
assert candidate(['pee', 'sat', 'erase']) == -1
assert candidate(['eeeeeeee', 'wwwwseeeeew', 'wwwwwzxdef']) == 2
def test_check():
check(contain_complicated_words)
test_check() | [
"\ndef",
"\n#",
"\nif",
"\nclass"
] |
|
def eat(number: int, need: int, remaining: int) -> list[int]:
"""
You're a hungry rabbit, and you already have eaten a certain number of carrots,
but now you need to eat more carrots to complete the day's meals.
you should return an array of [ total number of eaten carrots after your meals,
the number of carrots left after your meals ]
if there are not enough remaining carrots, you will eat all remaining carrots, but will still be hungry.
Example:
>>> eat(5, 6, 10)
[11, 4]
>>> eat(4, 8, 9)
[12, 1]
>>> eat(1, 10, 10)
[11, 0]
>>> eat(2, 11, 5)
[7, 0]
Variables:
@number : integer
the number of carrots that you have eaten.
@need : integer
the number of carrots that you need to eat.
@remaining : integer
the number of remaining carrots thet exist in stock
Constrain:
* 0 <= number <= 1000
* 0 <= need <= 1000
* 0 <= remaining <= 1000
Have fun :)
""" | def eat(number: int, need: int, remaining: int) -> list[int]:
"""
You're a hungry rabbit, and you already have eaten a certain number of carrots,
but now you need to eat more carrots to complete the day's meals.
you should return an array of [ total number of eaten carrots after your meals,
the number of carrots left after your meals ]
if there are not enough remaining carrots, you will eat all remaining carrots, but will still be hungry.
Example:
>>> eat(5, 6, 10)
[11, 4]
>>> eat(4, 8, 9)
[12, 1]
>>> eat(1, 10, 10)
[11, 0]
>>> eat(2, 11, 5)
[7, 0]
Variables:
@number : integer
the number of carrots that you have eaten.
@need : integer
the number of carrots that you need to eat.
@remaining : integer
the number of remaining carrots thet exist in stock
Constrain:
* 0 <= number <= 1000
* 0 <= need <= 1000
* 0 <= remaining <= 1000
Have fun :)
"""
if need <= remaining:
return [number + need, remaining - need]
else:
return [number + remaining, 0] | eat | def eat_days(numbers: list[int], need: int, remaining: int) -> list[int]:
"""
You're a hungry rabbit, and every you already have eaten a certain number
of carrots in your friend's house, but now you need to eat more carrots to
complete the day's meals.
you should return an array of [
total number of eaten carrots after a couple of days,
the number of remaining carrots in a stock after a couple of days ]
if there are not enough remaining carrots, you will eat all remaining carrots,
and sleep in a hunger status. (you will not eat more carrots in the next day)
Example:
>>> eat_week([3, 7, 4, 6, 5, 2, 9], 7, 10)
[50, 0]
Variables:
@numbers:
the number of carrots that you already have eaten in your friend's house during
a couple of days.
@need : integer
the number of carrots that you need to eat during a day.
@remaining : integer
the number of remaining carrots thet exist in stock
Constrain:
* 0 <= the elements in numbers <= 1000
* 0 <= need <= 1000
* 0 <= remaining <= 1000
Have fun :)
""" | def eat_days(numbers: list[int], need: int, remaining: int) -> list[int]:
"""
You're a hungry rabbit, and every you already have eaten a certain number
of carrots in your friend's house, but now you need to eat more carrots to
complete the day's meals.
you should return an array of [
total number of eaten carrots after a couple of days,
the number of remaining carrots in a stock after a couple of days ]
if there are not enough remaining carrots, you will eat all remaining carrots,
and sleep in a hunger status. (you will not eat more carrots in the next day)
Example:
>>> eat_week([3, 7, 4, 6, 5, 2, 9], 7, 10)
[50, 0]
Variables:
@numbers:
the number of carrots that you already have eaten in your friend's house during
a couple of days.
@need : integer
the number of carrots that you need to eat during a day.
@remaining : integer
the number of remaining carrots thet exist in stock
Constrain:
* 0 <= the elements in numbers <= 1000
* 0 <= need <= 1000
* 0 <= remaining <= 1000
Have fun :)
"""
(ans1, ans2) = (0, remaining)
for number in numbers:
(x1, ans2) = eat(number, max(need - number, 0), ans2)
ans1 += x1
return [ans1, ans2] | eat_days | def check(candidate):
assert candidate([3, 5, 4, 5], 5, 10) == [20, 7]
assert candidate([1, 2, 1, 2], 4, 5) == [11, 0]
assert candidate([3, 5], 4, 2) == [9, 1]
def test_check():
check(eat_days)
test_check() | [
"\ndef",
"\n#",
"\nif",
"\nclass"
] |
|
def do_algebra(operator: list[str], operand: list[int]) -> int:
"""
Given two lists operator, and operand. The first list has basic algebra operations, and
the second list is a list of integers. Use the two given lists to build the algebric
expression and return the evaluation of this expression.
The basic algebra operations:
Addition ( + )
Subtraction ( - )
Multiplication ( * )
Floor division ( // )
Exponentiation ( ** )
Example:
operator['+', '*', '-']
array = [2, 3, 4, 5]
result = 2 + 3 * 4 - 5
=> result = 9
Note:
The length of operator list is equal to the length of operand list minus one.
Operand is a list of of non-negative integers.
Operator list has at least one operator, and operand list has at least two operands.
""" | def do_algebra(operator: list[str], operand: list[int]) -> int:
"""
Given two lists operator, and operand. The first list has basic algebra operations, and
the second list is a list of integers. Use the two given lists to build the algebric
expression and return the evaluation of this expression.
The basic algebra operations:
Addition ( + )
Subtraction ( - )
Multiplication ( * )
Floor division ( // )
Exponentiation ( ** )
Example:
operator['+', '*', '-']
array = [2, 3, 4, 5]
result = 2 + 3 * 4 - 5
=> result = 9
Note:
The length of operator list is equal to the length of operand list minus one.
Operand is a list of of non-negative integers.
Operator list has at least one operator, and operand list has at least two operands.
"""
expression = str(operand[0])
for (oprt, oprn) in zip(operator, operand[1:]):
expression += oprt + str(oprn)
return eval(expression) | do_algebra | def do_algebra_sequentially(operator: list, operand: list) -> list[int]:
"""
Given two lists operator, and operand. The first list has basic algebra operations, and
the second list is a list of integers. Use the two given lists to build the algebric
expression and return the evaluation of this expression. Note that the operator is applied
sequentially from left to right.
The basic algebra operations:
Addition ( + )
Subtraction ( - )
Multiplication ( * )
Floor division ( // )
Exponentiation ( ** )
Example:
operator['+', '*', '-']
array = [2, 3, 4, 5]
result = (((2 + 3) * 4) - 5)
=> result = 15
Note:
The length of operator list is equal to the length of operand list minus one.
Operand is a list of of non-negative integers.
Operator list has at least one operator, and operand list has at least two operands.
""" | def do_algebra_sequentially(operator: list, operand: list) -> list[int]:
"""
Given two lists operator, and operand. The first list has basic algebra operations, and
the second list is a list of integers. Use the two given lists to build the algebric
expression and return the evaluation of this expression. Note that the operator is applied
sequentially from left to right.
The basic algebra operations:
Addition ( + )
Subtraction ( - )
Multiplication ( * )
Floor division ( // )
Exponentiation ( ** )
Example:
operator['+', '*', '-']
array = [2, 3, 4, 5]
result = (((2 + 3) * 4) - 5)
=> result = 15
Note:
The length of operator list is equal to the length of operand list minus one.
Operand is a list of of non-negative integers.
Operator list has at least one operator, and operand list has at least two operands.
"""
val = operand[0]
for (op, val2) in zip(operator, operand[1:]):
val = do_algebra([op], [val, val2])
return val | do_algebra_sequentially | def check(candidate):
assert candidate(['-', '*', '+'], [3, 1, 4, 5]) == 13
assert candidate(['-', '-', '//', '+'], [9, 3, 2, 3, 5]) == 6
assert candidate(['*', '+'], [3, 5, 7]) == 22
def test_check():
check(do_algebra_sequentially)
test_check() | [
"\ndef",
"\n#",
"\nif",
"\nclass"
] |
|
from typing import Optional | def string_to_md5(text: str) -> Optional[str]:
"""
Given a string 'text', return its md5 hash equivalent string.
If 'text' is an empty string, return None.
>>> string_to_md5('Hello world')
'3e25960a79dbc69b674cd4ec67a72c62'
""" | def string_to_md5(text: str) -> Optional[str]:
"""
Given a string 'text', return its md5 hash equivalent string.
If 'text' is an empty string, return None.
>>> string_to_md5('Hello world')
'3e25960a79dbc69b674cd4ec67a72c62'
"""
import hashlib
return hashlib.md5(text.encode('ascii')).hexdigest() if text else None | string_to_md5 | def match_password(password: str, h: str) -> bool:
"""
Given a string 'password' and its md5 hash equivalent string 'h',
return True if 'password' is the original string, otherwise return False.
if 'password' is an empty string, return False.
>>> match_password('Hello world', '3e25960a79dbc69b674cd4ec67a72c62')
True
>>> match_password('Hello world', '3e25960a79dbc69b674cd4ec67a73c62')
False
""" | def match_password(password: str, h: str) -> bool:
"""
Given a string 'password' and its md5 hash equivalent string 'h',
return True if 'password' is the original string, otherwise return False.
if 'password' is an empty string, return False.
>>> match_password('Hello world', '3e25960a79dbc69b674cd4ec67a72c62')
True
>>> match_password('Hello world', '3e25960a79dbc69b674cd4ec67a73c62')
False
"""
return string_to_md5(password) == h if len(password) > 0 else False | match_password | def check(candidate):
assert candidate('this is password', '8910e62fae2505e21f568632df8410a9') is True
assert candidate('this was password', '8910e62fae2505e21f568632df8410a9') is False
assert candidate('', '8910e62fae2505e21f568632df8410a9') is False
def test_check():
check(match_password)
test_check() | [
"\ndef",
"\n#",
"\nif",
"\nclass"
] |
def generate_integers(a: int, b: int) -> list[int]:
"""
Given two positive integers a and b, return the even digits between a
and b, in ascending order.
For example:
>>> generate_integers(2, 8)
[2, 4, 6, 8]
>>> generate_integers(8, 2)
[2, 4, 6, 8]
>>> generate_integers(10, 14)
[]
""" | def generate_integers(a: int, b: int) -> list[int]:
"""
Given two positive integers a and b, return the even digits between a
and b, in ascending order.
For example:
>>> generate_integers(2, 8)
[2, 4, 6, 8]
>>> generate_integers(8, 2)
[2, 4, 6, 8]
>>> generate_integers(10, 14)
[]
"""
lower = max(2, min(a, b))
upper = min(8, max(a, b))
return [i for i in range(lower, upper + 1) if i % 2 == 0] | generate_integers | def sum_of_even_digits(a: int, b: int) -> int:
"""
Given two positive integers a and b, return the sum of the even digits
between a and b, inclusive.
For example:
>>> sum_of_even_digits(2, 8)
20
>>> sum_of_even_digits(8, 2)
20
>>> sum_of_even_digits(10, 14)
0
""" | def sum_of_even_digits(a: int, b: int) -> int:
"""
Given two positive integers a and b, return the sum of the even digits
between a and b, inclusive.
For example:
>>> sum_of_even_digits(2, 8)
20
>>> sum_of_even_digits(8, 2)
20
>>> sum_of_even_digits(10, 14)
0
"""
return sum(generate_integers(a, b)) | sum_of_even_digits | def check(candidate):
assert candidate(7, 3) == 10
assert candidate(10, 1) == 20
assert candidate(6, 6) == 6
def test_check():
check(sum_of_even_digits)
test_check() | [
"\ndef",
"\n#",
"\nif",
"\nclass"
] |