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_137_compare_one.json-L40
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
return None elif isinstance(a, int) and isinstance(b, float): if a > b: return a elif a < b: return b else: return None elif isinstance(a, float) and isinstance(b, int): if a > b: return a elif a < b: return b else: return None elif isinstance(a, str) and isinstance(b, int): a_tmp = a.replace(',', '.') if float(a_tmp) > b: return a elif float(a_tmp) < b: return b else: return None elif isinstance(a, int) and isinstance(b, str): b_tmp = b.replace(',', '.') if a > float(b_tmp): return a elif a < float(b_tmp): return b else: return None elif isinstance(a, str) and isinstance(b, float): a_tmp = a.replace(',', '.') if float(a_tmp) > b: return a elif float(a_tmp) < b: return b
else:
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_20_find_closest_elements.json-L20
js
//From a supplied array 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] function find_closest_elements(numbers){ let closest = Math.abs(numbers[0] - numbers[1]); let a = numbers[0]; let b = numbers[1]; for (let i = 0; i < numbers.length; i++) { for (let j = i + 1; j < numbers.length; j++) { if (Math.abs(numbers[i] - numbers[j]) < closest) { closest = Math.abs(numbers[i] - numbers[j]); a = numbers[i]; b = numbers[j]; } } }
}
return a > b ? [b, a] : [a, b];
const assert = require('node:assert'); function test() { let candidate = find_closest_elements; assert.deepEqual(candidate([1.0, 2.0, 3.9, 4.0, 5.0, 2.2]),[3.9, 4.0]); assert.deepEqual(candidate([1.0, 2.0, 5.9, 4.0, 5.0]),[5.0, 5.9]); assert.deepEqual(candidate([1.0, 2.0, 3.0, 4.0, 5.0, 2.2]),[2.0, 2.2]); assert.deepEqual(candidate([1.0, 2.0, 3.0, 4.0, 5.0, 2.0]),[2.0, 2.0]); assert.deepEqual(candidate([1.1, 2.2, 3.1, 4.1, 5.1]),[2.2, 3.1]); } test();
humaneval-HumanEval_98_count_upper.json-L18
py
def count_upper(s: str) -> int: """ Given a string s, count the number of uppercase vowels in even indices. For example: >>> count_upper('aBCdEf') 1 >>> count_upper('abcdefg') 0 >>> count_upper('dBBE') 0 """ vowel_set = set('AEIOU') count = 0 for i in range(0, len(s), 2): if s[i] in vowel_set: count += 1
""" 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. """
return count
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_135_can_arrange.json-L16
js
//Create a function which returns the largest index of an element which // is not greater than or equal to the element immediately preceding it. If // no such element exists then return -1. The given array will not contain // duplicate values. // Examples: // >>> can_arrange([1, 2, 4, 3, 5]) // 3 // >>> can_arrange([1, 2, 3]) // -1 function can_arrange(arr){ var max = arr[0]; var res = -1; for(var i = 1; i < arr.length; i++){ if(arr[i] < max){ res = i;
max = arr[i]; } } return res; }
}else{
const assert = require('node:assert'); function test() { let candidate = can_arrange; assert.deepEqual(candidate([1, 2, 4, 3, 5]),3); assert.deepEqual(candidate([1, 2, 4, 5]),-1); assert.deepEqual(candidate([1, 4, 2, 5, 6, 7, 8, 9, 10]),2); assert.deepEqual(candidate([4, 8, 5, 7, 3]),4); assert.deepEqual(candidate([]),-1); } test();
humaneval-HumanEval_129_minPath.json-L33
js
//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 arrays 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 array 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] function minPath(grid, k){ let n = grid.length; let path = []; let startCell = grid[0][0]; for(let i = 0; i < n; i++){ for(let j = 0; j < n; j++){ let curr = grid[i][j]; if(curr < startCell){ startCell = curr;
} } let currCell = startCell; for(let l = 0; l < k; l++){ path.push(currCell); let neighbours = []; let x = null; let y = null; for(let i = 0; i < n; i++){ for(let j = 0; j < n; j++){ if(grid[i][j] === currCell){ x = i; y = j; } } } if(x > 0){ neighbours.push(grid[x - 1][y]); } if(x < n - 1){ neighbours.push(grid[x + 1][y]); } if(y > 0){ neighbours.push(grid[x][y - 1]); } if(y < n - 1){ neighbours.push(grid[x][y + 1]); } let nextCell = neighbours[0]; for(let i = 0; i < neighbours.length; i++){ let curr = neighbours[i]; if(curr < nextCell){ nextCell = curr; } } currCell = nextCell; } return path; }
}
const assert = require('node:assert'); function test() { let candidate = minPath; assert.deepEqual(candidate([[1, 2, 3], [4, 5, 6], [7, 8, 9]], 3),[1, 2, 1]); assert.deepEqual(candidate([[5, 9, 3], [4, 1, 6], [7, 8, 2]], 1),[1]); assert.deepEqual(candidate([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]], 4),[1, 2, 1, 2]); assert.deepEqual(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.deepEqual(candidate([[8, 14, 9, 2], [6, 4, 13, 15], [5, 7, 1, 12], [3, 10, 11, 16]], 5),[1, 7, 1, 7, 1]); assert.deepEqual(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.deepEqual(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.deepEqual(candidate([[2, 7, 4], [3, 1, 5], [6, 8, 9]], 8),[1, 3, 1, 3, 1, 3, 1, 3]); assert.deepEqual(candidate([[6, 1, 5], [3, 8, 9], [2, 7, 4]], 8),[1, 5, 1, 5, 1, 5, 1, 5]); assert.deepEqual(candidate([[1, 2], [3, 4]], 10),[1, 2, 1, 2, 1, 2, 1, 2, 1, 2]); assert.deepEqual(candidate([[1, 3], [3, 2]], 10),[1, 3, 1, 3, 1, 3, 1, 3, 1, 3]); } test();
humaneval-HumanEval_146_specialFilter.json-L29
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 takes an array array list of numbers as input and returns // the number of elements in the array array list that are greater than 10 and both // first and last digits of a number are odd (1, 3, 5, 7, 9). // For example: // >>> specialFilter((new ArrayList<Long>(Arrays.asList((long)15l, (long)-73l, (long)14l, (long)-15l)))) // (1l) // >>> specialFilter((new ArrayList<Long>(Arrays.asList((long)33l, (long)-2l, (long)-3l, (long)45l, (long)21l, (long)109l)))) // (2l) public static long specialFilter(ArrayList<Long> nums) { class helper { public long getFirstDigit(long n) { long[] digits = getDigits(n); return digits[0]; } public long getLastDigit(long n) { long[] digits = getDigits(n); return digits[digits.length - 1]; } public long[] getDigits(long n) { ArrayList<Long> digits = new ArrayList<Long>();
digits.add(n % 10); n /= 10; } Collections.reverse(digits); return digits.stream().mapToLong(i -> i).toArray(); } } helper h = new helper(); return nums.stream().filter(x -> x > 10).filter(x -> { long firstDigit = h.getFirstDigit(x); long lastDigit = h.getLastDigit(x); return firstDigit % 2 != 0 && lastDigit % 2 != 0; }).count(); } }
while (n != 0) {
} public static void main(String[] args) { assert(specialFilter((new ArrayList<Long>(Arrays.asList((long)5l, (long)-2l, (long)1l, (long)-5l)))) == (0l)); assert(specialFilter((new ArrayList<Long>(Arrays.asList((long)15l, (long)-73l, (long)14l, (long)-15l)))) == (1l)); assert(specialFilter((new ArrayList<Long>(Arrays.asList((long)33l, (long)-2l, (long)-3l, (long)45l, (long)21l, (long)109l)))) == (2l)); assert(specialFilter((new ArrayList<Long>(Arrays.asList((long)43l, (long)-12l, (long)93l, (long)125l, (long)121l, (long)109l)))) == (4l)); assert(specialFilter((new ArrayList<Long>(Arrays.asList((long)71l, (long)-2l, (long)-33l, (long)75l, (long)21l, (long)19l)))) == (3l)); assert(specialFilter((new ArrayList<Long>(Arrays.asList((long)1l)))) == (0l)); assert(specialFilter((new ArrayList<Long>(Arrays.asList()))) == (0l)); } }
humaneval-HumanEval_14_all_prefixes.json-L9
py
from typing import List def all_prefixes(string: str) -> List[str]: """ Return list of all prefixes from shortest to longest of the input string >>> all_prefixes('abc') ['a', 'ab', 'abc'] """ prefixes = []
prefixes.append(string[:i+1]) return prefixes
for i in range(len(string)):
def check(candidate): assert candidate('') == [] assert candidate('asdfgh') == ['a', 'as', 'asd', 'asdf', 'asdfg', 'asdfgh'] assert candidate('WWW') == ['W', 'WW', 'WWW'] def test_check(): check(all_prefixes) test_check()
humaneval-HumanEval_31_is_prime.json-L25
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Return true if a given number is prime, and false otherwise. // >>> isPrime((6l)) // (false) // >>> isPrime((101l)) // (true) // >>> isPrime((11l)) // (true) // >>> isPrime((13441l)) // (true) // >>> isPrime((61l)) // (true) // >>> isPrime((4l)) // (false) // >>> isPrime((1l)) // (false) public static boolean isPrime(long n) {
if (n <= 3) return true; if (n % 2 == 0 || n % 3 == 0) return false; long i = 5; while (i * i <= n) { if (n % i == 0 || n % (i + 2) == 0) return false; i += 6; } return true; } }
if (n <= 1) return false;
} public static void main(String[] args) { assert(isPrime((6l)) == (false)); assert(isPrime((101l)) == (true)); assert(isPrime((11l)) == (true)); assert(isPrime((13441l)) == (true)); assert(isPrime((61l)) == (true)); assert(isPrime((4l)) == (false)); assert(isPrime((1l)) == (false)); assert(isPrime((5l)) == (true)); assert(isPrime((11l)) == (true)); assert(isPrime((17l)) == (true)); assert(isPrime((85l)) == (false)); assert(isPrime((77l)) == (false)); assert(isPrime((255379l)) == (false)); } }
humaneval-HumanEval_57_monotonic.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 true is array list elements are monotonically increasing or decreasing. // >>> monotonic((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)4l, (long)20l)))) // (true) // >>> monotonic((new ArrayList<Long>(Arrays.asList((long)1l, (long)20l, (long)4l, (long)10l)))) // (false) // >>> monotonic((new ArrayList<Long>(Arrays.asList((long)4l, (long)1l, (long)0l, (long)-10l)))) // (true) public static boolean monotonic(ArrayList<Long> l) { long a = l.get(0); boolean inc = true; boolean dec = true; for (int i = 1; i < l.size(); i++) {
inc = false; } if (l.get(i) > a) { dec = false; } a = l.get(i); } return inc || dec; } }
if (l.get(i) < a) {
} public static void main(String[] args) { assert(monotonic((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)4l, (long)10l)))) == (true)); assert(monotonic((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)4l, (long)20l)))) == (true)); assert(monotonic((new ArrayList<Long>(Arrays.asList((long)1l, (long)20l, (long)4l, (long)10l)))) == (false)); assert(monotonic((new ArrayList<Long>(Arrays.asList((long)4l, (long)1l, (long)0l, (long)-10l)))) == (true)); assert(monotonic((new ArrayList<Long>(Arrays.asList((long)4l, (long)1l, (long)1l, (long)0l)))) == (true)); assert(monotonic((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)2l, (long)5l, (long)60l)))) == (false)); assert(monotonic((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l, (long)5l, (long)60l)))) == (true)); assert(monotonic((new ArrayList<Long>(Arrays.asList((long)9l, (long)9l, (long)9l, (long)9l)))) == (true)); } }
humaneval-HumanEval_95_check_dict_case.json-L44
js
//Given an object, return true if all keys are strings in lower // case or all keys are strings in upper case, else return false. // The function should return false is the given object is empty. // Examples: // >>> check_dict_case({"a": "apple", "b": "banana"}) // true // >>> check_dict_case({"a": "apple", "A": "banana", "B": "banana"}) // false // >>> check_dict_case({"a": "apple", 8: "banana", "a": "apple"}) // false // >>> check_dict_case({"Name": "John", "Age": "36", "City": "Houston"}) // false // >>> check_dict_case({"STATE": "NC", "ZIP": "12345"}) // true function check_dict_case(dict){ if (Object.keys(dict).length == 0){ return false; } var case_type = -1; for (let key in dict){ if (typeof key == "string"){ if (case_type == -1){ if (key == key.toUpperCase()){ case_type = 1; } else if (key == key.toLowerCase()){ case_type = 0; } else{ return false; } } else if (case_type == 1){ if (key != key.toUpperCase()){ return false; } } else if (case_type == 0){ if (key != key.toLowerCase()){ return false; } } }
return false; } } return true; }
else{
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_65_circular_shift.json-L9
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 len = str.length; 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 str = x.toString();
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_141_file_name_check.json-L17
js
//Create a function which takes a string representing a file's name, and returns // 'Yes' if the the file's name is valid, and returns 'No' otherwise. // A file's name is considered to be valid if and only if all the following conditions // are met: // - There should not be more than three digits ('0'-'9') in the file's name. // - The file's name contains exactly one dot '.' // - The substring before the dot should not be empty, and it starts with a letter from // the latin alphapet ('a'-'z' and 'A'-'Z'). // - The substring after the dot should be one of these: ['txt', 'exe', 'dll'] // Examples: // >>> file_name_check("example.txt") // "Yes" // >>> file_name_check("1example.dll") // "No" function file_name_check(file_name){ let str_1 = file_name.slice(0,file_name.indexOf('.'));
let str_3 = file_name.split(''); if (file_name.includes('.') && /[a-zA-Z]/.test(str_1[0]) && (str_2 == 'txt' || str_2 == 'exe' || str_2 == 'dll') && str_1.length != 0 && str_3.filter(item => /[0-9]/.test(item)).length < 4) { return 'Yes'; } return 'No'; }
let str_2 = file_name.slice(file_name.indexOf('.')+1);
const assert = require('node:assert'); function test() { let candidate = file_name_check; assert.deepEqual(candidate("example.txt"),"Yes"); assert.deepEqual(candidate("1example.dll"),"No"); assert.deepEqual(candidate("s1sdf3.asd"),"No"); assert.deepEqual(candidate("K.dll"),"Yes"); assert.deepEqual(candidate("MY16FILE3.exe"),"Yes"); assert.deepEqual(candidate("His12FILE94.exe"),"No"); assert.deepEqual(candidate("_Y.txt"),"No"); assert.deepEqual(candidate("?aREYA.exe"),"No"); assert.deepEqual(candidate("/this_is_valid.dll"),"No"); assert.deepEqual(candidate("this_is_valid.wow"),"No"); assert.deepEqual(candidate("this_is_valid.txt"),"Yes"); assert.deepEqual(candidate("this_is_valid.txtexe"),"No"); assert.deepEqual(candidate("#this2_i4s_5valid.ten"),"No"); assert.deepEqual(candidate("@this1_is6_valid.exe"),"No"); assert.deepEqual(candidate("this_is_12valid.6exe4.txt"),"No"); assert.deepEqual(candidate("all.exe.txt"),"No"); assert.deepEqual(candidate("I563_No.exe"),"Yes"); assert.deepEqual(candidate("Is3youfault.txt"),"Yes"); assert.deepEqual(candidate("no_one#knows.dll"),"Yes"); assert.deepEqual(candidate("1I563_Yes3.exe"),"No"); assert.deepEqual(candidate("I563_Yes3.txtt"),"No"); assert.deepEqual(candidate("final..txt"),"No"); assert.deepEqual(candidate("final132"),"No"); assert.deepEqual(candidate("_f4indsartal132."),"No"); assert.deepEqual(candidate(".txt"),"No"); assert.deepEqual(candidate("s."),"No"); } test();
humaneval-HumanEval_39_prime_fib.json-L32
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;
temp = a; a = a + b; b = temp; num--; } return b; } var res = 0; var fibNum = 0; while(res < n){ if(isPrime(fib(fibNum))){ res++; } fibNum++; } return fib(fibNum - 1); }
while (num >= 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_141_file_name_check.json-L46
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Create a function which takes a string representing a file's name, and returns // 'Yes' if the the file's name is valid, and returns 'No' otherwise. // A file's name is considered to be valid if and only if all the following conditions // are met: // - There should not be more than three digits ('0'-'9') in the file's name. // - The file's name contains exactly one dot '.' // - The substring before the dot should not be empty, and it starts with a letter from // the latin alphapet ('a'-'z' and 'A'-'Z'). // - The substring after the dot should be one of these: ['txt', 'exe', 'dll'] // Examples: // >>> fileNameCheck(("example.txt")) // ("Yes") // >>> fileNameCheck(("1example.dll")) // ("No") public static String fileNameCheck(String file_name) { String result = "No"; String[] tokens = file_name.split("\\."); if (tokens.length != 2) { return result; } String extension = tokens[1]; if (!(extension.equals("txt") || extension.equals("exe") || extension.equals("dll"))) { return result; } String name = tokens[0]; int count = 0; for (int i = 0; i < name.length(); i++) { if (Character.isDigit(name.charAt(i))) { count++; } } if (count > 3) { return result; } if (name.length() == 0) { return result; }
return result; } return "Yes"; } }
if (!Character.isLetter(name.charAt(0))) {
} 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_147_get_max_triples.json-L21
py
def get_max_triples(n: int) -> int: """ You are given a positive integer n. You have to create an integer array a of length n. For each i (1 ≤ i ≤ n), the value of a[i] = i * i - i + 1. Return the number of triples (a[i], a[j], a[k]) of a where i < j < k, and a[i] + a[j] + a[k] is a multiple of 3. Example : >>> get_max_triples(5) 1 Explanation: a = [1, 3, 7, 13, 21] The only valid triple is (1, 7, 13). """ a = [i * i - i + 1 for i in range(1, n + 1)] i = 0 j = 1 k = 2 count = 0 while (i < n - 2):
while (k < n): if (a[i] + a[j] + a[k]) % 3 == 0: count += 1 k += 1 j += 1 k = j + 1 i += 1 j = i + 1 k = j + 1 return count
while (j < n - 1):
def check(candidate): assert candidate(5) == 1 assert candidate(6) == 4 assert candidate(10) == 36 assert candidate(100) == 53361 def test_check(): check(get_max_triples) test_check()
humaneval-HumanEval_126_is_sorted.json-L38
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_81_numerical_letter_grade.json-L28
js
//It is the last week of the semester and the teacher has to give the grades // to students. The teacher has been making her own algorithm for grading. // The only problem is, she has lost the code she used for grading. // She has given you an array of GPAs for some students and you have to write // a function that can output an array of letter grades using the following table: // GPA | Letter grade // 4.0 A+ // > 3.7 A // > 3.3 A- // > 3.0 B+ // > 2.7 B // > 2.3 B- // > 2.0 C+ // > 1.7 C // > 1.3 C- // > 1.0 D+ // > 0.7 D // > 0.0 D- // 0.0 E // Example: // >>> grade_equation([4.0, 3, 1.7, 2, 3.5]) // ["A+", "B", "C-", "C", "A-"] function numerical_letter_grade(grades){ var grades_array = []; for (var i = 0; i < grades.length; i++){ if (grades[i] >= 4.0){ grades_array.push("A+");
else if (grades[i] > 3.7){ grades_array.push("A"); } else if (grades[i] > 3.3){ grades_array.push("A-"); } else if (grades[i] > 3.0){ grades_array.push("B+"); } else if (grades[i] > 2.7){ grades_array.push("B"); } else if (grades[i] > 2.3){ grades_array.push("B-"); } else if (grades[i] > 2.0){ grades_array.push("C+"); } else if (grades[i] > 1.7){ grades_array.push("C"); } else if (grades[i] > 1.3){ grades_array.push("C-"); } else if (grades[i] > 1.0){ grades_array.push("D+"); } else if (grades[i] > 0.7){ grades_array.push("D"); } else if (grades[i] > 0.0){ grades_array.push("D-"); } else if (grades[i] == 0.0){ grades_array.push("E"); } } return grades_array; }
}
const assert = require('node:assert'); function test() { let candidate = numerical_letter_grade; assert.deepEqual(candidate([4.0, 3, 1.7, 2, 3.5]),["A+", "B", "C-", "C", "A-"]); assert.deepEqual(candidate([1.2]),["D+"]); assert.deepEqual(candidate([0.5]),["D-"]); assert.deepEqual(candidate([0.0]),["E"]); assert.deepEqual(candidate([1.0, 0.3, 1.5, 2.8, 3.3]),["D", "D-", "C-", "B", "B+"]); assert.deepEqual(candidate([0.0, 0.7]),["E", "D-"]); } test();
humaneval-HumanEval_156_int_to_mini_roman.json-L41
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) {
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; } }
res += "c";
} 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_7_filter_by_substring.json-L13
js
//Filter an input array of strings only for ones that contain given substring // >>> filter_by_substring([], "a") // [] // >>> filter_by_substring(["abc", "bacd", "cde", "array"], "a") // ["abc", "bacd", "array"] function filter_by_substring(strings, substring){ var filtered = []; for(var i = 0; i < strings.length; i++){ if(strings[i].includes(substring)){ filtered.push(strings[i]); } }
}
return filtered;
const assert = require('node:assert'); function test() { let candidate = filter_by_substring; assert.deepEqual(candidate([], "john"),[]); assert.deepEqual(candidate(["xxx", "asd", "xxy", "john doe", "xxxAAA", "xxx"], "xxx"),["xxx", "xxxAAA", "xxx"]); assert.deepEqual(candidate(["xxx", "asd", "aaaxxy", "john doe", "xxxAAA", "xxx"], "xx"),["xxx", "aaaxxy", "xxxAAA", "xxx"]); assert.deepEqual(candidate(["grunt", "trumpet", "prune", "gruesome"], "run"),["grunt", "prune"]); } test();
humaneval-HumanEval_25_factorize.json-L18
js
//Return array of prime factors of given integer in the order from smallest to largest. // Each of the factors should be arrayed 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] function factorize(n){ let factor = 2; let arr = []; while (n > 1) { if (n % factor == 0) { arr.push(factor); n = n / factor; } else {
} } return arr; }
factor++;
const assert = require('node:assert'); function test() { let candidate = factorize; assert.deepEqual(candidate(2),[2]); assert.deepEqual(candidate(4),[2, 2]); assert.deepEqual(candidate(8),[2, 2, 2]); assert.deepEqual(candidate(57),[3, 19]); assert.deepEqual(candidate(3249),[3, 3, 19, 19]); assert.deepEqual(candidate(185193),[3, 3, 3, 19, 19, 19]); assert.deepEqual(candidate(20577),[3, 19, 19, 19]); assert.deepEqual(candidate(18),[2, 3, 3]); } test();
humaneval-HumanEval_148_bf.json-L22
py
from typing import Tuple def bf(planet1: str, planet2: str) -> Tuple[str, ...]: """ There are eight planets in our solar system: the closerst to the Sun is Mercury, the next one is Venus, then Earth, Mars, Jupiter, Saturn, Uranus, Neptune. Write a function that takes two planet names as strings planet1 and planet2. The function should return a tuple containing all planets whose orbits are located between the orbit of planet1 and the orbit of planet2, sorted by the proximity to the sun. The function should return an empty tuple if planet1 or planet2 are not correct planet names. Examples >>> bf('Jupiter', 'Neptune') ('Saturn', 'Uranus') >>> bf('Earth', 'Mercury') 'Venus' >>> bf('Mercury', 'Uranus') ('Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn') """
if planet1 not in planets or planet2 not in planets: return () start = planets.index(planet1) end = planets.index(planet2) if start < end: planets = planets[start+1:end] else: planets = planets[end+1:start] return tuple(planets)
planets = ('Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune')
def check(candidate): assert candidate('Jupiter', 'Neptune') == ('Saturn', 'Uranus') assert candidate('Earth', 'Mercury') == ('Venus',) assert candidate('Mercury', 'Uranus') == ('Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn') assert candidate('Neptune', 'Venus') == ('Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus') assert candidate('Earth', 'Earth') == () assert candidate('Mars', 'Earth') == () assert candidate('Jupiter', 'Makemake') == () def test_check(): check(bf) test_check()
humaneval-HumanEval_153_Strongest_Extension.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 { // 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;
strength = diff; strongest = s; } } return class_name + "." + strongest; } }
if (diff > strength) {
} 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_26_remove_duplicates.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 { // From an array array list of integers, remove all elements that occur more than once. // Keep order of elements left the same as in the input. // >>> removeDuplicates((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)2l, (long)4l)))) // (new ArrayList<Long>(Arrays.asList((long)1l, (long)3l, (long)4l))) public static ArrayList<Long> removeDuplicates(ArrayList<Long> numbers) { HashMap<Long, Long> hashmap = new HashMap<Long, Long>(); for (int i = 0; i < numbers.size(); i++) { Long key = numbers.get(i); if (hashmap.containsKey(key)) { hashmap.put(key, hashmap.get(key) + 1); } else { hashmap.put(key, 1L); }
ArrayList<Long> out = new ArrayList<Long>(); for (int i = 0; i < numbers.size(); i++) { Long key = numbers.get(i); if (hashmap.get(key) == 1) { out.add(key); } } return out; } }
}
} public static void main(String[] args) { assert(removeDuplicates((new ArrayList<Long>(Arrays.asList()))).equals((new ArrayList<Long>(Arrays.asList())))); assert(removeDuplicates((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(removeDuplicates((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)2l, (long)4l, (long)3l, (long)5l)))).equals((new ArrayList<Long>(Arrays.asList((long)1l, (long)4l, (long)5l))))); } }
humaneval-HumanEval_81_numerical_letter_grade.json-L59
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 { // It is the last week of the semester and the teacher has to give the grades // to students. The teacher has been making her own algorithm for grading. // The only problem is, she has lost the code she used for grading. // She has given you an array array list of GPAs for some students and you have to write // a function that can output an array array list of letter grades using the following table: // GPA | Letter grade // 4.0 A+ // > 3.7 A // > 3.3 A- // > 3.0 B+ // > 2.7 B // > 2.3 B- // > 2.0 C+ // > 1.7 C // > 1.3 C- // > 1.0 D+ // > 0.7 D // > 0.0 D- // 0.0 E // Example: // >>> gradeEquation((new ArrayList<Float>(Arrays.asList((float)4.0f, (float)3l, (float)1.7f, (float)2l, (float)3.5f)))) // (new ArrayList<String>(Arrays.asList((String)"A+", (String)"B", (String)"C-", (String)"C", (String)"A-"))) public static ArrayList<String> numericalLetterGrade(ArrayList<Float> grades) { ArrayList<String> letterGrades = new ArrayList<String>(); for (int i = 0; i < grades.size(); i++) { float currentGrade = grades.get(i); if (currentGrade == 4.0f) { letterGrades.add("A+"); } else if (currentGrade > 3.7f) { letterGrades.add("A"); } else if (currentGrade > 3.3f) { letterGrades.add("A-"); } else if (currentGrade > 3.0f) { letterGrades.add("B+"); } else if (currentGrade > 2.7f) { letterGrades.add("B"); } else if (currentGrade > 2.3f) { letterGrades.add("B-"); } else if (currentGrade > 2.0f) { letterGrades.add("C+"); } else if (currentGrade > 1.7f) { letterGrades.add("C"); } else if (currentGrade > 1.3f) { letterGrades.add("C-"); } else if (currentGrade > 1.0f) { letterGrades.add("D+"); } else if (currentGrade > 0.7f) { letterGrades.add("D"); } else if (currentGrade > 0.0f) { letterGrades.add("D-");
letterGrades.add("E"); } } return letterGrades; } }
} else {
} public static void main(String[] args) { assert(numericalLetterGrade((new ArrayList<Float>(Arrays.asList((float)4.0f, (float)3l, (float)1.7f, (float)2l, (float)3.5f)))).equals((new ArrayList<String>(Arrays.asList((String)"A+", (String)"B", (String)"C-", (String)"C", (String)"A-"))))); assert(numericalLetterGrade((new ArrayList<Float>(Arrays.asList((float)1.2f)))).equals((new ArrayList<String>(Arrays.asList((String)"D+"))))); assert(numericalLetterGrade((new ArrayList<Float>(Arrays.asList((float)0.5f)))).equals((new ArrayList<String>(Arrays.asList((String)"D-"))))); assert(numericalLetterGrade((new ArrayList<Float>(Arrays.asList((float)0.0f)))).equals((new ArrayList<String>(Arrays.asList((String)"E"))))); assert(numericalLetterGrade((new ArrayList<Float>(Arrays.asList((float)1.0f, (float)0.3f, (float)1.5f, (float)2.8f, (float)3.3f)))).equals((new ArrayList<String>(Arrays.asList((String)"D", (String)"D-", (String)"C-", (String)"B", (String)"B+"))))); assert(numericalLetterGrade((new ArrayList<Float>(Arrays.asList((float)0.0f, (float)0.7f)))).equals((new ArrayList<String>(Arrays.asList((String)"E", (String)"D-"))))); } }
humaneval-HumanEval_18_how_many_times.json-L10
js
//Find how many times a given substring can be found in the original string. Count overlaping cases. // >>> how_many_times("", "a") // 0 // >>> how_many_times("aaa", "a") // 3 // >>> how_many_times("aaaa", "aa") // 3 function how_many_times(string, substring){ var i = 0;
while(string.indexOf(substring, i) !== -1){ count++; i = string.indexOf(substring, i) + 1; } return count; }
var count = 0;
const assert = require('node:assert'); function test() { let candidate = how_many_times; assert.deepEqual(candidate("", "x"),0); assert.deepEqual(candidate("xyxyxyx", "x"),4); assert.deepEqual(candidate("cacacacac", "cac"),4); assert.deepEqual(candidate("john doe", "john"),1); } test();
humaneval-HumanEval_75_is_multiply_prime.json-L14
js
//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 function is_multiply_prime(a){ a = Math.abs(a); const prime = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]; let i = 0; let check = []; while(a != 1){
a = a / prime[i]; check.push(prime[i]); }else{ i++; } } if(check.length == 3){ return true; }else{ return false; } }
if(a % prime[i] == 0){
const assert = require('node:assert'); function test() { let candidate = is_multiply_prime; assert.deepEqual(candidate(5),false); assert.deepEqual(candidate(30),true); assert.deepEqual(candidate(8),true); assert.deepEqual(candidate(10),false); assert.deepEqual(candidate(125),true); assert.deepEqual(candidate(105),true); assert.deepEqual(candidate(126),false); assert.deepEqual(candidate(729),false); assert.deepEqual(candidate(891),false); assert.deepEqual(candidate(1001),true); } test();
humaneval-HumanEval_156_int_to_mini_roman.json-L30
js
//Given a positive integer, obtain its roman numeral equivalent as a string, // and return it in lowercase. // Restrictions: 1 <= num <= 1000 // Examples: // >>> int_to_mini_roman(19) // "xix" // >>> int_to_mini_roman(152) // "clii" // >>> int_to_mini_roman(426) // "cdxxvi" function int_to_mini_roman(number){ var roman_conversion = { 1000: "m", 900: "cm", 500: "d", 400: "cd", 100: "c", 90: "xc", 50: "l", 40: "xl", 10: "x", 9: "ix", 5: "v", 4: "iv", 1: "i" }; var output = ""; while (number > 0){ var key_list = Object.keys(roman_conversion).map(Number);
for (var i = 0; i < key_list.length; i++){ if (key_list[i] <= number){ output += roman_conversion[key_list[i]]; number -= key_list[i]; break; } } } return output; }
key_list.sort(function(a, b){return b-a});
const assert = require('node:assert'); function test() { let candidate = int_to_mini_roman; assert.deepEqual(candidate(19),"xix"); assert.deepEqual(candidate(152),"clii"); assert.deepEqual(candidate(251),"ccli"); assert.deepEqual(candidate(426),"cdxxvi"); assert.deepEqual(candidate(500),"d"); assert.deepEqual(candidate(1),"i"); assert.deepEqual(candidate(4),"iv"); assert.deepEqual(candidate(43),"xliii"); assert.deepEqual(candidate(90),"xc"); assert.deepEqual(candidate(94),"xciv"); assert.deepEqual(candidate(532),"dxxxii"); assert.deepEqual(candidate(900),"cm"); assert.deepEqual(candidate(994),"cmxciv"); assert.deepEqual(candidate(1000),"m"); } test();
humaneval-HumanEval_116_sort_array.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 { // In this Kata, you have to sort an array array list 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: // >>> sortArray((new ArrayList<Long>(Arrays.asList((long)1l, (long)5l, (long)2l, (long)3l, (long)4l)))) // (new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l, (long)5l))) // >>> sortArray((new ArrayList<Long>(Arrays.asList((long)-2l, (long)-3l, (long)-4l, (long)-5l, (long)-6l)))) // (new ArrayList<Long>(Arrays.asList((long)-6l, (long)-5l, (long)-4l, (long)-3l, (long)-2l))) // >>> sortArray((new ArrayList<Long>(Arrays.asList((long)1l, (long)0l, (long)2l, (long)3l, (long)4l)))) // (new ArrayList<Long>(Arrays.asList((long)0l, (long)1l, (long)2l, (long)3l, (long)4l))) public static ArrayList<Long> sortArray(ArrayList<Long> arr) { Collections.sort(arr, (a, b) -> {
if (a1 < 0) { a1 = -a1; } if (b1 < 0) { b1 = -b1; } return Long.bitCount(a1) == Long.bitCount(b1) ? Long.compare(a, b) : Integer.compare(Long.bitCount(a1), Long.bitCount(b1)); }); return arr; } }
long a1 = a, b1 = b;
} public static void main(String[] args) { assert(sortArray((new ArrayList<Long>(Arrays.asList((long)1l, (long)5l, (long)2l, (long)3l, (long)4l)))).equals((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)4l, (long)3l, (long)5l))))); assert(sortArray((new ArrayList<Long>(Arrays.asList((long)-2l, (long)-3l, (long)-4l, (long)-5l, (long)-6l)))).equals((new ArrayList<Long>(Arrays.asList((long)-4l, (long)-2l, (long)-6l, (long)-5l, (long)-3l))))); assert(sortArray((new ArrayList<Long>(Arrays.asList((long)1l, (long)0l, (long)2l, (long)3l, (long)4l)))).equals((new ArrayList<Long>(Arrays.asList((long)0l, (long)1l, (long)2l, (long)4l, (long)3l))))); assert(sortArray((new ArrayList<Long>(Arrays.asList()))).equals((new ArrayList<Long>(Arrays.asList())))); assert(sortArray((new ArrayList<Long>(Arrays.asList((long)2l, (long)5l, (long)77l, (long)4l, (long)5l, (long)3l, (long)5l, (long)7l, (long)2l, (long)3l, (long)4l)))).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)2l, (long)4l, (long)4l, (long)3l, (long)3l, (long)5l, (long)5l, (long)5l, (long)7l, (long)77l))))); assert(sortArray((new ArrayList<Long>(Arrays.asList((long)3l, (long)6l, (long)44l, (long)12l, (long)32l, (long)5l)))).equals((new ArrayList<Long>(Arrays.asList((long)32l, (long)3l, (long)5l, (long)6l, (long)12l, (long)44l))))); assert(sortArray((new ArrayList<Long>(Arrays.asList((long)2l, (long)4l, (long)8l, (long)16l, (long)32l)))).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)4l, (long)8l, (long)16l, (long)32l))))); assert(sortArray((new ArrayList<Long>(Arrays.asList((long)2l, (long)4l, (long)8l, (long)16l, (long)32l)))).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)4l, (long)8l, (long)16l, (long)32l))))); } }
humaneval-HumanEval_63_fibfib.json-L40
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 FibFib number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows: // fibfib(0) == 0 // fibfib(1) == 0 // fibfib(2) == 1 // fibfib(n) == fibfib(n-1) + fibfib(n-2) + fibfib(n-3). // Please write a function to efficiently compute the n-th element of the fibfib number sequence. // >>> fibfib((1l)) // (0l) // >>> fibfib((5l)) // (4l) // >>> fibfib((8l)) // (24l) public static long fibfib(long n) { if (n == 0) { return 0; } if (n == 1) { return 0; } if (n == 2) { return 1; } long[] memo = new long[(int) n + 1]; memo[0] = 0; memo[1] = 0; memo[2] = 1; for (int i = 3; i <= n; i++) { memo[i] = memo[i - 1] + memo[i - 2] + memo[i - 3]; } return memo[(int) n]; }
}
} public static void main(String[] args) { assert(fibfib((2l)) == (1l)); assert(fibfib((1l)) == (0l)); assert(fibfib((5l)) == (4l)); assert(fibfib((8l)) == (24l)); assert(fibfib((10l)) == (81l)); assert(fibfib((12l)) == (274l)); assert(fibfib((14l)) == (927l)); } }
humaneval-HumanEval_81_numerical_letter_grade.json-L53
py
from typing import List def numerical_letter_grade(grades: List[float]) -> List[str]: """It is the last week of the semester and the teacher has to give the grades to students. The teacher has been making her own algorithm for grading. The only problem is, she has lost the code she used for grading. She has given you a list of GPAs for some students and you have to write a function that can output a list of letter grades using the following table: GPA | Letter grade 4.0 A+ > 3.7 A > 3.3 A- > 3.0 B+ > 2.7 B > 2.3 B- > 2.0 C+ > 1.7 C > 1.3 C- > 1.0 D+ > 0.7 D > 0.0 D- 0.0 E Example: >>> grade_equation([4.0, 3, 1.7, 2, 3.5]) ['A+', 'B', 'C-', 'C', 'A-'] """ final = [] for x in grades: if x == 4.0: final.append('A+') elif x > 3.7: final.append('A') elif x > 3.3: final.append('A-') elif x > 3.0: final.append('B+') elif x > 2.7: final.append('B') elif x > 2.3: final.append('B-') elif x > 2.0: final.append('C+') elif x > 1.7: final.append('C') elif x > 1.3: final.append('C-') elif x > 1.0: final.append('D+') elif x > 0.7: final.append('D')
final.append('D-') else: final.append('E') return final
elif x > 0.0:
def check(candidate): assert candidate([4.0, 3, 1.7, 2, 3.5]) == ['A+', 'B', 'C-', 'C', 'A-'] assert candidate([1.2]) == ['D+'] assert candidate([0.5]) == ['D-'] assert candidate([0.0]) == ['E'] assert candidate([1.0, 0.3, 1.5, 2.8, 3.3]) == ['D', 'D-', 'C-', 'B', 'B+'] assert candidate([0.0, 0.7]) == ['E', 'D-'] def test_check(): check(numerical_letter_grade) test_check()
humaneval-HumanEval_155_even_odd_count.json-L20
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) if digit % 2 == 0: even_count += 1 else:
return even_count, odd_count
odd_count += 1
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_101_words_string.json-L20
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // You will be given a string of words separated by commas or spaces. Your task is // to split the string into words and return an array array list of the words. // For example: // >>> wordsString(("Hi, my name is John")) // (new ArrayList<String>(Arrays.asList((String)"Hi", (String)"my", (String)"name", (String)"is", (String)"John"))) // >>> wordsString(("One, two, three, four, five, six")) // (new ArrayList<String>(Arrays.asList((String)"One", (String)"two", (String)"three", (String)"four", (String)"five", (String)"six"))) public static ArrayList<String> wordsString(String s) { ArrayList<String> al = new ArrayList<String>(); StringTokenizer st = new StringTokenizer(s, " , "); while (st.hasMoreTokens()) {
} return al; } }
al.add(st.nextToken());
} public static void main(String[] args) { assert(wordsString(("Hi, my name is John")).equals((new ArrayList<String>(Arrays.asList((String)"Hi", (String)"my", (String)"name", (String)"is", (String)"John"))))); assert(wordsString(("One, two, three, four, five, six")).equals((new ArrayList<String>(Arrays.asList((String)"One", (String)"two", (String)"three", (String)"four", (String)"five", (String)"six"))))); assert(wordsString(("Hi, my name")).equals((new ArrayList<String>(Arrays.asList((String)"Hi", (String)"my", (String)"name"))))); assert(wordsString(("One,, two, three, four, five, six,")).equals((new ArrayList<String>(Arrays.asList((String)"One", (String)"two", (String)"three", (String)"four", (String)"five", (String)"six"))))); assert(wordsString(("")).equals((new ArrayList<String>(Arrays.asList())))); assert(wordsString(("ahmed , gamal")).equals((new ArrayList<String>(Arrays.asList((String)"ahmed", (String)"gamal"))))); } }
humaneval-HumanEval_86_anti_shuffle.json-L20
js
//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" function anti_shuffle(s){ var result = []; var strings = s.split(" "); strings.forEach(function(str){ var temp = str.split(""); temp.sort(); result.push(temp.join(""));
return result.join(" "); }
});
const assert = require('node:assert'); function test() { let candidate = anti_shuffle; assert.deepEqual(candidate("Hi"),"Hi"); assert.deepEqual(candidate("hello"),"ehllo"); assert.deepEqual(candidate("number"),"bemnru"); assert.deepEqual(candidate("abcd"),"abcd"); assert.deepEqual(candidate("Hello World!!!"),"Hello !!!Wdlor"); assert.deepEqual(candidate(""),""); assert.deepEqual(candidate("Hi. My name is Mister Robot. How are you?"),".Hi My aemn is Meirst .Rboot How aer ?ouy"); } test();
humaneval-HumanEval_91_is_bored.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 { // 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: // >>> isBored(("Hello world")) // (0l) // >>> isBored(("The sky is blue. The sun is shining. I love this weather")) // (1l) public static long isBored(String S) { long boredoms = 0; String[] sentences = S.split("\\.\\s|\\?\\s|\\!\\s"); for (String sentence : sentences) {
if (words.length > 0 && words[0].equals("I")) { boredoms++; } } return boredoms; } }
String[] words = sentence.split("\\s");
} public static void main(String[] args) { assert(isBored(("Hello world")) == (0l)); assert(isBored(("Is the sky blue?")) == (0l)); assert(isBored(("I love It !")) == (1l)); assert(isBored(("bIt")) == (0l)); assert(isBored(("I feel good today. I will be productive. will kill It")) == (2l)); assert(isBored(("You and I are going for a walk")) == (0l)); } }
humaneval-HumanEval_126_is_sorted.json-L54
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 numbers, return whether or not they are sorted // in ascending order. If array list has more than 1 duplicate of the same // number, return false. Assume no negative numbers and only integers. // Examples // >>> isSorted((new ArrayList<Long>(Arrays.asList((long)5l)))) // (true) // >>> isSorted((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l, (long)5l)))) // (true) // >>> isSorted((new ArrayList<Long>(Arrays.asList((long)1l, (long)3l, (long)2l, (long)4l, (long)5l)))) // (false) // >>> isSorted((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l, (long)5l, (long)6l)))) // (true) // >>> isSorted((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l, (long)5l, (long)6l, (long)7l)))) // (true) // >>> isSorted((new ArrayList<Long>(Arrays.asList((long)1l, (long)3l, (long)2l, (long)4l, (long)5l, (long)6l, (long)7l)))) // (false) // >>> isSorted((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)2l, (long)3l, (long)3l, (long)4l)))) // (true) // >>> isSorted((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)2l, (long)2l, (long)3l, (long)4l)))) // (false) public static boolean isSorted(ArrayList<Long> lst) { if (lst.size() == 0) { return true; } else { int running_max = 0; int previous_number = 0; boolean first_time = true; boolean seen_2_in_a_row = false; for (Long number : lst) { if (first_time) { first_time = false; previous_number = number.intValue(); running_max = number.intValue(); } else { if (running_max > number.intValue()) { return false; } else { if (previous_number == number.intValue()) { if (seen_2_in_a_row) { return false; } else {
} } else { seen_2_in_a_row = false; } previous_number = number.intValue(); running_max = number.intValue(); } } } return true; } } }
seen_2_in_a_row = true;
} public static void main(String[] args) { assert(isSorted((new ArrayList<Long>(Arrays.asList((long)5l)))) == (true)); assert(isSorted((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l, (long)5l)))) == (true)); assert(isSorted((new ArrayList<Long>(Arrays.asList((long)1l, (long)3l, (long)2l, (long)4l, (long)5l)))) == (false)); assert(isSorted((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l, (long)5l, (long)6l)))) == (true)); assert(isSorted((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l, (long)5l, (long)6l, (long)7l)))) == (true)); assert(isSorted((new ArrayList<Long>(Arrays.asList((long)1l, (long)3l, (long)2l, (long)4l, (long)5l, (long)6l, (long)7l)))) == (false)); assert(isSorted((new ArrayList<Long>(Arrays.asList()))) == (true)); assert(isSorted((new ArrayList<Long>(Arrays.asList((long)1l)))) == (true)); assert(isSorted((new ArrayList<Long>(Arrays.asList((long)3l, (long)2l, (long)1l)))) == (false)); assert(isSorted((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)2l, (long)2l, (long)3l, (long)4l)))) == (false)); assert(isSorted((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)3l, (long)3l, (long)4l)))) == (false)); assert(isSorted((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)2l, (long)3l, (long)3l, (long)4l)))) == (true)); assert(isSorted((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l)))) == (true)); } }
humaneval-HumanEval_61_correct_bracketing.json-L20
py
def correct_bracketing(brackets: str) -> bool: """ brackets is a string of "(" and ")". return True if every opening bracket has a corresponding closing bracket. >>> correct_bracketing('(') False >>> correct_bracketing('()') True >>> correct_bracketing('(()())') True >>> correct_bracketing(')(()') False """ count = 0 for char in brackets: if char == '(': count += 1 elif char == ')': count -= 1
return False return count == 0
if count < 0:
def check(candidate): assert candidate('()') == True assert candidate('(()())') == True assert candidate('()()(()())()') == True assert candidate('()()((()()())())(()()(()))') == True assert candidate('((()())))') == False assert candidate(')(()') == False assert candidate('(') == False assert candidate('((((') == False assert candidate(')') == False assert candidate('(()') == False assert candidate('()()(()())())(()') == False assert candidate('()()(()())()))()') == False def test_check(): check(correct_bracketing) test_check()
humaneval-HumanEval_100_make_a_pile.json-L14
js
//Given a positive integer n, you have to make a pile of n levels of stones. // The first level has n stones. // The number of stones in the next level is: // - the next odd number if n is odd. // - the next even number if n is even. // Return the number of stones in each level in an array, where element at index // i represents the number of stones in the level (i+1). // Examples: // >>> make_a_pile(3) // [3, 5, 7] function make_a_pile(n){ let arr = []; for(let i = 0; i < n; i++){
} return arr; }
arr.push(n + (i * 2));
const assert = require('node:assert'); function test() { let candidate = make_a_pile; assert.deepEqual(candidate(3),[3, 5, 7]); assert.deepEqual(candidate(4),[4, 6, 8, 10]); assert.deepEqual(candidate(5),[5, 7, 9, 11, 13]); assert.deepEqual(candidate(6),[6, 8, 10, 12, 14, 16]); assert.deepEqual(candidate(8),[8, 10, 12, 14, 16, 18, 20, 22]); } test();
humaneval-HumanEval_147_get_max_triples.json-L24
py
def get_max_triples(n: int) -> int: """ You are given a positive integer n. You have to create an integer array a of length n. For each i (1 ≤ i ≤ n), the value of a[i] = i * i - i + 1. Return the number of triples (a[i], a[j], a[k]) of a where i < j < k, and a[i] + a[j] + a[k] is a multiple of 3. Example : >>> get_max_triples(5) 1 Explanation: a = [1, 3, 7, 13, 21] The only valid triple is (1, 7, 13). """ a = [i * i - i + 1 for i in range(1, n + 1)] i = 0 j = 1 k = 2 count = 0 while (i < n - 2): while (j < n - 1): while (k < n): if (a[i] + a[j] + a[k]) % 3 == 0:
k += 1 j += 1 k = j + 1 i += 1 j = i + 1 k = j + 1 return count
count += 1
def check(candidate): assert candidate(5) == 1 assert candidate(6) == 4 assert candidate(10) == 36 assert candidate(100) == 53361 def test_check(): check(get_max_triples) test_check()
humaneval-HumanEval_33_sort_third.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 { // This function takes an array array list l and returns an array array list l' such that // l' is identical to l in the indicies that are not divisible by three, while its values at the indicies that are divisible by three are equal // to the values of the corresponding indicies of l, but sorted. // >>> sortThird((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l)))) // (new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l))) // >>> sortThird((new ArrayList<Long>(Arrays.asList((long)5l, (long)6l, (long)3l, (long)4l, (long)8l, (long)9l, (long)2l)))) // (new ArrayList<Long>(Arrays.asList((long)2l, (long)6l, (long)3l, (long)4l, (long)8l, (long)9l, (long)5l))) public static ArrayList<Long> sortThird(ArrayList<Long> l) { ArrayList<Long> l_r = new ArrayList<Long>(); ArrayList<Long> l_e = new ArrayList<Long>();
for (int i = 0; i < l.size(); i++) { if (i % 3 == 0) { l_e.add(l.get(i)); } else { l_r.add(l.get(i)); } } for (int i = 0; i < l_e.size(); i++) { long min = l_e.get(i); for (int j = i; j < l_e.size(); j++) { if (l_e.get(j) < min) { min = l_e.get(j); l_e.set(j, l_e.get(i)); l_e.set(i, min); } } } int j = 0; for (int i = 0; i < l.size(); i++) { if (i % 3 == 0) { l_s.add(l_e.get(j)); j++; } else { l_s.add(l_r.get(i - j)); } } return l_s; } }
ArrayList<Long> l_s = new ArrayList<Long>();
} public static void main(String[] args) { assert(sortThird((new ArrayList<Long>(Arrays.asList((long)5l, (long)6l, (long)3l, (long)4l, (long)8l, (long)9l, (long)2l)))).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)6l, (long)3l, (long)4l, (long)8l, (long)9l, (long)5l))))); assert(sortThird((new ArrayList<Long>(Arrays.asList((long)5l, (long)8l, (long)3l, (long)4l, (long)6l, (long)9l, (long)2l)))).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)8l, (long)3l, (long)4l, (long)6l, (long)9l, (long)5l))))); assert(sortThird((new ArrayList<Long>(Arrays.asList((long)5l, (long)6l, (long)9l, (long)4l, (long)8l, (long)3l, (long)2l)))).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)6l, (long)9l, (long)4l, (long)8l, (long)3l, (long)5l))))); assert(sortThird((new ArrayList<Long>(Arrays.asList((long)5l, (long)6l, (long)3l, (long)4l, (long)8l, (long)9l, (long)2l, (long)1l)))).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)6l, (long)3l, (long)4l, (long)8l, (long)9l, (long)5l, (long)1l))))); } }
humaneval-HumanEval_99_closest_integer.json-L20
js
//Create a function that takes a value (string) representing a number // and returns the closest integer to it. If the number is equidistant // from two integers, round it away from zero. // Examples // >>> closest_integer("10") // 10 // >>> closest_integer("15.3") // 15 // Note: // Rounding away from zero means that if the given number is equidistant // from two integers, the one you should return is the one that is the // farthest from zero. For example closest_integer("14.5") should // return 15 and closest_integer("-14.5") should return -15. function closest_integer(value){ value = parseFloat(value); if(value > 0){ if(value - Math.floor(value) < 0.5){ return Math.floor(value); }else{
} }else{ if(value - Math.floor(value) > -0.5){ return Math.floor(value); }else{ return Math.ceil(value); } } }
return Math.ceil(value);
const assert = require('node:assert'); function test() { let candidate = closest_integer; assert.deepEqual(candidate("10"),10); assert.deepEqual(candidate("14.5"),15); assert.deepEqual(candidate("-15.5"),-16); assert.deepEqual(candidate("15.3"),15); assert.deepEqual(candidate("0"),0); } test();
humaneval-HumanEval_54_same_chars.json-L17
js
//Check if two words have the same characters. // >>> same_chars("eabcdzzzz", "dddzzzzzzzddeddabc") // true // >>> same_chars("abcd", "dddddddabc") // true // >>> same_chars("dddddddabc", "abcd") // true // >>> same_chars("eabcd", "dddddddabc") // false // >>> same_chars("abcd", "dddddddabce") // false // >>> same_chars("eabcdzzzz", "dddzzzzzzzddddabc") // false function same_chars(s0, s1){ let res = true; for(let i = 0; i < s0.length; i++){
res = false; break; } } for(let i = 0; i < s1.length; i++){ if(s0.indexOf(s1[i]) === -1){ res = false; break; } } return res; }
if(s1.indexOf(s0[i]) === -1){
const assert = require('node:assert'); function test() { let candidate = same_chars; assert.deepEqual(candidate("eabcdzzzz", "dddzzzzzzzddeddabc"),true); assert.deepEqual(candidate("abcd", "dddddddabc"),true); assert.deepEqual(candidate("dddddddabc", "abcd"),true); assert.deepEqual(candidate("eabcd", "dddddddabc"),false); assert.deepEqual(candidate("abcd", "dddddddabcf"),false); assert.deepEqual(candidate("eabcdzzzz", "dddzzzzzzzddddabc"),false); assert.deepEqual(candidate("aabb", "aaccc"),false); } test();
humaneval-HumanEval_128_prod_signs.json-L13
js
//You are given an array arr of integers and you need to return // sum of magnitudes of integers multiplied by product of all signs // of each number in the array, represented by 1, -1 or 0. // Note: return undefined for empty arr. // Example: // >>> prod_signs([1, 2, 2, -4]) // 9 // >>> prod_signs([0, 1]) // 0 // >>> prod_signs([]) // undefined function prod_signs(arr){
var len = arr.length; var pro = 1; if(len == 0){ return undefined; } else{ for(var i = 0; i < len; i++){ total += Math.abs(arr[i]); if(arr[i] < 0){ pro *= -1; } else if(arr[i] == 0){ pro *= 0; } } total *= pro; return total; } }
var total = 0;
const assert = require('node:assert'); function test() { let candidate = prod_signs; assert.deepEqual(candidate([1, 2, 2, -4]),-9); assert.deepEqual(candidate([0, 1]),0); assert.deepEqual(candidate([1, 1, 1, 2, 3, -1, 1]),-10); assert.deepEqual(candidate([]),undefined); assert.deepEqual(candidate([2, 4, 1, 2, -1, -1, 9]),20); assert.deepEqual(candidate([-1, 1, -1, 1]),4); assert.deepEqual(candidate([-1, 1, 1, 1]),-4); assert.deepEqual(candidate([-1, 1, 1, 0]),0); } test();
humaneval-HumanEval_33_sort_third.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 { // This function takes an array array list l and returns an array array list l' such that // l' is identical to l in the indicies that are not divisible by three, while its values at the indicies that are divisible by three are equal // to the values of the corresponding indicies of l, but sorted. // >>> sortThird((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l)))) // (new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l))) // >>> sortThird((new ArrayList<Long>(Arrays.asList((long)5l, (long)6l, (long)3l, (long)4l, (long)8l, (long)9l, (long)2l)))) // (new ArrayList<Long>(Arrays.asList((long)2l, (long)6l, (long)3l, (long)4l, (long)8l, (long)9l, (long)5l))) public static ArrayList<Long> sortThird(ArrayList<Long> l) { ArrayList<Long> l_r = new ArrayList<Long>(); ArrayList<Long> l_e = new ArrayList<Long>(); ArrayList<Long> l_s = new ArrayList<Long>(); for (int i = 0; i < l.size(); i++) { if (i % 3 == 0) { l_e.add(l.get(i)); } else { l_r.add(l.get(i)); } } for (int i = 0; i < l_e.size(); i++) { long min = l_e.get(i); for (int j = i; j < l_e.size(); j++) {
min = l_e.get(j); l_e.set(j, l_e.get(i)); l_e.set(i, min); } } } int j = 0; for (int i = 0; i < l.size(); i++) { if (i % 3 == 0) { l_s.add(l_e.get(j)); j++; } else { l_s.add(l_r.get(i - j)); } } return l_s; } }
if (l_e.get(j) < min) {
} public static void main(String[] args) { assert(sortThird((new ArrayList<Long>(Arrays.asList((long)5l, (long)6l, (long)3l, (long)4l, (long)8l, (long)9l, (long)2l)))).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)6l, (long)3l, (long)4l, (long)8l, (long)9l, (long)5l))))); assert(sortThird((new ArrayList<Long>(Arrays.asList((long)5l, (long)8l, (long)3l, (long)4l, (long)6l, (long)9l, (long)2l)))).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)8l, (long)3l, (long)4l, (long)6l, (long)9l, (long)5l))))); assert(sortThird((new ArrayList<Long>(Arrays.asList((long)5l, (long)6l, (long)9l, (long)4l, (long)8l, (long)3l, (long)2l)))).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)6l, (long)9l, (long)4l, (long)8l, (long)3l, (long)5l))))); assert(sortThird((new ArrayList<Long>(Arrays.asList((long)5l, (long)6l, (long)3l, (long)4l, (long)8l, (long)9l, (long)2l, (long)1l)))).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)6l, (long)3l, (long)4l, (long)8l, (long)9l, (long)5l, (long)1l))))); } }
humaneval-HumanEval_10_make_palindrome.json-L16
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){ return s == s.split("").reverse().join(""); };
while(i > 0){ if(is_palindrome(string.substring(0, i))){ return string + string.substring(0, string_length - i).split("").reverse().join(""); } i--; } return string; }
var i = string_length;
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_81_numerical_letter_grade.json-L62
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 { // It is the last week of the semester and the teacher has to give the grades // to students. The teacher has been making her own algorithm for grading. // The only problem is, she has lost the code she used for grading. // She has given you an array array list of GPAs for some students and you have to write // a function that can output an array array list of letter grades using the following table: // GPA | Letter grade // 4.0 A+ // > 3.7 A // > 3.3 A- // > 3.0 B+ // > 2.7 B // > 2.3 B- // > 2.0 C+ // > 1.7 C // > 1.3 C- // > 1.0 D+ // > 0.7 D // > 0.0 D- // 0.0 E // Example: // >>> gradeEquation((new ArrayList<Float>(Arrays.asList((float)4.0f, (float)3l, (float)1.7f, (float)2l, (float)3.5f)))) // (new ArrayList<String>(Arrays.asList((String)"A+", (String)"B", (String)"C-", (String)"C", (String)"A-"))) public static ArrayList<String> numericalLetterGrade(ArrayList<Float> grades) { ArrayList<String> letterGrades = new ArrayList<String>(); for (int i = 0; i < grades.size(); i++) { float currentGrade = grades.get(i); if (currentGrade == 4.0f) { letterGrades.add("A+"); } else if (currentGrade > 3.7f) { letterGrades.add("A"); } else if (currentGrade > 3.3f) { letterGrades.add("A-"); } else if (currentGrade > 3.0f) { letterGrades.add("B+"); } else if (currentGrade > 2.7f) { letterGrades.add("B"); } else if (currentGrade > 2.3f) { letterGrades.add("B-"); } else if (currentGrade > 2.0f) { letterGrades.add("C+"); } else if (currentGrade > 1.7f) { letterGrades.add("C"); } else if (currentGrade > 1.3f) { letterGrades.add("C-"); } else if (currentGrade > 1.0f) { letterGrades.add("D+"); } else if (currentGrade > 0.7f) { letterGrades.add("D"); } else if (currentGrade > 0.0f) { letterGrades.add("D-"); } else { letterGrades.add("E"); }
return letterGrades; } }
}
} public static void main(String[] args) { assert(numericalLetterGrade((new ArrayList<Float>(Arrays.asList((float)4.0f, (float)3l, (float)1.7f, (float)2l, (float)3.5f)))).equals((new ArrayList<String>(Arrays.asList((String)"A+", (String)"B", (String)"C-", (String)"C", (String)"A-"))))); assert(numericalLetterGrade((new ArrayList<Float>(Arrays.asList((float)1.2f)))).equals((new ArrayList<String>(Arrays.asList((String)"D+"))))); assert(numericalLetterGrade((new ArrayList<Float>(Arrays.asList((float)0.5f)))).equals((new ArrayList<String>(Arrays.asList((String)"D-"))))); assert(numericalLetterGrade((new ArrayList<Float>(Arrays.asList((float)0.0f)))).equals((new ArrayList<String>(Arrays.asList((String)"E"))))); assert(numericalLetterGrade((new ArrayList<Float>(Arrays.asList((float)1.0f, (float)0.3f, (float)1.5f, (float)2.8f, (float)3.3f)))).equals((new ArrayList<String>(Arrays.asList((String)"D", (String)"D-", (String)"C-", (String)"B", (String)"B+"))))); assert(numericalLetterGrade((new ArrayList<Float>(Arrays.asList((float)0.0f, (float)0.7f)))).equals((new ArrayList<String>(Arrays.asList((String)"E", (String)"D-"))))); } }
humaneval-HumanEval_133_sum_squares.json-L26
py
from typing import List def sum_squares(lst: List[float]) -> int: """You are given a list of numbers. You need to return the sum of squared numbers in the given list, round each element in the list to the upper int(Ceiling) first. Examples: >>> lst([1.0, 2.0, 3.0]) 14 >>> lst([1.0, 4.0, 9.0]) 98 >>> lst([1.0, 3.0, 5.0, 7.0]) 84 >>> lst([1.4, 4.2, 0.0]) 29 >>> lst([-2.4, 1.0, 1.0]) 6 """ import math for i in range(len(lst)): lst[i] = math.ceil(lst[i]) total = 0 for i in lst:
return total
total += i**2
def check(candidate): assert candidate([1.0, 2.0, 3.0]) == 14 assert candidate([1.0, 2.0, 3.0]) == 14 assert candidate([1.0, 3.0, 5.0, 7.0]) == 84 assert candidate([1.4, 4.2, 0.0]) == 29 assert candidate([-2.4, 1.0, 1.0]) == 6 assert candidate([100.0, 1.0, 15.0, 2.0]) == 10230 assert candidate([10000.0, 10000.0]) == 200000000 assert candidate([-1.4, 4.6, 6.3]) == 75 assert candidate([-1.4, 17.9, 18.9, 19.9]) == 1086 assert candidate([0.0]) == 0 assert candidate([-1.0]) == 1 assert candidate([-1.0, 1.0, 0.0]) == 2 def test_check(): check(sum_squares) test_check()
humaneval-HumanEval_76_is_simple_power.json-L21
js
//Your task is to write a function that returns true if a number x is a simple // power of n and false in other cases. // x is a simple power of n if n**int=x // For example: // >>> is_simple_power(1, 4) // true // >>> is_simple_power(2, 2) // true // >>> is_simple_power(8, 2) // true // >>> is_simple_power(3, 2) // false // >>> is_simple_power(3, 1) // false // >>> is_simple_power(5, 3) // false function is_simple_power(x, n){ if(x===1){ return true; }
return false; } if(x % n !== 0){ return false; } return is_simple_power(x/n, n); }
if(x < n){
const assert = require('node:assert'); function test() { let candidate = is_simple_power; assert.deepEqual(candidate(16, 2),true); assert.deepEqual(candidate(143214, 16),false); assert.deepEqual(candidate(4, 2),true); assert.deepEqual(candidate(9, 3),true); assert.deepEqual(candidate(16, 4),true); assert.deepEqual(candidate(24, 2),false); assert.deepEqual(candidate(128, 4),false); assert.deepEqual(candidate(12, 6),false); assert.deepEqual(candidate(1, 1),true); assert.deepEqual(candidate(1, 12),true); } test();
humaneval-HumanEval_91_is_bored.json-L13
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){
boredoms++; } } return boredoms; }
if(line.match(/^\s*I /)){
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_86_anti_shuffle.json-L14
js
//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" function anti_shuffle(s){
var strings = s.split(" "); strings.forEach(function(str){ var temp = str.split(""); temp.sort(); result.push(temp.join("")); }); return result.join(" "); }
var result = [];
const assert = require('node:assert'); function test() { let candidate = anti_shuffle; assert.deepEqual(candidate("Hi"),"Hi"); assert.deepEqual(candidate("hello"),"ehllo"); assert.deepEqual(candidate("number"),"bemnru"); assert.deepEqual(candidate("abcd"),"abcd"); assert.deepEqual(candidate("Hello World!!!"),"Hello !!!Wdlor"); assert.deepEqual(candidate(""),""); assert.deepEqual(candidate("Hi. My name is Mister Robot. How are you?"),".Hi My aemn is Meirst .Rboot How aer ?ouy"); } test();
humaneval-HumanEval_74_total_match.json-L37
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Write a function that accepts two array lists of strings and returns the array list that has // total number of chars in the all strings of the array list less than the other array list. // if the two array lists have the same number of chars, return the first array list. // Examples // >>> totalMatch((new ArrayList<String>(Arrays.asList())), (new ArrayList<String>(Arrays.asList()))) // (new ArrayList<String>(Arrays.asList())) // >>> totalMatch((new ArrayList<String>(Arrays.asList((String)"hi", (String)"admin"))), (new ArrayList<String>(Arrays.asList((String)"hI", (String)"Hi")))) // (new ArrayList<String>(Arrays.asList((String)"hI", (String)"Hi"))) // >>> totalMatch((new ArrayList<String>(Arrays.asList((String)"hi", (String)"admin"))), (new ArrayList<String>(Arrays.asList((String)"hi", (String)"hi", (String)"admin", (String)"project")))) // (new ArrayList<String>(Arrays.asList((String)"hi", (String)"admin"))) // >>> totalMatch((new ArrayList<String>(Arrays.asList((String)"hi", (String)"admin"))), (new ArrayList<String>(Arrays.asList((String)"hI", (String)"hi", (String)"hi")))) // (new ArrayList<String>(Arrays.asList((String)"hI", (String)"hi", (String)"hi"))) // >>> totalMatch((new ArrayList<String>(Arrays.asList((String)"4"))), (new ArrayList<String>(Arrays.asList((String)"1", (String)"2", (String)"3", (String)"4", (String)"5")))) // (new ArrayList<String>(Arrays.asList((String)"4"))) public static ArrayList<String> totalMatch(ArrayList<String> lst1, ArrayList<String> lst2) { int sum1 = 0; int sum2 = 0; for (String s : lst1) { sum1 += s.length(); } for (String s : lst2) { sum2 += s.length(); } if (sum1 <= sum2) { return lst1; } else { return lst2; }
}
}
} public static void main(String[] args) { assert(totalMatch((new ArrayList<String>(Arrays.asList())), (new ArrayList<String>(Arrays.asList()))).equals((new ArrayList<String>(Arrays.asList())))); assert(totalMatch((new ArrayList<String>(Arrays.asList((String)"hi", (String)"admin"))), (new ArrayList<String>(Arrays.asList((String)"hi", (String)"hi")))).equals((new ArrayList<String>(Arrays.asList((String)"hi", (String)"hi"))))); assert(totalMatch((new ArrayList<String>(Arrays.asList((String)"hi", (String)"admin"))), (new ArrayList<String>(Arrays.asList((String)"hi", (String)"hi", (String)"admin", (String)"project")))).equals((new ArrayList<String>(Arrays.asList((String)"hi", (String)"admin"))))); assert(totalMatch((new ArrayList<String>(Arrays.asList((String)"4"))), (new ArrayList<String>(Arrays.asList((String)"1", (String)"2", (String)"3", (String)"4", (String)"5")))).equals((new ArrayList<String>(Arrays.asList((String)"4"))))); assert(totalMatch((new ArrayList<String>(Arrays.asList((String)"hi", (String)"admin"))), (new ArrayList<String>(Arrays.asList((String)"hI", (String)"Hi")))).equals((new ArrayList<String>(Arrays.asList((String)"hI", (String)"Hi"))))); assert(totalMatch((new ArrayList<String>(Arrays.asList((String)"hi", (String)"admin"))), (new ArrayList<String>(Arrays.asList((String)"hI", (String)"hi", (String)"hi")))).equals((new ArrayList<String>(Arrays.asList((String)"hI", (String)"hi", (String)"hi"))))); assert(totalMatch((new ArrayList<String>(Arrays.asList((String)"hi", (String)"admin"))), (new ArrayList<String>(Arrays.asList((String)"hI", (String)"hi", (String)"hii")))).equals((new ArrayList<String>(Arrays.asList((String)"hi", (String)"admin"))))); assert(totalMatch((new ArrayList<String>(Arrays.asList())), (new ArrayList<String>(Arrays.asList((String)"this")))).equals((new ArrayList<String>(Arrays.asList())))); assert(totalMatch((new ArrayList<String>(Arrays.asList((String)"this"))), (new ArrayList<String>(Arrays.asList()))).equals((new ArrayList<String>(Arrays.asList())))); } }
humaneval-HumanEval_155_even_odd_count.json-L18
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_137_compare_one.json-L64
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(',', '.') if float(a_tmp) > b: return a elif float(a_tmp) < b: return b else: return None
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
elif isinstance(a, int) and isinstance(b, str):
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_99_closest_integer.json-L25
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Create a function that takes a value (string) representing a number // and returns the closest integer to it. If the number is equidistant // from two integers, round it away from zero. // Examples // >>> closestInteger(("10")) // (10l) // >>> closestInteger(("15.3")) // (15l) // Note: // Rounding away from zero means that if the given number is equidistant // from two integers, the one you should return is the one that is the // farthest from zero. For example closest_integer("14.5") should // return 15 and closest_integer("-14.5") should return -15. public static long closestInteger(String value) { BigDecimal bd = new BigDecimal(value); bd = bd.setScale(0, BigDecimal.ROUND_HALF_UP);
} }
return bd.longValue();
} public static void main(String[] args) { assert(closestInteger(("10")) == (10l)); assert(closestInteger(("14.5")) == (15l)); assert(closestInteger(("-15.5")) == (-16l)); assert(closestInteger(("15.3")) == (15l)); assert(closestInteger(("0")) == (0l)); } }
humaneval-HumanEval_36_fizz_buzz.json-L13
py
def fizz_buzz(n: int) -> int: """Return the number of times the digit 7 appears in integers less than n which are divisible by 11 or 13. >>> fizz_buzz(50) 0 >>> fizz_buzz(78) 2 >>> fizz_buzz(79) 3 """ x = 0 for i in range(n): if i % 11 == 0 or i % 13 == 0:
return x
x += str(i).count('7')
def check(candidate): assert candidate(50) == 0 assert candidate(78) == 2 assert candidate(79) == 3 assert candidate(100) == 3 assert candidate(200) == 6 assert candidate(4000) == 192 assert candidate(10000) == 639 assert candidate(100000) == 8026 def test_check(): check(fizz_buzz) test_check()
humaneval-HumanEval_43_pairs_sum_to_zero.json-L27
js
//pairs_sum_to_zero takes an array of integers as an input. // it returns true if there are two distinct elements in the array that // sum to zero, and false otherwise. // >>> pairs_sum_to_zero([1, 3, 5, 0]) // false // >>> pairs_sum_to_zero([1, 3, -2, 1]) // false // >>> pairs_sum_to_zero([1, 2, 3, 7]) // false // >>> pairs_sum_to_zero([2, 4, -5, 3, 5, 7]) // true // >>> pairs_sum_to_zero([1]) // false function pairs_sum_to_zero(l){ var i = 0 while (i < l.length){ var j = i+1 while (j < l.length){ if ((l[i] + l[j]) === 0){ return true } j = j + 1 } i = i + 1 } return false
}
const assert = require('node:assert'); function test() { let candidate = pairs_sum_to_zero; assert.deepEqual(candidate([1, 3, 5, 0]),false); assert.deepEqual(candidate([1, 3, -2, 1]),false); assert.deepEqual(candidate([1, 2, 3, 7]),false); assert.deepEqual(candidate([2, 4, -5, 3, 5, 7]),true); assert.deepEqual(candidate([1]),false); assert.deepEqual(candidate([-3, 9, -1, 3, 2, 30]),true); assert.deepEqual(candidate([-3, 9, -1, 3, 2, 31]),true); assert.deepEqual(candidate([-3, 9, -1, 4, 2, 30]),false); assert.deepEqual(candidate([-3, 9, -1, 4, 2, 31]),false); } test();
humaneval-HumanEval_158_find_max.json-L21
py
from typing import List def find_max(words: List[str]) -> str: """Write a function that accepts a list of strings. The list contains different words. Return the word with maximum number of unique characters. If multiple strings have maximum number of unique characters, return the one which comes first in lexicographical order. >>> find_max(['name', 'of', 'string']) 'string' >>> find_max(['name', 'enam', 'game']) 'enam' >>> find_max(['aaaaaaa', 'bb', 'cc']) 'aaaaaaa' """ max_num = 0 max_word = "" for word in words: unique_num = len(set(word)) if unique_num > max_num:
max_word = word elif unique_num == max_num: if word < max_word: max_word = word return max_word
max_num = unique_num
def check(candidate): assert candidate(['name', 'of', 'string']) == 'string' assert candidate(['name', 'enam', 'game']) == 'enam' assert candidate(['aaaaaaa', 'bb', 'cc']) == 'aaaaaaa' assert candidate(['abc', 'cba']) == 'abc' assert candidate(['play', 'this', 'game', 'of', 'footbott']) == 'footbott' assert candidate(['we', 'are', 'gonna', 'rock']) == 'gonna' assert candidate(['we', 'are', 'a', 'mad', 'nation']) == 'nation' assert candidate(['this', 'is', 'a', 'prrk']) == 'this' assert candidate(['b']) == 'b' assert candidate(['play', 'play', 'play']) == 'play' def test_check(): check(find_max) test_check()
humaneval-HumanEval_11_string_xor.json-L18
js
//Input are two strings a and b consisting only of 1s and 0s. // Perform binary XOR on these inputs and return result also as a string. // >>> string_xor("010", "110") // "100" function string_xor(a, b){ var arrayA = []; var arrayB = []; var arrayXOR = []; var result = ''; for (var i = 0; i < a.length; i++) { arrayA.push(parseInt(a[i])); } for (var j = 0; j < b.length; j++) { arrayB.push(parseInt(b[j])); } for (var k = 0; k < arrayA.length; k++) { if (arrayA[k] !== arrayB[k]) {
} else { arrayXOR.push(0); } } result = arrayXOR.join(''); return result; }
arrayXOR.push(1);
const assert = require('node:assert'); function test() { let candidate = string_xor; assert.deepEqual(candidate("111000", "101010"),"010010"); assert.deepEqual(candidate("1", "1"),"0"); assert.deepEqual(candidate("0101", "0000"),"0101"); } test();
humaneval-HumanEval_27_flip_case.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 { // For a given string, flip lowercase characters to uppercase and uppercase to lowercase. // >>> flipCase(("Hello")) // ("hELLO") public static String flipCase(String string) { String answer = ""; for (int i = 0; i < string.length(); i++) { if (Character.isLowerCase(string.charAt(i))) { answer += Character.toUpperCase(string.charAt(i)); } else { answer += Character.toLowerCase(string.charAt(i)); } } return answer;
}
}
} public static void main(String[] args) { assert(flipCase(("")).equals((""))); assert(flipCase(("Hello!")).equals(("hELLO!"))); assert(flipCase(("These violent delights have violent ends")).equals(("tHESE VIOLENT DELIGHTS HAVE VIOLENT ENDS"))); } }
humaneval-HumanEval_137_compare_one.json-L76
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(',', '.') 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
return b
elif 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_63_fibfib.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 { // The FibFib number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows: // fibfib(0) == 0 // fibfib(1) == 0 // fibfib(2) == 1 // fibfib(n) == fibfib(n-1) + fibfib(n-2) + fibfib(n-3). // Please write a function to efficiently compute the n-th element of the fibfib number sequence. // >>> fibfib((1l)) // (0l) // >>> fibfib((5l)) // (4l) // >>> fibfib((8l)) // (24l) public static long fibfib(long n) { if (n == 0) { return 0; } if (n == 1) { return 0; } if (n == 2) { return 1; } long[] memo = new long[(int) n + 1]; memo[0] = 0; memo[1] = 0; memo[2] = 1; for (int i = 3; i <= n; i++) { memo[i] = memo[i - 1] + memo[i - 2] + memo[i - 3]; } return memo[(int) n];
}
}
} public static void main(String[] args) { assert(fibfib((2l)) == (1l)); assert(fibfib((1l)) == (0l)); assert(fibfib((5l)) == (4l)); assert(fibfib((8l)) == (24l)); assert(fibfib((10l)) == (81l)); assert(fibfib((12l)) == (274l)); assert(fibfib((14l)) == (927l)); } }
humaneval-HumanEval_118_get_closest_vowel.json-L20
py
def get_closest_vowel(word: str) -> str: """You are given a word. Your task is to find the closest vowel that stands between two consonants from the right side of the word (case sensitive). Vowels in the beginning and ending doesn't count. Return empty string if you didn't find any vowel met the above condition. You may assume that the given string contains English letter only. Example: >>> get_closest_vowel('yogurt') 'u' >>> get_closest_vowel('FULL') 'U' >>> get_closest_vowel('quick') '' >>> get_closest_vowel('ab') '' """
return '' for i in range(len(word) - 2, 0, -1): if word[i] in 'aeiouAEIOU' and word[i-1] not in 'aeiouAEIOU' and word[i+1] not in 'aeiouAEIOU': return word[i] return ''
if len(word) < 3:
def check(candidate): assert candidate('yogurt') == 'u' assert candidate('full') == 'u' assert candidate('easy') == '' assert candidate('eAsy') == '' assert candidate('ali') == '' assert candidate('bad') == 'a' assert candidate('most') == 'o' assert candidate('ab') == '' assert candidate('ba') == '' assert candidate('quick') == '' assert candidate('anime') == 'i' assert candidate('Asia') == '' assert candidate('Above') == 'o' def test_check(): check(get_closest_vowel) test_check()
humaneval-HumanEval_49_modp.json-L29
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 2^n modulo p (be aware of numerics). // >>> modp((3l), (5l)) // (3l) // >>> modp((1101l), (101l)) // (2l) // >>> modp((0l), (101l)) // (1l) // >>> modp((3l), (11l)) // (8l) // >>> modp((100l), (101l)) // (1l) public static long modp(long n, long p) { if (n == 0) return 1; long sqrt = modp(n / 2, p); sqrt = (sqrt * sqrt) % p; if (n % 2 == 0) { return sqrt; } return (sqrt * 2) % p; }
}
} public static void main(String[] args) { assert(modp((3l), (5l)) == (3l)); assert(modp((1101l), (101l)) == (2l)); assert(modp((0l), (101l)) == (1l)); assert(modp((3l), (11l)) == (8l)); assert(modp((100l), (101l)) == (1l)); assert(modp((30l), (5l)) == (4l)); assert(modp((31l), (5l)) == (3l)); } }
humaneval-HumanEval_56_correct_bracketing.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 { // brackets is a string of "<" and ">". // return true if every opening bracket has a corresponding closing bracket. // >>> correctBracketing(("<")) // (false) // >>> correctBracketing(("<>")) // (true) // >>> correctBracketing(("<<><>>")) // (true) // >>> correctBracketing(("><<>")) // (false) public static boolean correctBracketing(String brackets) { int open = 0; for (int i = 0; i < brackets.length(); i++) { char c = brackets.charAt(i); if (c == '<') {
} else { open--; } if (open < 0) { return false; } } return open == 0; } }
open++;
} public static void main(String[] args) { assert(correctBracketing(("<>")) == (true)); assert(correctBracketing(("<<><>>")) == (true)); assert(correctBracketing(("<><><<><>><>")) == (true)); assert(correctBracketing(("<><><<<><><>><>><<><><<>>>")) == (true)); assert(correctBracketing(("<<<><>>>>")) == (false)); assert(correctBracketing(("><<>")) == (false)); assert(correctBracketing(("<")) == (false)); assert(correctBracketing(("<<<<")) == (false)); assert(correctBracketing((">")) == (false)); assert(correctBracketing(("<<>")) == (false)); assert(correctBracketing(("<><><<><>><>><<>")) == (false)); assert(correctBracketing(("<><><<><>><>>><>")) == (false)); } }
humaneval-HumanEval_119_match_parens.json-L32
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // You are given an array array list of two strings, both strings consist of open // parentheses '(' or close parentheses ')' only. // Your job is to check if it is possible to concatenate the two strings in // some order, that the resulting string will be good. // A string S is considered to be good if and only if all parentheses in S // are balanced. For example: the string '(())()' is good, while the string // '())' is not. // Return 'Yes' if there's a way to make a good string, and return 'No' otherwise. // Examples: // >>> matchParens((new ArrayList<String>(Arrays.asList((String)"()(", (String)")")))) // ("Yes") // >>> matchParens((new ArrayList<String>(Arrays.asList((String)")", (String)")")))) // ("No") public static String matchParens(ArrayList<String> lst) { String s1 = lst.get(0); String s2 = lst.get(1); String s3 = s1+s2; String s4 = s2+s1; int c1 = 0; int c2 = 0; for (int i = 0; i < s3.length(); i++) { if (s3.charAt(i) == '(') c1 += 1; else c1 -= 1;
} for (int i = 0; i < s4.length(); i++) { if (s4.charAt(i) == '(') c2 += 1; else c2 -= 1; if (c2 < 0) break; } if (c1 == 0 || c2 == 0) return "Yes"; else return "No"; } }
if (c1 < 0) break;
} public static void main(String[] args) { assert(matchParens((new ArrayList<String>(Arrays.asList((String)"()(", (String)")")))).equals(("Yes"))); assert(matchParens((new ArrayList<String>(Arrays.asList((String)")", (String)")")))).equals(("No"))); assert(matchParens((new ArrayList<String>(Arrays.asList((String)"(()(())", (String)"())())")))).equals(("No"))); assert(matchParens((new ArrayList<String>(Arrays.asList((String)")())", (String)"(()()(")))).equals(("Yes"))); assert(matchParens((new ArrayList<String>(Arrays.asList((String)"(())))", (String)"(()())((")))).equals(("Yes"))); assert(matchParens((new ArrayList<String>(Arrays.asList((String)"()", (String)"())")))).equals(("No"))); assert(matchParens((new ArrayList<String>(Arrays.asList((String)"(()(", (String)"()))()")))).equals(("Yes"))); assert(matchParens((new ArrayList<String>(Arrays.asList((String)"((((", (String)"((())")))).equals(("No"))); assert(matchParens((new ArrayList<String>(Arrays.asList((String)")(()", (String)"(()(")))).equals(("No"))); assert(matchParens((new ArrayList<String>(Arrays.asList((String)")(", (String)")(")))).equals(("No"))); assert(matchParens((new ArrayList<String>(Arrays.asList((String)"(", (String)")")))).equals(("Yes"))); assert(matchParens((new ArrayList<String>(Arrays.asList((String)")", (String)"(")))).equals(("Yes"))); } }
humaneval-HumanEval_147_get_max_triples.json-L27
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // You are given a positive integer n. You have to create an integer array array list a of length n. // For each i (1 ≤ i ≤ n), the value of a[i] = i * i - i + 1. // Return the number of triples (a[i], a[j], a[k]) of a where i < j < k, // and a[i] + a[j] + a[k] is a multiple of 3. // Example : // >>> getMaxTriples((5l)) // (1l) // Explanation: // a = [1, 3, 7, 13, 21] // The only valid triple is (1, 7, 13). public static long getMaxTriples(long n) { int count = 0; ArrayList<Integer> arrayList = new ArrayList<Integer>(); for (int i = 1; i <= n; i++) { arrayList.add(i * i - i + 1); } for (int i = 0; i < arrayList.size(); i++) { for (int j = i + 1; j < arrayList.size(); j++) {
if ((arrayList.get(i) + arrayList.get(j) + arrayList.get(k)) % 3 == 0) { count++; } } } } return count; } }
for (int k = j + 1; k < arrayList.size(); k++) {
} public static void main(String[] args) { assert(getMaxTriples((5l)) == (1l)); assert(getMaxTriples((6l)) == (4l)); assert(getMaxTriples((10l)) == (36l)); assert(getMaxTriples((100l)) == (53361l)); } }
humaneval-HumanEval_1_separate_paren_groups.json-L25
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // 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(); }
temp.append(c); } else if (c == ')') { open_paren--; temp.append(c); if (open_paren == 0) { output.add(temp.toString()); } } } return output; } }
open_paren++;
} 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_68_pluck.json-L49
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((long)minIndex); return newArr; } }
newArr.add(minValue);
} 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_135_can_arrange.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 returns the largest index of an element which // is not greater than or equal to the element immediately preceding it. If // no such element exists then return -1. The given array array list will not contain // duplicate values. // Examples: // >>> canArrange((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)4l, (long)3l, (long)5l)))) // (3l) // >>> canArrange((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l)))) // (-1l) public static long canArrange(ArrayList<Long> arr) { long p = -1l; for (int i = arr.size() - 1; i > 0; i--) { if (arr.get(i) < arr.get(i - 1)) { p = (long)i; break;
} return p; } }
}
} public static void main(String[] args) { assert(canArrange((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)4l, (long)3l, (long)5l)))) == (3l)); assert(canArrange((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)4l, (long)5l)))) == (-1l)); assert(canArrange((new ArrayList<Long>(Arrays.asList((long)1l, (long)4l, (long)2l, (long)5l, (long)6l, (long)7l, (long)8l, (long)9l, (long)10l)))) == (2l)); assert(canArrange((new ArrayList<Long>(Arrays.asList((long)4l, (long)8l, (long)5l, (long)7l, (long)3l)))) == (4l)); assert(canArrange((new ArrayList<Long>(Arrays.asList()))) == (-1l)); } }
humaneval-HumanEval_17_parse_music.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 { // 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 list 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 // >>> parseMusic(("o o| .| o| o| .| .| .| .| o o")) // (new ArrayList<Long>(Arrays.asList((long)4l, (long)2l, (long)1l, (long)2l, (long)2l, (long)1l, (long)1l, (long)1l, (long)1l, (long)4l, (long)4l))) public static ArrayList<Long> parseMusic(String music_string) { ArrayList<Long> res = new ArrayList<Long>(); char[] chars = music_string.toCharArray(); for (int i = 0; i < chars.length; i++) { if (chars[i] == 'o') { if (i + 1 < chars.length && chars[i + 1] == '|') {
i += 1; } else { res.add((long)4l); } } else if (chars[i] == '.') { if (i + 1 < chars.length && chars[i + 1] == '|') { res.add((long)1l); i += 1; } } } return res; } }
res.add((long)2l);
} public static void main(String[] args) { assert(parseMusic(("")).equals((new ArrayList<Long>(Arrays.asList())))); assert(parseMusic(("o o o o")).equals((new ArrayList<Long>(Arrays.asList((long)4l, (long)4l, (long)4l, (long)4l))))); assert(parseMusic((".| .| .| .|")).equals((new ArrayList<Long>(Arrays.asList((long)1l, (long)1l, (long)1l, (long)1l))))); assert(parseMusic(("o| o| .| .| o o o o")).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)2l, (long)1l, (long)1l, (long)4l, (long)4l, (long)4l, (long)4l))))); assert(parseMusic(("o| .| o| .| o o| o o|")).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)1l, (long)2l, (long)1l, (long)4l, (long)2l, (long)4l, (long)2l))))); } }
humaneval-HumanEval_121_solution.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 non-empty array list of integers, return the sum of all of the odd elements that are in even positions. // Examples // >>> solution((new ArrayList<Long>(Arrays.asList((long)5l, (long)8l, (long)7l, (long)1l)))) // (12l) // >>> solution((new ArrayList<Long>(Arrays.asList((long)3l, (long)3l, (long)3l, (long)3l, (long)3l)))) // (9l) // >>> solution((new ArrayList<Long>(Arrays.asList((long)30l, (long)13l, (long)24l, (long)321l)))) // (0l) public static long solution(ArrayList<Long> lst) { long sum = 0; for (int i = 0; i < lst.size(); i++) { if (i % 2 == 0 && lst.get(i) % 2 == 1) { sum += lst.get(i); }
return sum; } }
}
} public static void main(String[] args) { assert(solution((new ArrayList<Long>(Arrays.asList((long)5l, (long)8l, (long)7l, (long)1l)))) == (12l)); assert(solution((new ArrayList<Long>(Arrays.asList((long)3l, (long)3l, (long)3l, (long)3l, (long)3l)))) == (9l)); assert(solution((new ArrayList<Long>(Arrays.asList((long)30l, (long)13l, (long)24l, (long)321l)))) == (0l)); assert(solution((new ArrayList<Long>(Arrays.asList((long)5l, (long)9l)))) == (5l)); assert(solution((new ArrayList<Long>(Arrays.asList((long)2l, (long)4l, (long)8l)))) == (0l)); assert(solution((new ArrayList<Long>(Arrays.asList((long)30l, (long)13l, (long)23l, (long)32l)))) == (23l)); assert(solution((new ArrayList<Long>(Arrays.asList((long)3l, (long)13l, (long)2l, (long)9l)))) == (3l)); } }
humaneval-HumanEval_131_digits.json-L28
js
//Given a positive integer n, return the product of the odd digits. // Return 0 if all digits are even. // For example: // >>> digits(1) // 1 // >>> digits(4) // 0 // >>> digits(235) // 15 function digits(n){ if(!n){ return "error"; } if(n < 0){ return "error"; } var temp = 0; var prod = 1; var odd = true; for(n; n > 0; n = Math.floor(n/10)){ temp = n % 10; if(temp % 2 != 0){ prod *= temp; odd = false; } } if(odd){
} return prod; }
return 0;
const assert = require('node:assert'); function test() { let candidate = digits; assert.deepEqual(candidate(5),5); assert.deepEqual(candidate(54),5); assert.deepEqual(candidate(120),1); assert.deepEqual(candidate(5014),5); assert.deepEqual(candidate(98765),315); assert.deepEqual(candidate(5576543),2625); assert.deepEqual(candidate(2468),0); } test();
humaneval-HumanEval_75_is_multiply_prime.json-L21
js
//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 function is_multiply_prime(a){ a = Math.abs(a); const prime = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]; let i = 0; let check = []; while(a != 1){ if(a % prime[i] == 0){ a = a / prime[i]; check.push(prime[i]); }else{ i++; } }
return true; }else{ return false; } }
if(check.length == 3){
const assert = require('node:assert'); function test() { let candidate = is_multiply_prime; assert.deepEqual(candidate(5),false); assert.deepEqual(candidate(30),true); assert.deepEqual(candidate(8),true); assert.deepEqual(candidate(10),false); assert.deepEqual(candidate(125),true); assert.deepEqual(candidate(105),true); assert.deepEqual(candidate(126),false); assert.deepEqual(candidate(729),false); assert.deepEqual(candidate(891),false); assert.deepEqual(candidate(1001),true); } test();
humaneval-HumanEval_99_closest_integer.json-L21
py
def closest_integer(value: str) -> int: """ Create a function that takes a value (string) representing a number and returns the closest integer to it. If the number is equidistant from two integers, round it away from zero. Examples >>> closest_integer('10') 10 >>> closest_integer('15.3') 15 Note: Rounding away from zero means that if the given number is equidistant from two integers, the one you should return is the one that is the farthest from zero. For example closest_integer("14.5") should return 15 and closest_integer("-14.5") should return -15. """ value = float(value) integer_val = int(value)
return integer_val if abs(value - integer_val) < 0.5 else (integer_val + 1) if value > 0 else (integer_val - 1)
def check(candidate): assert candidate('10') == 10 assert candidate('14.5') == 15 assert candidate('-15.5') == -16 assert candidate('15.3') == 15 assert candidate('0') == 0 def test_check(): check(closest_integer) test_check()
humaneval-HumanEval_124_valid_date.json-L32
js
//You have to write a function which validates a given date string and // returns true if the date is valid otherwise false. // The date is valid if all of the following rules are satisfied: // 1. The date string is not empty. // 2. The number of days is not less than 1 or higher than 31 days for months 1,3,5,7,8,10,12. And the number of days is not less than 1 or higher than 30 days for months 4,6,9,11. And, the number of days is not less than 1 or higher than 29 for the month 2. // 3. The months should not be less than 1 or higher than 12. // 4. The date should be in the format: mm-dd-yyyy // >>> valid_date("03-11-2000") // true // >>> valid_date("15-01-2012") // false // >>> valid_date("04-0-2040") // false // >>> valid_date("06-04-2020") // true // >>> valid_date("06/04/2020") // false function valid_date(date){ var date_arr = date.split("-"); if(date_arr.length == 3){ var month = parseInt(date_arr[0]); var day = parseInt(date_arr[1]); var year = parseInt(date_arr[2]); if(month < 1 || month > 12){ return false; }else if(month == 2){ if(day < 1 || day > 29){ return false; } }else if((month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) && (day < 1 || day > 31)){ return false;
return false; } return true; } return false; }
}else if((month == 4 || month == 6 || month == 9 || month == 11) && (day < 1 || day > 30)){
const assert = require('node:assert'); function test() { let candidate = valid_date; assert.deepEqual(candidate("03-11-2000"),true); assert.deepEqual(candidate("15-01-2012"),false); assert.deepEqual(candidate("04-0-2040"),false); assert.deepEqual(candidate("06-04-2020"),true); assert.deepEqual(candidate("01-01-2007"),true); assert.deepEqual(candidate("03-32-2011"),false); assert.deepEqual(candidate(""),false); assert.deepEqual(candidate("04-31-3000"),false); assert.deepEqual(candidate("06-06-2005"),true); assert.deepEqual(candidate("21-31-2000"),false); assert.deepEqual(candidate("04-12-2003"),true); assert.deepEqual(candidate("04122003"),false); assert.deepEqual(candidate("20030412"),false); assert.deepEqual(candidate("2003-04"),false); assert.deepEqual(candidate("2003-04-12"),false); assert.deepEqual(candidate("04-2003"),false); } test();
humaneval-HumanEval_152_compare.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 { // 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_116_sort_array.json-L14
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;
if (aBinary === bBinary) { return a - b; } else { return aBinary - bBinary; } }); }
let bBinary = b.toString(2).split('').filter(el => el === '1').length;
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_55_fib.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 { // Return n-th Fibonacci number. // >>> fib((10l)) // (55l) // >>> fib((1l)) // (1l) // >>> fib((8l)) // (21l) public static long fib(long n) { if (n == 0) { return 0l; } else if (n == 1) { return 1l;
else { return Problem.fib((n - 1)) + Problem.fib((n - 2)); } } }
}
} public static void main(String[] args) { assert(fib((10l)) == (55l)); assert(fib((1l)) == (1l)); assert(fib((8l)) == (21l)); assert(fib((11l)) == (89l)); assert(fib((12l)) == (144l)); } }
humaneval-HumanEval_67_fruit_distribution.json-L29
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // In this task, you will be given a string that represents a number of apples and oranges // that are distributed in a basket of fruit this basket contains // apples, oranges, and mango fruits. Given the string that represents the total number of // the oranges and apples and an integer that represent the total number of the fruits // in the basket return the number of the mango fruits in the basket. // for examble: // >>> fruitDistribution(("5 apples and 6 oranges"), (19l)) // (8l) // >>> fruitDistribution(("0 apples and 1 oranges"), (3l)) // (2l) // >>> fruitDistribution(("2 apples and 3 oranges"), (100l)) // (95l) // >>> fruitDistribution(("100 apples and 1 oranges"), (120l)) // (19l) public static long fruitDistribution(String s, long n) { String[] splitted = s.split(" "); long apples = Long.parseLong(splitted[0]); long oranges = Long.parseLong(splitted[3]); return n - apples - oranges; }
}
} public static void main(String[] args) { assert(fruitDistribution(("5 apples and 6 oranges"), (19l)) == (8l)); assert(fruitDistribution(("5 apples and 6 oranges"), (21l)) == (10l)); assert(fruitDistribution(("0 apples and 1 oranges"), (3l)) == (2l)); assert(fruitDistribution(("1 apples and 0 oranges"), (3l)) == (2l)); assert(fruitDistribution(("2 apples and 3 oranges"), (100l)) == (95l)); assert(fruitDistribution(("2 apples and 3 oranges"), (5l)) == (0l)); assert(fruitDistribution(("1 apples and 100 oranges"), (120l)) == (19l)); } }
humaneval-HumanEval_94_skjkasdkd.json-L17
js
//You are given an array of integers. // You need to find the largest prime value and return the sum of its digits. // Examples: // >>> skjkasdkd([0, 3, 2, 1, 3, 5, 7, 4, 5, 5, 5, 2, 181, 32, 4, 32, 3, 2, 32, 324, 4, 3]) // 10 // >>> skjkasdkd([1, 0, 1, 8, 2, 4597, 2, 1, 3, 40, 1, 2, 1, 2, 4, 2, 5, 1]) // 25 // >>> skjkasdkd([1, 3, 1, 32, 5107, 34, 83278, 109, 163, 23, 2323, 32, 30, 1, 9, 3]) // 13 // >>> skjkasdkd([0, 724, 32, 71, 99, 32, 6, 0, 5, 91, 83, 0, 5, 6]) // 11 // >>> skjkasdkd([0, 81, 12, 3, 1, 21]) // 3 // >>> skjkasdkd([0, 8, 1, 2, 1, 7]) // 7 function skjkasdkd(lst){
if (n<2) return false; for (let i=2; i<=Math.sqrt(n); i++){ if (n%i==0) return false; } return true; } let max = Math.max(...lst.filter(x=>prime(x))); let digits = String(max).split(''); let sum = 0; for (let i=0; i<digits.length; i++){ sum += Number(digits[i]); } return sum; }
function prime(n){
const assert = require('node:assert'); function test() { let candidate = skjkasdkd; assert.deepEqual(candidate([0, 3, 2, 1, 3, 5, 7, 4, 5, 5, 5, 2, 181, 32, 4, 32, 3, 2, 32, 324, 4, 3]),10); assert.deepEqual(candidate([1, 0, 1, 8, 2, 4597, 2, 1, 3, 40, 1, 2, 1, 2, 4, 2, 5, 1]),25); assert.deepEqual(candidate([1, 3, 1, 32, 5107, 34, 83278, 109, 163, 23, 2323, 32, 30, 1, 9, 3]),13); assert.deepEqual(candidate([0, 724, 32, 71, 99, 32, 6, 0, 5, 91, 83, 0, 5, 6]),11); assert.deepEqual(candidate([0, 81, 12, 3, 1, 21]),3); assert.deepEqual(candidate([0, 8, 1, 2, 1, 7]),7); assert.deepEqual(candidate([8191]),19); assert.deepEqual(candidate([8191, 123456, 127, 7]),19); assert.deepEqual(candidate([127, 97, 8192]),10); } test();
humaneval-HumanEval_17_parse_music.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 representing musical notes in a special ASCII format. // Your task is to parse this string and return array list 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 // >>> parseMusic(("o o| .| o| o| .| .| .| .| o o")) // (new ArrayList<Long>(Arrays.asList((long)4l, (long)2l, (long)1l, (long)2l, (long)2l, (long)1l, (long)1l, (long)1l, (long)1l, (long)4l, (long)4l))) public static ArrayList<Long> parseMusic(String music_string) { ArrayList<Long> res = new ArrayList<Long>(); char[] chars = music_string.toCharArray(); for (int i = 0; i < chars.length; i++) { if (chars[i] == 'o') { if (i + 1 < chars.length && chars[i + 1] == '|') { res.add((long)2l); i += 1; } else { res.add((long)4l); } } else if (chars[i] == '.') { if (i + 1 < chars.length && chars[i + 1] == '|') { res.add((long)1l); i += 1; } }
return res; } }
}
} public static void main(String[] args) { assert(parseMusic(("")).equals((new ArrayList<Long>(Arrays.asList())))); assert(parseMusic(("o o o o")).equals((new ArrayList<Long>(Arrays.asList((long)4l, (long)4l, (long)4l, (long)4l))))); assert(parseMusic((".| .| .| .|")).equals((new ArrayList<Long>(Arrays.asList((long)1l, (long)1l, (long)1l, (long)1l))))); assert(parseMusic(("o| o| .| .| o o o o")).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)2l, (long)1l, (long)1l, (long)4l, (long)4l, (long)4l, (long)4l))))); assert(parseMusic(("o| .| o| .| o o| o o|")).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)1l, (long)2l, (long)1l, (long)4l, (long)2l, (long)4l, (long)2l))))); } }
humaneval-HumanEval_99_closest_integer.json-L21
js
//Create a function that takes a value (string) representing a number // and returns the closest integer to it. If the number is equidistant // from two integers, round it away from zero. // Examples // >>> closest_integer("10") // 10 // >>> closest_integer("15.3") // 15 // Note: // Rounding away from zero means that if the given number is equidistant // from two integers, the one you should return is the one that is the // farthest from zero. For example closest_integer("14.5") should // return 15 and closest_integer("-14.5") should return -15. function closest_integer(value){ value = parseFloat(value); if(value > 0){ if(value - Math.floor(value) < 0.5){ return Math.floor(value); }else{ return Math.ceil(value);
}else{ if(value - Math.floor(value) > -0.5){ return Math.floor(value); }else{ return Math.ceil(value); } } }
}
const assert = require('node:assert'); function test() { let candidate = closest_integer; assert.deepEqual(candidate("10"),10); assert.deepEqual(candidate("14.5"),15); assert.deepEqual(candidate("-15.5"),-16); assert.deepEqual(candidate("15.3"),15); assert.deepEqual(candidate("0"),0); } test();
humaneval-HumanEval_135_can_arrange.json-L27
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Create a function which returns the largest index of an element which // is not greater than or equal to the element immediately preceding it. If // no such element exists then return -1. The given array array list will not contain // duplicate values. // Examples: // >>> canArrange((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)4l, (long)3l, (long)5l)))) // (3l) // >>> canArrange((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l)))) // (-1l) public static long canArrange(ArrayList<Long> arr) { long p = -1l; for (int i = arr.size() - 1; i > 0; i--) { if (arr.get(i) < arr.get(i - 1)) { p = (long)i; break; } } return p;
}
}
} public static void main(String[] args) { assert(canArrange((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)4l, (long)3l, (long)5l)))) == (3l)); assert(canArrange((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)4l, (long)5l)))) == (-1l)); assert(canArrange((new ArrayList<Long>(Arrays.asList((long)1l, (long)4l, (long)2l, (long)5l, (long)6l, (long)7l, (long)8l, (long)9l, (long)10l)))) == (2l)); assert(canArrange((new ArrayList<Long>(Arrays.asList((long)4l, (long)8l, (long)5l, (long)7l, (long)3l)))) == (4l)); assert(canArrange((new ArrayList<Long>(Arrays.asList()))) == (-1l)); } }
humaneval-HumanEval_43_pairs_sum_to_zero.json-L21
py
from typing import List def pairs_sum_to_zero(l: List[int]) -> bool: """ pairs_sum_to_zero takes a list of integers as an input. it returns True if there are two distinct elements in the list that sum to zero, and False otherwise. >>> pairs_sum_to_zero([1, 3, 5, 0]) False >>> pairs_sum_to_zero([1, 3, -2, 1]) False >>> pairs_sum_to_zero([1, 2, 3, 7]) False >>> pairs_sum_to_zero([2, 4, -5, 3, 5, 7]) True >>> pairs_sum_to_zero([1]) False """ for x in l: for y in l:
return True return False
if x+y == 0 and x != y:
def check(candidate): assert candidate([1, 3, 5, 0]) == False assert candidate([1, 3, -2, 1]) == False assert candidate([1, 2, 3, 7]) == False assert candidate([2, 4, -5, 3, 5, 7]) == True assert candidate([1]) == False assert candidate([-3, 9, -1, 3, 2, 30]) == True assert candidate([-3, 9, -1, 3, 2, 31]) == True assert candidate([-3, 9, -1, 4, 2, 30]) == False assert candidate([-3, 9, -1, 4, 2, 31]) == False def test_check(): check(pairs_sum_to_zero) test_check()
humaneval-HumanEval_51_remove_vowels.json-L15
py
def remove_vowels(text: str) -> str: """ remove_vowels is a function that takes string and returns string without vowels. >>> remove_vowels('') '' >>> remove_vowels('abcdef') 'bcdf' >>> remove_vowels('aaaaa') '' >>> remove_vowels('aaBAA') 'B' >>> remove_vowels('zbcd') 'zbcd' """
return ''.join(filter(lambda x: x not in vowels, text))
vowels = 'aeiouAEIOU'
def check(candidate): assert candidate('') == '' assert candidate('abcdef\nghijklm') == 'bcdf\nghjklm' assert candidate('fedcba') == 'fdcb' assert candidate('eeeee') == '' assert candidate('acBAA') == 'cB' assert candidate('EcBOO') == 'cB' assert candidate('ybcd') == 'ybcd' def test_check(): check(remove_vowels) test_check()
humaneval-HumanEval_162_string_to_md5.json-L7
js
//Given a string 'text', return its md5 hash equivalent string. // If 'text' is an empty string, return undefined. // >>> string_to_md5("Hello world") // "3e25960a79dbc69b674cd4ec67a72c62" function string_to_md5(text){ if(text === ''){
} return require('crypto').createHash('md5').update(text).digest('hex'); }
return undefined;
const assert = require('node:assert'); function test() { let candidate = string_to_md5; assert.deepEqual(candidate("Hello world"),"3e25960a79dbc69b674cd4ec67a72c62"); assert.deepEqual(candidate(""),undefined); assert.deepEqual(candidate("A B C"),"0ef78513b0cb8cef12743f5aeb35f888"); assert.deepEqual(candidate("password"),"5f4dcc3b5aa765d61d8327deb882cf99"); } test();
humaneval-HumanEval_158_find_max.json-L17
py
from typing import List def find_max(words: List[str]) -> str: """Write a function that accepts a list of strings. The list contains different words. Return the word with maximum number of unique characters. If multiple strings have maximum number of unique characters, return the one which comes first in lexicographical order. >>> find_max(['name', 'of', 'string']) 'string' >>> find_max(['name', 'enam', 'game']) 'enam' >>> find_max(['aaaaaaa', 'bb', 'cc']) 'aaaaaaa' """ max_num = 0
for word in words: unique_num = len(set(word)) if unique_num > max_num: max_num = unique_num max_word = word elif unique_num == max_num: if word < max_word: max_word = word return max_word
max_word = ""
def check(candidate): assert candidate(['name', 'of', 'string']) == 'string' assert candidate(['name', 'enam', 'game']) == 'enam' assert candidate(['aaaaaaa', 'bb', 'cc']) == 'aaaaaaa' assert candidate(['abc', 'cba']) == 'abc' assert candidate(['play', 'this', 'game', 'of', 'footbott']) == 'footbott' assert candidate(['we', 'are', 'gonna', 'rock']) == 'gonna' assert candidate(['we', 'are', 'a', 'mad', 'nation']) == 'nation' assert candidate(['this', 'is', 'a', 'prrk']) == 'this' assert candidate(['b']) == 'b' assert candidate(['play', 'play', 'play']) == 'play' def test_check(): check(find_max) test_check()
humaneval-HumanEval_67_fruit_distribution.json-L22
py
def fruit_distribution(s: str, n: int) -> int: """ In this task, you will be given a string that represents a number of apples and oranges that are distributed in a basket of fruit this basket contains apples, oranges, and mango fruits. Given the string that represents the total number of the oranges and apples and an integer that represent the total number of the fruits in the basket return the number of the mango fruits in the basket. for examble: >>> fruit_distribution('5 apples and 6 oranges', 19) 8 >>> fruit_distribution('0 apples and 1 oranges', 3) 2 >>> fruit_distribution('2 apples and 3 oranges', 100) 95 >>> fruit_distribution('100 apples and 1 oranges', 120) 19 """ fruits = [] for fruit in s.split(' '): try: fruits.append(int(fruit))
pass return n - sum(fruits)
except:
def check(candidate): assert candidate('5 apples and 6 oranges', 19) == 8 assert candidate('5 apples and 6 oranges', 21) == 10 assert candidate('0 apples and 1 oranges', 3) == 2 assert candidate('1 apples and 0 oranges', 3) == 2 assert candidate('2 apples and 3 oranges', 100) == 95 assert candidate('2 apples and 3 oranges', 5) == 0 assert candidate('1 apples and 100 oranges', 120) == 19 def test_check(): check(fruit_distribution) test_check()
humaneval-HumanEval_124_valid_date.json-L28
js
//You have to write a function which validates a given date string and // returns true if the date is valid otherwise false. // The date is valid if all of the following rules are satisfied: // 1. The date string is not empty. // 2. The number of days is not less than 1 or higher than 31 days for months 1,3,5,7,8,10,12. And the number of days is not less than 1 or higher than 30 days for months 4,6,9,11. And, the number of days is not less than 1 or higher than 29 for the month 2. // 3. The months should not be less than 1 or higher than 12. // 4. The date should be in the format: mm-dd-yyyy // >>> valid_date("03-11-2000") // true // >>> valid_date("15-01-2012") // false // >>> valid_date("04-0-2040") // false // >>> valid_date("06-04-2020") // true // >>> valid_date("06/04/2020") // false function valid_date(date){ var date_arr = date.split("-"); if(date_arr.length == 3){ var month = parseInt(date_arr[0]); var day = parseInt(date_arr[1]); var year = parseInt(date_arr[2]); if(month < 1 || month > 12){ return false; }else if(month == 2){ if(day < 1 || day > 29){
} }else if((month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) && (day < 1 || day > 31)){ return false; }else if((month == 4 || month == 6 || month == 9 || month == 11) && (day < 1 || day > 30)){ return false; } return true; } return false; }
return false;
const assert = require('node:assert'); function test() { let candidate = valid_date; assert.deepEqual(candidate("03-11-2000"),true); assert.deepEqual(candidate("15-01-2012"),false); assert.deepEqual(candidate("04-0-2040"),false); assert.deepEqual(candidate("06-04-2020"),true); assert.deepEqual(candidate("01-01-2007"),true); assert.deepEqual(candidate("03-32-2011"),false); assert.deepEqual(candidate(""),false); assert.deepEqual(candidate("04-31-3000"),false); assert.deepEqual(candidate("06-06-2005"),true); assert.deepEqual(candidate("21-31-2000"),false); assert.deepEqual(candidate("04-12-2003"),true); assert.deepEqual(candidate("04122003"),false); assert.deepEqual(candidate("20030412"),false); assert.deepEqual(candidate("2003-04"),false); assert.deepEqual(candidate("2003-04-12"),false); assert.deepEqual(candidate("04-2003"),false); } test();
humaneval-HumanEval_7_filter_by_substring.json-L8
js
//Filter an input array of strings only for ones that contain given substring // >>> filter_by_substring([], "a") // [] // >>> filter_by_substring(["abc", "bacd", "cde", "array"], "a") // ["abc", "bacd", "array"] function filter_by_substring(strings, substring){ var filtered = [];
if(strings[i].includes(substring)){ filtered.push(strings[i]); } } return filtered; }
for(var i = 0; i < strings.length; i++){
const assert = require('node:assert'); function test() { let candidate = filter_by_substring; assert.deepEqual(candidate([], "john"),[]); assert.deepEqual(candidate(["xxx", "asd", "xxy", "john doe", "xxxAAA", "xxx"], "xxx"),["xxx", "xxxAAA", "xxx"]); assert.deepEqual(candidate(["xxx", "asd", "aaaxxy", "john doe", "xxxAAA", "xxx"], "xx"),["xxx", "aaaxxy", "xxxAAA", "xxx"]); assert.deepEqual(candidate(["grunt", "trumpet", "prune", "gruesome"], "run"),["grunt", "prune"]); } test();
humaneval-HumanEval_154_cycpattern_check.json-L16
js
//You are given 2 words. You need to return true if the second word or any of its rotations is a substring in the first word // >>> cycpattern_check("abcd", "abd") // false // >>> cycpattern_check("hello", "ell") // true // >>> cycpattern_check("whassup", "psus") // false // >>> cycpattern_check("abab", "baa") // true // >>> cycpattern_check("efef", "eeff") // false // >>> cycpattern_check("himenss", "simen") // true function cycpattern_check(a, b){ var result = false;
result = result || a.includes(b); b = b.slice(1) + b[0]; } return result; }
for(var i = 0; i < b.length; i++){
const assert = require('node:assert'); function test() { let candidate = cycpattern_check; assert.deepEqual(candidate("xyzw", "xyw"),false); assert.deepEqual(candidate("yello", "ell"),true); assert.deepEqual(candidate("whattup", "ptut"),false); assert.deepEqual(candidate("efef", "fee"),true); assert.deepEqual(candidate("abab", "aabb"),false); assert.deepEqual(candidate("winemtt", "tinem"),true); } test();
humaneval-HumanEval_43_pairs_sum_to_zero.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 { // 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 j = i + 1; j < l.size(); j++) { if (l.get(i) + l.get(j) == 0) { return true; } } } return false; } }
for (int i = 0; i < l.size(); i++) {
} 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_6_parse_nested_parens.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 { // Input to this function is a string represented multiple groups for nested parentheses separated by spaces. // For each of the group, output the deepest level of nesting of parentheses. // E.g. (()()) has maximum two levels of nesting while ((())) has three. // >>> parseNestedParens(("(()()) ((())) () ((())()())")) // (new ArrayList<Long>(Arrays.asList((long)2l, (long)3l, (long)1l, (long)3l))) public static ArrayList<Long> parseNestedParens(String paren_string) { ArrayList<Long> result = new ArrayList<Long>(); String[] paren_strings = paren_string.split(" "); for (String paren : paren_strings) {
long current_depth = 0; for (char c : paren.toCharArray()) { if (c == '(') { current_depth += 1; max_depth = Math.max(max_depth, current_depth); } else if (c == ')') { current_depth -= 1; } } result.add(max_depth); } return result; } }
long max_depth = 0;
} public static void main(String[] args) { assert(parseNestedParens(("(()()) ((())) () ((())()())")).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)3l, (long)1l, (long)3l))))); assert(parseNestedParens(("() (()) ((())) (((())))")).equals((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l))))); assert(parseNestedParens(("(()(())((())))")).equals((new ArrayList<Long>(Arrays.asList((long)4l))))); } }
humaneval-HumanEval_23_strlen.json-L10
py
def strlen(string: str) -> int: """ Return length of given string >>> strlen('') 0 >>> strlen('abc') 3 """ length = 0 for char in string:
return length
length += 1
def check(candidate): assert candidate('') == 0 assert candidate('x') == 1 assert candidate('asdasnakj') == 9 def test_check(): check(strlen) test_check()
humaneval-HumanEval_137_compare_one.json-L71
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(',', '.') 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:
elif isinstance(a, str) and isinstance(b, float): a_tmp = a.replace(',', '.') if float(a_tmp) > b: return a elif float(a_tmp) < b: return b
return None
def check(candidate): assert candidate(1, 2) == 2 assert candidate(1, 2.5) == 2.5 assert candidate(2, 3) == 3 assert candidate(5, 6) == 6 assert candidate(1, '2,3') == '2,3' assert candidate('5,1', '6') == '6' assert candidate('1', '2') == '2' assert candidate('1', 1) == None def test_check(): check(compare_one) test_check()
humaneval-HumanEval_141_file_name_check.json-L31
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Create a function which takes a string representing a file's name, and returns // 'Yes' if the the file's name is valid, and returns 'No' otherwise. // A file's name is considered to be valid if and only if all the following conditions // are met: // - There should not be more than three digits ('0'-'9') in the file's name. // - The file's name contains exactly one dot '.' // - The substring before the dot should not be empty, and it starts with a letter from // the latin alphapet ('a'-'z' and 'A'-'Z'). // - The substring after the dot should be one of these: ['txt', 'exe', 'dll'] // Examples: // >>> fileNameCheck(("example.txt")) // ("Yes") // >>> fileNameCheck(("1example.dll")) // ("No") public static String fileNameCheck(String file_name) { String result = "No"; String[] tokens = file_name.split("\\."); if (tokens.length != 2) { return result; } String extension = tokens[1]; if (!(extension.equals("txt") || extension.equals("exe") || extension.equals("dll"))) {
} 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"; } }
return result;
} 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_112_reverse_delete.json-L24
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_141_file_name_check.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 { // Create a function which takes a string representing a file's name, and returns // 'Yes' if the the file's name is valid, and returns 'No' otherwise. // A file's name is considered to be valid if and only if all the following conditions // are met: // - There should not be more than three digits ('0'-'9') in the file's name. // - The file's name contains exactly one dot '.' // - The substring before the dot should not be empty, and it starts with a letter from // the latin alphapet ('a'-'z' and 'A'-'Z'). // - The substring after the dot should be one of these: ['txt', 'exe', 'dll'] // Examples: // >>> fileNameCheck(("example.txt")) // ("Yes") // >>> fileNameCheck(("1example.dll")) // ("No") public static String fileNameCheck(String file_name) { String result = "No"; String[] tokens = file_name.split("\\."); if (tokens.length != 2) { return result; } String extension = tokens[1]; if (!(extension.equals("txt") || extension.equals("exe") || extension.equals("dll"))) { return result; } String name = tokens[0]; int count = 0; for (int i = 0; i < name.length(); i++) { if (Character.isDigit(name.charAt(i))) { count++; } } if (count > 3) { return result; } if (name.length() == 0) { return result;
if (!Character.isLetter(name.charAt(0))) { return result; } return "Yes"; } }
}
} public static void main(String[] args) { assert(fileNameCheck(("example.txt")).equals(("Yes"))); assert(fileNameCheck(("1example.dll")).equals(("No"))); assert(fileNameCheck(("s1sdf3.asd")).equals(("No"))); assert(fileNameCheck(("K.dll")).equals(("Yes"))); assert(fileNameCheck(("MY16FILE3.exe")).equals(("Yes"))); assert(fileNameCheck(("His12FILE94.exe")).equals(("No"))); assert(fileNameCheck(("_Y.txt")).equals(("No"))); assert(fileNameCheck(("?aREYA.exe")).equals(("No"))); assert(fileNameCheck(("/this_is_valid.dll")).equals(("No"))); assert(fileNameCheck(("this_is_valid.wow")).equals(("No"))); assert(fileNameCheck(("this_is_valid.txt")).equals(("Yes"))); assert(fileNameCheck(("this_is_valid.txtexe")).equals(("No"))); assert(fileNameCheck(("#this2_i4s_5valid.ten")).equals(("No"))); assert(fileNameCheck(("@this1_is6_valid.exe")).equals(("No"))); assert(fileNameCheck(("this_is_12valid.6exe4.txt")).equals(("No"))); assert(fileNameCheck(("all.exe.txt")).equals(("No"))); assert(fileNameCheck(("I563_No.exe")).equals(("Yes"))); assert(fileNameCheck(("Is3youfault.txt")).equals(("Yes"))); assert(fileNameCheck(("no_one#knows.dll")).equals(("Yes"))); assert(fileNameCheck(("1I563_Yes3.exe")).equals(("No"))); assert(fileNameCheck(("I563_Yes3.txtt")).equals(("No"))); assert(fileNameCheck(("final..txt")).equals(("No"))); assert(fileNameCheck(("final132")).equals(("No"))); assert(fileNameCheck(("_f4indsartal132.")).equals(("No"))); assert(fileNameCheck((".txt")).equals(("No"))); assert(fileNameCheck(("s.")).equals(("No"))); } }
humaneval-HumanEval_142_sum_squares.json-L20
py
from typing import List def sum_squares(lst: List[int]) -> int: """" This function will take a list of integers. For all entries in the list, the function shall square the integer entry if its index is a multiple of 3 and will cube the integer entry if its index is a multiple of 4 and not a multiple of 3. The function will not change the entries in the list whose indexes are not a multiple of 3 or 4. The function shall then return the sum of all entries. Examples: >>> lst [1, 2, 3] >>> lst [] >>> lst [-1, -5, 2, -1, -5] """ for index in range(len(lst)): if index % 3 == 0: lst[index] = lst[index] ** 2
lst[index] = lst[index] ** 3 return sum(lst)
elif index % 4 == 0:
def check(candidate): assert candidate([1, 2, 3]) == 6 assert candidate([1, 4, 9]) == 14 assert candidate([]) == 0 assert candidate([1, 1, 1, 1, 1, 1, 1, 1, 1]) == 9 assert candidate([-1, -1, -1, -1, -1, -1, -1, -1, -1]) == -3 assert candidate([0]) == 0 assert candidate([-1, -5, 2, -1, -5]) == -126 assert candidate([-56, -99, 1, 0, -2]) == 3030 assert candidate([-1, 0, 0, 0, 0, 0, 0, 0, -1]) == 0 assert candidate([-16, -9, -2, 36, 36, 26, -20, 25, -40, 20, -4, 12, -26, 35, 37]) == -14196 assert candidate([-1, -3, 17, -1, -15, 13, -1, 14, -14, -12, -5, 14, -14, 6, 13, 11, 16, 16, 4, 10]) == -1448 def test_check(): check(sum_squares) test_check()
humaneval-HumanEval_74_total_match.json-L20
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; let sum_lst2 = 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; } }
}
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_115_max_fill.json-L36
py
from typing import List def max_fill(grid: List[List[int]], capacity: int) -> int: """ You are given a rectangular grid of wells. Each row represents a single well, and each 1 in a row represents a single unit of water. Each well has a corresponding bucket that can be used to extract water from it, and all buckets have the same capacity. Your task is to use the buckets to empty the wells. Output the number of times you need to lower the buckets. Example 1: >>> max_fill([[0, 0, 1, 0], [0, 1, 0, 0], [1, 1, 1, 1]], 1) 6 Example 2: >>> max_fill([[0, 0, 1, 1], [0, 0, 0, 0], [1, 1, 1, 1], [0, 1, 1, 1]], 2) 5 Example 3: >>> max_fill([[0, 0, 0], [0, 0, 0]], 5) 0 Constraints: * all wells have the same length * 1 <= grid.length <= 10^2 * 1 <= grid[:,1].length <= 10^2 * grid[i][j] -> 0 | 1 * 1 <= capacity <= 10 """ times = 0 for row in grid: for i in range(0, len(row), capacity): if 1 in row[i:i+capacity]: times += 1
return times
def check(candidate): assert candidate([[0, 0, 1, 0], [0, 1, 0, 0], [1, 1, 1, 1]], 1) == 6 assert candidate([[0, 0, 1, 1], [0, 0, 0, 0], [1, 1, 1, 1], [0, 1, 1, 1]], 2) == 5 assert candidate([[0, 0, 0], [0, 0, 0]], 5) == 0 assert candidate([[1, 1, 1, 1], [1, 1, 1, 1]], 2) == 4 assert candidate([[1, 1, 1, 1], [1, 1, 1, 1]], 9) == 2 def test_check(): check(max_fill) test_check()