giulio98/xlcost-single-prompt huggingface dataset:
# minimum cost to make two strings identical | returns length of lcs for x [ 0. . m - 1 ] , y [ 0. . n - 1 ] ; following steps build l [ m + 1 ] [ n + 1 ] in bottom up fashion . note that l [ i ] [ j ] contains length of lcs of x [ 0. . i - 1 ] and y [ 0. . j - 1 ] ; l [ m ] [ n ] contains length of lcs for x [ 0. . n - 1 ] and y [ 0. . m - 1 ] ; returns cost of making x [ ] and y [ ] identical . costx is cost of removing a character from x [ ] and costy is cost of removing a character from y [ ] ; find lcs of x [ ] and y [ ] ; cost of making two strings identical is sum of following two 1 ) cost of removing extra characters from first string 2 ) cost of removing extra characters from second string ; 
def lcs(X, Y, m, n):
    L = [[0 for i in range(n + 1)]for i in range(m + 1)]
    for i in range(m + 1):
        for j in range(n + 1):
            if i == 0 or j == 0:
                L[i][j] = 0
            elif X[i - 1] == Y[j - 1]:
                L[i][j] = L[i - 1][j - 1] + 1
            else:
                L[i][j] = max(L[i - 1][j], L[i][j - 1])
    return L[m][n]


def findMinCost(X, Y, costX, costY):
    m = len(X)
    n = len(Y)
    len_LCS = lcs(X, Y, m, n)
    return (costX * (m - len_LCS) + costY * (n - len_LCS))


X = "ef"
Y = "gh"
print('Minimum Cost to make two strings ', end='')
print('identical is = ', findMinCost(X, Y, 10, 20))

# Expected output:
Minimum Cost to make two strings identical is =  60
# number of non | returns count of solutions of a + b + c = n ; initialize result ; consider all triplets and increment result whenever sum of a triplet is n . ; 
def countIntegralSolutions(n):
    result = 0
    for i in range(n + 1):
        for j in range(n + 1):
            for k in range(n + 1):
                if i + j + k == n:
                    result += 1
    return result


n = 3
print(countIntegralSolutions(n))

# Expected output:
10
# number of non | returns count of solutions of a + b + c = n ; 
def countIntegralSolutions(n):
    return int(((n + 1) * (n + 2)) / 2)


n = 3
print(countIntegralSolutions(n))

# Expected output:
10
# maximum absolute difference between sum of two contiguous sub | find maximum subarray sum for subarray [ 0. . i ] using standard kadane ' s ▁ algorithm . ▁ this ▁ version ▁ ▁ of ▁ kadane ' s algorithm will work if all numbers are negative . ; find maximum subarray sum for subarray [ i . . n ] using kadane ' s ▁ algorithm . ▁ this ▁ version ▁ of ▁ kadane ' s algorithm will work if all numbers are negative ; the function finds two non - overlapping contiguous sub - arrays such that the absolute difference between the sum of two sub - array is maximum . ; create and build an array that stores maximum sums of subarrays that lie in arr [ 0. . . i ] ; create and build an array that stores maximum sums of subarrays that lie in arr [ i + 1. . . n - 1 ] ; invert array ( change sign ) to find minumum sum subarrays . ; create and build an array that stores minimum sums of subarrays that lie in arr [ 0. . . i ] ; create and build an array that stores minimum sums of subarrays that lie in arr [ i + 1. . . n - 1 ] ; for each index i , take maximum of 1. abs ( max sum subarray that lies in arr [ 0. . . i ] - min sum subarray that lies in arr [ i + 1. . . n - 1 ] ) 2. abs ( min sum subarray that lies in arr [ 0. . . i ] - max sum subarray that lies in arr [ i + 1. . . n - 1 ] ) ; 
def maxLeftSubArraySum(a, size, sum):
    max_so_far = a[0]
    curr_max = a[0]
    sum[0] = max_so_far
    for i in range(1, size):
        curr_max = max(a[i], curr_max + a[i])
        max_so_far = max(max_so_far, curr_max)
        sum[i] = max_so_far
    return max_so_far


