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_111_histogram.json-L30
py
from typing import Dict def histogram(test: str) -> Dict[str, int]: """Given a string representing a space separated lowercase letters, return a dictionary of the letter with the most repetition and containing the corresponding count. If several letters have the same occurrence, return all of them. Example: >>> histogram('a b c') { 'a': 1, 'b': 1, 'c': 1 } >>> histogram('a b b a') { 'a': 2, 'b': 2 } >>> histogram('a b c a b') { 'a': 2, 'b': 2 } >>> histogram('b b b b a') { 'b': 4 } >>> histogram('') { } """ letters = {} most_count = 0 result = {} for letter in test.split(): letters[letter] = letters.get(letter, 0) + 1 if letters[letter] >= most_count: most_count = letters[letter] for letter in letters: if letters[letter] == most_count:
return result
result[letter] = most_count
def check(candidate): assert candidate('a b b a') == { 'a': 2, 'b': 2 } assert candidate('a b c a b') == { 'a': 2, 'b': 2 } assert candidate('a b c d g') == { 'a': 1, 'b': 1, 'c': 1, 'd': 1, 'g': 1 } assert candidate('r t g') == { 'r': 1, 't': 1, 'g': 1 } assert candidate('b b b b a') == { 'b': 4 } assert candidate('r t g') == { 'r': 1, 't': 1, 'g': 1 } assert candidate('') == { } assert candidate('a') == { 'a': 1 } def test_check(): check(histogram) test_check()
humaneval-HumanEval_40_triples_sum_to_zero.json-L27
py
from typing import List def triples_sum_to_zero(l: List[int]) -> bool: """ triples_sum_to_zero takes a list of integers as an input. it returns True if there are three distinct elements in the list that sum to zero, and False otherwise. >>> triples_sum_to_zero([1, 3, 5, 0]) False >>> triples_sum_to_zero([1, 3, -2, 1]) True >>> triples_sum_to_zero([1, 2, 3, 7]) False >>> triples_sum_to_zero([2, 4, -5, 3, 9, 7]) True >>> triples_sum_to_zero([1]) False """ assert len(l) > 0, "The input list cannot be empty" l.sort() for i in range(len(l)): for j in range(i + 1, len(l)): for k in range(j + 1, len(l)): if l[i] + l[j] + l[k] == 0: return True
return False
def check(candidate): assert candidate([1, 3, 5, 0]) == False assert candidate([1, 3, 5, -1]) == False assert candidate([1, 3, -2, 1]) == True assert candidate([1, 2, 3, 7]) == False assert candidate([1, 2, 5, 7]) == False assert candidate([2, 4, -5, 3, 9, 7]) == True assert candidate([1]) == False assert candidate([1, 3, 5, -100]) == False assert candidate([100, 3, 5, -100]) == False def test_check(): check(triples_sum_to_zero) test_check()
humaneval-HumanEval_125_split_words.json-L19
js
//Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you // should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the // alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25 // Examples // >>> split_words("Hello world!") // ["Hello", "world!"] // >>> split_words("Hello,world!") // ["Hello", "world!"] // >>> split_words("abcdef") // 3 function split_words(txt){ if(txt.includes(' ')){ return txt.split(' '); } else if(txt.includes(',')){ return txt.split(','); } else{
for(let i = 0; i < txt.length; i++){ if(i % 2 != 0){ if(txt[i] == txt[i].toLowerCase()){ count++; } } } return count; } }
let count = 0;
const assert = require('node:assert'); function test() { let candidate = split_words; assert.deepEqual(candidate("Hello world!"),["Hello", "world!"]); assert.deepEqual(candidate("Hello,world!"),["Hello", "world!"]); assert.deepEqual(candidate("Hello world,!"),["Hello", "world,!"]); assert.deepEqual(candidate("Hello,Hello,world !"),["Hello,Hello,world", "!"]); assert.deepEqual(candidate("abcdef"),3); assert.deepEqual(candidate("aaabb"),2); assert.deepEqual(candidate("aaaBb"),1); assert.deepEqual(candidate(""),0); } test();
humaneval-HumanEval_1_separate_paren_groups.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 containing multiple groups of nested parentheses. Your goal is to // separate those group into separate strings and return the array list of those. // Separate groups are balanced (each open brace is properly closed) and not nested within each other // Ignore any spaces in the input string. // >>> separateParenGroups(("( ) (( )) (( )( ))")) // (new ArrayList<String>(Arrays.asList((String)"()", (String)"(())", (String)"(()())"))) public static ArrayList<String> separateParenGroups(String paren_string) { ArrayList<String> output = new ArrayList<String>(); StringBuffer temp = new StringBuffer(); int open_paren = 0; for (int i = 0; i < paren_string.length(); i++) { char c = paren_string.charAt(i); if (c == '(') { if (open_paren == 0) { temp = new StringBuffer();
open_paren++; temp.append(c); } else if (c == ')') { open_paren--; temp.append(c); if (open_paren == 0) { output.add(temp.toString()); } } } return output; } }
}
} public static void main(String[] args) { assert(separateParenGroups(("(()()) ((())) () ((())()())")).equals((new ArrayList<String>(Arrays.asList((String)"(()())", (String)"((()))", (String)"()", (String)"((())()())"))))); assert(separateParenGroups(("() (()) ((())) (((())))")).equals((new ArrayList<String>(Arrays.asList((String)"()", (String)"(())", (String)"((()))", (String)"(((())))"))))); assert(separateParenGroups(("(()(())((())))")).equals((new ArrayList<String>(Arrays.asList((String)"(()(())((())))"))))); assert(separateParenGroups(("( ) (( )) (( )( ))")).equals((new ArrayList<String>(Arrays.asList((String)"()", (String)"(())", (String)"(()())"))))); } }
humaneval-HumanEval_129_minPath.json-L49
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_156_int_to_mini_roman.json-L76
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Given a positive integer, obtain its roman numeral equivalent as a string, // and return it in lowercase. // Restrictions: 1 <= num <= 1000 // Examples: // >>> intToMiniRoman((19l)) // ("xix") // >>> intToMiniRoman((152l)) // ("clii") // >>> intToMiniRoman((426l)) // ("cdxxvi") public static String intToMiniRoman(long number) { int num = (int) number; String res = ""; if (num == 0) return ""; while (num >= 1000) { res += "m"; num -= 1000; } if (num >= 900) { res += "cm"; num -= 900; } if (num >= 500) { res += "d"; num -= 500; } if (num >= 400) { res += "cd"; num -= 400; } while (num >= 100) { res += "c"; num -= 100; } if (num >= 90) { res += "xc"; num -= 90; } if (num >= 50) { res += "l"; num -= 50; } 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;
} 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_10_make_palindrome.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 { // 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. // >>> makePalindrome(("")) // ("") // >>> makePalindrome(("cat")) // ("catac") // >>> makePalindrome(("cata")) // ("catac") public static String makePalindrome(String string) { StringBuilder newString = new StringBuilder(string); String reverse = new StringBuilder(string).reverse().toString(); for (int index = 0; index < string.length(); index++) { if (string.substring(index).equals(reverse.substring(0, string.length() - index))) { newString.append(reverse.substring(string.length() - index));
} } return newString.toString(); } }
break;
} public static void main(String[] args) { assert(makePalindrome(("")).equals((""))); assert(makePalindrome(("x")).equals(("x"))); assert(makePalindrome(("xyz")).equals(("xyzyx"))); assert(makePalindrome(("xyx")).equals(("xyx"))); assert(makePalindrome(("jerry")).equals(("jerryrrej"))); } }
humaneval-HumanEval_29_filter_by_prefix.json-L8
js
//Filter an input array of strings only for ones that start with a given prefix. // >>> filter_by_prefix([], "a") // [] // >>> filter_by_prefix(["abc", "bcd", "cde", "array"], "a") // ["abc", "array"] function filter_by_prefix(strings, prefix){ return strings.filter( function(str){
}); }
return str.startsWith(prefix);
const assert = require('node:assert'); function test() { let candidate = filter_by_prefix; assert.deepEqual(candidate([], "john"),[]); assert.deepEqual(candidate(["xxx", "asd", "xxy", "john doe", "xxxAAA", "xxx"], "xxx"),["xxx", "xxxAAA", "xxx"]); } test();
humaneval-HumanEval_117_select_words.json-L47
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Given a string s and a natural number n, you have been tasked to implement // a function that returns an array array list of all words from string s that contain exactly // n consonants, in order these words appear in the string s. // If the string s is empty then the function should return an empty array list. // Note: you may assume the input string contains only letters and spaces. // Examples: // >>> selectWords(("Mary had a little lamb"), (4l)) // (new ArrayList<String>(Arrays.asList((String)"little"))) // >>> selectWords(("Mary had a little lamb"), (3l)) // (new ArrayList<String>(Arrays.asList((String)"Mary", (String)"lamb"))) // >>> selectWords(("simple white space"), (2l)) // (new ArrayList<String>(Arrays.asList())) // >>> selectWords(("Hello world"), (4l)) // (new ArrayList<String>(Arrays.asList((String)"world"))) // >>> selectWords(("Uncle sam"), (3l)) // (new ArrayList<String>(Arrays.asList((String)"Uncle"))) public static ArrayList<String> selectWords(String s, long n) { ArrayList<String> ret = new ArrayList<String>(); String[] words = s.split(" "); for (String word : words) { String wordInLowerCase = word.toLowerCase(); long consonants = 0l; for (char c : wordInLowerCase.toCharArray()) { switch (c) { case 'a': case 'e': case 'i': case 'o': case 'u': break; default: consonants++; break; } } if (consonants == n) { ret.add(word); }
return ret; } }
}
} public static void main(String[] args) { assert(selectWords(("Mary had a little lamb"), (4l)).equals((new ArrayList<String>(Arrays.asList((String)"little"))))); assert(selectWords(("Mary had a little lamb"), (3l)).equals((new ArrayList<String>(Arrays.asList((String)"Mary", (String)"lamb"))))); assert(selectWords(("simple white space"), (2l)).equals((new ArrayList<String>(Arrays.asList())))); assert(selectWords(("Hello world"), (4l)).equals((new ArrayList<String>(Arrays.asList((String)"world"))))); assert(selectWords(("Uncle sam"), (3l)).equals((new ArrayList<String>(Arrays.asList((String)"Uncle"))))); assert(selectWords((""), (4l)).equals((new ArrayList<String>(Arrays.asList())))); assert(selectWords(("a b c d e f"), (1l)).equals((new ArrayList<String>(Arrays.asList((String)"b", (String)"c", (String)"d", (String)"f"))))); } }
humaneval-HumanEval_131_digits.json-L13
py
def digits(n: int) -> int: """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 """ if n < 10:
d, m = divmod(n, 10) return digits(d) * (m if m % 2 == 1 else 1)
return n if n % 2 == 1 else 0
def check(candidate): assert candidate(5) == 5 assert candidate(54) == 5 assert candidate(120) == 1 assert candidate(5014) == 5 assert candidate(98765) == 315 assert candidate(5576543) == 2625 assert candidate(2468) == 0 def test_check(): check(digits) test_check()
humaneval-HumanEval_156_int_to_mini_roman.json-L22
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",
5: "v", 4: "iv", 1: "i" }; var output = ""; while (number > 0){ var key_list = Object.keys(roman_conversion).map(Number); key_list.sort(function(a, b){return b-a}); for (var i = 0; i < key_list.length; i++){ if (key_list[i] <= number){ output += roman_conversion[key_list[i]]; number -= key_list[i]; break; } } } return output; }
9: "ix",
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_72_will_it_fly.json-L26
py
from typing import List def will_it_fly(q: List[int], w: int) -> bool: """ Write a function that returns True if the object q will fly, and False otherwise. The object q will fly if it's balanced (it is a palindromic list) and the sum of its elements is less than or equal the maximum possible weight w. Example: >>> will_it_fly([1, 2], 5) False # 1+2 is less than the maximum possible weight, but it's unbalanced. >>> will_it_fly([3, 2, 3], 1) False # it's balanced, but 3+2+3 is more than the maximum possible weight. >>> will_it_fly([3, 2, 3], 9) True # 3+2+3 is less than the maximum possible weight, and it's balanced. >>> will_it_fly([3], 5) True # 3 is less than the maximum possible weight, and it's balanced. """ s = sum(q)
return s <= w and q == q[::-1]
def check(candidate): assert candidate([3, 2, 3], 9) == True assert candidate([1, 2], 5) == False assert candidate([3], 5) == True assert candidate([3, 2, 3], 1) == False assert candidate([1, 2, 3], 6) == False assert candidate([5], 5) == True def test_check(): check(will_it_fly) test_check()
humaneval-HumanEval_80_is_happy.json-L26
js
//You are given a string s. // Your task is to check if the string is hapjs or not. // A string is hapjs if its length is at least 3 and every 3 consecutive letters are distinct // For example: // >>> is_happy(a) // false // >>> is_happy(aa) // false // >>> is_happy(abcd) // true // >>> is_happy(aabb) // false // >>> is_happy(adb) // true // >>> is_happy(xyy) // false function is_happy(s){ let happy = true; if(s.length<3){ happy = false; } for(let i=2; i<s.length; i++){ if(s[i]===s[i-1] || s[i]===s[i-2]){ happy = false; }
return happy; }
}
const assert = require('node:assert'); function test() { let candidate = is_happy; assert.deepEqual(candidate("a"),false); assert.deepEqual(candidate("aa"),false); assert.deepEqual(candidate("abcd"),true); assert.deepEqual(candidate("aabb"),false); assert.deepEqual(candidate("adb"),true); assert.deepEqual(candidate("xyy"),false); assert.deepEqual(candidate("iopaxpoi"),true); assert.deepEqual(candidate("iopaxioi"),false); } test();
humaneval-HumanEval_143_words_in_sentence.json-L22
js
//You are given a string representing a sentence, // the sentence contains some words separated by a space, // and you have to return a string that contains the words from the original sentence, // whose lengths are prime numbers, // the order of the words in the new string should be the same as the original one. // Example 1: // >>> words_in_sentence("This is a test") // "is" // Example 2: // >>> words_in_sentence("lets go for swimming") // "go for" // Constraints: // * 1 <= len(sentence) <= 100 // * sentence contains only letters function words_in_sentence(sentence){ return sentence.split(' ').filter(word => { var number = word.length; var isPrime = true; if(number === 1 || number === 0){ return false; }
if(number % i === 0){ isPrime = false; break; } } return isPrime; }).join(' '); }
for(var i = 2; i < number; i++){
const assert = require('node:assert'); function test() { let candidate = words_in_sentence; assert.deepEqual(candidate("This is a test"),"is"); assert.deepEqual(candidate("lets go for swimming"),"go for"); assert.deepEqual(candidate("there is no place available here"),"there is no place"); assert.deepEqual(candidate("Hi I am Hussein"),"Hi am Hussein"); assert.deepEqual(candidate("go for it"),"go for it"); assert.deepEqual(candidate("here"),""); assert.deepEqual(candidate("here is"),"is"); } test();
humaneval-HumanEval_72_will_it_fly.json-L22
js
//Write a function that returns true if the object q will fly, and false otherwise. // The object q will fly if it's balanced (it is a palindromic array) and the sum of its elements is less than or equal the maximum possible weight w. // Example: // >>> will_it_fly([1, 2], 5) // false // # 1+2 is less than the maximum possible weight, but it's unbalanced. // >>> will_it_fly([3, 2, 3], 1) // false // # it's balanced, but 3+2+3 is more than the maximum possible weight. // >>> will_it_fly([3, 2, 3], 9) // true // # 3+2+3 is less than the maximum possible weight, and it's balanced. // >>> will_it_fly([3], 5) // true // # 3 is less than the maximum possible weight, and it's balanced. function will_it_fly(q, w){ let sum = 0; let balanced = true; for(let i = 0; i < q.length; i++){ sum += q[i]; }
if(q[i] !== q[q.length - 1 - i]){ balanced = false; break; } } return balanced && sum <= w; }
for(let i = 0; i < q.length; i++){
const assert = require('node:assert'); function test() { let candidate = will_it_fly; assert.deepEqual(candidate([3, 2, 3], 9),true); assert.deepEqual(candidate([1, 2], 5),false); assert.deepEqual(candidate([3], 5),true); assert.deepEqual(candidate([3, 2, 3], 1),false); assert.deepEqual(candidate([1, 2, 3], 6),false); assert.deepEqual(candidate([5], 5),true); } test();
humaneval-HumanEval_147_get_max_triples.json-L36
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // You are given a 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++) { for (int k = j + 1; k < arrayList.size(); k++) { if ((arrayList.get(i) + arrayList.get(j) + arrayList.get(k)) % 3 == 0) { count++; } } } } return count; }
}
} public static void main(String[] args) { assert(getMaxTriples((5l)) == (1l)); assert(getMaxTriples((6l)) == (4l)); assert(getMaxTriples((10l)) == (36l)); assert(getMaxTriples((100l)) == (53361l)); } }
humaneval-HumanEval_61_correct_bracketing.json-L15
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
if char == '(': count += 1 elif char == ')': count -= 1 if count < 0: return False return count == 0
for char in brackets:
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_137_compare_one.json-L52
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
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
elif a < 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_33_sort_third.json-L42
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // 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++) { 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++;
l_s.add(l_r.get(i - j)); } } return l_s; } }
} else {
} 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_33_sort_third.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 { // 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++) {
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; } }
if (i % 3 == 0) {
} 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_41_car_race_collision.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 { // Imagine a road that's a perfectly straight infinitely long line. // n cars are driving left to right; simultaneously, a different set of n cars // are driving right to left. The two sets of cars start out being very far from // each other. All cars move in the same speed. Two cars are said to collide // when a car that's moving left to right hits a car that's moving right to left. // However, the cars are infinitely sturdy and strong; as a result, they continue moving // in their trajectory as if they did not collide. // This function outputs the number of such collisions. public static long carRaceCollision(long n) { BigInteger nBigInteger = BigInteger.valueOf(n); BigInteger nSquared = nBigInteger.multiply(nBigInteger); return nSquared.longValue(); }
}
} public static void main(String[] args) { assert(carRaceCollision((2l)) == (4l)); assert(carRaceCollision((3l)) == (9l)); assert(carRaceCollision((4l)) == (16l)); assert(carRaceCollision((8l)) == (64l)); assert(carRaceCollision((10l)) == (100l)); } }
humaneval-HumanEval_40_triples_sum_to_zero.json-L20
js
//triples_sum_to_zero takes an array of integers as an input. // it returns true if there are three distinct elements in the array that // sum to zero, and false otherwise. // >>> triples_sum_to_zero([1, 3, 5, 0]) // false // >>> triples_sum_to_zero([1, 3, -2, 1]) // true // >>> triples_sum_to_zero([1, 2, 3, 7]) // false // >>> triples_sum_to_zero([2, 4, -5, 3, 9, 7]) // true // >>> triples_sum_to_zero([1]) // false function triples_sum_to_zero(l){ for (var i = 0; i < l.length; i++) { for (var j = 0; j < l.length; j++) { for (var k = 0; k < l.length; k++) { if (i !== j && i !== k && j !== k) { if (l[i] + l[j] + l[k] === 0) {
} } } } } return false; }
return true;
const assert = require('node:assert'); function test() { let candidate = triples_sum_to_zero; assert.deepEqual(candidate([1, 3, 5, 0]),false); assert.deepEqual(candidate([1, 3, 5, -1]),false); assert.deepEqual(candidate([1, 3, -2, 1]),true); assert.deepEqual(candidate([1, 2, 3, 7]),false); assert.deepEqual(candidate([1, 2, 5, 7]),false); assert.deepEqual(candidate([2, 4, -5, 3, 9, 7]),true); assert.deepEqual(candidate([1]),false); assert.deepEqual(candidate([1, 3, 5, -100]),false); assert.deepEqual(candidate([100, 3, 5, -100]),false); } test();
humaneval-HumanEval_158_find_max.json-L23
js
//Write a function that accepts an array of strings. // The array contains different words. Return the word with maximum number // of unique characters. If multiple strings have maximum number of unique // characters, return the one which comes first in lexicographical order. // >>> find_max(["name", "of", "string"]) // "string" // >>> find_max(["name", "enam", "game"]) // "enam" // >>> find_max(["aaaaaaa", "bb", "cc"]) // "aaaaaaa" function find_max(words){ var max_unique = {}; var max_unique_word = ""; for(var i = 0; i < words.length; i++){ var unique_word = {}; var word = words[i]; for(var j = 0; j < word.length; j++){ var char = word[j]; if(unique_word[char] === undefined){ unique_word[char] = 1; } }
max_unique_word = word; max_unique = unique_word; } else if(Object.keys(unique_word).length > Object.keys(max_unique).length){ max_unique_word = word; max_unique = unique_word; } else if(Object.keys(unique_word).length === Object.keys(max_unique).length){ if(word < max_unique_word){ max_unique_word = word; max_unique = unique_word; } } } return max_unique_word; }
if(max_unique_word === ""){
const assert = require('node:assert'); function test() { let candidate = find_max; assert.deepEqual(candidate(["name", "of", "string"]),"string"); assert.deepEqual(candidate(["name", "enam", "game"]),"enam"); assert.deepEqual(candidate(["aaaaaaa", "bb", "cc"]),"aaaaaaa"); assert.deepEqual(candidate(["abc", "cba"]),"abc"); assert.deepEqual(candidate(["play", "this", "game", "of", "footbott"]),"footbott"); assert.deepEqual(candidate(["we", "are", "gonna", "rock"]),"gonna"); assert.deepEqual(candidate(["we", "are", "a", "mad", "nation"]),"nation"); assert.deepEqual(candidate(["this", "is", "a", "prrk"]),"this"); assert.deepEqual(candidate(["b"]),"b"); assert.deepEqual(candidate(["play", "play", "play"]),"play"); } test();
humaneval-HumanEval_135_can_arrange.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 { // 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) {
for (int i = arr.size() - 1; i > 0; i--) { if (arr.get(i) < arr.get(i - 1)) { p = (long)i; break; } } return p; } }
long p = -1l;
} 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_123_get_odd_collatz.json-L28
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Given a positive integer n, return a sorted array list that has the odd numbers in collatz sequence. // The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined // as follows: start with any positive integer n. Then each term is obtained from the // previous term as follows: if the previous term is even, the next term is one half of // the previous term. If the previous term is odd, the next term is 3 times the previous // term plus 1. The conjecture is that no matter what value of n, the sequence will always reach 1. // Note: // 1. Collatz(1) is [1]. // 2. returned array list sorted in increasing order. // For example: // get_odd_collatz(5) returns [1, 5] # The collatz sequence for 5 is [5, 16, 8, 4, 2, 1], so the odd numbers are only 1, and 5. // >>> getOddCollatz((5l)) // (new ArrayList<Long>(Arrays.asList((long)1l, (long)5l))) public static ArrayList<Long> getOddCollatz(long n) { if (n <= 0) return new ArrayList<Long>(); HashSet<Long> odds = new HashSet<Long>(); long n1 = n; while (n1 > 1) { if (n1 % 2 == 1) odds.add(n1);
} odds.add(1l); Long[] odds_arr = odds.toArray(new Long[odds.size()]); ArrayList<Long> ans = new ArrayList<Long>(Arrays.asList(odds_arr)); Collections.sort(ans); return ans; } }
n1 = n1 % 2 == 0 ? n1 / 2 : 3 * n1 + 1;
} public static void main(String[] args) { assert(getOddCollatz((14l)).equals((new ArrayList<Long>(Arrays.asList((long)1l, (long)5l, (long)7l, (long)11l, (long)13l, (long)17l))))); assert(getOddCollatz((5l)).equals((new ArrayList<Long>(Arrays.asList((long)1l, (long)5l))))); assert(getOddCollatz((12l)).equals((new ArrayList<Long>(Arrays.asList((long)1l, (long)3l, (long)5l))))); assert(getOddCollatz((1l)).equals((new ArrayList<Long>(Arrays.asList((long)1l))))); } }
humaneval-HumanEval_81_numerical_letter_grade.json-L45
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+')
final.append('C') elif x > 1.3: final.append('C-') elif x > 1.0: final.append('D+') elif x > 0.7: final.append('D') elif x > 0.0: final.append('D-') else: final.append('E') return final
elif x > 1.7:
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_156_int_to_mini_roman.json-L34
py
def int_to_mini_roman(number: int) -> str: """ Given a positive integer, obtain its roman numeral equivalent as a string, and return it in lowercase. Restrictions: 1 <= num <= 1000 Examples: >>> int_to_mini_roman(19) 'xix' >>> int_to_mini_roman(152) 'clii' >>> int_to_mini_roman(426) 'cdxxvi' """ roman_numerals = { 1000: 'm', 900: 'cm', 500: 'd', 400: 'cd', 100: 'c', 90: 'xc', 50: 'l', 40: 'xl', 10: 'x', 9: 'ix', 5: 'v', 4: 'iv', 1: 'i' } roman_numeral = '' for key in sorted(roman_numerals.keys(), reverse=True): roman_numeral += roman_numerals[key] * (number // key) number = number % key
return roman_numeral
def check(candidate): assert candidate(19) == 'xix' assert candidate(152) == 'clii' assert candidate(251) == 'ccli' assert candidate(426) == 'cdxxvi' assert candidate(500) == 'd' assert candidate(1) == 'i' assert candidate(4) == 'iv' assert candidate(43) == 'xliii' assert candidate(90) == 'xc' assert candidate(94) == 'xciv' assert candidate(532) == 'dxxxii' assert candidate(900) == 'cm' assert candidate(994) == 'cmxciv' assert candidate(1000) == 'm' def test_check(): check(int_to_mini_roman) test_check()
humaneval-HumanEval_61_correct_bracketing.json-L29
js
//brackets is a string of "(" and ")". // return true if every opening bracket has a corresponding closing bracket. // >>> correct_bracketing("(") // false // >>> correct_bracketing("()") // true // >>> correct_bracketing("(()())") // true // >>> correct_bracketing(")(()") // false function correct_bracketing(brackets){ var opens = []; for (var i = 0; i < brackets.length; i++){ if (brackets[i] == "("){ opens.push(brackets[i]); } else if (brackets[i] == ")"){ if (opens.length > 0){ opens.pop(); } else { return false; } } } if (opens.length == 0){ return true; }
return false; } }
else {
const assert = require('node:assert'); function test() { let candidate = correct_bracketing; assert.deepEqual(candidate("()"),true); assert.deepEqual(candidate("(()())"),true); assert.deepEqual(candidate("()()(()())()"),true); assert.deepEqual(candidate("()()((()()())())(()()(()))"),true); assert.deepEqual(candidate("((()())))"),false); assert.deepEqual(candidate(")(()"),false); assert.deepEqual(candidate("("),false); assert.deepEqual(candidate("(((("),false); assert.deepEqual(candidate(")"),false); assert.deepEqual(candidate("(()"),false); assert.deepEqual(candidate("()()(()())())(()"),false); assert.deepEqual(candidate("()()(()())()))()"),false); } test();
humaneval-HumanEval_56_correct_bracketing.json-L23
js
//brackets is a string of "<" and ">". // return true if every opening bracket has a corresponding closing bracket. // >>> correct_bracketing("<") // false // >>> correct_bracketing("<>") // true // >>> correct_bracketing("<<><>>") // true // >>> correct_bracketing("><<>") // false function correct_bracketing(brackets){ var opens = 0; for (var i = 0; i < brackets.length; i++) { if (brackets[i] === "<") { opens++; } else if (brackets[i] === ">") { opens--; } if (opens < 0) { return false; }
return opens === 0; }
}
const assert = require('node:assert'); function test() { let candidate = correct_bracketing; assert.deepEqual(candidate("<>"),true); assert.deepEqual(candidate("<<><>>"),true); assert.deepEqual(candidate("<><><<><>><>"),true); assert.deepEqual(candidate("<><><<<><><>><>><<><><<>>>"),true); assert.deepEqual(candidate("<<<><>>>>"),false); assert.deepEqual(candidate("><<>"),false); assert.deepEqual(candidate("<"),false); assert.deepEqual(candidate("<<<<"),false); assert.deepEqual(candidate(">"),false); assert.deepEqual(candidate("<<>"),false); assert.deepEqual(candidate("<><><<><>><>><<>"),false); assert.deepEqual(candidate("<><><<><>><>>><>"),false); } test();
humaneval-HumanEval_49_modp.json-L28
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // 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_14_all_prefixes.json-L10
js
//Return array of all prefixes from shortest to longest of the input string // >>> all_prefixes("abc") // ["a", "ab", "abc"] function all_prefixes(string){ var result = []; for (var i = 1; i <= string.length; i++){ result.push(string.slice(0, i)); } return result;
}
const assert = require('node:assert'); function test() { let candidate = all_prefixes; assert.deepEqual(candidate(""),[]); assert.deepEqual(candidate("asdfgh"),["a", "as", "asd", "asdf", "asdfg", "asdfgh"]); assert.deepEqual(candidate("WWW"),["W", "WW", "WWW"]); } test();
humaneval-HumanEval_126_is_sorted.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 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;
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 { seen_2_in_a_row = true; } } else { seen_2_in_a_row = false; } previous_number = number.intValue(); running_max = number.intValue(); } } } return true; } } }
previous_number = number.intValue();
} 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_81_numerical_letter_grade.json-L33
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){
} 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; }
grades_array.push("A-");
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_6_parse_nested_parens.json-L26
js
//Input to this function is a string represented multiple groups for nested parentheses separated by spaces. // For each of the group, output the deepest level of nesting of parentheses. // E.g. (()()) has maximum two levels of nesting while ((())) has three. // >>> parse_nested_parens("(()()) ((())) () ((())()())") // [2, 3, 1, 3] function parse_nested_parens(paren_string){ var level = 0; var maxlevel = 0; var result = []; for (var i = 0; i < paren_string.length; i++){ if (paren_string[i] == "("){ level += 1; if (level > maxlevel){ maxlevel = level; } } else if (paren_string[i] == ")"){ level -= 1; } else if (paren_string[i] == " "){ result.push(maxlevel); maxlevel = 0; level = 0; } }
return result; }
result.push(maxlevel);
const assert = require('node:assert'); function test() { let candidate = parse_nested_parens; assert.deepEqual(candidate("(()()) ((())) () ((())()())"),[2, 3, 1, 3]); assert.deepEqual(candidate("() (()) ((())) (((())))"),[1, 2, 3, 4]); assert.deepEqual(candidate("(()(())((())))"),[4]); } test();
humaneval-HumanEval_52_below_threshold.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 true if all numbers in the array list l are below threshold t. // >>> belowThreshold((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)4l, (long)10l))), (100l)) // (true) // >>> belowThreshold((new ArrayList<Long>(Arrays.asList((long)1l, (long)20l, (long)4l, (long)10l))), (5l)) // (false) public static boolean belowThreshold(ArrayList<Long> l, long t) { Long[] a = l.toArray(new Long[l.size()]); for (int i = 0; i < a.length; i++) { if (a[i] >= t) { return false; } } return true;
}
}
} public static void main(String[] args) { assert(belowThreshold((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)4l, (long)10l))), (100l)) == (true)); assert(belowThreshold((new ArrayList<Long>(Arrays.asList((long)1l, (long)20l, (long)4l, (long)10l))), (5l)) == (false)); assert(belowThreshold((new ArrayList<Long>(Arrays.asList((long)1l, (long)20l, (long)4l, (long)10l))), (21l)) == (true)); assert(belowThreshold((new ArrayList<Long>(Arrays.asList((long)1l, (long)20l, (long)4l, (long)10l))), (22l)) == (true)); assert(belowThreshold((new ArrayList<Long>(Arrays.asList((long)1l, (long)8l, (long)4l, (long)10l))), (11l)) == (true)); assert(belowThreshold((new ArrayList<Long>(Arrays.asList((long)1l, (long)8l, (long)4l, (long)10l))), (10l)) == (false)); } }
humaneval-HumanEval_55_fib.json-L13
js
//Return n-th Fibonacci number. // >>> fib(10) // 55 // >>> fib(1) // 1 // >>> fib(8) // 21 function fib(n){ if(n <= 2){ return 1; } else { return fib(n-1) + fib(n-2);
}
}
const assert = require('node:assert'); function test() { let candidate = fib; assert.deepEqual(candidate(10),55); assert.deepEqual(candidate(1),1); assert.deepEqual(candidate(8),21); assert.deepEqual(candidate(11),89); assert.deepEqual(candidate(12),144); } test();
humaneval-HumanEval_105_by_length.json-L41
js
//Given an array of integers, sort the integers that are between 1 and 9 inclusive, // reverse the resulting array, and then replace each digit by its corresponding name from // "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine". // For example: // >>> by_length([2, 1, 1, 4, 5, 8, 2, 3]) // ["Eight", "Five", "Four", "Three", "Two", "Two", "One", "One"] // If the array is empty, return an empty array: // >>> by_length([]) // [] // If the array has any strange number ignore it: // >>> by_length([1, -1, 55]) // ["One"] function by_length(arr){ var arr2 = []; for(var i = 0; i < arr.length; i++){ var num = arr[i]; if(num > 0 && num < 10){ arr2.push(num); } } arr2.sort(); arr2.reverse(); var arr3 = []; for(var i = 0; i < arr2.length; i++){ var num = arr2[i]; if(num == 1){ arr3.push("One"); } else if(num == 2){ arr3.push("Two"); } else if(num == 3){ arr3.push("Three"); } else if(num == 4){ arr3.push("Four"); } else if(num == 5){ arr3.push("Five"); }
arr3.push("Six"); } else if(num == 7){ arr3.push("Seven"); } else if(num == 8){ arr3.push("Eight"); } else if(num == 9){ arr3.push("Nine"); } } return arr3; }
else if(num == 6){
const assert = require('node:assert'); function test() { let candidate = by_length; assert.deepEqual(candidate([2, 1, 1, 4, 5, 8, 2, 3]),["Eight", "Five", "Four", "Three", "Two", "Two", "One", "One"]); assert.deepEqual(candidate([]),[]); assert.deepEqual(candidate([1, -1, 55]),["One"]); assert.deepEqual(candidate([1, -1, 3, 2]),["Three", "Two", "One"]); assert.deepEqual(candidate([9, 4, 8]),["Nine", "Eight", "Four"]); } test();
humaneval-HumanEval_161_solve.json-L23
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // You are given a string s. // if s[i] is a letter, reverse its case from lower to upper or vise versa, // otherwise keep it as it is. // If the string contains no letters, reverse the string. // The function should return the resulted string. // Examples // >>> solve(("1234")) // ("4321") // >>> solve(("ab")) // ("AB") // >>> solve(("#a@C")) // ("#A@c") public static String solve(String s) { boolean letterNotFound = true;
if (s.length() == 0) return s; for (int i = 0; i < s.length(); i++) { if (Character.isLetter(s.charAt(i))) { letterNotFound = false; if (Character.isUpperCase(s.charAt(i))) { sb.append(Character.toLowerCase(s.charAt(i))); } else { sb.append(Character.toUpperCase(s.charAt(i))); } } else { sb.append(s.charAt(i)); } } if (letterNotFound) { return sb.reverse().toString(); } return sb.toString(); } }
StringBuilder sb = new StringBuilder();
} public static void main(String[] args) { assert(solve(("AsDf")).equals(("aSdF"))); assert(solve(("1234")).equals(("4321"))); assert(solve(("ab")).equals(("AB"))); assert(solve(("#a@C")).equals(("#A@c"))); assert(solve(("#AsdfW^45")).equals(("#aSDFw^45"))); assert(solve(("#6@2")).equals(("2@6#"))); assert(solve(("#$a^D")).equals(("#$A^d"))); assert(solve(("#ccc")).equals(("#CCC"))); } }
humaneval-HumanEval_126_is_sorted.json-L58
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 { seen_2_in_a_row = true; } } else {
} previous_number = number.intValue(); running_max = number.intValue(); } } } return true; } } }
seen_2_in_a_row = false;
} 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_93_encode.json-L12
js
//Write a function that takes a message, and encodes in such a // way that it swaps case of all letters, replaces all vowels in // the message with the letter that appears 2 places ahead of that // vowel in the english alphabet. // Assume only letters. // Examples: // >>> encode("test") // "TGST" // >>> encode("This is a message") // "tHKS KS C MGSSCGG" function encode(message){
let result = ""; for(let i = 0; i < message.length; i++){ let letter = message[i]; if(vowels.includes(letter.toLowerCase())){ let newIndex = (letter.charCodeAt(0) + 2 - (letter.toLowerCase() === letter ? 'a'.charCodeAt(0) : 'A'.charCodeAt(0))) % 26; letter = String.fromCharCode(newIndex + (letter.toLowerCase() === letter ? 'a'.charCodeAt(0) : 'A'.charCodeAt(0))); } result += letter.toUpperCase() === letter ? letter.toLowerCase() : letter.toUpperCase(); } return result; }
const vowels = "aeiou";
const assert = require('node:assert'); function test() { let candidate = encode; assert.deepEqual(candidate("TEST"),"tgst"); assert.deepEqual(candidate("Mudasir"),"mWDCSKR"); assert.deepEqual(candidate("YES"),"ygs"); assert.deepEqual(candidate("This is a message"),"tHKS KS C MGSSCGG"); assert.deepEqual(candidate("I DoNt KnOw WhAt tO WrItE"),"k dQnT kNqW wHcT Tq wRkTg"); } test();
humaneval-HumanEval_110_exchange.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 { // In this problem, you will implement a function that takes two array lists of numbers, // and determines whether it is possible to perform an exchange of elements // between them to make lst1 an array array list of only even numbers. // There is no limit on the number of exchanged elements between lst1 and lst2. // If it is possible to exchange elements between the lst1 and lst2 to make // all the elements of lst1 to be even, return "YES". // Otherwise, return "NO". // For example: // >>> exchange((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l))), (new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l)))) // ("YES") // >>> exchange((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l))), (new ArrayList<Long>(Arrays.asList((long)1l, (long)5l, (long)3l, (long)4l)))) // ("NO") // It is assumed that the input array lists will be non-empty. public static String exchange(ArrayList<Long> lst1, ArrayList<Long> lst2) { for (int i = 0; i < lst1.size(); i++) { if (lst1.get(i) % 2 == 1) {
if (lst2.get(j) % 2 == 0) { lst1.set(i, lst2.get(j)); lst2.set(j, (long) 1); break; } } } } return (lst1.stream().allMatch(x -> x % 2 == 0)) ? "YES" : "NO"; } }
for (int j = 0; j < lst2.size(); j++) {
} public static void main(String[] args) { assert(exchange((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l))), (new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l)))).equals(("YES"))); assert(exchange((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l))), (new ArrayList<Long>(Arrays.asList((long)1l, (long)5l, (long)3l, (long)4l)))).equals(("NO"))); assert(exchange((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l))), (new ArrayList<Long>(Arrays.asList((long)2l, (long)1l, (long)4l, (long)3l)))).equals(("YES"))); assert(exchange((new ArrayList<Long>(Arrays.asList((long)5l, (long)7l, (long)3l))), (new ArrayList<Long>(Arrays.asList((long)2l, (long)6l, (long)4l)))).equals(("YES"))); assert(exchange((new ArrayList<Long>(Arrays.asList((long)5l, (long)7l, (long)3l))), (new ArrayList<Long>(Arrays.asList((long)2l, (long)6l, (long)3l)))).equals(("NO"))); assert(exchange((new ArrayList<Long>(Arrays.asList((long)3l, (long)2l, (long)6l, (long)1l, (long)8l, (long)9l))), (new ArrayList<Long>(Arrays.asList((long)3l, (long)5l, (long)5l, (long)1l, (long)1l, (long)1l)))).equals(("NO"))); assert(exchange((new ArrayList<Long>(Arrays.asList((long)100l, (long)200l))), (new ArrayList<Long>(Arrays.asList((long)200l, (long)200l)))).equals(("YES"))); } }
humaneval-HumanEval_125_split_words.json-L18
py
from typing import Union, List def split_words(txt: str) -> Union[List[str], int]: """ Given a string of words, return a list of words split on whitespace, if no whitespaces exists in the text you should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25 Examples >>> split_words('Hello world!') ['Hello', 'world!'] >>> split_words('Hello,world!') ['Hello', 'world!'] >>> split_words('abcdef') 3 """ alphabet = [chr(letter) for letter in range(ord('a'), ord('z') + 1)] if ' ' in txt:
elif ',' in txt: return txt.split(',') else: return len([letter for letter in txt if letter in alphabet and alphabet.index(letter) % 2 == 1])
return txt.split(' ')
def check(candidate): assert candidate('Hello world!') == ['Hello', 'world!'] assert candidate('Hello,world!') == ['Hello', 'world!'] assert candidate('Hello world,!') == ['Hello', 'world,!'] assert candidate('Hello,Hello,world !') == ['Hello,Hello,world', '!'] assert candidate('abcdef') == 3 assert candidate('aaabb') == 2 assert candidate('aaaBb') == 1 assert candidate('') == 0 def test_check(): check(split_words) test_check()
humaneval-HumanEval_94_skjkasdkd.json-L19
js
//You are given an array of integers. // You need to find the largest prime value and return the sum of its digits. // Examples: // >>> skjkasdkd([0, 3, 2, 1, 3, 5, 7, 4, 5, 5, 5, 2, 181, 32, 4, 32, 3, 2, 32, 324, 4, 3]) // 10 // >>> skjkasdkd([1, 0, 1, 8, 2, 4597, 2, 1, 3, 40, 1, 2, 1, 2, 4, 2, 5, 1]) // 25 // >>> skjkasdkd([1, 3, 1, 32, 5107, 34, 83278, 109, 163, 23, 2323, 32, 30, 1, 9, 3]) // 13 // >>> skjkasdkd([0, 724, 32, 71, 99, 32, 6, 0, 5, 91, 83, 0, 5, 6]) // 11 // >>> skjkasdkd([0, 81, 12, 3, 1, 21]) // 3 // >>> skjkasdkd([0, 8, 1, 2, 1, 7]) // 7 function skjkasdkd(lst){ function prime(n){ if (n<2) return false;
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; }
for (let i=2; i<=Math.sqrt(n); i++){
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_137_compare_one.json-L34
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):
b_tmp = b.replace(',', '.') if float(a_tmp) > float(b_tmp): return a elif float(a_tmp) < float(b_tmp): return b else: return None elif isinstance(a, int) and isinstance(b, float): if a > b: return a elif a < b: return b else: return None elif isinstance(a, float) and isinstance(b, int): if a > b: return a elif a < b: return b else: return None elif isinstance(a, str) and isinstance(b, int): a_tmp = a.replace(',', '.') if float(a_tmp) > b: return a elif float(a_tmp) < b: return b else: return None elif isinstance(a, int) and isinstance(b, str): b_tmp = b.replace(',', '.') if a > float(b_tmp): return a elif a < float(b_tmp): return b else: return None elif isinstance(a, str) and isinstance(b, float): a_tmp = a.replace(',', '.') if float(a_tmp) > b: return a elif float(a_tmp) < b: return b
a_tmp = a.replace(',', '.')
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_28_concatenate.json-L16
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Concatenate array list of strings into a single string // >>> concatenate((new ArrayList<String>(Arrays.asList()))) // ("") // >>> concatenate((new ArrayList<String>(Arrays.asList((String)"a", (String)"b", (String)"c")))) // ("abc") public static String concatenate(ArrayList<String> strings) { return strings.stream().collect(Collectors.joining());
}
}
} public static void main(String[] args) { assert(concatenate((new ArrayList<String>(Arrays.asList()))).equals((""))); assert(concatenate((new ArrayList<String>(Arrays.asList((String)"x", (String)"y", (String)"z")))).equals(("xyz"))); assert(concatenate((new ArrayList<String>(Arrays.asList((String)"x", (String)"y", (String)"z", (String)"w", (String)"k")))).equals(("xyzwk"))); } }
humaneval-HumanEval_62_derivative.json-L12
js
//xs represent coefficients of a polynomial. // xs[0] + xs[1] * x + xs[2] * x^2 + .... // Return derivative of this polynomial in the same form. // >>> derivative([3, 1, 2, 4, 5]) // [1, 4, 12, 20] // >>> derivative([1, 2, 3]) // [2, 6] function derivative(xs){ let coeff = []; for(let i = 1; i < xs.length; i++){ coeff.push(xs[i] * i);
return coeff; }
}
const assert = require('node:assert'); function test() { let candidate = derivative; assert.deepEqual(candidate([3, 1, 2, 4, 5]),[1, 4, 12, 20]); assert.deepEqual(candidate([1, 2, 3]),[2, 6]); assert.deepEqual(candidate([3, 2, 1]),[2, 2]); assert.deepEqual(candidate([3, 2, 1, 0, 4]),[2, 2, 0, 16]); assert.deepEqual(candidate([1]),[]); } test();
humaneval-HumanEval_104_unique_digits.json-L38
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Given an array array list of positive integers x. return a sorted array list of all // elements that hasn't any even digit. // Note: Returned array list should be sorted in increasing order. // For example: // >>> uniqueDigits((new ArrayList<Long>(Arrays.asList((long)15l, (long)33l, (long)1422l, (long)1l)))) // (new ArrayList<Long>(Arrays.asList((long)1l, (long)15l, (long)33l))) // >>> uniqueDigits((new ArrayList<Long>(Arrays.asList((long)152l, (long)323l, (long)1422l, (long)10l)))) // (new ArrayList<Long>(Arrays.asList())) public static ArrayList<Long> uniqueDigits(ArrayList<Long> x) { ArrayList<Long> b = new ArrayList<Long>(); for (int i = 0; i < x.size(); i++) { if (x.get(i) < 0) { x.set(i, x.get(i)*(long)-1); } boolean unique = true; long z = x.get(i); while (z > 0) { long y = z % 10; if (y % 2 == 0) { unique = false; break; } z = z / 10; } if (unique) { b.add(x.get(i)); } } Collections.sort(b);
} }
return b;
} public static void main(String[] args) { assert(uniqueDigits((new ArrayList<Long>(Arrays.asList((long)15l, (long)33l, (long)1422l, (long)1l)))).equals((new ArrayList<Long>(Arrays.asList((long)1l, (long)15l, (long)33l))))); assert(uniqueDigits((new ArrayList<Long>(Arrays.asList((long)152l, (long)323l, (long)1422l, (long)10l)))).equals((new ArrayList<Long>(Arrays.asList())))); assert(uniqueDigits((new ArrayList<Long>(Arrays.asList((long)12345l, (long)2033l, (long)111l, (long)151l)))).equals((new ArrayList<Long>(Arrays.asList((long)111l, (long)151l))))); assert(uniqueDigits((new ArrayList<Long>(Arrays.asList((long)135l, (long)103l, (long)31l)))).equals((new ArrayList<Long>(Arrays.asList((long)31l, (long)135l))))); } }
humaneval-HumanEval_13_greatest_common_divisor.json-L13
js
//Return a greatest common divisor of two integers a and b // >>> greatest_common_divisor(3, 5) // 1 // >>> greatest_common_divisor(25, 15) // 5 function greatest_common_divisor(a, b){ let max = Math.max(a, b) let min = Math.min(a, b) if (max % min == 0) { return min } else { return greatest_common_divisor(min, max % min)
}
}
const assert = require('node:assert'); function test() { let candidate = greatest_common_divisor; assert.deepEqual(candidate(3, 7),1); assert.deepEqual(candidate(10, 15),5); assert.deepEqual(candidate(49, 14),7); assert.deepEqual(candidate(144, 60),12); } test();
humaneval-HumanEval_64_vowels_count.json-L22
js
//Write a function vowels_count which takes a string representing // a word as input and returns the number of vowels in the string. // Vowels in this case are 'a', 'e', 'i', 'o', 'u'. Here, 'y' is also a // vowel, but only when it is at the end of the given word. // Example: // >>> vowels_count("abcde") // 2 // >>> vowels_count("ACEDY") // 3 function vowels_count(s){ s=s.toLowerCase(); var vowels = ['a','e','i','o','u']; var count = 0; for(var i=0; i<s.length; i++){ if(vowels.indexOf(s[i])!=-1){ count++; } } if(s[s.length-1]=='y'){ count++; }
}
return count;
const assert = require('node:assert'); function test() { let candidate = vowels_count; assert.deepEqual(candidate("abcde"),2); assert.deepEqual(candidate("Alone"),3); assert.deepEqual(candidate("key"),2); assert.deepEqual(candidate("bye"),1); assert.deepEqual(candidate("keY"),2); assert.deepEqual(candidate("bYe"),1); assert.deepEqual(candidate("ACEDY"),3); } test();
humaneval-HumanEval_71_triangle_area.json-L13
js
//Given the lengths of the three sides of a triangle. Return the area of // the triangle rounded to 2 decimal points if the three sides form a valid triangle. // Otherwise return -1 // Three sides make a valid triangle when the sum of any two sides is greater // than the third side. // Example: // >>> triangle_area(3, 4, 5) // 6.0 // >>> triangle_area(1, 2, 10) // -1 function triangle_area(a, b, c){ if(a+b>c && a+c>b && b+c>a){
return Math.sqrt(s*(s-a)*(s-b)*(s-c)).toFixed(2); }else{ return -1; } }
var s = (a+b+c)/2;
const assert = require('node:assert'); function test() { let candidate = triangle_area; assert.deepEqual(candidate(3, 4, 5),6.0); assert.deepEqual(candidate(1, 2, 10),-1); assert.deepEqual(candidate(4, 8, 5),8.18); assert.deepEqual(candidate(2, 2, 2),1.73); assert.deepEqual(candidate(1, 2, 3),-1); assert.deepEqual(candidate(10, 5, 7),16.25); assert.deepEqual(candidate(2, 6, 3),-1); assert.deepEqual(candidate(1, 1, 1),0.43); assert.deepEqual(candidate(2, 2, 10),-1); } test();
humaneval-HumanEval_59_largest_prime_factor.json-L10
py
def largest_prime_factor(n: int) -> int: """Return the largest prime factor of n. Assume n > 1 and is not a prime. >>> largest_prime_factor(13195) 29 >>> largest_prime_factor(2048) 2 """ largest = 1 factor = 2
if n % factor == 0: largest = factor while n % factor == 0: n = n // factor factor += 1 return max(largest, n)
while factor < n:
def check(candidate): assert candidate(15) == 5 assert candidate(27) == 3 assert candidate(63) == 7 assert candidate(330) == 11 assert candidate(13195) == 29 def test_check(): check(largest_prime_factor) test_check()
humaneval-HumanEval_152_compare.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 { // 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++) {
result.add(Math.abs(game.get(i) - guess.get(i))); } else { result.add((long)0); } } return result; } }
if (game.get(i) != guess.get(i)) {
} public static void main(String[] args) { assert(compare((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l, (long)5l, (long)1l))), (new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l, (long)2l, (long)-2l)))).equals((new ArrayList<Long>(Arrays.asList((long)0l, (long)0l, (long)0l, (long)0l, (long)3l, (long)3l))))); assert(compare((new ArrayList<Long>(Arrays.asList((long)0l, (long)0l, (long)0l, (long)0l, (long)0l, (long)0l))), (new ArrayList<Long>(Arrays.asList((long)0l, (long)0l, (long)0l, (long)0l, (long)0l, (long)0l)))).equals((new ArrayList<Long>(Arrays.asList((long)0l, (long)0l, (long)0l, (long)0l, (long)0l, (long)0l))))); assert(compare((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l))), (new ArrayList<Long>(Arrays.asList((long)-1l, (long)-2l, (long)-3l)))).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)4l, (long)6l))))); assert(compare((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)5l))), (new ArrayList<Long>(Arrays.asList((long)-1l, (long)2l, (long)3l, (long)4l)))).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)0l, (long)0l, (long)1l))))); } }
humaneval-HumanEval_141_file_name_check.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 { // 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++; } }
return result; } if (name.length() == 0) { return result; } if (!Character.isLetter(name.charAt(0))) { return result; } return "Yes"; } }
if (count > 3) {
} 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_97_multiply.json-L16
js
//Complete the function that takes two integers and returns // the product of their unit digits. // Assume the input is always valid. // Examples: // >>> multiply(148, 412) // 16 // >>> multiply(19, 28) // 72 // >>> multiply(2020, 1851) // 0 // >>> multiply(14, -15) // 20 function multiply(a, b){ let aStr = a.toString() let bStr = b.toString()
}
return parseInt(aStr[aStr.length - 1]) * parseInt(bStr[bStr.length - 1])
const assert = require('node:assert'); function test() { let candidate = multiply; assert.deepEqual(candidate(148, 412),16); assert.deepEqual(candidate(19, 28),72); assert.deepEqual(candidate(2020, 1851),0); assert.deepEqual(candidate(14, -15),20); assert.deepEqual(candidate(76, 67),42); assert.deepEqual(candidate(17, 27),49); assert.deepEqual(candidate(0, 1),0); assert.deepEqual(candidate(0, 0),0); } test();
humaneval-HumanEval_81_numerical_letter_grade.json-L58
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_141_file_name_check.json-L33
py
def file_name_check(file_name: str) -> str: """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' """ if not file_name: return 'No' s_count = 0 e_count = 0 for i in file_name: if i.isdigit(): s_count += 1 if i == '.': e_count += 1 if s_count > 3 or e_count != 1: return 'No' s_name = file_name.split('.')[0] e_name = file_name.split('.')[1] if not s_name or not e_name or not s_name[0].isalpha(): return 'No' if e_name not in ['txt', 'exe', 'dll']:
return 'Yes'
return 'No'
def check(candidate): assert candidate('example.txt') == 'Yes' assert candidate('1example.dll') == 'No' assert candidate('s1sdf3.asd') == 'No' assert candidate('K.dll') == 'Yes' assert candidate('MY16FILE3.exe') == 'Yes' assert candidate('His12FILE94.exe') == 'No' assert candidate('_Y.txt') == 'No' assert candidate('?aREYA.exe') == 'No' assert candidate('/this_is_valid.dll') == 'No' assert candidate('this_is_valid.wow') == 'No' assert candidate('this_is_valid.txt') == 'Yes' assert candidate('this_is_valid.txtexe') == 'No' assert candidate('#this2_i4s_5valid.ten') == 'No' assert candidate('@this1_is6_valid.exe') == 'No' assert candidate('this_is_12valid.6exe4.txt') == 'No' assert candidate('all.exe.txt') == 'No' assert candidate('I563_No.exe') == 'Yes' assert candidate('Is3youfault.txt') == 'Yes' assert candidate('no_one#knows.dll') == 'Yes' assert candidate('1I563_Yes3.exe') == 'No' assert candidate('I563_Yes3.txtt') == 'No' assert candidate('final..txt') == 'No' assert candidate('final132') == 'No' assert candidate('_f4indsartal132.') == 'No' assert candidate('.txt') == 'No' assert candidate('s.') == 'No' def test_check(): check(file_name_check) test_check()
humaneval-HumanEval_31_is_prime.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 { // 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 <= 1) return false; if (n <= 3) return true;
long i = 5; while (i * i <= n) { if (n % i == 0 || n % (i + 2) == 0) return false; i += 6; } return true; } }
if (n % 2 == 0 || n % 3 == 0) 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_93_encode.json-L18
py
def encode(message: str) -> str: """ Write a function that takes a message, and encodes in such a way that it swaps case of all letters, replaces all vowels in the message with the letter that appears 2 places ahead of that vowel in the english alphabet. Assume only letters. Examples: >>> encode('test') 'TGST' >>> encode('This is a message') 'tHKS KS C MGSSCGG' """ def swap_case(ch: str) -> str: if ch.isupper(): return ch.lower()
return ch.upper() def encode_vowel(ch: str) -> str: if ch.lower() in 'aeiou': if ch.lower() in 'wxyz': return ch.lower() return chr(ord(ch) + 2) return ch return ''.join(map(lambda ch: encode_vowel(swap_case(ch)), message))
else:
def check(candidate): assert candidate('TEST') == 'tgst' assert candidate('Mudasir') == 'mWDCSKR' assert candidate('YES') == 'ygs' assert candidate('This is a message') == 'tHKS KS C MGSSCGG' assert candidate('I DoNt KnOw WhAt tO WrItE') == 'k dQnT kNqW wHcT Tq wRkTg' def test_check(): check(encode) test_check()
humaneval-HumanEval_161_solve.json-L18
js
//You are given a string s. // if s[i] is a letter, reverse its case from lower to upper or vise versa, // otherwise keep it as it is. // If the string contains no letters, reverse the string. // The function should return the resulted string. // Examples // >>> solve("1234") // "4321" // >>> solve("ab") // "AB" // >>> solve("#a@C") // "#A@c" function solve(s){ let letters = s.match(/[a-z]/ig); if(letters) { const swapped = s.split('').map(char => { if(/[a-z]/i.test(char)) {
? char.toUpperCase() : char.toLowerCase(); } return char; }); return swapped.join(''); } return s.split('').reverse().join(''); }
return char === char.toLowerCase()
const assert = require('node:assert'); function test() { let candidate = solve; assert.deepEqual(candidate("AsDf"),"aSdF"); assert.deepEqual(candidate("1234"),"4321"); assert.deepEqual(candidate("ab"),"AB"); assert.deepEqual(candidate("#a@C"),"#A@c"); assert.deepEqual(candidate("#AsdfW^45"),"#aSDFw^45"); assert.deepEqual(candidate("#6@2"),"2@6#"); assert.deepEqual(candidate("#$a^D"),"#$A^d"); assert.deepEqual(candidate("#ccc"),"#CCC"); } test();
humaneval-HumanEval_138_is_equal_to_sum_even.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 { // Evaluate whether the given number n can be written as the sum of exactly 4 positive even numbers // Example // >>> isEqualToSumEven((4l)) // (false) // >>> isEqualToSumEven((6l)) // (false) // >>> isEqualToSumEven((8l)) // (true) public static boolean isEqualToSumEven(long n) { if (n < 4) { return false; } long d = 2; if (n % 2 == 1) { d = 1; }
long maxX = n / 4; while (minX <= maxX) { long x = (minX + maxX) / 2; long y = n - 2 * x; if (y % 2 == 1) { y--; } if (2 * x + y < n) { minX = x + 1; } else if (2 * x + y > n) { maxX = x - 1; } else { return true; } } return false; } }
long minX = d;
} public static void main(String[] args) { assert(isEqualToSumEven((4l)) == (false)); assert(isEqualToSumEven((6l)) == (false)); assert(isEqualToSumEven((8l)) == (true)); assert(isEqualToSumEven((10l)) == (true)); assert(isEqualToSumEven((11l)) == (false)); assert(isEqualToSumEven((12l)) == (true)); assert(isEqualToSumEven((13l)) == (false)); assert(isEqualToSumEven((16l)) == (true)); } }
humaneval-HumanEval_118_get_closest_vowel.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 { // You are given a word. Your task is to find the closest vowel that stands between // two consonants from the right side of the word (case sensitive). // Vowels in the beginning and ending doesn't count. Return empty string if you didn't // find any vowel met the above condition. // You may assume that the given string contains English letter only. // Example: // >>> getClosestVowel(("yogurt")) // ("u") // >>> getClosestVowel(("FULL")) // ("U") // >>> getClosestVowel(("quick")) // ("") // >>> getClosestVowel(("ab")) // ("") public static String getClosestVowel(String word) { final String vowels = "aeiou"; final String consonants = "bcdfghjklmnpqrstvwxyz"; List<Integer> idx = new ArrayList<>(); word = word.toLowerCase(); for (int i = 0; i < word.length(); i++) { if (vowels.indexOf(word.charAt(i)) != -1) { idx.add(i); } } for (int i = idx.size() - 1; i >= 0; i--) { int j = idx.get(i); if (j == 0 || j == word.length() - 1) continue; char left = word.charAt(j - 1); char right = word.charAt(j + 1); if (consonants.indexOf(left) != -1 && consonants.indexOf(right) != -1) { return String.valueOf(word.charAt(j)); }
return ""; } }
}
} public static void main(String[] args) { assert(getClosestVowel(("yogurt")).equals(("u"))); assert(getClosestVowel(("full")).equals(("u"))); assert(getClosestVowel(("easy")).equals((""))); assert(getClosestVowel(("eAsy")).equals((""))); assert(getClosestVowel(("ali")).equals((""))); assert(getClosestVowel(("bad")).equals(("a"))); assert(getClosestVowel(("most")).equals(("o"))); assert(getClosestVowel(("ab")).equals((""))); assert(getClosestVowel(("ba")).equals((""))); assert(getClosestVowel(("quick")).equals((""))); assert(getClosestVowel(("anime")).equals(("i"))); assert(getClosestVowel(("Asia")).equals((""))); assert(getClosestVowel(("Above")).equals(("o"))); } }
humaneval-HumanEval_73_smallest_change.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 { // Given an array array list arr of integers, find the minimum number of elements that // need to be changed to make the array array list palindromic. A palindromic array array list is an array array list that // is read the same backwards and forwards. In one change, you can change one element to any other element. // For example: // >>> smallestChange((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)5l, (long)4l, (long)7l, (long)9l, (long)6l)))) // (4l) // >>> smallestChange((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l, (long)3l, (long)2l, (long)2l)))) // (1l) // >>> smallestChange((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)2l, (long)1l)))) // (0l) public static long smallestChange(ArrayList<Long> arr) { int first = 0; int last = arr.size() - 1; int count = 0; while (first < last) { if (arr.get(first) != arr.get(last)) { count++; } first++; last--;
return count; } }
}
} public static void main(String[] args) { assert(smallestChange((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)5l, (long)4l, (long)7l, (long)9l, (long)6l)))) == (4l)); assert(smallestChange((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l, (long)3l, (long)2l, (long)2l)))) == (1l)); assert(smallestChange((new ArrayList<Long>(Arrays.asList((long)1l, (long)4l, (long)2l)))) == (1l)); assert(smallestChange((new ArrayList<Long>(Arrays.asList((long)1l, (long)4l, (long)4l, (long)2l)))) == (1l)); assert(smallestChange((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)2l, (long)1l)))) == (0l)); assert(smallestChange((new ArrayList<Long>(Arrays.asList((long)3l, (long)1l, (long)1l, (long)3l)))) == (0l)); assert(smallestChange((new ArrayList<Long>(Arrays.asList((long)1l)))) == (0l)); assert(smallestChange((new ArrayList<Long>(Arrays.asList((long)0l, (long)1l)))) == (1l)); } }
humaneval-HumanEval_81_numerical_letter_grade.json-L44
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:
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') elif x > 0.0: final.append('D-') else: final.append('E') return final
final.append('C+')
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_60_sum_to_n.json-L14
js
//sum_to_n is a function that sums numbers from 1 to n. // >>> sum_to_n(30) // 465 // >>> sum_to_n(100) // 5050 // >>> sum_to_n(5) // 15 // >>> sum_to_n(10) // 55 // >>> sum_to_n(1) // 1 function sum_to_n(n){ var sum = 0;
sum += i; } return sum; }
for(var i = 1; i <= n; i++){
const assert = require('node:assert'); function test() { let candidate = sum_to_n; assert.deepEqual(candidate(1),1); assert.deepEqual(candidate(6),21); assert.deepEqual(candidate(11),66); assert.deepEqual(candidate(30),465); assert.deepEqual(candidate(100),5050); } test();
humaneval-HumanEval_137_compare_one.json-L29
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
return b else: return None elif isinstance(a, str) and isinstance(b, str): a_tmp = a.replace(',', '.') b_tmp = b.replace(',', '.') if float(a_tmp) > float(b_tmp): return a elif float(a_tmp) < float(b_tmp): return b else: return None elif isinstance(a, int) and isinstance(b, float): if a > b: return a elif a < b: return b else: return None elif isinstance(a, float) and isinstance(b, int): if a > b: return a elif a < b: return b else: return None elif isinstance(a, str) and isinstance(b, int): a_tmp = a.replace(',', '.') if float(a_tmp) > b: return a elif float(a_tmp) < b: return b else: return None elif isinstance(a, int) and isinstance(b, str): b_tmp = b.replace(',', '.') if a > float(b_tmp): return a elif a < float(b_tmp): return b else: return None elif isinstance(a, str) and isinstance(b, float): a_tmp = a.replace(',', '.') if float(a_tmp) > b: return a elif float(a_tmp) < b: return b
elif a < 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_107_even_odd_palindrome.json-L21
js
//Given a positive integer n, return an array that has the number of even and odd // integer palindromes that fall within the range(1, n), inclusive. // Example 1: // >>> even_odd_palindrome(3) // [1, 2] // Explanation: // Integer palindrome are 1, 2, 3. one of them is even, and two of them are odd. // Example 2: // >>> even_odd_palindrome(12) // [4, 6] // Explanation: // Integer palindrome are 1, 2, 3, 4, 5, 6, 7, 8, 9, 11. four of them are even, and 6 of them are odd. // Note: // 1. 1 <= n <= 10^3 // 2. returned array has the number of even and odd integer palindromes respectively. function even_odd_palindrome(n){ var pal = []; var isPalindrome = function(x){ var y = x.toString().split('').reverse().join(''); return y == x;
for(var i = 1; i <= n; i++){ if(isPalindrome(i)){ pal.push(i); } } var odd = 0; var even = 0; for(var i = 0; i < pal.length; i++){ if(pal[i] % 2 == 0){ even++; } else{ odd++; } } return [even, odd]; }
}
const assert = require('node:assert'); function test() { let candidate = even_odd_palindrome; assert.deepEqual(candidate(123),[8, 13]); assert.deepEqual(candidate(12),[4, 6]); assert.deepEqual(candidate(3),[1, 2]); assert.deepEqual(candidate(63),[6, 8]); assert.deepEqual(candidate(25),[5, 6]); assert.deepEqual(candidate(19),[4, 6]); assert.deepEqual(candidate(9),[4, 5]); assert.deepEqual(candidate(1),[0, 1]); } test();
humaneval-HumanEval_158_find_max.json-L33
js
//Write a function that accepts an array of strings. // The array contains different words. Return the word with maximum number // of unique characters. If multiple strings have maximum number of unique // characters, return the one which comes first in lexicographical order. // >>> find_max(["name", "of", "string"]) // "string" // >>> find_max(["name", "enam", "game"]) // "enam" // >>> find_max(["aaaaaaa", "bb", "cc"]) // "aaaaaaa" function find_max(words){ var max_unique = {}; var max_unique_word = ""; for(var i = 0; i < words.length; i++){ var unique_word = {}; var word = words[i]; for(var j = 0; j < word.length; j++){ var char = word[j]; if(unique_word[char] === undefined){ unique_word[char] = 1; } } if(max_unique_word === ""){ max_unique_word = word; max_unique = unique_word; } else if(Object.keys(unique_word).length > Object.keys(max_unique).length){ max_unique_word = word; max_unique = unique_word; } else if(Object.keys(unique_word).length === Object.keys(max_unique).length){ if(word < max_unique_word){
max_unique = unique_word; } } } return max_unique_word; }
max_unique_word = word;
const assert = require('node:assert'); function test() { let candidate = find_max; assert.deepEqual(candidate(["name", "of", "string"]),"string"); assert.deepEqual(candidate(["name", "enam", "game"]),"enam"); assert.deepEqual(candidate(["aaaaaaa", "bb", "cc"]),"aaaaaaa"); assert.deepEqual(candidate(["abc", "cba"]),"abc"); assert.deepEqual(candidate(["play", "this", "game", "of", "footbott"]),"footbott"); assert.deepEqual(candidate(["we", "are", "gonna", "rock"]),"gonna"); assert.deepEqual(candidate(["we", "are", "a", "mad", "nation"]),"nation"); assert.deepEqual(candidate(["this", "is", "a", "prrk"]),"this"); assert.deepEqual(candidate(["b"]),"b"); assert.deepEqual(candidate(["play", "play", "play"]),"play"); } test();
humaneval-HumanEval_40_triples_sum_to_zero.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 { // triples_sum_to_zero takes an array array list of integers as an input. // it returns true if there are three distinct elements in the array list that // sum to zero, and false otherwise. // >>> triplesSumToZero((new ArrayList<Long>(Arrays.asList((long)1l, (long)3l, (long)5l, (long)0l)))) // (false) // >>> triplesSumToZero((new ArrayList<Long>(Arrays.asList((long)1l, (long)3l, (long)-2l, (long)1l)))) // (true) // >>> triplesSumToZero((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)7l)))) // (false) // >>> triplesSumToZero((new ArrayList<Long>(Arrays.asList((long)2l, (long)4l, (long)-5l, (long)3l, (long)9l, (long)7l)))) // (true) // >>> triplesSumToZero((new ArrayList<Long>(Arrays.asList((long)1l)))) // (false) public static boolean triplesSumToZero(ArrayList<Long> l) { if (l.size() < 3) { return false; } ArrayList<Long> sortedList = new ArrayList<Long>(l); Collections.sort(sortedList); for (int i = 0; i < sortedList.size() - 2; i++) { int j = i + 1; int k = sortedList.size() - 1; while (j < k) { long currSum = sortedList.get(i) + sortedList.get(j) + sortedList.get(k); if (currSum == 0) { return true; } else if (currSum < 0) { j++; } else { k--; }
} return false; } }
}
} public static void main(String[] args) { assert(triplesSumToZero((new ArrayList<Long>(Arrays.asList((long)1l, (long)3l, (long)5l, (long)0l)))) == (false)); assert(triplesSumToZero((new ArrayList<Long>(Arrays.asList((long)1l, (long)3l, (long)5l, (long)-1l)))) == (false)); assert(triplesSumToZero((new ArrayList<Long>(Arrays.asList((long)1l, (long)3l, (long)-2l, (long)1l)))) == (true)); assert(triplesSumToZero((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)7l)))) == (false)); assert(triplesSumToZero((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)5l, (long)7l)))) == (false)); assert(triplesSumToZero((new ArrayList<Long>(Arrays.asList((long)2l, (long)4l, (long)-5l, (long)3l, (long)9l, (long)7l)))) == (true)); assert(triplesSumToZero((new ArrayList<Long>(Arrays.asList((long)1l)))) == (false)); assert(triplesSumToZero((new ArrayList<Long>(Arrays.asList((long)1l, (long)3l, (long)5l, (long)-100l)))) == (false)); assert(triplesSumToZero((new ArrayList<Long>(Arrays.asList((long)100l, (long)3l, (long)5l, (long)-100l)))) == (false)); } }
humaneval-HumanEval_125_split_words.json-L15
js
//Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you // should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the // alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25 // Examples // >>> split_words("Hello world!") // ["Hello", "world!"] // >>> split_words("Hello,world!") // ["Hello", "world!"] // >>> split_words("abcdef") // 3 function split_words(txt){ if(txt.includes(' ')){ return txt.split(' '); }
return txt.split(','); } else{ let count = 0; for(let i = 0; i < txt.length; i++){ if(i % 2 != 0){ if(txt[i] == txt[i].toLowerCase()){ count++; } } } return count; } }
else if(txt.includes(',')){
const assert = require('node:assert'); function test() { let candidate = split_words; assert.deepEqual(candidate("Hello world!"),["Hello", "world!"]); assert.deepEqual(candidate("Hello,world!"),["Hello", "world!"]); assert.deepEqual(candidate("Hello world,!"),["Hello", "world,!"]); assert.deepEqual(candidate("Hello,Hello,world !"),["Hello,Hello,world", "!"]); assert.deepEqual(candidate("abcdef"),3); assert.deepEqual(candidate("aaabb"),2); assert.deepEqual(candidate("aaaBb"),1); assert.deepEqual(candidate(""),0); } test();
humaneval-HumanEval_54_same_chars.json-L22
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++){ if(s1.indexOf(s0[i]) === -1){ res = false; break; } }
if(s0.indexOf(s1[i]) === -1){ res = false; break; } } return res; }
for(let i = 0; i < s1.length; i++){
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_43_pairs_sum_to_zero.json-L23
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_137_compare_one.json-L36
js
//Create a function that takes integers, floats, or strings representing // real numbers, and returns the larger variable in its given variable type. // Return undefined if the values are equal. // Note: If a real number is represented as a string, the floating point might be . or , // >>> compare_one(1, 2.5) // 2.5 // >>> compare_one(1, "2,3") // "2,3" // >>> compare_one("5,1", "6") // "6" // >>> compare_one("1", 1) // undefined function compare_one(a, b){ if (typeof a === typeof b){ if (a > b) { return a; } else if (a < b) { return b; } else { return undefined; } } else if (typeof a === "string" && typeof b === "number"){ if (a[0] > b){ return a; } else if (a[0] < b){ return b; } else { return undefined; } } else if (typeof a === "number" && typeof b === "string"){ if (a > b[0]){ return a; } else if (a < b[0]){
} else { return undefined; } } }
return b;
const assert = require('node:assert'); function test() { let candidate = compare_one; assert.deepEqual(candidate(1, 2),2); assert.deepEqual(candidate(1, 2.5),2.5); assert.deepEqual(candidate(2, 3),3); assert.deepEqual(candidate(5, 6),6); assert.deepEqual(candidate(1, "2,3"),"2,3"); assert.deepEqual(candidate("5,1", "6"),"6"); assert.deepEqual(candidate("1", "2"),"2"); assert.deepEqual(candidate("1", 1),undefined); } test();
humaneval-HumanEval_61_correct_bracketing.json-L32
js
//brackets is a string of "(" and ")". // return true if every opening bracket has a corresponding closing bracket. // >>> correct_bracketing("(") // false // >>> correct_bracketing("()") // true // >>> correct_bracketing("(()())") // true // >>> correct_bracketing(")(()") // false function correct_bracketing(brackets){ var opens = []; for (var i = 0; i < brackets.length; i++){ if (brackets[i] == "("){ opens.push(brackets[i]); } else if (brackets[i] == ")"){ if (opens.length > 0){ opens.pop(); } else { return false; } } } if (opens.length == 0){ return true; } else { return false; }
}
const assert = require('node:assert'); function test() { let candidate = correct_bracketing; assert.deepEqual(candidate("()"),true); assert.deepEqual(candidate("(()())"),true); assert.deepEqual(candidate("()()(()())()"),true); assert.deepEqual(candidate("()()((()()())())(()()(()))"),true); assert.deepEqual(candidate("((()())))"),false); assert.deepEqual(candidate(")(()"),false); assert.deepEqual(candidate("("),false); assert.deepEqual(candidate("(((("),false); assert.deepEqual(candidate(")"),false); assert.deepEqual(candidate("(()"),false); assert.deepEqual(candidate("()()(()())())(()"),false); assert.deepEqual(candidate("()()(()())()))()"),false); } test();
humaneval-HumanEval_72_will_it_fly.json-L39
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Write a function that returns true if the object q will fly, and false otherwise. // The object q will fly if it's balanced (it is a palindromic array list) and the sum of its elements is less than or equal the maximum possible weight w. // Example: // >>> willItFly((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l))), (5l)) // (false) // # 1+2 is less than the maximum possible weight, but it's unbalanced. // >>> willItFly((new ArrayList<Long>(Arrays.asList((long)3l, (long)2l, (long)3l))), (1l)) // (false) // # it's balanced, but 3+2+3 is more than the maximum possible weight. // >>> willItFly((new ArrayList<Long>(Arrays.asList((long)3l, (long)2l, (long)3l))), (9l)) // (true) // # 3+2+3 is less than the maximum possible weight, and it's balanced. // >>> willItFly((new ArrayList<Long>(Arrays.asList((long)3l))), (5l)) // (true) // # 3 is less than the maximum possible weight, and it's balanced. public static boolean willItFly(ArrayList<Long> q, long w) { if (q.size() == 0) { return false; } if (q.size() == 1) { return true; } Long sum = 0l; for (int i = 0; i < q.size(); i++) { sum += q.get(i); } if (sum > w) { return false; } for (int i = 0; i < q.size() / 2; i++) {
return false; } } return true; } }
if (q.get(i) != q.get(q.size() - 1 - i)) {
} public static void main(String[] args) { assert(willItFly((new ArrayList<Long>(Arrays.asList((long)3l, (long)2l, (long)3l))), (9l)) == (true)); assert(willItFly((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l))), (5l)) == (false)); assert(willItFly((new ArrayList<Long>(Arrays.asList((long)3l))), (5l)) == (true)); assert(willItFly((new ArrayList<Long>(Arrays.asList((long)3l, (long)2l, (long)3l))), (1l)) == (false)); assert(willItFly((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l))), (6l)) == (false)); assert(willItFly((new ArrayList<Long>(Arrays.asList((long)5l))), (5l)) == (true)); } }
humaneval-HumanEval_111_histogram.json-L37
js
//Given a string representing a space separated lowercase letters, return an object // of the letter with the most repetition and containing the corresponding count. // If several letters have the same occurrence, return all of them. // Example: // >>> histogram("a b c") // {"a": 1, "b": 1, "c": 1} // >>> histogram("a b b a") // {"a": 2, "b": 2} // >>> histogram("a b c a b") // {"a": 2, "b": 2} // >>> histogram("b b b b a") // {"b": 4} // >>> histogram("") // {} function histogram(test){ if (test.length === 0){ return {}; } var lst = test.split(" "); var count = {}; for (var i = 0; i < lst.length; i++){ if (count[lst[i]]){ count[lst[i]] += 1; } else{ count[lst[i]] = 1; } } console.log(count); var max = 0; var result = {}; for (var key in count){ if (count[key] > max){ max = count[key]; result = {}; result[key] = max;
else if (count[key] === max){ result[key] = max; } } return result; }
}
const assert = require('node:assert'); function test() { let candidate = histogram; assert.deepEqual(candidate("a b b a"),{"a": 2, "b": 2}); assert.deepEqual(candidate("a b c a b"),{"a": 2, "b": 2}); assert.deepEqual(candidate("a b c d g"),{"a": 1, "b": 1, "c": 1, "d": 1, "g": 1}); assert.deepEqual(candidate("r t g"),{"r": 1, "t": 1, "g": 1}); assert.deepEqual(candidate("b b b b a"),{"b": 4}); assert.deepEqual(candidate("r t g"),{"r": 1, "t": 1, "g": 1}); assert.deepEqual(candidate(""),{}); assert.deepEqual(candidate("a"),{"a": 1}); } test();
humaneval-HumanEval_24_largest_divisor.json-L15
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // For a given number n, find the largest number that divides n evenly, smaller than n // >>> largestDivisor((15l)) // (5l) public static long largestDivisor(long n) { for (long i = 2; i <= Math.floor(Math.sqrt(n)); i++) { if (n % i == 0) {
} } return 1; } }
return n / i;
} public static void main(String[] args) { assert(largestDivisor((3l)) == (1l)); assert(largestDivisor((7l)) == (1l)); assert(largestDivisor((10l)) == (5l)); assert(largestDivisor((100l)) == (50l)); assert(largestDivisor((49l)) == (7l)); } }
humaneval-HumanEval_74_total_match.json-L28
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // 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_156_int_to_mini_roman.json-L56
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Given a positive integer, obtain its roman numeral equivalent as a string, // and return it in lowercase. // Restrictions: 1 <= num <= 1000 // Examples: // >>> intToMiniRoman((19l)) // ("xix") // >>> intToMiniRoman((152l)) // ("clii") // >>> intToMiniRoman((426l)) // ("cdxxvi") public static String intToMiniRoman(long number) { int num = (int) number; String res = ""; if (num == 0) return ""; while (num >= 1000) { res += "m"; num -= 1000; } if (num >= 900) { res += "cm"; num -= 900; } if (num >= 500) { res += "d"; num -= 500; } if (num >= 400) { res += "cd"; num -= 400; } while (num >= 100) { res += "c"; num -= 100; } if (num >= 90) { res += "xc"; num -= 90; } if (num >= 50) { res += "l"; num -= 50; } if (num >= 40) { res += "xl"; num -= 40; }
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; } }
while (num >= 10) {
} public static void main(String[] args) { assert(intToMiniRoman((19l)).equals(("xix"))); assert(intToMiniRoman((152l)).equals(("clii"))); assert(intToMiniRoman((251l)).equals(("ccli"))); assert(intToMiniRoman((426l)).equals(("cdxxvi"))); assert(intToMiniRoman((500l)).equals(("d"))); assert(intToMiniRoman((1l)).equals(("i"))); assert(intToMiniRoman((4l)).equals(("iv"))); assert(intToMiniRoman((43l)).equals(("xliii"))); assert(intToMiniRoman((90l)).equals(("xc"))); assert(intToMiniRoman((94l)).equals(("xciv"))); assert(intToMiniRoman((532l)).equals(("dxxxii"))); assert(intToMiniRoman((900l)).equals(("cm"))); assert(intToMiniRoman((994l)).equals(("cmxciv"))); assert(intToMiniRoman((1000l)).equals(("m"))); } }
humaneval-HumanEval_72_will_it_fly.json-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 { // Write a function that returns true if the object q will fly, and false otherwise. // The object q will fly if it's balanced (it is a palindromic array list) and the sum of its elements is less than or equal the maximum possible weight w. // Example: // >>> willItFly((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l))), (5l)) // (false) // # 1+2 is less than the maximum possible weight, but it's unbalanced. // >>> willItFly((new ArrayList<Long>(Arrays.asList((long)3l, (long)2l, (long)3l))), (1l)) // (false) // # it's balanced, but 3+2+3 is more than the maximum possible weight. // >>> willItFly((new ArrayList<Long>(Arrays.asList((long)3l, (long)2l, (long)3l))), (9l)) // (true) // # 3+2+3 is less than the maximum possible weight, and it's balanced. // >>> willItFly((new ArrayList<Long>(Arrays.asList((long)3l))), (5l)) // (true) // # 3 is less than the maximum possible weight, and it's balanced. public static boolean willItFly(ArrayList<Long> q, long w) { if (q.size() == 0) { return false; } if (q.size() == 1) { return true; } Long sum = 0l; for (int i = 0; i < q.size(); i++) { sum += q.get(i); } if (sum > w) { return false; } for (int i = 0; i < q.size() / 2; i++) { if (q.get(i) != q.get(q.size() - 1 - i)) { return false;
} return true; } }
}
} public static void main(String[] args) { assert(willItFly((new ArrayList<Long>(Arrays.asList((long)3l, (long)2l, (long)3l))), (9l)) == (true)); assert(willItFly((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l))), (5l)) == (false)); assert(willItFly((new ArrayList<Long>(Arrays.asList((long)3l))), (5l)) == (true)); assert(willItFly((new ArrayList<Long>(Arrays.asList((long)3l, (long)2l, (long)3l))), (1l)) == (false)); assert(willItFly((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l))), (6l)) == (false)); assert(willItFly((new ArrayList<Long>(Arrays.asList((long)5l))), (5l)) == (true)); } }
humaneval-HumanEval_129_minPath.json-L36
py
from typing import List def minPath(grid: List[List[int]], k: int) -> List[int]: """ Given a grid with N rows and N columns (N >= 2) and a positive integer k, each cell of the grid contains a value. Every integer in the range [1, N * N] inclusive appears exactly once on the cells of the grid. You have to find the minimum path of length k in the grid. You can start from any cell, and in each step you can move to any of the neighbor cells, in other words, you can go to cells which share an edge with you current cell. Please note that a path of length k means visiting exactly k cells (not necessarily distinct). You CANNOT go off the grid. A path A (of length k) is considered less than a path B (of length k) if after making the ordered lists of the values on the cells that A and B go through (let's call them lst_A and lst_B), lst_A is lexicographically less than lst_B, in other words, there exist an integer index i (1 <= i <= k) such that lst_A[i] < lst_B[i] and for any j (1 <= j < i) we have lst_A[j] = lst_B[j]. It is guaranteed that the answer is unique. Return an ordered list of the values on the cells that the minimum path go through. Examples: >>> minPath([[1, 2, 3], [4, 5, 6], [7, 8, 9]], 3) [1, 2, 1] >>> minPath([[5, 9, 3], [4, 1, 6], [7, 8, 2]], 1) [1] """ min_val = float('inf') for i in range(len(grid)): for j in range(len(grid[0])): if grid[i][j] < min_val:
row = i col = j path = [min_val] while len(path) < k: min_val = float('inf') for i, j in (row - 1, col), (row + 1, col), (row, col - 1), (row, col + 1): if 0 <= i < len(grid) and 0 <= j < len(grid[0]) and grid[i][j] < min_val: min_val = grid[i][j] row = i col = j path.append(min_val) return path
min_val = grid[i][j]
def check(candidate): assert candidate([[1, 2, 3], [4, 5, 6], [7, 8, 9]], 3) == [1, 2, 1] assert candidate([[5, 9, 3], [4, 1, 6], [7, 8, 2]], 1) == [1] assert candidate([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]], 4) == [1, 2, 1, 2] assert candidate([[6, 4, 13, 10], [5, 7, 12, 1], [3, 16, 11, 15], [8, 14, 9, 2]], 7) == [1, 10, 1, 10, 1, 10, 1] assert candidate([[8, 14, 9, 2], [6, 4, 13, 15], [5, 7, 1, 12], [3, 10, 11, 16]], 5) == [1, 7, 1, 7, 1] assert candidate([[11, 8, 7, 2], [5, 16, 14, 4], [9, 3, 15, 6], [12, 13, 10, 1]], 9) == [1, 6, 1, 6, 1, 6, 1, 6, 1] assert candidate([[12, 13, 10, 1], [9, 3, 15, 6], [5, 16, 14, 4], [11, 8, 7, 2]], 12) == [1, 6, 1, 6, 1, 6, 1, 6, 1, 6, 1, 6] assert candidate([[2, 7, 4], [3, 1, 5], [6, 8, 9]], 8) == [1, 3, 1, 3, 1, 3, 1, 3] assert candidate([[6, 1, 5], [3, 8, 9], [2, 7, 4]], 8) == [1, 5, 1, 5, 1, 5, 1, 5] assert candidate([[1, 2], [3, 4]], 10) == [1, 2, 1, 2, 1, 2, 1, 2, 1, 2] assert candidate([[1, 3], [3, 2]], 10) == [1, 3, 1, 3, 1, 3, 1, 3, 1, 3] def test_check(): check(minPath) test_check()
humaneval-HumanEval_71_triangle_area.json-L15
py
def triangle_area(a: int, b: int, c: int) -> float: """ Given the lengths of the three sides of a triangle. Return the area of the triangle rounded to 2 decimal points if the three sides form a valid triangle. Otherwise return -1 Three sides make a valid triangle when the sum of any two sides is greater than the third side. Example: >>> triangle_area(3, 4, 5) 6.0 >>> triangle_area(1, 2, 10) -1 """ if a + b > c and a + c > b and b + c > a:
area = (perimeter * (perimeter - a) * (perimeter - b) * (perimeter - c)) ** 0.5 return round(area, 2) else: return -1
perimeter = (a + b + c) / 2
def check(candidate): assert candidate(3, 4, 5) == 6.0 assert candidate(1, 2, 10) == -1 assert candidate(4, 8, 5) == 8.18 assert candidate(2, 2, 2) == 1.73 assert candidate(1, 2, 3) == -1 assert candidate(10, 5, 7) == 16.25 assert candidate(2, 6, 3) == -1 assert candidate(1, 1, 1) == 0.43 assert candidate(2, 2, 10) == -1 def test_check(): check(triangle_area) test_check()
humaneval-HumanEval_33_sort_third.json-L10
js
//This function takes an array l and returns an array l' such that // l' is identical to l in the indicies that are not divisible by three, while its values at the indicies that are divisible by three are equal // to the values of the corresponding indicies of l, but sorted. // >>> sort_third([1, 2, 3]) // [1, 2, 3] // >>> sort_third([5, 6, 3, 4, 8, 9, 2]) // [2, 6, 3, 4, 8, 9, 5] function sort_third(l){ let x=[];
let k=0; for(let i=0;i<l.length;i++){ if(i%3==0){ y[k]=l[i]; k=k+1; } else{ x[i]=l[i]; } } y.sort(); k=0; for(let i=0;i<l.length;i++){ if(i%3==0){ x[i]=y[k]; k=k+1; } } return x; }
let y=[];
const assert = require('node:assert'); function test() { let candidate = sort_third; assert.deepEqual(candidate([5, 6, 3, 4, 8, 9, 2]),[2, 6, 3, 4, 8, 9, 5]); assert.deepEqual(candidate([5, 8, 3, 4, 6, 9, 2]),[2, 8, 3, 4, 6, 9, 5]); assert.deepEqual(candidate([5, 6, 9, 4, 8, 3, 2]),[2, 6, 9, 4, 8, 3, 5]); assert.deepEqual(candidate([5, 6, 3, 4, 8, 9, 2, 1]),[2, 6, 3, 4, 8, 9, 5, 1]); } test();
humaneval-HumanEval_61_correct_bracketing.json-L31
js
//brackets is a string of "(" and ")". // return true if every opening bracket has a corresponding closing bracket. // >>> correct_bracketing("(") // false // >>> correct_bracketing("()") // true // >>> correct_bracketing("(()())") // true // >>> correct_bracketing(")(()") // false function correct_bracketing(brackets){ var opens = []; for (var i = 0; i < brackets.length; i++){ if (brackets[i] == "("){ opens.push(brackets[i]); } else if (brackets[i] == ")"){ if (opens.length > 0){ opens.pop(); } else { return false; } } } if (opens.length == 0){ return true; } else { return false;
}
}
const assert = require('node:assert'); function test() { let candidate = correct_bracketing; assert.deepEqual(candidate("()"),true); assert.deepEqual(candidate("(()())"),true); assert.deepEqual(candidate("()()(()())()"),true); assert.deepEqual(candidate("()()((()()())())(()()(()))"),true); assert.deepEqual(candidate("((()())))"),false); assert.deepEqual(candidate(")(()"),false); assert.deepEqual(candidate("("),false); assert.deepEqual(candidate("(((("),false); assert.deepEqual(candidate(")"),false); assert.deepEqual(candidate("(()"),false); assert.deepEqual(candidate("()()(()())())(()"),false); assert.deepEqual(candidate("()()(()())()))()"),false); } test();
humaneval-HumanEval_102_choose_num.json-L12
js
//This function takes two positive numbers x and y and returns the // biggest even integer number that is in the range [x, y] inclusive. If // there's no such number, then the function should return -1. // For example: // >>> choose_num(12, 15) // 14 // >>> choose_num(13, 12) // -1 function choose_num(x, y){ var num = -1; for(var i = x; i <= y; i++){
num = i; } } return num; }
if(i % 2 == 0){
const assert = require('node:assert'); function test() { let candidate = choose_num; assert.deepEqual(candidate(12, 15),14); assert.deepEqual(candidate(13, 12),-1); assert.deepEqual(candidate(33, 12354),12354); assert.deepEqual(candidate(5234, 5233),-1); assert.deepEqual(candidate(6, 29),28); assert.deepEqual(candidate(27, 10),-1); assert.deepEqual(candidate(7, 7),-1); assert.deepEqual(candidate(546, 546),546); } test();
humaneval-HumanEval_114_minSubArraySum.json-L26
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Given an array array list of integers nums, find the minimum sum of any non-empty sub-array array list // of nums. // Example // >>> minSubArraySum((new ArrayList<Long>(Arrays.asList((long)2l, (long)3l, (long)4l, (long)1l, (long)2l, (long)4l)))) // (1l) // >>> minSubArraySum((new ArrayList<Long>(Arrays.asList((long)-1l, (long)-2l, (long)-3l)))) // (-6l) public static long minSubArraySum(ArrayList<Long> nums) { long minSum = Long.MAX_VALUE; long prevMinSum = Long.MAX_VALUE; for (int i = 0; i < nums.size(); i++) { long currSum = nums.get(i); if (currSum < prevMinSum) { prevMinSum = currSum; } if (currSum < minSum) { minSum = currSum;
for (int j = i + 1; j < nums.size(); j++) { currSum += nums.get(j); if (currSum < prevMinSum) { prevMinSum = currSum; } if (currSum < minSum) { minSum = currSum; } } } return minSum; } }
}
} public static void main(String[] args) { assert(minSubArraySum((new ArrayList<Long>(Arrays.asList((long)2l, (long)3l, (long)4l, (long)1l, (long)2l, (long)4l)))) == (1l)); assert(minSubArraySum((new ArrayList<Long>(Arrays.asList((long)-1l, (long)-2l, (long)-3l)))) == (-6l)); assert(minSubArraySum((new ArrayList<Long>(Arrays.asList((long)-1l, (long)-2l, (long)-3l, (long)2l, (long)-10l)))) == (-14l)); assert(minSubArraySum((new ArrayList<Long>(Arrays.asList((long)-9999999999999999l)))) == (-9999999999999999l)); assert(minSubArraySum((new ArrayList<Long>(Arrays.asList((long)0l, (long)10l, (long)20l, (long)1000000l)))) == (0l)); assert(minSubArraySum((new ArrayList<Long>(Arrays.asList((long)-1l, (long)-2l, (long)-3l, (long)10l, (long)-5l)))) == (-6l)); assert(minSubArraySum((new ArrayList<Long>(Arrays.asList((long)100l, (long)-1l, (long)-2l, (long)-3l, (long)10l, (long)-5l)))) == (-6l)); assert(minSubArraySum((new ArrayList<Long>(Arrays.asList((long)10l, (long)11l, (long)13l, (long)8l, (long)3l, (long)4l)))) == (3l)); assert(minSubArraySum((new ArrayList<Long>(Arrays.asList((long)100l, (long)-33l, (long)32l, (long)-1l, (long)0l, (long)-2l)))) == (-33l)); assert(minSubArraySum((new ArrayList<Long>(Arrays.asList((long)-10l)))) == (-10l)); assert(minSubArraySum((new ArrayList<Long>(Arrays.asList((long)7l)))) == (7l)); assert(minSubArraySum((new ArrayList<Long>(Arrays.asList((long)1l, (long)-1l)))) == (-1l)); } }
humaneval-HumanEval_86_anti_shuffle.json-L22
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Write a function 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: // >>> antiShuffle(("Hi")) // ("Hi") // >>> antiShuffle(("hello")) // ("ehllo") // >>> antiShuffle(("Hello World!!!")) // ("Hello !!!Wdlor") public static String antiShuffle(String s) {
String[] words = s.split(" "); for (String word : words) { char[] chars = word.toCharArray(); Arrays.sort(chars); sb.append(new String(chars)); sb.append(" "); } sb.deleteCharAt(sb.length() - 1); return sb.toString(); } }
StringBuilder sb = new StringBuilder();
} public static void main(String[] args) { assert(antiShuffle(("Hi")).equals(("Hi"))); assert(antiShuffle(("hello")).equals(("ehllo"))); assert(antiShuffle(("number")).equals(("bemnru"))); assert(antiShuffle(("abcd")).equals(("abcd"))); assert(antiShuffle(("Hello World!!!")).equals(("Hello !!!Wdlor"))); assert(antiShuffle(("")).equals((""))); assert(antiShuffle(("Hi. My name is Mister Robot. How are you?")).equals((".Hi My aemn is Meirst .Rboot How aer ?ouy"))); } }
humaneval-HumanEval_129_minPath.json-L40
py
from typing import List def minPath(grid: List[List[int]], k: int) -> List[int]: """ Given a grid with N rows and N columns (N >= 2) and a positive integer k, each cell of the grid contains a value. Every integer in the range [1, N * N] inclusive appears exactly once on the cells of the grid. You have to find the minimum path of length k in the grid. You can start from any cell, and in each step you can move to any of the neighbor cells, in other words, you can go to cells which share an edge with you current cell. Please note that a path of length k means visiting exactly k cells (not necessarily distinct). You CANNOT go off the grid. A path A (of length k) is considered less than a path B (of length k) if after making the ordered lists of the values on the cells that A and B go through (let's call them lst_A and lst_B), lst_A is lexicographically less than lst_B, in other words, there exist an integer index i (1 <= i <= k) such that lst_A[i] < lst_B[i] and for any j (1 <= j < i) we have lst_A[j] = lst_B[j]. It is guaranteed that the answer is unique. Return an ordered list of the values on the cells that the minimum path go through. Examples: >>> minPath([[1, 2, 3], [4, 5, 6], [7, 8, 9]], 3) [1, 2, 1] >>> minPath([[5, 9, 3], [4, 1, 6], [7, 8, 2]], 1) [1] """ min_val = float('inf') for i in range(len(grid)): for j in range(len(grid[0])): if grid[i][j] < min_val: min_val = grid[i][j] row = i col = j path = [min_val]
min_val = float('inf') for i, j in (row - 1, col), (row + 1, col), (row, col - 1), (row, col + 1): if 0 <= i < len(grid) and 0 <= j < len(grid[0]) and grid[i][j] < min_val: min_val = grid[i][j] row = i col = j path.append(min_val) return path
while len(path) < k:
def check(candidate): assert candidate([[1, 2, 3], [4, 5, 6], [7, 8, 9]], 3) == [1, 2, 1] assert candidate([[5, 9, 3], [4, 1, 6], [7, 8, 2]], 1) == [1] assert candidate([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]], 4) == [1, 2, 1, 2] assert candidate([[6, 4, 13, 10], [5, 7, 12, 1], [3, 16, 11, 15], [8, 14, 9, 2]], 7) == [1, 10, 1, 10, 1, 10, 1] assert candidate([[8, 14, 9, 2], [6, 4, 13, 15], [5, 7, 1, 12], [3, 10, 11, 16]], 5) == [1, 7, 1, 7, 1] assert candidate([[11, 8, 7, 2], [5, 16, 14, 4], [9, 3, 15, 6], [12, 13, 10, 1]], 9) == [1, 6, 1, 6, 1, 6, 1, 6, 1] assert candidate([[12, 13, 10, 1], [9, 3, 15, 6], [5, 16, 14, 4], [11, 8, 7, 2]], 12) == [1, 6, 1, 6, 1, 6, 1, 6, 1, 6, 1, 6] assert candidate([[2, 7, 4], [3, 1, 5], [6, 8, 9]], 8) == [1, 3, 1, 3, 1, 3, 1, 3] assert candidate([[6, 1, 5], [3, 8, 9], [2, 7, 4]], 8) == [1, 5, 1, 5, 1, 5, 1, 5] assert candidate([[1, 2], [3, 4]], 10) == [1, 2, 1, 2, 1, 2, 1, 2, 1, 2] assert candidate([[1, 3], [3, 2]], 10) == [1, 3, 1, 3, 1, 3, 1, 3, 1, 3] def test_check(): check(minPath) test_check()
humaneval-HumanEval_80_is_happy.json-L26
py
def is_happy(s: str) -> bool: """You are given a string s. Your task is to check if the string is happy or not. A string is happy if its length is at least 3 and every 3 consecutive letters are distinct For example: >>> is_happy(a) False >>> is_happy(aa) False >>> is_happy(abcd) True >>> is_happy(aabb) False >>> is_happy(adb) True >>> is_happy(xyy) False """ n = len(s) if n < 3: return False else: for i in range(n - 2): if s[i] == s[i + 1] or s[i] == s[i + 2] or s[i + 1] == s[i + 2]: return False
return True
def check(candidate): assert candidate('a') == False assert candidate('aa') == False assert candidate('abcd') == True assert candidate('aabb') == False assert candidate('adb') == True assert candidate('xyy') == False assert candidate('iopaxpoi') == True assert candidate('iopaxioi') == False def test_check(): check(is_happy) test_check()
humaneval-HumanEval_129_minPath.json-L48
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_46_fib4.json-L25
js
//The Fib4 number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows: // fib4(0) -> 0 // fib4(1) -> 0 // fib4(2) -> 2 // fib4(3) -> 0 // fib4(n) -> fib4(n-1) + fib4(n-2) + fib4(n-3) + fib4(n-4). // Please write a function to efficiently compute the n-th element of the fib4 number sequence. Do not use recursion. // >>> fib4(5) // 4 // >>> fib4(6) // 8 // >>> fib4(7) // 14 function fib4(n){ var prev = [0,0,2,0]; if(n<prev.length){ return prev[n]; } for(var i=4;i<=n;i++){ var curr = prev[0]+prev[1]+prev[2]+prev[3]; prev[0] = prev[1]; prev[1] = prev[2]; prev[2] = prev[3]; prev[3] = curr;
return prev[3]; }
}
const assert = require('node:assert'); function test() { let candidate = fib4; assert.deepEqual(candidate(5),4); assert.deepEqual(candidate(8),28); assert.deepEqual(candidate(10),104); assert.deepEqual(candidate(12),386); } test();
humaneval-HumanEval_137_compare_one.json-L26
js
//Create a function that takes integers, floats, or strings representing // real numbers, and returns the larger variable in its given variable type. // Return undefined if the values are equal. // Note: If a real number is represented as a string, the floating point might be . or , // >>> compare_one(1, 2.5) // 2.5 // >>> compare_one(1, "2,3") // "2,3" // >>> compare_one("5,1", "6") // "6" // >>> compare_one("1", 1) // undefined function compare_one(a, b){ if (typeof a === typeof b){ if (a > b) { return a; } else if (a < b) { return b; } else { return undefined; } } else if (typeof a === "string" && typeof b === "number"){ if (a[0] > b){ return a;
return b; } else { return undefined; } } else if (typeof a === "number" && typeof b === "string"){ if (a > b[0]){ return a; } else if (a < b[0]){ return b; } else { return undefined; } } }
} else if (a[0] < b){
const assert = require('node:assert'); function test() { let candidate = compare_one; assert.deepEqual(candidate(1, 2),2); assert.deepEqual(candidate(1, 2.5),2.5); assert.deepEqual(candidate(2, 3),3); assert.deepEqual(candidate(5, 6),6); assert.deepEqual(candidate(1, "2,3"),"2,3"); assert.deepEqual(candidate("5,1", "6"),"6"); assert.deepEqual(candidate("1", "2"),"2"); assert.deepEqual(candidate("1", 1),undefined); } test();
humaneval-HumanEval_160_do_algebra.json-L32
py
from typing import List def do_algebra(operator: List[str], operand: List[int]) -> int: """ Given two lists operator, and operand. The first list has basic algebra operations, and the second list is a list of integers. Use the two given lists to build the algebric expression and return the evaluation of this expression. The basic algebra operations: Addition ( + ) Subtraction ( - ) Multiplication ( * ) Floor division ( // ) Exponentiation ( ** ) Example: operator['+', '*', '-'] array = [2, 3, 4, 5] result = 2 + 3 * 4 - 5 => result = 9 Note: The length of operator list is equal to the length of operand list minus one. Operand is a list of of non-negative integers. Operator list has at least one operator, and operand list has at least two operands. """ if len(operator) != len(operand) - 1: raise ValueError("Invalid number of operators") expr = [str(operand[0])] for idx, op in enumerate(operator):
expr.append(str(operand[idx + 1])) return eval("".join(expr))
expr.append(op)
def check(candidate): assert candidate(['**', '*', '+'], [2, 3, 4, 5]) == 37 assert candidate(['+', '*', '-'], [2, 3, 4, 5]) == 9 assert candidate(['//', '*'], [7, 3, 4]) == 8 def test_check(): check(do_algebra) test_check()
humaneval-HumanEval_100_make_a_pile.json-L25
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Given 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 array list, where element at index // i represents the number of stones in the level (i+1). // Examples: // >>> makeAPile((3l)) // (new ArrayList<Long>(Arrays.asList((long)3l, (long)5l, (long)7l))) public static ArrayList<Long> makeAPile(long n) { ArrayList<Long> levels = new ArrayList<Long>(); for (long i = 0; i < n; i++) { levels.add(n + 2 * i); } return levels;
}
}
} public static void main(String[] args) { assert(makeAPile((3l)).equals((new ArrayList<Long>(Arrays.asList((long)3l, (long)5l, (long)7l))))); assert(makeAPile((4l)).equals((new ArrayList<Long>(Arrays.asList((long)4l, (long)6l, (long)8l, (long)10l))))); assert(makeAPile((5l)).equals((new ArrayList<Long>(Arrays.asList((long)5l, (long)7l, (long)9l, (long)11l, (long)13l))))); assert(makeAPile((6l)).equals((new ArrayList<Long>(Arrays.asList((long)6l, (long)8l, (long)10l, (long)12l, (long)14l, (long)16l))))); assert(makeAPile((8l)).equals((new ArrayList<Long>(Arrays.asList((long)8l, (long)10l, (long)12l, (long)14l, (long)16l, (long)18l, (long)20l, (long)22l))))); } }
humaneval-HumanEval_41_car_race_collision.json-L20
py
def car_race_collision(n: int) -> int: """ Imagine a road that's a perfectly straight infinitely long line. n cars are driving left to right; simultaneously, a different set of n cars are driving right to left. The two sets of cars start out being very far from each other. All cars move in the same speed. Two cars are said to collide when a car that's moving left to right hits a car that's moving right to left. However, the cars are infinitely sturdy and strong; as a result, they continue moving in their trajectory as if they did not collide. This function outputs the number of such collisions. """ l = n * n count = 0 left_cars = [i for i in range(l)] right_cars = [i for i in range(l)] for i in range(l): for j in range(l): if left_cars[i] == right_cars[j]:
return count
count += 1
def check(candidate): assert candidate(2) == 4 assert candidate(3) == 9 assert candidate(4) == 16 assert candidate(8) == 64 assert candidate(10) == 100 def test_check(): check(car_race_collision) test_check()
humaneval-HumanEval_57_monotonic.json-L26
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // Return 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++) { if (l.get(i) < a) { inc = false; } if (l.get(i) > a) { dec = false;
a = l.get(i); } return inc || dec; } }
}
} 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_63_fibfib.json-L15
py
def fibfib(n: int) -> int: """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(1) 0 >>> fibfib(5) 4 >>> fibfib(8) 24 """
while n > 0: a, b, c = b, c, a + b + c n -= 1 return a
a, b, c = 0, 0, 1
def check(candidate): assert candidate(2) == 1 assert candidate(1) == 0 assert candidate(5) == 4 assert candidate(8) == 24 assert candidate(10) == 81 assert candidate(12) == 274 assert candidate(14) == 927 def test_check(): check(fibfib) test_check()
humaneval-HumanEval_161_solve.json-L24
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // You are given a string s. // if s[i] is a letter, reverse its case from lower to upper or vise versa, // otherwise keep it as it is. // If the string contains no letters, reverse the string. // The function should return the resulted string. // Examples // >>> solve(("1234")) // ("4321") // >>> solve(("ab")) // ("AB") // >>> solve(("#a@C")) // ("#A@c") public static String solve(String s) { boolean letterNotFound = true; StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); i++) { if (Character.isLetter(s.charAt(i))) { letterNotFound = false; if (Character.isUpperCase(s.charAt(i))) { sb.append(Character.toLowerCase(s.charAt(i))); } else { sb.append(Character.toUpperCase(s.charAt(i))); } } else { sb.append(s.charAt(i)); } } if (letterNotFound) { return sb.reverse().toString(); } return sb.toString(); } }
if (s.length() == 0) return s;
} public static void main(String[] args) { assert(solve(("AsDf")).equals(("aSdF"))); assert(solve(("1234")).equals(("4321"))); assert(solve(("ab")).equals(("AB"))); assert(solve(("#a@C")).equals(("#A@c"))); assert(solve(("#AsdfW^45")).equals(("#aSDFw^45"))); assert(solve(("#6@2")).equals(("2@6#"))); assert(solve(("#$a^D")).equals(("#$A^d"))); assert(solve(("#ccc")).equals(("#CCC"))); } }
humaneval-HumanEval_136_largest_smallest_integers.json-L26
py
from typing import List, Tuple, Optional def largest_smallest_integers(lst: List[int]) -> Tuple[Optional[int], Optional[int]]: """ Create a function that returns a tuple (a, b), where 'a' is the largest of negative integers, and 'b' is the smallest of positive integers in a list. If there is no negative or positive integers, return them as None. Examples: >>> largest_smallest_integers([2, 4, 1, 3, 5, 7]) (None, 1) >>> largest_smallest_integers([]) (None, None) >>> largest_smallest_integers([0]) (None, None) """ smallest_positive = None largest_negative = None for num in lst: if num > 0: if smallest_positive is None or num < smallest_positive: smallest_positive = num elif num < 0: if largest_negative is None or num > largest_negative:
return (largest_negative, smallest_positive)
largest_negative = num
def check(candidate): assert candidate([2, 4, 1, 3, 5, 7]) == (None, 1) assert candidate([2, 4, 1, 3, 5, 7, 0]) == (None, 1) assert candidate([1, 3, 2, 4, 5, 6, -2]) == (-2, 1) assert candidate([4, 5, 3, 6, 2, 7, -7]) == (-7, 2) assert candidate([7, 3, 8, 4, 9, 2, 5, -9]) == (-9, 2) assert candidate([]) == (None, None) assert candidate([0]) == (None, None) assert candidate([-1, -3, -5, -6]) == (-1, None) assert candidate([-1, -3, -5, -6, 0]) == (-1, None) assert candidate([-6, -4, -4, -3, 1]) == (-3, 1) assert candidate([-6, -4, -4, -3, -100, 1]) == (-3, 1) def test_check(): check(largest_smallest_integers) test_check()
humaneval-HumanEval_24_largest_divisor.json-L17
java
import java.util.*; import java.lang.reflect.*; import org.javatuples.*; import java.security.*; import java.math.*; import java.io.*; import java.util.stream.*; class Problem { // For a given number n, find the largest number that divides n evenly, smaller than n // >>> largestDivisor((15l)) // (5l) public static long largestDivisor(long n) { for (long i = 2; i <= Math.floor(Math.sqrt(n)); i++) { if (n % i == 0) { return n / i; }
return 1; } }
}
} public static void main(String[] args) { assert(largestDivisor((3l)) == (1l)); assert(largestDivisor((7l)) == (1l)); assert(largestDivisor((10l)) == (5l)); assert(largestDivisor((100l)) == (50l)); assert(largestDivisor((49l)) == (7l)); } }
humaneval-HumanEval_3_below_zero.json-L13
js
//You're given an array of deposit and withdrawal operations on a bank account that starts with // zero balance. Your task is to detect if at any point the balance of account fallls below zero, and // at that point function should return true. Otherwise it should return false. // >>> below_zero([1, 2, 3]) // false // >>> below_zero([1, 2, -4, 5]) // true function below_zero(operations){ var sum = 0; for (var i = 0; i < operations.length; i++) { sum += operations[i]; if (sum < 0) {
} } return false; }
return true;
const assert = require('node:assert'); function test() { let candidate = below_zero; assert.deepEqual(candidate([]),false); assert.deepEqual(candidate([1, 2, -3, 1, 2, -3]),false); assert.deepEqual(candidate([1, 2, -4, 5, 6]),true); assert.deepEqual(candidate([1, -1, 2, -2, 5, -5, 4, -4]),false); assert.deepEqual(candidate([1, -1, 2, -2, 5, -5, 4, -5]),true); assert.deepEqual(candidate([1, -2, 2, -2, 5, -5, 4, -4]),true); } test();