giulio98/xlcost-single-prompt huggingface dataset:
# minimize replacements by previous or next alphabet required to make all characters of a string the same | function to find the minimum count of operations to make all characters of the string same ; set min to some large value ; find minimum operations for each character ; initialize cnt ; add the value to cnt ; update minvalue ; return minvalue ; 
def minCost(s, n):
    minValue = 100000000
    for i in range(26):
        cnt = 0
        for j in range(n):
            cnt += min(abs(i - (ord(s[j]) - ord('a'))),
                       26 - abs(i - (ord(s[j]) - ord('a'))))
        minValue = min(minValue, cnt)
    return minValue


if __name__ == "__main__":
    st = "geeksforgeeks"
    N = len(st)
    print(minCost(st, N))

# Expected output:
60
# longest palindromic string possible by concatenating strings from a given array | python3 program for the above approach ; stores the distinct strings from the given array ; insert the strings into set ; stores the left and right substrings of the given string ; stores the middle substring ; traverse the array of strings ; reverse the current string ; checking if the is itself a palindrome or not ; check if the reverse of the is present or not ; append to the left substring ; append to the right substring ; erase both the strings from the set ; print the left substring ; print the middle substring ; print the right substring ; 
def max_len(s, N, M):
    set_str = {}
    for i in s:
        set_str[i] = 1
    left_ans, right_ans = [], []
    mid = ""
    for i in range(N):
        t = s[i]
        t = t[::-1]
        if (t == s[i]):
            mid = t
        elif (t in set_str):
            left_ans .append(s[i])
            right_ans .append(t)
            del set_str[s[i]]
            del set_str[t]
    for x in left_ans:
        print(x, end="")
    print(mid, end="")
    right_ans = right_ans[::-1]
    for x in right_ans:
        print(x, end="")


if __name__ == '__main__':
    N = 4
    M = 3
    s = ["omg", "bbb", "ffd", "gmo"]
    max_len(s, N, M)

# Expected output:
omgbbbgmo
# minimize steps defined by a string required to reach the destination from a given source | function to find the minimum length of string required to reach from source to destination ; size of the string ; stores the index of the four directions e , w , n , s ; if destination reached ; iterate over the string ; move east ; change x1 according to direction e ; move west ; change x1 according to direction w ; move north ; change y1 according to direction n ; move south ; change y1 according to direction s ; store the max of all positions ; print the minimum length of string required ; otherwise , it is impossible ; given string ; 
def minimum_length(x1, y1, x2, y2, str):
    n = len(str)
    pos1 = -1
    pos2 = -1
    pos3 = -1
    pos4 = -1
    if (x1 == x2 and y1 == y2):
        print("0")
    else:
        for i in range(n):
            if (x2 > x1):
                if (str[i] == 'E'):
                    x1 = x1 + 1
                    if (x1 == x2):
                        pos1 = i
            if (x2 < x1):
                if (str[i] == 'W'):
                    x1 = x1 - 1
                    if (x1 == x2):
                        pos2 = i
            if (y2 > y1):
                if (str[i] == 'N'):
                    y1 = y1 + 1
                    if (y1 == y2):
                        pos3 = i
            if (y2 < y1):
                if (str[i] == 'S'):
                    y1 = y1 - 1
                    if (y1 == y2):
                        pos4 = i
        z = 0
        z = max(pos1, max(max(pos2, pos3), pos4))
        if (x1 == x2 and y1 == y2):
            print(z + 1)
        else:
            print("-1")


str = "SESNW"
x1 = 0
x2 = 1
y1 = 0
y2 = 1
minimum_length(x1, y1, x2, y2, str)

