giulio98/xlcost-single-prompt huggingface dataset:
# length of longest palindromic sub | function to find maximum of the two variables ; function to find the longest palindromic substring : recursion ; base condition when the start index is greater than end index ; base condition when both the start and end index are equal ; condition when corner characters are equal in the string ; recursive call to find the longest palindromic string by excluding the corner characters ; recursive call to find the longest palindromic string by including one corner character at a time ; function to find the longest palindromic sub - string ; utility function call ; 
def maxi(x, y):
    if x > y:
        return x
    else:
        return y


def longestPalindromic(strn, i, j, count):
    if i > j:
        return count
    if i == j:
        return (count + 1)
    if strn[i] == strn[j]:
        count = longestPalindromic(strn, i + 1, j - 1, count + 2)
        return maxi(
            count,
            maxi(
                longestPalindromic(
                    strn,
                    i + 1,
                    j,
                    0),
                longestPalindromic(
                    strn,
                    i,
                    j - 1,
                    0)))
    return maxi(
        longestPalindromic(
            strn,
            i + 1,
            j,
            0),
        longestPalindromic(
            strn,
            i,
            j - 1,
            0))


def longest_palindromic_substr(strn):
    k = len(strn) - 1
    return longestPalindromic(strn, 0, k, 0)


strn = "aaaabbaa"
print(longest_palindromic_substr(strn))

# Expected output:
6
# maximum length prefix such that frequency of each character is atmost number of characters with minimum frequency | function to find the maximum possible prefix of the string ; hash map to store the frequency of the characters in the string ; iterate over the string to find the occurence of each character ; minimum frequency of the characters ; loop to find the count of minimum frequency in the hash - map ; loop to find the maximum possible length of the prefix in the string ; condition to check if the frequency is greater than minimum possible freq ; maxprefix string and its length . ; 
def MaxPrefix(string):
    Dict = {}
    maxprefix = 0
    for i in string:
        Dict[i] = Dict .get(i, 0) + 1
    minfrequency = min(Dict .values())
    countminFrequency = 0
    for x in Dict:
        if (Dict[x] == minfrequency):
            countminFrequency += 1
    mapper = {}
    indi = 0
    for i in string:
        mapper[i] = mapper .get(i, 0) + 1
        if (mapper[i] > countminFrequency):
            break
        indi += 1
    print(string[:indi])


if __name__ == '__main__':
    str = 'aabcdaab'
    MaxPrefix(str)

# Expected output:
aabcd
# count of substrings that can be formed without using the given list of characters | function to find the number of sub - strings without using given character ; the freq array ; count variable to store the count of the characters until a character from given l is encountered ; if a character from l is encountered , then the answer variable is incremented by the value obtained by using the mentioned formula and count is set to 0 ; for last remaining characters ; 
def countSubstring(S, L, n):
    freq = [0 for i in range(26)]
    for i in range(n):
        freq[(ord(L[i]) - ord('a'))] = 1
    count, ans = 0, 0
    for x in S:
        if (freq[ord(x) - ord('a')]):
            ans += (count * count + count) // 2
            count = 0
        else:
            count += 1
    ans += (count * count + count) // 2
    return ans


S = "abcpxyz"
L = ['a', 'p', 'q']
n = len(L)
print(countSubstring(S, L, n))

# Expected output:
9
# program to accept strings starting with a vowel | function to check if first character is vowel ; function to check ; 
def checkIfStartsWithVowels(string):

    if (not (string[0] == 'A' or string[0] == 'a' or string[0] == 'E' or string[0] == 'e' or string[0]
             == 'I' or string[0] == 'i' or string[0] == 'O' or string[0] == 'o' or string[0] == 'U' or string[0] == 'u')):
        return 1
    else:
        return 0


def check(string):

    if (checkIfStartsWithVowels(string)):
        print("NotAccepted")
    else:
        print("Accepted")


if __name__ == "__main__":
    string = "animal"
    check(string)
    string = "zebra"
    check(string)

# Expected output:
Accepted
NotAccepted
# find the nth occurrence of a character in the given string | function to find the nth occurrence of a character ; loop to find the nth occurrence of the character ; 
def findNthOccur(string, ch, N):
    occur = 0
    for i in range(len(string)):
        if (string[i] == ch):
            occur += 1
        if (occur == N):
            return i
    return -1


if __name__ == "__main__":
    string = "geeks"
    ch = 'e'
    N = 2
    print(findNthOccur(string, ch, N))

