giulio98/xlcost-single-prompt huggingface dataset:
# count digit groupings of a number with given constraints | maximum length of input number string ; a memoization table to store results of subproblems length of string is 40 and maximum sum will be 9 * 40 = 360. ; function to find the count of splits with given condition ; terminating condition ; if already evaluated for a given sub problem then return the value ; countgroups for current sub - group is 0 ; sum of digits ; traverse all digits from current position to rest of the length of string ; if forward_sum is greater than the previous sum , then call the method again ; note : we pass current sum as previous sum ; total number of subgroups till the current position ; 

MAX = 40
dp = [[-1 for i in range(9 * MAX + 1)]for i in range(MAX)]


def countGroups(position, previous_sum, length, num):
    if (position == length):
        return 1
    if (dp[position][previous_sum] != -1):
        return dp[position][previous_sum]
    dp[position][previous_sum] = 0
    res = 0
    sum_ = 0
    for i in range(position, length):
        sum_ += (ord(num[i]) - ord('0'))
        if (sum_ >= previous_sum):
            res += countGroups(i + 1, sum_, length, num)
    dp[position][previous_sum] = res
    return res


num = "1119"
len_ = len(num)
print(countGroups(0, 0, len_, num))

# Expected output:
7
# a space optimized dp solution for 0 | val [ ] is for storing maximum profit for each weight wt [ ] is for storing weights n number of item w maximum capacity of bag dp [ w + 1 ] to store final result ; initially profit with 0 to w knapsack capacity is 0 ; iterate through all items ; traverse dp array from right to left ; above line finds out maximum of dp [ j ] ( excluding ith element value ) and val [ i ] + dp [ j - wt [ i ] ] ( including ith element value and the profit with " knapsack ▁ capacity ▁ - ▁ ith ▁ element ▁ weight " ) * ; 
def KnapSack(val, wt, n, W):
    dp = [0] * (W + 1)
    for i in range(n):
        for j in range(W, wt[i], -1):
            dp[j] = max(dp[j], val[i] + dp[j - wt[i]])
    return dp[W]


val = [7, 8, 4]
wt = [3, 8, 6]
W = 10
n = 3
print(KnapSack(val, wt, n, W))

# Expected output:
11
# find number of times a string occurs as a subsequence in given string | iterative dp function to find the number of times the second string occurs in the first string , whether continuous or discontinuous ; create a table to store results of sub - problems ; if first string is empty ; if second string is empty ; fill lookup [ ] [ ] in bottom up manner ; if last characters are same , we have two options - 1. consider last characters of both strings in solution 2. ignore last character of first string ; if last character are different , ignore last character of first string ; 
def count(a, b):
    m = len(a)
    n = len(b)
    lookup = [[0] * (n + 1)for i in range(m + 1)]
    for i in range(n + 1):
        lookup[0][i] = 0
    for i in range(m + 1):
        lookup[i][0] = 1
    for i in range(1, m + 1):
        for j in range(1, n + 1):
            if a[i - 1] == b[j - 1]:
                lookup[i][j] = lookup[i - 1][j - 1] + lookup[i - 1][j]
            else:
                lookup[i][j] = lookup[i - 1][j]
    return lookup[m][n]


if __name__ == '__main__':
    a = "GeeksforGeeks"
    b = "Gks"
    print(count(a, b))