# Expected output:
4
# remove all duplicate adjacent characters from a string using stack | function to remove adjacent duplicate elements ; store the string without duplicate elements ; store the index of str ; traverse the string str ; checks if stack is empty or top of the stack is not equal to current character ; if top element of the stack is equal to the current character ; if stack is empty ; if stack is not empty ; 
def ShortenString(str1):
    st = []
    i = 0
    while i < len(str1):
        if len(st) == 0 or str1[i] != st[-1]:
            st .append(str1[i])
            i += 1
        else:
            st .pop()
            i += 1
    if len(st) == 0:
        return ("Empty String")
    else:
        short_string = ""
        for i in st:
            short_string += str(i)
        return (short_string)


if __name__ == "__main__":
    str1 = "azzxzy"
    print(ShortenString(str1))

# Expected output:
axzy
# count ways to place all the characters of two given strings alternately | function to get the factorial of n ; function to get the total number of distinct ways ; length of str1 ; length of str2 ; if both strings have equal length ; if both strings do not have equal length ; 
def fact(n):
    res = 1
    for i in range(1, n + 1):
        res = res * i
    return res


def distinctWays(str1, str2):
    n = len(str1)
    m = len(str2)
    if (n == m):
        return 2 * fact(n) * fact(m)
    return fact(n) * fact(m)


str1 = "aegh"
str2 = "rsw"
print(distinctWays(str1, str2))

# Expected output:
144
# smallest string without any multiplication sign that represents the product of two given numbers | python3 program for the above approach ; function to find the string which evaluates to the product of a and b ; stores the result ; 2 ^ logg <= b && 2 ^ ( logg + 1 ) > b ; update res to res += a x 2 ^ logg ; update res to res += a x 2 ^ 0 ; find the remainder ; if remainder is not equal to 0 ; return the resultant string ; function to find the minimum length representation of a * b ; find representation of form a << k1 + a << k2 + ... + a << kn ; find representation of form b << k1 + b << k2 + ... + b << kn ; compare the length of the representations ; 

from math import log


def lenn(A, B):
    res = ""
    logg = 0
    while True:
        logg = log(B) // log(2)
        if (logg != 0):
            res += (str(A) + "<<" + str(int(logg)))
        else:
            res += A
            break
        B = B - pow(2, logg)
        if (B != 0):
            res += "+"
        else:
            break
        if logg == 0:
            break
    return res


def minimumString(A, B):
    res1 = lenn(A, B)
    res2 = lenn(B, A)
    if (len(res1) > len(res2)):
        print(res2)
    else:
        print(res1)


if __name__ == '__main__':
    A = 6
    B = 10
    minimumString(A, B)

# Expected output:
6<<3+6<<1
# count substrings of a given string whose anagram is a palindrome | function to prcount of substrings whose anagrams are palindromic ; stores the answer ; iterate over the string ; set the current character ; parity update ; print final count ; 
def countSubString(s):
    res = 0
    for i in range(len(s)):
        x = 0
        for j in range(i, len(s)):
            temp = 1 << ord(s[j]) - ord('a')
            x ^= temp
            if ((x & (x - 1)) == 0):
                res += 1
    print(res)


if __name__ == '__main__':
    str = "aaa"
    countSubString(str)

# Expected output:
6
# count substrings of a given string whose anagram is a palindrome | python3 program for the above approach ; function to get the count of substrings whose anagrams are palindromic ; store the answer ; map to store the freq of masks ; set frequency for mask 00. . .00 to 1 ; store mask in x from 0 to i ; update answer ; update frequency ; print the answer ; 

from collections import defaultdict


def countSubstring(s):
    answer = 0
    m = defaultdict(lambda: 0)
    m[0] = 1
    x = 0
    for j in range(len(s)):
        x ^= 1 << (ord(s[j]) - ord('a'))
        answer += m[x]
        for i in range(26):
            answer += m[x ^ (1 << i)]
        m[x] += 1
    print(answer)


str = "abab"
countSubstring(str)