# Expected output:
2
# longest equal substring with cost less than k | function to find the maximum length ; fill the prefix array with the difference of letters ; update the maximum length ; 
def solve(X, Y, N, K):
    count = [0] * (N + 1)
    sol = 0
    count[0] = 0
    for i in range(1, N + 1):
        count[i] = (count[i - 1] + abs(ord(X[i - 1]) - ord(Y[i - 1])))
    j = 0
    for i in range(1, N + 1):
        while ((count[i] - count[j]) > K):
            j += 1
        sol = max(sol, i - j)
    return sol


if __name__ == '__main__':
    N = 4
    X = "abcd"
    Y = "bcde"
    K = 3
    print(solve(X, Y, N, K))

# Expected output:
3
# jaro and jaro | python3 implementation of above approach ; function to calculate the jaro similarity of two strings ; if the strings are equal ; length of two strings ; maximum distance upto which matching is allowed ; count of matches ; hash for matches ; traverse through the first string ; check if there is any matches ; if there is a match ; if there is no match ; number of transpositions ; count number of occurrences where two characters match but there is a third matched character in between the indices ; find the next matched character in second string ; return the jaro similarity ; jaro winkler similarity ; if the jaro similarity is above a threshold ; find the length of common prefix ; if the characters match ; else break ; maximum of 4 characters are allowed in prefix ; calculate jaro winkler similarity ; 

from math import floor


