giulio98/xlcost-single-prompt huggingface dataset:
# boyer moore algorithm | good suffix heuristic | preprocessing for strong good suffix rule ; m is the length of pattern ; if character at position i - 1 is not equivalent to character at j - 1 , then continue searching to right of the pattern for border ; the character preceding the occurrence of t in pattern p is different than the mismatching character in p , we stop skipping the occurrences and shift the pattern from i to j ; update the position of next border ; p [ i - 1 ] matched with p [ j - 1 ] , border is found . store the beginning position of border ; preprocessing for case 2 ; set the border position of the first character of the pattern to all indices in array shift having shift [ i ] = 0 ; suffix becomes shorter than bpos [ 0 ] , use the position of next widest border as value of j ; search for a pattern in given text using boyer moore algorithm with good suffix rule ; s is shift of the pattern with respect to text ; initialize all occurrence of shift to 0 ; do preprocessing ; keep reducing index j of pattern while characters of pattern and text are matching at this shift s ; if the pattern is present at the current shift , then index j will become - 1 after the above loop ; pat [ i ] != pat [ s + j ] so shift the pattern shift [ j + 1 ] times ; 
def preprocess_strong_suffix(shift, bpos, pat, m):
    i = m
    j = m + 1
    bpos[i] = j
    while i > 0:
        while j <= m and pat[i - 1] != pat[j - 1]:
            if shift[j] == 0:
                shift[j] = j - i
            j = bpos[j]
        i -= 1
        j -= 1
        bpos[i] = j


def preprocess_case2(shift, bpos, pat, m):
    j = bpos[0]
    for i in range(m + 1):
        if shift[i] == 0:
            shift[i] = j
        if i == j:
            j = bpos[j]


def search(text, pat):
    s = 0
    m = len(pat)
    n = len(text)
    bpos = [0] * (m + 1)
    shift = [0] * (m + 1)
    preprocess_strong_suffix(shift, bpos, pat, m)
    preprocess_case2(shift, bpos, pat, m)
    while s <= n - m:
        j = m - 1
        while j >= 0 and pat[j] == text[s + j]:
            j -= 1
        if j < 0:
            print("pattern occurs at shift = %d" % s)
            s += shift[0]
        else:
            s += shift[j + 1]


if __name__ == "__main__":
    text = "ABAAAABAACD"
    pat = "ABA"
    search(text, pat)

# Expected output:
pattern occurs at shift = 0
pattern occurs at shift = 5
# maximum length prefix of one string that occurs as subsequence in another | return the maximum length prefix which is subsequence . ; iterating string t . ; if end of string s . ; if character match , increment counter . ; 
def maxPrefix(s, t):
    count = 0
    for i in range(0, len(t)):
        if (count == len(s)):
            break
        if (t[i] == s[count]):
            count = count + 1
    return count


S = "digger"
T = "biggerdiagram"
print(maxPrefix(S, T))

# Expected output:
3
# replace all occurrences of string ab with c without using extra space | python 3 program to replace all occurrences of " ab " with " c " ; start traversing from second character ; if previous character is ' a ' and current character is 'b" ; replace previous character with ' c ' and move all subsequent characters one position back ; 
def translate(st):
    for i in range(1, len(st)):
        if (st[i - 1] == 'A' and st[i] == 'B'):
            st[i - 1] = 'C'
            for j in range(i, len(st) - 1):
                st[j] = st[j + 1]
            st[len(st) - 1] = ' '
    return


st = list("helloABworldABGfG")
translate(st)
print("The modified string is :")
print(''.join(st))

# Expected output:
The modified string is :
helloCworldCGfG
# find all occurrences of a given word in a matrix | python3 program to find all occurrences of the word in a matrix ; check whether given cell ( row , col ) is a valid cell or not . ; return true if row number and column number is in range ; these arrays are used to get row and column numbers of 8 neighboursof a given cell ; a utility function to do dfs for a 2d boolean matrix . it only considers the 8 neighbours as adjacent vertices ; return if current character doesn 't match with  the next character in the word ; append current character position to path ; current character matches with the last character \ in the word ; recur for all connected neighbours ; the main function to find all occurrences of the word in a matrix ; traverse through the all cells of given matrix ; occurrence of first character in matrix ; check and prif path exists ; 