# Expected output:
7
# sum of an array of large numbers | function to prthe result of the summation of numbers having k - digit ; reverse the array to obtain the result ; print every digit of the answer ; function to calculate the total sum ; stores the array of large numbers in integer format ; convert each element from character to integer ; stores the carry ; stores the result of summation ; initialize the sum ; calculate sum ; update the sum by adding existing carry ; store the number of digits ; increase count of digits ; if the number exceeds 9 , store the unit digit in carry ; store the rest of the sum ; append digit by digit into result array ; append result until carry is 0 ; print the result ; 
def printResult(result):
    result = result[::-1]
    i = 0
    while (i < len(result)):
        print(result[i], end="")
        i += 1


def sumOfLargeNumbers(v, k, N):
    x = [[]for i in range(1000)]
    for i in range(k):
        for j in range(N):
            x[i].append(ord(v[i][j]) - ord('0'))
    carry = 0
    result = []
    for i in range(N - 1, -1, -1):
        sum = 0
        for j in range(k):
            sum += x[j][i]
        sum += carry
        temp = sum
        count = 0
        while (temp > 9):
            temp = temp % 10
            count += 1
        l = pow(10, count)
        if (l != 1):
            carry = sum / l
        sum = sum % 10
        result .append(sum)
    while (carry != 0):
        a = carry % 10
        result .append(a)
        carry = carry // 10
    printResult(result)


if __name__ == '__main__':
    K = 10
    N = 5
    arr = [
        "1111111111",
        "1111111111",
        "1111111111",
        "1111111111",
        "1111111111"]
    sumOfLargeNumbers(arr, N, K)

# Expected output:
5555555555
# reverse words in a given string | set 2 | function to reverse the words of a given string ; stack to store each word of the string ; store the whole string in stream ; push each word of the into the stack ; print the in reverse order of the words ; 
def printRev(strr):
    strr = strr .split(" ")
    st = []
    for i in strr:
        st .append(i)
    while len(st) > 0:
        print(st[-1], end=" ")
        del st[-1]


if __name__ == '__main__':
    strr = "geeks quiz practice code"
    printRev(strr)

# Expected output:
code practice quiz geeks
# count of substrings of a binary string containing only 1 s | function to find the total number of substring having only ones ; 
def countOfSubstringWithOnlyOnes(s):
    count = 0
    res = 0
    for i in range(0, len(s)):
        if s[i] == '1':
            count = count + 1
        else:
            count = 0
        res = res + count
    return res


s = "0110111"
print(countOfSubstringWithOnlyOnes(s))

# Expected output:
9
# count of distinct strings possible by inserting k characters in the original string | python3 program for the above approach ; function to calculate and return x ^ n in log ( n ) time using binary exponentiation ; function to calculate the factorial of a number ; function to calculate combination ; nci = ( n ! ) / ( ( n - i ) ! * i ! ) ; using euler 's theorem of modular  multiplicative inverse to find  the inverse of a number.  (1/a)%mod=a^(m?2)%mod ; function to find the count of possible strings ; number of ways to form all possible strings ; number of ways to form strings that don 't contain the input  string as a subsequence ; checking for all prefix length from 0 to | s | - 1. ; to calculate nci ; select the remaining characters 25 ^ ( n - i ) ; add the answer for this prefix length to the final answer ; answer is the difference of allways and noways ; print the answer ; 

mod = 1000000007


def binExp(base, power):
    x = 1
    while (power):
        if (power % 2 == 1):
            x = (((x % mod) * (base % mod)) % mod)
        base = (((base % mod) * (base % mod)) % mod)
        power = power // 2
    return x


def fact(num):
    result = 1
    for i in range(1, num + 1):
        result = (((result % mod) * (i % mod)) % mod)
    return result


def calculate_nCi(N, i):
    nfact = fact(N)
    ifact = fact(i)
    dfact = fact(N - i)
    inv_ifact = binExp(ifact, mod - 2)
    inv_dfact = binExp(dfact, mod - 2)
    denm = (((inv_ifact % mod) * (inv_dfact % mod)) % mod)
    answer = (((nfact % mod) * (denm % mod)) % mod)
    return answer


