giulio98/xlcost-single-prompt huggingface dataset:
# validation of equation given as string | function that returns true if the equation is valid ; if it is an integer then add it to another string array ; evaluation of 1 st operator ; evaluation of 2 nd operator ; evaluation of 3 rd operator ; if the lhs result is equal to the rhs ; 
def isValid(string):
    k = 0
    operands = [""] * 5
    operators = [""] * 4
    ans = 0
    ans1 = 0
    ans2 = 0
    for i in range(len(string)):
        if (string[i] != '+' and string[i] != '=' and string[i] != '-'):
            operands[k] += string[i]
        else:
            operators[k] = string[i]
            if (k == 1):
                if (operators[k - 1] == '+'):
                    ans += int(operands[k - 1]) + int(operands[k])
                if (operators[k - 1] == '-'):
                    ans += int(operands[k - 1]) - int(operands[k])
            if (k == 2):
                if (operators[k - 1] == '+'):
                    ans1 += ans + int(operands[k])
                if (operators[k - 1] == '-'):
                    ans1 -= ans - int(operands[k])
            if (k == 3):
                if (operators[k - 1] == '+'):
                    ans2 += ans1 + int(operands[k])
                if (operators[k - 1] == '-'):
                    ans2 -= ans1 - int(operands[k])
            k += 1
    if (ans2 == int(operands[4])):
        return True
    else:
        return False


if __name__ == "__main__":
    string = "2 + 5 + 3 + 1 = 11"
    if (isValid(string)):
        print("Valid")
    else:
        print("Invalid")

# Expected output:
Valid
# count of sub | function to return the count of sub - strings of str that are divisible by k ; take all sub - strings starting from i ; if current sub - string is divisible by k ; return the required count ; 
def countSubStr(str, l, k):
    count = 0
    for i in range(l):
        n = 0
        for j in range(i, l, 1):
            n = n * 10 + (ord(str[j]) - ord('0'))
            if (n % k == 0):
                count += 1
    return count


if __name__ == '__main__':
    str = "33445"
    l = len(str)
    k = 11
    print(countSubStr(str, l, k))

# Expected output:
3
# find the resulting colour combination | function to return colour combination ; check for b * g = y ; check for b * y = g ; check for y * g = b ; 
def Colour_Combination(s):
    temp = s[0]
    for i in range(1, len(s), 1):
        if (temp != s[i]):
            if ((temp == 'B' or temp == 'G') and (s[i] == 'G' or s[i] == 'B')):
                temp = 'Y'
            elif ((temp == 'B' or temp == 'Y') and (s[i] == 'Y' or s[i] == 'B')):
                temp = 'G'
            else:
                temp = 'B'
    return temp


if __name__ == '__main__':
    s = "GBYGB"
    print(Colour_Combination(s))

# Expected output:
B
# reverse middle x characters | function to reverse the middle x characters in a str1ing ; find the position from where the characters have to be reversed ; print the first n characters ; print the middle x characters in reverse ; print the last n characters ; 
def reverse(str1, x):
    n = (len(str1) - x) // 2
    for i in range(n):
        print(str1[i], end="")
    for i in range(n + x - 1, n - 1, -1):
        print(str1[i], end="")
    for i in range(n + x, len(str1)):
        print(str1[i], end="")


str1 = "geeksforgeeks"
x = 3
reverse(str1, x)

# Expected output:
geeksrofgeeks
# minimize the number of replacements to get a string with same number of ' a ' , ' b ' and ' c ' in it | function to count numbers ; count the number of ' a ' , ' b ' and ' c ' in string ; if equal previously ; if not a multiple of 3 ; increase the number of a ' s ▁ by ▁ ▁ removing ▁ extra ▁ ' b ' and c ; check if it is ' b ' and it more than n / 3 ; check if it is ' c ' and it more than n / 3 ; increase the number of b ' s ▁ by ▁ ▁ removing ▁ extra ▁ ' c ; check if it is ' c ' and it more than n / 3 ; increase the number of c 's from back ; check if it is ' a ' and it more than n / 3 ; increase the number of b 's from back ; check if it is ' a ' and it more than n / 3 ; increase the number of c 's from back ; check if it is ' b ' and it more than n / 3 ; 
def lexoSmallest(s, n):
    ca = 0
    cb = 0
    cc = 0
    for i in range(n):
        if (s[i] == 'a'):
            ca += 1
        elif (s[i] == 'b'):
            cb += 1
        else:
            cc += 1
    if (ca == cb and cb == cc):
        return s
    cnt = n // 3
    if (cnt * 3 != n):
        return "-1"
    i = 0
    while (ca < cnt and i < n):
        if (s[i] == 'b' and cb > cnt):
            cb -= 1
            s[i] = 'a'
            ca += 1
        elif (s[i] == 'c' and cc > cnt):
            cc -= 1
            s[i] = 'a'
            ca += 1
        i += 1
    i = 0

    while (cb < cnt and i < n):
        if (s[i] == 'c' and cc > cnt):
            cc -= 1
            s[i] = '1'
            cb += 1
        i += 1
    i = n - 1
    while (cc < cnt and i >= 0):
        if (s[i] == 'a' and ca > cnt):
            ca -= 1
            s[i] = 'c'
            cc += 1
        i -= 1
    i = n - 1
    while (cb < cnt and i >= 0):
        if (s[i] == 'a' and ca > cnt):
            ca -= 1
            s[i] = 'b'
            cb += 1
        i -= 1
    i = n - 1
    while (cc < cnt and i >= 0):
        if (s[i] == 'b' and cb > cnt):
            cb -= 1
            s[i] = 'c'
            cc += 1
        i -= 1
    return s


