giulio98/xlcost-single-prompt huggingface dataset:
# entringer number | return entringer number e ( n , k ) ; base cases ; finding dp [ i ] [ j ] ; 
def zigzag(n, k):
    dp = [[0 for x in range(k + 1)]for y in range(n + 1)]
    dp[0][0] = 1
    for i in range(1, n + 1):
        dp[i][0] = 0
    for i in range(1, n + 1):
        for j in range(1, k + 1):
            dp[i][j] = (dp[i][j - 1] + dp[i - 1][i - j])
    return dp[n][k]


n = 4
k = 3
print(zigzag(n, k))

# Expected output:
5
# lobb number | returns value of binomial coefficient c ( n , k ) ; calculate value of binomial coefficient in bottom up manner ; base cases ; calculate value using previously stored values ; return the lm , n lobb number . ; 
def binomialCoeff(n, k):
    C = [[0 for j in range(k + 1)]for i in range(n + 1)]
    for i in range(0, n + 1):
        for j in range(0, min(i, k) + 1):
            if (j == 0 or j == i):
                C[i][j] = 1
            else:
                C[i][j] = (C[i - 1][j - 1] + C[i - 1][j])
    return C[n][k]


def lobb(n, m):
    return (((2 * m + 1) * binomialCoeff(2 * n, m + n)) / (m + n + 1))


n = 5
m = 3
print(int(lobb(n, m)))

# Expected output:
35
# count of arrays having consecutive element with different values | return the number of lists with given constraints . ; initialising dp [ 0 ] and dp [ 1 ] ; computing f ( i ) for each 2 <= i <= n . ; 
def countarray(n, k, x):
    dp = list()
    dp .append(0)
    dp .append(1)
    i = 2
    while i < n:
        dp .append((k - 2) * dp[i - 1] + (k - 1) * dp[i - 2])
        i = i + 1
    return ((k - 1) * dp[n - 2]if x == 1 else dp[n - 1])


n = 4
k = 3
x = 2
print(countarray(n, k, x))

# Expected output:
3
# maximum sum path in a matrix from top to bottom | python3 implementation to find the maximum sum path in a matrix ; function to find the maximum sum path in a matric ; if there is a single elementif there is a single element only only ; dp [ ] [ ] matrix to store the results of each iteration ; base case , copying elements of last row ; building up the dp [ ] [ ] matrix from bottom to the top row ; finding the maximum diagonal element in the ( i + 1 ) th row if that cell exists ; adding that ' max ' element to the mat [ i ] [ j ] element ; finding the maximum value from the first row of dp [ ] [ ] ; required maximum sum ; 

SIZE = 10
INT_MIN = -10000000


def maxSum(mat, n):
    if n == 1:
        return mat[0][0]
    dp = [[0 for i in range(n)]for i in range(n)]
    maxSum = INT_MIN
    for j in range(n):
        dp[n - 1][j] = mat[n - 1][j]
    for i in range(n - 2, -1, -1):
        for j in range(n):
            maxi = INT_MIN
            if ((((j - 1) >= 0) and (maxi < dp[i + 1][j - 1]))):
                maxi = dp[i + 1][j - 1]
            if ((((j + 1) < n) and (maxi < dp[i + 1][j + 1]))):
                maxi = dp[i + 1][j + 1]
            dp[i][j] = mat[i][j] + maxi
    for j in range(n):
        if (maxSum < dp[0][j]):
            maxSum = dp[0][j]
    return maxSum


if __name__ == '__main__':
    mat = [[5, 6, 1, 7], [-2, 10, 8, -1], [3, -7, -9, 11], [12, -4, 2, 6]]
    n = 4
    print("Maximum Sum=", maxSum(mat, n))

