giulio98/xlcost-single-prompt huggingface dataset:
# count the number of words having sum of ascii values less than and greater than k | function to count the words ; sum of ascii values ; number of words having sum of ascii less than k ; if character is a space ; add the ascii value to sum ; handling the last word separately ; 
def CountWords(str, k):
    sum = 0
    NumberOfWords = 0
    counter = 0
    l = len(str)
    for i in range(l):
        if (str[i] == ' '):
            if (sum < k):
                counter += 1
            sum = 0
            NumberOfWords += 1
        else:
            sum += ord(str[i])
    NumberOfWords += 1
    if (sum < k):
        counter += 1
    print("Number of words having sum of ASCII",
          "values less than k =", counter)
    print(
        "Number of words having sum of ASCII values",
        "greater than or equal to k =",
        NumberOfWords - counter)


if __name__ == "__main__":
    str = "Learn how to code"
    k = 400
    CountWords(str, k)

# Expected output:
Number of words having sum of ASCII values less than k = 2
Number of words having sum of ASCII values greater than or equal to k = 2
# rearrange a string in the form of integer sum followed by the minimized character | function to return maximum volume ; separate digits and alphabets ; change digit sum to string ; change alphabet sum to string ; concatenate sum to alphabets string ; 
def separateChar(str__):
    n = len(str__)
    digitSum = 0
    alphabetSum = 0
    j = 0
    for i in range(n):
        if (ord(str__[i]) >= 48 and ord(str__[i]) <= 56):
            digitSum += ord(str__[i]) - ord('0')
        else:
            alphabetSum += ord(str__[i]) - ord('a') + 1
            alphabetSum %= 26
    sumStr = str(digitSum)
    alphabetStr = chr(alphabetSum + ord('a') - 1)
    sumStr += alphabetStr
    return sumStr


if __name__ == '__main__':
    str__ = "3652adyz3423"
    print(separateChar(str__))

# Expected output:
28d
# find the count of palindromic sub | python3 program to find the count of palindromic sub - string of a string in it 's ascending form ; function to return count of palindromic sub - string ; calculate frequency ; calculate count of palindromic sub - string ; return result ; 

MAX_CHAR = 26


