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_162_string_to_md5.json-L14
py
from typing import Optional def string_to_md5(text: str) -> Optional[str]: """ Given a string 'text', return its md5 hash equivalent string. If 'text' is an empty string, return None. >>> string_to_md5('Hello world') '3e25960a79dbc69b674cd4ec67a72c62' """ import hashlib if not text: return None
return hashlib.md5(text.encode('utf-8')).hexdigest()
else:
def check(candidate): assert candidate('Hello world') == '3e25960a79dbc69b674cd4ec67a72c62' assert candidate('') == None assert candidate('A B C') == '0ef78513b0cb8cef12743f5aeb35f888' assert candidate('password') == '5f4dcc3b5aa765d61d8327deb882cf99' def test_check(): check(string_to_md5) test_check()
humaneval-HumanEval_136_largest_smallest_integers.json-L14
js
//Create a function that returns an array (a, b), where 'a' is // the largest of negative integers, and 'b' is the smallest // of positive integers in an array. // If there is no negative or positive integers, return them as undefined. // Examples: // >>> largest_smallest_integers([2, 4, 1, 3, 5, 7]) // [undefined, 1] // >>> largest_smallest_integers([]) // [undefined, undefined] // >>> largest_smallest_integers([0]) // [undefined, undefined] function largest_smallest_integers(lst){ return[lst.filter(x=>x<0).sort((a,b)=>b-a)[0],lst.filter(x=>x>0).sort((a,b)=>a-b)[0]]
}
const assert = require('node:assert'); function test() { let candidate = largest_smallest_integers; assert.deepEqual(candidate([2, 4, 1, 3, 5, 7]),[undefined, 1]); assert.deepEqual(candidate([2, 4, 1, 3, 5, 7, 0]),[undefined, 1]); assert.deepEqual(candidate([1, 3, 2, 4, 5, 6, -2]),[-2, 1]); assert.deepEqual(candidate([4, 5, 3, 6, 2, 7, -7]),[-7, 2]); assert.deepEqual(candidate([7, 3, 8, 4, 9, 2, 5, -9]),[-9, 2]); assert.deepEqual(candidate([]),[undefined, undefined]); assert.deepEqual(candidate([0]),[undefined, undefined]); assert.deepEqual(candidate([-1, -3, -5, -6]),[-1, undefined]); assert.deepEqual(candidate([-1, -3, -5, -6, 0]),[-1, undefined]); assert.deepEqual(candidate([-6, -4, -4, -3, 1]),[-3, 1]); assert.deepEqual(candidate([-6, -4, -4, -3, -100, 1]),[-3, 1]); } test();
humaneval-HumanEval_155_even_odd_count.json-L14
js
//Given an integer. return an array that has the number of even and odd digits respectively. // Example: // >>> even_odd_count(-12) // [1, 1] // >>> even_odd_count(123) // [1, 2] function even_odd_count(num){ num = Math.abs(num); var evens = 0; var odds = 0; for(var i = 0; i < num.toString().length; i++){ if(num.toString()[i] % 2 == 0){ evens ++;
else{ odds ++; } } return [evens, odds]; }
}
const assert = require('node:assert'); function test() { let candidate = even_odd_count; assert.deepEqual(candidate(7),[0, 1]); assert.deepEqual(candidate(-78),[1, 1]); assert.deepEqual(candidate(3452),[2, 2]); assert.deepEqual(candidate(346211),[3, 3]); assert.deepEqual(candidate(-345821),[3, 3]); assert.deepEqual(candidate(-2),[1, 0]); assert.deepEqual(candidate(-45347),[2, 3]); assert.deepEqual(candidate(0),[1, 0]); } test();
humaneval-HumanEval_158_find_max.json-L27
js
//Write a function that accepts an array of strings. // The array 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" function find_max(words){ var max_unique = {}; var max_unique_word = ""; for(var i = 0; i < words.length; i++){ var unique_word = {}; var word = words[i]; for(var j = 0; j < word.length; j++){ var char = word[j]; if(unique_word[char] === undefined){ unique_word[char] = 1; } } if(max_unique_word === ""){ max_unique_word = word; max_unique = unique_word; }
max_unique_word = word; max_unique = unique_word; } else if(Object.keys(unique_word).length === Object.keys(max_unique).length){ if(word < max_unique_word){ max_unique_word = word; max_unique = unique_word; } } } return max_unique_word; }
else if(Object.keys(unique_word).length > Object.keys(max_unique).length){
const assert = require('node:assert'); function test() { let candidate = find_max; assert.deepEqual(candidate(["name", "of", "string"]),"string"); assert.deepEqual(candidate(["name", "enam", "game"]),"enam"); assert.deepEqual(candidate(["aaaaaaa", "bb", "cc"]),"aaaaaaa"); assert.deepEqual(candidate(["abc", "cba"]),"abc"); assert.deepEqual(candidate(["play", "this", "game", "of", "footbott"]),"footbott"); assert.deepEqual(candidate(["we", "are", "gonna", "rock"]),"gonna"); assert.deepEqual(candidate(["we", "are", "a", "mad", "nation"]),"nation"); assert.deepEqual(candidate(["this", "is", "a", "prrk"]),"this"); assert.deepEqual(candidate(["b"]),"b"); assert.deepEqual(candidate(["play", "play", "play"]),"play"); } test();
humaneval-HumanEval_156_int_to_mini_roman.json-L52
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 positive integer, obtain its roman numeral equivalent as a string, // and return it in lowercase. // Restrictions: 1 <= num <= 1000 // Examples: // >>> intToMiniRoman((19l)) // ("xix") // >>> intToMiniRoman((152l)) // ("clii") // >>> intToMiniRoman((426l)) // ("cdxxvi") public static String intToMiniRoman(long number) { int num = (int) number; String res = ""; if (num == 0) return ""; while (num >= 1000) { res += "m"; num -= 1000; } if (num >= 900) { res += "cm"; num -= 900; } if (num >= 500) { res += "d"; num -= 500; } if (num >= 400) { res += "cd"; num -= 400; } while (num >= 100) { res += "c"; num -= 100; } if (num >= 90) { res += "xc"; num -= 90; } if (num >= 50) { res += "l"; num -= 50; }
res += "xl"; num -= 40; } while (num >= 10) { res += "x"; num -= 10; } if (num >= 9) { res += "ix"; num -= 9; } if (num >= 5) { res += "v"; num -= 5; } if (num >= 4) { res += "iv"; num -= 4; } while (num >= 1) { res += "i"; num -= 1; } return res; } }
if (num >= 40) {
} public static void main(String[] args) { assert(intToMiniRoman((19l)).equals(("xix"))); assert(intToMiniRoman((152l)).equals(("clii"))); assert(intToMiniRoman((251l)).equals(("ccli"))); assert(intToMiniRoman((426l)).equals(("cdxxvi"))); assert(intToMiniRoman((500l)).equals(("d"))); assert(intToMiniRoman((1l)).equals(("i"))); assert(intToMiniRoman((4l)).equals(("iv"))); assert(intToMiniRoman((43l)).equals(("xliii"))); assert(intToMiniRoman((90l)).equals(("xc"))); assert(intToMiniRoman((94l)).equals(("xciv"))); assert(intToMiniRoman((532l)).equals(("dxxxii"))); assert(intToMiniRoman((900l)).equals(("cm"))); assert(intToMiniRoman((994l)).equals(("cmxciv"))); assert(intToMiniRoman((1000l)).equals(("m"))); } }
humaneval-HumanEval_72_will_it_fly.json-L23
js
//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) and the sum of its elements is less than or equal the maximum possible weight w. // Example: // >>> will_it_fly([1, 2], 5) // false // # 1+2 is less than the maximum possible weight, but it's unbalanced. // >>> will_it_fly([3, 2, 3], 1) // false // # it's balanced, but 3+2+3 is more than the maximum possible weight. // >>> will_it_fly([3, 2, 3], 9) // true // # 3+2+3 is less than the maximum possible weight, and it's balanced. // >>> will_it_fly([3], 5) // true // # 3 is less than the maximum possible weight, and it's balanced. function will_it_fly(q, w){ let sum = 0; let balanced = true; for(let i = 0; i < q.length; i++){ sum += q[i]; } for(let i = 0; i < q.length; i++){
balanced = false; break; } } return balanced && sum <= w; }
if(q[i] !== q[q.length - 1 - i]){
const assert = require('node:assert'); function test() { let candidate = will_it_fly; assert.deepEqual(candidate([3, 2, 3], 9),true); assert.deepEqual(candidate([1, 2], 5),false); assert.deepEqual(candidate([3], 5),true); assert.deepEqual(candidate([3, 2, 3], 1),false); assert.deepEqual(candidate([1, 2, 3], 6),false); assert.deepEqual(candidate([5], 5),true); } test();
humaneval-HumanEval_25_factorize.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 { // Return array list of prime factors of given integer in the order from smallest to largest. // Each of the factors should be array 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((8l)) // (new ArrayList<Long>(Arrays.asList((long)2l, (long)2l, (long)2l))) // >>> factorize((25l)) // (new ArrayList<Long>(Arrays.asList((long)5l, (long)5l))) // >>> factorize((70l)) // (new ArrayList<Long>(Arrays.asList((long)2l, (long)5l, (long)7l))) public static ArrayList<Long> factorize(long n) { ArrayList<Long> factors = new ArrayList<Long>(); for (long d = 2; d*d <= n; d++) { while (n % d == 0) { factors.add(d); n /= d; } }
factors.add(n); return factors; } }
if (n > 1)
} public static void main(String[] args) { assert(factorize((2l)).equals((new ArrayList<Long>(Arrays.asList((long)2l))))); assert(factorize((4l)).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)2l))))); assert(factorize((8l)).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)2l, (long)2l))))); assert(factorize((57l)).equals((new ArrayList<Long>(Arrays.asList((long)3l, (long)19l))))); assert(factorize((3249l)).equals((new ArrayList<Long>(Arrays.asList((long)3l, (long)3l, (long)19l, (long)19l))))); assert(factorize((185193l)).equals((new ArrayList<Long>(Arrays.asList((long)3l, (long)3l, (long)3l, (long)19l, (long)19l, (long)19l))))); assert(factorize((20577l)).equals((new ArrayList<Long>(Arrays.asList((long)3l, (long)19l, (long)19l, (long)19l))))); assert(factorize((18l)).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)3l, (long)3l))))); } }
humaneval-HumanEval_124_valid_date.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 { // 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) { boolean valid_date = false; 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]);
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; } }
int year = Integer.parseInt(parts[2]);
} 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_75_is_multiply_prime.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 { // 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; } } if (a > 2) { arr.add(a); } return arr.size() == 3;
}
}
} 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_153_Strongest_Extension.json-L26
py
from typing import List def Strongest_Extension(class_name: str, extensions: List[str]) -> str: """You will be given the name of a class (a string) and a list of extensions. The extensions are to be used to load additional classes to the class. The strength of the extension is as follows: Let CAP be the number of the uppercase letters in the extension's name, and let SM be the number of lowercase letters in the extension's name, the strength is given by the fraction CAP - SM. You should find the strongest extension and return a string in this format: ClassName.StrongestExtensionName. If there are two or more extensions with the same strength, you should choose the one that comes first in the list. For example, if you are given "Slices" as the class and a list of the extensions: ['SErviNGSliCes', 'Cheese', 'StuFfed'] then you should return 'Slices.SErviNGSliCes' since 'SErviNGSliCes' is the strongest extension (its strength is -1). Example: >>> Strongest_Extension('my_class', ['AA', 'Be', 'CC']) 'my_class.AA' """ best_strength, best_extension = -1, '' for extension in extensions: n_uppercase = sum(1 for c in extension if c.isupper()) n_lowercase = sum(1 for c in extension if c.islower()) if n_uppercase - n_lowercase > best_strength:
best_extension = extension return class_name + '.' + best_extension
best_strength = n_uppercase - n_lowercase
def check(candidate): assert candidate('Watashi', ['tEN', 'niNE', 'eIGHt8OKe']) == 'Watashi.eIGHt8OKe' assert candidate('Boku123', ['nani', 'NazeDa', 'YEs.WeCaNe', '32145tggg']) == 'Boku123.YEs.WeCaNe' assert candidate('__YESIMHERE', ['t', 'eMptY', 'nothing', 'zeR00', 'NuLl__', '123NoooneB321']) == '__YESIMHERE.NuLl__' assert candidate('K', ['Ta', 'TAR', 't234An', 'cosSo']) == 'K.TAR' assert candidate('__HAHA', ['Tab', '123', '781345', '-_-']) == '__HAHA.123' assert candidate('YameRore', ['HhAas', 'okIWILL123', 'WorkOut', 'Fails', '-_-']) == 'YameRore.okIWILL123' assert candidate('finNNalLLly', ['Die', 'NowW', 'Wow', 'WoW']) == 'finNNalLLly.WoW' assert candidate('_', ['Bb', '91245']) == '_.Bb' assert candidate('Sp', ['671235', 'Bb']) == 'Sp.671235' def test_check(): check(Strongest_Extension) test_check()
humaneval-HumanEval_68_pluck.json-L34
js
//"Given an array representing a branch of a tree that has non-negative integer nodes // your task is to pluck one of the nodes and return it. // The plucked node should be the node with the smallest even value. // If multiple nodes with the same smallest even value are found return the node that has smallest index. // The plucked node should be returned in an array, [ smalest_value, its index ], // If there are no even values or the given array is empty, return []. // Example 1: // >>> pluck([4, 2, 3]) // [2, 1] // Explanation: 2 has the smallest even value, and 2 has the smallest index. // Example 2: // >>> pluck([1, 2, 3]) // [2, 1] // Explanation: 2 has the smallest even value, and 2 has the smallest index. // Example 3: // >>> pluck([]) // [] // Example 4: // >>> pluck([5, 0, 3, 0, 4, 2]) // [0, 1] // Explanation: 0 is the smallest value, but there are two zeros, // so we will choose the first zero, which has the smallest index. // Constraints: // * 1 <= nodes.length <= 10000 // * 0 <= node.value function pluck(arr){ let result = [], index = -1; for(let i = 0; i < arr.length; i++){ if(arr[i] % 2 === 0){ if(result.length === 0 || result[0] > arr[i]){ result = [arr[i], i]; }
} return result; }
}
const assert = require('node:assert'); function test() { let candidate = pluck; assert.deepEqual(candidate([4, 2, 3]),[2, 1]); assert.deepEqual(candidate([1, 2, 3]),[2, 1]); assert.deepEqual(candidate([]),[]); assert.deepEqual(candidate([5, 0, 3, 0, 4, 2]),[0, 1]); assert.deepEqual(candidate([1, 2, 3, 0, 5, 3]),[0, 3]); assert.deepEqual(candidate([5, 4, 8, 4, 8]),[4, 1]); assert.deepEqual(candidate([7, 6, 7, 1]),[6, 1]); assert.deepEqual(candidate([7, 9, 7, 1]),[]); } test();
humaneval-HumanEval_152_compare.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 { // I think we all remember that feeling when the result of some long-awaited // event is finally known. The feelings and thoughts you have at that moment are // definitely worth noting down and comparing. // Your task is to determine if a person correctly guessed the results of a number of matches. // You are given two array array lists of scores and guesses of equal length, where each index shows a match. // Return an array array list of the same length denoting how far off each guess was. If they have guessed correctly, // the value is 0, and if not, the value is the absolute difference between the guess and the score. // example: // >>> compare((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l, (long)5l, (long)1l))), (new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l, (long)2l, (long)-2l)))) // (new ArrayList<Long>(Arrays.asList((long)0l, (long)0l, (long)0l, (long)0l, (long)3l, (long)3l))) // >>> compare((new ArrayList<Long>(Arrays.asList((long)0l, (long)5l, (long)0l, (long)0l, (long)0l, (long)4l))), (new ArrayList<Long>(Arrays.asList((long)4l, (long)1l, (long)1l, (long)0l, (long)0l, (long)-2l)))) // (new ArrayList<Long>(Arrays.asList((long)4l, (long)4l, (long)1l, (long)0l, (long)0l, (long)6l))) public static ArrayList<Long> compare(ArrayList<Long> game, ArrayList<Long> guess) { ArrayList<Long> result = new ArrayList<Long>();
if (game.get(i) != guess.get(i)) { result.add(Math.abs(game.get(i) - guess.get(i))); } else { result.add((long)0); } } return result; } }
for (int i = 0; i < game.size(); i++) {
} public static void main(String[] args) { assert(compare((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l, (long)5l, (long)1l))), (new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l, (long)2l, (long)-2l)))).equals((new ArrayList<Long>(Arrays.asList((long)0l, (long)0l, (long)0l, (long)0l, (long)3l, (long)3l))))); assert(compare((new ArrayList<Long>(Arrays.asList((long)0l, (long)0l, (long)0l, (long)0l, (long)0l, (long)0l))), (new ArrayList<Long>(Arrays.asList((long)0l, (long)0l, (long)0l, (long)0l, (long)0l, (long)0l)))).equals((new ArrayList<Long>(Arrays.asList((long)0l, (long)0l, (long)0l, (long)0l, (long)0l, (long)0l))))); assert(compare((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l))), (new ArrayList<Long>(Arrays.asList((long)-1l, (long)-2l, (long)-3l)))).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)4l, (long)6l))))); assert(compare((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)5l))), (new ArrayList<Long>(Arrays.asList((long)-1l, (long)2l, (long)3l, (long)4l)))).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)0l, (long)0l, (long)1l))))); } }
humaneval-HumanEval_70_strange_sort_list.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 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; 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; } }
}
} 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_70_strange_sort_list.json-L17
js
//Given array of integers, return array in strange order. // Strange sorting, is when you start with the minimum value, // then maximum of the remaining integers, then minimum and so on. // Examples: // >>> strange_sort_list([1, 2, 3, 4]) // [1, 4, 2, 3] // >>> strange_sort_list([5, 5, 5, 5]) // [5, 5, 5, 5] // >>> strange_sort_list([]) // [] function strange_sort_list(lst){ if(lst.length === 0){ return []; } var output = []; var tmp = lst.slice();
if(i % 2 === 0){ output.push(Math.min.apply(null, tmp)); } else{ output.push(Math.max.apply(null, tmp)); } tmp.splice(tmp.indexOf(output[i]), 1); } return output; }
for(var i = 0; i < lst.length; i++){
const assert = require('node:assert'); function test() { let candidate = strange_sort_list; assert.deepEqual(candidate([1, 2, 3, 4]),[1, 4, 2, 3]); assert.deepEqual(candidate([5, 6, 7, 8, 9]),[5, 9, 6, 8, 7]); assert.deepEqual(candidate([1, 2, 3, 4, 5]),[1, 5, 2, 4, 3]); assert.deepEqual(candidate([5, 6, 7, 8, 9, 1]),[1, 9, 5, 8, 6, 7]); assert.deepEqual(candidate([5, 5, 5, 5]),[5, 5, 5, 5]); assert.deepEqual(candidate([]),[]); assert.deepEqual(candidate([1, 2, 3, 4, 5, 6, 7, 8]),[1, 8, 2, 7, 3, 6, 4, 5]); assert.deepEqual(candidate([0, 2, 2, 2, 5, 5, -5, -5]),[-5, 5, -5, 5, 0, 2, 2, 2]); assert.deepEqual(candidate([111111]),[111111]); } test();
humaneval-HumanEval_25_factorize.json-L20
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 i <= n: while n % i == 0: factors.append(i) n = n / i
return factors
i += 1
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_131_digits.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 a positive integer n, return the product of the odd digits. // Return 0 if all digits are even. // For example: // >>> digits((1l)) // (1l) // >>> digits((4l)) // (0l) // >>> digits((235l)) // (15l) public static long digits(long n) { if (n < 10) { return n % 2 == 1 ? n : 0;
return digits(n / 10) * (n % 2 == 1 ? n % 10 : 1); } }
}
} public static void main(String[] args) { assert(digits((5l)) == (5l)); assert(digits((54l)) == (5l)); assert(digits((120l)) == (1l)); assert(digits((5014l)) == (5l)); assert(digits((98765l)) == (315l)); assert(digits((5576543l)) == (2625l)); assert(digits((2468l)) == (0l)); } }
humaneval-HumanEval_31_is_prime.json-L18
py
def is_prime(n: int) -> bool: """Return true if a given number is prime, and false otherwise. >>> is_prime(6) False >>> is_prime(101) True >>> is_prime(11) True >>> is_prime(13441) True >>> is_prime(61) True >>> is_prime(4) False >>> is_prime(1) False """
return False for i in range(2, n//2 + 1): if n % i == 0: return False return True
if n <= 1:
def check(candidate): assert candidate(6) == False assert candidate(101) == True assert candidate(11) == True assert candidate(13441) == True assert candidate(61) == True assert candidate(4) == False assert candidate(1) == False assert candidate(5) == True assert candidate(11) == True assert candidate(17) == True assert candidate(85) == False assert candidate(77) == False assert candidate(255379) == False def test_check(): check(is_prime) test_check()
humaneval-HumanEval_10_make_palindrome.json-L14
js
//Find the shortest palindrome that begins with a supplied string. // Algorithm idea is simple: // - Find the longest postfix of supplied string that is a palindrome. // - Append to the end of the string reverse of a string prefix that comes before the palindromic suffix. // >>> make_palindrome("") // "" // >>> make_palindrome("cat") // "catac" // >>> make_palindrome("cata") // "catac" function make_palindrome(string){ var string_length = string.length; var is_palindrome = function(s){
}; var i = string_length; while(i > 0){ if(is_palindrome(string.substring(0, i))){ return string + string.substring(0, string_length - i).split("").reverse().join(""); } i--; } return string; }
return s == s.split("").reverse().join("");
const assert = require('node:assert'); function test() { let candidate = make_palindrome; assert.deepEqual(candidate(""),""); assert.deepEqual(candidate("x"),"x"); assert.deepEqual(candidate("xyz"),"xyzyx"); assert.deepEqual(candidate("xyx"),"xyx"); assert.deepEqual(candidate("jerry"),"jerryrrej"); } test();
humaneval-HumanEval_1_separate_paren_groups.json-L19
py
from typing import List def separate_paren_groups(paren_string: str) -> List[str]: """ Input to this function is a string containing multiple groups of nested parentheses. Your goal is to separate those group into separate strings and return the list of those. Separate groups are balanced (each open brace is properly closed) and not nested within each other Ignore any spaces in the input string. >>> separate_paren_groups('( ) (( )) (( )( ))') ['()', '(())', '(()())'] """ paren_string = paren_string.replace(' ', '') groups = [] group = '' open_count = 0 for c in paren_string: if c == '(': open_count += 1 elif c == ')':
group += c if open_count == 0: groups.append(group) group = '' return groups
open_count -= 1
def check(candidate): assert candidate('(()()) ((())) () ((())()())') == ['(()())', '((()))', '()', '((())()())'] assert candidate('() (()) ((())) (((())))') == ['()', '(())', '((()))', '(((())))'] assert candidate('(()(())((())))') == ['(()(())((())))'] assert candidate('( ) (( )) (( )( ))') == ['()', '(())', '(()())'] def test_check(): check(separate_paren_groups) test_check()
humaneval-HumanEval_9_rolling_max.json-L14
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 { // From a given array list of integers, generate an array array list of rolling maximum element found until given moment // in the sequence. // >>> rollingMax((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)2l, (long)3l, (long)4l, (long)2l)))) // (new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)3l, (long)3l, (long)4l, (long)4l))) public static ArrayList<Long> rollingMax(ArrayList<Long> numbers) {
for (int i = 0; i < numbers.size(); i++) { results.add(numbers.subList(0, i + 1).stream().max(Long::compare).get()); } return results; } }
ArrayList<Long> results = new ArrayList<Long>();
} public static void main(String[] args) { assert(rollingMax((new ArrayList<Long>(Arrays.asList()))).equals((new ArrayList<Long>(Arrays.asList())))); assert(rollingMax((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l)))).equals((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l))))); assert(rollingMax((new ArrayList<Long>(Arrays.asList((long)4l, (long)3l, (long)2l, (long)1l)))).equals((new ArrayList<Long>(Arrays.asList((long)4l, (long)4l, (long)4l, (long)4l))))); assert(rollingMax((new ArrayList<Long>(Arrays.asList((long)3l, (long)2l, (long)3l, (long)100l, (long)3l)))).equals((new ArrayList<Long>(Arrays.asList((long)3l, (long)3l, (long)3l, (long)100l, (long)100l))))); } }
humaneval-HumanEval_97_multiply.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 { // Complete the function that takes two integers and returns // the product of their unit digits. // Assume the input is always valid. // Examples: // >>> multiply((148l), (412l)) // (16l) // >>> multiply((19l), (28l)) // (72l) // >>> multiply((2020l), (1851l)) // (0l) // >>> multiply((14l), (-15l)) // (20l) public static long multiply(long a, long b) {
long y = Math.abs(b % 10); return x * y; } }
long x = Math.abs(a % 10);
} public static void main(String[] args) { assert(multiply((148l), (412l)) == (16l)); assert(multiply((19l), (28l)) == (72l)); assert(multiply((2020l), (1851l)) == (0l)); assert(multiply((14l), (-15l)) == (20l)); assert(multiply((76l), (67l)) == (42l)); assert(multiply((17l), (27l)) == (49l)); assert(multiply((0l), (1l)) == (0l)); assert(multiply((0l), (0l)) == (0l)); } }
humaneval-HumanEval_5_intersperse.json-L15
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 { // Insert a number 'delimeter' between every two consecutive elements of input array list `numbers' // >>> intersperse((new ArrayList<Long>(Arrays.asList())), (4l)) // (new ArrayList<Long>(Arrays.asList())) // >>> intersperse((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l))), (4l)) // (new ArrayList<Long>(Arrays.asList((long)1l, (long)4l, (long)2l, (long)4l, (long)3l))) public static ArrayList<Long> intersperse(ArrayList<Long> numbers, long delimeter) {
for (int i = 0; i < (numbers.size()); i++) { result.add(numbers.get(i)); if ((i < (numbers.size() - 1))) { result.add(delimeter); } } return result; } }
ArrayList<Long> result = new ArrayList<Long>();
} public static void main(String[] args) { assert(intersperse((new ArrayList<Long>(Arrays.asList())), (7l)).equals((new ArrayList<Long>(Arrays.asList())))); assert(intersperse((new ArrayList<Long>(Arrays.asList((long)5l, (long)6l, (long)3l, (long)2l))), (8l)).equals((new ArrayList<Long>(Arrays.asList((long)5l, (long)8l, (long)6l, (long)8l, (long)3l, (long)8l, (long)2l))))); assert(intersperse((new ArrayList<Long>(Arrays.asList((long)2l, (long)2l, (long)2l))), (2l)).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)2l, (long)2l, (long)2l, (long)2l))))); } }
humaneval-HumanEval_116_sort_array.json-L18
js
//In this Kata, you have to sort an array of non-negative integers according to // number of ones in their binary representation in ascending order. // For similar number of ones, sort based on decimal value. // It must be implemented like this: // >>> sort_array([1, 5, 2, 3, 4]) // [1, 2, 3, 4, 5] // >>> sort_array([-2, -3, -4, -5, -6]) // [-6, -5, -4, -3, -2] // >>> sort_array([1, 0, 2, 3, 4]) // [0, 1, 2, 3, 4] function sort_array(arr){ return arr.sort((a, b) => { let aBinary = a.toString(2).split('').filter(el => el === '1').length; let bBinary = b.toString(2).split('').filter(el => el === '1').length; if (aBinary === bBinary) { return a - b; } else {
} }); }
return aBinary - bBinary;
const assert = require('node:assert'); function test() { let candidate = sort_array; assert.deepEqual(candidate([1, 5, 2, 3, 4]),[1, 2, 4, 3, 5]); assert.deepEqual(candidate([-2, -3, -4, -5, -6]),[-4, -2, -6, -5, -3]); assert.deepEqual(candidate([1, 0, 2, 3, 4]),[0, 1, 2, 4, 3]); assert.deepEqual(candidate([]),[]); assert.deepEqual(candidate([2, 5, 77, 4, 5, 3, 5, 7, 2, 3, 4]),[2, 2, 4, 4, 3, 3, 5, 5, 5, 7, 77]); assert.deepEqual(candidate([3, 6, 44, 12, 32, 5]),[32, 3, 5, 6, 12, 44]); assert.deepEqual(candidate([2, 4, 8, 16, 32]),[2, 4, 8, 16, 32]); assert.deepEqual(candidate([2, 4, 8, 16, 32]),[2, 4, 8, 16, 32]); } test();
humaneval-HumanEval_147_get_max_triples.json-L19
js
//You are given a positive integer n. You have to create an integer array a of length n. // For each i (1 ≤ i ≤ n), the value of a[i] = i * i - i + 1. // Return the number of triples (a[i], a[j], a[k]) of a where i < j < k, // and a[i] + a[j] + a[k] is a multiple of 3. // Example : // >>> get_max_triples(5) // 1 // Explanation: // a = [1, 3, 7, 13, 21] // The only valid triple is (1, 7, 13). function get_max_triples(n){ let result = 0; let arr = []; for(let i = 1; i<=n; i++){ arr.push(i*i-i+1); } for(let i = 0; i<arr.length; i++){ for(let j = i+1; j<arr.length; j++){
if((arr[i]+arr[j]+arr[k])%3 === 0){ result++; } } } } return result; }
for(let k = j+1; k<arr.length; k++){
const assert = require('node:assert'); function test() { let candidate = get_max_triples; assert.deepEqual(candidate(5),1); assert.deepEqual(candidate(6),4); assert.deepEqual(candidate(10),36); assert.deepEqual(candidate(100),53361); } test();
humaneval-HumanEval_159_eat.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're a hungry rabbit, and you already have eaten a certain number of carrots, // but now you need to eat more carrots to complete the day's meals. // you should return an array array list of [ total number of eaten carrots after your meals, // the number of carrots left after your meals ] // if there are not enough remaining carrots, you will eat all remaining carrots, but will still be hungry. // Example: // >>> eat((5l), (6l), (10l)) // (new ArrayList<Long>(Arrays.asList((long)11l, (long)4l))) // >>> eat((4l), (8l), (9l)) // (new ArrayList<Long>(Arrays.asList((long)12l, (long)1l))) // >>> eat((1l), (10l), (10l)) // (new ArrayList<Long>(Arrays.asList((long)11l, (long)0l))) // >>> eat((2l), (11l), (5l)) // (new ArrayList<Long>(Arrays.asList((long)7l, (long)0l))) // Variables: // @number : integer // the number of carrots that you have eaten. // @need : integer // the number of carrots that you need to eat. // @remaining : integer // the number of remaining carrots thet exist in stock // Constrain: // * 0 <= number <= 1000 // * 0 <= need <= 1000 // * 0 <= remaining <= 1000 // Have fun :) public static ArrayList<Long> eat(long number, long need, long remaining) { long total = number + Math.min(need, remaining); long left = Math.max(0, remaining - need); return new ArrayList<Long>(Arrays.asList(total, left));
}
}
} public static void main(String[] args) { assert(eat((5l), (6l), (10l)).equals((new ArrayList<Long>(Arrays.asList((long)11l, (long)4l))))); assert(eat((4l), (8l), (9l)).equals((new ArrayList<Long>(Arrays.asList((long)12l, (long)1l))))); assert(eat((1l), (10l), (10l)).equals((new ArrayList<Long>(Arrays.asList((long)11l, (long)0l))))); assert(eat((2l), (11l), (5l)).equals((new ArrayList<Long>(Arrays.asList((long)7l, (long)0l))))); assert(eat((4l), (5l), (7l)).equals((new ArrayList<Long>(Arrays.asList((long)9l, (long)2l))))); assert(eat((4l), (5l), (1l)).equals((new ArrayList<Long>(Arrays.asList((long)5l, (long)0l))))); } }
humaneval-HumanEval_87_get_row.json-L21
js
//You are given a 2 dimensional data, as a nested arrays, // which is similar to matrix, however, unlike matrices, // each row may contain a different number of columns. // Given lst, and integer x, find integers x in the array, // and return array of arrays, [(x1, y1), (x2, y2) ...] such that // each array is a coordinate - (row, columns), starting with 0. // Sort coordinates initially by rows in ascending order. // Also, sort coordinates of the row by columns in descending order. // Examples: // >>> get_row([[1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 1, 6], [1, 2, 3, 4, 5, 1]], 1) // [[0, 0], [1, 4], [1, 0], [2, 5], [2, 0]] // >>> get_row([], 1) // [] // >>> get_row([[], [1], [1, 2, 3]], 3) // [[2, 2]] function get_row(lst, x){ let coordinates = []; for (let i = 0; i < lst.length; i++){ let array = lst[i]; for (let j = 0; j < array.length; j++){
coordinates.push([i, j]); } } } return coordinates.sort(function(a, b){ return a[0] - b[0] || b[1] - a[1]; }); }
if (lst[i][j] === x){
const assert = require('node:assert'); function test() { let candidate = get_row; assert.deepEqual(candidate([[1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 1, 6], [1, 2, 3, 4, 5, 1]], 1),[[0, 0], [1, 4], [1, 0], [2, 5], [2, 0]]); assert.deepEqual(candidate([[1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6]], 2),[[0, 1], [1, 1], [2, 1], [3, 1], [4, 1], [5, 1]]); assert.deepEqual(candidate([[1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6], [1, 1, 3, 4, 5, 6], [1, 2, 1, 4, 5, 6], [1, 2, 3, 1, 5, 6], [1, 2, 3, 4, 1, 6], [1, 2, 3, 4, 5, 1]], 1),[[0, 0], [1, 0], [2, 1], [2, 0], [3, 2], [3, 0], [4, 3], [4, 0], [5, 4], [5, 0], [6, 5], [6, 0]]); assert.deepEqual(candidate([], 1),[]); assert.deepEqual(candidate([[1]], 2),[]); assert.deepEqual(candidate([[], [1], [1, 2, 3]], 3),[[2, 2]]); } test();
humaneval-HumanEval_78_hex_key.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 have been tasked to write a function that receives // a hexadecimal number as a string and counts the number of hexadecimal // digits that are primes (prime number, or a prime, is a natural number // greater than 1 that is not a product of two smaller natural numbers). // Hexadecimal digits are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F. // Prime numbers are 2, 3, 5, 7, 11, 13, 17,... // So you have to determine a number of the following digits: 2, 3, 5, 7, // B (=decimal 11), D (=decimal 13). // Note: you may assume the input is always correct or empty string, // and symbols A,B,C,D,E,F are always uppercase. // Examples: // >>> hexKey(("AB")) // (1l) // >>> hexKey(("1077E")) // (2l) // >>> hexKey(("ABED1A33")) // (4l) // >>> hexKey(("123456789ABCDEF0")) // (6l) // >>> hexKey(("2020")) // (2l) public static long hexKey(String num) { long result = 0; for (int i = 0; i < num.length(); i++) { if (num.charAt(i) == '2' || num.charAt(i) == '3' || num.charAt(i) == '5' || num.charAt(i) == '7' || num.charAt(i) == 'B' || num.charAt(i) == 'D') { result++; } } return result; }
}
} public static void main(String[] args) { assert(hexKey(("AB")) == (1l)); assert(hexKey(("1077E")) == (2l)); assert(hexKey(("ABED1A33")) == (4l)); assert(hexKey(("2020")) == (2l)); assert(hexKey(("123456789ABCDEF0")) == (6l)); assert(hexKey(("112233445566778899AABBCCDDEEFF00")) == (12l)); } }
humaneval-HumanEval_105_by_length.json-L22
py
from typing import List def by_length(arr: List[int]) -> List[str]: """ 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'] """ digits = [x for x in arr if 1 <= x <= 9]
digits.reverse() for i in range(len(digits)): digits[i] = ['One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine'][digits[i] - 1] return digits
digits.sort()
def check(candidate): assert candidate([2, 1, 1, 4, 5, 8, 2, 3]) == ['Eight', 'Five', 'Four', 'Three', 'Two', 'Two', 'One', 'One'] assert candidate([]) == [] assert candidate([1, -1, 55]) == ['One'] assert candidate([1, -1, 3, 2]) == ['Three', 'Two', 'One'] assert candidate([9, 4, 8]) == ['Nine', 'Eight', 'Four'] def test_check(): check(by_length) test_check()
humaneval-HumanEval_86_anti_shuffle.json-L19
py
def anti_shuffle(s: str) -> str: """ Write a function that takes a string and returns an ordered version of it. Ordered version of string, is a string where all words (separated by space) are replaced by a new word where all the characters arranged in ascending order based on ascii value. Note: You should keep the order of words and blank spaces in the sentence. For example: >>> anti_shuffle('Hi') 'Hi' >>> anti_shuffle('hello') 'ehllo' >>> anti_shuffle('Hello World!!!') 'Hello !!!Wdlor' """ words = s.split(' ') shuffled_words = [''.join(sorted(word)) for word in words]
return ' '.join(shuffled_words)
def check(candidate): assert candidate('Hi') == 'Hi' assert candidate('hello') == 'ehllo' assert candidate('number') == 'bemnru' assert candidate('abcd') == 'abcd' assert candidate('Hello World!!!') == 'Hello !!!Wdlor' assert candidate('') == '' assert candidate('Hi. My name is Mister Robot. How are you?') == '.Hi My aemn is Meirst .Rboot How aer ?ouy' def test_check(): check(anti_shuffle) test_check()
humaneval-HumanEval_25_factorize.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 { // Return array list of prime factors of given integer in the order from smallest to largest. // Each of the factors should be array 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((8l)) // (new ArrayList<Long>(Arrays.asList((long)2l, (long)2l, (long)2l))) // >>> factorize((25l)) // (new ArrayList<Long>(Arrays.asList((long)5l, (long)5l))) // >>> factorize((70l)) // (new ArrayList<Long>(Arrays.asList((long)2l, (long)5l, (long)7l))) public static ArrayList<Long> factorize(long n) { ArrayList<Long> factors = new ArrayList<Long>(); for (long d = 2; d*d <= n; d++) {
factors.add(d); n /= d; } } if (n > 1) factors.add(n); return factors; } }
while (n % d == 0) {
} public static void main(String[] args) { assert(factorize((2l)).equals((new ArrayList<Long>(Arrays.asList((long)2l))))); assert(factorize((4l)).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)2l))))); assert(factorize((8l)).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)2l, (long)2l))))); assert(factorize((57l)).equals((new ArrayList<Long>(Arrays.asList((long)3l, (long)19l))))); assert(factorize((3249l)).equals((new ArrayList<Long>(Arrays.asList((long)3l, (long)3l, (long)19l, (long)19l))))); assert(factorize((185193l)).equals((new ArrayList<Long>(Arrays.asList((long)3l, (long)3l, (long)3l, (long)19l, (long)19l, (long)19l))))); assert(factorize((20577l)).equals((new ArrayList<Long>(Arrays.asList((long)3l, (long)19l, (long)19l, (long)19l))))); assert(factorize((18l)).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)3l, (long)3l))))); } }
humaneval-HumanEval_35_max_element.json-L12
py
from typing import List def max_element(l: List[int]) -> int: """Return maximum element in the list. >>> max_element([1, 2, 3]) 3 >>> max_element([5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) 123 """ max_elem = l[0] for i in range(1, len(l)):
max_elem = l[i] return max_elem
if l[i] > max_elem:
def check(candidate): assert candidate([1, 2, 3]) == 3 assert candidate([5, 3, -5, 2, -3, 3, 9, 0, 124, 1, -10]) == 124 def test_check(): check(max_element) test_check()
humaneval-HumanEval_27_flip_case.json-L10
js
//For a given string, flip lowercase characters to uppercase and uppercase to lowercase. // >>> flip_case("Hello") // "hELLO" function flip_case(string){ var result = ""; for(var i = 0; i < string.length; i++){ if(string[i] == string[i].toUpperCase()){ result += string[i].toLowerCase(); }else{
} } return result; }
result += string[i].toUpperCase();
const assert = require('node:assert'); function test() { let candidate = flip_case; assert.deepEqual(candidate(""),""); assert.deepEqual(candidate("Hello!"),"hELLO!"); assert.deepEqual(candidate("These violent delights have violent ends"),"tHESE VIOLENT DELIGHTS HAVE VIOLENT ENDS"); } test();
humaneval-HumanEval_91_is_bored.json-L18
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 lines = S.split(/[.?!]/); let boredoms = 0; for (let line of lines){ if(line.match(/^\s*I /)){ boredoms++; } } return boredoms;
}
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_24_largest_divisor.json-L6
js
//For a given number n, find the largest number that divides n evenly, smaller than n // >>> largest_divisor(15) // 5 function largest_divisor(n){ let ld = 0;
if(n%i===0){ if(i>ld){ ld = i; } } } return ld; }
for(i=1; i<n; i++){
const assert = require('node:assert'); function test() { let candidate = largest_divisor; assert.deepEqual(candidate(3),1); assert.deepEqual(candidate(7),1); assert.deepEqual(candidate(10),5); assert.deepEqual(candidate(100),50); assert.deepEqual(candidate(49),7); } test();
humaneval-HumanEval_158_find_max.json-L12
js
//Write a function that accepts an array of strings. // The array 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" function find_max(words){
var max_unique_word = ""; for(var i = 0; i < words.length; i++){ var unique_word = {}; var word = words[i]; for(var j = 0; j < word.length; j++){ var char = word[j]; if(unique_word[char] === undefined){ unique_word[char] = 1; } } if(max_unique_word === ""){ max_unique_word = word; max_unique = unique_word; } else if(Object.keys(unique_word).length > Object.keys(max_unique).length){ max_unique_word = word; max_unique = unique_word; } else if(Object.keys(unique_word).length === Object.keys(max_unique).length){ if(word < max_unique_word){ max_unique_word = word; max_unique = unique_word; } } } return max_unique_word; }
var max_unique = {};
const assert = require('node:assert'); function test() { let candidate = find_max; assert.deepEqual(candidate(["name", "of", "string"]),"string"); assert.deepEqual(candidate(["name", "enam", "game"]),"enam"); assert.deepEqual(candidate(["aaaaaaa", "bb", "cc"]),"aaaaaaa"); assert.deepEqual(candidate(["abc", "cba"]),"abc"); assert.deepEqual(candidate(["play", "this", "game", "of", "footbott"]),"footbott"); assert.deepEqual(candidate(["we", "are", "gonna", "rock"]),"gonna"); assert.deepEqual(candidate(["we", "are", "a", "mad", "nation"]),"nation"); assert.deepEqual(candidate(["this", "is", "a", "prrk"]),"this"); assert.deepEqual(candidate(["b"]),"b"); assert.deepEqual(candidate(["play", "play", "play"]),"play"); } test();
humaneval-HumanEval_39_prime_fib.json-L39
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--; }
} var res = 0; var fibNum = 0; while(res < n){ if(isPrime(fib(fibNum))){ res++; } fibNum++; } return fib(fibNum - 1); }
return b;
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_137_compare_one.json-L53
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: 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:
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 b
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_27_flip_case.json-L5
js
//For a given string, flip lowercase characters to uppercase and uppercase to lowercase. // >>> flip_case("Hello") // "hELLO" function flip_case(string){
for(var i = 0; i < string.length; i++){ if(string[i] == string[i].toUpperCase()){ result += string[i].toLowerCase(); }else{ result += string[i].toUpperCase(); } } return result; }
var result = "";
const assert = require('node:assert'); function test() { let candidate = flip_case; assert.deepEqual(candidate(""),""); assert.deepEqual(candidate("Hello!"),"hELLO!"); assert.deepEqual(candidate("These violent delights have violent ends"),"tHESE VIOLENT DELIGHTS HAVE VIOLENT ENDS"); } test();
humaneval-HumanEval_1_separate_paren_groups.json-L21
py
from typing import List def separate_paren_groups(paren_string: str) -> List[str]: """ Input to this function is a string containing multiple groups of nested parentheses. Your goal is to separate those group into separate strings and return the list of those. Separate groups are balanced (each open brace is properly closed) and not nested within each other Ignore any spaces in the input string. >>> separate_paren_groups('( ) (( )) (( )( ))') ['()', '(())', '(()())'] """ paren_string = paren_string.replace(' ', '') groups = [] group = '' open_count = 0 for c in paren_string: if c == '(': open_count += 1 elif c == ')': open_count -= 1 group += c
groups.append(group) group = '' return groups
if open_count == 0:
def check(candidate): assert candidate('(()()) ((())) () ((())()())') == ['(()())', '((()))', '()', '((())()())'] assert candidate('() (()) ((())) (((())))') == ['()', '(())', '((()))', '(((())))'] assert candidate('(()(())((())))') == ['(()(())((())))'] assert candidate('( ) (( )) (( )( ))') == ['()', '(())', '(()())'] def test_check(): check(separate_paren_groups) test_check()
humaneval-HumanEval_104_unique_digits.json-L18
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 positive integers x. return a sorted array list of all // elements that hasn't any even digit. // Note: Returned array list should be sorted in increasing order. // For example: // >>> uniqueDigits((new ArrayList<Long>(Arrays.asList((long)15l, (long)33l, (long)1422l, (long)1l)))) // (new ArrayList<Long>(Arrays.asList((long)1l, (long)15l, (long)33l))) // >>> uniqueDigits((new ArrayList<Long>(Arrays.asList((long)152l, (long)323l, (long)1422l, (long)10l)))) // (new ArrayList<Long>(Arrays.asList())) public static ArrayList<Long> uniqueDigits(ArrayList<Long> x) {
for (int i = 0; i < x.size(); i++) { if (x.get(i) < 0) { x.set(i, x.get(i)*(long)-1); } boolean unique = true; long z = x.get(i); while (z > 0) { long y = z % 10; if (y % 2 == 0) { unique = false; break; } z = z / 10; } if (unique) { b.add(x.get(i)); } } Collections.sort(b); return b; } }
ArrayList<Long> b = new ArrayList<Long>();
} public static void main(String[] args) { assert(uniqueDigits((new ArrayList<Long>(Arrays.asList((long)15l, (long)33l, (long)1422l, (long)1l)))).equals((new ArrayList<Long>(Arrays.asList((long)1l, (long)15l, (long)33l))))); assert(uniqueDigits((new ArrayList<Long>(Arrays.asList((long)152l, (long)323l, (long)1422l, (long)10l)))).equals((new ArrayList<Long>(Arrays.asList())))); assert(uniqueDigits((new ArrayList<Long>(Arrays.asList((long)12345l, (long)2033l, (long)111l, (long)151l)))).equals((new ArrayList<Long>(Arrays.asList((long)111l, (long)151l))))); assert(uniqueDigits((new ArrayList<Long>(Arrays.asList((long)135l, (long)103l, (long)31l)))).equals((new ArrayList<Long>(Arrays.asList((long)31l, (long)135l))))); } }
humaneval-HumanEval_161_solve.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 { // 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_134_check_if_last_char_is_a_letter.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 { // 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: // >>> checkIfLastCharIsALetter(("apple pie")) // (false) // >>> checkIfLastCharIsALetter(("apple pi e")) // (true) // >>> checkIfLastCharIsALetter(("apple pi e ")) // (false) // >>> checkIfLastCharIsALetter(("")) // (false) public static boolean checkIfLastCharIsALetter(String txt) { if (txt.length() == 0) { return false; } int len = txt.length(); if (txt.substring(len - 1, len).matches("[A-Z]") || txt.substring(len - 1, len).matches("[a-z]")) {
return true; } if (txt.substring(len - 2, len - 1).matches(" ")) { return true; } } return false; } }
if (len == 1) {
} public static void main(String[] args) { assert(checkIfLastCharIsALetter(("apple")) == (false)); assert(checkIfLastCharIsALetter(("apple pi e")) == (true)); assert(checkIfLastCharIsALetter(("eeeee")) == (false)); assert(checkIfLastCharIsALetter(("A")) == (true)); assert(checkIfLastCharIsALetter(("Pumpkin pie ")) == (false)); assert(checkIfLastCharIsALetter(("Pumpkin pie 1")) == (false)); assert(checkIfLastCharIsALetter(("")) == (false)); assert(checkIfLastCharIsALetter(("eeeee e ")) == (false)); assert(checkIfLastCharIsALetter(("apple pie")) == (false)); assert(checkIfLastCharIsALetter(("apple pi e ")) == (false)); } }
humaneval-HumanEval_152_compare.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 { // I think we all remember that feeling when the result of some long-awaited // event is finally known. The feelings and thoughts you have at that moment are // definitely worth noting down and comparing. // Your task is to determine if a person correctly guessed the results of a number of matches. // You are given two array array lists of scores and guesses of equal length, where each index shows a match. // Return an array array list of the same length denoting how far off each guess was. If they have guessed correctly, // the value is 0, and if not, the value is the absolute difference between the guess and the score. // example: // >>> compare((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l, (long)5l, (long)1l))), (new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l, (long)2l, (long)-2l)))) // (new ArrayList<Long>(Arrays.asList((long)0l, (long)0l, (long)0l, (long)0l, (long)3l, (long)3l))) // >>> compare((new ArrayList<Long>(Arrays.asList((long)0l, (long)5l, (long)0l, (long)0l, (long)0l, (long)4l))), (new ArrayList<Long>(Arrays.asList((long)4l, (long)1l, (long)1l, (long)0l, (long)0l, (long)-2l)))) // (new ArrayList<Long>(Arrays.asList((long)4l, (long)4l, (long)1l, (long)0l, (long)0l, (long)6l))) public static ArrayList<Long> compare(ArrayList<Long> game, ArrayList<Long> guess) { ArrayList<Long> result = new ArrayList<Long>(); for (int i = 0; i < game.size(); i++) { if (game.get(i) != guess.get(i)) { result.add(Math.abs(game.get(i) - guess.get(i))); } else { result.add((long)0);
} return result; } }
}
} public static void main(String[] args) { assert(compare((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l, (long)5l, (long)1l))), (new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l, (long)2l, (long)-2l)))).equals((new ArrayList<Long>(Arrays.asList((long)0l, (long)0l, (long)0l, (long)0l, (long)3l, (long)3l))))); assert(compare((new ArrayList<Long>(Arrays.asList((long)0l, (long)0l, (long)0l, (long)0l, (long)0l, (long)0l))), (new ArrayList<Long>(Arrays.asList((long)0l, (long)0l, (long)0l, (long)0l, (long)0l, (long)0l)))).equals((new ArrayList<Long>(Arrays.asList((long)0l, (long)0l, (long)0l, (long)0l, (long)0l, (long)0l))))); assert(compare((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l))), (new ArrayList<Long>(Arrays.asList((long)-1l, (long)-2l, (long)-3l)))).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)4l, (long)6l))))); assert(compare((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)5l))), (new ArrayList<Long>(Arrays.asList((long)-1l, (long)2l, (long)3l, (long)4l)))).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)0l, (long)0l, (long)1l))))); } }
humaneval-HumanEval_109_move_one_ball.json-L29
js
//We have an array 'arr' of N integers arr[1], arr[2], ..., arr[N].The // numbers in the array will be randomly ordered. Your task is to determine if // it is possible to get an array sorted in non-decreasing order by performing // the following operation on the given array: // You are allowed to perform right shift operation any number of times. // One right shift operation means shifting all elements of the array by one // position in the right direction. The last element of the array will be moved to // the starting position in the array i.e. 0th index. // If it is possible to obtain the sorted array by performing the above operation // then return true else return false. // If the given array is empty then return true. // Note: The given array is guaranteed to have unique elements. // For Example: // >>> move_one_ball([3, 4, 5, 1, 2]) // true // Explanation: By performin 2 right shift operations, non-decreasing order can // be achieved for the given array. // >>> move_one_ball([3, 5, 4, 1, 2]) // false // Explanation:It is not possible to get non-decreasing order for the given // array by performing any number of right shift operations. function move_one_ball(arr){ var diff_count = 0; var i = 0; var temp = 0; for(var i = 0; i < arr.length - 1; i++){ if(arr[i] > arr[i + 1]){ diff_count += 1;
} if(diff_count > 1){ return false; } else{ return true; } }
}
const assert = require('node:assert'); function test() { let candidate = move_one_ball; assert.deepEqual(candidate([3, 4, 5, 1, 2]),true); assert.deepEqual(candidate([3, 5, 10, 1, 2]),true); assert.deepEqual(candidate([4, 3, 1, 2]),false); assert.deepEqual(candidate([3, 5, 4, 1, 2]),false); assert.deepEqual(candidate([]),true); } test();
humaneval-HumanEval_118_get_closest_vowel.json-L37
js
//You are given a word. Your task is to find the closest vowel that stands between // two consonants from the right side of the word (case sensitive). // Vowels in the beginning and ending doesn't count. Return empty string if you didn't // find any vowel met the above condition. // You may assume that the given string contains English letter only. // Example: // >>> get_closest_vowel("yogurt") // "u" // >>> get_closest_vowel("FULL") // "U" // >>> get_closest_vowel("quick") // "" // >>> get_closest_vowel("ab") // "" function get_closest_vowel(word){ let vowels = ["a", "e", "i", "o", "u"]; let i = word.length - 1; let result = []; if (word.length === 1) { return "" } else { while (i >= 0) { if (vowels.includes(word[i])) { if (i > 0 && i < word.length - 1) { if (!vowels.includes(word[i-1]) && !vowels.includes(word[i+1])) { result.push(word[i]); } } } i--; } if (result.length === 0) { return "" } else { return result[0]; }
}
}
const assert = require('node:assert'); function test() { let candidate = get_closest_vowel; assert.deepEqual(candidate("yogurt"),"u"); assert.deepEqual(candidate("full"),"u"); assert.deepEqual(candidate("easy"),""); assert.deepEqual(candidate("eAsy"),""); assert.deepEqual(candidate("ali"),""); assert.deepEqual(candidate("bad"),"a"); assert.deepEqual(candidate("most"),"o"); assert.deepEqual(candidate("ab"),""); assert.deepEqual(candidate("ba"),""); assert.deepEqual(candidate("quick"),""); assert.deepEqual(candidate("anime"),"i"); assert.deepEqual(candidate("Asia"),""); assert.deepEqual(candidate("Above"),"o"); } test();
humaneval-HumanEval_91_is_bored.json-L11
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 lines = S.split(/[.?!]/);
for (let line of lines){ if(line.match(/^\s*I /)){ boredoms++; } } return boredoms; }
let boredoms = 0;
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_98_count_upper.json-L15
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
if s[i] in vowel_set: count += 1 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. """
for i in range(0, len(s), 2):
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_160_do_algebra.json-L64
js
//Given two arrays operator, and operand. The first array has basic algebra operations, and // the second array is an array of integers. Use the two given arrays 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 array is equal to the length of operand array minus one. // Operand is an array of of non-negative integers. // Operator array has at least one operator, and operand array has at least two operands. function do_algebra(operator, operand){ let do_again; let count = 0; let temp; let answer; while(count < operator.length){ switch(operator[count]){ case '*': operand[count] = operand[count] * operand[count + 1]; operand.splice(count + 1, 1); operator.splice(count, 1); count = 0; do_again = true; break; case '//': operand[count] = Math.floor(operand[count] / operand[count + 1]); operand.splice(count + 1, 1); operator.splice(count, 1); count = 0; do_again = true; break; case '**': operand[count] = Math.pow(operand[count], operand[count + 1]); operand.splice(count + 1, 1); operator.splice(count, 1); count = 0; do_again = true; break; default: count++; do_again = false; } } answer = operand[0]; operand.splice(0, 1); while(operand.length > 0){ switch(operator[0]){ case '+': answer += operand[0]; break; case '-': answer -= operand[0]; break; } operand.splice(0, 1);
} return answer; }
operator.splice(0, 1);
const assert = require('node:assert'); function test() { let candidate = do_algebra; assert.deepEqual(candidate(["**", "*", "+"], [2, 3, 4, 5]),37); assert.deepEqual(candidate(["+", "*", "-"], [2, 3, 4, 5]),9); assert.deepEqual(candidate(["//", "*"], [7, 3, 4]),8); } test();
humaneval-HumanEval_90_next_smallest.json-L23
py
from typing import List, Optional def next_smallest(lst: List[int]) -> Optional[int]: """ You are given a list of integers. Write a function next_smallest() that returns the 2nd smallest element of the list. Return None if there is no such element. >>> next_smallest([1, 2, 3, 4, 5]) 2 >>> next_smallest([5, 1, 4, 3, 2]) 2 >>> next_smallest([]) None >>> next_smallest([1, 1]) None """ if len(lst) < 2: return None min1 = min(lst[0], lst[1]) min2 = max(lst[0], lst[1]) for i in range(2, len(lst)): if lst[i] < min1:
min1 = lst[i] elif lst[i] < min2: min2 = lst[i] return min2 if min1 != min2 else None
min2 = min1
def check(candidate): assert candidate([1, 2, 3, 4, 5]) == 2 assert candidate([5, 1, 4, 3, 2]) == 2 assert candidate([]) == None assert candidate([1, 1]) == None assert candidate([1, 1, 1, 1, 0]) == 1 assert candidate([1, 1]) == None assert candidate([-35, 34, 12, -45]) == -35 def test_check(): check(next_smallest) test_check()
humaneval-HumanEval_65_circular_shift.json-L10
js
//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" function circular_shift(x, shift){ var str = x.toString();
var res = ''; if(len < shift){ for(var i = len-1; i >= 0; i--){ res += str[i]; } }else{ res = str.substring(len-shift) + str.substring(0, len-shift); } return res; }
var len = str.length;
const assert = require('node:assert'); function test() { let candidate = circular_shift; assert.deepEqual(candidate(100, 2),"001"); assert.deepEqual(candidate(12, 2),"12"); assert.deepEqual(candidate(97, 8),"79"); assert.deepEqual(candidate(12, 1),"21"); assert.deepEqual(candidate(11, 101),"11"); } test();
humaneval-HumanEval_89_encrypt.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 { // Create a function encrypt that takes a string as an argument and // returns a string encrypted with the alphabet being rotated. // The alphabet should be rotated in a manner such that the letters // shift down by two multiplied to two places. // For example: // >>> encrypt(("hi")) // ("lm") // >>> encrypt(("asdfghjkl")) // ("ewhjklnop") // >>> encrypt(("gf")) // ("kj") // >>> encrypt(("et")) // ("ix") public static String encrypt(String s) { StringBuffer b = new StringBuffer(); for (char c : s.toCharArray()) { b.append((char)((c+4) > 'z' ? (((c+4)%'z')+'a'-1) : c+4)); } return b.toString();
}
}
} public static void main(String[] args) { assert(encrypt(("hi")).equals(("lm"))); assert(encrypt(("asdfghjkl")).equals(("ewhjklnop"))); assert(encrypt(("gf")).equals(("kj"))); assert(encrypt(("et")).equals(("ix"))); assert(encrypt(("faewfawefaewg")).equals(("jeiajeaijeiak"))); assert(encrypt(("hellomyfriend")).equals(("lippsqcjvmirh"))); assert(encrypt(("dxzdlmnilfuhmilufhlihufnmlimnufhlimnufhfucufh")).equals(("hbdhpqrmpjylqmpyjlpmlyjrqpmqryjlpmqryjljygyjl"))); assert(encrypt(("a")).equals(("e"))); } }
humaneval-HumanEval_115_max_fill.json-L26
js
//You are given a rectangular grid of wells. Each row represents a single well, // and each 1 in a row represents a single unit of water. // Each well has a corresponding bucket that can be used to extract water from it, // and all buckets have the same capacity. // Your task is to use the buckets to empty the wells. // Output the number of times you need to lower the buckets. // Example 1: // >>> max_fill([[0, 0, 1, 0], [0, 1, 0, 0], [1, 1, 1, 1]], 1) // 6 // Example 2: // >>> max_fill([[0, 0, 1, 1], [0, 0, 0, 0], [1, 1, 1, 1], [0, 1, 1, 1]], 2) // 5 // Example 3: // >>> max_fill([[0, 0, 0], [0, 0, 0]], 5) // 0 // Constraints: // * all wells have the same length // * 1 <= grid.length <= 10^2 // * 1 <= grid[:,1].length <= 10^2 // * grid[i][j] -> 0 | 1 // * 1 <= capacity <= 10 function max_fill(grid, capacity){ var maxFill = 0; var sum = 0; var c = 1;
var c = grid[0].length; for(var i = 0; i < r; i++){ sum = 0; for(var j = 0; j < c; j++){ sum += grid[i][j]; } maxFill += Math.ceil(sum/capacity); } return maxFill; }
var r = grid.length;
const assert = require('node:assert'); function test() { let candidate = max_fill; assert.deepEqual(candidate([[0, 0, 1, 0], [0, 1, 0, 0], [1, 1, 1, 1]], 1),6); assert.deepEqual(candidate([[0, 0, 1, 1], [0, 0, 0, 0], [1, 1, 1, 1], [0, 1, 1, 1]], 2),5); assert.deepEqual(candidate([[0, 0, 0], [0, 0, 0]], 5),0); assert.deepEqual(candidate([[1, 1, 1, 1], [1, 1, 1, 1]], 2),4); assert.deepEqual(candidate([[1, 1, 1, 1], [1, 1, 1, 1]], 9),2); } test();
humaneval-HumanEval_138_is_equal_to_sum_even.json-L25
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_93_encode.json-L22
js
//Write a function that takes a message, and encodes in such a // way that it swaps case of all letters, replaces all vowels in // the message with the letter that appears 2 places ahead of that // vowel in the english alphabet. // Assume only letters. // Examples: // >>> encode("test") // "TGST" // >>> encode("This is a message") // "tHKS KS C MGSSCGG" function encode(message){ const vowels = "aeiou"; let result = ""; for(let i = 0; i < message.length; i++){ let letter = message[i]; if(vowels.includes(letter.toLowerCase())){ let newIndex = (letter.charCodeAt(0) + 2 - (letter.toLowerCase() === letter ? 'a'.charCodeAt(0) : 'A'.charCodeAt(0))) % 26; letter = String.fromCharCode(newIndex + (letter.toLowerCase() === letter ? 'a'.charCodeAt(0) : 'A'.charCodeAt(0))); } result += letter.toUpperCase() === letter ? letter.toLowerCase() : letter.toUpperCase(); }
}
return result;
const assert = require('node:assert'); function test() { let candidate = encode; assert.deepEqual(candidate("TEST"),"tgst"); assert.deepEqual(candidate("Mudasir"),"mWDCSKR"); assert.deepEqual(candidate("YES"),"ygs"); assert.deepEqual(candidate("This is a message"),"tHKS KS C MGSSCGG"); assert.deepEqual(candidate("I DoNt KnOw WhAt tO WrItE"),"k dQnT kNqW wHcT Tq wRkTg"); } test();
humaneval-HumanEval_153_Strongest_Extension.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 { // You will be given the name of a class (a string) and an array array list of extensions. // The extensions are to be used to load additional classes to the class. The // strength of the extension is as follows: Let CAP be the number of the uppercase // letters in the extension's name, and let SM be the number of lowercase letters // in the extension's name, the strength is given by the fraction CAP - SM. // You should find the strongest extension and return a string in this // format: ClassName.StrongestExtensionName. // If there are two or more extensions with the same strength, you should // choose the one that comes first in the array list. // For example, if you are given "Slices" as the class and an array array list of the // extensions: ['SErviNGSliCes', 'Cheese', 'StuFfed'] then you should // return 'Slices.SErviNGSliCes' since 'SErviNGSliCes' is the strongest extension // (its strength is -1). // Example: // >>> StrongestExtension(("my_class"), (new ArrayList<String>(Arrays.asList((String)"AA", (String)"Be", (String)"CC")))) // ("my_class.AA") public static String StrongestExtension(String class_name, ArrayList<String> extensions) { if (extensions.size() == 0) { return class_name; } int strength = Integer.MIN_VALUE;
for (String s : extensions) { int cap = (int)s.chars().filter(c -> Character.isUpperCase(c)).count(); int sm = (int)s.chars().filter(c -> Character.isLowerCase(c)).count(); int diff = cap - sm; if (diff > strength) { strength = diff; strongest = s; } } return class_name + "." + strongest; } }
String strongest = "";
} public static void main(String[] args) { assert(StrongestExtension(("Watashi"), (new ArrayList<String>(Arrays.asList((String)"tEN", (String)"niNE", (String)"eIGHt8OKe")))).equals(("Watashi.eIGHt8OKe"))); assert(StrongestExtension(("Boku123"), (new ArrayList<String>(Arrays.asList((String)"nani", (String)"NazeDa", (String)"YEs.WeCaNe", (String)"32145tggg")))).equals(("Boku123.YEs.WeCaNe"))); assert(StrongestExtension(("__YESIMHERE"), (new ArrayList<String>(Arrays.asList((String)"t", (String)"eMptY", (String)"nothing", (String)"zeR00", (String)"NuLl__", (String)"123NoooneB321")))).equals(("__YESIMHERE.NuLl__"))); assert(StrongestExtension(("K"), (new ArrayList<String>(Arrays.asList((String)"Ta", (String)"TAR", (String)"t234An", (String)"cosSo")))).equals(("K.TAR"))); assert(StrongestExtension(("__HAHA"), (new ArrayList<String>(Arrays.asList((String)"Tab", (String)"123", (String)"781345", (String)"-_-")))).equals(("__HAHA.123"))); assert(StrongestExtension(("YameRore"), (new ArrayList<String>(Arrays.asList((String)"HhAas", (String)"okIWILL123", (String)"WorkOut", (String)"Fails", (String)"-_-")))).equals(("YameRore.okIWILL123"))); assert(StrongestExtension(("finNNalLLly"), (new ArrayList<String>(Arrays.asList((String)"Die", (String)"NowW", (String)"Wow", (String)"WoW")))).equals(("finNNalLLly.WoW"))); assert(StrongestExtension(("_"), (new ArrayList<String>(Arrays.asList((String)"Bb", (String)"91245")))).equals(("_.Bb"))); assert(StrongestExtension(("Sp"), (new ArrayList<String>(Arrays.asList((String)"671235", (String)"Bb")))).equals(("Sp.671235"))); } }
humaneval-HumanEval_36_fizz_buzz.json-L13
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('');
if(arr[j] === '7'){ result++; } } } } return result; }
for(let j = 0; j < arr.length; j++){
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_139_special_factorial.json-L19
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;
long local_result = 1; long temp = n; while (temp > 0) { local_result *= temp; temp--; } result *= local_result; n--; } return result; } }
while (n > 0) {
} public static void main(String[] args) { assert(specialFactorial((4l)) == (288l)); assert(specialFactorial((5l)) == (34560l)); assert(specialFactorial((7l)) == (125411328000l)); assert(specialFactorial((1l)) == (1l)); } }
humaneval-HumanEval_156_int_to_mini_roman.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 a positive integer, obtain its roman numeral equivalent as a string, // and return it in lowercase. // Restrictions: 1 <= num <= 1000 // Examples: // >>> intToMiniRoman((19l)) // ("xix") // >>> intToMiniRoman((152l)) // ("clii") // >>> intToMiniRoman((426l)) // ("cdxxvi") public static String intToMiniRoman(long number) { int num = (int) number; String res = ""; if (num == 0)
while (num >= 1000) { res += "m"; num -= 1000; } if (num >= 900) { res += "cm"; num -= 900; } if (num >= 500) { res += "d"; num -= 500; } if (num >= 400) { res += "cd"; num -= 400; } while (num >= 100) { res += "c"; num -= 100; } if (num >= 90) { res += "xc"; num -= 90; } if (num >= 50) { res += "l"; num -= 50; } if (num >= 40) { res += "xl"; num -= 40; } while (num >= 10) { res += "x"; num -= 10; } if (num >= 9) { res += "ix"; num -= 9; } if (num >= 5) { res += "v"; num -= 5; } if (num >= 4) { res += "iv"; num -= 4; } while (num >= 1) { res += "i"; num -= 1; } return res; } }
return "";
} public static void main(String[] args) { assert(intToMiniRoman((19l)).equals(("xix"))); assert(intToMiniRoman((152l)).equals(("clii"))); assert(intToMiniRoman((251l)).equals(("ccli"))); assert(intToMiniRoman((426l)).equals(("cdxxvi"))); assert(intToMiniRoman((500l)).equals(("d"))); assert(intToMiniRoman((1l)).equals(("i"))); assert(intToMiniRoman((4l)).equals(("iv"))); assert(intToMiniRoman((43l)).equals(("xliii"))); assert(intToMiniRoman((90l)).equals(("xc"))); assert(intToMiniRoman((94l)).equals(("xciv"))); assert(intToMiniRoman((532l)).equals(("dxxxii"))); assert(intToMiniRoman((900l)).equals(("cm"))); assert(intToMiniRoman((994l)).equals(("cmxciv"))); assert(intToMiniRoman((1000l)).equals(("m"))); } }
humaneval-HumanEval_155_even_odd_count.json-L17
py
from typing import Tuple def even_odd_count(num: int) -> Tuple[int, int]: """Given an integer. return a tuple that has the number of even and odd digits respectively. Example: >>> even_odd_count(-12) (1, 1) >>> even_odd_count(123) (1, 2) """ num_str = str(abs(num)) even_count = 0 odd_count = 0 for ch in num_str: digit = int(ch)
even_count += 1 else: odd_count += 1 return even_count, odd_count
if digit % 2 == 0:
def check(candidate): assert candidate(7) == (0, 1) assert candidate(-78) == (1, 1) assert candidate(3452) == (2, 2) assert candidate(346211) == (3, 3) assert candidate(-345821) == (3, 3) assert candidate(-2) == (1, 0) assert candidate(-45347) == (2, 3) assert candidate(0) == (1, 0) def test_check(): check(even_odd_count) test_check()
humaneval-HumanEval_153_Strongest_Extension.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 will be given the name of a class (a string) and an array array list of extensions. // The extensions are to be used to load additional classes to the class. The // strength of the extension is as follows: Let CAP be the number of the uppercase // letters in the extension's name, and let SM be the number of lowercase letters // in the extension's name, the strength is given by the fraction CAP - SM. // You should find the strongest extension and return a string in this // format: ClassName.StrongestExtensionName. // If there are two or more extensions with the same strength, you should // choose the one that comes first in the array list. // For example, if you are given "Slices" as the class and an array array list of the // extensions: ['SErviNGSliCes', 'Cheese', 'StuFfed'] then you should // return 'Slices.SErviNGSliCes' since 'SErviNGSliCes' is the strongest extension // (its strength is -1). // Example: // >>> StrongestExtension(("my_class"), (new ArrayList<String>(Arrays.asList((String)"AA", (String)"Be", (String)"CC")))) // ("my_class.AA") public static String StrongestExtension(String class_name, ArrayList<String> extensions) { if (extensions.size() == 0) { return class_name; } int strength = Integer.MIN_VALUE; String strongest = ""; for (String s : extensions) { int cap = (int)s.chars().filter(c -> Character.isUpperCase(c)).count(); int sm = (int)s.chars().filter(c -> Character.isLowerCase(c)).count(); int diff = cap - sm; if (diff > strength) { strength = diff; strongest = s; } } return class_name + "." + strongest; }
}
} public static void main(String[] args) { assert(StrongestExtension(("Watashi"), (new ArrayList<String>(Arrays.asList((String)"tEN", (String)"niNE", (String)"eIGHt8OKe")))).equals(("Watashi.eIGHt8OKe"))); assert(StrongestExtension(("Boku123"), (new ArrayList<String>(Arrays.asList((String)"nani", (String)"NazeDa", (String)"YEs.WeCaNe", (String)"32145tggg")))).equals(("Boku123.YEs.WeCaNe"))); assert(StrongestExtension(("__YESIMHERE"), (new ArrayList<String>(Arrays.asList((String)"t", (String)"eMptY", (String)"nothing", (String)"zeR00", (String)"NuLl__", (String)"123NoooneB321")))).equals(("__YESIMHERE.NuLl__"))); assert(StrongestExtension(("K"), (new ArrayList<String>(Arrays.asList((String)"Ta", (String)"TAR", (String)"t234An", (String)"cosSo")))).equals(("K.TAR"))); assert(StrongestExtension(("__HAHA"), (new ArrayList<String>(Arrays.asList((String)"Tab", (String)"123", (String)"781345", (String)"-_-")))).equals(("__HAHA.123"))); assert(StrongestExtension(("YameRore"), (new ArrayList<String>(Arrays.asList((String)"HhAas", (String)"okIWILL123", (String)"WorkOut", (String)"Fails", (String)"-_-")))).equals(("YameRore.okIWILL123"))); assert(StrongestExtension(("finNNalLLly"), (new ArrayList<String>(Arrays.asList((String)"Die", (String)"NowW", (String)"Wow", (String)"WoW")))).equals(("finNNalLLly.WoW"))); assert(StrongestExtension(("_"), (new ArrayList<String>(Arrays.asList((String)"Bb", (String)"91245")))).equals(("_.Bb"))); assert(StrongestExtension(("Sp"), (new ArrayList<String>(Arrays.asList((String)"671235", (String)"Bb")))).equals(("Sp.671235"))); } }
humaneval-HumanEval_107_even_odd_palindrome.json-L27
js
//Given a positive integer n, return an array that has the number of even and odd // integer palindromes that fall within the range(1, n), inclusive. // Example 1: // >>> even_odd_palindrome(3) // [1, 2] // Explanation: // Integer palindrome are 1, 2, 3. one of them is even, and two of them are odd. // Example 2: // >>> even_odd_palindrome(12) // [4, 6] // Explanation: // Integer palindrome are 1, 2, 3, 4, 5, 6, 7, 8, 9, 11. four of them are even, and 6 of them are odd. // Note: // 1. 1 <= n <= 10^3 // 2. returned array has the number of even and odd integer palindromes respectively. function even_odd_palindrome(n){ var pal = []; var isPalindrome = function(x){ var y = x.toString().split('').reverse().join(''); return y == x; } for(var i = 1; i <= n; i++){ if(isPalindrome(i)){ pal.push(i); } }
var even = 0; for(var i = 0; i < pal.length; i++){ if(pal[i] % 2 == 0){ even++; } else{ odd++; } } return [even, odd]; }
var odd = 0;
const assert = require('node:assert'); function test() { let candidate = even_odd_palindrome; assert.deepEqual(candidate(123),[8, 13]); assert.deepEqual(candidate(12),[4, 6]); assert.deepEqual(candidate(3),[1, 2]); assert.deepEqual(candidate(63),[6, 8]); assert.deepEqual(candidate(25),[5, 6]); assert.deepEqual(candidate(19),[4, 6]); assert.deepEqual(candidate(9),[4, 5]); assert.deepEqual(candidate(1),[0, 1]); } test();
humaneval-HumanEval_138_is_equal_to_sum_even.json-L33
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; if (n % 2 == 1) { 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--; }
minX = x + 1; } else if (2 * x + y > n) { maxX = x - 1; } else { return true; } } return false; } }
if (2 * x + y < n) {
} 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_120_maximum.json-L39
py
from typing import List def maximum(arr: List[int], k: int) -> List[int]: """ Given an array arr of integers and a positive integer k, return a sorted list of length k with the maximum k numbers in arr. Example 1: >>> maximum([-3, -4, 5], 3) [-4, -3, 5] Example 2: >>> maximum([4, -4, 4], 2) [4, 4] Example 3: >>> maximum([-3, 2, 1, 2, -1, -2, 1], 1) [2] Note: 1. The length of the array will be in the range of [1, 1000]. 2. The elements in the array will be in the range of [-1000, 1000]. 3. 0 <= k <= len(arr) """ def get_max(arr: List[int], k: int) -> List[int]: """ Returns the maximum k numbers in the given array """ if k == 0: return [] elif k == 1: return [max(arr)] else: max_num = max(arr) arr.remove(max_num)
return sorted(get_max(arr, k))
return [max_num] + get_max(arr, k - 1)
def check(candidate): assert candidate([-3, -4, 5], 3) == [-4, -3, 5] assert candidate([4, -4, 4], 2) == [4, 4] assert candidate([-3, 2, 1, 2, -1, -2, 1], 1) == [2] assert candidate([123, -123, 20, 0, 1, 2, -3], 3) == [2, 20, 123] assert candidate([-123, 20, 0, 1, 2, -3], 4) == [0, 1, 2, 20] assert candidate([5, 15, 0, 3, -13, -8, 0], 7) == [-13, -8, 0, 0, 3, 5, 15] assert candidate([-1, 0, 2, 5, 3, -10], 2) == [3, 5] assert candidate([1, 0, 5, -7], 1) == [5] assert candidate([4, -4], 2) == [-4, 4] assert candidate([-10, 10], 2) == [-10, 10] assert candidate([1, 2, 3, -23, 243, -400, 0], 0) == [] def test_check(): check(maximum) test_check()
humaneval-HumanEval_39_prime_fib.json-L41
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 fibNum = 0; while(res < n){ if(isPrime(fib(fibNum))){ res++; } fibNum++; } return fib(fibNum - 1); }
var res = 0;
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_106_f.json-L16
js
//Implement the function f that takes n as a parameter, // and returns an array of size n, such that the value of the element at index i is the factorial of i if i is even // or the sum of numbers from 1 to i otherwise. // i starts from 1. // the factorial of i is the multiplication of the numbers from 1 to i (1 * 2 * ... * i). // Example: // >>> f(5) // [1, 2, 6, 24, 15] function f(n){ var result = []; var sum = 0; var factorial = 1; for(var i = 1; i <= n; i++){ if(i % 2 == 0){ for(var j = 1; j <= i; j++){
} result.push(factorial); factorial = 1; }else{ for(var k = 1; k <= i; k++){ sum += k; } result.push(sum); sum = 0; } } return result; }
factorial *= j;
const assert = require('node:assert'); function test() { let candidate = f; assert.deepEqual(candidate(5),[1, 2, 6, 24, 15]); assert.deepEqual(candidate(7),[1, 2, 6, 24, 15, 720, 28]); assert.deepEqual(candidate(1),[1]); assert.deepEqual(candidate(3),[1, 2, 6]); } test();
humaneval-HumanEval_119_match_parens.json-L16
js
//You are given an array of two strings, both strings consist of open // parentheses '(' or close parentheses ')' only. // Your job is to check if it is possible to concatenate the two strings in // some order, that the resulting string will be good. // A string S is considered to be good if and only if all parentheses in S // are balanced. For example: the string '(())()' is good, while the string // '())' is not. // Return 'Yes' if there's a way to make a good string, and return 'No' otherwise. // Examples: // >>> match_parens(["()(", ")"]) // "Yes" // >>> match_parens([")", ")"]) // "No" function match_parens(lst){ const open = '(';
const is_good = (s) => { let stack = []; for (let p of s){ if (p === open){ stack.push(p); } else if (p === close){ if (stack.length === 0){ return false; } stack.pop(); } } return stack.length === 0; }; const str1 = lst[0]; const str2 = lst[1]; if (is_good(str1 + str2)){ return 'Yes'; } if (is_good(str2 + str1)){ return 'Yes'; } return 'No'; }
const close = ')';
const assert = require('node:assert'); function test() { let candidate = match_parens; assert.deepEqual(candidate(["()(", ")"]),"Yes"); assert.deepEqual(candidate([")", ")"]),"No"); assert.deepEqual(candidate(["(()(())", "())())"]),"No"); assert.deepEqual(candidate([")())", "(()()("]),"Yes"); assert.deepEqual(candidate(["(())))", "(()())(("]),"Yes"); assert.deepEqual(candidate(["()", "())"]),"No"); assert.deepEqual(candidate(["(()(", "()))()"]),"Yes"); assert.deepEqual(candidate(["((((", "((())"]),"No"); assert.deepEqual(candidate([")(()", "(()("]),"No"); assert.deepEqual(candidate([")(", ")("]),"No"); assert.deepEqual(candidate(["(", ")"]),"Yes"); assert.deepEqual(candidate([")", "("]),"Yes"); } test();
humaneval-HumanEval_48_is_palindrome.json-L13
py
def is_palindrome(text: str) -> bool: """ Checks if given string is a palindrome >>> is_palindrome('') True >>> is_palindrome('aba') True >>> is_palindrome('aaaaa') True >>> is_palindrome('zbcd') False """
for i in range(length): if text[i] != text[-i - 1]: return False return True
length = len(text)
def check(candidate): assert candidate('') == True assert candidate('aba') == True assert candidate('aaaaa') == True assert candidate('zbcd') == False assert candidate('xywyx') == True assert candidate('xywyz') == False assert candidate('xywzx') == False def test_check(): check(is_palindrome) test_check()
humaneval-HumanEval_154_cycpattern_check.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 { // You are given 2 words. You need to return true if the second word or any of its rotations is a substring in the first word // >>> cycpatternCheck(("abcd"), ("abd")) // (false) // >>> cycpatternCheck(("hello"), ("ell")) // (true) // >>> cycpatternCheck(("whassup"), ("psus")) // (false) // >>> cycpatternCheck(("abab"), ("baa")) // (true) // >>> cycpatternCheck(("efef"), ("eeff")) // (false) // >>> cycpatternCheck(("himenss"), ("simen")) // (true) public static boolean cycpatternCheck(String a, String b) { int len = b.length();
for (int i = 0; i < len; i++) { b = b.substring(1) + b.charAt(0); found = a.contains(b); if (found) break; } return found; } }
boolean found = false;
} public static void main(String[] args) { assert(cycpatternCheck(("xyzw"), ("xyw")) == (false)); assert(cycpatternCheck(("yello"), ("ell")) == (true)); assert(cycpatternCheck(("whattup"), ("ptut")) == (false)); assert(cycpatternCheck(("efef"), ("fee")) == (true)); assert(cycpatternCheck(("abab"), ("aabb")) == (false)); assert(cycpatternCheck(("winemtt"), ("tinem")) == (true)); } }
humaneval-HumanEval_126_is_sorted.json-L40
js
//Given an array of numbers, return whether or not they are sorted // in ascending order. If array has more than 1 duplicate of the same // number, return false. Assume no negative numbers and only integers. // Examples // >>> is_sorted([5]) // true // >>> is_sorted([1, 2, 3, 4, 5]) // true // >>> is_sorted([1, 3, 2, 4, 5]) // false // >>> is_sorted([1, 2, 3, 4, 5, 6]) // true // >>> is_sorted([1, 2, 3, 4, 5, 6, 7]) // true // >>> is_sorted([1, 3, 2, 4, 5, 6, 7]) // false // >>> is_sorted([1, 2, 2, 3, 3, 4]) // true // >>> is_sorted([1, 2, 2, 2, 3, 4]) // false function is_sorted(lst){ var last = null; var dupe_found = false; for (var x of lst){ if (last == null){ last = x; } else if (x < last){ return false; } else if (x == last){ if (dupe_found){ return false; } else { dupe_found = true; } } else { last = x; dupe_found = false; } }
}
return true;
const assert = require('node:assert'); function test() { let candidate = is_sorted; assert.deepEqual(candidate([5]),true); assert.deepEqual(candidate([1, 2, 3, 4, 5]),true); assert.deepEqual(candidate([1, 3, 2, 4, 5]),false); assert.deepEqual(candidate([1, 2, 3, 4, 5, 6]),true); assert.deepEqual(candidate([1, 2, 3, 4, 5, 6, 7]),true); assert.deepEqual(candidate([1, 3, 2, 4, 5, 6, 7]),false); assert.deepEqual(candidate([]),true); assert.deepEqual(candidate([1]),true); assert.deepEqual(candidate([3, 2, 1]),false); assert.deepEqual(candidate([1, 2, 2, 2, 3, 4]),false); assert.deepEqual(candidate([1, 2, 3, 3, 3, 4]),false); assert.deepEqual(candidate([1, 2, 2, 3, 3, 4]),true); assert.deepEqual(candidate([1, 2, 3, 4]),true); } test();
humaneval-HumanEval_61_correct_bracketing.json-L23
js
//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 function correct_bracketing(brackets){ var opens = []; for (var i = 0; i < brackets.length; i++){ if (brackets[i] == "("){ opens.push(brackets[i]); } else if (brackets[i] == ")"){ if (opens.length > 0){ opens.pop(); } else { return false;
} } if (opens.length == 0){ return true; } else { return false; } }
}
const assert = require('node:assert'); function test() { let candidate = correct_bracketing; assert.deepEqual(candidate("()"),true); assert.deepEqual(candidate("(()())"),true); assert.deepEqual(candidate("()()(()())()"),true); assert.deepEqual(candidate("()()((()()())())(()()(()))"),true); assert.deepEqual(candidate("((()())))"),false); assert.deepEqual(candidate(")(()"),false); assert.deepEqual(candidate("("),false); assert.deepEqual(candidate("(((("),false); assert.deepEqual(candidate(")"),false); assert.deepEqual(candidate("(()"),false); assert.deepEqual(candidate("()()(()())())(()"),false); assert.deepEqual(candidate("()()(()())()))()"),false); } test();
humaneval-HumanEval_1_separate_paren_groups.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 { // 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 list of those. // Separate groups are balanced (each open brace is properly closed) and not nested within each other // Ignore any spaces in the input string. // >>> separateParenGroups(("( ) (( )) (( )( ))")) // (new ArrayList<String>(Arrays.asList((String)"()", (String)"(())", (String)"(()())"))) public static ArrayList<String> separateParenGroups(String paren_string) { ArrayList<String> output = new ArrayList<String>(); StringBuffer temp = new StringBuffer(); int open_paren = 0; for (int i = 0; i < paren_string.length(); i++) { char c = paren_string.charAt(i); if (c == '(') { if (open_paren == 0) { temp = new StringBuffer(); } open_paren++; temp.append(c); } else if (c == ')') { open_paren--; temp.append(c); if (open_paren == 0) { output.add(temp.toString()); } } }
} }
return output;
} public static void main(String[] args) { assert(separateParenGroups(("(()()) ((())) () ((())()())")).equals((new ArrayList<String>(Arrays.asList((String)"(()())", (String)"((()))", (String)"()", (String)"((())()())"))))); assert(separateParenGroups(("() (()) ((())) (((())))")).equals((new ArrayList<String>(Arrays.asList((String)"()", (String)"(())", (String)"((()))", (String)"(((())))"))))); assert(separateParenGroups(("(()(())((())))")).equals((new ArrayList<String>(Arrays.asList((String)"(()(())((())))"))))); assert(separateParenGroups(("( ) (( )) (( )( ))")).equals((new ArrayList<String>(Arrays.asList((String)"()", (String)"(())", (String)"(()())"))))); } }
humaneval-HumanEval_20_find_closest_elements.json-L18
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]) temp_index, temp2_index = 0, 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)):
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]))
if abs(numbers[i] - numbers[j]) < temp:
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_31_is_prime.json-L29
js
//Return true if a given number is prime, and false otherwise. // >>> is_prime(6) // false // >>> is_prime(101) // true // >>> is_prime(11) // true // >>> is_prime(13441) // true // >>> is_prime(61) // true // >>> is_prime(4) // false // >>> is_prime(1) // false function is_prime(n){ if (n==1) { return false; } if (n==2) { return true; } if (n%2==0) { return false; }
for (var i = 3; i <= limit; i += 2) { if (n%i==0) { return false; } } return true; }
var limit = Math.sqrt(n);
const assert = require('node:assert'); function test() { let candidate = is_prime; assert.deepEqual(candidate(6),false); assert.deepEqual(candidate(101),true); assert.deepEqual(candidate(11),true); assert.deepEqual(candidate(13441),true); assert.deepEqual(candidate(61),true); assert.deepEqual(candidate(4),false); assert.deepEqual(candidate(1),false); assert.deepEqual(candidate(5),true); assert.deepEqual(candidate(11),true); assert.deepEqual(candidate(17),true); assert.deepEqual(candidate(85),false); assert.deepEqual(candidate(77),false); assert.deepEqual(candidate(255379),false); } test();
humaneval-HumanEval_156_int_to_mini_roman.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 positive integer, obtain its roman numeral equivalent as a string, // and return it in lowercase. // Restrictions: 1 <= num <= 1000 // Examples: // >>> intToMiniRoman((19l)) // ("xix") // >>> intToMiniRoman((152l)) // ("clii") // >>> intToMiniRoman((426l)) // ("cdxxvi") public static String intToMiniRoman(long number) { int num = (int) number; String res = ""; if (num == 0) return ""; while (num >= 1000) { res += "m"; num -= 1000; }
res += "cm"; num -= 900; } if (num >= 500) { res += "d"; num -= 500; } if (num >= 400) { res += "cd"; num -= 400; } while (num >= 100) { res += "c"; num -= 100; } if (num >= 90) { res += "xc"; num -= 90; } if (num >= 50) { res += "l"; num -= 50; } if (num >= 40) { res += "xl"; num -= 40; } while (num >= 10) { res += "x"; num -= 10; } if (num >= 9) { res += "ix"; num -= 9; } if (num >= 5) { res += "v"; num -= 5; } if (num >= 4) { res += "iv"; num -= 4; } while (num >= 1) { res += "i"; num -= 1; } return res; } }
if (num >= 900) {
} public static void main(String[] args) { assert(intToMiniRoman((19l)).equals(("xix"))); assert(intToMiniRoman((152l)).equals(("clii"))); assert(intToMiniRoman((251l)).equals(("ccli"))); assert(intToMiniRoman((426l)).equals(("cdxxvi"))); assert(intToMiniRoman((500l)).equals(("d"))); assert(intToMiniRoman((1l)).equals(("i"))); assert(intToMiniRoman((4l)).equals(("iv"))); assert(intToMiniRoman((43l)).equals(("xliii"))); assert(intToMiniRoman((90l)).equals(("xc"))); assert(intToMiniRoman((94l)).equals(("xciv"))); assert(intToMiniRoman((532l)).equals(("dxxxii"))); assert(intToMiniRoman((900l)).equals(("cm"))); assert(intToMiniRoman((994l)).equals(("cmxciv"))); assert(intToMiniRoman((1000l)).equals(("m"))); } }
humaneval-HumanEval_95_check_dict_case.json-L38
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; } }
if (key != key.toLowerCase()){ return false; } } } else{ return false; } } return true; }
else if (case_type == 0){
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_129_minPath.json-L42
py
from typing import List def minPath(grid: List[List[int]], k: int) -> List[int]: """ Given a grid with N rows and N columns (N >= 2) and a positive integer k, each cell of the grid contains a value. Every integer in the range [1, N * N] inclusive appears exactly once on the cells of the grid. You have to find the minimum path of length k in the grid. You can start from any cell, and in each step you can move to any of the neighbor cells, in other words, you can go to cells which share an edge with you current cell. Please note that a path of length k means visiting exactly k cells (not necessarily distinct). You CANNOT go off the grid. A path A (of length k) is considered less than a path B (of length k) if after making the ordered lists of the values on the cells that A and B go through (let's call them lst_A and lst_B), lst_A is lexicographically less than lst_B, in other words, there exist an integer index i (1 <= i <= k) such that lst_A[i] < lst_B[i] and for any j (1 <= j < i) we have lst_A[j] = lst_B[j]. It is guaranteed that the answer is unique. Return an ordered list of the values on the cells that the minimum path go through. Examples: >>> minPath([[1, 2, 3], [4, 5, 6], [7, 8, 9]], 3) [1, 2, 1] >>> minPath([[5, 9, 3], [4, 1, 6], [7, 8, 2]], 1) [1] """ min_val = float('inf') for i in range(len(grid)): for j in range(len(grid[0])): if grid[i][j] < min_val: min_val = grid[i][j] row = i col = j path = [min_val] while len(path) < k: min_val = float('inf')
if 0 <= i < len(grid) and 0 <= j < len(grid[0]) and grid[i][j] < min_val: min_val = grid[i][j] row = i col = j path.append(min_val) return path
for i, j in (row - 1, col), (row + 1, col), (row, col - 1), (row, col + 1):
def check(candidate): assert candidate([[1, 2, 3], [4, 5, 6], [7, 8, 9]], 3) == [1, 2, 1] assert candidate([[5, 9, 3], [4, 1, 6], [7, 8, 2]], 1) == [1] assert candidate([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]], 4) == [1, 2, 1, 2] assert candidate([[6, 4, 13, 10], [5, 7, 12, 1], [3, 16, 11, 15], [8, 14, 9, 2]], 7) == [1, 10, 1, 10, 1, 10, 1] assert candidate([[8, 14, 9, 2], [6, 4, 13, 15], [5, 7, 1, 12], [3, 10, 11, 16]], 5) == [1, 7, 1, 7, 1] assert candidate([[11, 8, 7, 2], [5, 16, 14, 4], [9, 3, 15, 6], [12, 13, 10, 1]], 9) == [1, 6, 1, 6, 1, 6, 1, 6, 1] assert candidate([[12, 13, 10, 1], [9, 3, 15, 6], [5, 16, 14, 4], [11, 8, 7, 2]], 12) == [1, 6, 1, 6, 1, 6, 1, 6, 1, 6, 1, 6] assert candidate([[2, 7, 4], [3, 1, 5], [6, 8, 9]], 8) == [1, 3, 1, 3, 1, 3, 1, 3] assert candidate([[6, 1, 5], [3, 8, 9], [2, 7, 4]], 8) == [1, 5, 1, 5, 1, 5, 1, 5] assert candidate([[1, 2], [3, 4]], 10) == [1, 2, 1, 2, 1, 2, 1, 2, 1, 2] assert candidate([[1, 3], [3, 2]], 10) == [1, 3, 1, 3, 1, 3, 1, 3, 1, 3] def test_check(): check(minPath) test_check()
humaneval-HumanEval_105_by_length.json-L26
py
from typing import List def by_length(arr: List[int]) -> List[str]: """ 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'] """ digits = [x for x in arr if 1 <= x <= 9] digits.sort() digits.reverse() for i in range(len(digits)): digits[i] = ['One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine'][digits[i] - 1]
return digits
def check(candidate): assert candidate([2, 1, 1, 4, 5, 8, 2, 3]) == ['Eight', 'Five', 'Four', 'Three', 'Two', 'Two', 'One', 'One'] assert candidate([]) == [] assert candidate([1, -1, 55]) == ['One'] assert candidate([1, -1, 3, 2]) == ['Three', 'Two', 'One'] assert candidate([9, 4, 8]) == ['Nine', 'Eight', 'Four'] def test_check(): check(by_length) test_check()
humaneval-HumanEval_142_sum_squares.json-L14
js
//" // This function will take an array of integers. For all entries in the array, the function shall square the integer entry if its index is a // multiple of 3 and will cube the integer entry if its index is a multiple of 4 and not a multiple of 3. The function will not // change the entries in the array whose indexes are not a multiple of 3 or 4. The function shall then return the sum of all entries. // Examples: // >>> lst // [1, 2, 3] // >>> lst // [] // >>> lst // [-1, -5, 2, -1, -5] function sum_squares(lst){ var sum = 0;
for (var i = 0; i < len; i++){ if (i % 3 == 0){ sum += lst[i]*lst[i]; } else if (i % 4 == 0){ sum += lst[i]*lst[i]*lst[i]; } else { sum += lst[i]; } } return sum; }
var len = lst.length;
const assert = require('node:assert'); function test() { let candidate = sum_squares; assert.deepEqual(candidate([1, 2, 3]),6); assert.deepEqual(candidate([1, 4, 9]),14); assert.deepEqual(candidate([]),0); assert.deepEqual(candidate([1, 1, 1, 1, 1, 1, 1, 1, 1]),9); assert.deepEqual(candidate([-1, -1, -1, -1, -1, -1, -1, -1, -1]),-3); assert.deepEqual(candidate([0]),0); assert.deepEqual(candidate([-1, -5, 2, -1, -5]),-126); assert.deepEqual(candidate([-56, -99, 1, 0, -2]),3030); assert.deepEqual(candidate([-1, 0, 0, 0, 0, 0, 0, 0, -1]),0); assert.deepEqual(candidate([-16, -9, -2, 36, 36, 26, -20, 25, -40, 20, -4, 12, -26, 35, 37]),-14196); assert.deepEqual(candidate([-1, -3, 17, -1, -15, 13, -1, 14, -14, -12, -5, 14, -14, 6, 13, 11, 16, 16, 4, 10]),-1448); } test();
humaneval-HumanEval_112_reverse_delete.json-L22
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 = []; if (filterString === filterStringReverse) { result.push(filterString, true); } else { result.push(filterString, false);
return result; }
}
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_98_count_upper.json-L19
js
//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 function count_upper(s){ var index; var result = 0; var vowel = ['A', 'E', 'I', 'O', 'U']; for (index = 0; index < s.length; index += 2){ if (vowel.indexOf(s[index]) > -1){ result += 1; } } return result;
}
const assert = require('node:assert'); function test() { let candidate = count_upper; assert.deepEqual(candidate("aBCdEf"),1); assert.deepEqual(candidate("abcdefg"),0); assert.deepEqual(candidate("dBBE"),0); assert.deepEqual(candidate("B"),0); assert.deepEqual(candidate("U"),1); assert.deepEqual(candidate(""),0); assert.deepEqual(candidate("EEEE"),2); } test();
humaneval-HumanEval_137_compare_one.json-L34
js
//Create a function that takes integers, floats, or strings representing // real numbers, and returns the larger variable in its given variable type. // Return undefined 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) // undefined function compare_one(a, b){ if (typeof a === typeof b){ if (a > b) { return a; } else if (a < b) { return b; } else { return undefined; } } else if (typeof a === "string" && typeof b === "number"){ if (a[0] > b){ return a; } else if (a[0] < b){ return b; } else { return undefined; } } else if (typeof a === "number" && typeof b === "string"){ if (a > b[0]){
} else if (a < b[0]){ return b; } else { return undefined; } } }
return a;
const assert = require('node:assert'); function test() { let candidate = compare_one; assert.deepEqual(candidate(1, 2),2); assert.deepEqual(candidate(1, 2.5),2.5); assert.deepEqual(candidate(2, 3),3); assert.deepEqual(candidate(5, 6),6); assert.deepEqual(candidate(1, "2,3"),"2,3"); assert.deepEqual(candidate("5,1", "6"),"6"); assert.deepEqual(candidate("1", "2"),"2"); assert.deepEqual(candidate("1", 1),undefined); } test();
humaneval-HumanEval_158_find_max.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 { // 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_61_correct_bracketing.json-L19
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 == ')':
if count < 0: return False return count == 0
count -= 1
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_43_pairs_sum_to_zero.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 { // pairs_sum_to_zero takes an array array list of integers as an input. // it returns true if there are two distinct elements in the array list that // sum to zero, and false otherwise. // >>> pairsSumToZero((new ArrayList<Long>(Arrays.asList((long)1l, (long)3l, (long)5l, (long)0l)))) // (false) // >>> pairsSumToZero((new ArrayList<Long>(Arrays.asList((long)1l, (long)3l, (long)-2l, (long)1l)))) // (false) // >>> pairsSumToZero((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)7l)))) // (false) // >>> pairsSumToZero((new ArrayList<Long>(Arrays.asList((long)2l, (long)4l, (long)-5l, (long)3l, (long)5l, (long)7l)))) // (true) // >>> pairsSumToZero((new ArrayList<Long>(Arrays.asList((long)1l)))) // (false) public static boolean pairsSumToZero(ArrayList<Long> l) { for (int i = 0; i < l.size(); i++) { for (int j = i + 1; j < l.size(); j++) { if (l.get(i) + l.get(j) == 0) {
} } } return false; } }
return true;
} public static void main(String[] args) { assert(pairsSumToZero((new ArrayList<Long>(Arrays.asList((long)1l, (long)3l, (long)5l, (long)0l)))) == (false)); assert(pairsSumToZero((new ArrayList<Long>(Arrays.asList((long)1l, (long)3l, (long)-2l, (long)1l)))) == (false)); assert(pairsSumToZero((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)7l)))) == (false)); assert(pairsSumToZero((new ArrayList<Long>(Arrays.asList((long)2l, (long)4l, (long)-5l, (long)3l, (long)5l, (long)7l)))) == (true)); assert(pairsSumToZero((new ArrayList<Long>(Arrays.asList((long)1l)))) == (false)); assert(pairsSumToZero((new ArrayList<Long>(Arrays.asList((long)-3l, (long)9l, (long)-1l, (long)3l, (long)2l, (long)30l)))) == (true)); assert(pairsSumToZero((new ArrayList<Long>(Arrays.asList((long)-3l, (long)9l, (long)-1l, (long)3l, (long)2l, (long)31l)))) == (true)); assert(pairsSumToZero((new ArrayList<Long>(Arrays.asList((long)-3l, (long)9l, (long)-1l, (long)4l, (long)2l, (long)30l)))) == (false)); assert(pairsSumToZero((new ArrayList<Long>(Arrays.asList((long)-3l, (long)9l, (long)-1l, (long)4l, (long)2l, (long)31l)))) == (false)); } }
humaneval-HumanEval_137_compare_one.json-L58
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: 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(',', '.')
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
if float(a_tmp) > b:
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_148_bf.json-L35
js
//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 an array 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 array 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"] function bf(planet1, planet2){ var planets = { 'Mercury':1, 'Venus':2, 'Earth':3, 'Mars':4, 'Jupiter':5, 'Saturn':6, 'Uranus':7, 'Neptune':8 } if(!planets[planet1] || !planets[planet2]){ return []; } var keys = Object.keys(planets); var position1 = keys.indexOf(planet1); var position2 = keys.indexOf(planet2); if(position1 > position2){
position1 = position2; position2 = temp; } var res = []; for(var i = position1 + 1; i < position2; i++){ res.push(keys[i]); } return res; }
var temp = position1;
const assert = require('node:assert'); function test() { let candidate = bf; assert.deepEqual(candidate("Jupiter", "Neptune"),["Saturn", "Uranus"]); assert.deepEqual(candidate("Earth", "Mercury"),["Venus"]); assert.deepEqual(candidate("Mercury", "Uranus"),["Venus", "Earth", "Mars", "Jupiter", "Saturn"]); assert.deepEqual(candidate("Neptune", "Venus"),["Earth", "Mars", "Jupiter", "Saturn", "Uranus"]); assert.deepEqual(candidate("Earth", "Earth"),[]); assert.deepEqual(candidate("Mars", "Earth"),[]); assert.deepEqual(candidate("Jupiter", "Makemake"),[]); } test();
humaneval-HumanEval_156_int_to_mini_roman.json-L45
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 positive integer, obtain its roman numeral equivalent as a string, // and return it in lowercase. // Restrictions: 1 <= num <= 1000 // Examples: // >>> intToMiniRoman((19l)) // ("xix") // >>> intToMiniRoman((152l)) // ("clii") // >>> intToMiniRoman((426l)) // ("cdxxvi") public static String intToMiniRoman(long number) { int num = (int) number; String res = ""; if (num == 0) return ""; while (num >= 1000) { res += "m"; num -= 1000; } if (num >= 900) { res += "cm"; num -= 900; } if (num >= 500) { res += "d"; num -= 500; } if (num >= 400) { res += "cd"; num -= 400; } while (num >= 100) { res += "c"; num -= 100; } if (num >= 90) {
num -= 90; } if (num >= 50) { res += "l"; num -= 50; } if (num >= 40) { res += "xl"; num -= 40; } while (num >= 10) { res += "x"; num -= 10; } if (num >= 9) { res += "ix"; num -= 9; } if (num >= 5) { res += "v"; num -= 5; } if (num >= 4) { res += "iv"; num -= 4; } while (num >= 1) { res += "i"; num -= 1; } return res; } }
res += "xc";
} public static void main(String[] args) { assert(intToMiniRoman((19l)).equals(("xix"))); assert(intToMiniRoman((152l)).equals(("clii"))); assert(intToMiniRoman((251l)).equals(("ccli"))); assert(intToMiniRoman((426l)).equals(("cdxxvi"))); assert(intToMiniRoman((500l)).equals(("d"))); assert(intToMiniRoman((1l)).equals(("i"))); assert(intToMiniRoman((4l)).equals(("iv"))); assert(intToMiniRoman((43l)).equals(("xliii"))); assert(intToMiniRoman((90l)).equals(("xc"))); assert(intToMiniRoman((94l)).equals(("xciv"))); assert(intToMiniRoman((532l)).equals(("dxxxii"))); assert(intToMiniRoman((900l)).equals(("cm"))); assert(intToMiniRoman((994l)).equals(("cmxciv"))); assert(intToMiniRoman((1000l)).equals(("m"))); } }
humaneval-HumanEval_17_parse_music.json-L14
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 => {
song.push(4); }else if(s === 'o|'){ song.push(2); }else if(s === '.|'){ song.push(1); } }); return song; }
if(s === 'o'){
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_36_fizz_buzz.json-L20
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_160_do_algebra.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 { // 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("-")) list.add(-operand.get(i + 1));
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(); } }
else if (op.get(i).equals("*"))
} 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_9_rolling_max.json-L12
js
//From a given array of integers, generate an array of rolling maximum element found until given moment // in the sequence. // >>> rolling_max([1, 2, 3, 2, 3, 4, 2]) // [1, 2, 3, 3, 3, 4, 4] function rolling_max(numbers){ let max = []; let tempMax = 0; for(let i = 0; i < numbers.length; i++){ if(tempMax < numbers[i]){ tempMax = numbers[i]; }
} return max; }
max.push(tempMax);
const assert = require('node:assert'); function test() { let candidate = rolling_max; assert.deepEqual(candidate([]),[]); assert.deepEqual(candidate([1, 2, 3, 4]),[1, 2, 3, 4]); assert.deepEqual(candidate([4, 3, 2, 1]),[4, 4, 4, 4]); assert.deepEqual(candidate([3, 2, 3, 100, 3]),[3, 3, 3, 100, 100]); } test();
humaneval-HumanEval_40_triples_sum_to_zero.json-L23
js
//triples_sum_to_zero takes an array of integers as an input. // it returns true if there are three distinct elements in the array that // sum to zero, and false otherwise. // >>> triples_sum_to_zero([1, 3, 5, 0]) // false // >>> triples_sum_to_zero([1, 3, -2, 1]) // true // >>> triples_sum_to_zero([1, 2, 3, 7]) // false // >>> triples_sum_to_zero([2, 4, -5, 3, 9, 7]) // true // >>> triples_sum_to_zero([1]) // false function triples_sum_to_zero(l){ for (var i = 0; i < l.length; i++) { for (var j = 0; j < l.length; j++) { for (var k = 0; k < l.length; k++) { if (i !== j && i !== k && j !== k) { if (l[i] + l[j] + l[k] === 0) { return true; } }
} } return false; }
}
const assert = require('node:assert'); function test() { let candidate = triples_sum_to_zero; assert.deepEqual(candidate([1, 3, 5, 0]),false); assert.deepEqual(candidate([1, 3, 5, -1]),false); assert.deepEqual(candidate([1, 3, -2, 1]),true); assert.deepEqual(candidate([1, 2, 3, 7]),false); assert.deepEqual(candidate([1, 2, 5, 7]),false); assert.deepEqual(candidate([2, 4, -5, 3, 9, 7]),true); assert.deepEqual(candidate([1]),false); assert.deepEqual(candidate([1, 3, 5, -100]),false); assert.deepEqual(candidate([100, 3, 5, -100]),false); } test();
humaneval-HumanEval_46_fib4.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 { // 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((5l)) // (4l) // >>> fib4((6l)) // (8l) // >>> fib4((7l)) // (14l) public static long fib4(long n) { if (n == 0) return 0; if (n == 1) return 0; if (n == 2) return 2; if (n == 3) return 0; return fib4(n-1) + fib4(n-2) + fib4(n-3) + fib4(n-4);
}
}
} public static void main(String[] args) { assert(fib4((5l)) == (4l)); assert(fib4((8l)) == (28l)); assert(fib4((10l)) == (104l)); assert(fib4((12l)) == (386l)); } }
humaneval-HumanEval_75_is_multiply_prime.json-L10
py
def is_multiply_prime(a: int) -> bool: """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: >>> is_multiply_prime(30) True 30 = 2 * 3 * 5 """
d = 2 prime_factors = [] while d * d <= n: if n % d == 0: prime_factors.append(d) n //= d else: d += 1 if n > 1: prime_factors.append(n) if len(prime_factors) == 3: return True else: return False
n = a
def check(candidate): assert candidate(5) == False assert candidate(30) == True assert candidate(8) == True assert candidate(10) == False assert candidate(125) == True assert candidate(105) == True assert candidate(126) == False assert candidate(729) == False assert candidate(891) == False assert candidate(1001) == True def test_check(): check(is_multiply_prime) test_check()
humaneval-HumanEval_141_file_name_check.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 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[] 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"; } }
String result = "No";
} 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_68_pluck.json-L51
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_37_sort_even.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 { // 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> evenIndexed = new ArrayList<Long>(); int index = 0; for (Long num : l) { if (index % 2 == 0) { evenIndexed.add(num); } 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; } }
ArrayList<Long> res = new ArrayList<Long>();
} 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_158_find_max.json-L26
js
//Write a function that accepts an array of strings. // The array 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" function find_max(words){ var max_unique = {}; var max_unique_word = ""; for(var i = 0; i < words.length; i++){ var unique_word = {}; var word = words[i]; for(var j = 0; j < word.length; j++){ var char = word[j]; if(unique_word[char] === undefined){ unique_word[char] = 1; } } if(max_unique_word === ""){ max_unique_word = word; max_unique = unique_word;
else if(Object.keys(unique_word).length > Object.keys(max_unique).length){ max_unique_word = word; max_unique = unique_word; } else if(Object.keys(unique_word).length === Object.keys(max_unique).length){ if(word < max_unique_word){ max_unique_word = word; max_unique = unique_word; } } } return max_unique_word; }
}
const assert = require('node:assert'); function test() { let candidate = find_max; assert.deepEqual(candidate(["name", "of", "string"]),"string"); assert.deepEqual(candidate(["name", "enam", "game"]),"enam"); assert.deepEqual(candidate(["aaaaaaa", "bb", "cc"]),"aaaaaaa"); assert.deepEqual(candidate(["abc", "cba"]),"abc"); assert.deepEqual(candidate(["play", "this", "game", "of", "footbott"]),"footbott"); assert.deepEqual(candidate(["we", "are", "gonna", "rock"]),"gonna"); assert.deepEqual(candidate(["we", "are", "a", "mad", "nation"]),"nation"); assert.deepEqual(candidate(["this", "is", "a", "prrk"]),"this"); assert.deepEqual(candidate(["b"]),"b"); assert.deepEqual(candidate(["play", "play", "play"]),"play"); } test();
humaneval-HumanEval_74_total_match.json-L17
js
//Write a function that accepts two arrays of strings and returns the array that has // total number of chars in the all strings of the array less than the other array. // if the two arrays have the same number of chars, return the first array. // Examples // >>> total_match([], []) // [] // >>> total_match(["hi", "admin"], ["hI", "Hi"]) // ["hI", "Hi"] // >>> total_match(["hi", "admin"], ["hi", "hi", "admin", "project"]) // ["hi", "admin"] // >>> total_match(["hi", "admin"], ["hI", "hi", "hi"]) // ["hI", "hi", "hi"] // >>> total_match(["4"], ["1", "2", "3", "4", "5"]) // ["4"] function total_match(lst1, lst2){ let sum_lst1 = 0;
for(let item of lst1){ sum_lst1 += item.length; } for(let item of lst2){ sum_lst2 += item.length; } if(sum_lst1 > sum_lst2){ return lst2; } else{ return lst1; } }
let sum_lst2 = 0;
const assert = require('node:assert'); function test() { let candidate = total_match; assert.deepEqual(candidate([], []),[]); assert.deepEqual(candidate(["hi", "admin"], ["hi", "hi"]),["hi", "hi"]); assert.deepEqual(candidate(["hi", "admin"], ["hi", "hi", "admin", "project"]),["hi", "admin"]); assert.deepEqual(candidate(["4"], ["1", "2", "3", "4", "5"]),["4"]); assert.deepEqual(candidate(["hi", "admin"], ["hI", "Hi"]),["hI", "Hi"]); assert.deepEqual(candidate(["hi", "admin"], ["hI", "hi", "hi"]),["hI", "hi", "hi"]); assert.deepEqual(candidate(["hi", "admin"], ["hI", "hi", "hii"]),["hi", "admin"]); assert.deepEqual(candidate([], ["this"]),[]); assert.deepEqual(candidate(["this"], []),[]); } test();
humaneval-HumanEval_111_histogram.json-L44
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(" "); for (String sss : ss) { 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; } }
}
} 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))))); } }