# Expected output:
Maximum Sum= 28
# longest repeated subsequence | this function mainly returns lcs ( str , str ) with a condition that same characters at same index are not considered . ; this part of code is same as below post it fills dp [ ] [ ] https : www . geeksforgeeks . org / longest - repeating - subsequence / or the code mentioned above ; this part of code finds the result string using dp [ ] [ ] initialize result ; traverse dp [ ] [ ] from bottom right ; if this cell is same as diagonally adjacent cell just above it , then same characters are present at str [ i - 1 ] and str [ j - 1 ] . append any of them to result . ; otherwise we move to the side that gave us maximum result . ; since we traverse dp [ ] [ ] from bottom , we get result in reverse order . ; 
def longestRepeatedSubSeq(str):
    n = len(str)
    dp = [[0 for i in range(n + 1)]for j in range(n + 1)]
    for i in range(1, n + 1):
        for j in range(1, n + 1):
            if (str[i - 1] == str[j - 1] and i != j):
                dp[i][j] = 1 + dp[i - 1][j - 1]
            else:
                dp[i][j] = max(dp[i][j - 1], dp[i - 1][j])
    res = ''
    i = n
    j = n
    while (i > 0 and j > 0):
        if (dp[i][j] == dp[i - 1][j - 1] + 1):
            res += str[i - 1]
            i -= 1
            j -= 1
        elif (dp[i][j] == dp[i - 1][j]):
            i -= 1
        else:
            j -= 1
    res = ''.join(reversed(res))
    return res


str = 'AABEBCDD'
print(longestRepeatedSubSeq(str))

# Expected output:
ABD
# Sub | Tree traversal to compute minimum difference ; Initial min difference is the color of node ; Traversing its children ; Not traversing the parent ; If the child is Adding positively to difference , we include it in the answer Otherwise , we leave the sub - tree and include 0 ( nothing ) in the answer ; DFS for colour difference : 1 colour - 2 colour ; Minimum colour difference is maximum answer value ; Clearing the current value to check for colour2 as well ; Interchanging the colours ; DFS for colour difference : 2 colour - 1 colour ; Checking if colour2 makes the minimum colour difference ; Nodes ; Adjacency list representation ; Edges ; Index represent the colour of that node There is no Node 0 , so we start from index 1 to N ; Printing the result
def dfs(node, parent, tree, colour, answer):
    answer[node] = colour[node]
    for u in tree[node]:
        if (u == parent):
            continue
        dfs(u, node, tree, colour, answer)
        answer[node] += max(answer[u], 0)


def maxDiff(tree, colour, N):
    answer = [0 for _ in range(N + 1)]
    dfs(1, 0, tree, colour, answer)
    high = 0
    for i in range(1, N + 1):
        high = max(high, answer[i])
        answer[i] = 0
    for i in range(1, N + 1):
        if colour[i] == -1:
            colour[i] = 1
        else:
            colour[i] = -1
    dfs(1, 0, tree, colour, answer)
    for i in range(1, N):
        high = max(high, answer[i])
    return high


N = 5
tree = [list()for _ in range(N + 1)]
tree[1].append(2)
tree[2].append(1)
tree[1].append(3)
tree[3].append(1)
tree[2].append(4)
tree[4].append(2)
tree[3].append(5)
tree[5].append(3)
colour = [0, 1, 1, -1, -1, 1]
print(maxDiff(tree, colour, N))

# Expected output:
2
# remove array end element to maximize the sum of product | python 3 program to find maximum score we can get by removing elements from either end . ; if only one element left . ; if already calculated , return the value . ; computing maximum value when element at index i and index j is to be choosed . ; 

MAX = 50


def solve(dp, a, low, high, turn):
    if (low == high):
        return a[low] * turn
    if (dp[low][high] != 0):
        return dp[low][high]
    dp[low][high] = max(
        a[low] *
        turn +
        solve(
            dp,
            a,
            low +
            1,
            high,
            turn +
            1),
        a[high] *
        turn +
        solve(
            dp,
            a,
            low,
            high -
            1,
            turn +
            1))
    return dp[low][high]


if __name__ == "__main__":
    arr = [1, 3, 1, 5, 2]
    n = len(arr)
    dp = [[0 for x in range(MAX)]for y in range(MAX)]
    print(solve(dp, arr, 0, n - 1, 1))