def countSubstring(N, s, k):
    allWays = binExp(26, N)
    noWays = 0
    for i in range(s):
        nCi = calculate_nCi(N, i)
        remaining = binExp(25, N - i)
        multiply = (((nCi % mod) * (remaining % mod)) % mod)
        noWays = (((noWays % mod) + (multiply % mod)) % mod)
    answer = (((allWays % mod) - (noWays % mod)) % mod)
    if (answer < 0):
        answer += mod
    print(answer)


if __name__ == "__main__":
    st = "abc"
    k = 2
    s = len(st)
    N = s + k
    countSubstring(N, s, k)

# Expected output:
6376
# calculate sum of ratio of special characters to length of substrings of the given string | python3 program to implement the above approach ; stores frequency of special characters in the array ; stores prefix sum ; function to check whether a character is special or not ; if current character is special ; otherwise ; function to find sum of ratio of count of special characters and length of substrings ; calculate the prefix sum of special nodes ; generate prefix sum array ; calculate ratio for substring ; 

N = 100005
prefix = [0] * N
sum = [0] * N


def isSpecial(c, special):
    for i in special:
        if (i == c):
            return True
    return False


def countRatio(s, special):
    n = len(s)
    for i in range(n):
        prefix[i] = int(isSpecial(s[i], special))
        if (i > 0):
            prefix[i] += prefix[i - 1]
    for i in range(n):
        sum[i] = prefix[i]
        if (i > 0):
            sum[i] += sum[i - 1]
    ans = 0
    for i in range(1, n + 1):
        if i > 1:
            count = sum[n - 1] - sum[i - 2]
        else:
            count = sum[n - 1]
        if i < n:
            count -= sum[n - i - 1]
        ans += count / i
    return ans


if __name__ == "__main__":
    s = "abcd"
    special = ['b', 'c']
    ans = countRatio(s, special)
    print('%.6f' % ans)

# Expected output:
5.833333
# minimum replacements in a string to make adjacent characters unequal | function which counts the minimum number of required operations ; n stores the length of the string s ; ans will store the required ans ; i is the current index in the string ; move j until characters s [ i ] & s [ j ] are equal or the end of the string is reached ; diff stores the length of the substring such that all the characters are equal in it ; we need atleast diff / 2 operations for this substring ; 
def count_minimum(s):
    n = len(s)
    ans = 0
    i = 0
    while i < n:
        j = i
        while j < n and (s[j] == s[i]):
            j += 1
        diff = j - i
        ans += diff // 2
        i = j
    print(ans)


if __name__ == "__main__":
    str = "caaab"
    count_minimum(str)

# Expected output:
1
# minimum cost to convert given string to consist of only vowels | function to find the minimum cost ; store vowels ; loop for iteration of string ; loop to calculate the cost ; add minimum cost ; 
def min_cost(st):
    vow = "aeiou"
    cost = 0
    for i in range(len(st)):
        costs = []
        for j in range(5):
            costs .append(abs(ord(st[i]) - ord(vow[j])))
        cost += min(costs)
    return cost


str = "abcde"
print(min_cost(str))

# Expected output:
4
# check if a given string is even | function to check if the string str is palindromic or not ; pointers to iterate the string from both ends ; if characters are found to be distinct ; return true if the string is palindromic ; function to generate string from characters at odd indices ; function to generate string from characters at even indices ; functions to checks if string is even - odd palindrome or not ; generate odd indexed string ; generate even indexed string ; check for palindrome ; 
def isPalindrome(Str):
    l = 0
    h = len(Str) - 1
    while (h > l):
        if (Str[l] != Str[h]):
            return False
        l += 1
        h -= 1
    return True


def makeOddString(Str):
    odd = ""
    for i in range(1, len(Str), 2):
        odd += Str[i]
    return odd


def makeevenString(Str):
    even = ""
    for i in range(0, len(Str), 2):
        even += Str[i]
    return even