# Expected output:
4
# longest geometric progression | returns length of the longest gp subset of sett [ ] ; base cases ; let us sort the sett first ; an entry l [ i ] [ j ] in this table stores llgp with sett [ i ] and sett [ j ] as first two elements of gp and j > i . ; initialize result ( a single element is always a gp ) ; initialize values of last column ; consider every element as second element of gp ; search for i and k for j ; two cases when i , j and k don 't form  a gp. ; i , j and k form gp , llgp with i and j as first two elements is equal to llgp with j and k as first two elements plus 1. l [ j ] [ k ] must have been filled before as we run the loop from right side ; update overall llgp ; change i and k to fill more l [ i ] [ j ] values for current j ; if the loop was stopped due to k becoming more than n - 1 , set the remaining entries in column j as 1 or 2 based on divisibility of sett [ j ] by sett [ i ] ; return result ; 
def lenOfLongestGP(sett, n):
    if n < 2:
        return n
    if n == 2:
        return 2 if (sett[1] % sett[0] == 0)else 1
    sett .sort()
    L = [[0 for i in range(n)]for i in range(n)]
    llgp = 1
    for i in range(0, n - 1):
        if sett[n - 1] % sett[i] == 0:
            L[i][n - 1] = 2
            if 2 > llgp:
                llgp = 2
        else:
            L[i][n - 1] = 1
    L[n - 1][n - 1] = 1
    for j in range(n - 2, 0, -1):
        i = j - 1
        k = j + 1
        while i >= 0 and k <= n - 1:
            if sett[i] * sett[k] < sett[j] * sett[j]:
                k += 1
            elif sett[i] * sett[k] > sett[j] * sett[j]:
                if sett[j] % sett[i] == 0:
                    L[i][j] = 2
                else:
                    L[i][j] = 1
                i -= 1
            else:
                if sett[j] % sett[i] == 0:
                    L[i][j] = L[j][k] + 1
                    if L[i][j] > llgp:
                        llgp = L[i][j]
                else:
                    L[i][j] = 1
                i -= 1
                k += 1
        while i >= 0:
            if sett[j] % sett[i] == 0:
                L[i][j] = 2
            else:
                L[i][j] = 1
            i -= 1
    return llgp


if __name__ == '__main__':
    set1 = [1, 3, 9, 27, 81, 243]
    n1 = len(set1)
    print(lenOfLongestGP(set1, n1))
    set2 = [1, 3, 4, 9, 7, 27]
    n2 = len(set2)
    print(lenOfLongestGP(set2, n2))
    set3 = [2, 3, 5, 7, 11, 13]
    n3 = len(set3)
    print(lenOfLongestGP(set3, n3))

# Expected output:
6
4
1
# print maximum length chain of pairs | dynamic programming solution to construct maximum length chain of pairs ; comparator function for sort function ; function to construct maximum length chain of pairs ; sort by start time ; l [ i ] stores maximum length of chain of arr [ 0. . i ] that ends with arr [ i ] . ; l [ 0 ] is equal to arr [ 0 ] ; start from index 1 ; for every j less than i ; l [ i ] = { max ( l [ j ] ) } + arr [ i ] where j < i and arr [ j ] . b < arr [ i ] . a ; print max length vector ; 

class Pair:
    def __init__(self, a, b):
        self .a = a
        self .b = b

    def __lt__(self, other):
        return self .a < other .a


def maxChainLength(arr):
    arr .sort()
    L = [[]for x in range(len(arr))]
    L[0].append(arr[0])
    for i in range(1, len(arr)):
        for j in range(i):
            if (arr[j].b < arr[i].a and len(L[j]) > len(L[i])):
                L[i] = L[j]
        L[i].append(arr[i])
    maxChain = []
    for x in L:
        if len(x) > len(maxChain):
            maxChain = x
    for pair in maxChain:
        print("({a},{b})".format(a=pair .a, b=pair .b), end=" ")
    print()


if __name__ == "__main__":
    arr = [Pair(5, 29), Pair(39, 40), Pair(15, 28), Pair(27, 40), Pair(50, 90)]
    n = len(arr)
    maxChainLength(arr)

# Expected output:
(5,29) (39,40) (50,90)
# printing longest bitonic subsequence | utility function to print longest bitonic subsequence ; function to construct and print longest bitonic subsequence ; lis [ i ] stores the length of the longest increasing subsequence ending with arr [ i ] ; initialize lis [ 0 ] to arr [ 0 ] ; compute lis values from left to right ; for every j less than i ; lds [ i ] stores the length of the longest decreasing subsequence starting with arr [ i ] ; initialize lds [ n - 1 ] to arr [ n - 1 ] ; compute lds values from right to left ; for every j greater than i ; reverse as vector as we 're inserting at end ; lds [ i ] now stores maximum decreasing subsequence of arr [ i . . n ] that starts with arr [ i ] ; find maximum value of size of lis [ i ] + size of lds [ i ] - 1 ; print all but last element of lis [ maxindex ] vector ; print all elements of lds [ maxindex ] vector ; 
def _print(arr: list, size: int):
    for i in range(size):
        print(arr[i], end=" ")