ROW = 3
COL = 5


def isvalid(row, col, prevRow, prevCol):
    return (
        row >= 0) and (
        row < ROW) and (
            col >= 0) and (
                col < COL) and not (
                    row == prevRow and col == prevCol)


rowNum = [-1, -1, -1, 0, 0, 1, 1, 1]
colNum = [-1, 0, 1, -1, 1, -1, 0, 1]


def DFS(mat, row, col, prevRow, prevCol, word, path, index, n):
    if (index > n or mat[row][col] != word[index]):
        return
    path += word[index] + "(" + str(row) + ", " + str(col) + ") "
    if (index == n):
        print(path)
        return
    for k in range(8):
        if (isvalid(row + rowNum[k], col + colNum[k], prevRow, prevCol)):
            DFS(mat, row + rowNum[k], col + colNum[k],
                row, col, word, path, index + 1, n)


def findWords(mat, word, n):
    for i in range(ROW):
        for j in range(COL):
            if (mat[i][j] == word[0]):
                DFS(mat, i, j, -1, -1, word, "", 0, n)


mat = [['B', 'N', 'E', 'Y', 'S'], [
    'H', 'E', 'D', 'E', 'S'], ['S', 'G', 'N', 'D', 'E']]
word = list("DES")
findWords(mat, word, len(word) - 1)

# Expected output:
D(1, 2) E(1, 1) S(2, 0) 
D(1, 2) E(1, 3) S(0, 4) 
D(1, 2) E(1, 3) S(1, 4) 
D(2, 3) E(1, 3) S(0, 4) 
D(2, 3) E(1, 3) S(1, 4) 
D(2, 3) E(2, 4) S(1, 4)
# check if two array of string are equal by performing swapping operations | function to check whether brr [ ] can be made equal to arr [ ] by doing swapping operations ; siz variable to store size of string ; iterate till n to sort strings ; sort each string in arr [ ] ; sort each string in brr [ ] ; sort both the vectors so that all the comparable strings will be arranged ; iterate till n to compare string in arr [ ] and brr [ ] ; compare each string ; return false becaues if atleast one string is not equal then brr [ ] cannot be converted to arr [ ] ; all the strings are compared so at last return true . ; 
def checkEqualArrays(arr, brr, N):
    siz = len(arr[0])
    for i in range(N):
        temp1 = list(arr[i])
        temp1 .sort()
        arr[i] = "".join(temp1)
        temp2 = list(brr[i])
        temp2 .sort()
        brr[i] = "".join(temp2)
    arr .sort()
    brr .sort()
    for i in range(N):
        if (arr[i] != brr[i]):
            return False
    return True


if __name__ == "__main__":
    N = 2
    arr = ["bcd", "aac"]
    brr = ["aca", "dbc"]
    ans = checkEqualArrays(arr, brr, N)
    if (ans):
        print("true")
    else:
        print("false")

# Expected output:
true
# maximum length of string formed by concatenation having even frequency of each character | python3 implementation of the above approach ; function to check the string ; count the frequency of the string ; check the frequency of the string ; store the length of the new string ; function to find the longest concatenated string having every character of even frequency ; checking the string ; dont include the string ; include the string ; 

maxi = 0
ans1 = ""


def calculate(ans):
    global maxi, ans1
    dp = [0] * 26
    for i in range(len(ans)):
        dp[ord(ans[i]) - ord('A')] += 1
    for i in range(26):
        if (dp[i] % 2 == 1):
            return
    if (maxi < len(ans)):
        maxi = len(ans)
        ans1 = ans


def longestString(arr, index, string):
    if (index == len(arr)):
        return
    longestString(arr, index + 1, string)
    string += arr[index]
    calculate(string)
    longestString(arr, index + 1, string)