def maxRightSubArraySum(a, n, sum):
    max_so_far = a[n]
    curr_max = a[n]
    sum[n] = max_so_far
    for i in range(n - 1, -1, -1):
        curr_max = max(a[i], curr_max + a[i])
        max_so_far = max(max_so_far, curr_max)
        sum[i] = max_so_far
    return max_so_far


def findMaxAbsDiff(arr, n):
    leftMax = [0 for i in range(n)]
    maxLeftSubArraySum(arr, n, leftMax)
    rightMax = [0 for i in range(n)]
    maxRightSubArraySum(arr, n - 1, rightMax)
    invertArr = [0 for i in range(n)]
    for i in range(n):
        invertArr[i] = -arr[i]
    leftMin = [0 for i in range(n)]
    maxLeftSubArraySum(invertArr, n, leftMin)
    for i in range(n):
        leftMin[i] = -leftMin[i]
    rightMin = [0 for i in range(n)]
    maxRightSubArraySum(invertArr, n - 1, rightMin)
    for i in range(n):
        rightMin[i] = -rightMin[i]
    result = -2147483648
    for i in range(n - 1):
        absValue = max(abs(leftMax[i] - rightMin[i + 1]),
                       abs(leftMin[i] - rightMax[i + 1]))
        if (absValue > result):
            result = absValue
    return result


a = [-2, -3, 4, -1, -2, 1, 5, -3]
n = len(a)
print(findMaxAbsDiff(a, n))

# Expected output:
12
# ways to arrange balls such that adjacent balls are of different types | returns count of arrangements where last placed ball is ' last ' . ' last ' is 0 for ' p ' , 1 for ' q ' and 2 for 'r ; if number of balls of any color becomes less than 0 the number of ways arrangements is 0. ; if last ball required is of type p and the number of balls of p type is 1 while number of balls of other color is 0 the number of ways is 1. ; same case as above for ' q ' and 'r ; if last ball required is p and the number of ways is the sum of number of ways to form sequence with ' p - 1' p balls , q q balls and r r balls ending with q and r . ; same as above case for ' q ' and 'r ; returns count of required arrangements ; three cases arise : last required balls is type p last required balls is type q last required balls is type r ; 
def countWays(p, q, r, last):
    if (p < 0 or q < 0 or r < 0):
        return 0
    if (p == 1 and q == 0 and
            r == 0 and last == 0):
        return 1
    if (p == 0 and q == 1 and
            r == 0 and last == 1):
        return 1

    if (p == 0 and q == 0 and
            r == 1 and last == 2):
        return 1
    if (last == 0):
        return (countWays(p - 1, q, r, 1) +
                countWays(p - 1, q, r, 2))
    if (last == 1):
        return (countWays(p, q - 1, r, 0) +
                countWays(p, q - 1, r, 2))
    if (last == 2):
        return (countWays(p, q, r - 1, 0) +
                countWays(p, q, r - 1, 1))


def countUtil(p, q, r):
    return (countWays(p, q, r, 0) +
            countWays(p, q, r, 1) +
            countWays(p, q, r, 2))


p = 1
q = 1
r = 1
print(countUtil(p, q, r))

# Expected output:
6
# partition a set into two subsets such that the difference of subset sums is minimum | function to find the minimum sum ; if we have reached last element . sum of one subset is sumcalculated , sum of other subset is sumtotal - sumcalculated . return absolute difference of two sums . ; for every item arr [ i ] , we have two choices ( 1 ) we do not include it first set ( 2 ) we include it in first set we return minimum of two choices ; returns minimum possible difference between sums of two subsets ; compute total sum of elements ; compute result using recursive function ; 
def findMinRec(arr, i, sumCalculated, sumTotal):
    if (i == 0):
        return abs((sumTotal - sumCalculated) - sumCalculated)
    return min(findMinRec(arr,
                          i - 1,
                          sumCalculated + arr[i - 1],
                          sumTotal),
               findMinRec(arr,
               i - 1,
               sumCalculated,
               sumTotal))


def findMin(arr, n):
    sumTotal = 0
    for i in range(n):
        sumTotal += arr[i]
    return findMinRec(arr, n, 0, sumTotal)