def printLBS(arr: list, n: int):
    LIS = [0] * n
    for i in range(n):
        LIS[i] = []
    LIS[0].append(arr[0])
    for i in range(1, n):
        for j in range(i):
            if ((arr[j] < arr[i]) and (len(LIS[j]) > len(LIS[i]))):
                LIS[i] = LIS[j].copy()
        LIS[i].append(arr[i])
    LDS = [0] * n
    for i in range(n):
        LDS[i] = []
    LDS[n - 1].append(arr[n - 1])
    for i in range(n - 2, -1, -1):
        for j in range(n - 1, i, -1):
            if ((arr[j] < arr[i]) and (len(LDS[j]) > len(LDS[i]))):
                LDS[i] = LDS[j].copy()
        LDS[i].append(arr[i])
    for i in range(n):
        LDS[i] = list(reversed(LDS[i]))
    max = 0
    maxIndex = -1
    for i in range(n):
        if (len(LIS[i]) + len(LDS[i]) - 1 > max):
            max = len(LIS[i]) + len(LDS[i]) - 1
            maxIndex = i
    _print(LIS[maxIndex], len(LIS[maxIndex]) - 1)
    _print(LDS[maxIndex], len(LDS[maxIndex]))


if __name__ == "__main__":
    arr = [1, 11, 2, 10, 4, 5, 2, 1]
    n = len(arr)
    printLBS(arr, n)

# Expected output:
1 11 10 5 2 1
# find if string is k | find if given string is k - palindrome or not ; create a table to store results of subproblems ; fill dp [ ] [ ] in bottom up manner ; if first string is empty , only option is to remove all characters of second string ; if second string is empty , only option is to remove all characters of first string ; if last characters are same , ignore last character and recur for remaining string ; if last character are different , remove it and find minimum ; dp [ i ] [ j ] = 1 + min ( dp [ i - 1 ] [ j ] , remove from str1 ( dp [ i ] [ j - 1 ] ) ) remove from str2 ; returns true if str is k palindrome . ; 
def isKPalDP(str1, str2, m, n):
    dp = [[0] * (n + 1) for _ in range(m + 1)]
    for i in range(m + 1):
        for j in range(n + 1):
            if not i:
                dp[i][j] = j
            elif not j:
                dp[i][j] = i
            elif (str1[i - 1] == str2[j - 1]):
                dp[i][j] = dp[i - 1][j - 1]
            else:
                dp[i][j] = 1 + min(dp[i - 1][j],
                                   (dp[i][j - 1]))
    return dp[m][n]


def isKPal(string, k):
    revStr = string[::-1]
    l = len(string)
    return (isKPalDP(string, revStr, l, l) <= k * 2)


string = "acdcb"
k = 2
print("Yes"if isKPal(string, k)else "No")

# Expected output:
Yes
# a space optimized solution of lcs | returns length of lcs for x [ 0. . m - 1 ] , y [ 0. . n - 1 ] ; find lengths of two strings ; binary index , used to index current row and previous row . ; compute current binary index ; last filled entry contains length of lcs for x [ 0. . n - 1 ] and y [ 0. . m - 1 ] ; 
def lcs(X, Y):
    m = len(X)
    n = len(Y)
    L = [[0 for i in range(n + 1)]for j in range(2)]
    bi = bool
    for i in range(m):
        bi = i & 1
        for j in range(n + 1):
            if (i == 0 or j == 0):
                L[bi][j] = 0
            elif (X[i] == Y[j - 1]):
                L[bi][j] = L[1 - bi][j - 1] + 1
            else:
                L[bi][j] = max(L[1 - bi][j], L[bi][j - 1])
    return L[bi][n]


X = "AGGTAB"
Y = "GXTXAYB"
print("Length of LCS is", lcs(X, Y))

# Expected output:
Length of LCS is 4
# count number of subsets having a particular xor value | python 3 arr dynamic programming solution to finding the number of subsets having xor of their elements as k ; returns count of subsets of arr [ ] with xor value equals to k . ; find maximum element in arr [ ] ; maximum possible xor value ; initializing all the values of dp [ i ] [ j ] as 0 ; the xor of empty subset is 0 ; fill the dp table ; the answer is the number of subset from set arr [ 0. . n - 1 ] having xor of elements as k ; 

import math


