prompt
stringlengths 96
1.46k
| canonical_solution
stringlengths 16
1.4k
| lang
stringclasses 5
values | source
stringclasses 1
value |
---|---|---|---|
import (
"math"
)
// Check if in given list of numbers, are any two numbers closer to each other than given threshold.
// >>> HasCloseElements([]float64{1.0, 2.0, 3.0}, 0.5)
// false
// >>> HasCloseElements([]float64{1.0, 2.8, 3.0, 4.0, 5.0, 2.0}, 0.3)
// true
func HasCloseElements(numbers []float64, threshold float64) bool {
| for i := 0; i < len(numbers); i++ {
for j := i + 1; j < len(numbers); j++ {
var distance float64 = math.Abs(numbers[i] - numbers[j])
if distance < threshold {
return true
}
}
}
return false
}
| go | THUDM/humaneval-x |
// Input to this function is a string containing multiple groups of nested parentheses. Your goal is to
// separate those group into separate strings and return the list of those.
// Separate groups are balanced (each open brace is properly closed) and not nested within each other
// Ignore any spaces in the input string.
// >>> SeparateParenGroups('( ) (( )) (( )( ))')
// ['()', '(())', '(()())']
func SeparateParenGroups(paren_string string) []string {
| result := make([]string, 0)
current_string := make([]rune, 0)
current_depth := 0
for _, c := range paren_string {
if c == '(' {
current_depth += 1
current_string = append(current_string, c)
}else if c== ')'{
current_depth -= 1
current_string = append(current_string, c)
if current_depth == 0{
result = append(result, string(current_string))
current_string = make([]rune, 0)
}
}
}
return result
}
| go | THUDM/humaneval-x |
import (
"math"
)
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
//
// Return the decimal part of the number.
// >>> TruncateNumber(3.5)
// 0.5
func TruncateNumber(number float64) float64 {
| return math.Mod(number,1)
}
| go | THUDM/humaneval-x |
// 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.
// >>> BelowZero([1, 2, 3])
// false
// >>> BelowZero([1, 2, -4, 5])
// true
func BelowZero(operations []int) bool {
| balance := 0
for _, op := range operations {
balance += op
if balance < 0 {
return true
}
}
return false
}
| go | THUDM/humaneval-x |
import (
"math"
)
// For a given list of input numbers, calculate Mean Absolute Deviation
// around the mean of this dataset.
// Mean Absolute Deviation is the average absolute difference between each
// element and a centerpoint (mean in this case):
// MAD = average | x - x_mean |
// >>> MeanAbsoluteDeviation([1.0, 2.0, 3.0, 4.0])
// 1.0
func MeanAbsoluteDeviation(numbers []float64) float64 {
| sum := func(numbers []float64) float64 {
sum := 0.0
for _, num := range numbers {
sum += num
}
return sum
}
mean := sum(numbers) / float64(len(numbers))
numList := make([]float64, 0)
for _, x := range numbers {
numList = append(numList, math.Abs(x-mean))
}
return sum(numList) / float64(len(numbers))
}
| go | THUDM/humaneval-x |
// Insert a number 'delimeter' between every two consecutive elements of input list `numbers'
// >>> Intersperse([], 4)
// []
// >>> Intersperse([1, 2, 3], 4)
// [1, 4, 2, 4, 3]
func Intersperse(numbers []int, delimeter int) []int {
| result := make([]int, 0)
if len(numbers) == 0 {
return result
}
for i := 0; i < len(numbers)-1; i++ {
n := numbers[i]
result = append(result, n)
result = append(result, delimeter)
}
result = append(result, numbers[len(numbers)-1])
return result
}
| go | THUDM/humaneval-x |
import (
"math"
"strings"
)
// Input to this function is a string represented multiple groups for nested parentheses separated by spaces.
// For each of the group, output the deepest level of nesting of parentheses.
// E.g. (()()) has maximum two levels of nesting while ((())) has three.
//
// >>> ParseNestedParens('(()()) ((())) () ((())()())')
// [2, 3, 1, 3]
func ParseNestedParens(paren_string string) []int {
| parse_paren_group := func(s string) int {
depth := 0
max_depth := 0
for _, c := range s {
if c == '(' {
depth += 1
max_depth = int(math.Max(float64(depth), float64(max_depth)))
} else {
depth -= 1
}
}
return max_depth
}
result := make([]int, 0)
for _, x := range strings.Split(paren_string, " ") {
result = append(result, parse_paren_group(x))
}
return result
}
| go | THUDM/humaneval-x |
import (
"strings"
)
// Filter an input list of strings only for ones that contain given substring
// >>> FilterBySubstring([], 'a')
// []
// >>> FilterBySubstring(['abc', 'bacd', 'cde', 'array'], 'a')
// ['abc', 'bacd', 'array']
func FilterBySubstring(stringList []string, substring string) []string {
| result := make([]string, 0)
for _, x := range stringList {
if strings.Index(x, substring) != -1 {
result = append(result, x)
}
}
return result
}
| go | THUDM/humaneval-x |
// For a given list of integers, return a tuple consisting of a sum and a product of all the integers in a list.
// Empty sum should be equal to 0 and empty product should be equal to 1.
// >>> SumProduct([])
// (0, 1)
// >>> SumProduct([1, 2, 3, 4])
// (10, 24)
func SumProduct(numbers []int) [2]int {
| sum_value := 0
prod_value := 1
for _, n := range numbers {
sum_value += n
prod_value *= n
}
return [2]int{sum_value, prod_value}
}
| go | THUDM/humaneval-x |
import (
"math"
)
// From a given list of integers, generate a list of rolling maximum element found until given moment
// in the sequence.
// >>> RollingMax([1, 2, 3, 2, 3, 4, 2])
// [1, 2, 3, 3, 3, 4, 4]
func RollingMax(numbers []int) []int {
| running_max := math.MinInt32
result := make([]int, 0)
for _, n := range numbers {
if running_max == math.MinInt32 {
running_max = n
} else {
running_max = int(math.Max(float64(running_max), float64(n)))
}
result = append(result, running_max)
}
return result
}
| go | THUDM/humaneval-x |
import (
"strings"
)
// Test if given string is a palindrome.
func IsPalindrome(str string) bool {
runes := []rune(str)
result := make([]rune, 0)
for i := len(runes) - 1; i >= 0; i-- {
result = append(result, runes[i])
}
return str == string(result)
}
// 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'
func MakePalindrome(str string) string {
| if strings.TrimSpace(str) == "" {
return ""
}
beginning_of_suffix := 0
runes := []rune(str)
for !IsPalindrome(string(runes[beginning_of_suffix:])) {
beginning_of_suffix += 1
}
result := make([]rune, 0)
for i := len(str[:beginning_of_suffix]) - 1; i >= 0; i-- {
result = append(result, runes[i])
}
return str + string(result)
}
| go | THUDM/humaneval-x |
import (
"fmt"
)
// Input are two strings a and b consisting only of 1s and 0s.
// Perform binary XOR on these inputs and return result also as a string.
// >>> StringXor('010', '110')
// '100'
func StringXor(a string, b string) string {
| s2b := func(bs string) int32 {
result := int32(0)
runes := []rune(bs)
for _, r := range runes {
result = result << 1
temp := r - rune('0')
result += temp
}
return result
}
ab := s2b(a)
bb := s2b(b)
res := ab ^ bb
sprint := fmt.Sprintf("%b", res)
for i := 0; i < len(a)-len(sprint); i++ {
sprint = "0" + sprint
}
return sprint
}
| go | THUDM/humaneval-x |
// Out of list of strings, return the Longest one. Return the first one in case of multiple
// strings of the same length. Return nil in case the input list is empty.
// >>> Longest([])
// nil
// >>> Longest(['a', 'b', 'c'])
// 'a'
// >>> Longest(['a', 'bb', 'ccc'])
// 'ccc'
func Longest(strings []string) interface{}{
| if strings == nil || len(strings) == 0 {
return nil
}
maxlen := 0
maxi := 0
for i, s := range strings {
if maxlen < len(s) {
maxlen = len(s)
maxi = i
}
}
return strings[maxi]
}
| go | THUDM/humaneval-x |
// Return a greatest common divisor of two integers a and b
// >>> GreatestCommonDivisor(3, 5)
// 1
// >>> GreatestCommonDivisor(25, 15)
// 5
func GreatestCommonDivisor(a int,b int) int{
| if b < 2 {
return b
}
var gcd int = 1
for i := 2; i < b; i++ {
if a%i == 0 && b%i == 0 {
gcd = i
}
}
return gcd
}
| go | THUDM/humaneval-x |
// Return list of all prefixes from shortest to longest of the input string
// >>> AllPrefixes('abc')
// ['a', 'ab', 'abc']
func AllPrefixes(str string) []string{
| prefixes := make([]string, 0, len(str))
for i := 0; i < len(str); i++ {
prefixes = append(prefixes, str[:i+1])
}
return prefixes
}
| go | THUDM/humaneval-x |
import (
"strconv"
)
// Return a string containing space-delimited numbers starting from 0 upto n inclusive.
// >>> StringSequence(0)
// '0'
// >>> StringSequence(5)
// '0 1 2 3 4 5'
func StringSequence(n int) string{
| var seq string
for i := 0; i <= n; i++ {
seq += strconv.Itoa(i)
if i != n {
seq += " "
}
}
return seq
}
| go | THUDM/humaneval-x |
import (
"strings"
)
// Given a string, find out how many distinct characters (regardless of case) does it consist of
// >>> CountDistinctCharacters('xyzXYZ')
// 3
// >>> CountDistinctCharacters('Jerry')
// 4
func CountDistinctCharacters(str string) int{
| lower := strings.ToLower(str)
count := 0
set := make(map[rune]bool)
for _, i := range lower {
if set[i] == true {
continue
} else {
set[i] = true
count++
}
}
return count
}
| go | THUDM/humaneval-x |
// Input to this function is a string representing musical notes in a special ASCII format.
// Your task is to parse this string and return 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')
// [4, 2, 1, 2, 2, 1, 1, 1, 1, 4, 4]
func ParseMusic(music_string string) []int{
| note_map := map[string]int{"o": 4, "o|": 2, ".|": 1}
split := strings.Split(music_string, " ")
result := make([]int, 0)
for _, x := range split {
if i, ok := note_map[x]; ok {
result = append(result, i)
}
}
return result
}
| go | THUDM/humaneval-x |
// Find how many times a given substring can be found in the original string. Count overlaping cases.
// >>> HowManyTimes('', 'a')
// 0
// >>> HowManyTimes('aaa', 'a')
// 3
// >>> HowManyTimes('aaaa', 'aa')
// 3
func HowManyTimes(str string,substring string) int{
| times := 0
for i := 0; i < (len(str) - len(substring) + 1); i++ {
if str[i:i+len(substring)] == substring {
times += 1
}
}
return times
}
| go | THUDM/humaneval-x |
import (
"sort"
"strings"
)
// 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
// >>> SortNumbers('three one five')
// 'one three five'
func SortNumbers(numbers string) string{
| valueMap := map[string]int{
"zero": 0,
"one": 1,
"two": 2,
"three": 3,
"four": 4,
"five": 5,
"six": 6,
"seven": 7,
"eight": 8,
"nine": 9,
}
stringMap := make(map[int]string)
for s, i := range valueMap {
stringMap[i] = s
}
split := strings.Split(numbers, " ")
temp := make([]int, 0)
for _, s := range split {
if i, ok := valueMap[s]; ok {
temp = append(temp, i)
}
}
sort.Ints(temp)
result := make([]string, 0)
for _, i := range temp {
result = append(result, stringMap[i])
}
return strings.Join(result, " ")
}
| go | THUDM/humaneval-x |
// From a supplied list of numbers (of length at least two) select and return two that are the closest to each
// other and return them in order (smaller number, larger number).
// >>> FindClosestElements([1.0, 2.0, 3.0, 4.0, 5.0, 2.2])
// (2.0, 2.2)
// >>> FindClosestElements([1.0, 2.0, 3.0, 4.0, 5.0, 2.0])
// (2.0, 2.0)
func FindClosestElements(numbers []float64) [2]float64 {
| distance := math.MaxFloat64
var closestPair [2]float64
for idx, elem := range numbers {
for idx2, elem2 := range numbers {
if idx != idx2 {
if distance == math.MinInt64 {
distance = math.Abs(elem - elem2)
float64s := []float64{elem, elem2}
sort.Float64s(float64s)
closestPair = [2]float64{float64s[0], float64s[1]}
} else {
newDistance := math.Abs(elem - elem2)
if newDistance < distance{
distance = newDistance
float64s := []float64{elem, elem2}
sort.Float64s(float64s)
closestPair = [2]float64{float64s[0], float64s[1]}
}
}
}
}
}
return closestPair
}
| go | THUDM/humaneval-x |
// Given list of numbers (of at least two elements), apply a linear transform to that list,
// such that the smallest number will become 0 and the largest will become 1
// >>> RescaleToUnit([1.0, 2.0, 3.0, 4.0, 5.0])
// [0.0, 0.25, 0.5, 0.75, 1.0]
func RescaleToUnit(numbers []float64) []float64 {
| smallest := numbers[0]
largest := smallest
for _, n := range numbers {
if smallest > n {
smallest = n
}
if largest < n {
largest = n
}
}
if smallest == largest {
return numbers
}
for i, n := range numbers {
numbers[i] = (n - smallest) / (largest - smallest)
}
return numbers
}
| go | THUDM/humaneval-x |
// Filter given list of any values only for integers
// >>> FilterIntegers(['a', 3.14, 5])
// [5]
// >>> FilterIntegers([1, 2, 3, 'abc', {}, []])
// [1, 2, 3]
func FilterIntegers(values []interface{}) []int {
| result := make([]int, 0)
for _, val := range values {
switch i := val.(type) {
case int:
result = append(result, i)
}
}
return result
}
| go | THUDM/humaneval-x |
// Return length of given string
// >>> Strlen('')
// 0
// >>> Strlen('abc')
// 3
func Strlen(str string) int {
| return len(str)
}
| go | THUDM/humaneval-x |
// For a given number n, find the largest number that divides n evenly, smaller than n
// >>> LargestDivisor(15)
// 5
func LargestDivisor(n int) int {
| for i := n - 1; i > 0; i-- {
if n % i == 0 {
return i
}
}
return 0
}
| go | THUDM/humaneval-x |
import (
"math"
)
// Return list of prime factors of given integer in the order from smallest to largest.
// Each of the factors should be listed number of times corresponding to how many times it appeares in factorization.
// Input number should be equal to the product of all factors
// >>> Factorize(8)
// [2, 2, 2]
// >>> Factorize(25)
// [5, 5]
// >>> Factorize(70)
// [2, 5, 7]
func Factorize(n int) []int {
| fact := make([]int, 0)
for i := 2; i <= int(math.Sqrt(float64(n))+1); {
if n%i == 0 {
fact = append(fact, i)
n = n / i
} else {
i++
}
}
if n > 1 {
fact = append(fact, n)
}
return fact
}
| go | THUDM/humaneval-x |
// From a list of integers, remove all elements that occur more than once.
// Keep order of elements left the same as in the input.
// >>> RemoveDuplicates([1, 2, 3, 2, 4])
// [1, 3, 4]
func RemoveDuplicates(numbers []int) []int {
| c := make(map[int] int)
for _, number := range numbers {
if i, ok := c[number]; ok {
c[number] = i + 1
} else {
c[number] = 1
}
}
result := make([]int, 0)
for _, number := range numbers {
if c[number] <= 1 {
result = append(result, number)
}
}
return result
}
| go | THUDM/humaneval-x |
import (
"strings"
)
// For a given string, flip lowercase characters to uppercase and uppercase to lowercase.
// >>> FlipCase('Hello')
// 'hELLO'
func FlipCase(str string) string {
| result := []rune{}
for _, c := range str {
if c >= 'A' && c <= 'Z' {
result = append(result, 'a' + ((c - 'A' + 26) % 26))
} else if c >= 'a' && c <= 'z' {
result = append(result, 'A' + ((c - 'a' + 26) % 26))
} else {
result = append(result, c)
}
}
return string(result)
}
| go | THUDM/humaneval-x |
// Concatenate list of strings into a single string
// >>> Concatenate([])
// ''
// >>> Concatenate(['a', 'b', 'c'])
// 'abc'
func Concatenate(strings []string) string {
| if len(strings) == 0 {
return ""
}
return strings[0] + Concatenate(strings[1:])
}
| go | THUDM/humaneval-x |
// Filter an input list of strings only for ones that start with a given prefix.
// >>> FilterByPrefix([], 'a')
// []
// >>> FilterByPrefix(['abc', 'bcd', 'cde', 'array'], 'a')
// ['abc', 'array']
func FilterByPrefix(strings []string,prefix string) []string {
| if len(strings) == 0 {
return []string{}
}
res := make([]string, 0, len(strings))
for _, s := range strings {
if s[:len(prefix)] == prefix {
res = append(res, s)
}
}
return res
}
| go | THUDM/humaneval-x |
// Return only positive numbers in the list.
// >>> GetPositive([-1, 2, -4, 5, 6])
// [2, 5, 6]
// >>> GetPositive([5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10])
// [5, 3, 2, 3, 9, 123, 1]
func GetPositive(l []int) []int {
| res := make([]int, 0)
for _, x := range l {
if x > 0 {
res = append(res, x)
}
}
return res
}
| go | THUDM/humaneval-x |
// Return true if a given number is prime, and false otherwise.
// >>> IsPrime(6)
// false
// >>> IsPrime(101)
// true
// >>> IsPrime(11)
// true
// >>> IsPrime(13441)
// true
// >>> IsPrime(61)
// true
// >>> IsPrime(4)
// false
// >>> IsPrime(1)
// false
func IsPrime(n int) bool {
| if n <= 1 {
return false
}
if n == 2 {
return true
}
if n%2 == 0 {
return false
}
for i := 3; i*i <= n; i += 2 {
if n%i == 0 {
return false
}
}
return true
}
| go | THUDM/humaneval-x |
import (
"math"
)
// Evaluates polynomial with coefficients xs at point x.
// return xs[0] + xs[1] * x + xs[1] * x^2 + .... xs[n] * x^n
func Poly(xs []int, x float64) float64{
sum := 0.0
for i, coeff := range xs {
sum += float64(coeff) * math.Pow(x,float64(i))
}
return sum
}
// xs are coefficients of a polynomial.
// FindZero find x such that Poly(x) = 0.
// FindZero returns only only zero point, even if there are many.
// Moreover, FindZero only takes list xs having even number of coefficients
// and largest non zero coefficient as it guarantees
// a solution.
// >>> round(FindZero([1, 2]), 2) # f(x) = 1 + 2x
// -0.5
// >>> round(FindZero([-6, 11, -6, 1]), 2) # (x - 1) * (x - 2) * (x - 3) = -6 + 11x - 6x^2 + x^3
// 1.0
func FindZero(xs []int) float64 {
| begin := -1.0
end := 1.0
for Poly(xs, begin)*Poly(xs, end) > 0 {
begin *= 2
end *= 2
}
for end-begin > 1e-10 {
center := (begin + end) / 2
if Poly(xs, center)*Poly(xs, begin) > 0 {
begin = center
} else {
end = center
}
}
return begin
}
| go | THUDM/humaneval-x |
import (
"sort"
)
// This function takes a list l and returns a list l' such that
// l' is identical to l in the indicies that are not divisible by three, while its values at the indicies that are divisible by three are equal
// to the values of the corresponding indicies of l, but sorted.
// >>> SortThird([1, 2, 3])
// [1, 2, 3]
// >>> SortThird([5, 6, 3, 4, 8, 9, 2])
// [2, 6, 3, 4, 8, 9, 5]
func SortThird(l []int) []int {
| temp := make([]int, 0)
for i := 0; i < len(l); i = i + 3 {
temp = append(temp, l[i])
}
sort.Ints(temp)
j := 0
for i := 0; i < len(l); i = i + 3 {
l[i] = temp[j]
j++
}
return l
}
| go | THUDM/humaneval-x |
import (
"sort"
)
// Return sorted Unique elements in a list
// >>> Unique([5, 3, 5, 2, 3, 3, 9, 0, 123])
// [0, 2, 3, 5, 9, 123]
func Unique(l []int) []int {
| set := make(map[int]interface{})
for _, i := range l {
set[i]=nil
}
l = make([]int,0)
for i, _ := range set {
l = append(l, i)
}
sort.Ints(l)
return l
}
| go | THUDM/humaneval-x |
// Return maximum element in the list.
// >>> MaxElement([1, 2, 3])
// 3
// >>> MaxElement([5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10])
// 123
func MaxElement(l []int) int {
| max := l[0]
for _, x := range l {
if x > max {
max = x
}
}
return max
}
| go | THUDM/humaneval-x |
import (
"strconv"
"strings"
)
// Return the number of times the digit 7 appears in integers less than n which are divisible by 11 or 13.
// >>> FizzBuzz(50)
// 0
// >>> FizzBuzz(78)
// 2
// >>> FizzBuzz(79)
// 3
func FizzBuzz(n int) int {
| ns := make([]int, 0)
for i := 0; i < n; i++ {
if i%11 == 0 || i%13 == 0 {
ns = append(ns, i)
}
}
temp := make([]string, 0)
for _, i := range ns {
temp = append(temp, strconv.Itoa(i))
}
join := strings.Join(temp, "")
ans := 0
for _, c := range join {
if c == '7' {
ans++
}
}
return ans
}
| go | THUDM/humaneval-x |
import (
"sort"
)
// This function takes a list l and returns a list l' such that
// l' is identical to l in the odd indicies, while its values at the even indicies are equal
// to the values of the even indicies of l, but sorted.
// >>> SortEven([1, 2, 3])
// [1, 2, 3]
// >>> SortEven([5, 6, 3, 4])
// [3, 6, 5, 4]
func SortEven(l []int) []int {
| evens := make([]int, 0)
for i := 0; i < len(l); i += 2 {
evens = append(evens, l[i])
}
sort.Ints(evens)
j := 0
for i := 0; i < len(l); i += 2 {
l[i] = evens[j]
j++
}
return l
}
| go | THUDM/humaneval-x |
import (
"math"
"strings"
"time"
)
// returns encoded string by cycling groups of three characters.
func EncodeCyclic(s string) string {
groups := make([]string, 0)
for i := 0; i < ((len(s) + 2) / 3); i++ {
groups = append(groups, s[3*i:int(math.Min(float64(3*i+3), float64(len(s))))])
}
newGroups := make([]string, 0)
for _, group := range groups {
runes := []rune(group)
if len(group) == 3 {
newGroups = append(newGroups, string(append(runes[1:], runes[0])))
} else {
newGroups = append(newGroups, group)
}
}
return strings.Join(newGroups, "")
}
// takes as input string encoded with EncodeCyclic function. Returns decoded string.
func DecodeCyclic(s string) string {
| return EncodeCyclic(EncodeCyclic(s))
}
| go | THUDM/humaneval-x |
import (
"math"
)
// PrimeFib returns n-th number that is a Fibonacci number and it's also prime.
// >>> PrimeFib(1)
// 2
// >>> PrimeFib(2)
// 3
// >>> PrimeFib(3)
// 5
// >>> PrimeFib(4)
// 13
// >>> PrimeFib(5)
// 89
func PrimeFib(n int) int {
| isPrime := func(p int) bool {
if p < 2 {
return false
}
for i := 2; i < int(math.Min(math.Sqrt(float64(p))+1, float64(p-1))); i++ {
if p%i == 0 {
return false
}
}
return true
}
f := []int{0, 1}
for {
f = append(f, f[len(f)-1]+f[len(f)-2])
if isPrime(f[len(f)-1]) {
n -= 1
}
if n == 0 {
return f[len(f)-1]
}
}
}
| go | THUDM/humaneval-x |
// TriplesSumToZero takes a list of integers as an input.
// it returns true if there are three distinct elements in the list that
// sum to zero, and false otherwise.
//
// >>> TriplesSumToZero([1, 3, 5, 0])
// false
// >>> TriplesSumToZero([1, 3, -2, 1])
// true
// >>> TriplesSumToZero([1, 2, 3, 7])
// false
// >>> TriplesSumToZero([2, 4, -5, 3, 9, 7])
// true
// >>> TriplesSumToZero([1])
// false
func TriplesSumToZero(l []int) bool {
| for i := 0; i < len(l) - 2; i++ {
for j := i + 1; j < len(l) - 1; j++ {
for k := j + 1; k < len(l); k++ {
if l[i] + l[j] + l[k] == 0 {
return true
}
}
}
}
return false
}
| go | THUDM/humaneval-x |
// Imagine a road that's a perfectly straight infinitely long line.
// n cars are driving left to right; simultaneously, a different set of n cars
// are driving right to left. The two sets of cars start out being very far from
// each other. All cars move in the same speed. Two cars are said to collide
// when a car that's moving left to right hits a car that's moving right to left.
// However, the cars are infinitely sturdy and strong; as a result, they continue moving
// in their trajectory as if they did not collide.
//
// This function outputs the number of such collisions.
func CarRaceCollision(n int) int {
| return n * n
}
| go | THUDM/humaneval-x |
// Return list with elements incremented by 1.
// >>> IncrList([1, 2, 3])
// [2, 3, 4]
// >>> IncrList([5, 3, 5, 2, 3, 3, 9, 0, 123])
// [6, 4, 6, 3, 4, 4, 10, 1, 124]
func IncrList(l []int) []int {
| n := len(l)
for i := 0; i < n; i++ {
l[i]++
}
return l
}
| go | THUDM/humaneval-x |
// PairsSumToZero takes a list of integers as an input.
// it returns true if there are two distinct elements in the list that
// sum to zero, and false otherwise.
// >>> PairsSumToZero([1, 3, 5, 0])
// false
// >>> PairsSumToZero([1, 3, -2, 1])
// false
// >>> PairsSumToZero([1, 2, 3, 7])
// false
// >>> PairsSumToZero([2, 4, -5, 3, 5, 7])
// true
// >>> PairsSumToZero([1])
// false
func PairsSumToZero(l []int) bool {
| seen := map[int]bool{}
for i := 0; i < len(l); i++ {
for j := i + 1; j < len(l); j++ {
if l[i] + l[j] == 0 {
if _, ok := seen[l[i]]; !ok {
seen[l[i]] = true
return true
}
if _, ok := seen[l[j]]; !ok {
seen[l[j]] = true
return true
}
}
}
}
return false
}
| go | THUDM/humaneval-x |
import (
"strconv"
)
// Change numerical base of input number x to base.
// return string representation after the conversion.
// base numbers are less than 10.
// >>> ChangeBase(8, 3)
// '22'
// >>> ChangeBase(8, 2)
// '1000'
// >>> ChangeBase(7, 2)
// '111'
func ChangeBase(x int, base int) string {
| if x >= base {
return ChangeBase(x/base, base) + ChangeBase(x%base, base)
}
return strconv.Itoa(x)
}
| go | THUDM/humaneval-x |
// Given length of a side and high return area for a triangle.
// >>> TriangleArea(5, 3)
// 7.5
func TriangleArea(a float64, h float64) float64 {
| return a * h / 2
}
| go | THUDM/humaneval-x |
// 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
func Fib4(n int) int {
| switch n {
case 0:
return 0
case 1:
return 0
case 2:
return 2
case 3:
return 0
default:
return Fib4(n-1) + Fib4(n-2) + Fib4(n-3) + Fib4(n-4)
}
}
| go | THUDM/humaneval-x |
import (
"sort"
)
// Return Median of elements in the list l.
// >>> Median([3, 1, 2, 4, 5])
// 3.0
// >>> Median([-10, 4, 6, 1000, 10, 20])
// 15.0
func Median(l []int) float64 {
| sort.Ints(l)
if len(l)%2==1{
return float64(l[len(l)/2])
}else{
return float64(l[len(l)/2-1]+l[len(l)/2])/2.0
}
}
| go | THUDM/humaneval-x |
// Checks if given string is a palindrome
// >>> IsPalindrome('')
// true
// >>> IsPalindrome('aba')
// true
// >>> IsPalindrome('aaaaa')
// true
// >>> IsPalindrome('zbcd')
// false
func IsPalindrome(text string) bool {
| runes := []rune(text)
result := make([]rune, 0)
for i := len(runes) - 1; i >= 0; i-- {
result = append(result, runes[i])
}
return text == string(result)
}
| go | THUDM/humaneval-x |
// Return 2^n modulo p (be aware of numerics).
// >>> Modp(3, 5)
// 3
// >>> Modp(1101, 101)
// 2
// >>> Modp(0, 101)
// 1
// >>> Modp(3, 11)
// 8
// >>> Modp(100, 101)
// 1
func Modp(n int,p int) int {
| ret := 1
for i:= 0; i < n; i++ {
ret = (2 * ret) % p
}
return ret
}
| go | THUDM/humaneval-x |
// returns encoded string by shifting every character by 5 in the alphabet.
func EncodeShift(s string) string {
runes := []rune(s)
newRunes := make([]rune, 0)
for _, ch := range runes {
newRunes = append(newRunes, (ch+5-'a')%26+'a')
}
return string(runes)
}
// takes as input string encoded with EncodeShift function. Returns decoded string.
func DecodeShift(s string) string {
| runes := []rune(s)
newRunes := make([]rune, 0)
for _, ch := range runes {
newRunes = append(newRunes, (ch-5-'a')%26+'a')
}
return string(runes)
}
| go | THUDM/humaneval-x |
import (
"regexp"
)
// RemoveVowels is a function that takes string and returns string without vowels.
// >>> RemoveVowels('')
// ''
// >>> RemoveVowels("abcdef\nghijklm")
// 'bcdf\nghjklm'
// >>> RemoveVowels('abcdef')
// 'bcdf'
// >>> RemoveVowels('aaaaa')
// ''
// >>> RemoveVowels('aaBAA')
// 'B'
// >>> RemoveVowels('zbcd')
// 'zbcd'
func RemoveVowels(text string) string {
| var re = regexp.MustCompile("[aeiouAEIOU]")
text = re.ReplaceAllString(text, "")
return text
}
| go | THUDM/humaneval-x |
// Return true if all numbers in the list l are below threshold t.
// >>> BelowThreshold([1, 2, 4, 10], 100)
// true
// >>> BelowThreshold([1, 20, 4, 10], 5)
// false
func BelowThreshold(l []int,t int) bool {
| for _, n := range l {
if n >= t {
return false
}
}
return true
}
| go | THUDM/humaneval-x |
// Add two numbers x and y
// >>> Add(2, 3)
// 5
// >>> Add(5, 7)
// 12
func Add(x int, y int) int {
| return x + y
}
| go | THUDM/humaneval-x |
// Check if two words have the same characters.
// >>> SameChars('eabcdzzzz', 'dddzzzzzzzddeddabc')
// true
// >>> SameChars('abcd', 'dddddddabc')
// true
// >>> SameChars('dddddddabc', 'abcd')
// true
// >>> SameChars('eabcd', 'dddddddabc')
// false
// >>> SameChars('abcd', 'dddddddabce')
// false
// >>> SameChars('eabcdzzzz', 'dddzzzzzzzddddabc')
// false
func SameChars(s0 string, s1 string) bool {
| set0 := make(map[int32]interface{})
set1 := make(map[int32]interface{})
for _, i := range s0 {
set0[i] = nil
}
for _, i := range s1 {
set1[i] = nil
}
for i, _ := range set0 {
if _,ok:=set1[i];!ok{
return false
}
}
for i, _ := range set1 {
if _,ok:=set0[i];!ok{
return false
}
}
return true
}
| go | THUDM/humaneval-x |
// Return n-th Fibonacci number.
// >>> Fib(10)
// 55
// >>> Fib(1)
// 1
// >>> Fib(8)
// 21
func Fib(n int) int {
| if n <= 1 {
return n
}
return Fib(n-1) + Fib(n-2)
}
| go | THUDM/humaneval-x |
// brackets is a string of "<" and ">".
// return true if every opening bracket has a corresponding closing bracket.
//
// >>> CorrectBracketing("<")
// false
// >>> CorrectBracketing("<>")
// true
// >>> CorrectBracketing("<<><>>")
// true
// >>> CorrectBracketing("><<>")
// false
func CorrectBracketing(brackets string) bool {
| l := len(brackets)
count := 0
for index := 0; index < l; index++ {
if brackets[index] == '<' {
count++
} else if brackets[index] == '>' {
count--
}
if count < 0 {
return false
}
}
if count == 0 {
return true
} else {
return false
}
}
| go | THUDM/humaneval-x |
// Return true is list elements are Monotonically increasing or decreasing.
// >>> Monotonic([1, 2, 4, 20])
// true
// >>> Monotonic([1, 20, 4, 10])
// false
// >>> Monotonic([4, 1, 0, -10])
// true
func Monotonic(l []int) bool {
| flag := true
if len(l) > 1 {
for i := 0; i < len(l)-1; i++ {
if l[i] != l[i+1] {
flag = l[i] > l[i+1]
break
}
}
} else {
return false
}
for i := 0; i < len(l)-1; i++ {
if flag != (l[i] >= l[i+1]) {
return false
}
}
return true
}
| go | THUDM/humaneval-x |
import (
"sort"
)
// Return sorted unique Common elements for two lists.
// >>> Common([1, 4, 3, 34, 653, 2, 5], [5, 7, 1, 5, 9, 653, 121])
// [1, 5, 653]
// >>> Common([5, 3, 2, 8], [3, 2])
// [2, 3]
func Common(l1 []int,l2 []int) []int {
| m := make(map[int]bool)
for _, e1 := range l1 {
if m[e1] {
continue
}
for _, e2 := range l2 {
if e1 == e2 {
m[e1] = true
break
}
}
}
res := make([]int, 0, len(m))
for k, _ := range m {
res = append(res, k)
}
sort.Ints(res)
return res
}
| go | THUDM/humaneval-x |
// Return the largest prime factor of n. Assume n > 1 and is not a prime.
// >>> LargestPrimeFactor(13195)
// 29
// >>> LargestPrimeFactor(2048)
// 2
func LargestPrimeFactor(n int) int {
| isPrime := func(n int) bool {
for i := 2; i < int(math.Pow(float64(n), 0.5)+1); i++ {
if n%i == 0 {
return false
}
}
return true
}
largest := 1
for j := 2; j < n + 1; j++ {
if n % j == 0 && isPrime(j) {
if j > largest {
largest = j
}
}
}
return largest
}
| go | THUDM/humaneval-x |
// SumToN is a function that sums numbers from 1 to n.
// >>> SumToN(30)
// 465
// >>> SumToN(100)
// 5050
// >>> SumToN(5)
// 15
// >>> SumToN(10)
// 55
// >>> SumToN(1)
// 1
func SumToN(n int) int {
| if n <= 0 {
return 0
} else {
return n + SumToN(n - 1)
}
}
| go | THUDM/humaneval-x |
import (
"strings"
)
// brackets is a string of "(" and ")".
// return true if every opening bracket has a corresponding closing bracket.
//
// >>> CorrectBracketing("(")
// false
// >>> CorrectBracketing("()")
// true
// >>> CorrectBracketing("(()())")
// true
// >>> CorrectBracketing(")(()")
// false
func CorrectBracketing(brackets string) bool {
| brackets = strings.Replace(brackets, "(", " ( ", -1)
brackets = strings.Replace(brackets, ")", ") ", -1)
open := 0
for _, b := range brackets {
if b == '(' {
open++
} else if b == ')' {
open--
}
if open < 0 {
return false
}
}
return open == 0
}
| go | THUDM/humaneval-x |
// xs represent coefficients of a polynomial.
// xs[0] + xs[1] * x + xs[2] * x^2 + ....
// Return Derivative of this polynomial in the same form.
// >>> Derivative([3, 1, 2, 4, 5])
// [1, 4, 12, 20]
// >>> Derivative([1, 2, 3])
// [2, 6]
func Derivative(xs []int) []int {
| l := len(xs)
y := make([]int, l - 1)
for i := 0; i < l - 1; i++ {
y[i] = xs[i + 1] * (i + 1)
}
return y
}
| go | THUDM/humaneval-x |
// The FibFib number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:
// Fibfib(0) == 0
// Fibfib(1) == 0
// Fibfib(2) == 1
// Fibfib(n) == Fibfib(n-1) + Fibfib(n-2) + Fibfib(n-3).
// Please write a function to efficiently compute the n-th element of the Fibfib number sequence.
// >>> Fibfib(1)
// 0
// >>> Fibfib(5)
// 4
// >>> Fibfib(8)
// 24
func Fibfib(n int) int {
| if n <= 0 {
return 0
}
switch n {
case 0:
return 0
case 1:
return 0
case 2:
return 1
default:
return Fibfib(n-1) + Fibfib(n-2) + Fibfib(n-3)
}
}
| go | THUDM/humaneval-x |
import (
"strings"
)
// Write a function VowelsCount 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")
// 2
// >>> VowelsCount("ACEDY")
// 3
func VowelsCount(s string) int {
| s = strings.ToLower(s)
vowels := map[int32]interface{}{'a': nil, 'e': nil, 'i': nil, 'o': nil, 'u': nil}
count := 0
for _, i := range s {
if _, ok := vowels[i]; ok {
count++
}
}
if (s[len(s)-1]) == 'y' {
count++
}
return count
}
| go | THUDM/humaneval-x |
// Circular shift the digits of the integer x, shift the digits right by shift
// and return the result as a string.
// If shift > number of digits, return digits reversed.
// >>> CircularShift(12, 1)
// "21"
// >>> CircularShift(12, 2)
// "12"
func CircularShift(x int,shift int) string {
| s := strconv.Itoa(x)
if shift > len(s) {
runes := make([]rune, 0)
for i := len(s)-1; i >= 0; i-- {
runes = append(runes, rune(s[i]))
}
return string(runes)
}else{
return s[len(s)-shift:]+s[:len(s)-shift]
}
}
| go | THUDM/humaneval-x |
// 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
func Digitsum(x string) int {
| if len(x) == 0 {
return 0
}
result := 0
for _, i := range x {
if 'A' <= i && i <= 'Z' {
result += int(i)
}
}
return result
}
| go | THUDM/humaneval-x |
import (
"strconv"
"strings"
)
// In this task, you will be given a string that represents a number of apples and oranges
// that are distributed in a basket of fruit this basket contains
// apples, oranges, and mango fruits. Given the string that represents the total number of
// the oranges and apples and an integer that represent the total number of the fruits
// in the basket return the number of the mango fruits in the basket.
// for examble:
// FruitDistribution("5 apples and 6 oranges", 19) ->19 - 5 - 6 = 8
// FruitDistribution("0 apples and 1 oranges",3) -> 3 - 0 - 1 = 2
// FruitDistribution("2 apples and 3 oranges", 100) -> 100 - 2 - 3 = 95
// FruitDistribution("100 apples and 1 oranges",120) -> 120 - 100 - 1 = 19
func FruitDistribution(s string,n int) int {
| split := strings.Split(s, " ")
for _, i := range split {
atoi, err := strconv.Atoi(i)
if err != nil {
continue
}
n = n - atoi
}
return n
}
| go | THUDM/humaneval-x |
import (
"math"
)
// 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 a list, [ smalest_value, its index ],
// If there are no even values or the given array is empty, return [].
//
// Example 1:
// Input: [4,2,3]
// Output: [2, 1]
// Explanation: 2 has the smallest even value, and 2 has the smallest index.
//
// Example 2:
// Input: [1,2,3]
// Output: [2, 1]
// Explanation: 2 has the smallest even value, and 2 has the smallest index.
//
// Example 3:
// Input: []
// Output: []
//
// Example 4:
// Input: [5, 0, 3, 0, 4, 2]
// Output: [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
func Pluck(arr []int) []int {
| result := make([]int, 0)
if len(arr) == 0 {
return result
}
evens := make([]int, 0)
min := math.MaxInt64
minIndex := 0
for i, x := range arr {
if x%2 == 0 {
evens = append(evens, x)
if x < min {
min = x
minIndex = i
}
}
}
if len(evens) == 0 {
return result
}
result = []int{min, minIndex}
return result
}
| go | THUDM/humaneval-x |
// 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
func Search(lst []int) int {
| countMap := make(map[int]int)
for _, i := range lst {
if count, ok := countMap[i]; ok {
countMap[i] = count + 1
} else {
countMap[i] = 1
}
}
max := -1
for i, count := range countMap {
if count >= i && count > max {
max = i
}
}
return max
}
| go | THUDM/humaneval-x |
import (
"sort"
)
// Given list of integers, return 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([1, 2, 3, 4]) == [1, 4, 2, 3]
// StrangeSortList([5, 5, 5, 5]) == [5, 5, 5, 5]
// StrangeSortList([]) == []
func StrangeSortList(lst []int) []int {
| sort.Ints(lst)
result := make([]int, 0)
for i := 0; i < len(lst)/2; i++ {
result = append(result, lst[i])
result = append(result, lst[len(lst)-i-1])
}
if len(lst)%2 != 0 {
result = append(result, lst[len(lst)/2])
}
return result
}
| go | THUDM/humaneval-x |
import (
"math"
)
// Given the lengths of the three sides of a triangle. Return the area of
// the triangle rounded to 2 decimal points if the three sides form a valid triangle.
// Otherwise return -1
// Three sides make a valid triangle when the sum of any two sides is greater
// than the third side.
// Example:
// TriangleArea(3, 4, 5) == 6.00
// TriangleArea(1, 2, 10) == -1
func TriangleArea(a float64, b float64, c float64) interface{} {
| if a+b <= c || a+c <= b || b+c <= a {
return -1
}
s := (a + b + c) / 2
area := math.Pow(s * (s - a) * (s - b) * (s - c), 0.5)
area = math.Round(area*100)/100
return area
}
| go | THUDM/humaneval-x |
// Write a function that returns true if the object q will fly, and false otherwise.
// The object q will fly if it's balanced (it is a palindromic list) and the sum of its elements is less than or equal the maximum possible weight w.
//
// Example:
// WillItFly([1, 2], 5) β false
// 1+2 is less than the maximum possible weight, but it's unbalanced.
//
// WillItFly([3, 2, 3], 1) β false
// it's balanced, but 3+2+3 is more than the maximum possible weight.
//
// WillItFly([3, 2, 3], 9) β true
// 3+2+3 is less than the maximum possible weight, and it's balanced.
//
// WillItFly([3], 5) β true
// 3 is less than the maximum possible weight, and it's balanced.
func WillItFly(q []int,w int) bool {
| sum := 0
for i := 0; i < len(q); i++ {
sum += q[i]
}
if sum <= w && isPalindrome(q) {
return true
}
return false
}
func isPalindrome(arr []int) bool {
for i := 0; i < (len(arr) / 2); i++ {
if arr[i] != arr[len(arr) - i - 1] {
return false
}
}
return true
}
| go | THUDM/humaneval-x |
// Given an array arr of integers, find the minimum number of elements that
// need to be changed to make the array palindromic. A palindromic array is an array that
// is read the same backwards and forwards. In one change, you can change one element to any other element.
//
// For example:
// SmallestChange([1,2,3,5,4,7,9,6]) == 4
// SmallestChange([1, 2, 3, 4, 3, 2, 2]) == 1
// SmallestChange([1, 2, 3, 2, 1]) == 0
func SmallestChange(arr []int) int {
| count := 0
for i := 0; i < len(arr) - 1; i++ {
a := arr[len(arr) - i - 1]
if arr[i] != a {
arr[i] = a
count++
}
}
return count
}
| go | THUDM/humaneval-x |
// Write a function that accepts two lists of strings and returns the list that has
// total number of chars in the all strings of the list less than the other list.
//
// if the two lists have the same number of chars, return the first list.
//
// Examples
// TotalMatch([], []) β []
// TotalMatch(['hi', 'admin'], ['hI', 'Hi']) β ['hI', 'Hi']
// TotalMatch(['hi', 'admin'], ['hi', 'hi', 'admin', 'project']) β ['hi', 'admin']
// TotalMatch(['hi', 'admin'], ['hI', 'hi', 'hi']) β ['hI', 'hi', 'hi']
// TotalMatch(['4'], ['1', '2', '3', '4', '5']) β ['4']
func TotalMatch(lst1 []string,lst2 []string) []string {
| var numchar1 = 0
var numchar2 = 0
for _, item := range lst1 {
numchar1 += len(item)
}
for _, item := range lst2 {
numchar2 += len(item)
}
if numchar1 <= numchar2 {
return lst1
} else {
return lst2
}
}
| go | THUDM/humaneval-x |
// Write a function that returns true if the given number is the multiplication of 3 prime numbers
// and false otherwise.
// Knowing that (a) is less then 100.
// Example:
// IsMultiplyPrime(30) == true
// 30 = 2 * 3 * 5
func IsMultiplyPrime(a int) bool {
| isPrime := func(n int) bool {
for i := 2; i < int(math.Pow(float64(n), 0.5)+1); i++ {
if n%i == 0 {
return false
}
}
return true
}
for i := 2; i < 101; i++ {
if !isPrime(i) {
continue
}
for j := 2; j < 101; j++ {
if !isPrime(j) {
continue
}
for k := 2; k < 101; k++ {
if !isPrime(k) {
continue
}
if i*j*k == a {
return true
}
}
}
}
return false
}
| go | THUDM/humaneval-x |
// Your task is to write a function that returns true if a number x is a simple
// power of n and false in other cases.
// x is a simple power of n if n**int=x
// For example:
// IsSimplePower(1, 4) => true
// IsSimplePower(2, 2) => true
// IsSimplePower(8, 2) => true
// IsSimplePower(3, 2) => false
// IsSimplePower(3, 1) => false
// IsSimplePower(5, 3) => false
func IsSimplePower(x int,n int) bool {
| if x == 1 {
return true
}
if n==1 {
return false
}
if x % n != 0 {
return false
}
return IsSimplePower(x / n, n)
}
| go | THUDM/humaneval-x |
import (
"math"
)
// Write a function that takes an integer a and returns true
// if this ingeger is a cube of some integer number.
// Note: you may assume the input is always valid.
// Examples:
// Iscube(1) ==> true
// Iscube(2) ==> false
// Iscube(-1) ==> true
// Iscube(64) ==> true
// Iscube(0) ==> true
// Iscube(180) ==> false
func Iscube(a int) bool {
| abs := math.Abs(float64(a))
return int(math.Pow(math.Round(math.Pow(abs, 1.0/3.0)), 3.0)) == int(abs)
}
| go | THUDM/humaneval-x |
// You have been tasked to write a function that receives
// a hexadecimal number as a string and counts the number of hexadecimal
// digits that are primes (prime number, or a prime, is a natural number
// greater than 1 that is not a product of two smaller natural numbers).
// Hexadecimal digits are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F.
// Prime numbers are 2, 3, 5, 7, 11, 13, 17,...
// So you have to determine a number of the following digits: 2, 3, 5, 7,
// B (=decimal 11), D (=decimal 13).
// Note: you may assume the input is always correct or empty string,
// and symbols A,B,C,D,E,F are always uppercase.
// Examples:
// For num = "AB" the output should be 1.
// For num = "1077E" the output should be 2.
// For num = "ABED1A33" the output should be 4.
// For num = "123456789ABCDEF0" the output should be 6.
// For num = "2020" the output should be 2.
func HexKey(num string) int {
| primes := map[int32]interface{}{'2': nil, '3': nil, '5': nil, '7': nil, 'B': nil, 'D': nil}
total := 0
for _, c := range num {
if _, ok := primes[c]; ok {
total++
}
}
return total
}
| go | THUDM/humaneval-x |
import (
"fmt"
)
// You will be given a number in decimal form and your task is to convert it to
// binary format. The function should return a string, with each character representing a binary
// number. Each character in the string will be '0' or '1'.
//
// There will be an extra couple of characters 'db' at the beginning and at the end of the string.
// The extra characters are there to help with the format.
//
// Examples:
// DecimalToBinary(15) # returns "db1111db"
// DecimalToBinary(32) # returns "db100000db"
func DecimalToBinary(decimal int) string {
| return fmt.Sprintf("db%bdb", decimal)
}
| go | THUDM/humaneval-x |
// You are given a string s.
// Your task is to check if the string is happy or not.
// A string is happy if its length is at least 3 and every 3 consecutive letters are distinct
// For example:
// IsHappy(a) => false
// IsHappy(aa) => false
// IsHappy(abcd) => true
// IsHappy(aabb) => false
// IsHappy(adb) => true
// IsHappy(xyy) => false
func IsHappy(s string) bool {
| if len(s) < 3 {
return false
}
for i := 0; i < len(s)-2; i++ {
if s[i] == s[i+1] || s[i+1] == s[i+2] || s[i] == s[i+2] {
return false
}
}
return true
}
| go | THUDM/humaneval-x |
// It is the last week of the semester and the teacher has to give the grades
// to students. The teacher has been making her own algorithm for grading.
// The only problem is, she has lost the code she used for grading.
// She has given you a list of GPAs for some students and you have to write
// a function that can output a list of letter grades using the following table:
// GPA | Letter grade
// 4.0 A+
// > 3.7 A
// > 3.3 A-
// > 3.0 B+
// > 2.7 B
// > 2.3 B-
// > 2.0 C+
// > 1.7 C
// > 1.3 C-
// > 1.0 D+
// > 0.7 D
// > 0.0 D-
// 0.0 E
//
//
// Example:
// grade_equation([4.0, 3, 1.7, 2, 3.5]) ==> ["A+", "B", "C-", "C", "A-"]
func NumericalLetterGrade(grades []float64) []string {
| letter_grade := make([]string, 0, len(grades))
for _, gpa := range grades {
switch {
case gpa == 4.0:
letter_grade = append(letter_grade, "A+")
case gpa > 3.7:
letter_grade = append(letter_grade, "A")
case gpa > 3.3:
letter_grade = append(letter_grade, "A-")
case gpa > 3.0:
letter_grade = append(letter_grade, "B+")
case gpa > 2.7:
letter_grade = append(letter_grade, "B")
case gpa > 2.3:
letter_grade = append(letter_grade, "B-")
case gpa > 2.0:
letter_grade = append(letter_grade, "C+")
case gpa > 1.7:
letter_grade = append(letter_grade, "C")
case gpa > 1.3:
letter_grade = append(letter_grade, "C-")
case gpa > 1.0:
letter_grade = append(letter_grade, "D+")
case gpa > 0.7:
letter_grade = append(letter_grade, "D")
case gpa > 0.0:
letter_grade = append(letter_grade, "D-")
default:
letter_grade = append(letter_grade, "E")
}
}
return letter_grade
}
| go | THUDM/humaneval-x |
// Write a function that takes a string and returns true if the string
// length is a prime number or false otherwise
// Examples
// PrimeLength('Hello') == true
// PrimeLength('abcdcba') == true
// PrimeLength('kittens') == true
// PrimeLength('orange') == false
func PrimeLength(s string) bool {
| l := len(s)
if l == 0 || l == 1 {
return false
}
for i := 2; i < l; i++ {
if l%i == 0 {
return false
}
}
return true
}
| go | THUDM/humaneval-x |
import (
"math"
)
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1.
func StartsOneEnds(n int) int {
| if n == 1 {
return 1
}
return 18 * int(math.Pow(10, float64(n-2)))
}
| go | THUDM/humaneval-x |
import (
"fmt"
"strconv"
)
// Given a positive integer N, return the total sum of its digits in binary.
//
// Example
// For N = 1000, the sum of digits will be 1 the output should be "1".
// For N = 150, the sum of digits will be 6 the output should be "110".
// For N = 147, the sum of digits will be 12 the output should be "1100".
//
// Variables:
// @N integer
// Constraints: 0 β€ N β€ 10000.
// Output:
// a string of binary number
func Solve(N int) string {
| sum := 0
for _, c := range strconv.Itoa(N) {
sum += int(c - '0')
}
return fmt.Sprintf("%b", sum)
}
| go | THUDM/humaneval-x |
// Given a non-empty list of integers lst. Add the even elements that are at odd indices..
//
// Examples:
// Add([4, 2, 6, 7]) ==> 2
func Add(lst []int) int {
| sum := 0
for i := 1; i < len(lst); i += 2 {
if lst[i]%2 == 0 {
sum += lst[i]
}
}
return sum
}
| go | THUDM/humaneval-x |
import (
"sort"
"strings"
)
// Write a function that takes a string and returns an ordered version of it.
// Ordered version of string, is a string where all words (separated by space)
// are replaced by a new word where all the characters arranged in
// ascending order based on ascii value.
// Note: You should keep the order of words and blank spaces in the sentence.
//
// For example:
// AntiShuffle('Hi') returns 'Hi'
// AntiShuffle('hello') returns 'ehllo'
// AntiShuffle('Hello World!!!') returns 'Hello !!!Wdlor'
func AntiShuffle(s string) string {
| strs := make([]string, 0)
for _, i := range strings.Fields(s) {
word := []rune(i)
sort.Slice(word, func(i, j int) bool {
return word[i] < word[j]
})
strs = append(strs, string(word))
}
return strings.Join(strs, " ")
}
| go | THUDM/humaneval-x |
import (
"sort"
)
// You are given a 2 dimensional data, as a nested lists,
// which is similar to matrix, however, unlike matrices,
// each row may contain a different number of columns.
// Given lst, and integer x, find integers x in the list,
// and return list of tuples, [(x1, y1), (x2, y2) ...] such that
// each tuple is a coordinate - (row, columns), starting with 0.
// Sort coordinates initially by rows in ascending order.
// Also, sort coordinates of the row by columns in descending order.
//
// Examples:
// GetRow([
// [1,2,3,4,5,6],
// [1,2,3,4,1,6],
// [1,2,3,4,5,1]
// ], 1) == [(0, 0), (1, 4), (1, 0), (2, 5), (2, 0)]
// GetRow([], 1) == []
// GetRow([[], [1], [1, 2, 3]], 3) == [(2, 2)]
func GetRow(lst [][]int, x int) [][2]int {
| coords := make([][2]int, 0)
for i, row := range lst {
for j, item := range row {
if item == x {
coords = append(coords, [2]int{i, j})
}
}
}
sort.Slice(coords, func(i, j int) bool {
if coords[i][0] == coords[j][0] {
return coords[i][1] > coords[j][1]
}
return coords[i][0] < coords[j][0]
})
return coords
}
| go | THUDM/humaneval-x |
import (
"sort"
)
// Given an array of non-negative integers, return a copy of the given array after sorting,
// you will sort the given array in ascending order if the sum( first index value, last index value) is odd,
// or sort it in descending order if the sum( first index value, last index value) is even.
//
// Note:
// * don't change the given array.
//
// Examples:
// * SortArray([]) => []
// * SortArray([5]) => [5]
// * SortArray([2, 4, 3, 0, 1, 5]) => [0, 1, 2, 3, 4, 5]
// * SortArray([2, 4, 3, 0, 1, 5, 6]) => [6, 5, 4, 3, 2, 1, 0]
func SortArray(array []int) []int {
| arr := make([]int, len(array))
copy(arr, array)
if len(arr) == 0 {
return arr
}
if (arr[0]+arr[len(arr)-1])%2 == 0 {
sort.Slice(arr, func(i, j int) bool {
return arr[i] > arr[j]
})
} else {
sort.Slice(arr, func(i, j int) bool {
return arr[i] < arr[j]
})
}
return arr
}
| go | THUDM/humaneval-x |
import (
"strings"
)
// Create a function Encrypt that takes a string as an argument and
// returns a string Encrypted with the alphabet being rotated.
// The alphabet should be rotated in a manner such that the letters
// shift down by two multiplied to two places.
// For example:
// Encrypt('hi') returns 'lm'
// Encrypt('asdfghjkl') returns 'ewhjklnop'
// Encrypt('gf') returns 'kj'
// Encrypt('et') returns 'ix'
func Encrypt(s string) string {
| d := "abcdefghijklmnopqrstuvwxyz"
out := make([]rune, 0, len(s))
for _, c := range s {
pos := strings.IndexRune(d, c)
if pos != -1 {
out = append(out, []rune(d)[(pos+2*2)%26])
} else {
out = append(out, c)
}
}
return string(out)
}
| go | THUDM/humaneval-x |
import (
"math"
"sort"
)
// You are given a list of integers.
// Write a function NextSmallest() that returns the 2nd smallest element of the list.
// Return nil if there is no such element.
//
// NextSmallest([1, 2, 3, 4, 5]) == 2
// NextSmallest([5, 1, 4, 3, 2]) == 2
// NextSmallest([]) == nil
// NextSmallest([1, 1]) == nil
func NextSmallest(lst []int) interface{} {
| set := make(map[int]struct{})
for _, i := range lst {
set[i] = struct{}{}
}
vals := make([]int, 0, len(set))
for k := range set {
vals = append(vals, k)
}
sort.Slice(vals, func(i, j int) bool {
return vals[i] < vals[j]
})
if len(vals) < 2 {
return nil
}
return vals[1]
}
| go | THUDM/humaneval-x |
import (
"regexp"
)
// You'll be given a string of words, and your task is to count the number
// of boredoms. A boredom is a sentence that starts with the word "I".
// Sentences are delimited by '.', '?' or '!'.
//
// For example:
// >>> IsBored("Hello world")
// 0
// >>> IsBored("The sky is blue. The sun is shining. I love this weather")
// 1
func IsBored(S string) int {
| r, _ := regexp.Compile(`[.?!]\s*`)
sentences := r.Split(S, -1)
sum := 0
for _, s := range sentences {
if len(s) >= 2 && s[:2] == "I " {
sum++
}
}
return sum
}
| go | THUDM/humaneval-x |
// Create a function that takes 3 numbers.
// Returns true if one of the numbers is equal to the sum of the other two, and all numbers are integers.
// Returns false in any other cases.
//
// Examples
// AnyInt(5, 2, 7) β true
//
// AnyInt(3, 2, 2) β false
//
// AnyInt(3, -2, 1) β true
//
// AnyInt(3.6, -2.2, 2) β false
func AnyInt(x, y, z interface{}) bool {
| xx, ok := x.(int)
if !ok {
return false
}
yy, ok := y.(int)
if !ok {
return false
}
zz, ok := z.(int)
if !ok {
return false
}
if (xx+yy == zz) || (xx+zz == yy) || (yy+zz == xx) {
return true
}
return false
}
| go | THUDM/humaneval-x |
import (
"strings"
)
// 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'
func Encode(message string) string {
| vowels := "aeiouAEIOU"
vowels_replace := make(map[rune]rune)
for _, c := range vowels {
vowels_replace[c] = c + 2
}
result := make([]rune, 0, len(message))
for _, c := range message {
if 'a' <= c && c <= 'z' {
c += 'A' - 'a'
} else if 'A' <= c && c <= 'Z' {
c += 'a' - 'A'
}
if strings.ContainsRune(vowels, c) {
result = append(result, vowels_replace[c])
} else {
result = append(result, c)
}
}
return string(result)
}
| go | THUDM/humaneval-x |
import (
"math"
"strconv"
)
// You are given a list of integers.
// You need to find the largest prime value and return the sum of its digits.
//
// Examples:
// For lst = [0,3,2,1,3,5,7,4,5,5,5,2,181,32,4,32,3,2,32,324,4,3] the output should be 10
// For lst = [1,0,1,8,2,4597,2,1,3,40,1,2,1,2,4,2,5,1] the output should be 25
// For lst = [1,3,1,32,5107,34,83278,109,163,23,2323,32,30,1,9,3] the output should be 13
// For lst = [0,724,32,71,99,32,6,0,5,91,83,0,5,6] the output should be 11
// For lst = [0,81,12,3,1,21] the output should be 3
// For lst = [0,8,1,2,1,7] the output should be 7
func Skjkasdkd(lst []int) int {
| isPrime := func(n int) bool {
for i := 2; i < int(math.Pow(float64(n), 0.5)+1); i++ {
if n%i == 0 {
return false
}
}
return true
}
maxx := 0
i := 0
for i < len(lst) {
if lst[i] > maxx && isPrime(lst[i]) {
maxx = lst[i]
}
i++
}
sum := 0
for _, d := range strconv.Itoa(maxx) {
sum += int(d - '0')
}
return sum
}
| go | THUDM/humaneval-x |
import (
"strings"
)
// Given a dictionary, 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 dictionary is empty.
// Examples:
// CheckDictCase({"a":"apple", "b":"banana"}) should return true.
// CheckDictCase({"a":"apple", "A":"banana", "B":"banana"}) should return false.
// CheckDictCase({"a":"apple", 8:"banana", "a":"apple"}) should return false.
// CheckDictCase({"Name":"John", "Age":"36", "City":"Houston"}) should return false.
// CheckDictCase({"STATE":"NC", "ZIP":"12345" }) should return true.
func CheckDictCase(dict map[interface{}]interface{}) bool {
| if len(dict) == 0 {
return false
}
state := "start"
key := ""
ok := false
for k := range dict {
if key, ok = k.(string); !ok {
state = "mixed"
break
}
if state == "start" {
if key == strings.ToUpper(key) {
state = "upper"
} else if key == strings.ToLower(key) {
state = "lower"
} else {
break
}
} else if (state == "upper" && key != strings.ToUpper(key)) || (state == "lower" && key != strings.ToLower(key)) {
state = "mixed"
break
} else {
break
}
}
return state == "upper" || state == "lower"
}
| go | THUDM/humaneval-x |
// 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:
// CountUpTo(5) => [2,3]
// CountUpTo(11) => [2,3,5,7]
// CountUpTo(0) => []
// CountUpTo(20) => [2,3,5,7,11,13,17,19]
// CountUpTo(1) => []
// CountUpTo(18) => [2,3,5,7,11,13,17]
func CountUpTo(n int) []int {
| primes := make([]int, 0)
for i := 2; i < n; i++ {
is_prime := true
for j := 2; j < i; j++ {
if i%j == 0 {
is_prime = false
break
}
}
if is_prime {
primes = append(primes, i)
}
}
return primes
}
| go | THUDM/humaneval-x |
import (
"math"
)
// Complete the function that takes two integers and returns
// the product of their unit digits.
// Assume the input is always valid.
// Examples:
// Multiply(148, 412) should return 16.
// Multiply(19, 28) should return 72.
// Multiply(2020, 1851) should return 0.
// Multiply(14,-15) should return 20.
func Multiply(a, b int) int {
| return int(math.Abs(float64(a%10)) * math.Abs(float64(b%10)))
}
| go | THUDM/humaneval-x |
import (
"strings"
)
// Given a string s, count the number of uppercase vowels in even indices.
//
// For example:
// CountUpper('aBCdEf') returns 1
// CountUpper('abcdefg') returns 0
// CountUpper('dBBE') returns 0
func CountUpper(s string) int {
| count := 0
runes := []rune(s)
for i := 0; i < len(runes); i += 2 {
if strings.ContainsRune("AEIOU", runes[i]) {
count += 1
}
}
return count
}
| go | THUDM/humaneval-x |
import (
"math"
"strconv"
"strings"
)
// Create a function that takes a value (string) representing a number
// and returns the closest integer to it. If the number is equidistant
// from two integers, round it away from zero.
//
// Examples
// >>> ClosestInteger("10")
// 10
// >>> ClosestInteger("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 ClosestInteger("14.5") should
// return 15 and ClosestInteger("-14.5") should return -15.
func ClosestInteger(value string) int {
| if strings.Count(value, ".") == 1 {
// remove trailing zeros
for value[len(value)-1] == '0' {
value = value[:len(value)-1]
}
}
var res float64
num, _ := strconv.ParseFloat(value, 64)
if len(value) >= 2 && value[len(value)-2:] == ".5" {
if num > 0 {
res = math.Ceil(num)
} else {
res = math.Floor(num)
}
} else if len(value) > 0 {
res = math.Round(num)
} else {
res = 0
}
return int(res)
}
| go | THUDM/humaneval-x |
End of preview. Expand
in Dataset Viewer.
README.md exists but content is empty.
Use the Edit dataset card button to edit it.
- Downloads last month
- 0