def checkevenOddPalindrome(Str):
    odd = makeOddString(Str)
    even = makeevenString(Str)
    if (isPalindrome(odd) and isPalindrome(even)):
        print("Yes")
    else:
        print("No")


Str = "abzzab"
checkevenOddPalindrome(Str)

# Expected output:
Yes
# check given string is oddly palindrome or not | function to check if the string str is palindromic or not ; iterate the string str from left and right pointers ; keep comparing characters while they are same ; if they are not same then return false ; return true if the string is palindromic ; function to make string using odd indices of string str ; functions checks if characters at odd index of the string forms palindrome or not ; make odd indexed string ; check for palindrome ; 
def isPalindrome(str):
    l = 0
    h = len(str) - 1
    while (h > l):
        if (str[l] != str[h]):
            return False
        l += 1
        h -= 1
    return True


def makeOddString(str):
    odd = ""
    for i in range(1, len(str), 2):
        odd += str[i]
    return odd


def checkOddlyPalindrome(str):
    odd = makeOddString(str)
    if (isPalindrome(odd)):
        print("Yes")
    else:
        print("No")


str = "ddwfefwde"
checkOddlyPalindrome(str)

# Expected output:
Yes
# count of binary strings of given length consisting of at least one 1 | function to return the count of strings ; calculate pow ( 2 , n ) ; return pow ( 2 , n ) - 1 ; 
def count_Strings(n):
    x = 1
    for i in range(1, n):
        x = (1 << x)
    return x - 1


if __name__ == '__main__':
    n = 3
    print(count_Strings(n))

# Expected output:
3
# string formed with middle character of every right substring followed by left sequentially | function to decrypt and print the new string ; if the whole string has been traversed ; to calculate middle index of the string ; print the character at middle index ; recursively call for right - substring ; recursive call for left - substring ; 
def decrypt(Str, Start, End):
    if (Start > End):
        return
    mid = (Start + End) >> 1
    print(Str[mid], end="")
    decrypt(Str, mid + 1, End)
    decrypt(Str, Start, mid - 1)


N = 4
Str = "abcd"
decrypt(Str, 0, N - 1)
print()
N = 6
Str = "gyuitp"
decrypt(Str, 0, N - 1)

# Expected output:
bcda
utpigy
# check whether the binary equivalent of a number ends with given string or not | function returns true if s1 is suffix of s2 ; function to check if binary equivalent of a number ends in "111" or not ; to store the binary number ; count used to store exponent value ; 
def isSuffix(s1, s2):
    n1 = len(s1)
    n2 = len(s2)
    if (n1 > n2):
        return False
    for i in range(n1):
        if (s1[n1 - i - 1] != s2[n2 - i - 1]):
            return False
    return True


def CheckBinaryEquivalent(N, s):
    B_Number = 0
    cnt = 0
    while (N != 0):
        rem = N % 2
        c = pow(10, cnt)
        B_Number += rem * c
        N //= 2
        cnt += 1
    bin = str(B_Number)
    return isSuffix(s, bin)


if __name__ == "__main__":
    N = 23
    s = "111"
    if (CheckBinaryEquivalent(N, s)):
        print("Yes")
    else:
        print("No")

# Expected output:
Yes
# count of substrings consisting only of vowels | function to check if a character is vowel or not ; function to check whether string contains only vowel ; check if the character is not vowel then invalid ; function to count all substrings in a string which contains only vowels ; generate all substring of s ; if temp contains only vowels ; increment the count ; 
def isvowel(ch):
    return (ch == 'a' or ch == 'e' or ch == 'i' or ch == 'o' or ch == 'u')


def isvalid(s):
    n = len(s)
    for i in range(n):
        if (not isvowel(s[i])):
            return False
    return True


def CountTotal(s):
    ans = 0
    n = len(s)
    for i in range(n):
        temp = ""
        for j in range(i, n):
            temp += s[j]
            if (isvalid(temp)):
                ans += 1
    return ans