def subsetXOR(arr, n, k):
    max_ele = arr[0]
    for i in range(1, n):
        if arr[i] > max_ele:
            max_ele = arr[i]
    m = (1 << (int)(math .log2(max_ele) + 1)) - 1
    if (k > m):
        return 0
    dp = [[0 for i in range(m + 1)]for i in range(n + 1)]
    dp[0][0] = 1
    for i in range(1, n + 1):
        for j in range(m + 1):
            dp[i][j] = (dp[i - 1][j] + dp[i - 1][j ^ arr[i - 1]])
    return dp[n][k]


arr = [1, 2, 3, 4, 5]
k = 4
n = len(arr)
print("Count of subsets is", subsetXOR(arr, n, k))

# Expected output:
Count of subsets is 4
# partition a set into two subsets such that the difference of subset sums is minimum | a recursive python3 program to solve minimum sum partition problem . ; returns the minimum value of the difference of the two sets . ; calculate sum of all elements ; create an 2d list to store results of subproblems ; initialize first column as true . 0 sum is possible with all elements . ; initialize top row , except dp [ 0 ] [ 0 ] , as false . with 0 elements , no other sum except 0 is possible ; fill the partition table in bottom up manner ; if i 'th element is excluded ; if i 'th element is included ; initialize difference of two sums . ; find the largest j such that dp [ n ] [ j ] is true where j loops from sum / 2 t0 0 ; 

import sys


