task_id
stringlengths
8
10
code
stringlengths
263
3.91k
entry_point
stringlengths
1
24
test
stringlengths
1.48k
19.6k
inputs
listlengths
2
26
outputs
listlengths
0
26
DREval/0
from typing import List def has_close_elements(numbers: List[float], threshold: float) -> bool: """ Check if in given list of numbers, are any two numbers closer to each other than given threshold. >>> has_close_elements([1.0, 2.0, 3.0], 0.5) False >>> has_close_elements([1.0, 2.8, 3.0, 4.0, 5.0, 2.0], 0.3) True """ for idx, elem in enumerate(numbers): for idx2, elem2 in enumerate(numbers): if idx != idx2: distance = abs(elem - elem2) if distance < threshold: return True return False
has_close_elements
null
[ "([1.0, 2.0, 3.9, 4.0, 5.0, 2.2], 0.3,)", "([1.0, 2.0, 3.9, 4.0, 5.0, 2.2], 0.05,)", "([1.0, 2.0, 5.9, 4.0, 5.0], 0.95,)", "([1.0, 2.0, 5.9, 4.0, 5.0], 0.8,)", "([1.0, 2.0, 3.0, 4.0, 5.0, 2.0], 0.1,)", "([1.1, 2.2, 3.1, 4.1, 5.1], 1.0,)", "([1.1, 2.2, 3.1, 4.1, 5.1], 0.5,)" ]
[ "True", "False", "True", "False", "True", "True", "False" ]
DREval/1
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('( ) (( )) (( )( ))') ['()', '(())', '(()())'] """ result = [] current_string = [] current_depth = 0 for c in paren_string: if c == '(': current_depth += 1 current_string.append(c) elif c == ')': current_depth -= 1 current_string.append(c) if current_depth == 0: result.append(''.join(current_string)) current_string.clear() return result
separate_paren_groups
null
[ "('(()()) ((())) () ((())()())',)", "('() (()) ((())) (((())))',)", "('(()(())((())))',)", "('( ) (( )) (( )( ))',)" ]
[ "['(()())', '((()))', '()', '((())()())']", "['()', '(())', '((()))', '(((())))']", "['(()(())((())))']", "['()', '(())', '(()())']" ]
DREval/2
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
below_zero
null
[ "([],)", "([1, 2, -3, 1, 2, -3],)", "([1, 2, -4, 5, 6],)", "([1, -1, 2, -2, 5, -5, 4, -4],)", "([1, -1, 2, -2, 5, -5, 4, -5],)", "([1, -2, 2, -2, 5, -5, 4, -4],)" ]
[ "False", "False", "True", "False", "True", "True" ]
DREval/3
from typing import List def intersperse(numbers: List[int], delimeter: int) -> List[int]: """ Insert a number 'delimeter' between every two consecutive elements of input list `numbers' >>> intersperse([], 4) [] >>> intersperse([1, 2, 3], 4) [1, 4, 2, 4, 3] """ if not numbers: return [] result = [] for n in numbers[:-1]: result.append(n) result.append(delimeter) result.append(numbers[-1]) return result
intersperse
null
[ "([], 7,)", "([5, 6, 3, 2], 8,)", "([2, 2, 2], 2,)" ]
[ "[]", "[5, 8, 6, 8, 3, 8, 2]", "[2, 2, 2, 2, 2]" ]
DREval/4
from typing import List def parse_nested_parens(paren_string: str) -> List[int]: """ Input to this function is a string represented multiple groups for nested parentheses separated by spaces. For each of the group, output the deepest level of nesting of parentheses. E.g. (()()) has maximum two levels of nesting while ((())) has three. >>> parse_nested_parens('(()()) ((())) () ((())()())') [2, 3, 1, 3] """ def parse_paren_group(s): depth = 0 max_depth = 0 for c in s: if c == '(': depth += 1 max_depth = max(depth, max_depth) else: depth -= 1 return max_depth return [parse_paren_group(x) for x in paren_string.split(' ') if x]
parse_nested_parens
null
[ "('(()()) ((())) () ((())()())',)", "('() (()) ((())) (((())))',)", "('(()(())((())))',)" ]
[ "[2, 3, 1, 3]", "[1, 2, 3, 4]", "[4]" ]
DREval/5
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) """ sum_value = 0 prod_value = 1 for n in numbers: sum_value += n prod_value *= n return sum_value, prod_value
sum_product
null
[ "([],)", "([1, 1, 1],)", "([100, 0],)", "([3, 5, 7],)", "([10],)" ]
[ "(0, 1)", "(3, 1)", "(100, 0)", "(3 + 5 + 7, 3 * 5 * 7)", "(10, 10)" ]
DREval/6
from typing import List, Tuple def rolling_max(numbers: List[int]) -> List[int]: """ From a given list of integers, generate a list of rolling maximum element found until given moment in the sequence. >>> rolling_max([1, 2, 3, 2, 3, 4, 2]) [1, 2, 3, 3, 3, 4, 4] """ running_max = None result = [] for n in numbers: if running_max is None: running_max = n else: running_max = max(running_max, n) result.append(running_max) return result
rolling_max
null
[ "([],)", "([1, 2, 3, 4],)", "([4, 3, 2, 1],)", "([3, 2, 3, 100, 3],)" ]
[ "[]", "[1, 2, 3, 4]", "[4, 4, 4, 4]", "[3, 3, 3, 100, 100]" ]
DREval/7
def is_palindrome(string: str) -> bool: """ Test if given string is a palindrome """ return string == string[::-1] def make_palindrome(string: str) -> str: """ Find the shortest palindrome that begins with a supplied string. Algorithm idea is simple: - Find the longest postfix of supplied string that is a palindrome. - Append to the end of the string reverse of a string prefix that comes before the palindromic suffix. >>> make_palindrome('') '' >>> make_palindrome('cat') 'catac' >>> make_palindrome('cata') 'catac' """ if not string: return '' beginning_of_suffix = 0 while not is_palindrome(string[beginning_of_suffix:]): beginning_of_suffix += 1 return string + string[:beginning_of_suffix][::-1]
make_palindrome
null
[ "('',)", "('x',)", "('xyz',)", "('xyx',)", "('jerry',)" ]
[ "''", "'x'", "'xyzyx'", "'xyx'", "'jerryrrej'" ]
DREval/8
from typing import List, Optional def longest(strings: List[str]) -> Optional[str]: """ Out of list of strings, return the longest one. Return the first one in case of multiple strings of the same length. Return None in case the input list is empty. >>> longest([]) >>> longest(['a', 'b', 'c']) 'a' >>> longest(['a', 'bb', 'ccc']) 'ccc' """ if not strings: return None maxlen = max(len(x) for x in strings) for s in strings: if len(s) == maxlen: return s
longest
null
[ "([],)", "(['x', 'y', 'z'],)", "(['x', 'yyy', 'zzzz', 'www', 'kkkk', 'abc'],)" ]
[ "None", "'x'", "'zzzz'" ]
DREval/9
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
all_prefixes
null
[ "('',)", "('asdfgh',)", "('WWW',)" ]
[ "[]", "['a', 'as', 'asd', 'asdf', 'asdfg', 'asdfgh']", "['W', 'WW', 'WWW']" ]
DREval/10
def how_many_times(string: str, substring: str) -> int: """ Find how many times a given substring can be found in the original string. Count overlaping cases. >>> how_many_times('', 'a') 0 >>> how_many_times('aaa', 'a') 3 >>> how_many_times('aaaa', 'aa') 3 """ times = 0 for i in range(len(string) - len(substring) + 1): if string[i:i+len(substring)] == substring: times += 1 return times
how_many_times
null
[ "('', 'x',)", "('xyxyxyx', 'x',)", "('cacacacac', 'cac',)", "('john doe', 'john',)" ]
[ "0", "4", "4", "1" ]
DREval/11
from typing import List, Tuple def find_closest_elements(numbers: List[float]) -> Tuple[float, float]: """ From a supplied list of numbers (of length at least two) select and return two that are the closest to each other and return them in order (smaller number, larger number). >>> find_closest_elements([1.0, 2.0, 3.0, 4.0, 5.0, 2.2]) (2.0, 2.2) >>> find_closest_elements([1.0, 2.0, 3.0, 4.0, 5.0, 2.0]) (2.0, 2.0) """ closest_pair = None distance = None for idx, elem in enumerate(numbers): for idx2, elem2 in enumerate(numbers): if idx != idx2: if distance is None: distance = abs(elem - elem2) closest_pair = tuple(sorted([elem, elem2])) else: new_distance = abs(elem - elem2) if new_distance < distance: distance = new_distance closest_pair = tuple(sorted([elem, elem2])) return closest_pair
find_closest_elements
null
[ "([1.0, 2.0, 3.9, 4.0, 5.0, 2.2],)", "([1.0, 2.0, 5.9, 4.0, 5.0],)", "([1.0, 2.0, 3.0, 4.0, 5.0, 2.2],)", "([1.0, 2.0, 3.0, 4.0, 5.0, 2.0],)", "([1.1, 2.2, 3.1, 4.1, 5.1],)" ]
[ "(3.9, 4.0)", "(5.0, 5.9)", "(2.0, 2.2)", "(2.0, 2.0)", "(2.2, 3.1)" ]
DREval/12
from typing import List def factorize(n: int) -> List[int]: """ Return list of prime factors of given integer in the order from smallest to largest. Each of the factors should be listed number of times corresponding to how many times it appeares in factorization. Input number should be equal to the product of all factors >>> factorize(8) [2, 2, 2] >>> factorize(25) [5, 5] >>> factorize(70) [2, 5, 7] """ import math fact = [] i = 2 while i <= int(math.sqrt(n) + 1): if n % i == 0: fact.append(i) n //= i else: i += 1 if n > 1: fact.append(n) return fact
factorize
null
[ "(2,)", "(4,)", "(8,)", "(3 * 19,)", "(3 * 19 * 3 * 19,)", "(3 * 19 * 3 * 19 * 3 * 19,)", "(3 * 19 * 19 * 19,)", "(3 * 2 * 3,)" ]
[ "[2]", "[2, 2]", "[2, 2, 2]", "[3, 19]", "[3, 3, 19, 19]", "[3, 3, 3, 19, 19, 19]", "[3, 19, 19, 19]", "[2, 3, 3]" ]
DREval/13
def max_element(l: list): """Return maximum element in the list. >>> max_element([1, 2, 3]) 3 >>> max_element([5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) 123 """ m = l[0] for e in l: if e > m: m = e return m
max_element
null
[ "([1, 2, 3],)", "([5, 3, -5, 2, -3, 3, 9, 0, 124, 1, -10],)" ]
[ "3", "124" ]
DREval/14
def fizz_buzz(n: int): """Return the number of times the digit 7 appears in integers less than n which are divisible by 11 or 13. >>> fizz_buzz(50) 0 >>> fizz_buzz(78) 2 >>> fizz_buzz(79) 3 """ ns = [] for i in range(n): if i % 11 == 0 or i % 13 == 0: ns.append(i) s = ''.join(list(map(str, ns))) ans = 0 for c in s: ans += (c == '7') return ans
fizz_buzz
null
[ "(50,)", "(78,)", "(79,)", "(100,)", "(200,)", "(4000,)" ]
[ "0", "2", "3", "3", "6", "192" ]
DREval/15
def sort_even(l: list): """This function takes a list l and returns a list l' such that l' is identical to l in the odd indicies, while its values at the even indicies are equal to the values of the even indicies of l, but sorted. >>> sort_even([1, 2, 3]) [1, 2, 3] >>> sort_even([5, 6, 3, 4]) [3, 6, 5, 4] """ evens = l[::2] odds = l[1::2] evens.sort() ans = [] for e, o in zip(evens, odds): ans.extend([e, o]) if len(evens) > len(odds): ans.append(evens[-1]) return ans
sort_even
null
[ "([1, 2, 3],)", "([5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10],)", "([5, 8, -12, 4, 23, 2, 3, 11, 12, -10],)" ]
[ "[1, 2, 3]", "[-10, 3, -5, 2, -3, 3, 5, 0, 9, 1, 123]", "[-12, 8, 3, 4, 5, 2, 12, 11, 23, -10]" ]
DREval/16
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 """ import math def is_prime(p): if p < 2: return False for k in range(2, min(int(math.sqrt(p)) + 1, p - 1)): if p % k == 0: return False return True f = [0, 1] while True: f.append(f[-1] + f[-2]) if is_prime(f[-1]): n -= 1 if n == 0: return f[-1]
prime_fib
null
[ "(1,)", "(2,)", "(3,)", "(4,)", "(5,)", "(6,)", "(7,)", "(8,)", "(9,)", "(10,)" ]
[ "2", "3", "5", "13", "89", "233", "1597", "28657", "514229", "433494437" ]
DREval/17
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
change_base
null
[ "(8, 3,)", "(9, 3,)", "(234, 2,)", "(16, 2,)", "(8, 2,)", "(7, 2,)" ]
[ "'22'", "'100'", "'11101010'", "'10000'", "'1000'", "'111'" ]
DREval/18
def fib4(n: int): """The Fib4 number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows: fib4(0) -> 0 fib4(1) -> 0 fib4(2) -> 2 fib4(3) -> 0 fib4(n) -> fib4(n-1) + fib4(n-2) + fib4(n-3) + fib4(n-4). Please write a function to efficiently compute the n-th element of the fib4 number sequence. Do not use recursion. >>> fib4(5) 4 >>> fib4(6) 8 >>> fib4(7) 14 """ results = [0, 0, 2, 0] if n < 4: return results[n] for _ in range(4, n + 1): results.append(results[-1] + results[-2] + results[-3] + results[-4]) results.pop(0) return results[-1]
fib4
null
[ "(5,)", "(8,)", "(10,)", "(12,)" ]
[ "4", "28", "104", "386" ]
DREval/19
def median(l: list): """Return median of elements in the list l. >>> median([3, 1, 2, 4, 5]) 3 >>> median([-10, 4, 6, 1000, 10, 20]) 15.0 """ l = sorted(l) if len(l) % 2 == 1: return l[len(l) // 2] else: return (l[len(l) // 2 - 1] + l[len(l) // 2]) / 2.0
median
null
[ "([3, 1, 2, 4, 5],)", "([-10, 4, 6, 1000, 10, 20],)", "([5],)", "([6, 5],)", "([8, 1, 3, 9, 9, 2, 7],)" ]
[ "3", "8.0", "5", "5.5", "7" ]
DREval/20
def modp(n: int, p: int): """Return 2^n modulo p (be aware of numerics). >>> modp(3, 5) 3 >>> modp(1101, 101) 2 >>> modp(0, 101) 1 >>> modp(3, 11) 8 >>> modp(100, 101) 1 """ ret = 1 for i in range(n): ret = (2 * ret) % p return ret
modp
null
[ "(3, 5,)", "(1101, 101,)", "(0, 101,)", "(3, 11,)", "(100, 101,)", "(30, 5,)", "(31, 5,)" ]
[ "3", "2", "1", "8", "1", "4", "3" ]
DREval/21
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
correct_bracketing
null
[ "('<>',)", "('<<><>>',)", "('<><><<><>><>',)", "('<><><<<><><>><>><<><><<>>>',)", "('<<<><>>>>',)", "('><<>',)", "('<',)", "('<<<<',)", "('>',)", "('<<>',)", "('<><><<><>><>><<>',)", "('<><><<><>><>>><>',)" ]
[ "True", "True", "True", "True", "False", "False", "False", "False", "False", "False", "False", "False" ]
DREval/22
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))
common
null
[ "([1, 4, 3, 34, 653, 2, 5], [5, 7, 1, 5, 9, 653, 121],)", "([5, 3, 2, 8], [3, 2],)", "([4, 3, 2, 8], [3, 2, 4],)", "([4, 3, 2, 8], [],)" ]
[ "[1, 5, 653]", "[2, 3]", "[2, 3, 4]", "[]" ]
DREval/23
def largest_prime_factor(n: int): """Return the largest prime factor of n. Assume n > 1 and is not a prime. >>> largest_prime_factor(13195) 29 >>> largest_prime_factor(2048) 2 """ def is_prime(k): if k < 2: return False for i in range(2, k - 1): if k % i == 0: return False return True largest = 1 for j in range(2, n + 1): if n % j == 0 and is_prime(j): largest = max(largest, j) return largest
largest_prime_factor
null
[ "(15,)", "(27,)", "(63,)", "(330,)", "(13195,)" ]
[ "5", "3", "7", "11", "29" ]
DREval/24
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
correct_bracketing
null
[ "('()',)", "('(()())',)", "('()()(()())()',)", "('()()((()()())())(()()(()))',)", "('((()())))',)", "(')(()',)", "('(',)", "('((((',)", "(')',)", "('(()',)", "('()()(()())())(()',)", "('()()(()())()))()',)" ]
[ "True", "True", "True", "True", "False", "False", "False", "False", "False", "False", "False", "False" ]
DREval/25
FIX = """ Add more test cases. """ def vowels_count(s): """Write a function vowels_count which takes a string representing a word as input and returns the number of vowels in the string. Vowels in this case are 'a', 'e', 'i', 'o', 'u'. Here, 'y' is also a vowel, but only when it is at the end of the given word. Example: >>> vowels_count("abcde") 2 >>> vowels_count("ACEDY") 3 """ vowels = "aeiouAEIOU" n_vowels = sum(c in vowels for c in s) if s[-1] == 'y' or s[-1] == 'Y': n_vowels += 1 return n_vowels
vowels_count
null
[ "('abcde',)", "('Alone',)", "('key',)", "('bye',)", "('keY',)", "('bYe',)", "('ACEDY',)" ]
[ "2", "3", "2", "1", "2", "1", "3" ]
DREval/26
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]
circular_shift
null
[ "(100, 2,)", "(12, 2,)", "(97, 8,)", "(12, 1,)", "(11, 101,)" ]
[ "'001'", "'12'", "'79'", "'21'", "'11'" ]
DREval/27
def fruit_distribution(s,n): """ In this task, you will be given a string that represents a number of apples and oranges that are distributed in a basket of fruit this basket contains apples, oranges, and mango fruits. Given the string that represents the total number of the oranges and apples and an integer that represent the total number of the fruits in the basket return the number of the mango fruits in the basket. for examble: fruit_distribution("5 apples and 6 oranges", 19) ->19 - 5 - 6 = 8 fruit_distribution("0 apples and 1 oranges",3) -> 3 - 0 - 1 = 2 fruit_distribution("2 apples and 3 oranges", 100) -> 100 - 2 - 3 = 95 fruit_distribution("100 apples and 1 oranges",120) -> 120 - 100 - 1 = 19 """ lis = list() for i in s.split(' '): if i.isdigit(): lis.append(int(i)) return n - sum(lis)
fruit_distribution
null
[ "('5 apples and 6 oranges', 19,)", "('5 apples and 6 oranges', 21,)", "('0 apples and 1 oranges', 3,)", "('1 apples and 0 oranges', 3,)", "('2 apples and 3 oranges', 100,)", "('2 apples and 3 oranges', 5,)", "('1 apples and 100 oranges', 120,)" ]
[ "8", "10", "2", "2", "95", "0", "19" ]
DREval/28
def pluck(arr): """ "Given an array representing a branch of a tree that has non-negative integer nodes your task is to pluck one of the nodes and return it. The plucked node should be the node with the smallest even value. If multiple nodes with the same smallest even value are found return the node that has smallest index. The plucked node should be returned in a list, [ smalest_value, its index ], If there are no even values or the given array is empty, return []. Example 1: Input: [4,2,3] Output: [2, 1] Explanation: 2 has the smallest even value, and 2 has the smallest index. Example 2: Input: [1,2,3] Output: [2, 1] Explanation: 2 has the smallest even value, and 2 has the smallest index. Example 3: Input: [] Output: [] Example 4: Input: [5, 0, 3, 0, 4, 2] Output: [0, 1] Explanation: 0 is the smallest value, but there are two zeros, so we will choose the first zero, which has the smallest index. Constraints: * 1 <= nodes.length <= 10000 * 0 <= node.value """ if(len(arr) == 0): return [] evens = list(filter(lambda x: x%2 == 0, arr)) if(evens == []): return [] return [min(evens), arr.index(min(evens))]
pluck
null
[ "([4, 2, 3],)", "([1, 2, 3],)", "([],)", "([5, 0, 3, 0, 4, 2],)", "([1, 2, 3, 0, 5, 3],)", "([5, 4, 8, 4, 8],)", "([7, 6, 7, 1],)", "([7, 9, 7, 1],)" ]
[ "[2, 1]", "[2, 1]", "[]", "[0, 1]", "[0, 3]", "[4, 1]", "[6, 1]", "[]" ]
DREval/29
def search(lst): ''' You are given a non-empty list of positive integers. Return the greatest integer that is greater than zero, and has a frequency greater than or equal to the value of the integer itself. The frequency of an integer is the number of times it appears in the list. If no such a value exist, return -1. Examples: search([4, 1, 2, 2, 3, 1]) == 2 search([1, 2, 2, 3, 3, 3, 4, 4, 4]) == 3 search([5, 5, 4, 4, 4]) == -1 ''' frq = [0] * (max(lst) + 1) for i in lst: frq[i] += 1; ans = -1 for i in range(1, len(frq)): if frq[i] >= i: ans = i return ans
search
null
[ "([5, 5, 5, 5, 1],)", "([4, 1, 4, 1, 4, 4],)", "([3, 3],)", "([8, 8, 8, 8, 8, 8, 8, 8],)", "([2, 3, 3, 2, 2],)", "([2, 7, 8, 8, 4, 8, 7, 3, 9, 6, 5, 10, 4, 3, 6, 7, 1, 7, 4, 10, 8, 1],)", "([3, 2, 8, 2],)", "([6, 7, 1, 8, 8, 10, 5, 8, 5, 3, 10],)", "([8, 8, 3, 6, 5, 6, 4],)", "([6, 9, 6, 7, 1, 4, ...
[ "1", "4", "-1", "8", "2", "1", "2", "1", "-1", "1", "1", "5", "1", "4", "2", "1", "4", "4", "2", "-1", "-1", "2", "1", "1", "-1" ]
DREval/30
def strange_sort_list(lst): ''' Given list of integers, return list in strange order. Strange sorting, is when you start with the minimum value, then maximum of the remaining integers, then minimum and so on. Examples: strange_sort_list([1, 2, 3, 4]) == [1, 4, 2, 3] strange_sort_list([5, 5, 5, 5]) == [5, 5, 5, 5] strange_sort_list([]) == [] ''' res, switch = [], True while lst: res.append(min(lst) if switch else max(lst)) lst.remove(res[-1]) switch = not switch return res
strange_sort_list
null
[ "([1, 2, 3, 4],)", "([5, 6, 7, 8, 9],)", "([1, 2, 3, 4, 5],)", "([5, 6, 7, 8, 9, 1],)", "([5, 5, 5, 5],)", "([],)", "([1, 2, 3, 4, 5, 6, 7, 8],)", "([0, 2, 2, 2, 5, 5, -5, -5],)", "([111111],)" ]
[ "[1, 4, 2, 3]", "[5, 9, 6, 8, 7]", "[1, 5, 2, 4, 3]", "[1, 9, 5, 8, 6, 7]", "[5, 5, 5, 5]", "[]", "[1, 8, 2, 7, 3, 6, 4, 5]", "[-5, 5, -5, 5, 0, 2, 2, 2]", "[111111]" ]
DREval/31
def will_it_fly(q,w): ''' Write a function that returns True if the object q will fly, and False otherwise. The object q will fly if it's balanced (it is a palindromic list) and the sum of its elements is less than or equal the maximum possible weight w. Example: will_it_fly([1, 2], 5) ➞ False # 1+2 is less than the maximum possible weight, but it's unbalanced. will_it_fly([3, 2, 3], 1) ➞ False # it's balanced, but 3+2+3 is more than the maximum possible weight. will_it_fly([3, 2, 3], 9) ➞ True # 3+2+3 is less than the maximum possible weight, and it's balanced. will_it_fly([3], 5) ➞ True # 3 is less than the maximum possible weight, and it's balanced. ''' if sum(q) > w: return False i, j = 0, len(q)-1 while i<j: if q[i] != q[j]: return False i+=1 j-=1 return True
will_it_fly
null
[ "([3, 2, 3], 9,)", "([1, 2], 5,)", "([3], 5,)", "([3, 2, 3], 1,)", "([1, 2, 3], 6,)", "([5], 5,)" ]
[ "True", "False", "True", "False", "False", "True" ]
DREval/32
def smallest_change(arr): """ Given an array arr of integers, find the minimum number of elements that need to be changed to make the array palindromic. A palindromic array is an array that is read the same backwards and forwards. In one change, you can change one element to any other element. For example: smallest_change([1,2,3,5,4,7,9,6]) == 4 smallest_change([1, 2, 3, 4, 3, 2, 2]) == 1 smallest_change([1, 2, 3, 2, 1]) == 0 """ ans = 0 for i in range(len(arr) // 2): if arr[i] != arr[len(arr) - i - 1]: ans += 1 return ans
smallest_change
null
[ "([1, 2, 3, 5, 4, 7, 9, 6],)", "([1, 2, 3, 4, 3, 2, 2],)", "([1, 4, 2],)", "([1, 4, 4, 2],)", "([1, 2, 3, 2, 1],)", "([3, 1, 1, 3],)", "([1],)", "([0, 1],)" ]
[ "4", "1", "1", "1", "0", "0", "0", "1" ]
DREval/33
def total_match(lst1, lst2): ''' Write a function that accepts two lists of strings and returns the list that has total number of chars in the all strings of the list less than the other list. if the two lists have the same number of chars, return the first list. Examples total_match([], []) ➞ [] total_match(['hi', 'admin'], ['hI', 'Hi']) ➞ ['hI', 'Hi'] total_match(['hi', 'admin'], ['hi', 'hi', 'admin', 'project']) ➞ ['hi', 'admin'] total_match(['hi', 'admin'], ['hI', 'hi', 'hi']) ➞ ['hI', 'hi', 'hi'] total_match(['4'], ['1', '2', '3', '4', '5']) ➞ ['4'] ''' l1 = 0 for st in lst1: l1 += len(st) l2 = 0 for st in lst2: l2 += len(st) if l1 <= l2: return lst1 else: return lst2
total_match
null
[ "([], [],)", "(['hi', 'admin'], ['hi', 'hi'],)", "(['hi', 'admin'], ['hi', 'hi', 'admin', 'project'],)", "(['4'], ['1', '2', '3', '4', '5'],)", "(['hi', 'admin'], ['hI', 'Hi'],)", "(['hi', 'admin'], ['hI', 'hi', 'hi'],)", "(['hi', 'admin'], ['hI', 'hi', 'hii'],)", "([], ['this'],)", "(['this'], [],)...
[ "[]", "['hi', 'hi']", "['hi', 'admin']", "['4']", "['hI', 'Hi']", "['hI', 'hi', 'hi']", "['hi', 'admin']", "[]", "[]" ]
DREval/34
def is_simple_power(x, n): """Your task is to write a function that returns true if a number x is a simple power of n and false in other cases. x is a simple power of n if n**int=x For example: is_simple_power(1, 4) => true is_simple_power(2, 2) => true is_simple_power(8, 2) => true is_simple_power(3, 2) => false is_simple_power(3, 1) => false is_simple_power(5, 3) => false """ if (n == 1): return (x == 1) power = 1 while (power < x): power = power * n return (power == x)
is_simple_power
null
[ "(16, 2,)", "(143214, 16,)", "(4, 2,)", "(9, 3,)", "(16, 4,)", "(24, 2,)", "(128, 4,)", "(12, 6,)", "(1, 1,)", "(1, 12,)" ]
[ "True", "False", "True", "True", "True", "False", "False", "False", "True", "True" ]
DREval/35
def hex_key(num): """You have been tasked to write a function that receives a hexadecimal number as a string and counts the number of hexadecimal digits that are primes (prime number, or a prime, is a natural number greater than 1 that is not a product of two smaller natural numbers). Hexadecimal digits are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F. Prime numbers are 2, 3, 5, 7, 11, 13, 17,... So you have to determine a number of the following digits: 2, 3, 5, 7, B (=decimal 11), D (=decimal 13). Note: you may assume the input is always correct or empty string, and symbols A,B,C,D,E,F are always uppercase. Examples: For num = "AB" the output should be 1. For num = "1077E" the output should be 2. For num = "ABED1A33" the output should be 4. For num = "123456789ABCDEF0" the output should be 6. For num = "2020" the output should be 2. """ primes = ('2', '3', '5', '7', 'B', 'D') total = 0 for i in range(0, len(num)): if num[i] in primes: total += 1 return total
hex_key
null
[ "('AB',)", "('1077E',)", "('ABED1A33',)", "('2020',)", "('123456789ABCDEF0',)", "('112233445566778899AABBCCDDEEFF00',)", "([],)" ]
[ "1", "2", "4", "2", "6", "12", "0" ]
DREval/36
def numerical_letter_grade(grades): """It is the last week of the semester and the teacher has to give the grades to students. The teacher has been making her own algorithm for grading. The only problem is, she has lost the code she used for grading. She has given you a list of GPAs for some students and you have to write a function that can output a list of letter grades using the following table: GPA | Letter grade 4.0 A+ > 3.7 A > 3.3 A- > 3.0 B+ > 2.7 B > 2.3 B- > 2.0 C+ > 1.7 C > 1.3 C- > 1.0 D+ > 0.7 D > 0.0 D- 0.0 E Example: grade_equation([4.0, 3, 1.7, 2, 3.5]) ==> ['A+', 'B', 'C-', 'C', 'A-'] """ letter_grade = [] for gpa in grades: if gpa == 4.0: letter_grade.append("A+") elif gpa > 3.7: letter_grade.append("A") elif gpa > 3.3: letter_grade.append("A-") elif gpa > 3.0: letter_grade.append("B+") elif gpa > 2.7: letter_grade.append("B") elif gpa > 2.3: letter_grade.append("B-") elif gpa > 2.0: letter_grade.append("C+") elif gpa > 1.7: letter_grade.append("C") elif gpa > 1.3: letter_grade.append("C-") elif gpa > 1.0: letter_grade.append("D+") elif gpa > 0.7: letter_grade.append("D") elif gpa > 0.0: letter_grade.append("D-") else: letter_grade.append("E") return letter_grade
numerical_letter_grade
null
[ "([4.0, 3, 1.7, 2, 3.5],)", "([1.2],)", "([0.5],)", "([0.0],)", "([1, 0.3, 1.5, 2.8, 3.3],)", "([0, 0.7],)" ]
[ "['A+', 'B', 'C-', 'C', 'A-']", "['D+']", "['D-']", "['E']", "['D', 'D-', 'C-', 'B', 'B+']", "['E', 'D-']" ]
DREval/37
def prime_length(string): """Write a function that takes a string and returns True if the string length is a prime number or False otherwise Examples prime_length('Hello') == True prime_length('abcdcba') == True prime_length('kittens') == True prime_length('orange') == False """ l = len(string) if l == 0 or l == 1: return False for i in range(2, l): if l % i == 0: return False return True
prime_length
null
[ "('Hello',)", "('abcdcba',)", "('kittens',)", "('orange',)", "('wow',)", "('world',)", "('MadaM',)", "('Wow',)", "('',)", "('HI',)", "('go',)", "('gogo',)", "('aaaaaaaaaaaaaaa',)", "('Madam',)", "('M',)", "('0',)" ]
[ "True", "True", "True", "False", "True", "True", "True", "True", "False", "True", "True", "False", "False", "True", "False", "False" ]
DREval/38
def encrypt(s): """Create a function encrypt that takes a string as an argument and returns a string encrypted with the alphabet being rotated. The alphabet should be rotated in a manner such that the letters shift down by two multiplied to two places. For example: encrypt('hi') returns 'lm' encrypt('asdfghjkl') returns 'ewhjklnop' encrypt('gf') returns 'kj' encrypt('et') returns 'ix' """ d = 'abcdefghijklmnopqrstuvwxyz' out = '' for c in s: if c in d: out += d[(d.index(c)+2*2) % 26] else: out += c return out
encrypt
null
[ "('hi',)", "('asdfghjkl',)", "('gf',)", "('et',)", "('faewfawefaewg',)", "('hellomyfriend',)", "('dxzdlmnilfuhmilufhlihufnmlimnufhlimnufhfucufh',)", "('a',)" ]
[ "'lm'", "'ewhjklnop'", "'kj'", "'ix'", "'jeiajeaijeiak'", "'lippsqcjvmirh'", "'hbdhpqrmpjylqmpyjlpmlyjrqpmqryjlpmqryjljygyjl'", "'e'" ]
DREval/39
def skjkasdkd(lst): """You are given a list of integers. You need to find the largest prime value and return the sum of its digits. Examples: For lst = [0,3,2,1,3,5,7,4,5,5,5,2,181,32,4,32,3,2,32,324,4,3] the output should be 10 For lst = [1,0,1,8,2,4597,2,1,3,40,1,2,1,2,4,2,5,1] the output should be 25 For lst = [1,3,1,32,5107,34,83278,109,163,23,2323,32,30,1,9,3] the output should be 13 For lst = [0,724,32,71,99,32,6,0,5,91,83,0,5,6] the output should be 11 For lst = [0,81,12,3,1,21] the output should be 3 For lst = [0,8,1,2,1,7] the output should be 7 """ def isPrime(n): for i in range(2,int(n**0.5)+1): if n%i==0: return False return True maxx = 0 i = 0 while i < len(lst): if(lst[i] > maxx and isPrime(lst[i])): maxx = lst[i] i+=1 result = sum(int(digit) for digit in str(maxx)) return result
skjkasdkd
null
[ "([0, 3, 2, 1, 3, 5, 7, 4, 5, 5, 5, 2, 181, 32, 4, 32, 3, 2, 32, 324, 4, 3],)", "([1, 0, 1, 8, 2, 4597, 2, 1, 3, 40, 1, 2, 1, 2, 4, 2, 5, 1],)", "([1, 3, 1, 32, 5107, 34, 83278, 109, 163, 23, 2323, 32, 30, 1, 9, 3],)", "([0, 724, 32, 71, 99, 32, 6, 0, 5, 91, 83, 0, 5, 6],)", "([0, 81, 12, 3, 1, 21],)", "(...
[ "10", "25", "13", "11", "3", "7", "19", "19", "10" ]
DREval/40
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,17,19] count_up_to(1) => [] count_up_to(18) => [2,3,5,7,11,13,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
count_up_to
null
[ "(5,)", "(6,)", "(7,)", "(10,)", "(0,)", "(22,)", "(1,)", "(18,)", "(47,)", "(101,)" ]
[ "[2, 3]", "[2, 3, 5]", "[2, 3, 5]", "[2, 3, 5, 7]", "[]", "[2, 3, 5, 7, 11, 13, 17, 19]", "[]", "[2, 3, 5, 7, 11, 13, 17]", "[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43]", "[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]" ]
DREval/41
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
count_upper
null
[ "('aBCdEf',)", "('abcdefg',)", "('dBBE',)", "('B',)", "('U',)", "('',)", "('EEEE',)" ]
[ "1", "0", "0", "0", "1", "0", "2" ]
DREval/42
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
closest_integer
null
[ "('10',)", "('14.5',)", "('-15.5',)", "('15.3',)", "('0',)" ]
[ "10", "15", "-16", "15", "0" ]
DREval/43
def words_string(s): """ You will be given a string of words separated by commas or spaces. Your task is to split the string into words and return an array of the words. For example: words_string("Hi, my name is John") == ["Hi", "my", "name", "is", "John"] words_string("One, two, three, four, five, six") == ["One", "two", "three", "four", "five", "six"] """ if not s: return [] s_list = [] for letter in s: if letter == ',': s_list.append(' ') else: s_list.append(letter) s_list = "".join(s_list) return s_list.split()
words_string
null
[ "('Hi, my name is John',)", "('One, two, three, four, five, six',)", "('Hi, my name',)", "('One,, two, three, four, five, six,',)", "('',)", "('ahmed , gamal',)" ]
[ "['Hi', 'my', 'name', 'is', 'John']", "['One', 'two', 'three', 'four', 'five', 'six']", "['Hi', 'my', 'name']", "['One', 'two', 'three', 'four', 'five', 'six']", "[]", "['ahmed', 'gamal']" ]
DREval/44
def rounded_avg(n, m): """You are given two positive integers n and m, and your task is to compute the average of the integers from n through m (including n and m). Round the answer to the nearest integer and convert that to binary. If n is greater than m, return -1. Example: rounded_avg(1, 5) => "0b11" rounded_avg(7, 5) => -1 rounded_avg(10, 20) => "0b1111" rounded_avg(20, 33) => "0b11010" """ if m < n: return -1 summation = 0 for i in range(n, m+1): summation += i return bin(round(summation/(m - n + 1)))
rounded_avg
null
[ "(1, 5,)", "(7, 13,)", "(964, 977,)", "(996, 997,)", "(560, 851,)", "(185, 546,)", "(362, 496,)", "(350, 902,)", "(197, 233,)", "(7, 5,)", "(5, 1,)", "(5, 5,)" ]
[ "'0b11'", "'0b1010'", "'0b1111001010'", "'0b1111100100'", "'0b1011000010'", "'0b101101110'", "'0b110101101'", "'0b1001110010'", "'0b11010111'", "-1", "-1", "'0b101'" ]
DREval/45
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]) [] """ 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)
unique_digits
null
[ "([15, 33, 1422, 1],)", "([152, 323, 1422, 10],)", "([12345, 2033, 111, 151],)", "([135, 103, 31],)" ]
[ "[1, 15, 33]", "[]", "[111, 151]", "[31, 135]" ]
DREval/46
def by_length(arr): """ Given an array of integers, sort the integers that are between 1 and 9 inclusive, reverse the resulting array, and then replace each digit by its corresponding name from "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine". 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
by_length
null
[ "([2, 1, 1, 4, 5, 8, 2, 3],)", "([],)", "([1, -1, 55],)", "([1, -1, 3, 2],)", "([9, 4, 8],)" ]
[ "['Eight', 'Five', 'Four', 'Three', 'Two', 'Two', 'One', 'One']", "[]", "['One']", "['Three', 'Two', 'One']", "['Nine', 'Eight', 'Four']" ]
DREval/47
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] """ 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
f
null
[ "(5,)", "(7,)", "(1,)", "(3,)" ]
[ "[1, 2, 6, 24, 15]", "[1, 2, 6, 24, 15, 720, 28]", "[1]", "[1, 2, 6]" ]
DREval/48
def even_odd_palindrome(n): """ Given a positive integer n, return a tuple that has the number of even and odd integer palindromes that fall within the range(1, n), inclusive. Example 1: Input: 3 Output: (1, 2) Explanation: Integer palindrome are 1, 2, 3. one of them is even, and two of them are odd. Example 2: Input: 12 Output: (4, 6) Explanation: Integer palindrome are 1, 2, 3, 4, 5, 6, 7, 8, 9, 11. four of them are even, and 6 of them are odd. Note: 1. 1 <= n <= 10^3 2. returned tuple has the number of even and odd integer palindromes respectively. """ def is_palindrome(n): return str(n) == str(n)[::-1] even_palindrome_count = 0 odd_palindrome_count = 0 for i in range(1, n+1): if i%2 == 1 and is_palindrome(i): odd_palindrome_count += 1 elif i%2 == 0 and is_palindrome(i): even_palindrome_count += 1 return (even_palindrome_count, odd_palindrome_count)
even_odd_palindrome
null
[ "(123,)", "(12,)", "(3,)", "(63,)", "(25,)", "(19,)", "(9,)", "(1,)" ]
[ "(8, 13)", "(4, 6)", "(1, 2)", "(6, 8)", "(5, 6)", "(4, 6)", "(4, 5)", "(0, 1)" ]
DREval/49
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 """ 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])))
count_nums
null
[ "([],)", "([-1, -2, 0],)", "([1, 1, 2, -2, 3, 4, 5],)", "([1, 6, 9, -6, 0, 1, 5],)", "([1, 100, 98, -7, 1, -1],)", "([12, 23, 34, -45, -56, 0],)", "([-0, 1 ** 0],)", "([1],)" ]
[ "0", "0", "6", "5", "4", "5", "1", "1" ]
DREval/50
def move_one_ball(arr): """We have an array 'arr' of N integers arr[1], arr[2], ..., arr[N].The numbers in the array will be randomly ordered. Your task is to determine if it is possible to get an array sorted in non-decreasing order by performing the following operation on the given array: You are allowed to perform right shift operation any number of times. One right shift operation means shifting all elements of the array by one position in the right direction. The last element of the array will be moved to the starting position in the array i.e. 0th index. If it is possible to obtain the sorted array by performing the above operation then return True else return False. If the given array is empty then return True. Note: The given list is guaranteed to have unique elements. For Example: move_one_ball([3, 4, 5, 1, 2])==>True Explanation: By performin 2 right shift operations, non-decreasing order can be achieved for the given array. move_one_ball([3, 5, 4, 1, 2])==>False Explanation:It is not possible to get non-decreasing order for the given array by performing any number of right shift operations. """ if len(arr)==0: return True sorted_array=sorted(arr) my_arr=[] min_value=min(arr) min_index=arr.index(min_value) my_arr=arr[min_index:]+arr[0:min_index] for i in range(len(arr)): if my_arr[i]!=sorted_array[i]: return False return True
move_one_ball
null
[ "([3, 4, 5, 1, 2],)", "([3, 5, 10, 1, 2],)", "([4, 3, 1, 2],)", "([3, 5, 4, 1, 2],)", "([],)" ]
[ "True", "True", "False", "False", "True" ]
DREval/51
def exchange(lst1, lst2): """In this problem, you will implement a function that takes two lists of numbers, and determines whether it is possible to perform an exchange of elements between them to make lst1 a list of only even numbers. There is no limit on the number of exchanged elements between lst1 and lst2. If it is possible to exchange elements between the lst1 and lst2 to make all the elements of lst1 to be even, return "YES". Otherwise, return "NO". For example: exchange([1, 2, 3, 4], [1, 2, 3, 4]) => "YES" exchange([1, 2, 3, 4], [1, 5, 3, 4]) => "NO" It is assumed that the input lists will be non-empty. """ odd = 0 even = 0 for i in lst1: if i%2 == 1: odd += 1 for i in lst2: if i%2 == 0: even += 1 if even >= odd: return "YES" return "NO"
exchange
null
[ "([1, 2, 3, 4], [1, 2, 3, 4],)", "([1, 2, 3, 4], [1, 5, 3, 4],)", "([1, 2, 3, 4], [2, 1, 4, 3],)", "([5, 7, 3], [2, 6, 4],)", "([5, 7, 3], [2, 6, 3],)", "([3, 2, 6, 1, 8, 9], [3, 5, 5, 1, 1, 1],)", "([100, 200], [200, 200],)" ]
[ "'YES'", "'NO'", "'YES'", "'YES'", "'NO'", "'NO'", "'YES'" ]
DREval/52
def histogram(test): """Given a string representing a space separated lowercase letters, return a dictionary of the letter with the most repetition and containing the corresponding count. If several letters have the same occurrence, return all of them. Example: histogram('a b c') == {'a': 1, 'b': 1, 'c': 1} histogram('a b b a') == {'a': 2, 'b': 2} histogram('a b c a b') == {'a': 2, 'b': 2} histogram('b b b b a') == {'b': 4} histogram('') == {} """ dict1={} list1=test.split(" ") t=0 for i in list1: if(list1.count(i)>t) and i!='': t=list1.count(i) if t>0: for i in list1: if(list1.count(i)==t): dict1[i]=t return dict1
histogram
null
[ "('a b b a',)", "('a b c a b',)", "('a b c d g',)", "('r t g',)", "('b b b b a',)", "('r t g',)", "('',)", "('a',)" ]
[ "{'a': 2, 'b': 2}", "{'a': 2, 'b': 2}", "{'a': 1, 'b': 1, 'c': 1, 'd': 1, 'g': 1}", "{'r': 1, 't': 1, 'g': 1}", "{'b': 4}", "{'r': 1, 't': 1, 'g': 1}", "{}", "{'a': 1}" ]
DREval/53
def odd_count(lst): """Given a list of strings, where each string consists of only digits, return a list. Each element i of the output should be "the number of odd elements in the string i of the input." where all the i's should be replaced by the number of odd digits in the i'th string of the input. >>> odd_count(['1234567']) ["the number of odd elements 4n the str4ng 4 of the 4nput."] >>> odd_count(['3',"11111111"]) ["the number of odd elements 1n the str1ng 1 of the 1nput.", "the number of odd elements 8n the str8ng 8 of the 8nput."] """ res = [] for arr in lst: n = sum(int(d)%2==1 for d in arr) res.append("the number of odd elements " + str(n) + "n the str"+ str(n) +"ng "+ str(n) +" of the "+ str(n) +"nput.") return res
odd_count
null
[ "(['1234567'],)", "(['3', '11111111'],)", "(['271', '137', '314'],)" ]
[ "['the number of odd elements 4n the str4ng 4 of the 4nput.']", "['the number of odd elements 1n the str1ng 1 of the 1nput.', 'the number of odd elements 8n the str8ng 8 of the 8nput.']", "['the number of odd elements 2n the str2ng 2 of the 2nput.', 'the number of odd elements 3n the str3ng 3 of the 3nput.', 't...
DREval/54
def minSubArraySum(nums): """ Given an array of integers nums, find the minimum sum of any non-empty sub-array of nums. Example minSubArraySum([2, 3, 4, 1, 2, 4]) == 1 minSubArraySum([-1, -2, -3]) == -6 """ max_sum = 0 s = 0 for num in nums: s += -num if (s < 0): s = 0 max_sum = max(s, max_sum) if max_sum == 0: max_sum = max(-i for i in nums) min_sum = -max_sum return min_sum
minSubArraySum
null
[ "([2, 3, 4, 1, 2, 4],)", "([-1, -2, -3],)", "([-1, -2, -3, 2, -10],)", "([-9999999999999999],)", "([0, 10, 20, 1000000],)", "([-1, -2, -3, 10, -5],)", "([100, -1, -2, -3, 10, -5],)", "([10, 11, 13, 8, 3, 4],)", "([100, -33, 32, -1, 0, -2],)", "([-10],)", "([7],)", "([1, -1],)" ]
[ "1", "-6", "-14", "-9999999999999999", "0", "-6", "-6", "3", "-33", "-10", "7", "-1" ]
DREval/55
def select_words(s, n): """Given a string s and a natural number n, you have been tasked to implement a function that returns a list of all words from string s that contain exactly n consonants, in order these words appear in the string s. If the string s is empty then the function should return an empty list. Note: you may assume the input string contains only letters and spaces. Examples: select_words("Mary had a little lamb", 4) ==> ["little"] select_words("Mary had a little lamb", 3) ==> ["Mary", "lamb"] select_words("simple white space", 2) ==> [] select_words("Hello world", 4) ==> ["world"] select_words("Uncle sam", 3) ==> ["Uncle"] """ result = [] for word in s.split(): n_consonants = 0 for i in range(0, len(word)): if word[i].lower() not in ["a","e","i","o","u"]: n_consonants += 1 if n_consonants == n: result.append(word) return result
select_words
null
[ "('Mary had a little lamb', 4,)", "('Mary had a little lamb', 3,)", "('simple white space', 2,)", "('Hello world', 4,)", "('Uncle sam', 3,)", "('', 4,)", "('a b c d e f', 1,)" ]
[ "['little']", "['Mary', 'lamb']", "[]", "['world']", "['Uncle']", "[]", "['b', 'c', 'd', 'f']" ]
DREval/56
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' ''' def check(s): val = 0 for i in s: if i == '(': val = val + 1 else: val = val - 1 if val < 0: return False return True if val == 0 else False S1 = lst[0] + lst[1] S2 = lst[1] + lst[0] return 'Yes' if check(S1) or check(S2) else 'No'
match_parens
null
[ "(['()(', ')'],)", "([')', ')'],)", "(['(()(())', '())())'],)", "([')())', '(()()('],)", "(['(())))', '(()())(('],)", "(['()', '())'],)", "(['(()(', '()))()'],)", "(['((((', '((())'],)", "([')(()', '(()('],)", "([')(', ')('],)", "(['(', ')'],)", "([')', '('],)" ]
[ "'Yes'", "'No'", "'No'", "'Yes'", "'Yes'", "'No'", "'Yes'", "'No'", "'No'", "'No'", "'Yes'", "'Yes'" ]
DREval/57
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. """ if n%2==0: odd_collatz = [] else: odd_collatz = [n] while n > 1: if n % 2 == 0: n = n/2 else: n = n*3 + 1 if n%2 == 1: odd_collatz.append(int(n)) return sorted(odd_collatz)
get_odd_collatz
null
[ "(14,)", "(5,)", "(12,)", "(1,)" ]
[ "[1, 5, 7, 11, 13, 17]", "[1, 5]", "[1, 3, 5]", "[1]" ]
DREval/58
def valid_date(date): """You have to write a function which validates a given date string and returns True if the date is valid otherwise False. The date is valid if all of the following rules are satisfied: 1. The date string is not empty. 2. The number of days is not less than 1 or higher than 31 days for months 1,3,5,7,8,10,12. And the number of days is not less than 1 or higher than 30 days for months 4,6,9,11. And, the number of days is not less than 1 or higher than 29 for the month 2. 3. The months should not be less than 1 or higher than 12. 4. The date should be in the format: mm-dd-yyyy for example: valid_date('03-11-2000') => True valid_date('15-01-2012') => False valid_date('04-0-2040') => False valid_date('06-04-2020') => True valid_date('06/04/2020') => False """ try: date = date.strip() month, day, year = date.split('-') month, day, year = int(month), int(day), int(year) if month < 1 or month > 12: return False if month in [1,3,5,7,8,10,12] and day < 1 or day > 31: return False if month in [4,6,9,11] and day < 1 or day > 30: return False if month == 2 and day < 1 or day > 29: return False except: return False return True
valid_date
null
[ "('03-11-2000',)", "('15-01-2012',)", "('04-0-2040',)", "('06-04-2020',)", "('01-01-2007',)", "('03-32-2011',)", "('',)", "('04-31-3000',)", "('06-06-2005',)", "('21-31-2000',)", "('04-12-2003',)", "('04122003',)", "('20030412',)", "('2003-04',)", "('2003-04-12',)", "('04-2003',)" ]
[ "True", "False", "False", "True", "True", "False", "False", "False", "True", "False", "True", "False", "False", "False", "False", "False" ]
DREval/59
def is_sorted(lst): ''' Given a list of numbers, return whether or not they are sorted in ascending order. If list has more than 1 duplicate of the same number, return False. Assume no negative numbers and only integers. Examples is_sorted([5]) ➞ True is_sorted([1, 2, 3, 4, 5]) ➞ True is_sorted([1, 3, 2, 4, 5]) ➞ False is_sorted([1, 2, 3, 4, 5, 6]) ➞ True is_sorted([1, 2, 3, 4, 5, 6, 7]) ➞ True is_sorted([1, 3, 2, 4, 5, 6, 7]) ➞ False is_sorted([1, 2, 2, 3, 3, 4]) ➞ True is_sorted([1, 2, 2, 2, 3, 4]) ➞ False ''' count_digit = dict([(i, 0) for i in lst]) for i in lst: count_digit[i]+=1 if any(count_digit[i] > 2 for i in lst): return False if all(lst[i-1] <= lst[i] for i in range(1, len(lst))): return True else: return False
is_sorted
null
[ "([5],)", "([1, 2, 3, 4, 5],)", "([1, 3, 2, 4, 5],)", "([1, 2, 3, 4, 5, 6],)", "([1, 2, 3, 4, 5, 6, 7],)", "([1, 3, 2, 4, 5, 6, 7],)", "([],)", "([1],)", "([3, 2, 1],)", "([1, 2, 2, 2, 3, 4],)", "([1, 2, 3, 3, 3, 4],)", "([1, 2, 2, 3, 3, 4],)", "([1, 2, 3, 4],)" ]
[ "True", "True", "False", "True", "True", "False", "True", "True", "False", "False", "False", "True", "True" ]
DREval/60
def intersection(interval1, interval2): """You are given two intervals, where each interval is a pair of integers. For example, interval = (start, end) = (1, 2). The given intervals are closed which means that the interval (start, end) includes both start and end. For each given interval, it is assumed that its start is less or equal its end. Your task is to determine whether the length of intersection of these two intervals is a prime number. Example, the intersection of the intervals (1, 3), (2, 4) is (2, 3) which its length is 1, which not a prime number. If the length of the intersection is a prime number, return "YES", otherwise, return "NO". If the two intervals don't intersect, return "NO". [input/output] samples: intersection((1, 2), (2, 3)) ==> "NO" intersection((-1, 1), (0, 4)) ==> "NO" intersection((-3, -1), (-5, 5)) ==> "YES" """ def is_prime(num): if num == 1 or num == 0: return False if num == 2: return True for i in range(2, num): if num%i == 0: return False return True l = max(interval1[0], interval2[0]) r = min(interval1[1], interval2[1]) length = r - l if length > 0 and is_prime(length): return "YES" return "NO"
intersection
null
[ "((1, 2), (2, 3),)", "((-1, 1), (0, 4),)", "((-3, -1), (-5, 5),)", "((-2, 2), (-4, 0),)", "((-11, 2), (-1, -1),)", "((1, 2), (3, 5),)", "((1, 2), (1, 2),)", "((-2, -2), (-3, -2),)" ]
[ "'NO'", "'NO'", "'YES'", "'YES'", "'NO'", "'NO'", "'NO'", "'NO'" ]
DREval/61
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] """ 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
minPath
null
[ "([[1, 2, 3], [4, 5, 6], [7, 8, 9]], 3,)", "([[5, 9, 3], [4, 1, 6], [7, 8, 2]], 1,)", "([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]], 4,)", "([[6, 4, 13, 10], [5, 7, 12, 1], [3, 16, 11, 15], [8, 14, 9, 2]], 7,)", "([[8, 14, 9, 2], [6, 4, 13, 15], [5, 7, 1, 12], [3, 10, 11, 16]], 5,)", "...
[ "[1, 2, 1]", "[1]", "[1, 2, 1, 2]", "[1, 10, 1, 10, 1, 10, 1]", "[1, 7, 1, 7, 1]", "[1, 6, 1, 6, 1, 6, 1, 6, 1]", "[1, 6, 1, 6, 1, 6, 1, 6, 1, 6, 1, 6]", "[1, 3, 1, 3, 1, 3, 1, 3]", "[1, 5, 1, 5, 1, 5, 1, 5]", "[1, 2, 1, 2, 1, 2, 1, 2, 1, 2]", "[1, 3, 1, 3, 1, 3, 1, 3, 1, 3]" ]
DREval/62
def tri(n): """Everyone knows Fibonacci sequence, it was studied deeply by mathematicians in the last couple centuries. However, what people don't know is Tribonacci sequence. Tribonacci sequence is defined by the recurrence: tri(1) = 3 tri(n) = 1 + n / 2, if n is even. tri(n) = tri(n - 1) + tri(n - 2) + tri(n + 1), if n is odd. For example: tri(2) = 1 + (2 / 2) = 2 tri(4) = 3 tri(3) = tri(2) + tri(1) + tri(4) = 2 + 3 + 3 = 8 You are given a non-negative integer number n, you have to a return a list of the first n + 1 numbers of the Tribonacci sequence. Examples: tri(3) = [1, 3, 2, 8] """ if n == 0: return [1] my_tri = [1, 3] for i in range(2, n + 1): if i % 2 == 0: my_tri.append(i / 2 + 1) else: my_tri.append(my_tri[i - 1] + my_tri[i - 2] + (i + 3) / 2) return my_tri
tri
null
[ "(3,)", "(4,)", "(5,)", "(6,)", "(7,)", "(8,)", "(9,)", "(20,)", "(0,)", "(1,)" ]
[ "[1, 3, 2.0, 8.0]", "[1, 3, 2.0, 8.0, 3.0]", "[1, 3, 2.0, 8.0, 3.0, 15.0]", "[1, 3, 2.0, 8.0, 3.0, 15.0, 4.0]", "[1, 3, 2.0, 8.0, 3.0, 15.0, 4.0, 24.0]", "[1, 3, 2.0, 8.0, 3.0, 15.0, 4.0, 24.0, 5.0]", "[1, 3, 2.0, 8.0, 3.0, 15.0, 4.0, 24.0, 5.0, 35.0]", "[1, 3, 2.0, 8.0, 3.0, 15.0, 4.0, 24.0, 5.0, 35....
DREval/63
def digits(n): """Given a positive integer n, return the product of the odd digits. Return 0 if all digits are even. For example: digits(1) == 1 digits(4) == 0 digits(235) == 15 """ product = 1 odd_count = 0 for digit in str(n): int_digit = int(digit) if int_digit%2 == 1: product= product*int_digit odd_count+=1 if odd_count ==0: return 0 else: return product
digits
null
[ "(5,)", "(54,)", "(120,)", "(5014,)", "(98765,)", "(5576543,)", "(2468,)" ]
[ "5", "5", "1", "5", "315", "2625", "0" ]
DREval/64
def is_nested(string): ''' Create a function that takes a string as input which contains only square brackets. The function should return True if and only if there is a valid subsequence of brackets where at least one bracket in the subsequence is nested. is_nested('[[]]') ➞ True is_nested('[]]]]]]][[[[[]') ➞ False is_nested('[][]') ➞ False is_nested('[]') ➞ False is_nested('[[][]]') ➞ True is_nested('[[]][[') ➞ True ''' opening_bracket_index = [] closing_bracket_index = [] for i in range(len(string)): if string[i] == '[': opening_bracket_index.append(i) else: closing_bracket_index.append(i) closing_bracket_index.reverse() cnt = 0 i = 0 l = len(closing_bracket_index) for idx in opening_bracket_index: if i < l and idx < closing_bracket_index[i]: cnt += 1 i += 1 return cnt >= 2
is_nested
null
[ "('[[]]',)", "('[]]]]]]][[[[[]',)", "('[][]',)", "('[]',)", "('[[[[]]]]',)", "('[]]]]]]]]]]',)", "('[][][[]]',)", "('[[]',)", "('[]]',)", "('[[]][[',)", "('[[][]]',)", "('',)", "('[[[[[[[[',)", "(']]]]]]]]',)" ]
[ "True", "False", "False", "False", "True", "False", "True", "False", "False", "True", "True", "False", "False", "False" ]
DREval/65
def sum_squares(lst): """You are given a list of numbers. You need to return the sum of squared numbers in the given list, round each element in the list to the upper int(Ceiling) first. Examples: For lst = [1,2,3] the output should be 14 For lst = [1,4,9] the output should be 98 For lst = [1,3,5,7] the output should be 84 For lst = [1.4,4.2,0] the output should be 29 For lst = [-2.4,1,1] the output should be 6 """ import math squared = 0 for i in lst: squared += math.ceil(i)**2 return squared
sum_squares
null
[ "([1, 2, 3],)", "([1.0, 2, 3],)", "([1, 3, 5, 7],)", "([1.4, 4.2, 0],)", "([-2.4, 1, 1],)", "([100, 1, 15, 2],)", "([10000, 10000],)", "([-1.4, 4.6, 6.3],)", "([-1.4, 17.9, 18.9, 19.9],)", "([0],)", "([-1],)", "([-1, 1, 0],)" ]
[ "14", "14", "84", "29", "6", "10230", "200000000", "75", "1086", "0", "1", "2" ]
DREval/66
def can_arrange(arr): """Create a function which returns the largest index of an element which is not greater than or equal to the element immediately preceding it. If no such element exists then return -1. The given array will not contain duplicate values. Examples: can_arrange([1,2,4,3,5]) = 3 can_arrange([1,2,3]) = -1 """ ind=-1 i=1 while i<len(arr): if arr[i]<arr[i-1]: ind=i i+=1 return ind
can_arrange
null
[ "([1, 2, 4, 3, 5],)", "([1, 2, 4, 5],)", "([1, 4, 2, 5, 6, 7, 8, 9, 10],)", "([4, 8, 5, 7, 3],)", "([],)" ]
[ "3", "-1", "2", "4", "-1" ]
DREval/67
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 """ temp_a, temp_b = a, b if isinstance(temp_a, str): temp_a = temp_a.replace(',','.') if isinstance(temp_b, str): temp_b = temp_b.replace(',','.') if float(temp_a) == float(temp_b): return None return a if float(temp_a) > float(temp_b) else b
compare_one
null
[ "(1, 2,)", "(1, 2.5,)", "(2, 3,)", "(5, 6,)", "(1, '2,3',)", "('5,1', '6',)", "('1', '2',)", "('1', 1,)" ]
[ "2", "2.5", "3", "6", "'2,3'", "'6'", "'2'", "None" ]
DREval/68
def special_factorial(n): """The Brazilian factorial is defined as: brazilian_factorial(n) = n! * (n-1)! * (n-2)! * ... * 1! where n > 0 For example: >>> special_factorial(4) 288 The function will receive an integer as input and should return the special factorial of this integer. """ fact_i = 1 special_fact = 1 for i in range(1, n+1): fact_i *= i special_fact *= fact_i return special_fact
special_factorial
null
[ "(4,)", "(5,)", "(7,)", "(1,)" ]
[ "288", "34560", "125411328000", "1" ]
DREval/69
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" """ new_text = "" i = 0 start, end = 0, 0 while i < len(text): if text[i] == " ": end += 1 else: if end - start > 2: new_text += "-"+text[i] elif end - start > 0: new_text += "_"*(end - start)+text[i] else: new_text += text[i] start, end = i+1, i+1 i+=1 if end - start > 2: new_text += "-" elif end - start > 0: new_text += "_" return new_text
fix_spaces
null
[ "('Example',)", "('Mudasir Hanif ',)", "('Yellow Yellow Dirty Fellow',)", "('Exa mple',)", "(' Exa 1 2 2 mple',)" ]
[ "'Example'", "'Mudasir_Hanif_'", "'Yellow_Yellow__Dirty__Fellow'", "'Exa-mple'", "'-Exa_1_2_2_mple'" ]
DREval/70
def file_name_check(file_name): """Create a function which takes a string representing a file's name, and returns 'Yes' if the the file's name is valid, and returns 'No' otherwise. A file's name is considered to be valid if and only if all the following conditions are met: - There should not be more than three digits ('0'-'9') in the file's name. - The file's name contains exactly one dot '.' - The substring before the dot should not be empty, and it starts with a letter from the latin alphapet ('a'-'z' and 'A'-'Z'). - The substring after the dot should be one of these: ['txt', 'exe', 'dll'] Examples: file_name_check("example.txt") # => 'Yes' file_name_check("1example.dll") # => 'No' (the name should start with a latin alphapet letter) """ suf = ['txt', 'exe', 'dll'] lst = file_name.split(sep='.') if len(lst) != 2: return 'No' if not lst[1] in suf: return 'No' if len(lst[0]) == 0: return 'No' if not lst[0][0].isalpha(): return 'No' t = len([x for x in lst[0] if x.isdigit()]) if t > 3: return 'No' return 'Yes'
file_name_check
null
[ "('example.txt',)", "('1example.dll',)", "('s1sdf3.asd',)", "('K.dll',)", "('MY16FILE3.exe',)", "('His12FILE94.exe',)", "('_Y.txt',)", "('?aREYA.exe',)", "('/this_is_valid.dll',)", "('this_is_valid.wow',)", "('this_is_valid.txt',)", "('this_is_valid.txtexe',)", "('#this2_i4s_5valid.ten',)", ...
[ "'Yes'", "'No'", "'No'", "'Yes'", "'Yes'", "'No'", "'No'", "'No'", "'No'", "'No'", "'Yes'", "'No'", "'No'", "'No'", "'No'", "'No'", "'Yes'", "'Yes'", "'Yes'", "'No'", "'No'", "'No'", "'No'", "'No'", "'No'", "'No'" ]
DREval/71
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 """ result =[] for i in range(len(lst)): if i %3 == 0: result.append(lst[i]**2) elif i % 4 == 0 and i%3 != 0: result.append(lst[i]**3) else: result.append(lst[i]) return sum(result)
sum_squares
null
[ "([1, 2, 3],)", "([1, 4, 9],)", "([],)", "([1, 1, 1, 1, 1, 1, 1, 1, 1],)", "([-1, -1, -1, -1, -1, -1, -1, -1, -1],)", "([0],)", "([-1, -5, 2, -1, -5],)", "([-56, -99, 1, 0, -2],)", "([-1, 0, 0, 0, 0, 0, 0, 0, -1],)", "([-16, -9, -2, 36, 36, 26, -20, 25, -40, 20, -4, 12, -26, 35, 37],)", "([-1, -...
[ "6", "14", "0", "9", "-3", "0", "-126", "3030", "0", "-14196", "-1448" ]
DREval/72
def words_in_sentence(sentence): """ You are given a string representing a sentence, the sentence contains some words separated by a space, and you have to return a string that contains the words from the original sentence, whose lengths are prime numbers, the order of the words in the new string should be the same as the original one. Example 1: Input: sentence = "This is a test" Output: "is" Example 2: Input: sentence = "lets go for swimming" Output: "go for" Constraints: * 1 <= len(sentence) <= 100 * sentence contains only letters """ new_lst = [] for word in sentence.split(): flg = 0 if len(word) == 1: flg = 1 for i in range(2, len(word)): if len(word)%i == 0: flg = 1 if flg == 0 or len(word) == 2: new_lst.append(word) return " ".join(new_lst)
words_in_sentence
null
[ "('This is a test',)", "('lets go for swimming',)", "('there is no place available here',)", "('Hi I am Hussein',)", "('go for it',)", "('here',)", "('here is',)" ]
[ "'is'", "'go for'", "'there is no place'", "'Hi am Hussein'", "'go for it'", "''", "'is'" ]
DREval/73
def simplify(x, n): """Your task is to implement a function that will simplify the expression x * n. The function returns True if x * n evaluates to a whole number and False otherwise. Both x and n, are string representation of a fraction, and have the following format, <numerator>/<denominator> where both numerator and denominator are positive whole numbers. You can assume that x, and n are valid fractions, and do not have zero as denominator. simplify("1/5", "5/1") = True simplify("1/6", "2/1") = False simplify("7/10", "10/2") = False """ a, b = x.split("/") c, d = n.split("/") numerator = int(a) * int(c) denom = int(b) * int(d) if (numerator/denom == int(numerator/denom)): return True return False
simplify
null
[ "('1/5', '5/1',)", "('1/6', '2/1',)", "('5/1', '3/1',)", "('7/10', '10/2',)", "('2/10', '50/10',)", "('7/2', '4/2',)", "('11/6', '6/1',)", "('2/3', '5/2',)", "('5/2', '3/5',)", "('2/4', '8/4',)", "('2/4', '4/2',)", "('1/5', '5/1',)", "('1/5', '1/5',)" ]
[ "True", "False", "True", "False", "True", "True", "True", "False", "False", "True", "True", "True", "False" ]
DREval/74
def order_by_points(nums): """ Write a function which sorts the given list of integers in ascending order according to the sum of their digits. Note: if there are several items with similar sum of their digits, order them based on their index in original list. For example: >>> order_by_points([1, 11, -1, -11, -12]) == [-1, -11, 1, -12, 11] >>> order_by_points([]) == [] """ def digits_sum(n): neg = 1 if n < 0: n, neg = -1 * n, -1 n = [int(i) for i in str(n)] n[0] = n[0] * neg return sum(n) return sorted(nums, key=digits_sum)
order_by_points
null
[ "([1, 11, -1, -11, -12],)", "([1234, 423, 463, 145, 2, 423, 423, 53, 6, 37, 3457, 3, 56, 0, 46],)", "([],)", "([1, -11, -32, 43, 54, -98, 2, -3],)", "([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11],)", "([0, 6, 6, -76, -21, 23, 4],)" ]
[ "[-1, -11, 1, -12, 11]", "[0, 2, 3, 6, 53, 423, 423, 423, 1234, 145, 37, 46, 56, 463, 3457]", "[]", "[-3, -32, -98, -11, 1, 2, 43, 54]", "[1, 10, 2, 11, 3, 4, 5, 6, 7, 8, 9]", "[-76, -21, 0, 4, 23, 6, 6]" ]
DREval/75
def specialFilter(nums): """Write a function that takes an array of numbers as input and returns the number of elements in the array that are greater than 10 and both first and last digits of a number are odd (1, 3, 5, 7, 9). For example: specialFilter([15, -73, 14, -15]) => 1 specialFilter([33, -2, -3, 45, 21, 109]) => 2 """ count = 0 for num in nums: if num > 10: odd_digits = (1, 3, 5, 7, 9) number_as_string = str(num) if int(number_as_string[0]) in odd_digits and int(number_as_string[-1]) in odd_digits: count += 1 return count
specialFilter
null
[ "([5, -2, 1, -5],)", "([15, -73, 14, -15],)", "([33, -2, -3, 45, 21, 109],)", "([43, -12, 93, 125, 121, 109],)", "([71, -2, -33, 75, 21, 19],)", "([1],)", "([],)" ]
[ "0", "1", "2", "4", "3", "0", "0" ]
DREval/76
def get_max_triples(n): """ You are given a positive integer n. You have to create an integer array a of length n. For each i (1 ≤ i ≤ n), the value of a[i] = i * i - i + 1. Return the number of triples (a[i], a[j], a[k]) of a where i < j < k, and a[i] + a[j] + a[k] is a multiple of 3. Example : Input: n = 5 Output: 1 Explanation: a = [1, 3, 7, 13, 21] The only valid triple is (1, 7, 13). """ A = [i*i - i + 1 for i in range(1,n+1)] ans = [] for i in range(n): for j in range(i+1,n): for k in range(j+1,n): if (A[i]+A[j]+A[k])%3 == 0: ans += [(A[i],A[j],A[k])] return len(ans)
get_max_triples
null
[ "(5,)", "(6,)", "(10,)" ]
[ "1", "4", "36" ]
DREval/77
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])
bf
null
[ "('Jupiter', 'Neptune',)", "('Earth', 'Mercury',)", "('Mercury', 'Uranus',)", "('Neptune', 'Venus',)", "('Earth', 'Earth',)", "('Mars', 'Earth',)", "('Jupiter', 'Makemake',)" ]
[ "('Saturn', 'Uranus')", "('Venus',)", "('Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn')", "('Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus')", "()", "()", "()" ]
DREval/78
def sorted_list_sum(lst): """Write a function that accepts a list of strings as a parameter, deletes the strings that have odd lengths from it, and returns the resulted list with a sorted order, The list is always a list of strings and never an array of numbers, and it may contain duplicates. The order of the list should be ascending by length of each word, and you should return the list sorted by that rule. If two words have the same length, sort the list alphabetically. The function should return a list of strings in sorted order. You may assume that all words will have the same length. For example: assert list_sort(["aa", "a", "aaa"]) => ["aa"] assert list_sort(["ab", "a", "aaa", "cd"]) => ["ab", "cd"] """ lst.sort() new_lst = [] for i in lst: if len(i)%2 == 0: new_lst.append(i) return sorted(new_lst, key=len)
sorted_list_sum
null
[ "(['aa', 'a', 'aaa'],)", "(['school', 'AI', 'asdf', 'b'],)", "(['d', 'b', 'c', 'a'],)", "(['d', 'dcba', 'abcd', 'a'],)", "(['AI', 'ai', 'au'],)", "(['a', 'b', 'b', 'c', 'c', 'a'],)", "(['aaaa', 'bbbb', 'dd', 'cc'],)" ]
[ "['aa']", "['AI', 'asdf', 'school']", "[]", "['abcd', 'dcba']", "['AI', 'ai', 'au']", "[]", "['cc', 'dd', 'aaaa', 'bbbb']" ]
DREval/79
def Strongest_Extension(class_name, extensions): """You will be given the name of a class (a string) and a list of extensions. The extensions are to be used to load additional classes to the class. The strength of the extension is as follows: Let CAP be the number of the uppercase letters in the extension's name, and let SM be the number of lowercase letters in the extension's name, the strength is given by the fraction CAP - SM. You should find the strongest extension and return a string in this format: ClassName.StrongestExtensionName. If there are two or more extensions with the same strength, you should choose the one that comes first in the list. For example, if you are given "Slices" as the class and a list of the extensions: ['SErviNGSliCes', 'Cheese', 'StuFfed'] then you should return 'Slices.SErviNGSliCes' since 'SErviNGSliCes' is the strongest extension (its strength is -1). Example: for Strongest_Extension('my_class', ['AA', 'Be', 'CC']) == 'my_class.AA' """ strong = extensions[0] my_val = len([x for x in extensions[0] if x.isalpha() and x.isupper()]) - len([x for x in extensions[0] if x.isalpha() and x.islower()]) for s in extensions: val = len([x for x in s if x.isalpha() and x.isupper()]) - len([x for x in s if x.isalpha() and x.islower()]) if val > my_val: strong = s my_val = val ans = class_name + "." + strong return ans
Strongest_Extension
null
[ "('Watashi', ['tEN', 'niNE', 'eIGHt8OKe'],)", "('Boku123', ['nani', 'NazeDa', 'YEs.WeCaNe', '32145tggg'],)", "('__YESIMHERE', ['t', 'eMptY', 'nothing', 'zeR00', 'NuLl__', '123NoooneB321'],)", "('K', ['Ta', 'TAR', 't234An', 'cosSo'],)", "('__HAHA', ['Tab', '123', '781345', '-_-'],)", "('YameRore', ['HhAas'...
[ "'Watashi.eIGHt8OKe'", "'Boku123.YEs.WeCaNe'", "'__YESIMHERE.NuLl__'", "'K.TAR'", "'__HAHA.123'", "'YameRore.okIWILL123'", "'finNNalLLly.WoW'", "'_.Bb'", "'Sp.671235'" ]
DREval/80
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
cycpattern_check
null
[ "('xyzw', 'xyw',)", "('yello', 'ell',)", "('whattup', 'ptut',)", "('efef', 'fee',)", "('abab', 'aabb',)", "('winemtt', 'tinem',)" ]
[ "False", "True", "False", "True", "False", "True" ]
DREval/81
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) """ even_count = 0 odd_count = 0 for i in str(abs(num)): if int(i)%2==0: even_count +=1 else: odd_count +=1 return (even_count, odd_count)
even_odd_count
null
[ "(7,)", "(-78,)", "(3452,)", "(346211,)", "(-345821,)", "(-2,)", "(-45347,)", "(0,)" ]
[ "(0, 1)", "(1, 1)", "(2, 2)", "(3, 3)", "(3, 3)", "(1, 0)", "(2, 3)", "(1, 0)" ]
DREval/82
def int_to_mini_roman(number): """ Given a positive integer, obtain its roman numeral equivalent as a string, and return it in lowercase. Restrictions: 1 <= num <= 1000 Examples: >>> int_to_mini_roman(19) == 'xix' >>> int_to_mini_roman(152) == 'clii' >>> int_to_mini_roman(426) == 'cdxxvi' """ num = [1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900, 1000] sym = ["I", "IV", "V", "IX", "X", "XL", "L", "XC", "C", "CD", "D", "CM", "M"] i = 12 res = '' while number: div = number // num[i] number %= num[i] while div: res += sym[i] div -= 1 i -= 1 return res.lower()
int_to_mini_roman
null
[ "(19,)", "(152,)", "(251,)", "(426,)", "(500,)", "(1,)", "(4,)", "(43,)", "(90,)", "(94,)", "(532,)", "(900,)", "(994,)", "(1000,)" ]
[ "'xix'", "'clii'", "'ccli'", "'cdxxvi'", "'d'", "'i'", "'iv'", "'xliii'", "'xc'", "'xciv'", "'dxxxii'", "'cm'", "'cmxciv'", "'m'" ]
DREval/83
def do_algebra(operator, operand): """ Given two lists operator, and operand. The first list has basic algebra operations, and the second list is a list of integers. Use the two given lists to build the algebric expression and return the evaluation of this expression. The basic algebra operations: Addition ( + ) Subtraction ( - ) Multiplication ( * ) Floor division ( // ) Exponentiation ( ** ) Example: operator['+', '*', '-'] array = [2, 3, 4, 5] result = 2 + 3 * 4 - 5 => result = 9 Note: The length of operator list is equal to the length of operand list minus one. Operand is a list of of non-negative integers. Operator list has at least one operator, and operand list has at least two operands. """ expression = str(operand[0]) for oprt, oprn in zip(operator, operand[1:]): expression+= oprt + str(oprn) return eval(expression)
do_algebra
null
[ "(['**', '*', '+'], [2, 3, 4, 5],)", "(['+', '*', '-'], [2, 3, 4, 5],)", "(['//', '*'], [7, 3, 4],)" ]
[ "37", "9", "8" ]
DREval/84
def solve(s): """You are given a string s. if s[i] is a letter, reverse its case from lower to upper or vise versa, otherwise keep it as it is. If the string contains no letters, reverse the string. The function should return the resulted string. Examples solve("1234") = "4321" solve("ab") = "AB" solve("#a@C") = "#A@c" """ flg = 0 idx = 0 new_str = list(s) for i in s: if i.isalpha(): new_str[idx] = i.swapcase() flg = 1 idx += 1 s = "" for i in new_str: s += i if flg == 0: return s[len(s)::-1] return s
solve
null
[ "('AsDf',)", "('1234',)", "('ab',)", "('#a@C',)", "('#AsdfW^45',)", "('#6@2',)", "('#$a^D',)", "('#ccc',)" ]
[ "'aSdF'", "'4321'", "'AB'", "'#A@c'", "'#aSDFw^45'", "'2@6#'", "'#$A^d'", "'#CCC'" ]
DREval/85
import math class AreaCalculator: def __init__(self, radius): self.radius = radius def calculate_circle_area(self): return math.pi * self.radius ** 2 def calculate_sphere_area(self): return 4 * math.pi * self.radius ** 2 def calculate_cylinder_area(self, height): return 2 * math.pi * self.radius * (self.radius + height) def calculate_sector_area(self, angle): return self.radius ** 2 * angle / 2 def calculate_annulus_area(self, inner_radius, outer_radius): return math.pi * (outer_radius ** 2 - inner_radius ** 2)
AreaCalculator
import unittest class AreaCalculatorTestCalculateCircleArea(unittest.TestCase): def test_calculate_circle_area(self): areaCalculator = AreaCalculator(2) self.assertAlmostEqual(12.56, areaCalculator.calculate_circle_area(), delta=0.01) def test_calculate_circle_area_2(self): areaCalculator = AreaCalculator(2.5) self.assertAlmostEqual(19.63, areaCalculator.calculate_circle_area(), delta=0.01) def test_calculate_circle_area_3(self): areaCalculator = AreaCalculator(2000) self.assertAlmostEqual(12566370.61, areaCalculator.calculate_circle_area(), delta=0.01) def test_calculate_circle_area_4(self): areaCalculator = AreaCalculator(0) self.assertAlmostEqual(0, areaCalculator.calculate_circle_area(), delta=0.01) def test_calculate_circle_area_5(self): areaCalculator = AreaCalculator(0.1) self.assertAlmostEqual(0.031, areaCalculator.calculate_circle_area(), delta=0.01) class AreaCalculatorTestCalculateSphereArea(unittest.TestCase): def test_calculate_sphere_area(self): areaCalculator = AreaCalculator(2) self.assertAlmostEqual(50.27, areaCalculator.calculate_sphere_area(), delta=0.01) def test_calculate_sphere_area_2(self): areaCalculator = AreaCalculator(2.5) self.assertAlmostEqual(19.63, areaCalculator.calculate_circle_area(), delta=0.01) def test_calculate_sphere_area_3(self): areaCalculator = AreaCalculator(2000) self.assertAlmostEqual(12566370.61, areaCalculator.calculate_circle_area(), delta=0.01) def test_calculate_sphere_area_4(self): areaCalculator = AreaCalculator(0) self.assertAlmostEqual(0, areaCalculator.calculate_circle_area(), delta=0.01) def test_calculate_sphere_area_5(self): areaCalculator = AreaCalculator(0.1) self.assertAlmostEqual(0.031, areaCalculator.calculate_circle_area(), delta=0.01) class AreaCalculatorTestCalculateCylinderArea(unittest.TestCase): def test_calculate_cylinder_area(self): areaCalculator = AreaCalculator(2) self.assertAlmostEqual(50.27, areaCalculator.calculate_cylinder_area(2), delta=0.01) def test_calculate_cylinder_area_2(self): areaCalculator = AreaCalculator(2) self.assertAlmostEqual(25.13, areaCalculator.calculate_cylinder_area(0), delta=0.01) def test_calculate_cylinder_area_3(self): areaCalculator = AreaCalculator(0) self.assertAlmostEqual(0, areaCalculator.calculate_cylinder_area(2000), delta=0.01) def test_calculate_cylinder_area_4(self): areaCalculator = AreaCalculator(2.5) self.assertAlmostEqual(70.68, areaCalculator.calculate_cylinder_area(2), delta=0.01) def test_calculate_cylinder_area_5(self): areaCalculator = AreaCalculator(2.5) self.assertAlmostEqual(62.83, areaCalculator.calculate_cylinder_area(1.5), delta=0.01) class AreaCalculatorTestCalculateSectorArea(unittest.TestCase): def test_calculate_sector_area(self): areaCalculator = AreaCalculator(1.5) self.assertAlmostEqual(3.53, areaCalculator.calculate_sector_area(math.pi), delta=0.01) def test_calculate_sector_area_2(self): areaCalculator = AreaCalculator(2) self.assertAlmostEqual(3.14, areaCalculator.calculate_sector_area(math.pi/2), delta=0.01) def test_calculate_sector_area_3(self): areaCalculator = AreaCalculator(2) self.assertAlmostEqual(0, areaCalculator.calculate_sector_area(0), delta=0.01) def test_calculate_sector_area_4(self): areaCalculator = AreaCalculator(2) self.assertAlmostEqual(12.56, areaCalculator.calculate_sector_area(2*math.pi), delta=0.01) def test5_calculate_sector_area_5(self): areaCalculator = AreaCalculator(0) self.assertAlmostEqual(0, areaCalculator.calculate_sector_area(math.pi), delta=0.01) class AreaCalculatorTestCalculateAnnulusArea(unittest.TestCase): def test_calculate_annulus_area(self): areaCalculator = AreaCalculator(2) self.assertAlmostEqual(25.128, areaCalculator.calculate_annulus_area(1, 3), delta=0.01) def test_calculate_annulus_area_2(self): areaCalculator = AreaCalculator(2.5) self.assertAlmostEqual(0, areaCalculator.calculate_annulus_area(3, 3), delta=0.01) def test_calculate_annulus_area_3(self): areaCalculator = AreaCalculator(2000) self.assertAlmostEqual(3.14, areaCalculator.calculate_annulus_area(0, 1), delta=0.01) def test_calculate_annulus_area_4(self): areaCalculator = AreaCalculator(0) self.assertAlmostEqual(25.13, areaCalculator.calculate_annulus_area(1, 3), delta=0.01) def test_calculate_annulus_area_5(self): areaCalculator = AreaCalculator(2.5) self.assertAlmostEqual(25.13, areaCalculator.calculate_annulus_area(1, 3), delta=0.01) class AreaCalculatorTestCalculateMain(unittest.TestCase): def test_main(self): areaCalculator = AreaCalculator(2) self.assertAlmostEqual(12.56, areaCalculator.calculate_circle_area(), delta=0.01) self.assertAlmostEqual(50.27, areaCalculator.calculate_sphere_area(), delta=0.01) self.assertAlmostEqual(50.27, areaCalculator.calculate_cylinder_area(2), delta=0.01) self.assertAlmostEqual(6.28, areaCalculator.calculate_sector_area(math.pi), delta=0.01) self.assertAlmostEqual(25.128, areaCalculator.calculate_annulus_area(1, 3), delta=0.01)
[ "areaCalculator = AreaCalculator(2)\nassertAlmostEqual(12.56, areaCalculator.calculate_circle_area(), delta=0.01)\n", "areaCalculator = AreaCalculator(2)\nassertAlmostEqual(50.27, areaCalculator.calculate_sphere_area(), delta=0.01)\n", "areaCalculator = AreaCalculator(2)\nassertAlmostEqual(50.27, areaCalculator...
[]
DREval/86
class ArgumentParser: def __init__(self): self.arguments = {} self.required = set() self.types = {} def parse_arguments(self, command_string): args = command_string.split()[1:] for i in range(len(args)): arg = args[i] if arg.startswith('--'): key_value = arg[2:].split('=') if len(key_value) == 2: self.arguments[key_value[0]] = self._convert_type(key_value[0], key_value[1]) else: self.arguments[key_value[0]] = True elif arg.startswith('-'): key = arg[1:] if i + 1 < len(args) and not args[i + 1].startswith('-'): self.arguments[key] = self._convert_type(key, args[i + 1]) else: self.arguments[key] = True missing_args = self.required - set(self.arguments.keys()) if missing_args: return False, missing_args return True, None def get_argument(self, key): return self.arguments.get(key) def add_argument(self, arg, required=False, arg_type=str): if required: self.required.add(arg) self.types[arg] = arg_type def _convert_type(self, arg, value): try: return self.types[arg](value) except (ValueError, KeyError): return value
ArgumentParser
import unittest class ArgumentParserTestParseArguments(unittest.TestCase): def setUp(self): self.parser = ArgumentParser() # key value arguments def test_parse_arguments_1(self): command_str = "script --name=John --age=25" self.parser.add_argument("name") self.parser.add_argument("age", arg_type=int) result, missing_args = self.parser.parse_arguments(command_str) self.assertTrue(result) self.assertIsNone(missing_args) self.assertEqual(self.parser.get_argument("name"), "John") self.assertEqual(self.parser.get_argument("age"), 25) # switches options def test_parse_arguments_2(self): command_str = "script --verbose -d" self.parser.add_argument("verbose", arg_type=bool) self.parser.add_argument("d") result, missing_args = self.parser.parse_arguments(command_str) self.assertTrue(result) self.assertIsNone(missing_args) self.assertEqual(self.parser.get_argument("verbose"), True) self.assertEqual(self.parser.get_argument("d"), True) # miss required def test_parse_arguments_3(self): command_str = "script --name=John" self.parser.add_argument("name") self.parser.add_argument("age", required=True, arg_type=int) result, missing_args = self.parser.parse_arguments(command_str) self.assertFalse(result) self.assertEqual(missing_args, {"age"}) def test_parse_arguments_4(self): command_str = "script --name=John" self.parser.add_argument("name") self.parser.add_argument("age", required=False, arg_type=int) result, missing_args = self.parser.parse_arguments(command_str) self.assertTrue(result) self.assertEqual(missing_args, None) def test_parse_arguments_5(self): command_str = "script --name=John" self.parser.add_argument("name") self.parser.add_argument("age", arg_type=int) result, missing_args = self.parser.parse_arguments(command_str) self.assertTrue(result) self.assertEqual(missing_args, None) class ArgumentParserTestGetArgument(unittest.TestCase): def setUp(self): self.parser = ArgumentParser() # key exists def test_get_argument_1(self): self.parser.arguments = {"name": "John"} result = self.parser.get_argument("name") self.assertEqual(result, "John") # key not exists def test_get_argument_2(self): self.parser.arguments = {"name": "John", "age": 25} result = self.parser.get_argument("age") self.assertEqual(result, 25) def test_get_argument_3(self): self.parser.arguments = {"name": "John", "age": "25", "verbose": True} result = self.parser.get_argument("verbose") self.assertEqual(result, True) def test_get_argument_4(self): self.parser.arguments = {"name": "Amy", "age": 25, "verbose": True, "d": True} result = self.parser.get_argument("d") self.assertEqual(result, True) def test_get_argument_5(self): self.parser.arguments = {"name": "John", "age": 25, "verbose": True, "d": True, "option": "value"} result = self.parser.get_argument("option") self.assertEqual(result, "value") class ArgumentParserTestAddArgument(unittest.TestCase): def setUp(self): self.parser = ArgumentParser() def test_add_argument(self): self.parser.add_argument("name") self.parser.add_argument("age", required=True, arg_type=int) self.assertEqual(self.parser.required, {"age"}) self.assertEqual(self.parser.types, {"name": str, "age": int}) def test_add_argument_2(self): self.parser.add_argument("name") self.parser.add_argument("age", required=False, arg_type=int) self.parser.add_argument("verbose", arg_type=bool) self.assertEqual(self.parser.required, set()) self.assertEqual(self.parser.types, {"name": str, "age": int, "verbose": bool}) def test_add_argument_3(self): self.parser.add_argument("name") self.parser.add_argument("age", required=False, arg_type=int) self.parser.add_argument("verbose", arg_type=bool) self.parser.add_argument("d") self.assertEqual(self.parser.required, set()) self.assertEqual(self.parser.types, {"name": str, "age": int, "verbose": bool, "d": str}) def test_add_argument_4(self): self.parser.add_argument("name") self.parser.add_argument("age", required=False, arg_type=int) self.parser.add_argument("verbose", arg_type=bool) self.parser.add_argument("d") self.parser.add_argument("option") self.assertEqual(self.parser.required, set()) self.assertEqual(self.parser.types, {"name": str, "age": int, "verbose": bool, "d": str, "option": str}) def test_add_argument_5(self): self.parser.add_argument("name") self.parser.add_argument("age", required=False, arg_type=int) self.parser.add_argument("verbose", arg_type=bool) self.parser.add_argument("d") self.parser.add_argument("option") self.parser.add_argument("option2", arg_type=bool) self.assertEqual(self.parser.required, set()) self.assertEqual(self.parser.types, {"name": str, "age": int, "verbose": bool, "d": str, "option": str, "option2": bool}) class ArgumentParserTestConvertType(unittest.TestCase): def setUp(self): self.parser = ArgumentParser() def test_convert_type_1(self): self.parser.types = {"age": int} result = self.parser._convert_type("age", "25") self.assertEqual(result, 25) # fail def test_convert_type_2(self): self.parser.types = {"age": int} result = self.parser._convert_type("age", "twenty-five") self.assertEqual(result, "twenty-five") def test_convert_type_3(self): self.parser.types = {"age": int} result = self.parser._convert_type("age", "25") self.assertEqual(result, 25) def test_convert_type_4(self): self.parser.types = {"age": int, "verbose": bool} result = self.parser._convert_type("verbose", "True") self.assertEqual(result, True) def test_convert_type_5(self): self.parser.types = {"age": int, "verbose": bool} result = self.parser._convert_type("verbose", "False") self.assertEqual(result, True) class ArgumentParserTestMain(unittest.TestCase): def test_main(self): parser = ArgumentParser() command = "script --arg1=21 --option1 -arg2 value -option2" parser.add_argument('arg1', required=True, arg_type=int) parser.add_argument('arg2') self.assertEqual(parser.required, {'arg1'}) self.assertEqual(parser.types, {'arg1': int, 'arg2': str}) self.assertEqual(parser.arguments, {}) parser.parse_arguments(command) arguments = {'arg1': 21, 'option1': True, 'arg2': 'value', 'option2': True} self.assertEqual(parser.arguments, arguments)
[ "command_str = \"script --name=John --age=25\"\nself.parser.add_argument(\"name\")\nself.parser.add_argument(\"age\", arg_type=int)\nresult, missing_args = self.parser.parse_arguments(command_str)\nassertTrue(result)\nassertIsNone(missing_args)\nassertEqual(self.parser.get_argument(\"name\"), \"John\")\nassertEqual...
[]
DREval/87
import itertools class ArrangementCalculator: def __init__(self, datas): self.datas = datas @staticmethod def count(n, m=None): if m is None or n == m: return ArrangementCalculator.factorial(n) else: return ArrangementCalculator.factorial(n) // ArrangementCalculator.factorial(n - m) @staticmethod def count_all(n): total = 0 for i in range(1, n + 1): total += ArrangementCalculator.count(n, i) return total def select(self, m=None): if m is None: m = len(self.datas) result = [] for permutation in itertools.permutations(self.datas, m): result.append(list(permutation)) return result def select_all(self): result = [] for i in range(1, len(self.datas) + 1): result.extend(self.select(i)) return result @staticmethod def factorial(n): result = 1 for i in range(2, n + 1): result *= i return result
ArrangementCalculator
import unittest class ArrangementCalculatorTestCount(unittest.TestCase): def test_count_1(self): res = ArrangementCalculator.count(5, 3) self.assertEqual(res, 60) def test_count_2(self): res = ArrangementCalculator.count(4, 3) self.assertEqual(res, 24) def test_count_3(self): res = ArrangementCalculator.count(6, 3) self.assertEqual(res, 120) def test_count_4(self): res = ArrangementCalculator.count(7, 3) self.assertEqual(res, 210) def test_count_5(self): res = ArrangementCalculator.count(4, 4) self.assertEqual(res, 24) class ArrangementCalculatorTestCountAll(unittest.TestCase): def test_count_all_1(self): res = ArrangementCalculator.count_all(4) self.assertEqual(res, 64) def test_count_all_2(self): res = ArrangementCalculator.count_all(1) self.assertEqual(res, 1) def test_count_all_3(self): res = ArrangementCalculator.count_all(2) self.assertEqual(res, 4) def test_count_all_4(self): res = ArrangementCalculator.count_all(3) self.assertEqual(res, 15) def test_count_all_5(self): res = ArrangementCalculator.count_all(5) self.assertEqual(res, 325) class ArrangementCalculatorTestSelect(unittest.TestCase): def test_select_1(self): ac = ArrangementCalculator([1, 2, 3, 4]) res = ac.select(2) expected = [[1, 2], [1, 3], [1, 4], [2, 1], [2, 3], [2, 4], [3, 1], [3, 2], [3, 4], [4, 1], [4, 2], [4, 3]] self.assertEqual(res, expected) def test_select_2(self): ac = ArrangementCalculator([1, 2, 3]) res = ac.select(2) expected = [[1, 2], [1, 3], [2, 1], [2, 3], [3, 1], [3, 2]] self.assertEqual(res, expected) def test_select_3(self): ac = ArrangementCalculator([2, 3, 4]) res = ac.select(2) expected = [[2, 3], [2, 4], [3, 2], [3, 4], [4, 2], [4, 3]] self.assertEqual(res, expected) def test_select_4(self): ac = ArrangementCalculator([1, 2]) res = ac.select(2) expected = [[1, 2], [2, 1]] self.assertEqual(res, expected) def test_select_5(self): ac = ArrangementCalculator([1, 2, 3, 4]) res = ac.select(1) expected = [[1], [2], [3], [4]] self.assertEqual(res, expected) def test_select_6(self): ac = ArrangementCalculator([1, 2]) res = ac.select() expected = [[1, 2], [2, 1]] self.assertEqual(res, expected) class ArrangementCalculatorTestSelectAll(unittest.TestCase): def test_select_all_1(self): ac = ArrangementCalculator([1, 2, 3]) res = ac.select_all() expected = [[1], [2], [3], [1, 2], [1, 3], [2, 1], [2, 3], [3, 1], [3, 2], [1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]] self.assertEqual(res, expected) def test_select_all_2(self): ac = ArrangementCalculator([1, 2, 4]) res = ac.select_all() expected = [[1], [2], [4], [1, 2], [1, 4], [2, 1], [2, 4], [4, 1], [4, 2], [1, 2, 4], [1, 4, 2], [2, 1, 4], [2, 4, 1], [4, 1, 2], [4, 2, 1]] self.assertEqual(res, expected) def test_select_all_3(self): ac = ArrangementCalculator([1, 2]) res = ac.select_all() expected = [[1], [2], [1, 2], [2, 1]] self.assertEqual(res, expected) def test_select_all_4(self): ac = ArrangementCalculator([1, 3]) res = ac.select_all() expected = [[1], [3], [1, 3], [3, 1]] self.assertEqual(res, expected) def test_select_all_5(self): ac = ArrangementCalculator([1]) res = ac.select_all() expected = [[1]] self.assertEqual(res, expected) class ArrangementCalculatorTestFactorial(unittest.TestCase): def test_factorial_1(self): res = ArrangementCalculator.factorial(4) self.assertEqual(res, 24) def test_factorial_2(self): res = ArrangementCalculator.factorial(5) self.assertEqual(res, 120) def test_factorial_3(self): res = ArrangementCalculator.factorial(3) self.assertEqual(res, 6) def test_factorial_4(self): res = ArrangementCalculator.factorial(2) self.assertEqual(res, 2) def test_factorial_5(self): res = ArrangementCalculator.factorial(1) self.assertEqual(res, 1) class ArrangementCalculatorTest(unittest.TestCase): def test_arrangementcalculator(self): res = ArrangementCalculator.count(5, 3) self.assertEqual(res, 60) res = ArrangementCalculator.count_all(4) self.assertEqual(res, 64) ac = ArrangementCalculator([1, 2, 3, 4]) res = ac.select(2) expected = [[1, 2], [1, 3], [1, 4], [2, 1], [2, 3], [2, 4], [3, 1], [3, 2], [3, 4], [4, 1], [4, 2], [4, 3]] self.assertEqual(res, expected) ac = ArrangementCalculator([1, 2, 3]) res = ac.select_all() expected = [[1], [2], [3], [1, 2], [1, 3], [2, 1], [2, 3], [3, 1], [3, 2], [1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]] self.assertEqual(res, expected) res = ArrangementCalculator.factorial(4) self.assertEqual(res, 24)
[ "res = ArrangementCalculator.count(5, 3)\nassertEqual(res, 60)\n", "res = ArrangementCalculator.count_all(4)\nassertEqual(res, 64)\n", "ac = ArrangementCalculator([1, 2, 3, 4])\nres = ac.select(2)\nexpected = [[1, 2], [1, 3], [1, 4], [2, 1], [2, 3], [2, 4], [3, 1], [3, 2], [3, 4], [4, 1], [4, 2], [4, 3]]\nasser...
[]
DREval/88
class AssessmentSystem: def __init__(self): self.students = {} def add_student(self, name, grade, major): self.students[name] = {'name': name, 'grade': grade, 'major': major, 'courses': {}} def add_course_score(self, name, course, score): if name in self.students: self.students[name]['courses'][course] = score def get_gpa(self, name): if name in self.students and self.students[name]['courses']: return sum(self.students[name]['courses'].values()) / len(self.students[name]['courses']) else: return None def get_all_students_with_fail_course(self): students = [] for name, student in self.students.items(): for course, score in student['courses'].items(): if score < 60: students.append(name) break return students def get_course_average(self, course): total = 0 count = 0 for student in self.students.values(): if course in student['courses']: score = student['courses'][course] if score is not None: total += score count += 1 return total / count if count > 0 else None def get_top_student(self): top_student = None top_gpa = 0 for name, student in self.students.items(): gpa = self.get_gpa(name) if gpa is not None and gpa > top_gpa: top_gpa = gpa top_student = name return top_student
AssessmentSystem
import unittest class AssessmentSystemTestAddStudent(unittest.TestCase): def test_add_student(self): assessment_system = AssessmentSystem() assessment_system.add_student("Alice", 3, "Mathematics") self.assertEqual(assessment_system.students["Alice"], {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': {}}) def test_add_student_2(self): assessment_system = AssessmentSystem() assessment_system.add_student("Alice", 3, "Mathematics") assessment_system.add_student("Bob", 2, "Science") self.assertEqual(assessment_system.students, {'Alice': {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': {}}, 'Bob': {'name': 'Bob', 'grade': 2, 'major': 'Science', 'courses': {}}}) def test_add_student_3(self): assessment_system = AssessmentSystem() assessment_system.add_student("Alice", 3, "Mathematics") assessment_system.add_student("Bob", 2, "Science") assessment_system.add_student("Charlie", 4, "Chemistry") self.assertEqual(assessment_system.students, {'Alice': {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': {}}, 'Bob': {'name': 'Bob', 'grade': 2, 'major': 'Science', 'courses': {}}, 'Charlie': {'name': 'Charlie', 'grade': 4, 'major': 'Chemistry', 'courses': {}}}) def test_add_student_4(self): assessment_system = AssessmentSystem() assessment_system.add_student("Alice", 3, "Mathematics") assessment_system.add_student("Bob", 2, "Science") assessment_system.add_student("Charlie", 4, "Chemistry") assessment_system.add_student("David", 1, "Physics") self.assertEqual(assessment_system.students, {'Alice': {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': {}}, 'Bob': {'name': 'Bob', 'grade': 2, 'major': 'Science', 'courses': {}}, 'Charlie': {'name': 'Charlie', 'grade': 4, 'major': 'Chemistry', 'courses': {}}, 'David': {'name': 'David', 'grade': 1, 'major': 'Physics', 'courses': {}}}) def test_add_student_5(self): assessment_system = AssessmentSystem() assessment_system.add_student("Alice", 3, "Mathematics") assessment_system.add_student("Bob", 2, "Science") assessment_system.add_student("Charlie", 4, "Chemistry") assessment_system.add_student("David", 1, "Physics") assessment_system.add_student("Eve", 3, "Mathematics") self.assertEqual(assessment_system.students, {'Alice': {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': {}}, 'Bob': {'name': 'Bob', 'grade': 2, 'major': 'Science', 'courses': {}}, 'Charlie': {'name': 'Charlie', 'grade': 4, 'major': 'Chemistry', 'courses': {}}, 'David': {'name': 'David', 'grade': 1, 'major': 'Physics', 'courses': {}}, 'Eve': {'name': 'Eve', 'grade': 3, 'major': 'Mathematics', 'courses': {}}}) class AssessmentSystemTestAddCourseScore(unittest.TestCase): def test_add_course_score(self): assessment_system = AssessmentSystem() assessment_system.students = {"Alice": {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': {}}} assessment_system.add_course_score("Alice", "Math", 90) self.assertEqual(assessment_system.students["Alice"]["courses"]["Math"], 90) def test_add_course_score_2(self): assessment_system = AssessmentSystem() assessment_system.students["Alice"] = {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': {}} assessment_system.add_course_score("Alice", "Math", 90) self.assertEqual(assessment_system.students["Alice"]["courses"]["Math"], 90) def test_add_course_score_3(self): assessment_system = AssessmentSystem() assessment_system.students["Alice"] = {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': {}} assessment_system.add_course_score("Alice", "Math", 90) assessment_system.add_course_score("Alice", "Science", 80) assessment_system.add_course_score("Alice", "Math", 95) self.assertEqual(assessment_system.students["Alice"]["courses"]["Math"], 95) self.assertEqual(assessment_system.students["Alice"]["courses"]["Science"], 80) def test_add_course_score_4(self): assessment_system = AssessmentSystem() assessment_system.students["Alice"] = {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': {}} assessment_system.add_course_score("Alice", "Math", 90) assessment_system.add_course_score("Alice", "Science", 80) assessment_system.add_course_score("Alice", "Math", 95) assessment_system.add_course_score("Alice", "Science", 85) self.assertEqual(assessment_system.students["Alice"]["courses"]["Math"], 95) self.assertEqual(assessment_system.students["Alice"]["courses"]["Science"], 85) def test_add_course_score_5(self): assessment_system = AssessmentSystem() assessment_system.students["Alice"] = {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': {}} assessment_system.add_course_score("Bob", "Math", 90) self.assertEqual(assessment_system.students["Alice"]["courses"], {}) class AssessmentSystemTestGetGPA(unittest.TestCase): def test_get_gpa_1(self): assessment_system = AssessmentSystem() assessment_system.students = {'Alice': {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': {'Mathematics': 90, 'Science': 80}}} self.assertEqual(assessment_system.get_gpa("Alice"), 85.0) # No such student def test_get_gpa_2(self): assessment_system = AssessmentSystem() self.assertEqual(assessment_system.get_gpa('Alice'), None) # student don't have any scores def test_get_gpa_3(self): assessment_system = AssessmentSystem() assessment_system.students = {'Alice': {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': {}}} self.assertEqual(assessment_system.get_gpa('Alice'), None) def test_get_gpa_4(self): assessment_system = AssessmentSystem() assessment_system.students = {'Alice': {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': {'Mathematics': 90}}} self.assertEqual(assessment_system.get_gpa('Bob'), None) def test_get_gpa_5(self): assessment_system = AssessmentSystem() assessment_system.students = {'Alice': {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': {'Mathematics': 90}}} self.assertEqual(assessment_system.get_gpa('Alice'), 90.0) class AssessmentSystemTestGetAllStudentsWithFailCourse(unittest.TestCase): def test_get_all_students_with_fail_course(self): assessment_system = AssessmentSystem() assessment_system.students = {'Alice': {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': {'Mathematics': 90, 'Science': 80}}, 'Bob': {'name': 'Bob', 'grade': 4, 'major': 'Physics', 'courses': {'Physics': 50}}, 'Charlie': {'name': 'Charlie', 'grade': 2, 'major': 'Chemistry', 'courses': {'Chemistry': 70}}, 'David': {'name': 'David', 'grade': 1, 'major': 'Physics', 'courses': {'Physics': 60}}, 'Eve': {'name': 'Eve', 'grade': 3, 'major': 'Mathematics', 'courses': {'Mathematics': 90}}} self.assertEqual(assessment_system.get_all_students_with_fail_course(), ['Bob']) def test_get_all_students_with_fail_course_2(self): assessment_system = AssessmentSystem() assessment_system.students = {'Alice': {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': {'Mathematics': 90, 'Science': 80}}, 'Bob': {'name': 'Bob', 'grade': 4, 'major': 'Physics', 'courses': {'Physics': 70}}, 'Charlie': {'name': 'Charlie', 'grade': 2, 'major': 'Chemistry', 'courses': {'Chemistry': 70}}, 'David': {'name': 'David', 'grade': 1, 'major': 'Physics', 'courses': {'Physics': 70}}, 'Eve': {'name': 'Eve', 'grade': 3, 'major': 'Mathematics', 'courses': {'Mathematics': 90}}} self.assertEqual(assessment_system.get_all_students_with_fail_course(), []) def test_get_all_students_with_fail_course_3(self): assessment_system = AssessmentSystem() assessment_system.students = {} self.assertEqual(assessment_system.get_all_students_with_fail_course(), []) def test_get_all_students_with_fail_course_4(self): assessment_system = AssessmentSystem() assessment_system.students = {'Alice': {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': {}}} self.assertEqual(assessment_system.get_all_students_with_fail_course(), []) def test_get_all_students_with_fail_course_5(self): assessment_system = AssessmentSystem() assessment_system.students = {'Alice': {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': {'Mathematics': 90, 'Science': 50}}, 'Bob': {'name': 'Bob', 'grade': 4, 'major': 'Physics', 'courses': {'Physics': 50}}, 'Charlie': {'name': 'Charlie', 'grade': 2, 'major': 'Chemistry', 'courses': {'Chemistry': 70}}, 'David': {'name': 'David', 'grade': 1, 'major': 'Physics', 'courses': {'Physics': 70}}, 'Eve': {'name': 'Eve', 'grade': 3, 'major': 'Mathematics', 'courses': {'Mathematics': 90}}} self.assertEqual(assessment_system.get_all_students_with_fail_course(), ['Alice', 'Bob']) class AssessmentSystemTestGetCourseAverage(unittest.TestCase): def test_get_course_average_1(self): assessment_system = AssessmentSystem() assessment_system.students = {'Alice': {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': {'Mathematics': 90, 'Science': 80}}, 'Bob': {'name': 'Bob', 'grade': 4, 'major': 'Physics', 'courses': {'Physics': 90}}, 'Charlie': {'name': 'Charlie', 'grade': 2, 'major': 'Chemistry', 'courses': {'Chemistry': 70,'Physics': 80}} } self.assertEqual(assessment_system.get_course_average("Physics"), 85.0) def test_get_course_average_2(self): assessment_system = AssessmentSystem() assessment_system.students = {'Alice': {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': {'Mathematics': 90, 'Science': 80}}, 'Bob': {'name': 'Bob', 'grade': 4, 'major': 'Physics', 'courses': {'Physics': 85}}, 'Charlie': {'name': 'Charlie', 'grade': 2, 'major': 'Chemistry', 'courses': {'Chemistry': 70,'Physics': None }} } self.assertEqual(assessment_system.get_course_average('Physics'), 85) def test_get_course_average_3(self): assessment_system = AssessmentSystem() assessment_system.students = {'Alice': {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': {'Mathematics': 90, 'Science': 80}}, 'Bob': {'name': 'Bob', 'grade': 4, 'major': 'Physics', 'courses': {'Physics': 85}}, 'Charlie': {'name': 'Charlie', 'grade': 2, 'major': 'Chemistry', 'courses': {'Chemistry': 70, 'Physics': 80}} } self.assertEqual(assessment_system.get_course_average('Computer'), None) def test_get_course_average_4(self): assessment_system = AssessmentSystem() assessment_system.students = {} self.assertEqual(assessment_system.get_course_average('Computer'), None) def test_get_course_average_5(self): assessment_system = AssessmentSystem() assessment_system.students = {'Alice': {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': {'Mathematics': 90, 'Science': 80}}, 'Bob': {'name': 'Bob', 'grade': 4, 'major': 'Physics', 'courses': {'Physics': 85}}, 'Charlie': {'name': 'Charlie', 'grade': 2, 'major': 'Chemistry', 'courses': {'Chemistry': 70, 'Physics': 80}} } self.assertEqual(assessment_system.get_course_average('Mathematics'), 90) class AssessmentSystemTestGetTopStudent(unittest.TestCase): def test_get_top_student(self): assessment_system = AssessmentSystem() assessment_system.students = {'Alice': {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': {'Mathematics': 90}}, 'Bob': {'name': 'Bob', 'grade': 4, 'major': 'Physics', 'courses': {'Physics': 85}} } self.assertEqual(assessment_system.get_top_student(), "Alice") def test_get_top_student_2(self): assessment_system = AssessmentSystem() assessment_system.students = {'Alice': {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': { }}, 'Bob': {'name': 'Bob', 'grade': 4, 'major': 'Physics', 'courses': {'Physics': 85}}, 'Charlie': {'name': 'Charlie', 'grade': 2, 'major': 'Chemistry', 'courses': {'Chemistry': 70, 'Physics': 80}} } self.assertEqual(assessment_system.get_top_student(), "Bob") def test_get_top_student_3(self): assessment_system = AssessmentSystem() assessment_system.students = {} self.assertEqual(assessment_system.get_top_student(), None) def test_get_top_student_4(self): assessment_system = AssessmentSystem() assessment_system.students = {'Alice': {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': {'Mathematics': 90, 'Science': 60}}, 'Bob': {'name': 'Bob', 'grade': 4, 'major': 'Physics', 'courses': {'Physics': 85}}, 'Charlie': {'name': 'Charlie', 'grade': 2, 'major': 'Chemistry', 'courses': {'Chemistry': 70, 'Physics': 80}} } self.assertEqual(assessment_system.get_top_student(), "Bob") def test_get_top_student_5(self): assessment_system = AssessmentSystem() assessment_system.students = {'Alice': {'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': {'Mathematics': 90, 'Science': 60}}, 'Bob': {'name': 'Bob', 'grade': 4, 'major': 'Physics', 'courses': {'Physics': 85}}, 'Charlie': {'name': 'Charlie', 'grade': 2, 'major': 'Chemistry', 'courses': {'Chemistry': 70, 'Physics': 80}}, 'David': {'name': 'David', 'grade': 2, 'major': 'Chemistry', 'courses': {'Chemistry': 70, 'Physics': 80}} } self.assertEqual(assessment_system.get_top_student(), "Bob") class AssessmentSystemTestMain(unittest.TestCase): def test_main(self): system = AssessmentSystem() system.add_student('student 1', 3, 'SE') system.add_student('student 2', 2, 'SE') self.assertEqual({'student 1': {'name': 'student 1', 'grade': 3, 'major': 'SE', 'courses': {}}, 'student 2': {'name': 'student 2', 'grade': 2, 'major': 'SE', 'courses': {}}}, system.students) system.add_course_score('student 1', 'course 1', 86) system.add_course_score('student 2', 'course 1', 59) system.add_course_score('student 1', 'course 2', 78) system.add_course_score('student 2', 'course 2', 90) self.assertEqual(system.students['student 1']['courses']['course 1'], 86) self.assertEqual(system.students['student 1']['courses']['course 2'], 78) self.assertEqual(system.students['student 2']['courses']['course 1'], 59) self.assertEqual(system.students['student 2']['courses']['course 2'], 90) self.assertEqual(system.get_all_students_with_fail_course(), ['student 2']) self.assertEqual(system.get_course_average('course 1'), 72.5) self.assertEqual(system.get_course_average('course 2'), 84) self.assertEqual(system.get_gpa('student 1'), 82.0) self.assertEqual(system.get_gpa('student 2'), 74.5) self.assertEqual(system.get_top_student(), 'student 1')
[ "assessment_system = AssessmentSystem()\nassessment_system.add_student(\"Alice\", 3, \"Mathematics\")\nassertEqual(assessment_system.students[\"Alice\"],\n{'name': 'Alice', 'grade': 3, 'major': 'Mathematics', 'courses': {}})\n", "assessment_system = AssessmentSystem()\nassessment_system.students = {\"Alice\": {'n...
[]
DREval/89
class AutomaticGuitarSimulator: def __init__(self, text) -> None: self.play_text = text def interpret(self, display=False): if len(self.play_text) == 0: return else: play_list = [] play_segs = self.play_text.split(" ") for play_seg in play_segs: pos = 0 for ele in play_seg: if ele.isalpha(): pos += 1 continue break play_chord = play_seg[0:pos] play_value = play_seg[pos:] play_list.append({'Chord': play_chord, 'Tune': play_value}) if display: self.display(play_chord, play_value) return play_list def display(self, key, value): return "Normal Guitar Playing -- Chord: %s, Play Tune: %s" % (key, value)
AutomaticGuitarSimulator
import unittest class AutomaticGuitarSimulatorTestInterpret(unittest.TestCase): def test_interpret_1(self): context = AutomaticGuitarSimulator("C53231323") play_list = context.interpret() self.assertEqual(play_list, [{'Chord': 'C', 'Tune': '53231323'}]) def test_interpret_2(self): context = AutomaticGuitarSimulator("F43231323") play_list = context.interpret() self.assertEqual(play_list, [{'Chord': 'F', 'Tune': '43231323'}]) def test_interpret_3(self): context = AutomaticGuitarSimulator("Em43231323") play_list = context.interpret() self.assertEqual(play_list, [{'Chord': 'Em', 'Tune': '43231323'}]) def test_interpret_4(self): context = AutomaticGuitarSimulator("G63231323") play_list = context.interpret() self.assertEqual(play_list, [{'Chord': 'G', 'Tune': '63231323'}]) def test_interpret_5(self): context = AutomaticGuitarSimulator("F43231323 G63231323") play_list = context.interpret() self.assertEqual(play_list, [{'Chord': 'F', 'Tune': '43231323'}, {'Chord': 'G', 'Tune': '63231323'}]) def test_interpret_6(self): context = AutomaticGuitarSimulator(" ") play_list = context.interpret() self.assertEqual(play_list, [{'Chord': '', 'Tune': ''}, {'Chord': '', 'Tune': ''}]) def test_interpret_7(self): context = AutomaticGuitarSimulator("ABC43231323 DEF63231323") play_list = context.interpret() self.assertEqual(play_list, [{'Chord': 'ABC', 'Tune': '43231323'}, {'Chord': 'DEF', 'Tune': '63231323'}]) def test_interpret_8(self): context = AutomaticGuitarSimulator("C53231323") play_list = context.interpret(display=True) self.assertEqual(play_list, [{'Chord': 'C', 'Tune': '53231323'}]) def test_interpret_9(self): context = AutomaticGuitarSimulator("") play_list = context.interpret() self.assertIsNone(play_list) class AutomaticGuitarSimulatorTestDisplay(unittest.TestCase): def test_display_1(self): context = AutomaticGuitarSimulator("C53231323 Em43231323") play_list = context.interpret() str = context.display(play_list[0]['Chord'], play_list[0]['Tune']) self.assertEqual(str, "Normal Guitar Playing -- Chord: C, Play Tune: 53231323") def test_display_2(self): context = AutomaticGuitarSimulator("C53231323 Em43231323") play_list = context.interpret() str = context.display(play_list[1]['Chord'], play_list[1]['Tune']) self.assertEqual(str, "Normal Guitar Playing -- Chord: Em, Play Tune: 43231323") def test_display_3(self): context = AutomaticGuitarSimulator("F43231323 G63231323") play_list = context.interpret() str = context.display(play_list[0]['Chord'], play_list[0]['Tune']) self.assertEqual(str, "Normal Guitar Playing -- Chord: F, Play Tune: 43231323") def test_display_4(self): context = AutomaticGuitarSimulator("F43231323 G63231323") play_list = context.interpret() str = context.display(play_list[1]['Chord'], play_list[1]['Tune']) self.assertEqual(str, "Normal Guitar Playing -- Chord: G, Play Tune: 63231323") def test_display_5(self): context = AutomaticGuitarSimulator("") str = context.display('', '') self.assertEqual(str, "Normal Guitar Playing -- Chord: , Play Tune: ") class AutomaticGuitarSimulatorTest(unittest.TestCase): def test_AutomaticGuitarSimulator(self): context = AutomaticGuitarSimulator("C53231323") play_list = context.interpret() self.assertEqual(play_list, [{'Chord': 'C', 'Tune': '53231323'}]) context = AutomaticGuitarSimulator("C53231323 Em43231323") play_list = context.interpret() str = context.display(play_list[0]['Chord'], play_list[0]['Tune']) self.assertEqual(str, "Normal Guitar Playing -- Chord: C, Play Tune: 53231323")
[ "context = AutomaticGuitarSimulator(\"C53231323\")\nplay_list = context.interpret()\nassertEqual(play_list, [{'Chord': 'C', 'Tune': '53231323'}])\n", "context = AutomaticGuitarSimulator(\"C53231323 Em43231323\")\nplay_list = context.interpret()\nstr = context.display(play_list[0]['Chord'], play_list[0]['Tune'])\n...
[]
DREval/90
class AvgPartition: def __init__(self, lst, limit): self.lst = lst self.limit = limit def setNum(self): size = len(self.lst) // self.limit remainder = len(self.lst) % self.limit return size, remainder def get(self, index): size, remainder = self.setNum() start = index * size + min(index, remainder) end = start + size if index + 1 <= remainder: end += 1 return self.lst[start:end]
AvgPartition
import unittest class AvgPartitionTestSetNum(unittest.TestCase): def test_setNum(self): a = AvgPartition([1, 2, 3, 4], 2) self.assertEqual(a.setNum(), (2, 0)) def test_setNum_2(self): a = AvgPartition([1, 2, 3, 4, 5], 2) self.assertEqual(a.setNum(), (2, 1)) def test_setNum_3(self): a = AvgPartition([1, 2, 3, 4, 5], 3) self.assertEqual(a.setNum(), (1, 2)) def test_setNum_4(self): a = AvgPartition([1, 2, 3, 4, 5], 4) self.assertEqual(a.setNum(), (1, 1)) def test_setNum_5(self): a = AvgPartition([1, 2, 3, 4, 5], 5) self.assertEqual(a.setNum(), (1, 0)) class AvgPartitionTestGet(unittest.TestCase): def test_get(self): a = AvgPartition([1, 2, 3, 4], 2) self.assertEqual(a.get(0), [1, 2]) def test_get_2(self): a = AvgPartition([1, 2, 3, 4], 2) self.assertEqual(a.get(1), [3, 4]) def test_get_3(self): a = AvgPartition([1, 2, 3, 4, 5], 2) self.assertEqual(a.get(0), [1, 2, 3]) def test_get_4(self): a = AvgPartition([1, 2, 3, 4, 5], 2) self.assertEqual(a.get(1), [4, 5]) def test_get_5(self): a = AvgPartition([1, 2, 3, 4, 5], 3) self.assertEqual(a.get(0), [1, 2]) class AvgPartitionTestMain(unittest.TestCase): def test_main(self): a = AvgPartition([1, 2, 3, 4], 2) self.assertEqual(a.setNum(), (2, 0)) self.assertEqual(a.get(0), [1, 2])
[ "a = AvgPartition([1, 2, 3, 4], 2)\nassertEqual(a.setNum(), (2, 0))\n", "a = AvgPartition([1, 2, 3, 4], 2)\nassertEqual(a.get(0), [1, 2])\n", "a = AvgPartition([1, 2, 3, 4], 2)\nassertEqual(a.setNum(), (2, 0))\nassertEqual(a.get(0), [1, 2])\n" ]
[]
DREval/91
class BalancedBrackets: def __init__(self, expr): self.stack = [] self.left_brackets = ["(", "{", "["] self.right_brackets = [")", "}", "]"] self.expr = expr def clear_expr(self): self.expr = ''.join(c for c in self.expr if (c in self.left_brackets or c in self.right_brackets)) def check_balanced_brackets(self): self.clear_expr() for Brkt in self.expr: if Brkt in self.left_brackets: self.stack.append(Brkt) else: Current_Brkt = self.stack.pop() if Current_Brkt == "(": if Brkt != ")": return False if Current_Brkt == "{": if Brkt != "}": return False if Current_Brkt == "[": if Brkt != "]": return False if self.stack: return False return True
BalancedBrackets
import unittest class BalancedBracketsTestClearExpr(unittest.TestCase): def test_clear_expr(self): b = BalancedBrackets("a(b)c") b.clear_expr() self.assertEqual(b.expr, "()") def test_clear_expr_2(self): b = BalancedBrackets("a(b){c}") b.clear_expr() self.assertEqual(b.expr, "(){}") def test_clear_expr_3(self): b = BalancedBrackets("[a](b){c}") b.clear_expr() self.assertEqual(b.expr, "[](){}") def test_clear_expr_4(self): b = BalancedBrackets("[a(b){c}") b.clear_expr() self.assertEqual(b.expr, "[(){}") def test_clear_expr_5(self): b = BalancedBrackets("a(b){c}]") b.clear_expr() self.assertEqual(b.expr, "(){}]") class BalancedBracketsTestCheckBalancedBrackets(unittest.TestCase): def test_check_balanced_brackets(self): b = BalancedBrackets("a(b)c") self.assertEqual(b.check_balanced_brackets(), True) def test_check_balanced_brackets_2(self): b = BalancedBrackets("a(b){c}") self.assertEqual(b.check_balanced_brackets(), True) def test_check_balanced_brackets_3(self): b = BalancedBrackets("[a](b){c}") self.assertEqual(b.check_balanced_brackets(), True) def test_check_balanced_brackets_4(self): b = BalancedBrackets("[a(b){c}") self.assertEqual(b.check_balanced_brackets(), False) def test_check_balanced_brackets_5(self): b = BalancedBrackets("a(b{c}]") self.assertEqual(b.check_balanced_brackets(), False) def test_check_balanced_brackets_6(self): b = BalancedBrackets("a(b{c]]") self.assertEqual(b.check_balanced_brackets(), False) def test_check_balanced_brackets_7(self): b = BalancedBrackets("[a)(b){c}") self.assertEqual(b.check_balanced_brackets(), False) class BalancedBracketsTestMain(unittest.TestCase): def test_main(self): b = BalancedBrackets("a(b)c") b.clear_expr() self.assertEqual(b.expr, "()") self.assertEqual(b.check_balanced_brackets(), True) def test_main_2(self): b = BalancedBrackets("[a(b){c}") b.clear_expr() self.assertEqual(b.expr, "[(){}") self.assertEqual(b.check_balanced_brackets(), False) def test_main_3(self): b = BalancedBrackets("a(b{c}]") b.clear_expr() self.assertEqual(b.expr, "({}]") self.assertEqual(b.check_balanced_brackets(), False)
[ "b = BalancedBrackets(\"a(b)c\")\nb.clear_expr()\nassertEqual(b.expr, \"()\")\n", "b = BalancedBrackets(\"a(b)c\")\nassertEqual(b.check_balanced_brackets(), True)\n", "b = BalancedBrackets(\"a(b)c\")\nb.clear_expr()\nassertEqual(b.expr, \"()\")\nassertEqual(b.check_balanced_brackets(), True)\n" ]
[]
DREval/92
class BankAccount: def __init__(self, balance=0): self.balance = balance def deposit(self, amount): if amount < 0: raise ValueError("Invalid amount") self.balance += amount return self.balance def withdraw(self, amount): if amount < 0: raise ValueError("Invalid amount") if amount > self.balance: raise ValueError("Insufficient balance.") self.balance -= amount return self.balance def view_balance(self): return self.balance def transfer(self, other_account, amount): self.withdraw(amount) other_account.deposit(amount)
BankAccount
import unittest class BankAccountTestDeposit(unittest.TestCase): def test_deposit(self): account1 = BankAccount() ret = account1.deposit(1000) self.assertEqual(ret, 1000) def test_deposit_2(self): account1 = BankAccount() account1.deposit(1000) ret = account1.deposit(2000) self.assertEqual(ret, 3000) def test_deposit_3(self): account1 = BankAccount() with self.assertRaises(ValueError) as context: account1.deposit(-1000) self.assertEqual(str(context.exception), "Invalid amount") def test_deposit_4(self): account1 = BankAccount() ret = account1.deposit(0) self.assertEqual(ret, 0) def test_deposit_5(self): account1 = BankAccount() account1.deposit(1000) ret = account1.deposit(1000) self.assertEqual(ret, 2000) class BankAccountTestWithdraw(unittest.TestCase): def test_withdraw(self): account1 = BankAccount() account1.balance = 1000 ret = account1.withdraw(200) self.assertEqual(ret, 800) def test_withdraw_2(self): account1 = BankAccount() account1.balance = 500 with self.assertRaises(ValueError) as context: account1.withdraw(1000) self.assertEqual(str(context.exception), "Insufficient balance.") def test_withdraw_3(self): account1 = BankAccount() with self.assertRaises(ValueError) as context: account1.withdraw(-1000) self.assertEqual(str(context.exception), "Invalid amount") def test_withdraw_4(self): account1 = BankAccount() account1.balance = 1000 ret = account1.withdraw(500) self.assertEqual(ret, 500) def test_withdraw_5(self): account1 = BankAccount() account1.balance = 1000 ret = account1.withdraw(1000) self.assertEqual(ret, 0) class BankAccountTestViewBalance(unittest.TestCase): def test_view_balance(self): account1 = BankAccount() self.assertEqual(account1.view_balance(), 0) def test_view_balance_2(self): account1 = BankAccount() account1.balance = 1000 self.assertEqual(account1.view_balance(), 1000) def test_view_balance_3(self): account1 = BankAccount() account1.balance = 500 self.assertEqual(account1.view_balance(), 500) def test_view_balance_4(self): account1 = BankAccount() account1.balance = 1500 self.assertEqual(account1.view_balance(), 1500) def test_view_balance_5(self): account1 = BankAccount() account1.balance = 2000 self.assertEqual(account1.view_balance(), 2000) class BankAccountTestTransfer(unittest.TestCase): def test_transfer(self): account1 = BankAccount() account2 = BankAccount() account1.balance = 800 account2.balance = 1000 account1.transfer(account2, 300) self.assertEqual(account1.view_balance(), 500) self.assertEqual(account2.view_balance(), 1300) def test_transfer_2(self): account1 = BankAccount() account2 = BankAccount() account1.balance = 500 with self.assertRaises(ValueError) as context: account1.transfer(account2, 600) self.assertEqual(str(context.exception), "Insufficient balance.") def test_transfer_3(self): account1 = BankAccount() account2 = BankAccount() account1.balance = 500 account2.balance = 1000 with self.assertRaises(ValueError) as context: account1.transfer(account2, -600) self.assertEqual(str(context.exception), "Invalid amount") def test_transfer_4(self): account1 = BankAccount() account2 = BankAccount() account1.balance = 500 account2.balance = 1000 account1.transfer(account2, 500) self.assertEqual(account1.view_balance(), 0) self.assertEqual(account2.view_balance(), 1500) def test_transfer_5(self): account1 = BankAccount() account2 = BankAccount() account1.balance = 500 account2.balance = 1000 account1.transfer(account2, 200) self.assertEqual(account1.view_balance(), 300) self.assertEqual(account2.view_balance(), 1200) class BankAccountTest(unittest.TestCase): def test_all(self): account1 = BankAccount() account2 = BankAccount() account1.deposit(1000) account1.withdraw(200) account1.transfer(account2, 300) self.assertEqual(account1.view_balance(), 500) self.assertEqual(account2.view_balance(), 300) def test_all2(self): account1 = BankAccount() account2 = BankAccount() account1.deposit(1000) account1.withdraw(200) account1.transfer(account2, 300) account2.withdraw(100) self.assertEqual(account1.view_balance(), 500) self.assertEqual(account2.view_balance(), 200)
[ "account1 = BankAccount()\nret = account1.deposit(1000)\nassertEqual(ret, 1000)\n", "account1 = BankAccount()\naccount1.balance = 1000\nret = account1.withdraw(200)\nassertEqual(ret, 800)\n", "account1 = BankAccount()\nassertEqual(account1.view_balance(), 0)\n", "account1 = BankAccount()\naccount2 = BankAccou...
[]
DREval/93
class BigNumCalculator: @staticmethod def add(num1, num2): max_length = max(len(num1), len(num2)) num1 = num1.zfill(max_length) num2 = num2.zfill(max_length) carry = 0 result = [] for i in range(max_length - 1, -1, -1): digit_sum = int(num1[i]) + int(num2[i]) + carry carry = digit_sum // 10 digit = digit_sum % 10 result.insert(0, str(digit)) if carry > 0: result.insert(0, str(carry)) return ''.join(result) @staticmethod def subtract(num1, num2): if len(num1) < len(num2): num1, num2 = num2, num1 negative = True elif len(num1) > len(num2): negative = False else: if num1 < num2: num1, num2 = num2, num1 negative = True else: negative = False max_length = max(len(num1), len(num2)) num1 = num1.zfill(max_length) num2 = num2.zfill(max_length) borrow = 0 result = [] for i in range(max_length - 1, -1, -1): digit_diff = int(num1[i]) - int(num2[i]) - borrow if digit_diff < 0: digit_diff += 10 borrow = 1 else: borrow = 0 result.insert(0, str(digit_diff)) while len(result) > 1 and result[0] == '0': result.pop(0) if negative: result.insert(0, '-') return ''.join(result) @staticmethod def multiply(num1, num2): len1, len2 = len(num1), len(num2) result = [0] * (len1 + len2) for i in range(len1 - 1, -1, -1): for j in range(len2 - 1, -1, -1): mul = int(num1[i]) * int(num2[j]) p1, p2 = i + j, i + j + 1 total = mul + result[p2] result[p1] += total // 10 result[p2] = total % 10 start = 0 while start < len(result) - 1 and result[start] == 0: start += 1 return ''.join(map(str, result[start:]))
BigNumCalculator
import unittest class BigNumCalculatorTestAdd(unittest.TestCase): def test_add(self): bigNum = BigNumCalculator() self.assertEqual(bigNum.add("12345678901234567890", "98765432109876543210"), "111111111011111111100") def test_add_2(self): bigNum = BigNumCalculator() self.assertEqual(bigNum.add("123456789012345678922", "98765432109876543210"), "222222221122222222132") def test_add_3(self): bigNum = BigNumCalculator() self.assertEqual(bigNum.add("123456789012345678934", "98765432109876543210"), "222222221122222222144") def test_add_4(self): bigNum = BigNumCalculator() self.assertEqual(bigNum.add("123456789012345678946", "98765432109876543210"), "222222221122222222156") def test_add_5(self): bigNum = BigNumCalculator() self.assertEqual(bigNum.add("123456789012345678958", "98765432109876543210"), "222222221122222222168") class BigNumCalculatorTestSubtract(unittest.TestCase): def test_subtract(self): bigNum = BigNumCalculator() self.assertEqual(bigNum.subtract("12345678901234567890", "98765432109876543210"), "-86419753208641975320") def test_subtract_2(self): bigNum = BigNumCalculator() self.assertEqual(bigNum.subtract("123456789012345678922", "98765432109876543210"), "24691356902469135712") def test_subtract_3(self): bigNum = BigNumCalculator() self.assertEqual(bigNum.subtract("123456789012345678934", "98765432109876543"), "123358023580235802391") def test_subtract_4(self): bigNum = BigNumCalculator() self.assertEqual(bigNum.subtract("12345678901234567", "98765432109876543210"), "-98753086430975308643") def test_subtract_5(self): bigNum = BigNumCalculator() self.assertEqual(bigNum.subtract("923456789", "187654321"), "735802468") class BigNumCalculatorTestMultiply(unittest.TestCase): def test_multiply(self): bigNum = BigNumCalculator() self.assertEqual(bigNum.multiply("12345678901234567890", "98765432109876543210"), "1219326311370217952237463801111263526900") def test_multiply_2(self): bigNum = BigNumCalculator() self.assertEqual(bigNum.multiply("123456789012345678922", "98765432109876543210"), "12193263113702179524547477517529919219620") def test_multiply_3(self): bigNum = BigNumCalculator() self.assertEqual(bigNum.multiply("123456789012345678934", "98765432109876543"), "12193263113702179499806737010255845162") def test_multiply_4(self): bigNum = BigNumCalculator() self.assertEqual(bigNum.multiply("12345678901234567", "98765432109876543210"), "1219326311370217864336229223321140070") def test_multiply_5(self): bigNum = BigNumCalculator() self.assertEqual(bigNum.multiply("923456789", "187654321"), "173290656712635269") def test_multiply_6(self): bigNum = BigNumCalculator() self.assertEqual(bigNum.multiply("000000001", "000000001"), "1") class BigNumCalculatorTestMain(unittest.TestCase): def test_main(self): bigNum = BigNumCalculator() self.assertEqual(bigNum.add("12345678901234567890", "98765432109876543210"), "111111111011111111100") self.assertEqual(bigNum.subtract("12345678901234567890", "98765432109876543210"), "-86419753208641975320") self.assertEqual(bigNum.multiply("12345678901234567890", "98765432109876543210"), "1219326311370217952237463801111263526900")
[ "bigNum = BigNumCalculator()\nassertEqual(bigNum.add(\"12345678901234567890\", \"98765432109876543210\"), \"111111111011111111100\")\n", "bigNum = BigNumCalculator()\nassertEqual(bigNum.subtract(\"12345678901234567890\", \"98765432109876543210\"), \"-86419753208641975320\")\n", "bigNum = BigNumCalculator()\nass...
[]
DREval/94
class BinaryDataProcessor: def __init__(self, binary_string): self.binary_string = binary_string self.clean_non_binary_chars() def clean_non_binary_chars(self): self.binary_string = ''.join(filter(lambda x: x in '01', self.binary_string)) def calculate_binary_info(self): zeroes_count = self.binary_string.count('0') ones_count = self.binary_string.count('1') total_length = len(self.binary_string) zeroes_percentage = (zeroes_count / total_length) ones_percentage = (ones_count / total_length) return { 'Zeroes': zeroes_percentage, 'Ones': ones_percentage, 'Bit length': total_length } def convert_to_ascii(self): byte_array = bytearray() for i in range(0, len(self.binary_string), 8): byte = self.binary_string[i:i+8] decimal = int(byte, 2) byte_array.append(decimal) return byte_array.decode('ascii') def convert_to_utf8(self): byte_array = bytearray() for i in range(0, len(self.binary_string), 8): byte = self.binary_string[i:i+8] decimal = int(byte, 2) byte_array.append(decimal) return byte_array.decode('utf-8')
BinaryDataProcessor
import unittest class BinaryDataProcessorTestCleanNonBinaryChars(unittest.TestCase): def test_clean_non_binary_chars(self): bdp = BinaryDataProcessor("01101000daf3e4r01100101011011000110110001101111") self.assertEqual(bdp.binary_string, "0110100001100101011011000110110001101111") def test_clean_non_binary_chars_2(self): bdp = BinaryDataProcessor("01101000daf3e4r01100101011011addf0110001d1111") self.assertEqual(bdp.binary_string, "011010000110010101101101100011111") def test_clean_non_binary_chars_3(self): bdp = BinaryDataProcessor("0sd1000daf3e4r01100101011011addf0110001d1111") self.assertEqual(bdp.binary_string, "010000110010101101101100011111") def test_clean_non_binary_chars_4(self): bdp = BinaryDataProcessor("sdsdf") self.assertEqual(bdp.binary_string, "") def test_clean_non_binary_chars_5(self): bdp = BinaryDataProcessor("0") self.assertEqual(bdp.binary_string, "0") class BinaryDataProcessorTestCalculateBinaryInfo(unittest.TestCase): def test_calculate_binary_info(self): bdp = BinaryDataProcessor("0110100001100101011011000110110001101111") self.assertEqual(bdp.calculate_binary_info(), {'Zeroes': 0.475, 'Ones': 0.525, 'Bit length': 40}) def test_calculate_binary_info_2(self): bdp = BinaryDataProcessor("0110100001100101011010011111") self.assertEqual(bdp.calculate_binary_info(), {'Bit length': 28, 'Ones': 0.5357142857142857, 'Zeroes': 0.4642857142857143}) def test_calculate_binary_info_3(self): bdp = BinaryDataProcessor("01101001111100101011010011111") self.assertEqual(bdp.calculate_binary_info(), {'Bit length': 29, 'Ones': 0.6206896551724138, 'Zeroes': 0.3793103448275862}) def test_calculate_binary_info_4(self): bdp = BinaryDataProcessor("011010011111001") self.assertEqual(bdp.calculate_binary_info(), {'Bit length': 15, 'Ones': 0.6, 'Zeroes': 0.4}) def test_calculate_binary_info_5(self): bdp = BinaryDataProcessor("0110100111110010") self.assertEqual(bdp.calculate_binary_info(), {'Bit length': 16, 'Ones': 0.5625, 'Zeroes': 0.4375}) class BinaryDataProcessorTestConvertToAscii(unittest.TestCase): def test_convert_to_ascii(self): bdp = BinaryDataProcessor("0110100001100101011011000110110001101111") self.assertEqual(bdp.convert_to_ascii(), "hello") def test_convert_to_ascii_2(self): bdp = BinaryDataProcessor("0110100000100101011011000110110001101111") self.assertEqual(bdp.convert_to_ascii(), "h%llo") def test_convert_to_ascii_3(self): bdp = BinaryDataProcessor("01101000011011010110001001101111") self.assertEqual(bdp.convert_to_ascii(), "hmbo") def test_convert_to_ascii_4(self): bdp = BinaryDataProcessor("01101000011001010110001001101111") self.assertEqual(bdp.convert_to_ascii(), "hebo") def test_convert_to_ascii_5(self): bdp = BinaryDataProcessor("0110100001100101011011000110110001101111") self.assertEqual(bdp.convert_to_ascii(), "hello") class BinaryDataProcessorTestConvertToUtf8(unittest.TestCase): def test_convert_to_utf8(self): bdp = BinaryDataProcessor("0110100001100101011011000110110001101111") self.assertEqual(bdp.convert_to_utf8(), "hello") def test_convert_to_utf8_2(self): bdp = BinaryDataProcessor("0110100001100101011011000110110001101001") self.assertEqual(bdp.convert_to_utf8(), "helli") def test_convert_to_utf8_3(self): bdp = BinaryDataProcessor("0110000001100101011011000110110001101111") self.assertEqual(bdp.convert_to_utf8(), "`ello") def test_convert_to_utf8_4(self): bdp = BinaryDataProcessor("0110101101100101011011000110110001101111") self.assertEqual(bdp.convert_to_utf8(), "kello") def test_convert_to_utf8_5(self): bdp = BinaryDataProcessor("0110101101100100011011000110110001101111") self.assertEqual(bdp.convert_to_utf8(), "kdllo") class BinaryDataProcessorTestMain(unittest.TestCase): def test_main(self): bdp = BinaryDataProcessor("01101000daf3e4r01100101011011000110110001101111") self.assertEqual(bdp.binary_string, "0110100001100101011011000110110001101111") self.assertEqual(bdp.calculate_binary_info(), {'Zeroes': 0.475, 'Ones': 0.525, 'Bit length': 40}) self.assertEqual(bdp.convert_to_ascii(), "hello") self.assertEqual(bdp.convert_to_utf8(), "hello")
[ "bdp = BinaryDataProcessor(\"01101000daf3e4r01100101011011000110110001101111\")\nassertEqual(bdp.binary_string, \"0110100001100101011011000110110001101111\")\n", "bdp = BinaryDataProcessor(\"0110100001100101011011000110110001101111\")\nassertEqual(bdp.calculate_binary_info(), {'Zeroes': 0.475, 'Ones': 0.525, 'Bit...
[]
DREval/95
class BitStatusUtil: @staticmethod def add(states, stat): BitStatusUtil.check([states, stat]) return states | stat @staticmethod def has(states, stat): BitStatusUtil.check([states, stat]) return (states & stat) == stat @staticmethod def remove(states, stat): BitStatusUtil.check([states, stat]) if BitStatusUtil.has(states, stat): return states ^ stat return states @staticmethod def check(args): for arg in args: if arg < 0: raise ValueError(f"{arg} must be greater than or equal to 0") if arg % 2 != 0: raise ValueError(f"{arg} not even")
BitStatusUtil
import unittest class BitStatusUtilTestAdd(unittest.TestCase): def test_add(self): bit_status_util = BitStatusUtil() self.assertEqual(bit_status_util.add(2, 4), 6) def test_add_2(self): bit_status_util = BitStatusUtil() self.assertEqual(bit_status_util.add(2, 0), 2) def test_add_3(self): bit_status_util = BitStatusUtil() self.assertEqual(bit_status_util.add(0, 0), 0) def test_add_4(self): bit_status_util = BitStatusUtil() self.assertEqual(bit_status_util.add(0, 2), 2) def test_add_5(self): bit_status_util = BitStatusUtil() self.assertEqual(bit_status_util.add(2, 2), 2) class BitStatusUtilTestHas(unittest.TestCase): def test_has(self): bit_status_util = BitStatusUtil() self.assertTrue(bit_status_util.has(6, 2)) def test_has_2(self): bit_status_util = BitStatusUtil() self.assertFalse(bit_status_util.has(8, 2)) def test_has_3(self): bit_status_util = BitStatusUtil() self.assertTrue(bit_status_util.has(6, 4)) def test_has_4(self): bit_status_util = BitStatusUtil() self.assertFalse(bit_status_util.has(8, 6)) def test_has_5(self): bit_status_util = BitStatusUtil() self.assertTrue(bit_status_util.has(6, 6)) class BitStatusUtilTestRemove(unittest.TestCase): def test_remove(self): bit_status_util = BitStatusUtil() self.assertEqual(bit_status_util.remove(6, 2), 4) def test_remove_2(self): bit_status_util = BitStatusUtil() self.assertEqual(bit_status_util.remove(8, 2), 8) def test_remove_3(self): bit_status_util = BitStatusUtil() self.assertEqual(bit_status_util.remove(6, 4), 2) def test_remove_4(self): bit_status_util = BitStatusUtil() self.assertEqual(bit_status_util.remove(8, 6), 8) def test_remove_5(self): bit_status_util = BitStatusUtil() self.assertEqual(bit_status_util.remove(6, 6), 0) class BitStatusUtilTestCheck(unittest.TestCase): def test_check(self): bit_status_util = BitStatusUtil() bit_status_util.check([2]) def test_check_2(self): bit_status_util = BitStatusUtil() with self.assertRaises(ValueError): bit_status_util.check([3]) def test_check_3(self): bit_status_util = BitStatusUtil() with self.assertRaises(ValueError): bit_status_util.check([-1]) def test_check_4(self): bit_status_util = BitStatusUtil() with self.assertRaises(ValueError): bit_status_util.check([2, 3, 4]) def test_check_5(self): bit_status_util = BitStatusUtil() with self.assertRaises(ValueError): bit_status_util.check([2, 3, 4, 5]) class BitStatusUtilTestMain(unittest.TestCase): def test_main(self): bit_status_util = BitStatusUtil() self.assertEqual(bit_status_util.add(2, 4), 6) self.assertTrue(bit_status_util.has(6, 2)) self.assertEqual(bit_status_util.remove(6, 2), 4) with self.assertRaises(ValueError): bit_status_util.check([2, 3, 4])
[ "bit_status_util = BitStatusUtil()\nassertEqual(bit_status_util.add(2, 4), 6)\n", "bit_status_util = BitStatusUtil()\nassertTrue(bit_status_util.has(6, 2))\n", "bit_status_util = BitStatusUtil()\nassertEqual(bit_status_util.remove(6, 2), 4)\n", "bit_status_util = BitStatusUtil()\nbit_status_util.check([2])\n"...
[]
DREval/96
class BookManagement: def __init__(self): self.inventory = {} def add_book(self, title, quantity=1): if title in self.inventory: self.inventory[title] += quantity else: self.inventory[title] = quantity def remove_book(self, title, quantity): if title not in self.inventory or self.inventory[title] < quantity: raise False self.inventory[title] -= quantity if self.inventory[title] == 0: del (self.inventory[title]) def view_inventory(self): return self.inventory def view_book_quantity(self, title): if title not in self.inventory: return 0 return self.inventory[title]
BookManagement
import unittest class BookManagementTestAddBook(unittest.TestCase): def test_add_book_1(self): bookManagement = BookManagement() bookManagement.add_book("book1") self.assertEqual({"book1": 1}, bookManagement.inventory) def test_add_book_2(self): bookManagement = BookManagement() self.assertEqual({}, bookManagement.inventory) def test_add_book_3(self): bookManagement = BookManagement() bookManagement.add_book("book1") bookManagement.add_book("book1", 2) self.assertEqual({"book1": 3}, bookManagement.inventory) def test_add_book_4(self): bookManagement = BookManagement() bookManagement.add_book("book1", 2) self.assertEqual({"book1": 2}, bookManagement.inventory) def test_add_book_5(self): bookManagement = BookManagement() bookManagement.add_book("book1", 2) bookManagement.add_book("book1") self.assertEqual({"book1": 3}, bookManagement.inventory) class BookManagementTestRemoveBook(unittest.TestCase): def setUp(self) -> None: self.bookManagement = BookManagement() self.bookManagement.add_book("book1", 2) self.bookManagement.add_book("book2") # remove all this title books def test_remove_book_1(self): self.bookManagement.remove_book("book1", 2) self.assertEqual(self.bookManagement.inventory, {"book2": 1}) # remove part def test_remove_book_2(self): self.bookManagement.remove_book("book1", 1) self.assertEqual(self.bookManagement.inventory, {"book1": 1, "book2": 1}) # remove the title that doesn't exist def test_remove_book_3(self): with self.assertRaises(Exception): self.bookManagement.remove_book("book3", 1) # invalid quantity def test_remove_book_4(self): with self.assertRaises(Exception): self.bookManagement.remove_book("book2", 2) def test_remove_book_5(self): with self.assertRaises(Exception): self.bookManagement.remove_book("book2", 5) class BookManagementTestViewInventory(unittest.TestCase): def test_view_inventory_1(self): bookManagement = BookManagement() bookManagement.add_book("book1", 2) bookManagement.add_book("book2") expected = {"book1": 2, "book2": 1} self.assertEqual(expected, bookManagement.inventory) def test_view_inventory_2(self): bookManagement = BookManagement() expected = {} self.assertEqual(expected, bookManagement.inventory) def test_view_inventory_3(self): bookManagement = BookManagement() bookManagement.add_book("book1", 2) bookManagement.add_book("book2") expected = {"book1": 2, "book2": 1} self.assertEqual(expected, bookManagement.inventory) def test_view_inventory_4(self): bookManagement = BookManagement() bookManagement.add_book("book1", 2) bookManagement.add_book("book2") bookManagement.remove_book("book1", 2) expected = {"book2": 1} self.assertEqual(expected, bookManagement.inventory) def test_view_inventory_5(self): bookManagement = BookManagement() bookManagement.add_book("book1", 2) bookManagement.add_book("book2", 1) bookManagement.remove_book("book1", 2) bookManagement.remove_book("book2",1) expected = {} self.assertEqual(expected, bookManagement.inventory) class BookManagementTestViewBookQuantity(unittest.TestCase): def test_view_book_quantity_1(self): bookManagement = BookManagement() bookManagement.add_book("book1", 2) self.assertEqual(2, bookManagement.view_book_quantity("book1")) def test_view_book_quantity_2(self): bookManagement = BookManagement() self.assertEqual(0, bookManagement.view_book_quantity("book1")) def test_view_book_quantity_3(self): bookManagement = BookManagement() bookManagement.add_book("book1", 2) self.assertEqual(2, bookManagement.view_book_quantity("book1")) def test_view_book_quantity_4(self): bookManagement = BookManagement() bookManagement.add_book("book1", 2) bookManagement.remove_book("book1", 2) self.assertEqual(0, bookManagement.view_book_quantity("book1")) def test_view_book_quantity_5(self): bookManagement = BookManagement() bookManagement.add_book("book1", 3) bookManagement.remove_book("book1", 2) self.assertEqual(1, bookManagement.view_book_quantity("book1")) class BookManagementTestMain(unittest.TestCase): def test_main(self): bookManagement = BookManagement() bookManagement.add_book("book1", 2) bookManagement.add_book("book2") self.assertEqual(bookManagement.view_inventory(), {"book1": 2, "book2": 1}) bookManagement.remove_book("book2", 1) self.assertEqual(bookManagement.view_inventory(), {"book1": 2}) self.assertEqual(0, bookManagement.view_book_quantity("book2"))
[ "bookManagement = BookManagement()\nbookManagement.add_book(\"book1\")\nassertEqual({\"book1\": 1}, bookManagement.inventory)\n", "self.bookManagement.remove_book(\"book1\", 2)\nassertEqual(self.bookManagement.inventory, {\"book2\": 1})\n", "bookManagement = BookManagement()\nbookManagement.add_book(\"book1\", ...
[]
DREval/97
class BoyerMooreSearch: def __init__(self, text, pattern): self.text, self.pattern = text, pattern self.textLen, self.patLen = len(text), len(pattern) def match_in_pattern(self, char): for i in range(self.patLen - 1, -1, -1): if char == self.pattern[i]: return i return -1 def mismatch_in_text(self, currentPos): for i in range(self.patLen - 1, -1, -1): if self.pattern[i] != self.text[currentPos + i]: return currentPos + i return -1 def bad_character_heuristic(self): positions = [] for i in range(self.textLen - self.patLen + 1): mismatch_index = self.mismatch_in_text(i) if mismatch_index == -1: positions.append(i) else: match_index = self.match_in_pattern(self.text[mismatch_index]) i = (mismatch_index - match_index) return positions
BoyerMooreSearch
import unittest class BoyerMooreSearchTestMatchInPattern(unittest.TestCase): def test_match_in_pattern(self): boyerMooreSearch = BoyerMooreSearch("ABAABA", "AB") self.assertEqual(boyerMooreSearch.match_in_pattern("A"), 0) def test_match_in_pattern_2(self): boyerMooreSearch = BoyerMooreSearch("ABAABA", "ABAB") self.assertEqual(boyerMooreSearch.match_in_pattern("B"), 3) def test_match_in_pattern_3(self): boyerMooreSearch = BoyerMooreSearch("ABAABA", "ABCABC") self.assertEqual(boyerMooreSearch.match_in_pattern("C"), 5) def test_match_in_pattern_4(self): boyerMooreSearch = BoyerMooreSearch("ABAABA", "ABCABC") self.assertEqual(boyerMooreSearch.match_in_pattern("D"), -1) def test_match_in_pattern_5(self): boyerMooreSearch = BoyerMooreSearch("ABAABA", "ABCABC") self.assertEqual(boyerMooreSearch.match_in_pattern("E"), -1) class BoyerMooreSearchTestMismatchInText(unittest.TestCase): def test_mismatch_in_text(self): boyerMooreSearch = BoyerMooreSearch("ABAABA", "AB") self.assertEqual(boyerMooreSearch.mismatch_in_text(0), -1) def test_mismatch_in_text_2(self): boyerMooreSearch = BoyerMooreSearch("ABAABA", "ABC") self.assertEqual(boyerMooreSearch.mismatch_in_text(0), 2) def test_mismatch_in_text_3(self): boyerMooreSearch = BoyerMooreSearch("AAAA", "ABC") self.assertEqual(boyerMooreSearch.mismatch_in_text(0), 2) def test_mismatch_in_text_4(self): boyerMooreSearch = BoyerMooreSearch("ABAABA", "") self.assertEqual(boyerMooreSearch.mismatch_in_text(0), -1) def test_mismatch_in_text_5(self): boyerMooreSearch = BoyerMooreSearch("ABAABA", "ABC") self.assertEqual(boyerMooreSearch.mismatch_in_text(3), 5) class BoyerMooreSearchTestBadCharacterHeuristic(unittest.TestCase): def test_bad_character_heuristic(self): boyerMooreSearch = BoyerMooreSearch("ABAABA", "AB") self.assertEqual(boyerMooreSearch.bad_character_heuristic(), [0, 3]) def test_bad_character_heuristic_2(self): boyerMooreSearch = BoyerMooreSearch("ABAABA", "ABC") self.assertEqual(boyerMooreSearch.bad_character_heuristic(), []) def test_bad_character_heuristic_3(self): boyerMooreSearch = BoyerMooreSearch("ABAABA", "") self.assertEqual(boyerMooreSearch.bad_character_heuristic(), [0, 1, 2, 3, 4, 5, 6]) def test_bad_character_heuristic_4(self): boyerMooreSearch = BoyerMooreSearch("ABACABA", "ABA") self.assertEqual(boyerMooreSearch.bad_character_heuristic(), [0, 4]) def test_bad_character_heuristic_5(self): boyerMooreSearch = BoyerMooreSearch("ABACABA", "ABAC") self.assertEqual(boyerMooreSearch.bad_character_heuristic(), [0]) class BoyerMooreSearchTestMain(unittest.TestCase): def test_main(self): boyerMooreSearch = BoyerMooreSearch("ABAABA", "AB") self.assertEqual(boyerMooreSearch.match_in_pattern("A"), 0) self.assertEqual(boyerMooreSearch.mismatch_in_text(0), -1) self.assertEqual(boyerMooreSearch.bad_character_heuristic(), [0, 3])
[ "boyerMooreSearch = BoyerMooreSearch(\"ABAABA\", \"AB\")\nassertEqual(boyerMooreSearch.match_in_pattern(\"A\"), 0)\n", "boyerMooreSearch = BoyerMooreSearch(\"ABAABA\", \"AB\")\nassertEqual(boyerMooreSearch.mismatch_in_text(0), -1)\n", "boyerMooreSearch = BoyerMooreSearch(\"ABAABA\", \"AB\")\nassertEqual(boyerMo...
[]
DREval/98
class CamelCaseMap: def __init__(self): self._data = {} def __getitem__(self, key): return self._data[self._convert_key(key)] def __setitem__(self, key, value): self._data[self._convert_key(key)] = value def __delitem__(self, key): del self._data[self._convert_key(key)] def __iter__(self): return iter(self._data) def __len__(self): return len(self._data) def _convert_key(self, key): if isinstance(key, str): return self._to_camel_case(key) return key @staticmethod def _to_camel_case(key): parts = key.split('_') return parts[0] + ''.join(part.title() for part in parts[1:])
CamelCaseMap
import unittest class CamelCaseMapTestGetitem(unittest.TestCase): def test_getitem_1(self): camelize_map = CamelCaseMap() camelize_map['first_name'] = 'John' self.assertEqual(camelize_map.__getitem__('first_name'), 'John') def test_getitem_2(self): camelize_map = CamelCaseMap() camelize_map['last_name'] = 'Doe' self.assertEqual(camelize_map.__getitem__('last_name'), 'Doe') def test_getitem_3(self): camelize_map = CamelCaseMap() camelize_map['age'] = 30 self.assertEqual(camelize_map.__getitem__('age'), 30) def test_getitem_4(self): camelize_map = CamelCaseMap() camelize_map['first_name'] = 'John' self.assertEqual(camelize_map.__getitem__('first_Name'), 'John') def test_getitem_5(self): camelize_map = CamelCaseMap() camelize_map['first_name'] = 'John' self.assertEqual(camelize_map.__getitem__('firstName'), 'John') class CamelCaseMapTestSetitem(unittest.TestCase): def test_setitem_1(self): camelize_map = CamelCaseMap() camelize_map['first_name'] = 'John' camelize_map.__setitem__('first_name', 'newname') self.assertEqual(camelize_map['first_name'], 'newname') def test_setitem_2(self): camelize_map = CamelCaseMap() camelize_map['first_name'] = 'John' camelize_map.__setitem__('first_name', 'John') self.assertEqual(camelize_map['first_name'], 'John') def test_setitem_3(self): camelize_map = CamelCaseMap() camelize_map['first_name'] = 'John' camelize_map.__setitem__('first_Name', 'newname') self.assertEqual(camelize_map['first_name'], 'newname') def test_setitem_4(self): camelize_map = CamelCaseMap() camelize_map['first_name'] = 'John' camelize_map.__setitem__('firstName', 'newname') self.assertEqual(camelize_map['first_name'], 'newname') def test_setitem_5(self): camelize_map = CamelCaseMap() camelize_map['first_name'] = 'John' camelize_map.__setitem__('first_name', '') self.assertEqual(camelize_map['first_name'], '') class CamelCaseMapTestDelitem(unittest.TestCase): def test_delitem_1(self): camelize_map = CamelCaseMap() camelize_map['first_name'] = 'John' camelize_map['last_name'] = 'Doe' camelize_map.__delitem__('first_name') self.assertEqual(camelize_map['last_name'], 'Doe') def test_delitem_2(self): camelize_map = CamelCaseMap() camelize_map['first_name'] = 'John' camelize_map.__delitem__('first_name') self.assertEqual('first_name' in camelize_map, False) def test_delitem_3(self): camelize_map = CamelCaseMap() camelize_map['first_name'] = 'John' camelize_map.__delitem__('first_Name') self.assertEqual('first_name' in camelize_map, False) def test_delitem_4(self): camelize_map = CamelCaseMap() camelize_map['first_name'] = 'John' camelize_map.__delitem__('firstName') self.assertEqual('first_name' in camelize_map, False) def test_delitem_5(self): camelize_map = CamelCaseMap() camelize_map['first_name'] = '' camelize_map.__delitem__('first_name') self.assertEqual('first_name' in camelize_map, False) class CamelCaseMapTestIter(unittest.TestCase): def test_iter_1(self): camelize_map = CamelCaseMap() camelize_map['first_name'] = 'John' camelize_map['last_name'] = 'Doe' camelize_map['age'] = 30 lst = ['firstName', 'lastName', 'age'] iter = camelize_map.__iter__() i = 0 for key in iter: self.assertEqual(key, lst[i]) i += 1 def test_iter_2(self): camelize_map = CamelCaseMap() camelize_map['firstname'] = 'John' camelize_map['lastname'] = 'Doe' camelize_map['age'] = 30 lst = ['firstname', 'lastname', 'age'] iter = camelize_map.__iter__() i = 0 for key in iter: self.assertEqual(key, lst[i]) i += 1 def test_iter_3(self): camelize_map = CamelCaseMap() camelize_map['first_Name'] = 'John' camelize_map['last_Name'] = 'Doe' camelize_map['age'] = 30 lst = ['firstName', 'lastName', 'age'] iter = camelize_map.__iter__() i = 0 for key in iter: self.assertEqual(key, lst[i]) i += 1 def test_iter_4(self): camelize_map = CamelCaseMap() camelize_map['first_Name'] = 'John' camelize_map['last_Name'] = 'Doe' lst = ['firstName', 'lastName'] iter = camelize_map.__iter__() i = 0 for key in iter: self.assertEqual(key, lst[i]) i += 1 def test_iter_5(self): camelize_map = CamelCaseMap() camelize_map['first_Name'] = 'John' lst = ['firstName'] iter = camelize_map.__iter__() i = 0 for key in iter: self.assertEqual(key, lst[i]) i += 1 class CamelCaseMapTestLen(unittest.TestCase): def test_len_1(self): camelize_map = CamelCaseMap() camelize_map['first_name'] = 'John' self.assertEqual(camelize_map.__len__(), 1) def test_len_2(self): camelize_map = CamelCaseMap() camelize_map['last_name'] = 'Doe' self.assertEqual(camelize_map.__len__(), 1) def test_len_3(self): camelize_map = CamelCaseMap() camelize_map['age'] = 30 self.assertEqual(camelize_map.__len__(), 1) def test_len_4(self): camelize_map = CamelCaseMap() camelize_map['first_name'] = 'John' camelize_map['last_Name'] = 'Doe' camelize_map['age'] = 30 self.assertEqual(camelize_map.__len__(), 3) def test_len_5(self): camelize_map = CamelCaseMap() self.assertEqual(camelize_map.__len__(), 0) class CamelCaseMapTestConvertKey(unittest.TestCase): def test_convert_key_1(self): camelize_map = CamelCaseMap() self.assertEqual(camelize_map._convert_key('aaa_bbb'), 'aaaBbb') def test_convert_key_2(self): camelize_map = CamelCaseMap() self.assertEqual(camelize_map._convert_key('first_name'), 'firstName') def test_convert_key_3(self): camelize_map = CamelCaseMap() self.assertEqual(camelize_map._convert_key('last_name'), 'lastName') def test_convert_key_4(self): camelize_map = CamelCaseMap() self.assertEqual(camelize_map._convert_key('ccc_ddd'), 'cccDdd') def test_convert_key_5(self): camelize_map = CamelCaseMap() self.assertEqual(camelize_map._convert_key('eee_fff'), 'eeeFff') def test_convert_key_6(self): camelize_map = CamelCaseMap() self.assertEqual(camelize_map._convert_key(1234), 1234) class CamelCaseMapTestToCamelCase(unittest.TestCase): def test_to_camel_case_1(self): self.assertEqual(CamelCaseMap._to_camel_case('aaa_bbb'), 'aaaBbb') def test_to_camel_case_2(self): self.assertEqual(CamelCaseMap._to_camel_case('first_name'), 'firstName') def test_to_camel_case_3(self): self.assertEqual(CamelCaseMap._to_camel_case('last_name'), 'lastName') def test_to_camel_case_4(self): self.assertEqual(CamelCaseMap._to_camel_case('ccc_ddd'), 'cccDdd') def test_to_camel_case_5(self): self.assertEqual(CamelCaseMap._to_camel_case('eee_fff'), 'eeeFff') class CamelCaseMapTest(unittest.TestCase): def test_CamelCaseMap(self): camelize_map = CamelCaseMap() camelize_map['first_name'] = 'John' self.assertEqual(camelize_map.__getitem__('first_name'), 'John') camelize_map = CamelCaseMap() camelize_map['first_name'] = 'John' camelize_map.__setitem__('first_name', 'newname') self.assertEqual(camelize_map['first_name'], 'newname')
[ "camelize_map = CamelCaseMap()\ncamelize_map['first_name'] = 'John'\nassertEqual(camelize_map.__getitem__('first_name'), 'John')\n", "camelize_map = CamelCaseMap()\ncamelize_map['first_name'] = 'John'\ncamelize_map.__setitem__('first_name', 'newname')\nassertEqual(camelize_map['first_name'], 'newname')\n", "cam...
[]
DREval/99
class ChandrasekharSieve: def __init__(self, n): self.n = n self.primes = self.generate_primes() def generate_primes(self): if self.n < 2: return [] sieve = [True] * (self.n + 1) sieve[0] = sieve[1] = False p = 2 while p * p <= self.n: if sieve[p]: for i in range(p * p, self.n + 1, p): sieve[i] = False p += 1 primes = [] for i in range(2, self.n + 1): if sieve[i]: primes.append(i) return primes def get_primes(self): return self.primes
ChandrasekharSieve
import unittest class ChandrasekharSieveTestGeneratePrimes(unittest.TestCase): def test_generate_primes_1(self): cs = ChandrasekharSieve(20) res = cs.generate_primes() self.assertEqual(res, [2, 3, 5, 7, 11, 13, 17, 19]) def test_generate_primes_2(self): cs = ChandrasekharSieve(18) res = cs.generate_primes() self.assertEqual(res, [2, 3, 5, 7, 11, 13, 17]) def test_generate_primes_3(self): cs = ChandrasekharSieve(15) res = cs.generate_primes() self.assertEqual(res, [2, 3, 5, 7, 11, 13]) def test_generate_primes_4(self): cs = ChandrasekharSieve(10) res = cs.generate_primes() self.assertEqual(res, [2, 3, 5, 7]) def test_generate_primes_5(self): cs = ChandrasekharSieve(1) res = cs.generate_primes() self.assertEqual(res, []) class ChandrasekharSieveTestGetPrimes(unittest.TestCase): def test_get_primes_1(self): cs = ChandrasekharSieve(20) cs.generate_primes() res = cs.get_primes() self.assertEqual(res, [2, 3, 5, 7, 11, 13, 17, 19]) def test_get_primes_2(self): cs = ChandrasekharSieve(18) cs.generate_primes() res = cs.get_primes() self.assertEqual(res, [2, 3, 5, 7, 11, 13, 17]) def test_get_primes_3(self): cs = ChandrasekharSieve(15) cs.generate_primes() res = cs.get_primes() self.assertEqual(res, [2, 3, 5, 7, 11, 13]) def test_get_primes_4(self): cs = ChandrasekharSieve(10) cs.generate_primes() res = cs.get_primes() self.assertEqual(res, [2, 3, 5, 7]) def test_get_primes_5(self): cs = ChandrasekharSieve(1) res = cs.get_primes() self.assertEqual(res, []) class ChandrasekharSieveTest(unittest.TestCase): def test_chandrasekharsieve(self): cs = ChandrasekharSieve(20) res = cs.generate_primes() self.assertEqual(res, [2, 3, 5, 7, 11, 13, 17, 19]) res = cs.get_primes() self.assertEqual(res, [2, 3, 5, 7, 11, 13, 17, 19])
[ "cs = ChandrasekharSieve(20)\nres = cs.generate_primes()\nassertEqual(res, [2, 3, 5, 7, 11, 13, 17, 19])\n", "cs = ChandrasekharSieve(20)\ncs.generate_primes()\nres = cs.get_primes()\nassertEqual(res, [2, 3, 5, 7, 11, 13, 17, 19])\n", "cs = ChandrasekharSieve(20)\nres = cs.generate_primes()\nassertEqual(res, [2...
[]