if __name__ == "__main__":
    arr = [3, 1, 4, 2, 2, 1]
    n = len(arr)
    print("The minimum difference " + "between two sets is ", findMin(arr, n))

# Expected output:
The minimum difference between two sets is  1
# count number of ways to partition a set into k subsets | returns count of different partitions of n elements in k subsets ; base cases ; s ( n + 1 , k ) = k * s ( n , k ) + s ( n , k - 1 ) ; 
def countP(n, k):
    if (n == 0 or k == 0 or k > n):
        return 0
    if (k == 1 or k == n):
        return 1
    return (k * countP(n - 1, k) + countP(n - 1, k - 1))


if __name__ == "__main__":
    print(countP(3, 2))

# Expected output:
3
# count number of ways to partition a set into k subsets | returns count of different partitions of n elements in k subsets ; table to store results of subproblems ; base cases ; fill rest of the entries in dp [ ] [ ] in bottom up manner ; 
def countP(n, k):
    dp = [[0 for i in range(k + 1)]for j in range(n + 1)]
    for i in range(n + 1):
        dp[i][0] = 0
    for i in range(k + 1):
        dp[0][k] = 0
    for i in range(1, n + 1):
        for j in range(1, k + 1):
            if (j == 1 or i == j):
                dp[i][j] = 1
            else:
                dp[i][j] = (j * dp[i - 1][j] + dp[i - 1][j - 1])
    return dp[n][k]


if __name__ == '__main__':
    print(countP(5, 2))

# Expected output:
15
# count number of ways to cover a distance | returns count of ways to cover 'dist ; base cases ; recur for all previous 3 and add the results ; 
def printCountRec(dist):
    if dist < 0:
        return 0
    if dist == 0:
        return 1
    return (
        printCountRec(
            dist -
            1) +
        printCountRec(
            dist -
            2) +
        printCountRec(
            dist -
            3))


dist = 4
print(printCountRec(dist))

# Expected output:
7
# count number of ways to cover a distance | a dynamic programming based c ++ program to count number of ways ; create the array of size 3. ; initialize the bases cases ; run a loop from 3 to n bottom up approach to fill the array ; 
def prCountDP(dist):
    ways = [0] * 3
    n = dist
    ways[0] = 1
    ways[1] = 1
    ways[2] = 2
    for i in range(3, n + 1):
        ways[i % 3] = ways[(i - 1) % 3] + ways[(i - 2) % 3] + ways[(i - 3) % 3]
    return ways[n % 3]


dist = 4
print(prCountDP(dist))

# Expected output:
7
# count numbers from 1 to n that have 4 as a digit | returns sum of all digits in numbers from 1 to n ; one by one compute sum of digits in every number from 1 to n ; a utility function to compute sum of digits in a given number x ; 
def has4(x):
    while (x != 0):
        if (x % 10 == 4):
            return True
        x = x // 10

    return False


def countNumbersWith4(n):
    result = 0
    for x in range(1, n + 1):
        if (has4(x) == True):
            result = result + 1

    return result


n = 328
print("Count of numbers from 1 to ", n,
      " that have 4 as a digit is ", countNumbersWith4(n))

# Expected output:
Count of numbers from 1 to  328  that have 4 as a digit is  60
# count numbers from 1 to n that have 4 as a digit | python3 program to count numbers having 4 as a digit ; function to count numbers from 1 to n that have 4 as a digit ; base case ; d = number of digits minus one in n . for 328 , d is 2 ; computing count of numbers from 1 to 10 ^ d - 1 , d = 0 a [ 0 ] = 0 d = 1 a [ 1 ] = count of numbers from 0 to 9 = 1 d = 2 a [ 2 ] = count of numbers from 0 to 99 = a [ 1 ] * 9 + 10 = 19 d = 3 a [ 3 ] = count of numbers from 0 to 999 = a [ 2 ] * 19 + 100 = 171 ; computing 10 ^ d ; most significant digit ( msd ) of n , for 328 , msd is 3 which can be obtained using 328 / 100 ; if msd is 4. for example if n = 428 , then count of numbers is sum of following . 1 ) count of numbers from 1 to 399 2 ) count of numbers from 400 to 428 which is 29. ; if msd > 4. for example if n is 728 , then count of numbers is sum of following . 1 ) count of numbers from 1 to 399 and count of numbers from 500 to 699 , i . e . , " a [ 2 ] ▁ * ▁ 6" 2 ) count of numbers from 400 to 499 , i . e . 100 3 ) count of numbers from 700 to 728 , recur for 28 ; if msd < 4. for example if n is 328 , then count of numbers is sum of following . 1 ) count of numbers from 1 to 299 a 2 ) count of numbers from 300 to 328 , recur for 28 ; 

