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_72_will_it_fly.json-L32 | java | import java.util.*;
import java.lang.reflect.*;
import org.javatuples.*;
import java.security.*;
import java.math.*;
import java.io.*;
import java.util.stream.*;
class Problem {
// 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; | 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;
}
} | for (int i = 0; i < q.size(); 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_44_change_base.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 {
// Change numerical base of input number x to base.
// return string representation after the conversion.
// base numbers are less than 10.
// >>> changeBase((8l), (3l))
// ("22")
// >>> changeBase((8l), (2l))
// ("1000")
// >>> changeBase((7l), (2l))
// ("111")
public static String changeBase(long x, long base) {
if (x<0 || base<2 || base>9) {
throw new IllegalArgumentException("bad input"); | if (x==0) {
return "0";
}
StringBuilder sb = new StringBuilder();
while (x>0) {
sb.append(x%base);
x = x/base;
}
return sb.reverse().toString();
}
} | } | }
public static void main(String[] args) {
assert(changeBase((8l), (3l)).equals(("22")));
assert(changeBase((9l), (3l)).equals(("100")));
assert(changeBase((234l), (2l)).equals(("11101010")));
assert(changeBase((16l), (2l)).equals(("10000")));
assert(changeBase((8l), (2l)).equals(("1000")));
assert(changeBase((7l), (2l)).equals(("111")));
assert(changeBase((2l), (3l)).equals(("2")));
assert(changeBase((3l), (4l)).equals(("3")));
assert(changeBase((4l), (5l)).equals(("4")));
assert(changeBase((5l), (6l)).equals(("5")));
assert(changeBase((6l), (7l)).equals(("6")));
assert(changeBase((7l), (8l)).equals(("7")));
}
}
|
humaneval-HumanEval_111_histogram.json-L30 | 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 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;
}
| var max = 0; | 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_110_exchange.json-L29 | java | import java.util.*;
import java.lang.reflect.*;
import org.javatuples.*;
import java.security.*;
import java.math.*;
import java.io.*;
import java.util.stream.*;
class Problem {
// In this problem, you will implement a function that takes two array lists of numbers,
// and determines whether it is possible to perform an exchange of elements
// between them to make lst1 an array array list of only even numbers.
// There is no limit on the number of exchanged elements between lst1 and lst2.
// If it is possible to exchange elements between the lst1 and lst2 to make
// all the elements of lst1 to be even, return "YES".
// Otherwise, return "NO".
// For example:
// >>> exchange((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l))), (new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l))))
// ("YES")
// >>> exchange((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l))), (new ArrayList<Long>(Arrays.asList((long)1l, (long)5l, (long)3l, (long)4l))))
// ("NO")
// It is assumed that the input array lists will be non-empty.
public static String exchange(ArrayList<Long> lst1, ArrayList<Long> lst2) {
for (int i = 0; i < lst1.size(); i++) {
if (lst1.get(i) % 2 == 1) {
for (int j = 0; j < lst2.size(); j++) {
if (lst2.get(j) % 2 == 0) {
lst1.set(i, lst2.get(j));
lst2.set(j, (long) 1); | }
}
}
}
return (lst1.stream().allMatch(x -> x % 2 == 0)) ? "YES" : "NO";
}
} | break; | }
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_83_starts_one_ends.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 {
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1.
public static long startsOneEnds(long n) {
long lower = (long) Math.pow(10, n - 1);
long upper = (long) Math.pow(10, n) - 1;
long count = 0;
for (long i = lower; i <= upper; i++) {
String s = "" + i;
if (s.startsWith("1") || s.endsWith("1"))
count++; | return count;
}
} | } | }
public static void main(String[] args) {
assert(startsOneEnds((1l)) == (1l));
assert(startsOneEnds((2l)) == (18l));
assert(startsOneEnds((3l)) == (180l));
assert(startsOneEnds((4l)) == (1800l));
assert(startsOneEnds((5l)) == (18000l));
}
}
|
humaneval-HumanEval_81_numerical_letter_grade.json-L51 | 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){ | }
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("C-"); | 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_101_words_string.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 {
// You will be given a string of words separated by commas or spaces. Your task is
// to split the string into words and return an array array list of the words.
// For example:
// >>> wordsString(("Hi, my name is John"))
// (new ArrayList<String>(Arrays.asList((String)"Hi", (String)"my", (String)"name", (String)"is", (String)"John")))
// >>> wordsString(("One, two, three, four, five, six"))
// (new ArrayList<String>(Arrays.asList((String)"One", (String)"two", (String)"three", (String)"four", (String)"five", (String)"six")))
public static ArrayList<String> wordsString(String s) {
| StringTokenizer st = new StringTokenizer(s, " , ");
while (st.hasMoreTokens()) {
al.add(st.nextToken());
}
return al;
}
} | ArrayList<String> al = new ArrayList<String>(); | }
public static void main(String[] args) {
assert(wordsString(("Hi, my name is John")).equals((new ArrayList<String>(Arrays.asList((String)"Hi", (String)"my", (String)"name", (String)"is", (String)"John")))));
assert(wordsString(("One, two, three, four, five, six")).equals((new ArrayList<String>(Arrays.asList((String)"One", (String)"two", (String)"three", (String)"four", (String)"five", (String)"six")))));
assert(wordsString(("Hi, my name")).equals((new ArrayList<String>(Arrays.asList((String)"Hi", (String)"my", (String)"name")))));
assert(wordsString(("One,, two, three, four, five, six,")).equals((new ArrayList<String>(Arrays.asList((String)"One", (String)"two", (String)"three", (String)"four", (String)"five", (String)"six")))));
assert(wordsString(("")).equals((new ArrayList<String>(Arrays.asList()))));
assert(wordsString(("ahmed , gamal")).equals((new ArrayList<String>(Arrays.asList((String)"ahmed", (String)"gamal")))));
}
}
|
humaneval-HumanEval_108_count_nums.json-L19 | py | from typing import List
def count_nums(arr: List[int]) -> int:
"""
Write a function count_nums which takes an array of integers and returns
the number of elements which has a sum of digits > 0.
If a number is negative, then its first signed digit will be negative:
e.g. -123 has signed digits -1, 2, and 3.
>>> count_nums([])
0
>>> count_nums([-1, 11, -11])
1
>>> count_nums([1, 1, 2])
3
"""
n = 0
for i in arr:
if i < 0: | s = -1 * int(str(i)[0])
for j in str(i)[1:]:
s += int(j)
else:
s = 0
for j in str(i):
s += int(j)
if s > 0:
n += 1
return n
| i = abs(i) | def check(candidate):
assert candidate([]) == 0
assert candidate([-1, -2, 0]) == 0
assert candidate([1, 1, 2, -2, 3, 4, 5]) == 6
assert candidate([1, 6, 9, -6, 0, 1, 5]) == 5
assert candidate([1, 100, 98, -7, 1, -1]) == 4
assert candidate([12, 23, 34, -45, -56, 0]) == 5
assert candidate([0, 1]) == 1
assert candidate([1]) == 1
def test_check():
check(count_nums)
test_check()
|
humaneval-HumanEval_99_closest_integer.json-L19 | py | def closest_integer(value: str) -> int:
"""
Create a function that takes a value (string) representing a number
and returns the closest integer to it. If the number is equidistant
from two integers, round it away from zero.
Examples
>>> closest_integer('10')
10
>>> closest_integer('15.3')
15
Note:
Rounding away from zero means that if the given number is equidistant
from two integers, the one you should return is the one that is the
farthest from zero. For example closest_integer("14.5") should
return 15 and closest_integer("-14.5") should return -15.
"""
| integer_val = int(value)
return integer_val if abs(value - integer_val) < 0.5 else (integer_val + 1) if value > 0 else (integer_val - 1)
| value = float(value) | def check(candidate):
assert candidate('10') == 10
assert candidate('14.5') == 15
assert candidate('-15.5') == -16
assert candidate('15.3') == 15
assert candidate('0') == 0
def test_check():
check(closest_integer)
test_check()
|
humaneval-HumanEval_64_vowels_count.json-L26 | java | import java.util.*;
import java.lang.reflect.*;
import org.javatuples.*;
import java.security.*;
import java.math.*;
import java.io.*;
import java.util.stream.*;
class Problem {
// Write a function 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:
// >>> vowelsCount(("abcde"))
// (2l)
// >>> vowelsCount(("ACEDY"))
// (3l)
public static long vowelsCount(String s) {
long sum = 0;
String sUpper = s.toUpperCase();
int lastIndex = sUpper.length() - 1;
for (int i = 0; i < sUpper.length(); i++) {
if (sUpper.charAt(i) == 'A' || sUpper.charAt(i) == 'E' || sUpper.charAt(i) == 'I' || sUpper.charAt(i) == 'O' || sUpper.charAt(i) == 'U') {
sum++;
} | sum++;
}
}
return sum;
}
} | if (sUpper.charAt(i) == 'Y' && i == lastIndex) { | }
public static void main(String[] args) {
assert(vowelsCount(("abcde")) == (2l));
assert(vowelsCount(("Alone")) == (3l));
assert(vowelsCount(("key")) == (2l));
assert(vowelsCount(("bye")) == (1l));
assert(vowelsCount(("keY")) == (2l));
assert(vowelsCount(("bYe")) == (1l));
assert(vowelsCount(("ACEDY")) == (3l));
}
}
|
humaneval-HumanEval_118_get_closest_vowel.json-L28 | js | //You are given a word. Your task is to find the closest vowel that stands between
// two consonants from the right side of the word (case sensitive).
// Vowels in the beginning and ending doesn't count. Return empty string if you didn't
// find any vowel met the above condition.
// You may assume that the given string contains English letter only.
// Example:
// >>> get_closest_vowel("yogurt")
// "u"
// >>> get_closest_vowel("FULL")
// "U"
// >>> get_closest_vowel("quick")
// ""
// >>> get_closest_vowel("ab")
// ""
function get_closest_vowel(word){
let vowels = ["a", "e", "i", "o", "u"];
let i = word.length - 1;
let result = [];
if (word.length === 1) {
return ""
} else {
while (i >= 0) {
if (vowels.includes(word[i])) {
if (i > 0 && i < word.length - 1) {
if (!vowels.includes(word[i-1]) && !vowels.includes(word[i+1])) {
result.push(word[i]);
} | }
i--;
}
if (result.length === 0) {
return ""
} else {
return result[0];
}
}
} | } | const assert = require('node:assert');
function test() {
let candidate = get_closest_vowel;
assert.deepEqual(candidate("yogurt"),"u");
assert.deepEqual(candidate("full"),"u");
assert.deepEqual(candidate("easy"),"");
assert.deepEqual(candidate("eAsy"),"");
assert.deepEqual(candidate("ali"),"");
assert.deepEqual(candidate("bad"),"a");
assert.deepEqual(candidate("most"),"o");
assert.deepEqual(candidate("ab"),"");
assert.deepEqual(candidate("ba"),"");
assert.deepEqual(candidate("quick"),"");
assert.deepEqual(candidate("anime"),"i");
assert.deepEqual(candidate("Asia"),"");
assert.deepEqual(candidate("Above"),"o");
}
test(); |
humaneval-HumanEval_74_total_match.json-L30 | java | import java.util.*;
import java.lang.reflect.*;
import org.javatuples.*;
import java.security.*;
import java.math.*;
import java.io.*;
import java.util.stream.*;
class Problem {
// 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) { | }
if (sum1 <= sum2) {
return lst1;
} else {
return lst2;
}
}
} | sum2 += s.length(); | }
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_131_digits.json-L17 | js | //Given a positive integer n, return the product of the odd digits.
// Return 0 if all digits are even.
// For example:
// >>> digits(1)
// 1
// >>> digits(4)
// 0
// >>> digits(235)
// 15
function digits(n){
if(!n){
return "error";
}
if(n < 0){
return "error";
} | var prod = 1;
var odd = true;
for(n; n > 0; n = Math.floor(n/10)){
temp = n % 10;
if(temp % 2 != 0){
prod *= temp;
odd = false;
}
}
if(odd){
return 0;
}
return prod;
}
| var temp = 0; | const assert = require('node:assert');
function test() {
let candidate = digits;
assert.deepEqual(candidate(5),5);
assert.deepEqual(candidate(54),5);
assert.deepEqual(candidate(120),1);
assert.deepEqual(candidate(5014),5);
assert.deepEqual(candidate(98765),315);
assert.deepEqual(candidate(5576543),2625);
assert.deepEqual(candidate(2468),0);
}
test(); |
humaneval-HumanEval_46_fib4.json-L18 | 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_147_get_max_triples.json-L29 | py | def get_max_triples(n: int) -> int:
"""
You are given a positive integer n. You have to create an integer array a of length n.
For each i (1 ≤ i ≤ n), the value of a[i] = i * i - i + 1.
Return the number of triples (a[i], a[j], a[k]) of a where i < j < k,
and a[i] + a[j] + a[k] is a multiple of 3.
Example :
>>> get_max_triples(5)
1
Explanation:
a = [1, 3, 7, 13, 21]
The only valid triple is (1, 7, 13).
"""
a = [i * i - i + 1 for i in range(1, n + 1)]
i = 0
j = 1
k = 2
count = 0
while (i < n - 2):
while (j < n - 1):
while (k < n):
if (a[i] + a[j] + a[k]) % 3 == 0:
count += 1
k += 1
j += 1
k = j + 1
i += 1 | k = j + 1
return count
| j = i + 1 | def check(candidate):
assert candidate(5) == 1
assert candidate(6) == 4
assert candidate(10) == 36
assert candidate(100) == 53361
def test_check():
check(get_max_triples)
test_check()
|
humaneval-HumanEval_150_x_or_y.json-L15 | js | //A simple program which should return the value of x if n is
// a prime number and should return the value of y otherwise.
// Examples:
// >>> x_or_y(7, 34, 12)
// 34
// >>> x_or_y(15, 8, 5)
// 5
function x_or_y(n, x, y){
if(n<2){
return y;
}
for(var i=2; i<n; i++){
if(n%i==0){
return y; | }
return x;
} | } | const assert = require('node:assert');
function test() {
let candidate = x_or_y;
assert.deepEqual(candidate(7, 34, 12),34);
assert.deepEqual(candidate(15, 8, 5),5);
assert.deepEqual(candidate(3, 33, 5212),33);
assert.deepEqual(candidate(1259, 3, 52),3);
assert.deepEqual(candidate(7919, -1, 12),-1);
assert.deepEqual(candidate(3609, 1245, 583),583);
assert.deepEqual(candidate(91, 56, 129),129);
assert.deepEqual(candidate(6, 34, 1234),1234);
assert.deepEqual(candidate(1, 2, 0),0);
assert.deepEqual(candidate(2, 2, 0),2);
}
test(); |
humaneval-HumanEval_148_bf.json-L44 | js | //There are eight planets in our solar system: the closerst to the Sun
// is Mercury, the next one is Venus, then Earth, Mars, Jupiter, Saturn,
// Uranus, Neptune.
// Write a function that takes two planet names as strings planet1 and planet2.
// The function should return an array containing all planets whose orbits are
// located between the orbit of planet1 and the orbit of planet2, sorted by
// the proximity to the sun.
// The function should return an empty array if planet1 or planet2
// are not correct planet names.
// Examples
// >>> bf("Jupiter", "Neptune")
// ["Saturn", "Uranus"]
// >>> bf("Earth", "Mercury")
// "Venus"
// >>> bf("Mercury", "Uranus")
// ["Venus", "Earth", "Mars", "Jupiter", "Saturn"]
function bf(planet1, planet2){
var planets = {
'Mercury':1,
'Venus':2,
'Earth':3,
'Mars':4,
'Jupiter':5,
'Saturn':6,
'Uranus':7,
'Neptune':8
}
if(!planets[planet1] || !planets[planet2]){
return [];
}
var keys = Object.keys(planets);
var position1 = keys.indexOf(planet1);
var position2 = keys.indexOf(planet2);
if(position1 > position2){
var temp = position1;
position1 = position2;
position2 = temp;
}
var res = [];
for(var i = position1 + 1; i < position2; i++){
res.push(keys[i]);
}
return res; | } | const assert = require('node:assert');
function test() {
let candidate = bf;
assert.deepEqual(candidate("Jupiter", "Neptune"),["Saturn", "Uranus"]);
assert.deepEqual(candidate("Earth", "Mercury"),["Venus"]);
assert.deepEqual(candidate("Mercury", "Uranus"),["Venus", "Earth", "Mars", "Jupiter", "Saturn"]);
assert.deepEqual(candidate("Neptune", "Venus"),["Earth", "Mars", "Jupiter", "Saturn", "Uranus"]);
assert.deepEqual(candidate("Earth", "Earth"),[]);
assert.deepEqual(candidate("Mars", "Earth"),[]);
assert.deepEqual(candidate("Jupiter", "Makemake"),[]);
}
test(); |
|
humaneval-HumanEval_102_choose_num.json-L12 | py | def choose_num(x: int, y: int) -> int:
"""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
"""
| even_numbers = list(filter(lambda num: num % 2 == 0, numbers))
return max(even_numbers) if even_numbers else -1
| numbers = list(range(x, y + 1)) | def check(candidate):
assert candidate(12, 15) == 14
assert candidate(13, 12) == -1
assert candidate(33, 12354) == 12354
assert candidate(5234, 5233) == -1
assert candidate(6, 29) == 28
assert candidate(27, 10) == -1
assert candidate(7, 7) == -1
assert candidate(546, 546) == 546
def test_check():
check(choose_num)
test_check()
|
humaneval-HumanEval_142_sum_squares.json-L22 | py | from typing import List
def sum_squares(lst: List[int]) -> int:
""""
This function will take a list of integers. For all entries in the list, the function shall square the integer entry if its index is a
multiple of 3 and will cube the integer entry if its index is a multiple of 4 and not a multiple of 3. The function will not
change the entries in the list whose indexes are not a multiple of 3 or 4. The function shall then return the sum of all entries.
Examples:
>>> lst
[1, 2, 3]
>>> lst
[]
>>> lst
[-1, -5, 2, -1, -5]
"""
for index in range(len(lst)):
if index % 3 == 0:
lst[index] = lst[index] ** 2
elif index % 4 == 0:
lst[index] = lst[index] ** 3 | return sum(lst) | def check(candidate):
assert candidate([1, 2, 3]) == 6
assert candidate([1, 4, 9]) == 14
assert candidate([]) == 0
assert candidate([1, 1, 1, 1, 1, 1, 1, 1, 1]) == 9
assert candidate([-1, -1, -1, -1, -1, -1, -1, -1, -1]) == -3
assert candidate([0]) == 0
assert candidate([-1, -5, 2, -1, -5]) == -126
assert candidate([-56, -99, 1, 0, -2]) == 3030
assert candidate([-1, 0, 0, 0, 0, 0, 0, 0, -1]) == 0
assert candidate([-16, -9, -2, 36, 36, 26, -20, 25, -40, 20, -4, 12, -26, 35, 37]) == -14196
assert candidate([-1, -3, 17, -1, -15, 13, -1, 14, -14, -12, -5, 14, -14, 6, 13, 11, 16, 16, 4, 10]) == -1448
def test_check():
check(sum_squares)
test_check()
|
|
humaneval-HumanEval_111_histogram.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 {
// Given a string representing a space separated lowercase letters, return a hash map
// of the letter with the most repetition and containing the corresponding count.
// If several letters have the same occurrence, return all of them.
// Example:
// >>> histogram(("a b c"))
// (new HashMap<String,Long>(Map.of("a", 1l, "b", 1l, "c", 1l)))
// >>> histogram(("a b b a"))
// (new HashMap<String,Long>(Map.of("a", 2l, "b", 2l)))
// >>> histogram(("a b c a b"))
// (new HashMap<String,Long>(Map.of("a", 2l, "b", 2l)))
// >>> histogram(("b b b b a"))
// (new HashMap<String,Long>(Map.of("b", 4l)))
// >>> histogram((""))
// (new HashMap<String,Long>())
public static HashMap<String,Long> histogram(String test) {
HashMap<String,Long> s = new HashMap<String,Long>();
if (test.length() > 0) {
HashMap<String,Long> hm = new HashMap<String,Long>();
String[] ss = test.split(" ");
for (String sss : ss) {
if (hm.containsKey(sss)) {
hm.put(sss, hm.get(sss) + 1);
} else {
hm.put(sss, 1l);
}
}
long max = 0;
for (String key : hm.keySet()) {
if (hm.get(key) > max) {
max = hm.get(key); | }
for (String key : hm.keySet()) {
if (hm.get(key) == max) {
s.put(key, hm.get(key));
}
}
}
return s;
}
} | } | }
public static void main(String[] args) {
assert(histogram(("a b b a")).equals((new HashMap<String,Long>(Map.of("a", 2l, "b", 2l)))));
assert(histogram(("a b c a b")).equals((new HashMap<String,Long>(Map.of("a", 2l, "b", 2l)))));
assert(histogram(("a b c d g")).equals((new HashMap<String,Long>(Map.of("a", 1l, "b", 1l, "c", 1l, "d", 1l, "g", 1l)))));
assert(histogram(("r t g")).equals((new HashMap<String,Long>(Map.of("r", 1l, "t", 1l, "g", 1l)))));
assert(histogram(("b b b b a")).equals((new HashMap<String,Long>(Map.of("b", 4l)))));
assert(histogram(("r t g")).equals((new HashMap<String,Long>(Map.of("r", 1l, "t", 1l, "g", 1l)))));
assert(histogram(("")).equals((new HashMap<String,Long>())));
assert(histogram(("a")).equals((new HashMap<String,Long>(Map.of("a", 1l)))));
}
}
|
humaneval-HumanEval_147_get_max_triples.json-L14 | js | //You are given a positive integer n. You have to create an integer array a of length n.
// For each i (1 ≤ i ≤ n), the value of a[i] = i * i - i + 1.
// Return the number of triples (a[i], a[j], a[k]) of a where i < j < k,
// and a[i] + a[j] + a[k] is a multiple of 3.
// Example :
// >>> get_max_triples(5)
// 1
// Explanation:
// a = [1, 3, 7, 13, 21]
// The only valid triple is (1, 7, 13).
function get_max_triples(n){
let result = 0;
let arr = []; | arr.push(i*i-i+1);
}
for(let i = 0; i<arr.length; i++){
for(let j = i+1; j<arr.length; j++){
for(let k = j+1; k<arr.length; k++){
if((arr[i]+arr[j]+arr[k])%3 === 0){
result++;
}
}
}
}
return result;
}
| for(let i = 1; i<=n; i++){ | const assert = require('node:assert');
function test() {
let candidate = get_max_triples;
assert.deepEqual(candidate(5),1);
assert.deepEqual(candidate(6),4);
assert.deepEqual(candidate(10),36);
assert.deepEqual(candidate(100),53361);
}
test(); |
humaneval-HumanEval_96_count_up_to.json-L25 | js | //Implement a function that takes an non-negative integer and returns an array of the first n
// integers that are prime numbers and less than n.
// for example:
// >>> count_up_to(5)
// [2, 3]
// >>> count_up_to(11)
// [2, 3, 5, 7]
// >>> count_up_to(0)
// []
// >>> count_up_to(20)
// [2, 3, 5, 7, 11, 13, 17, 19]
// >>> count_up_to(1)
// []
// >>> count_up_to(18)
// [2, 3, 5, 7, 11, 13, 17]
function count_up_to(n){
if (n < 2) return [];
var output = [2];
for (var i = 3; i < n; i += 2){
var prime = true;
for (var j = 3; j < i; j += 2){
if (i % j === 0){
prime = false;
break; | }
if (prime) output.push(i);
}
return output;
}
| } | const assert = require('node:assert');
function test() {
let candidate = count_up_to;
assert.deepEqual(candidate(5),[2, 3]);
assert.deepEqual(candidate(6),[2, 3, 5]);
assert.deepEqual(candidate(7),[2, 3, 5]);
assert.deepEqual(candidate(10),[2, 3, 5, 7]);
assert.deepEqual(candidate(0),[]);
assert.deepEqual(candidate(22),[2, 3, 5, 7, 11, 13, 17, 19]);
assert.deepEqual(candidate(1),[]);
assert.deepEqual(candidate(18),[2, 3, 5, 7, 11, 13, 17]);
assert.deepEqual(candidate(47),[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43]);
assert.deepEqual(candidate(101),[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]);
}
test(); |
humaneval-HumanEval_128_prod_signs.json-L21 | py | from typing import List, Optional
def prod_signs(arr: List[int]) -> Optional[int]:
"""
You are given an array arr of integers and you need to return
sum of magnitudes of integers multiplied by product of all signs
of each number in the array, represented by 1, -1 or 0.
Note: return None for empty arr.
Example:
>>> prod_signs([1, 2, 2, -4])
9
>>> prod_signs([0, 1])
0
>>> prod_signs([])
None
"""
def product(lst: List[int]) -> int:
out = 1
for item in lst: | return out
if len(arr) == 0:
return None
else:
sign_arr = []
for num in arr:
if num > 0:
sign_arr.append(1)
elif num < 0:
sign_arr.append(-1)
else:
sign_arr.append(0)
return sum(map(abs, arr)) * product(sign_arr) | out *= item | def check(candidate):
assert candidate([1, 2, 2, -4]) == -9
assert candidate([0, 1]) == 0
assert candidate([1, 1, 1, 2, 3, -1, 1]) == -10
assert candidate([]) == None
assert candidate([2, 4, 1, 2, -1, -1, 9]) == 20
assert candidate([-1, 1, -1, 1]) == 4
assert candidate([-1, 1, 1, 1]) == -4
assert candidate([-1, 1, 1, 0]) == 0
def test_check():
check(prod_signs)
test_check()
|
humaneval-HumanEval_51_remove_vowels.json-L30 | java | import java.util.*;
import java.lang.reflect.*;
import org.javatuples.*;
import java.security.*;
import java.math.*;
import java.io.*;
import java.util.stream.*;
class Problem {
// remove_vowels is a function that takes string and returns string without vowels.
// >>> removeVowels((""))
// ("")
// >>> removeVowels(("abcdef"))
// ("bcdf")
// >>> removeVowels(("aaaaa"))
// ("")
// >>> removeVowels(("aaBAA"))
// ("B")
// >>> removeVowels(("zbcd"))
// ("zbcd")
public static String removeVowels(String text) {
String vowels = "aeiouAEIOU";
String newText = "";
for (int i = 0; i < text.length(); i++) {
if (vowels.indexOf(text.charAt(i)) == -1) {
newText += text.charAt(i);
}
}
return newText;
} | } | }
public static void main(String[] args) {
assert(removeVowels(("")).equals(("")));
assert(removeVowels(("abcdef\nghijklm")).equals(("bcdf\nghjklm")));
assert(removeVowels(("fedcba")).equals(("fdcb")));
assert(removeVowels(("eeeee")).equals(("")));
assert(removeVowels(("acBAA")).equals(("cB")));
assert(removeVowels(("EcBOO")).equals(("cB")));
assert(removeVowels(("ybcd")).equals(("ybcd")));
}
}
|
|
humaneval-HumanEval_143_words_in_sentence.json-L33 | java | import java.util.*;
import java.lang.reflect.*;
import org.javatuples.*;
import java.security.*;
import java.math.*;
import java.io.*;
import java.util.stream.*;
class Problem {
// 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:
// >>> wordsInSentence(("This is a test"))
// ("is")
// Example 2:
// >>> wordsInSentence(("lets go for swimming"))
// ("go for")
// Constraints:
// * 1 <= len(sentence) <= 100
// * sentence contains only letters
public static String wordsInSentence(String sentence) {
StringBuilder ans = new StringBuilder();
String[] words = sentence.split(" ");
int[] primes = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97};
boolean isPrime;
for (String word : words) {
isPrime = false;
for (int prime : primes) {
if (word.length() == prime) {
isPrime = true; | }
}
if (isPrime) {
ans.append(word + " ");
}
}
if (ans.length() > 0) {
ans.deleteCharAt(ans.length() - 1);
}
return ans.toString();
}
} | break; | }
public static void main(String[] args) {
assert(wordsInSentence(("This is a test")).equals(("is")));
assert(wordsInSentence(("lets go for swimming")).equals(("go for")));
assert(wordsInSentence(("there is no place available here")).equals(("there is no place")));
assert(wordsInSentence(("Hi I am Hussein")).equals(("Hi am Hussein")));
assert(wordsInSentence(("go for it")).equals(("go for it")));
assert(wordsInSentence(("here")).equals(("")));
assert(wordsInSentence(("here is")).equals(("is")));
}
}
|
humaneval-HumanEval_44_change_base.json-L13 | js | //Change numerical base of input number x to base.
// return string representation after the conversion.
// base numbers are less than 10.
// >>> change_base(8, 3)
// "22"
// >>> change_base(8, 2)
// "1000"
// >>> change_base(7, 2)
// "111"
function change_base(x, base){
let r = x % base;
let q = Math.floor(x / base); | return change_base(q, base) + r.toString();
}
| if (q === 0) return r.toString(); | const assert = require('node:assert');
function test() {
let candidate = change_base;
assert.deepEqual(candidate(8, 3),"22");
assert.deepEqual(candidate(9, 3),"100");
assert.deepEqual(candidate(234, 2),"11101010");
assert.deepEqual(candidate(16, 2),"10000");
assert.deepEqual(candidate(8, 2),"1000");
assert.deepEqual(candidate(7, 2),"111");
assert.deepEqual(candidate(2, 3),"2");
assert.deepEqual(candidate(3, 4),"3");
assert.deepEqual(candidate(4, 5),"4");
assert.deepEqual(candidate(5, 6),"5");
assert.deepEqual(candidate(6, 7),"6");
assert.deepEqual(candidate(7, 8),"7");
}
test(); |
humaneval-HumanEval_120_maximum.json-L29 | py | from typing import List
def maximum(arr: List[int], k: int) -> List[int]:
"""
Given an array arr of integers and a positive integer k, return a sorted list
of length k with the maximum k numbers in arr.
Example 1:
>>> maximum([-3, -4, 5], 3)
[-4, -3, 5]
Example 2:
>>> maximum([4, -4, 4], 2)
[4, 4]
Example 3:
>>> maximum([-3, 2, 1, 2, -1, -2, 1], 1)
[2]
Note:
1. The length of the array will be in the range of [1, 1000].
2. The elements in the array will be in the range of [-1000, 1000].
3. 0 <= k <= len(arr)
"""
def get_max(arr: List[int], k: int) -> List[int]: | Returns the maximum k numbers in the given array
"""
if k == 0:
return []
elif k == 1:
return [max(arr)]
else:
max_num = max(arr)
arr.remove(max_num)
return [max_num] + get_max(arr, k - 1)
return sorted(get_max(arr, k))
| """ | def check(candidate):
assert candidate([-3, -4, 5], 3) == [-4, -3, 5]
assert candidate([4, -4, 4], 2) == [4, 4]
assert candidate([-3, 2, 1, 2, -1, -2, 1], 1) == [2]
assert candidate([123, -123, 20, 0, 1, 2, -3], 3) == [2, 20, 123]
assert candidate([-123, 20, 0, 1, 2, -3], 4) == [0, 1, 2, 20]
assert candidate([5, 15, 0, 3, -13, -8, 0], 7) == [-13, -8, 0, 0, 3, 5, 15]
assert candidate([-1, 0, 2, 5, 3, -10], 2) == [3, 5]
assert candidate([1, 0, 5, -7], 1) == [5]
assert candidate([4, -4], 2) == [-4, 4]
assert candidate([-10, 10], 2) == [-10, 10]
assert candidate([1, 2, 3, -23, 243, -400, 0], 0) == []
def test_check():
check(maximum)
test_check()
|
humaneval-HumanEval_17_parse_music.json-L33 | java | import java.util.*;
import java.lang.reflect.*;
import org.javatuples.*;
import java.security.*;
import java.math.*;
import java.io.*;
import java.util.stream.*;
class Problem {
// Input to this function is a string representing musical notes in a special ASCII format.
// Your task is to parse this string and return array list of integers corresponding to how many beats does each
// not last.
// Here is a legend:
// 'o' - whole note, lasts four beats
// 'o|' - half note, lasts two beats
// '.|' - quater note, lasts one beat
// >>> parseMusic(("o o| .| o| o| .| .| .| .| o o"))
// (new ArrayList<Long>(Arrays.asList((long)4l, (long)2l, (long)1l, (long)2l, (long)2l, (long)1l, (long)1l, (long)1l, (long)1l, (long)4l, (long)4l)))
public static ArrayList<Long> parseMusic(String music_string) {
ArrayList<Long> res = new ArrayList<Long>();
char[] chars = music_string.toCharArray();
for (int i = 0; i < chars.length; i++) {
if (chars[i] == 'o') {
if (i + 1 < chars.length && chars[i + 1] == '|') {
res.add((long)2l);
i += 1;
} else {
res.add((long)4l);
}
} else if (chars[i] == '.') {
if (i + 1 < chars.length && chars[i + 1] == '|') {
res.add((long)1l);
i += 1; | }
}
return res;
}
} | } | }
public static void main(String[] args) {
assert(parseMusic(("")).equals((new ArrayList<Long>(Arrays.asList()))));
assert(parseMusic(("o o o o")).equals((new ArrayList<Long>(Arrays.asList((long)4l, (long)4l, (long)4l, (long)4l)))));
assert(parseMusic((".| .| .| .|")).equals((new ArrayList<Long>(Arrays.asList((long)1l, (long)1l, (long)1l, (long)1l)))));
assert(parseMusic(("o| o| .| .| o o o o")).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)2l, (long)1l, (long)1l, (long)4l, (long)4l, (long)4l, (long)4l)))));
assert(parseMusic(("o| .| o| .| o o| o o|")).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)1l, (long)2l, (long)1l, (long)4l, (long)2l, (long)4l, (long)2l)))));
}
}
|
humaneval-HumanEval_137_compare_one.json-L22 | 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]){
return b;
} else {
return undefined;
}
}
}
| } | 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_109_move_one_ball.json-L38 | py | from typing import List
def move_one_ball(arr: List[int]) -> bool:
"""We have an array 'arr' of N integers arr[1], arr[2], ..., arr[N].The
numbers in the array will be randomly ordered. Your task is to determine if
it is possible to get an array sorted in non-decreasing order by performing
the following operation on the given array:
You are allowed to perform right shift operation any number of times.
One right shift operation means shifting all elements of the array by one
position in the right direction. The last element of the array will be moved to
the starting position in the array i.e. 0th index.
If it is possible to obtain the sorted array by performing the above operation
then return True else return False.
If the given array is empty then return True.
Note: The given list is guaranteed to have unique elements.
For Example:
>>> move_one_ball([3, 4, 5, 1, 2])
True
Explanation: By performin 2 right shift operations, non-decreasing order can
be achieved for the given array.
>>> move_one_ball([3, 5, 4, 1, 2])
False
Explanation:It is not possible to get non-decreasing order for the given
array by performing any number of right shift operations.
"""
flag = False
for i in range(1, len(arr)):
if arr[i-1] > arr[i]:
if flag == True:
return False
flag = True | flag = False
return True
| elif arr[i-1] < arr[i]: | def check(candidate):
assert candidate([3, 4, 5, 1, 2]) == True
assert candidate([3, 5, 10, 1, 2]) == True
assert candidate([4, 3, 1, 2]) == False
assert candidate([3, 5, 4, 1, 2]) == False
assert candidate([]) == True
def test_check():
check(move_one_ball)
test_check()
|
humaneval-HumanEval_33_sort_third.json-L16 | js | //This function takes an array l and returns an array l' such that
// l' is identical to l in the indicies that are not divisible by three, while its values at the indicies that are divisible by three are equal
// to the values of the corresponding indicies of l, but sorted.
// >>> sort_third([1, 2, 3])
// [1, 2, 3]
// >>> sort_third([5, 6, 3, 4, 8, 9, 2])
// [2, 6, 3, 4, 8, 9, 5]
function sort_third(l){
let x=[];
let y=[];
let k=0;
for(let i=0;i<l.length;i++){
if(i%3==0){
y[k]=l[i];
k=k+1; | else{
x[i]=l[i];
}
}
y.sort();
k=0;
for(let i=0;i<l.length;i++){
if(i%3==0){
x[i]=y[k];
k=k+1;
}
}
return x;
} | } | 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_39_prime_fib.json-L17 | js | //prime_fib returns n-th number that is a Fibonacci number and it's also prime.
// >>> prime_fib(1)
// 2
// >>> prime_fib(2)
// 3
// >>> prime_fib(3)
// 5
// >>> prime_fib(4)
// 13
// >>> prime_fib(5)
// 89
function prime_fib(n){
function isPrime(number){
if(number <= 3){
return number > 1;
} | return false;
}
else{
for(var i = 5; i * i <= number; i += 6){
if(number % i == 0 || number % (i + 2) == 0){
return false;
}
}
return true;
}
}
function fib(num){
var a = 1, b = 0, temp;
while (num >= 0){
temp = a;
a = a + b;
b = temp;
num--;
}
return b;
}
var res = 0;
var fibNum = 0;
while(res < n){
if(isPrime(fib(fibNum))){
res++;
}
fibNum++;
}
return fib(fibNum - 1);
} | else if(number % 2 == 0 || number % 3 == 0){ | const assert = require('node:assert');
function test() {
let candidate = prime_fib;
assert.deepEqual(candidate(1),2);
assert.deepEqual(candidate(2),3);
assert.deepEqual(candidate(3),5);
assert.deepEqual(candidate(4),13);
assert.deepEqual(candidate(5),89);
assert.deepEqual(candidate(6),233);
assert.deepEqual(candidate(7),1597);
assert.deepEqual(candidate(8),28657);
assert.deepEqual(candidate(9),514229);
assert.deepEqual(candidate(10),433494437);
}
test(); |
humaneval-HumanEval_160_do_algebra.json-L24 | js | //Given two arrays operator, and operand. The first array has basic algebra operations, and
// the second array is an array of integers. Use the two given arrays to build the algebric
// expression and return the evaluation of this expression.
// The basic algebra operations:
// Addition ( + )
// Subtraction ( - )
// Multiplication ( * )
// Floor division ( // )
// Exponentiation ( ** )
// Example:
// operator['+', '*', '-']
// array = [2, 3, 4, 5]
// result = 2 + 3 * 4 - 5
// => result = 9
// Note:
// The length of operator array is equal to the length of operand array minus one.
// Operand is an array of of non-negative integers.
// Operator array has at least one operator, and operand array has at least two operands.
function do_algebra(operator, operand){
let do_again;
let count = 0;
let temp;
let answer; | switch(operator[count]){
case '*':
operand[count] = operand[count] * operand[count + 1];
operand.splice(count + 1, 1);
operator.splice(count, 1);
count = 0;
do_again = true;
break;
case '//':
operand[count] = Math.floor(operand[count] / operand[count + 1]);
operand.splice(count + 1, 1);
operator.splice(count, 1);
count = 0;
do_again = true;
break;
case '**':
operand[count] = Math.pow(operand[count], operand[count + 1]);
operand.splice(count + 1, 1);
operator.splice(count, 1);
count = 0;
do_again = true;
break;
default:
count++;
do_again = false;
}
}
answer = operand[0];
operand.splice(0, 1);
while(operand.length > 0){
switch(operator[0]){
case '+':
answer += operand[0];
break;
case '-':
answer -= operand[0];
break;
}
operand.splice(0, 1);
operator.splice(0, 1);
}
return answer;
}
| while(count < operator.length){ | const assert = require('node:assert');
function test() {
let candidate = do_algebra;
assert.deepEqual(candidate(["**", "*", "+"], [2, 3, 4, 5]),37);
assert.deepEqual(candidate(["+", "*", "-"], [2, 3, 4, 5]),9);
assert.deepEqual(candidate(["//", "*"], [7, 3, 4]),8);
}
test(); |
humaneval-HumanEval_148_bf.json-L30 | java | import java.util.*;
import java.lang.reflect.*;
import org.javatuples.*;
import java.security.*;
import java.math.*;
import java.io.*;
import java.util.stream.*;
class Problem {
// There are eight planets in our solar system: the closerst to the Sun
// is Mercury, the next one is Venus, then Earth, Mars, Jupiter, Saturn,
// Uranus, Neptune.
// Write a function that takes two planet names as strings planet1 and planet2.
// The function should return a pair containing all planets whose orbits are
// located between the orbit of planet1 and the orbit of planet2, sorted by
// the proximity to the sun.
// The function should return an empty pair if planet1 or planet2
// are not correct planet names.
// Examples
// >>> bf(("Jupiter"), ("Neptune"))
// (new ArrayList<String>(Arrays.asList((String)"Saturn", (String)"Uranus")))
// >>> bf(("Earth"), ("Mercury"))
// (ArrayList<String>("Venus"))
// >>> bf(("Mercury"), ("Uranus"))
// (new ArrayList<String>(Arrays.asList((String)"Venus", (String)"Earth", (String)"Mars", (String)"Jupiter", (String)"Saturn")))
public static ArrayList<String> bf(String planet1, String planet2) {
ArrayList<String> planets = new ArrayList<String>(Arrays.asList((String)"Mercury", (String)"Venus", (String)"Earth", (String)"Mars", (String)"Jupiter", (String)"Saturn", (String)"Uranus", (String)"Neptune"));
int indexPlanet1 = planets.indexOf(planet1);
int indexPlanet2 = planets.indexOf(planet2);
int indexMin = 0; | if (indexPlanet1 >= 0 && indexPlanet2 >= 0) {
if (indexPlanet1 < indexPlanet2) {
indexMin = indexPlanet1;
indexMax = indexPlanet2;
} else {
indexMin = indexPlanet2;
indexMax = indexPlanet1;
}
ArrayList<String> planetsInBetween = new ArrayList<String>();
for (int i = indexMin + 1; i < indexMax; i++) {
planetsInBetween.add(planets.get(i));
}
return planetsInBetween;
} else {
return new ArrayList<String>();
}
}
} | int indexMax = 0; | }
public static void main(String[] args) {
assert(bf(("Jupiter"), ("Neptune")).equals((new ArrayList<String>(Arrays.asList((String)"Saturn", (String)"Uranus")))));
assert(bf(("Earth"), ("Mercury")).equals((new ArrayList<String>(Arrays.asList((String)"Venus")))));
assert(bf(("Mercury"), ("Uranus")).equals((new ArrayList<String>(Arrays.asList((String)"Venus", (String)"Earth", (String)"Mars", (String)"Jupiter", (String)"Saturn")))));
assert(bf(("Neptune"), ("Venus")).equals((new ArrayList<String>(Arrays.asList((String)"Earth", (String)"Mars", (String)"Jupiter", (String)"Saturn", (String)"Uranus")))));
assert(bf(("Earth"), ("Earth")).equals((new ArrayList<String>(Arrays.asList()))));
assert(bf(("Mars"), ("Earth")).equals((new ArrayList<String>(Arrays.asList()))));
assert(bf(("Jupiter"), ("Makemake")).equals((new ArrayList<String>(Arrays.asList()))));
}
}
|
humaneval-HumanEval_143_words_in_sentence.json-L24 | py | def words_in_sentence(sentence: str) -> str:
"""
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
"""
def is_prime(n: int) -> bool:
if n <= 1:
return False | if n % i == 0:
return False
return True
words = sentence.split()
prime_words = []
for word in words:
if is_prime(len(word)):
prime_words.append(word)
return ' '.join(prime_words) | for i in range(2, n): | def check(candidate):
assert candidate('This is a test') == 'is'
assert candidate('lets go for swimming') == 'go for'
assert candidate('there is no place available here') == 'there is no place'
assert candidate('Hi I am Hussein') == 'Hi am Hussein'
assert candidate('go for it') == 'go for it'
assert candidate('here') == ''
assert candidate('here is') == 'is'
def test_check():
check(words_in_sentence)
test_check()
|
humaneval-HumanEval_27_flip_case.json-L11 | py | def flip_case(string: str) -> str:
""" For a given string, flip lowercase characters to uppercase and uppercase to lowercase.
>>> flip_case('Hello')
'hELLO'
"""
new_string = ""
for character in string:
if character.isupper():
new_string += character.lower()
else: | return new_string
| new_string += character.upper() | def check(candidate):
assert candidate('') == ''
assert candidate('Hello!') == 'hELLO!'
assert candidate('These violent delights have violent ends') == 'tHESE VIOLENT DELIGHTS HAVE VIOLENT ENDS'
def test_check():
check(flip_case)
test_check()
|
humaneval-HumanEval_138_is_equal_to_sum_even.json-L13 | py | def is_equal_to_sum_even(n: int) -> bool:
"""Evaluate whether the given number n can be written as the sum of exactly 4 positive even numbers
Example
>>> is_equal_to_sum_even(4)
False
>>> is_equal_to_sum_even(6)
False
>>> is_equal_to_sum_even(8)
True
"""
if n < 8:
return False | return n % 2 == 0 | def check(candidate):
assert candidate(4) == False
assert candidate(6) == False
assert candidate(8) == True
assert candidate(10) == True
assert candidate(11) == False
assert candidate(12) == True
assert candidate(13) == False
assert candidate(16) == True
def test_check():
check(is_equal_to_sum_even)
test_check()
|
|
humaneval-HumanEval_160_do_algebra.json-L20 | js | //Given two arrays operator, and operand. The first array has basic algebra operations, and
// the second array is an array of integers. Use the two given arrays to build the algebric
// expression and return the evaluation of this expression.
// The basic algebra operations:
// Addition ( + )
// Subtraction ( - )
// Multiplication ( * )
// Floor division ( // )
// Exponentiation ( ** )
// Example:
// operator['+', '*', '-']
// array = [2, 3, 4, 5]
// result = 2 + 3 * 4 - 5
// => result = 9
// Note:
// The length of operator array is equal to the length of operand array minus one.
// Operand is an array of of non-negative integers.
// Operator array has at least one operator, and operand array has at least two operands.
function do_algebra(operator, operand){
| let count = 0;
let temp;
let answer;
while(count < operator.length){
switch(operator[count]){
case '*':
operand[count] = operand[count] * operand[count + 1];
operand.splice(count + 1, 1);
operator.splice(count, 1);
count = 0;
do_again = true;
break;
case '//':
operand[count] = Math.floor(operand[count] / operand[count + 1]);
operand.splice(count + 1, 1);
operator.splice(count, 1);
count = 0;
do_again = true;
break;
case '**':
operand[count] = Math.pow(operand[count], operand[count + 1]);
operand.splice(count + 1, 1);
operator.splice(count, 1);
count = 0;
do_again = true;
break;
default:
count++;
do_again = false;
}
}
answer = operand[0];
operand.splice(0, 1);
while(operand.length > 0){
switch(operator[0]){
case '+':
answer += operand[0];
break;
case '-':
answer -= operand[0];
break;
}
operand.splice(0, 1);
operator.splice(0, 1);
}
return answer;
}
| let do_again; | const assert = require('node:assert');
function test() {
let candidate = do_algebra;
assert.deepEqual(candidate(["**", "*", "+"], [2, 3, 4, 5]),37);
assert.deepEqual(candidate(["+", "*", "-"], [2, 3, 4, 5]),9);
assert.deepEqual(candidate(["//", "*"], [7, 3, 4]),8);
}
test(); |
humaneval-HumanEval_148_bf.json-L43 | 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 {
// There are eight planets in our solar system: the closerst to the Sun
// is Mercury, the next one is Venus, then Earth, Mars, Jupiter, Saturn,
// Uranus, Neptune.
// Write a function that takes two planet names as strings planet1 and planet2.
// The function should return a pair containing all planets whose orbits are
// located between the orbit of planet1 and the orbit of planet2, sorted by
// the proximity to the sun.
// The function should return an empty pair if planet1 or planet2
// are not correct planet names.
// Examples
// >>> bf(("Jupiter"), ("Neptune"))
// (new ArrayList<String>(Arrays.asList((String)"Saturn", (String)"Uranus")))
// >>> bf(("Earth"), ("Mercury"))
// (ArrayList<String>("Venus"))
// >>> bf(("Mercury"), ("Uranus"))
// (new ArrayList<String>(Arrays.asList((String)"Venus", (String)"Earth", (String)"Mars", (String)"Jupiter", (String)"Saturn")))
public static ArrayList<String> bf(String planet1, String planet2) {
ArrayList<String> planets = new ArrayList<String>(Arrays.asList((String)"Mercury", (String)"Venus", (String)"Earth", (String)"Mars", (String)"Jupiter", (String)"Saturn", (String)"Uranus", (String)"Neptune"));
int indexPlanet1 = planets.indexOf(planet1);
int indexPlanet2 = planets.indexOf(planet2);
int indexMin = 0;
int indexMax = 0;
if (indexPlanet1 >= 0 && indexPlanet2 >= 0) {
if (indexPlanet1 < indexPlanet2) {
indexMin = indexPlanet1;
indexMax = indexPlanet2;
} else {
indexMin = indexPlanet2;
indexMax = indexPlanet1;
}
ArrayList<String> planetsInBetween = new ArrayList<String>();
for (int i = indexMin + 1; i < indexMax; i++) {
planetsInBetween.add(planets.get(i));
} | } else {
return new ArrayList<String>();
}
}
} | return planetsInBetween; | }
public static void main(String[] args) {
assert(bf(("Jupiter"), ("Neptune")).equals((new ArrayList<String>(Arrays.asList((String)"Saturn", (String)"Uranus")))));
assert(bf(("Earth"), ("Mercury")).equals((new ArrayList<String>(Arrays.asList((String)"Venus")))));
assert(bf(("Mercury"), ("Uranus")).equals((new ArrayList<String>(Arrays.asList((String)"Venus", (String)"Earth", (String)"Mars", (String)"Jupiter", (String)"Saturn")))));
assert(bf(("Neptune"), ("Venus")).equals((new ArrayList<String>(Arrays.asList((String)"Earth", (String)"Mars", (String)"Jupiter", (String)"Saturn", (String)"Uranus")))));
assert(bf(("Earth"), ("Earth")).equals((new ArrayList<String>(Arrays.asList()))));
assert(bf(("Mars"), ("Earth")).equals((new ArrayList<String>(Arrays.asList()))));
assert(bf(("Jupiter"), ("Makemake")).equals((new ArrayList<String>(Arrays.asList()))));
}
}
|
humaneval-HumanEval_31_is_prime.json-L27 | js | //Return true if a given number is prime, and false otherwise.
// >>> is_prime(6)
// false
// >>> is_prime(101)
// true
// >>> is_prime(11)
// true
// >>> is_prime(13441)
// true
// >>> is_prime(61)
// true
// >>> is_prime(4)
// false
// >>> is_prime(1)
// false
function is_prime(n){
if (n==1) {
return false;
}
if (n==2) {
return true;
}
if (n%2==0) {
return false; |
var limit = Math.sqrt(n);
for (var i = 3; i <= limit; i += 2) {
if (n%i==0) {
return false;
}
}
return true;
}
| } | const assert = require('node:assert');
function test() {
let candidate = is_prime;
assert.deepEqual(candidate(6),false);
assert.deepEqual(candidate(101),true);
assert.deepEqual(candidate(11),true);
assert.deepEqual(candidate(13441),true);
assert.deepEqual(candidate(61),true);
assert.deepEqual(candidate(4),false);
assert.deepEqual(candidate(1),false);
assert.deepEqual(candidate(5),true);
assert.deepEqual(candidate(11),true);
assert.deepEqual(candidate(17),true);
assert.deepEqual(candidate(85),false);
assert.deepEqual(candidate(77),false);
assert.deepEqual(candidate(255379),false);
}
test(); |
humaneval-HumanEval_141_file_name_check.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 {
// Create a function which takes a string representing a file's name, and returns
// 'Yes' if the the file's name is valid, and returns 'No' otherwise.
// A file's name is considered to be valid if and only if all the following conditions
// are met:
// - There should not be more than three digits ('0'-'9') in the file's name.
// - The file's name contains exactly one dot '.'
// - The substring before the dot should not be empty, and it starts with a letter from
// the latin alphapet ('a'-'z' and 'A'-'Z').
// - The substring after the dot should be one of these: ['txt', 'exe', 'dll']
// Examples:
// >>> fileNameCheck(("example.txt"))
// ("Yes")
// >>> fileNameCheck(("1example.dll"))
// ("No")
public static String fileNameCheck(String file_name) {
String result = "No";
String[] tokens = file_name.split("\\.");
if (tokens.length != 2) {
return result;
}
String extension = tokens[1];
if (!(extension.equals("txt") || extension.equals("exe") || extension.equals("dll"))) {
return result;
}
String name = tokens[0];
int count = 0;
for (int i = 0; i < name.length(); i++) {
if (Character.isDigit(name.charAt(i))) {
count++; | }
if (count > 3) {
return result;
}
if (name.length() == 0) {
return result;
}
if (!Character.isLetter(name.charAt(0))) {
return result;
}
return "Yes";
}
} | } | }
public static void main(String[] args) {
assert(fileNameCheck(("example.txt")).equals(("Yes")));
assert(fileNameCheck(("1example.dll")).equals(("No")));
assert(fileNameCheck(("s1sdf3.asd")).equals(("No")));
assert(fileNameCheck(("K.dll")).equals(("Yes")));
assert(fileNameCheck(("MY16FILE3.exe")).equals(("Yes")));
assert(fileNameCheck(("His12FILE94.exe")).equals(("No")));
assert(fileNameCheck(("_Y.txt")).equals(("No")));
assert(fileNameCheck(("?aREYA.exe")).equals(("No")));
assert(fileNameCheck(("/this_is_valid.dll")).equals(("No")));
assert(fileNameCheck(("this_is_valid.wow")).equals(("No")));
assert(fileNameCheck(("this_is_valid.txt")).equals(("Yes")));
assert(fileNameCheck(("this_is_valid.txtexe")).equals(("No")));
assert(fileNameCheck(("#this2_i4s_5valid.ten")).equals(("No")));
assert(fileNameCheck(("@this1_is6_valid.exe")).equals(("No")));
assert(fileNameCheck(("this_is_12valid.6exe4.txt")).equals(("No")));
assert(fileNameCheck(("all.exe.txt")).equals(("No")));
assert(fileNameCheck(("I563_No.exe")).equals(("Yes")));
assert(fileNameCheck(("Is3youfault.txt")).equals(("Yes")));
assert(fileNameCheck(("no_one#knows.dll")).equals(("Yes")));
assert(fileNameCheck(("1I563_Yes3.exe")).equals(("No")));
assert(fileNameCheck(("I563_Yes3.txtt")).equals(("No")));
assert(fileNameCheck(("final..txt")).equals(("No")));
assert(fileNameCheck(("final132")).equals(("No")));
assert(fileNameCheck(("_f4indsartal132.")).equals(("No")));
assert(fileNameCheck((".txt")).equals(("No")));
assert(fileNameCheck(("s.")).equals(("No")));
}
}
|
humaneval-HumanEval_147_get_max_triples.json-L15 | js | //You are given a positive integer n. You have to create an integer array a of length n.
// For each i (1 ≤ i ≤ n), the value of a[i] = i * i - i + 1.
// Return the number of triples (a[i], a[j], a[k]) of a where i < j < k,
// and a[i] + a[j] + a[k] is a multiple of 3.
// Example :
// >>> get_max_triples(5)
// 1
// Explanation:
// a = [1, 3, 7, 13, 21]
// The only valid triple is (1, 7, 13).
function get_max_triples(n){
let result = 0;
let arr = [];
for(let i = 1; i<=n; i++){ | }
for(let i = 0; i<arr.length; i++){
for(let j = i+1; j<arr.length; j++){
for(let k = j+1; k<arr.length; k++){
if((arr[i]+arr[j]+arr[k])%3 === 0){
result++;
}
}
}
}
return result;
}
| arr.push(i*i-i+1); | const assert = require('node:assert');
function test() {
let candidate = get_max_triples;
assert.deepEqual(candidate(5),1);
assert.deepEqual(candidate(6),4);
assert.deepEqual(candidate(10),36);
assert.deepEqual(candidate(100),53361);
}
test(); |
humaneval-HumanEval_123_get_odd_collatz.json-L41 | js | //Given a positive integer n, return a sorted array 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 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.
// >>> get_odd_collatz(5)
// [1, 5]
function get_odd_collatz(n){
var collatz_sequence = []
var odd_numbers = []
var odd_count = 0
collatz_sequence.push(n)
for(var i = 0; i < collatz_sequence.length; i++){
if(collatz_sequence[i]%2 == 0){
collatz_sequence.push(collatz_sequence[i]/2)
}
else if(collatz_sequence[i]%2 == 1){
collatz_sequence.push(collatz_sequence[i]*3+1)
}
if(collatz_sequence[i]%2 == 1){
odd_numbers.push(collatz_sequence[i])
odd_count += 1
}
if(collatz_sequence[i] == 1){
break
}
}
if(odd_count != 0){
odd_numbers.sort(function(a, b){return a-b})
return odd_numbers
}
else{
odd_numbers.push(1)
return odd_numbers | }
| } | const assert = require('node:assert');
function test() {
let candidate = get_odd_collatz;
assert.deepEqual(candidate(14),[1, 5, 7, 11, 13, 17]);
assert.deepEqual(candidate(5),[1, 5]);
assert.deepEqual(candidate(12),[1, 3, 5]);
assert.deepEqual(candidate(1),[1]);
}
test(); |
humaneval-HumanEval_93_encode.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 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")
public static String encode(String message) {
char[] arr = message.toCharArray();
char[] vowels = "AEIOUaeiou".toCharArray();
for (int i = 0; i < arr.length; i++) {
if (Arrays.binarySearch(vowels, arr[i]) > -1) {
arr[i] = (char) (arr[i] + 2);
}
if (Character.isUpperCase(arr[i])) {
arr[i] = Character.toLowerCase(arr[i]); | arr[i] = Character.toUpperCase(arr[i]);
}
}
return new String(arr);
}
} | } else { | }
public static void main(String[] args) {
assert(encode(("TEST")).equals(("tgst")));
assert(encode(("Mudasir")).equals(("mWDCSKR")));
assert(encode(("YES")).equals(("ygs")));
assert(encode(("This is a message")).equals(("tHKS KS C MGSSCGG")));
assert(encode(("I DoNt KnOw WhAt tO WrItE")).equals(("k dQnT kNqW wHcT Tq wRkTg")));
}
}
|
humaneval-HumanEval_143_words_in_sentence.json-L25 | py | def words_in_sentence(sentence: str) -> str:
"""
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
"""
def is_prime(n: int) -> bool:
if n <= 1:
return False
for i in range(2, n): | return False
return True
words = sentence.split()
prime_words = []
for word in words:
if is_prime(len(word)):
prime_words.append(word)
return ' '.join(prime_words) | if n % i == 0: | def check(candidate):
assert candidate('This is a test') == 'is'
assert candidate('lets go for swimming') == 'go for'
assert candidate('there is no place available here') == 'there is no place'
assert candidate('Hi I am Hussein') == 'Hi am Hussein'
assert candidate('go for it') == 'go for it'
assert candidate('here') == ''
assert candidate('here is') == 'is'
def test_check():
check(words_in_sentence)
test_check()
|
humaneval-HumanEval_3_below_zero.json-L13 | py | from typing import List
def below_zero(operations: List[int]) -> bool:
""" You're given a list of deposit and withdrawal operations on a bank account that starts with
zero balance. Your task is to detect if at any point the balance of account fallls below zero, and
at that point function should return True. Otherwise it should return False.
>>> below_zero([1, 2, 3])
False
>>> below_zero([1, 2, -4, 5])
True
"""
balance = 0 | balance += operation
if balance < 0:
return True
return False
print(below_zero([1, 2, 3]))
print(below_zero([1, 2, -4, 5])) | for operation in operations: | def check(candidate):
assert candidate([]) == False
assert candidate([1, 2, -3, 1, 2, -3]) == False
assert candidate([1, 2, -4, 5, 6]) == True
assert candidate([1, -1, 2, -2, 5, -5, 4, -4]) == False
assert candidate([1, -1, 2, -2, 5, -5, 4, -5]) == True
assert candidate([1, -2, 2, -2, 5, -5, 4, -4]) == True
def test_check():
check(below_zero)
test_check()
|
humaneval-HumanEval_1_separate_paren_groups.json-L15 | js | //Input to this function is a string containing multiple groups of nested parentheses. Your goal is to
// separate those group into separate strings and return the array of those.
// Separate groups are balanced (each open brace is properly closed) and not nested within each other
// Ignore any spaces in the input string.
// >>> separate_paren_groups("( ) (( )) (( )( ))")
// ["()", "(())", "(()())"]
function separate_paren_groups(paren_string){
var count = 0;
var group = '';
var groups = [];
for (var i = 0; i < paren_string.length; i++){
if (paren_string[i] === '('){
count++;
group += paren_string[i]; | count--;
group += paren_string[i];
}
if (count === 0 && group){
groups.push(group);
group = '';
}
}
return groups;
}
| } else if (paren_string[i] === ')'){ | const assert = require('node:assert');
function test() {
let candidate = separate_paren_groups;
assert.deepEqual(candidate("(()()) ((())) () ((())()())"),["(()())", "((()))", "()", "((())()())"]);
assert.deepEqual(candidate("() (()) ((())) (((())))"),["()", "(())", "((()))", "(((())))"]);
assert.deepEqual(candidate("(()(())((())))"),["(()(())((())))"]);
assert.deepEqual(candidate("( ) (( )) (( )( ))"),["()", "(())", "(()())"]);
}
test(); |
humaneval-HumanEval_110_exchange.json-L18 | js | //In this problem, you will implement a function that takes two arrays of numbers,
// and determines whether it is possible to perform an exchange of elements
// between them to make lst1 an array of only even numbers.
// There is no limit on the number of exchanged elements between lst1 and lst2.
// If it is possible to exchange elements between the lst1 and lst2 to make
// all the elements of lst1 to be even, return "YES".
// Otherwise, return "NO".
// For example:
// >>> exchange([1, 2, 3, 4], [1, 2, 3, 4])
// "YES"
// >>> exchange([1, 2, 3, 4], [1, 5, 3, 4])
// "NO"
// It is assumed that the input arrays will be non-empty.
function exchange(lst1, lst2){
var num1 = 0;
var num2 = 0;
var exchange = true; | if(lst1[num1] % 2 !== 0){
exchange = false;
if(num2 < lst2.length){
while(num2 < lst2.length && exchange == false){
if(lst2[num2] % 2 == 0){
lst1[num1] = lst2[num2];
exchange = true;
}
num2++;
}
}
}
num1++;
}
if(exchange){
return "YES";
}else{
return "NO";
}
}
| while(num1 < lst1.length && exchange){ | const assert = require('node:assert');
function test() {
let candidate = exchange;
assert.deepEqual(candidate([1, 2, 3, 4], [1, 2, 3, 4]),"YES");
assert.deepEqual(candidate([1, 2, 3, 4], [1, 5, 3, 4]),"NO");
assert.deepEqual(candidate([1, 2, 3, 4], [2, 1, 4, 3]),"YES");
assert.deepEqual(candidate([5, 7, 3], [2, 6, 4]),"YES");
assert.deepEqual(candidate([5, 7, 3], [2, 6, 3]),"NO");
assert.deepEqual(candidate([3, 2, 6, 1, 8, 9], [3, 5, 5, 1, 1, 1]),"NO");
assert.deepEqual(candidate([100, 200], [200, 200]),"YES");
}
test(); |
humaneval-HumanEval_153_Strongest_Extension.json-L27 | java | import java.util.*;
import java.lang.reflect.*;
import org.javatuples.*;
import java.security.*;
import java.math.*;
import java.io.*;
import java.util.stream.*;
class Problem {
// You will be given the name of a class (a string) and an array array list of extensions.
// The extensions are to be used to load additional classes to the class. The
// strength of the extension is as follows: Let CAP be the number of the uppercase
// letters in the extension's name, and let SM be the number of lowercase letters
// in the extension's name, the strength is given by the fraction CAP - SM.
// You should find the strongest extension and return a string in this
// format: ClassName.StrongestExtensionName.
// If there are two or more extensions with the same strength, you should
// choose the one that comes first in the array list.
// For example, if you are given "Slices" as the class and an array array list of the
// extensions: ['SErviNGSliCes', 'Cheese', 'StuFfed'] then you should
// return 'Slices.SErviNGSliCes' since 'SErviNGSliCes' is the strongest extension
// (its strength is -1).
// Example:
// >>> StrongestExtension(("my_class"), (new ArrayList<String>(Arrays.asList((String)"AA", (String)"Be", (String)"CC"))))
// ("my_class.AA")
public static String StrongestExtension(String class_name, ArrayList<String> extensions) {
if (extensions.size() == 0) { | }
int strength = Integer.MIN_VALUE;
String strongest = "";
for (String s : extensions) {
int cap = (int)s.chars().filter(c -> Character.isUpperCase(c)).count();
int sm = (int)s.chars().filter(c -> Character.isLowerCase(c)).count();
int diff = cap - sm;
if (diff > strength) {
strength = diff;
strongest = s;
}
}
return class_name + "." + strongest;
}
} | return class_name; | }
public static void main(String[] args) {
assert(StrongestExtension(("Watashi"), (new ArrayList<String>(Arrays.asList((String)"tEN", (String)"niNE", (String)"eIGHt8OKe")))).equals(("Watashi.eIGHt8OKe")));
assert(StrongestExtension(("Boku123"), (new ArrayList<String>(Arrays.asList((String)"nani", (String)"NazeDa", (String)"YEs.WeCaNe", (String)"32145tggg")))).equals(("Boku123.YEs.WeCaNe")));
assert(StrongestExtension(("__YESIMHERE"), (new ArrayList<String>(Arrays.asList((String)"t", (String)"eMptY", (String)"nothing", (String)"zeR00", (String)"NuLl__", (String)"123NoooneB321")))).equals(("__YESIMHERE.NuLl__")));
assert(StrongestExtension(("K"), (new ArrayList<String>(Arrays.asList((String)"Ta", (String)"TAR", (String)"t234An", (String)"cosSo")))).equals(("K.TAR")));
assert(StrongestExtension(("__HAHA"), (new ArrayList<String>(Arrays.asList((String)"Tab", (String)"123", (String)"781345", (String)"-_-")))).equals(("__HAHA.123")));
assert(StrongestExtension(("YameRore"), (new ArrayList<String>(Arrays.asList((String)"HhAas", (String)"okIWILL123", (String)"WorkOut", (String)"Fails", (String)"-_-")))).equals(("YameRore.okIWILL123")));
assert(StrongestExtension(("finNNalLLly"), (new ArrayList<String>(Arrays.asList((String)"Die", (String)"NowW", (String)"Wow", (String)"WoW")))).equals(("finNNalLLly.WoW")));
assert(StrongestExtension(("_"), (new ArrayList<String>(Arrays.asList((String)"Bb", (String)"91245")))).equals(("_.Bb")));
assert(StrongestExtension(("Sp"), (new ArrayList<String>(Arrays.asList((String)"671235", (String)"Bb")))).equals(("Sp.671235")));
}
}
|
humaneval-HumanEval_74_total_match.json-L19 | js | //Write a function that accepts two arrays of strings and returns the array that has
// total number of chars in the all strings of the array less than the other array.
// if the two arrays have the same number of chars, return the first array.
// Examples
// >>> total_match([], [])
// []
// >>> total_match(["hi", "admin"], ["hI", "Hi"])
// ["hI", "Hi"]
// >>> total_match(["hi", "admin"], ["hi", "hi", "admin", "project"])
// ["hi", "admin"]
// >>> total_match(["hi", "admin"], ["hI", "hi", "hi"])
// ["hI", "hi", "hi"]
// >>> total_match(["4"], ["1", "2", "3", "4", "5"])
// ["4"]
function total_match(lst1, lst2){
let sum_lst1 = 0;
let sum_lst2 = 0;
for(let item of lst1){ | }
for(let item of lst2){
sum_lst2 += item.length;
}
if(sum_lst1 > sum_lst2){
return lst2;
}
else{
return lst1;
}
}
| sum_lst1 += item.length; | const assert = require('node:assert');
function test() {
let candidate = total_match;
assert.deepEqual(candidate([], []),[]);
assert.deepEqual(candidate(["hi", "admin"], ["hi", "hi"]),["hi", "hi"]);
assert.deepEqual(candidate(["hi", "admin"], ["hi", "hi", "admin", "project"]),["hi", "admin"]);
assert.deepEqual(candidate(["4"], ["1", "2", "3", "4", "5"]),["4"]);
assert.deepEqual(candidate(["hi", "admin"], ["hI", "Hi"]),["hI", "Hi"]);
assert.deepEqual(candidate(["hi", "admin"], ["hI", "hi", "hi"]),["hI", "hi", "hi"]);
assert.deepEqual(candidate(["hi", "admin"], ["hI", "hi", "hii"]),["hi", "admin"]);
assert.deepEqual(candidate([], ["this"]),[]);
assert.deepEqual(candidate(["this"], []),[]);
}
test(); |
humaneval-HumanEval_108_count_nums.json-L20 | py | from typing import List
def count_nums(arr: List[int]) -> int:
"""
Write a function count_nums which takes an array of integers and returns
the number of elements which has a sum of digits > 0.
If a number is negative, then its first signed digit will be negative:
e.g. -123 has signed digits -1, 2, and 3.
>>> count_nums([])
0
>>> count_nums([-1, 11, -11])
1
>>> count_nums([1, 1, 2])
3
"""
n = 0
for i in arr:
if i < 0:
i = abs(i) | for j in str(i)[1:]:
s += int(j)
else:
s = 0
for j in str(i):
s += int(j)
if s > 0:
n += 1
return n
| s = -1 * int(str(i)[0]) | def check(candidate):
assert candidate([]) == 0
assert candidate([-1, -2, 0]) == 0
assert candidate([1, 1, 2, -2, 3, 4, 5]) == 6
assert candidate([1, 6, 9, -6, 0, 1, 5]) == 5
assert candidate([1, 100, 98, -7, 1, -1]) == 4
assert candidate([12, 23, 34, -45, -56, 0]) == 5
assert candidate([0, 1]) == 1
assert candidate([1]) == 1
def test_check():
check(count_nums)
test_check()
|
humaneval-HumanEval_86_anti_shuffle.json-L18 | js | //Write a function that takes a string and returns an ordered version of it.
// Ordered version of string, is a string where all words (separated by space)
// are replaced by a new word where all the characters arranged in
// ascending order based on ascii value.
// Note: You should keep the order of words and blank spaces in the sentence.
// For example:
// >>> anti_shuffle("Hi")
// "Hi"
// >>> anti_shuffle("hello")
// "ehllo"
// >>> anti_shuffle("Hello World!!!")
// "Hello !!!Wdlor"
function anti_shuffle(s){
var result = [];
var strings = s.split(" ");
strings.forEach(function(str){
var temp = str.split(""); | result.push(temp.join(""));
});
return result.join(" ");
} | temp.sort(); | const assert = require('node:assert');
function test() {
let candidate = anti_shuffle;
assert.deepEqual(candidate("Hi"),"Hi");
assert.deepEqual(candidate("hello"),"ehllo");
assert.deepEqual(candidate("number"),"bemnru");
assert.deepEqual(candidate("abcd"),"abcd");
assert.deepEqual(candidate("Hello World!!!"),"Hello !!!Wdlor");
assert.deepEqual(candidate(""),"");
assert.deepEqual(candidate("Hi. My name is Mister Robot. How are you?"),".Hi My aemn is Meirst .Rboot How aer ?ouy");
}
test(); |
humaneval-HumanEval_156_int_to_mini_roman.json-L69 | 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) { | num -= 4;
}
while (num >= 1) {
res += "i";
num -= 1;
}
return res;
}
} | res += "iv"; | }
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_137_compare_one.json-L39 | 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): | else:
return None
elif isinstance(a, int) and isinstance(b, float):
if a > b:
return a
elif a < b:
return b
else:
return None
elif isinstance(a, float) and isinstance(b, int):
if a > b:
return a
elif a < b:
return b
else:
return None
elif isinstance(a, str) and isinstance(b, int):
a_tmp = a.replace(',', '.')
if float(a_tmp) > b:
return a
elif float(a_tmp) < b:
return b
else:
return None
elif isinstance(a, int) and isinstance(b, str):
b_tmp = b.replace(',', '.')
if a > float(b_tmp):
return a
elif a < float(b_tmp):
return b
else:
return None
elif isinstance(a, str) and isinstance(b, float):
a_tmp = a.replace(',', '.')
if float(a_tmp) > b:
return a
elif float(a_tmp) < b:
return b | return 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_72_will_it_fly.json-L25 | java | import java.util.*;
import java.lang.reflect.*;
import org.javatuples.*;
import java.security.*;
import java.math.*;
import java.io.*;
import java.util.stream.*;
class Problem {
// Write a function that 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) {
| 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;
}
} | if (q.size() == 0) { | }
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_66_digitSum.json-L20 | py | def digitSum(s: str) -> int:
"""Task
Write a function that takes a string as input and returns the sum of the upper characters only'
ASCII codes.
Examples:
>>> digitSum('')
0
>>> digitSum('abAB')
131
>>> digitSum('abcCd')
67
>>> digitSum('helloE')
69
>>> digitSum('woArBld')
131
>>> digitSum('aAaaaXa')
153
"""
| return sum(map(ord, filter(str.isupper, s))) | def check(candidate):
assert candidate('') == 0
assert candidate('abAB') == 131
assert candidate('abcCd') == 67
assert candidate('helloE') == 69
assert candidate('woArBld') == 131
assert candidate('aAaaaXa') == 153
assert candidate(' How are yOu?') == 151
assert candidate('You arE Very Smart') == 327
def test_check():
check(digitSum)
test_check()
|
|
humaneval-HumanEval_56_correct_bracketing.json-L17 | 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++;
} | opens--;
}
if (opens < 0) {
return false;
}
}
return opens === 0;
}
| else if (brackets[i] === ">") { | 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_20_find_closest_elements.json-L11 | js | //From a supplied array of numbers (of length at least two) select and return two that are the closest to each
// other and return them in order (smaller number, larger number).
// >>> find_closest_elements([1.0, 2.0, 3.0, 4.0, 5.0, 2.2])
// [2.0, 2.2]
// >>> find_closest_elements([1.0, 2.0, 3.0, 4.0, 5.0, 2.0])
// [2.0, 2.0]
function find_closest_elements(numbers){
let closest = Math.abs(numbers[0] - numbers[1]);
let a = numbers[0];
let b = numbers[1]; | for (let j = i + 1; j < numbers.length; j++) {
if (Math.abs(numbers[i] - numbers[j]) < closest) {
closest = Math.abs(numbers[i] - numbers[j]);
a = numbers[i];
b = numbers[j];
}
}
}
return a > b ? [b, a] : [a, b];
}
| for (let i = 0; i < numbers.length; i++) { | const assert = require('node:assert');
function test() {
let candidate = find_closest_elements;
assert.deepEqual(candidate([1.0, 2.0, 3.9, 4.0, 5.0, 2.2]),[3.9, 4.0]);
assert.deepEqual(candidate([1.0, 2.0, 5.9, 4.0, 5.0]),[5.0, 5.9]);
assert.deepEqual(candidate([1.0, 2.0, 3.0, 4.0, 5.0, 2.2]),[2.0, 2.2]);
assert.deepEqual(candidate([1.0, 2.0, 3.0, 4.0, 5.0, 2.0]),[2.0, 2.0]);
assert.deepEqual(candidate([1.1, 2.2, 3.1, 4.1, 5.1]),[2.2, 3.1]);
}
test(); |
humaneval-HumanEval_47_median.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 {
// Return median of elements in the array list l.
// >>> median((new ArrayList<Long>(Arrays.asList((long)3l, (long)1l, (long)2l, (long)4l, (long)5l))))
// (float)3l
// >>> median((new ArrayList<Long>(Arrays.asList((long)-10l, (long)4l, (long)6l, (long)1000l, (long)10l, (long)20l))))
// (15.0f)
public static float median(ArrayList<Long> l) {
float ret = 0;
Collections.sort(l);
int size = l.size();
if (size % 2 == 0) {
ret = (l.get(size / 2) + l.get(size / 2 - 1)) / 2f;
} else {
ret = l.get(size / 2);
} | }
} | return ret; | }
public static void main(String[] args) {
assert(median((new ArrayList<Long>(Arrays.asList((long)3l, (long)1l, (long)2l, (long)4l, (long)5l)))) == (float)3l);
assert(median((new ArrayList<Long>(Arrays.asList((long)-10l, (long)4l, (long)6l, (long)1000l, (long)10l, (long)20l)))) == (8.0f));
assert(median((new ArrayList<Long>(Arrays.asList((long)5l)))) == (float)5l);
assert(median((new ArrayList<Long>(Arrays.asList((long)6l, (long)5l)))) == (5.5f));
assert(median((new ArrayList<Long>(Arrays.asList((long)8l, (long)1l, (long)3l, (long)9l, (long)9l, (long)2l, (long)7l)))) == (float)7l);
}
}
|
humaneval-HumanEval_20_find_closest_elements.json-L18 | js | //From a supplied array of numbers (of length at least two) select and return two that are the closest to each
// other and return them in order (smaller number, larger number).
// >>> find_closest_elements([1.0, 2.0, 3.0, 4.0, 5.0, 2.2])
// [2.0, 2.2]
// >>> find_closest_elements([1.0, 2.0, 3.0, 4.0, 5.0, 2.0])
// [2.0, 2.0]
function find_closest_elements(numbers){
let closest = Math.abs(numbers[0] - numbers[1]);
let a = numbers[0];
let b = numbers[1];
for (let i = 0; i < numbers.length; i++) {
for (let j = i + 1; j < numbers.length; j++) {
if (Math.abs(numbers[i] - numbers[j]) < closest) {
closest = Math.abs(numbers[i] - numbers[j]);
a = numbers[i];
b = numbers[j];
} | }
return a > b ? [b, a] : [a, b];
}
| } | const assert = require('node:assert');
function test() {
let candidate = find_closest_elements;
assert.deepEqual(candidate([1.0, 2.0, 3.9, 4.0, 5.0, 2.2]),[3.9, 4.0]);
assert.deepEqual(candidate([1.0, 2.0, 5.9, 4.0, 5.0]),[5.0, 5.9]);
assert.deepEqual(candidate([1.0, 2.0, 3.0, 4.0, 5.0, 2.2]),[2.0, 2.2]);
assert.deepEqual(candidate([1.0, 2.0, 3.0, 4.0, 5.0, 2.0]),[2.0, 2.0]);
assert.deepEqual(candidate([1.1, 2.2, 3.1, 4.1, 5.1]),[2.2, 3.1]);
}
test(); |
humaneval-HumanEval_137_compare_one.json-L38 | 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]){
return b;
} else { | }
}
}
| return undefined; | 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_117_select_words.json-L26 | py | from typing import List
def select_words(s: str, n: int) -> List[str]:
"""Given a string s and a natural number n, you have been tasked to implement
a function that returns a list of all words from string s that contain exactly
n consonants, in order these words appear in the string s.
If the string s is empty then the function should return an empty list.
Note: you may assume the input string contains only letters and spaces.
Examples:
>>> select_words('Mary had a little lamb', 4)
['little']
>>> select_words('Mary had a little lamb', 3)
['Mary', 'lamb']
>>> select_words('simple white space', 2)
[]
>>> select_words('Hello world', 4)
['world']
>>> select_words('Uncle sam', 3)
['Uncle']
"""
CONSONANTS = 'bcdfghjklmnpqrstvwxyz'
words = s.split()
result = []
for word in words:
count = 0 | if char.lower() in CONSONANTS:
count += 1
if count == n:
result.append(word)
return result
| for char in word: | def check(candidate):
assert candidate('Mary had a little lamb', 4) == ['little']
assert candidate('Mary had a little lamb', 3) == ['Mary', 'lamb']
assert candidate('simple white space', 2) == []
assert candidate('Hello world', 4) == ['world']
assert candidate('Uncle sam', 3) == ['Uncle']
assert candidate('', 4) == []
assert candidate('a b c d e f', 1) == ['b', 'c', 'd', 'f']
def test_check():
check(select_words)
test_check()
|
humaneval-HumanEval_95_check_dict_case.json-L30 | js | //Given an object, return true if all keys are strings in lower
// case or all keys are strings in upper case, else return false.
// The function should return false is the given object is empty.
// Examples:
// >>> check_dict_case({"a": "apple", "b": "banana"})
// true
// >>> check_dict_case({"a": "apple", "A": "banana", "B": "banana"})
// false
// >>> check_dict_case({"a": "apple", 8: "banana", "a": "apple"})
// false
// >>> check_dict_case({"Name": "John", "Age": "36", "City": "Houston"})
// false
// >>> check_dict_case({"STATE": "NC", "ZIP": "12345"})
// true
function check_dict_case(dict){
if (Object.keys(dict).length == 0){
return false;
}
var case_type = -1;
for (let key in dict){
if (typeof key == "string"){
if (case_type == -1){
if (key == key.toUpperCase()){
case_type = 1;
}
else if (key == key.toLowerCase()){
case_type = 0;
}
else{ | }
}
else if (case_type == 1){
if (key != key.toUpperCase()){
return false;
}
}
else if (case_type == 0){
if (key != key.toLowerCase()){
return false;
}
}
}
else{
return false;
}
}
return true;
} | return false; | const assert = require('node:assert');
function test() {
let candidate = check_dict_case;
assert.deepEqual(candidate({"p": "pineapple", "b": "banana"}),true);
assert.deepEqual(candidate({"p": "pineapple", "A": "banana", "B": "banana"}),false);
assert.deepEqual(candidate({"p": "pineapple", "5": "banana", "a": "apple"}),false);
assert.deepEqual(candidate({"Name": "John", "Age": "36", "City": "Houston"}),false);
assert.deepEqual(candidate({"STATE": "NC", "ZIP": "12345"}),true);
assert.deepEqual(candidate({"fruit": "Orange", "taste": "Sweet"}),true);
assert.deepEqual(candidate({}),false);
}
test(); |
humaneval-HumanEval_129_minPath.json-L55 | 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_125_split_words.json-L24 | 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{
let count = 0;
for(let i = 0; i < txt.length; i++){
if(i % 2 != 0){
if(txt[i] == txt[i].toLowerCase()){
count++; | }
}
return count;
}
} | } | 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_68_pluck.json-L31 | js | //"Given an array representing a branch of a tree that has non-negative integer nodes
// your task is to pluck one of the nodes and return it.
// The plucked node should be the node with the smallest even value.
// If multiple nodes with the same smallest even value are found return the node that has smallest index.
// The plucked node should be returned in an array, [ smalest_value, its index ],
// If there are no even values or the given array is empty, return [].
// Example 1:
// >>> pluck([4, 2, 3])
// [2, 1]
// Explanation: 2 has the smallest even value, and 2 has the smallest index.
// Example 2:
// >>> pluck([1, 2, 3])
// [2, 1]
// Explanation: 2 has the smallest even value, and 2 has the smallest index.
// Example 3:
// >>> pluck([])
// []
// Example 4:
// >>> pluck([5, 0, 3, 0, 4, 2])
// [0, 1]
// Explanation: 0 is the smallest value, but there are two zeros,
// so we will choose the first zero, which has the smallest index.
// Constraints:
// * 1 <= nodes.length <= 10000
// * 0 <= node.value
function pluck(arr){
let result = [],
index = -1;
for(let i = 0; i < arr.length; i++){
if(arr[i] % 2 === 0){ | result = [arr[i], i];
}
}
}
return result;
}
| if(result.length === 0 || result[0] > arr[i]){ | const assert = require('node:assert');
function test() {
let candidate = pluck;
assert.deepEqual(candidate([4, 2, 3]),[2, 1]);
assert.deepEqual(candidate([1, 2, 3]),[2, 1]);
assert.deepEqual(candidate([]),[]);
assert.deepEqual(candidate([5, 0, 3, 0, 4, 2]),[0, 1]);
assert.deepEqual(candidate([1, 2, 3, 0, 5, 3]),[0, 3]);
assert.deepEqual(candidate([5, 4, 8, 4, 8]),[4, 1]);
assert.deepEqual(candidate([7, 6, 7, 1]),[6, 1]);
assert.deepEqual(candidate([7, 9, 7, 1]),[]);
}
test(); |
humaneval-HumanEval_156_int_to_mini_roman.json-L16 | 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 = { | 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
| 1000: 'm', | 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_107_even_odd_palindrome.json-L29 | 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; | if(pal[i] % 2 == 0){
even++;
}
else{
odd++;
}
}
return [even, odd];
} | for(var i = 0; i < pal.length; i++){ | 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_161_solve.json-L21 | 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)) {
return char === char.toLowerCase()
? char.toUpperCase()
: char.toLowerCase(); | return char;
});
return swapped.join('');
}
return s.split('').reverse().join('');
}
| } | 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_127_intersection.json-L28 | py | from typing import Tuple
def intersection(interval1: Tuple[int, int], interval2: Tuple[int, int]) -> str:
"""You are given two intervals,
where each interval is a pair of integers. For example, interval = (start, end) = (1, 2).
The given intervals are closed which means that the interval (start, end)
includes both start and end.
For each given interval, it is assumed that its start is less or equal its end.
Your task is to determine whether the length of intersection of these two
intervals is a prime number.
Example, the intersection of the intervals (1, 3), (2, 4) is (2, 3)
which its length is 1, which not a prime number.
If the length of the intersection is a prime number, return "YES",
otherwise, return "NO".
If the two intervals don't intersect, return "NO".
[input/output] samples:
>>> intersection((1, 2), (2, 3))
'NO'
>>> intersection((-1, 1), (0, 4))
'NO'
>>> intersection((-3, -1), (-5, 5))
'YES'
"""
start = max(interval1[0], interval2[0])
end = min(interval1[1], interval2[1]) | return "NO"
return "YES" if end - start == 2 else "NO"
| if start > end: | def check(candidate):
assert candidate((1, 2), (2, 3)) == 'NO'
assert candidate((-1, 1), (0, 4)) == 'NO'
assert candidate((-3, -1), (-5, 5)) == 'YES'
assert candidate((-2, 2), (-4, 0)) == 'YES'
assert candidate((-11, 2), (-1, -1)) == 'NO'
assert candidate((1, 2), (3, 5)) == 'NO'
assert candidate((1, 2), (1, 2)) == 'NO'
assert candidate((-2, -2), (-3, -2)) == 'NO'
def test_check():
check(intersection)
test_check()
|
humaneval-HumanEval_72_will_it_fly.json-L26 | java | import java.util.*;
import java.lang.reflect.*;
import org.javatuples.*;
import java.security.*;
import java.math.*;
import java.io.*;
import java.util.stream.*;
class Problem {
// Write a function that 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) { | }
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;
}
} | return false; | }
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_108_count_nums.json-L24 | py | from typing import List
def count_nums(arr: List[int]) -> int:
"""
Write a function count_nums which takes an array of integers and returns
the number of elements which has a sum of digits > 0.
If a number is negative, then its first signed digit will be negative:
e.g. -123 has signed digits -1, 2, and 3.
>>> count_nums([])
0
>>> count_nums([-1, 11, -11])
1
>>> count_nums([1, 1, 2])
3
"""
n = 0
for i in arr:
if i < 0:
i = abs(i)
s = -1 * int(str(i)[0])
for j in str(i)[1:]:
s += int(j)
else: | for j in str(i):
s += int(j)
if s > 0:
n += 1
return n
| s = 0 | def check(candidate):
assert candidate([]) == 0
assert candidate([-1, -2, 0]) == 0
assert candidate([1, 1, 2, -2, 3, 4, 5]) == 6
assert candidate([1, 6, 9, -6, 0, 1, 5]) == 5
assert candidate([1, 100, 98, -7, 1, -1]) == 4
assert candidate([12, 23, 34, -45, -56, 0]) == 5
assert candidate([0, 1]) == 1
assert candidate([1]) == 1
def test_check():
check(count_nums)
test_check()
|
humaneval-HumanEval_1_separate_paren_groups.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 {
// 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) { | }
open_paren++;
temp.append(c);
} else if (c == ')') {
open_paren--;
temp.append(c);
if (open_paren == 0) {
output.add(temp.toString());
}
}
}
return output;
}
} | temp = new StringBuffer(); | }
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_69_search.json-L25 | py | from typing import List
def search(lst: List[int]) -> int:
"""
You are given a non-empty list of positive integers. Return the greatest integer that is greater than
zero, and has a frequency greater than or equal to the value of the integer itself.
The frequency of an integer is the number of times it appears in the list.
If no such a value exist, return -1.
Examples:
>>> search([4, 1, 2, 2, 3, 1])
2
>>> search([1, 2, 2, 3, 3, 3, 4, 4, 4])
3
>>> search([5, 5, 4, 4, 4])
-1
"""
dic = dict()
for i in lst:
if i in dic:
dic[i] += 1
else:
dic[i] = 1
maxValue = -1
for key, value in dic.items(): | maxValue = key
return maxValue
| if value >= key and key > maxValue: | def check(candidate):
assert candidate([5, 5, 5, 5, 1]) == 1
assert candidate([4, 1, 4, 1, 4, 4]) == 4
assert candidate([3, 3]) == -1
assert candidate([8, 8, 8, 8, 8, 8, 8, 8]) == 8
assert candidate([2, 3, 3, 2, 2]) == 2
assert candidate([2, 7, 8, 8, 4, 8, 7, 3, 9, 6, 5, 10, 4, 3, 6, 7, 1, 7, 4, 10, 8, 1]) == 1
assert candidate([3, 2, 8, 2]) == 2
assert candidate([6, 7, 1, 8, 8, 10, 5, 8, 5, 3, 10]) == 1
assert candidate([8, 8, 3, 6, 5, 6, 4]) == -1
assert candidate([6, 9, 6, 7, 1, 4, 7, 1, 8, 8, 9, 8, 10, 10, 8, 4, 10, 4, 10, 1, 2, 9, 5, 7, 9]) == 1
assert candidate([1, 9, 10, 1, 3]) == 1
assert candidate([6, 9, 7, 5, 8, 7, 5, 3, 7, 5, 10, 10, 3, 6, 10, 2, 8, 6, 5, 4, 9, 5, 3, 10]) == 5
assert candidate([1]) == 1
assert candidate([8, 8, 10, 6, 4, 3, 5, 8, 2, 4, 2, 8, 4, 6, 10, 4, 2, 1, 10, 2, 1, 1, 5]) == 4
assert candidate([2, 10, 4, 8, 2, 10, 5, 1, 2, 9, 5, 5, 6, 3, 8, 6, 4, 10]) == 2
assert candidate([1, 6, 10, 1, 6, 9, 10, 8, 6, 8, 7, 3]) == 1
assert candidate([9, 2, 4, 1, 5, 1, 5, 2, 5, 7, 7, 7, 3, 10, 1, 5, 4, 2, 8, 4, 1, 9, 10, 7, 10, 2, 8, 10, 9, 4]) == 4
assert candidate([2, 6, 4, 2, 8, 7, 5, 6, 4, 10, 4, 6, 3, 7, 8, 8, 3, 1, 4, 2, 2, 10, 7]) == 4
assert candidate([9, 8, 6, 10, 2, 6, 10, 2, 7, 8, 10, 3, 8, 2, 6, 2, 3, 1]) == 2
assert candidate([5, 5, 3, 9, 5, 6, 3, 2, 8, 5, 6, 10, 10, 6, 8, 4, 10, 7, 7, 10, 8]) == -1
assert candidate([10]) == -1
assert candidate([9, 7, 7, 2, 4, 7, 2, 10, 9, 7, 5, 7, 2]) == 2
assert candidate([5, 4, 10, 2, 1, 1, 10, 3, 6, 1, 8]) == 1
assert candidate([7, 9, 9, 9, 3, 4, 1, 5, 9, 1, 2, 1, 1, 10, 7, 5, 6, 7, 6, 7, 7, 6]) == 1
assert candidate([3, 10, 10, 9, 2]) == -1
def test_check():
check(search)
test_check()
|
humaneval-HumanEval_15_string_sequence.json-L10 | js | //Return a string containing space-delimited numbers starting from 0 upto n inclusive.
// >>> string_sequence(0)
// "0"
// >>> string_sequence(5)
// "0 1 2 3 4 5"
function string_sequence(n){
let arr = [];
for(let i = 0; i <= n; i++){
arr.push(i); | return arr.join(" ");
}
| } | const assert = require('node:assert');
function test() {
let candidate = string_sequence;
assert.deepEqual(candidate(0),"0");
assert.deepEqual(candidate(3),"0 1 2 3");
assert.deepEqual(candidate(10),"0 1 2 3 4 5 6 7 8 9 10");
}
test(); |
humaneval-HumanEval_119_match_parens.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 {
// You are given an array array list of two strings, both strings consist of open
// parentheses '(' or close parentheses ')' only.
// Your job is to check if it is possible to concatenate the two strings in
// some order, that the resulting string will be good.
// A string S is considered to be good if and only if all parentheses in S
// are balanced. For example: the string '(())()' is good, while the string
// '())' is not.
// Return 'Yes' if there's a way to make a good string, and return 'No' otherwise.
// Examples:
// >>> matchParens((new ArrayList<String>(Arrays.asList((String)"()(", (String)")"))))
// ("Yes")
// >>> matchParens((new ArrayList<String>(Arrays.asList((String)")", (String)")"))))
// ("No")
public static String matchParens(ArrayList<String> lst) {
String s1 = lst.get(0);
String s2 = lst.get(1);
String s3 = s1+s2;
String s4 = s2+s1;
int c1 = 0; | for (int i = 0; i < s3.length(); i++) {
if (s3.charAt(i) == '(') c1 += 1;
else c1 -= 1;
if (c1 < 0) break;
}
for (int i = 0; i < s4.length(); i++) {
if (s4.charAt(i) == '(') c2 += 1;
else c2 -= 1;
if (c2 < 0) break;
}
if (c1 == 0 || c2 == 0) return "Yes";
else return "No";
}
} | int c2 = 0; | }
public static void main(String[] args) {
assert(matchParens((new ArrayList<String>(Arrays.asList((String)"()(", (String)")")))).equals(("Yes")));
assert(matchParens((new ArrayList<String>(Arrays.asList((String)")", (String)")")))).equals(("No")));
assert(matchParens((new ArrayList<String>(Arrays.asList((String)"(()(())", (String)"())())")))).equals(("No")));
assert(matchParens((new ArrayList<String>(Arrays.asList((String)")())", (String)"(()()(")))).equals(("Yes")));
assert(matchParens((new ArrayList<String>(Arrays.asList((String)"(())))", (String)"(()())((")))).equals(("Yes")));
assert(matchParens((new ArrayList<String>(Arrays.asList((String)"()", (String)"())")))).equals(("No")));
assert(matchParens((new ArrayList<String>(Arrays.asList((String)"(()(", (String)"()))()")))).equals(("Yes")));
assert(matchParens((new ArrayList<String>(Arrays.asList((String)"((((", (String)"((())")))).equals(("No")));
assert(matchParens((new ArrayList<String>(Arrays.asList((String)")(()", (String)"(()(")))).equals(("No")));
assert(matchParens((new ArrayList<String>(Arrays.asList((String)")(", (String)")(")))).equals(("No")));
assert(matchParens((new ArrayList<String>(Arrays.asList((String)"(", (String)")")))).equals(("Yes")));
assert(matchParens((new ArrayList<String>(Arrays.asList((String)")", (String)"(")))).equals(("Yes")));
}
}
|
humaneval-HumanEval_117_select_words.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 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) { | 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;
}
} | String wordInLowerCase = word.toLowerCase(); | }
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_1_separate_paren_groups.json-L21 | js | //Input to this function is a string containing multiple groups of nested parentheses. Your goal is to
// separate those group into separate strings and return the array of those.
// Separate groups are balanced (each open brace is properly closed) and not nested within each other
// Ignore any spaces in the input string.
// >>> separate_paren_groups("( ) (( )) (( )( ))")
// ["()", "(())", "(()())"]
function separate_paren_groups(paren_string){
var count = 0;
var group = '';
var groups = [];
for (var i = 0; i < paren_string.length; i++){
if (paren_string[i] === '('){
count++;
group += paren_string[i];
} else if (paren_string[i] === ')'){
count--;
group += paren_string[i];
}
if (count === 0 && group){
groups.push(group); | }
}
return groups;
}
| group = ''; | const assert = require('node:assert');
function test() {
let candidate = separate_paren_groups;
assert.deepEqual(candidate("(()()) ((())) () ((())()())"),["(()())", "((()))", "()", "((())()())"]);
assert.deepEqual(candidate("() (()) ((())) (((())))"),["()", "(())", "((()))", "(((())))"]);
assert.deepEqual(candidate("(()(())((())))"),["(()(())((())))"]);
assert.deepEqual(candidate("( ) (( )) (( )( ))"),["()", "(())", "(()())"]);
}
test(); |
humaneval-HumanEval_149_sorted_list_sum.json-L22 | js | //Write a function that accepts an array of strings as a parameter,
// deletes the strings that have odd lengths from it,
// and returns the resulted array with a sorted order,
// The array is always an array of strings and never an array of numbers,
// and it may contain duplicates.
// The order of the array should be ascending by length of each word, and you
// should return the array sorted by that rule.
// If two words have the same length, sort the array alphabetically.
// The function should return an array of strings in sorted order.
// You may assume that all words will have the same length.
// For example:
// >>> list_sort(["aa", "a", "aaa"])
// ["aa"]
// >>> list_sort(["ab", "a", "aaa", "cd"])
// ["ab", "cd"]
function sorted_list_sum(lst){
var result = [];
for(var i = 0; i < lst.length; i++){
if(lst[i].length % 2 == 0){
result.push(lst[i]);
} | return result.sort(function(a, b){
if(a.length < b.length){
return -1;
}
else if(a.length > b.length){
return 1;
}
else{
if(a < b){
return -1;
}
else if(a > b){
return 1;
}
else{
return 0;
}
}
});
}
var a = ["aa", "a", "aaa"];
var b = ["ab", "a", "aaa", "cd"]; | } | const assert = require('node:assert');
function test() {
let candidate = sorted_list_sum;
assert.deepEqual(candidate(["aa", "a", "aaa"]),["aa"]);
assert.deepEqual(candidate(["school", "AI", "asdf", "b"]),["AI", "asdf", "school"]);
assert.deepEqual(candidate(["d", "b", "c", "a"]),[]);
assert.deepEqual(candidate(["d", "dcba", "abcd", "a"]),["abcd", "dcba"]);
assert.deepEqual(candidate(["AI", "ai", "au"]),["AI", "ai", "au"]);
assert.deepEqual(candidate(["a", "b", "b", "c", "c", "a"]),[]);
assert.deepEqual(candidate(["aaaa", "bbbb", "dd", "cc"]),["cc", "dd", "aaaa", "bbbb"]);
}
test(); |
humaneval-HumanEval_124_valid_date.json-L25 | py | def valid_date(date: str) -> bool:
"""You have to write a function which validates a given date string and
returns True if the date is valid otherwise False.
The date is valid if all of the following rules are satisfied:
1. The date string is not empty.
2. The number of days is not less than 1 or higher than 31 days for months 1,3,5,7,8,10,12. And the number of days is not less than 1 or higher than 30 days for months 4,6,9,11. And, the number of days is not less than 1 or higher than 29 for the month 2.
3. The months should not be less than 1 or higher than 12.
4. The date should be in the format: mm-dd-yyyy
>>> valid_date('03-11-2000')
True
>>> valid_date('15-01-2012')
False
>>> valid_date('04-0-2040')
False
>>> valid_date('06-04-2020')
True
>>> valid_date('06/04/2020')
False
"""
| return False
days_per_month = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
date_list = [int(d) for d in date.split('-')]
if len(date_list) != 3:
return False
if date_list[0] < 1 or date_list[0] > 12:
return False
if date_list[1] < 1 or date_list[1] > days_per_month[date_list[0] - 1]:
return False
if len(str(date_list[2])) != 4:
return False
return True | if not date: | def check(candidate):
assert candidate('03-11-2000') == True
assert candidate('15-01-2012') == False
assert candidate('04-0-2040') == False
assert candidate('06-04-2020') == True
assert candidate('01-01-2007') == True
assert candidate('03-32-2011') == False
assert candidate('') == False
assert candidate('04-31-3000') == False
assert candidate('06-06-2005') == True
assert candidate('21-31-2000') == False
assert candidate('04-12-2003') == True
assert candidate('04122003') == False
assert candidate('20030412') == False
assert candidate('2003-04') == False
assert candidate('2003-04-12') == False
assert candidate('04-2003') == False
def test_check():
check(valid_date)
test_check()
|
humaneval-HumanEval_70_strange_sort_list.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 array list of integers, return array list in strange order.
// Strange sorting, is when you start with the minimum value,
// then maximum of the remaining integers, then minimum and so on.
// Examples:
// >>> strangeSortList((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l))))
// (new ArrayList<Long>(Arrays.asList((long)1l, (long)4l, (long)2l, (long)3l)))
// >>> strangeSortList((new ArrayList<Long>(Arrays.asList((long)5l, (long)5l, (long)5l, (long)5l))))
// (new ArrayList<Long>(Arrays.asList((long)5l, (long)5l, (long)5l, (long)5l)))
// >>> strangeSortList((new ArrayList<Long>(Arrays.asList())))
// (new ArrayList<Long>(Arrays.asList()))
public static ArrayList<Long> strangeSortList(ArrayList<Long> lst) {
if (lst.size() <= 1) {
return lst;
}
ArrayList<Long> result = new ArrayList<Long>();
ArrayList<Long> sorted = new ArrayList<Long>(lst);
Collections.sort(sorted);
int min = 0;
int max = sorted.size() - 1;
while (min <= max) { | min++;
if (min <= max) {
result.add(sorted.get(max));
max--;
}
}
return result;
}
} | result.add(sorted.get(min)); | }
public static void main(String[] args) {
assert(strangeSortList((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l)))).equals((new ArrayList<Long>(Arrays.asList((long)1l, (long)4l, (long)2l, (long)3l)))));
assert(strangeSortList((new ArrayList<Long>(Arrays.asList((long)5l, (long)6l, (long)7l, (long)8l, (long)9l)))).equals((new ArrayList<Long>(Arrays.asList((long)5l, (long)9l, (long)6l, (long)8l, (long)7l)))));
assert(strangeSortList((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l, (long)5l)))).equals((new ArrayList<Long>(Arrays.asList((long)1l, (long)5l, (long)2l, (long)4l, (long)3l)))));
assert(strangeSortList((new ArrayList<Long>(Arrays.asList((long)5l, (long)6l, (long)7l, (long)8l, (long)9l, (long)1l)))).equals((new ArrayList<Long>(Arrays.asList((long)1l, (long)9l, (long)5l, (long)8l, (long)6l, (long)7l)))));
assert(strangeSortList((new ArrayList<Long>(Arrays.asList((long)5l, (long)5l, (long)5l, (long)5l)))).equals((new ArrayList<Long>(Arrays.asList((long)5l, (long)5l, (long)5l, (long)5l)))));
assert(strangeSortList((new ArrayList<Long>(Arrays.asList()))).equals((new ArrayList<Long>(Arrays.asList()))));
assert(strangeSortList((new ArrayList<Long>(Arrays.asList((long)1l, (long)2l, (long)3l, (long)4l, (long)5l, (long)6l, (long)7l, (long)8l)))).equals((new ArrayList<Long>(Arrays.asList((long)1l, (long)8l, (long)2l, (long)7l, (long)3l, (long)6l, (long)4l, (long)5l)))));
assert(strangeSortList((new ArrayList<Long>(Arrays.asList((long)0l, (long)2l, (long)2l, (long)2l, (long)5l, (long)5l, (long)-5l, (long)-5l)))).equals((new ArrayList<Long>(Arrays.asList((long)-5l, (long)5l, (long)-5l, (long)5l, (long)0l, (long)2l, (long)2l, (long)2l)))));
assert(strangeSortList((new ArrayList<Long>(Arrays.asList((long)111111l)))).equals((new ArrayList<Long>(Arrays.asList((long)111111l)))));
}
}
|
humaneval-HumanEval_154_cycpattern_check.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 {
// You are given 2 words. You need to return true if the second word or any of its rotations is a substring in the first word
// >>> cycpatternCheck(("abcd"), ("abd"))
// (false)
// >>> cycpatternCheck(("hello"), ("ell"))
// (true)
// >>> cycpatternCheck(("whassup"), ("psus"))
// (false)
// >>> cycpatternCheck(("abab"), ("baa"))
// (true)
// >>> cycpatternCheck(("efef"), ("eeff"))
// (false)
// >>> cycpatternCheck(("himenss"), ("simen"))
// (true)
public static boolean cycpatternCheck(String a, String b) {
int len = b.length();
boolean found = false;
for (int i = 0; i < len; i++) { | found = a.contains(b);
if (found) break;
}
return found;
}
} | b = b.substring(1) + b.charAt(0); | }
public static void main(String[] args) {
assert(cycpatternCheck(("xyzw"), ("xyw")) == (false));
assert(cycpatternCheck(("yello"), ("ell")) == (true));
assert(cycpatternCheck(("whattup"), ("ptut")) == (false));
assert(cycpatternCheck(("efef"), ("fee")) == (true));
assert(cycpatternCheck(("abab"), ("aabb")) == (false));
assert(cycpatternCheck(("winemtt"), ("tinem")) == (true));
}
}
|
humaneval-HumanEval_156_int_to_mini_roman.json-L29 | js | //Given a positive integer, obtain its roman numeral equivalent as a string,
// and return it in lowercase.
// Restrictions: 1 <= num <= 1000
// Examples:
// >>> int_to_mini_roman(19)
// "xix"
// >>> int_to_mini_roman(152)
// "clii"
// >>> int_to_mini_roman(426)
// "cdxxvi"
function int_to_mini_roman(number){
var roman_conversion = {
1000: "m",
900: "cm",
500: "d",
400: "cd",
100: "c",
90: "xc",
50: "l",
40: "xl",
10: "x",
9: "ix",
5: "v",
4: "iv",
1: "i"
};
var output = "";
while (number > 0){ | 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;
}
| var key_list = Object.keys(roman_conversion).map(Number); | 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_60_sum_to_n.json-L13 | 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){
| for(var i = 1; i <= n; i++){
sum += i;
}
return sum;
}
| var sum = 0; | 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_56_correct_bracketing.json-L19 | py | def correct_bracketing(brackets: str) -> bool:
""" brackets is a string of "<" and ">".
return True if every opening bracket has a corresponding closing bracket.
>>> correct_bracketing('<')
False
>>> correct_bracketing('<>')
True
>>> correct_bracketing('<<><>>')
True
>>> correct_bracketing('><<>')
False
"""
num_left_brackets = 0
for bracket in brackets:
if bracket == '<':
num_left_brackets += 1
elif bracket == '>': | if num_left_brackets < 0:
return False
return num_left_brackets == 0
| num_left_brackets -= 1 | def check(candidate):
assert candidate('<>') == True
assert candidate('<<><>>') == True
assert candidate('<><><<><>><>') == True
assert candidate('<><><<<><><>><>><<><><<>>>') == True
assert candidate('<<<><>>>>') == False
assert candidate('><<>') == False
assert candidate('<') == False
assert candidate('<<<<') == False
assert candidate('>') == False
assert candidate('<<>') == False
assert candidate('<><><<><>><>><<>') == False
assert candidate('<><><<><>><>>><>') == False
def test_check():
check(correct_bracketing)
test_check()
|
humaneval-HumanEval_19_sort_numbers.json-L12 | js | //Input is a space-delimited string of numberals from 'zero' to 'nine'.
// Valid choices are 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight' and 'nine'.
// Return the string with numbers sorted from smallest to largest
// >>> sort_numbers("three one five")
// "one three five"
function sort_numbers(numbers){
var numString = numbers.split(" ");
var numMap = {
"zero": 0,
"one": 1,
"two": 2, | "four": 4,
"five": 5,
"six": 6,
"seven": 7,
"eight": 8,
"nine": 9
};
numString.sort(function(a, b){
return numMap[a] - numMap[b];
});
numString = numString.join(" ");
return numString;
} | "three": 3, | const assert = require('node:assert');
function test() {
let candidate = sort_numbers;
assert.deepEqual(candidate(""),"");
assert.deepEqual(candidate("three"),"three");
assert.deepEqual(candidate("three five nine"),"three five nine");
assert.deepEqual(candidate("five zero four seven nine eight"),"zero four five seven eight nine");
assert.deepEqual(candidate("six five four three two one zero"),"zero one two three four five six");
}
test(); |
humaneval-HumanEval_124_valid_date.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 {
// You have to write a function which validates a given date string and
// returns true if the date is valid otherwise false.
// The date is valid if all of the following rules are satisfied:
// 1. The date string is not empty.
// 2. The number of days is not less than 1 or higher than 31 days for months 1,3,5,7,8,10,12. And the number of days is not less than 1 or higher than 30 days for months 4,6,9,11. And, the number of days is not less than 1 or higher than 29 for the month 2.
// 3. The months should not be less than 1 or higher than 12.
// 4. The date should be in the format: mm-dd-yyyy
// >>> validDate(("03-11-2000"))
// (true)
// >>> validDate(("15-01-2012"))
// (false)
// >>> validDate(("04-0-2040"))
// (false)
// >>> validDate(("06-04-2020"))
// (true)
// >>> validDate(("06/04/2020"))
// (false)
public static boolean validDate(String date) {
boolean valid_date = false;
if (date.equals("")) return valid_date;
String[] parts = date.split("-");
if (parts.length != 3) return valid_date;
try {
int month = Integer.parseInt(parts[0]);
int day = Integer.parseInt(parts[1]);
int year = Integer.parseInt(parts[2]);
if (month < 1 || month > 12) return valid_date;
if (month == 2) {
if (day < 1 || day > 29) return valid_date;
} else if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {
if (day < 1 || day > 31) return valid_date; | if (day < 1 || day > 30) return valid_date;
}
valid_date = true;
} catch (Exception e) {
valid_date = false;
}
return valid_date;
}
} | } else { | }
public static void main(String[] args) {
assert(validDate(("03-11-2000")) == (true));
assert(validDate(("15-01-2012")) == (false));
assert(validDate(("04-0-2040")) == (false));
assert(validDate(("06-04-2020")) == (true));
assert(validDate(("01-01-2007")) == (true));
assert(validDate(("03-32-2011")) == (false));
assert(validDate(("")) == (false));
assert(validDate(("04-31-3000")) == (false));
assert(validDate(("06-06-2005")) == (true));
assert(validDate(("21-31-2000")) == (false));
assert(validDate(("04-12-2003")) == (true));
assert(validDate(("04122003")) == (false));
assert(validDate(("20030412")) == (false));
assert(validDate(("2003-04")) == (false));
assert(validDate(("2003-04-12")) == (false));
assert(validDate(("04-2003")) == (false));
}
}
|
humaneval-HumanEval_18_how_many_times.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 {
// Find how many times a given substring can be found in the original string. Count overlaping cases.
// >>> howManyTimes((""), ("a"))
// (0l)
// >>> howManyTimes(("aaa"), ("a"))
// (3l)
// >>> howManyTimes(("aaaa"), ("aa"))
// (3l)
public static long howManyTimes(String string, String substring) {
long count = 0;
int index = 0; | index = string.indexOf(substring, index);
if (index != -1) {
index++;
count++;
}
}
return count;
}
} | while (index != -1) { | }
public static void main(String[] args) {
assert(howManyTimes((""), ("x")) == (0l));
assert(howManyTimes(("xyxyxyx"), ("x")) == (4l));
assert(howManyTimes(("cacacacac"), ("cac")) == (4l));
assert(howManyTimes(("john doe"), ("john")) == (1l));
}
}
|
humaneval-HumanEval_95_check_dict_case.json-L33 | js | //Given an object, return true if all keys are strings in lower
// case or all keys are strings in upper case, else return false.
// The function should return false is the given object is empty.
// Examples:
// >>> check_dict_case({"a": "apple", "b": "banana"})
// true
// >>> check_dict_case({"a": "apple", "A": "banana", "B": "banana"})
// false
// >>> check_dict_case({"a": "apple", 8: "banana", "a": "apple"})
// false
// >>> check_dict_case({"Name": "John", "Age": "36", "City": "Houston"})
// false
// >>> check_dict_case({"STATE": "NC", "ZIP": "12345"})
// true
function check_dict_case(dict){
if (Object.keys(dict).length == 0){
return false;
}
var case_type = -1;
for (let key in dict){
if (typeof key == "string"){
if (case_type == -1){
if (key == key.toUpperCase()){
case_type = 1;
}
else if (key == key.toLowerCase()){
case_type = 0;
}
else{
return false;
}
} | if (key != key.toUpperCase()){
return false;
}
}
else if (case_type == 0){
if (key != key.toLowerCase()){
return false;
}
}
}
else{
return false;
}
}
return true;
} | else if (case_type == 1){ | const assert = require('node:assert');
function test() {
let candidate = check_dict_case;
assert.deepEqual(candidate({"p": "pineapple", "b": "banana"}),true);
assert.deepEqual(candidate({"p": "pineapple", "A": "banana", "B": "banana"}),false);
assert.deepEqual(candidate({"p": "pineapple", "5": "banana", "a": "apple"}),false);
assert.deepEqual(candidate({"Name": "John", "Age": "36", "City": "Houston"}),false);
assert.deepEqual(candidate({"STATE": "NC", "ZIP": "12345"}),true);
assert.deepEqual(candidate({"fruit": "Orange", "taste": "Sweet"}),true);
assert.deepEqual(candidate({}),false);
}
test(); |
humaneval-HumanEval_115_max_fill.json-L32 | java | import java.util.*;
import java.lang.reflect.*;
import org.javatuples.*;
import java.security.*;
import java.math.*;
import java.io.*;
import java.util.stream.*;
class Problem {
// You are given a rectangular grid of wells. Each row represents a single well,
// and each 1 in a row represents a single unit of water.
// Each well has a corresponding bucket that can be used to extract water from it,
// and all buckets have the same capacity.
// Your task is to use the buckets to empty the wells.
// Output the number of times you need to lower the buckets.
// Example 1:
// >>> maxFill((new ArrayList<ArrayList<Long>>(Arrays.asList((ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)0l, (long)0l, (long)1l, (long)0l)), (ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)0l, (long)1l, (long)0l, (long)0l)), (ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)1l, (long)1l, (long)1l, (long)1l))))), (1l))
// (6l)
// Example 2:
// >>> maxFill((new ArrayList<ArrayList<Long>>(Arrays.asList((ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)0l, (long)0l, (long)1l, (long)1l)), (ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)0l, (long)0l, (long)0l, (long)0l)), (ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)1l, (long)1l, (long)1l, (long)1l)), (ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)0l, (long)1l, (long)1l, (long)1l))))), (2l))
// (5l)
// Example 3:
// >>> maxFill((new ArrayList<ArrayList<Long>>(Arrays.asList((ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)0l, (long)0l, (long)0l)), (ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)0l, (long)0l, (long)0l))))), (5l))
// (0l)
// Constraints:
// * all wells have the same length
// * 1 <= grid.length <= 10^2
// * 1 <= grid[:,1].length <= 10^2
// * grid[i][j] -> 0 | 1
// * 1 <= capacity <= 10
public static long maxFill(ArrayList<ArrayList<Long>> grid, long capacity) {
long count = 0l; | long level = 0l;
for (Long unit : well) {
if (unit == 1l) {
level += 1l;
}
}
long units = level / capacity;
if (level % capacity != 0l) {
units += 1l;
}
count += units;
}
return count;
}
} | for (ArrayList<Long> well : grid) { | }
public static void main(String[] args) {
assert(maxFill((new ArrayList<ArrayList<Long>>(Arrays.asList((ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)0l, (long)0l, (long)1l, (long)0l)), (ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)0l, (long)1l, (long)0l, (long)0l)), (ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)1l, (long)1l, (long)1l, (long)1l))))), (1l)) == (6l));
assert(maxFill((new ArrayList<ArrayList<Long>>(Arrays.asList((ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)0l, (long)0l, (long)1l, (long)1l)), (ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)0l, (long)0l, (long)0l, (long)0l)), (ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)1l, (long)1l, (long)1l, (long)1l)), (ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)0l, (long)1l, (long)1l, (long)1l))))), (2l)) == (5l));
assert(maxFill((new ArrayList<ArrayList<Long>>(Arrays.asList((ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)0l, (long)0l, (long)0l)), (ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)0l, (long)0l, (long)0l))))), (5l)) == (0l));
assert(maxFill((new ArrayList<ArrayList<Long>>(Arrays.asList((ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)1l, (long)1l, (long)1l, (long)1l)), (ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)1l, (long)1l, (long)1l, (long)1l))))), (2l)) == (4l));
assert(maxFill((new ArrayList<ArrayList<Long>>(Arrays.asList((ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)1l, (long)1l, (long)1l, (long)1l)), (ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)1l, (long)1l, (long)1l, (long)1l))))), (9l)) == (2l));
}
}
|
humaneval-HumanEval_119_match_parens.json-L29 | py | from typing import List
def match_parens(lst: List[str]) -> str:
"""
You are given a list of two strings, both strings consist of open
parentheses '(' or close parentheses ')' only.
Your job is to check if it is possible to concatenate the two strings in
some order, that the resulting string will be good.
A string S is considered to be good if and only if all parentheses in S
are balanced. For example: the string '(())()' is good, while the string
'())' is not.
Return 'Yes' if there's a way to make a good string, and return 'No' otherwise.
Examples:
>>> match_parens(['()(', ')'])
'Yes'
>>> match_parens([')', ')'])
'No'
"""
s1, s2 = lst
strings = [s1 + s2, s2 + s1]
for s in strings:
open_parens = 0
close_parens = 0
for c in s:
if c == '(':
open_parens += 1
elif c == ')': | open_parens -= 1
else:
close_parens += 1
if open_parens == 0 and close_parens == 0:
return 'Yes'
return 'No'
| if open_parens: | def check(candidate):
assert candidate(['()(', ')']) == 'Yes'
assert candidate([')', ')']) == 'No'
assert candidate(['(()(())', '())())']) == 'No'
assert candidate([')())', '(()()(']) == 'Yes'
assert candidate(['(())))', '(()())((']) == 'Yes'
assert candidate(['()', '())']) == 'No'
assert candidate(['(()(', '()))()']) == 'Yes'
assert candidate(['((((', '((())']) == 'No'
assert candidate([')(()', '(()(']) == 'No'
assert candidate([')(', ')(']) == 'No'
assert candidate(['(', ')']) == 'Yes'
assert candidate([')', '(']) == 'Yes'
def test_check():
check(match_parens)
test_check()
|
humaneval-HumanEval_115_max_fill.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 {
// You are given a rectangular grid of wells. Each row represents a single well,
// and each 1 in a row represents a single unit of water.
// Each well has a corresponding bucket that can be used to extract water from it,
// and all buckets have the same capacity.
// Your task is to use the buckets to empty the wells.
// Output the number of times you need to lower the buckets.
// Example 1:
// >>> maxFill((new ArrayList<ArrayList<Long>>(Arrays.asList((ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)0l, (long)0l, (long)1l, (long)0l)), (ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)0l, (long)1l, (long)0l, (long)0l)), (ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)1l, (long)1l, (long)1l, (long)1l))))), (1l))
// (6l)
// Example 2:
// >>> maxFill((new ArrayList<ArrayList<Long>>(Arrays.asList((ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)0l, (long)0l, (long)1l, (long)1l)), (ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)0l, (long)0l, (long)0l, (long)0l)), (ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)1l, (long)1l, (long)1l, (long)1l)), (ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)0l, (long)1l, (long)1l, (long)1l))))), (2l))
// (5l)
// Example 3:
// >>> maxFill((new ArrayList<ArrayList<Long>>(Arrays.asList((ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)0l, (long)0l, (long)0l)), (ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)0l, (long)0l, (long)0l))))), (5l))
// (0l)
// Constraints:
// * all wells have the same length
// * 1 <= grid.length <= 10^2
// * 1 <= grid[:,1].length <= 10^2
// * grid[i][j] -> 0 | 1
// * 1 <= capacity <= 10
public static long maxFill(ArrayList<ArrayList<Long>> grid, long capacity) {
long count = 0l;
for (ArrayList<Long> well : grid) {
long level = 0l;
for (Long unit : well) {
if (unit == 1l) {
level += 1l;
} | long units = level / capacity;
if (level % capacity != 0l) {
units += 1l;
}
count += units;
}
return count;
}
} | } | }
public static void main(String[] args) {
assert(maxFill((new ArrayList<ArrayList<Long>>(Arrays.asList((ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)0l, (long)0l, (long)1l, (long)0l)), (ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)0l, (long)1l, (long)0l, (long)0l)), (ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)1l, (long)1l, (long)1l, (long)1l))))), (1l)) == (6l));
assert(maxFill((new ArrayList<ArrayList<Long>>(Arrays.asList((ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)0l, (long)0l, (long)1l, (long)1l)), (ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)0l, (long)0l, (long)0l, (long)0l)), (ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)1l, (long)1l, (long)1l, (long)1l)), (ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)0l, (long)1l, (long)1l, (long)1l))))), (2l)) == (5l));
assert(maxFill((new ArrayList<ArrayList<Long>>(Arrays.asList((ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)0l, (long)0l, (long)0l)), (ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)0l, (long)0l, (long)0l))))), (5l)) == (0l));
assert(maxFill((new ArrayList<ArrayList<Long>>(Arrays.asList((ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)1l, (long)1l, (long)1l, (long)1l)), (ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)1l, (long)1l, (long)1l, (long)1l))))), (2l)) == (4l));
assert(maxFill((new ArrayList<ArrayList<Long>>(Arrays.asList((ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)1l, (long)1l, (long)1l, (long)1l)), (ArrayList<Long>)new ArrayList<Long>(Arrays.asList((long)1l, (long)1l, (long)1l, (long)1l))))), (9l)) == (2l));
}
}
|
humaneval-HumanEval_1_separate_paren_groups.json-L22 | js | //Input to this function is a string containing multiple groups of nested parentheses. Your goal is to
// separate those group into separate strings and return the array of those.
// Separate groups are balanced (each open brace is properly closed) and not nested within each other
// Ignore any spaces in the input string.
// >>> separate_paren_groups("( ) (( )) (( )( ))")
// ["()", "(())", "(()())"]
function separate_paren_groups(paren_string){
var count = 0;
var group = '';
var groups = [];
for (var i = 0; i < paren_string.length; i++){
if (paren_string[i] === '('){
count++;
group += paren_string[i];
} else if (paren_string[i] === ')'){
count--;
group += paren_string[i];
}
if (count === 0 && group){
groups.push(group);
group = ''; | }
return groups;
}
| } | const assert = require('node:assert');
function test() {
let candidate = separate_paren_groups;
assert.deepEqual(candidate("(()()) ((())) () ((())()())"),["(()())", "((()))", "()", "((())()())"]);
assert.deepEqual(candidate("() (()) ((())) (((())))"),["()", "(())", "((()))", "(((())))"]);
assert.deepEqual(candidate("(()(())((())))"),["(()(())((())))"]);
assert.deepEqual(candidate("( ) (( )) (( )( ))"),["()", "(())", "(()())"]);
}
test(); |
humaneval-HumanEval_105_by_length.json-L21 | 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.reverse();
var arr3 = [];
for(var i = 0; i < arr2.length; i++){
var num = arr2[i];
if(num == 1){
arr3.push("One");
}
else if(num == 2){
arr3.push("Two");
}
else if(num == 3){
arr3.push("Three");
}
else if(num == 4){
arr3.push("Four");
}
else if(num == 5){
arr3.push("Five");
}
else if(num == 6){
arr3.push("Six");
}
else if(num == 7){
arr3.push("Seven");
}
else if(num == 8){
arr3.push("Eight");
}
else if(num == 9){
arr3.push("Nine");
}
}
return arr3;
} | arr2.sort(); | 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_10_make_palindrome.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 {
// 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(); | if (string.substring(index).equals(reverse.substring(0, string.length() - index))) {
newString.append(reverse.substring(string.length() - index));
break;
}
}
return newString.toString();
}
} | for (int index = 0; index < string.length(); index++) { | }
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_3_below_zero.json-L14 | 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 true; | }
return false;
}
| } | 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(); |
humaneval-HumanEval_58_common.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 {
// Return sorted unique common elements for two array lists.
// >>> common((new ArrayList<Long>(Arrays.asList((long)1l, (long)4l, (long)3l, (long)34l, (long)653l, (long)2l, (long)5l))), (new ArrayList<Long>(Arrays.asList((long)5l, (long)7l, (long)1l, (long)5l, (long)9l, (long)653l, (long)121l))))
// (new ArrayList<Long>(Arrays.asList((long)1l, (long)5l, (long)653l)))
// >>> common((new ArrayList<Long>(Arrays.asList((long)5l, (long)3l, (long)2l, (long)8l))), (new ArrayList<Long>(Arrays.asList((long)3l, (long)2l))))
// (new ArrayList<Long>(Arrays.asList((long)2l, (long)3l)))
public static ArrayList<Long> common(ArrayList<Long> l1, ArrayList<Long> l2) {
| l1.stream()
.filter(l2::contains)
.collect(Collectors.toSet())
);
}
} | return new ArrayList<Long>( | }
public static void main(String[] args) {
assert(common((new ArrayList<Long>(Arrays.asList((long)1l, (long)4l, (long)3l, (long)34l, (long)653l, (long)2l, (long)5l))), (new ArrayList<Long>(Arrays.asList((long)5l, (long)7l, (long)1l, (long)5l, (long)9l, (long)653l, (long)121l)))).equals((new ArrayList<Long>(Arrays.asList((long)1l, (long)5l, (long)653l)))));
assert(common((new ArrayList<Long>(Arrays.asList((long)5l, (long)3l, (long)2l, (long)8l))), (new ArrayList<Long>(Arrays.asList((long)3l, (long)2l)))).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)3l)))));
assert(common((new ArrayList<Long>(Arrays.asList((long)4l, (long)3l, (long)2l, (long)8l))), (new ArrayList<Long>(Arrays.asList((long)3l, (long)2l, (long)4l)))).equals((new ArrayList<Long>(Arrays.asList((long)2l, (long)3l, (long)4l)))));
assert(common((new ArrayList<Long>(Arrays.asList((long)4l, (long)3l, (long)2l, (long)8l))), (new ArrayList<Long>(Arrays.asList()))).equals((new ArrayList<Long>(Arrays.asList()))));
}
}
|
humaneval-HumanEval_156_int_to_mini_roman.json-L33 | java | import java.util.*;
import java.lang.reflect.*;
import org.javatuples.*;
import java.security.*;
import java.math.*;
import java.io.*;
import java.util.stream.*;
class Problem {
// 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) { | 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;
}
} | res += "d"; | }
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_104_unique_digits.json-L32 | java | import java.util.*;
import java.lang.reflect.*;
import org.javatuples.*;
import java.security.*;
import java.math.*;
import java.io.*;
import java.util.stream.*;
class Problem {
// Given an array array list 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_148_bf.json-L28 | py | from typing import Tuple
def bf(planet1: str, planet2: str) -> Tuple[str, ...]:
"""
There are eight planets in our solar system: the closerst to the Sun
is Mercury, the next one is Venus, then Earth, Mars, Jupiter, Saturn,
Uranus, Neptune.
Write a function that takes two planet names as strings planet1 and planet2.
The function should return a tuple containing all planets whose orbits are
located between the orbit of planet1 and the orbit of planet2, sorted by
the proximity to the sun.
The function should return an empty tuple if planet1 or planet2
are not correct planet names.
Examples
>>> bf('Jupiter', 'Neptune')
('Saturn', 'Uranus')
>>> bf('Earth', 'Mercury')
'Venus'
>>> bf('Mercury', 'Uranus')
('Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn')
"""
planets = ('Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune')
if planet1 not in planets or planet2 not in planets:
return ()
start = planets.index(planet1)
end = planets.index(planet2)
if start < end: | else:
planets = planets[end+1:start]
return tuple(planets) | planets = planets[start+1:end] | def check(candidate):
assert candidate('Jupiter', 'Neptune') == ('Saturn', 'Uranus')
assert candidate('Earth', 'Mercury') == ('Venus',)
assert candidate('Mercury', 'Uranus') == ('Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn')
assert candidate('Neptune', 'Venus') == ('Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus')
assert candidate('Earth', 'Earth') == ()
assert candidate('Mars', 'Earth') == ()
assert candidate('Jupiter', 'Makemake') == ()
def test_check():
check(bf)
test_check()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.