def findMin(a, n):
    su = 0
    su = sum(a)
    dp = [[0 for i in range(su + 1)]for j in range(n + 1)]
    for i in range(n + 1):
        dp[i][0] = True
    for j in range(1, su + 1):
        dp[0][j] = False
    for i in range(1, n + 1):
        for j in range(1, su + 1):
            dp[i][j] = dp[i - 1][j]
            if a[i - 1] <= j:
                dp[i][j] |= dp[i - 1][j - a[i - 1]]
    diff = sys .maxsize
    for j in range(su // 2, -1, -1):
        if dp[n][j]:
            diff = su - (2 * j)
            break
    return diff


a = [3, 1, 4, 2, 2, 1]
n = len(a)
print("The minimum difference between " "2 sets is ", findMin(a, n))

# Expected output:
The minimum difference between 2 sets is  1
# count number of paths with at | python3 program to count number of paths with maximum k turns allowed ; table to store results of subproblems ; returns count of paths to reach ( i , j ) from ( 0 , 0 ) using at - most k turns . d is current direction , d = 0 indicates along row , d = 1 indicates along column . ; if invalid row or column indexes ; if current cell is top left itself ; if 0 turns left ; if direction is row , then we can reach here only if direction is row and row is 0. ; if direction is column , then we can reach here only if direction is column and column is 0. ; if this subproblem is already evaluated ; if current direction is row , then count paths for two cases 1 ) we reach here through previous row . 2 ) we reach here through previous column , so number of turns k reduce by 1. ; similar to above if direction is column ; this function mainly initializes ' dp ' array as - 1 and calls countpathsutil ( ) ; if ( 0 , 0 ) is target itself ; recur for two cases : moving along row and along column ; 

MAX = 100
dp = [[[[-1 for col in range(2)]for col in range(MAX)]
       for row in range(MAX)]for row in range(MAX)]


def countPathsUtil(i, j, k, d):
    if (i < 0 or j < 0):
        return 0
    if (i == 0 and j == 0):
        return 1
    if (k == 0):
        if (d == 0 and i == 0):
            return 1
        if (d == 1 and j == 0):
            return 1
        return 0
    if (dp[i][j][k][d] != -1):
        return dp[i][j][k][d]
    if (d == 0):
        dp[i][j][k][d] = countPathsUtil(
            i, j - 1, k, d) + countPathsUtil(i - 1, j, k - 1, not d)
        return dp[i][j][k][d]
    dp[i][j][k][d] = countPathsUtil(
        i - 1, j, k, d) + countPathsUtil(i, j - 1, k - 1, not d)
    return dp[i][j][k][d]


def countPaths(i, j, k):
    if (i == 0 and j == 0):
        return 1
    return countPathsUtil(i - 1, j, k, 1) + countPathsUtil(i, j - 1, k, 0)


if __name__ == '__main__':
    m = 3
    n = 3
    k = 2
    print("Number of paths is", countPaths(m - 1, n - 1, k))

# Expected output:
Number of paths is 4
# find minimum possible size of array with given rules for removing elements | python3 program to find size of minimum possible array after removing elements according to given rules ; dp [ i ] [ j ] denotes the minimum number of elements left in the subarray arr [ i . . j ] . ; if already evaluated ; if size of array is less than 3 ; initialize result as the case when first element is separated ( not removed using given rules ) ; now consider all cases when first element forms a triplet and removed . check for all possible triplets ( low , i , j ) ; check if this triplet follows the given rules of removal . and elements between ' low ' and ' i ' , and between ' i ' and ' j ' can be recursively removed . ; insert value in table and return result ; this function mainly initializes dp table and calls recursive function minsizerec ; 

MAX = 1000
dp = [[-1 for i in range(MAX)]for i in range(MAX)]


def minSizeRec(arr, low, high, k):
    if dp[low][high] != -1:
        return dp[low][high]
    if (high - low + 1) < 3:
        return (high - low + 1)
    res = 1 + minSizeRec(arr, low + 1, high, k)
    for i in range(low + 1, high):
        for j in range(i + 1, high + 1):
            if (
                arr[i] == (
                    arr[low] +
                    k) and arr[j] == (
                    arr[low] +
                    2 *
                    k) and minSizeRec(
                    arr,
                    low +
                    1,
                    i -
                    1,
                    k) == 0 and minSizeRec(
                    arr,
                    i +
                    1,
                    j -
                    1,
                    k) == 0):
                res = min(res, minSizeRec(arr, j + 1, high, k))
    dp[low][high] = res
    return res


def minSize(arr, n, k):
    dp = [[-1 for i in range(MAX)]for i in range(MAX)]
    return minSizeRec(arr, 0, n - 1, k)


if __name__ == '__main__':
    arr = [2, 3, 4, 5, 6, 4]
    n = len(arr)
    k = 1
    print(minSize(arr, n, k))

# Expected output:
0
# find number of solutions of a linear equation of n variables | recursive function that returns count of solutions for given rhs value and coefficients coeff [ stat ... end ] ; base case ; initialize count of solutions ; one by one subtract all smaller or equal coefficients and recur ; 
def countSol(coeff, start, end, rhs):
    if (rhs == 0):
        return 1
    result = 0
    for i in range(start, end + 1):
        if (coeff[i] <= rhs):
            result += countSol(coeff, i, end, rhs - coeff[i])
    return result


coeff = [2, 2, 5]
rhs = 4
n = len(coeff)
print(countSol(coeff, 0, n - 1, rhs))

# Expected output:
3
# maximum weight transformation of a given string | returns weight of the maximum weight transformation ; base case ; if this subproblem is already solved ; don 't make pair, so  weight gained is 1 ; if we can make pair ; if elements are dissimilar ; if elements are similar so for making a pair we toggle any of them . since toggle cost is 1 so overall weight gain becomes 3 ; save and return maximum of above cases ; initializes lookup table and calls getmaxrec ( ) ; create and initialize lookup table ; call recursive function ; 
def getMaxRec(string, i, n, lookup):
    if i >= n:
        return 0
    if lookup[i] != -1:
        return lookup[i]
    ans = 1 + getMaxRec(string, i + 1, n, lookup)
    if i + 1 < n:
        if string[i] != string[i + 1]:
            ans = max(4 + getMaxRec(string, i + 2, n, lookup), ans)
        else:
            ans = max(3 + getMaxRec(string, i + 2, n, lookup), ans)
    lookup[i] = ans
    return ans


def getMaxWeight(string):
    n = len(string)
    lookup = [-1] * (n)
    return getMaxRec(string, 0, len(string), lookup)


if __name__ == "__main__":
    string = "AAAAABB"
    print("Maximum weight of a transformation of",
          string, "is", getMaxWeight(string))

# Expected output:
Maximum weight of a transformation of AAAAABB is 11
# minimum steps to reach a destination | python program to count number of steps to reach a point ; source -> source vertex step -> value of last step taken dest -> destination vertex ; base cases ; if we go on positive side ; if we go on negative side ; minimum of both cases ; 

import sys


def steps(source, step, dest):
    if (abs(source) > (dest)):
        return sys .maxsize
    if (source == dest):
        return step
    pos = steps(source + step + 1, step + 1, dest)
    neg = steps(source - step - 1, step + 1, dest)
    return min(pos, neg)


dest = 11
print("No. of steps required", " to reach ", dest, " is ", steps(0, 0, dest))

# Expected output:
No. of steps required  to reach  11  is  5
# longest common substring | dp | function to find the length of the longest lcs ; create dp table ; 
def LCSubStr(s, t, n, m):
    dp = [[0 for i in range(m + 1)]for j in range(2)]
    res = 0
    for i in range(1, n + 1):
        for j in range(1, m + 1):
            if (s[i - 1] == t[j - 1]):
                dp[i % 2][j] = dp[(i - 1) % 2][j - 1] + 1
                if (dp[i % 2][j] > res):
                    res = dp[i % 2][j]
            else:
                dp[i % 2][j] = 0
    return res


X = "OldSite:GeeksforGeeks.org"
Y = "NewSite:GeeksQuiz.com"
m = len(X)
n = len(Y)
print(LCSubStr(X, Y, m, n))

# Expected output:
10
# longest common substring | dp | returns length of function for longest common substring of x [ 0. . m - 1 ] and y [ 0. . n - 1 ] ; 
def lcs(i, j, count):
    if (i == 0 or j == 0):
        return count
    if (X[i - 1] == Y[j - 1]):
        count = lcs(i - 1, j - 1, count + 1)
    count = max(count, max(lcs(i, j - 1, 0), lcs(i - 1, j, 0)))
    return count


if __name__ == "__main__":
    X = "abcdxyz"
    Y = "xyzabcd"
    n = len(X)
    m = len(Y)
    print(lcs(n, m, 0))

# Expected output:
4
# make array elements equal by replacing adjacent elements with their xor | function to check if it is possible to make all the array elements equal using the given operation ; stores the xor of all elements of array a [ ] ; case 1 , check if the xor of the array a [ ] is 0 ; maintains the xor till the current element ; iterate over the array ; if the current xor is equal to the total xor increment the count and initialize current xor as 0 ; print answer ; 
def possibleEqualArray(A, N):
    tot_XOR = 0
    for i in range(N):
        tot_XOR ^= A[i]
    if (tot_XOR == 0):
        print("YES")
        return
    cur_XOR = 0
    cnt = 0
    for i in range(N):
        cur_XOR ^= A[i]
        if (cur_XOR == tot_XOR):
            cnt += 1
            cur_XOR = 0
    if (cnt > 2):
        print("YES")
    else:
        print("NO")


if __name__ == '__main__':
    A = [0, 2, 2]
    N = len(A)
    possibleEqualArray(A, N)

# Expected output:
YES
# count of palindromes that can be obtained by concatenating equal length prefix and substrings | function to calculate the number of palindromes ; calculation of z - array ; calculation of sigma ( z [ i ] + 1 ) ; return the count ; 
def countPalindrome(S):
    N = len(S)
    Z = [0] * N
    l = 0
    r = 0
    for i in range(1, N):
        if i <= r:
            Z[i] = min(r - i + 1, Z[i - 1])
        while ((i + Z[i]) < N and (S[Z[i]] == S[i + Z[i]])):
            Z[i] += 1
        if ((i + Z[i] - 1) > r):
            l = ir = i + Z[i] - 1
    sum = 0
    for i in range(0, len(Z)):
        sum += Z[i] + 1
    return sum


S = "abab"
print(countPalindrome(S))

# Expected output:
6
# extract substrings between any pair of delimiters | function to print strings present between any pair of delimeters ; stores the indices ; if opening delimeter is encountered ; if closing delimeter is encountered ; extract the position of opening delimeter ; length of substring ; extract the substring ; 
def printSubsInDelimeters(string):
    dels = []
    for i in range(len(string)):
        if (string[i] == '['):
            dels .append(i)
        elif (string[i] == ']' and len(dels) != 0):
            pos = dels[-1]
            dels .pop()
            length = i - 1 - pos
            ans = string[pos + 1:pos + 1 + length]
            print(ans)


if __name__ == "__main__":
    string = "[This is first] ignored text [This is second]"
    printSubsInDelimeters(string)

# Expected output:
This is first
This is second