if __name__ == "__main__":
    A = ["ABAB", "ABF", "CDA", "AD", "CCC"]
    longestString(A, 0, "")
    print(ans1, len(ans1))

# Expected output:
ABABCDAADCCC 12
# find the next number by adding natural numbers in order on alternating indices from last | function to generate the resultant number using the given criteria ; storing end result ; find the length of numeric string ; traverse the string ; storing digit at ith position ; checking that the number would be added or not ; logic for summing the digits if the digit is greater than 10 ; storing the result ; returning the result ; 
def generateNumber(number):
    temp = 0
    adding_number = 0
    result = ""
    l = len(number)
    for i in range(l - 1, -1, -1):
        digit = ord(number[i]) - ord('0')
        if (temp % 2 == 0):
            adding_number += 1
            digit += adding_number
            if (digit >= 10):
                digit %= 9
                if (digit == 0):
                    digit = 9
        result = str(digit) + result
        temp += 1
    return result


if __name__ == "__main__":
    S = "1345"
    print(generateNumber(S))

# Expected output:
1546
# find the single digit sum of alphabetical values of a string | python program for the above approach ; traverse the given string ; if character is an alphabet ; stores the sum of order of values ; find the score ; find the single digit sum ; return the resultant sum ; 
def findTheSum(str):
    alpha = ""
    for i in range(0, len(str)):
        if ((str[i] >= 'A' and str[i] <= 'Z') or (
                str[i] >= 'a' and str[i] <= 'z')):
            alpha += str[i]
    score = 0
    n = 0
    for i in range(0, len(alpha)):
        if (alpha[i] >= 'A' and alpha[i] <= 'Z'):
            score += ord(alpha[i]) - ord('A') + 1
        else:
            score += ord(alpha[i]) - ord('a') + 1
    while (score > 0 or n > 9):
        if (score == 0):
            score = n
            n = 0
        n += score % 10
        score = score // 10
    return n


if __name__ == "__main__":
    S = "GeeksforGeeks"
    print(findTheSum(S))

# Expected output:
7
# minimum value of k such that each substring of size k has the given character | function to find the minimum value of k such that char c occurs in all k sized substrings of string s ; store the string length ; store difference of lengths of segments of every two consecutive occurrences of c ; stores the maximum difference ; store the previous occurence of char c ; check if the current character is c or not ; stores the difference of consecutive occurrences of c ; update previous occurrence of c with current occurence ; comparing diff with max ; if string doesn 't contain c ; return max ; 
def findK(s, c):
    n = len(s)
    diff = 0
    max = 0
    prev = 0
    for i in range(0, n):
        if (s[i] == c):
            diff = i - prev
            prev = i
            if (diff > max):
                max = diff
    if (max == 0):
        return -1
    return max


if __name__ == "__main__":
    S = "abdegb"
    ch = 'b'
    print(findK(S, ch))