import math as mt


def countNumbersWith4(n):
    if (n < 4):
        return 0
    d = int(mt .log10(n))
    a = [1 for i in range(d + 1)]
    a[0] = 0
    if len(a) > 1:
        a[1] = 1
    for i in range(2, d + 1):
        a[i] = a[i - 1] * 9 + mt .ceil(pow(10, i - 1))
    p = mt .ceil(pow(10, d))
    msd = n // p
    if (msd == 4):
        return (msd) * a[d] + (n % p) + 1
    if (msd > 4):
        return ((msd - 1) * a[d] + p + countNumbersWith4(n % p))
    return (msd) * a[d] + countNumbersWith4(n % p)


n = 328
print(
    "Count of numbers from 1 to",
    n,
    "that have 4 as a digit is",
    countNumbersWith4(n))

# Expected output:
Count of numbers from 1 to 328 that have 4 as a digit is 60
# remove minimum elements from either side such that 2 * min becomes more than max | a o ( n * n ) solution to find the minimum of elements to be removed ; returns the minimum number of removals from either end in arr [ l . . h ] so that 2 * min becomes greater than max . ; initialize starting and ending indexes of the maximum sized subarray with property 2 * min > max ; choose different elements as starting point ; initialize min and max for the current start ; choose different ending points for current start ; update min and max if necessary ; if the property is violated , then no point to continue for a bigger array ; update longest_start and longest_end if needed ; if not even a single element follow the property , then return n ; return the number of elements to be removed ; 

import sys


def minRemovalsDP(arr, n):
    longest_start = -1
    longest_end = 0
    for start in range(n):
        min = sys .maxsize
        max = -sys .maxsize
        for end in range(start, n):
            val = arr[end]
            if (val < min):
                min = val
            if (val > max):
                max = val
            if (2 * min <= max):
                break
            if (end - start > longest_end - longest_start or longest_start == -1):
                longest_start = start
                longest_end = end
    if (longest_start == -1):
        return n
    return (n - (longest_end - longest_start + 1))


arr = [4, 5, 100, 9, 10, 11, 12, 15, 200]
n = len(arr)
print(minRemovalsDP(arr, n))

# Expected output:
4
# optimal strategy for a game | dp | returns optimal value possible that a player can collect from an array of coins of size n . note than n must be even ; create a table to store solutions of subproblems ; fill table using above recursive formula . note that the table is filled in diagonal fashion ( similar to http : goo . gl / pqqos ) , from diagonal elements to table [ 0 ] [ n - 1 ] which is the result . ; here x is value of f ( i + 2 , j ) , y is f ( i + 1 , j - 1 ) and z is f ( i , j - 2 ) in above recursive formula ; 
def optimalStrategyOfGame(arr, n):
    table = [[0 for i in range(n)]for i in range(n)]
    for gap in range(n):
        for j in range(gap, n):
            i = j - gap
            x = 0
            if ((i + 2) <= j):
                x = table[i + 2][j]
            y = 0
            if ((i + 1) <= (j - 1)):
                y = table[i + 1][j - 1]
            z = 0
            if (i <= (j - 2)):
                z = table[i][j - 2]
            table[i][j] = max(arr[i] + min(x, y), arr[j] + min(y, z))
    return table[0][n - 1]


arr1 = [8, 15, 3, 7]
n = len(arr1)
print(optimalStrategyOfGame(arr1, n))
arr2 = [2, 2, 2, 2]
n = len(arr2)
print(optimalStrategyOfGame(arr2, n))
arr3 = [20, 30, 2, 2, 2, 10]
n = len(arr3)
print(optimalStrategyOfGame(arr3, n))