def countPalindrome(str):
    n = len(str)
    sum = 0
    hashTable = [0] * MAX_CHAR
    for i in range(n):
        hashTable[ord(str[i]) - ord('a')] += 1
    for i in range(26):
        if (hashTable[i]):
            sum += (hashTable[i] * (hashTable[i] + 1) // 2)
    return sum


if __name__ == "__main__":
    str = "ananananddd"
    print(countPalindrome(str))

# Expected output:
26
# minimum number of elements to be removed so that pairwise consecutive elements are same | function to count the minimum number of elements to remove from a number so that pairwise two consecutive digits are same . ; initialize counting variable ; check if two consecutive digits are same ; 
def countConsecutive(s):
    count = -1
    for i in range(len(s) - 1):
        if (i <= len(s)):
            if (s[i] is s[i + 1]):
                i += 1
            else:
                count += 1
    return count


if __name__ == '__main__':
    str = "44522255"
    print(countConsecutive(str))

# Expected output:
2
# smallest odd digits number not less than n | function to check if all digits are odd of a given number ; iterate for all digits ; if digit is even ; all digits are odd ; function to return the smallest number with all digits odd ; iterate till we find a number with all digits odd ; 
def check_digits(n):
    while (n):
        if ((n % 10) % 2 == 0):
            return 0
        n = int(n / 10)
    return 1


def smallest_number(n):
    i = n
    while (1):
        if (check_digits(i)):
            return i
        i += 1


if __name__ == '__main__':
    N = 2397
    print(smallest_number(N))

# Expected output:
3111
# smallest odd digits number not less than n | function to return the smallest number with all digits odd ; convert the number to string to perform operations ; find out the first even number ; if no even numbers are there , than n is the answer ; add all digits till first even ; increase the even digit by 1 ; add 1 to the right of the even number ; 
def smallestNumber(n):
    num = 0
    s = ""
    duplicate = n
    while (n):
        s = chr(n % 10 + 48) + s
        n //= 10
    index = -1
    for i in range(len(s)):
        digit = ord(s[i]) - ord('0')
        if ((digit & 1) == 0):
            index = i
            break
    if (index == -1):
        return duplicate
    for i in range(index):
        num = num * 10 + (ord(s[i]) - ord('0'))
    num = num * 10 + (ord(s[index]) - ord('0') + 1)
    for i in range(index + 1, len(s)):
        num = num * 10 + 1
    return num


if __name__ == "__main__":
    N = 2397
    print(smallestNumber(N))

# Expected output:
3111
# count and print the alphabets having ascii value in the range [ l , r ] | function to count the number of characters whose ascii value is in range [ l , r ] ; initializing the count to 0 ; increment the count if the value is less ; return the count ; 
def CountCharacters(str1, l, r):
    cnt = 0
    len1 = len(str1)
    for i in str1:
        if (l <= ord(i) and ord(i) <= r):
            cnt = cnt + 1
            print(i, end=" ")
    return cnt


if __name__ == '__main__':
    str1 = "geeksforgeeks"
    l = 102
    r = 111
    print("Characters with ASCII values " + "in the range [l, r] are")
    print("andtheircountis", CountCharacters(str1, l, r))

# Expected output:
Characters with ASCII values in the range [l, r] are
g k f o g k andtheircountis 6
# Minimum steps to remove substring 010 from a binary string | Function to find the minimum steps ; substring "010" found ; Get the binary string ; Find the minimum steps
def minSteps(str):
    count = 0
    i = 0
    while i < len(str) - 2:
        if str[i] == '0':
            if (str[i + 1] == '1'):
                if (str[i + 2] == '0'):
                    count = count + 1
                    i = i + 2
        i = i + 1
    return count


str = "0101010"
print(minSteps(str))

# Expected output:
2
# xor of prime frequencies of characters in a string | python3 program to find xor of prime frequencies of characters in a string ; function to create sieve to check primes ; false here indicates that it is not prime ; if prime [ p ] is not changed , then it is a prime ; update all multiples of p , set them to non - prime ; function to find xor of prime frequencies ; map is used to store character frequencies ; traverse the map ; calculate xor of all prime frequencies ; 

from collections import defaultdict


def SieveOfEratosthenes(prime, p_size):
    prime[0] = False
    prime[1] = False
    p = 2
    while p * p <= p_size:
        if prime[p]:
            for i in range(p * 2, p_size + 1, p):
                prime[i] = False
        p += 1


def xorOfPrime(s):
    prime = [True] * 100005
    SieveOfEratosthenes(prime, 10005)
    m = defaultdict(lambda: 0)
    for i in range(0, len(s)):
        m[s[i]] += 1
    result = flag = 0
    for it in m:
        if prime[m[it]]:
            result ^= m[it]
            flag = 1
    if not flag:
        return -1
    return result


if __name__ == "__main__":
    s = "gggggeeekkkks"
    print(xorOfPrime(s))

# Expected output:
6
# count of alphabets having ascii value less than and greater than k | function to count the number of characters whose ascii value is less than k ; initialising the count to 0 ; incrementing the count if the value is less ; return the count ; 
def CountCharacters(str, k):
    cnt = 0
    l = len(str)
    for i in range(l):
        if (ord(str[i]) < k):
            cnt += 1
    return cnt


if __name__ == "__main__":
    str = "GeeksForGeeks"
    k = 90
    count = CountCharacters(str, k)
    print("Characters with ASCII values", "less than K are", count)
    print(
        "Characters with ASCII values",
        "greater than or equal to K are",
        len(str) - count)

# Expected output:
Characters with ASCII values less than K are 3
Characters with ASCII values greater than or equal to K are 10
# de bruijn sequence | set 1 | python3 implementation of the above approach ; modified dfs in which no edge is traversed twice ; function to find a de bruijn sequence of order n on k characters ; clearing global variables ; number of edges ; 

import math
seen = set()
edges = []


def dfs(node, k, A):
    for i in range(k):
        str = node + A[i]
        if (str not in seen):
            seen .add(str)
            dfs(str[1:], k, A)
            edges .append(i)


def deBruijn(n, k, A):
    seen .clear()
    edges .clear()
    startingNode = A[0] * (n - 1)
    dfs(startingNode, k, A)
    S = ""
    l = int(math .pow(k, n))
    for i in range(l):
        S += A[edges[i]]
    S += startingNode
    return S


n = 3
k = 2
A = "01"
print(deBruijn(n, k, A))

# Expected output:
0011101000
# number of words in a camelcase sequence | function to find the count of words in a camelcase sequence ; 
def countWords(str):
    count = 1
    for i in range(1, len(str) - 1):
        if (str[i].isupper()):
            count += 1
    return count


str = "geeksForGeeks"
print(countWords(str))

# Expected output:
3
# check whether frequency of characters in a string makes fibonacci sequence | python3 program to check whether the frequency of characters in a string make fibonacci sequence ; function to check if the frequencies are in fibonacci series ; map to store the frequencies of character ; vector to store first n fibonacci numbers ; get the size of the map ; a and b are first and second terms of fibonacci series ; vector v contains elements of fibonacci series ; compare vector elements with values in map ; 

from collections import defaultdict


def isFibonacci(s):
    m = defaultdict(lambda: 0)
    for i in range(0, len(s)):
        m[s[i]] += 1
    v = []
    n = len(m)
    a = b = 1
    v .append(a)
    v .append(b)
    for i in range(0, n - 2):
        v .append(a + b)
        c = a + b
        a, b = b, c
    flag, i = 1, 0
    for itr in sorted(m):
        if m[itr] != v[i]:
            flag = 0
            break
        i += 1
    if flag == 1:
        return "YES"
    else:
        return "NO"


if __name__ == "__main__":
    s = "abeeedd"
    print(isFibonacci(s))

# Expected output:
YES
# lexicographically smallest string formed by removing at most one character | function to return the smallest string ; iterate the string ; first point where s [ i ] > s [ i + 1 ] ; append the string without i - th character in it ; leave the last character ; 
def smallest(s):
    l = len(s)
    ans = ""
    for i in range(l - 1):
        if (s[i] > s[i + 1]):
            for j in range(l):
                if (i != j):
                    ans += s[j]
            return ans
    ans = s[0:l - 1]
    return ans


if __name__ == "__main__":
    s = "abcda"
    print(smallest(s))

# Expected output:
abca
# arrangement of the characters of a word such that all vowels are at odd places | python3 program to find the number of ways in which the characters of the word can be arranged such that the vowels occupy only the odd positions ; function to return the factorial of a number ; calculating npr ; function to find the number of ways in which the characters of the word can be arranged such that the vowels occupy only the odd positions ; get total even positions ; get total odd positions ; store frequency of each character of the string ; count total number of vowels ; count total number of consonants ; calculate the total number of ways ; 

import math


def fact(n):
    f = 1
    for i in range(2, n + 1):
        f = f * i
    return f


def npr(n, r):
    return fact(n) / fact(n - r)


def countPermutations(str):
    even = math .floor(len(str) / 2)
    odd = len(str) - even
    ways = 0
    freq = [0] * 26
    for i in range(len(str)):
        freq[ord(str[i]) - ord('a')] += 1
    nvowels = (freq[0] + freq[4] + freq[8] + freq[14] + freq[20])
    nconsonants = len(str) - nvowels
    ways = (npr(odd, nvowels) * npr(nconsonants, nconsonants))
    return int(ways)


str = "geeks"
print(countPermutations(str))

# Expected output:
36
# replace all consonants with nearest vowels in a string | function to replace consonant with nearest vowels ; 
def replacingConsonants(s):
    nVowel = "aaaeeeeiiiiioooooouuuuuuuu"
    for i in range(0, len(s)):
        s = s .replace(s[i], nVowel[ord(s[i]) - 97])
    return s


s = "geeksforgeeks"
print(replacingConsonants(s))

# Expected output:
eeeiueooeeeiu
# replace consonants with next immediate consonants alphabetically in a string | function to check if a character is vowel or not ; function that replaces consonant with next immediate consonant alphabatically ; start traversing the string ; if character is z , than replace it with character b ; if the alphabet is not z ; replace the element with next immediate alphabet ; if next immediate alphabet is vowel , than take next 2 nd immediate alphabet ( since no two vowels occurs consecutively in alphabets ) hence no further checking is required ; 
def isVowel(ch):
    if (ch != 'a' and ch != 'e' and ch != 'i' and ch != 'o' and ch != 'u'):
        return False
    return True


def replaceConsonants(s):
    for i in range(len(s)):
        if (isVowel(s[i]) == False):
            if (s[i] == 'z'):
                s[i] = 'b'
            else:
                s[i] = chr(ord(s[i]) + 1)
                if (isVowel(s[i])):
                    s[i] = chr(ord(s[i]) + 1)
    return ''.join(s)


s = "geeksforgeeks"
print(replaceConsonants(list(s)))

# Expected output:
heeltgosheelt
# remove characters from string that appears strictly less than k times | python 3 program to reduce the string by removing the characters which appears less than k times ; function to reduce the string by removing the characters which appears less than k times ; hash table initialised to 0 ; increment the frequency of the character ; create a new empty string ; append the characters which appears more than equal to k times ; 

MAX_CHAR = 26


def removeChars(str, k):
    hash = [0] * (MAX_CHAR)
    n = len(str)
    for i in range(n):
        hash[ord(str[i]) - ord('a')] += 1
    res = ""
    for i in range(n):
        if (hash[ord(str[i]) - ord('a')] >= k):
            res += str[i]
    return res


if __name__ == "__main__":
    str = "geeksforgeeks"
    k = 2
    print(removeChars(str, k))

# Expected output:
geeksgeeks
# count changes in led lights to display digits one by one | python3 program to count number of on offs to display digits of a number . ; store the led lights required to display a particular number . ; compute the change in led and keep on adding the change ; 
def countOnOff(n):
    Led = [6, 2, 5, 5, 4, 5, 6, 3, 7, 5]
    leng = len(n)
    sum = Led[int(n[0]) - int('0')]
    for i in range(1, leng):
        sum = (sum + abs(Led[int(n[i]) - int('0')] -
               Led[int(n[i - 1]) - int('0')]))
    return sum


if __name__ == '__main__':
    n = "082"
    print(countOnOff(n))

# Expected output:
9
# program to check if all characters have even frequency | python implementation of the above approach ; creating a frequency array ; finding length of s ; counting frequency of all characters ; checking if any odd frequency is there or not ; 
def check(s):
    freq = [0] * 26
    n = len(s)
    for i in range(n):
        freq[ord(s[i]) - 97] += 1
    for i in range(26):
        if (freq[i] % 2 == 1):
            return False
    return True


s = "abaccaba"
if (check(s)):
    print("Yes")
else:
    print("No")

# Expected output:
Yes
# maximum consecutive zeroes in concatenated binary string | returns the maximum size of a substring consisting only of zeroes after k concatenation ; stores the maximum length of the required substring ; if the current character is 0 ; stores maximum length of current substrings with zeroes ; if the whole is filled with zero ; computes the length of the maximal prefix which contains only zeroes ; computes the length of the maximal suffix which contains only zeroes ; if more than 1 concatenations are to be made ; 
def max_length_substring(st, n, k):
    max_len = 0
    len = 0
    for i in range(0, n):
        if (st[i] == '0'):
            len = len + 1
        else:
            len = 0
        max_len = max(max_len, len)
    if (max_len == n):
        return n * k
    pref = 0
    suff = 0
    i = 0
    while (st[i] == '0'):
        i = i + 1
        pref = pref + 1
    i = n - 1
    while (st[i] == '0'):
        i = i - 1
        suff = suff + 1
    if (k > 1):
        max_len = max(max_len, pref + suff)
    return max_len


n = 6
k = 3
st = "110010"
ans = max_length_substring(st, n, k)
print(ans)

# Expected output:
2
# count number of substrings with numeric value greater than x | function that counts valid sub - strings ; only take those numbers that do not start with '0' . ; converting the sub - string starting from index ' i ' and having length ' len ' to int and checking if it is greater than x or not ; 
def countSubStr(S, X):
    cnt = 0
    N = len(S)
    for i in range(0, N):
        if (S[i] != '0'):
            j = 1
            while ((j + i) <= N):
                num = int(S[i:i + j])
                if (num > X):
                    cnt = cnt + 1
                j = j + 1
    return cnt


S = "2222"
X = 97
print(countSubStr(S, X))

# Expected output:
3
# check whether a binary string can be formed by concatenating given n numbers sequentially | function that returns false if the number passed as argument contains digit ( s ) other than '0' or '1 ; function that checks whether the binary string can be formed or not ; empty string for storing the binary number ; check if a [ i ] can be a part of the binary string ; conversion of int into string ; if a [ i ] can 't be a part  then break the loop ; possible to create binary string ; impossible to create binary string ; 
def isBinary(n):
    while n != 0:
        temp = n % 10
        if temp != 0 and temp != 1:
            return False
        n = n // 10
    return True


def formBinaryStr(n, a):
    flag = True
    s = ""
    for i in range(0, n):
        if isBinary(a[i]):
            s += str(a[i])
        else:
            flag = False
            break
    if flag:
        print(s)
    else:
        print(-1)


if __name__ == "__main__":
    a = [10, 1, 0, 11, 10]
    N = len(a)
    formBinaryStr(N, a)

# Expected output:
10101110
# check if all the palindromic sub | function to check if the string is palindrome ; function that checks whether all the palindromic sub - strings are of odd length . ; creating each substring ; if the sub - string is of even length and is a palindrome then , we return false ; 
def checkPalindrome(s):
    for i in range(len(s)):
        if (s[i] != s[len(s) - i - 1]):
            return False
    return True


def CheckOdd(s):
    n = len(s)
    for i in range(n):
        x = ""
        for j in range(i, n):
            x += s[j]
            if (len(x) % 2 == 0 and checkPalindrome(x)):
                return False
    return True


s = "geeksforgeeks"
if (CheckOdd(s)):
    print("YES")
else:
    print("NO")

# Expected output:
NO
# number of permutations of a string in which all the occurrences of a given character occurs together | function to return factorial of the number passed as argument ; function to get the total permutations which satisfy the given condition ; create has to store count of each character ; store character occurrences ; count number of times particular character comes ; if particular character isn 't  present in the string then return 0 ; remove count of particular character ; total length of the string ; assume all occurrences of particular character as a single character . ; compute factorial of the length ; divide by the factorials of the no . of occurrences of all the characters . ; return the result ; 
def fact(n):
    result = 1
    for i in range(1, n + 1):
        result *= i
    return result


def getResult(string, ch):
    has = [0] * 26
    for i in range(len(string)):
        has[ord(string[i]) - ord('A')] += 1
    particular = has[ord(ch) - ord('A')]
    if particular == 0:
        return 0
    has[ord(ch) - ord('A')] = 0
    total = len(string)
    total = total - particular + 1
    result = fact(total)
    for i in range(26):
        if has[i] > 1:
            result /= fact(has[i])
    return result


if __name__ == "__main__":
    string = "MISSISSIPPI"
    print(getResult(string, 'S'))

# Expected output:
840.0
# check if there exists any sub | function to check if there exists at least 1 sub - sequence in a string which is not palindrome ; use set to count number of distinct characters ; insert each character in set ; if there is more than 1 unique characters , return true ; else , return false ; 
def isAnyNotPalindrome(s):
    unique = set()
    for i in range(0, len(s)):
        unique .add(s[i])
    if (len(unique) > 1):
        return True
    else:
        return False


if __name__ == '__main__':
    s = "aaaaab"
    if (isAnyNotPalindrome(s)):
        print("YES")
    else:
        print("NO")

# Expected output:
YES
# Arrangement of words without changing the relative position of vowel and consonants | this function return n ! ; this will return total number of ways ; freq maintains frequency of each character in word ; check character is vowel or not ; the characters that are not vowel must be consonant ; number of ways to arrange vowel ; multiply both as these are independent ; string contains only capital letters ; this will contain ans
def factorial(n):
    res = 1
    for i in range(1, n + 1):
        res = res * i
    return res


def count(word):
    freq = [0 for i in range(30)]
    vowel = 0
    consonant = 0
    for i in range(len(word)):
        freq[ord(word[i]) - 65] += 1
        if (word[i] == 'A' or word[i] == 'E' or word[i]
                == 'I' or word[i] == 'O' or word[i] == 'U'):
            vowel += 1
        else:
            consonant += 1
    vowelArrange = factorial(vowel)
    vowelArrange //= factorial(freq[0])
    vowelArrange //= factorial(freq[4])
    vowelArrange //= factorial(freq[8])
    vowelArrange //= factorial(freq[14])
    vowelArrange //= factorial(freq[20])
    consonantArrange = factorial(consonant)
    for i in range(26):
        if (i != 0 and i != 4 and i != 8 and i != 14 and i != 20):
            consonantArrange //= factorial(freq[i])
    total = vowelArrange * consonantArrange
    return total


word = "COMPUTER"
ans = count(word)
print(ans)

# Expected output:
720
# check if it is possible to create a palindrome string from given n | function to check if a string is palindrome or not ; string that stores characters of s in reverse order ; length of the string s ; string used to form substring using n ; variable to store sum of digits of n ; forming the substring by traversing n ; appending the substr to str till it 's length becomes equal to sum ; trimming the string str so that it 's length becomes equal to sum ; 
def isPalindrome(s):
    s1 = ""
    N = len(s)
    i = (N - 1)
    while (i >= 0):
        s1 += s[i]
        i = i - 1
    if (s == s1):
        return True
    return False


def createString(N):
    s2 = ""
    s = str(N)
    letters = "abcdefghij"
    sum = 0
    substr = ""
    for i in range(0, len(s)):
        digit = int(s[i])
        substr += letters[digit]
        sum += digit
    while (len(s2) <= sum):
        s2 += substr
    s2 = s2[:sum]
    return isPalindrome(s2)


N = 61
flag = createString(N)
if (flag):
    print("YES")
else:
    print("NO")

# Expected output:
YES
# program to find the product of ascii values of characters in a string | function to find product of ascii value of characters in string ; traverse string to find the product ; return the product ; 
def productAscii(str):
    prod = 1
    for i in range(0, len(str)):
        prod = prod * ord(str[i])
    return prod


if __name__ == '__main__':
    str = "GfG"
    print(productAscii(str))

# Expected output:
514182