# Expected output:
4
# count subsequences 01 in string generated by concatenation of given numeric string k times | function to calculate the number of subsequences of "01" ; store count of 0 ' s ▁ and ▁ 1' s ; count of subsequences without concatenation ; case 1 ; case 2 ; return the total count ; 
def countSubsequence(S, N, K):
    C = 0
    C1 = 0
    C0 = 0
    for i in range(0, N):
        if (S[i] == '1'):
            C1 += 1
        elif (S[i] == '0'):
            C0 += 1
    B1 = 0
    for i in range(0, N):
        if (S[i] == '1'):
            B1 += 1
        elif (S[i] == '0'):
            C = C + (C1 - B1)
    ans = C * K
    ans += (C1 * C0 * (((K) * (K - 1)) // 2))
    return ans


if __name__ == "__main__":
    S = "230013110087"
    K = 2
    N = len(S)
    print(countSubsequence(S, N, K))

# Expected output:
24
# count of distinct groups of strings formed after performing equivalent operation | function to perform the find operation to find the parent of a disjoint set ; function to perform union operation of disjoint set union ; find the parent of node a and b ; update the rank ; function to find the number of distinct strings after performing the given operations ; stores the parent elements of the sets ; stores the rank of the sets ; update parent [ i ] to i ; stores the total characters traversed through the strings ; stores the current characters traversed through a string ; update current [ i ] to false ; update current [ ch - ' a ' ] to true ; check if current [ j ] is true ; update total [ j ] to true ; add arr [ i ] [ 0 ] - ' a ' and j elements to same set ; stores the count of distinct strings ; check total [ i ] is true and parent of i is i only ; increment the value of distcount by 1 ; print the value of distcount ; 
def Find(parent, a):
    if parent[a] == a:
        parent[a] = a
        return parent[a]
    else:
        parent[a] = Find(parent, parent[a])
        return parent[a]


def Union(parent, rank, a, b):
    a = Find(parent, a)
    b = Find(parent, b)
    if (rank[a] == rank[b]):
        rank[a] += 1
    if (rank[a] > rank[b]):
        parent[b] = a
    else:
        parent[a] = b


def numOfDistinctStrings(arr, N):
    parent = [0 for _ in range(27)]
    rank = [0 for _ in range(27)]
    for j in range(0, 27):
        parent[j] = j
    total = [False for _ in range(26)]
    current = [False for _ in range(26)]
    for i in range(0, N):
        for j in range(0, 26):
            current[j] = False
        for ch in arr[i]:
            current[ord(ch) - ord('a')] = True
        for j in range(0, 26):
            if (current[j]):
                total[j] = True
                Union(parent, rank, ord(arr[i][0]) - ord('a'), j)
    distCount = 0
    for i in range(0, 26):
        if (total[i] and Find(parent, i) == i):
            distCount += 1
    print(distCount)


if __name__ == "__main__":
    arr = ["a", "ab", "b", "d"]
    N = len(arr)
    numOfDistinctStrings(arr, N)

# Expected output:
2
# minimum adjacent swaps required to make a binary string alternating | function to find the minimum number of adjacent swaps to make the string alternating ; count the no of zeros and ones ; base case ; store no of min swaps when string starts with "1" ; keep track of the odd positions ; checking for when the string starts with "1" ; adding the no of swaps to fix "1" at odd positions ; store no of min swaps when string starts with "0" ; keep track of the odd positions ; checking for when the string starts with "0" ; adding the no of swaps to fix "1" at odd positions ; returning the answer based on the conditions when string length is even ; when string length is odd ; when no of ones is greater than no of zeros ; when no of ones is greater than no of zeros ; 
def minSwaps(s):
    ones = 0
    zeros = 0
    N = len(s)
    for i in range(N):
        if s[i] == '1':
            ones += 1
        else:
            zeros += 1
    if ((N % 2 == 0 and ones != zeros) or (N %
                                           2 == 1 and abs(ones - zeros) != 1)):
        return -1
    ans_1 = 0
    j = 0
    for i in range(N):
        if (s[i] == '1'):
            ans_1 += abs(j - i)
            j += 2
    ans_0 = 0
    k = 0
    for i in range(N):
        if (s[i] == '0'):
            ans_0 += abs(k - i)
            k += 2
    if (N % 2 == 0):
        return min(ans_1, ans_0)
    else:
        if (ones > zeros):
            return ans_1
        else:
            return ans_0


if __name__ == '__main__':
    S = "110100"
    print(minSwaps(S))

# Expected output:
2
# print all ways to reach the nth stair with the jump of 1 or 2 units at a time | function to find all the ways to reach nth stair using one or two jumps ; base cases ; recur for jump1 and jump2 ; stores the total possible jumps ; add "1" with every element present in jump1 ; add "2" with every element present in jump2 ; 
def TotalPossibleJumps(N):
    if ((N - 1) == 0):
        newvec = []
        newvec .append("")
        return newvec
    else:
        if (N < 0):
            newvec = []
            return newvec
    jump1 = TotalPossibleJumps(N - 1)
    jump2 = TotalPossibleJumps(N - 2)
    totaljumps = []
    for s in jump1:
        totaljumps .append("1" + s)
    for s in jump2:
        totaljumps .append("2" + s)
    return totaljumps


if __name__ == "__main__":
    N = 3
    Ans = TotalPossibleJumps(N)
    for it in Ans:
        print(it)

# Expected output:
11
2
# find any permutation of binary string of given size not present in array | function to find a binary string of n bits that does not occur in the givrn array arr [ ] ; stores the resultant string ; loop to iterate over all the given strings in a diagonal order ; append the complement of element at current index into ans ; return answer ; 
def findString(arr, N):
    ans = ""
    for i in range(N):
        ans += '1'if arr[i][i] == '0'else '0'
    return ans


if __name__ == '__main__':
    arr = ["111", "011", "001"]
    N = len(arr)
    print(findString(arr, N))

# Expected output:
000
# check if the string has a reversible equal substring at the ends | function to print longest substring that appears at beginning of string and also at end in reverse order ; stores the resultant string ; if the characters are same ; otherwise , break ; if the string can 't be formed ; otherwise print resultant string ; 
def commonSubstring(s):
    n = len(s)
    i = 0
    j = n - 1
    ans = ""
    while (j >= 0):
        if (s[i] == s[j]):
            ans += s[i]
            i = i + 1
            j = j - 1
        else:
            break
    if (len(ans) == 0):
        print("False")
    else:
        print("True")
        print(ans)


if __name__ == "__main__":
    S = "abca"
    commonSubstring(S)

# Expected output:
True
a
# length of smallest non prime subsequence in given numeric string | function to find the smallest length of resultant subsequence ; check for a subsequence of size 1 ; check for a subsequence of size 2 ; if none of the above check is successful then subsequence must be of size 3 ; never executed ; 
def findMinimumSubsequence(S):
    flag = False
    dummy = ''
    for j in range(len(S)):
        if (S[j] != '2' and S[j] != '3' and S[j] != '5' and S[j] != '7'):
            print(1)
            flag = True
            break
    if (flag == False):
        for j in range(len(S)):
            for j1 in range(j + 1, len(S), 1):
                dummy = S[j] + S[j1]
                if (dummy != "23" and dummy !=
                        "37" and dummy != "53" and dummy != "73"):
                    print(2)
                if (flag):
                    break
                else:
                    flag = True
            if (flag):
                break
    if (flag == False):
        if (len(S) >= 3):
            print(3)
        else:
            print(-1)


if __name__ == '__main__':
    S = "237"
    findMinimumSubsequence(S)

# Expected output:
2
# minimize changes to make all characters equal by changing vowel to consonant and vice versa | python 3 program for the above approach ; function to find the minimum number of steps to make all characters equal ; initializing the variables ; store the frequency ; iterate over the string ; calculate the total number of vowels ; storing frequency of each vowel ; count the consonants ; storing the frequency of each consonant ; iterate over the 2 maps ; maximum frequency of consonant ; maximum frequency of vowel ; find the result ; 

import sys
from collections import defaultdict


def operations(s):
    ans = 0
    vowels = 0
    consonants = 0
    max_vowels = -sys .maxsize - 1
    max_consonants = -sys .maxsize - 1
    freq_consonants = defaultdict(int)
    freq_vowels = defaultdict(int)
    for i in range(len(s)):
        if (s[i] == 'a' or s[i] == 'e' or s[i] ==
                'i' or s[i] == 'o' or s[i] == 'u'):
            vowels += 1
            freq_vowels[s[i]] += 1
        else:
            consonants += 1
            freq_consonants[s[i]] += 1
    for it in freq_consonants:
        max_consonants = max(max_consonants, freq_consonants[it])
    for it in freq_vowels:
        max_vowels = max(max_vowels, freq_vowels[it])
    ans = min((2 * (vowels - max_vowels) + consonants),
              (2 * (consonants - max_vowels) + consonants))
    return ans


if __name__ == "__main__":
    S = "geeksforgeeks"
    print(operations(S))

# Expected output:
10
# count of ways to empty given string by recursively removing all adjacent duplicates | python3 implementation for the above approach ; define the dp table globally ; recursive function to calculate the dp values for range [ l , r ] ; the range is odd length ; the state is already calculated ; if the length is 2 ; total answer for this state ; variable to store the current answer . ; remove characters s [ l ] and s [ i ] . ; initialize all the states of dp to - 1 memset ( dp , - 1 , sizeof ( dp ) ) ; ; calculate all combinations ; 

import numpy as np
dp = np .zeros((505, 505))
choose = np .zeros((502, 502))


def calc(l, r, s):
    if (abs(r - l) % 2 == 0):
        return 0
    if (l > r):
        dp[l][r] = 1
        return dp[l][r]
    if (dp[l][r] != -1):
        return dp[l][r]
    if ((r - l) == 1):
        if (s[l] == s[r]):
            dp[l][r] = 1
        else:
            dp[l][r] = 0
        return dp[l][r]
    ans = 0
    for k in range(l + 1, r + 1, 2):
        temp = 1
        if (s[l] == s[k]):
            temp = calc(l + 1, k - 1, s) * calc(k + 1, r, s) * \
                choose[(r - l + 1) // 2][(r - k) // 2]
            ans += temp
    dp[l][r] = ans
    return dp[l][r]


def waysToClearString(S):
    for i in range(505):
        for j in range(505):
            dp[i][j] = -1
    n = len(S)
    choose[0][0] = 1
    for i in range(1, (n // 2) + 1):
        choose[i][0] = 1
        for j in range(1, i + 1):
            choose[i][j] = choose[i - 1][j] + choose[i - 1][j - 1]
    return calc(0, n - 1, S)


if __name__ == "__main__":
    S = "aabccb"
    print(waysToClearString(S))

# Expected output:
3.0
# divide given numeric string into at most two increasing subsequences which form an increasing string upon concatenation | function to check for valid subsequences ; stores which element belongs to which subsequence ; check for each pos if a possible subsequence exist or not ; last member of 1 subsequence ; last member of 2 nd subsequence ; check if current element can go to 2 nd subsequence ; check if the current elements belongs to first subsequence ; if the current element does not belong to any subsequence ; check if last digit of first subsequence is greater than pos ; if a subsequence is found , find the subsequences ; stores the resulting subsequences ; print the subsequence ; if no subsequence found , print - 1 ; 
def findSubsequence(str):
    n = len(str)
    res = ['0'for i in range(n)]
    for pos in range(10):
        lst1 = '0'
        flag = 1
        lst2 = chr(pos + 48)
        for i in range(n):
            if (lst2 <= str[i]):
                res[i] = '2'
                lst2 = str[i]
            elif (lst1 <= str[i]):
                res[i] = '1'
                lst1 = str[i]
            else:
                flag = 0
        if (lst1 > chr(pos + 48)):
            flag = 0
        if (flag):
            S1 = ""
            S2 = ""
            for i in range(n):
                if (res[i] == '1'):
                    S1 += str[i]
                else:
                    S2 += str[i]
            print(S1, S2)
            return
    print("-1")


if __name__ == '__main__':
    S = "040425524644"
    findSubsequence(S)
    S = "123456789"
    findSubsequence(S)

# Expected output:
0022444 44556
 123456789
# minimum swaps to balance the given brackets at any index | function to balance the given bracket by swap ; to count the number of uunbalanced pairs ; if there is an opening bracket and we encounter closing bracket then it will decrement the count of unbalanced bracket . ; else it will increment unbalanced pair count ; 
def BalancedStringBySwapping(s):
    unbalancedPair = 0
    for i in range(len(s)):
        if (unbalancedPair > 0 and s[i] == ']'):
            unbalancedPair -= 1
        elif (s[i] == '['):
            unbalancedPair += 1
    return (unbalancedPair + 1) // 2


if __name__ == "__main__":
    s = "]]][[["
    print(BalancedStringBySwapping(s))

# Expected output:
2