s = "aaaaaa"
n = len(s)
print(*lexoSmallest(list(s), n), sep="")

# Expected output:
aabbcc
# minimum moves to reach from i to j in a cyclic string | function to return the count of steps required to move from i to j ; starting from i + 1 ; count of steps ; current character ; if current character is different from previous ; increment steps ; update current character ; return total steps ; function to return the minimum number of steps required to reach j from i ; swap the values so that i <= j ; steps to go from i to j ( left to right ) ; while going from i to j ( right to left ) first go from i to 0 then from ( n - 1 ) to j ; if first and last character is different then it 'll add a step to stepstoleft ; return the minimum of two paths ; 
def getSteps(str, i, j, n):
    k = i + 1
    steps = 0
    ch = str[i]
    while (k <= j):
        if (str[k] != ch):
            steps = steps + 1
            ch = str[k]
        k = k + 1
    return steps


def getMinSteps(str, i, j, n):
    if (j < i):
        temp = i
        i = j
        j = temp
    stepsToRight = getSteps(str, i, j, n)
    stepsToLeft = getSteps(str, 0, i, n) + getSteps(str, j, n - 1, n)
    if (str[0] != str[n - 1]):
        stepsToLeft = stepsToLeft + 1
    return min(stepsToLeft, stepsToRight)


str = "SSNSS"
n = len(str)
i = 0
j = 3
print(getMinSteps(str, i, j, n))

# Expected output:
0
# count distinct substrings that contain some characters at most k times | python3 implementation of the approach ; function to return the count of valid sub - strings ; store all characters of anotherstr in a direct index table for quick lookup . ; to store distinct output substrings ; traverse through the given string and one by one generate substrings beginning from s [ i ] . ; one by one generate substrings ending with s [ j ] ; if character is illegal ; if current substring is valid ; if current substring is invalid , adding more characters would not help . ; return the count of distinct sub - strings ; 

MAX_CHAR = 256


def countSubStrings(s, anotherStr, k):
    illegal = [False] * MAX_CHAR
    for i in range(len(anotherStr)):
        illegal[ord(anotherStr[i])] = True
    us = set()
    for i in range(len(s)):
        ss = ""
        count = 0
        for j in range(i, len(s)):
            if (illegal[ord(s[j])]):
                count += 1
            ss = ss + s[j]
            if (count <= k):
                us .add(ss)
            else:
                break
    return len(us)


if __name__ == "__main__":
    string = "acbacbacaa"
    anotherStr = "abcdefghijklmnopqrstuvwxyz"
    k = 2
    print(countSubStrings(string, anotherStr, k))

# Expected output:
8
# count pairs of parentheses sequences such that parentheses are balanced | python3 program to count the number of pairs of balanced parentheses ; function to count the number of pairs ; hashing function to count the opening and closing brackets ; traverse for all bracket sequences ; get the string ; counts the opening and closing required ; traverse in the string ; if it is a opening bracket ; if openings are there , then close it ; else : else increase count of closing ; if requirements of openings are there and no closing ; if requirements of closing are there and no opening ; perfect ; divide by two since two perfect makes one pair ; traverse in the open and find corresponding minimum ; 

import math as mt