def jaro_distance(s1, s2):
    if (s1 == s2):
        return 1.0
    len1 = len(s1)
    len2 = len(s2)
    if (len1 == 0 or len2 == 0):
        return 0.0
    max_dist = (max(len(s1), len(s2)) // 2) - 1
    match = 0
    hash_s1 = [0] * len(s1)
    hash_s2 = [0] * len(s2)
    for i in range(len1):
        for j in range(max(0, i - max_dist), min(len2, i + max_dist + 1)):
            if (s1[i] == s2[j] and hash_s2[j] == 0):
                hash_s1[i] = 1
                hash_s2[j] = 1
                match += 1
                break
    if (match == 0):
        return 0.0
    t = 0
    point = 0
    for i in range(len1):
        if (hash_s1[i]):
            while (hash_s2[point] == 0):
                point += 1
            if (s1[i] != s2[point]):
                point += 1
                t += 1
            else:
                point += 1
        t /= 2
    return ((match / len1 + match / len2 + (match - t) / match) / 3.0)


def jaro_Winkler(s1, s2):
    jaro_dist = jaro_distance(s1, s2)
    if (jaro_dist > 0.7):
        prefix = 0
        for i in range(min(len(s1), len(s2))):
            if (s1[i] == s2[i]):
                prefix += 1
            else:
                break
        prefix = min(4, prefix)
        jaro_dist += 0.1 * prefix * (1 - jaro_dist)
    return jaro_dist


if __name__ == "__main__":
    s1 = "TRATE"
    s2 = "TRACE"
    print("Jaro-Winkler Similarity =", jaro_Winkler(s1, s2))

# Expected output:
Jaro-Winkler Similarity = 0.9066666666666667
# check if a word is present in a sentence | function that returns true if the word is found ; to break the sentence in words ; to temporarily store each individual word ; comparing the current word with the word to be searched ; 
def isWordPresent(sentence, word):
    s = sentence .split(" ")
    for i in s:
        if (i == word):
            return True
    return False


s = "Geeks for Geeks"
word = "Geeks"
if (isWordPresent(s, word)):
    print("Yes")
else:
    print("No")

# Expected output:
Yes
# check if a word is present in a sentence | function that returns true if the word is found ; to convert the word in uppercase ; to convert the complete sentence in uppercase ; to break the sentence in words ; to store the individual words of the sentence ; compare the current word with the word to be searched ; 
def isWordPresent(sentence, word):
    word = word .upper()
    sentence = sentence .upper()
    s = sentence .split()
    for temp in s:
        if (temp == word):
            return True
    return False


if __name__ == "__main__":
    s = "Geeks for Geeks"
    word = "geeks"
    if (isWordPresent(s, word)):
        print("Yes")
    else:
        print("No")

# Expected output:
Yes
# count of 1 | function to return the count of required characters ; while there are characters left ; single bit character ; two - bit character ; update the count ; 
def countChars(string, n):
    i = 0
    cnt = 0
    while (i < n):
        if (string[i] == '0'):
            i += 1
        else:
            i += 2
        cnt += 1
    return cnt


if __name__ == "__main__":
    string = "11010"
    n = len(string)
    print(countChars(string, n))

# Expected output:
3
# print the frequency of each character in alphabetical order | python3 implementation of the approach ; function to print the frequency of each of the characters of s in alphabetical order ; to store the frequency of the characters ; update the frequency array ; print the frequency in alphatecial order ; if the current alphabet doesn 't  appear in the string ; 

MAX = 26


def compressString(s, n):
    freq = [0] * MAX
    for i in range(n):
        freq[ord(s[i]) - ord('a')] += 1
    for i in range(MAX):
        if (freq[i] == 0):
            continue
        print((chr)(i + ord('a')), freq[i], end=" ")


if __name__ == "__main__":
    s = "geeksforgeeks"
    n = len(s)
    compressString(s, n)

# Expected output:
e 4 f 1 g 2 k 2 o 1 r 1 s 2
# find the number obtained after concatenation of binary representation of m and n | python3 implementation of the approach ; function to convert decimal number n to its binary representation stored as an array arr [ ] ; funtion to convert the number represented as a binary array arr [ ] its decimal equivalent ; function to concatenate the binary numbers and return the decimal result ; number of bits in both the numbers ; convert the bits in both the gers to the arrays a [ ] and b [ ] ; c [ ] will be the binary array for the result ; update the c [ ] array ; return the decimal equivalent of the result ; 

import math


def decBinary(arr, n):
    k = int(math .log2(n))
    while (n > 0):
        arr[k] = n % 2
        k = k - 1
        n = n // 2


def binaryDec(arr, n):
    ans = 0
    for i in range(0, n):
        ans = ans + (arr[i] << (n - i - 1))
    return ans


def concat(m, n):
    k = int(math .log2(m)) + 1
    l = int(math .log2(n)) + 1
    a = [0 for i in range(0, k)]
    b = [0 for i in range(0, l)]
    c = [0 for i in range(0, k + l)]
    decBinary(a, m)
    decBinary(b, n)
    iin = 0
    for i in range(0, k):
        c[iin] = a[i]
        iin = iin + 1
    for i in range(0, l):
        c[iin] = b[i]
        iin = iin + 1
    return (binaryDec(c, k + l))


m = 4
n = 5
print(concat(m, n))

# Expected output:
37
# find the number obtained after concatenation of binary representation of m and n | utility function to calculate binary length of a number . ; function to concatenate the binary numbers and return the decimal result ; find binary length of n ; left binary shift m and then add n ; 
def getBinaryLength(n):
    length = 0
    while (n > 0):
        length += 1
        n //= 2
    return length


def concat(m, n):
    length = getBinaryLength(n)
    return (m << length) + n


m, n = 4, 5
print(concat(m, n))

# Expected output:
37
# xor two binary strings of unequal lengths | function to insert n 0 s in the beginning of the given string ; function to return the xor of the given strings ; lengths of the given strings ; make both the strings of equal lengths by inserting 0 s in the beginning ; updated length ; to store the resultant xor ; 
def addZeros(strr, n):
    for i in range(n):
        strr = "0" + strr
    return strr


def getXOR(a, b):
    aLen = len(a)
    bLen = len(b)
    if (aLen > bLen):
        b = addZeros(b, aLen - bLen)
    elif (bLen > aLen):
        a = addZeros(a, bLen - aLen)
    lenn = max(aLen, bLen)
    res = ""
    for i in range(lenn):
        if (a[i] == b[i]):
            res += "0"
        else:
            res += "1"
    return res


a = "11001"
b = "111111"
print(getXOR(a, b))

# Expected output:
100110
# minimum operations required to make the string satisfy the given condition | python implementation of the approach ; function to return the minimum operations required ; to store the first and the last occurrence of all the characters ; set the first and the last occurrence of all the characters to - 1 ; update the occurrences of the characters ; only set the first occurrence if it hasn 't already been set ; to store the minimum operations ; if the frequency of the current character in the string is less than 2 ; count of characters to be removed so that the string starts and ends at the current character ; 

MAX = 26


def minOperation(str, len):
    first, last = [0] * MAX, [0] * MAX
    for i in range(MAX):
        first[i] = -1
        last[i] = -1
    for i in range(len):
        index = (ord(str[i]) - ord('a'))
        if (first[index] == -1):
            first[index] = i
        last[index] = i
    minOp = -1
    for i in range(MAX):
        if (first[i] == -1 or first[i] == last[i]):
            continue
        cnt = len - (last[i] - first[i] + 1)
        if (minOp == -1 or cnt < minOp):
            minOp = cnt
    return minOp


str = "abcda"
len = len(str)
print(minOperation(str, len))

# Expected output:
0
# queries to find the count of vowels in the substrings of the given string | python3 implementation of the approach ; function that returns true if ch is a vowel ; function to return the count of vowels in the substring str [ l ... r ] ; to store the count of vowels ; for every character in the index range [ l , r ] ; if the current character is a vowel ; for every query ; find the count of vowels for the current query ; 

N = 2


def isVowel(ch):
    return (ch == 'a' or ch == 'e' or ch == 'i' or ch == 'o' or ch == 'u')


def countVowels(string, l, r):
    cnt = 0
    for i in range(l, r + 1):
        if (isVowel(string[i])):
            cnt += 1
    return cnt


def performQueries(string, queries, q):
    for i in range(q):
        print(countVowels(string, queries[i][0], queries[i][1]))


if __name__ == "__main__":
    string = "geeksforgeeks"
    queries = [[1, 3], [2, 4], [1, 9]]
    q = len(queries)
    performQueries(string, queries, q)

# Expected output:
2
1
4
# reduce the string to minimum length with the given operation | function to return the minimum possible length str can be reduced to with the given operation ; stack to store the characters of the given string ; for every character of the string ; if the stack is empty then push the current character in the stack ; get the top character ; if the top element is not equal to the current element and it only differs in the case ; pop the top element from stack ; else push the current element ; 
def minLength(string, l):
    s = []
    for i in range(l):
        if (len(s) == 0):
            s .append(string[i])
        else:
            c = s[-1]
            if (c != string[i] and c .upper() == string[i].upper()):
                s .pop()
            else:
                s .append(string[i])
    return len(s)


if __name__ == "__main__":
    string = "ASbBsd"
    l = len(string)
    print(minLength(string, l))

# Expected output:
2
# check whether two strings can be made equal by copying their characters with the adjacent ones | python3 implementation of the approach ; function that returns true if both the strings can be made equal with the given operation ; lengths of both the strings have to be equal ; to store the frequency of the characters of str1 ; for every character of str2 ; if current character of str2 also appears in str1 ; 

MAX = 26


def canBeMadeEqual(str1, str2):
    len1 = len(str1)
    len2 = len(str2)
    if (len1 == len2):
        freq = [0 for i in range(MAX)]
        for i in range(len1):
            freq[ord(str1[i]) - ord('a')] += 1
        for i in range(len2):
            if (freq[ord(str2[i]) - ord('a')] > 0):
                return True
    return False


str1 = "abc"
str2 = "defa"
if (canBeMadeEqual(str1, str2)):
    print("Yes")
else:
    print("No")

# Expected output:
No
# minimum characters that are to be inserted such that no three consecutive characters are same | function to return the count of characters that are to be inserted in str1 such that no three consecutive characters are same ; to store the count of operations required ; a character needs to be inserted after str1 [ i + 1 ] ; current three consecutive characters are not same ; 
def getCount(str1, n):
    cnt = 0
    i = 0
    while (i < n - 2):
        if (str1[i] == str1[i + 1] and str1[i] == str1[i + 2]):
            cnt += 1
            i = i + 2
        else:
            i += 1
    return cnt


str1 = "aabbbcc"
n = len(str1)
print(getCount(str1, n))

# Expected output:
1
# find the number of strings formed using distinct characters of a given string | function to return the factorial of n ; function to return the count of all possible strings that can be formed with the characters of the given string without repeating characters ; to store the distinct characters of the string str ; 
def fact(n):
    fact = 1
    for i in range(1, n + 1):
        fact *= i
    return fact


def countStrings(string, n):
    distinct_char = set()
    for i in range(n):
        distinct_char .add(string[i])
    return fact(len(distinct_char))


if __name__ == "__main__":
    string = "geeksforgeeks"
    n = len(string)
    print(countStrings(string, n))

# Expected output:
5040
# find the character made by adding all the characters of the given string | function to return the required character ; to store the summ of the characters of the given string ; add the current character to the summ ; return the required character ; 
def getChar(strr):
    summ = 0
    for i in range(len(strr)):
        summ += (ord(strr[i]) - ord('a') + 1)
    if (summ % 26 == 0):
        return ord('z')
    else:
        summ = summ % 26
        return chr(ord('a') + summ - 1)


strr = "gfg"
print(getChar(strr))

# Expected output:
t
# reverse the given string in the range [ l , r ] | function to return the string after reversing characters in the range [ l , r ] ; invalid range ; while there are characters to swap ; swap ( str [ l ] , str [ r ] ) ; 
def reverse(string, length, l, r):
    if (l < 0 or r >= length or l > r):
        return string
    string = list(string)
    while (l < r):
        c = string[l]
        string[l] = string[r]
        string[r] = c
        l += 1
        r -= 1
    return "".join(string)


if __name__ == "__main__":
    string = "geeksforgeeks"
    length = len(string)
    l = 5
    r = 7
    print(reverse(string, length, l, r))

# Expected output:
geeksrofgeeks
# check if expression contains redundant bracket or not | set 2 | function to check for redundant braces ; count of no of signs ; 
def IsRedundantBraces(A):
    a, b = 0, 0
    for i in range(len(A)):
        if (A[i] == '(' and A[i + 2] == ')'):
            return True
        if (A[i] == '*' or A[i] == '+' or A[i] == '-' or A[i] == '/'):
            a += 1
        if (A[i] == '('):
            b += 1
    if (b > a):
        return True
    return False


if __name__ == '__main__':
    A = "(((a+b) + c) + d)"
    if (IsRedundantBraces(A)):
        print("YES")
    else:
        print("NO")

# Expected output:
NO
# convert an unbalanced bracket sequence to a balanced sequence | function to return balancedbrackets string ; initializing dep to 0 ; stores maximum negative depth ; if dep is less than mindep ; if mindep is less than 0 then there is need to add ' ( ' at the front ; reinitializing to check the updated string ; if dep is not 0 then there is need to add ' ) ' at the back ; 
def balancedBrackets(Str):
    dep = 0
    minDep = 0
    for i in Str:
        if (i == '('):
            dep += 1
        else:
            dep -= 1
        if (minDep > dep):
            minDep = dep
    if (minDep < 0):
        for i in range(abs(minDep)):
            Str = '(' + Str
    dep = 0
    for i in Str:
        if (i == '('):
            dep += 1
        else:
            dep -= 1
    if (dep != 0):
        for i in range(dep):
            Str = Str + ')'
    return Str


Str = ")))()"
print(balancedBrackets(Str))

# Expected output:
((()))()
# minimum operations required to convert a binary string to all 0 s or all 1 s | function to return the count of minimum operations required ; increment count when consecutive characters are different ; answer is rounding off the ( count / 2 ) to lower ; 
def minOperations(str, n):
    count = 0
    for i in range(n - 1):
        if (str[i] != str[i + 1]):
            count += 1
    return (count + 1) // 2


str = "000111"
n = len(str)
print(minOperations(str, n))

# Expected output:
1
# append a digit in the end to make the number equal to the length of the remaining string | function to return the required digit ; to store the position of the first numeric digit in the string ; to store the length of the string without the numeric digits in the end ; pw stores the current power of 10 and num is to store the number which is appended in the end ; if current character is a numeric digit ; get the current digit ; build the number ; if number exceeds the length ; next power of 10 ; append 0 in the end ; required number that must be added ; if number is not a single digit ; 
def find_digit(s, n):
    first_digit = -1
    for i in range(n - 1, -1, -1):
        if s[i] < '0' or s[i] > '9':
            first_digit = i
            break
    first_digit += 1
    s_len = first_digit
    num = 0
    pw = 1
    i = n - 1
    while i >= 0:
        if s[i] >= '0' and s[i] <= '9':
            digit = ord(s[i]) - ord('0')
            num = num + (pw * digit)
            if num >= s_len:
                return -1
            pw = pw * 10
        i -= 1
    num = num * 10
    req = s_len - num
    if req > 9 or req < 0:
        return -1
    return req


if __name__ == "__main__":
    s = "abcd0"
    n = len(s)
    print(find_digit(s, n))

# Expected output:
4
# check whether str1 can be converted to str2 with the given operations | function that returns true if str1 can be converted to str2 with the given operations ; traverse from left to right ; if the two characters do not match ; if possible to combine ; if not possible to combine ; if the two characters match ; if possible to convert one string to another ; 
def canConvert(str1, str2):
    i, j = 0, 0
    while (i < len(str1) and j < len(str2)):
        if (str1[i] != str2[j]):
            if (str1[i] == '0' and str2[j] == '1' and i +
                    1 < len(str1) and str1[i + 1] == '0'):
                i += 2
                j += 1
            else:
                return False
        else:
            i += 1
            j += 1
    if (i == len(str1) and j == len(str2)):
        return True
    return False


str1 = "00100"
str2 = "111"
if (canConvert(str1, str2)):
    print("Yes")
else:
    print("No")

# Expected output:
Yes