# Expected output:
43
# maximum sum bitonic subarray | function to find the maximum sum bitonic subarray ; ' msis [ ] ' to store the maximum sum increasing subarray up to each index of ' arr ' from the beginning ' msds [ ] ' to store the maximum sum decreasing subarray from each index of ' arr ' up to the end ; to store the maximum sum bitonic subarray ; building up the maximum sum increasing subarray for each array index ; building up the maximum sum decreasing subarray for each array index ; for each array index , calculating the maximum sum of bitonic subarray of which it is a part of ; if true , then update ' max ' bitonic subarray sum ; required maximum sum ; 
def maxSumBitonicSubArr(arr, n):
    msis = [None] * n
    msds = [None] * n
    max_sum = 0
    msis[0] = arr[0]
    for i in range(1, n):
        if (arr[i] > arr[i - 1]):
            msis[i] = msis[i - 1] + arr[i]
        else:
            msis[i] = arr[i]
    msds[n - 1] = arr[n - 1]
    for i in range(n - 2, -1, -1):
        if (arr[i] > arr[i + 1]):
            msds[i] = msds[i + 1] + arr[i]
        else:
            msds[i] = arr[i]
    for i in range(n):
        if (max_sum < (msis[i] + msds[i] - arr[i])):
            max_sum = (msis[i] + msds[i] - arr[i])
    return max_sum


arr = [5, 3, 9, 2, 7, 6, 4]
n = len(arr)
print("Maximum Sum = " + str(maxSumBitonicSubArr(arr, n)))

# Expected output:
Maximum Sum = 19
# shortest possible combination of two strings | prints super sequence of a [ 0. . m - 1 ] and b [ 0. . n - 1 ] ; fill table in bottom up manner ; below steps follow above recurrence ; following code is used to print supersequence ; create a string of size index + 1 to store the result ; start from the right - most - bottom - most corner and one by one store characters in res [ ] ; if current character in a [ ] and b are same , then current character is part of lcs ; put current character in result ; reduce values of i , j and indexs ; if not same , then find the larger of two and go in the direction of larger value ; copy remaining characters of string 'a ; copy remaining characters of string 'b ; print the result ; 
def printSuperSeq(a, b):
    m = len(a)
    n = len(b)
    dp = [[0] * (n + 1) for i in range(m + 1)]
    for i in range(0, m + 1):
        for j in range(0, n + 1):
            if not i:
                dp[i][j] = j
            elif not j:
                dp[i][j] = i
            elif (a[i - 1] == b[j - 1]):
                dp[i][j] = 1 + dp[i - 1][j - 1]
            else:
                dp[i][j] = 1 + min(dp[i - 1][j],
                                   dp[i][j - 1])
    index = dp[m][n]
    res = [""] * (index)
    i = m
    j = n
    while (i > 0 and j > 0):
        if (a[i - 1] == b[j - 1]):
            res[index - 1] = a[i - 1]
            i -= 1
            j -= 1
            index -= 1
        elif (dp[i - 1][j] < dp[i][j - 1]):
            res[index - 1] = a[i - 1]
            i -= 1
            index -= 1

        else:
            res[index - 1] = b[j - 1]
            j -= 1
            index -= 1
    while (i > 0):
        res[index - 1] = a[i - 1]
        i -= 1
        index -= 1
    while (j > 0):
        res[index - 1] = b[j - 1]
        j -= 1
        index -= 1
    print("".join(res))


if __name__ == '__main__':
    a = "algorithm"
    b = "rhythm"
    printSuperSeq(a, b)