def countPairs(bracks, num):
    openn = dict()
    close = dict()
    cnt = 0
    for i in range(num):
        s = bracks[i]
        l = len(s)
        op, cl = 0, 0
        for j in range(l):
            if (s[j] == '('):
                op += 1
                if (op):
                    op -= 1
                    cl += 1
        if (op and cl == 0):
            if op in openn .keys():
                openn[op] += 1
            else:
                openn[op] = 1
        if (cl and op == 0):
            if cl in openn .keys():
                close[cl] += 1
            else:
                close[cl] = 1
        if (op == 0 and cl == 0):
            cnt += 1
    cnt = cnt // 2
    for it in openn:
        cnt += min(openn[it], close[it])
    return cnt


bracks = [")())", ")", "((", "((", "(", ")", ")"]
num = len(bracks)
print(countPairs(bracks, num))

# Expected output:
1
# decrypt a string according to given rules | function to return the original string after decryption ; stores the decrypted string ; if length is odd ; step counter ; starting and ending index ; iterate till all characters are decrypted ; even step ; odd step ; if length is even ; step counter ; starting and ending index ; even step ; odd step ; reverse the decrypted string ; 
def decrypt(s, l):
    ans = ""
    if (l % 2):
        cnt = 0
        indl = 0
        indr = l - 1
        while (len(ans) != l):
            if (cnt % 2 == 0):
                ans += s[indl]
                indl += 1
            else:
                ans += s[indr]
                indr -= 1
            cnt += 1
    else:
        cnt = 0
        indl = 0
        indr = l - 1
        while (len(ans) != l):
            if (cnt % 2 == 0):
                ans += s[indr]
                indr -= 1
            else:
                ans += s[indl]
                indl += 1
            cnt += 1
    string = list(ans)
    string .reverse()
    ans = ''.join(string)
    return ans


if __name__ == "__main__":
    s = "segosegekfrek"
    l = len(s)
    print(decrypt(s, l))

# Expected output:
geeksforgeeks
# remove consecutive alphabets which are in same case | function to return the modified string ; traverse through the remaining characters in the string ; if the current and the previous characters are not in the same case then take the character ; 
def removeChars(s):
    modifiedStr = ""
    modifiedStr += s[0]
    for i in range(1, len(s)):
        if (s[i].isupper() and s[i - 1].islower()
                or s[i].islower() and s[i - 1].isupper()):
            modifiedStr += s[i]
    return modifiedStr


if __name__ == "__main__":
    s = "GeeksForGeeks"
    print(removeChars(s))

# Expected output:
GeFoGe
# cost to make a string panagram | function to return the total cost required to make the string pangram ; mark all the alphabets that occurred in the string ; calculate the total cost for the missing alphabets ; 
def pangramCost(arr, string):
    cost = 0
    occurred = [False] * 26
    for i in range(len(string)):
        occurred[ord(string[i]) - ord('a')] = True
    for i in range(26):
        if (not occurred[i]):
            cost += arr[i]
    return cost


if __name__ == "__main__":
    arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
           15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26]
    string = "abcdefghijklmopqrstuvwz"
    print(pangramCost(arr, string))

# Expected output:
63
# recursive program to insert a star between pair of identical characters | function to insert * at desired position ; append current character ; if we reached last character ; if next character is same , append '* ; 
def pairStar(Input, Output, i=0):
    Output = Output + Input[i]
    if (i == len(Input) - 1):
        print(Output)
        return

    if (Input[i] == Input[i + 1]):
        Output = Output + '*'
    pairStar(Input, Output, i + 1)


if __name__ == "__main__":
    Input = "geeks"
    Output = ""
    pairStar(Input, Output)

# Expected output:
ge*eks
# split a string in equal parts such that all parts are palindromes | function to return the frequency array for the given string ; function to return the required count ; add frequencies of the even appearing characters ; count of the characters that appeared odd number of times ; if there are no characters with odd frequency ; if there are no characters with even frequency ; only a single character with odd frequency ; more than 1 character with odd frequency string isn 't a palindrome ; all odd appearing characters can also contribute to the even length palindrome if one character is removed from the frequency leaving it as even ; if k palindromes are possible where k is the number of characters with odd frequency ; current character can no longer be an element in a string other than the mid character ; if current character has odd frequency > 1 take two characters which can be used in any of the parts ; update the frequency ; if not possible , then every character of the string will act as a separate palindrome ; 
def getFrequencies(string):
    freq = [0] * 26
    for i in range(len(string)):
        freq[ord(string[i]) - ord('a')] += 1
    return freq