# Expected output:
22
4
42
# maximum sum increasing subsequence | dp | maxsumis ( ) returns the maximum sum of increasing subsequence in arr [ ] of size n ; initialize msis values for all indexes ; compute maximum sum values in bottom up manner ; pick maximum of all msis values ; 
def maxSumIS(arr, n):
    max = 0
    msis = [0 for x in range(n)]
    for i in range(n):
        msis[i] = arr[i]
    for i in range(1, n):
        for j in range(i):
            if (arr[i] > arr[j] and msis[i] < msis[j] + arr[i]):
                msis[i] = msis[j] + arr[i]
    for i in range(n):
        if max < msis[i]:
            max = msis[i]
    return max


arr = [1, 101, 2, 3, 100, 4, 5]
n = len(arr)
print("Sum of maximum sum increasing " +
      "subsequence is " + str(maxSumIS(arr, n)))

# Expected output:
Sum of maximum sum increasing subsequence is 106
# find position i to split array such that prefix sum till i | function to check if there is an element forming g . p . series having common ratio k ; if size of array is less than three then return - 1 ; initialize the variables ; calculate total sum of array ; calculate middle element of g . p . series ; iterate over the range ; store the first element of g . p . series in the variable temp ; return position of middle element of the g . p . series if the first element is in g . p . of common ratio k ; else return 0 ; if middle element is not found in arr [ ] ; 
def checkArray(arr, N, k):
    if (N < 3):
        return -1
    Sum = 0
    temp = 0
    for i in range(0, N):
        Sum += arr[i]
    R = (k * k + k + 1)
    if (Sum % R != 0):
        return 0
    Mid = k * (Sum // R)
    for i in range(1, N - 1):
        temp += arr[i - 1]
        if (arr[i] == Mid):
            if (temp == Mid // k):
                return i + 1
            else:
                return 0
    return 0


if __name__ == "__main__":
    arr = [5, 1, 4, 20, 6, 15, 9, 10]
    N = len(arr)
    K = 2
    print(checkArray(arr, N, K))

# Expected output:
4
# repeat last occurrence of each alphanumeric character to their position in character family times | function to encode the given string ; variable string to store the result ; arrays to store the last occuring index of every character in the string ; length of the string ; iterate over the range ; if str [ i ] is between 0 and 9 ; if str [ i ] is between a and z ; if str [ i ] is between a and z ; iterate over the range ; if str [ i ] is between a and z and i is the last occurence in str ; if str [ i ] is between a and z and i is the last occurence in str ; if str [ i ] is between 0 and 9 and i is the last occurence in str ; print the result ; 
def encodeString(str):
    res = ""
    small = [0 for i in range(26)]
    capital = [0 for i in range(26)]
    num = [0 for i in range(10)]
    n = len(str)
    for i in range(n):
        if (str[i] >= '0' and str[i] <= '9'):
            num[ord(str[i]) - 48] = i
        elif (str[i] >= 'a' and str[i] <= 'z'):
            small[ord(str[i]) - 97] = i
        elif (str[i] >= 'A' and str[i] <= 'Z'):
            capital[ord(str[i]) - 65] = i
    for i in range(n):
        if ((str[i] >= 'a' and str[i] <= 'z')
                and small[ord(str[i]) - 97] == i):
            occ = ord(str[i]) - 96
            while (occ > 0):
                res += str[i]
                occ -= 1
        elif ((str[i] >= 'A' and str[i] <= 'Z') and capital[ord(str[i]) - 65] == i):
            occ = ord(str[i]) - 64
            while (occ > 0):
                res += str[i]
                occ -= 1
        elif ((str[i] >= '0' and str[i] <= '9') and num[ord(str[i]) - 48] == i):
            occ = ord(str[i]) - 48
            while (occ > 0):
                res += str[i]
                occ -= 1
        else:
            res += str[i]
    print(res)


if __name__ == '__main__':
    str = "Ea2, 0, E"
    encodeString(str)

# Expected output:
Ea22, , EEEEE
# 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 prefix xor array ; calculate prefix [ i ] ; case 1 , check if the xor of the input array is 0 ; case 2 iterate over all the ways to divide the array into three non empty subarrays ; xor of middle block ; xor of left block ; xor of right block ; not possible ; 
def possibleEqualArray(A, N):
    pref = [0 for i in range(N)]
    pref[0] = A[0]
    for i in range(1, N, 1):
        pref[i] = pref[i - 1] ^ A[i]
    if (pref[N - 1] == 0):
        print("YES")
        return
    cur_xor = 0
    i = N - 1
    while (i >= 0):
        cur_xor ^= A[i]
        for j in range(i):
            if (j):
                middle_xor = pref[j - 1] ^ pref[i - 1]
                left_xor = pref[j - 1]
                right_xor = cur_xor
                if (left_xor == middle_xor and middle_xor == right_xor):
                    print("YES")
                    return
        i -= 1
    print("NO")


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

# Expected output:
YES
# construct an array whose prefix xor array starting from x is an n | function to print the required array ; iteratie from 1 to n ; print the i - th element ; update prev_xor to i ; 
def GenerateArray(N, X):
    prev_xor = X
    for i in range(1, N + 1, 1):
        print(i ^ prev_xor, end="")
        if (i != N):
            print(" ", end="")
        prev_xor = i


if __name__ == '__main__':
    N = 4
    X = 3
    print("The generated array is ", end="")
    GenerateArray(N, X)

# Expected output:
The generated array is 2 3 1 7
# check if elements of a binary matrix can be made alternating | function to create the possible grids ; function to test if any one of them matches with the given 2 - d array ; function to print the grid , if possible ; function to check if the grid can be made alternating or not ; grids to store the possible grids ; 
def createGrid(grid, is1, N, M):
    for i in range(N):
        for j in range(M):
            if (is1):
                grid[i][j] = '0'
                is1 = False
            else:
                grid[i][j] = '1'
                is1 = True
        if (M % 2 == 0):
            is1 = True if is1 == False else False


def testGrid(testGrid, Grid, N, M):
    for i in range(N):
        for j in range(M):
            if (Grid[i][j] != '*'):
                if (Grid[i][j] != testGrid[i][j]):
                    return False
    return True


def printGrid(grid, N, M):
    for i in range(N):
        for j in range(M):
            print(grid[i][j], end=" ")
        print("", end="")


def findPossibleGrid(N, M, grid):
    gridTest1 = [[''for i in range(1001)]for j in range(N)]
    gridTest2 = [[''for i in range(1001)]for j in range(N)]
    createGrid(gridTest1, True, N, M)
    createGrid(gridTest2, False, N, M)
    if (testGrid(gridTest1, grid, N, M)):
        print("Yes")
        printGrid(gridTest1, N, M)
    elif (testGrid(gridTest2, grid, N, M)):
        print("Yes")
        printGrid(gridTest2, N, M)
    else:
        print("No")


if __name__ == '__main__':
    N = 4
    M = 4
    grid = [['*', '*', '1', '0'], ['*', '*', '*', '*'],
            ['*', '*', '*', '*'], ['*', '*', '0', '1']]
    findPossibleGrid(N, M, grid)

# Expected output:
Yes
1 0 1 0 0 1 0 1 1 0 1 0 0 1 0 1
# find non | python 3 program for the above approach . ; function to find the possible output array ; base case for the recursion ; if ind becomes half of the size then print the array . ; exit the function . ; iterate in the range . ; put the values in the respective indices . ; call the function to find values for other indices . ; 

import sys
N = 200 * 1000 + 13
n = 0
arr = [0 for i in range(N)]
brr = [0 for i in range(N)]


def brute(ind, l, r):
    if (ind == n / 2):
        for i in range(n):
            print(brr[i], end=" ")
        sys .exit()
    for i in range(l, arr[ind] // 2 + 1, 1):
        if (arr[ind] - i <= r):
            brr[ind] = i
            brr[n - ind - 1] = arr[ind] - i
            brute(ind + 1, i, arr[ind] - i)


if __name__ == '__main__':
    n = 2
    n *= 2
    arr[0] = 5
    arr[1] = 6
    INF64 = 1000000000000000000
    brute(0, 0, INF64)

# Expected output:
0 1 5 5