if __name__ == '__main__':
    s = "aeoibsddaaeiouudb"
    print(CountTotal(s))

# Expected output:
38
# longest substring of vowels with no two adjacent alphabets same | function to check a character is vowel or not ; function to check a substring is valid or not ; if size is 1 then check only first character ; if 0 'th character is  not vowel then invalid ; if two adjacent characters are same or i 'th char is  not vowel then invalid ; function to find length of longest substring consisting only of vowels and no similar adjacent alphabets ; stores max length of valid substring ; for current substring ; check if substring is valid ; size of substring is ( j - i + 1 ) ; 
def isVowel(c):
    return (c == 'a' or c == 'e' or c == 'i' or c == 'o' or c == 'u')


def isValid(s):
    n = len(s)
    if (n == 1):
        return (isVowel(s[0]))
    if (isVowel(s[0]) == False):
        return False
    for i in range(1, n):
        if (s[i] == s[i - 1] or not isVowel(s[i])):
            return False
    return True


def findMaxLen(s):
    maxLen = 0
    n = len(s)
    for i in range(n):
        temp = ""
        for j in range(i, n):
            temp = temp + s[j]
            if (isValid(temp)):
                maxLen = (max(maxLen, (j - i + 1)))
    return maxLen


if __name__ == "__main__":
    Str = "aeoibsddaeiouudb"
    print(findMaxLen(Str))

# Expected output:
5
# check if the number is balanced | function to check whether n is balanced number or not ; calculating the leftsum and rightsum simultaneously ; typecasting each character to integer and adding the digit to respective sums ; 
def BalancedNumber(s):
    Leftsum = 0
    Rightsum = 0
    for i in range(0, int(len(s) / 2)):
        Leftsum = Leftsum + int(s[i])
        Rightsum = (Rightsum + int(s[len(s) - 1 - i]))
    if (Leftsum == Rightsum):
        print("Balanced", end='')
    else:
        print("Not Balanced", end='')


s = "12321"
BalancedNumber(s)

# Expected output:
Balanced
# count of n size strings consisting of at least one vowel and one consonant | python3 program to count all possible strings of length n consisting of atleast one vowel and one consonant ; function to return base ^ exponent ; function to count all possible strings ; all possible strings of length n ; vowels only ; consonants only ; return the final result ; 

mod = 1e9 + 7


def expo(base, exponent):
    ans = 1
    while (exponent != 0):
        if ((exponent & 1) == 1):
            ans = ans * base
            ans = ans % mod
        base = base * base
        base %= mod
        exponent >>= 1
    return ans % mod


def findCount(N):
    ans = ((expo(26, N) - expo(5, N) - expo(21, N)) % mod)
    ans += mod
    ans %= mod
    return ans


if __name__ == "__main__":
    N = 3
    print(int(findCount(N)))

# Expected output:
8190
# sum of decomposition values of all suffixes of an array | python3 implementation to find the sum of decomposition values of all suffixes of an array ; function to find the decomposition values of the array ; stack ; variable to maintain min value in stack ; loop to iterate over the array ; condition to check if the stack is empty ; condition to check if the top of the stack is greater than the current element ; loop to pop the element out ; the size of the stack is the max no of subarrays for suffix till index i from the right ; 

import sys


def decompose(S):
    s = []
    N = len(S)
    ans = 0
    nix = sys .maxsize
    for i in range(N - 1, -1, -1):
        if (len(s) == 0):
            s .append(S[i])
            nix = S[i]
        else:
            if (S[i] < s[-1]):
                s .append(S[i])
                nix = min(nix, S[i])
            else:
                val = S[i]
                while (len(s) != 0 and val >= s[-1]):
                    s .pop()
                nix = min(nix, S[i])
                s .append(nix)
        ans += len(s)
    return ans


if __name__ == "__main__":
    S = [9, 6, 9, 35]
    print(decompose(S))

# Expected output:
8