def countMinParts(string):
    n = len(string)
    freq = getFrequencies(string)
    oddFreq = []
    evenFreq = []
    sumEven = 0
    for i in range(26):
        if freq[i] == 0:
            continue
        if freq[i] % 2 == 0:
            evenFreq .append(freq[i])
        else:
            oddFreq .append(freq[i])
    for i in range(len(evenFreq)):
        sumEven += evenFreq[i]
    if len(oddFreq) == 0:
        return 1
    if sumEven == 0:
        if len(oddFreq) == 1:
            return 1
        return 0
    i = 0
    while (i < len(oddFreq)):
        if ((sumEven / 2) % len(oddFreq) == 0):
            return len(oddFreq)
        if (oddFreq[i] == 1):
            i += 1
            continue
        sumEven += 2
        oddFreq[i] = oddFreq[i] - 2
    return n


if __name__ == "__main__":
    s = "noonpeep"
    print(countMinParts(s))

# Expected output:
1
# substring reverse pattern | function to print the required pattern ; print the unmodified string ; reverse the string ; replace the first and last character by ' * ' then second and second last character and so on until the string has characters remaining ; 
def printPattern(s, n):
    print(''.join(s))
    i, j = 0, n - 1
    while i < j:
        s[i], s[j] = s[j], s[i]
        i += 1
        j -= 1
    i, j = 0, n - 1
    while j - i > 1:
        s[i], s[j] = '*', '*'
        print(''.join(s))
        i += 1
        j -= 1


if __name__ == "__main__":
    s = "geeks"
    n = len(s)
    printPattern(list(s), n)

# Expected output:
geeks
*kee*
**e**
# check if the string satisfies the given condition | function that returns true if n is prime ; corner cases ; this is checked so that we can skip middle five numbers in below loop ; function that returns true if c is a vowel ; function that returns true if the count of vowels in word is prime ; if count of vowels is prime ; 
def prime(n):
    if (n <= 1):
        return False
    if (n <= 3):
        return True
    if (n % 2 == 0 or n % 3 == 0):
        return False
    i = 5
    while i * i <= n:
        if (n % i == 0 or n % (i + 2) == 0):
            return False
        i += 6
    return True


def isVowel(c):
    c = c .lower()
    if (c == 'a' or c == 'e' or c == 'i' or c == 'o' or c == 'u'):
        return True
    return False


def isValidString(word):
    cnt = 0
    for i in range(len(word)):
        if (isVowel(word[i])):
            cnt += 1
    if (prime(cnt)):
        return True
    else:
        return False


if __name__ == "__main__":
    s = "geeksforgeeks"
    if (isValidString(s)):
        print("YES")
    else:
        print("NO")

# Expected output:
YES
# concatenate suffixes of a string | function to print the expansion of the string ; take sub - string from i to n - 1 ; print the sub - string ; 
def printExpansion(str):
    suff = ""
    for i in range(len(str) - 1, -1, -1):
        suff = suff + str[i]
        print(suff, end="")


if __name__ == "__main__":
    str = "geeks"
    printExpansion(str)

# Expected output:
sskskeskeeskeeg
# solve the logical expression given by string | python3 program to solve the logical expression . ; function to evaluate the logical expression ; traversing string from the end . ; for not operation ; for and and or operation ; 

import math as mt


def logicalExpressionEvaluation(string):

    arr = list()
    n = len(string)
    for i in range(n - 1, -1, -1):
        if (string[i] == "["):

            s = list()

            while (arr[-1] != "]"):
                s.append(arr[-1])
                arr.pop()

            arr.pop()
            if (len(s) == 3):
                if s[2] == "1":
                    arr.append("0")
                else:
                    arr.append("1")
            elif (len(s) == 5):
                a = int(s[0]) - 48
                b = int(s[4]) - 48
                c = 0
                if s[2] == "&":
                    c = a & b
                else:
                    c = a | b
                arr.append((c) + 48)

        else:
            arr.append(string[i])

    return arr[-1]


string = "[[0,&,1],|,[!,1]]"

print(logicalExpressionEvaluation(string))

# Expected output:
0
# find number of substrings of length k whose sum of ascii value of characters is divisible by k | python3 program to find number of substrings of length k whose sum of ascii value of characters is divisible by k ; finding length of string ; finding sum of ascii value of first substring ; using sliding window technique to find sum of ascii value of rest of the substring ; checking if sum is divisible by k ; 
def count(s, k):
    n = len(s)
    d, count = 0, 0
    for i in range(k):
        d += ord(s[i])
        if (d % k == 0):
            count += 1
            for i in range(k, n):
                prev = ord(s[i - k])
                d -= prev
                d += ord(s[i])
                if (d % k == 0):
                    count += 1
                    return count


s = "bcgabc"
k = 3
ans = count(s, k)
print(ans)

