name
stringlengths
34
63
language
stringclasses
3 values
prompt
stringlengths
91
2.81k
suffix
stringlengths
0
1.57k
canonical_solution
stringlengths
1
219
tests
stringlengths
149
4.98k
humaneval-HumanEval_6_parse_nested_parens.json-L7
js
//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] function parse_nested_parens(paren_string){
var maxlevel = 0; var result = []; for (var i = 0; i < paren_string.length; i++){ if (paren_string[i] == "("){ level += 1; if (level > maxlevel){ maxlevel = level; } } else if (paren_string[i] == ")"){ level -= 1; } else if (paren_string[i] == " "){ result.push(maxlevel); maxlevel = 0; level = 0; } } result.push(maxlevel); return result; }
var level = 0;
const assert = require('node:assert'); function test() { let candidate = parse_nested_parens; assert.deepEqual(candidate("(()()) ((())) () ((())()())"),[2, 3, 1, 3]); assert.deepEqual(candidate("() (()) ((())) (((())))"),[1, 2, 3, 4]); assert.deepEqual(candidate("(()(())((())))"),[4]); } test();
humaneval-HumanEval_70_strange_sort_list.json-L27
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Given array list of integers, return array 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: // >>> strangeSortList((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l)))) // (new ArrayList<Long>(Arrays.asList((long)1l, (long)4l, (long)2l, (long)3l))) // >>> strangeSortList((new ArrayList<Long>(Arrays.asList((long)5l, (long)5l, (long)5l, (long)5l)))) // (new ArrayList<Long>(Arrays.asList((long)5l, (long)5l, (long)5l, (long)5l))) // >>> strangeSortList((new ArrayList<Long>(Arrays.asList()))) // (new ArrayList<Long>(Arrays.asList())) public static ArrayList<Long> strangeSortList(ArrayList<Long> lst) { if (lst.size() <= 1) { return lst; } ArrayList<Long> result = new ArrayList<Long>(); ArrayList<Long> sorted = new ArrayList<Long>(lst); Collections.sort(sorted); int min = 0;
while (min <= max) { result.add(sorted.get(min)); min++; if (min <= max) { result.add(sorted.get(max)); max--; } } return result; } }
int max = sorted.size() - 1;
} public static void main(String[] args) { assert(strangeSortList((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l)))).equals((new ArrayList<Long>(Arrays.asList((long)1l, (long)4l, (long)2l, (long)3l))))); assert(strangeSortList((new ArrayList<Long>(Arrays.asList((long)5l, (long)6l, (long)7l, (long)8l, (long)9l)))).equals((new ArrayList<Long>(Arrays.asList((long)5l, (long)9l, (long)6l, (long)8l, (long)7l))))); assert(strangeSortList((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l, (long)5l)))).equals((new ArrayList<Long>(Arrays.asList((long)1l, (long)5l, (long)2l, (long)4l, (long)3l))))); assert(strangeSortList((new ArrayList<Long>(Arrays.asList((long)5l, (long)6l, (long)7l, (long)8l, (long)9l, (long)1l)))).equals((new ArrayList<Long>(Arrays.asList((long)1l, (long)9l, (long)5l, (long)8l, (long)6l, (long)7l))))); assert(strangeSortList((new ArrayList<Long>(Arrays.asList((long)5l, (long)5l, (long)5l, (long)5l)))).equals((new ArrayList<Long>(Arrays.asList((long)5l, (long)5l, (long)5l, (long)5l))))); assert(strangeSortList((new ArrayList<Long>(Arrays.asList()))).equals((new ArrayList<Long>(Arrays.asList())))); assert(strangeSortList((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l, (long)5l, (long)6l, (long)7l, (long)8l)))).equals((new ArrayList<Long>(Arrays.asList((long)1l, (long)8l, (long)2l, (long)7l, (long)3l, (long)6l, (long)4l, (long)5l))))); assert(strangeSortList((new ArrayList<Long>(Arrays.asList((long)0l, (long)2l, (long)2l, (long)2l, (long)5l, (long)5l, (long)-5l, (long)-5l)))).equals((new ArrayList<Long>(Arrays.asList((long)-5l, (long)5l, (long)-5l, (long)5l, (long)0l, (long)2l, (long)2l, (long)2l))))); assert(strangeSortList((new ArrayList<Long>(Arrays.asList((long)111111l)))).equals((new ArrayList<Long>(Arrays.asList((long)111111l))))); } }
humaneval-HumanEval_28_concatenate.json-L8
js
//Concatenate array of strings into a single string // >>> concatenate([]) // "" // >>> concatenate(["a", "b", "c"]) // "abc" function concatenate(strings){ if(strings.length === 0){
} var string = strings.join(""); return string; }
return "";
const assert = require('node:assert'); function test() { let candidate = concatenate; assert.deepEqual(candidate([]),""); assert.deepEqual(candidate(["x", "y", "z"]),"xyz"); assert.deepEqual(candidate(["x", "y", "z", "w", "k"]),"xyzwk"); } test();
humaneval-HumanEval_160_do_algebra.json-L30
py
from typing import List def do_algebra(operator: List[str], operand: List[int]) -> int: """ Given two lists operator, and operand. The first list has basic algebra operations, and the second list is a list of integers. Use the two given lists to build the algebric expression and return the evaluation of this expression. The basic algebra operations: Addition ( + ) Subtraction ( - ) Multiplication ( * ) Floor division ( // ) Exponentiation ( ** ) Example: operator['+', '*', '-'] array = [2, 3, 4, 5] result = 2 + 3 * 4 - 5 => result = 9 Note: The length of operator list is equal to the length of operand list minus one. Operand is a list of of non-negative integers. Operator list has at least one operator, and operand list has at least two operands. """ if len(operator) != len(operand) - 1: raise ValueError("Invalid number of operators")
for idx, op in enumerate(operator): expr.append(op) expr.append(str(operand[idx + 1])) return eval("".join(expr))
expr = [str(operand[0])]
def check(candidate): assert candidate(['**', '*', '+'], [2, 3, 4, 5]) == 37 assert candidate(['+', '*', '-'], [2, 3, 4, 5]) == 9 assert candidate(['//', '*'], [7, 3, 4]) == 8 def test_check(): check(do_algebra) test_check()
humaneval-HumanEval_105_by_length.json-L31
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Given an array array list of integers, sort the integers that are between 1 and 9 inclusive, // reverse the resulting array array list, and then replace each digit by its corresponding name from // "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine". // For example: // >>> byLength((new ArrayList<Long>(Arrays.asList((long)2l, (long)1l, (long)1l, (long)4l, (long)5l, (long)8l, (long)2l, (long)3l)))) // (new ArrayList<String>(Arrays.asList((String)"Eight", (String)"Five", (String)"Four", (String)"Three", (String)"Two", (String)"Two", (String)"One", (String)"One"))) // If the array array list is empty, return an empty array array list: // >>> byLength((new ArrayList<Long>(Arrays.asList()))) // (new ArrayList<String>(Arrays.asList())) // If the array array list has any strange number ignore it: // >>> byLength((new ArrayList<Long>(Arrays.asList((long)1l, (long)-1l, (long)55l)))) // (new ArrayList<String>(Arrays.asList((String)"One"))) public static ArrayList<String> byLength(ArrayList<Long> arr) { String[] a = new String[] {"One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"}; ArrayList<String> res = new ArrayList<String>(); ArrayList<Long> good = new ArrayList<Long>(); for (Long i : arr) { if (i >= 1 && i <= 9) { good.add(i); } } good.sort(new Comparator<Long>() {
return i1.compareTo(i2); } }); Collections.reverse(good); for (Long i : good) { res.add(a[i.intValue() - 1]); } return res; } }
public int compare(Long i1, Long i2) {
} public static void main(String[] args) { assert(byLength((new ArrayList<Long>(Arrays.asList((long)2l, (long)1l, (long)1l, (long)4l, (long)5l, (long)8l, (long)2l, (long)3l)))).equals((new ArrayList<String>(Arrays.asList((String)"Eight", (String)"Five", (String)"Four", (String)"Three", (String)"Two", (String)"Two", (String)"One", (String)"One"))))); assert(byLength((new ArrayList<Long>(Arrays.asList()))).equals((new ArrayList<String>(Arrays.asList())))); assert(byLength((new ArrayList<Long>(Arrays.asList((long)1l, (long)-1l, (long)55l)))).equals((new ArrayList<String>(Arrays.asList((String)"One"))))); assert(byLength((new ArrayList<Long>(Arrays.asList((long)1l, (long)-1l, (long)3l, (long)2l)))).equals((new ArrayList<String>(Arrays.asList((String)"Three", (String)"Two", (String)"One"))))); assert(byLength((new ArrayList<Long>(Arrays.asList((long)9l, (long)4l, (long)8l)))).equals((new ArrayList<String>(Arrays.asList((String)"Nine", (String)"Eight", (String)"Four"))))); } }
humaneval-HumanEval_105_by_length.json-L16
js
//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: // >>> by_length([2, 1, 1, 4, 5, 8, 2, 3]) // ["Eight", "Five", "Four", "Three", "Two", "Two", "One", "One"] // If the array is empty, return an empty array: // >>> by_length([]) // [] // If the array has any strange number ignore it: // >>> by_length([1, -1, 55]) // ["One"] function by_length(arr){ var arr2 = []; for(var i = 0; i < arr.length; i++){
if(num > 0 && num < 10){ arr2.push(num); } } arr2.sort(); arr2.reverse(); var arr3 = []; for(var i = 0; i < arr2.length; i++){ var num = arr2[i]; if(num == 1){ arr3.push("One"); } else if(num == 2){ arr3.push("Two"); } else if(num == 3){ arr3.push("Three"); } else if(num == 4){ arr3.push("Four"); } else if(num == 5){ arr3.push("Five"); } else if(num == 6){ arr3.push("Six"); } else if(num == 7){ arr3.push("Seven"); } else if(num == 8){ arr3.push("Eight"); } else if(num == 9){ arr3.push("Nine"); } } return arr3; }
var num = arr[i];
const assert = require('node:assert'); function test() { let candidate = by_length; assert.deepEqual(candidate([2, 1, 1, 4, 5, 8, 2, 3]),["Eight", "Five", "Four", "Three", "Two", "Two", "One", "One"]); assert.deepEqual(candidate([]),[]); assert.deepEqual(candidate([1, -1, 55]),["One"]); assert.deepEqual(candidate([1, -1, 3, 2]),["Three", "Two", "One"]); assert.deepEqual(candidate([9, 4, 8]),["Nine", "Eight", "Four"]); } test();
humaneval-HumanEval_34_unique.json-L16
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Return sorted unique elements in an array array list // >>> unique((new ArrayList<Long>(Arrays.asList((long)5l, (long)3l, (long)5l, (long)2l, (long)3l, (long)3l, (long)9l, (long)0l, (long)123l)))) // (new ArrayList<Long>(Arrays.asList((long)0l, (long)2l, (long)3l, (long)5l, (long)9l, (long)123l))) public static ArrayList<Long> unique(ArrayList<Long> l) { TreeSet<Long> tree = new TreeSet<Long>(l); return new ArrayList<Long>(tree); }
}
} public static void main(String[] args) { assert(unique((new ArrayList<Long>(Arrays.asList((long)5l, (long)3l, (long)5l, (long)2l, (long)3l, (long)3l, (long)9l, (long)0l, (long)123l)))).equals((new ArrayList<Long>(Arrays.asList((long)0l, (long)2l, (long)3l, (long)5l, (long)9l, (long)123l))))); } }
humaneval-HumanEval_99_closest_integer.json-L24
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // 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 // >>> closestInteger(("10")) // (10l) // >>> closestInteger(("15.3")) // (15l) // 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. public static long closestInteger(String value) { BigDecimal bd = new BigDecimal(value);
return bd.longValue(); } }
bd = bd.setScale(0, BigDecimal.ROUND_HALF_UP);
} public static void main(String[] args) { assert(closestInteger(("10")) == (10l)); assert(closestInteger(("14.5")) == (15l)); assert(closestInteger(("-15.5")) == (-16l)); assert(closestInteger(("15.3")) == (15l)); assert(closestInteger(("0")) == (0l)); } }
humaneval-HumanEval_75_is_multiply_prime.json-L35
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Write a function that returns true if the given number is the multiplication of 3 prime numbers // and false otherwise. // Knowing that (a) is less then 100. // Example: // >>> isMultiplyPrime((30l)) // (true) // 30 = 2 * 3 * 5 public static boolean isMultiplyPrime(long a) { if (a == 1) { return false; } if (a == 2) { return true; } long copyOfInput = a; ArrayList<Long> arr = new ArrayList<Long>(); while (a % 2 == 0) { arr.add(2l); a /= 2; } for (long i = 3; i <= Math.sqrt(a); i += 2) { while (a % i == 0) { arr.add(i); a /= i; } }
arr.add(a); } return arr.size() == 3; } }
if (a > 2) {
} public static void main(String[] args) { assert(isMultiplyPrime((5l)) == (false)); assert(isMultiplyPrime((30l)) == (true)); assert(isMultiplyPrime((8l)) == (true)); assert(isMultiplyPrime((10l)) == (false)); assert(isMultiplyPrime((125l)) == (true)); assert(isMultiplyPrime((105l)) == (true)); assert(isMultiplyPrime((126l)) == (false)); assert(isMultiplyPrime((729l)) == (false)); assert(isMultiplyPrime((891l)) == (false)); assert(isMultiplyPrime((1001l)) == (true)); } }
humaneval-HumanEval_136_largest_smallest_integers.json-L23
py
from typing import List, Tuple, Optional def largest_smallest_integers(lst: List[int]) -> Tuple[Optional[int], Optional[int]]: """ Create a function that returns a tuple (a, b), where 'a' is the largest of negative integers, and 'b' is the smallest of positive integers in a list. If there is no negative or positive integers, return them as None. Examples: >>> largest_smallest_integers([2, 4, 1, 3, 5, 7]) (None, 1) >>> largest_smallest_integers([]) (None, None) >>> largest_smallest_integers([0]) (None, None) """ smallest_positive = None largest_negative = None for num in lst: if num > 0: if smallest_positive is None or num < smallest_positive:
elif num < 0: if largest_negative is None or num > largest_negative: largest_negative = num return (largest_negative, smallest_positive)
smallest_positive = num
def check(candidate): assert candidate([2, 4, 1, 3, 5, 7]) == (None, 1) assert candidate([2, 4, 1, 3, 5, 7, 0]) == (None, 1) assert candidate([1, 3, 2, 4, 5, 6, -2]) == (-2, 1) assert candidate([4, 5, 3, 6, 2, 7, -7]) == (-7, 2) assert candidate([7, 3, 8, 4, 9, 2, 5, -9]) == (-9, 2) assert candidate([]) == (None, None) assert candidate([0]) == (None, None) assert candidate([-1, -3, -5, -6]) == (-1, None) assert candidate([-1, -3, -5, -6, 0]) == (-1, None) assert candidate([-6, -4, -4, -3, 1]) == (-3, 1) assert candidate([-6, -4, -4, -3, -100, 1]) == (-3, 1) def test_check(): check(largest_smallest_integers) test_check()
humaneval-HumanEval_148_bf.json-L25
py
from typing import Tuple def bf(planet1: str, planet2: str) -> Tuple[str, ...]: """ There are eight planets in our solar system: the closerst to the Sun is Mercury, the next one is Venus, then Earth, Mars, Jupiter, Saturn, Uranus, Neptune. Write a function that takes two planet names as strings planet1 and planet2. The function should return a tuple containing all planets whose orbits are located between the orbit of planet1 and the orbit of planet2, sorted by the proximity to the sun. The function should return an empty tuple if planet1 or planet2 are not correct planet names. Examples >>> bf('Jupiter', 'Neptune') ('Saturn', 'Uranus') >>> bf('Earth', 'Mercury') 'Venus' >>> bf('Mercury', 'Uranus') ('Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn') """ planets = ('Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune') if planet1 not in planets or planet2 not in planets: return ()
end = planets.index(planet2) if start < end: planets = planets[start+1:end] else: planets = planets[end+1:start] return tuple(planets)
start = planets.index(planet1)
def check(candidate): assert candidate('Jupiter', 'Neptune') == ('Saturn', 'Uranus') assert candidate('Earth', 'Mercury') == ('Venus',) assert candidate('Mercury', 'Uranus') == ('Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn') assert candidate('Neptune', 'Venus') == ('Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus') assert candidate('Earth', 'Earth') == () assert candidate('Mars', 'Earth') == () assert candidate('Jupiter', 'Makemake') == () def test_check(): check(bf) test_check()
humaneval-HumanEval_47_median.json-L17
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Return median of elements in the array list l. // >>> median((new ArrayList<Long>(Arrays.asList((long)3l, (long)1l, (long)2l, (long)4l, (long)5l)))) // (float)3l // >>> median((new ArrayList<Long>(Arrays.asList((long)-10l, (long)4l, (long)6l, (long)1000l, (long)10l, (long)20l)))) // (15.0f) public static float median(ArrayList<Long> l) { float ret = 0; Collections.sort(l);
if (size % 2 == 0) { ret = (l.get(size / 2) + l.get(size / 2 - 1)) / 2f; } else { ret = l.get(size / 2); } return ret; } }
int size = l.size();
} public static void main(String[] args) { assert(median((new ArrayList<Long>(Arrays.asList((long)3l, (long)1l, (long)2l, (long)4l, (long)5l)))) == (float)3l); assert(median((new ArrayList<Long>(Arrays.asList((long)-10l, (long)4l, (long)6l, (long)1000l, (long)10l, (long)20l)))) == (8.0f)); assert(median((new ArrayList<Long>(Arrays.asList((long)5l)))) == (float)5l); assert(median((new ArrayList<Long>(Arrays.asList((long)6l, (long)5l)))) == (5.5f)); assert(median((new ArrayList<Long>(Arrays.asList((long)8l, (long)1l, (long)3l, (long)9l, (long)9l, (long)2l, (long)7l)))) == (float)7l); } }
humaneval-HumanEval_64_vowels_count.json-L20
js
//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 function vowels_count(s){ s=s.toLowerCase(); var vowels = ['a','e','i','o','u']; var count = 0; for(var i=0; i<s.length; i++){ if(vowels.indexOf(s[i])!=-1){ count++; } } if(s[s.length-1]=='y'){
} return count; }
count++;
const assert = require('node:assert'); function test() { let candidate = vowels_count; assert.deepEqual(candidate("abcde"),2); assert.deepEqual(candidate("Alone"),3); assert.deepEqual(candidate("key"),2); assert.deepEqual(candidate("bye"),1); assert.deepEqual(candidate("keY"),2); assert.deepEqual(candidate("bYe"),1); assert.deepEqual(candidate("ACEDY"),3); } test();
humaneval-HumanEval_158_find_max.json-L16
py
from typing import List def find_max(words: List[str]) -> str: """Write a function that accepts a list of strings. The list contains different words. Return the word with maximum number of unique characters. If multiple strings have maximum number of unique characters, return the one which comes first in lexicographical order. >>> find_max(['name', 'of', 'string']) 'string' >>> find_max(['name', 'enam', 'game']) 'enam' >>> find_max(['aaaaaaa', 'bb', 'cc']) 'aaaaaaa' """
max_word = "" for word in words: unique_num = len(set(word)) if unique_num > max_num: max_num = unique_num max_word = word elif unique_num == max_num: if word < max_word: max_word = word return max_word
max_num = 0
def check(candidate): assert candidate(['name', 'of', 'string']) == 'string' assert candidate(['name', 'enam', 'game']) == 'enam' assert candidate(['aaaaaaa', 'bb', 'cc']) == 'aaaaaaa' assert candidate(['abc', 'cba']) == 'abc' assert candidate(['play', 'this', 'game', 'of', 'footbott']) == 'footbott' assert candidate(['we', 'are', 'gonna', 'rock']) == 'gonna' assert candidate(['we', 'are', 'a', 'mad', 'nation']) == 'nation' assert candidate(['this', 'is', 'a', 'prrk']) == 'this' assert candidate(['b']) == 'b' assert candidate(['play', 'play', 'play']) == 'play' def test_check(): check(find_max) test_check()
humaneval-HumanEval_71_triangle_area.json-L19
py
def triangle_area(a: int, b: int, c: int) -> float: """ Given the lengths of the three sides of a triangle. Return the area of the triangle rounded to 2 decimal points if the three sides form a valid triangle. Otherwise return -1 Three sides make a valid triangle when the sum of any two sides is greater than the third side. Example: >>> triangle_area(3, 4, 5) 6.0 >>> triangle_area(1, 2, 10) -1 """ if a + b > c and a + c > b and b + c > a: perimeter = (a + b + c) / 2 area = (perimeter * (perimeter - a) * (perimeter - b) * (perimeter - c)) ** 0.5 return round(area, 2) else:
return -1
def check(candidate): assert candidate(3, 4, 5) == 6.0 assert candidate(1, 2, 10) == -1 assert candidate(4, 8, 5) == 8.18 assert candidate(2, 2, 2) == 1.73 assert candidate(1, 2, 3) == -1 assert candidate(10, 5, 7) == 16.25 assert candidate(2, 6, 3) == -1 assert candidate(1, 1, 1) == 0.43 assert candidate(2, 2, 10) == -1 def test_check(): check(triangle_area) test_check()
humaneval-HumanEval_137_compare_one.json-L28
py
from typing import Union def compare_one(a: Union[int, float, str], b: Union[int, float, str]) -> Union[int, float, str, None]: """ Create a function that takes integers, floats, or strings representing real numbers, and returns the larger variable in its given variable type. Return None if the values are equal. Note: If a real number is represented as a string, the floating point might be . or , >>> compare_one(1, 2.5) 2.5 >>> compare_one(1, '2,3') '2,3' >>> compare_one('5,1', '6') '6' >>> compare_one('1', 1) None """ if isinstance(a, int) and isinstance(b, int): if a > b: return a elif a < b: return b else: return None elif isinstance(a, float) and isinstance(b, float): if a > b:
elif a < b: return b else: return None elif isinstance(a, str) and isinstance(b, str): a_tmp = a.replace(',', '.') b_tmp = b.replace(',', '.') if float(a_tmp) > float(b_tmp): return a elif float(a_tmp) < float(b_tmp): return b else: return None elif isinstance(a, int) and isinstance(b, float): if a > b: return a elif a < b: return b else: return None elif isinstance(a, float) and isinstance(b, int): if a > b: return a elif a < b: return b else: return None elif isinstance(a, str) and isinstance(b, int): a_tmp = a.replace(',', '.') if float(a_tmp) > b: return a elif float(a_tmp) < b: return b else: return None elif isinstance(a, int) and isinstance(b, str): b_tmp = b.replace(',', '.') if a > float(b_tmp): return a elif a < float(b_tmp): return b else: return None elif isinstance(a, str) and isinstance(b, float): a_tmp = a.replace(',', '.') if float(a_tmp) > b: return a elif float(a_tmp) < b: return b
return a
def check(candidate): assert candidate(1, 2) == 2 assert candidate(1, 2.5) == 2.5 assert candidate(2, 3) == 3 assert candidate(5, 6) == 6 assert candidate(1, '2,3') == '2,3' assert candidate('5,1', '6') == '6' assert candidate('1', '2') == '2' assert candidate('1', 1) == None def test_check(): check(compare_one) test_check()
humaneval-HumanEval_52_below_threshold.json-L7
js
//Return true if all numbers in the array l are below threshold t. // >>> below_threshold([1, 2, 4, 10], 100) // true // >>> below_threshold([1, 20, 4, 10], 5) // false function below_threshold(l, t){
}
return l.every(x => x < t);
const assert = require('node:assert'); function test() { let candidate = below_threshold; assert.deepEqual(candidate([1, 2, 4, 10], 100),true); assert.deepEqual(candidate([1, 20, 4, 10], 5),false); assert.deepEqual(candidate([1, 20, 4, 10], 21),true); assert.deepEqual(candidate([1, 20, 4, 10], 22),true); assert.deepEqual(candidate([1, 8, 4, 10], 11),true); assert.deepEqual(candidate([1, 8, 4, 10], 10),false); } test();
humaneval-HumanEval_80_is_happy.json-L20
js
//You are given a string s. // Your task is to check if the string is hapjs or not. // A string is hapjs if its length is at least 3 and every 3 consecutive letters are distinct // For example: // >>> is_happy(a) // false // >>> is_happy(aa) // false // >>> is_happy(abcd) // true // >>> is_happy(aabb) // false // >>> is_happy(adb) // true // >>> is_happy(xyy) // false function is_happy(s){ let happy = true; if(s.length<3){
} for(let i=2; i<s.length; i++){ if(s[i]===s[i-1] || s[i]===s[i-2]){ happy = false; } } return happy; }
happy = false;
const assert = require('node:assert'); function test() { let candidate = is_happy; assert.deepEqual(candidate("a"),false); assert.deepEqual(candidate("aa"),false); assert.deepEqual(candidate("abcd"),true); assert.deepEqual(candidate("aabb"),false); assert.deepEqual(candidate("adb"),true); assert.deepEqual(candidate("xyy"),false); assert.deepEqual(candidate("iopaxpoi"),true); assert.deepEqual(candidate("iopaxioi"),false); } test();
humaneval-HumanEval_36_fizz_buzz.json-L10
py
def fizz_buzz(n: int) -> int: """Return the number of times the digit 7 appears in integers less than n which are divisible by 11 or 13. >>> fizz_buzz(50) 0 >>> fizz_buzz(78) 2 >>> fizz_buzz(79) 3 """
for i in range(n): if i % 11 == 0 or i % 13 == 0: x += str(i).count('7') return x
x = 0
def check(candidate): assert candidate(50) == 0 assert candidate(78) == 2 assert candidate(79) == 3 assert candidate(100) == 3 assert candidate(200) == 6 assert candidate(4000) == 192 assert candidate(10000) == 639 assert candidate(100000) == 8026 def test_check(): check(fizz_buzz) test_check()
humaneval-HumanEval_138_is_equal_to_sum_even.json-L14
js
//Evaluate whether the given number n can be written as the sum of exactly 4 positive even numbers // Example // >>> is_equal_to_sum_even(4) // false // >>> is_equal_to_sum_even(6) // false // >>> is_equal_to_sum_even(8) // true function is_equal_to_sum_even(n){ let m =0; for(let i=2;i<n;i+=2){ for(let j=2;j<n;j+=2){ for(let k=2;k<n;k+=2){
if((i+j+k+l)==n){ m=1; break; } } } } } if(m==1){ return true; } else{ return false; } }
for(let l=2;l<n;l+=2){
const assert = require('node:assert'); function test() { let candidate = is_equal_to_sum_even; assert.deepEqual(candidate(4),false); assert.deepEqual(candidate(6),false); assert.deepEqual(candidate(8),true); assert.deepEqual(candidate(10),true); assert.deepEqual(candidate(11),false); assert.deepEqual(candidate(12),true); assert.deepEqual(candidate(13),false); assert.deepEqual(candidate(16),true); } test();
humaneval-HumanEval_16_count_distinct_characters.json-L20
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Given a string, find out how many distinct characters (regardless of case) does it consist of // >>> countDistinctCharacters(("xyzXYZ")) // (3l) // >>> countDistinctCharacters(("Jerry")) // (4l) public static long countDistinctCharacters(String string) { long result = 0; string = string.toLowerCase(); Set<Character> set = new HashSet<Character>(); for (int i = 0; i < string.length(); i++) { char c = string.charAt(i);
} result = set.size(); return result; } }
set.add(c);
} public static void main(String[] args) { assert(countDistinctCharacters(("")) == (0l)); assert(countDistinctCharacters(("abcde")) == (5l)); assert(countDistinctCharacters(("abcdecadeCADE")) == (5l)); assert(countDistinctCharacters(("aaaaAAAAaaaa")) == (1l)); assert(countDistinctCharacters(("Jerry jERRY JeRRRY")) == (5l)); } }
humaneval-HumanEval_28_concatenate.json-L7
js
//Concatenate array of strings into a single string // >>> concatenate([]) // "" // >>> concatenate(["a", "b", "c"]) // "abc" function concatenate(strings){
return ""; } var string = strings.join(""); return string; }
if(strings.length === 0){
const assert = require('node:assert'); function test() { let candidate = concatenate; assert.deepEqual(candidate([]),""); assert.deepEqual(candidate(["x", "y", "z"]),"xyz"); assert.deepEqual(candidate(["x", "y", "z", "w", "k"]),"xyzwk"); } test();
humaneval-HumanEval_113_odd_count.json-L21
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Given an array array list of strings, where each string consists of only digits, return an array array 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. // >>> oddCount((new ArrayList<String>(Arrays.asList((String)"1234567")))) // (new ArrayList<String>(Arrays.asList((String)"the number of odd elements 4n the str4ng 4 of the 4nput."))) // >>> oddCount((new ArrayList<String>(Arrays.asList((String)"3", (String)"11111111")))) // (new ArrayList<String>(Arrays.asList((String)"the number of odd elements 1n the str1ng 1 of the 1nput.", (String)"the number of odd elements 8n the str8ng 8 of the 8nput."))) public static ArrayList<String> oddCount(ArrayList<String> lst) { ArrayList<String> res = new ArrayList<String>(); for (int i = 0; i < lst.size(); i++) { int count = 0;
if (Integer.parseInt(lst.get(i).substring(j, j + 1)) % 2 == 1) { count++; } } res.add("the number of odd elements " + count + "n the str" + count + "ng " + count + " of the " + count + "nput."); } return res; } }
for (int j = 0; j < lst.get(i).length(); j++) {
} public static void main(String[] args) { assert(oddCount((new ArrayList<String>(Arrays.asList((String)"1234567")))).equals((new ArrayList<String>(Arrays.asList((String)"the number of odd elements 4n the str4ng 4 of the 4nput."))))); assert(oddCount((new ArrayList<String>(Arrays.asList((String)"3", (String)"11111111")))).equals((new ArrayList<String>(Arrays.asList((String)"the number of odd elements 1n the str1ng 1 of the 1nput.", (String)"the number of odd elements 8n the str8ng 8 of the 8nput."))))); assert(oddCount((new ArrayList<String>(Arrays.asList((String)"271", (String)"137", (String)"314")))).equals((new ArrayList<String>(Arrays.asList((String)"the number of odd elements 2n the str2ng 2 of the 2nput.", (String)"the number of odd elements 3n the str3ng 3 of the 3nput.", (String)"the number of odd elements 2n the str2ng 2 of the 2nput."))))); } }
humaneval-HumanEval_98_count_upper.json-L17
py
def count_upper(s: str) -> int: """ Given a string s, count the number of uppercase vowels in even indices. For example: >>> count_upper('aBCdEf') 1 >>> count_upper('abcdefg') 0 >>> count_upper('dBBE') 0 """ vowel_set = set('AEIOU') count = 0 for i in range(0, len(s), 2): if s[i] in vowel_set:
return count """ D.1 Recursion Given a positive integer n, write a recursive function that returns the sum of the squares of the positive odd integers smaller than n. Assume n is greater than or equal to 3. """
count += 1
def check(candidate): assert candidate('aBCdEf') == 1 assert candidate('abcdefg') == 0 assert candidate('dBBE') == 0 assert candidate('B') == 0 assert candidate('U') == 1 assert candidate('') == 0 assert candidate('EEEE') == 2 def test_check(): check(count_upper) test_check()
humaneval-HumanEval_122_add_elements.json-L12
js
//Given a non-empty array of integers arr and an integer k, return // the sum of the elements with at most two digits from the first k elements of arr. // Example: // >>> add_elements([111, 21, 3, 4000, 5, 6, 7, 8, 9], 4) // 24 // Constraints: // 1. 1 <= len(arr) <= 100 // 2. 1 <= k <= len(arr) function add_elements(arr, k){ var sum = 0; for(var i = 0; i < k; i++){
sum += arr[i]; } } return sum; }
if(arr[i] < 100){
const assert = require('node:assert'); function test() { let candidate = add_elements; assert.deepEqual(candidate([1, -2, -3, 41, 57, 76, 87, 88, 99], 3),-4); assert.deepEqual(candidate([111, 121, 3, 4000, 5, 6], 2),0); assert.deepEqual(candidate([11, 21, 3, 90, 5, 6, 7, 8, 9], 4),125); assert.deepEqual(candidate([111, 21, 3, 4000, 5, 6, 7, 8, 9], 4),24); assert.deepEqual(candidate([1], 1),1); } test();
humaneval-HumanEval_158_find_max.json-L26
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Write a function that accepts an array array list of strings. // The array list contains different words. Return the word with maximum number // of unique characters. If multiple strings have maximum number of unique // characters, return the one which comes first in lexicographical order. // >>> findMax((new ArrayList<String>(Arrays.asList((String)"name", (String)"of", (String)"string")))) // ("string") // >>> findMax((new ArrayList<String>(Arrays.asList((String)"name", (String)"enam", (String)"game")))) // ("enam") // >>> findMax((new ArrayList<String>(Arrays.asList((String)"aaaaaaa", (String)"bb", (String)"cc")))) // ("aaaaaaa") public static String findMax(ArrayList<String> words) { Map<String, Integer> wordsToUniqueCharacters = new HashMap<String, Integer>(); for (String word : words) { Set<Character> uniqueCharacters = new HashSet<Character>(); for (char c : word.toCharArray()) { uniqueCharacters.add(c); }
} words.sort(new Comparator<String>() { @Override public int compare(String o1, String o2) { int compareResult = wordsToUniqueCharacters.get(o2).compareTo(wordsToUniqueCharacters.get(o1)); if (compareResult == 0) { return o1.compareTo(o2); } return compareResult; } }); return words.get(0); } }
wordsToUniqueCharacters.put(word, uniqueCharacters.size());
} public static void main(String[] args) { assert(findMax((new ArrayList<String>(Arrays.asList((String)"name", (String)"of", (String)"string")))).equals(("string"))); assert(findMax((new ArrayList<String>(Arrays.asList((String)"name", (String)"enam", (String)"game")))).equals(("enam"))); assert(findMax((new ArrayList<String>(Arrays.asList((String)"aaaaaaa", (String)"bb", (String)"cc")))).equals(("aaaaaaa"))); assert(findMax((new ArrayList<String>(Arrays.asList((String)"abc", (String)"cba")))).equals(("abc"))); assert(findMax((new ArrayList<String>(Arrays.asList((String)"play", (String)"this", (String)"game", (String)"of", (String)"footbott")))).equals(("footbott"))); assert(findMax((new ArrayList<String>(Arrays.asList((String)"we", (String)"are", (String)"gonna", (String)"rock")))).equals(("gonna"))); assert(findMax((new ArrayList<String>(Arrays.asList((String)"we", (String)"are", (String)"a", (String)"mad", (String)"nation")))).equals(("nation"))); assert(findMax((new ArrayList<String>(Arrays.asList((String)"this", (String)"is", (String)"a", (String)"prrk")))).equals(("this"))); assert(findMax((new ArrayList<String>(Arrays.asList((String)"b")))).equals(("b"))); assert(findMax((new ArrayList<String>(Arrays.asList((String)"play", (String)"play", (String)"play")))).equals(("play"))); } }
humaneval-HumanEval_139_special_factorial.json-L21
py
def special_factorial(n: int) -> int: """The Brazilian factorial is defined as: brazilian_factorial(n) = n! * (n-1)! * (n-2)! * ... * 1! where n > 0 For example: >>> special_factorial(4) 288 The function will receive an integer as input and should return the special factorial of this integer. """ def factorial(n): if n <= 1: return 1 else: return n * factorial(n-1) if n <= 1: return 1 else:
return n * special_factorial(n-1) * factorial(n-1)
def check(candidate): assert candidate(4) == 288 assert candidate(5) == 34560 assert candidate(7) == 125411328000 assert candidate(1) == 1 def test_check(): check(special_factorial) test_check()
humaneval-HumanEval_160_do_algebra.json-L34
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Given two array lists operator, and operand. The first array list has basic algebra operations, and // the second array list is an array array list of integers. Use the two given array 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 array list = [2, 3, 4, 5] // result = 2 + 3 * 4 - 5 // => result = 9 // Note: // The length of operator array list is equal to the length of operand array list minus one. // Operand is an array array list of of non-negative integers. // Operator array list has at least one operator, and operand array list has at least two operands. public static long doAlgebra(ArrayList<String> op, ArrayList<Long> operand) { ArrayList<Long> list = new ArrayList<>(); list.add(operand.get(0)); for (int i = 0; i < op.size(); i++) { if (op.get(i).equals("+")) list.add(operand.get(i + 1)); else if (op.get(i).equals("-"))
else if (op.get(i).equals("*")) list.set(list.size() - 1, list.get(list.size() - 1) * operand.get(i + 1)); else if (op.get(i).equals("//")) list.set(list.size() - 1, list.get(list.size() - 1) / operand.get(i + 1)); else if (op.get(i).equals("**")) list.set(list.size() - 1, (long) Math.pow(list.get(list.size() - 1), operand.get(i + 1))); } return list.stream().mapToLong(x -> x).sum(); } }
list.add(-operand.get(i + 1));
} public static void main(String[] args) { assert(doAlgebra((new ArrayList<String>(Arrays.asList((String)"**", (String)"*", (String)"+"))), (new ArrayList<Long>(Arrays.asList((long)2l, (long)3l, (long)4l, (long)5l)))) == (37l)); assert(doAlgebra((new ArrayList<String>(Arrays.asList((String)"+", (String)"*", (String)"-"))), (new ArrayList<Long>(Arrays.asList((long)2l, (long)3l, (long)4l, (long)5l)))) == (9l)); assert(doAlgebra((new ArrayList<String>(Arrays.asList((String)"//", (String)"*"))), (new ArrayList<Long>(Arrays.asList((long)7l, (long)3l, (long)4l)))) == (8l)); } }
humaneval-HumanEval_138_is_equal_to_sum_even.json-L22
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Evaluate whether the given number n can be written as the sum of exactly 4 positive even numbers // Example // >>> isEqualToSumEven((4l)) // (false) // >>> isEqualToSumEven((6l)) // (false) // >>> isEqualToSumEven((8l)) // (true) public static boolean isEqualToSumEven(long n) { if (n < 4) { return false; } long d = 2;
d = 1; } long minX = d; long maxX = n / 4; while (minX <= maxX) { long x = (minX + maxX) / 2; long y = n - 2 * x; if (y % 2 == 1) { y--; } if (2 * x + y < n) { minX = x + 1; } else if (2 * x + y > n) { maxX = x - 1; } else { return true; } } return false; } }
if (n % 2 == 1) {
} public static void main(String[] args) { assert(isEqualToSumEven((4l)) == (false)); assert(isEqualToSumEven((6l)) == (false)); assert(isEqualToSumEven((8l)) == (true)); assert(isEqualToSumEven((10l)) == (true)); assert(isEqualToSumEven((11l)) == (false)); assert(isEqualToSumEven((12l)) == (true)); assert(isEqualToSumEven((13l)) == (false)); assert(isEqualToSumEven((16l)) == (true)); } }
humaneval-HumanEval_68_pluck.json-L53
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // "Given an array array list 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 an array array list, [ smalest_value, its index ], // If there are no even values or the given array array list is empty, return []. // Example 1: // >>> pluck((new ArrayList<Long>(Arrays.asList((long)4l, (long)2l, (long)3l)))) // (new ArrayList<Long>(Arrays.asList((long)2l, (long)1l))) // Explanation: 2 has the smallest even value, and 2 has the smallest index. // Example 2: // >>> pluck((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l)))) // (new ArrayList<Long>(Arrays.asList((long)2l, (long)1l))) // Explanation: 2 has the smallest even value, and 2 has the smallest index. // Example 3: // >>> pluck((new ArrayList<Long>(Arrays.asList()))) // (new ArrayList<Long>(Arrays.asList())) // Example 4: // >>> pluck((new ArrayList<Long>(Arrays.asList((long)5l, (long)0l, (long)3l, (long)0l, (long)4l, (long)2l)))) // (new ArrayList<Long>(Arrays.asList((long)0l, (long)1l))) // 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 public static ArrayList<Long> pluck(ArrayList<Long> arr) { int minIndex = -1; long minValue = -1; for (int i = 0; i < arr.size(); i++) { if (arr.get(i) % 2 == 0) { if (minIndex == -1 || arr.get(i) < minValue) { minIndex = i; minValue = arr.get(i); } } } ArrayList<Long> newArr = new ArrayList<Long>(); if (minIndex == -1) { return newArr; } newArr.add(minValue); newArr.add((long)minIndex); return newArr; }
}
} public static void main(String[] args) { assert(pluck((new ArrayList<Long>(Arrays.asList((long)4l, (long)2l, (long)3l)))).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)1l))))); assert(pluck((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l)))).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)1l))))); assert(pluck((new ArrayList<Long>(Arrays.asList()))).equals((new ArrayList<Long>(Arrays.asList())))); assert(pluck((new ArrayList<Long>(Arrays.asList((long)5l, (long)0l, (long)3l, (long)0l, (long)4l, (long)2l)))).equals((new ArrayList<Long>(Arrays.asList((long)0l, (long)1l))))); assert(pluck((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)0l, (long)5l, (long)3l)))).equals((new ArrayList<Long>(Arrays.asList((long)0l, (long)3l))))); assert(pluck((new ArrayList<Long>(Arrays.asList((long)5l, (long)4l, (long)8l, (long)4l, (long)8l)))).equals((new ArrayList<Long>(Arrays.asList((long)4l, (long)1l))))); assert(pluck((new ArrayList<Long>(Arrays.asList((long)7l, (long)6l, (long)7l, (long)1l)))).equals((new ArrayList<Long>(Arrays.asList((long)6l, (long)1l))))); assert(pluck((new ArrayList<Long>(Arrays.asList((long)7l, (long)9l, (long)7l, (long)1l)))).equals((new ArrayList<Long>(Arrays.asList())))); } }
humaneval-HumanEval_20_find_closest_elements.json-L12
py
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) """ temp, temp2 = abs(numbers[0] - numbers[1]), abs(numbers[0] - numbers[1])
if numbers[0] > numbers[1]: temp, temp2 = temp2, temp temp_index, temp2_index = temp2_index, temp_index for i in range(len(numbers)): for j in range(i+1, len(numbers)): if abs(numbers[i] - numbers[j]) < temp: temp = abs(numbers[i] - numbers[j]) temp_index = i temp2_index = j elif abs(numbers[i] - numbers[j]) == temp: if numbers[i] > numbers[j]: temp = abs(numbers[i] - numbers[j]) temp_index = i temp2_index = j if numbers[temp_index] > numbers[temp2_index]: temp, temp2 = numbers[temp2_index], numbers[temp_index] else: temp, temp2 = numbers[temp_index], numbers[temp2_index] return temp, temp2 print(find_closest_elements([1.0, 2.0, 3.0, 4.0, 5.0, 2.2]))
temp_index, temp2_index = 0, 1
def check(candidate): assert candidate([1.0, 2.0, 3.9, 4.0, 5.0, 2.2]) == (3.9, 4.0) assert candidate([1.0, 2.0, 5.9, 4.0, 5.0]) == (5.0, 5.9) assert candidate([1.0, 2.0, 3.0, 4.0, 5.0, 2.2]) == (2.0, 2.2) assert candidate([1.0, 2.0, 3.0, 4.0, 5.0, 2.0]) == (2.0, 2.0) assert candidate([1.1, 2.2, 3.1, 4.1, 5.1]) == (2.2, 3.1) def test_check(): check(find_closest_elements) test_check()
humaneval-HumanEval_95_check_dict_case.json-L24
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Given a hash map, return true if all keys are strings in lower // case or all keys are strings in upper case, else return false. // The function should return false is the given hash map is empty. // Examples: // >>> checkDictCase((new HashMap<String,String>(Map.of("a", "apple", "b", "banana")))) // (true) // >>> checkDictCase((new HashMap<String,String>(Map.of("a", "apple", "A", "banana", "B", "banana")))) // (false) // >>> checkDictCase((new HashMap<String,String>(Map.of("a", "apple", 8l, "banana", "a", "apple")))) // (false) // >>> checkDictCase((new HashMap<String,String>(Map.of("Name", "John", "Age", "36", "City", "Houston")))) // (false) // >>> checkDictCase((new HashMap<String,String>(Map.of("STATE", "NC", "ZIP", "12345")))) // (true) public static boolean checkDictCase(HashMap<String,String> dict) {
return false; } boolean allLowerCase = dict.keySet().stream().allMatch(k -> k.matches("^[a-z]+$")); boolean allUpperCase = dict.keySet().stream().allMatch(k -> k.matches("^[A-Z]+$")); return allLowerCase || allUpperCase; } }
if (dict.isEmpty()) {
} public static void main(String[] args) { assert(checkDictCase((new HashMap<String,String>(Map.of("p", "pineapple", "b", "banana")))) == (true)); assert(checkDictCase((new HashMap<String,String>(Map.of("p", "pineapple", "A", "banana", "B", "banana")))) == (false)); assert(checkDictCase((new HashMap<String,String>(Map.of("p", "pineapple", "5", "banana", "a", "apple")))) == (false)); assert(checkDictCase((new HashMap<String,String>(Map.of("Name", "John", "Age", "36", "City", "Houston")))) == (false)); assert(checkDictCase((new HashMap<String,String>(Map.of("STATE", "NC", "ZIP", "12345")))) == (true)); assert(checkDictCase((new HashMap<String,String>(Map.of("fruit", "Orange", "taste", "Sweet")))) == (true)); assert(checkDictCase((new HashMap<String,String>())) == (false)); } }
humaneval-HumanEval_133_sum_squares.json-L22
py
from typing import List def sum_squares(lst: List[float]) -> int: """You are given a list of numbers. You need to return the sum of squared numbers in the given list, round each element in the list to the upper int(Ceiling) first. Examples: >>> lst([1.0, 2.0, 3.0]) 14 >>> lst([1.0, 4.0, 9.0]) 98 >>> lst([1.0, 3.0, 5.0, 7.0]) 84 >>> lst([1.4, 4.2, 0.0]) 29 >>> lst([-2.4, 1.0, 1.0]) 6 """ import math
lst[i] = math.ceil(lst[i]) total = 0 for i in lst: total += i**2 return total
for i in range(len(lst)):
def check(candidate): assert candidate([1.0, 2.0, 3.0]) == 14 assert candidate([1.0, 2.0, 3.0]) == 14 assert candidate([1.0, 3.0, 5.0, 7.0]) == 84 assert candidate([1.4, 4.2, 0.0]) == 29 assert candidate([-2.4, 1.0, 1.0]) == 6 assert candidate([100.0, 1.0, 15.0, 2.0]) == 10230 assert candidate([10000.0, 10000.0]) == 200000000 assert candidate([-1.4, 4.6, 6.3]) == 75 assert candidate([-1.4, 17.9, 18.9, 19.9]) == 1086 assert candidate([0.0]) == 0 assert candidate([-1.0]) == 1 assert candidate([-1.0, 1.0, 0.0]) == 2 def test_check(): check(sum_squares) test_check()
humaneval-HumanEval_17_parse_music.json-L20
js
//Input to this function is a string representing musical notes in a special ASCII format. // Your task is to parse this string and return array of integers corresponding to how many beats does each // not last. // Here is a legend: // 'o' - whole note, lasts four beats // 'o|' - half note, lasts two beats // '.|' - quater note, lasts one beat // >>> parse_music("o o| .| o| o| .| .| .| .| o o") // [4, 2, 1, 2, 2, 1, 1, 1, 1, 4, 4] function parse_music(music_string){ let songs = music_string.split(' '); let song = []; songs.forEach(s => { if(s === 'o'){ song.push(4); }else if(s === 'o|'){ song.push(2); }else if(s === '.|'){ song.push(1);
}); return song; }
}
const assert = require('node:assert'); function test() { let candidate = parse_music; assert.deepEqual(candidate(""),[]); assert.deepEqual(candidate("o o o o"),[4, 4, 4, 4]); assert.deepEqual(candidate(".| .| .| .|"),[1, 1, 1, 1]); assert.deepEqual(candidate("o| o| .| .| o o o o"),[2, 2, 1, 1, 4, 4, 4, 4]); assert.deepEqual(candidate("o| .| o| .| o o| o o|"),[2, 1, 2, 1, 4, 2, 4, 2]); } test();
humaneval-HumanEval_156_int_to_mini_roman.json-L16
js
//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" function int_to_mini_roman(number){ var roman_conversion = { 1000: "m", 900: "cm", 500: "d",
100: "c", 90: "xc", 50: "l", 40: "xl", 10: "x", 9: "ix", 5: "v", 4: "iv", 1: "i" }; var output = ""; while (number > 0){ var key_list = Object.keys(roman_conversion).map(Number); key_list.sort(function(a, b){return b-a}); for (var i = 0; i < key_list.length; i++){ if (key_list[i] <= number){ output += roman_conversion[key_list[i]]; number -= key_list[i]; break; } } } return output; }
400: "cd",
const assert = require('node:assert'); function test() { let candidate = int_to_mini_roman; assert.deepEqual(candidate(19),"xix"); assert.deepEqual(candidate(152),"clii"); assert.deepEqual(candidate(251),"ccli"); assert.deepEqual(candidate(426),"cdxxvi"); assert.deepEqual(candidate(500),"d"); assert.deepEqual(candidate(1),"i"); assert.deepEqual(candidate(4),"iv"); assert.deepEqual(candidate(43),"xliii"); assert.deepEqual(candidate(90),"xc"); assert.deepEqual(candidate(94),"xciv"); assert.deepEqual(candidate(532),"dxxxii"); assert.deepEqual(candidate(900),"cm"); assert.deepEqual(candidate(994),"cmxciv"); assert.deepEqual(candidate(1000),"m"); } test();
humaneval-HumanEval_108_count_nums.json-L22
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Write a function count_nums which takes an array array list 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. // >>> countNums((new ArrayList<Long>(Arrays.asList()))) // (0l) // >>> countNums((new ArrayList<Long>(Arrays.asList((long)-1l, (long)11l, (long)-11l)))) // (1l) // >>> countNums((new ArrayList<Long>(Arrays.asList((long)1l, (long)1l, (long)2l)))) // (3l) public static long countNums(ArrayList<Long> arr) { long result = 0l; for (long i : arr) {
int sum = 0; if (str.startsWith("-")) { sum = sum - (int) Character.getNumericValue(str.charAt(1)); for (int j = 2; j < str.length(); j++) { sum = sum + (int) Character.getNumericValue(str.charAt(j)); } } else { for (int j = 0; j < str.length(); j++) { sum = sum + (int) Character.getNumericValue(str.charAt(j)); } } if (sum > 0) { result++; } } return result; } }
String str = String.valueOf(i);
} public static void main(String[] args) { assert(countNums((new ArrayList<Long>(Arrays.asList()))) == (0l)); assert(countNums((new ArrayList<Long>(Arrays.asList((long)-1l, (long)-2l, (long)0l)))) == (0l)); assert(countNums((new ArrayList<Long>(Arrays.asList((long)1l, (long)1l, (long)2l, (long)-2l, (long)3l, (long)4l, (long)5l)))) == (6l)); assert(countNums((new ArrayList<Long>(Arrays.asList((long)1l, (long)6l, (long)9l, (long)-6l, (long)0l, (long)1l, (long)5l)))) == (5l)); assert(countNums((new ArrayList<Long>(Arrays.asList((long)1l, (long)100l, (long)98l, (long)-7l, (long)1l, (long)-1l)))) == (4l)); assert(countNums((new ArrayList<Long>(Arrays.asList((long)12l, (long)23l, (long)34l, (long)-45l, (long)-56l, (long)0l)))) == (5l)); assert(countNums((new ArrayList<Long>(Arrays.asList((long)0l, (long)1l)))) == (1l)); assert(countNums((new ArrayList<Long>(Arrays.asList((long)1l)))) == (1l)); } }
humaneval-HumanEval_73_smallest_change.json-L32
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Given an array array list arr of integers, find the minimum number of elements that // need to be changed to make the array array list palindromic. A palindromic array array list is an array array list that // is read the same backwards and forwards. In one change, you can change one element to any other element. // For example: // >>> smallestChange((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)5l, (long)4l, (long)7l, (long)9l, (long)6l)))) // (4l) // >>> smallestChange((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l, (long)3l, (long)2l, (long)2l)))) // (1l) // >>> smallestChange((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)2l, (long)1l)))) // (0l) public static long smallestChange(ArrayList<Long> arr) { int first = 0; int last = arr.size() - 1; int count = 0; while (first < last) { if (arr.get(first) != arr.get(last)) { count++; } first++; last--; } return count; }
}
} public static void main(String[] args) { assert(smallestChange((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)5l, (long)4l, (long)7l, (long)9l, (long)6l)))) == (4l)); assert(smallestChange((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l, (long)3l, (long)2l, (long)2l)))) == (1l)); assert(smallestChange((new ArrayList<Long>(Arrays.asList((long)1l, (long)4l, (long)2l)))) == (1l)); assert(smallestChange((new ArrayList<Long>(Arrays.asList((long)1l, (long)4l, (long)4l, (long)2l)))) == (1l)); assert(smallestChange((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)2l, (long)1l)))) == (0l)); assert(smallestChange((new ArrayList<Long>(Arrays.asList((long)3l, (long)1l, (long)1l, (long)3l)))) == (0l)); assert(smallestChange((new ArrayList<Long>(Arrays.asList((long)1l)))) == (0l)); assert(smallestChange((new ArrayList<Long>(Arrays.asList((long)0l, (long)1l)))) == (1l)); } }
humaneval-HumanEval_147_get_max_triples.json-L25
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // You are given a positive integer n. You have to create an integer array array list 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 : // >>> getMaxTriples((5l)) // (1l) // Explanation: // a = [1, 3, 7, 13, 21] // The only valid triple is (1, 7, 13). public static long getMaxTriples(long n) { int count = 0; ArrayList<Integer> arrayList = new ArrayList<Integer>(); for (int i = 1; i <= n; i++) { arrayList.add(i * i - i + 1); }
for (int j = i + 1; j < arrayList.size(); j++) { for (int k = j + 1; k < arrayList.size(); k++) { if ((arrayList.get(i) + arrayList.get(j) + arrayList.get(k)) % 3 == 0) { count++; } } } } return count; } }
for (int i = 0; i < arrayList.size(); i++) {
} public static void main(String[] args) { assert(getMaxTriples((5l)) == (1l)); assert(getMaxTriples((6l)) == (4l)); assert(getMaxTriples((10l)) == (36l)); assert(getMaxTriples((100l)) == (53361l)); } }
humaneval-HumanEval_111_histogram.json-L28
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Given a string representing a space separated lowercase letters, return a hash map // 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")) // (new HashMap<String,Long>(Map.of("a", 1l, "b", 1l, "c", 1l))) // >>> histogram(("a b b a")) // (new HashMap<String,Long>(Map.of("a", 2l, "b", 2l))) // >>> histogram(("a b c a b")) // (new HashMap<String,Long>(Map.of("a", 2l, "b", 2l))) // >>> histogram(("b b b b a")) // (new HashMap<String,Long>(Map.of("b", 4l))) // >>> histogram(("")) // (new HashMap<String,Long>()) public static HashMap<String,Long> histogram(String test) { HashMap<String,Long> s = new HashMap<String,Long>(); if (test.length() > 0) { HashMap<String,Long> hm = new HashMap<String,Long>(); String[] ss = test.split(" ");
if (hm.containsKey(sss)) { hm.put(sss, hm.get(sss) + 1); } else { hm.put(sss, 1l); } } long max = 0; for (String key : hm.keySet()) { if (hm.get(key) > max) { max = hm.get(key); } } for (String key : hm.keySet()) { if (hm.get(key) == max) { s.put(key, hm.get(key)); } } } return s; } }
for (String sss : ss) {
} public static void main(String[] args) { assert(histogram(("a b b a")).equals((new HashMap<String,Long>(Map.of("a", 2l, "b", 2l))))); assert(histogram(("a b c a b")).equals((new HashMap<String,Long>(Map.of("a", 2l, "b", 2l))))); assert(histogram(("a b c d g")).equals((new HashMap<String,Long>(Map.of("a", 1l, "b", 1l, "c", 1l, "d", 1l, "g", 1l))))); assert(histogram(("r t g")).equals((new HashMap<String,Long>(Map.of("r", 1l, "t", 1l, "g", 1l))))); assert(histogram(("b b b b a")).equals((new HashMap<String,Long>(Map.of("b", 4l))))); assert(histogram(("r t g")).equals((new HashMap<String,Long>(Map.of("r", 1l, "t", 1l, "g", 1l))))); assert(histogram(("")).equals((new HashMap<String,Long>()))); assert(histogram(("a")).equals((new HashMap<String,Long>(Map.of("a", 1l))))); } }
humaneval-HumanEval_127_intersection.json-L29
js
//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" function intersection(interval1, interval2){ let start = Math.max(interval1[0], interval2[0]); let end = Math.min(interval1[1], interval2[1]); if (start >= end) { return "NO"; } let length = end - start; let primes = [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]; return primes.includes(length) ? "YES" : "NO";
}
const assert = require('node:assert'); function test() { let candidate = intersection; assert.deepEqual(candidate([1, 2], [2, 3]),"NO"); assert.deepEqual(candidate([-1, 1], [0, 4]),"NO"); assert.deepEqual(candidate([-3, -1], [-5, 5]),"YES"); assert.deepEqual(candidate([-2, 2], [-4, 0]),"YES"); assert.deepEqual(candidate([-11, 2], [-1, -1]),"NO"); assert.deepEqual(candidate([1, 2], [3, 5]),"NO"); assert.deepEqual(candidate([1, 2], [1, 2]),"NO"); assert.deepEqual(candidate([-2, -2], [-3, -2]),"NO"); } test();
humaneval-HumanEval_52_below_threshold.json-L11
py
from typing import List def below_threshold(l: List[int], t: int) -> bool: """Return True if all numbers in the list l are below threshold t. >>> below_threshold([1, 2, 4, 10], 100) True >>> below_threshold([1, 20, 4, 10], 5) False """ for num in l:
return False return True
if num >= t:
def check(candidate): assert candidate([1, 2, 4, 10], 100) == True assert candidate([1, 20, 4, 10], 5) == False assert candidate([1, 20, 4, 10], 21) == True assert candidate([1, 20, 4, 10], 22) == True assert candidate([1, 8, 4, 10], 11) == True assert candidate([1, 8, 4, 10], 10) == False def test_check(): check(below_threshold) test_check()
humaneval-HumanEval_27_flip_case.json-L20
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // For a given string, flip lowercase characters to uppercase and uppercase to lowercase. // >>> flipCase(("Hello")) // ("hELLO") public static String flipCase(String string) { String answer = ""; for (int i = 0; i < string.length(); i++) { if (Character.isLowerCase(string.charAt(i))) { answer += Character.toUpperCase(string.charAt(i)); } else { answer += Character.toLowerCase(string.charAt(i)); }
return answer; } }
}
} public static void main(String[] args) { assert(flipCase(("")).equals((""))); assert(flipCase(("Hello!")).equals(("hELLO!"))); assert(flipCase(("These violent delights have violent ends")).equals(("tHESE VIOLENT DELIGHTS HAVE VIOLENT ENDS"))); } }
humaneval-HumanEval_147_get_max_triples.json-L23
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // You are given a positive integer n. You have to create an integer array array list 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 : // >>> getMaxTriples((5l)) // (1l) // Explanation: // a = [1, 3, 7, 13, 21] // The only valid triple is (1, 7, 13). public static long getMaxTriples(long n) { int count = 0; ArrayList<Integer> arrayList = new ArrayList<Integer>(); for (int i = 1; i <= n; i++) {
} for (int i = 0; i < arrayList.size(); i++) { for (int j = i + 1; j < arrayList.size(); j++) { for (int k = j + 1; k < arrayList.size(); k++) { if ((arrayList.get(i) + arrayList.get(j) + arrayList.get(k)) % 3 == 0) { count++; } } } } return count; } }
arrayList.add(i * i - i + 1);
} public static void main(String[] args) { assert(getMaxTriples((5l)) == (1l)); assert(getMaxTriples((6l)) == (4l)); assert(getMaxTriples((10l)) == (36l)); assert(getMaxTriples((100l)) == (53361l)); } }
humaneval-HumanEval_110_exchange.json-L27
js
//In this problem, you will implement a function that takes two arrays of numbers, // and determines whether it is possible to perform an exchange of elements // between them to make lst1 an array 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 arrays will be non-empty. function exchange(lst1, lst2){ var num1 = 0; var num2 = 0; var exchange = true; while(num1 < lst1.length && exchange){ if(lst1[num1] % 2 !== 0){ exchange = false; if(num2 < lst2.length){ while(num2 < lst2.length && exchange == false){ if(lst2[num2] % 2 == 0){ lst1[num1] = lst2[num2]; exchange = true; }
} } } num1++; } if(exchange){ return "YES"; }else{ return "NO"; } }
num2++;
const assert = require('node:assert'); function test() { let candidate = exchange; assert.deepEqual(candidate([1, 2, 3, 4], [1, 2, 3, 4]),"YES"); assert.deepEqual(candidate([1, 2, 3, 4], [1, 5, 3, 4]),"NO"); assert.deepEqual(candidate([1, 2, 3, 4], [2, 1, 4, 3]),"YES"); assert.deepEqual(candidate([5, 7, 3], [2, 6, 4]),"YES"); assert.deepEqual(candidate([5, 7, 3], [2, 6, 3]),"NO"); assert.deepEqual(candidate([3, 2, 6, 1, 8, 9], [3, 5, 5, 1, 1, 1]),"NO"); assert.deepEqual(candidate([100, 200], [200, 200]),"YES"); } test();
humaneval-HumanEval_124_valid_date.json-L27
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // 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 // >>> validDate(("03-11-2000")) // (true) // >>> validDate(("15-01-2012")) // (false) // >>> validDate(("04-0-2040")) // (false) // >>> validDate(("06-04-2020")) // (true) // >>> validDate(("06/04/2020")) // (false) public static boolean validDate(String date) {
if (date.equals("")) return valid_date; String[] parts = date.split("-"); if (parts.length != 3) return valid_date; try { int month = Integer.parseInt(parts[0]); int day = Integer.parseInt(parts[1]); int year = Integer.parseInt(parts[2]); if (month < 1 || month > 12) return valid_date; if (month == 2) { if (day < 1 || day > 29) return valid_date; } else if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) { if (day < 1 || day > 31) return valid_date; } else { if (day < 1 || day > 30) return valid_date; } valid_date = true; } catch (Exception e) { valid_date = false; } return valid_date; } }
boolean valid_date = false;
} public static void main(String[] args) { assert(validDate(("03-11-2000")) == (true)); assert(validDate(("15-01-2012")) == (false)); assert(validDate(("04-0-2040")) == (false)); assert(validDate(("06-04-2020")) == (true)); assert(validDate(("01-01-2007")) == (true)); assert(validDate(("03-32-2011")) == (false)); assert(validDate(("")) == (false)); assert(validDate(("04-31-3000")) == (false)); assert(validDate(("06-06-2005")) == (true)); assert(validDate(("21-31-2000")) == (false)); assert(validDate(("04-12-2003")) == (true)); assert(validDate(("04122003")) == (false)); assert(validDate(("20030412")) == (false)); assert(validDate(("2003-04")) == (false)); assert(validDate(("2003-04-12")) == (false)); assert(validDate(("04-2003")) == (false)); } }
humaneval-HumanEval_25_factorize.json-L16
py
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] """ factors = [] i = 2
while n % i == 0: factors.append(i) n = n / i i += 1 return factors
while i <= n:
def check(candidate): assert candidate(2) == [2] assert candidate(4) == [2, 2] assert candidate(8) == [2, 2, 2] assert candidate(57) == [3, 19] assert candidate(3249) == [3, 3, 19, 19] assert candidate(185193) == [3, 3, 3, 19, 19, 19] assert candidate(20577) == [3, 19, 19, 19] assert candidate(18) == [2, 3, 3] def test_check(): check(factorize) test_check()
humaneval-HumanEval_13_greatest_common_divisor.json-L8
py
def greatest_common_divisor(a: int, b: int) -> int: """ Return a greatest common divisor of two integers a and b >>> greatest_common_divisor(3, 5) 1 >>> greatest_common_divisor(25, 15) 5 """
a, b = b, a if a == 0: return b return greatest_common_divisor(b % a, a)
if a > b:
def check(candidate): assert candidate(3, 7) == 1 assert candidate(10, 15) == 5 assert candidate(49, 14) == 7 assert candidate(144, 60) == 12 def test_check(): check(greatest_common_divisor) test_check()
humaneval-HumanEval_131_digits.json-L27
js
//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 function digits(n){ if(!n){ return "error"; } if(n < 0){ return "error"; } var temp = 0; var prod = 1; var odd = true; for(n; n > 0; n = Math.floor(n/10)){ temp = n % 10; if(temp % 2 != 0){ prod *= temp; odd = false; } }
return 0; } return prod; }
if(odd){
const assert = require('node:assert'); function test() { let candidate = digits; assert.deepEqual(candidate(5),5); assert.deepEqual(candidate(54),5); assert.deepEqual(candidate(120),1); assert.deepEqual(candidate(5014),5); assert.deepEqual(candidate(98765),315); assert.deepEqual(candidate(5576543),2625); assert.deepEqual(candidate(2468),0); } test();
humaneval-HumanEval_161_solve.json-L42
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // 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") public static String solve(String s) { boolean letterNotFound = true; StringBuilder sb = new StringBuilder(); if (s.length() == 0) return s; for (int i = 0; i < s.length(); i++) { if (Character.isLetter(s.charAt(i))) { letterNotFound = false; if (Character.isUpperCase(s.charAt(i))) { sb.append(Character.toLowerCase(s.charAt(i))); } else { sb.append(Character.toUpperCase(s.charAt(i))); } } else { sb.append(s.charAt(i)); } } if (letterNotFound) { return sb.reverse().toString(); } return sb.toString(); }
}
} public static void main(String[] args) { assert(solve(("AsDf")).equals(("aSdF"))); assert(solve(("1234")).equals(("4321"))); assert(solve(("ab")).equals(("AB"))); assert(solve(("#a@C")).equals(("#A@c"))); assert(solve(("#AsdfW^45")).equals(("#aSDFw^45"))); assert(solve(("#6@2")).equals(("2@6#"))); assert(solve(("#$a^D")).equals(("#$A^d"))); assert(solve(("#ccc")).equals(("#CCC"))); } }
humaneval-HumanEval_110_exchange.json-L35
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // In this problem, you will implement a function that takes two array lists of numbers, // and determines whether it is possible to perform an exchange of elements // between them to make lst1 an array array 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((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l))), (new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l)))) // ("YES") // >>> exchange((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l))), (new ArrayList<Long>(Arrays.asList((long)1l, (long)5l, (long)3l, (long)4l)))) // ("NO") // It is assumed that the input array lists will be non-empty. public static String exchange(ArrayList<Long> lst1, ArrayList<Long> lst2) { for (int i = 0; i < lst1.size(); i++) { if (lst1.get(i) % 2 == 1) { for (int j = 0; j < lst2.size(); j++) { if (lst2.get(j) % 2 == 0) { lst1.set(i, lst2.get(j)); lst2.set(j, (long) 1); break; } } } } return (lst1.stream().allMatch(x -> x % 2 == 0)) ? "YES" : "NO";
}
}
} public static void main(String[] args) { assert(exchange((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l))), (new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l)))).equals(("YES"))); assert(exchange((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l))), (new ArrayList<Long>(Arrays.asList((long)1l, (long)5l, (long)3l, (long)4l)))).equals(("NO"))); assert(exchange((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l))), (new ArrayList<Long>(Arrays.asList((long)2l, (long)1l, (long)4l, (long)3l)))).equals(("YES"))); assert(exchange((new ArrayList<Long>(Arrays.asList((long)5l, (long)7l, (long)3l))), (new ArrayList<Long>(Arrays.asList((long)2l, (long)6l, (long)4l)))).equals(("YES"))); assert(exchange((new ArrayList<Long>(Arrays.asList((long)5l, (long)7l, (long)3l))), (new ArrayList<Long>(Arrays.asList((long)2l, (long)6l, (long)3l)))).equals(("NO"))); assert(exchange((new ArrayList<Long>(Arrays.asList((long)3l, (long)2l, (long)6l, (long)1l, (long)8l, (long)9l))), (new ArrayList<Long>(Arrays.asList((long)3l, (long)5l, (long)5l, (long)1l, (long)1l, (long)1l)))).equals(("NO"))); assert(exchange((new ArrayList<Long>(Arrays.asList((long)100l, (long)200l))), (new ArrayList<Long>(Arrays.asList((long)200l, (long)200l)))).equals(("YES"))); } }
humaneval-HumanEval_37_sort_even.json-L22
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // This function takes an array array list l and returns an array array 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. // >>> sortEven((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l)))) // (new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l))) // >>> sortEven((new ArrayList<Long>(Arrays.asList((long)5l, (long)6l, (long)3l, (long)4l)))) // (new ArrayList<Long>(Arrays.asList((long)3l, (long)6l, (long)5l, (long)4l))) public static ArrayList<Long> sortEven(ArrayList<Long> l) { ArrayList<Long> res = new ArrayList<Long>(); ArrayList<Long> evenIndexed = new ArrayList<Long>(); int index = 0; for (Long num : l) { if (index % 2 == 0) {
} index++; } Collections.sort(evenIndexed); index = 0; for (Long num : l) { if (index % 2 == 0) { res.add(evenIndexed.get(0)); evenIndexed.remove(0); } else { res.add(num); } index++; } return res; } }
evenIndexed.add(num);
} public static void main(String[] args) { assert(sortEven((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l)))).equals((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l))))); assert(sortEven((new ArrayList<Long>(Arrays.asList((long)5l, (long)3l, (long)-5l, (long)2l, (long)-3l, (long)3l, (long)9l, (long)0l, (long)123l, (long)1l, (long)-10l)))).equals((new ArrayList<Long>(Arrays.asList((long)-10l, (long)3l, (long)-5l, (long)2l, (long)-3l, (long)3l, (long)5l, (long)0l, (long)9l, (long)1l, (long)123l))))); assert(sortEven((new ArrayList<Long>(Arrays.asList((long)5l, (long)8l, (long)-12l, (long)4l, (long)23l, (long)2l, (long)3l, (long)11l, (long)12l, (long)-10l)))).equals((new ArrayList<Long>(Arrays.asList((long)-12l, (long)8l, (long)3l, (long)4l, (long)5l, (long)2l, (long)12l, (long)11l, (long)23l, (long)-10l))))); } }
humaneval-HumanEval_149_sorted_list_sum.json-L36
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Write a function that accepts an array array list of strings as a parameter, // deletes the strings that have odd lengths from it, // and returns the resulted array list with a sorted order, // The array list is always an array array list of strings and never an array array list of numbers, // and it may contain duplicates. // The order of the array list should be ascending by length of each word, and you // should return the array list sorted by that rule. // If two words have the same length, sort the array list alphabetically. // The function should return an array array list of strings in sorted order. // You may assume that all words will have the same length. // For example: // >>> listSort((new ArrayList<String>(Arrays.asList((String)"aa", (String)"a", (String)"aaa")))) // (new ArrayList<String>(Arrays.asList((String)"aa"))) // >>> listSort((new ArrayList<String>(Arrays.asList((String)"ab", (String)"a", (String)"aaa", (String)"cd")))) // (new ArrayList<String>(Arrays.asList((String)"ab", (String)"cd"))) public static ArrayList<String> sortedListSum(ArrayList<String> lst) { ArrayList<String> result = new ArrayList<String>(); for (String s : lst) { if (s.length() % 2 == 0) { result.add(s); } } Collections.sort(result, new Comparator<String>() { @Override public int compare(String s1, String s2) { if (s1.length() == s2.length()) { return s1.compareTo(s2);
return s1.length() - s2.length(); } }); return result; } }
}
} public static void main(String[] args) { assert(sortedListSum((new ArrayList<String>(Arrays.asList((String)"aa", (String)"a", (String)"aaa")))).equals((new ArrayList<String>(Arrays.asList((String)"aa"))))); assert(sortedListSum((new ArrayList<String>(Arrays.asList((String)"school", (String)"AI", (String)"asdf", (String)"b")))).equals((new ArrayList<String>(Arrays.asList((String)"AI", (String)"asdf", (String)"school"))))); assert(sortedListSum((new ArrayList<String>(Arrays.asList((String)"d", (String)"b", (String)"c", (String)"a")))).equals((new ArrayList<String>(Arrays.asList())))); assert(sortedListSum((new ArrayList<String>(Arrays.asList((String)"d", (String)"dcba", (String)"abcd", (String)"a")))).equals((new ArrayList<String>(Arrays.asList((String)"abcd", (String)"dcba"))))); assert(sortedListSum((new ArrayList<String>(Arrays.asList((String)"AI", (String)"ai", (String)"au")))).equals((new ArrayList<String>(Arrays.asList((String)"AI", (String)"ai", (String)"au"))))); assert(sortedListSum((new ArrayList<String>(Arrays.asList((String)"a", (String)"b", (String)"b", (String)"c", (String)"c", (String)"a")))).equals((new ArrayList<String>(Arrays.asList())))); assert(sortedListSum((new ArrayList<String>(Arrays.asList((String)"aaaa", (String)"bbbb", (String)"dd", (String)"cc")))).equals((new ArrayList<String>(Arrays.asList((String)"cc", (String)"dd", (String)"aaaa", (String)"bbbb"))))); } }
humaneval-HumanEval_23_strlen.json-L9
py
def strlen(string: str) -> int: """ Return length of given string >>> strlen('') 0 >>> strlen('abc') 3 """ length = 0
length += 1 return length
for char in string:
def check(candidate): assert candidate('') == 0 assert candidate('x') == 1 assert candidate('asdasnakj') == 9 def test_check(): check(strlen) test_check()
humaneval-HumanEval_70_strange_sort_list.json-L25
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Given array list of integers, return array 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: // >>> strangeSortList((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l)))) // (new ArrayList<Long>(Arrays.asList((long)1l, (long)4l, (long)2l, (long)3l))) // >>> strangeSortList((new ArrayList<Long>(Arrays.asList((long)5l, (long)5l, (long)5l, (long)5l)))) // (new ArrayList<Long>(Arrays.asList((long)5l, (long)5l, (long)5l, (long)5l))) // >>> strangeSortList((new ArrayList<Long>(Arrays.asList()))) // (new ArrayList<Long>(Arrays.asList())) public static ArrayList<Long> strangeSortList(ArrayList<Long> lst) { if (lst.size() <= 1) { return lst; } ArrayList<Long> result = new ArrayList<Long>(); ArrayList<Long> sorted = new ArrayList<Long>(lst);
int min = 0; int max = sorted.size() - 1; while (min <= max) { result.add(sorted.get(min)); min++; if (min <= max) { result.add(sorted.get(max)); max--; } } return result; } }
Collections.sort(sorted);
} public static void main(String[] args) { assert(strangeSortList((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l)))).equals((new ArrayList<Long>(Arrays.asList((long)1l, (long)4l, (long)2l, (long)3l))))); assert(strangeSortList((new ArrayList<Long>(Arrays.asList((long)5l, (long)6l, (long)7l, (long)8l, (long)9l)))).equals((new ArrayList<Long>(Arrays.asList((long)5l, (long)9l, (long)6l, (long)8l, (long)7l))))); assert(strangeSortList((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l, (long)5l)))).equals((new ArrayList<Long>(Arrays.asList((long)1l, (long)5l, (long)2l, (long)4l, (long)3l))))); assert(strangeSortList((new ArrayList<Long>(Arrays.asList((long)5l, (long)6l, (long)7l, (long)8l, (long)9l, (long)1l)))).equals((new ArrayList<Long>(Arrays.asList((long)1l, (long)9l, (long)5l, (long)8l, (long)6l, (long)7l))))); assert(strangeSortList((new ArrayList<Long>(Arrays.asList((long)5l, (long)5l, (long)5l, (long)5l)))).equals((new ArrayList<Long>(Arrays.asList((long)5l, (long)5l, (long)5l, (long)5l))))); assert(strangeSortList((new ArrayList<Long>(Arrays.asList()))).equals((new ArrayList<Long>(Arrays.asList())))); assert(strangeSortList((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l, (long)5l, (long)6l, (long)7l, (long)8l)))).equals((new ArrayList<Long>(Arrays.asList((long)1l, (long)8l, (long)2l, (long)7l, (long)3l, (long)6l, (long)4l, (long)5l))))); assert(strangeSortList((new ArrayList<Long>(Arrays.asList((long)0l, (long)2l, (long)2l, (long)2l, (long)5l, (long)5l, (long)-5l, (long)-5l)))).equals((new ArrayList<Long>(Arrays.asList((long)-5l, (long)5l, (long)-5l, (long)5l, (long)0l, (long)2l, (long)2l, (long)2l))))); assert(strangeSortList((new ArrayList<Long>(Arrays.asList((long)111111l)))).equals((new ArrayList<Long>(Arrays.asList((long)111111l))))); } }
humaneval-HumanEval_138_is_equal_to_sum_even.json-L22
js
//Evaluate whether the given number n can be written as the sum of exactly 4 positive even numbers // Example // >>> is_equal_to_sum_even(4) // false // >>> is_equal_to_sum_even(6) // false // >>> is_equal_to_sum_even(8) // true function is_equal_to_sum_even(n){ let m =0; for(let i=2;i<n;i+=2){ for(let j=2;j<n;j+=2){ for(let k=2;k<n;k+=2){ for(let l=2;l<n;l+=2){ if((i+j+k+l)==n){ m=1; break; } } } }
if(m==1){ return true; } else{ return false; } }
}
const assert = require('node:assert'); function test() { let candidate = is_equal_to_sum_even; assert.deepEqual(candidate(4),false); assert.deepEqual(candidate(6),false); assert.deepEqual(candidate(8),true); assert.deepEqual(candidate(10),true); assert.deepEqual(candidate(11),false); assert.deepEqual(candidate(12),true); assert.deepEqual(candidate(13),false); assert.deepEqual(candidate(16),true); } test();
humaneval-HumanEval_118_get_closest_vowel.json-L39
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // You are given a word. Your task is to find the closest vowel that stands between // two consonants from the right side of the word (case sensitive). // Vowels in the beginning and ending doesn't count. Return empty string if you didn't // find any vowel met the above condition. // You may assume that the given string contains English letter only. // Example: // >>> getClosestVowel(("yogurt")) // ("u") // >>> getClosestVowel(("FULL")) // ("U") // >>> getClosestVowel(("quick")) // ("") // >>> getClosestVowel(("ab")) // ("") public static String getClosestVowel(String word) { final String vowels = "aeiou"; final String consonants = "bcdfghjklmnpqrstvwxyz"; List<Integer> idx = new ArrayList<>(); word = word.toLowerCase(); for (int i = 0; i < word.length(); i++) { if (vowels.indexOf(word.charAt(i)) != -1) { idx.add(i); } } for (int i = idx.size() - 1; i >= 0; i--) { int j = idx.get(i); if (j == 0 || j == word.length() - 1) continue; char left = word.charAt(j - 1); char right = word.charAt(j + 1); if (consonants.indexOf(left) != -1 && consonants.indexOf(right) != -1) {
} } return ""; } }
return String.valueOf(word.charAt(j));
} public static void main(String[] args) { assert(getClosestVowel(("yogurt")).equals(("u"))); assert(getClosestVowel(("full")).equals(("u"))); assert(getClosestVowel(("easy")).equals((""))); assert(getClosestVowel(("eAsy")).equals((""))); assert(getClosestVowel(("ali")).equals((""))); assert(getClosestVowel(("bad")).equals(("a"))); assert(getClosestVowel(("most")).equals(("o"))); assert(getClosestVowel(("ab")).equals((""))); assert(getClosestVowel(("ba")).equals((""))); assert(getClosestVowel(("quick")).equals((""))); assert(getClosestVowel(("anime")).equals(("i"))); assert(getClosestVowel(("Asia")).equals((""))); assert(getClosestVowel(("Above")).equals(("o"))); } }
humaneval-HumanEval_13_greatest_common_divisor.json-L11
py
def greatest_common_divisor(a: int, b: int) -> int: """ Return a greatest common divisor of two integers a and b >>> greatest_common_divisor(3, 5) 1 >>> greatest_common_divisor(25, 15) 5 """ if a > b: a, b = b, a if a == 0:
return greatest_common_divisor(b % a, a)
return b
def check(candidate): assert candidate(3, 7) == 1 assert candidate(10, 15) == 5 assert candidate(49, 14) == 7 assert candidate(144, 60) == 12 def test_check(): check(greatest_common_divisor) test_check()
humaneval-HumanEval_13_greatest_common_divisor.json-L10
js
//Return a greatest common divisor of two integers a and b // >>> greatest_common_divisor(3, 5) // 1 // >>> greatest_common_divisor(25, 15) // 5 function greatest_common_divisor(a, b){ let max = Math.max(a, b) let min = Math.min(a, b) if (max % min == 0) {
} else { return greatest_common_divisor(min, max % min) } }
return min
const assert = require('node:assert'); function test() { let candidate = greatest_common_divisor; assert.deepEqual(candidate(3, 7),1); assert.deepEqual(candidate(10, 15),5); assert.deepEqual(candidate(49, 14),7); assert.deepEqual(candidate(144, 60),12); } test();
humaneval-HumanEval_106_f.json-L25
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Implement the function f that takes n as a parameter, // and returns an array array 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((5l)) // (new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)6l, (long)24l, (long)15l))) public static ArrayList<Long> f(long n) { ArrayList<Long> ret = new ArrayList<Long>(); for (long i = 1l; i <= n; i++) { long v = 0l; if (i % 2 == 0) { v = 1l; for (long j = 2l; j <= i; j++) { v *= j;
} else { v = (i * (i + 1l)) / 2l; } ret.add(v); } return ret; } }
}
} public static void main(String[] args) { assert(f((5l)).equals((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)6l, (long)24l, (long)15l))))); assert(f((7l)).equals((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)6l, (long)24l, (long)15l, (long)720l, (long)28l))))); assert(f((1l)).equals((new ArrayList<Long>(Arrays.asList((long)1l))))); assert(f((3l)).equals((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)6l))))); } }
humaneval-HumanEval_137_compare_one.json-L32
py
from typing import Union def compare_one(a: Union[int, float, str], b: Union[int, float, str]) -> Union[int, float, str, None]: """ Create a function that takes integers, floats, or strings representing real numbers, and returns the larger variable in its given variable type. Return None if the values are equal. Note: If a real number is represented as a string, the floating point might be . or , >>> compare_one(1, 2.5) 2.5 >>> compare_one(1, '2,3') '2,3' >>> compare_one('5,1', '6') '6' >>> compare_one('1', 1) None """ if isinstance(a, int) and isinstance(b, int): if a > b: return a elif a < b: return b else: return None elif isinstance(a, float) and isinstance(b, float): if a > b: return a elif a < b: return b else:
elif isinstance(a, str) and isinstance(b, str): a_tmp = a.replace(',', '.') b_tmp = b.replace(',', '.') if float(a_tmp) > float(b_tmp): return a elif float(a_tmp) < float(b_tmp): return b else: return None elif isinstance(a, int) and isinstance(b, float): if a > b: return a elif a < b: return b else: return None elif isinstance(a, float) and isinstance(b, int): if a > b: return a elif a < b: return b else: return None elif isinstance(a, str) and isinstance(b, int): a_tmp = a.replace(',', '.') if float(a_tmp) > b: return a elif float(a_tmp) < b: return b else: return None elif isinstance(a, int) and isinstance(b, str): b_tmp = b.replace(',', '.') if a > float(b_tmp): return a elif a < float(b_tmp): return b else: return None elif isinstance(a, str) and isinstance(b, float): a_tmp = a.replace(',', '.') if float(a_tmp) > b: return a elif float(a_tmp) < b: return b
return None
def check(candidate): assert candidate(1, 2) == 2 assert candidate(1, 2.5) == 2.5 assert candidate(2, 3) == 3 assert candidate(5, 6) == 6 assert candidate(1, '2,3') == '2,3' assert candidate('5,1', '6') == '6' assert candidate('1', '2') == '2' assert candidate('1', 1) == None def test_check(): check(compare_one) test_check()
humaneval-HumanEval_6_parse_nested_parens.json-L13
py
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] """ result = [] for parens in paren_string.split(' '):
current_depth = 0 for paren in parens: if paren == '(': current_depth += 1 max_depth = max(max_depth, current_depth) elif paren == ')': current_depth -= 1 result.append(max_depth) return result
max_depth = 0
def check(candidate): assert candidate('(()()) ((())) () ((())()())') == [2, 3, 1, 3] assert candidate('() (()) ((())) (((())))') == [1, 2, 3, 4] assert candidate('(()(())((())))') == [4] def test_check(): check(parse_nested_parens) test_check()
humaneval-HumanEval_15_string_sequence.json-L16
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Return a string containing space-delimited numbers starting from 0 upto n inclusive. // >>> stringSequence((0l)) // ("0") // >>> stringSequence((5l)) // ("0 1 2 3 4 5") public static String stringSequence(long n) { String result = "";
result += i + " "; } return result.trim(); } }
for (long i = 0; i <= n; i++) {
} public static void main(String[] args) { assert(stringSequence((0l)).equals(("0"))); assert(stringSequence((3l)).equals(("0 1 2 3"))); assert(stringSequence((10l)).equals(("0 1 2 3 4 5 6 7 8 9 10"))); } }
humaneval-HumanEval_36_fizz_buzz.json-L17
js
//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 function fizz_buzz(n){ let result = 0; for(let i = 0; i < n; i++){ if(i % 11 === 0 || i % 13 === 0){ let arr = i.toString().split(''); for(let j = 0; j < arr.length; j++){ if(arr[j] === '7'){ result++; }
} } return result; }
}
const assert = require('node:assert'); function test() { let candidate = fizz_buzz; assert.deepEqual(candidate(50),0); assert.deepEqual(candidate(78),2); assert.deepEqual(candidate(79),3); assert.deepEqual(candidate(100),3); assert.deepEqual(candidate(200),6); assert.deepEqual(candidate(4000),192); assert.deepEqual(candidate(10000),639); assert.deepEqual(candidate(100000),8026); } test();
humaneval-HumanEval_1_separate_paren_groups.json-L20
js
//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 array 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("( ) (( )) (( )( ))") // ["()", "(())", "(()())"] function separate_paren_groups(paren_string){ var count = 0; var group = ''; var groups = []; for (var i = 0; i < paren_string.length; i++){ if (paren_string[i] === '('){ count++; group += paren_string[i]; } else if (paren_string[i] === ')'){ count--; group += paren_string[i]; } if (count === 0 && group){
group = ''; } } return groups; }
groups.push(group);
const assert = require('node:assert'); function test() { let candidate = separate_paren_groups; assert.deepEqual(candidate("(()()) ((())) () ((())()())"),["(()())", "((()))", "()", "((())()())"]); assert.deepEqual(candidate("() (()) ((())) (((())))"),["()", "(())", "((()))", "(((())))"]); assert.deepEqual(candidate("(()(())((())))"),["(()(())((())))"]); assert.deepEqual(candidate("( ) (( )) (( )( ))"),["()", "(())", "(()())"]); } test();
humaneval-HumanEval_33_sort_third.json-L24
js
//This function takes an array l and returns an array l' such that // l' is identical to l in the indicies that are not divisible by three, while its values at the indicies that are divisible by three are equal // to the values of the corresponding indicies of l, but sorted. // >>> sort_third([1, 2, 3]) // [1, 2, 3] // >>> sort_third([5, 6, 3, 4, 8, 9, 2]) // [2, 6, 3, 4, 8, 9, 5] function sort_third(l){ let x=[]; let y=[]; let k=0; for(let i=0;i<l.length;i++){ if(i%3==0){ y[k]=l[i]; k=k+1; } else{ x[i]=l[i]; } } y.sort(); k=0; for(let i=0;i<l.length;i++){
x[i]=y[k]; k=k+1; } } return x; }
if(i%3==0){
const assert = require('node:assert'); function test() { let candidate = sort_third; assert.deepEqual(candidate([5, 6, 3, 4, 8, 9, 2]),[2, 6, 3, 4, 8, 9, 5]); assert.deepEqual(candidate([5, 8, 3, 4, 6, 9, 2]),[2, 8, 3, 4, 6, 9, 5]); assert.deepEqual(candidate([5, 6, 9, 4, 8, 3, 2]),[2, 6, 9, 4, 8, 3, 5]); assert.deepEqual(candidate([5, 6, 3, 4, 8, 9, 2, 1]),[2, 6, 3, 4, 8, 9, 5, 1]); } test();
humaneval-HumanEval_127_intersection.json-L27
py
from typing import Tuple def intersection(interval1: Tuple[int, int], interval2: Tuple[int, int]) -> str: """You are given two intervals, where each interval is a pair of integers. For example, interval = (start, end) = (1, 2). The given intervals are closed which means that the interval (start, end) includes both start and end. For each given interval, it is assumed that its start is less or equal its end. Your task is to determine whether the length of intersection of these two intervals is a prime number. Example, the intersection of the intervals (1, 3), (2, 4) is (2, 3) which its length is 1, which not a prime number. If the length of the intersection is a prime number, return "YES", otherwise, return "NO". If the two intervals don't intersect, return "NO". [input/output] samples: >>> intersection((1, 2), (2, 3)) 'NO' >>> intersection((-1, 1), (0, 4)) 'NO' >>> intersection((-3, -1), (-5, 5)) 'YES' """ start = max(interval1[0], interval2[0])
if start > end: return "NO" return "YES" if end - start == 2 else "NO"
end = min(interval1[1], interval2[1])
def check(candidate): assert candidate((1, 2), (2, 3)) == 'NO' assert candidate((-1, 1), (0, 4)) == 'NO' assert candidate((-3, -1), (-5, 5)) == 'YES' assert candidate((-2, 2), (-4, 0)) == 'YES' assert candidate((-11, 2), (-1, -1)) == 'NO' assert candidate((1, 2), (3, 5)) == 'NO' assert candidate((1, 2), (1, 2)) == 'NO' assert candidate((-2, -2), (-3, -2)) == 'NO' def test_check(): check(intersection) test_check()
humaneval-HumanEval_11_string_xor.json-L25
js
//Input are two strings a and b consisting only of 1s and 0s. // Perform binary XOR on these inputs and return result also as a string. // >>> string_xor("010", "110") // "100" function string_xor(a, b){ var arrayA = []; var arrayB = []; var arrayXOR = []; var result = ''; for (var i = 0; i < a.length; i++) { arrayA.push(parseInt(a[i])); } for (var j = 0; j < b.length; j++) { arrayB.push(parseInt(b[j])); } for (var k = 0; k < arrayA.length; k++) { if (arrayA[k] !== arrayB[k]) { arrayXOR.push(1); } else { arrayXOR.push(0); } } result = arrayXOR.join('');
}
return result;
const assert = require('node:assert'); function test() { let candidate = string_xor; assert.deepEqual(candidate("111000", "101010"),"010010"); assert.deepEqual(candidate("1", "1"),"0"); assert.deepEqual(candidate("0101", "0000"),"0101"); } test();
humaneval-HumanEval_57_monotonic.json-L12
py
from typing import List def monotonic(l: List[int]) -> bool: """Return True is list elements are monotonically increasing or decreasing. >>> monotonic([1, 2, 4, 20]) True >>> monotonic([1, 20, 4, 10]) False >>> monotonic([4, 1, 0, -10]) True """
return True return False
if l == sorted(l) or l == sorted(l, reverse=True):
def check(candidate): assert candidate([1, 2, 4, 10]) == True assert candidate([1, 2, 4, 20]) == True assert candidate([1, 20, 4, 10]) == False assert candidate([4, 1, 0, -10]) == True assert candidate([4, 1, 1, 0]) == True assert candidate([1, 2, 3, 2, 5, 60]) == False assert candidate([1, 2, 3, 4, 5, 60]) == True assert candidate([9, 9, 9, 9]) == True def test_check(): check(monotonic) test_check()
humaneval-HumanEval_73_smallest_change.json-L28
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Given an array array list arr of integers, find the minimum number of elements that // need to be changed to make the array array list palindromic. A palindromic array array list is an array array list that // is read the same backwards and forwards. In one change, you can change one element to any other element. // For example: // >>> smallestChange((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)5l, (long)4l, (long)7l, (long)9l, (long)6l)))) // (4l) // >>> smallestChange((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l, (long)3l, (long)2l, (long)2l)))) // (1l) // >>> smallestChange((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)2l, (long)1l)))) // (0l) public static long smallestChange(ArrayList<Long> arr) { int first = 0; int last = arr.size() - 1; int count = 0; while (first < last) { if (arr.get(first) != arr.get(last)) { count++; } first++;
} return count; } }
last--;
} public static void main(String[] args) { assert(smallestChange((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)5l, (long)4l, (long)7l, (long)9l, (long)6l)))) == (4l)); assert(smallestChange((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l, (long)3l, (long)2l, (long)2l)))) == (1l)); assert(smallestChange((new ArrayList<Long>(Arrays.asList((long)1l, (long)4l, (long)2l)))) == (1l)); assert(smallestChange((new ArrayList<Long>(Arrays.asList((long)1l, (long)4l, (long)4l, (long)2l)))) == (1l)); assert(smallestChange((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)2l, (long)1l)))) == (0l)); assert(smallestChange((new ArrayList<Long>(Arrays.asList((long)3l, (long)1l, (long)1l, (long)3l)))) == (0l)); assert(smallestChange((new ArrayList<Long>(Arrays.asList((long)1l)))) == (0l)); assert(smallestChange((new ArrayList<Long>(Arrays.asList((long)0l, (long)1l)))) == (1l)); } }
humaneval-HumanEval_82_prime_length.json-L16
js
//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 function prime_length(string){ let length = string.length; let primes = [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, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199]; if (primes.includes(length)){
} else { return false; } }
return true;
const assert = require('node:assert'); function test() { let candidate = prime_length; assert.deepEqual(candidate("Hello"),true); assert.deepEqual(candidate("abcdcba"),true); assert.deepEqual(candidate("kittens"),true); assert.deepEqual(candidate("orange"),false); assert.deepEqual(candidate("wow"),true); assert.deepEqual(candidate("world"),true); assert.deepEqual(candidate("MadaM"),true); assert.deepEqual(candidate("Wow"),true); assert.deepEqual(candidate(""),false); assert.deepEqual(candidate("HI"),true); assert.deepEqual(candidate("go"),true); assert.deepEqual(candidate("gogo"),false); assert.deepEqual(candidate("aaaaaaaaaaaaaaa"),false); assert.deepEqual(candidate("Madam"),true); assert.deepEqual(candidate("M"),false); assert.deepEqual(candidate("0"),false); } test();
humaneval-HumanEval_103_rounded_avg.json-L20
py
from typing import Union def rounded_avg(n: int, m: int) -> Union[str, int]: """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 n <= m: rounded_avg = round(((n + m) / 2))
else: return(-1)
return(bin(rounded_avg))
def check(candidate): assert candidate(1, 5) == '0b11' assert candidate(7, 13) == '0b1010' assert candidate(964, 977) == '0b1111001010' assert candidate(996, 997) == '0b1111100100' assert candidate(560, 851) == '0b1011000010' assert candidate(185, 546) == '0b101101110' assert candidate(362, 496) == '0b110101101' assert candidate(350, 902) == '0b1001110010' assert candidate(197, 233) == '0b11010111' assert candidate(7, 5) == -1 assert candidate(5, 1) == -1 assert candidate(5, 5) == '0b101' def test_check(): check(rounded_avg) test_check()
humaneval-HumanEval_112_reverse_delete.json-L18
js
//Task // We are given two strings s and c, you have to deleted all the characters in s that are equal to any character in c // then check if the result string is palindrome. // A string is called palindrome if it reads the same backward as forward. // You should return an array containing the result string and true/false for the check. // Example // >>> reverse_delete("abcde", "ae") // ["bcd", false] // >>> reverse_delete("abcdef", "b") // ["acdef", false] // >>> reverse_delete("abcdedcba", "ab") // ["cdedc", true] function reverse_delete(s, c){ const filter = s.split('').filter(x => c.includes(x) === false); const filterString = filter.join(''); const filterStringReverse = filter.reverse().join(''); const result = [];
result.push(filterString, true); } else { result.push(filterString, false); } return result; }
if (filterString === filterStringReverse) {
const assert = require('node:assert'); function test() { let candidate = reverse_delete; assert.deepEqual(candidate("abcde", "ae"),["bcd", false]); assert.deepEqual(candidate("abcdef", "b"),["acdef", false]); assert.deepEqual(candidate("abcdedcba", "ab"),["cdedc", true]); assert.deepEqual(candidate("dwik", "w"),["dik", false]); assert.deepEqual(candidate("a", "a"),["", true]); assert.deepEqual(candidate("abcdedcba", ""),["abcdedcba", true]); assert.deepEqual(candidate("abcdedcba", "v"),["abcdedcba", true]); assert.deepEqual(candidate("vabba", "v"),["abba", true]); assert.deepEqual(candidate("mamma", "mia"),["", true]); } test();
humaneval-HumanEval_73_smallest_change.json-L14
js
//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 function smallest_change(arr){ let changes = 0; for(let i = 0; i < arr.length/2; i++){
changes++; } } return changes; }
if(arr[i] != arr[arr.length - 1 - i]){
const assert = require('node:assert'); function test() { let candidate = smallest_change; assert.deepEqual(candidate([1, 2, 3, 5, 4, 7, 9, 6]),4); assert.deepEqual(candidate([1, 2, 3, 4, 3, 2, 2]),1); assert.deepEqual(candidate([1, 4, 2]),1); assert.deepEqual(candidate([1, 4, 4, 2]),1); assert.deepEqual(candidate([1, 2, 3, 2, 1]),0); assert.deepEqual(candidate([3, 1, 1, 3]),0); assert.deepEqual(candidate([1]),0); assert.deepEqual(candidate([0, 1]),1); } test();
humaneval-HumanEval_57_monotonic.json-L20
js
//Return true is array elements are monotonically increasing or decreasing. // >>> monotonic([1, 2, 4, 20]) // true // >>> monotonic([1, 20, 4, 10]) // false // >>> monotonic([4, 1, 0, -10]) // true function monotonic(l){ if(l.length <= 1){ return true; } if(l[0] < l[1]){ for(var i = 1; i < l.length - 1; i++){ if(l[i] > l[i + 1]){ return false; } } } else{
if(l[i] < l[i + 1]){ return false; } } } return true; }
for(var i = 1; i < l.length - 1; i++){
const assert = require('node:assert'); function test() { let candidate = monotonic; assert.deepEqual(candidate([1, 2, 4, 10]),true); assert.deepEqual(candidate([1, 2, 4, 20]),true); assert.deepEqual(candidate([1, 20, 4, 10]),false); assert.deepEqual(candidate([4, 1, 0, -10]),true); assert.deepEqual(candidate([4, 1, 1, 0]),true); assert.deepEqual(candidate([1, 2, 3, 2, 5, 60]),false); assert.deepEqual(candidate([1, 2, 3, 4, 5, 60]),true); assert.deepEqual(candidate([9, 9, 9, 9]),true); } test();
humaneval-HumanEval_6_parse_nested_parens.json-L19
py
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] """ result = [] for parens in paren_string.split(' '): max_depth = 0 current_depth = 0 for paren in parens: if paren == '(': current_depth += 1 max_depth = max(max_depth, current_depth)
current_depth -= 1 result.append(max_depth) return result
elif paren == ')':
def check(candidate): assert candidate('(()()) ((())) () ((())()())') == [2, 3, 1, 3] assert candidate('() (()) ((())) (((())))') == [1, 2, 3, 4] assert candidate('(()(())((())))') == [4] def test_check(): check(parse_nested_parens) test_check()
humaneval-HumanEval_156_int_to_mini_roman.json-L18
py
def int_to_mini_roman(number: int) -> str: """ Given a positive integer, obtain its roman numeral equivalent as a string, and return it in lowercase. Restrictions: 1 <= num <= 1000 Examples: >>> int_to_mini_roman(19) 'xix' >>> int_to_mini_roman(152) 'clii' >>> int_to_mini_roman(426) 'cdxxvi' """ roman_numerals = { 1000: 'm', 900: 'cm',
400: 'cd', 100: 'c', 90: 'xc', 50: 'l', 40: 'xl', 10: 'x', 9: 'ix', 5: 'v', 4: 'iv', 1: 'i' } roman_numeral = '' for key in sorted(roman_numerals.keys(), reverse=True): roman_numeral += roman_numerals[key] * (number // key) number = number % key return roman_numeral
500: 'd',
def check(candidate): assert candidate(19) == 'xix' assert candidate(152) == 'clii' assert candidate(251) == 'ccli' assert candidate(426) == 'cdxxvi' assert candidate(500) == 'd' assert candidate(1) == 'i' assert candidate(4) == 'iv' assert candidate(43) == 'xliii' assert candidate(90) == 'xc' assert candidate(94) == 'xciv' assert candidate(532) == 'dxxxii' assert candidate(900) == 'cm' assert candidate(994) == 'cmxciv' assert candidate(1000) == 'm' def test_check(): check(int_to_mini_roman) test_check()
humaneval-HumanEval_81_numerical_letter_grade.json-L40
js
//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 an array of GPAs for some students and you have to write // a function that can output an array 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-"] function numerical_letter_grade(grades){ var grades_array = []; for (var i = 0; i < grades.length; i++){ if (grades[i] >= 4.0){ grades_array.push("A+"); } else if (grades[i] > 3.7){ grades_array.push("A"); } else if (grades[i] > 3.3){ grades_array.push("A-"); } else if (grades[i] > 3.0){ grades_array.push("B+"); } else if (grades[i] > 2.7){ grades_array.push("B");
else if (grades[i] > 2.3){ grades_array.push("B-"); } else if (grades[i] > 2.0){ grades_array.push("C+"); } else if (grades[i] > 1.7){ grades_array.push("C"); } else if (grades[i] > 1.3){ grades_array.push("C-"); } else if (grades[i] > 1.0){ grades_array.push("D+"); } else if (grades[i] > 0.7){ grades_array.push("D"); } else if (grades[i] > 0.0){ grades_array.push("D-"); } else if (grades[i] == 0.0){ grades_array.push("E"); } } return grades_array; }
}
const assert = require('node:assert'); function test() { let candidate = numerical_letter_grade; assert.deepEqual(candidate([4.0, 3, 1.7, 2, 3.5]),["A+", "B", "C-", "C", "A-"]); assert.deepEqual(candidate([1.2]),["D+"]); assert.deepEqual(candidate([0.5]),["D-"]); assert.deepEqual(candidate([0.0]),["E"]); assert.deepEqual(candidate([1.0, 0.3, 1.5, 2.8, 3.3]),["D", "D-", "C-", "B", "B+"]); assert.deepEqual(candidate([0.0, 0.7]),["E", "D-"]); } test();
humaneval-HumanEval_18_how_many_times.json-L12
js
//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 function how_many_times(string, substring){ var i = 0; var count = 0; while(string.indexOf(substring, i) !== -1){
i = string.indexOf(substring, i) + 1; } return count; }
count++;
const assert = require('node:assert'); function test() { let candidate = how_many_times; assert.deepEqual(candidate("", "x"),0); assert.deepEqual(candidate("xyxyxyx", "x"),4); assert.deepEqual(candidate("cacacacac", "cac"),4); assert.deepEqual(candidate("john doe", "john"),1); } test();
humaneval-HumanEval_141_file_name_check.json-L32
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // 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: // >>> fileNameCheck(("example.txt")) // ("Yes") // >>> fileNameCheck(("1example.dll")) // ("No") public static String fileNameCheck(String file_name) { String result = "No"; String[] tokens = file_name.split("\\."); if (tokens.length != 2) { return result; } String extension = tokens[1]; if (!(extension.equals("txt") || extension.equals("exe") || extension.equals("dll"))) { return result;
String name = tokens[0]; int count = 0; for (int i = 0; i < name.length(); i++) { if (Character.isDigit(name.charAt(i))) { count++; } } if (count > 3) { return result; } if (name.length() == 0) { return result; } if (!Character.isLetter(name.charAt(0))) { return result; } return "Yes"; } }
}
} public static void main(String[] args) { assert(fileNameCheck(("example.txt")).equals(("Yes"))); assert(fileNameCheck(("1example.dll")).equals(("No"))); assert(fileNameCheck(("s1sdf3.asd")).equals(("No"))); assert(fileNameCheck(("K.dll")).equals(("Yes"))); assert(fileNameCheck(("MY16FILE3.exe")).equals(("Yes"))); assert(fileNameCheck(("His12FILE94.exe")).equals(("No"))); assert(fileNameCheck(("_Y.txt")).equals(("No"))); assert(fileNameCheck(("?aREYA.exe")).equals(("No"))); assert(fileNameCheck(("/this_is_valid.dll")).equals(("No"))); assert(fileNameCheck(("this_is_valid.wow")).equals(("No"))); assert(fileNameCheck(("this_is_valid.txt")).equals(("Yes"))); assert(fileNameCheck(("this_is_valid.txtexe")).equals(("No"))); assert(fileNameCheck(("#this2_i4s_5valid.ten")).equals(("No"))); assert(fileNameCheck(("@this1_is6_valid.exe")).equals(("No"))); assert(fileNameCheck(("this_is_12valid.6exe4.txt")).equals(("No"))); assert(fileNameCheck(("all.exe.txt")).equals(("No"))); assert(fileNameCheck(("I563_No.exe")).equals(("Yes"))); assert(fileNameCheck(("Is3youfault.txt")).equals(("Yes"))); assert(fileNameCheck(("no_one#knows.dll")).equals(("Yes"))); assert(fileNameCheck(("1I563_Yes3.exe")).equals(("No"))); assert(fileNameCheck(("I563_Yes3.txtt")).equals(("No"))); assert(fileNameCheck(("final..txt")).equals(("No"))); assert(fileNameCheck(("final132")).equals(("No"))); assert(fileNameCheck(("_f4indsartal132.")).equals(("No"))); assert(fileNameCheck((".txt")).equals(("No"))); assert(fileNameCheck(("s.")).equals(("No"))); } }
humaneval-HumanEval_65_circular_shift.json-L10
py
def circular_shift(x: int, shift: int) -> str: """Circular shift the digits of the integer x, shift the digits right by shift and return the result as a string. If shift > number of digits, return digits reversed. >>> circular_shift(12, 1) '21' >>> circular_shift(12, 2) '12' """
if shift > len(temp): return ''.join(reversed(temp)) else: return ''.join(temp[-shift:] + temp[:-shift])
temp = list(str(x))
def check(candidate): assert candidate(100, 2) == '001' assert candidate(12, 2) == '12' assert candidate(97, 8) == '79' assert candidate(12, 1) == '21' assert candidate(11, 101) == '11' def test_check(): check(circular_shift) test_check()
humaneval-HumanEval_134_check_if_last_char_is_a_letter.json-L19
js
//Create a function that returns true if the last character // of a given string is an alphabetical character and is not // a part of a word, and false otherwise. // Note: "word" is a group of characters separated by space. // Examples: // >>> check_if_last_char_is_a_letter("apple pie") // false // >>> check_if_last_char_is_a_letter("apple pi e") // true // >>> check_if_last_char_is_a_letter("apple pi e ") // false // >>> check_if_last_char_is_a_letter("") // false function check_if_last_char_is_a_letter(txt){ var result=txt.split(" "); if(result[result.length-1].length==1 && result[result.length-1].match(/[a-z]/i)){ return true; }
}
return false;
const assert = require('node:assert'); function test() { let candidate = check_if_last_char_is_a_letter; assert.deepEqual(candidate("apple"),false); assert.deepEqual(candidate("apple pi e"),true); assert.deepEqual(candidate("eeeee"),false); assert.deepEqual(candidate("A"),true); assert.deepEqual(candidate("Pumpkin pie "),false); assert.deepEqual(candidate("Pumpkin pie 1"),false); assert.deepEqual(candidate(""),false); assert.deepEqual(candidate("eeeee e "),false); assert.deepEqual(candidate("apple pie"),false); assert.deepEqual(candidate("apple pi e "),false); } test();
humaneval-HumanEval_101_words_string.json-L15
py
from typing import List def words_string(s: str) -> List[str]: """ 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'] """ s = s.replace(',', ' ')
return s.split()
def check(candidate): assert candidate('Hi, my name is John') == ['Hi', 'my', 'name', 'is', 'John'] assert candidate('One, two, three, four, five, six') == ['One', 'two', 'three', 'four', 'five', 'six'] assert candidate('Hi, my name') == ['Hi', 'my', 'name'] assert candidate('One,, two, three, four, five, six,') == ['One', 'two', 'three', 'four', 'five', 'six'] assert candidate('') == [] assert candidate('ahmed , gamal') == ['ahmed', 'gamal'] def test_check(): check(words_string) test_check()
humaneval-HumanEval_94_skjkasdkd.json-L30
js
//You are given an array of integers. // You need to find the largest prime value and return the sum of its digits. // Examples: // >>> skjkasdkd([0, 3, 2, 1, 3, 5, 7, 4, 5, 5, 5, 2, 181, 32, 4, 32, 3, 2, 32, 324, 4, 3]) // 10 // >>> skjkasdkd([1, 0, 1, 8, 2, 4597, 2, 1, 3, 40, 1, 2, 1, 2, 4, 2, 5, 1]) // 25 // >>> skjkasdkd([1, 3, 1, 32, 5107, 34, 83278, 109, 163, 23, 2323, 32, 30, 1, 9, 3]) // 13 // >>> skjkasdkd([0, 724, 32, 71, 99, 32, 6, 0, 5, 91, 83, 0, 5, 6]) // 11 // >>> skjkasdkd([0, 81, 12, 3, 1, 21]) // 3 // >>> skjkasdkd([0, 8, 1, 2, 1, 7]) // 7 function skjkasdkd(lst){ function prime(n){ if (n<2) return false; for (let i=2; i<=Math.sqrt(n); i++){ if (n%i==0) return false; } return true; } let max = Math.max(...lst.filter(x=>prime(x))); let digits = String(max).split(''); let sum = 0; for (let i=0; i<digits.length; i++){ sum += Number(digits[i]); }
}
return sum;
const assert = require('node:assert'); function test() { let candidate = skjkasdkd; assert.deepEqual(candidate([0, 3, 2, 1, 3, 5, 7, 4, 5, 5, 5, 2, 181, 32, 4, 32, 3, 2, 32, 324, 4, 3]),10); assert.deepEqual(candidate([1, 0, 1, 8, 2, 4597, 2, 1, 3, 40, 1, 2, 1, 2, 4, 2, 5, 1]),25); assert.deepEqual(candidate([1, 3, 1, 32, 5107, 34, 83278, 109, 163, 23, 2323, 32, 30, 1, 9, 3]),13); assert.deepEqual(candidate([0, 724, 32, 71, 99, 32, 6, 0, 5, 91, 83, 0, 5, 6]),11); assert.deepEqual(candidate([0, 81, 12, 3, 1, 21]),3); assert.deepEqual(candidate([0, 8, 1, 2, 1, 7]),7); assert.deepEqual(candidate([8191]),19); assert.deepEqual(candidate([8191, 123456, 127, 7]),19); assert.deepEqual(candidate([127, 97, 8192]),10); } test();
humaneval-HumanEval_39_prime_fib.json-L40
js
//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 function prime_fib(n){ function isPrime(number){ if(number <= 3){ return number > 1; } else if(number % 2 == 0 || number % 3 == 0){ return false; } else{ for(var i = 5; i * i <= number; i += 6){ if(number % i == 0 || number % (i + 2) == 0){ return false; } } return true; } } function fib(num){ var a = 1, b = 0, temp; while (num >= 0){ temp = a; a = a + b; b = temp; num--; } return b;
var res = 0; var fibNum = 0; while(res < n){ if(isPrime(fib(fibNum))){ res++; } fibNum++; } return fib(fibNum - 1); }
}
const assert = require('node:assert'); function test() { let candidate = prime_fib; assert.deepEqual(candidate(1),2); assert.deepEqual(candidate(2),3); assert.deepEqual(candidate(3),5); assert.deepEqual(candidate(4),13); assert.deepEqual(candidate(5),89); assert.deepEqual(candidate(6),233); assert.deepEqual(candidate(7),1597); assert.deepEqual(candidate(8),28657); assert.deepEqual(candidate(9),514229); assert.deepEqual(candidate(10),433494437); } test();
humaneval-HumanEval_46_fib4.json-L20
py
def fib4(n: int) -> int: """The Fib4 number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows: fib4(0) -> 0 fib4(1) -> 0 fib4(2) -> 2 fib4(3) -> 0 fib4(n) -> fib4(n-1) + fib4(n-2) + fib4(n-3) + fib4(n-4). Please write a function to efficiently compute the n-th element of the fib4 number sequence. Do not use recursion. >>> fib4(5) 4 >>> fib4(6) 8 >>> fib4(7) 14 """ if n == 0: return 0 elif n == 1: return 0
return 2 elif n == 3: return 0 else: return fib4(n-1) + fib4(n-2) + fib4(n-3) + fib4(n-4)
elif n == 2:
def check(candidate): assert candidate(5) == 4 assert candidate(8) == 28 assert candidate(10) == 104 assert candidate(12) == 386 def test_check(): check(fib4) test_check()
humaneval-HumanEval_156_int_to_mini_roman.json-L19
js
//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" function int_to_mini_roman(number){ var roman_conversion = { 1000: "m", 900: "cm", 500: "d", 400: "cd", 100: "c", 90: "xc",
40: "xl", 10: "x", 9: "ix", 5: "v", 4: "iv", 1: "i" }; var output = ""; while (number > 0){ var key_list = Object.keys(roman_conversion).map(Number); key_list.sort(function(a, b){return b-a}); for (var i = 0; i < key_list.length; i++){ if (key_list[i] <= number){ output += roman_conversion[key_list[i]]; number -= key_list[i]; break; } } } return output; }
50: "l",
const assert = require('node:assert'); function test() { let candidate = int_to_mini_roman; assert.deepEqual(candidate(19),"xix"); assert.deepEqual(candidate(152),"clii"); assert.deepEqual(candidate(251),"ccli"); assert.deepEqual(candidate(426),"cdxxvi"); assert.deepEqual(candidate(500),"d"); assert.deepEqual(candidate(1),"i"); assert.deepEqual(candidate(4),"iv"); assert.deepEqual(candidate(43),"xliii"); assert.deepEqual(candidate(90),"xc"); assert.deepEqual(candidate(94),"xciv"); assert.deepEqual(candidate(532),"dxxxii"); assert.deepEqual(candidate(900),"cm"); assert.deepEqual(candidate(994),"cmxciv"); assert.deepEqual(candidate(1000),"m"); } test();
humaneval-HumanEval_59_largest_prime_factor.json-L12
py
def largest_prime_factor(n: int) -> int: """Return the largest prime factor of n. Assume n > 1 and is not a prime. >>> largest_prime_factor(13195) 29 >>> largest_prime_factor(2048) 2 """ largest = 1 factor = 2 while factor < n: if n % factor == 0:
while n % factor == 0: n = n // factor factor += 1 return max(largest, n)
largest = factor
def check(candidate): assert candidate(15) == 5 assert candidate(27) == 3 assert candidate(63) == 7 assert candidate(330) == 11 assert candidate(13195) == 29 def test_check(): check(largest_prime_factor) test_check()
humaneval-HumanEval_55_fib.json-L11
py
def fib(n: int) -> int: """Return n-th Fibonacci number. >>> fib(10) 55 >>> fib(1) 1 >>> fib(8) 21 """ assert n >= 1
for i in range(n - 1): f0, f1 = f1, f0 + f1 return f1
f0, f1 = 0, 1
def check(candidate): assert candidate(10) == 55 assert candidate(1) == 1 assert candidate(8) == 21 assert candidate(11) == 89 assert candidate(12) == 144 def test_check(): check(fib) test_check()
humaneval-HumanEval_39_prime_fib.json-L13
js
//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 function prime_fib(n){
if(number <= 3){ return number > 1; } else if(number % 2 == 0 || number % 3 == 0){ return false; } else{ for(var i = 5; i * i <= number; i += 6){ if(number % i == 0 || number % (i + 2) == 0){ return false; } } return true; } } function fib(num){ var a = 1, b = 0, temp; while (num >= 0){ temp = a; a = a + b; b = temp; num--; } return b; } var res = 0; var fibNum = 0; while(res < n){ if(isPrime(fib(fibNum))){ res++; } fibNum++; } return fib(fibNum - 1); }
function isPrime(number){
const assert = require('node:assert'); function test() { let candidate = prime_fib; assert.deepEqual(candidate(1),2); assert.deepEqual(candidate(2),3); assert.deepEqual(candidate(3),5); assert.deepEqual(candidate(4),13); assert.deepEqual(candidate(5),89); assert.deepEqual(candidate(6),233); assert.deepEqual(candidate(7),1597); assert.deepEqual(candidate(8),28657); assert.deepEqual(candidate(9),514229); assert.deepEqual(candidate(10),433494437); } test();
humaneval-HumanEval_95_check_dict_case.json-L32
js
//Given an object, return true if all keys are strings in lower // case or all keys are strings in upper case, else return false. // The function should return false is the given object is empty. // Examples: // >>> check_dict_case({"a": "apple", "b": "banana"}) // true // >>> check_dict_case({"a": "apple", "A": "banana", "B": "banana"}) // false // >>> check_dict_case({"a": "apple", 8: "banana", "a": "apple"}) // false // >>> check_dict_case({"Name": "John", "Age": "36", "City": "Houston"}) // false // >>> check_dict_case({"STATE": "NC", "ZIP": "12345"}) // true function check_dict_case(dict){ if (Object.keys(dict).length == 0){ return false; } var case_type = -1; for (let key in dict){ if (typeof key == "string"){ if (case_type == -1){ if (key == key.toUpperCase()){ case_type = 1; } else if (key == key.toLowerCase()){ case_type = 0; } else{ return false; }
else if (case_type == 1){ if (key != key.toUpperCase()){ return false; } } else if (case_type == 0){ if (key != key.toLowerCase()){ return false; } } } else{ return false; } } return true; }
}
const assert = require('node:assert'); function test() { let candidate = check_dict_case; assert.deepEqual(candidate({"p": "pineapple", "b": "banana"}),true); assert.deepEqual(candidate({"p": "pineapple", "A": "banana", "B": "banana"}),false); assert.deepEqual(candidate({"p": "pineapple", "5": "banana", "a": "apple"}),false); assert.deepEqual(candidate({"Name": "John", "Age": "36", "City": "Houston"}),false); assert.deepEqual(candidate({"STATE": "NC", "ZIP": "12345"}),true); assert.deepEqual(candidate({"fruit": "Orange", "taste": "Sweet"}),true); assert.deepEqual(candidate({}),false); } test();
humaneval-HumanEval_71_triangle_area.json-L23
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Given the lengths of the three sides of a triangle. Return the area of // the triangle rounded to 2 decimal points if the three sides form a valid triangle. // Otherwise return -1 // Three sides make a valid triangle when the sum of any two sides is greater // than the third side. // Example: // >>> triangleArea((3l), (4l), (5l)) // (6.0f) // >>> triangleArea((1l), (2l), (10l)) // (float)-1l public static float triangleArea(long a, long b, long c) { if(a + b > c && a + c > b && b + c > a) { float s = (a + b + c) / 2.0f; float area = (float)Math.sqrt(s * (s - a) * (s - b) * (s - c));
} return -1; } }
return (float)Math.round(area * 100) / 100;
} public static void main(String[] args) { assert(triangleArea((3l), (4l), (5l)) == (6.0f)); assert(triangleArea((1l), (2l), (10l)) == (float)-1l); assert(triangleArea((4l), (8l), (5l)) == (8.18f)); assert(triangleArea((2l), (2l), (2l)) == (1.73f)); assert(triangleArea((1l), (2l), (3l)) == (float)-1l); assert(triangleArea((10l), (5l), (7l)) == (16.25f)); assert(triangleArea((2l), (6l), (3l)) == (float)-1l); assert(triangleArea((1l), (1l), (1l)) == (0.43f)); assert(triangleArea((2l), (2l), (10l)) == (float)-1l); } }
humaneval-HumanEval_61_correct_bracketing.json-L22
py
def correct_bracketing(brackets: str) -> bool: """ brackets is a string of "(" and ")". return True if every opening bracket has a corresponding closing bracket. >>> correct_bracketing('(') False >>> correct_bracketing('()') True >>> correct_bracketing('(()())') True >>> correct_bracketing(')(()') False """ count = 0 for char in brackets: if char == '(': count += 1 elif char == ')': count -= 1 if count < 0: return False
return count == 0
def check(candidate): assert candidate('()') == True assert candidate('(()())') == True assert candidate('()()(()())()') == True assert candidate('()()((()()())())(()()(()))') == True assert candidate('((()())))') == False assert candidate(')(()') == False assert candidate('(') == False assert candidate('((((') == False assert candidate(')') == False assert candidate('(()') == False assert candidate('()()(()())())(()') == False assert candidate('()()(()())()))()') == False def test_check(): check(correct_bracketing) test_check()
humaneval-HumanEval_91_is_bored.json-L10
js
//You'll be given a string of words, and your task is to count the number // of boredoms. A boredom is a sentence that starts with the word "I". // Sentences are delimited by '.', '?' or '!'. // For example: // >>> is_bored("Hello world") // 0 // >>> is_bored("The sky is blue. The sun is shining. I love this weather") // 1 function is_bored(S){
let boredoms = 0; for (let line of lines){ if(line.match(/^\s*I /)){ boredoms++; } } return boredoms; }
let lines = S.split(/[.?!]/);
const assert = require('node:assert'); function test() { let candidate = is_bored; assert.deepEqual(candidate("Hello world"),0); assert.deepEqual(candidate("Is the sky blue?"),0); assert.deepEqual(candidate("I love It !"),1); assert.deepEqual(candidate("bIt"),0); assert.deepEqual(candidate("I feel good today. I will be productive. will kill It"),2); assert.deepEqual(candidate("You and I are going for a walk"),0); } test();
humaneval-HumanEval_23_strlen.json-L7
js
//Return length of given string // >>> strlen("") // 0 // >>> strlen("abc") // 3 function strlen(string){
}
return string.length;
const assert = require('node:assert'); function test() { let candidate = strlen; assert.deepEqual(candidate(""),0); assert.deepEqual(candidate("x"),1); assert.deepEqual(candidate("asdasnakj"),9); } test();
humaneval-HumanEval_76_is_simple_power.json-L20
py
def is_simple_power(x: int, n: int) -> bool: """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 x == 0:
else: while x > 1: if x % n != 0: return False x /= n return True
return False
def check(candidate): assert candidate(16, 2) == True assert candidate(143214, 16) == False assert candidate(4, 2) == True assert candidate(9, 3) == True assert candidate(16, 4) == True assert candidate(24, 2) == False assert candidate(128, 4) == False assert candidate(12, 6) == False assert candidate(1, 1) == True assert candidate(1, 12) == True def test_check(): check(is_simple_power) test_check()
humaneval-HumanEval_139_special_factorial.json-L26
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // The Brazilian factorial is defined as: // brazilian_factorial(n) = n! * (n-1)! * (n-2)! * ... * 1! // where n > 0 // For example: // >>> specialFactorial((4l)) // (288l) // The function will receive an integer as input and should return the special // factorial of this integer. public static long specialFactorial(long n) { long result = 1; while (n > 0) { long local_result = 1; long temp = n; while (temp > 0) { local_result *= temp; temp--; }
n--; } return result; } }
result *= local_result;
} public static void main(String[] args) { assert(specialFactorial((4l)) == (288l)); assert(specialFactorial((5l)) == (34560l)); assert(specialFactorial((7l)) == (125411328000l)); assert(specialFactorial((1l)) == (1l)); } }
humaneval-HumanEval_68_pluck.json-L47
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // "Given an array array list 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 an array array list, [ smalest_value, its index ], // If there are no even values or the given array array list is empty, return []. // Example 1: // >>> pluck((new ArrayList<Long>(Arrays.asList((long)4l, (long)2l, (long)3l)))) // (new ArrayList<Long>(Arrays.asList((long)2l, (long)1l))) // Explanation: 2 has the smallest even value, and 2 has the smallest index. // Example 2: // >>> pluck((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l)))) // (new ArrayList<Long>(Arrays.asList((long)2l, (long)1l))) // Explanation: 2 has the smallest even value, and 2 has the smallest index. // Example 3: // >>> pluck((new ArrayList<Long>(Arrays.asList()))) // (new ArrayList<Long>(Arrays.asList())) // Example 4: // >>> pluck((new ArrayList<Long>(Arrays.asList((long)5l, (long)0l, (long)3l, (long)0l, (long)4l, (long)2l)))) // (new ArrayList<Long>(Arrays.asList((long)0l, (long)1l))) // 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 public static ArrayList<Long> pluck(ArrayList<Long> arr) { int minIndex = -1; long minValue = -1; for (int i = 0; i < arr.size(); i++) { if (arr.get(i) % 2 == 0) { if (minIndex == -1 || arr.get(i) < minValue) { minIndex = i; minValue = arr.get(i); } } } ArrayList<Long> newArr = new ArrayList<Long>(); if (minIndex == -1) {
} newArr.add(minValue); newArr.add((long)minIndex); return newArr; } }
return newArr;
} public static void main(String[] args) { assert(pluck((new ArrayList<Long>(Arrays.asList((long)4l, (long)2l, (long)3l)))).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)1l))))); assert(pluck((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l)))).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)1l))))); assert(pluck((new ArrayList<Long>(Arrays.asList()))).equals((new ArrayList<Long>(Arrays.asList())))); assert(pluck((new ArrayList<Long>(Arrays.asList((long)5l, (long)0l, (long)3l, (long)0l, (long)4l, (long)2l)))).equals((new ArrayList<Long>(Arrays.asList((long)0l, (long)1l))))); assert(pluck((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)0l, (long)5l, (long)3l)))).equals((new ArrayList<Long>(Arrays.asList((long)0l, (long)3l))))); assert(pluck((new ArrayList<Long>(Arrays.asList((long)5l, (long)4l, (long)8l, (long)4l, (long)8l)))).equals((new ArrayList<Long>(Arrays.asList((long)4l, (long)1l))))); assert(pluck((new ArrayList<Long>(Arrays.asList((long)7l, (long)6l, (long)7l, (long)1l)))).equals((new ArrayList<Long>(Arrays.asList((long)6l, (long)1l))))); assert(pluck((new ArrayList<Long>(Arrays.asList((long)7l, (long)9l, (long)7l, (long)1l)))).equals((new ArrayList<Long>(Arrays.asList())))); } }
humaneval-HumanEval_158_find_max.json-L25
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Write a function that accepts an array array list of strings. // The array list contains different words. Return the word with maximum number // of unique characters. If multiple strings have maximum number of unique // characters, return the one which comes first in lexicographical order. // >>> findMax((new ArrayList<String>(Arrays.asList((String)"name", (String)"of", (String)"string")))) // ("string") // >>> findMax((new ArrayList<String>(Arrays.asList((String)"name", (String)"enam", (String)"game")))) // ("enam") // >>> findMax((new ArrayList<String>(Arrays.asList((String)"aaaaaaa", (String)"bb", (String)"cc")))) // ("aaaaaaa") public static String findMax(ArrayList<String> words) { Map<String, Integer> wordsToUniqueCharacters = new HashMap<String, Integer>(); for (String word : words) { Set<Character> uniqueCharacters = new HashSet<Character>(); for (char c : word.toCharArray()) { uniqueCharacters.add(c);
wordsToUniqueCharacters.put(word, uniqueCharacters.size()); } words.sort(new Comparator<String>() { @Override public int compare(String o1, String o2) { int compareResult = wordsToUniqueCharacters.get(o2).compareTo(wordsToUniqueCharacters.get(o1)); if (compareResult == 0) { return o1.compareTo(o2); } return compareResult; } }); return words.get(0); } }
}
} public static void main(String[] args) { assert(findMax((new ArrayList<String>(Arrays.asList((String)"name", (String)"of", (String)"string")))).equals(("string"))); assert(findMax((new ArrayList<String>(Arrays.asList((String)"name", (String)"enam", (String)"game")))).equals(("enam"))); assert(findMax((new ArrayList<String>(Arrays.asList((String)"aaaaaaa", (String)"bb", (String)"cc")))).equals(("aaaaaaa"))); assert(findMax((new ArrayList<String>(Arrays.asList((String)"abc", (String)"cba")))).equals(("abc"))); assert(findMax((new ArrayList<String>(Arrays.asList((String)"play", (String)"this", (String)"game", (String)"of", (String)"footbott")))).equals(("footbott"))); assert(findMax((new ArrayList<String>(Arrays.asList((String)"we", (String)"are", (String)"gonna", (String)"rock")))).equals(("gonna"))); assert(findMax((new ArrayList<String>(Arrays.asList((String)"we", (String)"are", (String)"a", (String)"mad", (String)"nation")))).equals(("nation"))); assert(findMax((new ArrayList<String>(Arrays.asList((String)"this", (String)"is", (String)"a", (String)"prrk")))).equals(("this"))); assert(findMax((new ArrayList<String>(Arrays.asList((String)"b")))).equals(("b"))); assert(findMax((new ArrayList<String>(Arrays.asList((String)"play", (String)"play", (String)"play")))).equals(("play"))); } }
humaneval-HumanEval_73_smallest_change.json-L30
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Given an array array list arr of integers, find the minimum number of elements that // need to be changed to make the array array list palindromic. A palindromic array array list is an array array list that // is read the same backwards and forwards. In one change, you can change one element to any other element. // For example: // >>> smallestChange((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)5l, (long)4l, (long)7l, (long)9l, (long)6l)))) // (4l) // >>> smallestChange((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l, (long)3l, (long)2l, (long)2l)))) // (1l) // >>> smallestChange((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)2l, (long)1l)))) // (0l) public static long smallestChange(ArrayList<Long> arr) { int first = 0; int last = arr.size() - 1; int count = 0; while (first < last) { if (arr.get(first) != arr.get(last)) { count++; } first++; last--; }
} }
return count;
} public static void main(String[] args) { assert(smallestChange((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)5l, (long)4l, (long)7l, (long)9l, (long)6l)))) == (4l)); assert(smallestChange((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l, (long)3l, (long)2l, (long)2l)))) == (1l)); assert(smallestChange((new ArrayList<Long>(Arrays.asList((long)1l, (long)4l, (long)2l)))) == (1l)); assert(smallestChange((new ArrayList<Long>(Arrays.asList((long)1l, (long)4l, (long)4l, (long)2l)))) == (1l)); assert(smallestChange((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)2l, (long)1l)))) == (0l)); assert(smallestChange((new ArrayList<Long>(Arrays.asList((long)3l, (long)1l, (long)1l, (long)3l)))) == (0l)); assert(smallestChange((new ArrayList<Long>(Arrays.asList((long)1l)))) == (0l)); assert(smallestChange((new ArrayList<Long>(Arrays.asList((long)0l, (long)1l)))) == (1l)); } }
humaneval-HumanEval_72_will_it_fly.json-L37
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // 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 array list) and the sum of its elements is less than or equal the maximum possible weight w. // Example: // >>> willItFly((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l))), (5l)) // (false) // # 1+2 is less than the maximum possible weight, but it's unbalanced. // >>> willItFly((new ArrayList<Long>(Arrays.asList((long)3l, (long)2l, (long)3l))), (1l)) // (false) // # it's balanced, but 3+2+3 is more than the maximum possible weight. // >>> willItFly((new ArrayList<Long>(Arrays.asList((long)3l, (long)2l, (long)3l))), (9l)) // (true) // # 3+2+3 is less than the maximum possible weight, and it's balanced. // >>> willItFly((new ArrayList<Long>(Arrays.asList((long)3l))), (5l)) // (true) // # 3 is less than the maximum possible weight, and it's balanced. public static boolean willItFly(ArrayList<Long> q, long w) { if (q.size() == 0) { return false; } if (q.size() == 1) { return true; } Long sum = 0l; for (int i = 0; i < q.size(); i++) { sum += q.get(i); } if (sum > w) { return false;
for (int i = 0; i < q.size() / 2; i++) { if (q.get(i) != q.get(q.size() - 1 - i)) { return false; } } return true; } }
}
} public static void main(String[] args) { assert(willItFly((new ArrayList<Long>(Arrays.asList((long)3l, (long)2l, (long)3l))), (9l)) == (true)); assert(willItFly((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l))), (5l)) == (false)); assert(willItFly((new ArrayList<Long>(Arrays.asList((long)3l))), (5l)) == (true)); assert(willItFly((new ArrayList<Long>(Arrays.asList((long)3l, (long)2l, (long)3l))), (1l)) == (false)); assert(willItFly((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l))), (6l)) == (false)); assert(willItFly((new ArrayList<Long>(Arrays.asList((long)5l))), (5l)) == (true)); } }