# Expected output:
algorihythm
# minimum time to write characters using insert , delete and copy operation | python3 program to write characters in minimum time by inserting , removing and copying operation ; method returns minimum time to write ' n ' characters ; declare dp array and initialize with zero ; first char will always take insertion time ; loop for ' n ' number of times ; if current char count is even then choose minimum from result for ( i - 1 ) chars and time for insertion and result for half of chars and time for copy ; if current char count is odd then choose minimum from result for ( i - 1 ) chars and time for insertion and result for half of chars and time for copy and one extra character deletion ; 
def minTimeForWritingChars(N, insert, remov, cpy):
    if N == 0:
        return 0
    if N == 1:
        return insert
    dp = [0] * (N + 1)
    dp[1] = insert
    for i in range(2, N + 1):
        if i % 2 == 0:
            dp[i] = min(dp[i - 1] + insert, dp[i // 2] + cpy)
        else:
            dp[i] = min(dp[i - 1] + insert, dp[(i + 1) // 2] + cpy + remov)
    return dp[N]


if __name__ == "__main__":
    N = 9
    insert = 1
    remov = 2
    cpy = 1
    print(minTimeForWritingChars(N, insert, remov, cpy))

# Expected output:
5
# count the number of ways to tile the floor of size n x m using 1 x m size tiles | function to count the total number of ways ; table to store values of subproblems ; fill the table upto value n ; recurrence relation ; base cases ; i = = m ; required number of ways ; 
def countWays(n, m):
    count = []
    for i in range(n + 2):
        count .append(0)
    count[0] = 0
    for i in range(1, n + 1):
        if (i > m):
            count[i] = count[i - 1] + count[i - m]
        elif (i < m or i == 1):
            count[i] = 1
        else:
            count[i] = 2
    return count[n]


n = 7
m = 4
print("Number of ways = ", countWays(n, m))

# Expected output:
Number of ways =  5
# longest alternating subsequence | function for finding longest alternating subsequence ; " inc " and " dec " initialized as 1 as single element is still las ; iterate from second element ; " inc " changes iff " dec " changes ; " dec " changes iff " inc " changes ; return the maximum length ; 
def LAS(arr, n):
    inc = 1
    dec = 1
    for i in range(1, n):
        if (arr[i] > arr[i - 1]):
            inc = dec + 1
        elif (arr[i] < arr[i - 1]):
            dec = inc + 1
    return max(inc, dec)


if __name__ == "__main__":
    arr = [10, 22, 9, 33, 49, 50, 31, 60]
    n = len(arr)
    print(LAS(arr, n))

# Expected output:
6
# minimum number of deletions to make a string palindrome | utility function for calculating minimum element to delete ; condition to compare characters ; recursive function call ; return value , increamenting by 1 return minimum element between two values ; function to calculate the minimum element required to delete for making string pelindrom ; utility function call ; 
def utility_fun_for_del(Str, i, j):
    if (i >= j):
        return 0
    if (Str[i] == Str[j]):
        return utility_fun_for_del(Str, i + 1, j - 1)
    return (1 + min(utility_fun_for_del(Str, i + 1, j),
            utility_fun_for_del(Str, i, j - 1)))


def min_ele_del(Str):
    return utility_fun_for_del(Str, 0, len(Str) - 1)


Str = "abefbac"
print("Minimum element of deletions =", min_ele_del(Str))

# Expected output:
Minimum element of deletions = 2
# minimum number of deletions to make a string palindrome | function definition ; base cases ; checking the ndesired condition ; if yes increment the cunt ; if no ; return the value form the table ; else store the max tranforamtion from the subsequence ; return the dp [ - 1 ] [ - 1 ] ;  ; 
def transformation(s1, s2, i, j, dp):
    if i >= len(s1) or j >= len(s2):
        return 0
    if s1[i] == s2[j]:
        dp[i][j] = 1 + transformation(s1, s2, i + 1, j + 1, dp)
    if dp[i][j] != -1:
        return dp[i][j]
    else:
        dp[i][j] = max(
            transformation(
                s1,
                s2,
                i,
                j + i,
                dp),
            transformation(
                s1,
                s2,
                i + 1,
                j,
                dp))
    return dp[-1][-1]


s1 = "geeksforgeeks"
s2 = "geeks"
i = 0
j = 0
dp = [[-1 for _ in range(len(s1) + 1)]for _ in range(len(s2) + 1)]
print("MINIMUM NUMBER OF DELETIONS: ", len(s1) -
      transformation(s1, s2, 0, 0, dp), end=" ")
print("MINIMUM NUMBER OF INSERTIONS: ", len(s2) -
      transformation(s1, s2, 0, 0, dp), end=" ")
print("LCS LENGTH: ", transformation(s1, s2, 0, 0, dp))

# Expected output:
MINIMUM NUMBER OF DELETIONS:  8 MINIMUM NUMBER OF INSERTIONS:  0 LCS LENGTH:  5
# largest sum zigzag sequence in a matrix | python3 program to find the largest sum zigzag sequence ; returns largest sum of a zigzag sequence starting from ( i , j ) and ending at a bottom cell . ; if we have reached bottom ; find the largest sum by considering all possible next elements in sequence . ; returns largest possible sum of a zizag sequence starting from top and ending at bottom . ; consider all cells of top row as starting point ; 

MAX = 100


def largestZigZagSumRec(mat, i, j, n):
    if (i == n - 1):
        return mat[i][j]
    zzs = 0
    for k in range(n):
        if (k != j):
            zzs = max(zzs, largestZigZagSumRec(mat, i + 1, k, n))
    return zzs + mat[i][j]


def largestZigZag(mat, n):
    res = 0
    for j in range(n):
        res = max(res, largestZigZagSumRec(mat, 0, j, n))
    return res


if __name__ == "__main__":
    n = 3
    mat = [[4, 2, 1], [3, 9, 6], [11, 3, 15]]
    print("Largest zigzag sum: ", largestZigZag(mat, n))

# Expected output:
Largest zigzag sum:  28
# count ways to increase lcs length of two strings by one | python3 program to get number of ways to increase lcs by 1 ; method returns total ways to increase lcs length by 1 ; fill positions of each character in vector vector < int > position [ m ] ; ; initializing 2d array by 0 values ; filling lcs array for prefix substrings ; filling lcs array for suffix substrings ; looping for all possible insertion positions in first string ; trying all possible lower case characters ; now for each character , loop over same character positions in second string ; if both , left and right substrings make total lcs then increase result by 1 ; 

M = 26


def waysToIncreaseLCSBy1(str1, str2):
    m = len(str1)
    n = len(str2)
    position = [[]for i in range(M)]
    for i in range(1, n + 1, 1):
        position[ord(str2[i - 1]) - 97].append(i)
    lcsl = [[0 for i in range(n + 2)]for j in range(m + 2)]
    lcsr = [[0 for i in range(n + 2)]for j in range(m + 2)]
    for i in range(1, m + 1, 1):
        for j in range(1, n + 1, 1):
            if (str1[i - 1] == str2[j - 1]):
                lcsl[i][j] = 1 + lcsl[i - 1][j - 1]
            else:
                lcsl[i][j] = max(lcsl[i - 1][j], lcsl[i][j - 1])
    for i in range(m, 0, -1):
        for j in range(n, 0, -1):
            if (str1[i - 1] == str2[j - 1]):
                lcsr[i][j] = 1 + lcsr[i + 1][j + 1]
            else:
                lcsr[i][j] = max(lcsr[i + 1][j], lcsr[i][j + 1])
    ways = 0
    for i in range(0, m + 1, 1):
        for C in range(0, 26, 1):
            for j in range(0, len(position[C]), 1):
                p = position[C][j]
                if (lcsl[i][p - 1] + lcsr[i + 1][p + 1] == lcsl[m][n]):
                    ways += 1
    return ways


str1 = "abcabc"
str2 = "abcd"
print(waysToIncreaseLCSBy1(str1, str2))

# Expected output:
4
# count of strings that can be formed using a , b and c under given constraints | n is total number of characters . bcount and ccount are counts of ' b ' and ' c ' respectively . ; base cases ; three cases , we choose , a or b or c in all three cases n decreases by 1. ; 
def countStr(n, bCount, cCount):
    if (bCount < 0 or cCount < 0):
        return 0
    if (n == 0):
        return 1
    if (bCount == 0 and cCount == 0):
        return 1
    res = countStr(n - 1, bCount, cCount)
    res += countStr(n - 1, bCount - 1, cCount)
    res += countStr(n - 1, bCount, cCount - 1)
    return res


if __name__ == "__main__":
    n = 3
    print(countStr(n, 1, 2))

# Expected output:
19
# maximum path sum that starting with any cell of 0 | python3 program to find maximum path sum start any column in row '0' and ends up to any column in row 'n-1 ; function find maximum sum path ; create 2d matrix to store the sum of the path initialize all dp matrix as '0 ;  ; copy all element of first column into dp first column ; find maximum path sum that end ups at any column of last row 'n-1 ; return maximum sum path ; 

N = 4


def MaximumPath(Mat):
    result = 0
    dp = [[0 for i in range(N + 2)]for j in range(N)]
    for i in range(N):
        for j in range(1, N + 1):
            dp[i][j] = max(dp[i - 1][j - 1], max(dp[i - 1][j],
                           dp[i - 1][j + 1])) + Mat[i][j - 1]

    for i in range(N + 1):
        result = max(result, dp[N - 1][i])
    return result


Mat = [[4, 2, 3, 4], [2, 9, 1, 10], [15, 1, 3, 0], [16, 92, 41, 44]]
print(MaximumPath(Mat))

# Expected output:
120
# check if all people can vote on two machines | function returns true if n people can vote using two machines in x time . ; dp [ i ] [ j ] stores maximum possible number of people among arr [ 0. . i - 1 ] can vote in j time . ; find sum of all times ; fill dp [ ] [ ] in bottom up manner ( similar to knapsack ) . ; if remaining people can go to other machine . ; 
def canVote(a, n, x):
    dp = [[0] * (x + 1)for _ in range(n + 1)]
    a = a[:]
    a .append(0)
    sm = 0
    for i in range(n + 1):
        sm += a[i]
    for i in range(1, n + 1):
        for j in range(1, x + 1):
            if a[i] <= j:
                dp[i][j] = max(dp[i - 1][j], a[i] + dp[i - 1][j - a[i]])
            else:
                dp[i][j] = dp[i - 1][j]
    return (sm - dp[n][x]) <= x


if __name__ == "__main__":
    n = 3
    x = 4
    a = [2, 4, 2]
    print("YES"if canVote(a, n, x)else "NO")

# Expected output:
YES
# maximum path sum for each position with jumps under divisibility condition | python3 program to print maximum path sum ending with each position x such that all path step positions divide x . ; create an array such that dp [ i ] stores maximum path sum ending with i . ; calculating maximum sum path for each element . ; finding previous step for arr [ i ] moving from 1 to sqrt ( i + 1 ) since all the divisiors are present from sqrt ( i + 1 ) . ; checking if j is divisior of i + 1. ; checking which divisor will provide greater value . ; printing the answer ( maximum path sum ending with every position i + 1 ) . ; 
def printMaxSum(arr, n):
    dp = [0 for i in range(n)]
    for i in range(n):
        dp[i] = arr[i]
        maxi = 0
        for j in range(1, int((i + 1)**0.5) + 1):
            if ((i + 1) % j == 0 and (i + 1) != j):
                if (dp[j - 1] > maxi):
                    maxi = dp[j - 1]
                if (dp[(i + 1) // j - 1] > maxi and j != 1):
                    maxi = dp[(i + 1) // j - 1]
        dp[i] += maxi
    for i in range(n):
        print(dp[i], end=' ')


arr = [2, 3, 1, 4, 6, 5]
n = len(arr)
printMaxSum(arr, n)

# Expected output:
2 5 3 9 8 10
# minimum sum subsequence such that at least one of every four consecutive elements is picked | function to calculate min sum using dp ; if elements are less than or equal to 4 ; save start four element as it is ; compute sum [ ] for all rest elements ; sum [ i ] = ar [ i ] + ( * min_element ( sum + i - 4 , sum + i ) ) ; ; since one of the last 4 elements must be present ; 
def minSum(ar, n):
    if (n <= 4):
        return min(ar)
    sum = [0 for i in range(n)]
    sum[0] = ar[0]
    sum[1] = ar[1]
    sum[2] = ar[2]
    sum[3] = ar[3]
    for i in range(4, n):
        sum[i] = ar[i] + min(sum[i - 4:i])
    return min(sum[n - 4:n])


ar = [2, 4, 1, 5, 2, 3, 6, 1, 2, 4]
n = len(ar)
print("Minimum sum = ", minSum(ar, n))

# Expected output:
Minimum sum =  4