# Expected output:
2
# string which when repeated exactly k times gives a permutation of s | function to return a string which when repeated exactly k times gives a permutation of s ; size of string ; to frequency of each character ; get frequency of each character ; to store final answer ; check if frequency is divisible by k ; add to answer ; if frequency is not divisible by k ; 
def K_String(s, k):
    n = len(s)
    fre = [0] * 26
    for i in range(n):
        fre[ord(s[i]) - ord('a')] += 1
    str = ""
    for i in range(26):
        if (fre[i] % k == 0):
            x = fre[i] // k
            while (x):
                str += chr(i + ord('a'))
                x -= 1
        else:
            return "-1"
    return str


if __name__ == "__main__":
    s = "aabb"
    k = 2
    print(K_String(s, k))

# Expected output:
ab
# maximum even length sub | python3 code to find the maximum length of sub - string ( of even length ) which can be arranged into a palindrome ; function that returns true if the given sub - string can be arranged into a palindrome ; this function returns the maximum length of the sub - string ( of even length ) which can be arranged into a palindrome ; if we reach end of the string ; if string is of even length ; if string can be arranged into a palindrome ; even length sub - string ; check if current sub - string can be arranged into a palindrome ; odd length sub - string ; 

from collections import defaultdict


def canBePalindrome(count):
    for key in count:
        if count[key] % 2 != 0:
            return False
    return True


def maxPal(string, count, start, end):
    if end == len(string):
        if (end - start) % 2 == 0:
            if canBePalindrome(count):
                return end - start
        return 0
    else:
        if (end - start) % 2 == 0:
            if canBePalindrome(count):
                count[string[end]] += 1
                return max(end - start, maxPal(string, count, start, end + 1))
            else:
                count[string[end]] += 1
                return maxPal(string, count, start, end + 1)
        else:
            count[string[end]] += 1
            length = maxPal(string, count .copy(), start, end + 1)
            count[string[end]] -= 1
            count[string[start]] -= 1
            return max(length, maxPal(string, count, start + 1, end))


string = '124565463'
start, end = 0, 0
count = defaultdict(lambda: 0)
print(maxPal(string, count, start, end))

# Expected output:
6
# minimum deletions from string to reduce it to string with at most 2 unique characters | function to find the minimum deletions ; array to store the occurrences of each characters ; length of the string ; ascii of the character ; increasing the frequency for this character ; choosing two character ; finding the minimum deletion ; 
def check(s):
    fr = [0] * 26
    n = len(s)
    for i in range(n):
        x = ord(s[i])
        fr[x - 97] += 1
    minimum = 99999999999
    for i in range(26):
        for j in range(i + 1, 26):
            z = fr[i] + fr[j]
            minimum = min(minimum, n - z)
    return minimum


s = "geeksforgeeks"
print(check(s))

# Expected output:
7
# count and print the alphabets having ascii value not in the range [ l , r ] | function to count the number of characters whose ascii value not in range [ l , r ] ; initializing the count to 0 ; using map to pra character only once ; increment the count if the value is less ; return the count ; 
def CountCharacters(str, l, r):
    cnt = 0
    m = {}
    length = len(str)
    for i in range(0, length):
        if (not (l <= ord(str[i]) and ord(str[i]) <= r)):
            cnt += 1
            if ord(str[i])not in m:
                m[ord(str[i])] = 0
                print(str[i], end=" ")
            m[ord(str[i])] += 1
    return cnt


if __name__ == '__main__':
    str = "geeksforgeeks"
    str = str .strip()
    l = 102
    r = 111
    print("Characters with ASCII values", end="")
    print("notintherange[l,r]",  "inthegivenstringare:",  end="")
    print("andtheircountis", CountCharacters(str, l, r))

# Expected output:
Characters with ASCII valuesnotintherange[l,r] inthegivenstringare:e s r andtheircountis 7
# final state of the string after modification | function to return final positions of the boxes ; populate forces going from left to right ; populate forces going from right to left ; return final state of boxes ; 
def pushBoxes(S):
    N = len(S)
    force = [0] * N
    f = 0
    for i in range(0, N):
        if S[i] == 'R':
            f = N
        elif S[i] == 'L':
            f = 0
        else:
            f = max(f - 1, 0)
        force[i] += f
    f = 0
    for i in range(N - 1, -1, -1):
        if S[i] == 'L':
            f = N
        elif S[i] == 'R':
            f = 0
        else:
            f = max(f - 1, 0)
        force[i] -= f
    return "".join('.'if f == 0 else 'R'if f > 0 else 'L'for f in force)


S = ".L.R...LR..L.."
print(pushBoxes(S))

# Expected output:
LL.RR.LLRRLL..