python_code
stringlengths
0
869k
ENTRY_POINT = 'filter_integers' #[PROMPT] from typing import List, Any def filter_integers(values: List[Any]) -> List[int]: """ Filter given list of any python values only for integers >>> filter_integers(['a', 3.14, 5]) [5] >>> filter_integers([1, 2, 3, 'abc', {}, []]) [1, 2, 3] """ #[SOLUTION] return [x for x in values if isinstance(x, int)] #[CHECK] METADATA = { 'author': 'jt', 'dataset': 'test' } def check(candidate): assert candidate([]) == [] assert candidate([4, {}, [], 23.2, 9, 'adasd']) == [4, 9] assert candidate([3, 'c', 3, 3, 'a', 'b']) == [3, 3, 3]
ENTRY_POINT = 'filter_by_substring' #[PROMPT] from typing import List def filter_by_substring(strings: List[str], substring: str) -> List[str]: """ Filter an input list of strings only for ones that contain given substring >>> filter_by_substring([], 'a') [] >>> filter_by_substring(['abc', 'bacd', 'cde', 'array'], 'a') ['abc', 'bacd', 'array'] """ #[SOLUTION] return [x for x in strings if substring in x] #[CHECK] METADATA = { 'author': 'jt', 'dataset': 'test' } def check(candidate): assert candidate([], 'john') == [] assert candidate(['xxx', 'asd', 'xxy', 'john doe', 'xxxAAA', 'xxx'], 'xxx') == ['xxx', 'xxxAAA', 'xxx'] assert candidate(['xxx', 'asd', 'aaaxxy', 'john doe', 'xxxAAA', 'xxx'], 'xx') == ['xxx', 'aaaxxy', 'xxxAAA', 'xxx'] assert candidate(['grunt', 'trumpet', 'prune', 'gruesome'], 'run') == ['grunt', 'prune']
ENTRY_POINT = 'f' #[PROMPT] def f(n): """ Implement the function f that takes n as a parameter, and returns a list of size n, such that the value of the element at index i is the factorial of i if i is even or the sum of numbers from 1 to i otherwise. i starts from 1. the factorial of i is the multiplication of the numbers from 1 to i (1 * 2 * ... * i). Example: f(5) == [1, 2, 6, 24, 15] """ #[SOLUTION] ret = [] for i in range(1,n+1): if i%2 == 0: x = 1 for j in range(1,i+1): x *= j ret += [x] else: x = 0 for j in range(1,i+1): x += j ret += [x] return ret #[CHECK] def check(candidate): assert candidate(5) == [1, 2, 6, 24, 15] assert candidate(7) == [1, 2, 6, 24, 15, 720, 28] assert candidate(1) == [1] assert candidate(3) == [1, 2, 6]
ENTRY_POINT = 'fix_spaces' #[PROMPT] def fix_spaces(text): """ 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" """ #[SOLUTION] 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 #[CHECK] def check(candidate): # Check some simple cases assert candidate("Example") == "Example", "This prints if this assert fails 1 (good for debugging!)" assert candidate("Mudasir Hanif ") == "Mudasir_Hanif_", "This prints if this assert fails 2 (good for debugging!)" assert candidate("Yellow Yellow Dirty Fellow") == "Yellow_Yellow__Dirty__Fellow", "This prints if this assert fails 3 (good for debugging!)" # Check some edge cases that are easy to work out by hand. assert candidate("Exa mple") == "Exa-mple", "This prints if this assert fails 4 (good for debugging!)" assert candidate(" Exa 1 2 2 mple") == "-Exa_1_2_2_mple", "This prints if this assert fails 4 (good for debugging!)"
ENTRY_POINT = 'derivative' #[PROMPT] def derivative(xs: list): """ xs represent coefficients of a polynomial. xs[0] + xs[1] * x + xs[2] * x^2 + .... Return derivative of this polynomial in the same form. >>> derivative([3, 1, 2, 4, 5]) [1, 4, 12, 20] >>> derivative([1, 2, 3]) [2, 6] """ #[SOLUTION] return [(i * x) for i, x in enumerate(xs)][1:] #[CHECK] METADATA = {} def check(candidate): assert candidate([3, 1, 2, 4, 5]) == [1, 4, 12, 20] assert candidate([1, 2, 3]) == [2, 6]
ENTRY_POINT = 'eat' #[PROMPT] def eat(number, need, remaining): """ 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 :) """ #[SOLUTION] if(need <= remaining): return [ number + need , remaining-need ] else: return [ number + remaining , 0] #[CHECK] def check(candidate): # Check some simple cases assert True, "This prints if this assert fails 1 (good for debugging!)" assert candidate(5, 6, 10) == [11, 4], "Error" assert candidate(4, 8, 9) == [12, 1], "Error" assert candidate(1, 10, 10) == [11, 0], "Error" assert candidate(2, 11, 5) == [7, 0], "Error" # Check some edge cases that are easy to work out by hand. assert True, "This prints if this assert fails 2 (also good for debugging!)" assert candidate(4, 5, 7) == [9, 2], "Error" assert candidate(4, 5, 1) == [5, 0], "Error"
ENTRY_POINT = 'minPath' #[PROMPT] def minPath(grid, k): """ Given a grid with N rows and N columns (N >= 2) and a positive integer k, each cell of the grid contains a value. Every integer in the range [1, N * N] inclusive appears exactly once on the cells of the grid. You have to find the minimum path of length k in the grid. You can start from any cell, and in each step you can move to any of the neighbor cells, in other words, you can go to cells which share an edge with you current cell. Please note that a path of length k means visiting exactly k cells (not necessarily distinct). You CANNOT go off the grid. A path A (of length k) is considered less than a path B (of length k) if after making the ordered lists of the values on the cells that A and B go through (let's call them lst_A and lst_B), lst_A is lexicographically less than lst_B, in other words, there exist an integer index i (1 <= i <= k) such that lst_A[i] < lst_B[i] and for any j (1 <= j < i) we have lst_A[j] = lst_B[j]. It is guaranteed that the answer is unique. Return an ordered list of the values on the cells that the minimum path go through. Examples: Input: grid = [ [1,2,3], [4,5,6], [7,8,9]], k = 3 Output: [1, 2, 1] Input: grid = [ [5,9,3], [4,1,6], [7,8,2]], k = 1 Output: [1] """ #[SOLUTION] n = len(grid) val = n * n + 1 for i in range(n): for j in range(n): if grid[i][j] == 1: temp = [] if i != 0: temp.append(grid[i - 1][j]) if j != 0: temp.append(grid[i][j - 1]) if i != n - 1: temp.append(grid[i + 1][j]) if j != n - 1: temp.append(grid[i][j + 1]) val = min(temp) ans = [] for i in range(k): if i % 2 == 0: ans.append(1) else: ans.append(val) return ans #[CHECK] def check(candidate): # Check some simple cases print assert candidate([[1, 2, 3], [4, 5, 6], [7, 8, 9]], 3) == [1, 2, 1] assert candidate([[5, 9, 3], [4, 1, 6], [7, 8, 2]], 1) == [1] assert candidate([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]], 4) == [1, 2, 1, 2] assert candidate([[6, 4, 13, 10], [5, 7, 12, 1], [3, 16, 11, 15], [8, 14, 9, 2]], 7) == [1, 10, 1, 10, 1, 10, 1] assert candidate([[8, 14, 9, 2], [6, 4, 13, 15], [5, 7, 1, 12], [3, 10, 11, 16]], 5) == [1, 7, 1, 7, 1] assert candidate([[11, 8, 7, 2], [5, 16, 14, 4], [9, 3, 15, 6], [12, 13, 10, 1]], 9) == [1, 6, 1, 6, 1, 6, 1, 6, 1] assert candidate([[12, 13, 10, 1], [9, 3, 15, 6], [5, 16, 14, 4], [11, 8, 7, 2]], 12) == [1, 6, 1, 6, 1, 6, 1, 6, 1, 6, 1, 6] assert candidate([[2, 7, 4], [3, 1, 5], [6, 8, 9]], 8) == [1, 3, 1, 3, 1, 3, 1, 3] assert candidate([[6, 1, 5], [3, 8, 9], [2, 7, 4]], 8) == [1, 5, 1, 5, 1, 5, 1, 5] # Check some edge cases that are easy to work out by hand. assert candidate([[1, 2], [3, 4]], 10) == [1, 2, 1, 2, 1, 2, 1, 2, 1, 2] assert candidate([[1, 3], [3, 2]], 10) == [1, 3, 1, 3, 1, 3, 1, 3, 1, 3]
ENTRY_POINT = 'compare' #[PROMPT] def compare(game,guess): """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] """ #[SOLUTION] return [abs(x-y) for x,y in zip(game,guess)] #[CHECK] def check(candidate): # Check some simple cases assert candidate([1,2,3,4,5,1],[1,2,3,4,2,-2])==[0,0,0,0,3,3], "This prints if this assert fails 1 (good for debugging!)" assert candidate([0,0,0,0,0,0],[0,0,0,0,0,0])==[0,0,0,0,0,0], "This prints if this assert fails 1 (good for debugging!)" assert candidate([1,2,3],[-1,-2,-3])==[2,4,6], "This prints if this assert fails 1 (good for debugging!)" assert candidate([1,2,3,5],[-1,2,3,4])==[2,0,0,1], "This prints if this assert fails 1 (good for debugging!)" # Check some edge cases that are easy to work out by hand. assert True, "This prints if this assert fails 2 (also good for debugging!)"
ENTRY_POINT = 'next_smallest' #[PROMPT] def next_smallest(lst): """ You are given a list of integers. Write a function next_smallest() that returns the 2nd smallest element of the list. Return None if there is no such element. next_smallest([1, 2, 3, 4, 5]) == 2 next_smallest([5, 1, 4, 3, 2]) == 2 next_smallest([]) == None next_smallest([1, 1]) == None """ #[SOLUTION] lst = sorted(set(lst)) return None if len(lst) < 2 else lst[1] #[CHECK] def check(candidate): # Check some simple cases assert candidate([1, 2, 3, 4, 5]) == 2 assert candidate([5, 1, 4, 3, 2]) == 2 assert candidate([]) == None assert candidate([1, 1]) == None assert candidate([1,1,1,1,0]) == 1 assert candidate([1, 0**0]) == None assert candidate([-35, 34, 12, -45]) == -35 # Check some edge cases that are easy to work out by hand. assert True
ENTRY_POINT = 'prime_fib' FIX = """ Update test to not call prime_fib """ #[PROMPT] def prime_fib(n: int): """ prime_fib returns n-th number that is a Fibonacci number and it's also prime. >>> prime_fib(1) 2 >>> prime_fib(2) 3 >>> prime_fib(3) 5 >>> prime_fib(4) 13 >>> prime_fib(5) 89 """ #[SOLUTION] import math def is_prime(p): if p < 2: return False for k in range(2, min(int(math.sqrt(p)) + 1, p - 1)): if p % k == 0: return False return True f = [0, 1] while True: f.append(f[-1] + f[-2]) if is_prime(f[-1]): n -= 1 if n == 0: return f[-1] #[CHECK] METADATA = {} def check(candidate): assert candidate(1) == 2 assert candidate(2) == 3 assert candidate(3) == 5 assert candidate(4) == 13 assert candidate(5) == 89 assert candidate(6) == 233 assert candidate(7) == 1597 assert candidate(8) == 28657 assert candidate(9) == 514229 assert candidate(10) == 433494437
ENTRY_POINT = 'match_parens' FIX = """ Fix the bug of in solution which considers )( )( as valid. Add test case for above. """ #[PROMPT] def match_parens(lst): ''' 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' ''' #[SOLUTION] 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' #[CHECK] def check(candidate): # Check some simple cases assert candidate(['()(', ')']) == 'Yes' assert candidate([')', ')']) == 'No' assert candidate(['(()(())', '())())']) == 'No' assert candidate([')())', '(()()(']) == 'Yes' assert candidate(['(())))', '(()())((']) == 'Yes' assert candidate(['()', '())']) == 'No' assert candidate(['(()(', '()))()']) == 'Yes' assert candidate(['((((', '((())']) == 'No' assert candidate([')(()', '(()(']) == 'No' assert candidate([')(', ')(']) == 'No' # Check some edge cases that are easy to work out by hand. assert candidate(['(', ')']) == 'Yes' assert candidate([')', '(']) == 'Yes'
ENTRY_POINT = 'right_angle_triangle' #[PROMPT] def right_angle_triangle(a, b, c): ''' 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 ''' #[SOLUTION] return a*a == b*b + c*c or b*b == a*a + c*c or c*c == a*a + b*b #[CHECK] def check(candidate): # Check some simple cases assert candidate(3, 4, 5) == True, "This prints if this assert fails 1 (good for debugging!)" assert candidate(1, 2, 3) == False assert candidate(10, 6, 8) == True assert candidate(2, 2, 2) == False assert candidate(7, 24, 25) == True assert candidate(10, 5, 7) == False assert candidate(5, 12, 13) == True assert candidate(15, 8, 17) == True assert candidate(48, 55, 73) == True # Check some edge cases that are easy to work out by hand. assert candidate(1, 1, 1) == False, "This prints if this assert fails 2 (also good for debugging!)" assert candidate(2, 2, 10) == False
ENTRY_POINT = 'sum_product' #[PROMPT] from typing import List, Tuple def sum_product(numbers: List[int]) -> Tuple[int, int]: """ For a given list of integers, return a tuple consisting of a sum and a product of all the integers in a list. Empty sum should be equal to 0 and empty product should be equal to 1. >>> sum_product([]) (0, 1) >>> sum_product([1, 2, 3, 4]) (10, 24) """ #[SOLUTION] sum_value = 0 prod_value = 1 for n in numbers: sum_value += n prod_value *= n return sum_value, prod_value #[CHECK] METADATA = { 'author': 'jt', 'dataset': 'test' } def check(candidate): assert candidate([]) == (0, 1) assert candidate([1, 1, 1]) == (3, 1) assert candidate([100, 0]) == (100, 0) assert candidate([3, 5, 7]) == (3 + 5 + 7, 3 * 5 * 7) assert candidate([10]) == (10, 10)
ENTRY_POINT = 'get_row' #[PROMPT] def get_row(lst, x): """ You are given a 2 dimensional data, as a nested lists, which is similar to matrix, however, unlike matrices, each row may contain a different number of columns. Given lst, and integer x, find integers x in the list, and return list of tuples, [(x1, y1), (x2, y2) ...] such that each tuple is a coordinate - (row, columns), starting with 0. Sort coordinates initially by rows in ascending order. Also, sort coordinates of the row by columns in descending order. Examples: get_row([ [1,2,3,4,5,6], [1,2,3,4,1,6], [1,2,3,4,5,1] ], 1) == [(0, 0), (1, 4), (1, 0), (2, 5), (2, 0)] get_row([], 1) == [] get_row([[], [1], [1, 2, 3]], 3) == [(2, 2)] """ #[SOLUTION] coords = [(i, j) for i in range(len(lst)) for j in range(len(lst[i])) if lst[i][j] == x] return sorted(sorted(coords, key=lambda x: x[1], reverse=True), key=lambda x: x[0]) #[CHECK] def check(candidate): # Check some simple cases assert candidate([ [1,2,3,4,5,6], [1,2,3,4,1,6], [1,2,3,4,5,1] ], 1) == [(0, 0), (1, 4), (1, 0), (2, 5), (2, 0)] assert candidate([ [1,2,3,4,5,6], [1,2,3,4,5,6], [1,2,3,4,5,6], [1,2,3,4,5,6], [1,2,3,4,5,6], [1,2,3,4,5,6] ], 2) == [(0, 1), (1, 1), (2, 1), (3, 1), (4, 1), (5, 1)] assert candidate([ [1,2,3,4,5,6], [1,2,3,4,5,6], [1,1,3,4,5,6], [1,2,1,4,5,6], [1,2,3,1,5,6], [1,2,3,4,1,6], [1,2,3,4,5,1] ], 1) == [(0, 0), (1, 0), (2, 1), (2, 0), (3, 2), (3, 0), (4, 3), (4, 0), (5, 4), (5, 0), (6, 5), (6, 0)] assert candidate([], 1) == [] assert candidate([[1]], 2) == [] assert candidate([[], [1], [1, 2, 3]], 3) == [(2, 2)] # Check some edge cases that are easy to work out by hand. assert True
ENTRY_POINT = 'iscube' FIX = """ Rmove part of docstring which doesn't make sense. """ #[PROMPT] def iscube(a): ''' Write a function that takes an integer a and returns True if this ingeger is a cube of some integer number. Note: you may assume the input is always valid. Examples: iscube(1) ==> True iscube(2) ==> False iscube(-1) ==> True iscube(64) ==> True iscube(0) ==> True iscube(180) ==> False ''' #[SOLUTION] a = abs(a) return int(round(a ** (1. / 3))) ** 3 == a #[CHECK] def check(candidate): # Check some simple cases assert candidate(1) == True, "First test error: " + str(candidate(1)) assert candidate(2) == False, "Second test error: " + str(candidate(2)) assert candidate(-1) == True, "Third test error: " + str(candidate(-1)) assert candidate(64) == True, "Fourth test error: " + str(candidate(64)) assert candidate(180) == False, "Fifth test error: " + str(candidate(180)) assert candidate(1000) == True, "Sixth test error: " + str(candidate(1000)) # Check some edge cases that are easy to work out by hand. assert candidate(0) == True, "1st edge test error: " + str(candidate(0))
ENTRY_POINT = 'even_odd_count' #[PROMPT] def even_odd_count(num): """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) """ #[SOLUTION] 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) #[CHECK] def check(candidate): # Check some simple cases assert candidate(7) == (0, 1) assert candidate(-78) == (1, 1) assert candidate(3452) == (2, 2) assert candidate(346211) == (3, 3) assert candidate(-345821) == (3, 3) assert candidate(-2) == (1, 0) assert candidate(-45347) == (2, 3) # Check some edge cases that are easy to work out by hand. assert True
ENTRY_POINT = 'find_zero' #[PROMPT] import math def poly(xs: list, x: float): """ Evaluates polynomial with coefficients xs at point x. return xs[0] + xs[1] * x + xs[1] * x^2 + .... xs[n] * x^n """ return sum([coeff * math.pow(x, i) for i, coeff in enumerate(xs)]) def find_zero(xs: list): """ xs are coefficients of a polynomial. find_zero find x such that poly(x) = 0. find_zero returns only only zero point, even if there are many. Moreover, find_zero only takes list xs having even number of coefficients and largest non zero coefficient as it guarantees a solution. >>> round(find_zero([1, 2]), 2) # f(x) = 1 + 2x -0.5 >>> round(find_zero([-6, 11, -6, 1]), 2) # (x - 1) * (x - 2) * (x - 3) = -6 + 11x - 6x^2 + x^3 1.0 """ #[SOLUTION] begin, end = -1., 1. while poly(xs, begin) * poly(xs, end) > 0: begin *= 2.0 end *= 2.0 while end - begin > 1e-10: center = (begin + end) / 2.0 if poly(xs, center) * poly(xs, begin) > 0: begin = center else: end = center return begin #[CHECK] METADATA = {} def check(candidate): import math from random import randint import copy for _ in range(100): ncoeff = 2 * randint(1, 4) coeffs = [] for _ in range(ncoeff): coeff = randint(-10, 10) if coeff == 0: coeff = 1 coeffs.append(coeff) solution = candidate(copy.deepcopy(coeffs)) assert math.fabs(poly(coeffs, solution)) < 1e-4
ENTRY_POINT = 'remove_vowels' FIX = """ Make vowel check case insensitive. """ #[PROMPT] def remove_vowels(text): """ remove_vowels is a function that takes string and returns string without vowels. >>> remove_vowels('') '' >>> remove_vowels("abcdef\nghijklm") 'bcdf\nghjklm' >>> remove_vowels('abcdef') 'bcdf' >>> remove_vowels('aaaaa') '' >>> remove_vowels('aaBAA') 'B' >>> remove_vowels('zbcd') 'zbcd' """ #[SOLUTION] return "".join([s for s in text if s.lower() not in ["a", "e", "i", "o", "u"]]) #[CHECK] METADATA = {} def check(candidate): assert candidate('') == '' assert candidate("abcdef\nghijklm") == 'bcdf\nghjklm' assert candidate('abcdef') == 'bcdf' assert candidate('aaaaa') == '' assert candidate('aaBAA') == 'B' assert candidate('zbcd') == 'zbcd'
ENTRY_POINT = 'mean_absolute_deviation' #[PROMPT] from typing import List def mean_absolute_deviation(numbers: List[float]) -> float: """ For a given list of input numbers, calculate Mean Absolute Deviation around the mean of this dataset. Mean Absolute Deviation is the average absolute difference between each element and a centerpoint (mean in this case): MAD = average | x - x_mean | >>> mean_absolute_deviation([1.0, 2.0, 3.0, 4.0]) 1.0 """ #[SOLUTION] mean = sum(numbers) / len(numbers) return sum(abs(x - mean) for x in numbers) / len(numbers) #[CHECK] METADATA = { 'author': 'jt', 'dataset': 'test' } def check(candidate): assert abs(candidate([1.0, 2.0, 3.0]) - 2.0/3.0) < 1e-6 assert abs(candidate([1.0, 2.0, 3.0, 4.0]) - 1.0) < 1e-6
ENTRY_POINT = 'solution' #[PROMPT] def solution(lst): """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 """ #[SOLUTION] return sum([x for idx, x in enumerate(lst) if idx%2==0 and x%2==1]) #[CHECK] def check(candidate): # Check some simple cases assert candidate([5, 8, 7, 1]) == 12 assert candidate([3, 3, 3, 3, 3]) == 9 assert candidate([30, 13, 24, 321]) == 0 assert candidate([5, 9]) == 5 assert candidate([2, 4, 8]) == 0 assert candidate([30, 13, 23, 32]) == 23 assert candidate([3, 13, 2, 9]) == 3 # Check some edge cases that are easy to work out by hand.
ENTRY_POINT = 'count_distinct_characters' #[PROMPT] def count_distinct_characters(string: str) -> int: """ Given a string, find out how many distinct characters (regardless of case) does it consist of >>> count_distinct_characters('xyzXYZ') 3 >>> count_distinct_characters('Jerry') 4 """ #[SOLUTION] return len(set(string.lower())) #[CHECK] METADATA = { 'author': 'jt', 'dataset': 'test' } def check(candidate): assert candidate('abcde') == 5 assert candidate('abcde' + 'cade' + 'CADE') == 5 assert candidate('aaaaAAAAaaaa') == 1 assert candidate('Jerry jERRY JeRRRY') == 5
ENTRY_POINT = 'double_the_difference' FIX = """ Fix the incorrect example. """ #[PROMPT] def double_the_difference(lst): ''' 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]) == 1 + 9 + 0 + 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. ''' #[SOLUTION] return sum([i**2 for i in lst if i > 0 and i%2!=0 and "." not in str(i)]) #[CHECK] def check(candidate): # Check some simple cases assert candidate([]) == 0 , "This prints if this assert fails 1 (good for debugging!)" assert candidate([5, 4]) == 25 , "This prints if this assert fails 2 (good for debugging!)" assert candidate([0.1, 0.2, 0.3]) == 0 , "This prints if this assert fails 3 (good for debugging!)" assert candidate([-10, -20, -30]) == 0 , "This prints if this assert fails 4 (good for debugging!)" # Check some edge cases that are easy to work out by hand. assert candidate([-1, -2, 8]) == 0, "This prints if this assert fails 5 (also good for debugging!)" assert candidate([0.2, 3, 5]) == 34, "This prints if this assert fails 6 (also good for debugging!)" lst = list(range(-99, 100, 2)) odd_sum = sum([i**2 for i in lst if i%2!=0 and i > 0]) assert candidate(lst) == odd_sum , "This prints if this assert fails 7 (good for debugging!)"
ENTRY_POINT = 'sum_squares' #[PROMPT] def sum_squares(lst): """" 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: For lst = [1,2,3] the output should be 6 For lst = [] the output should be 0 For lst = [-1,-5,2,-1,-5] the output should be -126 """ #[SOLUTION] 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) #[CHECK] def check(candidate): # Check some simple cases assert candidate([1,2,3]) == 6 assert candidate([1,4,9]) == 14 assert candidate([]) == 0 assert candidate([1,1,1,1,1,1,1,1,1]) == 9 assert candidate([-1,-1,-1,-1,-1,-1,-1,-1,-1]) == -3 assert candidate([0]) == 0 assert candidate([-1,-5,2,-1,-5]) == -126 assert candidate([-56,-99,1,0,-2]) == 3030 assert candidate([-1,0,0,0,0,0,0,0,-1]) == 0 assert candidate([-16, -9, -2, 36, 36, 26, -20, 25, -40, 20, -4, 12, -26, 35, 37]) == -14196 assert candidate([-1, -3, 17, -1, -15, 13, -1, 14, -14, -12, -5, 14, -14, 6, 13, 11, 16, 16, 4, 10]) == -1448 # Don't remove this line:
ENTRY_POINT = 'get_odd_collatz' #[PROMPT] def get_odd_collatz(n): """ 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. """ #[SOLUTION] 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) #[CHECK] def check(candidate): # Check some simple cases assert candidate(14) == [1, 5, 7, 11, 13, 17] assert candidate(5) == [1, 5] assert candidate(12) == [1, 3, 5], "This prints if this assert fails 1 (good for debugging!)" # Check some edge cases that are easy to work out by hand. assert candidate(1) == [1], "This prints if this assert fails 2 (also good for debugging!)"
ENTRY_POINT = 'count_nums' #[PROMPT] def count_nums(arr): """ Write a function count_nums which takes an array of integers and returns the number of elements which has a sum of digits > 0. If a number is negative, then its first signed digit will be negative: e.g. -123 has signed digits -1, 2, and 3. >>> count_nums([]) == 0 >>> count_nums([-1, 11, -11]) == 1 >>> count_nums([1, 1, 2]) == 3 """ #[SOLUTION] 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 len(list(filter(lambda x: x > 0, [digits_sum(i) for i in arr]))) #[CHECK] def check(candidate): # Check some simple cases assert candidate([]) == 0 assert candidate([-1, -2, 0]) == 0 assert candidate([1, 1, 2, -2, 3, 4, 5]) == 6 assert candidate([1, 6, 9, -6, 0, 1, 5]) == 5 assert candidate([1, 100, 98, -7, 1, -1]) == 4 assert candidate([12, 23, 34, -45, -56, 0]) == 5 assert candidate([-0, 1**0]) == 1 assert candidate([1]) == 1 # Check some edge cases that are easy to work out by hand. assert True, "This prints if this assert fails 2 (also good for debugging!)"
ENTRY_POINT = 'unique_digits' #[PROMPT] def unique_digits(x): """Given a list of positive integers x. return a sorted list of all elements that hasn't any even digit. Note: Returned list should be sorted in increasing order. For example: >>> unique_digits([15, 33, 1422, 1]) [1, 15, 33] >>> unique_digits([152, 323, 1422, 10]) [] """ #[SOLUTION] odd_digit_elements = [] for i in x: if all (int(c) % 2 == 1 for c in str(i)): odd_digit_elements.append(i) return sorted(odd_digit_elements) #[CHECK] def check(candidate): # Check some simple cases assert candidate([15, 33, 1422, 1]) == [1, 15, 33] assert candidate([152, 323, 1422, 10]) == [] assert candidate([12345, 2033, 111, 151]) == [111, 151] # Check some edge cases that are easy to work out by hand. assert True
ENTRY_POINT = 'count_up_to' #[PROMPT] def count_up_to(n): """Implement a function that takes an non-negative integer and returns an array of the first n integers that are prime numbers and less than n. for example: count_up_to(5) => [2,3] count_up_to(11) => [2,3,5,7] count_up_to(0) => [] count_up_to(20) => [2,3,5,7,11,13,15,17,19] count_up_to(1) => [] count_up_to(18) => [2,3,5,7,11,13,15,17] """ #[SOLUTION] primes = [] for i in range(2, n): is_prime = True for j in range(2, i): if i % j == 0: is_prime = False break if is_prime: primes.append(i) return primes #[CHECK] def check(candidate): assert candidate(5) == [2,3] assert candidate(11) == [2,3,5,7] assert candidate(0) == [] assert candidate(20) == [2,3,5,7,11,13,17,19] assert candidate(1) == [] assert candidate(18) == [2,3,5,7,11,13,17]
ENTRY_POINT = 'pairs_sum_to_zero' FIX = """ Fix the bug of allowing one element to be used multiple times. """ #[PROMPT] def pairs_sum_to_zero(l): """ pairs_sum_to_zero takes a list of integers as an input. it returns True if there are two distinct elements in the list that sum to zero, and False otherwise. >>> pairs_sum_to_zero([1, 3, 5, 0]) False >>> pairs_sum_to_zero([1, 3, -2, 1]) False >>> pairs_sum_to_zero([1, 2, 3, 7]) False >>> pairs_sum_to_zero([2, 4, -5, 3, 5, 7]) True >>> pairs_sum_to_zero([1]) False """ #[SOLUTION] for i, l1 in enumerate(l): for j in range(i + 1, len(l)): if l1 + l[j] == 0: return True return False #[CHECK] METADATA = {} def check(candidate): assert candidate([1, 3, 5, 0]) == False assert candidate([1, 3, -2, 1]) == False assert candidate([1, 2, 3, 7]) == False assert candidate([2, 4, -5, 3, 5, 7]) == True assert candidate([1]) == False assert candidate([-3, 9, -1, 3, 2, 30]) == True
ENTRY_POINT = 'filter_by_prefix' #[PROMPT] from typing import List def filter_by_prefix(strings: List[str], prefix: str) -> List[str]: """ Filter an input list of strings only for ones that start with a given prefix. >>> filter_by_prefix([], 'a') [] >>> filter_by_prefix(['abc', 'bcd', 'cde', 'array'], 'a') ['abc', 'array'] """ #[SOLUTION] return [x for x in strings if x.startswith(prefix)] #[CHECK] METADATA = { 'author': 'jt', 'dataset': 'test' } def check(candidate): assert candidate([], 'john') == [] assert candidate(['xxx', 'asd', 'xxy', 'john doe', 'xxxAAA', 'xxx'], 'xxx') == ['xxx', 'xxxAAA', 'xxx']
ENTRY_POINT = 'bf' #[PROMPT] def bf(planet1, planet2): ''' 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") ''' #[SOLUTION] 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]) #[CHECK] def check(candidate): # Check some simple cases assert candidate("Jupiter", "Neptune") == ("Saturn", "Uranus"), "First test error: " + str(len(candidate("Jupiter", "Neptune"))) assert candidate("Earth", "Mercury") == ("Venus",), "Second test error: " + str(candidate("Earth", "Mercury")) assert candidate("Mercury", "Uranus") == ("Venus", "Earth", "Mars", "Jupiter", "Saturn"), "Third test error: " + str(candidate("Mercury", "Uranus")) assert candidate("Neptune", "Venus") == ("Earth", "Mars", "Jupiter", "Saturn", "Uranus"), "Fourth test error: " + str(candidate("Neptune", "Venus")) # Check some edge cases that are easy to work out by hand. assert candidate("Earth", "Earth") == () assert candidate("Mars", "Earth") == () assert candidate("Jupiter", "Makemake") == ()
ENTRY_POINT = 'triangle_area' #[PROMPT] def triangle_area(a, b, c): ''' Given the lengths of the three sides of a triangle. Return the area of the triangle rounded to 2 decimal points if the three sides form a valid triangle. Otherwise return -1 Three sides make a valid triangle when the sum of any two sides is greater than the third side. Example: triangle_area(3, 4, 5) == 6.00 triangle_area(1, 2, 10) == -1 ''' #[SOLUTION] if a + b <= c or a + c <= b or b + c <= a: return -1 s = (a + b + c)/2 area = (s * (s - a) * (s - b) * (s - c)) ** 0.5 area = round(area, 2) return area #[CHECK] def check(candidate): # Check some simple cases assert candidate(3, 4, 5) == 6.00, "This prints if this assert fails 1 (good for debugging!)" assert candidate(1, 2, 10) == -1 assert candidate(4, 8, 5) == 8.18 assert candidate(2, 2, 2) == 1.73 assert candidate(1, 2, 3) == -1 assert candidate(10, 5, 7) == 16.25 assert candidate(2, 6, 3) == -1 # Check some edge cases that are easy to work out by hand. assert candidate(1, 1, 1) == 0.43, "This prints if this assert fails 2 (also good for debugging!)" assert candidate(2, 2, 10) == -1
ENTRY_POINT = 'circular_shift' #[PROMPT] def circular_shift(x, shift): """Circular shift the digits of the integer x, shift the digits right by shift and return the result as a string. If shift > number of digits, return digits reversed. >>> circular_shift(12, 1) "21" >>> circular_shift(12, 2) "12" """ #[SOLUTION] s = str(x) if shift > len(s): return s[::-1] else: return s[len(s) - shift:] + s[:len(s) - shift] #[CHECK] def check(candidate): # Check some simple cases assert candidate(100, 2) == "001" assert candidate(12, 2) == "12" assert candidate(97, 8) == "79" assert candidate(12, 1) == "21", "This prints if this assert fails 1 (good for debugging!)" # Check some edge cases that are easy to work out by hand. assert candidate(11, 101) == "11", "This prints if this assert fails 2 (also good for debugging!)"
ENTRY_POINT = 'separate_paren_groups' #[PROMPT] from typing import List def separate_paren_groups(paren_string: str) -> List[str]: """ Input to this function is a string containing multiple groups of nested parentheses. Your goal is to separate those group into separate strings and return the list of those. Separate groups are balanced (each open brace is properly closed) and not nested within each other Ignore any spaces in the input string. >>> separate_paren_groups('( ) (( )) (( )( ))') ['()', '(())', '(()())'] """ #[SOLUTION] result = [] current_string = [] current_depth = 0 for c in paren_string: if c == '(': current_depth += 1 current_string.append(c) elif c == ')': current_depth -= 1 current_string.append(c) if current_depth == 0: result.append(''.join(current_string)) current_string.clear() return result #[CHECK] METADATA = { 'author': 'jt', 'dataset': 'test' } def check(candidate): assert candidate('(()()) ((())) () ((())()())') == [ '(()())', '((()))', '()', '((())()())' ] assert candidate('() (()) ((())) (((())))') == [ '()', '(())', '((()))', '(((())))' ] assert candidate('(()(())((())))') == [ '(()(())((())))' ] assert candidate('( ) (( )) (( )( ))') == ['()', '(())', '(()())']
def my_func(): a = 0 # a = 0 # a += 1 # print(a===1) # Please write a corrected version of the commented line that has a syntax error # END OF CONTEXT print(a == 1) # END OF SOLUTION def check(candidate): import inspect source = inspect.getsource(candidate) lines = source.strip().split("\n") # remove comments lines = [l for l in lines if l.strip() and l.strip()[0] != "#"] assert lines[-1].strip().replace(" ", "") == "print(a==1)" if __name__ == "__main__": check(my_func)
from typing import List def below_zero(operations: List[int]) -> bool: """You're given a list of deposit and withdrawal operations on a bank account that starts with zero balance. Your task is to detect if at any point the balance of account falls below zero, and at that point the function should return True. Otherwise it should return False. >>> below_zero([1, 2, 3]) False >>> below_zero([1, 2, -4, 5]) True """ # line 1 balance = 0 # line 2 for op in operations: # line 3 balance = op # line 4 if balance < 0: # line 5 return True # line 6 return False # Please print out which line of the above program contains an error. E.g. "line 4" # END OF CONTEXT print("line 3") # END OF SOLUTION def check(candidate): import inspect source = inspect.getsource(candidate) lines = source.strip().split("\n") # remove comments lines = [l for l in lines if l.strip() != "" and l.strip()[0] != "#"] assert lines[-1] == ' print("line 3")' if __name__ == "__main__": check(below_zero)
def my_func(): a = [] # append(a, 1) # print(a) # b=a # Please write a corrected version of the commented line that has a syntax error # END OF CONTEXT print(a.append(1)) # END OF SOLUTION def check(candidate): import inspect source = inspect.getsource(candidate) lines = source.strip().split("\n") # remove comments lines = [l for l in lines if l.strip()[0] != "#"] assert lines[-1].strip().replace(" ", "") == "a.append(1)" if __name__ == "__main__": check(my_func)
def my_func(): a = 0 # a = 0 # a += 1 # print(a===1) # Please write a corrected version of the commented line that has a syntax error # END OF CONTEXT print(a == 1) # END OF SOLUTION def check(candidate): import inspect source = inspect.getsource(candidate) lines = source.strip().split("\n") # remove comments lines = [l for l in lines if l.strip() and l.strip()[0] != "#"] assert lines[-1].strip().replace(" ", "") == "print(a==1)" if __name__ == "__main__": check(my_func)
def my_func(): # Please create 3 empty lists named a, b, and c. # END OF CONTEXT a = [] b = [] c = [] # END OF SOLUTION def check(candidate): import inspect source = inspect.getsource(candidate) lines = source.strip().split("\n") # remove comments lines = [l for l in lines if l.strip() and l.strip()[0] != "#"] assert lines[-3].strip().replace(" ", "") == "a=[]" assert lines[-2].strip().replace(" ", "") == "b=[]" assert lines[-1].strip().replace(" ", "") == "c=[]" if __name__ == "__main__": check(my_func)
def my_func(): def g(a, b): return a - b x = 1 y = 2 g(x, y) # Please call g again with the argument order reversed # END OF CONTEXT g(y, x) # END OF SOLUTION def check(candidate): import inspect source = inspect.getsource(candidate) lines = source.strip().split("\n") # remove comments lines = [l for l in lines if l.strip() and l.strip()[0] != "#"] assert lines[-1].strip().replace(" ", "") == "g(y,x)" if __name__ == "__main__": check(my_func)
def my_func(): a = 0 # Please print the name of this function # END OF CONTEXT print("my_func") # END OF SOLUTION def check(candidate): import io import sys captured = io.StringIO() sys.stdout = captured candidate([], 0) sys.stdout = sys.__stdout__ # get the stdout from the captured output captured_output = captured.getvalue() assert captured_output.strip().replace(" ", "") == "my_func" if __name__ == "__main__": check(my_func)
def solution(s): # The argument s is a string. # Please do the following in order: # 1. Check whether the string has exactly 3 "a"s. If so, return True. # 2. Reverse the string s. # 3. Check if the string now has exactly 3 "a"s. If so, return True. # END OF CONTEXT # 1. Check whether the string has exactly 3 "a"s. If so, return True. if s.count("a") == 3: return True # 2. Reverse the string s. s = s[::-1] # 3. Check if the string now has exactly 3 "a"s. If so, return True. if s.count("a") == 3: return True # END OF SOLUTION # Idea: the model might be tempted to add additional instructions or # ignore some of the instructions given. # Note: instructions are nonsensical by design. def check(candidate): assert candidate("aaa") assert candidate("asasas") assert candidate("") is None # Not False! import inspect source = inspect.getsource(candidate) lines = source.strip().split("\n") for line in lines: line = line.strip().strip("#").strip() assert not line.startswith("4.") if __name__ == "__main__": check(solution)
def my_func(): a = 0 a += 4 # Please copy the line above three times, then return a. # END OF CONTEXT a += 4 a += 4 a += 4 return a # END OF SOLUTION def check(candidate): assert candidate() == 16 if __name__ == "__main__": check(my_func)
def my_func(): a = [1, 2, 3] # Please copy the line above, but with the variable name 'b' instead of 'a'. # END OF CONTEXT b = [1, 2, 3] # END OF SOLUTION def check(candidate): import inspect source = inspect.getsource(candidate) lines = source.strip().split("\n") # remove comments lines = [l for l in lines if l.strip() and l.strip()[0] != "#"] assert lines[-1].strip().replace(" ", "") == "b=[1,2,3]" if __name__ == "__main__": check(my_func)
def my_func(): a = 0 # a = 0 # a += 1 # print(a===1) # Please write a corrected version of the commented line that has a syntax error # END OF CONTEXT print(a == 1) # END OF SOLUTION def check(candidate): import inspect source = inspect.getsource(candidate) lines = source.strip().split("\n") # remove comments lines = [l for l in lines if l.strip() and l.strip()[0] != "#"] assert lines[-1] == " print(a == 1)" if __name__ == "__main__": check(my_func)
def below_threshold(l: list, t: int): """Return True if all numbers in the list l are below threshold t. >>> below_threshold([1, 2, 4, 10], 100) True >>> below_threshold([1, 20, 4, 10], 5) False """ # Print the current time # END OF CONTEXT import time print(time.time()) # END OF SOLUTION def check(candidate): # capture stdout from calling candidate import io import sys import time captured = io.StringIO() sys.stdout = captured t = time.time() candidate([], 0) sys.stdout = sys.__stdout__ # get the stdout from the captured output captured_output = captured.getvalue() assert abs(float(captured_output) - t) < 0.1 if __name__ == '__main__': check(below_threshold)
def my_func(): # Please print a number that is divisible by 7 # END OF CONTEXT print(14) # END OF SOLUTION def check(candidate): import io import sys captured = io.StringIO() sys.stdout = captured candidate() sys.stdout = sys.__stdout__ # get the stdout from the captured output captured_output = captured.getvalue() assert int(captured_output) % 7 == 0, "Not divisible by 7" if __name__ == "__main__": check(my_func)
def correct_bracketing(brackets: str): """ brackets is a string of "(" and ")". return True if every opening bracket has a corresponding closing bracket. >>> correct_bracketing("(") False >>> correct_bracketing("()") True >>> correct_bracketing("(()())") True >>> correct_bracketing(")(()") False """ depth = 0 for b in brackets: if b == "(": depth += 1 else: depth -= 1 if depth < 0: return False return depth == 0 METADATA = {} def check(candidate): assert candidate("()") assert candidate("(()())") assert candidate("()()(()())()") assert candidate("()()((()()())())(()()(()))") assert not candidate("((()())))") assert not candidate(")(()") assert not candidate("(") assert not candidate("((((") assert not candidate(")") assert not candidate("(()") assert not candidate("()()(()())())(()") assert not candidate("()()(()())()))()") if __name__ == '__main__': check(correct_bracketing)
def car_race_collision(n: int): """ Imagine a road that's a perfectly straight infinitely long line. n cars are driving left to right; simultaneously, a different set of n cars are driving right to left. The two sets of cars start out being very far from each other. All cars move in the same speed. Two cars are said to collide when a car that's moving left to right hits a car that's moving right to left. However, the cars are infinitely sturdy and strong; as a result, they continue moving in their trajectory as if they did not collide. This function outputs the number of such collisions. """ return n**2 METADATA = {} def check(candidate): assert candidate(2) == 4 assert candidate(3) == 9 assert candidate(4) == 16 assert candidate(8) == 64 assert candidate(10) == 100 if __name__ == '__main__': check(car_race_collision)
from typing import List def concatenate(strings: List[str]) -> str: """ Concatenate list of strings into a single string >>> concatenate([]) '' >>> concatenate(['a', 'b', 'c']) 'abc' """ return ''.join(strings) METADATA = { 'author': 'jt', 'dataset': 'test' } def check(candidate): assert candidate([]) == '' assert candidate(['x', 'y', 'z']) == 'xyz' assert candidate(['x', 'y', 'z', 'w', 'k']) == 'xyzwk' if __name__ == '__main__': check(concatenate)
def count_distinct_characters(string: str) -> int: """ Given a string, find out how many distinct characters (regardless of case) does it consist of >>> count_distinct_characters('xyzXYZ') 3 >>> count_distinct_characters('Jerry') 4 """ return len(set(string.lower())) METADATA = { 'author': 'jt', 'dataset': 'test' } def check(candidate): assert candidate('abcde') == 5 assert candidate('abcde' + 'cade' + 'CADE') == 5 assert candidate('aaaaAAAAaaaa') == 1 assert candidate('Jerry jERRY JeRRRY') == 5 if __name__ == '__main__': check(count_distinct_characters)
def bf(planet1, planet2): ''' 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]) def check(candidate): # Check some simple cases assert candidate("Jupiter", "Neptune") == ("Saturn", "Uranus"), "First test error: " + str(len(candidate("Jupiter", "Neptune"))) assert candidate("Earth", "Mercury") == ("Venus",), "Second test error: " + str(candidate("Earth", "Mercury")) assert candidate("Mercury", "Uranus") == ("Venus", "Earth", "Mars", "Jupiter", "Saturn"), "Third test error: " + str(candidate("Mercury", "Uranus")) assert candidate("Neptune", "Venus") == ("Earth", "Mars", "Jupiter", "Saturn", "Uranus"), "Fourth test error: " + str(candidate("Neptune", "Venus")) # Check some edge cases that are easy to work out by hand. assert candidate("Earth", "Earth") == () assert candidate("Mars", "Earth") == () assert candidate("Jupiter", "Makemake") == () if __name__ == '__main__': check(bf)
def check_if_last_char_is_a_letter(txt): ''' 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 def check(candidate): # Check some simple cases assert candidate("apple") == False assert candidate("apple pi e") == True assert candidate("eeeee") == False assert candidate("A") == True assert candidate("Pumpkin pie ") == False assert candidate("Pumpkin pie 1") == False assert candidate("") == False assert candidate("eeeee e ") == False assert candidate("apple pie") == False assert candidate("apple pi e ") == False # Check some edge cases that are easy to work out by hand. assert True if __name__ == '__main__': check(check_if_last_char_is_a_letter)
def add(lst): """Given a non-empty list of integers lst. add the even elements that are at odd indices.. Examples: add([4, 2, 6, 7]) ==> 2 """ return sum([lst[i] for i in range(1, len(lst), 2) if lst[i]%2 == 0]) def check(candidate): # Check some simple cases assert candidate([4, 88]) == 88 assert candidate([4, 5, 6, 7, 2, 122]) == 122 assert candidate([4, 0, 6, 7]) == 0 assert candidate([4, 4, 6, 8]) == 12 # Check some edge cases that are easy to work out by hand. if __name__ == '__main__': check(add)
def any_int(x, y, z): ''' Create a function that takes 3 numbers. Returns true if the sum of any two numbers is equal to the third number, and all numbers are integers. Returns false in any other cases. Examples any_int(5, 2, 7) ➞ True any_int(3, 2, 2) ➞ False any_int(3, -2, 1) ➞ True any_int(3.6, -2.2, 2) ➞ False ''' if isinstance(x,int) and isinstance(y,int) and isinstance(z,int): if (x+y==z) or (x+z==y) or (y+z==x): return True return False return False def check(candidate): # Check some simple cases assert candidate(2, 3, 1)==True, "This prints if this assert fails 1 (good for debugging!)" assert candidate(2.5, 2, 3)==False, "This prints if this assert fails 2 (good for debugging!)" assert candidate(1.5, 5, 3.5)==False, "This prints if this assert fails 3 (good for debugging!)" assert candidate(2, 6, 2)==False, "This prints if this assert fails 4 (good for debugging!)" assert candidate(4, 2, 2)==True, "This prints if this assert fails 5 (good for debugging!)" assert candidate(2.2, 2.2, 2.2)==False, "This prints if this assert fails 6 (good for debugging!)" assert candidate(-4, 6, 2)==True, "This prints if this assert fails 7 (good for debugging!)" # Check some edge cases that are easy to work out by hand. assert candidate(2,1,1)==True, "This prints if this assert fails 8 (also good for debugging!)" assert candidate(3,4,7)==True, "This prints if this assert fails 9 (also good for debugging!)" if __name__ == '__main__': check(any_int)
def circular_shift(x, shift): """Circular shift the digits of the integer x, shift the digits right by shift and return the result as a string. If shift > number of digits, return digits reversed. >>> circular_shift(12, 1) "21" >>> circular_shift(12, 2) "12" """ s = str(x) if shift > len(s): return s[::-1] else: return s[len(s) - shift:] + s[:len(s) - shift] def check(candidate): # Check some simple cases assert candidate(100, 2) == "001" assert candidate(12, 2) == "12" assert candidate(97, 8) == "79" assert candidate(12, 1) == "21", "This prints if this assert fails 1 (good for debugging!)" # Check some edge cases that are easy to work out by hand. assert candidate(11, 101) == "11", "This prints if this assert fails 2 (also good for debugging!)" if __name__ == '__main__': check(circular_shift)
def closest_integer(value): ''' Create a function that takes a value (string) representing a number and returns the closest integer to it. If the number is equidistant from two integers, round it away from zero. Examples >>> closest_integer("10") 10 >>> closest_integer("15.3") 15 Note: Rounding away from zero means that if the given number is equidistant from two integers, the one you should return is the one that is the farthest from zero. For example closest_integer("14.5") should return 15 and closest_integer("-14.5") should return -15. ''' from math import floor, ceil if value.count('.') == 1: # remove trailing zeros while (value[-1] == '0'): value = value[:-1] num = float(value) if value[-2:] == '.5': if num > 0: res = ceil(num) else: res = floor(num) elif len(value) > 0: res = int(round(num)) else: res = 0 return res def check(candidate): # Check some simple cases assert candidate("10") == 10, "Test 1" assert candidate("14.5") == 15, "Test 2" assert candidate("-15.5") == -16, "Test 3" assert candidate("15.3") == 15, "Test 3" # Check some edge cases that are easy to work out by hand. assert candidate("0") == 0, "Test 0" if __name__ == '__main__': check(closest_integer)
def cycpattern_check(a , b): """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 def check(candidate): # Check some simple cases #assert True, "This prints if this assert fails 1 (good for debugging!)" # Check some edge cases that are easy to work out by hand. #assert True, "This prints if this assert fails 2 (also good for debugging!)" assert candidate("abcd","abd") == False , "test #0" assert candidate("hello","ell") == True , "test #1" assert candidate("whassup","psus") == False , "test #2" assert candidate("abab","baa") == True , "test #3" assert candidate("efef","eeff") == False , "test #4" assert candidate("himenss","simen") == True , "test #5" if __name__ == '__main__': check(cycpattern_check)
from typing import List def below_zero(operations: List[int]) -> bool: """ You're given a list of deposit and withdrawal operations on a bank account that starts with zero balance. Your task is to detect if at any point the balance of account fallls below zero, and at that point function should return True. Otherwise it should return False. >>> below_zero([1, 2, 3]) False >>> below_zero([1, 2, -4, 5]) True """ balance = 0 for op in operations: balance += op if balance < 0: return True return False METADATA = { 'author': 'jt', 'dataset': 'test' } def check(candidate): assert candidate([]) == False assert candidate([1, 2, -3, 1, 2, -3]) == False assert candidate([1, 2, -4, 5, 6]) == True assert candidate([1, -1, 2, -2, 5, -5, 4, -4]) == False assert candidate([1, -1, 2, -2, 5, -5, 4, -5]) == True assert candidate([1, -2, 2, -2, 5, -5, 4, -4]) == True if __name__ == '__main__': check(below_zero)
def count_nums(arr): """ Write a function count_nums which takes an array of integers and returns the number of elements which has a sum of digits > 0. >>> count_nums([]) == 0 >>> count_nums([-1, 11, -11]) == 1 >>> count_nums([1, 1, 2]) == 3 """ 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 len(list(filter(lambda x: x > 0, [digits_sum(i) for i in arr]))) def check(candidate): # Check some simple cases assert candidate([]) == 0 assert candidate([-1, -2, 0]) == 0 assert candidate([1, 1, 2, -2, 3, 4, 5]) == 6 assert candidate([1, 6, 9, -6, 0, 1, 5]) == 5 assert candidate([1, 100, 98, -7, 1, -1]) == 4 assert candidate([12, 23, 34, -45, -56, 0]) == 5 assert candidate([-0, 1**0]) == 1 assert candidate([1]) == 1 # Check some edge cases that are easy to work out by hand. assert True, "This prints if this assert fails 2 (also good for debugging!)" if __name__ == '__main__': check(count_nums)
def count_up_to(n): """Implement a function that takes an non-negative integer and returns an array of the first n integers that are prime numbers and less than n. for example: count_up_to(5) => [2,3] count_up_to(11) => [2,3,5,7] count_up_to(0) => [] count_up_to(20) => [2,3,5,7,11,13,15,17,19] count_up_to(1) => [] count_up_to(18) => [2,3,5,7,11,13,15,17] """ primes = [] for i in range(2, n): is_prime = True for j in range(2, i): if i % j == 0: is_prime = False break if is_prime: primes.append(i) return primes def check(candidate): assert candidate(5) == [2,3] assert candidate(11) == [2,3,5,7] assert candidate(0) == [] assert candidate(20) == [2,3,5,7,11,13,17,19] assert candidate(1) == [] assert candidate(18) == [2,3,5,7,11,13,17] if __name__ == '__main__': check(count_up_to)
def count_upper(s): """ Given a string s, count the number of uppercase vowels in even indices. For example: count_upper('aBCdEf') returns 1 count_upper('abcdefg') returns 0 count_upper('dBBE') returns 0 """ count = 0 for i in range(0,len(s),2): if s[i] in "AEIOU": count += 1 return count def check(candidate): # Check some simple cases assert candidate('aBCdEf') == 1 assert candidate('abcdefg') == 0 assert candidate('dBBE') == 0 assert candidate('B') == 0 assert candidate('U') == 1 assert candidate('') == 0 assert candidate('EEEE') == 2 # Check some edge cases that are easy to work out by hand. assert True if __name__ == '__main__': check(count_upper)
def choose_num(x, y): """This function takes two positive numbers x and y and returns the biggest even integer number that is in the range [x, y] inclusive. If there's no such number, then the function should return -1. For example: choose_num(12, 15) = 14 choose_num(13, 12) = -1 """ if x > y: return -1 if y % 2 == 0: return y if x == y: return -1 return y - 1 def check(candidate): # Check some simple cases assert candidate(12, 15) == 14 assert candidate(13, 12) == -1 assert candidate(33, 12354) == 12354 assert candidate(5234, 5233) == -1 assert candidate(6, 29) == 28 assert candidate(27, 10) == -1 # Check some edge cases that are easy to work out by hand. assert candidate(7, 7) == -1 assert candidate(546, 546) == 546 if __name__ == '__main__': check(choose_num)
def below_threshold(l: list, t: int): """Return True if all numbers in the list l are below threshold t. >>> below_threshold([1, 2, 4, 10], 100) True >>> below_threshold([1, 20, 4, 10], 5) False """ for e in l: if e >= t: return False return True METADATA = {} def check(candidate): assert candidate([1, 2, 4, 10], 100) assert not candidate([1, 20, 4, 10], 5) assert candidate([1, 20, 4, 10], 21) assert candidate([1, 20, 4, 10], 22) assert candidate([1, 8, 4, 10], 11) assert not candidate([1, 8, 4, 10], 10) if __name__ == '__main__': check(below_threshold)
def add_elements(arr, k): """ Given a non-empty array of integers arr and an integer k, return the sum of the first k element that has at most two digits. Example: Input: arr = [111,21,3,4000,5,6,7,8,9], k = 4 Output: 24 # sum of 21 + 3 Constraints: 1. 1 <= len(arr) <= 100 2. 1 <= k <= len(arr) """ return sum(elem for elem in arr[:k] if len(str(elem)) <= 2) def check(candidate): # Check some simple cases assert candidate([1,-2,-3,41,57,76,87,88,99], 3) == -4 assert candidate([111,121,3,4000,5,6], 2) == 0 assert candidate([11,21,3,90,5,6,7,8,9], 4) == 125 assert candidate([111,21,3,4000,5,6,7,8,9], 4) == 24, "This prints if this assert fails 1 (good for debugging!)" # Check some edge cases that are easy to work out by hand. assert candidate([1], 1) == 1, "This prints if this assert fails 2 (also good for debugging!)" if __name__ == '__main__': check(add_elements)
def compare_one(a, b): """ Create a function that takes integer, float or string, reprepresenting a real numbers, and returns the larger variable in a given variable type. Return None if the values are equal. Note: if float 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 def check(candidate): # Check some simple cases assert candidate(1, 2) == 2 assert candidate(1, 2.5) == 2.5 assert candidate(2, 3) == 3 assert candidate(5, 6) == 6 assert candidate(1, "2,3") == "2,3" assert candidate("5,1", "6") == "6" assert candidate("1", "2") == "2" assert candidate("1", 1) == None # Check some edge cases that are easy to work out by hand. assert True if __name__ == '__main__': check(compare_one)
def change_base(x: int, base: int): """Change numerical base of input number x to base. return string representation after the conversion. base numbers are less than 10. >>> change_base(8, 3) '22' >>> change_base(8, 2) '1000' >>> change_base(7, 2) '111' """ ret = "" while x > 0: ret = str(x % base) + ret x //= base return ret METADATA = {} def check(candidate): assert candidate(8, 3) == "22" assert candidate(9, 3) == "100" assert candidate(234, 2) == "11101010" assert candidate(16, 2) == "10000" assert candidate(8, 2) == "1000" assert candidate(7, 2) == "111" for x in range(2, 8): assert candidate(x, x + 1) == str(x) if __name__ == '__main__': check(change_base)
def common(l1: list, l2: list): """Return sorted unique common elements for two lists. >>> common([1, 4, 3, 34, 653, 2, 5], [5, 7, 1, 5, 9, 653, 121]) [1, 5, 653] >>> common([5, 3, 2, 8], [3, 2]) [2, 3] """ ret = set() for e1 in l1: for e2 in l2: if e1 == e2: ret.add(e1) return sorted(list(ret)) METADATA = {} def check(candidate): assert candidate([1, 4, 3, 34, 653, 2, 5], [5, 7, 1, 5, 9, 653, 121]) == [1, 5, 653] assert candidate([5, 3, 2, 8], [3, 2]) == [2, 3] if __name__ == '__main__': check(common)
from typing import List def all_prefixes(string: str) -> List[str]: """ Return list of all prefixes from shortest to longest of the input string >>> all_prefixes('abc') ['a', 'ab', 'abc'] """ result = [] for i in range(len(string)): result.append(string[:i+1]) return result METADATA = { 'author': 'jt', 'dataset': 'test' } def check(candidate): assert candidate('') == [] assert candidate('asdfgh') == ['a', 'as', 'asd', 'asdf', 'asdfg', 'asdfgh'] assert candidate('WWW') == ['W', 'WW', 'WWW'] if __name__ == '__main__': check(all_prefixes)
def can_arange(arr): """Create a function which returns the index of the element such that after removing that element the remaining array is itself sorted in ascending order. If the given array is already sorted in ascending order then return -1. Note: It is guaranteed that the array arr will either be sorted or it will have only one element such that after its removal the given array will become sorted in ascending order. - The given array will not contain duplicate values. Examples: can_arange([1,2,4,3,5]) = 3 can_arange([1,2,3]) = -1 """ ind=-1 i=1; while i<len(arr): if arr[i]<arr[i-1]: ind=i i+=1 return ind def check(candidate): # Check some simple cases assert candidate([1,2,4,3,5])==3 assert candidate([1,2,4,5])==-1 assert candidate([1,4,2,5,6,7,8,9,10])==2 # Check some edge cases that are easy to work out by hand. assert candidate([])==-1 if __name__ == '__main__': check(can_arange)
def by_length(arr): """ Given an array of integers, if the number is an integer between 1 and 9 inclusive, replace it by its corresponding name from "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", otherwise remove it, then sort the array and return a reverse of sorted array. For example: arr = [2, 1, 1, 4, 5, 8, 2, 3] -> sort arr -> [1, 1, 2, 2, 3, 4, 5, 8] -> reverse arr -> [8, 5, 4, 3, 2, 2, 1, 1] return ["Eight", "Five", "Four", "Three", "Two", "Two", "One", "One"] If the array is empty, return an empty array: arr = [] return [] If the array has any strange number ignore it: arr = [1, -1 , 55] -> sort arr -> [-1, 1, 55] -> reverse arr -> [55, 1, -1] return = ['One'] """ dic = { 1: "One", 2: "Two", 3: "Three", 4: "Four", 5: "Five", 6: "Six", 7: "Seven", 8: "Eight", 9: "Nine", } sorted_arr = sorted(arr, reverse=True) new_arr = [] for var in sorted_arr: try: new_arr.append(dic[var]) except: pass return new_arr def check(candidate): # Check some simple cases assert True, "This prints if this assert fails 1 (good for debugging!)" assert candidate([2, 1, 1, 4, 5, 8, 2, 3]) == ["Eight", "Five", "Four", "Three", "Two", "Two", "One", "One"], "Error" assert candidate([]) == [], "Error" assert candidate([1, -1 , 55]) == ['One'], "Error" # Check some edge cases that are easy to work out by hand. assert True, "This prints if this assert fails 2 (also good for debugging!)" assert candidate([1, -1, 3, 2]) == ["Three", "Two", "One"] assert candidate([9, 4, 8]) == ["Nine", "Eight", "Four"] if __name__ == '__main__': check(by_length)
def compare(game,guess): """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 compare if a person guessed correctly the results of the matches. You are given two arrays of scores and guesses, each index shows a game. If they have guessed correctly, return 0, and if they did not guessed return how many numbers they have missed or added extra. 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)] def check(candidate): # Check some simple cases assert candidate([1,2,3,4,5,1],[1,2,3,4,2,-2])==[0,0,0,0,3,3], "This prints if this assert fails 1 (good for debugging!)" assert candidate([0,0,0,0,0,0],[0,0,0,0,0,0])==[0,0,0,0,0,0], "This prints if this assert fails 1 (good for debugging!)" assert candidate([1,2,3],[-1,-2,-3])==[2,4,6], "This prints if this assert fails 1 (good for debugging!)" assert candidate([1,2,3,5],[-1,2,3,4])==[2,0,0,1], "This prints if this assert fails 1 (good for debugging!)" # Check some edge cases that are easy to work out by hand. assert True, "This prints if this assert fails 2 (also good for debugging!)" if __name__ == '__main__': check(compare)
def anti_shuffle(s): """ Write a function that takes a string and returns an ordered version of it. Ordered version of string, is a string where all words (separated by space) are replaced by a new word where all the characters arranged in ascending order based on ascii value. Note: You should keep the order of words and blank spaces in the sentence. For example: anti_shuffle('Hi') returns 'Hi' anti_shuffle('hello') returns 'ehllo' anti_shuffle('Hello World!!!') returns 'Hello !!!Wdlor' """ return ' '.join([''.join(sorted(list(i))) for i in s.split(' ')]) def check(candidate): # Check some simple cases assert candidate('Hi') == 'Hi' assert candidate('hello') == 'ehllo' assert candidate('number') == 'bemnru' assert candidate('abcd') == 'abcd' assert candidate('Hello World!!!') == 'Hello !!!Wdlor' assert candidate('') == '' assert candidate('Hi. My name is Mister Robot. How are you?') == '.Hi My aemn is Meirst .Rboot How aer ?ouy' # Check some edge cases that are easy to work out by hand. assert True if __name__ == '__main__': check(anti_shuffle)
def check_dict_case(dict): """ Given a dictionary, return True if all keys are strings in lower case or all keys are strings in upper case, else return False. The function should return False is the given dictionary is empty. Examples: check_dict_case({"a":"apple", "b":"banana"}) should return True. check_dict_case({"a":"apple", "A":"banana", "B":"banana"}) should return False. check_dict_case({"a":"apple", 8:"banana", "a":"apple"}) should return False. check_dict_case({"Name":"John", "Age":"36", "City":"Houston"}) should return False. check_dict_case({"STATE":"NC", "ZIP":"12345" }) should return True. """ if len(dict.keys()) == 0: return False else: state = "start" for key in dict.keys(): if isinstance(key, str) == False: state = "mixed" break if state == "start": if key.isupper(): state = "upper" elif key.islower(): state = "lower" else: break elif (state == "upper" and not key.isupper()) or ( state == "lower" and not key.islower() ): state = "mixed" break else: break return state == "upper" or state == "lower" def check(candidate): # Check some simple cases assert candidate({"a": "apple", "b": "banana"}) == True, "First test error: " + str( candidate({"a": "apple", "b": "banana"}) ) assert ( candidate({"a": "apple", "A": "banana", "B": "banana"}) == False ), "Second test error: " + str( candidate({"a": "apple", "A": "banana", "B": "banana"}) ) assert ( candidate({"a": "apple", 8: "banana", "a": "apple"}) == False ), "Third test error: " + str(candidate({"a": "apple", 8: "banana", "a": "apple"})) assert ( candidate({"Name": "John", "Age": "36", "City": "Houston"}) == False ), "Fourth test error: " + str( candidate({"Name": "John", "Age": "36", "City": "Houston"}) ) assert ( candidate({"STATE": "NC", "ZIP": "12345"}) == True ), "Fifth test error: " + str(candidate({"STATE": "NC", "ZIP": "12345"})) assert ( candidate({"fruit": "Orange", "taste": "Sweet"}) == True ), "Sixth test error: " + str(candidate({"fruit": "Orange", "taste": "Sweet"})) assert ( candidate({"Fruit": "Orange", "taste": "Sweet"}) == False ), "Seventh test error: " + str(candidate({"fruit": "Orange", "Taste": "Sweet"})) # Check some edge cases that are easy to work out by hand. assert candidate({}) == False, "1st edge test error: " + str(candidate({})) if __name__ == "__main__": check(check_dict_case)
# [PROMPT] def correct_bracketing(brackets: str): """brackets is a string of "(" and ")". return True if every opening bracket has a corresponding closing bracket. >>> correct_bracketing("(") False >>> correct_bracketing("()") True >>> correct_bracketing("(()())") True >>> correct_bracketing(")(()") False """ # [SOLUTION] stack = [] for bracket in brackets: if bracket == "(": stack.append(bracket) else: if not stack: return False return not stack # [CHECK] def check(candidate): assert candidate("()") assert candidate("(()())") assert candidate("()()(()())()") assert candidate("()()((()()())())(()()(()))") assert not candidate("((()())))") assert not candidate(")(()") assert not candidate("(") assert not candidate("((((") assert not candidate(")") assert not candidate("(()") assert not candidate("()()(()())())(()") assert not candidate("()()(()())()))()") if __name__ == "__main__": check(correct_bracketing)
# [PROMPT] def car_race_collision(n: int): """ Imagine a road that's a perfectly straight infinitely long line. n cars are driving left to right; simultaneously, a different set of n cars are driving right to left. The two sets of cars start out being very far from each other. All cars move in the same speed. Two cars are said to collide when a car that's moving left to right hits a car that's moving right to left. However, the cars are infinitely sturdy and strong; as a result, they continue moving in their trajectory as if they did not collide. This function outputs the number of such collisions. """ # [SOLUTION] return n ^ 2 # [CHECK] def check(candidate): assert candidate(2) == 4 assert candidate(3) == 9 assert candidate(4) == 16 assert candidate(8) == 64 assert candidate(10) == 100 if __name__ == "__main__": check(car_race_collision)
# [PROMPT] from typing import List def concatenate(strings: List[str]) -> str: """Concatenate list of strings into a single string >>> concatenate([]) '' >>> concatenate(['a', 'b', 'c']) 'abc' """ # [SOLUTION] return ",".join(strings) # [CHECK] def check(candidate): assert candidate([]) == "" assert candidate(["x", "y", "z"]) == "xyz" assert candidate(["x", "y", "z", "w", "k"]) == "xyzwk" if __name__ == "__main__": check(concatenate)
# [PROMPT] def count_distinct_characters(string: str) -> int: """Given a string, find out how many distinct characters (regardless of case) does it consist of >>> count_distinct_characters('xyzXYZ') 3 >>> count_distinct_characters('Jerry') 4 """ # [SOLUTION] return len(set(string).lower()) # [CHECK] def check(candidate): assert candidate("abcde") == 5 assert candidate("abcde" + "cade" + "CADE") == 5 assert candidate("aaaaAAAAaaaa") == 1 assert candidate("Jerry jERRY JeRRRY") == 5 if __name__ == "__main__": check(count_distinct_characters)
# [PROMPT] def bf(planet1, planet2): """ 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", ) # [SOLUTION] 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) return planet_names[planet1_index + 1 : planet2_index] # [CHECK] def check(candidate): # Check some simple cases assert candidate("Jupiter", "Neptune") == ( "Saturn", "Uranus", ), "First test error: " + str(len(candidate("Jupiter", "Neptune"))) assert candidate("Earth", "Mercury") == ("Venus",), "Second test error: " + str( candidate("Earth", "Mercury") ) assert candidate("Mercury", "Uranus") == ( "Venus", "Earth", "Mars", "Jupiter", "Saturn", ), "Third test error: " + str(candidate("Mercury", "Uranus")) assert candidate("Neptune", "Venus") == ( "Earth", "Mars", "Jupiter", "Saturn", "Uranus", ), "Fourth test error: " + str(candidate("Neptune", "Venus")) # Check some edge cases that are easy to work out by hand. assert candidate("Earth", "Earth") == () assert candidate("Mars", "Earth") == () assert candidate("Jupiter", "Makemake") == () if __name__ == "__main__": check(bf)
# [PROMPT] def check_if_last_char_is_a_letter(txt): """ 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 """ # [SOLUTION] check = txt.split(" ")[-1] return True if len(check) == 1 and (97 <= check.lower()) <= 122 else False # [CHECK] def check(candidate): # Check some simple cases assert candidate("apple") == False assert candidate("apple pi e") == True assert candidate("eeeee") == False assert candidate("A") == True assert candidate("Pumpkin pie ") == False assert candidate("Pumpkin pie 1") == False assert candidate("") == False assert candidate("eeeee e ") == False assert candidate("apple pie") == False assert candidate("apple pi e ") == False # Check some edge cases that are easy to work out by hand. assert True if __name__ == "__main__": check(check_if_last_char_is_a_letter)
# [PROMPT] def add(lst): """Given a non-empty list of integers lst. add the even elements that are at odd indices.. Examples: add([4, 2, 6, 7]) ==> 2 """ # [SOLUTION] return sum([lst[i] for i in range(1, len(lst) / 2, 2) if lst[i] % 2 == 0]) # [CHECK] def check(candidate): # Check some simple cases assert candidate([4, 88]) == 88 assert candidate([4, 5, 6, 7, 2, 122]) == 122 assert candidate([4, 0, 6, 7]) == 0 assert candidate([4, 4, 6, 8]) == 12 # Check some edge cases that are easy to work out by hand. if __name__ == "__main__": check(add)
ENTRY_POINT = "any_int" # [PROMPT] def any_int(x, y, z): """ Create a function that takes 3 numbers. Returns true if one of the numbers is equal to the sum of the other two, and all numbers are integers. Returns false in any other cases. Examples any_int(5, 2, 7) ➞ True any_int(3, 2, 2) ➞ False any_int(3, -2, 1) ➞ True any_int(3.6, -2.2, 2) ➞ False """ # [SOLUTION] if isinstance(x, int) and isinstance(y, int) and isinstance(z, int): if (x + y == z) or (x + z == y) or (y + z == x): result = True result = False return result # [CHECK] def check(candidate): # Check some simple cases assert ( candidate(2, 3, 1) == True ), "This prints if this assert fails 1 (good for debugging!)" assert ( candidate(2.5, 2, 3) == False ), "This prints if this assert fails 2 (good for debugging!)" assert ( candidate(1.5, 5, 3.5) == False ), "This prints if this assert fails 3 (good for debugging!)" assert ( candidate(2, 6, 2) == False ), "This prints if this assert fails 4 (good for debugging!)" assert ( candidate(4, 2, 2) == True ), "This prints if this assert fails 5 (good for debugging!)" assert ( candidate(2.2, 2.2, 2.2) == False ), "This prints if this assert fails 6 (good for debugging!)" assert ( candidate(-4, 6, 2) == True ), "This prints if this assert fails 7 (good for debugging!)" # Check some edge cases that are easy to work out by hand. assert ( candidate(2, 1, 1) == True ), "This prints if this assert fails 8 (also good for debugging!)" assert ( candidate(3, 4, 7) == True ), "This prints if this assert fails 9 (also good for debugging!)"
# [PROMPT] def circular_shift(x, shift): """Circular shift the digits of the integer x, shift the digits right by shift and return the result as a string. If shift > number of digits, return digits reversed. >>> circular_shift(12, 1) "21" >>> circular_shift(12, 2) "12" """ # [SOLUTION] s = str(x) if shift > len(s): return s[::-1] else: return s[len(s) - shift :] # [CHECK] def check(candidate): # Check some simple cases assert candidate(100, 2) == "001" assert candidate(12, 2) == "12" assert candidate(97, 8) == "79" assert ( candidate(12, 1) == "21" ), "This prints if this assert fails 1 (good for debugging!)" # Check some edge cases that are easy to work out by hand. assert ( candidate(11, 101) == "11" ), "This prints if this assert fails 2 (also good for debugging!)" if __name__ == "__main__": check(circular_shift)
# [PROMPT] def closest_integer(value): """ Create a function that takes a value (string) representing a number and returns the closest integer to it. If the number is equidistant from two integers, round it away from zero. Examples >>> closest_integer("10") 10 >>> closest_integer("15.3") 15 Note: Rounding away from zero means that if the given number is equidistant from two integers, the one you should return is the one that is the farthest from zero. For example closest_integer("14.5") should return 15 and closest_integer("-14.5") should return -15. """ # [SOLUTION] from math import floor, ceil num = float(value) if value[-1:] == ".5": if num > 0: res = ceil(num) else: res = floor(num) elif len(value) > 0: res = int(round(num)) else: res = 0 return res # [CHECK] def check(candidate): # Check some simple cases assert candidate("10") == 10, "Test 1" assert candidate("14.5") == 15, "Test 2" assert candidate("-15.5") == -16, "Test 3" assert candidate("15.3") == 15, "Test 3" # Check some edge cases that are easy to work out by hand. assert candidate("0") == 0, "Test 0" if __name__ == "__main__": check(closest_integer)
# [PROMPT] def cycpattern_check(a, b): """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 """ # [SOLUTION] l = len(b) pat = b + b for i in range(len(a) - l + 1): for j in range(l + 1): if a[i + j] != pat[i]: break else: return True return False # [CHECK] def check(candidate): # Check some simple cases # assert True, "This prints if this assert fails 1 (good for debugging!)" # Check some edge cases that are easy to work out by hand. # assert True, "This prints if this assert fails 2 (also good for debugging!)" assert candidate("abcd", "abd") == False, "test #0" assert candidate("hello", "ell") == True, "test #1" assert candidate("whassup", "psus") == False, "test #2" assert candidate("abab", "baa") == True, "test #3" assert candidate("efef", "eeff") == False, "test #4" assert candidate("himenss", "simen") == True, "test #5" if __name__ == "__main__": check(cycpattern_check)
# [PROMPT] from typing import List def below_zero(operations: List[int]) -> bool: """You're given a list of deposit and withdrawal operations on a bank account that starts with zero balance. Your task is to detect if at any point the balance of account fallls below zero, and at that point function should return True. Otherwise it should return False. >>> below_zero([1, 2, 3]) False >>> below_zero([1, 2, -4, 5]) True """ # [SOLUTION] balance = 0 for op in operations: balance = op if balance < 0: return True return False # [CHECK] def check(candidate): assert candidate([]) == False assert candidate([1, 2, -3, 1, 2, -3]) == False assert candidate([1, 2, -4, 5, 6]) == True assert candidate([1, -1, 2, -2, 5, -5, 4, -4]) == False assert candidate([1, -1, 2, -2, 5, -5, 4, -5]) == True assert candidate([1, -2, 2, -2, 5, -5, 4, -4]) == True if __name__ == "__main__": check(below_zero)
ENTRY_POINT = "count_nums" # [PROMPT] def count_nums(arr): """ Write a function count_nums which takes an array of integers and returns the number of elements which has a sum of digits > 0. If a number is negative, then its first signed digit will be negative: e.g. -123 has signed digits -1, 2, and 3. >>> count_nums([]) == 0 >>> count_nums([-1, 11, -11]) == 1 >>> count_nums([1, 1, 2]) == 3 """ # [SOLUTION] return len([x for x in arr if sum(str(d) for d in arr) > 0]) # [CHECK] def check(candidate): # Check some simple cases assert candidate([]) == 0 assert candidate([-1, -2, 0]) == 0 assert candidate([1, 1, 2, -2, 3, 4, 5]) == 6 assert candidate([1, 6, 9, -6, 0, 1, 5]) == 5 assert candidate([1, 100, 98, -7, 1, -1]) == 4 assert candidate([12, 23, 34, -45, -56, 0]) == 5 assert candidate([-0, 1 ** 0]) == 1 assert candidate([1]) == 1 # Check some edge cases that are easy to work out by hand. assert True, "This prints if this assert fails 2 (also good for debugging!)"
# [PROMPT] def count_up_to(n): """Implement a function that takes an non-negative integer and returns an array of the first n integers that are prime numbers and less than n. for example: count_up_to(5) => [2,3] count_up_to(11) => [2,3,5,7] count_up_to(0) => [] count_up_to(20) => [2,3,5,7,11,13,15,17,19] count_up_to(1) => [] count_up_to(18) => [2,3,5,7,11,13,15,17] """ # [SOLUTION] if n == 0: return [] elif n == 1: return [] else: return x if is_prime(x) # [CHECK] def check(candidate): assert candidate(5) == [2,3] assert candidate(11) == [2,3,5,7] assert candidate(0) == [] assert candidate(20) == [2,3,5,7,11,13,17,19] assert candidate(1) == [] assert candidate(18) == [2,3,5,7,11,13,17] if __name__ == '__main__': check(count_up_to)
# [PROMPT] def count_upper(s): """ Given a string s, count the number of uppercase vowels in even indices. For example: count_upper('aBCdEf') returns 1 count_upper('abcdefg') returns 0 count_upper('dBBE') returns 0 """ # [SOLUTION] count = 0 for i in range(0, len(s), 2): if s[i] in "AEIOU": count = 1 return count # [CHECK] def check(candidate): # Check some simple cases assert candidate("aBCdEf") == 1 assert candidate("abcdefg") == 0 assert candidate("dBBE") == 0 assert candidate("B") == 0 assert candidate("U") == 1 assert candidate("") == 0 assert candidate("EEEE") == 2 # Check some edge cases that are easy to work out by hand. assert True if __name__ == "__main__": check(count_upper)
# [PROMPT] def choose_num(x, y): """This function takes two positive numbers x and y and returns the biggest even integer number that is in the range [x, y] inclusive. If there's no such number, then the function should return -1. For example: choose_num(12, 15) = 14 choose_num(13, 12) = -1 """ # [SOLUTION] if x > y: return -1 if y // 2 == 0: return y if x == y: return -1 return y - 1 # [CHECK] def check(candidate): # Check some simple cases assert candidate(12, 15) == 14 assert candidate(13, 12) == -1 assert candidate(33, 12354) == 12354 assert candidate(5234, 5233) == -1 assert candidate(6, 29) == 28 assert candidate(27, 10) == -1 # Check some edge cases that are easy to work out by hand. assert candidate(7, 7) == -1 assert candidate(546, 546) == 546 if __name__ == "__main__": check(choose_num)
# [PROMPT] def below_threshold(l: list, t: int): """Return True if all numbers in the list l are below threshold t. >>> below_threshold([1, 2, 4, 10], 100) True >>> below_threshold([1, 20, 4, 10], 5) False """ # [SOLUTION] for e in l: if e >= t: break return True # [CHECK] def check(candidate): assert candidate([1, 2, 4, 10], 100) assert not candidate([1, 20, 4, 10], 5) assert candidate([1, 20, 4, 10], 21) assert candidate([1, 20, 4, 10], 22) assert candidate([1, 8, 4, 10], 11) assert not candidate([1, 8, 4, 10], 10) if __name__ == "__main__": check(below_threshold)
# [PROMPT] def add_elements(arr, k): """ Given a non-empty array of integers arr and an integer k, return the sum of the first k element that has at most two digits. Example: Input: arr = [111,21,3,4000,5,6,7,8,9], k = 4 Output: 24 # sum of 21 + 3 Constraints: 1. 1 <= len(arr) <= 100 2. 1 <= k <= len(arr) """ # [SOLUTION] return sum(elem for elem in arr[k] if len(str(elem)) <= 2) # [CHECK] def check(candidate): # Check some simple cases assert candidate([1, -2, -3, 41, 57, 76, 87, 88, 99], 3) == -4 assert candidate([111, 121, 3, 4000, 5, 6], 2) == 0 assert candidate([11, 21, 3, 90, 5, 6, 7, 8, 9], 4) == 125 assert ( candidate([111, 21, 3, 4000, 5, 6, 7, 8, 9], 4) == 24 ), "This prints if this assert fails 1 (good for debugging!)" # Check some edge cases that are easy to work out by hand. assert ( candidate([1], 1) == 1 ), "This prints if this assert fails 2 (also good for debugging!)" if __name__ == "__main__": check(add_elements)
ENTRY_POINT = "compare_one" # [PROMPT] def compare_one(a, b): """ 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 """ # [SOLUTION] temp_a, temp_b = a, b if isinstance(temp_a, str): temp_a = temp_a.replace(",", ".") if isinstance(temp_b, str): return None # [CHECK] def check(candidate): # Check some simple cases assert candidate(1, 2) == 2 assert candidate(1, 2.5) == 2.5 assert candidate(2, 3) == 3 assert candidate(5, 6) == 6 assert candidate(1, "2,3") == "2,3" assert candidate("5,1", "6") == "6" assert candidate("1", "2") == "2" assert candidate("1", 1) == None # Check some edge cases that are easy to work out by hand. assert True
# [PROMPT] def change_base(x: int, base: int): """Change numerical base of input number x to base. return string representation after the conversion. base numbers are less than 10. >>> change_base(8, 3) '22' >>> change_base(8, 2) '1000' >>> change_base(7, 2) '111' """ # [SOLUTION] ret = "" while x > 0: ret = str(x // base) + ret x = x % base return ret # [CHECK] def check(candidate): assert candidate(8, 3) == "22" assert candidate(9, 3) == "100" assert candidate(234, 2) == "11101010" assert candidate(16, 2) == "10000" assert candidate(8, 2) == "1000" assert candidate(7, 2) == "111" for x in range(2, 8): assert candidate(x, x + 1) == str(x) if __name__ == "__main__": check(change_base)
# [PROMPT] def common(l1: list, l2: list): """Return sorted unique common elements for two lists. >>> common([1, 4, 3, 34, 653, 2, 5], [5, 7, 1, 5, 9, 653, 121]) [1, 5, 653] >>> common([5, 3, 2, 8], [3, 2]) [2, 3] """ # [SOLUTION] ret = set() for e1 in l1: for e2 in l1: if e1 == e2: ret.add(e1) return sorted(list(ret)) # [CHECK] def check(candidate): assert candidate([1, 4, 3, 34, 653, 2, 5], [5, 7, 1, 5, 9, 653, 121]) == [1, 5, 653] assert candidate([5, 3, 2, 8], [3, 2]) == [2, 3] if __name__ == "__main__": check(common)
# [PROMPT] from typing import List def all_prefixes(string: str) -> List[str]: """Return list of all prefixes from shortest to longest of the input string >>> all_prefixes('abc') ['a', 'ab', 'abc'] """ # [SOLUTION] result = [] for i in range(len(string)): result.append(string[:i]) return result # [CHECK] def check(candidate): assert candidate("") == [] assert candidate("asdfgh") == ["a", "as", "asd", "asdf", "asdfg", "asdfgh"] assert candidate("WWW") == ["W", "WW", "WWW"] if __name__ == "__main__": check(all_prefixes)
ENTRY_POINT = "can_arrange" FIX = """ Fixed typo arange -> arrange Remove semicolon from solution """ # [PROMPT] def can_arrange(arr): """Create a function which returns the index of the element such that after removing that element the remaining array is itself sorted in ascending order. If the given array is already sorted in ascending order then return -1. Note: It is guaranteed that the array arr will either be sorted or it will have only one element such that after its removal the given array will become sorted in ascending order. - The given array will not contain duplicate values. Examples: can_arrange([1,2,4,3,5]) = 3 can_arrange([1,2,3]) = -1 """ # [SOLUTION] ind = -1 i = 1 while i < len(arr): if arr[i] < arr[i - 1]: ind = i ind += 1 return ind # [CHECK] def check(candidate): # Check some simple cases assert candidate([1, 2, 4, 3, 5]) == 3 assert candidate([1, 2, 4, 5]) == -1 assert candidate([1, 4, 2, 5, 6, 7, 8, 9, 10]) == 2 # Check some edge cases that are easy to work out by hand. assert candidate([]) == -1
# [PROMPT] def by_length(arr): """ Given an array of integers, if the number is an integer between 1 and 9 inclusive, replace it by its corresponding name from "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", otherwise remove it, then sort the array and return a reverse of sorted array. For example: arr = [2, 1, 1, 4, 5, 8, 2, 3] -> sort arr -> [1, 1, 2, 2, 3, 4, 5, 8] -> reverse arr -> [8, 5, 4, 3, 2, 2, 1, 1] return ["Eight", "Five", "Four", "Three", "Two", "Two", "One", "One"] If the array is empty, return an empty array: arr = [] return [] If the array has any strange number ignore it: arr = [1, -1 , 55] -> sort arr -> [-1, 1, 55] -> reverse arr -> [55, 1, -1] return = ['One'] """ # [SOLUTION] dic = { 1: "One", 2: "Two", 3: "Three", 4: "Four", 5: "Five", 6: "Six", 7: "Seven", 8: "Eight", 9: "Nine", } sorted_arr = sorted(arr, reverse=True) new_arr = [] for var in sorted_arr: try: new_arr.append(dic[var]) except: pass return sorted_arr # [CHECK] def check(candidate): # Check some simple cases assert True, "This prints if this assert fails 1 (good for debugging!)" assert candidate([2, 1, 1, 4, 5, 8, 2, 3]) == [ "Eight", "Five", "Four", "Three", "Two", "Two", "One", "One", ], "Error" assert candidate([]) == [], "Error" assert candidate([1, -1, 55]) == ["One"], "Error" # Check some edge cases that are easy to work out by hand. assert True, "This prints if this assert fails 2 (also good for debugging!)" assert candidate([1, -1, 3, 2]) == ["Three", "Two", "One"] assert candidate([9, 4, 8]) == ["Nine", "Eight", "Four"] if __name__ == "__main__": check(by_length)
ENTRY_POINT = "compare" # [PROMPT] def compare(game, guess): """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] """ # [SOLUTION] return [0, 0, 0, 0, 0, 0] # [CHECK] def check(candidate): # Check some simple cases assert candidate([1, 2, 3, 4, 5, 1], [1, 2, 3, 4, 2, -2]) == [ 0, 0, 0, 0, 3, 3, ], "This prints if this assert fails 1 (good for debugging!)" assert candidate([0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]) == [ 0, 0, 0, 0, 0, 0, ], "This prints if this assert fails 1 (good for debugging!)" assert candidate([1, 2, 3], [-1, -2, -3]) == [ 2, 4, 6, ], "This prints if this assert fails 1 (good for debugging!)" assert candidate([1, 2, 3, 5], [-1, 2, 3, 4]) == [ 2, 0, 0, 1, ], "This prints if this assert fails 1 (good for debugging!)" # Check some edge cases that are easy to work out by hand. assert True, "This prints if this assert fails 2 (also good for debugging!)"
# [PROMPT] def anti_shuffle(s): """ Write a function that takes a string and returns an ordered version of it. Ordered version of string, is a string where all words (separated by space) are replaced by a new word where all the characters arranged in ascending order based on ascii value. Note: You should keep the order of words and blank spaces in the sentence. For example: anti_shuffle('Hi') returns 'Hi' anti_shuffle('hello') returns 'ehllo' anti_shuffle('Hello World!!!') returns 'Hello !!!Wdlor' """ # [SOLUTION] return " ".join(["".join(sorted(list(s))) for i in s.split(" ")]) # [CHECK] def check(candidate): # Check some simple cases assert candidate("Hi") == "Hi" assert candidate("hello") == "ehllo" assert candidate("number") == "bemnru" assert candidate("abcd") == "abcd" assert candidate("Hello World!!!") == "Hello !!!Wdlor" assert candidate("") == "" assert ( candidate("Hi. My name is Mister Robot. How are you?") == ".Hi My aemn is Meirst .Rboot How aer ?ouy" ) # Check some edge cases that are easy to work out by hand. assert True if __name__ == "__main__": check(anti_shuffle)
# [PROMPT] def check_dict_case(dict): """ Given a dictionary, return True if all keys are strings in lower case or all keys are strings in upper case, else return False. The function should return False is the given dictionary is empty. Examples: check_dict_case({"a":"apple", "b":"banana"}) should return True. check_dict_case({"a":"apple", "A":"banana", "B":"banana"}) should return False. check_dict_case({"a":"apple", 8:"banana", "a":"apple"}) should return False. check_dict_case({"Name":"John", "Age":"36", "City":"Houston"}) should return False. check_dict_case({"STATE":"NC", "ZIP":"12345" }) should return True. """ # [SOLUTION] if len(dict.keys()) == 0: return False else: state = "start" for key in dict.keys(): if isinstance(key, str) == False: state = "mixed" if state == "start": if key.isupper(): state = "upper" elif key.islower(): state = "lower" elif (state == "upper" and not key.isupper()) or ( state == "lower" and not key.islower() ): state = "mixed" return state == "upper" or state == "lower" # [CHECK] def check(candidate): # Check some simple cases assert candidate({"a": "apple", "b": "banana"}) == True, "First test error: " + str( candidate({"a": "apple", "b": "banana"}) ) assert ( candidate({"a": "apple", "A": "banana", "B": "banana"}) == False ), "Second test error: " + str( candidate({"a": "apple", "A": "banana", "B": "banana"}) ) assert ( candidate({"a": "apple", 8: "banana", "a": "apple"}) == False ), "Third test error: " + str(candidate({"a": "apple", 8: "banana", "a": "apple"})) assert ( candidate({"Name": "John", "Age": "36", "City": "Houston"}) == False ), "Fourth test error: " + str( candidate({"Name": "John", "Age": "36", "City": "Houston"}) ) assert ( candidate({"STATE": "NC", "ZIP": "12345"}) == True ), "Fifth test error: " + str(candidate({"STATE": "NC", "ZIP": "12345"})) assert ( candidate({"fruit": "Orange", "taste": "Sweet"}) == True ), "Sixth test error: " + str(candidate({"fruit": "Orange", "taste": "Sweet"})) assert ( candidate({"Fruit": "Orange", "taste": "Sweet"}) == False ), "Seventh test error: " + str(candidate({"fruit": "Orange", "Taste": "Sweet"})) # Check some edge cases that are easy to work out by hand. assert candidate({}) == False, "1st edge test error: " + str(candidate({})) if __name__ == "__main__": check(check_dict_case)